from __future__ import annotations

import typing as t
import uuid

import pandas as pd
from sqlglot import exp

from sqlmesh.core.engine_adapter.base_postgres import BasePostgresEngineAdapter
from sqlmesh.core.engine_adapter.mixins import (
    GetCurrentCatalogFromFunctionMixin,
    LogicalMergeMixin,
    LogicalReplaceQueryMixin,
)
from sqlmesh.core.engine_adapter.shared import DataObject, DataObjectType, set_catalog

if t.TYPE_CHECKING:
    from sqlmesh.core._typing import SchemaName, TableName
    from sqlmesh.core.engine_adapter.base import QueryOrDF, SourceQuery

class RedshiftEngineAdapter(
    BasePostgresEngineAdapter,
    LogicalReplaceQueryMixin,
    LogicalMergeMixin,
    GetCurrentCatalogFromFunctionMixin,
):
    DIALECT = "redshift"
    ESCAPE_JSON = True
    COLUMNS_TABLE = "SVV_COLUMNS"  # Includes late-binding views
    CURRENT_CATALOG_FUNCTION = "current_database()"

    @property
    def cursor(self) -> t.Any:
        # Redshift by default uses a `format` paramstyle that has issues when we try to write our snapshot
        # data to snapshot table. There doesn't seem to be a way to disable parameter overriding so we just
        # set it to `qmark` since that doesn't cause issues.
        cursor = self._connection_pool.get_cursor()
        cursor.paramstyle = "qmark"
        return cursor

    def _fetch_native_df(
        self, query: t.Union[exp.Expression, str], quote_identifiers: bool = False
    ) -> pd.DataFrame:
        """Fetches a Pandas DataFrame from the cursor"""
        self.execute(query, quote_identifiers=quote_identifiers)
        return self.cursor.fetch_dataframe()

    def _create_table_from_source_queries(
        self,
        table_name: TableName,
        source_queries: t.List[SourceQuery],
        columns_to_types: t.Optional[t.Dict[str, exp.DataType]] = None,
        exists: bool = True,
        replace: bool = False,
        **kwargs: t.Any,
    ) -> None:
        """
        Redshift doesn't support `CREATE TABLE IF NOT EXISTS AS...` but does support `CREATE TABLE AS...` so
        we check if the exists check exists and if not then we can use the base implementation. Otherwise we
        manually check if it exists and if it does then this is a no-op anyways so we return and if it doesn't
        then we run the query with exists set to False since we just confirmed it doesn't exist.
        """
        if not exists:
            return super()._create_table_from_source_queries(
                table_name, source_queries, columns_to_types, exists, **kwargs
            )
        if self.table_exists(table_name):
            return
        super()._create_table_from_source_queries(
            table_name, source_queries, exists=False, **kwargs
        )

    def replace_query(
        self,
        table_name: TableName,
        query_or_df: QueryOrDF,
        columns_to_types: t.Optional[t.Dict[str, exp.DataType]] = None,
        **kwargs: t.Any,
    ) -> None:
        """
        Redshift doesn't support `CREATE OR REPLACE TABLE...` and it also doesn't support `VALUES` expression so we need to specially
        handle DataFrame replacements.

        If the table doesn't exist then we just create it and load it with insert statements
        If it does exist then we need to do the:
            `CREATE TABLE...`, `INSERT INTO...`, `RENAME TABLE...`, `RENAME TABLE...`, DROP TABLE...`  dance.
        """
        if not self.is_pandas_df(query_or_df) or not self.table_exists(table_name):
            return super().replace_query(table_name, query_or_df, columns_to_types, **kwargs)
        source_queries, columns_to_types = self._get_source_queries_and_columns_to_types(
            query_or_df, columns_to_types, target_table=table_name
        )
        columns_to_types = columns_to_types or self.columns(table_name)
        target_table = exp.to_table(table_name)
        with self.transaction():
            temp_table_name = f"{target_table.alias_or_name}_temp_{self._short_hash()}"
            temp_table = target_table.copy()
            temp_table.set("this", exp.to_identifier(temp_table_name))
            old_table_name = f"{target_table.alias_or_name}_old_{self._short_hash()}"
            old_table = target_table.copy()
            old_table.set("this", exp.to_identifier(old_table_name))
            self.create_table(temp_table, columns_to_types, exists=False, **kwargs)
            self._insert_append_source_queries(temp_table, source_queries, columns_to_types)
            self.rename_table(target_table, old_table)
            self.rename_table(temp_table, target_table)
            self.drop_table(old_table)

    def set_current_catalog(self, catalog_name: str) -> None:
        self.cursor.connection._database = catalog_name

    @set_catalog()
    def _get_data_objects(self, schema_name: SchemaName) -> t.List[DataObject]:
        """
        Returns all the data objects that exist in the given schema and optionally catalog.
        """
        query = f"""
            SELECT
                null AS catalog_name,
                tablename AS name,
                schemaname AS schema_name,
                'TABLE' AS type
            FROM pg_tables
            WHERE schemaname ILIKE '{schema_name}'
            UNION ALL
            SELECT
                null AS catalog_name,
                viewname AS name,
                schemaname AS schema_name,
                'VIEW' AS type
            FROM pg_views
            WHERE schemaname ILIKE '{schema_name}'
            AND definition not ilike '%create materialized view%'
            UNION ALL
            SELECT
                null AS catalog_name,
                viewname AS name,
                schemaname AS schema_name,
                'MATERIALIZED_VIEW' AS type
            FROM
                pg_views
            WHERE schemaname ILIKE '{schema_name}'
            AND definition ilike '%create materialized view%'
        """
        df = self.fetchdf(query)
        return [
            DataObject(
                catalog=row.catalog_name, schema=row.schema_name, name=row.name, type=DataObjectType.from_str(row.type)  # type: ignore
            )
            for row in df.itertuples()
        ]

    def _short_hash(self) -> str:
        return uuid.uuid4().hex[:8]


'''
Title           :Preprocessing.py
Description     :This script contains all functions required for data augmentation & preparation
Author          :Ilke Cugu & Eren Sener
Date Created    :28-04-2017
Date Modified   :09-06-2019
version         :1.1
python_version  :2.7.11
'''

from time import gmtime, strftime
import numpy as np
import cv2

def mirrorImages(img, newDim=84):
	mirror_img0 = img[0:224, 0:224]
	mirror_img0 = cv2.resize(mirror_img0, (newDim, newDim))
	mirror_img1 = img[0:224, 5:229]
	mirror_img1 = cv2.resize(mirror_img1, (newDim, newDim))
	mirror_img2 = img[0:224, 32:256]
	mirror_img2 = cv2.resize(mirror_img2, (newDim, newDim))
	mirror_img3 = img[5:229, 0:224]
	mirror_img3 = cv2.resize(mirror_img3, (newDim, newDim))
	mirror_img4 = img[32:256, 0:224]
	mirror_img4 = cv2.resize(mirror_img4, (newDim, newDim))
	mirror_img5 = img[5:229, 5:229]
	mirror_img5 = cv2.resize(mirror_img5, (newDim, newDim))
	mirror_img6 = img[32:256, 32:256]
	mirror_img6 = cv2.resize(mirror_img6, (newDim, newDim))
	mirror_img7 = img[5:229, 32:256]
	mirror_img7 = cv2.resize(mirror_img7, (newDim, newDim))
	return [mirror_img0, mirror_img1, mirror_img2, mirror_img3, mirror_img4, mirror_img5, mirror_img6, mirror_img7]

def deployImages(labelpath, TeacherSoftmaxInputs):
	images = []
	imageNames = []
	labels = np.array([])
	y_values = []
	with open(labelpath, "r") as labelfile:
		for f in labelfile:
			f = f.split(" ")
			filename = f[0]
			imageNames.append(filename)
			#imageNames.append(filename.split('/')[-1])
			label = int(f[1])
			im = cv2.imread(filename)
			gray_im = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
			mirror_ims = mirrorImages(gray_im)
			for i in mirror_ims:
				gray_im = i.reshape(i.shape[0]*i.shape[1])
				images.append(gray_im)
				labels = np.append(labels, label)
				if TeacherSoftmaxInputs != None:
					y_values.append(TeacherSoftmaxInputs[filename])

	return np.array(images), labels, np.array(y_values)

def produceOneHot(y, n_classes):
	n = y.shape[0]
	new_y = np.zeros([n, n_classes])
	for i in range(0,n):
		new_y[i][int(y[i])] = 1
	return new_y

def produce10foldCrossVal(x, y, teacherLogits, labelpath):
	# Separate validation and training sets
	folds = []
	labels = []
	with open(labelpath, "r") as labelfile:
		for f in labelfile:
			# This line gathers fold IDs (10-fold cross-val) from a label file with a format like:
			#	...
			#	/home/cuguilke/Desktop/CK_new/fold1/n01497344_S028_001_00018.jpeg 1
			#	/home/cuguilke/Desktop/CK_new/fold1/n01448192_S052_001_00045.jpeg 7
			#	/home/cuguilke/Desktop/CK_new/fold1/n01456384_S044_004_00065.jpeg 0
			#	/home/cuguilke/Desktop/CK_new/fold1/n01489152_S035_006_00021.jpeg 5
			#	...
			# Feel free to modify this part with your own way of indicating fold IDs
			labels.append(int(f.split('/')[5][-1]))
	partition_x = []
	partition_y = []
	partition_teacherLogits = []
	last_batch_no = 0
	n = len(labels)
	for i in range(n):
		batch_no = labels[i]
		if batch_no != last_batch_no:
			folds.append({'x': np.array(partition_x), 'y': np.array(partition_y), 'teacherLogits': None})
			partition_x = []
			partition_y = []
			partition_teacherLogits = []
		else:
			for j in range(i*8,(i+1)*8): # Since each image is mirrored
				partition_x.append(x[j])
				partition_y.append(y[j])
				if teacherLogits != None:
					teacherNetOut = teacherLogits[j]
					partition_teacherLogits.append(teacherNetOut)
				else:
					partition_teacherLogits.append([])
		last_batch_no = batch_no
	if len(partition_x) > 0:
		folds.append({'x': np.array(partition_x), 'y': np.array(partition_y), 'teacherLogits': None})
	return folds

def produceBatch(x, y, teacherLogits, batchSize):
	batches = []
	n = y.shape[0]
	batch_x = []
	batch_y = []
	batch_teacherLogits = []
	for i in range(0,n):
		if i % batchSize == 0 and i != 0:
			batches.append({'x': np.array(batch_x), 'y': np.array(batch_y), 'teacherLogits': np.array(batch_teacherLogits)})
			batch_x = []
			batch_y = []
			batch_teacherLogits = []
		batch_x.append(x[i])
		batch_y.append(y[i])
		if teacherLogits != None:
			batch_teacherLogits.append(teacherLogits[i])
		else:
			batch_teacherLogits.append([])
	if len(batch_x) > 0:
		batches.append({'x': np.array(batch_x), 'y': np.array(batch_y), 'teacherLogits': np.array(batch_teacherLogits)}) # Add the leftovers as the last batch
	return batches

def get_time():
	return strftime("%a, %d %b %Y %X", gmtime())


import json as _json

def pre_hook_response(method, path, json):
    """
    Format a Powerstrip pre-hook response JSON blob.
    """
    return _json.dumps(dict(
        PowerstripProtocolVersion=1,
        ModifiedClientRequest=dict(
            Method=method,
            Request=path,
            Body=json,
        )))


# 解析日志，并返回字典类型list，list中每个值对应一个事件(beta版本log格式不一样，不可用)
# 用法：a = Analyser('com.next.innovation.takatak')
#      result = a.analyse('1.txt')

import re

class Analyser:

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

    def event_analyser(self, lines):
        events = {}
        for line in lines:
            logs = line.split('│')
            # 去掉没有｜的log
            if len(logs) > 1:
                event_item = logs[-1]
                items = event_item.split(':', 1)
                if len(events) == 0:
                    events['eventName'] = items[0].strip()
                    items = items[1].split(':', 1)
                if len(items) == 2:
                    events[items[0].lstrip()] = items[1].strip(' ;')
        return events

    def analyse_taka(self, log_path):
        list_result = []
        with open(log_path) as file:
            events_log = file.read()
        event_logs = re.findall(r"┌.+?└", events_log, re.S)

        for event_log in event_logs:
            lines = event_log.splitlines()
            # 过滤掉send: statusCode: 200非打点log
            if len(lines) > 3:
                event_result = self.event_analyser(lines)
                list_result.append(event_result)
        return list_result

    def analyse_mxplayer(self, log_path):
        pass

    def analyse(self, log_file):
        if self.package_name == 'com.next.innovation.takatak':
            list_event = self.analyse_taka(log_file)
            return list_event
        if self.package_name == 'com.mxtech.videoplayer.ad':
            self.analyse_mxplayer(log_file)


# coding:utf-8

import random
import os
from PyQt5.QtWidgets import QApplication, QMainWindow, QDockWidget, QStyleFactory, QStatusBar, QGraphicsEffect, QAction
from PyQt5.QtCore import Qt, pyqtSignal, pyqtSlot
import time

import serialport_widget
import ethernet_widget
import dialog_con_type
from Command_module import *
from utility import *
import new
import qdarktheme

class MainWindow(QMainWindow):

    def __init__(self):
        super().__init__()
        self.resize(1000, 800)
        self.setWindowTitle('Connection Master v0.4')
        self.status_bar = QStatusBar()
        self.setStatusBar(self.status_bar)

        self.status_label = QLabel('hello')
        self.status_bar_layout = QHBoxLayout()
        self.status_bar.setLayout(self.status_bar_layout)
        self.status_bar_layout.addWidget(self.status_label)

        self.file_menu = self.menuBar().addMenu('&File')
        self.view_menu = self.menuBar().addMenu("&View")
        self.con_type_menu = self.menuBar().addMenu("&Connection type")
        self.theme_menu = self.menuBar().addMenu("&Theme")

        self.create_cmd_viewer_docker()
        self.create_con_interface()
        self.create_monitor_docker()
        # self.create_preselector_docker()
        self.create_urp_docker()
        self.create_status_bar()

        self.inteface_widget.signal.connect(self.sp_signal_handling, Qt.QueuedConnection)
        self.inteface_widget.signal_info.connect(self.show_info, Qt.QueuedConnection)
        self.cmd_viewer.signal_bytes.connect(self.cmd_signal_byte_handling, Qt.QueuedConnection)
        self.cmd_viewer.signal_info.connect(self.show_info, Qt.QueuedConnection)

        self.docker_urp.setVisible(False)
        self.docker_monitor.setVisible(False)

    def create_status_bar(self):
        self.file_menu.addAction(QIcon(r'icons/folder.svg'), 'Open', self.cmd_viewer.open_file_dialog,
                                 shortcut='Ctrl+O')
        self.file_menu.addAction(QIcon(r'icons/save.svg'), 'Save', self.cmd_viewer.save_file_changes, shortcut='Ctrl+S')
        self.file_menu.addAction(QIcon(r'icons/save.svg'), 'Save to..', self.cmd_viewer.save_to)
        self.file_menu.addSeparator()
        self.file_menu.addAction(QIcon(r'icons/x.svg'), 'Exit', self.close, shortcut='Ctrl+Q')
        self.con_type_menu.triggered.connect(self.set_new_con_interface)
        self.con_type_menu.addAction('Serial').setCheckable(True)
        self.con_type_menu.addAction('Ethernet').setCheckable(True)
        self.con_type_menu.actions()[0].setChecked(True)
        for theme in qdarktheme.get_themes():
            self.theme_menu.addAction(theme).setCheckable(True)
        self.theme_menu.actions()[0].setChecked(True)
        self.theme_menu.triggered.connect(self.set_new_theme)

    def create_con_interface(self):
        self.inteface_widget = serialport_widget.Widget()
        self.setCentralWidget(self.inteface_widget)

    @pyqtSlot(QAction)
    def set_new_con_interface(self, action: QAction):
        for act in self.con_type_menu.actions():
            act.setChecked(False)
        action.setChecked(True)
        if self.inteface_widget.connection.is_open():
            self.inteface_widget.connection.close()
        self.inteface_widget.close()
        if action.text() == 'Ethernet':
            self.inteface_widget = ethernet_widget.Widget()
        elif action.text() == 'Serial':
            self.inteface_widget = serialport_widget.Widget()

        self.setCentralWidget(self.inteface_widget)

    @pyqtSlot(QAction)
    def set_new_theme(self, action: QAction):
        for act in self.theme_menu.actions():
            act.setChecked(False)
        action.setChecked(True)
        stylesheet = qdarktheme.load_stylesheet(action.text())
        QApplication.instance().setStyleSheet(stylesheet)

    def create_cmd_viewer_docker(self):
        self.cmd_viewer = CmdViewerWidget()
        self.docker_cmd_viewer = QDockWidget('Command viewer', self)
        self.docker_cmd_viewer.setWidget(self.cmd_viewer)
        self.addDockWidget(Qt.RightDockWidgetArea, self.docker_cmd_viewer)
        self.view_menu.addAction(self.docker_cmd_viewer.toggleViewAction())

    def create_monitor_docker(self):
        self.monitor = new.Monitor(count=3, names=['Out', 'LO1', 'LO2'])
        self.docker_monitor = QDockWidget('Temperature monitoring', self)
        self.docker_monitor.setWidget(self.monitor)
        self.monitor.set_left_lable('Temperature', '°C')
        self.addDockWidget(Qt.RightDockWidgetArea, self.docker_monitor)
        self.view_menu.addAction(self.docker_monitor.toggleViewAction())

    def create_preselector_docker(self):
        self.preselector = new.Preselector()
        self.docker_preselector = QDockWidget('Preselector ', self)
        self.docker_preselector.setWidget(self.preselector)
        self.addDockWidget(Qt.RightDockWidgetArea, self.docker_preselector)
        self.view_menu.addAction(self.docker_preselector.toggleViewAction())

    def create_urp_docker(self):
        self.urp = new.URP()
        self.docker_urp = QDockWidget('URP', self)
        self.docker_urp.setWidget(self.urp)
        self.addDockWidget(Qt.RightDockWidgetArea, self.docker_urp)
        self.view_menu.addAction(self.docker_urp.toggleViewAction())

    @pyqtSlot(signal_type)
    def sp_signal_handling(self, signal):
        if signal.name == 'cmd':
            logger.debug(f'{self.cmd_viewer.cmdtree.currentIndex().row()}')

    @pyqtSlot(signal_cmd)
    def cmd_signal_byte_handling(self, signal: signal_cmd):
        if signal.name == 'send_cmd':
            logger.debug(f'signal cmd: {signal}')
            self.inteface_widget.write(signal.value)

    def monitor_signal_handling(self):
        if self.inteface_widget.connection.is_open():
            try:
                temp_out = int(self.inteface_widget.write_read(b'\x00\x0A\x00')[2])
                temp_lo1 = int(self.inteface_widget.write_read(b'\x10\x0A\x00')[2])
                temp_lo2 = int(self.inteface_widget.write_read(b'\x11\x0A\x00')[2])
                self.monitor.appendData([temp_out, temp_lo1, temp_lo2])
            except:
                print("monitor_signal_handling: IndexError: index out of range")

    @pyqtSlot(signal_info)
    def show_info(self, signal: signal_info):
        logger.debug(f'Info signal: {signal}')
        if signal.font is None:
            self.status_bar.setFont(self.font())
        else:
            self.status_bar.setFont(signal.font)
        self.status_bar.showMessage(signal.text, 8000)

    @pyqtSlot()
    def closeEvent(self, event):
        if self.cmd_viewer.check_changes():
            event.accept()
        else:
            event.ignore()

if __name__ == '__main__':
    import sys

    import dark_theme as dth

    app = QApplication(sys.argv)
    app.setStyleSheet(qdarktheme.load_stylesheet())
    # app.setStyle('Fusion')
    #app.setStyleSheet(dth.styleSheet)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())


#! /usr/bin/python

import argparse
from datetime import datetime
import glob
import csv
import sys
import os
import re

#
# utility class to assist in converting
# a tsv into a latex table - it can
# rename header columns (name_map)
# perform arbitrary transforms (row_func)
# and filter out columns
#
class TableFormatter:
    def __init__(self):
        self.name_map = dict()
        self.row_func = dict()
        self.column_filter = dict()
        self.table_spec = ""
        self.size = "normalsize"

# convert a pdf to a collection of pngs, returning a list of the generated filenames
def pdf_to_png(pdf_name, output_directory="report_images"):

    if not os.path.exists(output_directory):
        os.makedirs(output_directory)
    prefix = os.path.basename(pdf_name).replace(".pdf", "")
    os.system("pdftoppm %s %s/%s -png" % (pdf_name, output_directory, prefix))
    return sorted(glob.glob("%s/%s*.png" % (output_directory, prefix)))

# latex starting boilerplate to set up the document class, packages, etc
def write_preamble():

    p = r'''
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{array}
\usepackage{float}
\usepackage{longtable}
\usepackage[margin=0.15in]{geometry}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\begin{document}'''
    print(p)

# latex ending boilerplate
def write_postamble():

    p = r'''
\end{document}'''
    print(p)

# count the number of rows in a tsv file
def count_tsv(filename):

    c = 0
    with(open(filename)) as f:
        reader = csv.DictReader(f, delimiter="\t")
        for row in reader:
            c += 1
    return c

def format_ct(s):

    try:
        return "%.1f" % (float(s))
    except:
        return "NA"

def escape_latex(s):
    return s.replace("_", "\_")

# high-level function to transform a tsv into a latex table
# performing remapping of column names and arbitrary transformation
# of values within each column (e.g. escaping characters latex doesn't like)
# using table formatter
def tsv_to_table(filename, table_formatter):
    with(open(filename)) as f:
        reader = csv.DictReader(f, delimiter="\t")

        rows = list()
        header = list()

        for row in reader:

            # remove columns
            for k in table_formatter.column_filter:
                del row[k]

            if len(header) == 0:

                # remap column names
                for k in row.keys():
                    if k in table_formatter.name_map:
                        header.append(table_formatter.name_map[k])
                    else:
                        header.append(escape_latex(k))

            # transform with row func
            for k in row:
                if k in table_formatter.row_func:
                    row[k] = table_formatter.row_func[k](row[k])
            rows.append(row.values())

        # write latex to stdout
        write_table(table_formatter.table_spec, header, rows, table_formatter.size)

# latex for displaying an image
def write_image(image_filename, scale=1.0):
    print(r"\begin{center}")
    print("\includegraphics[scale=%f]{%s}" % (scale, image_filename))
    print(r"\end{center}")

# latex for displaying a table
def write_table(spec, header, rows, size):
    print(r"\begin{center}")
    print(r"\%s" % size)

    print(r"\begin{longtable}{%s}" % (spec))
    print(r"\hline")
    print(" & ".join(header) + r" \\ \hline")
    print(r"\endhead")
    for r in rows:
        print(" & ".join([escape_latex(v) for v in r]) + r" \\ \hline")

    print(r"\end{longtable}")
    print(r"\normalsize")
    print(r"\end{center}")

# parse a sample name from a filename, assuming the
# sample name is the first entry
def filename_to_sample(fn):
    return os.path.basename(fn).split(".")[0]

# write the section of the report describing the negative control checks
def write_negative_control_section():

    print(r"\section{Negative Control}")

    plot_path = args.negative_control_depth_figure.format(run_name=args.run_name)

    if os.path.exists(plot_path):
        nc_depth_figures = pdf_to_png(plot_path)

        # plot each depth image for the negative control samples
        for depth_png in nc_depth_figures:
            write_image(depth_png, 0.75)
    else:
        print(r"Negative control depth plots not found.")

    # write summary table
    table_path = args.negative_control_table.format(run_name=args.run_name)

    if os.path.exists(table_path):

        # set up TableFormatter to transform the tsv into a nicer display
        tf = TableFormatter()

        # map to rename header columns into more interpretable names
        tf.name_map = { "file" : "Sample",
                        "genome_covered_bases" : "Covered",
                        "genome_total_bases" : "Target Footprint",
                        "genome_covered_fraction" : "Percent Covered",
                        "amplicons_detected" : "Amplicons Detected"
                      }

        # map to transform selected row columns into more readable values
        tf.row_func = { "file" : lambda value : filename_to_sample(value),
                        "amplicons_detected" : lambda value : value.replace(",", ", "),
                        "genome_covered_fraction" : lambda value : "%.1f" % (float(value) * 100.0)
                      }

        tf.table_spec = "|c|c|c|c|c|p{5cm}|"
        tsv_to_table(table_path, tf)
    else:
        print(r"Negative control summary table not found.")
    return

# write the section of the report containing the tree-snps plot
# and the ambiguity report
def write_tree_section():
    print("\section{Sequence Variation}")

    tree_plot_path = args.tree_figure.format(run_name=args.run_name)
    write_image(tree_plot_path, 0.4)

    # Ambiguity subsection
    print(r"\subsection{Ambiguity Report}")

    if args.platform == "illumina":
        ambiguity_filename = args.ambiguity_table.format(run_name=args.run_name)
        row_count = count_tsv(ambiguity_filename)

        if row_count == 0:
            print(r"No positions in the genome had an ambiguous consensus base (IUPAC, but not N) in multiple samples.")
        else:
            s = "This table reports positions in the genome that had an ambiguous consensus base"\
                " (IUPAC, but not N) in multiple samples. This can be evidence of contamination"\
                " so these positions should be investigated."
            print(s)

            # Make the ambiguity table
            tf = TableFormatter()
            tf.name_map = { "position" : "Genome Position",
                            "count"    : "Number of ambiguous samples",
                            "alleles"  : "Observed Alleles" }
            tf.row_func = dict()
            tf.table_spec = "{|c|c|c|}"
            tsv_to_table(args.ambiguity_table.format(run_name=args.run_name), tf)
    else:
        print(r"The ambiguity report is not currently supported for Oxford Nanopore data")

    # Mixture/Contamination subsection
    print(r"\subsection{Mixture Report}")

    # The mixture table can be quite large so we report the samples as a list
    if args.platform == "illumina":
        mixture_report_fn = args.mixture_table.format(run_name=args.run_name)
        mixture_samples = set()
        with(open(mixture_report_fn)) as f:
            reader = csv.DictReader(f, delimiter="\t")
            for row in reader:
                mixture_samples.add(row['sample_a'])

        if len(mixture_samples) > 0:
            s = "The following samples were detected by \\texttt{mixture\_report.py} as having"\
                " read evidence for multiple distinct sequences. These samples should be checked"\
                " for contamation: "
            print(s + ", ".join([ "\\textbf{%s}" % escape_latex(a) for a in mixture_samples]) + ".")
        else:
            print(r"No samples were detected by \texttt{mixture\_report.py} as having read evidence for multiple distinct sequences.")
    else:
        print("The mixture report is not currently supported for Oxford Nanopore data")

# write the large per-sample QC table
def write_summary_qc_section():
    print(r"\section{Sample-level QC}")
    print(r"This table contains QC metrics and warning flags for each sample within this sequencing run.")

    tf = TableFormatter
    tf.size = "scriptsize"
    tf.name_map = { "sample" : "Sample",
                    "num_consensus_snvs" :  "Consensus SNVs",
                    "num_consensus_iupac" : "Consensus IUPAC",
                    "num_variants_snvs" : "Variant SNVs",
                    "num_variants_indel" : "Variant Indels",
                    "num_variants_indel_triplet" : "Variant Triplet Indels",
                    "qpcr_ct" : "ct",
                    "collection_date" : "Date",
                    "genome_completeness" : "Percent Complete",
                    "qc_pass" : "QC flags" }

    tf.row_func = { "qc_pass" : lambda value : value.replace(",", ", ").replace("POSSIBLE_FRAMESHIFT_INDELS", "POSSIBLE_FRAMESHIFT"),
                    "genome_completeness" : lambda value : "%.1f" % (float(value) * 100.0),
                    "qpcr_ct" : lambda value : format_ct(value) }

    tf.column_filter = [ "run_name", "mean_sequencing_depth",
                         "median_sequencing_depth", "num_consensus_n",
                         "num_weeks", "scaled_variants_snvs" ]
    tf.table_spec = "{|c|C{1.3cm}|C{1.3cm}|C{1.0cm}|C{1.0cm}|C{1.0cm}|c|c|C{1.2cm}|C{4.0cm}|}"
    tsv_to_table(args.summary_qc_table.format(run_name=args.run_name), tf)

# parse arguments, defaults are based on ncov-tools paths/filenames
parser = argparse.ArgumentParser()
parser.add_argument('--negative-control-depth-figure', type=str, default="plots/{run_name}_depth_by_position_negative_control.pdf")
parser.add_argument('--negative-control-table', type=str, default="qc_reports/{run_name}_negative_control_report.tsv")
parser.add_argument('--tree-figure', type=str, default="plots/{run_name}_tree_snps.pdf")
parser.add_argument('--ambiguity-table', type=str, default="qc_reports/{run_name}_ambiguous_position_report.tsv")
parser.add_argument('--mixture-table', type=str, default="qc_reports/{run_name}_mixture_report.tsv")
parser.add_argument('--summary-qc-table', type=str, default="qc_reports/{run_name}_summary_qc.tsv")
parser.add_argument('--negative-control-tsv', type=str, default="")
parser.add_argument('--run-name', type=str, default="", required=True)
parser.add_argument('--platform', type=str, default="", required=True)
args = parser.parse_args()

#
# Generate report
#
write_preamble()

print(r"\section{Summary}")
print("QC report generated for %s on %s by ncov-tools" % (escape_latex(args.run_name), datetime.today().strftime('%Y-%m-%d')))

write_tree_section()

write_negative_control_section()

write_summary_qc_section()

write_postamble()


from z3 import *

iters = [ Int(f"x{i}") for i in range(20) ]

solver = Solver()

for n,x in enumerate(iters):
    if n == 0:
        solver.add(x == 1111)
    else:
        last = iters[n - 1]
        solver.add(Or(x == last, (x * 2) == last, x == ((last * 3) + 1)))

solver.add(iters[-1] == 1)

print(solver.check())
print(solver.model())


from math import sqrt

cislo=float(input("Zadej číslo které chceš odmocnit: "))

# Osetrit si vstup od uzivatele, aby nam skript nespadl

if cislo < 0:
    print("Zadejte kladne cislo, zaporne nelze odmocnit")
elif cislo > 0:
    print("Odmocnina cisla ", cislo, "je ", sqrt(cislo))


# Webscraping is a process that can be used to automatically extract information from a website,
# and can easily be accomplished within a matter of minutes and not hours.

# In short term, Getting data from html web pages

# Beautiful Soup Objects
# Beautiful Soup is a Python library for pulling data out of HTML and XML files,
# we will focus on HTML files. This is accomplished by representing the HTML as a set of objects with methods used to parse the HTML.
# We can navigate the HTML as a tree and/or filter out what we are looking for.

from bs4 import BeautifulSoup
import requests

html = "<!DOCTYPE html><title>Page Title</title>
Lebron James

 Salary: $ 92,000,000

 Stephen Curry

 Salary: $85,000, 000

 Kevin Durant

 Salary: $73,200, 000
"
soup = BeautifulSoup(html, "html.parser")
# print(soup.prettify())

tag_object = soup.title # <title>Page Title</title>
# print("tag object:",tag_object)

type(tag_object) # <class 'bs4.element.Tag'>

tag_object = soup.h3 #
Lebron James

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

# The find_all() method looks through a tag’s descendants and retrieves all descendants that match your filters.
# The Method signature for find_all(name, attrs, recursive, string, limit, **kwargs)
# We can store it as a string in the variable table:
table_bs = BeautifulSoup(table, "html.parser")

# ---------------------------------------------------
table_bs.find_all(id="flight")

# find all the elements without href value
table_bs.find_all(href=False)

# With string you can search for strings instead of tags,
# where we find all the elments with Florida.
table_bs.find_all(string="Florida")

# Scrape data from HTML tables into a DataFrame using BeautifulSoup and read_html
# ....
# ....


import threading
import time
import requests
import xlwt
from xlwt import Workbook
from flask import Flask, json
import os
import datetime
from datetime import timedelta
from google.cloud._helpers import UTC

DEBUG = False

class WorkLoadGenerator:

    def __init__(self):
        self.atomic_workers_running = self.AtomicInteger()
        self.nr_work_success = self.AtomicInteger()
        self.nr_work_fail = self.AtomicInteger()
        self.logger_stop = self.AtomicInteger()
        self.logger_stop.set_value(0)
        self.run_time = []
        if not DEBUG:
            self.master_ip = "35.228.95.170"  # REAL DEAL
            self.split_port = "5000"
        else:
            self.master_ip = "localhost"
            self.split_port = "5001"

    def create_workload(self, nr_workers, post_intervall):

        thread_logger = threading.Thread(target=self.logger_thread, args=(self.atomic_workers_running, self.logger_stop))
        thread_logger.start()

        thread_list = []
        for i in range(nr_workers):
            print("Starting thread: %d" % i)
            thread = threading.Thread(target=self.worker_load, args=(self.atomic_workers_running, self.nr_work_success, self.nr_work_fail))
            thread_list.append(thread)
            thread.start()
            time.sleep(post_intervall)

        for thread in thread_list:
            thread.join()
        print("workers_running: " + self.atomic_workers_running.get_str())
        print("work_success: " + self.nr_work_success.get_str())
        print("work_fail: " + self.nr_work_fail.get_str())
        self.logger_stop.set_value(1)
        thread_logger.join()

        # Workbook is created
        wb = Workbook()
        # add_sheet is used to create sheet.
        sheet1 = wb.add_sheet('Sheet 1')
        row_count = 0

        avg_time = 0
        if len(self.run_time) != 0:
            for temp in self.run_time:
                temp_runtime = temp[0]
                temp_time = temp[1]
                avg_time += temp_runtime
                time_str = time.strftime("%H:%M:%S", time.localtime(temp_time))
                sheet1.write(row_count, 0, time_str)
                sheet1.write(row_count, 1, int(temp_runtime))
                row_count += 1
                print(time_str + " : " + str(temp_runtime))
            print("Avg time: %.2f" % (avg_time / self.nr_work_success.get_value()))
        wb.save('worker runtime.xls')
        print("Thread has finished")

    def logger_thread(self, atomic_workers_running, logger_stop):

        # Workbook is created
        wb = Workbook()
        # add_sheet is used to create sheet.
        sheet1 = wb.add_sheet('Sheet 1')

        row_count = 0
        start_time = time.time()
        expired_time = start_time + 10 * 60
        while time.time() < expired_time:
            named_tuple = time.localtime(time.time())  # get struct_time
            time_string = time.strftime("%H:%M:%S", named_tuple)
            workers_running = atomic_workers_running.get_value()
            print(str(time_string) + " " + str(workers_running))
            sheet1.write(row_count, 0, time_string)
            sheet1.write(row_count, 1, workers_running)
            row_count += 1

            temp_stop = logger_stop.get_value()
            if temp_stop == 1:
                break
            time.sleep(30)
        wb.save('worker_at_time.xls')

    def worker_load(self, atomic_workers_running, nr_work_success, nr_work_fail):
        atomic_workers_running.increase_value()

        request_connect = "http://" + self.master_ip + ":5000/client/connect"
        request_retrieve = "http://" + self.master_ip + ":5000/client/retrieve"

        start_time = time.time()
        expired_time_small = start_time + 5*60
        expired_time_big = start_time + 10*60

        while True:
            slip_ip = None
            uuid_name = None
            print("Stage 1")
            while True:
                try:
                    res = requests.get(request_connect)
                    if res.status_code == 200:
                        data = res.json()
                        slip_ip = data["ip"]
                        print("Success: Got split ip from master: " + slip_ip)
                        break
                    else:
                        print("Error: Retrying getting split ip")
                except:
                    print("Error: Retrying ip from master")
                if time.time() > expired_time_small:
                    break
                time.sleep(1)

            request_workload = "http://" + slip_ip + ":" + self.split_port + "/split_workload"

            print("Stage 2")
            try:
                res = requests.post(request_workload)
                if res.status_code == 200:
                    data = res.json()
                    uuid_name = data["id"]
                    print("Success: movie uploaded on split worker, uuid:" + uuid_name)
                else:
                    print("Error: Uploading movie to split worker ip: " + slip_ip)
            except:
                print("Error: Uploading movie to split worker ip: " + slip_ip)

            print("Stage 3")
            try:
                res = requests.post(request_retrieve, json=({'id': uuid_name}))
                if res.status_code == 200:
                    data = res.json()
                    print("Success: retrieved downloadUrl: " + data["downloadUrl"])
                    break
                else:
                    print("Error: on retrieved downloadUrl with uuid: " + uuid_name)
            except:
                print("Error: on retrieved downloadUrl with uuid: " + uuid_name)

            if time.time() > expired_time_small:
                nr_work_fail.increase_value()
                atomic_workers_running.decrease_value()
                break
            time.sleep(1)

            if time.time() > expired_time_big:
                nr_work_fail.increase_value()
                atomic_workers_running.decrease_value()
                return
        current_time = time.time()
        self.run_time.append((current_time - start_time, current_time))
        nr_work_success.increase_value()
        atomic_workers_running.decrease_value()

    class AtomicInteger(object):
        """
        Class representing an atomic integer.
        Creates an thread safe integer, set and get must be used to be thread safe.
        """

        def __init__(self):
            self.value = 0
            self.atomic_lock = threading.Lock()

        def increase_value(self):
            """
            Increase value by one
            :param value: Wanted value
            """
            self.atomic_lock.acquire()
            self.value += 1
            self.atomic_lock.release()

        def decrease_value(self):
            """
            Decrease value by one
            :param value: Wanted value
            """
            self.atomic_lock.acquire()
            self.value -= 1
            self.atomic_lock.release()

        def get_str(self):
            self.atomic_lock.acquire()
            temp = str(self.value)
            self.atomic_lock.release()
            return temp

        def set_value(self, value):
            """
            Changes the value of atomic integer
            :param value: Wanted value
            """
            self.atomic_lock.acquire()
            self.value = value
            self.atomic_lock.release()

        def get_value(self):
            """
            Returns the atomic integer.
            :return: The atomic integer.
            """
            self.atomic_lock.acquire()
            temp = self.value
            self.atomic_lock.release()
            return temp


# -------------------------------------------------------------------
# Tools to create synthetic waveforms.
# Synthetic and rotation.
#
# Author: Liang Ding
# Email: myliang.ding@mail.utoronto.ca
# -------------------------------------------------------------------

import numpy as np

def DSynRotateRTZ(mt, SGTs, ba_rad, n_lens):
    '''

    :param mt:      The calibrated moment tensor: [Mxx, Myy, Mzz, 2*Mxy, 2*Mxz, 2*Mxz]

                    * r-theta-phi to XYZ
                    * Mrr = Mzz
                    * Mtt = Myy
                    * Mpp = Mxx
                    * Mrt = -Myz
                    * Mrp = Mxz
                    * Mtp = -Mxy

    :param SGTs:    The strain Green's tensor. ordered in N-E-Z
    :param ba_rad:  The back azimuth in radius.
    :n_lens:        The length of the SGT data.
    :return:
    '''

    u_rtz = np.zeros((3, n_lens))
    #  N-E-Z from SGT to RTZ in displacement.
    e = np.dot(SGTs[:, 1, :], mt)
    n = np.dot(SGTs[:, 0, :], mt)
    u_rtz[2] = np.dot(SGTs[:, 2, :], mt)

    u_rtz[0] = - e * np.sin(ba_rad) - n * np.cos(ba_rad)
    u_rtz[1] = - e * np.cos(ba_rad) + n * np.sin(ba_rad)

    return u_rtz

def DSynENZ(mt, SGTs, n_lens):
    '''

    :param mt:      The calibrated moment tensor: [Mxx, Myy, Mzz, 2*Mxy, 2*Mxz, 2*Mxz]

                    * r-theta-phi to XYZ
                    * Mrr = Mzz
                    * Mtt = Myy
                    * Mpp = Mxx
                    * Mrt = -Myz
                    * Mrp = Mxz
                    * Mtp = -Mxy

    :param SGTs:    The strain Green's tensor. ordered in N-E-Z
    :param ba_rad:  The back azimuth in radius.
    :n_lens:        The length of the SGT data.
    :return:
    '''

    u_enz = np.zeros((3, n_lens))
    #  N-E-Z from SGT to RTZ in displacement.
    u_enz[0] = np.dot(SGTs[:, 1, :], mt)
    u_enz[1] = np.dot(SGTs[:, 0, :], mt)
    u_enz[2] = np.dot(SGTs[:, 2, :], mt)
    return u_enz

def DENZ2RTZ(enz_arr, ba_rad):
    '''
    Convert the data from E-N-Z to R-T-Z system.

    :param enz_arr: The data in E-N-Z
    :param ba_rad:  The back azimuth in radius.
    :return: Data in R-T-Z.
    '''

    rtz_arr = np.zeros_like(enz_arr)

    rtz_arr[2] = enz_arr[2]
    rtz_arr[0] = - enz_arr[0] * np.sin(ba_rad) - enz_arr[1] * np.cos(ba_rad)
    rtz_arr[1] = - enz_arr[0] * np.cos(ba_rad) + enz_arr[1] * np.sin(ba_rad)

    return rtz_arr


import Crossfire
import string
import random
import sys
import os
import CFItemBroker

class DialogRule:
    def __init__(self, keywords, presemaphores, messages, postsemaphores, suggested_response = None):
        self.__keywords = keywords
        self.__presems = presemaphores
        self.__messages = messages
        self.__postsems = postsemaphores
        self.__suggestions = suggested_response
        self.__prefunction = None

    # The keyword is a string.  Multiple keywords may be defined in the string
    # by delimiting them with vertical bar (|) characters.  "*" is a special
    # keyword that matches anything.
    def getKeyword(self):
        return self.__keywords

    # Messages are stored in a list of strings.  One or more messages may be
    # defined in the list.  If more than one message is present, a random
    # string is returned.
    def getMessage(self):
        msg = self.__messages
        l = len(msg)
        r = random.randint(0, l - 1)
        return msg[r]

    # Return the preconditions of a rule.  They are a list of one or more lists
    # that specify a flag name to check, and one or more acceptable values it
    # may have in order to allow the rule to be triggered.
    def getPreconditions(self):
        return self.__presems

    # Return the postconditions for a rule.  They are a list of one or more
    # lists that specify a flag to be set in the player file and what value it
    # should be set to.
    def getPostconditions(self):
        return self.__postsems

    # Return the possible responses to this rule
    # This is when a message is sent.
    def getSuggests(self):
        return self.__suggestions

    # Return a possible pre function, that will be called to ensure the rule matches.
    def getPreFunction(self):
        return self.__prefunction

    # Define a prefunction that will be called to match the rule.
    def setPreFunction(self, function):
        self.__prefunction = function

# This is a subclass of the generic dialog rule that we use for determining whether to
# 'include' additional rules.
class IncludeRule(DialogRule):
    def __init__(self, presemaphores):
        DialogRule.__init__(self, None, presemaphores, None, None, None )

class Dialog:
    # A character is the source that supplies keywords that drive the dialog.
    # The speaker is the NPC that responds to the keywords. A location is an
    # unique identifier that is used to distinguish dialogs from each other.
    def __init__(self, character, speaker, location):
        self.__character = character
        self.__location = location
        self.__speaker = speaker
        self.__rules = []

    # Create rules of the DialogRule class that define dialog flow. An index
    # defines the order in which rules are processed.  FIXME: addRule could
    # very easily create the index.  It is unclear why this mundane activity
    # is left for the dialog maker.
    def addRule(self, rule, index):
        self.__rules.insert(index, rule)

    # A function to call when saying something to an NPC to elicit a response
    # based on defined rules. It iterates through the rules and determines if
    # the spoken text matches a keyword.  If so, the rule preconditions and/or
    # prefunctions are checked.  If all conditions they define are met, then
    # the NPC responds, and postconditions, if any, are set.  Postfunctions
    # also execute if present.
    # some variable substitution is done on the message here, $me and $you
    # are replaced by the names of the npc and the player respectively
    def speak(self, msg):
        # query the animation system in case the NPC is playing an animation
        if self.__speaker.Event(self.__speaker, self.__speaker, "query_object_is_animated", 1):
            return 0

        key = self.uniqueKey()
        replies = None
        if key in Crossfire.GetPrivateDictionary():
          replies = Crossfire.GetPrivateDictionary()[key]
          Crossfire.GetPrivateDictionary()[key] = None

        for rule in self.__rules:
            if self.isAnswer(msg, rule.getKeyword()) == 1:
                if self.matchConditions(rule) == 1:
                    message = rule.getMessage()
                    message = message.replace('$me', self.__speaker.QueryName())
                    message = message.replace('$you', self.__character.QueryName())

                    Crossfire.NPCSay(self.__speaker, message);
                    if rule.getSuggests() != None:
                        for reply in rule.getSuggests():
                            Crossfire.AddReply(reply[0], reply[1])
                        Crossfire.GetPrivateDictionary()[key] = rule.getSuggests()
                    self.setConditions(rule)

                    # change the player's text if found
                    if replies != None:
                        for reply in replies:
                            if reply[0] == msg:
                                type = Crossfire.ReplyType.SAY
                                if len(reply) > 2:
                                    type = int(reply[2])
                                Crossfire.SetPlayerMessage(reply[1], type)
                                break

                    return 0
        return 1

    def uniqueKey(self):
      return self.__location + '_' + self.__character.QueryName()

    # Determine if the message sent to an NPC matches a string in the keyword
    # list. The match check is case-insensitive, and succeeds if a keyword
    # string is found in the message.  This means that the keyword string(s)
    # only need to be a substring of the message in order to trigger a reply.
    def isAnswer(self, msg, keywords):
        for ckey in keywords:
            if ckey == "*" or msg.lower().find(ckey.lower()) != -1:
                return 1
        return 0

    # Check the preconditions specified in rule have been met.  Preconditions
    # are lists of one or more conditions to check.  Each condition specifies
    # a check to perform and the options it should act on.
    # separate files are used for each type of check.
    def matchConditions(self, rule):
        character = self.__character
        location = self.__location
        speaker = self.__speaker
        verdict = True
        for condition in rule.getPreconditions():
            action = condition[0]
            args = condition[1:]
            path = os.path.join(Crossfire.DataDirectory(), Crossfire.MapDirectory(), 'python/dialog/pre/', action + '.py')
            if os.path.isfile(path):
                try:
                    exec(open(path).read())
                except:
                    Crossfire.Log(Crossfire.LogError, "CFDialog: Failed to evaluate condition %s." % condition)
                    verdict = False
                if verdict == False:
                    return 0
            else:
                Crossfire.Log(Crossfire.LogError, "CFDialog: Pre Block called with unknown action %s." % action)
                return 0

        if rule.getPreFunction() != None:
            if rule.getPreFunction()(self.__character, rule) != True:
                return 0
        return 1

    # If a rule triggers, this function goes through each condition and runs the file that handles it.
    def setConditions(self, rule):
        character = self.__character
        location = self.__location
        speaker = self.__speaker

        for condition in rule.getPostconditions():
            Crossfire.Log(Crossfire.LogDebug, "CFDialog: Trying to apply %s." % condition)
            action = condition[0]
            args = condition[1:]
            path = os.path.join(Crossfire.DataDirectory(), Crossfire.MapDirectory(), 'python/dialog/post/', action + '.py')
            if os.path.isfile(path):
                try:
                    exec(open(path).read())
                except:
                    Crossfire.Log(Crossfire.LogError, "CFDialog: Failed to set post-condition %s." %condition)
            else:
                Crossfire.Log(Crossfire.LogError, "CFDialog: Post Block called with unknown action %s." % action)

    # Search the player file for a particular flag, and if it exists, return
    # its value.  Flag names are combined with the unique dialog "location"
    # identifier, and are therefore are not required to be unique.  This also
    # prevents flags from conflicting with other non-dialog-related contents
    # in the player file.
    def getStatus(self, key):
        character_status=self.__character.ReadKey("dialog_"+self.__location);
        if character_status == "":
            return "0"
        pairs=character_status.split(";")
        for i in pairs:
            subpair=i.split(":")
            if subpair[0] == key:
                return subpair[1]
        return "0"

    # Store a flag in the player file and set it to the specified value.  Flag
    # names are combined with the unique dialog "location" identifier, and are
    # therefore are not required to be unique.  This also prevents flags from
    # conflicting with other non-dialog-related contents in the player file.
    def setStatus(self, key, value):
        if value == "*":
            return
        ishere = 0
        finished = ""
        character_status = self.__character.ReadKey("dialog_"+self.__location);
        if character_status != "":
            pairs = character_status.split(";")
            for i in pairs:
                subpair = i.split(":")
                if subpair[0] == key:
                    subpair[1] = value
                    ishere = 1
                if finished != "":
                    finished = finished+";"
                finished = finished + subpair[0] + ":" + subpair[1]
        if ishere == 0:
            if finished != "":
                finished = finished + ";"
            finished = finished + key + ":" + value
        self.__character.WriteKey("dialog_" + self.__location, finished, 1)

    # Search the NPC for a particular flag, and if it exists, return
    # its value.  Flag names are combined with the unique dialog "location"
    # identifier and the player's name, and are therefore are not required
    # to be unique.  This also prevents flags from conflicting with other
    # non-dialog-related contents in the NPC.
    def getNPCStatus(self, key):
        npc_status=self.__speaker.ReadKey("dialog_"+self.__location + "_" + self.__character.Name);
        if npc_status == "":
            return "0"
        pairs=npc_status.split(";")
        for i in pairs:
            subpair=i.split(":")
            if subpair[0] == key:
                return subpair[1]
        return "0"

    # Store a flag in the NPC and set it to the specified value.  Flag
    # names are combined with the unique dialog "location" identifier
    # and the player's name, and are therefore are not required to be unique.
    # This also prevents flags from conflicting with other non-dialog-related
    # contents in the player file.
    def setNPCStatus(self, key, value):
        if value == "*":
            return
        ishere = 0
        finished = ""
        npc_status = self.__speaker.ReadKey("dialog_"+self.__location + "_" + self.__character.Name);
        if npc_status != "":
            pairs = npc_status.split(";")
            for i in pairs:
                subpair = i.split(":")
                if subpair[0] == key:
                    subpair[1] = value
                    ishere = 1
                if finished != "":
                    finished = finished+";"
                finished = finished + subpair[0] + ":" + subpair[1]
        if ishere == 0:
            if finished != "":
                finished = finished + ";"
            finished = finished + key + ":" + value
        self.__speaker.WriteKey("dialog_" + self.__location + "_" + self.__character.Name, finished, 1)


from django import template
from ..models import Assignment, Response

register = template.Library()

@register.filter(name='assigned')
def assigned(student, assignment_id):
    css_class = ''
    assignment = Assignment.objects.get(id=assignment_id)
    if student.is_assigned(assignment_id):
        css_class = 'success'
    elif assignment.is_overdue:
        css_class = 'danger'
    return css_class

@register.filter(name='response_file_name')
def response_file_name(student, assignment_id):
    try:
        assignment = Assignment.objects.get(id=assignment_id)
        response = assignment.response_set.get(
            student=student)
        file_name = response.file_name
        print(file_name)
    except:
        file_name = ''

    return file_name

@register.filter(name='response_file_url')
def response_file_url(student, assignment_id):
    try:
        assignment = Assignment.objects.get(id=assignment_id)
        response = assignment.response_set.get(
            student=student)
        file_url = response.file_url
    except:
        file_url = ''

    return file_url

@register.filter(name='text_response')
def text_response(student, assignment_id):
    try:
        assignment = Assignment.objects.get(id=assignment_id)
        response = assignment.response_set.get(
            student=student)
        text_response = response.text_response
    except:
        text_response = ''

    return text_response


from itertools import count
print("La somme de tout les diviseurs propres:")
def get_factors(n):
    liste=[]
    for i in range(1,n+1):
        if n%i==0:
            liste.append(i)
    return liste.count()

print(get_factors(8))


from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy import ForeignKey
from sqlalchemy.orm import synonym, relationship
from datetime import date

builtin_list = list

db = SQLAlchemy()

def init_app(app):
    # Disable track modifications, as it unnecessarily uses memory.
    app.config.setdefault('SQLALCHEMY_TRACK_MODIFICATIONS', False)
    db.init_app(app)

def from_sql(row):
    """Translates a SQLAlchemy model instance into a dictionary"""
    data = row.__dict__.copy()
    data['id'] = row.id
    data.pop('_sa_instance_state')
    return data

# [START truck model]
class Truck(db.Model):
    __tablename__ = 'Truck'

    truckId = db.Column(db.Integer, primary_key=True)
    weightCapacity = db.Column(db.Numeric())
    inUse = db.Column(db.Numeric())
    type = db.Column(db.String(7))
    costPerMile = db.Column(db.Numeric())
    maxVolume = db.Column(db.Numeric())
    carrier = db.Column(db.String(30))
    id = synonym("truckId")

    def __repr__(self):
        return "<Truck(id='%i', carrier=%s)" % (self.truckId, self.carrier)

# [END truck model]

class Delivery(db.Model):
    __tablename__ = 'Delivery'

    truckId = db.Column(db.Integer, primary_key=True)
    orderId = db.Column(db.Integer, primary_key=True)
    deliveryDate = db.Column(db.Date())
    id = synonym("truckId")

class Order(db.Model):
    __tablename__ = 'Orders'

    orderId = db.Column(db.Integer, primary_key=True)
    weight = db.Column(db.Numeric())
    destStreetName = db.Column(db.String(20))
    destStreetNumber = db.Column(db.Integer)
    destAptNumber = db.Column(db.String(10))
    destCity = db.Column(db.String(30))
    destState = db.Column(db.String(2))
    destZip = db.Column(db.Integer)
    originStreetName = db.Column(db.Integer)
    originStreetNumber = db.Column(db.Integer)
    originAptNumber = db.Column(db.String(10))
    originCity = db.Column(db.String(30))
    originState = db.Column(db.String(2))
    originZip = db.Column(db.Integer)
    volume = db.Column(db.Numeric())
    dateOrdered = db.Column(db.Date())
    orderStatus = db.Column(db.String(16))
    id = synonym("orderId")

    def __repr__(self):
        if self.destAptNumber is None:
            return "<Order(id='%i'\nDestination Address:\n%i %s\n%s, %s, %i\n\nStatus='%s')" % (
                self.orderId, self.destStreetNumber, self.destStreetName, self.destCity, self.destState, self.destZip,
                self.orderStatus)
        return "<Order(id='%i'\nDestination Address:\n%i %s\n%s\n%s, %s, %i\n\nStatus='%s')" % (
            self.orderId, self.destStreetNumber, self.destStreetName, self.destAptNumber, self.destCity, self.destState,
            self.destZip, self.orderStatus)

class Item(db.Model):
    __tablename__ = 'Item'

    itemId = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(30))
    stock = db.Column(db.Integer)
    category = db.Column(db.String(30))
    weight = db.Column(db.Numeric())
    volume = db.Column(db.Numeric())
    id = synonym("itemId")

    def __repr__(self):
        return "<Item(id='%i' name='%s' stock='%i' weight='%f')" % (self.itemId, self.name, self.stock, self.weight)

class ItemsOrdered(db.Model):
    __tablename__ = 'ItemsOrdered'

    itemId = db.Column(db.Integer, primary_key=True)
    orderId = db.Column(db.Integer, primary_key=True)
    amount = db.Column(db.Integer)
    id = synonym('orderId')

# [START list]
def list():
    query = (Truck.query
             .order_by(Truck.costPerMile))
    trucks = builtin_list(map(from_sql, query.all()))
    return (trucks)

# [END list]

# [START read]
def read(id):
    result = Truck.query.get(id)
    if not result:
        return None
    return from_sql(result)

# [END read]

# [START create]
def create(data):
    print(data)
    truck = Truck(**data)
    db.session.add(truck)
    db.session.commit()
    return from_sql(truck)

# [END create]

# [START update]
def update(data, id):
    truck = Truck.query.get(id)
    for k, v in data.items():
        setattr(truck, k, v)
    db.session.commit()
    return from_sql(truck)

# [END update]

def delete(id):
    Truck.query.filter_by(id=id).delete()
    db.session.commit()

# [START list]
def listItem():
    query = (Item.query
             .order_by(Item.itemId))
    items = builtin_list(map(from_sql, query.all()))
    return (items)

# [END list]

# [START read]
def readItem(id):
    result = Item.query.get(id)
    if not result:
        return None
    return from_sql(result)

# [END read]

# [START create]
def createItem(data):
    item = Item(**data)
    db.session.add(item)
    db.session.commit()
    return from_sql(item)

# [END create]

# [START update]
def updateItem(data, id):
    item = Item.query.get(id)
    for k, v in data.items():
        setattr(item, k, v)
    db.session.commit()
    print(item)
    return from_sql(item)

# [END update]

def deleteItem(id):
    Item.query.filter_by(id=id).delete()
    db.session.commit()

# [START list]
def listOrder():
    query = (Order.query
             .order_by(Order.orderId))
    order = builtin_list(map(from_sql, query.all()))
    return (order)

# [END list]

# [START read]
def readOrder(id):
    result = Order.query.get(id)
    if not result:
        return None
    return from_sql(result)

# [END read]

# [START create]
def createOrder(data):
    order = Order(**data)
    order.volume = 0.0
    order.weight = 0.0
    order.orderStatus = "Processing"
    db.session.add(order)
    db.session.commit()
    return from_sql(order)

# [END create]

# [START update]
def updateOrder(data, id):
    order = Order.query.get(id)
    for k, v in data.items():
        setattr(order, k, v)
    db.session.commit()
    return from_sql(order)

# [END update]

def deleteOrder(id):
    Order.query.filter_by(id=id).delete()
    db.session.commit()

def updateItemsOrdered(data, itemId, orderId):
    item = ItemsOrdered.query.get((itemId, orderId))
    amount = int(data['amount']) + item.amount
    if amount <= 0:
        deleteItemsOrdered(itemId, orderId)
        return None
    else:
        setattr(item, 'amount', amount)
        db.session.commit()
        return from_sql(item)

def findItemsOrdered(itemId, orderId):
    query = ItemsOrdered.query.filter_by(itemId=itemId, orderId=orderId).first()
    if query is None:
        return None
    return from_sql(query)

def addItemsOrdered(itemId, orderId, amount):
    if amount == 0:
        return None
    data = {'orderId': orderId, 'itemId': itemId, 'amount': amount}
    order = Order.query.get(orderId)
    item = readItem(itemId)
    item['stock'] = item['stock'] - int(amount)
    if ItemsOrdered.query.get((itemId, orderId)) is None:
        orderItem = ItemsOrdered(**data)
        db.session.add(orderItem)
        db.session.commit()
    else:
        orderItem = updateItemsOrdered(data, itemId, orderId)

    newItem = updateItem(item, itemId)
    newWeight = (float(newItem['weight']) * int(amount)) + float(order.weight)
    newVolume = (float(newItem['volume']) * int(amount)) + float(order.volume)
    newOrder = from_sql(order)
    newOrder['weight'] = newWeight
    newOrder['volume'] = newVolume
    updateOrder(newOrder, orderId)
    return orderItem

def readItemsOrdered(id):
    query = ItemsOrdered.query.filter_by(orderId=id)
    result = builtin_list(map(from_sql, query.all()))
    if not result:
        return None
    return result

def deleteItemsOrdered(itemId, orderId):
    ItemsOrdered.query.filter_by(itemId=itemId, orderId=orderId).delete()
    db.session.commit()

def readDelivery(id):
    query = Delivery.query.filter_by(truckId=id)
    result = builtin_list(map(from_sql, query.all()))
    if not result:
        return None
    return result

def createDelivery(truckId, orderId):
    data = {'truckId': truckId, 'orderId': orderId, 'deliveryDate': None}
    delivery = Delivery(**data)
    db.session.add(delivery)
    db.session.commit()
    return from_sql(delivery)

def deliverItems(truckId):
    query = Delivery.query.filter_by(truckId=truckId).all()
    deliveries = builtin_list(map(from_sql, query))

    for order in deliveries:
        shippedOrder = readOrder(order['orderId'])
        shippedOrder['orderStatus'] = "Delivered"
        updateOrder(shippedOrder, order['orderId'])

def findTrucks(id):
    newOrder = from_sql(Order.query.get(id))
    notInUsetruck = Truck.query.filter_by(inUse=0).all()
    trucks = builtin_list(map(from_sql, notInUsetruck))
    currentAvailible = []

    for truck in trucks:
        weight = 0.0
        volume = 0.0
        # find all orders a given truck is currently shipping
        trucksOrder = Delivery.query.filter_by(truckId=truck['id']).all()
        trucksOrders = builtin_list(map(from_sql, trucksOrder))
        # add up the current volume and weight for all of the trucks orders
        for order in trucksOrders:
            currentOrder = Order.query.get(order['orderId'])
            weight += float(currentOrder.weight)
            volume += float(currentOrder.volume)
        # if there is room on the truck for the new order add it to the list
        if weight + float(newOrder['weight']) <= float(truck['weightCapacity']) and volume + float(
                newOrder['weight']) <= truck['maxVolume']:
            currentAvailible.append(truck)
    return currentAvailible


#!/usr/bin/env python3
# -*- coding utf-8 -*-
from transformers import pipeline

"""
使用OWL-ViT模型进行目标检测
"""

if __name__ == '__main__':
    # 加载模型
    detector = pipeline(model="google/owlvit-base-patch32", task="zero-shot-object-detection")

    # 进行检测
    detected = detector(
        "./data/cat.jpg",
        candidate_labels=["cat", "dog", "truck", "couch", "remote"],
    )

    # 输出检测到的物体
    print(detected)

"""
输出：
[{'score': 0.2868116796016693, 'label': 'cat', 'box': {'xmin': 324, 'ymin': 20, 'xmax': 640, 'ymax': 373}},
{'score': 0.2770090401172638, 'label': 'remote', 'box': {'xmin': 40, 'ymin': 72, 'xmax': 177, 'ymax': 115}},
{'score': 0.2537277638912201, 'label': 'cat', 'box': {'xmin': 1, 'ymin': 55, 'xmax': 315, 'ymax': 472}},
{'score': 0.14742951095104218, 'label': 'remote', 'box': {'xmin': 335, 'ymin': 74, 'xmax': 371, 'ymax': 187}},
{'score': 0.12083035707473755, 'label': 'couch', 'box': {'xmin': 4, 'ymin': 0, 'xmax': 642, 'ymax': 476}}]
"""


from django.urls import path
from blog_learning import views

urlpatterns = [
    path('', views.lista_posts, name='lista_posts'),
    path('filtrar-fecha/', views.filtrar_por_fecha, name='filtrar_por_fecha'),
    path('blog-detalle/<int:post_id>/', views.detalle_post, name='detalle_post'),
    path('blog-crear/', views.crear_post, name='crear_post'),
    path('blog-editar/<int:post_id>/', views.editar_post, name='editar_post'),
    path('blog-eliminar/<int:post_id>/', views.eliminar_post, name='eliminar_post'),
    path('about/', views.about, name='about'),
]


class Solution:
    def findKthLargest(self, nums: List[int], k: int) -> int:
        heap = []

        for x in nums:
            if len(heap) == k:
                heappushpop(heap, x)
            else:
                heappush(heap, x)

        return heappop(heap)


import os
import tkinter as tk
from tkinter import messagebox
from tkinter import filedialog
from tkinter import ttk
import time
import threading

try:
    from pip._internal import main as pip_main
except ImportError:
    # Show an error message if 'pip' module is not available
    messagebox.showerror("Error", "The 'pip' module is not available. Make sure you have Python and pip installed correctly.")
    exit()

# Automatic installation of missing dependencies
missing_modules = []
required_modules = ['chardet']
for module in required_modules:
    try:
        __import__(module)
    except ImportError:
        # Add missing module to the list
        missing_modules.append(module)

    # Install missing modules using pip
    for module in missing_modules:
        pip_main(['install', module])

valid_extensions = ['.ACFM', '.AMFM', '.DFONT', '.EOT', '.FNT', '.FON', '.GDF', '.GDR', '.GTF', '.MMM', '.OTF', '.PFA', '.TPF', '.TTC', '.TTF', '.WOFF']
import chardet

class SearchThread(threading.Thread):
    def __init__(self, path, search_mode, exclude_strings, progressbar, progress_text, results_text, results_label_var):
        super().__init__()
        self.path = path
        self.search_mode = search_mode
        self.exclude_strings = exclude_strings
        self.progressbar = progressbar
        self.progress_text = progress_text
        self.results_text = results_text
        self.results_label_var = results_label_var
        self.font_copyright_found = False
        self.num_results = 0

    def run(self):
        # Initialize progress and results display
        self.progressbar["value"] = 0
        self.progress_text.set("Analized fonts 0/0 (0.00%) - Remaining Time: 0.00 seconds")
        self.results_text.delete(1.0, tk.END)
        self.results_label_var.set("Results: 0 found")

        # Start the search
        self.search()

        # Display a message if no results were found
        results_available = self.font_copyright_found
        if not results_available:
            self.results_text.insert(tk.END, "No copyrighted fonts found.")

    def search(self):
        # Check if the path is a directory
        if not os.path.isdir(self.path):
            messagebox.showerror("Error", "The specified path is not a valid directory.")
            return

        results = []

        # Count the total number of valid font files
        total_files = 0
        for root_dir, _, files in os.walk(self.path):
            for file in files:
                extension = os.path.splitext(file)[1].upper()
                if extension in valid_extensions:
                    total_files += 1

        progress = 0
        start_time = time.time()

        # Search through the directory and its subdirectories for font files
        for root_dir, _, files in os.walk(self.path):
            for file in files:
                file_path = os.path.join(root_dir, file)

                extension = os.path.splitext(file_path)[1].upper()
                if extension not in valid_extensions:
                    continue

                # Check the file size
                if os.path.getsize(file_path) <= 10 * 1024 * 1024:  # Maximum size of 10 MB
                    # Detect file encoding
                    with open(file_path, 'rb') as f:
                        raw_data = f.read()
                        encoding = chardet.detect(raw_data)['encoding']

                    try:
                        # Open the file in read mode with the detected encoding
                        with open(file_path, 'r', encoding=encoding, errors='ignore') as f:
                            content = f.read()

                            # Check if the search mode is "monotype"
                            if self.search_mode == "monotype":
                                # If "monotype" is found in the file content, add the file path to the results
                                if "monotype" in content.lower():
                                    results.append(file_path)
                                    self.font_copyright_found = True
                                    self.num_results += 1
                            else:
                                # Check if any exclude string is not present and at least one keyword is present in the file content
                                if all((exclude_string.lower() not in content.lower() for exclude_string in self.exclude_strings)) \
                                        and any((keyword in content.lower() for keyword in ["copyright", "trademark"])):
                                    results.append(file_path)
                                    self.font_copyright_found = True
                                    self.num_results += 1
                    except UnicodeDecodeError:
                        pass

                progress += 1
                elapsed_time = time.time() - start_time
                remaining_files = total_files - progress
                remaining_time = elapsed_time * (remaining_files / progress) if progress > 0 else 0
                self.progressbar["value"] = (progress / total_files) * 100
                self.progress_text.set(
                    f"Analized fonts {progress}/{total_files} ({self.progressbar['value']:.2f}%) - Remaining Time: {remaining_time:.2f} seconds")
                self.results_text.delete(1.0, tk.END)
                self.results_text.insert(tk.END, "\n".join(results))
                self.results_label_var.set(f"Results: {self.num_results} founds")

                # Update the GUI
                self.progressbar.update_idletasks()
                self.results_text.update_idletasks()

            if progress == total_files:
                break

class Application(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("Copyrighted Fonts Finder")
        self.geometry("1200x600")
        self.configure(bg="#F0F0F0")

        # Dropzone label
        self.dropzone_label = tk.Label(self, text="Select a folder", font=("Arial", 16, "bold"), bg="#F0F0F0")
        self.dropzone_label.pack(pady=20)

        # Folder selection entry
        self.entry = tk.Entry(self, width=70, font=("Arial", 12))
        self.entry.pack(pady=10)

        # Browse button
        self.browse_button = tk.Button(self, text="Browse", command=self.select_folder,
                                       font=("Arial", 12, "bold"), bg="#FF9800", fg="black", relief=tk.RAISED, width=10)
        self.browse_button.pack(pady=10)

        # Search mode selection (radio buttons)
        self.mode_var = tk.StringVar()
        self.mode_var.set("copyright")

        self.radio_frame = tk.Frame(self, bg="#F0F0F0")
        self.radio_frame.pack(pady=10)

        self.radio_monotype = tk.Radiobutton(self.radio_frame, text="Only Monotype Fonts", variable=self.mode_var,
                                             value="monotype", font=("Arial", 12), bg="#F0F0F0")
        self.radio_monotype.pack(side=tk.LEFT, padx=10)

        self.radio_copyright = tk.Radiobutton(self.radio_frame, text="Any Copyright/Trademark ",
                                               variable=self.mode_var, value="copyright", font=("Arial", 12),
                                               bg="#F0F0F0")
        self.radio_copyright.pack(side=tk.LEFT)

        # Search button
        self.search_button = tk.Button(self, text="Search", command=self.start_search,
                                       font=("Arial", 12, "bold"), bg="#1E90FF", fg="black", relief=tk.RAISED, width=10)
        self.search_button.pack(pady=10)

        # Progress bar
        self.style = ttk.Style()
        self.style.theme_use("default")
        self.style.configure("Custom.Horizontal.TProgressbar", thickness=36, troughcolor="#E0E0E0",
                             troughrelief=tk.FLAT, background="#4CAF50")

        self.progressbar = ttk.Progressbar(self, orient=tk.HORIZONTAL, length=700, mode='determinate',
                                            style="Custom.Horizontal.TProgressbar", value=0)
        self.progressbar.pack(pady=10)

        # Progress label
        self.progress_text = tk.StringVar()
        self.progress_text.set("Analized fonts 0/0 (0.00%) - Remaining Time: 0.00 seconds")
        self.progress_label = tk.Label(self, textvariable=self.progress_text, font=("Arial", 12), bg="#F0F0F0")
        self.progress_label.pack(pady=10)

        # Results label
        self.results_label_var = tk.StringVar()
        self.results_label_var.set("Results: 0 found")
        self.results_label = tk.Label(self, textvariable=self.results_label_var, font=("Arial", 14, "bold"), bg="#F0F0F0")
        self.results_label.pack(pady=10)

        # Results text area with scrollbar
        self.scrollbar = tk.Scrollbar(self)
        self.scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

        self.results_text = tk.Text(self, width=160, height=8, font=("Arial", 10), wrap="word",
                                    yscrollcommand=self.scrollbar.set)
        self.results_text.pack(pady=10)

        self.scrollbar.config(command=self.results_text.yview)

        # Credits
        self.credit_frame = tk.Frame(self, bg="#F0F0F0")
        self.credit_frame.pack(side=tk.BOTTOM, anchor=tk.E, padx=10, pady=5)

        self.credit_label = tk.Label(self.credit_frame, text="Coded with", font=("Arial", 10), fg="black")
        self.credit_label.pack(side=tk.LEFT)

        self.heart_label = tk.Label(self.credit_frame, text="\u2764", font=("Arial", 10), fg="red")
        self.heart_label.pack(side=tk.LEFT)

        self.name_label = tk.Label(self.credit_frame, text="by Alberto Z.", font=("Arial", 10), fg="black")
        self.name_label.pack(side=tk.LEFT)

        self.search_thread = None

    def select_folder(self):
        # Open a folder selection dialog and set the selected folder path in the entry field
        folder = filedialog.askdirectory()
        if folder:
            self.entry.delete(0, tk.END)
            self.entry.insert(0, folder)

    def start_search(self):
        # Get the folder path, search mode, and exclude strings
        folder = self.entry.get()
        search_mode = self.mode_var.get()
        exclude_strings = ["adobe", "google", "microsoft"]  # Modify this list to include additional exclude strings

        # Create a new search thread and start the search
        self.search_thread = SearchThread(folder, search_mode, exclude_strings, self.progressbar,
                                          self.progress_text, self.results_text, self.results_label_var)

        self.search_thread.start()

# Create the application instance and start the main event loop
root = Application()
root.mainloop()


# Sorting06 나이순 정렬10814py
# 우선순위
# 1. 나이 , 2. 가입 순서
n  = int(input())
arr = []
for idx in range(n):
    age, name = map(str, input().split())
    arr.append((idx,int(age),name))
arr.sort(key=lambda x : (x[1],x[0]))
for a in arr :
    print(a[1], a[2], sep=' ')
    # age를 int처리 하지 않아 string sort 되서 wrong
    # Wrong since did not convert string to int from age value


import numpy as np
import sys
import math
import datetime
import os
import random
# import own modules #
sys.path.append('../public')
from my_modules import *
from constants  import *

class ShipDemand:
    def __init__(self, history_data=None, neu=None, sigma=None, u=None, d=None, p=None):
        if history_data is None:
            #self.yearly_history_data = load_history_data(YEAR,DEMAND_TYPE)
            self.monthly_history_data = load_history_data(MONTH,DEMAND_TYPE)
        else:
            self.yearly_history_data = history_data
        # initialize parameters
        if (neu is None or sigma is None or u is None or d is None or p is None):
            self.calc_params_from_history()
        else:
            self.neu, self.sigma, self.u, self.d, self.p = neu, sigma, u, d, p

    # calc neu and sigma from history data
    def calc_params_from_history(self):
        index   = 0
        delta_t = 1.0 / DELTA_T_DAY
        values  = np.array([])
        for date, ship_demand in self.monthly_history_data:
            if index == 0:
                # initialize the price
                s_0 = ship_demand
            else:
                s_t      = ship_demand
                base_val = math.log(s_t / s_0)
                values   = np.append(values, base_val)
                # update the price
                s_0      = ship_demand
            index += 1

        # substitute inf to nan in values
        values = inf_to_nan_in_array(values)
        self.neu    = np.nanmean(values)
        self.sigma  = np.nanstd(values)
        self.u      = np.exp(self.sigma * np.sqrt(delta_t))
        self.d      = np.exp(self.sigma * (-1) * np.sqrt(delta_t))
        self.p      = 0.5 + 0.5 * (self.neu / self.sigma) * np.sqrt(delta_t)
        return

    def calc_ship_demand(self, current_ship_demand):
        return self.u * current_ship_demand if random.randint(0,1) < self.p else self.d * current_ship_demand

    # generate predicted scenario
    def generate_scenario(self,predict_years=DEFAULT_PREDICT_YEARS,predict_pattern_number=DEFAULT_PREDICT_PATTERN_NUMBER):
        # default predict_years is 15 years [180 months]
        self.predict_years  = predict_years

        # predicted data type
        self.predicted_data = []
        for p_num in range(predict_pattern_number):
            self.predicted_data.append([])

        predict_months_num = int(self.predict_years * 12)

        # latest date from history_data
        latest_history_date_str, latest_ship_demand = self.monthly_history_data[-1]
        latest_history_date                      = datetime.datetime.strptime(latest_history_date_str.decode('UTF-8'), '%Y/%m/%d')
        for pattern in range(predict_pattern_number):
            current_date  = latest_history_date
            current_ship_demand = latest_ship_demand
            for predict_month_num in range(predict_months_num):
                current_date        = add_month(current_date)
                current_date_str    = datetime.datetime.strftime(current_date, '%Y/%m/%d')
                for time in range(DELTA_T_DAY):
                    current_ship_demand    = self.calc_ship_demand(current_ship_demand)
                self.predicted_data[pattern].append({'date':current_date_str, 'price':current_ship_demand})
        return


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

"""
This example shows a tooltip on a windows and a button
"""

import sys
from PyQt5.QtWidgets import QWidget, QToolTip, QPushButton, QApplication
from PyQt5.QtGui import QFont

class Example(QWidget):

    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        # 设置字体，大小
        QToolTip.setFont(QFont('SansSerif', 10))
        # 调用setToolTip()创建提示框可以使用富文本格式的内容
        self.setToolTip('This is a QWidget widget')
        # 创建一个按钮，并且为按钮添加了一个提示框
        btn = QPushButton('Button', self)
        btn.setToolTip('This is a QPushButton widget')
        # 调整按钮大小，并让按钮在屏幕上显示出来，sizeHint()方法提供了一个默认的按钮大小
        btn.resize(btn.sizeHint())
        btn.move(50, 50)

        self.setGeometry(300, 300, 300, 200)
        self.setWindowTitle('Tooltips')
        self.show()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())


def rsa_phi(p,q,verbose=False):
    if verbose:
        print("phi_n=("+str(p)+"-1)("+str(q)+"-1)="+str((p-1) * (q-1)))
    return (p-1) * (q-1)

registerFunction("rsa_phi", {
    "name" : "Find PHI(n) for RSA",
    "arguments_short":["p","q","verbose=False"],
    "arguments":["p of rsa (rsa n = p*q)", "q of rsa (rsa n = p*q)","print commands"],
    "description":"Returns phi_n where phi_n = (p-1) * (q-1) for RSA"
})


import tensorflow as tf

#tensorflow的变量定义有4种类型，整型，字符，浮点，布尔。
#第一个是参数名称，第二个参数是默认值，第三个是参数描述
tf.app.flags.DEFINE_string('str_name', 'def_v_1',"字符")
tf.app.flags.DEFINE_integer('int_name', 10,"整型")
tf.app.flags.DEFINE_float('float_name', 10.0,"浮点")
tf.app.flags.DEFINE_boolean('bool_name', False, "布尔")

FLAGS = tf.app.flags.FLAGS

#必须带参数，否则：'TypeError: main() takes no arguments (1 given)';   main的参数名随意定义，无要求
def main(_):
    print(FLAGS.str_name)
    print(FLAGS.int_name)
    print(FLAGS.float_name)
    print(FLAGS.bool_name)

#python flags_test.py --str_name test_str --int_name 99 --float_name 99.0 --bool_name True
if __name__ == '__main__':
    tf.app.run()  #执行main函数


#You need to climb a staircase that has n steps, and you decide to get some extra exercise by jumping up the steps. You can cover at most k steps in a single jump. Return all the possible sequences of jumps that you could take to climb the staircase, sorted.

#Example

#For n = 4 and k = 2, the output should be

#solution(n, k) =
#[[1, 1, 1, 1],
# [1, 1, 2],
# [1, 2, 1],
# [2, 1, 1],
# [2, 2]]
#There are 4 steps in the staircase, and you can jump up 2 or fewer steps at a time. There are 5 potential sequences in which you jump up the stairs either 2 or 1 at a time.

def solution(n, k):
    output = []
    steps = []
    helper(output, steps, k, n)
    return output

def helper(output, steps, k, left):
    if left == 0:
        output.append(list(steps)) # notice hard copy here
    else:
        for i in range(1, k+1):
            if i <= left:
                steps.append(i)
                helper(output, steps, k, left-i)
                steps.pop()


from bs4 import BeautifulSoup
from urllib.request import *
from urllib.parse import *
from os import makedirs
import os.path, time, re

# 이미 처리한 파일인지 확인용
proc_files = {}

# HTML 내부에 있는 링크 추출
def enum_links(html, base):
    soup = BeautifulSoup(html, "html.parser")
    links = soup.select("link[rel='stylesheet']") # css
    links += soup.select("a[href]") # link
    result = []

    # href 속성 추출, link를 절대 경로로 변환
    for a in links:
        href = a.attrs['href']
        url = urljoin(base, href)
        result.append(url)

    return result

# 파일을 다운로드, 저장
def download_file(url):
    o = urlparse(url)
    savepath = "./" + o.netloc + o.path

    print("*" * 20)
    print("o: ", o)
    print("url: ", url)
    print("o.netloc: ", o.netloc)
    print("o.path: ", o.path)

    if re.search(r"/$", savepath): # 플더라면 index.html
        savepath += "index.html"

    print("savepath: ", savepath)

    savedir = os.path.dirname(savepath)
    print("savedir: ", savedir)

    # 모두 다운됐는지 확인
    if os.path.exists(savepath): return savepath

    # 다운 받을 폴더 생성
    if not os.path.exists(savedir):
        print("mkdir=", savedir)
        makedirs(savedir)

    # 파일 다운 받기
    try:
        print("- download=", url)
        urlretrieve(url, savepath)

        time.sleep(1)
        return savepath
    except:
        print("failed to download: ", url)
        return None

# HTML 분석, 다운로드
def analyze_html(url, root_url):
    savepath = download_file(url)

    if savepath is None: return
    if savepath in proc_files: return # 이미 처리됨

    proc_files[savepath] = True
    print("analyze_html=", url)

    # extract link
    html = open(savepath, "r", encoding="utf-8").read()
    links = enum_links(html, url)

    for link_url in links:
        # link가 root이외의 경로면 무시
        if link_url.find(root_url) != 0:
            if not re.search(r".css$", link_url): continue

        # HTML이면
        if re.search(r".(html|htm)$", link_url):
        # 재귀적으로 HTML 파일 분석
            analyze_html(link_url, root_url)
            continue

        # 기타 파일
        download_file(link_url)

if __name__ == "__main__":
    url = "https://docs.python.org/3.5/library/"
    analyze_html(url, url)


from typing import Any, Dict, List

import pytest

from cdpctl.validation import fail, get_config_value, validator, warn
from cdpctl.validation.infra.issues import (
    AZURE_REGION_FEATURES_NOT_SUPPORTED,
    AZURE_REGION_NOT_SUPPORTED,
)

@pytest.mark.azure
@pytest.mark.infra
def azure_region_validation(
    config: Dict[str, Any], azure_supported_regions: List[str]
) -> None:  # pragma: no cover
    """Azure Region Supported."""  # noqa: D401
    azure_region(config, azure_supported_regions)

@validator
def azure_region(
    config: Dict[str, Any], azure_supported_regions: List[str]
) -> None:  # pragma: no cover
    """Check that the Azure region is supported."""  # noqa: D401,E501
    config_region: str = get_config_value(config=config, key="infra:azure:region")
    if config_region not in azure_supported_regions:
        fail(AZURE_REGION_NOT_SUPPORTED, config_region)

@pytest.mark.azure
@pytest.mark.infra
@pytest.mark.dependency(depends=["azure_region_validation"])
def azure_region_experiences_validation(
    config: Dict[str, Any], azure_supported_region_experiences: Dict[str, bool]
) -> None:  # pragma: no cover
    """Azure Region Experience Support."""  # noqa: D401
    azure_region_experiences(config, azure_supported_region_experiences)

@validator
def azure_region_experiences(
    config: Dict[str, Any], azure_supported_region_experiences: Dict[str, bool]
) -> None:  # pragma: no cover
    """Check for unsupported experiences."""  # noqa: D401,E501
    config_region: str = get_config_value(config=config, key="infra:azure:region")
    if config_region not in azure_supported_region_experiences:
        fail(AZURE_REGION_FEATURES_NOT_SUPPORTED, config_region)

    unsupported_experiences = []
    for experience, supported in azure_supported_region_experiences[
        config_region
    ].items():
        if not supported:
            unsupported_experiences.append(experience)

    if unsupported_experiences:
        warn(
            AZURE_REGION_FEATURES_NOT_SUPPORTED, config_region, unsupported_experiences
        )


def add_all(*args):
	total=0
	for i in args:
		total +=i
	return total

print (add_all(1,2,3,4,5,6,7,8,9,10))

w_dic={'a':'apple','b':'boy','c':'cat'}

wt=w_dic.items()

print (wt)

w_dic_again=dict(wt)
print (w_dic_again)

tel_cho={}
tel_cho['yamada','taro']='090-333-1111'
tel_cho['tanaka','jiro']='090-333-2222'
print (tel_cho)

for lname,fname in tel_cho:
	print (lname, fname, tel_cho[lname,fname])


#funtion returning two values
def func (int1,int2):
    add = int1 + int2
    multiply = int1*int2
    return add, multiply

print(func(2,4)) #it gives in one tuples value

#to print alag alag value
add, multiply = func(1,4)
print(add)
print(multiply)


from board import Board

class Node(object):
    def __init__(self, board: Board, parent, nets):
        self.board = board
        self.parent = parent
        self.score = 0
        self.games = 0
        self.children = None
        self.nets = nets

    def evaluate(self):
        if self.score == 0:
            value = self.rollout()
            self.registerScore(value)
        else:
            child = self.getChildNodeToEvaluate()
            if child is not None:
                child.evaluate()
            else:
                self.registerScore(0)

    def registerScore(self, value):
        self.score += value
        self.games += 1
        if self.parent is not None:
            self.parent.registerScore(value)

    def getChildNodeToEvaluate(self):
        raise NotImplementedError("getChildNodeToEvaluate should be implemented by inheritor of Node")

    def rollout(self):
        raise NotImplementedError("rollout should be implemented by inheritor of Node")


from turtle import width
from PIL import Image

'''
main function here! create a png image for the given size and color
'''
def main():
    size = width,height = 320,240;
    image = Image.new("RGB", size , 'White')
    image.show()

    del image

#call the functions!
if __name__ == '__main__':
    main()


import numpy as np
import matplotlib.pyplot as plt

from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.model_selection import KFold

def evaluatePerformance():
    '''
    Evaluate the performance of decision trees,
    averaged over 100 trials of 10-fold cross validation

    Return:
      a matrix giving the performance that will contain the following entries:
      stats[0,0] = mean accuracy of decision tree
      stats[0,1] = std deviation of decision tree accuracy
      stats[1,0] = mean accuracy of decision stump
      stats[1,1] = std deviation of decision stump accuracy
      stats[2,0] = mean accuracy of 3-level decision tree
      stats[2,1] = std deviation of 3-level decision tree

    ** Note that your implementation must follow this API**
    '''

    # Load Data
    filename = 'data/SPECTF.dat'
    data = np.loadtxt(filename, delimiter=',')
    X = data[:, 1:]
    y = np.array([data[:, 0]]).T
    n, d = X.shape

    # Shuffle the data
    idx = np.arange(n)
    np.random.seed(13)
    np.random.shuffle(idx)
    X = X[idx]
    y = y[idx]

    # Define the number of trials and folds
    num_trials = 100
    num_folds = 10

    # Initialize lists to store accuracy scores
    accuracy_scores_decision_tree = []
    accuracy_scores_decision_stump = []
    accuracy_scores_dt3 = []

    # Perform trials of cross-validation
    for _ in range(num_trials):
        # Initialize the cross-validation splitter
        kf = KFold(n_splits=num_folds, shuffle=True)

        # Initialize variables to store accuracy scores for each model
        decision_tree_scores = []
        decision_stump_scores = []
        dt3_scores = []

        # Perform cross-validation
        for train_index, test_index in kf.split(X):
            X_train, X_test = X[train_index], X[test_index]
            y_train, y_test = y[train_index], y[test_index]

            # Train the decision tree
            clf = tree.DecisionTreeClassifier()
            clf = clf.fit(X_train, y_train)

            # Make predictions on the test set
            y_pred = clf.predict(X_test)

            # Compute the accuracy score for decision tree
            decision_tree_accuracy = accuracy_score(y_test, y_pred)
            decision_tree_scores.append(decision_tree_accuracy)

            # Compute the accuracy score for decision stump
            majority_class = np.argmax(np.bincount(y_train.flatten()))
            y_pred_stump = np.full(y_test.shape, majority_class)
            decision_stump_accuracy = accuracy_score(y_test, y_pred_stump)
            decision_stump_scores.append(decision_stump_accuracy)

            # Train a 3-level decision tree
            clf_dt3 = tree.DecisionTreeClassifier(max_depth=3)
            clf_dt3 = clf_dt3.fit(X_train, y_train)

            # Make predictions on the test set
            y_pred_dt3 = clf_dt3.predict(X_test)

            # Compute the accuracy score for 3-level decision tree
            dt3_accuracy = accuracy_score(y_test, y_pred_dt3)
            dt3_scores.append(dt3_accuracy)

        # Calculate mean accuracy scores for each model in the current trial
        decision_tree_mean = np.mean(decision_tree_scores)
        decision_stump_mean = np.mean(decision_stump_scores)
        dt3_mean = np.mean(dt3_scores)

        # Append mean accuracy scores to the main lists
        accuracy_scores_decision_tree.append(decision_tree_mean)
        accuracy_scores_decision_stump.append(decision_stump_mean)
        accuracy_scores_dt3.append(dt3_mean)

    # Calculate mean and standard deviation of accuracy scores across trials
    meanDecisionTreeAccuracy = np.mean(accuracy_scores_decision_tree)
    stddevDecisionTreeAccuracy = np.std(accuracy_scores_decision_tree)
    meanDecisionStumpAccuracy = np.mean(accuracy_scores_decision_stump)
    stddevDecisionStumpAccuracy = np.std(accuracy_scores_decision_stump)
    meanDT3Accuracy = np.mean(accuracy_scores_dt3)
    stddevDT3Accuracy = np.std(accuracy_scores_dt3)

    # Make certain that the return value matches the API specification
    stats = np.zeros((3, 2))
    stats[0, 0] = meanDecisionTreeAccuracy
    stats[0, 1] = stddevDecisionTreeAccuracy
    stats[1, 0] = meanDecisionStumpAccuracy
    stats[1, 1] = stddevDecisionStumpAccuracy
    stats[2, 0] = meanDT3Accuracy
    stats[2, 1] = stddevDT3Accuracy
    return stats

if __name__ == "__main__":
    stats = evaluatePerformance()
    print("Decision Tree Accuracy = ", stats[0, 0], " (", stats[0, 1], ")")
    print("Decision Stump Accuracy = ", stats[1, 0], " (", stats[1, 1], ")")
    print("3-level Decision Tree = ", stats[2, 0], " (", stats[2, 1], ")")


"""

You are given two arrays of positive integers, boxes and warehouse, representing the heights of some boxes of unit width and the heights of n rooms in a warehouse respectively.
The warehouse's rooms are labeled from 0 to n - 1 from left to right where warehouse[i] (0-indexed) is the height of the ith room.

    Boxes are put into the warehouse by the following rules:
    Boxes cannot be stacked.
    You can rearrange the insertion order of the boxes.
    Boxes can be pushed into the warehouse from either side (left or right)

If the height of some room in the warehouse is less than the height of a box, then that box and all other boxes behind it will be stopped
before that room.
Return the maximum number of boxes you can put into the warehouse.

Constraints:
    n == warehouse.length
    1 <= boxes.length, warehouse.length <= 10^5
    1 <= boxes[i], warehouse[i] <= 10^9

Example 1:
Input: boxes = [1,2,2,3,4], warehouse = [3,4,1,2]
Output: 4

 I sorted the box
1. I store the maximum possible height to insert in index i from left and right (i.e left, right)
   It is increasing array upto the heighest pick value then it is decresing
2. Then I select the maximum from both arrays, max_height, idx
3. Then find the box which have a nearest height and it should less than that max_height
4. two pointers like l = idx -1 , r = idx + 1
5. I should insert by using two pointers

"""

class Solution:
    def maxBoxesInWarehouse(self, boxes: List[int], warehouse: List[int]) -> int:

        n = len(warehouse)

        left = [0] * n
        right = [0] * n
        minn = float("inf")
        for i in range(n):
            minn = min(minn, warehouse[i])
            left[i] = minn
        minn = float("inf")
        for i in range(n-1, -1, -1):
            minn = min(minn, warehouse[i])
            right[i] = minn
        maxx = max(max(left), max(right))
        idx = None
        for i, v in enumerate(left):
            if maxx == v:
                idx = i
                break
        for i, v in enumerate(right):
            if maxx == v:
                idx = i
                break
        l = idx - 1
        r = idx + 1
        count = 0
        boxes.sort()
        index = bisect.bisect_right(boxes, maxx) - 1
        if index == 0:
            return 0
        count += 1
        index -= 1
        while l >= 0 and r < n and index >= 0:
            v = boxes[index]
            if left[l] >= v:
                count += 1
                l -= 1
            elif right[r] >= v:
                r += 1
                count += 1
            index -= 1

        return count

# https://sharepad.io/live/tA2f4Rw