from collections import OrderedDict
import warnings

from .arraystep import ArrayStepShared
from ..model import modelcontext, inputvars
import theano.tensor as tt
from ..theanof import tt_rng, make_shared_replacements
import theano

__all__ = []

EXPERIMENTAL_WARNING = "Warning: Stochastic Gradient based sampling methods are experimental step methods and not yet"\
    " recommended for use in PyMC3!"

def _value_error(cond, str):
    """Throws ValueError if cond is False"""
    if not cond:
        raise ValueError(str)

def _check_minibatches(minibatch_tensors, minibatches):
    _value_error(
        isinstance(minibatch_tensors, list),
        'minibatch_tensors must be a list.')

    _value_error(
        hasattr(minibatches, "__iter__"), 'minibatches must be an iterator.')

def prior_dlogp(vars, model, flat_view):
    """Returns the gradient of the prior on the parameters as a vector of size D x 1"""
    terms = tt.concatenate(
        [theano.grad(var.logpt, var).flatten() for var in vars], axis=0)
    dlogp = theano.clone(terms, flat_view.replacements, strict=False)

    return dlogp

def elemwise_dlogL(vars, model, flat_view):
    """
    Returns Jacobian of the log likelihood for each training datum wrt vars
    as a matrix of size N x D
    """
    # select one observed random variable
    obs_var = model.observed_RVs[0]
    # tensor of shape (batch_size,)
    logL = obs_var.logp_elemwiset.sum(
        axis=tuple(range(1, obs_var.logp_elemwiset.ndim)))
    # calculate fisher information
    terms = []
    for var in vars:
        output, _ =  theano.scan(lambda i, logX=logL, v=var: theano.grad(logX[i], v).flatten(),\
                           sequences=[tt.arange(logL.shape[0])])
        terms.append(output)
    dlogL = theano.clone(
        tt.concatenate(terms, axis=1), flat_view.replacements, strict=False)
    return dlogL

class BaseStochasticGradient(ArrayStepShared):
    R"""
    BaseStochasticGradient Object

    For working with BaseStochasticGradient Object
    we need to supply the probabilistic model
    (:code:`model`) with the data supplied to observed
    variables of type `GeneratorOp`

    Parameters
    ----------
    vars : list
        List of variables for sampler
    batch_size`: int
        Batch Size for each step
    total_size : int
        Total size of the training data
    step_size : float
        Step size for the parameter update
    model : PyMC Model
        Optional model for sampling step. Defaults to None (taken from context)
    random_seed : int
        The seed to initialize the Random Stream
    minibatches : iterator
        If the ObservedRV.observed is not a GeneratorOp then this parameter must not be None
    minibatch_tensor : list of tensors
        If the ObservedRV.observed is not a GeneratorOp then this parameter must not be None
        The length of this tensor should be the same as the next(minibatches)

    Notes
    -----
    Defining a BaseStochasticGradient needs
    custom implementation of the following methods:
        - :code: `.mk_training_fn()`
            Returns a theano function which is called for each sampling step
        - :code: `._initialize_values()`
            Returns None it creates class variables which are required for the training fn
    """

    def __init__(self,
                 vars=None,
                 batch_size=None,
                 total_size=None,
                 step_size=1.0,
                 model=None,
                 random_seed=None,
                 minibatches=None,
                 minibatch_tensors=None,
                 **kwargs):
        warnings.warn(EXPERIMENTAL_WARNING)

        model = modelcontext(model)

        if vars is None:
            vars = model.vars

        vars = inputvars(vars)

        self.model = model
        self.vars = vars
        self.batch_size = batch_size
        self.total_size = total_size
        _value_error(
            total_size != None or batch_size != None,
            'total_size and batch_size of training data have to be specified')
        self.expected_iter = int(total_size / batch_size)

        # set random stream
        self.random = None
        if random_seed is None:
            self.random = tt_rng()
        else:
            self.random = tt_rng(random_seed)

        self.step_size = step_size

        shared = make_shared_replacements(vars, model)

        self.updates = OrderedDict()
        self.q_size = int(sum(v.dsize for v in self.vars))

        flat_view = model.flatten(vars)
        self.inarray = [flat_view.input]

        self.dlog_prior = prior_dlogp(vars, model, flat_view)
        self.dlogp_elemwise = elemwise_dlogL(vars, model, flat_view)
        self.q_size = int(sum(v.dsize for v in self.vars))

        if minibatch_tensors != None:
            _check_minibatches(minibatch_tensors, minibatches)
            self.minibatches = minibatches

            # Replace input shared variables with tensors
            def is_shared(t):
                return isinstance(t, theano.compile.sharedvalue.SharedVariable)

            tensors = [(t.type() if is_shared(t) else t)
                       for t in minibatch_tensors]
            updates = OrderedDict({
                t: t_
                for t, t_ in zip(minibatch_tensors, tensors) if is_shared(t)
            })
            self.minibatch_tensors = tensors
            self.inarray += self.minibatch_tensors
            self.updates.update(updates)

        self._initialize_values()
        super().__init__(vars, shared)

    def _initialize_values(self):
        """Initializes the parameters for the stochastic gradient minibatch
        algorithm"""
        raise NotImplementedError

    def mk_training_fn(self):
        raise NotImplementedError

    def training_complete(self):
        """Returns boolean if astep has been called expected iter number of times"""
        return self.expected_iter == self.t

    def astep(self, q0):
        """Perform a single update in the stochastic gradient method.

        Returns new shared values and values sampled
        The size and ordering of q0 and q must be the same
        Parameters
        -------
        q0: list
            List of shared values and values sampled from last estimate

        Returns
        -------
        q
        """
        if hasattr(self, 'minibatch_tensors'):
            return q0 + self.training_fn(q0, *next(self.minibatches))
        else:
            return q0 + self.training_fn(q0)


class Solution:
    def minCostClimbingStairs(self, cost: List[int]) -> int:
        a, b, c = 0,0,0

        for i in range(len(cost)-1, -1, -1):
            a = cost[i] + min(b, c)
            c = b
            b = a

        return min(b, c)


""" Actor for rodario framework """

# stdlib
import atexit
from uuid import uuid4
from time import sleep
from threading import Thread, Event
import pickle
import inspect

# local
from rodario import get_redis_connection
from rodario.registry import Registry
from rodario.exceptions import UUIDInUseException

REGISTRY = Registry()

# pylint: disable=E1101
class Actor(object):

    """ Base Actor class """

    #: Threading Event to tell the message handling loop to die
    # (needed in __del__ so must be defined here)
    _stop = None
    #: Redis PubSub client
    _pubsub = None

    def __init__(self, uuid=None):
        """
        Initialize the Actor object.

        :param str uuid: Optionally-provided UUID
        """

        atexit.register(self.__del__)
        self._stop = Event()
        #: Separate Thread for handling messages
        self._proc = None
        #: Redis connection
        self._redis = get_redis_connection()
        # pylint: disable=E1123
        self._pubsub = self._redis.pubsub(ignore_subscribe_messages=True)

        if uuid:
            self.uuid = uuid
        else:
            self.uuid = str(uuid4())

        if not REGISTRY.exists(self.uuid):
            REGISTRY.register(self.uuid)
        else:
            self.uuid = None
            raise UUIDInUseException('UUID is already taken')

    def __del__(self):
        """ Clean up. """

        if hasattr(self, 'uuid'):
            REGISTRY.unregister(self.uuid)

        self.stop()

    @property
    def is_alive(self):
        """
        Return True if this Actor is still alive.

        :rtype: :class:`bool`
        """

        return not self._stop.is_set()

    def _handler(self, message):
        """
        Send proxied method call results back through pubsub.

        :param tuple message: The message to dissect
        """

        data = pickle.loads(message['data'])

        if not data[2]:
            # empty method call; bail out
            return

        # call the function and respond to the proxy object with return value
        uuid = data[0]
        proxy = data[1]
        func = getattr(self, data[2])
        result = (uuid, func(*data[3], **data[4]))
        self._redis.publish('proxy:%s' % proxy, pickle.dumps(result))

    def _get_methods(self):
        """
        List all of this Actor's methods (for creating remote proxies).

        :rtype: :class:`list`
        """

        methods = inspect.getmembers(self, predicate=callable)
        method_list = set()

        for name, _ in methods:
            if (name in ('proxy', 'start', 'stop', 'part', 'join',)
                    or name[0] == '_'):
                continue

            method_list.add(name)

        return method_list

    def join(self, channel, func=None):
        """
        Join this Actor to a pubsub cluster channel.

        :param str channel: The channel to join
        :param callable func: The message handler function
        """

        self._pubsub.subscribe(**{'cluster:%s' % channel: func
                                                          if func is not None
                                                          else self._handler})

    def part(self, channel):
        """
        Remove this Actor from a pubsub cluster channel.

        :param str channel: The channel to part
        """

        self._pubsub.unsubscribe('cluster:%s' % channel)

    def proxy(self):
        """
        Wrap this Actor in an ActorProxy object.

        :rtype: :class:`rodario.actors.ActorProxy`
        """

        # avoid cyclic import
        proxy_module = __import__('rodario.actors', fromlist=('ActorProxy',))

        return proxy_module.ActorProxy(self)

    def start(self):
        """ Fire up the message handler thread. """

        def pubsub_thread():
            """ Call get_message in loop to fire _handler. """

            while not self._stop.is_set():
                self._pubsub.get_message()
                sleep(0.01)

        # subscribe to personal channel and fire up the message handler
        self._pubsub.subscribe(**{'actor:%s' % self.uuid: self._handler})
        self._proc = Thread(target=pubsub_thread)
        self._proc.daemon = True
        self._proc.start()

    def stop(self):
        """ Kill the message handler thread. """

        self._stop.set()


def printRuntime(seconds,finished=False):
    seconds = int(seconds)
    status = 'has been running for'
    if finished == True:
        status = 'finished in'

    if seconds < 60:
        print('The script {} {} seconds'.format(status,seconds))
        return
    elif seconds < 3600:
        minutes = seconds // 60
        seconds = seconds - 60*minutes
        print('The script {} {} minutes & {} seconds'.format(status,minutes,seconds))
        return
    else:
        hours = seconds // 3600
        minutes = (seconds - 3600*hours) // 60
        seconds = seconds - 3600*hours - 60*minutes
        print('The script {} {} hours, {} minutes & {} seconds'.format(status,hours,minutes,seconds))
        return

import time
startTime = time.time()


running = True
pokedex = {} # {name : description, name: description...}
while (running):
    try:
        comand, name = input().split(" ")

        if (comand == "ADD"):
            if (name in pokedex.keys()):
                print("Pokémon já adicionado na Pokédex")
            else:
                description = input()
                pokedex[name] = description
                print("Pokémon adicionado com sucesso")
        elif (comand == "DESC"):
            if (name not in pokedex.keys()):
                print("Ainda não há registro desse Pokémon")
            else:
                print(pokedex[name])
    except EOFError:
        running = False


class BootStrapForm(object):
    bootstrap_class_exclude = []

    def __init__(self, *args, **kwargs):
        bootstrap_class_exclude = []
        super().__init__(*args, **kwargs)
        for name, field in self.fields.items():
            # 因为此时调用bootstrap_class_exclude的self是form中的ProjectModelForm生成的对象，因此bootstrap_class_exclude优先去ProjectModelForm找
            if name in self.bootstrap_class_exclude:
                continue
            old_class = field.widget.attrs.get('class', "")
            field.widget.attrs['class'] = '{} form-control'.format(old_class)
            field.widget.attrs['placeholder'] = '请输入%s' % (field.label,)


"""Cards are built using various elements."""
from typing import Any, Literal, Optional, Union

from msteams_webhooks import types
from msteams_webhooks.actions import Action
from msteams_webhooks.base import Entity

class CardElement(Entity):
    """Base element class."""

class Image(CardElement):
    """Displays an image. Acceptable formats are PNG, JPEG, and GIF.

    Schema Explorer: https://adaptivecards.io/explorer/Image.html.
    """

    def __init__(
        self,
        url: str,
        *,
        alt_text: Optional[str] = None,
        background_color: Optional[str] = None,
        height: Optional[Union[str, Literal["auto", "stretch"]]] = None,
        horizontal_alignment: Optional[types.HorizontalAlignmentTypes] = None,
        select_action: Optional[Action] = None,
        size: Optional[types.ImageSizeTypes] = None,
        style: Optional[types.ImageStyleTypes] = None,
        width: Optional[str] = None,
    ) -> None:
        """Displays an image. Acceptable formats are PNG, JPEG, and GIF.

        Args:
            url: The URL to the image. Supports data URI in version 1.2+.
            alt_text: Alternate text describing the image.
            background_color: Applies a background to a transparent image.
                This property will respect the image style.
            height: The desired height of the image. If specified as a pixel value,
                ending in 'px', E.g., 50px, the image will distort to fit that exact
                height. This overrides the size property.
            horizontal_alignment: Controls how this element is horizontally positioned
                within its parent. When not specified, the value of horizontalAlignment
                is inherited from the parent container. If no parent container has
                horizontalAlignment set, it defaults to Left.
            select_action: An ``Action`` that will be invoked when the ``Image`` is tapped
                or selected. ``Action.ShowCard`` is not supported.
            size: Controls the approximate size of the image. The physical dimensions will
                vary per host.
            style: Controls how this ``Image`` is displayed.
            width: The desired on-screen width of the image, ending in 'px'. E.g., 50px.
                This overrides the size property.

        Returns:
            None.

        Raises:
            None.
        """
        self.url = url
        self.alt_text = alt_text
        self.background_color = background_color
        self.height = height
        self.horizontal_alignment = horizontal_alignment
        self.select_action = select_action
        self.size = size
        self.style = style
        self.width = width

    def serialize(self) -> dict[str, Any]:
        """Serialize object into data structure."""
        payload: dict[str, Any] = {
            "type": "Image",
            "url": self.url,
        }
        if self.alt_text:
            payload["altText"] = self.alt_text
        if self.background_color:
            payload["backgroundColor"] = self.background_color
        if self.height:
            payload["height"] = self.height
        if self.horizontal_alignment:
            payload["horizontalAlignment"] = self.horizontal_alignment
        if self.select_action:
            payload["selectAction"] = self.select_action.serialize()
        if self.size:
            payload["size"] = self.size
        if self.style:
            payload["style"] = self.style
        if self.width:
            payload["width"] = self.width
        return payload

class MediaSource(CardElement):
    """Defines a source for a Media element.

    Schema Explorer: https://adaptivecards.io/explorer/MediaSource.html
    """

    def __init__(self, url: str, *, mime_type: Optional[str] = None) -> None:
        """Defines a source for a Media element.

        Args:
            url: URL to media. Supports data URI in version 1.2+
            mime_type: Mime type of associated media (e.g. "video/mp4"). For YouTube
                and other Web video URLs, mime_type can be omitted.

        Returns:
            None.

        Raises:
            None.
        """
        self.url = url
        self.mime_type = mime_type

    def serialize(self) -> dict[str, Any]:
        """Serialize object into data structure."""
        payload: dict[str, Any] = {"url": self.url}
        if self.mime_type:
            payload["mimeType"] = self.mime_type
        return payload

class Media(CardElement):
    """Displays a media player for audio or video content.

    Schema Explorer: https://adaptivecards.io/explorer/Media.html
    """

    def __init__(
        self,
        sources: list[MediaSource],
        *,
        poster: Optional[str] = None,
        alt_text: Optional[str] = None,
    ) -> None:
        """Displays a media player for audio or video content.

        Args:
            sources: List of ``MediaSource`` elements to display.
            poster: URL of an image to display before playing. Supports data URI in version 1.2+.
                If poster is omitted, the Media element will either use a default poster
                (controlled by the host application) or will attempt to automatically pull
                the poster from the target video service when the source URL points to a
                video from a Web provider such as YouTube.
            alt_text: Alternate text describing the audio or video.

        Returns:
            None.

        Raises:
            None.
        """
        self.sources = sources
        self.poster = poster
        self.alt_text = alt_text

    def serialize(self) -> dict[str, Any]:
        """Serialize object into data structure."""
        payload: dict[str, Any] = {
            "type": "Media",
            "sources": [x.serialize() for x in self.sources],
        }
        if self.poster:
            payload["poster"] = self.poster
        if self.alt_text:
            payload["altText"] = self.alt_text
        return payload

class TextBlock(CardElement):
    """Displays text, allowing control over font sizes, weight, and color.

    Schema Explorer: https://adaptivecards.io/explorer/TextBlock.html
    """

    def __init__(
        self,
        text: str,
        *,
        color: Optional[types.Colors] = None,
        font_type: Optional[types.FontTypes] = None,
        horizontal_alignment: Optional[types.HorizontalAlignmentTypes] = None,
        is_subtle: Optional[bool] = None,
        max_lines: Optional[int] = None,
        size: Optional[types.FontSizes] = None,
        weight: Optional[types.FontWeights] = None,
        wrap: Optional[bool] = None,
        style: Optional[types.TextBlockStyles] = None,
    ) -> None:
        """Build a TextBlock element.

        Args:
            text: Text to display. A subset of markdown is supported (https://aka.ms/ACTextFeatures)
            color: Controls the color of TextBlock elements.
            font_type: Type of font to use for rendering.
            horizontal_alignment: Controls the horizontal text alignment. When not specified,
                the value of horizontalAlignment is inherited from the parent container. If no
                parent container has horizontalAlignment set, it defaults to Left.
            is_subtle: If true, displays text slightly toned down to appear less prominent.
                Default: ``False``
            max_lines: Specifies the maximum number of lines to display. `text` will be
                clipped if it exceeds `max_lines`.
            size: Controls size of text.
            weight: Controls the weight of TextBlock elements.
            wrap: If true, allow `text` to wrap. Otherwise, text is clipped. Default: False
            style: The style of this TextBlock for accessibility purposes.

        Returns:
            None.

        Raises:
            None.
        """
        self.text = text
        self.color = color
        self.font_type = font_type
        self.horizontal_alignment = horizontal_alignment
        self.is_subtle = is_subtle
        self.max_lines = max_lines
        self.size = size
        self.weight = weight
        self.wrap = wrap
        self.style = style

    def serialize(self) -> dict[str, Any]:
        """Serialize object into data structure."""
        payload: dict[str, Any] = {
            "type": "TextBlock",
            "text": self.text,
        }
        if self.color:
            payload["color"] = self.color
        if self.font_type:
            payload["fontType"] = self.font_type
        if self.horizontal_alignment:
            payload["horizontalAlignment"] = self.horizontal_alignment
        if self.is_subtle:
            payload["isSubtle"] = self.is_subtle
        if self.max_lines:
            payload["maxLines"] = self.max_lines
        if self.size:
            payload["size"] = self.size
        if self.weight:
            payload["weight"] = self.weight
        if self.wrap:
            payload["wrap"] = self.wrap
        if self.style:
            payload["style"] = self.style
        return payload


import numpy as np
import hybrid

print("____________EXTRACT____________")
predictions = np.load('../big_npy/resdata.npy',allow_pickle=True)
sent = np.load("../big_npy/testdata.npy",allow_pickle=True)
dictionary = np.load('../big_npy/lsa.npy',allow_pickle=True)
graph = np.load('../big_npy/graph.npy',allow_pickle=True)
graph_inverse = np.load('../big_npy/graph_inverse.npy',allow_pickle=True)
words_uniq = np.load('../big_npy/words_uniq.npy',allow_pickle=True)
n_occ = np.load('../big_npy/n_occ.npy',allow_pickle=True)
n_words = sum(n_occ)
dictionary = np.array(dictionary)
dictionary =  dictionary.tolist()

print("____________PREDICT____________")
sent = sent[:200]
predict = np.zeros((len(sent),5))
for i in range(len(sent)):
    print("###############")
    if i % 1 == 0:
        print("___",i,"___")
    for j in range(len(sent[i])):
        if sent[i][j]== '':
            del sent[i][j]
        print(sent[i][j])
        if sent[i][j] == '_____':
            print(sent[i][max(j-3,0):j])
            """try:
                print(predictions[i])
            except:
                print(len(predictions))
                print(len(sent))
                quit()"""
            b = hybrid.hybrid(predictions[i],sent[i][max(j-3,0):j],sent[i][j+1:min(j+4,len(sent[1])-1)],dictionary,graph,graph_inverse,words_uniq,n_occ,n_words,[1]*len(sent[i][max(j-3,0):j]+sent[i][j+1:min(j+4,len(sent[1])-1)]),1)
            predict[i] = b[0]
            break
    print("###############")
np.save("../big_npy/prob.npy",predict)
print("____________END_OF_PREDICT____________")

predict = np.load('../big_npy/prob.npy',allow_pickle=True)
resenja = np.load('../big_npy/resenja.npy',allow_pickle=True)

print(type(predict),type(predict[0]))

brojac = 0
uk = 0
for ind in range(len(predict)):

    res = np.argmax(predict[ind])
    print(res, resenja[ind])
    if  res == resenja[ind]:
        brojac += 1
    uk += 1

print(brojac/uk)


import bs4 as bs
import urllib.request
from pymongo import MongoClient
import pymongo

def mongo_connection():
  mongo_URL = "mongodb://mongodb-stitch-olympics-xhlhd:***@cis550-shard-00-00-a0sk1.mongodb.net:27017,cis550-shard-00-01-a0sk1.mongodb.net:27017,cis550-shard-00-02-a0sk1.mongodb.net:27017/test?ssl=true&replicaSet=Cis550-shard-0&authSource=admin"
  client = MongoClient(mongo_URL)
  db = client.data.olympics
  return db

def main():
  col = mongo_connection()
  count = 0
  with open('Athlete.txt','r', encoding="utf-16") as f:
    for line in f:
      name = get_name(line)
      athlete_info = find_info(name)
      if (athlete_info is not None):
        print (athlete_info)
        # col.insert(athlete_info)
        print (name,"success")

def get_name(raw_name):
  name_list = raw_name.replace("\"","").split(",")
  last_name = name_list[0].title().replace(" ","_")
  if (len(name_list) >= 2):
    first_name = name_list[1].strip().split(" ")[0]
    return first_name + "_" + last_name
  else:
    return last_name

def find_info(name):
  try:
    url_string = "https://en.wikipedia.org/wiki/" + str(name)
    sause = urllib.request.urlopen(url_string).read()
  except UnicodeEncodeError:
    print (name + ": UnicodeEncodeError")
    return
  except urllib.error.HTTPError:
    print (name + ": HTTP Error 404: Not Found")
    return
  soup = bs.BeautifulSoup(sause,'html.parser')

  athlete_info = {}
  athlete_info["Name"] = " ".join(name.split("_"));

  table = soup.find('table',{"class" : "infobox vcard"})
  try:
    table_row = table.find_all('tr')

    ##limiting table items to 10
    for tr in table_row[0:9]:
      td = tr.find_all('td')
      th = tr.find_all('th')

      key = [i.text for i in th]
      value = [i.text for i in td]

      if(len(key) > 0 and len(value) > 0):
        athlete_info[key[0]] = value[0].strip()
        # if (not key[0]):
        #   athlete_info[key[0]] = value[0].strip()

    return athlete_info

  except AttributeError:
    athlete_info = {"link":url_string,"Name":" ".join(name.split("_"))}
    return athlete_info

if __name__=="__main__":
    main()


import numpy as np

def random_feats(X, gamma=6, frequency_seed=None):
    scale = 1 / gamma
    if(frequency_seed is not None):
        np.random.seed(frequency_seed)
        W = np.random.normal(scale=scale, size=(X.shape[1], 1000))
    else:
        W = np.random.normal(scale=scale, size=(X.shape[1], 1000))
    XW = np.dot(X, W)
    sin_XW = np.sin(XW)
    cos_XW = np.cos(XW)
    Xnew = np.concatenate((cos_XW, sin_XW), axis=1)
    del sin_XW
    del cos_XW
    del XW
    #del W
    return Xnew, W

def kernel_herding(X, phi, num_samples):
    w_t = np.mean(phi, axis=0)
    w_0 = w_t
    subsample = []
    indices = []
    for i in range(1, num_samples + 1):
        new_ind = np.argmax(np.dot(phi, w_t))
        x_t = X[new_ind]
        w_t = w_t + w_0 - phi[new_ind]
        indices.append(new_ind)
        subsample.append(x_t)

    return indices, subsample

def kernel_herding_main(X, phi, num_subsamples):
    kh_indices, kh_samples = kernel_herding(X, phi, num_subsamples)
    kh_rf = phi[kh_indices]
    return kh_indices, kh_samples, kh_rf


import unittest

# Copied from somehwere
class Node:
  def __init__(self, data):
    self.left = None
    self.right = None
    self.data = data

  def val(self):
    return self.data

  def insertLeft(self, tree):
    self.left = tree

  def insertRight(self, tree):
    self.right = tree

  def PrintTree(self):
    if self.left:
        self.left.PrintTree()
    print( self.data),
    if self.right:
        self.right.PrintTree()

def Solution(root: Node):
  if (root is None):
    return 0

  leftCount = Solution(root.left)
  rightCount = Solution(root.right)

  rootCount = 0
  rootVal = root.val()
  if (root.left is not None and root.left.val() == rootVal and root.right is not None and root.right.val() == rootVal):
    rootCount = 1

  if (root.left is None and root.right is None):
    rootCount += 1

  return leftCount + rightCount + rootCount

class TestCase(unittest.TestCase):
  def test_num_1(self):
    root = Node(0)
    left = Node(1)
    right = Node(0)
    rigthRight = Node(0)

    rigthLeft = Node(1)
    rigthLeftLeft = Node(1)
    rigthLeftRight = Node(1)
    rigthLeft.insertLeft(rigthLeftLeft)
    rigthLeft.insertRight(rigthLeftRight)

    right.insertLeft(rigthLeft)
    right.insertRight(rigthRight)

    root.insertLeft(left)
    root.insertRight(right)

    sol = Solution(root)
    self.assertEqual(sol, 5)
  def test_num_2(self):
    root = Node(0)
    sol = Solution(root)
    self.assertEqual(sol, 1)
  def test_num_3(self):
    root = Node(0)
    left = Node(1)
    right = Node(0)
    rigthRight = Node(0)
    right.insertRight(rigthRight)

    root.insertLeft(left)
    root.insertRight(right)

    sol = Solution(root)
    self.assertEqual(sol, 2)

def main():
  unittest.main()

if __name__ == "__main__":
  main()


from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import Group
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from django.views.generic import UpdateView

from one.components.views import CreateView, FormMixin, ListView, SuccessMessageMixin
from one.contrib.auth.contexts.actions import (
    get_core_group_add,
    get_core_group_quick_add,
)
from one.contrib.auth.contexts.api.serializers import GroupSerializer
from one.contrib.auth.contexts.filters import GroupFilter
from one.contrib.auth.contexts.forms import ContextForm, GroupForm

class GroupCreateView(LoginRequiredMixin, SuccessMessageMixin, FormMixin, CreateView):
    model = Group

    form_class = GroupForm
    serializer_class = GroupSerializer
    success_message = _("Group created successfully")

    def get_context_data(self, **kwargs):
        kwargs = super().get_context_data(**kwargs)
        kwargs["app_name"] = _("Group")
        kwargs["page_title"] = _("Group Create")
        kwargs["page_breadcrumb"] = [
            {"name": _("Groups"), "url": reverse("auth:group-list")},
        ]

        kwargs["form_title"] = _("Group Form")
        kwargs["nested_forms"] = [
            {
                "form": ContextForm(),
                "title": _("Extend information"),
            }
        ]
        return kwargs

    def get_success_url(self):  # noqa
        if self.object:
            return reverse("auth:group-update", kwargs={"pk": self.object.pk})
        return reverse("auth:group-list")

    def post(self, request, *args, **kwargs):
        form = self.get_form()
        if form.is_valid():
            context_form = ContextForm(self.request.POST, self.request.FILES)
            if context_form.is_valid():
                response = self.form_valid(form)
                context_form = ContextForm(
                    self.request.POST, self.request.FILES, instance=self.object.context
                )
                context_form.save()
                return response
            self.object = None  # noqa
            self.add_error_messages(context_form)
        return self.form_invalid(form)

group_create_view = GroupCreateView.as_view()

class GroupListView(LoginRequiredMixin, ListView):
    template_name = "app/list.html"
    model = Group

    filter_class = GroupFilter

    def get_context_data(self, **kwargs):
        kwargs = super().get_context_data(**kwargs)
        kwargs["app_name"] = _("Group")
        kwargs["page_title"] = _("Group List")
        kwargs["actions"] = [get_core_group_add(), get_core_group_quick_add()]
        kwargs["urls"] = {
            "update": "auth:group-update",
        }
        kwargs["api_urls"] = {
            "list": "api:group-list",
            "delete": "api:group-delete",
        }
        return kwargs

group_list_view = GroupListView.as_view()

class GroupUpdateView(LoginRequiredMixin, SuccessMessageMixin, FormMixin, UpdateView):
    template_name = "app/update.html"
    model = Group

    form_class = GroupForm
    serializer_class = GroupSerializer
    success_message = _("Group successfully updated")

    def get_context_data(self, **kwargs):
        kwargs = super().get_context_data(**kwargs)
        kwargs["app_name"] = _("Group")
        kwargs["page_title"] = _("Group Update")
        kwargs["page_breadcrumb"] = [
            {"name": _("Groups"), "url": reverse("auth:group-list")},
        ]

        kwargs["form_title"] = _("Group Update")

        if self.request.method == "POST":
            context_form = ContextForm(
                self.request.POST, self.request.FILES, instance=self.object.context
            )
        else:
            context_form = ContextForm(instance=self.object.context)
        kwargs["nested_forms"] = [
            {
                "form": context_form,
                "title": _("Extend information"),
                "hidden_fields": [],
            }
        ]
        return kwargs

    def get_success_url(self):  # noqa
        return reverse("auth:group-list")

    def post(self, request, *args, **kwargs):
        """
        Handle POST requests: instantiate a form instance with the passed
        POST variables and then check if it's valid.
        """
        self.object = self.get_object()  # noqa
        context_form = ContextForm(
            self.request.POST, self.request.FILES, instance=self.object.context
        )
        form = self.get_form()
        if form.is_valid():
            if context_form.is_valid():
                self.form_valid(context_form, is_nested=True)
                return self.form_valid(form)
            self.add_error_messages(context_form)
        return self.form_invalid(form)

group_update_view = GroupUpdateView.as_view()


# snail()

def snail(height, day, night):
    curr_loc = 0
    day_cnt = 0
    while curr_loc < height:
        curr_loc += day
        if curr_loc >= height:
            day_cnt += 1
            break
        curr_loc -= night
        day_cnt += 1

    return day_cnt

print(snail(100, 10, 3))

# 자리수 더하기

## 반복문 사용

def sum_of_digit(number):
    num_str = str(number)
    answer = 0
    for i in num_str:
        num_i = int(i)
        answer += num_i

    return answer

print(sum_of_digit(12345))

### 교수님 코드

# def sum_of_digit(number):
#     # 1. 변수 초기화
#     total = 0
#     # 2. 반복문
#     while number / 10:
#         # 3. 몫과 나머지를 분리
#         remainder = number % 10
#         number = number // 10
#         # 4. 나온 나머지 더하기
#         total += remainder

#     return total

## 재귀문 사용

def sum_of_digit_reculsive(number):
    num_str = str(number)
    if len(num_str) < 2:
        return int(num_str[0])
    else:
        return int(num_str[0]) + sum_of_digit_reculsive(num_str[1:])

### 김태삼님 코드

# def sum_of_digit_reculsive(number):
#     if number < 10:
#         return number
#     else:
#         return (number % 10) + sum_of_digit_reculsive(number // 10)


with open('case1.txt') as fin:
    ls = [int(e.strip()) for e in fin.readlines()]
    prev = None
    inc = 0
    for _ in ls:
        if prev is None:
            prev = _
        else:
            if _ > prev:
                inc += 1
        prev = _
    print(inc)


from qiskit import QuantumCircuit, converters
from math import pi

def c_7mod15_gate(power):

    U = QuantumCircuit(4)
    # https://quantumcomputing.stackexchange.com/questions/15280/how-does-this-represent-modular-multiplication

    for _ in range(power):
      U.x(range(4))
      U.swap(1, 2)
      U.swap(2, 3)
      U.swap(0, 3)

    U = U.to_gate()
    U.name = "%i^%i mod 15" % (7, power)
    c_U = U.control()
    return c_U

# blatantly stole qft circuit generator from this:
# https://learn.qiskit.org/course/ch-algorithms/quantum-fourier-transform

def qft_rotations(circuit, n):
    """Performs qft on the first n qubits in circuit (without swaps)"""
    if n == 0:
        return circuit
    n -= 1
    circuit.h(n)
    for qubit in range(n):
        circuit.cp(pi/2**(n-qubit), qubit, n)
    # At the end of our function, we call the same function again on
    # the next qubits (we reduced n by one earlier in the function)
    qft_rotations(circuit, n)

def swap_registers(circuit, n):
    for qubit in range(n//2):
        circuit.swap(qubit, n-qubit-1)
    return circuit

def qft(circuit, n):
    """QFT on the first n qubits in circuit"""
    qft_rotations(circuit, n)
    swap_registers(circuit, n)
    return circuit

def qft_gate(n):
  qc = QuantumCircuit(n)
  qc.name = "QFT"
  qft(qc, n)
  gate = converters.circuit_to_gate(qc)

  return gate

def inverse_qft_gate(n):
  return qft_gate(n).inverse()


#	This will eventually hold all of the grain definitions and functions or methods or whatever python calls them
#
#
#	The basic hop class should be fed grain, lb, oz, ppg, degreesL, sugar type, and use
#		Default to generic,1,0,1.025,1,grain, other
#
#		-update() methods should allow the user to select grain, lb, oz, ppg, degreesL, sugar type, and method
#			the user should be able to name their own grain type (and fill in the rest of the data)
#		-get() methods should pull attributes from a database/xml for a given grain
#		-a weight conversion method should convert lb and oz to a common unit (which ever works best for calculations)
#		-an extract calculation method should pull weight, ppg, efficiency, and volume in order to calculate og per grain
#			perhaps getOG() and getVolume() methods should facilitate this
#		-color calculation should return color based on some stuff
#		-a points to (something--OG?) calculation should convert ppg to the proper display (50 ppg to 1.050)
#
#		other stuff will happen

class Grain(object):
#The basic class that all fermentables fall under

	count = 0

	def __init__(self, type= 'generic', lb = 1, oz = 0, ppg = 25, degreesL = 1, sugarType="grain", use="mashed"):

		Grain.count += 1
			#This might need to live outside of the Grain class at some point (in a Recipe class
			#that aggregates grains and stuff (and does the total OG/color calculations?))

		#establish the main attributes
		self.type = type
		self.lb = lb
		self.oz = oz
		self.weight = (lb * 16) + oz
		self.pounds = self.weight / 16
		self.ppg = ppg
		self.degreesL = degreesL
		self.sugarType = sugarType
		self.use = use

	def calculatePoints(self, volume, efficiency):
		#-returns the points added from a single fermentable
		#-this might not work for extract--look into that
		#-this should eventually take no inputs, but rather pull directly
		#	from a CONFIG module
		pts = ((self.ppg * self.pounds) / volume) * efficiency
		return pts
			#I'm not certain that this is correct--might have to do some Qbrew testing

	def returnOG(self, volume, efficiency):
		#return the gravity contribution of a single fermentable addition
		#-this should eventually take no inputs, but rather pull directly
		#	from a CONFIG module
		vol = volume
		efficient = efficiency
		pt = self.calculatePoints(vol, efficient)
		OG = 1 + (pt / 1000)
		return OG

	def calculateColor(self):
		#calculates the color contriution of a single fermentable addition
		#the color from all additions should be divided by the total volume
			#and fed through a color estimating formula (initially just Morey)
		#this might not be the most effective way to do things
		color = self.pounds * self.degreesL
		return color

#test main
#grain = Grain(ppg=30)
#grainlb = Grain(oz=8)
#points = grain.calculatePoints(5, 0.75)
#og = grain.returnOG(5, 0.75)
#color = grain.calculateColor()

#print('type:', grain.type)
#print('weight:', grain.weight, 'oz')
#print('weight:', grainlb.pounds, 'lb')
#print('points:', points)
#print('OG:', og)
#print('count:', grain.count)
#print('Count:', Grain.count)
#print('Color:',color)
#print('Color:',grainlb.calculateColor())
#input("\nExit")


from django.conf.urls import url
from . import views
app_name='test'
urlpatterns = [
    url(r'^register/$',views.register,name='register'),
    url(r'^login/$',views.login_1,name='login'),
    url(r'^logout/$',views.logout_1,name='logout'),
    url(r'^enterdetails/$',views.enterdetails,name='enterdetails'),
    url(r'^teacherdetails/$',views.teacherdetails,name='teacherdetails'),
    url(r'^choice/$',views.fchoice,name='fchoice'),
    url(r'studentupdate/(?P<pk>[0-9]+)/$',views.StudentUpdate.as_view(),name='student-update'),
    url(r'teacherupdate/(?P<pk>[0-9]+)/$',views.teacherUpdate.as_view(),name='teacher-update'),
    url(r'studentdetails/(?P<id>[0-9]+)/$',views.StudentDetails,name='student-details'),
    url(r'detailsteacher/(?P<id>[0-9]+)/$',views.DetailsTeacher,name='details-teacher'),
    url(r'faceupdate/(?P<id>[0-9]+)/$',views.create_dataset,name='create_dataset'),
    url(r'^check/$',views.check,name='check'),
    url(r'^teacherstudent/$',views.teacherstudent,name='teacherstudent')

]


from random import *
import binascii

'''
Function Name: randomPrime
Parameters: None
Description: Retrieves a random prime number between 10 and 30
Returns: Returns the prime if it is prime
'''
def randomPrime():
    x = randint(10, 30)
    if checkPrime(x):
        return x
    else:
        randomPrime()

def checkPrime(a):
    if a == 2:
        return False

    elif (a % 2) == 1:
        return True

    else:
        return False

def totient(a,b):
    return (a-1)*(b-1)

def gcd(a, b):
    if a == 0:
        return b
    elif b == 0:
        return a
    else:
        return gcd(b, a % b)

def isCoPrime(a, b):
    if gcd(a, b) == 1:
        return True
    else:
        return False

def getPublicExponentRand(phi):
    x = randint(1, phi-1)

    if isCoPrime(x, phi):
        return x
    else:
        return getPublicExponentRand(phi)

def getPublicExponentIter(phi):
    for x in range(2,phi):
        if isCoPrime(phi, x):
            return x

def getD(phi, tempPhi, e, rightTop, otherX):

#if our b == 0
#if our a == 1

    if e == 0:
        if tempPhi ==1:
            return otherX

    else:
        #temp will store our remainder for the first iteration, we do phi mod e essentially
        # a / b   what's the quotient? Store in temp
        r = tempPhi // e
        x = r * e
        newX = tempPhi - x
        #remember that our new a is just our old b, and our new b is our remainder
        newE = newX
        newPhi = e

        #This stuff here, is the reverse Euclid part
        rightSideX = rightTop - (r * otherX)
        if rightSideX < 0:
            newOtherX = rightSideX % phi
        else:
            newOtherX = rightSideX
        if newE == 1:
            return newOtherX
        else:
            return getD(phi, newPhi, newE, otherX, newOtherX)

def getDStart(phi, e):
    return getD(phi, phi, e, phi, 1)

def encrypt(message, e, n):
    #cipher = [(ord(char) ** e) % n for char in message]
    cipher = []
    for char in message:
        unicodeValue = ord(char)
        finalValue = ((unicodeValue ** e) % n)
        cipher.append(finalValue)
    return cipher

def decrypt(cipherText, d, n):

    #for char in cipherText:
    #    tempChar = chr((char**d)%n)
    plaintext = [chr((char ** d) % n) for char in cipherText]
    return plaintext

if __name__ == '__main__':
    p = 17
    q = 19
    n = p * q
    print("First prime (p) = ", p)
    print("Second prime (q) = ", q)
    print("N = p*q = ", n)
    euler = totient(p, q)
    print("Here's the euler's totient phi(n) = (p-1)*(q-1) = ", euler)
    exponent = getPublicExponentRand(euler)
    print("We select a random exponent")
    d = getDStart(euler, exponent)
    print("here is the d: ", d)
    print("Public Key: (" + str(exponent) + "," + str(n) + ")")
    print("Private Key: (" + str(d) + "," + str(n) + ")")
    message = input("Please enter a message to encrypt: ")
    print("Encrypting message...")
    encrypted = encrypt(message,exponent,n)
    print(encrypted)
    print("decrypting...")
    decrypted = decrypt(encrypted,d,n)
    print(str(decrypted))

    """
    print("Enter a")
    a = input()
    print("Enter b")
    b = input()
    print(gcd(int(a), int(b)))
    """


import keras
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import tensorflow as tf
import sys as system
import datetime as dt
import pickle
from sklearn.preprocessing import MinMaxScaler
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, LSTM
from sklearn.preprocessing import RobustScaler
from sklearn.preprocessing import MinMaxScaler
from sklearn.preprocessing import LabelEncoder
from random import randrange
import os

MODEL_NAME = "aksjer.model"
TICKER_ID = "ATEA.XOSL"

df = pd.read_csv("dataset.csv", delimiter=";", parse_dates=['date'])
df = df.drop(columns=['date', 'id'])
# df['date'] = (df.date - df.date.min()).dt.days

train_size = int(len(df) * 0.9)
test_size = len(df) - train_size
# train, test = df.iloc[0:train_size], df.iloc[train_size:len(df)]
val_id = df['symbol'][randrange(len(df))]
train = df[df['symbol'] != TICKER_ID]
train = df[df['symbol'] != val_id]
test = df[df['symbol'] == TICKER_ID].iloc[2000:]
val = df[df['symbol'] == val_id]
print(f"Val ticker id: {val_id}")
print(train.shape, test.shape, val.shape)

f_columns = ['high', 'low', 'open', 'volume']
f_transformer = RobustScaler()
cnt_transformer = RobustScaler()
l_encoder = LabelEncoder()

f_transformer = f_transformer.fit(train[f_columns].to_numpy())
cnt_transformer = cnt_transformer.fit(train[['close']])
l_encoder = l_encoder.fit(df[['symbol']])

train.loc[:, f_columns] = f_transformer.transform(train[f_columns].to_numpy())
train['close'] = cnt_transformer.transform(train[['close']])
train['symbol'] = l_encoder.transform(train[['symbol']])

test.loc[:, f_columns] = f_transformer.transform(test[f_columns].to_numpy())
test['close'] = cnt_transformer.transform(test[['close']])
test['symbol'] = l_encoder.transform(test[['symbol']])

val.loc[:, f_columns] = f_transformer.transform(val[f_columns].to_numpy())
val['close'] = cnt_transformer.transform(val[['close']])
val['symbol'] = l_encoder.transform(val[['symbol']])

def create_dataset(X, y, time_steps=1, future_day=1):
    Xs, ys = [], []
    for i in range(time_steps, len(X) - future_day):
        v = X.iloc[i - time_steps:i].to_numpy()
        Xs.append(v)
        ys.append(y.iloc[i + future_day])
    return np.array(Xs), np.array(ys)

TIME_STEPS = 120
FUTURE_DAY = 90
X_train, y_train = create_dataset(train, train.close, time_steps=TIME_STEPS)
X_test, y_test = create_dataset(test, test.close, time_steps=TIME_STEPS)
X_val, y_val = create_dataset(val, val.close, time_steps=TIME_STEPS)

# [samples, time_steps, n_features]
print(X_train.shape, y_train.shape)
print(X_test.shape, y_test.shape)
print(X_val.shape, y_val.shape)

if os.path.exists(MODEL_NAME):
    model = keras.models.load_model(MODEL_NAME)
else:
    model = keras.Sequential()
    model.add(
        keras.layers.Bidirectional(
            keras.layers.LSTM(
                units=128,
                input_shape=(X_train.shape[1], X_train.shape[2])
            )
        )
    )
    model.add(keras.layers.Dropout(rate=0.2))
    model.add(keras.layers.Dense(units=1))
    model.compile(loss='mean_squared_error', optimizer='adam')
    history = model.fit(
        X_train, y_train,
        epochs=1,
        batch_size=256,
        validation_data=(X_val, y_val),
        shuffle=False
    )
    model.save(MODEL_NAME)

# plt.plot(history.history['loss'], label='train')
# plt.plot(history.history['val_loss'], label='validation')
# plt.legend()
# plt.show()

y_pred = model.predict(X_test)
y_train_inv = cnt_transformer.inverse_transform(y_train.reshape(1, -1))
y_test_inv = cnt_transformer.inverse_transform(y_test.reshape(1, -1))
y_pred_inv = cnt_transformer.inverse_transform(y_pred)

plt.plot(y_test_inv.flatten(), label='actual')
plt.plot(y_pred_inv.flatten(), 'r', label='predicted')
plt.legend()
plt.show()


#!/usr/bin/python3
import jenkins
from flask import Blueprint, render_template, redirect, session

jk = Blueprint ('jk', __name__ , url_prefix='/jenkins')
jc = jenkins.Jenkins('http://192.168.0.200:8080')

@jk.route('')
def home():
	if not session.get('auth'):
		return redirect ('/')
	for job in jc.get_jobs():
		if job ['name'] == 'Pipiline':
			pipiline= job
			break
	else:
		pipiline = {'name': 'Nenhum job encontrado', 'color' : ''}
	pipiline ['color'] = 'construiu' if pipiline['color'] == 'blue' else 'falhou'
	return render_template('jenkins.html', job=pipiline )

#sudo apt-get install python3-jenkins


import sys, os, random

from cnfParser import parseCNF

inCNF = sys.argv[1]
numWeights = int(sys.argv[2])
outF = sys.argv[3]

probLow = 0.3
probHi = 0.7

nVars, nCls, clauses, weighted, wEncountered, wType, litWts, projected, vpEncountered, projVars = parseCNF(inCNF)

if wEncountered == True:
	print("WARNING: Input formula is already weighted. Ignoring those weights\n")

if vpEncountered:
	pVars = sorted(projVars)
else:
	pVars = range(1,nVars+1)

wtLits = random.sample([v*k for v in pVars for k in (-1,1)], numWeights)
wtLits.sort()

wts = []
for lit in wtLits:
	wts.append(random.uniform(probLow,probHi))

f = open(outF,'w')
if projected:
	f.write('p wpcnf '+str(nVars)+' '+str(nCls)+'\n')
	f.write('vp ')
	for v in pVars:
		f.write(str(v)+ ' ')
	f.write('0\n')
else:
	f.write('p wcnf '+str(nVars)+' '+str(nCls)+'\n')
for i in range(len(wts)):
	wt = wts[i]
	lit = wtLits[i]
	f.write('w '+str(lit)+' '+str(wt)+'\n')
for cl in clauses:
	for lit in cl:
		f.write(str(lit)+' ')
	f.write('0\n')
f.close()


import json

# Dönüştürmek istediğimiz sözlük
sozluk = {
    "ad": "John Doe",
    "yas": 30,
    "meslek": "Mühendis",
    "email": "john@example.com"
}

# Sözlüğü JSON formatına dönüştürme
json_veri = json.dumps(sozluk)

# JSON formatındaki veriyi yazdırma
print(json_veri)


import os
import argparse
import logging
import time
import numpy as np
import scipy as scp
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from typing import Dict
from sklearn.cluster import KMeans

from src.utils import *

import warnings
warnings.filterwarnings('ignore')

def str_to_bool(value: str) -> bool:
    """
    This method converts boolean strings to boolean.
    :param value: String argument from command line.
    :return: Boolean based on the value field.
    """
    if value in ['true', 'True']:
        return True
    else:
        return False

def get_summary_stats(data_sets: Dict,
                      n_clusters: int = 4,
                      summary_stats_plots_path: str = 'plots/summary_statistics') -> None:
    """
    This method generates the summary statistics for the dataset at our hand.
    :param data_sets: This is the list of full training data, training data, validation data and the evaluation data.
    :param n_clusters: Number of clusters to implement the channel wise clustering analysis.
    :param summary_stats_plots_path: Location where the summary statistics plots are stored.
    :return: None
    """
    # Create a directory for the plots if it doesn't exist
    create_directory(summary_stats_plots_path)

    # The Exploratory Data Analysis is done for every dataset
    for name, data_set in data_sets.items():
        print(f'\nSummary stats for {name} ------------------------------------------------------------------\n')

        print(f'Number of Samples - {len(data_set)}')
        print(f'Shape of an Instance - {data_set[0][0].shape}')

        classes = np.array([instance[1] for instance in data_set])
        print(f'Class Distribution - \n{np.unique(classes, return_counts=True)}')

        data = np.array([instance[0] for instance in data_set])
        concatenated_data = np.concatenate(data, axis=1)
        correlation_matrix = np.corrcoef(concatenated_data)

        # Plotting the channel wise correlation heatmaps
        plt.figure(figsize=(20, 15))
        sns.heatmap(correlation_matrix)
        plt.title(f"Channel Wise Correlation Map for {name}", fontdict={'fontsize': 30})
        plt.savefig(f"./{summary_stats_plots_path}/{name}_heatmap.png")
        plt.show()

        # Trying out KMeans Clustering to see which channels cluster together
        kmeans = KMeans(n_clusters=n_clusters, random_state=0)
        kmeans.fit(correlation_matrix)
        cluster_labels = kmeans.labels_
        clusters = {}
        for cluster in range(n_clusters):
            clusters[cluster + 1] = []
        for channel, label in enumerate(cluster_labels):
            clusters[label + 1].append(channel + 1)
        print(f'Clustered Channels - \n{clusters}')
        x = np.linspace(1, 22, 22)
        y = cluster_labels + 1
        plt.figure(figsize=(15, 10))
        plt.scatter(x=x, y=y)
        plt.xlabel('Channel Number')
        plt.ylabel('Cluster Number')
        plt.title(f"Channel Wise Cluster Relation for {name}", fontdict={'fontsize': 30})
        plt.savefig(f"./{summary_stats_plots_path}/{name}_cluster_analysis.png")
        plt.show()

        actions = np.unique(classes)
        for action in actions:
            data = np.array([instance[0] for instance in data_set if instance[1] == action])
            concatenated_data = np.concatenate(data, axis=1)
            correlation_matrix = np.corrcoef(concatenated_data)
            plt.figure(figsize=(20, 15))
            sns.heatmap(correlation_matrix)
            plt.title(f"Channel Wise Correlation Map for {name} and Action = {action}", fontdict={'fontsize': 30})
            plt.savefig(f"./{summary_stats_plots_path}/{name}_action_{action}_heatmap.png")
            plt.show()

if __name__ == '__main__':
    cmdline_parser = argparse.ArgumentParser('Transformers for EEG')
    cmdline_parser.add_argument('-d', '--dataset_name',
                                default='BNCI2014001',
                                help='The name of the dataset to fetch',
                                type=str)
    cmdline_parser.add_argument('-s', '--subject_ids',
                                default='1,2,3,4,5,6,7,8,9',
                                help='Data of the Subject IDs to fetch',
                                type=str)
    cmdline_parser.add_argument('-dfn', '--data_folder_name',
                                default='data',
                                help='Folder name to store the data',
                                type=str)
    cmdline_parser.add_argument('-lf', '--l_freq',
                                default=4.0,
                                help='The lower limit of the Bandpass Filter',
                                type=float)
    cmdline_parser.add_argument('-hf', '--h_freq',
                                default=38.0,
                                help='The higher limit of the Bandpass Filter',
                                type=float)
    cmdline_parser.add_argument('-emsf', '--ems_factor',
                                default=1e-3,
                                help='Factor to apply exponential moving standardization',
                                type=float)
    cmdline_parser.add_argument('-ibs', '--init_block_size',
                                default=1000,
                                help='Initial block size to implement exponential moving standardization',
                                type=int)
    cmdline_parser.add_argument('-tsos', '--trial_start_offset_seconds',
                                default=-0.5,
                                help='This represents the duration (in seconds) before the event of interest starts',
                                type=float)
    cmdline_parser.add_argument('-tss', '--training_set_size',
                                default=0.8,
                                help='Provide the training set size in percentage, like 0.7 or 0.8',
                                type=float)
    cmdline_parser.add_argument('-nc', '--n_clusters',
                                default=4,
                                help='Number of clusters to execute the channel wise clustering',
                                type=int)
    cmdline_parser.add_argument('-sspp', '--summary_stats_plots_path',
                                default='plots/summary_statistics',
                                help='Location where the summary statistics plots are stored',
                                type=str)
    cmdline_parser.add_argument('-v', '--verbose',
                                default='INFO',
                                choices=['INFO', 'DEBUG'],
                                help='verbosity')

    args, unknowns = cmdline_parser.parse_known_args()
    log_lvl = logging.INFO if args.verbose == 'INFO' else logging.DEBUG
    logging.basicConfig(level=log_lvl)

    # Below, we get the split datasets required for training purposes after fetching and preprocessing it
    full_train_set,\
        train_set,\
        valid_set,\
        eval_set = get_data_and_preprocess(dataset_dir=args.data_folder_name,
                                           dataset_name=args.dataset_name,
                                           subject_ids=args.subject_ids,
                                           l_freq=args.l_freq,
                                           h_freq=args.h_freq,
                                           ems_factor=args.ems_factor,
                                           init_block_size=args.init_block_size,
                                           trial_start_offset_seconds=args.trial_start_offset_seconds,
                                           training_set_size=args.training_set_size)

    # Now we generate the summary statistics for the split datasets
    datasets = {
        'Full Training Set': full_train_set,
        'Training Set': train_set,
        'Validation Set': valid_set,
        'Evaluation Set': eval_set
    }
    get_summary_stats(datasets,
                      n_clusters=args.n_clusters,
                      summary_stats_plots_path=args.summary_stats_plots_path)


## Ejercicio del estudiante

def cadena(s):

    char=[i for i in str(s)]
    resultado=[False]
    vocal=['a','e','i','o','u']

    if(len(s)%2==0):
        medio=len(s)//2
    else:
        medio=len(s)//2+1

    cont_vocales=0
    aux=1
    inverso=''
    for i in s:
        #vocales
        for j in vocal:
            if(i==j):
                cont_vocales+=1
        if (medio==aux):
            for j in vocal:
                if(i==j):
                     resultado[0]=True
        inverso=i+inverso
        aux+=1
    resultado+=[cont_vocales,len(s)-cont_vocales,inverso]
    return resultado


import atm_details

def access_function():
    print("Main Menu:")
    print("1-> Check Balance")
    print("2-> Withdraw Cash")
    print("3-> Deposit Cash")
    print("4-> View Transaction History")
    print("5-> Change PIN")
    print("6-> Exit")

    option = int(input("Select an option: "))
    try:
        if option == 1:
            atm_details.check_balance()
        elif option == 2:
             atm_details.withdrawal_amount()
        elif option == 3:
             atm_details.deposit_amount()
        elif option == 4:
             atm_details.view_transaction_history()
        elif option == 5:
             atm_details.new_pin()
        elif option == 6:
             atm_details.exit()
        else:
            print(" Please Type 1, 2, 3, 4 ,5 or 6 only ")
    except ValueError:
        print("Type Number Only")

access_function()


import configparser
import enum
import json
from os import path

from src.common.error_handler import handle_error, ErrorSeverity

class Project:

    initialize_stanford_tagger = None
    config_custom_terms_file = None
    config_custom_code_file = None

    def __init__(self, configuration_file):
        config = configparser.ConfigParser()
        try:
            config.read(configuration_file)
        except configparser.MissingSectionHeaderError as  error:
            error_message = "%s" % str(error)
            handle_error('ConfigReader', error_message, ErrorSeverity.Critical, True)

        section_files = 'Files'
        section_properties = 'Properties'

        try:
            self.output_directory = config[section_files]['output_directory']
            self.input_file = config[section_files]['input_file']
        except KeyError as error:
            error_message = "Missing key in the configuration file: %s" % str(error)
            handle_error('ConfigReader', error_message, ErrorSeverity.Critical, True)

        try:
            self.junit_version = config[section_properties]['junit_version']
            self.junit_version = float(self.junit_version)
        except ValueError as error:
            self.junit_version = None
        except KeyError as error:
            error_message = "Missing key in the configuration file: %s" % str(error)
            handle_error('ConfigReader', error_message, ErrorSeverity.Error, False)
            self.junit_version = None

        try:
            self.custom_code_file = config[section_files]['custom_code']
            self.custom_terms_file = config[section_files]['custom_terms']
        except KeyError as error:
            error_message = "Missing key in the configuration file: %s" % str(error)
            handle_error('ConfigReader', error_message, ErrorSeverity.Error, False)

        if not path.exists(self.output_directory) or not path.isdir(self.output_directory):
            error_message = "Invalid \'Output Directory\': \'%s\'" % str(self.output_directory)
            handle_error('ConfigReader', error_message, ErrorSeverity.Critical, True)

        if not path.exists(self.input_file) or not path.isfile(self.input_file):
            error_message = "Invalid \'Input File\': \'%s\'" % str(self.input_file)
            handle_error('ConfigReader', error_message, ErrorSeverity.Critical, True)

        if not path.exists(self.custom_code_file) or not path.isfile(self.custom_code_file):
            error_message = "Invalid \'Custom Code File\': \'%s\'" % str(self.custom_code_file)
            handle_error('ConfigReader', error_message, ErrorSeverity.Warning, False)
        else:
            self.config_custom_code_file = configparser.ConfigParser()
            self.config_custom_code_file.read(self.custom_code_file)

        if not path.exists(self.custom_terms_file) or not path.isfile(self.custom_terms_file):
            error_message = "Invalid \'Custom Terms File\': \'%s\'" % str(self.custom_terms_file)
            handle_error('ConfigReader', error_message, ErrorSeverity.Warning, False)
        else:
            self.config_custom_terms_file = configparser.ConfigParser()
            self.config_custom_terms_file.read(self.custom_terms_file)

    def __get_config_value(self, file_type, config_file, section, key):
        try:
            return json.loads(config_file.get(section, key))
        except configparser.NoOptionError as key_error:
            error_message = "%s in the %s configuration file \'%s\'" % (str(key_error), file_type.name, config_file)
            handle_error('ConfigReader', error_message, ErrorSeverity.Warning, False)
        except configparser.NoSectionError as section_error:
            error_message = "%s in the %s configuration file \'%s\'" % (str(section_error), file_type.name, config_file)
            handle_error('ConfigReader', error_message, ErrorSeverity.Warning, False)

    def get_config_value(self, file_type, section, key):
        if file_type == ConfigCustomFileType.Code and self.config_custom_code_file is not None:
            return self.__get_config_value(file_type, self.config_custom_code_file, section, key)

        if file_type == ConfigCustomFileType.Terms and self.config_custom_terms_file is not None:
            return self.__get_config_value(file_type, self.config_custom_terms_file, section, key)

class ConfigCustomFileType(enum.Enum):
    Code = 1
    Terms = 2


from college.models import College
from django.db.models import F
import os
from django.conf import  settings
final_bulk_students = []
file_name = "scripts/new/college_data.csv"

csv_data = 'University code,College name,District name,Email,Mobile,Spoc name,Address'

colleges_list = College.objects.annotate(district_name=F('district__name')).values(
    'college_name',
    'college_code',
    'email',
    'mobile',
    'spoc_name',
    'address',
    'district_name',
).filter(college_type=2)

for obj in colleges_list:
    csv_data += f'\n{obj["college_code"]},' \
                f'{obj["college_name"]},' \
                f'{obj["district_name"]},' \
                f'{obj["email"]},' \
                f'{obj["mobile"]},' \
                f'{obj["spoc_name"]},' \
                f'{obj["address"]}' \
                f''
with open(os.path.join(settings.BASE_DIR, file_name), 'w') as f:
    f.write(csv_data)
    f.close()


import time
from datetime import datetime as dt

path_host = r"c:\Windows\System32\drivers\etc\hosts"
#path_host = "hosts"
redirect = "127.0.0.1"
websites = ["www.vk.com", "vk.com"]

count = 0
while True:
    if 8 < dt.now().hour < 16:
        with open(path_host, "r+") as myfile:
            content = myfile.read()
            for ws in websites:
                if ws in content:
                    pass
                else:
                    myfile.write(redirect + "       " + ws + "\n")
        print(1)
        time.sleep(5)
    else:
        with open(path_host, "r+") as myfile:
            content = myfile.readlines()
            myfile.seek(0)
            for line in content:
                if not any(ws in line for ws in websites):
                    myfile.write(line)
            myfile.truncate()

        print(2)
        time.sleep(5)


#For hauling in EVE
import cv2
import pyautogui
import time
import numpy as np
import mpld3
from mpld3 import plugins
from matplotlib import pyplot as plt
from datetime import datetime

def getCropCoords(img):
    def nothing(stuff):
        pass

    cv2.namedWindow('SC',cv2.WINDOW_NORMAL)
    cv2.createTrackbar('X1', 'SC', 0, 3360, nothing)
    cv2.createTrackbar('Y1', 'SC', 0, 2100, nothing)
    cv2.createTrackbar('X2', 'SC', 0, 3360, nothing)
    cv2.createTrackbar('Y2', 'SC', 0, 2100, nothing)

    cv2.resizeWindow('SC', 1600, 1000)

    while True:
        new_img = np.copy(img)
        x_one = cv2.getTrackbarPos("X1", "SC")
        y_one = cv2.getTrackbarPos("Y1", "SC")
        x_two = cv2.getTrackbarPos("X2", "SC")
        y_two = cv2.getTrackbarPos("Y2", "SC")

        new_img = cv2.rectangle(new_img, (x_one, y_one), (x_two, y_two), (255, 0, 0), 2)
        cv2.imshow("SC", new_img)
        #print(x_one, y_one, x_two, y_two)

        key = cv2.waitKey(1)

        if key == 27:
            break

    return y_one, y_two, x_one, x_two

def getColors(pixels, crop_img):
    res = []
    for pixel in pixels:
        BGR = (pixel[0], pixel[1], (crop_img[pixel[1]][pixel[0]][0], crop_img[pixel[1]][pixel[0]][1], crop_img[pixel[1]][pixel[0]][2]))
        res.append(BGR)

    print(res)

def calibrate(img):
    y_one, y_two, x_one, x_two = getCropCoords(img)

    print("Your crop selection is:", (y_one, y_two, x_one, x_two))

    crop_img = crop(img, (y_one, y_two, x_one, x_two))

    # cv2.imwrite("crop.png", crop_img)

    # cv2.imshow(crop_img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    fig, ax = plt.subplots()

    im = ax.imshow(crop_img, interpolation='none')
    fig.colorbar(im, ax=ax)

    ax.set_title('An Image', size=20)

    plugins.connect(fig, plugins.MousePosition(fontsize=14))

    mpld3.show()

    pixels = []

    print("Select Pixels: (enter 'stop' to stop)")

    while True:
        x = input("Enter x: ")
        y = input("Enter y: ")
        if x.isnumeric() and y.isnumeric():
            pixels.append((int(x), int(y)))
        elif x == 'stop' or y == 'stop':
            break

    getColors(pixels, crop_img)

def moveClick(x, y):
    pyautogui.moveTo(x, y, 0.1)
    time.sleep(0.25)
    pyautogui.click()

def mousePos(seconds=10):
    for i in range(seconds):
        time.sleep(1)
        print(pyautogui.position())

def screenshot():
    img = pyautogui.screenshot("screenshot.png")
    time.sleep(1)
    img = cv2.imread("screenshot.png", 1)
    return img

def crop(img, crop_dim):
    return img[crop_dim[0]:crop_dim[1], crop_dim[2]:crop_dim[3]]

def pix_eval(img, crop_dim, point_colors, variance):
    crop_img = crop(img, crop_dim)

    # cv2.imshow("img", crop_img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()

    #Compare pixels
    for pix in point_colors:
        crop_check = crop_img[pix[1]:pix[1] + 1, pix[0]:pix[0] + 1][0][0]
        #print()
        #print(crop_check)
        #print(pix[2])
        for i in range(len(crop_check)):

            pix_thresh = [pix[2][i]]
            for j in range(variance * -1, variance + 1):
                pix_thresh.append(pix[2][i] + j)

            if crop_check[i] not in pix_thresh:
                return False
    return True

def acceptMissionUndock():
    #Accept Mission
    moveClick(1107, 573)
    time.sleep(1)

    #Click Item Hangar
    moveClick(184, 168)
    time.sleep(0.2)

    #Click Cargo
    pyautogui.moveTo(328, 146, 0.5)
    time.sleep(0.5)

    #Drag Cargo
    pyautogui.mouseDown()
    pyautogui.moveTo(212, 101, 0.5)
    pyautogui.mouseUp()
    time.sleep(1)

    #Undock
    moveClick(1708, 233)

    time.sleep(15)

    #Set Destination
    for i in range(5):
        moveClick(358, 550 + i * 20)

def returnToStation():
    #Complete Mission
    moveClick(1107, 573)
    time.sleep(2)

    #Request New Mission
    moveClick(1107, 573)
    time.sleep(1)

    #Click station Location
    pyautogui.moveTo(748, 140, 0.5)
    pyautogui.rightClick()
    time.sleep(0.5)

    #Set Destination Back to Station
    moveClick(806, 172)
    time.sleep(1)

    #Undock
    moveClick(1708, 233)
    time.sleep(10)

def onRoute(img):
    undock_crop = (207, 256, 1639, 1809)
    undock_colors = [(80, 25, (175, 200, 209)), (97, 20, (154, 185, 197))]

    #Check if in station
    if pix_eval(img, undock_crop, undock_colors, 10):
        return True
    else:
        return False

def time_in_range(start, end, x):
    """Return true if x is in the range [start, end]"""
    if start <= end:
        return start <= x <= end
    else:
        return start <= x or x <= end

def main():
    done = False
    #acceptMissionUndock()
    repeat = 20
    repeat *= 2

    while repeat > 0:
        img = screenshot()
        state = onRoute(img)

        #Stop at downtime
        if time_in_range(6, 7, datetime.now().hour):
            break

        #Stop computer from sleeping
        pyautogui.press('volumedown')
        time.sleep(1)
        pyautogui.press('volumeup')

        if state:
            #print("At Station")
            #break
            #repeat -= 1
            if not done:
                #print("Going Back")
                done = True
                returnToStation()
            elif done:
                #print("Doing Mission")
                done = False
                acceptMissionUndock()
        else:
            #print("Still Warping")
            #Click Warp
            moveClick(1528, 249)
            time.sleep(0.25)

            for i in range(10):
                moveClick(1485, 141)
                time.sleep(1)

time.sleep(3)
main()
#calibrate(screenshot())
#acceptMissionUndock()
#returnToStation()
#mousePos()


#!/usr/bin/python3
""" See problem description in README.md """

def pascal_triangle(n):
    """Returns the first n rows of Pascal's Triangle

    Args:
        n (int): number of rows to return

    Return:
        List[List]: n rows of pascal's triangle
    """

    pascal = []
    for i in range(0, n):
        row = [1]
        if i:
            row += [prev_row[j] + prev_row[j - 1] for j in range(1, i)] + [1]
        pascal.append(row)
        prev_row = row
    return pascal


#!/usr/bin/env python

"""
Unit tests for Interval Data Class

- test_create_interval
- test_interval_properties
- test_interval_conversion
- test_interval_hash
- test_interval_contains
- test_interval_overlaps
- test_interval_intersect
- test_interval_union
- test_interval_random_values
- test_interval_random_intervals
- test_interval_from_intersect
- test_interval_from_union
- test_interval_from_object
- test_interval_from_text
"""

from dataclasses import asdict, astuple
from typing import List
from unittest import TestCase

from numpy import mean

from sources.core import Interval

class TestInterval(TestCase):

  test_intervals: List[Interval]
  overlaps: List[List[bool]]

  def setUp(self):
    self.test_intervals = []
    self.test_intervals.append(Interval(-10, 25))
    self.test_intervals.append(Interval(10.5, 45))
    self.test_intervals.append(Interval(-10.5, 45))
    self.test_intervals.append(Interval(10.5, -45))
    self.test_intervals.append(Interval(-10.5, -45))
    self.test_intervals.append(Interval(5, 5))
    self.test_intervals.append(Interval(5, 6))
    self.overlaps = [
      [True,  True,  True,  True,  False, True,  True],
      [True,  True,  True,  False, False, False, False],
      [True,  True,  True,  True,  False, True,  True],
      [True,  False, True,  True,  True,  True,  True],
      [False, False, False, True,  True,  False, False],
      [True,  False, True,  True,  False, True,  False],
      [True,  False, True,  True,  False, False, True]
    ]

  def test_create_interval(self):
    test_intervals = []
    test_intervals.append(Interval(10.5, 20))
    test_intervals.append(Interval(20, '10.5'))
    test_intervals.append(Interval(**{'lower': 10.5, 'upper': 20}))
    test_intervals.append(Interval(*('20', '10.5')))

    for interval in test_intervals:
      self.assertEqual(interval.lower, 10.5)
      self.assertEqual(interval.upper, 20)
      self.assertTrue(isinstance(interval.lower, float))
      self.assertTrue(isinstance(interval.upper, float))

  def test_interval_properties(self):
    for interval in self.test_intervals:
      #print(f'{interval}: length={interval.length} midpoint={interval.midpoint}')
      self.assertEqual(interval.length, interval.upper - interval.lower)
      self.assertEqual(interval.midpoint, mean([interval.lower, interval.upper]))

  def test_interval_conversion(self):
    for interval in self.test_intervals:
      #print(f'{interval}: dict={asdict(interval)}, tuple={astuple(interval)}')
      self.assertEqual(asdict(interval), {'lower': interval.lower, 'upper': interval.upper})
      self.assertEqual(astuple(interval), (interval.lower, interval.upper))

  def test_interval_hash(self):
    intervals = {}
    for interval in self.test_intervals:
      intervals[interval] = interval.length
    for interval in self.test_intervals:
      other = Interval(interval.lower, interval.upper)
      self.assertTrue(interval in intervals)
      self.assertEqual(interval.length, intervals[interval])
      self.assertTrue(interval == other)
      self.assertTrue(hash(interval) == hash(other))

  def test_interval_contains(self):
    interval = Interval(-5, 15)
    self.assertTrue(interval.lower in interval)
    self.assertTrue(interval.upper in interval)
    self.assertTrue(interval.midpoint in interval)
    self.assertTrue((interval.lower + 0.1) in interval)
    self.assertTrue((interval.upper - 0.1) in interval)
    self.assertFalse(interval.contains(interval.lower, inc_lower=False))
    self.assertFalse(interval.contains(interval.upper, inc_upper=False))
    self.assertFalse((interval.lower - 0.1) in interval)
    self.assertFalse((interval.upper + 0.1) in interval)

  def test_interval_encloses(self):
    interval = Interval(-5, 5)
    test_intervals = []
    test_intervals.append(Interval(-6, 4))
    test_intervals.append(Interval(-4, 4))
    test_intervals.append(Interval(-2, 2))
    test_intervals.append(Interval(4, 6))
    test_intervals.append(Interval(-5, 5))
    test_intervals.append(Interval(-6, 6))

    for subinterval in test_intervals:
      comparsion = interval.lower <= subinterval.lower <= subinterval.upper <= interval.upper
      #print(f'{subinterval} in {interval}: expect={comparsion} actual={subinterval in interval}')
      self.assertEqual(subinterval in interval, comparsion)

  def test_interval_overlaps(self):
    for i, first in enumerate(self.test_intervals):
      for j, second in enumerate(self.test_intervals):
        #print(f'{first} and {second}: expect={self.overlaps[i][j]}, actual={first.overlaps(second)}')
        self.assertEqual(first.overlaps(second), self.overlaps[i][j])

  def test_interval_intersect(self):
    for i, first in enumerate(self.test_intervals):
      for j, second in enumerate(self.test_intervals):
        intersect = first.intersect(second)
        if self.overlaps[i][j]:
          expected = first if first == second \
                           else Interval(max(first.lower, second.lower),
                                         min(first.upper, second.upper))

          #print(f'{first} and {second}:')
          #print(f'  expect={expected}')
          #print(f'  actual={intersect}')
          #print(f'  length={intersect.length}')
          self.assertEqual(intersect, expected)
        else:
          #print(f'{first} and {second}:')
          #print(f'  expect=None')
          #print(f'  actual={intersect}')
          self.assertEqual(intersect, None)

  def test_interval_union(self):
    for first in self.test_intervals:
      for second in self.test_intervals:
        union = first.union(second)
        #print(f'{first} and {second}:')
        #print(f'  union={union}')
        #print(f'  length={union.length}')
        self.assertTrue(first in union)
        self.assertTrue(second in union)

  def test_interval_random_values(self):
    interval = Interval(-5, 15)
    randoms = interval.random_values(5)
    #print(f'{interval}:')
    for value in randoms:
      #print(f'- {value}')
      self.assertTrue(interval.contains(value, inc_upper=False))

  def test_interval_random_interval(self):
    interval = Interval(-5, 15)
    randoms  = interval.random_intervals(5, Interval(0.25, 0.75))
    randoms += interval.random_intervals(5, Interval(0.25, 0.75), precision=0)
    #print(f'{interval}:')
    for subinterval in randoms:
      #print(f'- {subinterval}')
      self.assertTrue(subinterval in interval)

  def test_interval_from_intersect(self):
    intervals = [Interval(-x, x) for x in range(5, 1, -1)]
    for i in range(1, len(intervals)):
      intersect = Interval.from_intersect(intervals[0:i+1])
      #print(f'{intersect}')
      self.assertEqual(intervals[i], intersect)

    intervals = [Interval(x, x + 1) for x in range(5)]
    intersect = Interval.from_intersect(intervals)
    #print(f'{intersect}')
    self.assertEqual(None, intersect)

  def test_interval_from_union(self):
    intervals = [Interval(x, x + 1) for x in range(5)]
    for i in range(1, len(intervals)):
      union = Interval.from_union(intervals[0:i+1])
      #print(f'{union}')
      self.assertEqual(union, Interval(0, i + 1))

  def test_interval_from_object(self):
    test_interval = Interval(10.5, 20)
    objects = []
    objects.append([10.5, 20])
    objects.append((10.5, 20))
    objects.append({'lower': 10.5, 'upper': 20})

    for object in objects:
      #print(f'{object}')
      self.assertEqual(test_interval, Interval.from_object(object))

  def test_interval_from_text(self):
    test_interval = Interval(10.5, 20)
    texts = []
    texts.append(('[10.5,20]', 'json'))
    texts.append(('[10.5,20]', 'literal'))
    texts.append(('(10.5,20)', 'literal'))
    texts.append(('{"lower":10.5,"upper":20}', 'json'))
    texts.append(('{"lower":10.5,"upper":20}', 'literal'))
    texts.append(("{'lower':10.5,'upper':20}", 'literal'))

    for text in texts:
      #print(f'text="{text[0]}"' if "'" in text else f"text='{text[0]}'")
      #print(f'format={text[1]}')
      self.assertEqual(test_interval, Interval.from_text(*text))


import tensorflow as tf
import matplotlib.pyplot as plt

from tensorflow.keras.datasets import cifar10

#em jupyter, use esse comando
#%matplotlib inline

# Configurando o nome das classes que serão previstas
class_names = ['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']

# Carregando a base de dados
(X_train, y_train), (X_test, y_test) = cifar10.load_data()

#normalizar as imagens
X_train = X_train / 255.0
X_test = X_test / 255.0

#mostrar uma imagem aleatória
plt.imshow(X_test[1])

#configurando camadas
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, padding="same", activation="relu", input_shape=[32, 32, 3]))
model.add(tf.keras.layers.Conv2D(filters=32, kernel_size=3, padding="same", activation="relu"))
model.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2, padding='valid'))
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=3, padding="same", activation="relu"))
model.add(tf.keras.layers.Conv2D(filters=64, kernel_size=3, padding="same", activation="relu"))
model.add(tf.keras.layers.MaxPool2D(pool_size=2, strides=2, padding='valid'))
model.add(tf.keras.layers.Flatten())
model.add(tf.keras.layers.Dense(units=128, activation='relu'))
model.add(tf.keras.layers.Dense(units=10, activation='softmax'))
model.compile(loss="sparse_categorical_crossentropy", optimizer="Adam", metrics=["sparse_categorical_accuracy"])

#configurando as epochs
model.fit(X_train, y_train, epochs=5)

test_loss, test_accuracy = model.evaluate(X_test, y_test)

print("Test accuracy: {}".format(test_accuracy))


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

from functools import partial

import re
import tensorflow as tf

def session(graph=None, allow_soft_placement=True,
            log_device_placement=False, allow_growth=True):
    """Return a Session with simple config."""
    config = tf.ConfigProto(allow_soft_placement=allow_soft_placement,
                            log_device_placement=log_device_placement)
    config.gpu_options.allow_growth = allow_growth
    return tf.Session(graph=graph, config=config)

def summary(tensor_collection,
            summary_type=['mean', 'stddev', 'max', 'min', 'sparsity', 'histogram'],
            scope=None):
    """Summary.

    Usage:
        1. summary(tensor)
        2. summary([tensor_a, tensor_b])
        3. summary({tensor_a: 'a', tensor_b: 'b})
    """
    def _summary(tensor, name, summary_type):
        """Attach a lot of summaries to a Tensor."""
        if name is None:
            # Remove 'tower_[0-9]/' from the name in case this is a multi-GPU training
            # session. This helps the clarity of presentation on tensorboard.
            name = re.sub('%s_[0-9]*/' % 'tower', '', tensor.name)
            name = re.sub(':', '-', name)

        summaries = []
        if len(tensor.shape) == 0:
            summaries.append(tf.summary.scalar(name, tensor))
        else:
            if 'mean' in summary_type:
                mean = tf.reduce_mean(tensor)
                summaries.append(tf.summary.scalar(name + '/mean', mean))
            if 'stddev' in summary_type:
                mean = tf.reduce_mean(tensor)
                stddev = tf.sqrt(tf.reduce_mean(tf.square(tensor - mean)))
                summaries.append(tf.summary.scalar(name + '/stddev', stddev))
            if 'max' in summary_type:
                summaries.append(tf.summary.scalar(name + '/max', tf.reduce_max(tensor)))
            if 'min' in summary_type:
                summaries.append(tf.summary.scalar(name + '/min', tf.reduce_min(tensor)))
            if 'sparsity' in summary_type:
                summaries.append(tf.summary.scalar(name + '/sparsity', tf.nn.zero_fraction(tensor)))
            if 'histogram' in summary_type:
                summaries.append(tf.summary.histogram(name, tensor))
        return tf.summary.merge(summaries)

    if not isinstance(tensor_collection, (list, tuple, dict)):
        tensor_collection = [tensor_collection]

    with tf.name_scope(scope, 'summary'):
        summaries = []
        if isinstance(tensor_collection, (list, tuple)):
            for tensor in tensor_collection:
                summaries.append(_summary(tensor, None, summary_type))
        else:
            for tensor, name in tensor_collection.items():
                summaries.append(_summary(tensor, name, summary_type))
        return tf.summary.merge(summaries)

def load_checkpoint(ckpt_dir_or_file, session, var_list=None):
    """Load checkpoint.

    This function add some useless ops to the graph. It is better
    to use tf.train.init_from_checkpoint(...).
    """
    if os.path.isdir(ckpt_dir_or_file):
        ckpt_dir_or_file = tf.train.latest_checkpoint(ckpt_dir_or_file)

    restorer = tf.compat.v1.train.Saver(var_list)
    restorer.restore(session, ckpt_dir_or_file)
    print(' [*] Loading checkpoint succeeds! Copy variables from % s!' % ckpt_dir_or_file)


# -*- coding: utf-8 -*-
from __future__ import print_function, unicode_literals

from django.core.management.base import BaseCommand
from django.db import transaction

from candidates.models import (
    AreaExtra, OrganizationExtra, PostExtra, PartySet, PostExtraElection, MembershipExtra, PersonExtra, check_constraints
)
from candidates.views import get_change_metadata
from elections.models import Election
from popolo.models import Organization, Post, Person, Membership

import csv
import re
import string

from candidates.utils import strip_accents

PARTY_SET_SLUG = 'kenya_2017'
PARTY_SET_NAME = 'Register of Politial Parties'

PRESIDENCY_CANDIDATES_FILE = '2017_candidates_presidency.csv'
PRESIDENCY_ELECTION_SLUG = 'pres-2017'
PRESIDENCY_POST_SLUG = 'president'

SENATE_CANDIDATES_FILE = '2017_candidates_senate.csv'
SENATE_ELECTION_SLUG = 'senate-2017'
SENATE_POST_SLUG_PREFIX = 'senator'

WR_CANDIDATES_FILE = '2017_candidates_wr.csv'
WR_ELECTION_SLUG = 'wr-2017'
WR_POST_SLUG_PREFIX = 'wr'

GOV_CANDIDATES_FILE = '2017_candidates_governors.csv'
GOV_ELECTION_SLUG = 'governor-2017'
GOV_POST_SLUG_PREFIX = 'governor'

ASSEMBLY_CANDIDATES_FILE = '2017_candidates_assembly.csv'
ASSEMBLY_ELECTION_SLUG = 'assembly-2017'
ASSEMBLY_POST_SLUG_PREFIX = 'assembly'

WARD_CANDIDATES_FILE = '2017_candidates_county_assemblies.csv'
WARD_ELECTION_SLUG_PREFIX = 'county-assembly-2017'
WARD_POST_SLUG_PREFIX = 'county-assembly'

ELECTIONS = [
    {
        'CANDIDATES_FILE': '2017_candidates_presidency.csv',
        'ROW_TO_ELECTION_SLUG': lambda row: 'pr-2017',
        'ROW_TO_POST_ID': lambda row: 'pr-1',
        'CANDIDATE_ID_PREFIX': 'pr'
    },
    {
        'CANDIDATES_FILE': '2017_candidates_senate.csv',
        'ROW_TO_ELECTION_SLUG': lambda row: 'se-2017',
        'ROW_TO_POST_ID': lambda row: 'se-{0}'.format(row['County Code']),
        'CANDIDATE_ID_PREFIX': 'se'
    },
    {
        'CANDIDATES_FILE': '2017_candidates_wr.csv',
        'ROW_TO_ELECTION_SLUG': lambda row: 'wo-2017',
        'ROW_TO_POST_ID': lambda row: 'wo-{0}'.format(row['County Code']),
        'CANDIDATE_ID_PREFIX': 'wo'
    },
    {
        'CANDIDATES_FILE': '2017_candidates_governors.csv',
        'ROW_TO_ELECTION_SLUG': lambda row: 'go-2017',
        'ROW_TO_POST_ID': lambda row: 'go-{0}'.format(row['County Code']),
        'CANDIDATE_ID_PREFIX': 'go'
    },
    {
        'CANDIDATES_FILE': '2017_candidates_assembly.csv',
        'ROW_TO_ELECTION_SLUG': lambda row: 'na-2017',
        'ROW_TO_POST_ID': lambda row: 'na-{0}'.format(row['Constituency Code']),
        'CANDIDATE_ID_PREFIX': 'na'
    },
    {
        'CANDIDATES_FILE': '2017_candidates_county_assemblies.csv',
        'ROW_TO_ELECTION_SLUG': lambda row: 'co-{0}-2017'.format(row['County Code']),
        'ROW_TO_POST_ID': lambda row: 'co-{0}'.format(row['Ward Code']),
        'CANDIDATE_ID_PREFIX': 'co'
    }
]

class Command(BaseCommand):

    def get_or_create_person(self, scheme, identifier, name, surname, other_names, gender=None):

        try:
            person = Person.objects.get(
                identifiers__scheme=scheme,
                identifiers__identifier=identifier
            )
            person.name = name
        except Person.DoesNotExist:
            person = Person.objects.create(
                name=name
            )

            person.identifiers.create(
                scheme=scheme,
                identifier=identifier
            )

        person.family_name = surname
        person.given_name = other_names

        if gender:
            person.gender = gender

        person.save()

        personExtra, created = PersonExtra.objects.get_or_create(
            base=person,
            defaults={
                'versions': '[]'
            }
        )

        return person

    def get_or_create_party(self, identifier, name, party_set):

        party_slug = 'party:' + identifier

        try:
            party = Organization.objects.get(extra__slug=party_slug)
        except Organization.DoesNotExist:
            party = Organization.objects.create(
                name=name,
                classification='Party'
            )
            partyExtra, created = OrganizationExtra.objects.update_or_create(
                base=party,
                defaults={
                    'slug': party_slug
                }
            )

        # This should be in the party set!
        party_set.parties.add(party)

        return party

    def get_or_create_membership(self, person, post, party, election):

        membership, created = Membership.objects.get_or_create(
            person=person,
            post=post,
            on_behalf_of=party,
            role=election.candidate_membership_role
        )

        # We assume that each membership needs only one Extra object
        membershipExtra, created = MembershipExtra.objects.update_or_create(
            base=membership,
            defaults={
                'election': election,
                'elected': None
            }
        )

        source = "Added from initial import."

        change_metadata = get_change_metadata(None, source)
        person.extra.record_version(change_metadata)
        person.extra.save()

    def import_candidates_for_election(self, election, party_set):

        # Get the candidates
        reader = csv.DictReader(open('elections/kenya/data/' + election['CANDIDATES_FILE']))

        election_objects = {}

        for i, row in enumerate(reader):

            election_slug = election['ROW_TO_ELECTION_SLUG'](row)

            # Make sure the election exists
            election_object = election_objects.get(
                election_slug,
                Election.objects.get(slug=election_slug)
            )

            # Assemble a coherent name
            surname = string.capwords(row['Surname'])
            other_names = string.capwords(row['Other Names'])

            name = other_names + ' ' + surname

            # Build an identifier
            identifier = '{0}-{1}'.format(election['CANDIDATE_ID_PREFIX'], row['No'])

            person = self.get_or_create_person(
                'iebc-{0}-import-id'.format(election['CANDIDATE_ID_PREFIX']),
                identifier,
                name,
                surname,
                other_names,
                row['Gender'].title()
            )

            # Add the party!
            party = self.get_or_create_party(
                identifier=row['Party Code'],
                name=row['Political Party Name'].title(),
                party_set=party_set
            )

            # At this point we have a person and a party, so we can go ahead and create a membership

            # First, get the post.
            # If this post doesn't exist, we should drop out because someone hasn't run the posts script.
            post_slug = election['ROW_TO_POST_ID'](row)
            post = Post.objects.get(extra__slug=post_slug)

            membership = self.get_or_create_membership(
                person=person,
                post=post,
                party=party,
                election=election_object
            )

            if not (i + 1) % 50:
                print('Imported {}'.format(i + 1))

    @transaction.atomic
    def handle(self, *args, **options):

        # Make sure the PartySet exists
        party_set, created = PartySet.objects.update_or_create(
            slug=PARTY_SET_SLUG,
            defaults={
                'name': PARTY_SET_NAME
            }
        )

        for election in ELECTIONS:
            print('Importing candidates for election: {}'.format(election['CANDIDATES_FILE']))
            self.import_candidates_for_election(election, party_set)

        errors = check_constraints()
        if errors:
            for e in errors:
                print(e)
            raise Exception('Constraint errors detected. Aborting.')


import asyncio

import discord
from discord.ext import commands

class Help(commands.Cog, name="help"):
    def __init__(self, bot):
        self.bot = bot

    @commands.command(name="help")
    async def help(self, context):
        """
        List all commands from every Cog the bot has loaded.
        """
        embed = discord.Embed(title="Help", description="List of available commands:", color=0x42F56C)
        for i in self.bot.cogs:
            if i.capitalize() == "Help":
                continue
            cog = self.bot.get_cog(i.lower())
            commands = cog.get_commands()
            command_list = [command.name for command in commands]
            command_description = [command.help for command in commands]
            help_text = '\n'.join(f'{self.bot.command_prefix}{n} - {h}' for n, h in zip(command_list, command_description))
            embed.add_field(name=i.capitalize(), value=f'```{help_text}```', inline=False)
        await context.send(embed=embed)

    @commands.command(pass_context=True)
    @commands.has_permissions(administrator=True)
    async def clean(self, ctx, limit: int):
        await ctx.message.delete()
        await ctx.channel.purge(limit=limit)
        msg = await ctx.send('Cleared by {}'.format(ctx.author.mention))
        await asyncio.sleep(3)
        await msg.delete()

def setup(bot):
    bot.add_cog(Help(bot))


#This script first read the result files, then create an output in the required format for correlation

#plot mean of RT
#x-axis is the loss rate, left y-axis RT, rigth y-axis MBytes
#two lines: 1) RT to load the image, 2) RT to explore the 360 image (drag and drop mouse action)

import sys, os
import numpy as np
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import math
import scipy.stats

#===========================Prepare objective results=================
#=====================Initialize parameters===============
#input arguments
app="ImageView"
method=["display_updates_2"] #["autoit","display_updates","display_updates_2"] #"RT_marker_packets_2"
run_no="1-Pics13"
res_dir="/home/harlem1/SEEC/Windows-scripts/results"

#===================Read data======================
#two arrays RT and Bytes. each array has all the runs
for meth in method:
    file_name = app + "_RT_"+meth+"_run_"+str(run_no)
    #read data, all the colunm
    data_meth = "data-" + meth
    globals()[data_meth] = np.loadtxt(res_dir +'/' + file_name, delimiter=' ') #,unpack=True)
    no_tasks = ((globals()[data_meth][0].size - 2)/2) #find how many images are there in each run, -2 to remove the rtt and loss values

    #read only rt we don't need bytes
    rt_meth = "rt_"+meth
    globals()[rt_meth] = globals()[data_meth][:,np.arange(2,2+no_tasks)] #read specific col. of rt, remember the 1st two are rtt and loss so skip

# read rtt and loss values and create arrays based on loss values; just read it once it is the same for all results files
rtt  = globals()[data_meth][:,0]
loss = globals()[data_meth][:,1]

#==============Pre-process data===================
#find unique loss values
loss_uniq = np.unique(loss)
print("unique loss values = ",loss_uniq)
rtt_unique = np.unique(rtt)

#find indices where loss value equal to specific value and RTT of 0
rtt_0 = np.where(rtt==0)
print("rtt_0 ", rtt_0)

for l in loss_uniq:
    temp1 = "loss_" + str(l)
    x = np.where(loss==l)
    globals()[temp1] = np.intersect1d(x,rtt_0)
    total_runs=len(globals()[temp1])
    print("total_runs_",total_runs)
    #print("indices, " ,temp1,"  = ",globals()[temp1])
    #convert it to a list structure to easily access elemts in a loop
    temp2 = "loss_" + str(l) + "_index"
    globals()[temp2] = []

    #add indices to the list, one list for each loss value
    for i in range(len(globals()[temp1])):
        globals()[temp2].append(globals()[temp1][i])

#create arrays based on loss value, each array has all the images in a row, where each row is different run
for meth in method:
    for l in loss_uniq:
        rt_loss = "rt_"+meth+"_loss_" + str(l)
        globals()[rt_loss] = []

#add elemnts to the array based on the found indecies
for meth in method:
    rt_meth = "rt_"+meth
    for l in loss_uniq:
        temp2 = "loss_" + str(l) + "_index"
        rt_loss = "rt_"+meth+"_loss_" + str(l)
        for i in globals()[temp2]:
            globals()[rt_loss].append(globals()[rt_meth][i])

#for plotting, find geometric mean of each run, then find arthimetic mean of geo-mean, then append to array
#find geo-mean of each run, then find arithmetic mean of geo-mean
#create empty arrays to hold geo-mean
for meth in method:
    rt_amean = "rt_"+meth +"_amean" #arithmetic mean for the 3 loss values
    globals()[rt_amean] = [] #array to hold arthimetic mean for all loss values
    for l in loss_uniq:
        rt_loss = "rt_"+meth+"_loss_" + str(l)
        rt_loss_gmean = "rt_"+meth+"_loss_" + str(l) + "_geomean"
        globals()[rt_loss_gmean] = scipy.stats.mstats.gmean(globals()[rt_loss], axis=1)
        #add it to the arithmetic meean array
        globals()[rt_amean].append(np.mean(globals()[rt_loss_gmean]))

    print(rt_amean, " ", globals()[rt_amean])

#===============prepare subjective results============
app="ImageView-pics2"
run_name = "pilot-and-trial"

data_app = "data_"+app
globals()[data_app] = np.genfromtxt(res_dir+"/merged-"+app+"-QoE-results-"+run_name+".txt", delimiter=' ')

#seperate by app and packet loss rate. rtt is always 0 so don't worry about it
#also have another array based on app only, each array in the array have all the values for one of the loss values
data_app = "data_"+app
app_loss_all = app + "_loss_all"
app_mean = app + "_mean"
globals()[app_mean] = []

for l in loss_uniq:
    #create array based on app and loss value to hold QoS
    app_loss = app+"_"+str(l)
    globals()[app_loss] = []
    #read rows with specific loss value colunm 2 is loss value
    temp = globals()[data_app][np.where(globals()[data_app][:,2] == l)]
    globals()[app_mean].append(np.mean(temp[:,3]))
print(app_mean," ",globals()[app_mean])

#======================== find correlation=========================

rt_amean = "rt_"+meth +"_amean"
app_mean = app + "_mean"

obj = globals()[rt_amean]
sub = globals()[app_mean]

coef = scipy.stats.pearsonr(obj, sub)

print("coef = ",coef)