from nets import vgg
import tensorflow as tf
from preprocessing import vgg_preprocessing
from upsampling import bilinear_upsample_weights

slim = tf.contrib.slim

# Mean values for VGG-16
from preprocessing.vgg_preprocessing import _R_MEAN, _G_MEAN, _B_MEAN

wd = 5e-4

def leaky_relu(x, alpha=0.01):

    return tf.maximum(x, alpha * x)

def _score_layer(wd, bottom, in_features, kernel_size, name, num_classes):

    with tf.variable_scope(name) as scope:
        # get number of input channels
        shape = [kernel_size, kernel_size, in_features, num_classes]
        # He initialization Sheme
        if name == "fc_9_1":
            stddev = 0.0001

        # Apply convolution
        w_decay = wd

        weights = _variable_with_weight_decay(shape, stddev, w_decay,
                                                    decoder=True)
        conv = tf.nn.conv2d(bottom, weights, [1, 1, 1, 1], padding='SAME')
        # Apply bias
        conv_biases = _bias_variable([num_classes], constant=0.0)
        bias = tf.nn.bias_add(conv, conv_biases)

        return bias

def _variable_with_weight_decay(shape, stddev, wd, decoder=False):
        """Helper to create an initialized Variable with weight decay.
        Note that the Variable is initialized with a truncated normal
        distribution.
        A weight decay is added only if one is specified.
        Args:
          name: name of the variable
          shape: list of ints
          stddev: standard deviation of a truncated Gaussian
          wd: add L2Loss weight decay multiplied by this float. If None, weight
              decay is not added for this Variable.
        Returns:
          Variable Tensor
        """

        #initializer = tf.contrib.layers.variance_scaling_initializer()
        initializer = tf.truncated_normal_initializer(stddev=stddev)
        var = tf.get_variable('weights', shape=shape,
                              initializer=initializer)

        collection_name = tf.GraphKeys.REGULARIZATION_LOSSES
        if wd and (not tf.get_variable_scope().reuse):
            weight_decay = tf.multiply(
                tf.nn.l2_loss(var), wd, name='weight_loss')
            tf.add_to_collection(collection_name, weight_decay)

        return var

def _bias_variable(shape, constant=0.0):

        initializer = tf.constant_initializer(constant)
        var = tf.get_variable(name='biases', shape=shape,
                              initializer=initializer)

        return var

def FCN_8s(image_batch_tensor,
           number_of_classes,
           new_number_of_classes,
           is_training,
           is_reuse,
           is_fine_tune=False):
    """Returns the FCN-8s model definition.
    The function returns the model definition of a network that was described
    in 'Fully Convolutional Networks for Semantic Segmentation' by Long et al.
    The network subsamples the input by a factor of 32 and uses three bilinear
    upsampling layers to upsample prediction by a factor of 32. This means that
    if the image size is not of the factor 32, the prediction of different size
    will be delivered. To adapt the network for an any size input use
    adapt_network_for_any_size_input(FCN_8s, 32). Note: the upsampling kernel
    is fixed in this model definition, because it didn't give significant
    improvements according to aforementioned paper.

    Parameters
    ----------
    image_batch_tensor : [batch_size, height, width, depth] Tensor
        Tensor specifying input image batch
    number_of_classes : int
        An argument specifying the number of classes to be predicted.
        For example, for PASCAL VOC it is 21.
    is_training : boolean
        An argument specifying if the network is being evaluated or trained.
        It affects the work of underlying dropout layer of VGG-16.

    Returns
    -------
    upsampled_logits : [batch_size, height, width, number_of_classes] Tensor
        Tensor with logits representing predictions for each class.
        Be careful, the output can be of different size compared to input,
        use adapt_network_for_any_size_input to adapt network for any input size.
        Otherwise, the input images sizes should be of multiple 32.
    fcn_16s_variables_mapping : dict {string: variable}
        Dict which maps the FCN-8s model's variables to FCN-16s checkpoint variables
        names. We need this to initilize the weights of FCN-8s model with FCN-16s from
        checkpoint file. Look at ipython notebook for examples.
    """

    # Convert image to float32 before subtracting the
    # mean pixel value
    image_batch_float = tf.to_float(image_batch_tensor)

    # Subtract the mean pixel value from each pixel
    mean_centered_image_batch = image_batch_float - [_R_MEAN, _G_MEAN, _B_MEAN]

    upsample_filter_factor_2_np = bilinear_upsample_weights(factor=2,
                                                            number_of_classes=number_of_classes)

    upsample_filter_factor_8_np = bilinear_upsample_weights(factor=8,
                                                             number_of_classes=number_of_classes)

    upsample_filter_factor_2_tensor = tf.constant(upsample_filter_factor_2_np)
    upsample_filter_factor_8_tensor = tf.constant(upsample_filter_factor_8_np)

    with tf.variable_scope('FCN_slice', reuse = is_reuse):

       with tf.variable_scope("fcn_8s")  as fcn_8s_scope:
            # Define the model that we want to use -- specify to use only two classes at the last layer
            # TODO: make pull request to get this custom vgg feature accepted
            # to avoid using custom slim repo.
            with slim.arg_scope(vgg.vgg_arg_scope()):

                ## Original FCN-32s model definition

                last_layer_logits, end_points = vgg.vgg_16(mean_centered_image_batch,
                                                        num_classes=number_of_classes,
                                                        is_training=is_training,
                                                        dropout_keep_prob=0.5,
                                                        spatial_squeeze=False,
                                                        use_dilated=False,
                                                        scope='vgg_16',
                                                        fc_conv_padding='SAME',
                                                        global_pool=False)

                last_layer_logits_shape = tf.shape(last_layer_logits)

                # Calculate the ouput size of the upsampled tensor
                last_layer_upsampled_by_factor_2_logits_shape = tf.stack([
                                                                    last_layer_logits_shape[0],
                                                                    last_layer_logits_shape[1] * 2,
                                                                    last_layer_logits_shape[2] * 2,
                                                                    last_layer_logits_shape[3]
                                                                    ])

                last_layer_logits = slim.batch_norm(last_layer_logits, activation_fn=tf.nn.relu)

                # Perform the upsampling
                last_layer_upsampled_by_factor_2_logits = tf.nn.conv2d_transpose(last_layer_logits,
                                                                                upsample_filter_factor_2_tensor,
                                                                                output_shape=last_layer_upsampled_by_factor_2_logits_shape,
                                                                                strides=[1, 2, 2, 1],
                                                                                name='upscore2')

                ## Adding the skip here for FCN-16s model

                # We created vgg in the fcn_8s name scope -- so
                # all the vgg endpoints now are prepended with fcn_8s name

                pool4_features = end_points['FCN_slice/fcn_8s/vgg_16/pool4']

                # We zero initialize the weights to start training with the same
                # accuracy that we ended training FCN-32s

                pool4_features = slim.batch_norm(pool4_features, activation_fn=tf.nn.relu)

                pool4_logits = slim.conv2d(pool4_features,
                                        number_of_classes,
                                        [1, 1],
                                        activation_fn=None,
                                        normalizer_fn=None,
                                        weights_initializer=tf.zeros_initializer,
                                        scope='pool4_fc')

                fused_last_layer_and_pool4_logits = pool4_logits + last_layer_upsampled_by_factor_2_logits

                fused_last_layer_and_pool4_logits_shape = tf.shape(fused_last_layer_and_pool4_logits)

                # Calculate the ouput size of the upsampled tensor
                fused_last_layer_and_pool4_upsampled_by_factor_2_logits_shape = tf.stack([
                                                                            fused_last_layer_and_pool4_logits_shape[0],
                                                                            fused_last_layer_and_pool4_logits_shape[1] * 2,
                                                                            fused_last_layer_and_pool4_logits_shape[2] * 2,
                                                                            fused_last_layer_and_pool4_logits_shape[3]
                                                                            ])

                fused_last_layer_and_pool4_logits = slim.batch_norm(fused_last_layer_and_pool4_logits, activation_fn=tf.nn.relu)

                # Perform the upsampling
                fused_last_layer_and_pool4_upsampled_by_factor_2_logits = tf.nn.conv2d_transpose(fused_last_layer_and_pool4_logits,
                                                                            upsample_filter_factor_2_tensor,
                                                                            output_shape=fused_last_layer_and_pool4_upsampled_by_factor_2_logits_shape,
                                                                            strides=[1, 2, 2, 1],
                                                                            name='upscore4')

                ## Adding the skip here for FCN-8s model

                pool3_features = end_points['FCN_slice/fcn_8s/vgg_16/pool3']

                # We zero initialize the weights to start training with the same
                # accuracy that we ended training FCN-32s

                pool3_features = slim.batch_norm(pool3_features, activation_fn=tf.nn.relu)

                pool3_logits = slim.conv2d(pool3_features,
                                        number_of_classes,
                                        [1, 1],
                                        activation_fn=None,
                                        normalizer_fn=None,
                                        weights_initializer=tf.zeros_initializer,
                                        scope='pool3_fc')

                fused_last_layer_and_pool4_logits_and_pool_3_logits = pool3_logits + \
                                                fused_last_layer_and_pool4_upsampled_by_factor_2_logits

                fused_last_layer_and_pool4_logits_and_pool_3_logits_shape = tf.shape(fused_last_layer_and_pool4_logits_and_pool_3_logits)

                # Calculate the ouput size of the upsampled tensor
                fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits_shape = tf.stack([
                                                                            fused_last_layer_and_pool4_logits_and_pool_3_logits_shape[0],
                                                                            fused_last_layer_and_pool4_logits_and_pool_3_logits_shape[1] * 8,
                                                                            fused_last_layer_and_pool4_logits_and_pool_3_logits_shape[2] * 8,
                                                                            fused_last_layer_and_pool4_logits_and_pool_3_logits_shape[3]
                                                                            ])

                fused_last_layer_and_pool4_logits_and_pool_3_logits = slim.batch_norm(fused_last_layer_and_pool4_logits_and_pool_3_logits, activation_fn=tf.nn.relu)

                # Perform the upsampling
                fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits = tf.nn.conv2d_transpose(fused_last_layer_and_pool4_logits_and_pool_3_logits,
                                                                            upsample_filter_factor_8_tensor,
                                                                            output_shape=fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits_shape,
                                                                            strides=[1, 8, 8, 1],
                                                                            name='upscore32')

                fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits = slim.batch_norm(fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits, activation_fn=tf.nn.relu)

                fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits_3 = \
                _score_layer(wd, fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits, number_of_classes, 1, 'fc_9_1', new_number_of_classes)

                fcn_8s_variables_mapping = {}

                fcn_8s_variables = slim.get_variables(fcn_8s_scope)

                for variable in fcn_8s_variables:

                    # We only need FCN-16s variables to resture from checkpoint
                    # Variables of FCN-8s should be initialized
                    if not is_fine_tune:
                        if 'fc_9_1' in variable.name:
                            continue

                    # Here we remove the part of a name of the variable
                    # that is responsible for the current variable scope
                    original_fcn_8s_checkpoint_string = 'FCN_slice/fcn_8s' +  variable.name[len(fcn_8s_scope.name):-2]
                    fcn_8s_variables_mapping[original_fcn_8s_checkpoint_string] = variable

    return fused_last_layer_and_pool4_logits_and_pool_3_upsampled_by_factor_8_logits_3, fcn_8s_variables_mapping


import cv2
import numpy as np
img = cv2.imread('2.jpg',1)

# Escalar-REDIMENSIONAR
img_resize = cv2.resize(img,(320,240),
                        interpolation = cv2.INTER_LINEAR)

#img_resize = cv2.resize(img,None,fx=0.5, fy=0.5,
                        #interpolation = cv2.INTER_LINEAR)

print (img.shape)
print (img_resize.shape)

cv2.imshow('Imagen Original',img)
cv2.imshow('Imagen Escalada',img_resize)
cv2.waitKey(0)
cv2.destroyAllWindows()


"""
Trabajo Práctico 4 - Estructura iterativa:

Ejercicio N°3:
Realizar un programa para ingresar desde el teclado un conjunto de números y
mostrar por pantalla el menor y el mayor de ellos. Finalizar la lectura de datos
con un valor -1.
"""

n = int(input("Ingrese un número:"))

mayor = n
menor = n

while n != -1:

    if n > mayor:
     mayor = n
    if n < menor:
     menor = n

    n = int(input("Ingrese otro número, presione -1 para finalizar:"))

print("El número mayor es:",mayor,"y el número menor es:",menor)


"developer: pegah"

import collections
import string
import glob

from nltk.corpus import stopwords
from nltk.tokenize import word_tokenize
from nltk.tokenize import RegexpTokenizer
import os
import xml.etree.ElementTree as ET

#nltk.download('stopwords')
#nltk.download('punkt')

stop_words = set(stopwords.words('english'))
tokenizer = RegexpTokenizer(r'\w+')
exclude = set(string.punctuation)
path = os.path.abspath(os.path.join(os.getcwd(), os.pardir)) + '/TAC/u08_corr/'

class BQP_input_maker:

    def __init__(self, original_text, bigram_text, path_):

        self.original_text = original_text[0:-10]+'concat.xml'
        self.bigram_text = bigram_text
        #self.valid_summary_list = valid_summary_list
        self.path_ = path_

    def is_filter_token(self, input):

        no_punctuation_list = []
        for ch in input:
            if ch in exclude:
                return True
            else:
                no_punctuation_list.append(ch)

        no_punctuation = ''.join(i for i in no_punctuation_list)
        input = tokenizer.tokenize(no_punctuation)

        for w in input:
            if w in stop_words:
                return True

        return False

    def tokens_dictionary(self):

        bigram_dict = {}

        with open(self.bigram_text) as f:
            for line in f:
                tempo = line
                tt = tempo.split('\t')

                bigram_dict[tt[0]] = tt[1][0:-1]

        return  bigram_dict

    def clean_tockens(self, bigram_dic):
        real_bigrm_dic = dict()

        for key, value in bigram_dic.items():
            if not self.is_filter_token(value):
                real_bigrm_dic[key] = value

        return real_bigrm_dic

    def get_xml_source(self, with_filter = True):
        name = "concat-"+ self.path_[-8:-3]

        if with_filter:
            file = open(self.path_ + name + ".txt", 'w+')
        else:
            file = open(self.path_ + name + ".txt", 'w+')

        tree = ET.parse(self.original_text)
        root = tree.getroot()

        "number of sentences in the document"
        num_sent = len([child for child in root])
        file.write(str(num_sent))
        file.write('\n')

        bigram_dic = self.tokens_dictionary()
        if with_filter:
            "if we remove stop words and punctuations from the birgams"
            filter_bigram = ex.clean_tockens(bigram_dic)
            bigram_keys = [i for i in filter_bigram.keys()]
        else:
            "if we do no filtering"
            bigram_keys = [i for i in bigram_dic.keys()]

        sent_length_list = []
        dic_sent_tokens = dict()

        sent_id = 0
        for child in root:

            _bigram = child.find('bigrams').text
            tt = child.find('raw')

            sent_length_list.append(len((tt.text).split(' ')))

            if _bigram is None:
                dic_sent_tokens[sent_id] = []
            else:
                text_bigram = _bigram.split(' ')

                if tt is None:
                    print('****')
                    print(child[0].text)

                new_text_bigram = [i for i in text_bigram if i in bigram_keys]
                dic_sent_tokens[sent_id] = new_text_bigram

            sent_id += 1

        seti = set([])
        for element in dic_sent_tokens.values():
            seti = seti | set(element)

        indexed_tockens = dict()

        # "number of tockens"
        # num_tockens = sum(len(i) for i in dic_sent_tokens.values())
        # file.write(str(num_tockens))
        # file.write('\n')

        counter = 0
        for element in seti:
            indexed_tockens[element] = counter
            counter +=1

        vocabulary_size = len(seti)
        "vocabulary size"
        file.write(str(vocabulary_size))
        file.write('\n')

        "list of sentences length for the original text"

        for i in sent_length_list:
            file.write(str(i))
            file.write('\t')
        file.write('\n')

        for element in dic_sent_tokens.values():
            vector = [0]*vocabulary_size
            if len(element) > 0:
                counter = collections.Counter(element)
                for token, counter_ in counter.items():
                    vector[indexed_tockens[token]] = counter_

            for i in vector:
                file.write(str(i))
                file.write('\t')

            file.write('\n')

        file.close()
        return

if __name__ == '__main__':

    def get_directories(path_):
        directories = None
        for root, dirs, files in os.walk(path_):
            directories = dirs
            break
        return directories

    directory = get_directories(path)
    bigram = None

    counter = 1
    for dir in directory:
        sub_path = path+dir+'/'
        bigram = sub_path + 'index_bigrams'

        sub_sub_path = sub_path + dir + '-A/'
        # files = glob.glob(sub_sub_path +"*.xml")
        if counter < 10:
            files = [sub_sub_path + "concat.xml"]
        else:
            files = [sub_sub_path + "concat.xml"]
        for orig in files:
            print(orig)
            ex = BQP_input_maker(orig, bigram, sub_sub_path)
            ex.get_xml_source(with_filter=True)

        counter += 1

# sub_path = '/home/pegah/Documents/research/DVRC/NLP-for-NLP/BQP-summary/TAC/u08_corr/D0838/'
# bigram = sub_path + 'index_bigrams'
# sub_sub_path = '/home/pegah/Documents/research/DVRC/NLP-for-NLP/BQP-summary/TAC/u08_corr/D0838/D0838-A/'
# orig = sub_path + '/D0838-A/concat.xml'
#
#
# ex = BQP_input_maker(orig, bigram, sub_sub_path)
# ex.get_xml_source(with_filter=True)


import socket
if __name__ == '__main__':
    try:
        # init socket
        host = '127.0.0.1'  # server address
        # which is your preference for performing text analysis
        port = 5000  # server port
        clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  # set TCP IP4 connection
        clientSocket.setblocking(True)
        socket.setdefaulttimeout(60 * 2)  # set default blocking time to 5 minutes for all operations
        clientSocket.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 3500)  # set receive buffer size
        clientSocket.connect((host, port))  # connect to server
        mn = clientSocket.recv(3500).decode()  # receive response from server for first time
        while True:
            try:
                print(mn)
                data = input('You>>')  # get user request
                if not data:
                    continue
                elif data.isnumeric():
                    data = str(socket.htonl(int(data)))
                clientSocket.send(data.encode())  # send user request to server
                if data.strip().lower() == 'x':  # check if request is end connection
                    break  # break while loop
            except TimeoutError as e:
                continue
            except ConnectionError as e:
                print(str(f'Connection Ended'))
                break
            except KeyboardInterrupt as e:
                print(str(f'KIE {e}'))
                continue
            mn = clientSocket.recv(3500).decode()  # receive response from server

        clientSocket.close()  # end connection
    except ConnectionError as e:
        print(str(f'CE Connection Ended'))
    except socket.error as e:
        print(str(f'SE {e}'))
    except Exception as e:
        print(str(f'E {e}'))


# from dust i have come, dust i will be

import cv2
import numpy as np
import time

def calculate_dist(ref, test, idx, jdx):
    M = ref.shape[0]
    N = ref.shape[1]
    test_partial = test[idx: idx + M, jdx: jdx + N].astype(np.int64)

    # sum(diff in each cell ^ 2)
    ans = np.absolute(ref.astype(np.int64) - test_partial)
    ans = ans * ans

    return np.sum(ans)

def exhaustive_search(ref, test):
    start = time.time()

    M = ref.shape[0]
    N = ref.shape[1]
    I = test.shape[0]
    J = test.shape[1]

    print(ref.shape, test.shape)

    min_dist = np.inf
    selected_i = 0
    selected_j = 0

    for i in range(I - M + 1):
        for j in range(J - N + 1):
            dist = calculate_dist(ref, test, i, j)
            if dist < min_dist:
                min_dist = dist
                selected_i = i
                selected_j = j

    print(selected_i, selected_j, min_dist)
    print("time taken:", time.time() - start)
    # now that we have i, j selected we draw a red box
    # note that cv2 keeps the image in BGR format, not RGB!
    rgb_test = cv2.cvtColor(test, cv2.COLOR_GRAY2BGR)

    # cv2.rectangle(img, (x1, y1), (x2, y2), color, thickness)
    # i denotes row, so Y-axis, j denotes column, so X-axis
    cv2.rectangle(rgb_test, (selected_j, selected_i), (selected_j + N, selected_i + M), (0, 0, 255), 2)

    cv2.imshow("exhaustive search result", rgb_test)
    cv2.waitKey()
    cv2.destroyWindow("exhaustive search result")

if __name__ == "__main__":
    ref_img = cv2.imread("./io/reference.jpg", 0)
    test_img = cv2.imread("./io/main.PNG", 0)

    exhaustive_search(ref_img, test_img)


from abc import ABCMeta, abstractclassmethod
from collections import UserList
from warnings import warn

from gym.spaces import Box, Discrete
import numpy as np
import torch

def one_hot(labels, depth):
    """
    >>> one_hot(torch.tensor([0, 1, 0]), 2)
    tensor([[1., 0.],
            [0., 1.],
            [1., 0.]])
    """
    out = torch.zeros(*labels.size(), depth)
    out.scatter_(1, labels[:, None], 1)
    return out

def discount_rewards(rewards, discount):
    """
    >>> discount_rewards([0., 0., 1., 0.], 0.5)
    [0.25, 0.5, 1.0, 0.0]
    """
    current_reward = rewards[-1]
    discounted_rewards = [current_reward]
    for reward in rewards[-2::-1]:
        current_reward = reward + discount * current_reward
        discounted_rewards.append(current_reward)
    discounted_rewards.reverse()
    return discounted_rewards

def zip_dictionaries(dicts):
    keys = dicts[0].keys()
    return {
        key: [d[key] for d in dicts]
        for key in keys
    }

class SimpleTrainer(metaclass=ABCMeta):

    def __init__(
            self, env, *, reward_discount, should_render=False,
            exploration_prob=0.0, max_episode_length):
        self.env = env
        self.should_render = should_render
        self.reward_discount = reward_discount
        self.rng = np.random.RandomState()
        self.exploration_prob = exploration_prob
        self.max_episode_length = max_episode_length

    @property
    def box_action_std(self):
        return 0.25 * (
            self.env.action_space.high - self.env.action_space.low)

    @property
    def box_action_distribution(self):
        box_action_std_t = torch.tensor(
            self.box_action_std, dtype=torch.float32)
        return torch.distributions.Normal(
            torch.zeros_like(box_action_std_t),
            box_action_std_t)

    def train_one_episode(self):
        observations, actions, rewards = self._run_episode()
        total_reward = np.sum(rewards)
        discounted_rewards = discount_rewards(
            rewards, self.reward_discount)
        loss = self._train_on_episode(
            observations, actions, rewards, discounted_rewards)
        return total_reward, loss

    def _maybe_render(self):
        if self.should_render:
            self.env.render()

    def _extra_buffer_kwargs(
            self, observations, actions, rewards, discounted_rewards):
        return {}

    @abstractclassmethod
    def _choose_action(self, observation):
        pass

    def _train_on_episode(
            self, observations, actions, rewards, discounted_rewards):
        warn('Training without replay buffer')
        buffer = ReplayBuffer()
        extra_kwags = self._extra_buffer_kwargs(
            observations, actions, rewards, discounted_rewards)
        buffer.append_train_one_episode_result(
            observations, actions, rewards, discounted_rewards,
            **extra_kwags)
        dict_of_lists = zip_dictionaries(buffer)
        return self._train_on_replay_buffer(dict_of_lists)

    def _train_on_replay_buffer(self, replay_buffer_sample):
        raise NotImplemented(
            'Implement either _train_on_episode or _train_on_replay_buffer')

    def log(self, format, *args, **kwargs):
        if not self.should_render:
            return
        print(format.format(*args, **kwargs))

    def _run_episode(self):
        rewards = []
        done = False
        observation = self.env.reset()
        observations = [observation]
        actions = []
        self._maybe_render()
        while not done:
            chosen_action = self._choose_action(observation)
            actions.append(chosen_action)
            observation, reward, done, _ = self.env.step(chosen_action)
            if len(observations) > self.max_episode_length:
                done = True
            self._maybe_render()
            observations.append(observation)
            rewards.append(reward)
        return observations, actions, rewards

    def _sample_model_action(self, model_result):
        action_space = self.env.action_space
        if isinstance(action_space, Discrete):
            assert model_result.shape == (action_space.n, )
            return self.rng.choice(action_space.n, p=model_result)
        if isinstance(action_space, Box):
            assert model_result.shape == action_space.shape
            model_result += self.rng.normal(
                0, self.box_action_std, size=model_result.shape)
            model_result = np.clip(
                model_result, action_space.low, action_space.high)
            return model_result

        raise ValueError('Unsupported action space {}'.format(action_space))

    def _sample_action(self, model_result):
        if self.rng.uniform() < self.exploration_prob:
            return self.env.action_space.sample()
        return self._sample_model_action(model_result)

class Scaler(torch.nn.Module):

    def __init__(self, low, high):
        super().__init__()
        self.low = torch.tensor(low, dtype=torch.float32)
        self.delta = torch.tensor(
            high - low, dtype=torch.float32)

    def forward(self, inputs):
        return self.low + self.delta * inputs

class ReplayBuffer(UserList):
    def __init__(self, *args, rng=None, max_size=None, **kwargs):
        super().__init__(*args, **kwargs)
        self.max_size = max_size
        self.rng = rng
        if max_size and not rng:
            raise ValueError('If there is a max_size pass rng')

    def append_train_one_episode_result(
            self, observations, actions, rewards, discounted_rewards, **kwargs):
        self._clip_if_more_elements(len(observations) - 1)
        for i in range(len(observations) - 1):
            self.append({
                'current_state': observations[i],
                'future_state': observations[i + 1],
                'action': actions[i],
                'reward': rewards[i],
                'discounted_reward': rewards[i],
                'done': i + 2 == len(observations),
                **{
                    key: value[i]
                    for key, value in kwargs.items()
                },
            })

    def _clip_if_more_elements(self, num_new_entries):
        if not self.max_size:
            return
        if len(self) + num_new_entries <= self.max_size:
            return
        if num_new_entries >= self.max_size:
            print('Too small replay buffer', num_new_entries)
            self.data.clear()
            return
        self.data = (
            self.rng.choice(
                self.data, self.max_size - num_new_entries,
                replace=False).
            tolist())

def copy_model(dest, src):
    dest.load_state_dict(src.state_dict())

def polyak_update(dest, src, rate):
    dest_dict = dest.state_dict()
    src_dict = src.state_dict()
    assert dest_dict.keys() == src_dict.keys()
    new_dest_dict = {
        key: rate * dest_dict[key] + (1 - rate) * src_dict[key]
        for key in dest_dict
    }
    dest.load_state_dict(new_dest_dict)


import json
import sys

def main():

    try:
        with open("FinishedGames.json", 'r', encoding='utf8') as f:
            data = json.load(f.read())
    except:
        print('Finished game data file not found')
        print('Please rerun betchamp.py and try again')
        sys.exit(0)

if __name__ == "__main__":
    main()


# 회의실 배정 - 그리디

# 회의 길이 기준 => 겹치는 것까지 고려해야 함 => 첫번째 회의만 잘 정하면 됨
# 첫번째 회의 => 빨리 끝나는 회의가 결국 짧은 회의

import sys
N = int(sys.stdin.readline())
meetings = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
meetings = sorted(meetings, key=lambda x: (x[1], x[0]))

# 첫번째 회의: 가장 빨리 끝나는 회의
table = []
table.append(meetings[0])
if N > 1:
    for i in range(1, N):
        if meetings[i][0] >= table[-1][1]:
            table.append(meetings[i])

print(len(table))


# Задайте список из n чисел последовательности по формуле (1+ 1 /n)**n и выведите на экран их сумму.Пример:- Для n = 6: [2, 2, 2, 2, 2, 3]   13
num = int(input('Введите число: '))
nums_list =[]
for i in range(1, num+1):
    temp = round( (1 + 1/i)**i )
    nums_list.append(temp)

print(nums_list)
sum = 0
for j in nums_list:
    sum +=j
print(sum)


from __future__ import annotations

from pathlib import Path
from typing import Iterable

from docutils import nodes
from docutils.statemachine import ViewList
from docutils.parsers.rst import Directive
from sphinx.errors import SphinxError
from sphinx.util.nodes import nested_parse_with_titles
"""Custom extension to collect release notes from separate files

Use one of:
.. release_notes:: feature
.. release_notes:: fix
.. release_notes:: dev

"""

class ReleaseNotes(Directive):
    has_content = True

    @classmethod
    def make_rst(cls, note_type: str) -> ViewList:
        note_paths: Iterable[Path] = (Path() / 'docs' / 'release_notes' / 'next').glob(note_type + '*')

        rst = ViewList()
        try:
            note_paths = sorted(note_paths, key=lambda p: int(p.name.split('-')[1]))
        except ValueError as exc:
            raise cls.severe('Could not sort release notes, check filenames.') from exc

        for n, note_path in enumerate(note_paths):
            note_content = note_path.read_text().strip().split('\n')
            if len(note_content) != 1:
                raise cls.severe(f'Release note file should have 1 line: {note_path}.')

            rst.append(f"- {note_content[0]}", "generated.rst", n)

        return rst

    def run(self) -> list[nodes.Node]:
        if len(self.content) != 1:
            raise self.severe('Directive release_notes needs a value.')
        if not self.content[0].isalnum():
            raise self.severe(f'Value should be single word. Got "{self.content[0]}".')

        note_type = self.content[0]
        rst = self.make_rst(note_type)

        node = nodes.section()
        node.document = self.state.document
        nested_parse_with_titles(self.state, rst, node)

        return node.children

    @staticmethod
    def severe(message):
        """Override with an error strong enough to stop build"""
        return SphinxError(f'ReleaseNotes: {message}')

def setup(app):
    app.add_directive("release_notes", ReleaseNotes)

    return {
        'version': '0.1',
        'parallel_read_safe': True,
        'parallel_write_safe': True,
    }


import util

def get_results(endpoint_url, query):
    util.install_and_import('sparqlwrapper', "SPARQLWrapper")

    from SPARQLWrapper import SPARQLWrapper, JSON

    sparql = SPARQLWrapper(endpoint_url)
    sparql.setQuery(query)
    sparql.setReturnFormat(JSON)
    return sparql.query().convert()["results"]["bindings"]

def get_medicamentos():
    endpoint_url = "https://query.wikidata.org/sparql"

    query = """SELECT ?medicationLabel WHERE {
    SERVICE wikibase:label { bd:serviceParam wikibase:language "en". }
    ?medication wdt:P31 wd:Q12140.
    }
    LIMIT 100000"""

    json = get_results(endpoint_url, query)

    meds = []
    for e in json:
        for value in e.values():
            meds.append(value['value'])
    return meds


import re

text = 'vsRbbr678j'                 # 1

pattern = r'[R]b+[r]'

result = re.search(pattern, text)

print(result.group())

text = '9999-9999-9999-9989'            # 2

pattern = r'[0-9]{4}-[0-9]{4}-[0-9]{4}-[0-9]{4}' # for any card
pettern2 = r'9{4}-9{4}-9{4}-9{4}' # for card (9999-9999-9999-9999)

result = re.search(pattern, text)

print(result.group())

text = 'ry66uYf-Y1z_p@gmail.com'                        # 3

def is_it_gmail(text):

    regular = r'^[a-zA-Z0-9][a-zA-Z0-9_-]*@gmail.com$'
    if re.search(regular, text):
        if len(re.findall(r'-', text))>1:
            return False
        else:
            return True
    return False

print(is_it_gmail(text))

login = '25i6Yu59t9'                                # 4

def login_check(login):
    pattern = r'^[0-9a-zA-Z]{2,10}$'
    if re.search(pattern, login):
        return True
    else:
        return False

print(login_check(login))


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Script de nettoyage du bac à sable de Vikidia

# (C) Linedwell, 2011-2018
#
# Distribué sous licence GNU GPLv3
# Distributed under the terms of the GNU GPLv3 license
# http://www.gnu.org/licenses/gpl.html

import sys
sys.path.insert(1, '..') #ajoute au PYTHONPATH le répertoire parent

import mylogging

import pywikibot
from datetime import datetime, timedelta

# Déclarations
dicoFR = {
    'site' : pywikibot.Site('fr','vikidia'),
    'page' : u"Vikidia:Bac à sable",
    'template' : u"{{subst:Vikidia:Bac à sable/Zéro}}",
    'summary' : u"[[Vikidia:Robot|Robot]] : Nettoyage du bac à sable",
    'delay' : 30,
}

dicoIT = {
    'site' : pywikibot.Site('it','vikidia'),
    'page' : u"Vikidia:Area giochi",
    'template' : u"{{subst:Vikidia:Area giochi/Zero}}",
    'summary' : u"[[Vikidia:Bot|Bot]] : Pulizia dell'area giochi",
    'delay' : 30,
}

#Recharge le bac à sable avec un contenu prédéfini
def clean(dico):
    site = dico['site']
    page = pywikibot.Page(site,dico['page'])
    template = dico['template']
    summary = dico['summary']
    delay = dico['delay']
    if not page.userName() == site.user():
        limite = calcLimit(delay)
        if page.editTime() < limite:
            page.text = template
            page.save(summary)

#Calcule la "date" avant laquelle on s'autorise à blanchir le bas
def calcLimit(delay):
    today = datetime.utcnow()
    limit = today - timedelta(minutes=delay)
    return limit

#Exécution
def main():
    clean(dicoFR) #nettoyage fr
    clean(dicoIT) #nettoyage it

if __name__ == "__main__":
    try:
        main()
    finally:
        pywikibot.stopme()


from os import system
from time import sleep
import pygame

def main():
    x = 120
    for i in range(x + 1):
        sleep(1)
        print(formatTime(x))
        x -= 1
def formatTime(x):
    minutes = int(x / 60)
    seconds_rem = int(x % 60)
    if (seconds_rem < 10):
        return(str(minutes) + ":0" + str(seconds_rem))
    else:
        return(str(minutes) + ":" + str(seconds_rem))
main()

'''

def main():
    tempo = 1

    # Vai diminuindo de 1 em 1 minuto
    for minuto in range(tempo - 1, -1, -1):
        # Vai diminuindo de 1 em 1 segundo
        for segundo in range(59, -1, -1):
            #system("clear") # Comando para limpar a tela (Linux)
            # Use system("cls") se for executar no Windows
            print "Restam: %02d:%02d" %(minuto, segundo)
            sleep(1)

    return 0

tempo = 2 # tempo de escolha do personagem (minutos)
for minuto in range(tempo - 1, -1, -1):# Vai diminuindo de 1 em 1 minuto
    for segundo in range(59, -1, -1):# Vai diminuindo de 1 em 1 segundo
        pygame.display.update()
        fonte = pygame.font.Font("fontes/font.ttf",30)
        #texto = fonte.render(output_string, True,(0,0,0))
       # tela.blit(texto,[405,5])

        sleep(1)

if __name__ == "__main__": main()
'''


n = int(input())

G = []
L = []

for i in range(n):
    ary, num = input().split()
    num = int(num)
    if ary == 'G':
        G.append(num)
    else:
        L.append(num)
G.sort()
L.sort()

cnt = 0
for i in range(len(G)):
    j = 0
    while j < len(L) and G[i] > L[j]:
        j += 1
    cnt = max(cnt, i + 1 + len(L) - j)
print(n - cnt)


from datetime import datetime
import json
from time import sleep
from typing import List
import re

import requests

from pollers.poller import *

class MastrGenericPoller(Poller):
  # see https://www.marktstammdatenregister.de/MaStR/Einheit/EinheitJson/GetFilterColumnsErweiterteOeffentlicheEinheitStromerzeugung

  ENERGIETRAEGER_ANDERE_GASE_ID = 2411
  ENERGIETRAEGER_BIOMASSE_ID = 2493
  ENERGIETRAEGER_BRAUNKOHLE_ID = 2408
  ENERGIETRAEGER_DRUCK_AUS_GASLEITUNGEN_ID = 2957
  ENERGIETRAEGER_DRUCK_AUS_WASSERLEITUNGEN_ID = 2958
  ENERGIETRAEGER_ERDGAS_ID = 2410
  ENERGIETRAEGER_GEOTHERMIE_ID = 2403
  ENERGIETRAEGER_GRUBENGAS_ID = 2406
  ENERGIETRAEGER_KERNENERGIE_ID = 2494
  ENERGIETRAEGER_KLAERSCHLAMM_ID = 2405
  ENERGIETRAEGER_MINEARALOELPRODUKTE_ID = 2409
  ENERGIETRAEGER_NICHT_BIOGENER_ABFALL_ID = 2412
  ENERGIETRAEGER_SOLARE_STRAHLUNGSENERGIE_ID = 2495
  ENERGIETRAEGER_SOLARTHERMIE_ID = 2404
  ENERGIETRAEGER_SPEICHER_ID = 2496
  ENERGIETRAEGER_STEINKOHLE_ID = 2407
  ENERGIETRAEGER_WAERME_ID = 2413
  ENERGIETRAEGER_WASSER_ID = 2498
  ENERGIETRAEGER_WIND_ID = 2497

  BATTERIETECHNOLOGIE_BLEI = 'Blei'
  BATTERIETECHNOLOGIE_HOCHTEMPERATUR = 'Hochtemperatur'
  BATTERIETECHNOLOGIE_LITHIUM = 'Lithium'
  BATTERIETECHNOLOGIE_NICKEL = 'Nickel-Cadmium / Nickel-Metallhydrid'
  BATTERIETECHNOLOGIE_REDOX_FLOW = 'Redox-Flow'
  BATTERIETECHNOLOGIE_SONSTIGE = 'Sonstige'

  BATTERIETECHNOLOGIE_BY_ID = {
    728: BATTERIETECHNOLOGIE_BLEI,
    730: BATTERIETECHNOLOGIE_HOCHTEMPERATUR,
    727: BATTERIETECHNOLOGIE_LITHIUM,
    731: BATTERIETECHNOLOGIE_NICKEL,
    729: BATTERIETECHNOLOGIE_REDOX_FLOW,
    732: BATTERIETECHNOLOGIE_SONSTIGE,
  }

  HAUPTNEIGUNGSWINKEL_BIS_20 = "<20°"
  HAUPTNEIGUNGSWINKEL_20_BIS_40 = "20-40°"
  HAUPTNEIGUNGSWINKEL_40_BIS_60 = "40-60°"
  HAUPTNEIGUNGSWINKEL_AB_60 = ">60°"
  HAUPTNEIGUNGSWINKEL_FASSADE = "fassadenintegriert"
  HAUPTNEIGUNGSWINKEL_NACHGEFUEHRT = "nachgefuehrt"

  HAUPTNEIGUNGSWINKEL_BY_ID = {
    810: HAUPTNEIGUNGSWINKEL_BIS_20,
    809: HAUPTNEIGUNGSWINKEL_20_BIS_40,
    808: HAUPTNEIGUNGSWINKEL_40_BIS_60,
    807: HAUPTNEIGUNGSWINKEL_AB_60,
    806: HAUPTNEIGUNGSWINKEL_FASSADE,
    811: HAUPTNEIGUNGSWINKEL_NACHGEFUEHRT,
  }

  LAGE_FREIFLAECHE = "freiflaeche" # Freifläche
  LAGE_GEBAEUDE = "gebaeude" # Bauliche Anlagen (Hausdach, Gebäude und Fassade)
  LAGE_GEBAEUDE_OTHER = "gebaeude-other" # Bauliche Anlagen (Sonstige)
  LAGE_STECKER = "stecker" # Steckerfertige Erzeugungsanlage (sog. Plug-In- oder Balkon-PV-Anlage)
  LAGE_WINDKRAFT_LAND = "windkraft-land" # Windkraft an Land
  LAGE_WINDKRAFT_SEE = "windkraft-see" # Windkraft auf See

  LAGE_BY_ID = {
    852: LAGE_FREIFLAECHE,
    853: LAGE_GEBAEUDE,
    2484: LAGE_GEBAEUDE_OTHER,
    2961: LAGE_STECKER,
    888: LAGE_WINDKRAFT_LAND,
    889: LAGE_WINDKRAFT_SEE,
  }

  LEISTUNGSBEGRENZUNG_50 = "50%"
  LEISTUNGSBEGRENZUNG_60 = "60%"
  LEISTUNGSBEGRENZUNG_70 = "70%"
  LEISTUNGSBEGRENZUNG_SONSTIGE = "sonstige"
  LEISTUNGSBEGRENZUNG_OHNE = "ohne"

  LEISTUNGSBEGRENZUNG_BY_ID = {
    805: LEISTUNGSBEGRENZUNG_50,
    804: LEISTUNGSBEGRENZUNG_60,
    803: LEISTUNGSBEGRENZUNG_70,
    1535: LEISTUNGSBEGRENZUNG_SONSTIGE,
    802: LEISTUNGSBEGRENZUNG_OHNE
  }

  NETZBETREIBERPRUEFUNG_GEPRUEFT_ID = 2954
  NETZBETREIBERPRUEFUNG_IN_PRUEFUNG_ID = 2955

  NUTZUNGSBEREICH_GHD = "GHD" # Gewerbe, Handel, Dienstleistungen
  NUTZUNGSBEREICH_HAUSHALT = "haushalt"
  NUTZUNGSBEREICH_INDUSTRIE = "industrie"
  NUTZUNGSBEREICH_LANDWIRTSCHAFT = "landwirtschaft"
  NUTZUNGSBEREICH_OEFFENTLICH = "oeffentlich" # Öffentliches Gebäude
  NUTZUNGSBEREICH_SONSTIGE = "sonstige"

  NUTZUNGSBEREICH_BY_ID = {
    714: NUTZUNGSBEREICH_GHD,
    713: NUTZUNGSBEREICH_HAUSHALT,
    715: NUTZUNGSBEREICH_INDUSTRIE,
    716: NUTZUNGSBEREICH_LANDWIRTSCHAFT,
    717: NUTZUNGSBEREICH_OEFFENTLICH,
    718: NUTZUNGSBEREICH_SONSTIGE,
  }

  def query_with_pagination(self, page_size = 500, filter = '') -> List:
    items = []
    total = None
    page = 1

    while total is None or len(items) < total:
      url = f"https://www.marktstammdatenregister.de/MaStR/Einheit/EinheitJson/GetErweiterteOeffentlicheEinheitStromerzeugung?pageSize={page_size}&group=&filter={filter}&page={page}"
      print (f"> Query {url}")
      req = requests.get(url, headers = {
        'Connection': 'close'
      })

      if req.status_code != 200:
        raise Exception('Can\'t access webpage: Status code ' + str(req.status_code))

      # MaStR seems to use full-width ampersand ＆ (U+FF06) instead of normal ampersand & (U+0026)
      body = req.text.replace('＆', '&')

      payload = json.loads(body)

      if payload['Errors'] != None:
        raise Exception('Data error: %s' % payload['Errors'])

      if payload['Total'] == 0:
        raise Exception('Queried data is empty')
      elif total is None:
        total = payload['Total']
      elif payload['Total'] != total:
        raise Exception('Total count changed during consecutive paginated queries')

      if len(payload['Data']) > page_size:
        raise Exception('Received more items in single query than expected: page_size = %d, got %d' % (page_size, len(payload['Data'])))
      if len(payload['Data']) == 0:
        break

      items += payload['Data']
      page += 1

      sleep(0.5) # sleep 500ms to avoid Connection reset by peer errors

    if len(items) > total:
      raise Exception('Received more items in total than expected: total count = %d, got %d' % (total, len(items)))
    if len(items) < total:
      if len(items)+1 == total:
        # Sometimes, the returned data is exactly one item less the total amount. We decide to ignore that error.
        pass
      else:
        raise Exception('Received less items in total than expected: total count = %d, got %d' % (total, len(items)))

    return items

  def is_public(self, x: dict) -> bool:
    whitelist = [
      "ABR985464955328", # Gemeinde Vaterstetten
      "ABR920681169288", # 3E-eG Eigene Erneuerbare Energie Genossenschaft
      "ABR982596453098", # 3E-eG Eigene Erneuerbare Energie Genossenschaft
      "ABR935107317006", # Kath. Kirchenstiftung Maria Königin Baldham
      "ABR923417495323", # Kath. Kirchenstiftung Vaterstetten
      "ABR925649324174", # Kath. Siedlungswerk München
      "ABR964895737925", # Großmann Erden GmbH
      "ABR930947414953", # Energiehof Stefan Großmann-Neuhäusler
      "ABR932247507397", # ENTEGA NATURpur AG / Gymnasium Vaterstetten
      "ABR998244537751", # Bernhard Eschbaumer Forst- & Gartentechnik
      "ABR978161481993", # Brenner Selbstklebetechnik
      "ABR936688381776", # Raiffeisenbank Zorneding eG
      "ABR981935485455", # Auer Baustoffe GmbH ＆ Co. KG
      "ABR991822525591", # Landkreis Ebersberg
      "ABR939016877651", # Eurytos Energie GmbH ＆ Co. KG
      "ABR951481578482", # ibeko-solar GmbH
      "ABR981309102131", # ibeko-system GmbH
    ]

    if x['AnlagenbetreiberMaStRNummer'] in whitelist:
      return True

    if x['NutzungsbereichGebSA'] is not None and self.NUTZUNGSBEREICH_BY_ID[x['NutzungsbereichGebSA']] == self.NUTZUNGSBEREICH_OEFFENTLICH:
      return True

    has_betreiber_name = x['AnlagenbetreiberName'] is not None

    if has_betreiber_name and x['AnlagenbetreiberName'].startswith('natürliche Person'):
      return False

    if not x['IsAnonymisiert']: # IsAnonymisiert refers to whether Strasse and Ort are visible; this is true if Bruttoleistung >= 30 kWp
      return True

    if has_betreiber_name and 'GbR' in x['AnlagenbetreiberName']: # GbR firms are mostly used personally, since German law sometimes requires house owners to found a business for their photovoltaic system
      return False

    if has_betreiber_name and ('e.V.' in x['AnlagenbetreiberName'] or 'e. V.' in x['AnlagenbetreiberName'] or 'eG' in x['AnlagenbetreiberName']): # Vereine and Genossenschaften are public in general
      return True

    return False

  def parse_date(self, dateStr: str) -> str:
    if dateStr == None:
      return None

    regex_match = re.search(r'^\/Date\((-?[0-9]+)\)\/$', dateStr)

    if regex_match == None:
      raise Exception(f'Unknown date format: "{dateStr}"')

    unix_timestamp = regex_match.group(1)
    return datetime.utcfromtimestamp(int(unix_timestamp) / 1000).strftime('%Y-%m-%d')

  def parse_hausnummer(self, hausnummerStr: str) -> str:
    if hausnummerStr == None:
      return None

    hausnummerStr = hausnummerStr.strip()

    # try normalizing ranges like "26 a– 2c h" to "26 a - 26 h"
    matches_range = re.search(r'^([0-9a-z ]+)\s*[\-–]\s*([0-9a-z ]+)$', hausnummerStr)
    if matches_range != None:
      hausnummerStr = '%s - %s' % (matches_range.group(1), matches_range.group(2))

    return hausnummerStr

  def filter_vaterstetten(self, einheit: dict) -> bool:
    orte = [
      'Vaterstetten',
      'Baldham',
      'Weißenfeld',
      'Hergolding',
      'Parsdorf',
      'Neufarn',
      'Purfing'
    ]

    if not einheit['Ort'] in orte:
      # Uncomment this to identify mis-classified Einheiten and report them at https://www.marktstammdatenregister.de/MaStR/Startseite/Kontakt
      # print('Einheit with wrong Ort: %s %s, %s %s, %s (%s) https://www.marktstammdatenregister.de/MaStR/Einheit/Detail/IndexOeffentlich/%s' % (
      #   einheit['Plz'],
      #   einheit['Ort'],
      #   einheit['Strasse'] or '',
      #   einheit['Hausnummer'] or '',
      #   einheit['EinheitName'],
      #   einheit['AnlagenbetreiberName'],
      #   einheit['Id'],
      # ))
      return False

    return True


#!/usr/bin/env python
# coding=utf-8
from flask import Blueprint, render_template, g, abort
import rethinkdb as r
from rethinkdb.errors import RqlDriverError

import utils.Database as DB

blueprint = Blueprint('root', __name__, url_prefix='/')

# Add the testing-variable to the blueprint so we can know if we're in testing mode or not
@blueprint.record
def record_params(setup_state):
    blueprint.testing = setup_state.app.config.get('TESTING')
    if blueprint.testing:
        blueprint.database_name = setup_state.app.config.get('DB_NAME')

# The pattern we're using for managing database connections is to have **a connection per request**.
# We're using Flask's `@app.before_request` and `@app.teardown_request` for
# [opening a database connection](http://www.rethinkdb.com/api/python/connect/) and
# [closing it](http://www.rethinkdb.com/api/python/close/) respectively.
@blueprint.before_request
def before_request():
    db_name = DB.DB_AWS
    if blueprint.testing:
        db_name = blueprint.database_name

    try:
        g.rdb_conn = r.connect(host=DB.RDB_HOST, port=DB.RDB_PORT, db=db_name)
    except RqlDriverError:
        abort(503, "No database connection could be established.")

@blueprint.teardown_request
def teardown_request(exception):
    try:
        g.rdb_conn.close()
    except AttributeError:
        pass

@blueprint.route('/')
def root():
    # form = OwnPlantForm.OwnPlantForm()
    stats = list(r.table(DB.TABLE_STATISTICS).order_by(r.desc(DB.TABLE_STATISTICS_CREATED)).limit(30).run(g.rdb_conn))
    return render_template('root.html', stats=stats)


from setuptools import setup, find_packages

version = __import__('classytags').__version__

setup(
    name = 'django-classy-tags',
    version = version,
    description = 'Class based template tags for Django',
    author = 'Jonas Obrist',
    author_email = 'jonas.obrist@divio.ch',
    url = 'http://github.com/ojii/django-classy-tags',
    packages = find_packages(),
    zip_safe=False,
    test_suite='tests.suite',
)


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

# A simple setup script to create an executable using Tkinter. This also
# demonstrates the method for creating a Windows executable that does not have
# an associated console.
#
# SimpleTkApp.py is a very simple type of Tkinter application
#
# Run the build process by running the command 'python setup.py build'
#
# If everything works well you should find a subdirectory in the build
# subdirectory that contains the files needed to run the application

import sys
from cx_Freeze import setup, Executable
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')

opt = {
    'build_exe': {
        'include_files':[
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),
            'PTMfitter.exe',
         ],
    },
}
base = None
if sys.platform == 'win32':
    base = 'Win32GUI'

executables = [
    Executable('PTMGenerator.py', base=base)
]

setup(name='PTMgenerator',
      version='0.3',
      description='PTM Generator',
      executables=executables,
      options = opt
      )

#C:\Users\Elite>pip install --upgrade git+https://github.com/anthony-tuininga/cx_Freeze.git@master


import os
import logging
import subprocess
import numpy as np
import pandas as pd
import nibabel as nib

from pathlib import Path
from typing import Tuple, Union, List, Dict
from fastprogress import progress_bar

__all__ = ['compute_mp_fn', 'ComputeSubjectROIStats', 'PairedTTest']

# ============================== FUNCTIONS ==============================
def fill_missing_roi_values(df: pd.DataFrame, n_rois: int) -> pd.DataFrame:
    """Fill missing values with mean of that column.
    This function will check `roi_num` column from 1 to `n_rois` values,
    if there is any missing number then it will be filled using the mean
    value of the column.

    Args:
        df: pandas dataframe containing data
        n_rois: number of ROI's in the dataframe.
    """
    if df.roi_num.unique().shape[0] != n_rois:
        missing_rois = list(set(range(1, n_rois + 1)
                                ).difference(set(df.roi_num.unique())))
        total_missing = len(missing_rois)
        if total_missing != 0:
            # Too many missing values
            if total_missing > (df.shape[0] * .20):  # no more than 20%
                raise ValueError("Too much missing values.")
            for val in missing_rois:
                row = {'roi_num': val}
                columns = df.columns.to_list()
                columns.remove('roi_num')
                for colname in columns:
                    row[colname] = df[colname].mean()
                df = df.append(row, ignore_index=True)
                df = df.sort_values(by='roi_num').reset_index(drop=True)
            print(f"Interpolated {total_missing} missing value(s).")

    return df

def compute_mp_fn(kwargs):
    """Compute wrapper function for compute-stats-multi multiprocessing command
    """

    input_path = kwargs['input_path']
    template_path = kwargs['template_path']
    output_path = kwargs['output_path']
    logging.info(f"Computing ROI stats for {input_path}...")
    sstats = ComputeSubjectROIStats(input_path=input_path,
                                    subject_space_pcl_path=template_path,
                                    output_path=output_path,
                                    show_pb=False)
    ret_code = sstats.run()
    if ret_code == 0:
        logging.info("done!")
    else:
        logging.error(f"Error in computing stats for {input_path}")
    return 0

# ============================== CLASSES ==============================
class ComputeSubjectROIStats:
    def __init__(self,
                 input_path: Union[str, Path],
                 subject_space_pcl_path: Union[str, Path],
                 output_path: Union[str, Path],
                 stats_filename: str = 'dti_stats.csv',
                 show_pb: bool = True):
        """Compute ROI stats for one subject.

            Stats include mean and standard deviation of
            fractional anisotropy (FA), axial diffusivity (AD),
            and radial diffusivity (RD).

        Args:
            input_path: subject's DTI volume nifti file path.
            subject_space_pcl_path: Transformed to subject space ROI
                atlas nifti file path.
            output_path: where the output ROI files will be saved.
            stats_filename: name of the csv file containing computed stats.
                This file will be saved in `output_path`.
            show_pb: Enable/disable progress bar visualization.
                Useful to disable in multiprocessing.
        """
        self.input_path = Path(input_path)
        self.subject_space_pcl_path = Path(subject_space_pcl_path)
        self.output_path = Path(output_path)
        self.output_path.mkdir(parents=True, exist_ok=True)
        self.show_pb = show_pb

        self.subject_name = self.input_path.parent.stem
        # Set save path for csv file
        self.filepath = self.output_path / \
            f"{self.subject_name}__{stats_filename}"
        # Set a temporary file path for computation operations
        self.tmp_path = self.output_path/f"{self.subject_name}_tmp_roi.nii.gz"

    def run(self) -> int:
        # Get number of ROIs in parcellation / roi file.
        pcl_data = nib.load(self.subject_space_pcl_path)
        self.rois_values = [
            int(i)
            for i in np.unique(pcl_data.get_fdata())
            if i != 0  # Zero is for background
        ]
        self.n_rois = len(self.rois_values)
        print(f"Found {self.n_rois} unique ROI values.")

        # Compute ROI stats
        self.stats_df = self.make_subject_rois()
        self.stats_df.to_csv(self.filepath, index=False)

        # Remove temporary files
        if os.path.exists(self.tmp_path):
            os.remove(self.tmp_path)

        return 0

    def make_subject_rois(self) -> pd.DataFrame:
        """Split each ROI, binary threshold, and save as
            nifti files for further computation
        """
        from fsl.wrappers.fslmaths import fslmaths

        input_path = str(self.input_path)
        subject_stats = {
            'roi_num': [],
            'fa_mean': [], 'fa_std': [],
            'ad_mean': [], 'ad_std': [],
            'rd_mean': [], 'rd_std': [],
            'md_mean': [], 'md_std': [],
        }

        for roi_num in progress_bar(self.rois_values, display=self.show_pb):
            print("ROI_NUM =", roi_num)
            # Create binarized single ROI image
            (fslmaths(self.subject_space_pcl_path)
             .thr(roi_num)  # Threshold
             .uthr(roi_num)  # Upper threshold
             .bin()  # Binary thresholding
             .run(self.tmp_path))
            # Apply the ROI on subject
            fslmaths(input_path).mul(self.tmp_path).run(self.tmp_path)

            # Compute ROI stats
            roi_stats_dict = self._compute(self.tmp_path)
            subject_stats['roi_num'].append(roi_num)
            for k, v in roi_stats_dict.items():
                subject_stats[k].append(v)

        # Remove temporary file
        os.remove(self.tmp_path)

        return pd.DataFrame(subject_stats)

    def _compute(self, roi_path) -> dict:
        """Compute stats using given metrics and operations"""
        roi_stats = {}

        # Fractional Anisotropy (FA)
        ret_code = subprocess.run([
            'TVtool', '-in', roi_path, '-fa', '-out', 'tmp_roi.nii.gz'
        ]).returncode
        if ret_code == 0:
            fa_img = nib.load('tmp_roi.nii.gz').get_fdata()
            roi_stats['fa_mean'] = fa_img.mean()
            roi_stats['fa_std'] = fa_img.std()

        # Axial Diffusivity (AD)
        ret_code = subprocess.run([
            'TVtool', '-in', roi_path, '-ad', '-out', 'tmp_roi.nii.gz'
        ]).returncode
        if ret_code == 0:
            ad_img = nib.load('tmp_roi.nii.gz').get_fdata()
            roi_stats['ad_mean'] = ad_img.mean()
            roi_stats['ad_std'] = ad_img.std()

        # Radial Diffusivity (RD)
        ret_code = subprocess.run([
            'TVtool', '-in', roi_path, '-rd', '-out', 'tmp_roi.nii.gz'
        ]).returncode
        if ret_code == 0:
            rd_img = nib.load('tmp_roi.nii.gz').get_fdata()
            roi_stats['rd_mean'] = rd_img.mean()
            roi_stats['rd_std'] = rd_img.std()

        # Mean Diffusivity (MD)
        # To compute the map of trace (TR) (equal to 3 times the mean diffusivity)
        ret_code = subprocess.run([
            'TVtool', '-in', roi_path, '-tr', '-out', 'tmp_roi.nii.gz'
        ]).returncode
        if ret_code == 0:
            md_img = nib.load('tmp_roi.nii.gz').get_fdata() / 3
            roi_stats['md_mean'] = md_img.mean()
            roi_stats['md_std'] = md_img.std()
        return roi_stats

class DataLoader:
    from scipy import stats

    def __init__(self,
                 pre: List[Union[str, Path]],
                 post: List[Union[str, Path]],
                 n_rois: int,
                 fill_missing_roi: bool = True) -> None:
        """Data loader class for analysis using different tests

        Args:
            pre: list of paths of pre or group 1 csv data files.
            post: list of paths of post or group 2 csv data files.
            n_rois: Total number of ROIs present in the data.
                Make sure the ROI's numbering starts from 1 and consecutive.
            fill_missing_roi: if True, fill missing values with mean of the
                column.
        """
        # load data and set `roi_num` as index
        self.pre_dfs = self._load_data_safely(pre, fill_missing_roi, n_rois)
        self.post_dfs = self._load_data_safely(post, fill_missing_roi, n_rois)

        # set `roi_num` as index
        self.pre_dfs = {
            name: df.set_index('roi_num')
            for name, df in self.pre_dfs.items()
        }
        self.post_dfs = {
            name: df.set_index('roi_num')
            for name, df in self.post_dfs.items()
        }

        # Check if all dataframes are of same size
        size = [df.shape[0] == n_rois for name, df in self.pre_dfs.items()]
        _errmsg = f"All files must be of same size. Found {size}"
        assert all(size) == True, _errmsg

        self.n_rois = n_rois

    def _load_data_safely(self,
                          paths_list:  List[Union[str, Path]],
                          fill_missing_roi: bool,
                          n_rois: int):
        """Check and fix data before testing"""
        dfs = {}
        for p in paths_list:
            df = pd.read_csv(p)
            if fill_missing_roi:
                df = fill_missing_roi_values(df, n_rois)
            if df.shape[0] != n_rois:
                _errmsg = f"# ROIs in {p} != n_rois ({df.shape[0]} != {n_rois})."
                _errmsg += " set `fill_missing_roi = True` to fill missing values"
                raise ValueError(_errmsg)
            dfs[Path(p).stem] = df
        return dfs

    def paired_t_test(self,
                      var_name: str,
                      roi_num: Union[None, str, int, list],
                      roi_groups: Union[None, Dict[int, list]],
                      alpha: float = 0.05) -> dict:
        """Perform paired T-test on the given variable

        Args:
            var_name: column name of the variable to perform T-test.
            roi_num: ROI number i.e. specific brain region.
                [default is -1, means perform t-test on all regions one-by-one]
            roi_groups: Apply paried T-test on the groups of ROIs.
                There will be one p-value per group.
            alpha: Significance value
        """
        if (roi_num is not None) and (roi_groups is not None):
            raise AttributeError("Either pass `roi_num` or `roigrps`")

        elif roi_num is not None:
            if isinstance(roi_num, str) and (roi_num == 'all'):
                ret_dict = {}
                for i in range(1, self.n_rois + 1):
                    t_stat, p_value = self._one_roi_paired_t_test(
                        var_name, roi_num=i
                    )
                    ret_dict[i] = {
                        't_stat': t_stat,
                        'two_sided_p_value': p_value,
                        'p_value': p_value / 2,
                    }
                return ret_dict
            elif isinstance(roi_num, list):
                ret_dict = {}
                for i in roi_num:
                    t_stat, p_value = self._one_roi_paired_t_test(
                        var_name, roi_num=i
                    )
                    ret_dict[i] = {
                        't_stat': t_stat,
                        'two_sided_p_value': p_value,
                        'p_value': p_value / 2,
                    }
                return ret_dict
            else:
                try:
                    roi_num = int(roi_num)
                    if roi_num == 0:
                        raise ValueError("ROI number must be > 0.")
                except ValueError:
                    _errmsg = "`roi_num` must be an integer > 0 or `all`. "
                    _errmsg += f"Found roi_num = {roi_num}."
                    raise ValueError(_errmsg)
                t_stat, p_value = self._one_roi_paired_t_test(
                    var_name, roi_num=roi_num)
                return {roi_num: {
                        't_stat': t_stat,
                        'two_sided_p_value': p_value,
                        'p_value': p_value / 2,
                        }}

        elif roi_groups is not None:
            ret_dict = {}
            for group_num, group in roi_groups.items():
                ret = self._group_roi_paired_t_test(
                    var_name, group
                )
                group_t_stat, group_two_sided_p_value = ret
                group_p_value = group_two_sided_p_value / 2
                p_value = group_p_value / len(group)
                ret_dict[group_num] = {
                    'group_t_stat': group_t_stat,
                    'group_two_sided_p_value': group_two_sided_p_value,
                    'group_p_value': group_p_value,
                    'p_value': p_value
                }
            return ret_dict

    def _group_roi_paired_t_test(self, var_name: str, roi_group: list
                                 ) -> Tuple[float, float]:
        """Perform T-test on group of ROIs
        Args:
            var_name: Name of the variable (column of dataframe) to use.
            roi_group: list of roi numbers as a group.

        Returns:
            t-statistic, p-value
        """
        pre_values = [
            df.loc[roi_num, var_name]
            for df in self.pre_dfs.values() for roi_num in roi_group
        ]
        post_values = [
            df.loc[roi_num, var_name]
            for df in self.post_dfs.values() for roi_num in roi_group
        ]
        t_stat, two_sided_p_value = self.stats.ttest_rel(
            a=pre_values,
            b=post_values
        )
        return t_stat, two_sided_p_value

    def _one_roi_paired_t_test(self, var_name, roi_num
                               ) -> Tuple[float, float]:
        """Perform T-test on single ROI.
        Args:
            var_name: Name of the variable (column of dataframe) to use.
            roi_group: list of roi numbers as a group.

        Returns:
            t-statistic, p-value
        """
        pre_values = [
            df.loc[roi_num, var_name] for df in self.pre_dfs.values()
        ]
        post_values = [
            df.loc[roi_num, var_name] for df in self.post_dfs.values()
        ]
        t_stat, two_sided_p_value = self.stats.ttest_rel(
            a=pre_values,
            b=post_values
        )
        return t_stat, two_sided_p_value

class PairedTTest:
    from scipy import stats

    def __init__(self,
                 pre: List[Union[str, Path]],
                 post: List[Union[str, Path]],
                 n_rois: int,
                 fill_missing_roi: bool = True) -> None:
        """Perform Paired T-test
        Args:
            pre: list of paths of pre or group 1 csv data files.
            post: list of paths of post or group 2 csv data files.
            n_rois: Total number of ROIs present in the data.
                Make sure the ROI's numbering starts from 1 and consecutive.
            fill_missing_roi: if True, fill missing values with mean of the
                column.
        """
        # load data and set `roi_num` as index
        self.pre_dfs = self._load_data_safely(pre, fill_missing_roi, n_rois)
        self.post_dfs = self._load_data_safely(post, fill_missing_roi, n_rois)

        # set `roi_num` as index
        self.pre_dfs = {
            name: df.set_index('roi_num')
            for name, df in self.pre_dfs.items()
        }
        self.post_dfs = {
            name: df.set_index('roi_num')
            for name, df in self.post_dfs.items()
        }

        # Check if all dataframes are of same size
        size = [df.shape[0] == n_rois for name, df in self.pre_dfs.items()]
        _errmsg = f"All files must be of same size. Found {size}"
        assert all(size) == True, _errmsg

        # stack all subjects in an array

        self.n_rois = n_rois

    def run_roi(self,
                var_names: list,
                roi_num: Union[None, str, int, list],
                combine: bool = False
                ) -> dict:
        """Perform paired T-test on the given variable(s) collectively

        Args:
            var_names: list of column name(s) of the variable to
                perform T-test.
            roi_num: ROI number i.e. specific brain region.
                Pass an integer, 'all', or list of rois.
                Where `all` means perform t-test on all regions one-by-one.
            combine: If True, perform t-test on all variables and roi
                combined. If False, perform t-test all variables and for
                each roi separately
        Returns:
            dict containing t-statistic and p-value
        """
        # Pre and post data shapes must be (n_subjects, n_rois, n_variables)
        if isinstance(roi_num, str):
            if roi_num == 'all':
                pre_data, post_data = self._get_selected_roi_num_data(
                    roi_num,
                    var_names
                )
            else:
                try:
                    roi_num = int(roi_num)
                    if roi_num == 0:
                        raise ValueError("ROI number must be > 0.")
                    pre_data, post_data = self._get_selected_roi_num_data(
                        roi_num,
                        var_names
                    )
                except ValueError:
                    _errmsg = "`roi_num` must be an integer > 0 or `all`. "
                    _errmsg += f"Found roi_num = {roi_num}."
                    raise ValueError(_errmsg)
        elif isinstance(roi_num, (list, int)):
            if isinstance(roi_num, int) and (roi_num == 0):
                raise ValueError("ROI number must be > 0.")
            pre_data, post_data = self._get_selected_roi_num_data(
                roi_num,
                var_names)

        # number of subjects
        assert len(self.pre_dfs) == pre_data.shape[0]
        assert len(self.post_dfs) == post_data.shape[0]
        assert pre_data.shape == post_data.shape

        # Perform paired T-test
        if combine:
            t_stat, two_sided_p_value = self.stats.ttest_rel(
                a=pre_data.flatten(),
                b=post_data.flatten()
            )
            ret_dict = {
                't_stat': t_stat,
                'two_sided_p_value': two_sided_p_value,
                'p_value': two_sided_p_value / 2,
            }
        else:
            if isinstance(roi_num, list):
                ret_dict = {}
                for i, _roi in enumerate(roi_num):
                    t_stat, two_sided_p_value = self.stats.ttest_rel(
                        a=pre_data[:, i, :].flatten(),  # per ROI
                        b=post_data[:, i, :].flatten()
                    )
                    ret_dict[_roi] = {
                        't_stat': t_stat,
                        'two_sided_p_value': two_sided_p_value,
                        'p_value': two_sided_p_value / 2,
                    }
            elif roi_num == 'all':
                ret_dict = {}
                for i, _roi in enumerate(range(1, self.n_rois+1)):
                    t_stat, two_sided_p_value = self.stats.ttest_rel(
                        a=pre_data[:, i, :].flatten(),  # per ROI
                        b=post_data[:, i, :].flatten()
                    )
                    ret_dict[_roi] = {
                        't_stat': t_stat,
                        'two_sided_p_value': two_sided_p_value,
                        'p_value': two_sided_p_value / 2,
                    }
            else:
                # assert len(pre_data.shape) == 2
                t_stat, two_sided_p_value = self.stats.ttest_rel(
                    a=pre_data.flatten(),  # per ROI
                    b=post_data.flatten()
                )
                ret_dict = {
                    't_stat': t_stat,
                    'two_sided_p_value': two_sided_p_value,
                    'p_value': two_sided_p_value / 2,
                }
        return ret_dict

    def run_roi_groups(self,
                       var_names: list,
                       roi_groups: Union[None, Dict[int, list]]) -> dict:
        """Perform paired T-test on the given variable

        Args:
            var_names: list of column name(s) of the variable to
                perform T-test.
            roi_groups: Apply paried T-test on the groups of ROIs.
                There will be one p-value per group.
        """
        ret_dict = {}
        for grp_num, roi_list in roi_groups.items():
            results = self.run_roi(
                var_names=var_names,
                roi_num=roi_list,
                combine=True
            )
            results['group_p_value'] = results['p_value']
            # Normalize p_value
            results['p_value'] = results['group_p_value'] / len(roi_list)
            ret_dict[grp_num] = results
        return ret_dict

    def _load_data_safely(self,
                          paths_list:  List[Union[str, Path]],
                          fill_missing_roi: bool,
                          n_rois: int):
        """Check and fix data before testing"""
        dfs = {}
        for p in paths_list:
            df = pd.read_csv(p)
            try:
                if fill_missing_roi:
                    df = fill_missing_roi_values(df, n_rois)
            except ValueError as e:
                print(e)
                raise ValueError(f"Error @ `{p}`")

            if df.shape[0] != n_rois:
                _errmsg = f"# ROIs in {p} != n_rois ({df.shape[0]} != {n_rois})."
                _errmsg += " set `fill_missing_roi = True` to fill missing values"
                raise ValueError(_errmsg)
            dfs[Path(p).stem] = df
        return dfs

    def _get_selected_roi_num_data(
        self,
        roi_num: Union[str, int, list],
        var_names: List[str]
    ) -> Tuple[np.ndarray, np.ndarray]:
        """Get selected ROIs data from subject dataframes in np.array format
        """
        if roi_num == 'all':
            pre_data = np.array([
                s[var_names].values
                for s in self.pre_dfs.values()
            ])
            post_data = np.array([
                s[var_names].values
                for s in self.post_dfs.values()
            ])
        else:
            pre_data = np.array([
                s[var_names].loc[roi_num].values
                for s in self.pre_dfs.values()
            ])
            post_data = np.array([
                s[var_names].loc[roi_num].values
                for s in self.post_dfs.values()
            ])
        return pre_data, post_data


# -*- coding: utf-8 -*-
import os
import numpy as np
import pandas as pd
import tensorflow as tf
import tensorflow_addons as tfa
from PIL import Image

class Dataset:
    """
    Class handling tf_dataset creation for a segmentation dataset from two
    directories, containing 2D images and corresponding labels as png.

    All images in image_dir have to have a label with the same filename in
    label_dir. Images which do not have a corresponding label file in
    label_dir are assumed to be test images.
    This class can split these images in train/val folds and optionally
    normalise them. The way categories are calculated from label images can
    be changed in the function _load_label_images.

    Usage: An example on how to use this class can be found in experiment.py
    """
    def __init__(self, image_dir, label_dir, val_ratio=0.2,
                 cross_validation=False, n_folds=None, normalise=False,
                 ignore=None):
        """
        :param image_dir: string, directory where images can be found
        :param label_dir: string, directory where labels can be found -
        labels are expected to have the same name as corresponding image.
        :param val_ratio: float, ratio of samples with existing groundtruth to
        be used as validation set
        :param cross_validation: bool, whether to calculate crossvalidation
        folds
        :param n_folds: int, number of folds for crossvalidation
        :param normalise: whether to normalise images when loading
        :param ignore: list, image names to be ignored (the corresponding labels
        will automatically be ignored)
        """
        self.image_dir = image_dir
        self.label_dir = label_dir
        self.val_ratio = val_ratio
        self.cross_validation = cross_validation
        self.n_folds = n_folds

        self.img_shape = None
        self.ignore = ignore or []
        self.normalise = normalise
        self.split_df = self._calculate_data_split(self.val_ratio,
                                                   self.cross_validation,
                                                   self.n_folds)

    def _calculate_data_split(self, val_ratio=0.2, cross_validation=False,
                              n_folds=None):
        """
        Split dataset into purpose (train/val/test) or crossvalidation folds
        and test.

        :param val_ratio:  ratio of samples with existing groundtruth to be used
        as validation set, ignored if cross_validation=True
        :param cross_validation: whether to calculate crossvalidation folds
        :param n_folds: number of folds for crossvalidation
        :return: dataframe with entries for each sample and its corresponding
        purpose / fold.
        """
        if not cross_validation:
            if not (0 <= val_ratio <= 1):
                raise ValueError('Please choose a val_ratio between 0 and 1.')
        else:
            if type(n_folds) is not int:
                raise TypeError('Only integers are allowed for n_folds.')

        # fix seed to ensure reproducible results
        np.random.seed(1234)

        img_list = list(os.walk(self.image_dir))[0][2]
        label_list = list(os.walk(self.label_dir))[0][2]

        # remove samples to be ignored
        for name in self.ignore:
            img_list.remove(name)
            label_list.remove(name)

        # test images are missing corresponding labels with same name as image
        is_test = np.array([img not in label_list for img in img_list])

        split_df = pd.DataFrame(data={'img_name': img_list})
        test_idx = np.where(is_test)[0]
        split_df.loc[test_idx, 'purpose'] = 'test'

        if not cross_validation:
            self.n_val = int(val_ratio * len(label_list))
            self.n_train = len(label_list) - self.n_val
            # indices available for training and validation
            train_val_idx = np.where(~is_test)[0]
            # choose training indices randomly
            train_idx = np.random.choice(train_val_idx, self.n_train,
                                         replace=False)
            # take remaining indices for validation
            val_idx = np.setdiff1d(train_val_idx, train_idx)
            split_df.loc[train_idx, 'purpose'] = 'train'
            split_df.loc[val_idx, 'purpose'] = 'val'
        else:
            # choose indices for folds of crossvalidation
            n_train_samples = len(split_df) - len(test_idx)
            self.n_sample_per_fold = int(n_train_samples / n_folds)
            split_df.loc[:, 'fold'] = None
            for i in range(n_folds-1):
                unassigned_idx = np.where(split_df.fold.isnull())[0]
                available_idx = np.setdiff1d(unassigned_idx, test_idx)
                # choose fold indices randomly from remaining indices
                fold_idx = np.random.choice(available_idx,
                                            self.n_sample_per_fold,
                                            replace=False)
                split_df.loc[fold_idx, 'fold'] = i

            # take remaining samples for last fold
            unassigned_idx = np.where(split_df.fold.isnull())[0]
            remaining_idx = np.setdiff1d(unassigned_idx, test_idx)
            split_df.loc[remaining_idx, 'fold'] = i + 1

        return split_df

    def create_tf_dataset(self, purpose=None, cross_validation=False, fold=None,
                          return_stats=False):
        """
        Create a tensorflow dataset object, containing the images specified in
        purpose/fold.

        :param purpose: string, 'train'/'val'/'test'
        :param cross_validation: bool, whether to get crossvalidation folds
        :param fold: int, fold for crossvalidation
        :param return_stats: bool, whether to return class_ratios as list
        :return: tensorflow dataset (, class_ratio)
        """
        np_images = self._load_images(purpose, cross_validation, fold) / 255
        np_labels, class_ratio = self._load_labels(purpose,
                                                   cross_validation,
                                                   fold,
                                                   return_stats=True)

        tf_images = tf.convert_to_tensor(np_images, dtype=tf.float32)
        tf_labels = tf.convert_to_tensor(np_labels, dtype=tf.float32)

        tf_set = tf.data.Dataset.from_tensor_slices({'image': tf_images,
                                                     'label': tf_labels
                                                     })

        if return_stats:
            return tf_set, class_ratio
        else:
            return tf_set

    def _load_images(self, purpose=None, cross_validation=False, fold=None):
        """
        Load all images with specified properties as one numpy array.

        For documentation on properties see self._filter_df.
        :param purpose: string, 'train'/'val'/'test'
        :param cross_validation: bool, whether to get crossvalidation folds
        :param fold: int, fold for crossvalidation
        :return: numpy array, shape (n_sample, x, y, n_channel)
        """
        filtered_df = self._filter_df(purpose, cross_validation, fold)
        images = []
        for path in filtered_df.img_name:
            img = Image.open(os.path.join(self.image_dir, path)).convert('RGB')
            if self.normalise:
                img = tf.keras.utils.normalize(img)
            images.append(img)

        stack = np.stack(images)
        self.img_shape = stack.shape[1:]

        return stack

    def _load_labels(self, purpose=None, cross_validation=False, fold=None,
                     return_stats=False):
        """
        Load all labels with specified properties as one numpy array.

        For documentation on properties see self._filter_df.
        :param purpose: string,  'train'/'val'/'test'
        :param cross_validation: bool, whether to get crossvalidation folds
        :param fold: int, fold for crossvalidation
        :param return_stats: bool, whether to return ratio of different labels
        over all loaded data
        :return: numpy array, shape (n_samples, x, y, 1)
        or tuple of numpy array, class_ratios if return_stats is True
        """
        if purpose == 'test':
            raise AttributeError('Test images have no corresponding label.')

        filtered_df = self._filter_df(purpose, cross_validation, fold)
        labels = []
        for path in filtered_df.img_name:
            img_path = os.path.join(self.label_dir, path)
            label_img = Image.open(img_path).convert(mode='L')
            label = np.array(label_img)
            # assume three classes: pixel == 0, pixel == 2, and everything else
            label_mask = np.zeros_like(label)
            label_mask[(0 < label) & (label < 255)] = 1
            label_mask[label == 255] = 2
            label_mask = np.expand_dims(label_mask.astype('int32'), axis=-1)
            labels.append(label_mask)

        label_stack = np.stack(labels)

        if not return_stats:
            return label_stack

        class_count = np.bincount(label_stack.astype('int').flatten())
        class_ratio = class_count / np.size(label_stack)
        return label_stack, class_ratio

    def _filter_df(self, purpose=None, cross_validation=False, fold=None):
        """
        Filter dataframe with all samples for specified properties.

        Purpose is ignored, when cross_validation=True
        :param purpose: one of 'train'/'val'/'test'
        :param cross_validation: whether to use cross validation folds
        :param fold: crossvalidation fold to filter for
        :return: dataframe containing only filtered entries
        """
        if cross_validation:
            assert type(fold) is int
            filtered_df = self.split_df[self.split_df.fold == fold]
        else:
            assert type(purpose) is str
            filtered_df = self.split_df[self.split_df.purpose == purpose]
        return filtered_df

class DataAugmenter:
    """
    Class handling data augmentation for a tf_dataset.

    Usage: An example on how to use this class can be found in experiment.py
    """
    def __init__(self, flip_left_right=0.5, flip_up_down=0.5,
                 brightness=True, gaussian=0.2, gaussian_std=0.03,
                 rotate_prob=0.2, rotate_range=90):
        """
        :param flip_left_right: float, probability for doing a left-right flip
        for data augmentation
        :param flip_up_down: float, probability for doing a up_down flip for
        data augmentation
        :param brightness: bool, whether to do brightness augmentation on image
        :param gaussian: float, probability for adding gaussian noise to image
        as data augmentation
        :param gaussian_std: float, standard deviation for gaussian noise,
        only considered if gaussian > 0
        :param rotate_prob: float, probability for rotating data as augmentation
        :param rotate_range: float, if rotate_prob > 0, data will be rotated by
        a random angle in [-rotate_range, rotate_range] in degree.
        """
        self.flip_left_right = flip_left_right
        self.flip_up_down = flip_up_down
        self.brightness = brightness
        self.gaussian = gaussian
        self.gaussian_std = gaussian_std
        self.rotate_prob = rotate_prob
        self.rotate_range = rotate_range

    @tf.function
    def augment_train_images(self, datapoint):
        """
        Augment a datapoint consisting of an image and corresponding label.

        Augmentation functions are specified for class.
        :param datapoint: dictionary for one datapoint. Needs keys 'image' and
        'label'. Images and labels can be numpy arrays or tf.Tensor objects.
        :return: tuple augmented image, augmented label
        """
        # take arguments as class functions
        img = datapoint['image']
        label = datapoint['label']

        if self.flip_left_right:
            do_flip = tf.random.uniform([]) < self.flip_left_right
            img = tf.cond(do_flip,
                          lambda: tf.image.flip_left_right(img),
                          lambda: img)
            label = tf.cond(do_flip,
                            lambda: tf.image.flip_left_right(label),
                            lambda: label)

        if self.flip_up_down:
            do_flip = tf.random.uniform([]) < self.flip_up_down
            img = tf.cond(do_flip,
                          lambda: tf.image.flip_up_down(img),
                          lambda: img)
            label = tf.cond(do_flip,
                            lambda: tf.image.flip_up_down(label),
                            lambda: label)

        if self.brightness:
            do_bright = tf.random.uniform([]) < self.brightness
            img = tf.cond(do_bright,
                          lambda: tf.image.random_brightness(img,
                                                             max_delta=0.1),
                          lambda: img)

        if self.gaussian:
            do_noise = tf.random.uniform([]) < self.gaussian
            std = tf.random.normal(shape=[1], stddev=self.gaussian_std)
            noise = tf.random.normal(shape=tf.shape(img), stddev=std)
            img = tf.cond(do_noise, lambda: tf.add(img, noise), lambda: img)
            img = tf.clip_by_value(img, 0.0, 1.0)

        if self.rotate_prob > 0:
            angle = tf.random.uniform([],
                                      minval=-self.rotate_range,
                                      maxval=self.rotate_range)
            do_rotate = tf.random.uniform([]) < self.rotate_prob
            img = tf.cond(do_rotate,
                          lambda: tfa.image.rotate(img, angle,
                                                   interpolation='BILINEAR'),
                          lambda: img)
            label = tf.cond(do_rotate,
                            lambda: tfa.image.rotate(label, angle,
                                                     interpolation='NEAREST'),
                            lambda: label)

        return img, label

    @tf.function
    def load_validation_images(self, datapoint):
        """
        Load a datapoint without any augmentations.

        :param datapoint: dictionary for one datapoint. Needs keys 'image' and
        'label'. Images and labels can be numpy arrays or tf.Tensor objects.
        :return: tuple image, label
        """
        return datapoint['image'], datapoint['label']


from rest_framework import serializers

from .models import Review

class ReviewSerializer(serializers.ModelSerializer):
    """Serializer for Review obj"""
    reviewer = serializers.HiddenField(
        default=serializers.CurrentUserDefault()
    )

    class Meta:
        model = Review
        fields = ('id', 'rating', 'title', 'company', 'reviewer', 'summary')
        read_only_fields = ('id',)


import os
import numpy as np
import torch
import torchvision
from torch import nn
from torchinfo import summary
import matplotlib.pyplot as plt
from glob import glob

''' SEED Everything '''
from src.utils import seed_everything
seed_everything(seed=42)
print("Using Torch", torch.__version__, 'and Torchvision:', torchvision.__version__)

''' Load training data '''
root_dir        = 'path/to/dataset/dir/'
train_img_dir   = root_dir + '/train_data/images'       # train images inside this dir
train_gt_dir    = root_dir + '/train_data/ground-truth' # train GTs inside this dir
test_img_dir    = root_dir + '/test_data/images'        # test images inside this dir
test_gt_dir     = root_dir + '/test_data/ground-truth'  # test GTs inside this dir
train_img_paths = glob(train_img_dir + '/*.jpg')
test_img_paths  = glob(test_img_dir + '/*.jpg')
train_gt_paths  = glob(train_gt_dir + '/*.mat')
test_gt_paths   = glob(test_gt_dir + '/*.mat')
train_img_paths.sort(key=lambda f: int('_'.join(filter(str.isdigit, f))))
test_img_paths.sort(key=lambda f: int('_'.join(filter(str.isdigit, f))))
train_gt_paths.sort(key=lambda f: int('_'.join(filter(str.isdigit, f))))
test_gt_paths.sort(key=lambda f: int('_'.join(filter(str.isdigit, f))))

''' Create dataset '''
from src.Dataset import CrowdDataset2 as CrowdDataset
img_size   = (800, 800, 3) # size of the input image
gt_size    = (200, 200)  # size of the density map
sigma      = 10 # Gaussian kernal
batch_size = 2
num_workers= 1
train_ds   = CrowdDataset(train_img_paths, train_gt_paths, img_size, gt_size, sigma=sigma, augmentation=True)
test_ds    = CrowdDataset(test_img_paths, test_gt_paths, img_size, gt_size, sigma=sigma, augmentation=False)
train_dl   = torch.utils.data.DataLoader(train_ds, batch_size=batch_size, num_workers=num_workers, pin_memory=True, shuffle=True)
test_dl    = torch.utils.data.DataLoader(test_ds,  batch_size=1, num_workers=num_workers, pin_memory=True, shuffle=False)

###############  Taking a subset for test (Comment the below three lines to use full dataset)
from torch.utils.data import Subset
indices    = torch.randint(low=0, high=20, size=(32,))
train_ds   = Subset(train_ds, indices)
test_ds    = Subset(test_ds, indices)

from src.models.CSRNet import CSRNet
# torch.backends.cudnn.enabled   = True
# torch.backends.cudnn.benchmark = True

''' Define crowd counting model '''
device          = torch.device("cuda:1" if torch.cuda.is_available() else "cpu")
model           = CSRNet().to(device)
model_name      = model.__class__.__name__
optimizer       = torch.optim.Adam(model.parameters(), lr=0.0001, betas=(0.9, 0.999), eps=1e-08, weight_decay=0, amsgrad=False)
n_epochs        = 100
weights         = None # Define path to model weights if want to load for finetuning
# weights         = f'{os.getcwd()}/checkpoints/{model_name}_{ds_name}.pth'
checkpoint      = f'{os.getcwd()}/checkpoints/{model_name}.pth'
val_metric_best = np.Inf
params          = {'model': model,
                   'train_dl':train_dl,
                   'val_dl': test_dl,
                   'optimizer': optimizer,
                   'n_epochs': n_epochs,
                   'weights': weights,
                   'checkpoint': checkpoint,
                   'val_metric_best': val_metric_best,
                   'device': device
                   }
print(f'Models will be saved to >>>> {checkpoint}')

''' Start training '''
from src.trainer import Trainer
trainer = Trainer(params)
history = trainer.fit()


# implementing a queue for animal shelter

class Queue:
    def __init__(self):
        self.list = []

    def enqueue(self, animal):
        self.list.append(animal)
        return 'The animal has been successfully added'

    def dequeue_dog(self):
        # find the first dog
        for i,n in enumerate(self.list):
            if n == 'dog':
                return self.list.pop(i)
        return "No dogs are left"

    def dequeue_cat(self):
        # find the first dog
        for i,n in enumerate(self.list):
            if n == 'cat':
                return self.list.pop(i)
        return "No cats are left"

    def dequeue_any(self):
        if len(self.list) > 0:
            return self.list.pop(0)
        else:
            return "No animal in the shelter"

q = Queue()

q.enqueue('cat')
q.enqueue('cat')
q.enqueue('cat')
q.enqueue('dog')
q.enqueue('cat')
q.enqueue('cat')
q.dequeue_dog()


from typing import List

from polyaxon._contexts import paths as ctx_paths

def get_artifacts_store_args(artifacts_path: str, clean: bool) -> str:
    get_or_create = 'if [ ! -d "{dir}" ]; then mkdir -m 0777 -p {dir}; fi;'.format(
        dir=artifacts_path
    )
    delete_dir = (
        'if [ -d {path} ] && [ "$(ls -A {path})" ]; '
        "then rm -R {path}/*; fi;".format(path=artifacts_path)
    )
    if clean:
        return "{} {}".format(get_or_create, delete_dir)
    return "{}".format(get_or_create)

def init_artifact_context_args(run_path: str) -> List[str]:
    return [
        'if [ ! -d "{dir}" ]; then mkdir -m 0777 -p {dir}; fi;'.format(
            dir=ctx_paths.CONTEXT_MOUNT_ARTIFACTS_FORMAT.format(run_path)
        ),
        'if [ ! -d "{dir}" ]; then mkdir -m 0777 -p {dir}; fi;'.format(
            dir=ctx_paths.CONTEXT_MOUNT_ARTIFACTS_FORMAT.format(run_path) + "/outputs"
        ),
    ]


import pygame, sys
from settings import *
from level import Level
from player import Player

# pygame setup ======================================
pygame.init()
screen = pygame.display.set_mode(RES, vsync=1)
clock = pygame.time.Clock()

# Game setup ========================================
background = pygame.image.load('bg_minecraft.jpg').convert()

level = Level()

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

        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_SPACE:
                level.player.jump()

    # Draw - Update =================================
    screen.blit(background, (0,0))

    level.run()

# pygame setup ======================================
    pygame.display.update()
    clock.tick(60)
    pygame.display.set_caption(f'fps: {clock.get_fps():.0f}          Platformer')


import sys
sys.stdin = open("input.txt")

N = int(input())                      # N : 토핑의 종류의 수
A, B = map(int,input().split())       # A : 도우가격 , B : 토핑가격
C = int(input())                      # C : 도우 열량
Dlst = []                             # D : 토핑의 열량들

for _ in range(N):
    D = int(input())
    Dlst.append(D)

Dlst.sort(reverse=True)
# 피자가격 p = A + B*N
# 피자열량 cal = C + sum(Dlst)
# res = cal / p
ans = C / A

for i in range(1,N+1):
    cal = C + sum(Dlst[0:i])
    p = A + B*i
    res = cal / p

    if res > ans:
        ans = res
    else:
        pass

print(int(ans))


class Solution:
    def findLonelyPixel(self, picture: List[List[str]]) -> int:
        m, n = len(picture), len(picture[0])
        row, col = [0] * m, [0] * n
        for i in range(m):
            for j in range(n):
                if picture[i][j] == 'B':
                    row[i] += 1
                    col[j] += 1

        count = 0
        for i in range(m):
            for j in range(n):
                if picture[i][j] == 'B' and row[i] == 1 and col[j] == 1:
                    count += 1

        return count


from random import randint  #Importação de biblioteca para a geração de números pseudo-aleatórios

class Ship(object):

    def __init__(self):  # Construtor do navio
        self.ID = randint(1000, 9999)  # O navio possui um ID
        self.numberCont = randint(1, 16) # O navio possui de 1 a 16 conteiners
        self.averageWait = 0  # Tempo médio de espera do navio na fila
        self.stack1 = [] # Cada pilha tem a capacidade maxima de 4 conteiners
        self.stack2 = []
        self.stack3 = []
        self.stack4 = []

        # Distribuindo os conteiners pelas pilhas
        turn = 1
        for i in range(0, self.numberCont):
            if turn == 1:
                self.stack1.append(1)  # Número 1 representa um conteiner na pilha
                turn = 2
            elif turn == 2:
                self.stack2.append(1)
                turn = 3
            elif turn == 3:
                self.stack3.append(1)
                turn = 4
            elif turn == 4:
                self.stack4.append(1)
                turn = 1


#!/usr/bin/env python3
"""
This module sets up a basic Flask app with a single route.
"""
from typing import Any
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index() -> Any:
    """
    Render the index.html template.
    """
    return render_template('0-index.html')

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)