import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
from sklearn import metrics
import seaborn as sns

from sklearn.datasets import load_iris
dataset = load_iris()

X = dataset.data
y = dataset.target

plt.scatter(X[y==0,0],X[y==0,1],c='r',label='setosa')
plt.scatter(X[y==1,0],X[y==1,1],c='b',label='versicolor')
plt.scatter(X[y==2,0],X[y==2,1],c='g',label='verginica')
plt.xlabel('sepal_length')
plt.ylabel('sepal_width')
plt.legend()
plt.show()

plt.scatter(X[y==0,2],X[y==0,3],c='r',label='setosa')
plt.scatter(X[y==1,2],X[y==1,3],c='b',label='versicolor')
plt.scatter(X[y==2,2],X[y==2,3],c='g',label='verginica')
plt.legend()
plt.show()

from sklearn.model_selection import train_test_split
X_train, X_test, y_train, y_test = train_test_split(X,y)

from sklearn.linear_model import LogisticRegression
log_reg = LogisticRegression()
log_reg.fit(X_train,y_train)

y_pred = log_reg.predict(X_test)

from sklearn.metrics import confusion_matrix
cm = confusion_matrix(y_test,y_pred)

log_reg.score(X_train,y_train)
log_reg.score(X_test,y_test)
log_reg.score(X,y)

from sklearn.neighbors import KNeighborsClassifier
knn = KNeighborsClassifier(n_neighbors=5, p=2, metric='minkowski')
knn.fit(X_train, y_train)

knn.score(X_train, y_train)
knn.score(X_test, y_test)

from sklearn.metrics import precision_score, recall_score, f1_score
precision_score(y_test,y_pred,average = 'micro')
recall_score(y_test,y_pred,average = 'micro')
f1_score(y_test,y_pred,average = 'micro')

from sklearn.svm import SVC
svm = SVC(kernel='rbf', random_state=0, gamma=.10, C=1.0)
svm.fit(X_train, y_train)

svm.score(X_train, y_train)
svm.score(X_test, y_test)

from sklearn.tree import DecisionTreeClassifier
dtc= DecisionTreeClassifier()
dtc.fit(X_train,y_train)
y_pred = dtc.predict(X_test)
metrics.accuracy_score(y_pred,y_test)


import nltk
from transformers import AutoTokenizer, AutoModelForSeq2SeqLM
import torch
import re

DEVICE = 'cuda' if torch.cuda.is_available() else 'cpu'

class T5BaseSum:
    def __init__(self):
        nltk.download('punkt')

        self.__model_name = 'eenzeenee/t5-small-korean-summarization'

        self.__model = AutoModelForSeq2SeqLM.from_pretrained(self.__model_name).to(DEVICE)
        self.__model.eval()
        self.__tokenizer = AutoTokenizer.from_pretrained(self.__model_name)

        self.__prefix = "summarize: "

        self.__preprocess = lambda x: re.sub('\s+', ' ', re.sub('\n+', ' ', x.strip()))

    def get_sum(self, text):
        clean_text = self.__preprocess(text)

        inputs = [self.__prefix + clean_text]
        inputs_ids = self.__tokenizer(inputs, max_length=1024, truncation=True, return_tensors="pt").to(DEVICE)
        output = self.__model.generate(**inputs_ids, num_beams=3, do_sample=True, min_length=128, max_length=256)
        decoded_output = self.__tokenizer.batch_decode(output, skip_special_tokens=True)[0]
        result = nltk.sent_tokenize(decoded_output.strip())[0]

        return result


#! /usr/bin/python3

import os

import numpy as np
import tensorflow as tf
from sklearn.metrics import precision_recall_fscore_support
from tqdm import tqdm

def weightedLoss(originalLossFunc, weightsList):
    def lossFunc(true, pred):

        # axis = -1  # if channels last
        # axis = 1  # if channels first

        # argmax returns the index of the element with the greatest value
        # done in the class axis, it returns the class index
        # classSelectors = tf.argmax(true, axis=axis)
        # if your loss is sparse, use only true as classSelectors

        # considering weights are ordered by class, for each class
        # true(1) if the class index is equal to the weight index
        # convert i to int64
        # classSelectors = [tf.equal(tf.cast(i, tf.int64), classSelectors)
        #                   for i in range(len(weightsList))]

        classSelectors = [False, True]

        # casting boolean to float for calculations
        # each tensor in the list contains 1 where ground true class is equal to its index
        # if you sum all these, you will get a tensor full of ones.
        classSelectors = [tf.cast(x, tf.float32)
                          for x in classSelectors]

        # for each of the selections above, multiply their respective weight
        weights = [sel * w for sel, w in zip(classSelectors, weightsList)]

        # sums all the selections
        # result is a tensor with the respective weight for each element in predictions
        weightMultiplier = weights[0]
        for i in range(1, len(weights)):
            weightMultiplier = weightMultiplier + weights[i]

        # make sure your originalLossFunc only collapses the class axis
        # you need the other axes intact to multiply the weights tensor
        loss = originalLossFunc(true, pred)
        loss = loss * weightMultiplier

        return loss
    return lossFunc

class Metrics(tf.keras.callbacks.Callback):
    """Calculate metrics for a dev-/testset and add them to the logs."""

    def __init__(self, clf, data, steps, interval, prefix=''):
        self.clf = clf
        self.data = data
        self.steps = steps
        self.interval = interval
        self.prefix = prefix

    def on_epoch_end(self, epoch, logs):
        if (epoch + 1) % self.interval == 0:
            y_true, y_pred = self.clf.eval(
                self.data, self.steps, desc=self.prefix)
            p, r, f, s = precision_recall_fscore_support(y_true, y_pred)
        else:
            p, r, f, s = np.nan, np.nan, np.nan, np.nan
        logs_new = {'{}_precision'.format(self.prefix): p,
                    '{}_recall'.format(self.prefix): r,
                    '{}_f1'.format(self.prefix): f,
                    '{}_support'.format(self.prefix): s}
        logs.update(logs_new)

class Saver(tf.keras.callbacks.Callback):
    """Save the model."""

    def __init__(self, path, interval):
        self.path = path
        self.interval = interval

    def on_epoch_end(self, epoch, logs):
        if (epoch + 1) % self.interval == 0:
            file_name = os.path.join(
                self.path, 'model.{:03d}.h5'.format(epoch))
            self.model.save(file_name)

# pylint: disable=E1101
class LeafClassifier(object):
    """This classifier assigns labels to sequences based on words and HTML tags."""

    def __init__(self, input_size, num_layers, hidden_size, dropout, dense_size, class_weights):
        """Construct the network."""
        self.input_size = input_size
        self.num_layers = num_layers
        self.hidden_size = hidden_size
        self.dropout = dropout
        self.dense_size = dense_size
        self.class_weights = class_weights
        self.model = self._get_model()

    def _get_model(self):
        """Return a keras model."""
        model = tf.keras.Sequential()
        model.add(tf.keras.layers.InputLayer(
            input_shape=(None, self.input_size)))
        model.add(tf.keras.layers.Dense(self.dense_size, activation='relu'))
        model.add(tf.keras.layers.Masking(mask_value=0))
        for _ in range(self.num_layers):
            lstm = tf.keras.layers.LSTM(
                self.hidden_size, return_sequences=True)
            model.add(tf.keras.layers.Bidirectional(lstm))
        model.add(tf.keras.layers.Dropout(self.dropout))
        model.add(tf.keras.layers.Dense(1, activation='sigmoid'))

        model.compile(loss=weightedLoss(
            tf.keras.losses.binary_crossentropy, self.class_weights), optimizer='adam')
        return model

    def train(self, train_dataset, train_steps, epochs, log_file, ckpt,
              dev_dataset=None, dev_steps=None, test_dataset=None, test_steps=None, interval=1):
        """Train a number of input sequences."""
        callbacks = [Saver(ckpt, interval)]
        if dev_dataset is not None:
            callbacks.append(
                Metrics(self, dev_dataset, dev_steps, interval, 'dev'))
        if test_dataset is not None:
            callbacks.append(Metrics(self, test_dataset,
                             test_steps, interval, 'test'))
        callbacks.append(tf.keras.callbacks.CSVLogger(log_file))

        self.model.fit(train_dataset, steps_per_epoch=train_steps, epochs=epochs,
                       callbacks=callbacks)

    def eval(self, dataset, steps, desc=None):
        """Evaluate the model on the test data and return the metrics."""
        y_true, y_pred = [], []
        for b_x, b_y in tqdm(dataset, total=steps, desc=desc):
            # somehow this cast is necessary
            b_x = tf.dtypes.cast(b_x, 'float32')

            y_true.extend(b_y.numpy().flatten())
            y_pred.extend(
                np.around(self.model.predict_on_batch(b_x)).flatten())
        return y_true, y_pred


# Triángulos adultos

# NOTE: In this version f's inputs are the parents and the grandparent.

def triangle(f, axioms = [[1], [1, 1]], border = 0, layers = 10):
    triangle = list(axioms)

    for i in range(len(triangle), layers + len(triangle) - 1):
        new_layer = []

        new_layer.append(f(border, triangle[i - 1][0], border))

        for j in range(0, len(triangle[i - 1]) - 1):
            left_parent = triangle[i - 1][j]
            right_parent = triangle[i - 1][j + 1]
            grandparent = triangle[i - 2][j]

            new_layer.append(f(left_parent, right_parent, grandparent))

        new_layer.append(f(triangle[i - 1][-1], border, border))

        triangle.append(new_layer)

    return triangle


import os
import glob
import argparse
import configparser

from confluent_kafka.serialization import (
    SerializationContext,
    MessageField,
)
from confluent_kafka.schema_registry import SchemaRegistryClient
from confluent_kafka.schema_registry.avro import AvroDeserializer

if __name__ == "__main__":
    parser = argparse.ArgumentParser(description="AVRO deserialiser")
    parser.add_argument(
        "--config",
        dest="config",
        help=f"Configuration file to access the Schema Registry cluster (default 'config/test.ini')",
        default=os.path.join("config", "test.ini"),
    )
    parser.add_argument(
        "--schema",
        dest="schema",
        type=str,
        help=f"avro Schema file path",
        default=None,
    )
    args = parser.parse_args()

    # Schema Registry client
    config_data = configparser.ConfigParser()
    config_data.read(args.config)
    schema_registry_client = SchemaRegistryClient(dict(config_data["schema-registry"]))

    # AVRO Deserialiser object
    avro_deserializer = AvroDeserializer(
        schema_registry_client,
        schema_str=None if args.schema is None else open(args.schema, "r").read(),
    )

    # Read messages
    for file in glob.glob(os.path.join("data", "*.bin")):
        topic = "-".join(os.path.basename(file).split("-")[:-1])
        with open(file, "rb") as f:
            message_serialised = f.read()
            message_deserialised = avro_deserializer(
                message_serialised,
                SerializationContext(
                    topic,
                    MessageField.VALUE,
                ),
            )

        print(f"File: {file}")
        print(message_serialised)
        print(f"{message_deserialised}\n")


"""
Given head, the head of a linked list, determine if the linked list has a cycle in it.
"""

class Node:
    def __init__(self, data):
        self.data = data
        self.next = None

class Solution:
    def hasCycle(self, head):
        slow = fast = head

        while slow and fast and fast.next:
            slow = slow.next
            fast = fast.next.next
            print(slow.data, fast.data)
            if slow == fast:
                return True
        return False

if __name__ == "__main__":
    root = Node(1)
    n1 = Node(2)
    n2 = Node(3)
    n3 = Node(4)
    n4 = Node(5)
    n5 = Node(6)
    root.next = n1
    n1.next = n2
    n2.next = n3
    n3.next = n4
    n4.next = n5
    n5.next = n2

    obj = Solution()
    meet = obj.hasCycle(root)


import json
import os

if __name__ == '__main__':
    files = [i for i in os.listdir() if '.json' in i]
    #print(files)
    for file in files:
        print('\n\n====================\n\n')
        print(file)
        with open(file, 'r') as infile:
            data = json.load(infile)
        #print(data)
        ordered = sorted(data, key=lambda d: d['date'], reverse=False)
        full_text = ''
        for o in ordered:
            full_text = full_text + o['author'] + ': ' + o['content'] + '\n'
        full_text = full_text.strip()
        print(full_text)


from unittest import TestCase

from xsdata.models.enums import Namespace
from xsdata.models.enums import NamespaceType
from xsdata.models.xsd import AnyAttribute

class AnyAttributeTests(TestCase):
    def test_is_attribute(self):
        obj = AnyAttribute()
        self.assertTrue(obj.is_property)

    def test_property_raw_namespace(self):
        obj = AnyAttribute()
        self.assertEqual(NamespaceType.ANY_NS, obj.raw_namespace)

        obj.namespace = "foo"
        self.assertEqual("foo", obj.raw_namespace)

        obj = AnyAttribute(namespace="    foo  \n    \t  \r  bar foo ")
        self.assertEqual("foo bar", obj.raw_namespace)

    def test_property_real_name(self):
        obj = AnyAttribute()
        self.assertEqual("@any_attributes", obj.real_name)

        obj.namespace = "foo"
        self.assertEqual("@foo_attributes", obj.real_name)

        obj.namespace = "http://www.xsdata.com/somewhere.xsd"
        self.assertEqual("@xsdata_com/somewhere_attributes", obj.real_name)

        obj.namespace = "http://foo http://bar"
        self.assertEqual("@foo_bar_attributes", obj.real_name)

    def test_property_real_type(self):
        obj = AnyAttribute()
        obj.ns_map["xs"] = Namespace.XS.uri
        self.assertEqual(["xs:anyType"], list(obj.attr_types))

    def get_restrictions(self):
        obj = AnyAttribute()
        self.assertEqual({}, obj.get_restrictions())


#!/usr/bin/env python3

from pathlib import Path
from typing import Callable, NoReturn, Optional, Union
import os
import platform
import readline
import shutil
import sys

#

class Action:
    def __init__(self, name: str, f: Callable[[], Union[None, NoReturn]]) -> None:
        self.name = name
        self._f = f

    def __call__(self) -> None:
        self._f()

#

def colored(text: str, color: str) -> str:
    END = "\33[0m"
    return color + text + END

# Colors
RED = "\33[31m"
GREEN = "\33[32m"
BLUE = "\33[34m"

# Symbols
CROSS = colored("✗", RED)
TICK = colored("✓", GREEN)

#

def yn(question: str) -> bool:
    answer = input(f"{question} (y/N) ").strip()
    return answer.lower() in ["yes", "y"]

def really(func: Callable[[], None], question: str) -> None:
    if yn(question):
        func()
        print(colored(f"\tDone {TICK}", GREEN))
    else:
        print(colored(f"\tAborted {CROSS}", RED))

#

def rel(path: Path) -> str:
    try:
        return f"~/{path.relative_to(Path.home())}"
    except ValueError:
        return str(path)

def print_files(files: list[Path]) -> None:
    for file in files:
        symbol = TICK if file.exists() else CROSS
        text = colored(rel(file), BLUE) if file.is_dir() else rel(file)

        print(f"\t{text} {symbol}")

def delete_files(files: list[Path]) -> None:
    for file in files:
        if not file.exists():
            continue

        try:
            if file.is_dir():
                shutil.rmtree(file)
            else:
                os.remove(file)
        except OSError as e:
            print(colored(f"\tError: {rel(file)} - {e.strerror}", RED))

def search(
    root: Path,
    patterns: Optional[list[str]] = None,
    ignore_case: bool = False
) -> list[Path]:
    if not patterns:
        return list(root.rglob("*"))

    if ignore_case:
        f: Callable[[str], str] \
            = lambda c: f"[{c.lower()}{c.upper()}]" if c.isalpha() else c
        patterns = ["".join(map(f, p)) for p in patterns]

    files: list[Path] = []
    for p in patterns:
        files += root.rglob(p)

    return files

#

def print_and_delete(files: list[Path]) -> None:
    print_files(files)
    really(
        lambda: delete_files(files),
        "\n\tDo you really want to delete these files?"
    )

def search_and_delete(
    root: Optional[Path] = None,
    patterns: Optional[list[str]] = None,
    ignore_case: bool = False
) -> None:
    if root is None:
        while True:
            try:
                answer = input("\tRoot [~]: ").strip() or "~"
                root = Path(os.path.expandvars(answer)) \
                    .expanduser() \
                    .resolve(strict=True)
                break
            except (ValueError, FileNotFoundError):
                print(colored("\tPath not valid. Try again.\n", RED))

    if patterns is None:
        patterns = []
        while True:
            p = input(f"\tPattern #{len(patterns) + 1}: ").strip()
            if p:
                patterns.append(p)
            else:
                break

        if patterns:
            ignore_case = yn("\tIgnore case?")

    files = search(root, patterns, ignore_case)

    print()

    if files:
        print_and_delete(files)
    else:
        print(colored(f"\tNo files found {CROSS}", RED))

#

apple: list[str] = [
    "Assistant",
    "Caches",
    "Calendars",
    "Cookies",
    "Developer",
    "HTTPStorages",
    "LaunchAgents",
    "Logs",
    "Mail",
    "Maps",
    "Messages",
    "Metadata",
    "News",
    "Reminders",
    "Safari",
    "Saved Application State",
    "Spelling",
    "Suggestions",
    "SyncedPreferences",
    "WebKit",

    "Application Support/Caches",
    "Application Support/CloudDocs",
    "Application Support/com.apple.sharedfilelist",
    "Application Support/com.apple.spotlight",
    "Application Support/CrashReporter",
    "Application Support/Dock",
    "Application Support/FileProvider",

    "Preferences/.GlobalPreferences_m.plist",
    "Preferences/.GlobalPreferences.plist",
    "Preferences/ByHost",
    "Preferences/com.apple.dock.plist",
    "Preferences/com.apple.dt.Xcode.plist",
    "Preferences/com.apple.EmojiCache.plist",
    "Preferences/com.apple.EmojiPreferences.plist",
    "Preferences/com.apple.finder.plist",
    "Preferences/com.apple.mediaanalysisd.plist",
    "Preferences/com.apple.SFSymbols.plist",
    "Preferences/com.apple.Spotlight.plist",
    "Preferences/com.apple.Terminal.plist",
    "Preferences/com.apple.universalaccessAuthWarning.plist"
]

app: list[str] = [
    # Adobe
    "Application Support/Adobe",
    "Preferences/Adobe",
    "Preferences/com.adobe.AdobeRdrCEFHelper.plist",
    "Preferences/com.adobe.crashreporter.plist",
    "Preferences/com.adobe.Reader.plist",

    # Alacritty
    "Preferences/io.alacritty.plist",

    # GitKraken
    "Application Support/GitKraken",
    "Preferences/com.axosoft.gitkraken.plist",

    # Google
    "Application Support/Google",
    "Google",
    "Preferences/com.google.Chrome.plist",
    "Preferences/com.google.Keystone.Agent.plist",

    # ImageOptim
    "Application Scripts/net.pornel.ImageOptimizeExtension",
    "Containers/net.pornel.ImageOptimizeExtension",
    "Group Containers/59KZTZA4XR.net.pornel.ImageOptim",
    "Preferences/net.pornel.ImageOptim.plist",

    # JetBrains
    "Application Support/JetBrains",
    "Preferences/com.jetbrains.toolbox.renderer.plist",

    # Mozilla
    "Application Support/Firefox",
    "Application Support/Mozilla",
    "Preferences/org.mozilla.firefoxdeveloperedition.plist",

    # Notion
    "Application Support/Notion",
    "Preferences/notion.id.plist",

    # OBS
    "Application Support/obs-studio",
    "Preferences/com.obsproject.obs-studio.plist",

    # Postman
    "Application Support/Postman",
    "Preferences/com.postmanlabs.mac.plist",

    # ProtonVPN
    "Preferences/ch.protonvpn.mac.plist",

    # SEB
    "Preferences/org.safeexambrowser.SafeExamBrowser.plist",

    # Spotify
    "Application Support/Spotify",
    "Preferences/com.spotify.client.plist",

    # Visual Studio Code
    "Application Support/Code",
    "Preferences/com.microsoft.VSCode.plist",

    # Zoom
    "Application Support/zoom.us",
    "Preferences/us.zoom.xos.plist",
    "Preferences/ZoomChat.plist",

    # Other
    "Preferences/com.qtproject.plist"
]

#

if __name__ == "__main__":
    print(f"OS: {platform.system()}")
    print(f"HOME: {Path.home()}\n")

    # Setup
    home = Path.home()
    library = home / "Library"

    apple_files = [library / file for file in apple]
    app_files = [library / file for file in app]

    # Actions
    actions: list[Action] = [
        Action("Quit\n", sys.exit),

        Action("Delete Apple files", lambda: print_and_delete(apple_files)),
        Action("Delete App files", lambda: print_and_delete(app_files)),
        Action(
            "Delete 'Cache', 'Caches', 'Logs', 'Saved Application State' files\n",
            lambda: search_and_delete(
                library, ["Cache", "Caches", "Logs", "Saved Application State"]
            )
        ),

        Action(
            "Delete '.DS_Store' files\n",
            lambda: search_and_delete(home, [".DS_Store"])
        ),

        Action("Search", lambda: search_and_delete())
    ]

    print("Actions:")
    for i, action in enumerate(actions):
        print(f"\t{i} - {action.name}")

    # Loop
    while True:
        try:
            answer = int(input("\n> "))
            if answer in range(0, len(actions)):
                try:
                    actions[answer]()
                except EOFError:
                    print(colored(f"\n\tAborted {CROSS}", RED))
            else:
                print(colored("\tOut of range. Try again.", RED))
        except ValueError:
            print(colored("\tEnter a valid number!", RED))
        except (EOFError, KeyboardInterrupt):
            sys.exit()


import codecademylib3_seaborn
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
import matplotlib.pyplot as plt

#Loading the data into a dataframe
flags = pd.read_csv("flags.csv", header = 0)

#Investigating the data
print(flags.columns)
print(flags.head())

#Creating a decision tree to classify what Landmass a country is on
#Getting the labels (Landmass) to be used
labels = flags[["Landmass"]]
#Getting the columns containing the colors of flags; using only the colors of a flag to predict or classify the Landmass of a country
data = flags[["Red", "Green", "Blue", "Gold", "White", "Black", "Orange", "Circles",
"Crosses","Saltires","Quarters","Sunstars",
"Crescent","Triangle"]]

#Splitting the dataframes into training and test sets
train_data, test_data, train_labels, test_labels = train_test_split(data, labels, random_state = 1)

#Making and testing the model
#Calculating the accuracy of the tree 20 times as the size of the tree changes to see what size gives the best prediction accuracy, and plotting in a graph
scores = []
for i in range(1, 21):
  tree = DecisionTreeClassifier(random_state = 1, max_depth = i, max_leaf_nodes = 35)
  tree.fit(train_data, train_labels)
  scores.append(tree.score(test_data, test_labels))

#Plotting the scores
plt.plot(range(1, 21), scores)
plt.show()

#Adding more features (that has to do with shapes in flags) to data, used in classifying Landmass to see if accuracy will increase.
#The depth of the tree isn’t really having an impact on its performance. This might be a good indication that we’re not using enough features.

#Also, setting the max_leaf_nodes to see how accuracy changes (overfitting or underfitting?)

Maame Esi Baidoo Codecademy SML Project 53.py


from fpdf import FPDF
import cv2
import glob
import os
pdf = FPDF()

print(os.path.dirname(os.path.abspath(__file__)))
filenames = glob.glob(os.path.dirname(os.path.abspath(__file__))+'/Stldakash/*')
print(filenames)
i=1
for f in sorted(filenames):
    gray = cv2.imread(f,0)
    retval, thresh_gray = cv2.threshold(gray, thresh=120, maxval=255, type=cv2.THRESH_BINARY)
    cv2.imwrite('{}.png'.format(i),thresh_gray)
    pdf.add_page("L")
    pdf.image('{}.png'.format(i), x=0, y=0, h=210, w=297, type = '', link = '')
    i+=1
for i in glob.glob("*.png"):
    os.remove(i)
pdf.output('stldakash.pdf', 'F')


import warnings
warnings.filterwarnings("ignore")

import sys
import os
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.model_selection import LeaveOneOut
from sklearn.model_selection import cross_val_score
from sklearn.metrics import make_scorer
from sklearn.metrics import recall_score

from sklearn.metrics import f1_score
from sklearn.metrics import accuracy_score
from sklearn.metrics import recall_score
from sklearn.metrics import precision_score
from sklearn.metrics import roc_auc_score

sys.path.insert(0, "utils/")

""" Import all python file model_config"""
import models_config
""" Import all python files in utils folder """
import utils

""" List of Directories """
Input_DIR = 'output/preprocess'
Output_DIR = 'output/prediction'
Evaluation_DIR = 'output/evaluation'

if not os.path.exists(Output_DIR):
    os.makedirs(Output_DIR)

if not os.path.exists(Evaluation_DIR):
    os.makedirs(Evaluation_DIR)

def training ():
    """
    Saves CSV file of LOOCV cross validations
    and CSV files of preditions with proper naming
    for re-evaluation.

    """
    # dictionary for storage
    all_prediction = {}
    all_actual = {}
    all_metricCV = {}
    all_metricCV_Final = {}
    id_list = []

    for filename in os.listdir(Input_DIR):  # Goes through all the files in input directory
        if filename.endswith(".csv") : # checks the CSV files
            all_prediction[filename[:-4]], all_actual[filename[:-4]],all_metricCV[filename[:-4]], id_list = trainIndividually(filename,id_list)  # Individually train per file name: output is collected per file name
            print("---------------")
            print("---------------")
            print(filename + " predicted")

    for i in all_prediction:
        for j in all_prediction[i]:
            output_name ="[" + i + "]_["+ j + "]"  # name of CSV file
            all_metricCV_Final[output_name] = all_metricCV[i][j]
            print(output_name)
            # results
            # combine to a temporary diction for the actual and prediction
            tempt_prediction = all_prediction[i][j].copy()
            tempt_actual = all_actual[i][j].copy()
            tempt_dict = {"Actual":tempt_actual,"ID":id_list}
            tempt_dict['Prediction'] = tempt_prediction
            df = pd.DataFrame (tempt_dict)
            utils.saveData(Output_DIR, output_name, df)
            print(output_name + " SAVED")

    df = pd.DataFrame(all_metricCV_Final).T  # save cross validation into csv file
    df = df.reset_index()
    utils.saveData(Evaluation_DIR, "LOOCV Evaluation", df)

    return

def trainIndividually (filename, id_list ):
    """
    Splits data into train-test and then fit_predict and does cross validation
    Input:
        filename: str
            filename of the
        id_list: list
            number of runs
    Output:
        prediction: dictionary
            dictionary of predictions
        actual: dictionary
            dictionary of actual labels (y-test)
        metricCV: dictionary
            dictionary of LOOCV results
        id_list : list
            list of patient ID
    """
    file_description = models_config.fileDescription(filename)  # fileDescription: gets the preprocessing description from the file name

    print(filename)

    file_location = os.path.join(Input_DIR, filename)
    dataframe = pd.read_csv(file_location)

    prediction = {}
    actual = {}
    metricCV = {}

    model_description = models_config.modelDescription()

    df_copy = dataframe.copy()
    if len(id_list) == 0:
        id_list = df_copy['Patient Identification Number'].values.copy()
        print( "File ID  Copied from " + filename)
    else:
        tempt_list_1 = df_copy['Patient Identification Number'].values.copy()
        tempt_list_2 = id_list.copy()
        if len(tempt_list_1)== len(tempt_list_2) and len(tempt_list_1) == sum([1 for i, j in zip(tempt_list_1, tempt_list_2) if i == j]):
            print ("The ID lists of "+filename+ "are identical to previous")
            print("_______________________________________________________")
        else:
            print("Error !!!  Recalibrate all ID Files")

    df_copy = df_copy.drop("Patient Identification Number", axis=1)
    X, Y, features = utils.labelSeparator(df_copy,file_description['label'])  # separates labels and features from dataframe

    for i in model_description:  # goes through all the models # for Hyp 1: only regression models
        print("-------------------")
        print("-------------------")
        print(i['model_name'], " prediction !!!")

        metricCV[i['model_name']], prediction[i['model_name']], actual[i['model_name']] = trainCV(X, Y, i['model'])  # cross validation of training
        print(i['model_name'], " prediction DONE!!!")

    return prediction, actual, metricCV, id_list

def trainCV(X,Y, model):
    """
    Cross validation using LOOCV
    Input:
        X: matrix
            x-train
        Y: list
            y-train
        model: model function
            model
    Output:
        metricCV: dictionary
            cross validation results
        y_pred: list
            list of prediction using the specific and model imported file
        y_true:list
            list of actual value using the specific model and imported file

    """

    metricCV = {}

    # create loocv procedure
    cv = LeaveOneOut()
    # enumerate splits
    y_true, y_pred = list(), list()
    for train_ix, test_ix in cv.split(X):
        # split data
        X_train, X_test = X[train_ix, :], X[test_ix, :]
        y_train, y_test = Y[train_ix], Y[test_ix]
        model.fit(X_train, y_train)
        # evaluate model
        yhat = model.predict(X_test)
        # store
        y_true.append(y_test[0])
        y_pred.append(yhat[0])

    metricCV["accuracy"]= accuracy_score(y_true,y_pred)
    metricCV["sensitivity"] = recall_score(y_true,y_pred)
    metricCV["specificity"] = recall_score(y_true,y_pred, pos_label = 0 )
    metricCV["auc"] = roc_auc_score(y_true,y_pred)

    return metricCV, y_pred, y_true

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

  training()

  print("Done")


def test_can_configure_ngpf_ipv4(config_assistant):

    config = config_assistant.config
    vports = config.Vport.add().add()

    topology = config.Topology.add(Name='Topology 1', Ports=vports)

    device_group = topology.DeviceGroup.add(Name='Device 1', Multiplier='7')
    device_group.Enabled.Alternate(False)

    ethernet = device_group.Ethernet.add()

    ethernet.Mac.Decrement(start_value='00:00:de:ad:be:ef', step_value='00:00:fa:ce:fa:ce')

    ipv4 = ethernet.Ipv4.add(Name='Ipv4 1')

    ipv4.Address.Increment(start_value='1.1.1.1', step_value='0.1.1.1')
    config_assistant.commit()

    topology = config.Topology.find()
    device_group = topology[0].DeviceGroup.find()
    ethernet = device_group[0].Ethernet.find()
    ipv4 = ethernet[0].Ipv4.find()
    print(device_group.Enabled)
    assert(ipv4.Address == 'Inc: 1.1.1.1, 0.1.1.1')
    assert(len(topology) == 1)
    assert(len(device_group) == 1)
    assert (device_group.Enabled == 'Alt: False')
    assert(len(ethernet) == 1)
    assert (ethernet.Mac == 'Dec: 00:00:de:ad:be:ef, 00:00:fa:ce:fa:ce')


from data_providers.cifar import Cifar10DataProvider, Cifar100DataProvider, \
	Cifar10AugmentedDataProvider, Cifar100AugmentedDataProvider

def get_data_provider_by_name(name, train_params: dict):
	""" Return required data provider class """
	if name == 'C10':
		return Cifar10DataProvider(**train_params)
	if name == 'C10+':
		return Cifar10AugmentedDataProvider(**train_params)
	if name == 'C100':
		return Cifar100DataProvider(**train_params)
	if name == 'C100+':
		return Cifar100AugmentedDataProvider(**train_params)
	else:
		print('Sorry, data provider for `%s` dataset '
		      'was not implemented yet' % name)
		exit()


import asyncio
import os
from shutil import rmtree
import datetime
import wikipedia
import requests
from justwatch import JustWatch
from bs4 import BeautifulSoup
from search_engine_parser import GoogleSearch
from search_engine_parser.core.exceptions import NoResultsOrTrafficError as GoglError
from geopy.geocoders import Nominatim
from telethon.tl import types

from . import *

def progress(current, total):
    logger.info(
        "Downloaded {} of {}\nCompleted {}".format(
            current, total, (current / total) * 100
        )
    )

@bot.on(deadly_cmd(pattern="wikipedia (.*)"))
@bot.on(sudo_cmd(pattern="wikipedia (.*)", allow_sudo=True))
async def _(event):
    if event.fwd_from:
        return
    await edit_or_reply(event, "Processing ...")
    input_str = event.pattern_match.group(1)
    result = ""
    results = wikipedia.search(input_str)
    for s in results:
        page = wikipedia.page(s)
        url = page.url
        result += f"> [{s}]({url}) \n"
    await edit_or_reply(event, "WikiPedia **Search**: {} \n\n **Result**: \n\n{}".format(input_str, result)
    )

@bot.on(deadly_cmd(pattern="watch (.*)"))
@bot.on(sudo_cmd(pattern="watch (.*)", allow_sudo=True))
async def _(event):
    if event.fwd_from:
        return
    query = event.pattern_match.group(1)
    deadly = await eor(event, "Finding Sites...")
    streams = get_stream_data(query)
    title = streams["title"]
    thumb_link = streams["movie_thumb"]
    release_year = streams["release_year"]
    release_date = streams["release_date"]
    scores = streams["score"]
    try:
        imdb_score = scores["imdb"]
    except KeyError:
        imdb_score = None

    try:
        tmdb_score = scores["tmdb"]
    except KeyError:
        tmdb_score = None

    stream_providers = streams["providers"]
    if release_date is None:
        release_date = release_year

    output_ = f"**Movie:**\n`{title}`\n**Release Date:**\n`{release_date}`"
    if imdb_score:
        output_ = output_ + f"\n**IMDB: **{imdb_score}"
    if tmdb_score:
        output_ = output_ + f"\n**TMDB: **{tmdb_score}"

    output_ = output_ + "\n\n**Available on:**\n"
    for provider, link in stream_providers.items():
        if "sonyliv" in link:
            link = link.replace(" ", "%20")
        output_ += f"[{pretty(provider)}]({link})\n"

    await bot.send_file(
        event.chat_id,
        caption=output_,
        file=thumb_link,
        force_document=False,
        allow_cache=False,
        silent=True,
    )
    await event.delete()

@bot.on(deadly_cmd(pattern="google (.*)", outgoing=True))
@bot.on(sudo_cmd(pattern="google (.*)", allow_sudo=True))
async def google(event):
    input_str = event.pattern_match.group(1)
    if not input_str:
        return await eod(event, "`Give something to search..`")
    deadly = await eor(event, "Searching...")
    gos = GoogleSearch()
    try:
        got = await gos.async_search(f"{input_str}", cache=False)
    except GoglError as e:
        return await eod(event, str(e), 10)
    output = ""
    for i in range(len(got["links"])):
        text = got["titles"][i]
        url = got["links"][i]
        des = got["descriptions"][i]
        output += f" 👉🏻  [{text}]({url})\n`{des}`\n\n"
    res = f"**Google Search Query:**\n`{input_str}`\n\n**Results:**\n{output}"
    see = []
    for i in range(0, len(res), 4095):
        see.append(res[i : i + 4095])
    for j in see:
        await bot.send_message(event.chat_id, j, link_preview=False)
    await deadly.delete()
    see.clear()

@bot.on(deadly_cmd(pattern="img (.*)", outgoing=True))
@bot.on(sudo_cmd(pattern="img (.*)", allow_sudo=True))
async def img(event):
    sim = event.pattern_match.group(1)
    if not sim:
        return await eod(event, "`Give something to search...`")
    deadly = await eor(event, f"Searching for  `{sim}`...")
    if "-" in sim:
        try:
            lim = int(sim.split(";")[1])
            sim = sim.split(";")[0]
        except BaseExceptaion:
            lim = 5
    else:
        lim = 5
    imgs = googleimagesdownload()
    args = {
        "keywords": sim,
        "limit": lim,
        "format": "jpg",
        "output_directory": "./DOWNLOADS/",
    }
    letsgo = imgs.download(args)
    gotit = letsgo[0][sim]
    await event.client.send_file(event.chat_id, gotit, caption=sim, album=True)
    rmtree(f"./DOWNLOADS/{sim}/")
    await deadly.delete()

@bot.on(deadly_cmd(pattern="reverse"))
@bot.on(sudo_cmd(pattern="reverse", allow_sudo=True))
async def _(event):
    if event.fwd_from:
        return
    start = datetime.datetime.now()
    BASE_URL = "http://www.google.com"
    OUTPUT_STR = "Reply to an image to do Google Reverse Search"
    if event.reply_to_msg_id:
        deadly = await eor(event, "Pre Processing Media")
        previous_message = await event.get_reply_message()
        previous_message_text = previous_message.message
        if previous_message.media:
            downloaded_file_name = await bot.download_media(
                previous_message, Config.TMP_DOWNLOAD_DIRECTORY
            )
            SEARCH_URL = "{}/searchbyimage/upload".format(BASE_URL)
            multipart = {
                "encoded_image": (
                    downloaded_file_name,
                    open(downloaded_file_name, "rb"),
                ),
                "image_content": "",
            }
            # https://stackoverflow.com/a/28792943/4723940
            google_rs_response = requests.post(
                SEARCH_URL, files=multipart, allow_redirects=False
            )
            the_location = google_rs_response.headers.get("Location")
            os.remove(downloaded_file_name)
        else:
            previous_message_text = previous_message.message
            SEARCH_URL = "{}/searchbyimage?image_url={}"
            request_url = SEARCH_URL.format(BASE_URL, previous_message_text)
            google_rs_response = requests.get(request_url, allow_redirects=False)
            the_location = google_rs_response.headers.get("Location")
        await deadly.edit("Found Google Result. Processing results...")
        headers = {
            "User-Agent": "Mozilla/5.0 (X11; Linux x86_64; rv:58.0) Gecko/20100101 Firefox/58.0"
        }
        response = requests.get(the_location, headers=headers)
        soup = BeautifulSoup(response.text, "html.parser")
        # document.getElementsByClassName("r5a77d"): PRS
        prs_div = soup.find_all("div", {"class": "r5a77d"})[0]
        prs_anchor_element = prs_div.find("a")
        prs_url = BASE_URL + prs_anchor_element.get("href")
        prs_text = prs_anchor_element.text
        # document.getElementById("jHnbRc")
        img_size_div = soup.find(id="jHnbRc")
        img_size = img_size_div.find_all("div")
        end = datetime.datetime.now()
        ms = (end - start).seconds
        OUTPUT_STR = """Possible Related Search : {prs_text}

More Info: Open this Link in {ms} seconds""".format(
            **locals()
        )
    await deadly.edit(OUTPUT_STR, parse_mode="HTML", link_preview=False)

@bot.on(deadly_cmd(pattern="gps ?(.*)"))
@bot.on(sudo_cmd(pattern="gps ?(.*)", allow_sudo=True))
async def gps(event):
    if event.fwd_from:
        return
    reply_to_id = event.message
    if event.reply_to_msg_id:
        reply_to_id = await event.get_reply_message()
    input_str = event.pattern_match.group(1)
    if not input_str:
        return await eod(event, "What should i find? Give me location.🤨")

    await edit_or_reply(event, "Finding😁")

    geolocator = Nominatim(user_agent="DeadlyBot")
    geoloc = geolocator.geocode(input_str)

    if geoloc:
        lon = geoloc.longitude
        lat = geoloc.latitude
        await reply_to_id.reply(
            input_str, file=types.InputMediaGeoPoint(types.InputGeoPoint(lat, lon))
        )
        await event.delete()
    else:
        await eod(event, "I coudn't find it😫")

CmdHelp("google").add_command(
  "google", "<query>", "Does a google search for the query provided"
).add_command(
  "img", "<query>", "Does a image search for the query provided"
).add_command(
  "reverse", "<reply to a sticker/pic>", "Does a reverse image search on google and provides the similar images"
).add_command(
  "gps", "<place>", "Gives the location of the given place/city/state."
).add_command(
  "wikipedia", "<query>", "Searches for the query on Wikipedia."
).add_command(
  "watch", "<query>", "Searches for all the available sites for watching that movie or series."
).add_info(
  "Google Search."
).add_warning(
  "✅ Harmless Module."
).add()


import sublime, sublime_plugin, re

def new_style_hash(matchobj):
  spaces = len(matchobj.group(3) + matchobj.group(4)) - 1
  if spaces < 1: spaces = 1
  return "%s%s:%s" % (matchobj.group(1), matchobj.group(2), spaces * ' ')

class HashSyntax(sublime_plugin.TextCommand):
  def run(self, edit):
    regions = [region for region in self.view.sel() if not region.empty()]
    if not len(regions):
      regions = [sublime.Region(0, self.view.size())]
    for region in regions:
      self.replace_hashes(edit, region)

  def replace_hashes(self, edit, region):
    s = self.view.substr(region)
    s = re.sub(r'([^\:])\:([a-zA-Z_0-9]*)(\s*)=\>(\s*)', new_style_hash, s)
    self.view.replace(edit, region, s)


from ..diagramtype import DiagramType
from ..elementtype import ElementType
from ..connectiontype import ConnectionType
from ..projecttemplate import ProjectTemplate

from umlfri2.ufl.types.structured import UflObjectAttribute
from umlfri2.ufl.types.enum import UflEnumPossibility

from .attributetranslation import AttributeTranslation
from .configattributetransslation import ConfigAttributeTranslation

class Translation:
    def __init__(self, language, translations):
        self.__language = language
        self.__element_names = {}
        self.__diagram_names = {}
        self.__connection_names = {}
        self.__attribute_names = AttributeTranslation()
        self.__config_attribute_names = ConfigAttributeTranslation()
        self.__enum_item_names = AttributeTranslation()
        self.__template_names = {}

        for type, path, label in translations:
            if type == 'element':
                self.__element_names[path] = label
            elif type == 'diagram':
                self.__diagram_names[path] = label
            elif type == 'connection':
                self.__connection_names[path] = label
            elif type == 'attribute':
                child = self.__attribute_names
                for part in reversed(path.split('/')):
                    child = child.add_parent(part)
                child.label = label
            elif type == 'config':
                child = self.__config_attribute_names
                for part in reversed(path.split('/')):
                    child = child.add_parent(part)
                child.label = label
            elif type == 'enumitem':
                if path.endswith('*'):
                    raise Exception
                child = self.__enum_item_names
                for part in reversed(path.split('/')):
                    child = child.add_parent(part)
                child.label = label
            elif type == 'template':
                self.__template_names[path] = label

    @property
    def language(self):
        return self.__language

    def translate(self, object):
        if isinstance(object, ConnectionType):
            return self.__connection_names.get(object.id, object.id)
        elif isinstance(object, ElementType):
            return self.__element_names.get(object.id, object.id)
        elif isinstance(object, DiagramType):
            return self.__diagram_names.get(object.id, object.id)
        elif isinstance(object, UflObjectAttribute):
            ret = self.__attribute_names.translate(object)
            if ret is None:
                ret = self.__config_attribute_names.translate(object)
                if ret is None:
                    return object.name
            return ret
        elif isinstance(object, UflEnumPossibility):
            ret = self.__enum_item_names.translate(object)
            if ret is None:
                return object.name
            else:
                return ret
        elif isinstance(object, ProjectTemplate):
            return self.__template_names.get(object.id, object.id)
        raise Exception

POSIX_TRANSLATION = Translation("POSIX", ())


"""testfile.py -- Manage test files for unit tests."""

import locale
import os

def check_contents(filename, contents):
    """Check that the file contains the expected content."""
    encoding = locale.getpreferredencoding(False)
    with open(filename, 'rt', encoding=encoding) as fin:
        text = fin.read()
    assert text == contents

def create_file(filename, contents=''):
    """Create a file with the specified contents."""
    encoding = locale.getpreferredencoding(False)
    with open(filename, 'wt', encoding=encoding) as fout:
        fout.write(contents)

def remove_file(filename):
    """Remove the file if it exists."""
    if os.path.isfile(filename):
        os.remove(filename)
    assert not os.path.isfile(filename)


SIDEBAR_STYLE = {
    'top': 0,
    'left': 0,
    'bottom': 0,
    'width': '18vw',
    'padding': '2rem 1rem',
    'background-color': '#f8f9fa',
    'z-index': '1',
    'overflowY': 'auto',
    'min-width': '310px'
}

MAIN_STYLE = {
    'width': '100vw',
    'margin-left': '320px',
    'text-align': 'center'
}


class Solution(object):
    def firstUniqChar(self, s):
    	d = {}

    	for i in s:
    		if i not in d:
    			d[i] = 1
    		else:
    			d[i] += 1

    	for i,j in enumerate(s):
    		if d[j] == 1:
    			return i
    		else:
    			i += 1
    	return -1

s = Solution()
print(s.firstUniqChar("loveleetcode"))


import Player as p
import Tic_Tac_Toe_Game as ttt

game_type = 1
p1_sym = "X"
p2_sym = "O"

print("This program initializes a Tic Tac Toe Game.")
print("Player 1 will be X's and Player 2 will be O's")
p1_name = input("Player 1 name: ")
p2_name = input("Player 2 name: ")

p1 = p.Player(p1_name, p1_sym)
p2 = p.Player(p2_name, p2_sym)

ttt.Tic_Tac_Toe_Game(game_type, p1, p2)


from ufl.algorithms.transformer import ReuseTransformer, apply_transformer
from ufl.classes import Terminal
from ufl.constantvalue import Zero
from ufl.core.multiindex import FixedIndex, Index, MultiIndex
from ufl.differentiation import Grad
from ufl.utils.stacks import Stack, StackDict

class IndexExpander(ReuseTransformer):
    """Index expander."""

    def __init__(self):
        """Initialise."""
        ReuseTransformer.__init__(self)
        self._components = Stack()
        self._index2value = StackDict()

    def component(self):
        """Return current component tuple."""
        if self._components:
            return self._components.peek()
        return ()

    def terminal(self, x):
        """Apply to terminal."""
        if x.ufl_shape:
            c = self.component()
            if len(x.ufl_shape) != len(c):
                raise ValueError("Component size mismatch.")
            return x[c]
        return x

    def form_argument(self, x):
        """Apply to form_argument."""
        sh = x.ufl_shape
        if sh == ():
            return x
        else:
            e = x.ufl_element()
            r = len(sh)

            # Get component
            c = self.component()
            if r != len(c):
                raise ValueError("Component size mismatch.")

            # Map it through an eventual symmetry mapping
            if len(e.components) > 1:
                c = min(i for i, j in e.components.items() if j == e.components[c])
                if r != len(c):
                    raise ValueError("Component size mismatch after symmetry mapping.")

            return x[c]

    def zero(self, x):
        """Apply to zero."""
        if len(x.ufl_shape) != len(self.component()):
            raise ValueError("Component size mismatch.")

        s = set(x.ufl_free_indices) - set(i.count() for i in self._index2value.keys())
        if s:
            raise ValueError(f"Free index set mismatch, these indices have no value assigned: {s}.")

        # There is no index/shape info in this zero because that is asserted above
        return Zero()

    def scalar_value(self, x):
        """Apply to scalar_value."""
        if len(x.ufl_shape) != len(self.component()):
            self.print_visit_stack()
        if len(x.ufl_shape) != len(self.component()):
            raise ValueError("Component size mismatch.")

        s = set(x.ufl_free_indices) - set(i.count() for i in self._index2value.keys())
        if s:
            raise ValueError(f"Free index set mismatch, these indices have no value assigned: {s}.")

        return x._ufl_class_(x.value())

    def conditional(self, x):
        """Apply to conditional."""
        c, t, f = x.ufl_operands

        # Not accepting nonscalars in condition
        if c.ufl_shape != ():
            raise ValueError("Not expecting tensor in condition.")

        # Conditional may be indexed, push empty component
        self._components.push(())
        c = self.visit(c)
        self._components.pop()

        # Keep possibly non-scalar components for values
        t = self.visit(t)
        f = self.visit(f)

        return self.reuse_if_possible(x, c, t, f)

    def division(self, x):
        """Apply to division."""
        a, b = x.ufl_operands

        # Not accepting nonscalars in division anymore
        if a.ufl_shape != ():
            raise ValueError("Not expecting tensor in division.")
        if self.component() != ():
            raise ValueError("Not expecting component in division.")

        if b.ufl_shape != ():
            raise ValueError("Not expecting division by tensor.")
        a = self.visit(a)

        # self._components.push(())
        b = self.visit(b)
        # self._components.pop()

        return self.reuse_if_possible(x, a, b)

    def index_sum(self, x):
        """Apply to index_sum."""
        ops = []
        summand, multiindex = x.ufl_operands
        index, = multiindex

        # TODO: For the list tensor purging algorithm, do something like:
        # if index not in self._to_expand:
        #     return self.expr(x, *[self.visit(o) for o in x.ufl_operands])

        for value in range(x.dimension()):
            self._index2value.push(index, value)
            ops.append(self.visit(summand))
            self._index2value.pop()
        return sum(ops)

    def _multi_index_values(self, x):
        """Apply to _multi_index_values."""
        comp = []
        for i in x._indices:
            if isinstance(i, FixedIndex):
                comp.append(i._value)
            elif isinstance(i, Index):
                comp.append(self._index2value[i])
        return tuple(comp)

    def multi_index(self, x):
        """Apply to multi_index."""
        comp = self._multi_index_values(x)
        return MultiIndex(tuple(FixedIndex(i) for i in comp))

    def indexed(self, x):
        """Apply to indexed."""
        A, ii = x.ufl_operands

        # Push new component built from index value map
        self._components.push(self._multi_index_values(ii))

        # Hide index values (doing this is not correct behaviour)
        # for i in ii:
        #     if isinstance(i, Index):
        #         self._index2value.push(i, None)

        result = self.visit(A)

        # Un-hide index values
        # for i in ii:
        #     if isinstance(i, Index):
        #         self._index2value.pop()

        # Reset component
        self._components.pop()
        return result

    def component_tensor(self, x):
        """Apply to component_tensor."""
        # This function evaluates the tensor expression
        # with indices equal to the current component tuple
        expression, indices = x.ufl_operands
        if expression.ufl_shape != ():
            raise ValueError("Expecting scalar base expression.")

        # Update index map with component tuple values
        comp = self.component()
        if len(indices) != len(comp):
            raise ValueError("Index/component mismatch.")
        for i, v in zip(indices.indices(), comp):
            self._index2value.push(i, v)
        self._components.push(())

        # Evaluate with these indices
        result = self.visit(expression)

        # Revert index map
        for _ in comp:
            self._index2value.pop()
        self._components.pop()
        return result

    def list_tensor(self, x):
        """Apply to list_tensor."""
        # Pick the right subtensor and subcomponent
        c = self.component()
        c0, c1 = c[0], c[1:]
        op = x.ufl_operands[c0]
        # Evaluate subtensor with this subcomponent
        self._components.push(c1)
        r = self.visit(op)
        self._components.pop()
        return r

    def grad(self, x):
        """Apply to grad."""
        f, = x.ufl_operands
        if not isinstance(f, (Terminal, Grad)):
            raise ValueError("Expecting expand_derivatives to have been applied.")
        # No need to visit child as long as it is on the form [Grad]([Grad](terminal))
        return x[self.component()]

def expand_indices(e):
    """Expand indices."""
    return apply_transformer(e, IndexExpander())


####################################################################################
##
##  Script: NOAA_Pacific_CPC.py
##
##      - check out second example here - http://www.programcreek.com/python/example/81585/urllib.request.urlretrieve
##      - build in error checking
##      - figure out what this data is for
##      - find the download schedule
##      - unzip and load shapefile into postgres
##
####################################################################################

import os, sys,datetime, psycopg2,urllib2,urllib
import requests
from contextlib import closing
import csv

#Create Date Part  YYMMDD
print(datetime.datetime.today())

#YEAR
year = str(datetime.datetime.today().year)
formattedYear = (year[-2:])

#MONTH
month = datetime.datetime.today().month

if len(str(month)) == 1:
    formattedMonth = '0'+str(month)
    print(formattedMonth)
elif len(str(month)) == 2:
    formattedMonth = str(month)

#DAY - get previous day
day = datetime.datetime.today().day
print(len(str(day)))

if len(str(day)) == 1:
    formattedDay = '0'+str(day)
else:
    formattedDay = str(day)

formattedDate = formattedYear+formattedMonth+formattedDay

outputfolder = 'C:/Work/Projects/everyday/download_data/ClimatePredictionCenter/'+formattedDate
if not os.path.exists(outputfolder):
    os.makedirs(outputfolder)

#Week 1
#Tropical Cyclone Formation
cpc_week1_tcf_shp = 'http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/TC_W1_latest.zip'
urllib.urlretrieve(cpc_week1_tcf_shp, outputfolder+"/TC_W1_latest_"+formattedDate+".zip")
print('TC_W1_latest Downloaded')

#Upper Tercile Precipitation
cpc_week1_utp = 'http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/WET_W1_latest.zip'
urllib.urlretrieve(cpc_week1_utp, outputfolder+"/WET_W1_latest_"+formattedDate+".zip")
print('WET_W1_latest Downloaded')

#Lower Tercile Precipitation
cpc_week1_ltp = 'http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/DRY_W1_latest.zip'
urllib.urlretrieve(cpc_week1_ltp, outputfolder+"/DRY_W1_latest_"+formattedDate+".zip")
print('DRY_W1_latest Downloaded')

#Above Average Temperatures
cpc_week1_aat ='http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/WARM_W1_latest.zip'
urllib.urlretrieve(cpc_week1_aat, outputfolder+"/WARM_W1_latest_"+formattedDate+".zip")
print('WARM_W1_latest Downloaded')

#Below Average Temperatures
cpc_week1_bat = 'http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/COLD_W1_latest.zip'
urllib.urlretrieve(cpc_week1_bat, outputfolder+"/COLD_W1_latest_"+formattedDate+".zip")
print('COLD_W1_latest Downloaded')

#Week2
#Tropical Cyclone Formation
cpc_week2_tcf_shp='http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/TC_W2_latest.zip'
urllib.urlretrieve(cpc_week2_tcf_shp, outputfolder+"/TC_W2_latest_"+formattedDate+".zip")
print('TC_W2_latest Downloaded')

#Upper Tercile Precipitation
cpc_week2_utp ='http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/WET_W2_latest.zip'
urllib.urlretrieve(cpc_week2_utp, outputfolder+"/WET_W2_latest_"+formattedDate+".zip")
print('WET_W2_latest Downloaded')

#Lower Tercile Precipitation
cpc_week2_ltp ='http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/DRY_W2_latest.zip'
urllib.urlretrieve(cpc_week2_ltp, outputfolder+"/DRY_W2_latest_"+formattedDate+".zip")
print('DRY_W2_latest Downloaded')

#Above Average Temperatures
cpc_week2_aat ='http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/WARM_W2_latest.zip'
urllib.urlretrieve(cpc_week2_aat, outputfolder+"/WARM_W2_latest_"+formattedDate+".zip")
print('WARM_W2_latest Downloaded')

#Below Average Temperatures
cpc_week2_bat ='http://www.cpc.ncep.noaa.gov/products/precip/CWlink/ghazards/Shps/COLD_W2_latest.zip'
urllib.urlretrieve(cpc_week2_bat, outputfolder+"/COLD_W2_latest_"+formattedDate+".zip")
print('COLD_W2_latest Downloaded')

print('Script Complete')


import os
import logging
import psycopg2
import psycopg2.extras as psycop_extras
from nose.tools import nottest
from application.services import config_service
from application.services import logging_service
from application.services import debug_service
from application.services import conversion_service
from application.services import database_service
from application.models.classes import dycast_parameters

debug_service.enable_debugger()

current_dir = os.path.basename(os.path.dirname(os.path.realpath(__file__)))

@nottest
def init_test_environment():
    config_path = os.path.join(current_dir, '..', 'dycast.config')

    config_service.init_config(config_path)
    logging_service.init_logging()

@nottest
def get_dycast_parameters():
    dycast = dycast_parameters.DycastParameters()

    dycast.srid_of_cases = '3857'
    dycast.files_to_import = get_test_cases_import_files_latlong()

    dycast.spatial_domain = 600
    dycast.temporal_domain = 28
    dycast.close_in_space = 100
    dycast.close_in_time = 4
    dycast.case_threshold = 10

    dycast.startdate = conversion_service.get_date_object_from_string('2016-03-30')
    dycast.enddate = conversion_service.get_date_object_from_string('2016-03-31')
    dycast.extent_min_x = 1830400
    dycast.extent_min_y = 2120600
    dycast.extent_max_x = 1830700
    dycast.extent_max_y = 2120300
    dycast.srid_of_extent = 3857

    return dycast

@nottest
def get_test_data_directory():
    return os.path.join(current_dir, 'test_data')

@nottest
def get_test_data_import_directory():
    return os.path.join(get_test_data_directory(), 'import')

@nottest
def get_test_data_export_directory():
    return os.path.join(get_test_data_directory(), 'export')

@nottest
def get_test_cases_import_files_latlong():
    file_1 = os.path.join(get_test_data_import_directory(), 'input_cases_latlong1.tsv')
    file_2 = os.path.join(get_test_data_import_directory(), 'input_cases_latlong2.tsv')
    return [file_1, file_2]

@nottest
def get_test_cases_import_file_geometry():
    return os.path.join(get_test_data_import_directory(), 'input_cases_geometry.tsv')

@nottest
def get_count_from_table(table_name):
    cur, conn = database_service.init_db()
    querystring = "SELECT count(*) from " + table_name
    try:
        cur.execute(querystring)
    except Exception:
        conn.rollback()
        logging.exception("Can't select count from table, exiting...")
        raise
    new_row = cur.fetchone()
    return new_row[0]

@nottest
def insert_test_risk():
    cur, conn = database_service.init_db()
    querystring = "INSERT INTO risk VALUES %s"
    data_tuple = [('2016-03-30', 1830400, 2120400, 10, 1, 6, 7, 0.3946), ('2016-03-31', 1830400, 2120400, 10, 1, 6, 7, 0.3946)]
    try:
        psycop_extras.execute_values(cur, querystring, data_tuple)
    except psycopg2.IntegrityError:
        conn.rollback()
        logging.warning("Couldn't insert duplicate key in tuple: %s...", data_tuple)
    except Exception:
        conn.rollback()
        logging.exception("Couldn't insert tuple")
        raise
    conn.commit()


from datetime import datetime
from pipeline.task import create_task

def test_calls_correct_function():
    task_template = {
        "name": "convert_date",
        "function": {
            "name": "datetime.datetime.fromisoformat",
        },
        "input": [{"name": "date_str"}],
        "output": [{"name": "input_date"}]
    }

    task = create_task(task_template)

    assert task("2021-02-01") == datetime(year=2021, month=2, day=1)


CONF_FILE_PATH='macro_logic.json'
from .devicesMacroKeys import *
from . import listboxHelper
from . import confFileManager
macros_conf_loaded={}
confFileManager.check_path(CONF_FILE_PATH)
macros_conf_loaded=confFileManager.load_file(CONF_FILE_PATH, macros_conf_loaded)

class MacroDevice:
    def __init__(self, macrokey_arr, device_uid, device):
        self.macrokey_arr = macrokey_arr
        self.device_uid = device_uid
        self.device = device
        self.set_all_current_macros()

    def get_key(self, key_n):
        for k in self.macrokey_arr:
            if key_n == k.key:
                return k
        return None

    def set_macro(self, key, n_macro):
        key_obj=self.get_key(key)
        if not key_obj:
            raise ValueError("get_key() for key "+key+" returned None")
        macros_conf_loaded[self.device_uid][key]=n_macro
        key_obj._set_macro(self.device, n_macro)
        confFileManager.save_file(CONF_FILE_PATH, macros_conf_loaded)

    def set_all_current_macros(self):
        for key in self.macrokey_arr:
            key.set_current_macro(self.device)

class MacroKey:
    def __init__(self, key, macro=None):
        self.key = key
        self.macro = macro

    def _set_macro(self, device, n_macro):
        self.macro=n_macro
        if not n_macro:
            device.macro.del_macro(self.key)
            return
        script_macro=device.macro.create_script_macro_item(n_macro)
        # add macro doesn't append macros to the same key, it overwrites
        device.macro.add_macro(self.key, script_macro)

    def set_current_macro(self, device):
        self._set_macro(device, self.macro)

    def __repr__(self):
        return self.key

def make_shortcutslistbox_rows(m_dev):
    rowlist=[]
    for key in m_dev.macrokey_arr:
        rowlist.append(listboxHelper.make_2x_row(key.key, key.macro))
    return rowlist

def make_device(device_uid, device):
    try:
        if not device.name in macro_kls.keys(): # failsafe for unsupported devices
            return None
        mk_arr=[]
        if not device_uid in macros_conf_loaded.keys():
            macros_conf_loaded[device_uid] = dict()
            for key_n in macro_kls[device.name]:
                macros_conf_loaded[device_uid][key_n] = ''
            confFileManager.save_file(CONF_FILE_PATH, macros_conf_loaded)
        for key_n in macro_kls[device.name]:
            mk_arr.append(MacroKey(key_n, macros_conf_loaded[device_uid][key_n]))
        n_device = MacroDevice(mk_arr, device_uid, device)
        n_device.set_all_current_macros()
        return n_device
    except Exception as ex:
        print('Skipping macro logic for device {}\n  Exception: {}'.format(device.name, ex))
        return None


import sys, colorsys
import ioexpander as io
from colorama import init, Fore, Style
init()

from lib.logger import Logger

# ..............................................................................
class Potentiometer(object):
    '''
    Configures an IO Expander Potentiometer breakout, returning an analog
    value scaled to a specified range. For a center-zero pot simply
    specify the minimum value as (-1.0 * out_max).
    '''
    def __init__(self, config, level):
        super().__init__()
        self._log = Logger('ioe', level)
        if config is None:
            raise ValueError('no configuration provided.')
        _config = config['ros'].get('ioe_potentiometer')

        # 0x18 for IO Expander, 0x0E for the potentiometer breakout
#       self._i2c_addr = 0x0E
        self._i2c_addr   = _config.get('i2c_address')
        self._pin_red    = _config.get('pin_red')
        self._pin_green  = _config.get('pin_green')
        self._pin_blue   = _config.get('pin_blue')
        self._log.info("pins: red: {}; green: {}; blue: {}".format(self._pin_red, self._pin_green, self._pin_blue))

        self._pot_enc_a  = 12
        self._pot_enc_b  = 3
        self._pot_enc_c  = 11
        self._max_value  = 3.3                       # maximum voltage (3.3v supply)
        self._brightness = _config.get('brightness') # effectively max fraction of period LED will be on
        self._period = int(255 / self._brightness)   # add a period large enough to get 0-255 steps at the desired brightness

        _in_min = _config.get('in_min')  # minimum analog value from IO Expander
        _in_max = _config.get('in_max')  # maximum analog value from IO Expander
        self.set_input_limits(_in_min, _in_max)
        _out_min = _config.get('out_min') # minimum scaled output value
        _out_max = _config.get('out_max') # maximum scaled output value
        self.set_output_limits(_out_min, _out_max)

        # now configure IO Expander
        self._ioe = io.IOE(i2c_addr=self._i2c_addr)
        self._ioe.set_mode(self._pot_enc_a, io.PIN_MODE_PP)
        self._ioe.set_mode(self._pot_enc_b, io.PIN_MODE_PP)
        self._ioe.set_mode(self._pot_enc_c, io.ADC)
        self._ioe.output(self._pot_enc_a, 1)
        self._ioe.output(self._pot_enc_b, 0)
        self._ioe.set_pwm_period(self._period)
        self._ioe.set_pwm_control(divider=2)  # PWM as fast as we can to avoid LED flicker
        self._ioe.set_mode(self._pin_red,   io.PWM, invert=True)
        self._ioe.set_mode(self._pin_green, io.PWM, invert=True)
        self._ioe.set_mode(self._pin_blue,  io.PWM, invert=True)

        self._log.info("running LED with {} brightness steps.".format(int(self._period * self._brightness)))
        self._log.info("ready.")

    # ..........................................................................
    def set_input_limits(self, in_min, in_max):
        self._in_min = in_min
        self._in_max = in_max
        self._log.info('input range:\t{:>5.2f}-{:<5.2f}'.format(self._in_min, self._in_max))

    # ..........................................................................
    def set_output_limits(self, out_min, out_max):
        self._out_min = out_min
        self._out_max = out_max
        self._log.info('output range:\t{:>5.2f}-{:<5.2f}'.format(self._out_min, self._out_max))

    # ..........................................................................
    def get_value(self):
        value = self._max_value - self._ioe.input(self._pot_enc_c)
        self._log.debug(Fore.BLACK + 'value: {:<5.2f}'.format(value))
        return value

    # ..........................................................................
    def set_rgb(self, value):
        h = value / self._max_value # time.time() / 10.0
        r, g, b = [int(c * self._period * self._brightness) for c in colorsys.hsv_to_rgb(h, 1.0, 1.0)]
        self._ioe.output(self._pin_red, r)
        self._ioe.output(self._pin_green, g)
        self._ioe.output(self._pin_blue, b)
        self._log.debug('value: {:<5.2f}; rgb: {},{},{}'.format(value, r, g, b))

    # ..........................................................................
    def get_scaled_value(self, update_led=True):
        '''
        Return a scaled value while also updating the RGB LED if the
        argument is True (the default).
        '''
        _value = self.get_value()
        if update_led:
            self.set_rgb(_value)
        return self.scale_value(_value) # as float

#   # ..........................................................................
#   def x_get_scaled_value(self):
#       '''
#                  (out_max - out_min)(value - in_min)
#           f(x) = -----------------------------------  + out_min
#                           in_max - in_min

#           where: a = 0.0, b = 1.0, min = 0, max = 330.
#       '''
#       return (( self._out_max - self._out_min ) * ( self.get_value() - self._in_min ) / ( self._in_max - self._in_min )) + self._out_min

    # ..........................................................................
    def scale_value(self, value):
        '''
                   (out_max - out_min)(value - in_min)
            f(x) = -----------------------------------  + out_min
                            in_max - in_min

            where e.g.:  a = 0.0, b = 1.0, min = 0, max = 330.
        '''
        return (( self._out_max - self._out_min ) * ( value - self._in_min ) / ( self._in_max - self._in_min )) + self._out_min
#       return (( self._out_max - self._out_min ) * ( self.get_value() - self._in_min ) / ( self._in_max - self._in_min )) + self._out_min

#EOF


def cycle_crossover(parent1, parent2):
    ciclos = []
    cruce = []
    result = []

    for i in parent1:
        valor = parent2[parent1.index(i)]
        ciclo = []
        ciclo.append(i)
        if i != valor:
            ciclo.append(valor)
        while valor != i:
            valor = parent2[parent1.index(valor)]
            if valor != i:
                ciclo.append(valor)
        ciclos.append(ciclo)

    for i in parent1:
        for j in range(len(ciclos)):
            if i in ciclos[j]:
                cruce.append(j+1)
                break

    count = 0
    for element in cruce:
        if (element % 2 == 0):
            result.append(parent2[count])
        else:
            result.append(parent1[count])
        count += 1

    return resultc


import tkinter as tk
import psycopg2.extras

class PeopleForm(tk.Frame):

    result = []

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)

        self.parent = parent

        # Listbox
        self.listBox = tk.Listbox(self, selectmode=tk.SINGLE)
        self.listBox.bind('<<ListboxSelect>>', self.itemClicked)
        self.listBox.grid(row=1, column=0, columnspan=2, sticky=tk.W+tk.E+tk.N+tk.S)

        self.showAllUsers()

    def showAllUsers(self):
        cur = self.parent.db.cursor(cursor_factory=psycopg2.extras.DictCursor)
        cur.execute('SELECT * FROM "user"')

        self.result = cur.fetchall()

        cur.close()

        # Apagar lista de nomes
        self.listBox.delete(0, tk.END)

        for i, people in enumerate(self.result):
            self.listBox.insert(i, people['name'])

    def itemClicked(self, event):
        widget = event.widget
        self.parent.switchScreen(PeopleView(self.parent, self.result[self.listBox.curselection()[0]]))
        self.destroy()

class PeopleView(tk.Frame):

    def __init__(self, parent, people):
        tk.Frame.__init__(self, parent)

        self.parent = parent

        # Entry
        self.nameEntry = tk.Label(self, text=f'Nome: {people["name"]}')
        self.nameEntry.grid(row=0, column=0)

        self.nameEntry = tk.Label(self, text=f'Senha: {people["password"]}')
        self.nameEntry.grid(row=1, column=0)

        # Button
        self.backButton = tk.Button(self, text='Voltar', command = self.back)
        self.backButton.grid(row=2, column=0)

    def back(self):
        self.parent.switchScreen(PeopleForm(self.parent))
        self.destroy()


class MaxHeap():
    def __init__(self, arr = None):
        self.__heapList = []
        # heapify 将任意数组整理成堆的形状
        if arr:
            self.__heapList = arr
            i = self.__parent(len(self.__heapList) - 1)
            while i >= 0:
                self.__siftDown(i)
                i -= 1

    def getSize(self):
        return len(self.__heapList)

    def isEmpty(self):
        return self.__heapList.__len__() == 0

    # 返回完全二叉树的数组表示中，一个索引所表示的元素的父亲节点的索引
    def __parent(self, index):
        if index == 0:
            raise Exception("index-0 doesn't have parent")
        return (index - 1) // 2

    # 返回完全二叉树的数组表示中，一个索引所表示的元素的左孩子节点的索引
    def __leftchild(self, index):
        return index * 2 + 1

    # 返回完全二叉树的数组表示中，一个索引所表示的元素的右孩子节点的索引
    def __rightchild(self, index):
        return index * 2 + 2

    # 向堆中添加元素e，Sift up，上浮法
    # 1.先向堆尾部添加这个元素
    # 2.用添加后的元素(索引为堆的lenth-1)与其父亲节点比较，小则交换位置循环
    def add(self, e):
        self.__heapList.append(e)
        self.__siftUp(self.getSize() - 1)

    def __siftUp(self, index):
        while index > 0 and self.__heapList[index] > self.__heapList[self.__parent(index)]:
            # 交换位置
            self.__heapList[index], self.__heapList[self.__parent(index)] \
                = self.__heapList[self.__parent(index)],self.__heapList[index]
            index = self.__parent(index)

    # 查看堆中最大元素
    def findMax(self):
        if self.getSize() == 0:
            raise Exception("Cannot findMax when heap is empty")
        return self.__heapList[0]

    # 取出堆中最大元素
    # 移除的方法：Sift Down ，下沉法
    # 1.先将堆中最大的元素(即[0]位置元素) 与 堆末端元素(即[lenth-1]位置元素)交换位置
    # 2.删除[lenth-1]位置的元素
    # 3.将队首元素与左右子树中最大的元素比较，小于则互换，循环
    def extractMax(self):
        result = self.findMax()
        self.__heapList[0], self.__heapList[-1] = self.__heapList[-1], self.__heapList[0]
        self.__heapList.pop()
        self.__siftDown(0)

        return result

    def __siftDown(self, index):
        while self.__leftchild(index) < self.getSize():
            j = self.__leftchild(index)
            if j+1 < self.getSize() and self.__heapList[j+1] > self.__heapList[j]:
                j += 1
            # 现在的__heapList[j]是左右子树中的最大值
            if self.__heapList[j] <= self.__heapList[index]:
                break

            self.__heapList[index], self.__heapList[j] = self.__heapList[j], self.__heapList[index]
            index = j

    # replace操作 取出最大元素后放入一个新元素
    # 可以直接将堆顶元素替换以后sift down，一次O(logn)操作
    def replace(self, e):
        result = self.findMax()
        self.__heapList.insert(0, e)
        self.__siftDown(0)
        return result

if __name__ == '__main__':
    n = 1000000
    from time import time

    start_time1 = time()
    max_heap = MaxHeap()
    from random import randint
    for i in range(n):
        max_heap.add(randint(0, 1000))
    # for i in range(n):
    #     res = max_heap.extractMax()
    print('heap add: ', time() - start_time1) # heap add:  5.539180278778076

    # heapify的方式添加
    testList = []
    for i in range(n):
        testList.append(randint(0, 1000))
    start_time2 = time()
    max_heap2 = MaxHeap(testList)
    print('heapify add: ', time() - start_time2) # heapify add:  1.8540711402893066


"""
programa que rota los valores de 3 variables enteras x1, x2, x3 hacias la derecha de forma que al final x2 tenga el valor inicial de x1, x3 el de x2 y x1 el de x3.
program that rotates the values of 3 integer variables x1, x2, x3 to the right so that at the end x2 has the initial value of x1, x3 that of x2 and x1 that of x3.
@CatherineHerrera96

"""

x1 = int (input("enter the first number:"))
x2 = int (input("enter the second number:"))
x3 = int (input("enter the third number:"))

base = x1
x1 = x3
x3 = x2
x2 = base

print(x1)
print(x2)
print(x3)


import openai

from flask import Flask, render_template, request, jsonify
from datetime import datetime

app = Flask(__name__)

openai.api_key="OPENAI_API_KEY"

messages = {}

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/send_message/<room_id>", methods=["POST"])
def send_message(room_id):
    if room_id not in messages:
        messages[room_id] = []

    content = request.json
    name = content["name"]
    message = content["message"]
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    messages[room_id].append({"name": name, "message": message, "timestamp": timestamp})
    return jsonify({"status": "success"})

@app.route("/get_messages/<room_id>")
def get_messages(room_id):
    if room_id not in messages:
        messages[room_id] = []

    return jsonify(messages[room_id])

@app.route('/<path:path>')
def catch_all(path):
    return render_template("index.html")

@app.route("/gpt/<room_id>", methods=["POST"])
def gpt(room_id):
    prompt = request.json["prompt"]
    model = request.json["model"]
    max_tokens = request.json["max_tokens"]
    response = openai.ChatCompletion.create(
        model=model,
        messages=[
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "assistant", "content": "Provide examples"},
            {"role": "user", "content": prompt},
        ],
        temperature=0.8,
        max_tokens=max_tokens,
    )

    return jsonify({"response": response.choices[0].message.content})

@app.route("/send_gpt_response/<room_id>", methods=["POST"])
def send_gpt_response(room_id):
    if room_id not in messages:
        messages[room_id] = []

    content = request.json
    name = content["name"]
    message = content["message"]
    timestamp = content["timestamp"]
    messages[room_id].append({"name": name, "message": message, "timestamp": timestamp})
    return jsonify({"status": "success"})

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


## import
import maya.cmds as cmds
import maya.mel as mel
## import libs
import common.transforms as transforms
import namingAPI.naming as naming
import riggingAPI.joints as joints
import riggingAPI.constraints as constraints
import riggingAPI.controls as controls
import modelingAPI.curves as curves
import baseLimbRig
## function
class ikRPsolverRig(baseLimbRig.baseLimbRig):
	"""docstring for ikRPsolverRig"""
	def __init__(self, *args, **kwargs):
		super(ikRPsolverRig, self).__init__()

		if args:
			self._getRigInfo(args[0])
		else:
			sName = kwargs.get('sName', 'IkRPsolver')
			sSide = kwargs.get('sSide', 'm')
			sPart = kwargs.get('sPart', None)
			iIndex = kwargs.get('iIndex', None)
			lBpJnts = kwargs.get('lBpJnts', None)
			sBpCtrl = kwargs.get('sBpCtrl', None)
			sBpPv = kwargs.get('sBpPv', None)
			sBpRoot = kwargs.get('sBpRoot', None)
			bOrient = kwargs.get('bOrient', True)
			sConnectInCtrl = kwargs.get('sConnectInCtrl', 'controls')
			sConnectInJnt = kwargs.get('sConnectInJnt', 'rigJoints')
			bSub = kwargs.get('bSub', False)
			iStacks = kwargs.get('iStacks', 1)
			lLockHideAttrs = kwargs.get('lLockHideAttrs', ['sx', 'sy', 'sz', 'v'])

			self._sName = sName
			self._lBpJnts = lBpJnts
			self._sBpCtrl = sBpCtrl
			self._sBpPv = sBpPv
			self._sBpRoot = sBpRoot
			self._sSide = sSide
			self._sPart = sPart
			self._iIndex = iIndex
			self._bOrient = bOrient
			self._sConnectInCtrl = sConnectInCtrl
			self._sConnectInJnt = sConnectInJnt
			self._bSub = bSub
			self._iStacks = iStacks
			self._lLockHideAttrs = lLockHideAttrs

	@property
	def sIkHnd(self):
		return self._sIkHnd

	def create(self):
		sGrp = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sRig' %(self._sPart, self._sName), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = self._sConnectInJnt)
		sGrpCtrl = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sCtrl' %(self._sPart, self._sName), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = self._sConnectInCtrl)

		sParent_jnt = sGrp
		lJnts = []
		for i, sBpJnt in enumerate(self._lBpJnts):
			oJntName = naming.oName(sBpJnt)
			oJntName.sType = 'jnt'
			oJntName.sPart = '%s%s' %(oJntName.sPart, self._sName)
			sJnt = joints.createJntOnExistingNode(sBpJnt, sBpJnt, oJntName.sName, sParent = sParent_jnt)
			lJnts.append(sJnt)
			sParent_jnt = sJnt

		lCtrls = []
		for i, sBpJnt in enumerate([self._sBpRoot, self._sBpPv, self._sBpCtrl]):
			oJntName = naming.oName(sBpJnt)
			iRotateOrder = cmds.getAttr('%s.ro' %sBpJnt)
			if i == 2:
				lLockHideAttrs = self._lLockHideAttrs
			else:
				lLockHideAttrs = ['rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v']
			oCtrl = controls.create(oJntName.sPart, sSide = oJntName.sSide, iIndex = oJntName.iIndex, iStacks = self._iStacks, bSub = self._bSub, sParent = sGrpCtrl, sPos = sBpJnt, iRotateOrder = iRotateOrder, sShape = 'cube', fSize = 8, lLockHideAttrs = lLockHideAttrs)
			lCtrls.append(oCtrl.sName)

		## ik handle
		if self._bOrient:
			sJntEnd_rp = lJnts[-2]
			sIkHnd_sc = naming.oName(sType = 'ikHandle', sSide = self._sSide, sPart = '%sSCsolver' %self._sPart, iIndex = self._iIndex).sName
			cmds.ikHandle(sj = lJnts[-2], ee = lJnts[-1], sol = 'ikSCsolver', name = sIkHnd_sc)
		else:
			sJntEnd_rp = lJnts[-1]
			sIkHnd_sc = None
		sIkHnd_rp = naming.oName(sType = 'ikHandle', sSide = self._sSide, sPart = '%sRPsolver' %self._sPart, iIndex = self._iIndex).sName
		cmds.ikHandle(sj = lJnts[0], ee = sJntEnd_rp, sol = 'ikRPsolver', name = sIkHnd_rp)

		#### parent ik handle
		oCtrl = controls.oControl(lCtrls[2])
		sGrpIkHndle = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sRigIkHndle' %(self._sPart, self._sName), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = oCtrl.sOutput, bVis = False)
		cmds.parent(sIkHnd_rp, sGrpIkHndle)
		if sIkHnd_sc:
			cmds.parent(sIkHnd_sc, sGrpIkHndle)

		#### pole vector
		oCtrl = controls.oControl(lCtrls[1])
		cmds.poleVectorConstraint(oCtrl.sOutput, sIkHnd_rp)
		## pole vector line
		curves.createCurveLine(naming.oName(sType = 'curve', sSide = self._sSide, sPart = '%sPvLineIk' %self._sPart, iIndex = self._iIndex).sName, [lJnts[1], oCtrl.sOutput], sParent = sGrpCtrl)

		#### root control
		oCtrl = controls.oControl(lCtrls[0])
		cmds.pointConstraint(oCtrl.sOutput, lJnts[0], mo = False)

		#### control connect out node
		sConnectOutCtrl = transforms.createTransformNode(naming.oName(sType = 'grp', sSide = self._sSide, sPart = '%s%sRigConnectOutCtrl' %(self._sPart, self._sName), iIndex = self._iIndex).sName, lLockHideAttrs = ['tx', 'ty', 'tz', 'rx', 'ry', 'rz', 'sx', 'sy', 'sz', 'v'], sParent = oCtrl.sOutput, bVis = True)
		constraints.constraint([lJnts[-1], sConnectOutCtrl], sType = 'parent', bForce = True, bMaintainOffset = True)
		## write rig info
		sString_lJnts = self._convertListToString(lJnts)
		sString_lCtrls = self._convertListToString(lCtrls)
		lRigInfo = ['ikRPsolverRig', self._sConnectInJnt, self._sConnectInCtrl, lJnts[-1], sConnectOutCtrl, sString_lJnts, sString_lCtrls, sIkHnd_rp, sGrpCtrl, sGrp]
		lAttrs = ['sModuleType', 'sConnectInJnt', 'sConnectInCtrl', 'sConnectOutJnt', 'sConnectOutCtrl', 'lJnts', 'lCtrls', 'sIkHnd', 'sGrpCtrl', 'sModuleNode']
		self._writeRigInfo(sGrp, lRigInfo, lAttrs)

		self._getRigInfo(sGrp)

	def _getRigInfo(self, sModuleNode):
		super(ikRPsolverRig, self)._getRigInfo(sModuleNode)
		if cmds.attributeQuery('sIkHnd', node = sModuleNode, ex = True):
			self._sIkHnd = cmds.getAttr('%s.sIkHnd' %sModuleNode)


from typing import (
    Union,
)

from azul.openapi import (
    format_description_key,
    schema,
)
from azul.openapi.schema import (
    TYPE,
)
from azul.types import (
    JSON,
    PrimitiveJSON,
)

def path(name: str, type_: TYPE, **kwargs: PrimitiveJSON) -> JSON:
    """
    Returns an OpenAPI `parameters` specification of a URL path parameter.
    Note that path parameters cannot be optional.

    >>> from azul.doctests import assert_json
    >>> assert_json(path('foo', int))
    {
        "name": "foo",
        "in": "path",
        "required": true,
        "schema": {
            "type": "integer",
            "format": "int64"
        }
    }
    """
    return _make_param(name, in_='path', type_=type_, **kwargs)

def query(name: str,
          type_: Union[TYPE, schema.optional],
          **kwargs: PrimitiveJSON
          ) -> JSON:
    """
    Returns an OpenAPI `parameters` specification of a URL query parameter.

    >>> from azul.doctests import assert_json
    >>> assert_json(query('foo', schema.optional(int)))
    {
        "name": "foo",
        "in": "query",
        "required": false,
        "schema": {
            "type": "integer",
            "format": "int64"
        }
    }
    """
    return _make_param(name, in_='query', type_=type_, **kwargs)

def header(name: str,
           type_: Union[TYPE, schema.optional],
           **kwargs: PrimitiveJSON
           ) -> JSON:
    """
    Returns an OpenAPI `parameters` specification of a request header.

    >>> from azul.doctests import assert_json
    >>> assert_json(header('X-foo', schema.optional(int)))
    {
        "name": "X-foo",
        "in": "header",
        "required": false,
        "schema": {
            "type": "integer",
            "format": "int64"
        }
    }
    """
    return _make_param(name, in_='header', type_=type_, **kwargs)

def _make_param(name: str,
                in_: str,
                type_: Union[TYPE, schema.optional],
                **kwargs: PrimitiveJSON
                ) -> JSON:
    is_optional = isinstance(type_, schema.optional)
    if is_optional:
        type_ = type_.type_
    format_description_key(kwargs)
    schema_or_content = schema.make_type(type_)
    return {
        'name': name,
        'in': in_,
        'required': not is_optional,
        # https://swagger.io/docs/specification/describing-parameters/#schema-vs-content
        'content' if 'application/json' in schema_or_content else 'schema': schema_or_content,
        **kwargs
    }


#coding=utf-8

import time,sys,os,win32gui, win32ui, win32con,traceback,io,re
from PIL import Image
from PIL import ImageChops
from BI_SenseEngine.ShareScripts.data_yaml import datagetConfig
from BI_SenseEngine.ShareScripts.logger import Logger
from BI_SenseEngine.windows_test_case.WindowsUpperButtonAutoit_mouse import Autoit_Upper_machine_function
from BI_SenseEngine.ShareScripts.images_dispose import images_dispose

class Screenshots_operation(object):

    def __init__(self,resultname):
        '''
        创建文件并且截图
        '''
        self.getConfig = datagetConfig()
        path = "D:\\test\\test_result\\log_%s"%resultname + time.strftime('%m%d_%H%M%S') + '.txt'
        self.log = Logger(path, level='debug')
        self.upper_dis = Autoit_Upper_machine_function()
        self.img_dis = images_dispose()

    def create_file(self, fendsWith):
        gettime = time.strftime('%Y-%m-%d', time.gmtime())  # 获得当前时间的列表
        gettime = str(gettime + fendsWith)
        getpath = str(sys.path[0]) + self.getConfig.getConfig().get("screen_path") + gettime
        try:
            if (os.path.exists(gettime)):
                pass
                # print("文件已存在")
                # os.removedirs(getpath)#空目录删除成功
            else:
                os.mkdir(str(sys.path[0]) + self.getConfig.getConfig().get("screen_path") + gettime)
        except:
            print('文件创建失败,文件已经存在')
        # print(getpath)
        return getpath

    def window_capture(self,filename):
        """
                截取windows系统活动窗口
        """
        time.sleep(2)
        hwnd = win32gui.GetForegroundWindow()
        #         hwnd = 0 # 窗口的编号，0号表示当前活跃窗口
        # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
        hwndDC = win32gui.GetWindowDC(hwnd)
        # 根据窗口的DC获取mfcDC
        mfcDC = win32ui.CreateDCFromHandle(hwndDC)
        # mfcDC创建可兼容的DC
        saveDC = mfcDC.CreateCompatibleDC()
        # 创建bigmap准备保存图片
        saveBitMap = win32ui.CreateBitmap()
        l, t, r, b = win32gui.GetWindowRect(hwnd)
        w = r - l
        h = b - t
        saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
        # 高度saveDC，将截图保存到saveBitmap中
        saveDC.SelectObject(saveBitMap)
        # 截取从左上角（0，0）长宽为（w，h）的图片
        saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
        saveBitMap.SaveBitmapFile(saveDC, filename)
        time.sleep(1)

    def compare_images(self, path_one, path_two, box=None):
        """
                比较图片是否一样
        @path_one: 第一张图片的路径
        @path_two: 第二张图片的路径

        """
        #box = self.getConfig.getConfig().get("pic_comared_coordinate")
        box = (12, 8, 360, 400)
        image_one = Image.open(path_one).crop(box)
        image_two = Image.open(path_two).crop(box)
        try:
            diff = ImageChops.difference(image_one, image_two)
            if diff.getbbox() is None:
                self.log.logger.debug("Two pictures are the same.")
                return True
            else:
                self.log.logger.debug("Two pictures are the different.")
                return False
        except:
            traceback.print_exc()
            Logger('error.log', level='error').logger.error("-----compare_images Error-----")
            return False

    def screnn_vension(self,filename):#获取当前版本并判断输出版本号
        self.upper_dis.click_Config()
        self.upper_dis.click_GetVersion()
        self.window_capture(filename)
        #sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf8')
        vension_string = self.img_dis.get_img_text(str(filename))
        strings = "software version"
        flag = True
        try:
            vensions = re.findall(r"software version=(.+?)\n",vension_string)
            vension = vensions[0]
            if strings in vension_string:
                self.upper_dis.click_close_version()
                self.log.logger.debug("----------当前版本：%s--------"%vension)
                flag = True
        except:
            self.upper_dis.click_ok()
            self.log.logger.debug("----------当前没有获取到版本--fail-%s----------"%vension_string)
            flag = False
        return flag

    def screen_upload(self,upgradefile,filename):
        self.upper_dis.version_upgrade(upgradefile)
        self.window_capture(filename)
        self.upper_dis.close_upgrade()

if __name__ == '__main__':
    time.sleep(3)
    version_number = '2.10'

    ScreenFile = Screenshots_operation("log_BattchAddition测试结果.txt")
    # version_img = ScreenFile.create_file("版本查询截图文件") + "\\"  # 创建图片存在的文件夹
    # ScreenFile.window_capture(version_img + 'version.jpg')
    # version_img_path = str(version_img+ 'version.jpg')
    ScreenFile.screnn_vension("1.png")


import sys
from setuptools import setup, Extension

extension = Extension("extension", sources=["extension.c"])

if sys.platform != "win32":
    # Dynamicly create this file because it has a
    # name that is invalid on Windows
    with open('package/my"data.txt', "w") as fp:
        fp.write("This is on odd data file")

setup(
    name="simple-package",
    version="1.0",
    description="This is a demo package",
    include_package_data=True,
    packages=["package"],
    py_modules=["toplevel"],
    ext_modules=[extension],
)


# Exo 1:
def correspond(mot: str, mot_a_trous: str) -> bool:
    n1 = len(mot)
    n2 = len(mot_a_trous)
    if n1 != n2: return False
    for i in range(n1):
        if mot_a_trous[i] == '*':
            continue
        elif mot_a_trous[i] != mot[i]:
            return False
    return True

assert correspond('INFORMATIQUE', 'INFO*MA*IQUE') == True
assert correspond('AUTOMATIQUE', 'INFO*MA*IQUE') == False
assert correspond('STOP', 'S*') == False
assert correspond('AUTO', '*UT*') == True

# Exo 2:
def est_cyclique(plan):
    '''
    Prend en paramètre un dictionnaire `plan` correspondant à un
    plan d'envoi de messages (ici entre les personnes A, B, C, D,
    E, F).
    Renvoie True si le plan d'envoi de messages est cyclique et
    False sinon.
    '''
    expediteur = 'A'
    destinataire = plan[expediteur]
    nb_destinaires = 1
    while destinataire != expediteur:
        destinataire = plan[destinataire]
        nb_destinaires += 1
    return nb_destinaires == len(plan)

assert est_cyclique({'A':'E', 'F':'A', 'C':'D', 'E':'B', 'B':'F', 'D':'C'}) == False
assert est_cyclique({'A':'E', 'F':'C', 'C':'D', 'E':'B', 'B':'F','D':'A'}) == True
assert est_cyclique({'A':'B', 'F':'C', 'C':'D', 'E':'A', 'B':'F', 'D':'E'}) == True
assert est_cyclique({'A':'B', 'F':'A', 'C':'D', 'E':'C', 'B':'F', 'D':'E'}) == False


# -*- coding: utf-8 -*-
from Products.NaayaCore.SchemaTool.widgets.GlossaryWidget import (
        GlossaryWidget)

from Products.Naaya.tests.NaayaTestCase import NaayaTestCase

class GlossaryWidgetTestCase(NaayaTestCase):
    def afterSetUp(self):
        widget = GlossaryWidget('glossary-property', title='Glossary',
                lang='en')
        widget.default = "Default value"
        self.widget = widget.__of__(self.portal.portal_schemas.NyDocument)

    def test_render_html(self):
        html = self.widget.render_html('glossary')
        self.assertTrue('value="glossary"' in html)

    def test_default_value(self):
        """ """
        html = self.widget.render_html('')
        self.assertTrue('value="%s"' % self.widget.default in html)

    def test_translate_default_value(self):
        """If there are multiple languages translate the default value into
        different langs."""
        #This should put the message in the translation catalog
        html = self.widget.render_html(self.widget.default)
        self.assertTrue('value="%s"' % self.widget.default in html)
        #Add a site language
        portal_i18n = self.portal.getPortalI18n()
        portal_i18n.add_language('fr')

        translated_message = u"La valeur par défaut"
        #Translate the default value
        translation_tool = portal_i18n.get_message_catalog()
        translation_tool.edit_message(self.widget.default, 'fr',
                translated_message)

        #render and check if the default value has been translated.
        self.portal.gl_change_site_defaultlang('fr')
        html = self.widget.render_html('')
        self.assertTrue(u'value="%s"' % translated_message in html)


from tests import pydal_def as mydal
from _anvil_designer.set_up_user import new_user_in_db
import anvil.users
from tests.test_app_table import insert_get_contact_row_ref

def user_login():
    mydal.define_tables_of_db()
    user_ref = new_user_in_db()
    anvil.users.force_login(user_ref)
    user = anvil.users.get_user()
    assert user
    yield user
    anvil.users.logout()

from client_code.HomeForm import HomeForm
class TestHomeForm:
    def test_init(self):
        for user in user_login():
            contact_row, contact_ref = insert_get_contact_row_ref(user)
            home_form=HomeForm()
            home_form.contact_form.repeating_panel_2.raise_event("x-contact_name", uid=contact_ref)

    def test_login_with_form(self):
        mydal.define_tables_of_db()
        home_form = HomeForm()
        home_form.link_login_click()
        user = anvil.users.get_user()
        assert user
        anvil.users.logout(user)
        user = anvil.users.get_user()
        assert user is None


# -*- coding:UTF-8 -*-
services = {}  # (key:ip, value:서비스용량)이 저장될 딕셔너리 자료구조

with open('dev_access_log.20150611', 'r') as f:
    logs = f.readlines()
    for log in logs:
        log = log.split()
        ip = log[0]
        servicebyte = log[9]

        if servicebyte.isdigit():
            servicebyte = int(servicebyte)
        else:  # 제공한 콘텐츠의 크기가 0일 경우 '-'다음과 같은 문자로 정해지기에...
            servicebyte = 0

        if ip not in services:
            services[ip] = servicebyte
        else:
            services[ip] += servicebyte

ret = sorted(services.items(), key=lambda x: x[1], reverse=True)  # 서비스 용량을 기준으로 내림차순 정리

print('=' * 8 , '사용자IP - 서비스 용량' , '=' * 8)

for ip, b in ret:
    print('[IP ADDRESS: %s] - [%d byte]' % (ip, b))


############  K-Nearest Neighbor(K-최근접 이웃)
# • Classification Algorithm
# • 근접한 K 개의 data 의 class 별 비율을 기준으로 새로운 data 의 class 를 결정하는 Algorithm

# digits.png 파일 학습 방법
# • 하나의 숫자는 20x20 크기로 되어있음
# • 20x20 크기의 숫자가 총 5000개 있음
# • 20x20 영상으로 나누어서 1x400 형태로 변환
# • 총 5000개의 숫자를 1x400 형태로 변환하여 5000x400 형태 이미지 생성

'''
cv.ml_KNearest.findNearest(samples, k, results=None, neighborResponses=None, dist=None , flags=None)
-> retval, results, neighborResponses, dist
'''
# • sample : 입력 영상(data 별로 행 벡터로 저장됨) , np.ndarray, np.float32
# • k : 최근접 이웃 갯수
# • results : 각각의 입력 샘플에 대한 예측 결과
# • np.ndarray. shape=(N, 1), np.float32
# • neighborResponses : 예측에 사용된 k개의 최근접 이웃 클래스 정보 행렬.
# • shape=(N, k), np.float32.
# • dist: 입력벡터와 예측에 사용된 k개의 최근접 이웃과의 거리를 저장한 행렬
# • np.ndarray. shape=(N, k), np.float32
# • retval : 입력벡터가 하나인 경우 결과

'''
### knn 예제 ###
import numpy as np
import matplotlib.pyplot as plt
import cv2

np.random.seed(0)

### 데이터 만들기
data = np.random.randint(0, 100, (25,2)).astype(np.float32)
#print(data)

response = np.random.randint(0,2,(25,1)).astype(np.float32)
#print(response)
#print(response.ravel())  # ravel -> 가로 array로 합치기

#for i in range(25):
#    print(response[i], data[i])

red = data[response.ravel() == 0]
blue = data[response.ravel() == 1]

plt.scatter(red[:,0], red[:,1], 80, 'r', '^')
plt.scatter(blue[:,0], blue[:,1], 80, 'b', 's')
#plt.show()

knn = cv2.ml.KNearest_create()
knn.train(data, cv2.ml.ROW_SAMPLE, response)

newdata = np.random.randint(0, 100, (1,2)).astype(np.float32)
plt.scatter(newdata[:,0], newdata[:,1], 80, 'g', 'o')

ret, results, neighbors, distance = knn.findNearest(newdata, 5)

print('result :', results)
print('neighbors :', neighbors)
print('distance :', distance)

plt.show()
'''

##  digits.png 학습
import numpy as np
import cv2

x0, y0 = -1, -1

def mouse_fn(event, x, y, flags, param):
    global x0, y0

    if event == cv2.EVENT_LBUTTONDOWN:
        x0, y0 = x, y

    elif event == cv2.EVENT_LBUTTONUP:
        x0, y0 = -1, -1

    elif event == cv2.EVENT_MOUSEMOVE:
        if flags & cv2.EVENT_FLAG_LBUTTON:
            cv2.line(img, (x0,y0), (x,y), (255,255,255), 40, cv2.LINE_AA)
            x0, y0 = x, y
            cv2.imshow('img', img)

digits = cv2.imread('./images/ml/digits.png', cv2.IMREAD_GRAYSCALE)

h, w = digits.shape[:2]
#print(h,w)

# cells의 shape = (50, 100, 20, 20)
cells = [np.hsplit(row, w/20) for row in np.vsplit(digits, h//20)]

cells = np.array(cells)

train_images = cells.reshape(-1, 400).astype(np.float32)
train_labels = np.repeat(np.arange(10), len(train_images) / 10)

knn = cv2.ml.KNearest_create()
knn.train(train_images, cv2.ml.ROW_SAMPLE, train_labels)

img = np.zeros((400,400), np.uint8)

cv2.imshow('img', img)
cv2.setMouseCallback('img',mouse_fn)

while True:
    key = cv2.waitKey()

    if key == 27:
        break

    elif key == ord(' '):
        test_image = cv2.resize(img, (20,20), cv2.INTER_AREA)
        test_image = test_image.reshape(-1, 400).astype(np.float32)

        ret, _, _, _ = knn.findNearest(test_image, 5)
        print(int(ret))

        img.fill(0)
        cv2.imshow('img', img)


import itertools

# Your list
data = [[5], [1], [0], [8], [1], [8], [0], [3], [2, 3, 4], [3, 4, 5, 6], [2, 3, 4], [6], [3], [6], [4], [0]]

# Flatten the list
flattened_data = [str(item) for sublist in data for item in sublist]

# Generate all possible combinations of 16 characters
combinations = itertools.combinations(flattened_data, 16)

# Convert each combination to a string
keys = [''.join(combination) for combination in combinations]

# Print the keys
for key in keys:
    print(key)