import re
import json
import telebot
import bot_functions as btf

# Bot token
bot = telebot.TeleBot('5115979492:AAE1d6aCMRU3mIGIdegKelqdk9Ckz_eK8U8')

# groups = [-875440784, -827511175, -730167135]#, -635448596]

keyboard1 = telebot.types.ReplyKeyboardMarkup(True)

@bot.message_handler(commands=['start'])
def start_message(message):
    bot.send_message(message.chat.id, " ❓ Send me a word/phrase to get it's meaning \n\n /help to display options \n\n All definitions provided by Urban Dictionary", parse_mode="HTML", disable_web_page_preview=True)
    check = message.chat.id

    # if check not in groups:
    #     groups.append(check)

@bot.message_handler(commands=['id'])
def get_chatid(message):
    bot.send_message(message.chat.id, message.chat.id)

@bot.message_handler(content_types=['text'])
def send_text(message):
    if message.text == "/random":
        rand_word = btf.random_word()
        bot.send_message(message.chat.id, f" ⭐ Your random word/phrase is - {rand_word.word}", parse_mode="HTML")
        bot.send_message(message.chat.id, "🔎 Definition: \n" + re.sub(r"[\[\]]", "", rand_word.definition))
        # for x in rand_word:
        #     bot.send_message(message.chat.id, x)
    elif message.text == "/help":
        bot.send_message(message.chat.id, " ℹ List of commands: \n /help - exactly what got you here \n /random - fetch a definition for a random word/phrase", parse_mode="HTML")
    else:
        definition = btf.define(message.text)
        for x, i in zip(definition, range(len(definition))):
            x = re.sub(r"[\[\]]", "", x)
            bot.send_message(message.chat.id, f" 🔎 Definition {i+1}: \n{x}", parse_mode="HTML")

bot.polling()

# with open('json_data.json', 'w') as outfile:
#     outfile.write(json_string)


# Importing used libraries
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib as mpl
from main import dataFrequency, gatherTime

# Declaring global variables
global df

# Initializing style elements
mpl.style.use('bmh')

def importPlotData(path: str) -> pd.DataFrame:
    """
    Imports all data from the experiment (provided for by main.py)
    """
    return pd.read_csv(path)

def plot(df: pd.DataFrame, param: str, window_width: int = 20) -> bool:
    """
    Plots a certain parameter against time, needs the dataframe as well as the column title.
    """

    gdf = df.tail(window_width)

    tempplot = gdf.plot(x='Time', y=param)
    tempplot.set_ylabel(param)
    tempplot.set_xlabel('Time')
    tempplot.legend(loc="upper left")

    plt.xticks(rotation=90)

    return 0

def main():
    """
    Main function that contains all code to be run when the script is ran as a script, not imported as a module.
    """
    path = "./output.csv"
    df = importPlotData(path)

    labels = df[0]

    print(labels)

    iterations = dataFrequency * gatherTime

    plot(df, 'MF_CORI', iterations)
    plot(df, 'RHO_CORI', iterations)
    plot(df, 'T_CORI', iterations)
    plot(df, 'DP', iterations)

    plt.show()

    return 0

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Sat Jun 15 12:39:28 2019

@author: garci
"""
import csv
import numpy as np
import matplotlib.pyplot as plt

'''.csv files in data folder'''
filename1,label1='example1.csv','Example 1'
filename2,label2='example2.csv','Example 2'

def conv( filename = 'name' ):

    '''if the csv file is in a subfolder to this script's, specify path'''
    fname_path='data/'

    with open(fname_path+filename, 'r') as f:
        X = list(csv.reader(f, delimiter=","))
    Xc=np.array(X[1:], dtype=np.float)

    x=Xc[:,0]
    y=Xc[:,1]

#    return Xc
    return x,y

'Read & Plot'
x,y = conv(filename1)
plt.plot(x,y,'k',label = label1)

x,y = conv(filename2)
plt.plot(x,y,label = label2)
plt.legend()


from collections import defaultdict
import argparse
import json
import os
import sys

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--stamp', metavar='FILE', help='Touch FILE at the end.', required=True)
    parser.add_argument(
        '--depfile',
        metavar='FILE',
        help='Write a GN depfile to the given path',
        required=True)
    parser.add_argument(
        '--merged',
        metavar='FILE',
        help='Write a snapshot of this sysmgr config to the given path',
        required=True)
    parser.add_argument('manifest', help='config-data package manifest')
    args = parser.parse_args()

    with open(args.manifest, 'r') as f:
        lines = f.read().splitlines()

    # Build a list of all the source paths that contribute to sysmgr's config-data
    sysmgr_lines = [
        line for line in lines if line.startswith('meta/data/sysmgr/')
    ]
    sysmgr_config_files = [line.split('=')[1] for line in sysmgr_lines]

    # Parse all config files.
    #
    # Build a list of all conflicts, rather than
    # failing immediately on the first conflict. This allows us to print a more
    # useful build failure so that developers don't need to play whack-a-mole with
    # multiple conflicts.
    configs = []
    files_by_service = defaultdict(list)
    for config_file in sysmgr_config_files:
        with open(config_file, 'r') as f:
            config = json.load(f)
            configs.append(config)

            services = config.get('services')
            if services:
                for service in services.keys():
                    files_by_service[service].append(config_file)

    # If any conflicts were detected, print a useful error message and then
    # exit.
    service_conflicts = False
    for service, config_files in files_by_service.items():
        if len(config_files) > 1:
            print(
                'Duplicate sysmgr configuration for service {} in files: {}'.
                format(service, ', '.join(config_files)))
            service_conflicts = True

    if service_conflicts:
        return 1

    # Create a single merged configuration analogous to sysmgr's init itself.
    merged_config = {}
    for config in configs:
        for category, values in config.items():
            existing = merged_config.get(category)
            if type(existing) is dict:
                merged_config[category].update(values)
            elif type(existing) is list:
                merged_config[category] += values
            else:
                merged_config[category] = values

    with open(args.merged, 'w') as f:
        json.dump(
            merged_config, f, indent=2, separators=(',', ': '), sort_keys=True)

    # Write the depfile, which is a Makefile format file that has a single output
    # (the stamp file) and lists all input files as dependencies.
    with open(args.depfile, 'w') as f:
        f.write('{}: {}\n'.format(args.stamp, ' '.join(sysmgr_config_files)))

    # Write the stampfile.
    with open(args.stamp, 'w') as f:
        os.utime(f.name, None)

    return 0

if __name__ == '__main__':
    sys.exit(main())


from typing import List, Optional, Dict

from transformers import DPRReader, DPRReaderTokenizer

from pygaggle.qa.base import Reader, Answer, Question, Context
from pygaggle.qa.span_selection import DprSelection

class DprReader(Reader):
    """Class containing the DPR Reader
    Takes in a question and a list of the top passages selected by the retrieval model,
    and predicts a list of the best answer spans from the most relevant passages.

    Parameters
    ----------
    model_name : DPR Reader model name or path
    tokenizer_name : DPR Reader tokenizer name or path
    num_spans : Number of answer spans to return
    max_answer_length : Maximum length that an answer span can be
    num_spans_per_passage : Maximum number of answer spans to return per passage
    """

    def __init__(
            self,
            model_name: str,
            tokenizer_name: str = None,
            span_selection_rules=None,
            num_spans: int = 1,
            max_answer_length: int = 10,
            num_spans_per_passage: int = 10,
            batch_size: int = 16,
            device: str = 'cuda:0'
    ):
        if span_selection_rules is None:
            span_selection_rules = [DprSelection()]
        self.device = device
        self.model = DPRReader.from_pretrained(model_name).to(self.device).eval()
        if tokenizer_name:
            self.tokenizer = DPRReaderTokenizer.from_pretrained(tokenizer_name)
        else:
            self.tokenizer = DPRReaderTokenizer.from_pretrained(model_name)
        self.span_selection_rules = span_selection_rules
        self.num_spans = num_spans
        self.max_answer_length = max_answer_length
        self.num_spans_per_passage = num_spans_per_passage
        self.batch_size = batch_size

    def compute_spans(
            self,
            question: Question,
            contexts: List[Context],
    ):
        spans_for_contexts = []

        for i in range(0, len(contexts), self.batch_size):
            encoded_inputs = self.tokenizer(
                questions=question.text,
                titles=list(map(lambda t: t.title, contexts[i: i + self.batch_size])),
                texts=list(map(lambda t: t.text, contexts[i: i + self.batch_size])),
                return_tensors='pt',
                padding=True,
                truncation=True,
                max_length=350,
            )
            input_ids = encoded_inputs['input_ids'].to(self.device)
            attention_mask = encoded_inputs['attention_mask'].to(self.device)
            outputs = self.model(
                input_ids=input_ids,
                attention_mask=attention_mask,
            )
            outputs.start_logits = outputs.start_logits.cpu().detach().numpy()
            outputs.end_logits = outputs.end_logits.cpu().detach().numpy()
            outputs.relevance_logits = outputs.relevance_logits.cpu().detach().numpy()

            predicted_spans = self.tokenizer.decode_best_spans(
                encoded_inputs,
                outputs,
                self.batch_size * self.num_spans_per_passage,
                self.max_answer_length,
                self.num_spans_per_passage,
            )

            # collect spans for each context
            batch_spans_by_contexts = [[] for _ in range(len(outputs.relevance_logits))]
            for span in predicted_spans:
                batch_spans_by_contexts[span.doc_id].append(span)

            # sort spans by span score
            for k in range(len(outputs.relevance_logits)):
                spans_for_contexts.append(
                    sorted(batch_spans_by_contexts[k], reverse=True, key=lambda span: span.span_score)
                )

        return spans_for_contexts

    def predict(
            self,
            question: Question,
            contexts: List[Context],
            topk_retrievals: Optional[List[int]] = None,
    ) -> Dict[int, List[Answer]]:
        if isinstance(question, str):
            question = Question(question)
        if topk_retrievals is None:
            topk_retrievals = [len(contexts)]

        answers = {str(rule): {} for rule in self.span_selection_rules}
        prev_topk_retrieval = 0
        for rule in self.span_selection_rules:
            rule.reset()

        spans = self.compute_spans(question, contexts)

        for topk_retrieval in topk_retrievals:
            for rule in self.span_selection_rules:
                rule.add_answers(
                    spans[prev_topk_retrieval: topk_retrieval],
                    contexts[prev_topk_retrieval: topk_retrieval]
                )
                answers[str(rule)][topk_retrieval] = rule.top_answers(self.num_spans)

            prev_topk_retrieval = topk_retrieval

        return answers


##

from PySide import QtCore
from PySide import QtGui

##

scene = QtGui.QGraphicsScene()

view = QtGui.QGraphicsView(scene)

view.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)

##

view.show()

##

scene.addText("Hello, world!")

##

scene.setBackgroundBrush(QtCore.Qt.cyan)

##

scene.addEllipse(50, 0, 50, 50)

##

ellipse, text = scene.items()

ellipse.setPos(0, 0)

text.setPos(0, 0)

##

scene.views()[0] is view

scene.itemsBoundingRect()

brush = QtGui.QBrush(QtCore.Qt.lightGray, QtCore.Qt.CrossPattern)

scene.setForegroundBrush(brush)

view.rotate(-45)


#----------------------------------------------
# -*- encoding=utf-8 -*-                      #
# __author__:'焉知飞鱼'                        #
# CreateTime:                                 #
#       2020/4/29 16:48                       #
#                                             #
#               天下风云出我辈，                 #
#               一入江湖岁月催。                 #
#               皇图霸业谈笑中，                 #
#               不胜人生一场醉。                 #
#----------------------------------------------
import numpy as np
import time

data = np.random.randint(0,100,20)
# data = [1,2,4,6,6,5,8]
print(data)

def quick_sort(data,l,r):
    if l<r:
        i = l
        j = r
        x = data[i]
        while i<j:
            while(i<j and data[j]>x):#从右边开始找出一个比x小的数
                j-=1
            if i<j:
                data[i] = data[j]
                i+=1
            while(i<j and data[i]<x):
                i+=1
            if i<j:
                data[j]=data[i]
                j-=1

        data[i] = x
        quick_sort(data,l,i-1)
        quick_sort(data,i+1,r)

quick_sort(data,0,len(data)-1)
print(data)
print(type(data))

def quick_sort2(seq):
    if len(seq) <2:
        return seq

    else:
        base = seq[0]
        left = [elem for elem in seq[1:] if elem <=base]
        right = [elem for elem in seq[1:] if elem >base]
        return quick_sort2(left) + [base]  + quick_sort2(right)

data = quick_sort2(data)
print(data)
print(len(data))
print(type(data))


import os, cv2, math
from settings import DATABASES_DIR, BSD300_DIR, PROJECTIONS_DIR
import numpy as np
from typing import Dict, Tuple

from denoising.datasets import load_bsd300
from denoising.datasets import load_dataset
from denoising.datasets import extract_patches
from denoising.datasets import add_noise

DEFAULT_DIMENSION = (50,50)

class DataLoader:
    def __init__(self, config: Dict[str, str], check = False):
        self.config = config
        self.is_testing = check

        if isinstance(config['dataset'], str):
            self.x_train, self.y_train, self.x_test, self.y_test = self.get_dataset(config['dataset'])
        elif isinstance(config['dataset'], dict):
            train_dataset = config['dataset']['train']
            test_dataset = config['dataset']['test']
            self.x_train, self.y_train, _, _ = self.get_dataset(train_dataset)
            _, _, self.x_test, self.y_test = self.get_dataset(test_dataset)

        self.set_noise_statistics()

    def get_train(self):
        return (self.x_train, self.y_train)

    def get_test(self):
        return (self.x_test, self.y_test)

    def get(self):
        return self.x_train, self.y_train, self.x_test, self.y_test

    def get_dataset(self, dataset_name: str):
        (train_size, test_size) = self.get_size()

        if dataset_name.lower() == 'bsd300':
            y_train, y_test = self.load_bsd300()
            x_train, x_test = self.add_noise(y_train, y_test)

        elif dataset_name.lower() == 'dbt':
            x_train, y_train, x_test, y_test = self.load_dbt()
        elif dataset_name.lower() == 'spie_2021':
            x_train, y_train, x_test, y_test = self.load_spie_2021()
        elif dataset_name.lower() == '25x25':
            x_train, y_train, x_test, y_test = self.load_25x25()
        else:
          x_train, y_train, x_test, y_test = self.load_from_numpy(dataset_name)

        if self.should_normalize():
            x_train = cv2.normalize(x_train, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
            y_train = cv2.normalize(y_train, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
            x_test = cv2.normalize(x_test, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
            y_test = cv2.normalize(y_test, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)

        if self.should_shuffle():
            np.random.seed(13)
            np.random.shuffle(x_train)
            np.random.seed(13)
            np.random.shuffle(y_train)
            np.random.seed(43)
            np.random.shuffle(x_test)
            np.random.seed(43)
            np.random.shuffle(y_test)

        if self.should_divide_by_255():
            x_train = x_train.astype('float32') / 255.0
            y_train = y_train.astype('float32') / 255.0
            x_test = x_test.astype('float32') / 255.0
            y_test = y_test.astype('float32') / 255.0

        if self.is_testing:
            return (x_train[:10], y_train[:10], x_test[:10], y_test[:10])

        if train_size and test_size:
            return (x_train[:train_size], y_train[:train_size], \
                x_test[:test_size], y_test[:test_size])

        return (x_train, y_train, x_test, y_test)

    def set_noise_statistics(self):
        noise = self.config.get('noise', None)

        if not noise or (isinstance(noise, str) and noise == 'poisson'):
            noise = self.y_test - self.x_test
            self.mean = float(noise.mean())
            self.variance = float(np.var(noise))
            self.std = float(noise.std())

        if isinstance(noise, dict):
            assert 'type' in noise, "noise should have 'type' attribute. Options are: gaussian and poisson-gaussian."
            noise_type = noise['type']

            assert 'mean' in noise, "noise should have 'mean' attribute."
            assert 'variance' in noise, "noise should have 'variance' attribute."

            self.mean = float(noise['mean'])
            self.variance = float(noise['variance'])
            self.std = math.sqrt(self.variance)

    def get_noise_mean(self) -> float:
        return self.mean

    def get_noise_variance(self) -> float:
        return self.variance

    def get_noise_std(self) -> float:
        return self.std

    def load_bsd300(self) -> Tuple[np.ndarray, np.ndarray]:
        imgs = load_bsd300(BSD300_DIR)
        patch_dimension = self.get_patch_dimension()
        patches = extract_patches(imgs, begin=(0,0), stride=10,
            dimension=patch_dimension, quantity_per_image=(10,10))

        if self.should_shuffle():
            np.random.seed(10)
            np.random.shuffle(patches)

        y_train, y_test = load_dataset(patches, shuffle=False, split=(80,20))

        return y_train, y_test

    def load_dbt(self) -> Tuple[np.ndarray, np.ndarray]:
        noisy_projections = np.load(os.path.join(PROJECTIONS_DIR, 'noisy_10.npy'))
        noisy_projections = noisy_projections.reshape((-1, 1792, 2048, 1))

        if self.should_shuffle():
            np.random.seed(10)
            np.random.shuffle(noisy_projections)

        patch_dimension = self.get_patch_dimension()

        noisy_patches = extract_patches(noisy_projections, begin=(0,500), stride=10,
            dimension=patch_dimension, quantity_per_image=(10,10))

        x_train, x_test = load_dataset(noisy_patches, shuffle=False, split=(80,20))

        original_projections = np.load(os.path.join(PROJECTIONS_DIR, 'original_10.npy'))
        original_projections = original_projections.reshape((-1, 1792, 2048, 1))

        if self.should_shuffle():
            np.random.seed(10)
            np.random.shuffle(original_projections)

        original_patches = extract_patches(original_projections, begin=(0,500), stride=10,
            dimension=patch_dimension, quantity_per_image=(10,10))

        y_train, y_test = load_dataset(original_patches, shuffle=False, split=(80,20))

        return x_train, y_train, x_test, y_test

    def load_from_numpy(self, dataset_name: str):
      data_path = os.path.join(DATABASES_DIR, dataset_name)
      noisy_patches = np.load(os.path.join(data_path, 'noisy_patches.npy'))
      gt_patches = np.load(os.path.join(data_path, 'ground_truth_patches.npy'))

      noisy_patches = np.reshape(noisy_patches, (-1, noisy_patches.shape[1], noisy_patches.shape[2], 1))
      gt_patches = np.reshape(gt_patches, (-1, gt_patches.shape[1], gt_patches.shape[2], 1))

      if self.should_shuffle():
          np.random.seed(10)
          np.random.shuffle(noisy_patches)

          np.random.seed(10)
          np.random.shuffle(gt_patches)

      x_train, x_test = load_dataset(noisy_patches, shuffle=False, split=(80,20))
      y_train, y_test = load_dataset(gt_patches, shuffle=False, split=(80,20))

      return x_train, y_train, x_test, y_test

    def add_noise(self, y_train, y_test) -> Tuple[np.ndarray, np.ndarray]:
        noise = self.config.get('noise', None)

        if not noise:
            raise AssertionError("Config should have a noise type declared.")

        if isinstance(noise, str) and noise == 'poisson':
            x_train = add_noise(y_train, noise='poisson')
            x_test = add_noise(y_test, noise='poisson')
        if isinstance(noise, dict):
            assert 'type' in noise, "noise should have 'type' attribute. Options are: gaussian and poisson-gaussian."
            noise_type = noise['type']
            assert 'mean' in noise, "noise should have 'mean' attribute."
            assert 'variance' in noise, "noise should have 'variance' attribute."

            mean = float(noise['mean'])
            variance = float(noise['variance'])

            if noise_type == 'gaussian':
                x_train = add_noise(y_train, noise='gaussian', mean=mean, var=variance)
                x_test = add_noise(y_test, noise='gaussian', mean=mean, var=variance)
            elif noise_type == 'poisson-gaussian':
                x_train = add_noise(y_train, noise='poisson')
                x_test = add_noise(y_test, noise='poisson')

                x_train = add_noise(y_train, noise='gaussian', mean=mean, var=variance)
                x_test = add_noise(y_test, noise='gaussian', mean=mean, var=variance)

        return x_train, x_test

    def load_spie_2021(self):
        from denoising.datasets.spie_2021 import carrega_dataset, adiciona_a_dimensao_das_cores

        full_x_train, full_y_train, full_x_test, full_y_test = carrega_dataset(
          '/content/gdrive/My Drive/Colab Notebooks/dataset/patch-50x50-cada-projecao-200',
          divisao=(80,20), embaralhar=True)

        x_train =  np.reshape(full_x_train, (-1, 50, 50))
        x_test = np.reshape(full_x_test, (-1, 50, 50))
        y_train = np.reshape(full_y_train, (-1, 50, 50))
        y_test = np.reshape(full_y_test, (-1, 50, 50))

        del full_x_train
        del full_y_train
        del full_x_test
        del full_y_test

        x_train = x_train[:15000]
        y_train = y_train[:15000]

        x_test = x_test[:3750]
        y_test = y_test[:3750]

        np.random.seed(13)
        np.random.shuffle(x_train)

        np.random.seed(13)
        np.random.shuffle(y_train)

        np.random.seed(43)
        np.random.shuffle(x_test)

        np.random.seed(43)
        np.random.shuffle(y_test)

        x_train = cv2.normalize(x_train, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
        y_train = cv2.normalize(y_train, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
        x_test = cv2.normalize(x_test, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)
        y_test = cv2.normalize(y_test, None, alpha= 0, beta = 1, norm_type = cv2.NORM_MINMAX, dtype = cv2.CV_32F)

        x_train = adiciona_a_dimensao_das_cores(x_train)
        y_train = adiciona_a_dimensao_das_cores(y_train)
        x_test = adiciona_a_dimensao_das_cores(x_test)
        y_test = adiciona_a_dimensao_das_cores(y_test)

    def load_25x25(self):
        TRIAL_DIRECTORY = "/content/gdrive/My Drive/Colab Notebooks/dataset/Phantoms/Alvarado/"
        path = os.path.join(TRIAL_DIRECTORY, "numpy", "25x25")

        x_train = np.load(os.path.join(path, 'x_train.npy'))
        y_train = np.load(os.path.join(path, 'y_train.npy'))
        x_test = x_train
        y_test = y_train

        return x_train, y_train, x_test, y_test

    def get_patch_dimension(self) -> Tuple[int,int]:
        dim = self.config.get('dimension', None)

        if not dim:
            return DEFAULT_DIMENSION

        if 'x' in dim:
            dim = dim.split('x')
            return (int(dim[0]), int(dim[1]))
        else:
            raise AssertionError("dimension should be: 50x50 format.")

    def should_shuffle(self) -> bool:
        return self.config.get('shuffle', False)

    def should_normalize(self):
        return self.config.get('normalize', False)

    def should_divide_by_255(self):
        return self.config.get('divide_by_255', False)

    def get_size(self):
        size = self.config.get('size', None)

        if isinstance(size, dict):
            train_size = self.config['size'].get('train', None)
            test_size = self.config['size'].get('test', None)

            assert isinstance(train_size, int) and isinstance(test_size, int), \
                "Train and test size should be int."

            return (train_size, test_size)

        return (None, None)


#!/usr/bin/python3

# Importing things
import socket
import sys
import signal

# Handle Ctrl-C properly
def signal_handler(signal, frame):
        print('Cleanly exiting')
        sys.exit(0)

def get_hostname(buf):
    hostname_str = '#^Hostname: '
    end_char = '\n'
    result = buf[buf.find(hostname_str)+len(hostname_str):buf.find(end_char)]
    return result

# Set up socket bindings and signal listener
port = 5000
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.bind(("", port))
signal.signal(signal.SIGINT, signal_handler)
info_buffer = " "

# Start listening on port
print("waiting on port:", port)
while 1:
    # Make sure we can get a lot of data
    data, addr = s.recvfrom(2048)
    # Stripe \n from strings and decode bytes"
    print(data.rstrip().decode())
    info_buffer += data.rstrip().decode()
    if "#^Hostname" in data.rstrip().decode():
        buf = data.rstrip().decode()
        hostname = get_hostname(buf)
    if "#^END" in data.rstrip().decode():
        info_file = open('servers/' + hostname, "w+")
        info_file.write(info_buffer)
        buf = " "
        hostname = " "
        info_file.close()
        info_buffer = " "


def segment(sent, step=3, wind=[100, 70, 40]):
    """

    :param corp: corpus from which the segment are extracted
    :param step:
    :param wind: the lenghts of the differents segments extracted at a same time
    :return: a stack of embeded segments and a reference file
    """
    segs = []
    seg_ref = {}
    cpt = 0
    utt_lengths = []
    i_start = 0
    w1 = []
    w07 = []
    w04 = []
    n_search = sent.shape[0]
    while i_start <= n_search - 1 or i_start == 0:
        for ind in wind:
            if ind == 100:
                w1.append(cpt)
            elif ind == 70:
                w07.append(cpt)
            elif ind == 40:
                w04.append(cpt)
            sref = {}
            sref["wind"] = ind
            sref["time"] = i_start/100
            seg_ref[cpt] = sref
            seg=sent[i_start:i_start+ind]
            utt_lengths.append(seg.shape[0])
            i_start += step
            cpt +=1
            segs.append(seg)
    return segs, utt_lengths, w1, w04, w07


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 16 23:16:40 2020

@author: dsp
"""
# GRAYSCALING

import cv2

#load our input image
image=cv2.imread('./images/input.jpg')
cv2.imshow('Original',image)
cv2.waitKey(0)

#use cvtColor to convert image to grayscale
gray_image=cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.imshow('Grayscale', gray_image)
cv2.waitKey(0)
cv2.destroyAllWindows()


from fstrs import allowed_driving, fib
import pytest

@pytest.mark.parametrize("arg1, arg2, ret",[
    ('bob', 23, True),
    ('mark', 16, False),
    ('border', 18, True),
    ('anna', 19, True),
    ('simba', 8, False),
])
def test_allowed_driving(arg1, arg2, ret):
    assert allowed_driving(arg1, arg2) == ret

# capfd is a feature of pytest - which captures the standard output of the program and execution
# The reason we use this is that for the allowed_driving we want to check the boolean return
# and the actual output ... {name} is allowed / not allowed drive.
@pytest.mark.parametrize("arg1, arg2, ret",[
    ('bob', 23, True),
    ('border', 18, True),
    ('anna', 19, True),
])
def test_allowed_drive_true(arg1, arg2, ret, capfd):
    assert allowed_driving(arg1, arg2) == ret
    # To see what is being printed to the console we use the capfd
    # We re-direct the standard output, and throw away the error
    # Call the readouterr() func of capfd
    out = capfd.readouterr()[0]
    # We can just see what that gives us by using print statements
    # When calling pytest use pytest -s filename.py
    # print(out)
    # Now we can assert on that just as we do any other variables and functions
    # We use the rstrip() to strip of the new line at the right (we saw this in the print)
    assert out.rstrip() == f'{arg1} is allowed to drive'

@pytest.mark.parametrize("arg1, arg2, ret",[
    ('mark', 16, False),
    ('simba', 8, False),
])
def test_allowed_drive_false(arg1, arg2, ret, capfd):
    assert allowed_driving(arg1, arg2) == ret
    # To see what is being printed to the console we use the capfd
    # We re-direct the standard output, and throw away the error
    # Call the readouterr() func of capfd
    out = capfd.readouterr()[0]
    # We can just see what that gives us by using print statements
    # When calling pytest use pytest -s filename.py
    # print(out)
    # Now we can assert on that just as we do any other variables and functions
    # We use the rstrip() to strip of the new line at the right (we saw this in the print)
    assert out.rstrip() == f'{arg1} is not allowed to drive'

# Test that neg args to fib raise an error
def test_neg_fib():
    with pytest.raises(ValueError):
        fib(-1)

# Test that zero and one return 0, 1 as the first 2 fib numbers are 0, 1
def test_zero_one_fib():
    assert fib(0) == 0
    assert fib(1) == 1

# Test fib with legit values against expected output
# fib 0, 1, 1, 2, 3, 5, 8, 13, 21
@pytest.mark.parametrize("arg1, ret",[
    (2,1),
    (3,2),
    (4,3),
    (5,5),
    (6,8),
    (7,13),
])
def test_fib(arg1, ret):
    assert fib(arg1) == ret


import time
import re

def formatEpoch( epoch ):
  '''Formats a epoch timestamp to a string like JS's ISO standard.

  Parameters
  ----------
  epoch: int
    The epoch requested to format

  Returns
  -------
  formattedDate : str
    The formatted datetime string that is similar to JS's ISO standard.
  '''
  return time.strftime(
    '%Y-%m-%dT%H:%M:%S.',
    time.localtime(epoch / 1000 )
  ) + str( epoch )[-3:] + 'Z'

def formatDate( date ):
  '''Formats a datetime object to a string like JS's ISO standard.

  Parameters
  ----------
  date: datetime.datetime
    The datetime requested to format

  Returns
  -------
  formattedDate : str
    The formatted datetime string that is similar to JS's ISO standard.
  '''
  return date.strftime( '%Y-%m-%dT%H:%M:%S.' ) \
    + date.strftime('%f')[:3] + 'Z'

def objectToItemAtr( obj ):
  '''Formats any Python type to its respective DynamoDB syntax.

  Parameters
  ----------
  obj : any
    The object to be formatted into the DynamoDB syntax.

  Returns
  -------
  result : dict
    The DynamoDB syntax of the object.
  '''
  atr = _objectToItemAtr_singleton( obj )
  if atr is not None:
    return atr
  if isinstance( obj, dict ):
    return { 'M': {
      key: objectToItemAtr( value )
      for key, value in obj.items()
    } }
  atr = _objectToItemAtr_list( obj )
  if atr is not None:
    return atr
  if obj is None:
    return { 'NULL': True }
  raise Exception( 'Could not parse attribute: ', obj )

def _objectToItemAtr_singleton( obj ):
  '''Formats strings, numbers, and booleans into DynamoDB syntax.'''
  if isinstance( obj, str ):
    if obj in ('None', ''):
      return { 'NULL': True }
    return { 'S': obj }
  if isinstance( obj, ( float, int ) ):
    return { 'N': str( obj ) }
  if isinstance( obj, bool ):
    return { 'BOOL': obj }
  return None

def _objectToItemAtr_list( obj ):
  '''Formats lists into DynamoDB syntax.'''
  if isinstance( obj, list ) and \
    all( [re.match( r'[\d\D]+', string ) for string in obj] ):
    return { 'SS': [ str( string ) for string in obj ] }
  if isinstance( obj, list ):
    return { 'NS': obj }
  return None

class toItemException( Exception ):
  '''Exception raised for errors parsing a DynamoDB item to its respective
  object.

  Attributes
  ----------
  itemType = str
    The type of item attempted to parse from.
  '''
  def __init__( self, itemType ):
    self.itemType = itemType
    self.message = f'Could not parse { self.itemType }'
    super().__init__( self.message )


# Python
from typing import Optional, List
from enum import Enum

# Pydantic
from pydantic import BaseModel, Field

# FastAPI
from fastapi import FastAPI, status, Body, Query, Path

app = FastAPI()

# Models
class HairColor(Enum):
    white = 'white'
    brown = 'brown'
    black = 'black'
    blonde = 'blonde'
    red = 'red'

class Location(BaseModel):
    city: str
    state: str
    country: str

class Person(BaseModel):
    first_name: str = Field(
        ...,
        min_length=1,
        max_length=50,
        example='José'
    )
    last_name: str = Field(
        ...,
        min_length=1,
        max_length=50,
        example='Trezza'
    )
    age: int = Field(
        ...,
        gt=0,
        le=115
    )
    hair_color: Optional[HairColor] = Field(default=None)
    is_married: Optional[bool] = Field(default=None)

class PublicPerson(BaseModel):
    first_name: str = Field(
        ...,
        min_length=1,
        max_length=50,
        example='José'
    )
    last_name: str = Field(
        ...,
        min_length=1,
        max_length=50,
        example='Trezza'
    )

@app.get("/")
async def home():
    return {"Hello": "World"}

# Request and Response Body

@app.post('/person/new', response_model=PublicPerson,status_code=status.HTTP_201_CREATED)
async def create_person(person: Person = Body(...)):
    return person

# Validaciones: query parameters

@app.get('/person/detail')
async def show_person(
    name: Optional[str] = Query(
        None,
        min_length=1,
        max_length=50,
        title="Person Name",
        description="This is the person's name. It's between 1 and 50 characters",
        example="Rocío"
    ),
    age: int = Query(
        ...,
        title="Person's age",
        description="This is the person's age. It's required",
        gt=17,
        example=25
    )
):
    return {name: age}

# Validaciones: Path
@app.get('/person/detail/{person_id}')
async def person_detail(
    person_id: int = Path(
        ...,
        title="Person's ID",
        description="This is the person's ID. It's required and must be greater than 0.",
        gt=0
    )
):
    return {person_id: "It exists!"}

# Validaciones: Request Body
@app.put('/person/{person_id}')
async def update_person(
    person_id: int = Path(
        ...,
        title="Person ID",
        description="This is the person's ID",
        gt=0
    ),
    person: Person = Body(
        ...
    ),
    location: Location = Body(...)
):
    results = person.dict()
    results.update(location.dict())
    return results

a: List[int] = [1,2,3,4,5]
b: list[int] = [6,7,8,9,0]


from random import randint
from klasy import Menu, Gra, Papier
ekwipunek = ["stary_kilof"]
sakwa_na_mineraly = []
wynik = []
kasa = 0

startkasa = randint(0,200)

if startkasa >= 0 and startkasa <= 5:
	kasa += kasa + 9000
	print("Poczatkowe pieniadze: 9000$")
elif startkasa > 5 and startkasa <= 15:
	kasa += kasa + 6000
	print("Poczatkowe pieniadze: 6000$")
elif startkasa > 15 and startkasa <= 30:
	kasa += 4500
	print("Poczatkowe pieniadze 4500$")
elif startkasa > 30 and startkasa <= 50:
	kasa += 2000
	print("Poczatkowe pieniadze: 2000$")
elif startkasa > 50 and startkasa <= 80:
	kasa += 1000
	print("Poczatkowe pieniadze: 1000$")
elif startkasa > 80 and startkasa <= 130:
	kasa += 500
	print("Poczatkowe pieniadze: 500$")
elif startkasa > 130 and startkasa <= 200:
	print("Poczatkowe pieniadze: 0$")

hartowany_zelazny_kilof = 0
stalowy_kilof = 0
tytanowe_wiertlo = 0
stary_kilof = 1
zardzewialy_kilof = 0
super_motyka = 0

rubin = 0
szmaragd = 0
opal = 0
beryl = 0
szafir = 0

p = 0
ptkU = 0
ptkC = 0

i = 0
st = Menu()
rt = Gra()

while i < 7:
  i += 1
  print("dzien - ", i)
  st.tawerna(kasa,ekwipunek, sakwa_na_mineraly)
  rt.petla(wynik,szmaragd,rubin,szafir,beryl, opal,kasa,sakwa_na_mineraly)
  szmaragd = wynik[0]
  rubin = wynik[1]
  szafir = wynik[2]
  beryl = wynik[3]
  opal = wynik[4]
  kasa = wynik[5]
  wynik = []

  rt.petla(wynik,szmaragd,rubin,szafir,beryl, opal,kasa,sakwa_na_mineraly)
  szmaragd = wynik[0]
  rubin = wynik[1]
  szafir = wynik[2]
  beryl = wynik[3]
  opal = wynik[4]
  kasa = wynik[5]
  wynik = []

  if i >= 2:
    if stalowy_kilof >= 1:
      wynik = []
      rt.stalowykilofgra(szmaragd, rubin, szafir, beryl, opal, kasa,sakwa_na_mineraly,wynik)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []
      rt.stalowykilofgra(szmaragd, rubin, szafir, beryl, opal, kasa,sakwa_na_mineraly,wynik)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []
    elif hartowany_zelazny_kilof >= 1:
      wynik = []
      rt.petla(wynik, szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]

      wynik = []
      rt.petla(wynik, szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []

      rt.petla(wynik, szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []

    elif tytanowe_wiertlo >= 1:
      wynik = []
      rt.petla(wynik, szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []
      rt.petla(wynik, szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []
      rt.petla(wynik, szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []
      rt.petla(wynik, szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]
      kasa = wynik[5]
      wynik = []
    elif super_motyka >= 1:
      rt.super_motyka_gra(szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly, wynik)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]

      wynik = []
      rt.super_motyka_gra(szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly, wynik)
      szmaragd = wynik[0]
      rubin = wynik[1]
      szafir = wynik[2]
      beryl = wynik[3]
      opal = wynik[4]

      wynik = []

  rt.sprzedaz(szmaragd, rubin, szafir, beryl, opal, kasa, sakwa_na_mineraly, wynik)
  szmaragd = wynik[0]
  rubin = wynik[1]
  szafir = wynik[2]
  beryl = wynik[3]
  opal = wynik[4]
  kasa = wynik[5]

  wynik = []
  rt.sklep(kasa, stary_kilof, stalowy_kilof, hartowany_zelazny_kilof, tytanowe_wiertlo, ekwipunek, wynik,super_motyka)
  kasa = wynik[0]
  stary_kilof = wynik[1]
  stalowy_kilof = wynik[2]
  hartowany_zelazny_kilof = wynik[3]
  tytanowe_wiertlo = wynik[4]
  super_motyka = wynik[5]
  Papier.pkn(p,ptkU, ptkC)
  print("TWOJE STATYSTYKI PO TYM DNIU:")
  print("TWOJ EKWIPUNEK:", ekwipunek)
  print("TWOJE PIENIADZE:", kasa)
  print("TWOJE MINERALY:", sakwa_na_mineraly)

  wynik = []

if kasa >= 25000:
	print("WYGRALES ZDOBYWAJAC OKRESLONA PULE PIENIEDZY, TWOJE PIENIADZE TO:", kasa)
elif kasa < 25000:
	print("NIE WYGRYWASZ, BO NIE OSIAGNALES OKRESLONEJ PULI PIENIEDZY, TWOJE PIENIADZE TO:", kasa)


import requests
import re

# Extract code snippets from code.txt
code_snippets = {}
with open("code.txt", "r") as file:
    content = file.read()
    matches = re.findall(r"(Code\d+.txt):\n```python\n(.*?)\n```", content, re.DOTALL)
    for match in matches:
        code_snippets[match[0]] = match[1].strip()

# Generate image for each code snippet
url = "https://carbonara.solopov.dev/api/cook"
headers = {'Content-Type': 'application/json'}

for file_name, code in code_snippets.items():
    payload = {
        "code": code,
        "backgroundColor": "#7367F0"  # You can modify other parameters here
    }

    response = requests.post(url, headers=headers, json=payload)

    if response.status_code == 200:
        with open(f"../Generation/images/{file_name}.png", "wb") as img_file:
            img_file.write(response.content)
        print(f"Generated {file_name}.png")
    else:
        print(f"Failed to generate image for {file_name}", response.status_code)


#----------------------------------------------------------------------*/influxdb_client
# 2022.03.11 UECS
# sudo apt-get install python3-pip -y
# sudo apt-get install python3-pandas -y
# sudo apt-get install python3-influxdb -y
# sudo pip3 install influxdb-client
# sudo pip3 install xmltodict
#----------------------------------------------------------------------*/
#!/usr/bin/python3

from socket import *
import time as t
import pandas as pd
import xmltodict,json,os,configparser
from multiprocessing import Process
from influxdb_client.client.write_api import SYNCHRONOUS
from influxdb_client import InfluxDBClient, Point, WriteOptions

## 初期設定
class Initialset():
    def parm_set():
        # 受信設定ファイルを読み込む。
        ccm_json = os.path.dirname(os.path.abspath(__file__)) + '/receive_ccm.json' #CNF
        json_open = open(ccm_json, 'r')
        json_load = json.load(json_open)
        # 保存用種別を4つ作成
        up_ ,diff_ ,max_ ,abc_=[],[],[],[]

        for k in json_load.keys():
            recv_ccm = json_load[k]["type"].split(".")[0]
            recv_ccm += "_" + json_load[k]["room"]
            recv_ccm += "_" + json_load[k]["region"]
            recv_ccm += "_" + json_load[k]["order"]
            recv_ccm = recv_ccm.lower()                   # 小文字に変換
            if json_load[k]["savemode"] not in (None,""):
                up_.append(recv_ccm)
            if json_load[k]["savemode"] == "diff":
                diff_.append(recv_ccm)
            elif json_load[k]["savemode"] in ("on","off"):
                max_.append(recv_ccm)
            elif json_load[k]["savemode"] =="abc":
                abc_.append(recv_ccm)

        recv_ccm = {"flag_up":set(up_) ,"flag_diff":set(diff_) ,  # 集合型に変換
                    "flag_max":set(max_) ,"flag_abc":set(abc_)}

        # read config
        filepath = os.path.dirname(os.path.abspath(__file__))+ '/uecs2influxdb.cfg'
        config = configparser.ConfigParser()
        config.read(filepath)

        return recv_ccm,config

## UDP受信クラス
class udprecv():
    def __init__(self,config):

        SrcIP = ""                                               # 受信元IP
        SrcPort = 16520                                          # 受信元ポート番号
        self.SrcAddr = (SrcIP, SrcPort)                          # アドレスをtupleに格納

        self.BUFSIZE = 512                                       # バッファサイズ指定
        self.udpServSock = socket(AF_INET, SOCK_DGRAM)           # ソケット作成
        self.udpServSock.bind(self.SrcAddr)                      # 受信元アドレスでバインド

        # influxdb パラメータ
        param = os.path.dirname(os.path.abspath(__file__))+ '/uecs2influxdb.cfg'
        self.bucket = config["influx2"]["bucket"]
        self.client = InfluxDBClient.from_config_file(param)
        self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
        self.query_api = self.client.query_api()

    def recv(self,debug=False,debug_sec=None,ccm_list=[]):
        if debug_sec is not None:    # debug_sec が指定されている場合
            start=t.time()
            debug_list=[]
            print("ccm_list",ccm_list)

        while True:                                              # 常に受信待ち
            ccm, addr = self.udpServSock.recvfrom(self.BUFSIZE)  # 受信
#            print(ccm.decode(), addr)                            # 受信データと送信アドレス表示

            p = Process(target=self.save_df, args=(debug,ccm,ccm_list))        # マルチプロセス化でDB処理などを実行する
            p.start()
            if p.join(5) is None:
                p.terminate()
            # デバックモード
            if debug:
                print(ccm.decode(), addr)                           # 受信データと送信アドレス表示
                if debug_sec is not None:                           # 秒 指定がある場合
                    end=t.time()
                    debug_list.append(ccm)
                    print("Main process ID:",os.getppid())
                    if end-start>=debug_sec:
                        print("debug_time:",round(end-start,2),"ExecCount:",len(debug_list))
                        break;

    # DB保存処理
    def save_df(self,debug,ccm,ccm_list):
        dictionary = xmltodict.parse(ccm)                            # xmlを辞書型へ変換
        json_string = json.dumps(dictionary)                         # json形式のstring
        json_string = json_string.replace('@', '').replace('#', '')  # 「#や@」 をreplace
        json_object = json.loads(json_string)                        # Stringを再度json形式で読み込む

        measurement = json_object["UECS"]["DATA"]["type"].split(".")[0]
        measurement += "_" + json_object["UECS"]["DATA"]["room"]
        measurement += "_" + json_object["UECS"]["DATA"]["region"]
        measurement += "_" + json_object["UECS"]["DATA"]["order"]
        measurement = measurement.lower()                             # 小文字に変換
        datetime    = pd.Timestamp.utcnow()
        val         = float(json_object["UECS"]["DATA"]["text"])*1.0
        priority    = json_object["UECS"]["DATA"]["priority"]

        # 保存用のCCMでない場合、EXITする
        if measurement not in ccm_list["flag_up"]:
            exit(0)

        # 前回のデータと今回のデータの差分処理
        if measurement in ccm_list["flag_diff"] :
            p = {"_bucket": self.bucket ,"_measurement": measurement}
            q ='''
                  from(bucket: _bucket)
                  |> range(start: -1y)
                  |> filter(fn: (r) => r["_measurement"] == _measurement)
                  |> filter(fn: (r) => r["cloud"] == "0" and r["downsample"] == "0" )
                  |> filter(fn: (r) => r["_field"] == "value")
                  |> aggregateWindow(every: 1y, fn: last, createEmpty: false)
               '''
            tables = self.query_api.query(query=q, params=p)

            last_val=None
            for table in tables:
                for record in table.records:
                    last_val = float(record["_value"])

            if last_val in (None,0): #前回のデータがなければ、今回のデータを使う
                last_val= val
            val = abs(val - last_val) #絶対値

        # 四捨五入する 0,1 のデータを対象とする
        if measurement in ccm_list["flag_max"]:
            val = round(val) * 1.0

        # ↓↓↓  influxDB用整形
        data = {"measurement": measurement,
                 "tags": {"cloud": "0","downsample": "0"} ,
                 "fields": {"value": val}}
        # ↑↑↑  influxDB用整形
        p = Process(target=self.influx_write, args=(debug,data))        # マルチプロセス化でDB処理などを実行する
        p.start()
        if p.join(5) is None:
            p.terminate()

        if debug:
            print("Sub_process ID:",os.getppid())

    def influx_write(self,debug,data):
        with self.client.write_api(write_options=WriteOptions(batch_size=500,
                                                      flush_interval=10_000,
                                                      jitter_interval=2_000,
                                                      retry_interval=5_000,
                                                      max_retries=5,
                                                      max_retry_delay=30_000,
                                                      exponential_base=2)) as _write_client:

            _write_client.write(bucket=self.bucket, record=data)

#-------------------------------------------------------#
# Main 処理
#-------------------------------------------------------#

# パラメータセット
ccm_list,config=Initialset.parm_set()

#UECS受信
udp = udprecv(config)     # クラス呼び出し
#udp.recv(debug=True,debug_sec=30,ccm_list=ccm_list)     # デバックモード　10秒間
udp.recv(debug=True,ccm_list=ccm_list)                 # 本番処理　debug_secを指定しない


from GuessGame import play as guess_game_play
from memoryGame import play as memory_game_play
from currency_roulette_game import play as currency_roulette_game_play
# from Utils import screen_cleaner as screen_cleaner
from Scores import *

def input_validation(validationmethod, firsvalidator, secondvalidator, evaluatee):
    if validationmethod == "intrange":
        # check if evaluatee is integer
        try:
            isintcheck = int(evaluatee)
        except ValueError:
            return False
        return int(evaluatee) >= int(firsvalidator) and int(evaluatee) <= secondvalidator
    return False

def welcome(name):
    return str('Hello %s and welcome to the World of Games (WOG).\nHere you can find many cool games to play' % name)

def choose_game():
    games = {'1': {
            'Title': 'Memory Game',
            'Description': 'a sequence of numbers will appear for 1 second and you have to guess it back.'
           },
           '2': {
            'Title': 'Guess Game',
            'Description': 'guess a number and see if you chose like the computer.'
           },
           '3': {
            'Title': 'Currency Roulette',
            'Description': 'Try and guess the value of random amount of USD in ILS.'
            }
        }
    number_of_games = len(games.keys())
    print("Please Choose a game to play - \nEnter a choice between 1 to %s or 0 to quit:" % number_of_games)
    for game_number in games.keys():
        print(game_number+". "+games[game_number]['Title']+" - "+games[game_number]['Description'])
    game_to_load = input()
    while not input_validation("intrange", 0, number_of_games, game_to_load):
        game_to_load = input("You have entered an invalid choice. Please Enter a choice between 1 to %s\n or 0 to quit" % number_of_games)
    return game_to_load

def choose_level():
    game_level = input("Please choose game difficulty from 1 to 5:\n")
    while not input_validation("intrange", 1, 5, game_level):
        game_level = input("You have entered an invalid choice. Please Enter a choice between 1 to 5\n")
    return int(game_level)

def load_game():
    game = choose_game()
    if not game == '0':
        level = choose_level()
        if game == '1':
            game_outcome = memory_game_play(level)
        if game == '2':
            game_outcome = guess_game_play(level)
        if game == '3':
                game_outcome = currency_roulette_game_play(level)
        if game_outcome:
            print("Success! you won the game!")
            add_score(level)
        else:
            print("Defeat! you lost the game!")
            screen_cleaner()
            load_game()
    else:
        screen_cleaner()
        print("Screen cleared!")
        print("quitting!")

screen_cleaner()
print(welcome("Guy"))
load_game()