from collections import deque
from math import inf

#uproszczenie:
#uniemożliwić komunikację z A do B(nie z B do A).Linie telegraficzne są skierowane.

#min_cut = max_flow

def BFS(G,s,t): #indeksuje grafy od zera, lekko zmodyfikowany BFS
    n = len(G)
    Q = deque()
    visited = [False]*n
    d = [-1]*n #odleglosci, jesli -1 to znaczy ze nie ma polaczenia
    parents = [None]*n

    d[s] = 0
    Q.append(s)
    visited[s] = True

    while Q:
        u = Q.popleft()
        for i in range(n):
            if not visited[i] and G[u][i] != 0:
                visited[i] = True
                d[i] = d[u] + 1
                parents[i] = u
                Q.append(i)
                if i == t:
                    return True,parents

    return False,parents

def BFS_classic(G, s): #indeksuje grafy od zera
    n = len(G)
    Q = deque()
    visited = [False]*n
    d = [-1]*n #odleglosci, jesli -1 to znaczy ze nie ma polaczenia
    parents = [None]*n

    d[s] = 0
    Q.append(s)
    visited[s] = True

    while Q:
        u = Q.popleft()
        for i in range(n):
            if not visited[i] and G[u][i] != 0:
                visited[i] = True
                d[i] = d[u] + 1
                parents[i] = u
                Q.append(i)

    return visited

def edmonds_karp(G,s,t):
    path = True
    max_flow = 0

    while(path):
        path, parents = BFS(G,s,t)

        if path:
            temp_max = inf
            i = t
            while i != s:
                temp_max = min(temp_max,G[parents[i]][i]) #szukam "najwęższej krawędzi" w znalezionej ścieżce
                i = parents[i]

            max_flow += temp_max #maksymalizuje przepływ

            i = t
            while i != s: #po znalezionej ścieżce odejmuje maksymalny przepływ w stronę skierowaną(możliwy przepływ do wykorzystania)
                G[parents[i]][i] -= temp_max
                G[i][parents[i]] += temp_max #w drugą stronę dodaje ten przepływ, tyle można wyprowadzić
                i = parents[i]

    return G

def subversion(cities,lines,A,B):
    S = [] #zbiory na wierzchołki
    T = []
    n = len(lines)
    k = len(cities)

    G = [[0]*k for _ in range(k)]

    for i in range(n):
        G[lines[i][0]][lines[i][1]] = lines[i][2]

    G = edmonds_karp(G,A,B) #G to siec residualna

    visited = BFS_classic(G,A)

    for i in range(k): #generowanie zbiorów
        if visited[i]:
            S.append(i)

    for i in range(k):
        if not visited[i]:
            T.append(i)

    x = len(S)
    y = len(T)
    min_val = 0
    result = []

    for i in range(x): #szukanie krawędzi miedzy zbiorami S oraz T w sieci residualnej, ich suma to max_flow (min_cut)
        for j in range(y):
            if G[S[i]][T[j]] != 0:
                min_val += G[S[i]][T[j]]
                result.append((T[j],S[i],G[S[i]][T[j]]))
            elif G[T[j]][S[i]]:
                min_val += G[T[j]][S[i]]
                result.append((S[i],T[j], G[T[j]][S[i]]))
    return min_val,result

#(5, [(2, 1, 3), (4, 1, 2)])
cities = [0, 1, 2, 3, 4] #dla uproszczenia daje indeksy samiast stringów, mozna zmapować dla w razie potrzeb
lines = [[0, 3, 3],
        [0, 2, 4],
        [3, 4, 3],
        [2, 4, 2],
        [2, 1, 3],
        [4, 1, 2]]

print(subversion(cities,lines,0,1))

#(3, [(0, 2, 1), (1, 2, 1), (3, 2, 1)])
cities = [0,1,2,3]
lines = [[0,1,2],
         [0,3,2],
         [0,2,1],
         [3,2,1],
         [1,2,1]]
print(subversion(cities,lines,0,2))

#(3, [(0, 2, 1), (1, 2, 1), (3, 2, 1)])
cities = [0,1,2,3,4]
lines = [[0,1,2],
         [0,3,2],
         [0,2,1],
         [3,2,1],
         [1,2,1],
         [2,4,4]]
print(subversion(cities,lines,0,4))

#(2, [(2, 4, 2)])
cities = [0,1,2,3,4]
lines = [[0,1,2],
         [0,3,2],
         [0,2,1],
         [3,2,1],
         [1,2,1],
         [2,4,2]]
print(subversion(cities,lines,0,4))


from absl import logging
import abc
from collections import namedtuple, defaultdict
from enum import Enum
import socket
import os
import threading
import time
from typing import Dict, NamedTuple

import numpy as np
from kazoo.retry import KazooRetry
from monolith.native_training.zk_utils import MonolithKazooClient
from kazoo.client import KazooState
from kazoo.exceptions import NoNodeError, NodeExistsError

from monolith.native_training import consul
from monolith.native_training.zk_utils import default_zk_servers
from monolith.native_training.mlp_utils import MLPEnv, check_port

class ServiceDiscoveryType(Enum):
  PRIMUS = 1
  CONSUL = 2
  ZK = 3
  MLP = 4

class ServiceDiscovery(abc.ABC):

  @abc.abstractmethod
  def register(self, name: str, index: int, addr: str):
    """Register the port to the index"""

  @abc.abstractmethod
  def deregister(self, name: str, index: int, addr: str):
    """Deregister the port from index."""

  def query(self, name) -> Dict[int, str]:
    """Returns a dict that maps index to str"""

  def close(self):
    pass

_HostAndPort = namedtuple("_HostAndPort", ["host", "port"])

_RETRY_MAX_BACKOFF_SECS = 5

def retry_with_socket_error(http_call):
  tries = 5
  for i in range(tries):
    try:
      return http_call()
    except socket.error:
      if i < tries - 1:
        time.sleep(np.random.rand() * _RETRY_MAX_BACKOFF_SECS)
        continue
      raise

class ConsulServiceDiscovery(ServiceDiscovery):

  def __init__(self, consul_id: str, retry_time_secs: float = 3.0):
    self._consul_id = consul_id
    self._client = consul.Client()
    self._retry_time_secs = retry_time_secs

  def register(self, name: str, index: int, addr: str):
    # This is best effort, deregister the address with the same name & index.
    while True:
      index_to_addr = self.query(name)
      if index in index_to_addr:
        self.deregister(name, index, index_to_addr[index])
      else:
        break
      time.sleep(self._retry_time_secs)

    host, port = self._get_host_and_port(addr)
    retry_with_socket_error(lambda: self._client.register(
        self._consul_id, port, tags={
            "index": index,
            "name": name,
            "ip": host,
        }))

    # We need to make sure we can be registered

    # We wait upto 180 secs before we think the machine is blacklisted.
    max_retries = max(2, 180 / max(1, _RETRY_MAX_BACKOFF_SECS))
    retries = 0
    while True:
      index_to_addr = self.query(name)
      if index in index_to_addr:
        break
      retries += 1
      if retries > max_retries:
        raise OSError("This machine is blacklisted by consul.")
      time.sleep(_RETRY_MAX_BACKOFF_SECS)

  def deregister(self, name: str, index: int, addr: str):
    del name
    del index
    host, port = self._get_host_and_port(addr)
    retry_with_socket_error(
        lambda: self._client.deregister(self._consul_id, port))

  def query_all(self) -> Dict[str, Dict[int, str]]:
    elements = retry_with_socket_error(
        lambda: self._client.lookup(self._consul_id, timeout=15))
    addrs = defaultdict(dict)

    for element in elements:
      name = element["Tags"]["name"]
      addr = "{}:{}".format(element["Tags"]["ip"], element["Port"])
      index = int(element["Tags"]["index"])
      addrs[name][index] = addr

    return addrs

  def query(self, name: str):
    named_addrs = self.query_all()
    return named_addrs[name]

  def _get_host_and_port(self, addr: str) -> _HostAndPort:
    components = addr.split(":")
    if len(components) != 2:
      raise ValueError("Invalid addr: {}".format(addr))
    return _HostAndPort(host=components[0], port=int(components[1]))

class TfConfigServiceDiscovery(ServiceDiscovery):

  def __init__(self, tf_config):
    self._tf_config = tf_config

  def register(self, name: str, index: int, addr: str):
    pass

  def deregister(self, name: str, index: int, addr: str):
    pass

  def query(self, name: str):
    if name == 'ps':
      addr_list = self._tf_config['cluster'][name]
    elif name == 'worker':
      if 'chief' in self._tf_config['cluster']:
        addr_list = self._tf_config['cluster']['chief'] + \
                    self._tf_config['cluster'][name]
      else:
        addr_list = self._tf_config['cluster'][name]
    else:
      raise ValueError('name must be ps/worker')

    return {i: addr for i, addr in enumerate(addr_list)}

  @property
  def server_type(self):
    task = self._tf_config['task']
    return 'worker' if task['type'] == 'chief' else task['type']

  @property
  def addr(self):
    task = self._tf_config['task']
    return self._tf_config['cluster'][task['type']][task['index']]

  @property
  def index(self):
    task = self._tf_config['task']
    if 'chief' in self._tf_config['cluster']:
      return task['index'] + 1 if task['type'] == 'worker' else task['index']
    else:
      return task['index']

class ZKListener(object):

  def __init__(self, zkds: 'ZKServiceDiscovery'):
    self._zksd = zkds
    self._has_lost = False

  def __call__(self, state: KazooState) -> None:
    if state == KazooState.LOST:
      # The connection has been confirmed dead
      logging.warning(
          "Any ephemeral nodes will need to be recreated upon re-establishing a connection."
      )
      self._has_lost = True
    elif state == KazooState.SUSPENDED:
      # Handle being disconnected from Zookeeper
      return
    else:
      # Handle being connected/reconnected to Zookeeper
      if self._has_lost:
        logging.info(
            "connected/reconnected after lost, restart updater and watcher")
        self._zksd.do_all_registrations()
        self._has_lost = False

_ZK_REGISTRATION_PERIOD = 30 * 60

class ZKServiceDiscovery(ServiceDiscovery):

  class ThreadSet(NamedTuple):
    stop: threading.Event
    wakeup: threading.Event
    thread: threading.Thread

    def stop_and_join(self):
      self.stop.set()
      self.wakeup.set()
      self.thread.join()

  def __init__(self,
               job_name: str,
               zk_server: str = None,
               max_tries: int = 3,
               delay: int = 5):
    self._max_tries = max_tries
    self._delay = delay
    # /monolith/{job_name}/server_type.index -> host:port
    self._path_prefix = '/monolith/{}'.format(job_name)
    self._lock = threading.Lock()
    self._cluster = {}
    # Maps (name, index) to thread set.
    self._threads: Dict[Tuple[str, int], ZKServiceDiscovery.ThreadSet] = {}

    try:
      zk_server = zk_server or default_zk_servers()
      self._client = MonolithKazooClient(zk_server)
      self._client.add_listener(ZKListener(self))
      self._client.start()
      self._client.ensure_path(self._path_prefix)
    except Exception as e:
      logging.error("cannot create zk client, {}".format(e))
      raise e

    self._watch_data()

  def do_all_registrations(self):
    for ts in self._threads.values():
      ts.wakeup.set()

  def _get_node_name(self, server_type: str, index: int):
    return '{}.{}'.format(server_type, index)

  def _get_path(self, server_type: str, index: int):
    return "{}/{}".format(self._path_prefix,
                          self._get_node_name(server_type, index))

  def _try_create(self, path: str, value: str):
    value_bytes = bytes(value, 'utf-8')
    try:
      self._client.create(path,
                          value=value_bytes,
                          makepath=True,
                          ephemeral=True)
    except NodeExistsError:
      self._client.set(path, value_bytes)

  def _try_delete(self, path):
    try:
      self._client.delete(path=path, recursive=True)
    except NoNodeError:
      logging.info("{path} is not exist, no need to delete".format(path=path))

  def _children_watch(self, children):
    with self._lock:
      old_children = set(
          self._get_node_name(serve_type, index)
          for serve_type in self._cluster
          for index in self._cluster[serve_type])
      new_children = set(child for child in children if child)
      added = new_children - old_children

    for node in added:
      path = '{}/{}'.format(self._path_prefix, node)
      self._client.DataWatch(path, func=self._get_data_watch(path))

  def _get_data_watch(self, path):

    def data_watch(data, stat):
      server_type, index = os.path.basename(path).split('.')
      index = int(index)

      with self._lock:
        if data is not None and len(data) > 0:
          addr = data.decode("utf-8")
          if server_type in self._cluster:
            self._cluster[server_type][index] = addr
          else:
            self._cluster[server_type] = {index: addr}
        else:
          if server_type in self._cluster:
            if index in self._cluster[server_type]:
              del self._cluster[server_type][index]

    return data_watch

  def _watch_data(self):
    self._client.ChildrenWatch(self._path_prefix, self._children_watch)

  def register(self, name: str, index: int, addr: str):
    self._internal_register(name, index, addr, register_periodically=True)

  def _periodically_register(self, name: str, index: int, addr: str,
                             stop: threading.Event, wakeup: threading.Event):
    while True:
      if wakeup.wait(_ZK_REGISTRATION_PERIOD):
        wakeup.clear()
      if stop.is_set():
        break
      try:
        self._internal_register(name, index, addr, register_periodically=False)
      except Exception:
        # This is the best effort.
        pass

  def _internal_register(self, name: str, index: int, addr: str,
                         register_periodically: bool):
    path = self._get_path(name, index)
    retry = KazooRetry(max_tries=self._max_tries, delay=self._delay)
    try:
      retry(self._try_create, path, addr)
    except Exception as e:
      logging.error("server_type: {} , index:{} register fail".format(
          name, index))
      raise e

    if register_periodically:
      stop = threading.Event()
      wakeup = threading.Event()
      thread = threading.Thread(target=self._periodically_register,
                                args=(name, index, addr, stop, wakeup),
                                daemon=True)
      thread.start()
      self._threads[(name, index)] = ZKServiceDiscovery.ThreadSet(stop=stop,
                                                                  wakeup=wakeup,
                                                                  thread=thread)

  def deregister(self, name: str, index: int, addr: str):
    path = self._get_path(name, index)
    retry = KazooRetry(max_tries=self._max_tries, delay=self._delay)
    try:
      retry(self._try_delete, path)
    except Exception as e:
      logging.error("server_type: {} , index:{} deregister fail".format(
          name, index))
      raise e
    key = (name, index)
    ts = self._threads[key]
    ts.stop_and_join()
    del self._threads[key]

  def query(self, name) -> Dict[int, str]:
    with self._lock:
      if name in self._cluster:
        return self._cluster[name]
      else:
        return {}

  def close(self):
    if self._client is not None:
      self._client.stop()
      self._client.close()
      self._client = None

    for ts in self._threads.values():
      ts.stop_and_join()

  def __del__(self):
    self.close()

class MLPServiceDiscovery(ServiceDiscovery):
  def __init__(self):
    self._mlp_env = MLPEnv()
    self._filters = set()
    self.addr = f"{self._mlp_env.host}:{self._mlp_env.port}"

  def _check(self, name: str, index: int, addr: str):
    if self._mlp_env is None:
      return
    assert name.upper() in self._mlp_env.all_roles
    assert index < self._mlp_env.num_replicas(name)
    exp_addr = self._mlp_env.get_addr(name, index=index)
    exp_host, exp_port = exp_addr.split(':')
    real_host, real_port = addr.split(':')
    assert real_host in {'local', 'localhost', '127.0.0.1', '0.0.0.0',
                         exp_host, self._mlp_env.host,
                         self._mlp_env.get_host(is_primary=False)}
    assert exp_port == real_port

  def register(self, name: str, index: int, addr: str):
    self._check(name, index, addr)
    key = f'{name.lower()}:{index}'
    if key in self._filters:
      self._filters.remove(key)

  def deregister(self, name: str, index: int, addr: str):
    self._check(name, index, addr)
    self._filters.add(f'{name.lower()}:{index}')

  def query(self, name, skip_port_check: bool = False) -> Dict[int, str]:
    assert name is not None and len(name) > 0
    if self._mlp_env is None:
      return {}
    result = {}
    for idx in range(self._mlp_env.num_replicas(name)):
      addr = self._mlp_env.get_addr(name, index=idx)
      assert addr is not None
      key = f'{name.lower()}:{idx}'
      if key not in self._filters:
        result[idx] = addr
        if name.lower() == 'ps' and not skip_port_check:
          host, port = addr.split(':')
          assert check_port(host, int(port), timeout=3600), f'{addr} connect error!'
    return result

  def deregister_all(self) -> Dict[str, Dict[int, str]]:
    if self._mlp_env is None:
      return {}
    for name, num in self._mlp_env.all_roles.items():
      for idx in range(num):
        key = f'{name.lower()}:{idx}'
        self._filters.add(key)

  def query_all(self):
    if self._mlp_env is None:
      return {}
    result = {}
    for name, num in self._mlp_env.all_roles.items():
      if name.lower() in {'ps', 'worker', 'chief'}:
        name = name.lower()
        result[name] = self.query(name, True)
    return result

  @property
  def server_type(self):
    if self._mlp_env is None:
      return None
    return self._mlp_env.role.lower()

  @property
  def index(self):
    if self._mlp_env is None:
      return None
    return self._mlp_env.index

  def close(self):
    self._mlp_env = None
    self._filters.clear()

  def __del__(self):
    self.close()

def deregister_all(consul_id: str):
  """Deregisters all records in the given consul_id."""
  discovery = ConsulServiceDiscovery(consul_id)
  named_addrs = discovery.query_all()
  for name, addrs in named_addrs.items():
    for idx, addr in addrs.items():
      discovery.deregister(name, idx, addr)


import lyricsgenius
import spotipy
from spotipy.oauth2 import SpotifyClientCredentials

class Authenticator:
    def __init__(
        self,
        spotify_client_id,
        spotify_client_secret,
        genius_api_key,
    ):
        # Initialise the tracking values
        self.genius_auth = self.authenticate_genius(genius_api_key)
        self.spotify_auth = self.authenticate_spotify(
            spotify_client_id, spotify_client_secret
        )

    def authenticate_genius(self, genius_api_key):
        genius_auth = lyricsgenius.Genius(
            genius_api_key,
            verbose=False,
        )
        return genius_auth

    def authenticate_spotify(self, spotify_client_id, spotify_client_secret):
        auth_manager = SpotifyClientCredentials(
        client_id=spotify_client_id, client_secret=spotify_client_secret
        )
        spotify_auth = spotipy.Spotify(auth_manager=auth_manager)
        return spotify_auth


from flask import Flask, jsonify
from flask_redis import Redis

app = Flask(__name__)
redis = Redis(app)

@app.route('/trends/<name>/<slug>')
def trends(name, slug):
  key = name + '/' + slug
  ranked_trends = redis.zrange(key, 0, 4, desc=True, withscores=True)
  trends = [{'term': trend[0], 'rank': trend[1]} for trend in ranked_trends]

  return jsonify({'trends': trends})

@app.route('/tweets/<name>/<slug>/<term>')
def tweets(name, slug, term):
  key = name + '/' + slug + '/' + term
  tweets = redis.lrange(key, 0, -1)

  if tweets is None:
    tweets = []

  return jsonify({'term': term, 'tweets': tweets})

if __name__ == '__main__':
  #v = redis.lrange("nba/espn/espn", 0, -1)
  app.run(host='0.0.0.0')


import tkinter as Tk

ERROR_TEXT = "'{}' n'est pas un caractère correct en base {}"
RESULT_TEXT = "'{}' en base {} vaut '{}' en base {}"

DEFAULT_START_BASE = 10
DEFAULT_ARRIVED_BASE = 2
DEFAULT_START_NUMBER = 0
DEFAULT_ARRIVED_NUMBER = 0

ALPHA = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"

def convertBase(number, base1, base2):
    global ALPHA
    n_dec = 0
    for i in range(len(number)): #conversion en base 10
        n_dec += ALPHA.index(number[i]) * (base1 ** (len(number)-i-1))
        dig = []
    while n_dec > 0: #conversion en base b2
        r = ALPHA[n_dec % base2]
        dig.append(r)
        n_dec //= base2
    return "".join(dig)[::-1]

class Gui:
    def __init__(self, root):
        self.root = root

        self.errorBase = Tk.StringVar()
        self.startNumber = Tk.StringVar()
        self.startBase = Tk.IntVar()
        self.arrivedBase = Tk.IntVar()
        self.arrivedNumber = 0
        self.resultText = Tk.StringVar()

        self.mainFrame = Tk.Frame(self.root)
        self.explicationLabel = Tk.Label(self.mainFrame, text="Bienvenue dans notre convertisseur de base.")

        self.startNumberFrame = Tk.Frame(self.mainFrame)
        self.startNumberLabel = Tk.Label(self.startNumberFrame, text="Entrez un nombre")
        self.startNumberEntry = Tk.Entry(self.startNumberFrame, textvariable=self.startNumber)

        self.startNumberErrorLabel = Tk.Label(self.startNumberFrame, textvariable=self.errorBase, fg="red")

        self.startBaseFrame = Tk.Frame(self.mainFrame)
        self.startBaseLabel = Tk.Label(self.startBaseFrame, text="En base : ")
        self.startBaseSpinBox = Tk.Spinbox(self.startBaseFrame, from_=2, to=36, textvariable=self.startBase)
        self.arrivedBaseFrame = Tk.Frame(self.mainFrame)
        self.arrivedBaseLabel = Tk.Label(self.arrivedBaseFrame, text="Vers la base : ")
        self.arrivedBaseSpinBox = Tk.Spinbox(self.arrivedBaseFrame, from_=2, to=36, textvariable=self.arrivedBase)

        self.buttonFrame = Tk.Frame(self.mainFrame)
        self.calculateButton = Tk.Button(self.buttonFrame, text="Convertir", command=self.convert)
        self.resetButton = Tk.Button(self.buttonFrame, text="Reset", command=self.reset)
        self.switchButton = Tk.Button(self.buttonFrame, text="Échanger les bases", command=self.switchBase)
        self.copyButton = Tk.Button(self.buttonFrame, text="Copier le résultat", command=self.copyResult)

        self.resultLabel = Tk.Label(self.arrivedBaseFrame, textvariable=self.resultText)

        self.packMainFrameItems()
        self.displayMainFrame()

    def packMainFrameItems(self):
        self.explicationLabel.pack()

        self.startNumberFrame.pack()
        self.startNumberLabel.pack()
        self.startNumberEntry.pack()

        self.startBaseFrame.pack()
        self.startBaseLabel.pack()
        self.startBaseSpinBox.pack()
        self.arrivedBaseFrame.pack()
        self.arrivedBaseLabel.pack()
        self.arrivedBaseSpinBox.pack()

        self.buttonFrame.pack()
        self.calculateButton.grid(row = 1, column = 1)
        self.resetButton.grid(row = 1, column = 2)
        self.switchButton.grid(row = 2, column = 1)
        self.copyButton.grid(row = 2, column = 2)

        self.startBase.set(DEFAULT_START_BASE)
        self.arrivedBase.set(DEFAULT_ARRIVED_BASE)

    def displayMainFrame(self):
        self.mainFrame.pack(expand=True, fill= Tk.BOTH)

    def convert(self):
        self.startBase.set(int(self.startBaseSpinBox.get()))
        self.arrivedBase.set(int(self.arrivedBaseSpinBox.get()))

        self.startNumber.set(self.startNumberEntry.get().upper())
        charIndex = self.checkIfNumberEntredIsCorrect()
        if charIndex != -1:
            self.errorBase.set(ERROR_TEXT.format(self.startNumber.get()[charIndex], self.startBase.get()))
            self.startNumberErrorLabel.pack()
            return

        self.startNumberErrorLabel.pack_forget()

        self.arrivedNumber = convertBase(self.startNumber.get(), self.startBase.get(), self.arrivedBase.get())

        self.resultText.set(RESULT_TEXT.format(self.startNumber.get(), self.startBase.get(), self.arrivedNumber, self.arrivedBase.get()))
        self.resultLabel.pack()

    def reset(self):
        self.startNumber.set("")
        self.arrivedNumber = DEFAULT_START_NUMBER

        self.errorBase.set("")
        self.resultText.set("")

        self.startBase.set(DEFAULT_START_BASE)
        self.arrivedBase.set(DEFAULT_ARRIVED_BASE)

        self.startNumberErrorLabel.pack_forget()
        self.resultLabel.pack_forget()

    def switchBase(self):
        b1 = self.startBase.get()
        b2 = self.arrivedBase.get()

        self.startBase.set(b2)
        self.arrivedBase.set(b1)

    def copyResult(self):
        if self.resultLabel.winfo_ismapped():
            self.root.clipboard_clear()
            self.root.clipboard_append(self.arrivedNumber)
            self.root.update()
        else:
            self.root.clipboard_clear()
            self.root.update()

    def checkIfNumberEntredIsCorrect(self):
        global ALPHA
        charIndex = 0
        for i in self.startNumber.get():
            if ALPHA.index(i) >= self.startBase.get():
                return charIndex
            charIndex += 1
        return -1

if __name__ == "__main__":
    root = Tk.Tk()
    gui = Gui(root)
    root.mainloop()


import sys
input = sys.stdin.readline

N = int(input())
nums = list(map(int, input().split()))
dp = [nums[0]]

for i in range(1, N):
    dp.append(max(dp[i - 1] + nums[i], nums[i]))

print(max(dp))

'''
# 시간초과
import sys
input = sys.stdin.readline

N = int(input())
nums = list(map(int, input().split()))

maxV, sumV = -1000
for i in range(N):
    for j in range(N - i):
        maxV = max(maxV, sum(nums[j:j + i + 1]))
print(maxV)
'''


import random
from math import gcd
import json
import base64
import array
def fermat_test_prime(n, times=3):
    '''
        if random number k < n
        then power(k,n)%n == k%n
        if we test many times then probility is very high to confirm its a prime number

    '''
    def test(n):
        r_num = random.randrange(n)
        r = pow(r_num,n,n)
        if r == r_num:
            return True
        else:
            return False

    for x in range(times):
        if not test(n):
            return False
    return True

def generate_prime(lower_bound=2**1000, higher_bound=2**1200):

    while True:
        n = random.randrange(lower_bound, higher_bound)
        if n%2==0 or n%3==0 or n%5==0 or n%7==0 or n%13==0:
            continue
        if fermat_test_prime(n):
            return n

def generate_e(euler_n,lower_bound=2**100,higher_bound=2**110):
    while True:
        n = random.randrange(lower_bound, higher_bound)
        if gcd(n,euler_n) == 1:
            return n

def generate_pvtkey(e, euler_n):
    def computeD(fn, e):
        (x, y, r) = extendedGCD(fn, e)
        #y maybe < 0, so convert it
        if y < 0:
            return fn + y
        return y
    for _ in range(100):
        res = computeD(euler_n, e)
        if bin_len(res) > 2048:
            return res
def extendedGCD(a, b):
    #a*xi + b*yi = ri
    if b == 0:
        return (1, 0, a)
    #a*x1 + b*y1 = a
    x1 = 1
    y1 = 0
    #a*x2 + b*y2 = b
    x2 = 0
    y2 = 1
    while b != 0:
        q = a // b
        #ri = r(i-2) % r(i-1)
        r = a % b
        a = b
        b = r
        #xi = x(i-2) - q*x(i-1)
        x = x1 - q*x2
        x1 = x2
        x2 = x
        #yi = y(i-2) - q*y(i-1)
        y = y1 - q*y2
        y1 = y2
        y2 = y
    return(x1, y1, a)

def encrypt(msg,e,pubkey):

    bytes_of_msg = bytes(msg, "utf-8")
    # print(bytes_of_msg)
    datas = []
    for x in bytes_of_msg:
        datas.append(pow(x,e,pubkey))

    return json.dumps(datas)

def decrypt(msg, pubkey ,pvtkey):
    datas = json.loads(msg )

    decrypted_datas = []
    for x in datas:
        tmp = pow(x, pvtkey, pubkey)
        decrypted_datas.append(tmp)
    msg = array.array('B', decrypted_datas).tostring()
    return msg.decode('utf-8')

def demo1():
    msg = input("please input a msg :")
    p = generate_prime()
    q = generate_prime()
    n = p*q
    euler_n = (p-1)*(q-1)
    e = generate_e(euler_n)
    pvtkey = generate_pvtkey(e, euler_n)
    pubkey =  n
    enctrpted_msg = encrypt(msg,e, pubkey)
    decrypted_msg = decrypt(enctrpted_msg, pubkey, pvtkey)

    print("="*30)
    print("="*30)
    print("the enctyped msg is: ",enctrpted_msg,)
    print("="*30)
    print("="*30)
    print("the decryted msg is: ",decrypted_msg)
    print("="*30)
    print("="*30)
    print("[+] public key len: ",bin_len(n)," (bit)")
    print("[+] phi-n  len: ", bin_len(euler_n), " (bit)")
    print("[+] e len: ", bin_len(e), '(bit)' )
    print("[+] private key len: ",bin_len(pvtkey)," (bit)")

def bin_len(a):
    return len(bin(a)[2:])

if __name__ == "__main__":

    demo1()


#!/usr/bin/env python
# coding: utf-8

# # Generator of Discrete Random Variable with Mersenne Twister

# In[94]:

import numpy as np
from RNG_Uniform import *

# In[95]:

MT=MT19937()
MT.seed(3213)

# In[96]:

def Expectation(Xn):
    return sum(Xn)/len(Xn)

def Variance(Xn):
    exp=Expectation(Xn)
    var=0
    for i in range(len(Xn)):
        var += pow((Xn[i]-exp),2)
    return(var/len(Xn))

# ## Uniform Discrete

# In[172]:

def Uniform_Discrete(a,b,size=1):
    '''
    Give a random number between a and b with uniform probability
    '''
    if size==1:
        U = MT.uniform()
        return a + int( U * (b-a+1))
    res = []
    for i in range(size):
        U = MT.uniform()
        res.append(a + int( U * (b-a+1)))
    return res

# In[179]:

Sn = Uniform_Discrete(-5,5,10000)
print("Expectation :",Expectation(Sn))
print("Variance :",Variance(Sn))
plt.hist(Sn,bins=11)

# ## Bernouilli

# In[62]:

def Bernouilli(p,size=1):
    if size==1:
        U = MT.uniform()
        if (U<1-p):
            return 0
        else:
            return 1
    res=[]
    for i in range(size):
        U = MT.uniform()
        if (U<1-p):
            res.append(0)
        else:
            res.append(1)
    return res

# In[60]:

size = 100000
Sn=Bernouilli(0.3,size)
print("Expectation :",Expectation(Sn))
print("Variance :",Variance(Sn))
print(0.3*0.7)
plt.hist(Sn)

# ## Binomial

# In[194]:

def Binomial(n,p,size=1):
    if size == 1 :
        return(sum(Bernouilli(p,n)))
    res = []
    for i in range(size):
        res.append(sum(Bernouilli(p,int(n))))
    return res

# In[195]:

Sn = Binomial(10,0.3,size=100000)
print("Expectation :",Expectation(Sn))
print("Variance :",Variance(Sn))
plt.hist(Sn)

# ## Geometric
#

# In[196]:

def Geometric(p,size=1):
    if size==1:
        res = 1
        U = MT.uniform()
        while (U>p):
            U = MT.uniform()
            res +=1
        return res
    res = []
    for i in range(n):
        U = MT.uniform()
        res_tmp = 1
        while (U>p):
            U = MT.uniform()
            res_tmp +=1
        res.append(res_tmp)
    return res

# In[197]:

Sn = Geometric(0.5,size=10000)
print("Expectation :",Expectation(Sn))
print("Variance :",Variance(Sn))
plt.hist(Sn)

# ## Poisson

# Simultion method using the Th. : $(X_n)$ is an i.i.d. sequence of exponential law of parameters $\lambda$ then for $S_n = \sum_{i=1}^n X_n$ $\forall n \in \mathbb{N}, \mathbb{P}(S_n \le 1 \le S_{n+1})=\frac{\lambda^k}{k!}e^{-k}$
# $\textit{Looking for Proof}$

# In[237]:

def Poisson(lambdaa,size=1):
    if size==1:
        k=0
        p=1
        while (p > np.exp(-lambdaa)):
            U = MT.uniform()
            p = p*u
            k +=1
        return (k-1)
    res = []
    for i in range(size):
        k=0
        p=1
        cond = np.exp(-lambdaa)
        while (p > cond):
            U = MT.uniform()
            p = p*U
            k +=1
        res.append(k-1)
    return res

# In[239]:

Sn = Poisson(5,size=10000)
print("Expectation :",Expectation(Sn))
print("Variance :",Variance(Sn))
plt.hist(Sn)

# Another simulation method using the fact that the Poisson law is the limit of a Binomial($n$,$p_n$) with $p_n = \frac{\lambda}{n}$.
# A minimal condition is $\lambda <10$

# In[204]:

def Poisson_2(lambdaa,size=1):
    n = 100.0
    p = lambdaa/n
    if size==1:
        return Binomial(n,p,1)
    return Binomial(n,p,size)

# In[207]:

Sn = Poisson_2(4,size=10000)
print("Expectation :",Expectation(Sn))
print("Variance :",Variance(Sn))
plt.hist(Sn)


#二叉搜索树的中序遍历就是有序的，有序数组找第k个
def kthSmallest(root, k):
    """
    :type root: TreeNode
    :type k: int
    :rtype: int
    """
    stack = []
    count = 1
    p = root
    while p != None or len(stack) != 0:
        if p != None:
            stack.append(p)
            p = p.left
        else:
            top = stack.pop()
            if k == count:
                return top.val
            count += 1
            p = top.right

二叉搜索树中第k个.py


#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
test_runner
----------------------------------

Tests for `cdapsutil.runner` module.
"""

import os
import stat
import sys
import tempfile
import shutil
import unittest

import ndex2
import cdapsutil
from cdapsutil.runner import Runner

class TestRunner(unittest.TestCase):

    def setUp(self):
        pass

    def tearDown(self):
        pass

    def get_data_dir(self):
        return os.path.join(os.path.dirname(__file__), 'data')

    def get_human_hiv_as_nice_cx(self):
        """

        :return:
        """
        return ndex2.create_nice_cx_from_file(os.path.join(self.get_data_dir(),
                                                           'hiv_human_ppi.cx'))

    def get_edge_dict(self, net_cx):
        edge_dict = {}
        for edge_id, edge_obj in net_cx.get_edges():
            if edge_obj['s'] not in edge_dict:
                edge_dict[edge_obj['s']] = set()
            edge_dict[edge_obj['s']].add(edge_obj['t'])
        return edge_dict

    def test_get_edge_list(self):
        net_cx = self.get_human_hiv_as_nice_cx()

        edge_dict = self.get_edge_dict(net_cx)

        res = Runner._get_edge_list(net_cx)
        for entry in res.split('\n'):
            if len(entry.strip()) == 0:
                continue
            splitentry = entry.split('\t')
            self.assertTrue(int(splitentry[1]) in
                            edge_dict[int(splitentry[0])])

    def test_write_edge_list(self):
        temp_dir = tempfile.mkdtemp()
        try:
            net_cx = self.get_human_hiv_as_nice_cx()

            edge_dict = self.get_edge_dict(net_cx)

            input_edgelist = Runner._write_edge_list(net_cx, temp_dir)
            with open(input_edgelist, 'r') as f:
                for entry in f:
                    if len(entry.strip()) == 0:
                        continue
                    splitentry = entry.split('\t')
                    self.assertTrue(int(splitentry[1]) in
                                    edge_dict[int(splitentry[0])])
        finally:
            shutil.rmtree(temp_dir)

    def test_get_algorithms(self):
        runner = Runner()
        try:
            runner.get_algorithms()
            self.fail('Expected CommunityDetectionError')
        except cdapsutil.CommunityDetectionError as ce:
            self.assertEqual('Not implemented for this Runner', str(ce))

    def test_run(self):
        runner = Runner()
        try:
            runner.run()
            self.fail('Expected CommunityDetectionError')
        except cdapsutil.CommunityDetectionError as ce:
            self.assertEqual('Not implemented for this Runner', str(ce))

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


from __future__ import annotations

import logging
import re
from typing import Sequence

from app.media_types import MediaTypes
from lxml import etree
from ncar_airsigmet_code.parse_airsigmet_intl import IntlSigmetParser
from ncar_airsigmet_code.parse_airsigmet_us import SigmetParser
from ncar_airsigmet_code.util import airsigmet_common
from ncar_airsigmet_code.writers.iwxxm_30_writer import IwxxmWriter
from ncar_airsigmet_code.writers.iwxxm_us_30_writer import IwxxmUsWriter

from .base import ConversionInput, ConversionResult, Converter

class SigmetConverter(Converter):
    """Converts AIRMET and SIGMET text products to IWXXM or IWXXM-US."""

    SIGMET_REGEX = rb'\d{3}[\n\r]+\w{4}\d{2} \w{4} \d{6}[\n\r]+(.*)[\n\r]+(.*)[\n\r]+(.*)[\n\r]+.*(SIGMET|AIRMET)'

    def __init__(self):
        self._domesticParser = None
        self._intlParser = None
        self._re = {}

        self.__logger = logging.getLogger(__name__)

        # Control characters \x01 === ^A and \x03 === ^C
        self._re['bulletin'] = re.compile(r'(\x01.*?\x03)', re.DOTALL)

        # if it doesn't look like 'WSUS...' then it should be parsed as an international even though it is US.
        # internal US SIGMETs look different than Intl US SIGMETs
        self._re['airsig_domestic'] = re.compile(r"""(
        ^(?P<prefix>.*?)\s*
        (?P<head>(?P<head_prefix>W(A|S|V)(?P<us_region>US|HW|AK)([0-9]+))\s(?P<issuing_center_id>[K|P][A-Z0-9]{3})\s(?P<head_time>([0-3][0-9])([0-2][0-9])([0-5][0-9])))\s
        (?P<remainder>.*?)
        )""", re.VERBOSE | re.DOTALL)

        self._re['sig_intl'] = re.compile(r"""(
        ^(?P<prefix>.*?)\s*
        (?P<head>W(?P<intl_type>C|S|V)([A-Z]{2})[0-9]{2}\s([A-Z][A-Z0-9]{3})\s([0-3][0-9])([0-2][0-9])([0-5][0-9])\s?(CC[A-Z])?)\s
        (?P<remainder>.*?)
        )""", re.VERBOSE | re.DOTALL)

        self._re['air_intl'] = re.compile(r"""(
        ^(?P<prefix>.*?)\s*
        (?P<head>W(A)([A-Z]{2})[0-9]{2}([A-Z]*)\s([A-Z][A-Z0-9]{3})\s([0-3][0-9])([0-2][0-9])([0-5][0-9])\s?(CC[A-Z])?)\s
        (?P<remainder>.*?)
        )""", re.VERBOSE | re.DOTALL)

        # Note: This regex is also used in parse_airsigmet_intl.py. Update there if you make changes here.
        self._re['intl_hdr'] = re.compile(r"""(
        ^(?P<prefix>.*?)\s*
        (?P<wmo>(?P<seq>[0-9]{3})?\s*
        (?P<ttaaii>[A-Z0-9]{6})\s
        (?P<cccc>[A-Z][A-Z0-9]{3})\s
        (?P<dd>[0-3][0-9])(?P<hh>[0-2][0-9])(?P<mm>[0-5][0-9])\s*
        (?P<bbb>[CAR]{2}[A-Z])?\s*
        (?P<awips>[A-Z]{3}[A-Z0-9]{3})?
        )
        )""", re.VERBOSE | re.DOTALL)

        self.Errors = 0
        self.Warnings = 0
        self.Bulletins = 0

    async def _convert(self, inputs: Sequence[ConversionInput]) -> Sequence[ConversionResult]:
        results = []
        data = inputs[0].data.decode('utf-8')
        parsed_sigmets = self.parse_file(data)
        # parsed_sigmets = self.parse_file(data, verbosity=3)
        for sig in parsed_sigmets:
            sig_xml = self.produce_xml(sigmet=sig)
            # TODO: could be IWXXM or IWXXM-US
            result = ConversionResult(str.encode(sig_xml), MediaTypes.APPLICATION_IWXXM_XML, id='SIGMET')
            results.append(result)

        return results

    # This was slightly modified from NCAR's split_airsigmet.py tool.
    def parse_file(self, product, verbosity=0):
        """Parse raw product and split bulletins into AIRMETs or SIGMETs and output XML.

        :param product:                     input stream containing the data
        :param verbosity:                   desired verbosity level, for diagnostic logging
        :return:
            a collection of resulting air/sigmet parsed parameter objects
        """
        bulletins = self._re['bulletin'].findall(product)

        # if no bulletins are found we may be passed the raw text without WMO headers
        self.__logger.debug(f'Found {len(bulletins)} bulletin items')
        if len(bulletins) == 0:
            if verbosity >= 3:
                self.__logger.debug('Parsing bulletin items as raw text')
            bulletins = [product]

        sigmets = []
        for text in bulletins:
            text = airsigmet_common.strip_non_ascii(text)

            if text.find(' TEST ') >= 0 or text.find(' EXERCISE ') >= 0:
                self.__logger.info(f'Ignoring test bulletin: "{" ".join(text.split())}"')
                continue

            verbosity = verbosity

            if verbosity >= 3:
                self.__logger.debug('Start bulletin')

            dom = self._re['airsig_domestic'].match(text)
            intl_sig = self._re['sig_intl'].match(text)
            intl_air = self._re['air_intl'].match(text)

            is_domestic = True
            if dom and intl_sig:
                # Call this domestic unless it's an Alaska SIGMET. airTrafficUnit will not be KKCI
                m = self._re['intl_hdr'].match(text)
                if m:
                    d = m.groupdict()
                    air_traffic_unit = d['cccc']
                    if air_traffic_unit is not None and 'KKCI' not in air_traffic_unit:
                        is_domestic = False

            # if dom and not intl_sig: # Alaska SIGMETs must be parsed as international reports
            if dom and is_domestic:
                has_sub_bulletins = False
                if not self._domesticParser:
                    self._domesticParser = SigmetParser(verbosity)

                d = dom.groupdict()
                if verbosity >= 2:
                    if d['head'][1:2] == 'A':
                        self.__logger.debug('Domestic AIRMET: ' + d['head'])

                        # Handle Alaska and Hawaii AIRMETs, with different hazards lumped into one bulletin...
                        if d['us_region'] is not None and (d['us_region'] == 'AK' or d['us_region'] == 'HW'):
                            self.__logger.debug(
                                f'Checking {d["us_region"]} AIRMET bulletin to see if it contains multiple bulletins'
                            )
                            temp_parser = SigmetParser(verbosity)
                            sub_bulletins = temp_parser.split_AKHI_AIRMETs(text, d['us_region'])
                            if len(sub_bulletins) > 1:
                                self.__logger.debug(f'Splitting AIRMET into {str(len(sub_bulletins))} sub-bulletins...')
                                has_sub_bulletins = True

                                for bul in sub_bulletins:
                                    sigmets.extend(self._domesticParser.parse(bul))

                    else:
                        self.__logger.debug('Domestic SIGMET: ' + d['head'])

                if not has_sub_bulletins:
                    sigmets.extend(self._domesticParser.parse(text))

            elif intl_sig:
                d = intl_sig.groupdict()
                if verbosity >= 2:
                    self.__logger.debug('International SIGMET: ' + d['head'])

                if not self._intlParser:
                    self._intlParser = IntlSigmetParser(verbosity)

                typ = d['intl_type']
                if typ == 'V':
                    sigmets.extend(self._intlParser.parse(text))
                elif typ == 'C':
                    sigmets.extend(self._intlParser.parse(text))
                elif typ == 'S':
                    sigmets.extend(self._intlParser.parse(text))
                else:
                    self.__logger.warning("Unknown international SIGMET type: %s. Halting.  Raw file: %s" % (type))

            elif intl_air:

                d = intl_air.groupdict()
                if verbosity >= 2:
                    self.__logger.debug('International AIRMET: ' + d['head'])

                if not self._intlParser:
                    self._intlParser = IntlSigmetParser(verbosity)

                sigmets.extend(self._intlParser.parse(text))

            else:
                self.__logger.warning("Could not determine report/bulletin type in '%s'. Processing as raw text")
                if not self._intlParser:
                    self._intlParser = IntlSigmetParser(verbosity)

                sigmets.extend(self._intlParser.parse(text))

        if verbosity >= 3:
            self.__logger.debug('End bulletin')
        if verbosity >= 1:
            self.__logger.info("Finished parsing %s bulletins" % len(bulletins))

        errors = 0
        warnings = 0
        if self._intlParser:
            if verbosity >= 3:
                self.__logger.info('International parser: %s warnings, %s errors' % (
                    self._intlParser.getNWarnings(),
                    self._intlParser.getNErrors()
                ))
            errors = self._intlParser.getNErrors()
            warnings = self._intlParser.getNWarnings()
            self._intlParser.clearErrorsWarnings()
        if self._domesticParser:
            if verbosity >= 3:
                self.__logger.info('Domestic parser: %s warnings, %s errors' % (
                    self._domesticParser.getNWarnings(),
                    self._domesticParser.getNErrors()
                ))
            errors += self._domesticParser.getNErrors()
            warnings += self._domesticParser.getNWarnings()
            self._domesticParser.clearErrorsWarnings()

        return sigmets

    # Produce the iwxxm output for the sigmet.  The sigmet argument is a Sigmet object, not a string
    def produce_xml(self, sigmet):
        if (self._domesticParser):
            iwxxm_writer = IwxxmUsWriter()
        else:
            iwxxm_writer = IwxxmWriter()
        root_elem, text_id, uuid = iwxxm_writer.create_xml(airsigmetdata=sigmet)
        xmlstr = etree.tostring(root_elem, pretty_print=True, xml_declaration=True, encoding="UTF-8")
        xmlstr = xmlstr.decode('utf-8')
        # replace single quotes with double, as is convention
        return xmlstr.replace("<?xml version='1.0' encoding='UTF-8'?>", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>")


"""
This assignment requires that you to find at least two datasets on the web which are related, and that you visualize these datasets to answer a question with the broad topic of sports or athletics (see below) for the region of Ann Arbor, Michigan, United States, or United States more broadly.

Choice:

The goal is to see trends (if any) of rising temperatures on crop yields.
Crop yield is represented in tonnes per hectare, and is plotted against the
temperature increase over the previous year from 1961-2018. Data sets/pots
represent the world, and countries divided into economic groups.

Crop data comes from http://www.fao.org/faostat/en/#data/QC
Temperature data comes from http://www.fao.org/faostat/en/#data/ET
"""
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker
import matplotlib.lines as mlines
import pandas as pd
import sys, os
from scipy.stats import ttest_ind
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

__author__ = 'Chris Hilldrup'

# Continents
reg_contin = {'Africa': 'Africa',
             'Asia': 'Asia',
             'Australia and New Zealand': 'Australia',
             'Europe': 'Europe',
             'Central America': 'North America',
             'Northern America':'North America',
             'Caribbean': 'North America',
             'South America': 'South America'}

# Economic Regions
reg_economic = {'Northern America': 'Developed Region',
               'Europe': 'Developed Region',
               'Japan': 'Developed Region',
               'Australia and New Zealand': 'Developed Region',
               'Israel': 'Developed Region',
               'Botswana': 'Developed Region',
               'Lesotho': 'Developed Region',
               'Namibia': 'Developed Region',
               'South Africa': 'Developed Region',
               'Eswatini': 'Developed Region',
               'Slovenia': 'Developed Region',
               'Africa': 'Developing Region',
               'Caribbean': 'Developing Region',
               'Central America': 'Developing Region',
               'South America': 'Developing Region',
               'Asia': 'Developing Region',
               'Oceania': 'Developing Region',
               'Azerbaijan': 'Transition Country',
               'Belarus': 'Transition Country',
               'Kazakhstan': 'Transition Country',
               'Kyrgyzstan': 'Transition Country',
               'Armenia': 'Transition Country',
               'Moldova': 'Transition Country',
               'Russia': 'Transition Country',
               'Tajikistan': 'Transition Country',
               'Uzbekistan': 'Transition Country',
               'Turkmenistan': 'Transition Country',
               'Ukraine': 'Transition Country',
               'Albania': 'Transition Country',
               'Bosnia and Herzegovina': 'Transition Country',
               'Croatia': 'Transition Country',
               'Serbia and Montenegro': 'Transition Country',
               'Montenegro': 'Transition Country',
               'Serbia': 'Transition Country',
               'North Macedonia': 'Transition Country',
               'Land Locked Developing Countries': 'Developing Countries',
               'Small Island Developing States': 'Developing Countries',
               'Least Developed Countries': 'Developing Countries'}

def dataframe_ttest(df=None, axis=None):
    '''
    Calculate p-value between two series and apply values to axis. Also
    determines if variance is equal or not.

    Parameters:
        df - DataFrame object with values to be compared. Currently requires
             columns labeled 'Value_x' and 'Value_y'.
        axis - The axis object to apply the p-value to.
    '''
    if df is None or axis is None:
        return

    varcrop = df['Value_x'].var()
    vartemp = df['Value_y'].var()
    varequal = (varcrop == vartemp)
    p = ttest_ind(a=df['Value_x'], b=df['Value_y'], equal_var=varequal)
    axis.text(0.01, 0.92,
              'p = ' + str(p[1]) + '\n' +
              'equal variance - ' +
              str(varequal),
              transform=axis.transAxes,
              fontsize=8)

# A list of areas from the above dictionaries
reg_wanted = list(reg_contin.keys())
reg_wanted.extend(list(reg_economic.keys()))
reg_wanted.append('World')

temperature = pd.read_csv(sys.path[-1] + '/Data/Environment_Temperature_change_E_All_Data_(Normalized).zip',
                          usecols=[1,3,5,7,9], encoding='iso-8859-1')

# Filter unwanted timepoints, temeprature statistics, and areas
temperature = temperature[temperature['Months'] == 'Meteorological year']
temperature = temperature[temperature['Element'] == 'Temperature change']
temperature = temperature[temperature['Area'].isin(reg_wanted)]

crops = pd.read_csv(sys.path[-1] + '/Data/Production_Crops_E_All_Data_(Normalized).zip',
                    usecols=[1,3,7,8,9], encoding='iso-8859-1')

# Keep only ha and tonne values
crops = crops[crops['Unit'] != 'hg/ha']

crop_totals = ['Cereals (Rice Milled Eqv)','Cereals, Total','Citrus Fruit, Total',
               'Coarse Grain, Total', 'Fibre Crops Primary','Fruit Primary',
               'Oilcrops', 'Oilcrops, Cake Equivalent','Oilcrops, Oil Equivalent',
               'Pulses, Total','Roots and Tubers, Total', 'Treenuts, Total',
               'Vegetables Primary']

# Filter unwanted areas, and crops
crops = crops[crops['Area'].isin(reg_wanted)]
crops = crops[crops['Item'].isin(crop_totals)]

df = pd.DataFrame()

# Calculate tonnes/ha for each area and year
for x,y in crops.groupby(by=['Area','Year']):
    tonnes = y[y['Unit'] == 'tonnes']
    hect = y[y['Unit'] == 'ha']
    df =df.append({'Area': x[0],
                   'Year': x[1],
                   'Unit': 'tph',
                   'Value': tonnes['Value'].sum()/hect['Value'].sum(),
                  },
                   ignore_index=True)

df['Year'] = df['Year'].astype(int)
df = df.merge(temperature, on=['Area','Year'])

# World data used for ax1 and ax2
world = df[df['Area'] == 'World']

fig = plt.figure()
gs = fig.add_gridspec(2,4)
ax1 = fig.add_subplot(gs[0,1:3])

# Line plot for crop yield over time for the world
wline = ax1.plot(world['Year'], world['Value_x'], label='Crop Yield')
ax1.set_ylim(0,6)
ax1.set_title('World')
ax1.set_ylabel('Crop Yield (tonnes/hectare)')
ax1.spines['top'].set_visible(False)
ax1.grid(axis='y', alpha=.5)

dataframe_ttest(world, ax1)

# Bar plot for temperature delta for the world
ax2 = ax1.twinx()
wbar = ax2.bar(world['Year'], world['Value_y'], color='lightgray', alpha=.5, label='$\Delta$T')
ax2.set_ylim(-1.0,2.0)
ax2.set_ylabel('$\Delta$T from Previous Year ($^\circ$C)')
ax2.spines['top'].set_visible(False)

economic = df[df['Area'].isin(list(reg_economic.keys()))]
economic.set_index('Area', inplace=True)

subax = [] # Container for second row plots

# Group counties into economic statues
for x,y in economic.groupby(reg_economic):
    # Aggregate multiple entries for years 1961-2018 in each group
    s = y.groupby('Year').mean()

    bottomax = fig.add_subplot(gs[1,len(subax)])

    # Line plots of economic country groups for crop yield over time
    bottomax.plot(s.index, s['Value_x'], label='Crop Yield')
    bottomax.spines['top'].set_visible(False)
    bottomax.spines['right'].set_visible(False)
    bottomax.set_ylim(0,6)
    bottomax.set_title(x)

    for x in range(1,7):
        bottomax.axhline(x, color='black', linewidth=1, alpha=.1)

    if len(subax) == 0:
        bottomax.set_ylabel('Crop Yield (tonnes/hectare)')

    if len(subax) > 0:
        bottomax.spines['left'].set_visible(False)
        bottomax.yaxis.set_major_locator(plt.NullLocator())

    bottomax.spines['top'].set_visible(False)

    # Temperature delta for each economic group plot
    bottomax2 = bottomax.twinx()
    bottomax2.bar(s.index, s['Value_y'], color='lightgray', alpha=.5, label='$\Delta$T')
    bottomax2.spines['top'].set_visible(False)
    bottomax2.spines['left'].set_visible(False)
    bottomax2.set_ylim(-1.0,2.0)

    if len(subax) < 3:
        bottomax2.spines['right'].set_visible(False)
        bottomax2.yaxis.set_major_locator(plt.NullLocator())

    if len(subax) == 3:
        bottomax2.set_ylabel('$\Delta$T from Previous Year ($^\circ$C)')

    dataframe_ttest(y,bottomax)

    subax.append([bottomax, bottomax2])

fig.suptitle('Does Crop Yield$^1$ change as Surface Temperatures$^2$ Rise for\n' +
             'the World and Economic Country Groups$^3$ from 1961-2018')

# Proxy artist for line plot legend entry
blueline = mlines.Line2D([], [], color='C0')
fig.legend((blueline, wbar),('Crop Yield','$\Delta$T'))

plt.figtext(0.005, 0.9,
            '$^1$ Crop data source - http:/www.fao.org/faostat/en/#data/QC\n' +
            '$^2$ Temperature data source - http:/www.fao.org/faostat/en/#data/ET\n' +
            '$^3$ Economic Country Groups according to UN M49 (2009)\n' +
            '- This is a general analysis. Underlying or additional factors\nare not considered.',
            horizontalalignment='left')

plt.show()

Applied Plotting, Charting & Data Representation in Python/a3.py


import re

def main():
    rule = input("Enter rule: ")
    new_rule = read_rule(rule)
    print(new_rule)

def read_rule(rule):
    new_rules = {}
    x = re.search("(Rule|rule) (?P<RuleID>[0-9]*) (if|If) the (?P<Variable1>[0-1A-Za-z_]+) is (?P<Value1>[0-1A-Za-z_]+) (?P<Operator>and|or) the (?P<Variable2>[0-1A-Za-z_]+) is (?P<Value2>[0-1A-Za-z_]+) then the (?P<Output>[0-1A-Za-z]+) will be (?P<Value>[0-1A-Za-z]+)" , rule)
    if x is None:
        print("Invalid rule")
    else:
        ID = x.group("RuleID")
        variables = [x.group("Variable1"), x.group("Variable2")]
        values = [x.group("Value1"),x.group("Value2")]
        operator = x.group("Operator")
        output = x.group("Output")
        value = x.group("Value")

        new_rules = {"ID": ID, "Variables":variables, "Values":values, "Operator":operator, "Output":{output: value}}
        return new_rules

if __name__ == '__main__':
    main()


import utils

def calculate_min_fuel(positions, part):
    counter = utils.create_counter_list(
        positions, min(positions), max(positions)+1)

    fuel = []

    for i in range(len(counter)):
        fuel.append(utils.calculate_fuel(counter, i, part))

    return min(fuel)

if __name__ == '__main__':
    crabs_positions = utils.read_as_int_list(7)
    utils.display_part(1, calculate_min_fuel(crabs_positions, 1))
    utils.display_part(2, calculate_min_fuel(crabs_positions, 2))


from django.core.exceptions import ObjectDoesNotExist
from django.http import JsonResponse
from django.db import IntegrityError
from .models import *
from ..constants import *
import base64
import json
from ..s3Client import *
from ..serializers import *
from rest_framework.response import Response
from rest_framework.views import APIView

# Get specific poll or topic
class getPost(APIView):
    # GET request
    def get(self, request):
        type = request.GET.get(type_param)
        text = request.GET.get(text_param)
        username = request.GET.get(username_param)

        try:
            if type == 'topic':
                topic = Topic.objects.filter(title=text)
                topicSerializer = TopicSerializer(topic, many=True)
                reviews = Review.objects.filter(topicID=topic)
                reviewsSerializer = ReviewSerializer(reviews, many=True)
                opinions = []
                uservotes = []
                images =[]
                # getting the image, if there is any
                # imageKey = createReviewKey(username=username, topicTitle=topic)
                # image = getObject(bucketName=bucket_name, key=imageKey)
                for review in reviews:
                    upvotes = len(Opinion.objects.filter(reviewID=review, upvote=True))
                    downvotes = len(Opinion.objects.filter(reviewID=review, upvote=False))
                    opinions.append({'reviewID': review.pk, 'upvotes': upvotes, 'downvotes': downvotes })
                    if username is not None:
                        if len(UserProfile.objects.filter(username=username)) != 0:
                            u = UserProfile.objects.filter(username=username)
                            if len(Opinion.objects.filter(userID=u, reviewID=review)) != 0:
                                uservotes.append({'reviewID': review.pk, 'upvote':
                                    Opinion.objects.get(userID=u, reviewID=review).upvote})

                return JsonResponse({'status': 200, 'topic': topicSerializer.data, 'reviews': reviewsSerializer.data,
                                     'opinions': opinions, 'uservotes': uservotes, 'images':images}, safe=False)

            elif type == 'poll':
                poll = Poll.objects.filter(text=text)
                pollSerializer = PollSerializer(poll, many=True)
                pc = PollChoice.objects.filter(pollID=poll)
                pcSerializer = PollChoiceSerializer(pc, many=True)
                return JsonResponse({'status': 200, 'poll': pollSerializer.data, 'pc': pcSerializer.data }, safe=False)

            # Type is incorrect
            else:
                return JsonResponse(getPost_400_TP, status=400)
        # Data does not exist
        except ObjectDoesNotExist:
            return JsonResponse(DATA_400, status=400)

    # POST request
    def post(self, request):
        return JsonResponse(GET_400, status=400)

# https://stackoverflow.com/a/23788795


from hashlib import new
import math
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.utils.checkpoint as checkpoint
import numpy as np
from functools import reduce
import operator
from timm.models.layers import DropPath, trunc_normal_

from mmcv.runner import load_checkpoint
from mmaction.utils import get_root_logger
from ..builder import BACKBONES

from functools import reduce, lru_cache
from operator import mul
from einops import rearrange

from .ops.modules import MS3DDeformAttn
from .swin_transformer import (
    Mlp, window_partition, window_reverse, get_window_size, PatchEmbed3D,
    PatchMerging)

@lru_cache()
def compute_mask(D, H, W, window_size, shift_size, device):
    """Attention mask for EACH WINDOW"""
    img_mask = torch.zeros((1, D, H, W, 1), device=device)  # 1 Dp Hp Wp 1
    cnt = 0
    for d in [slice(-window_size[0]),
              slice(-window_size[0],
              -shift_size[0]),
              slice(-shift_size[0], None)]:
        for h in [slice(-window_size[1]),
                  slice(-window_size[1],
                  -shift_size[1]),
                  slice(-shift_size[1], None)]:
            for w in [slice(-window_size[2]),
                      slice(-window_size[2],
                      -shift_size[2]),
                      slice(-shift_size[2], None)]:
                img_mask[:, d, h, w, :] = cnt
                cnt += 1

    # nW, ws[0]*ws[1]*ws[2], 1
    mask_windows = window_partition(img_mask, window_size)
    mask_windows = mask_windows.squeeze(-1)  # nW, ws[0]*ws[1]*ws[2]

    attn_mask = mask_windows.unsqueeze(1) - mask_windows.unsqueeze(2)
    attn_mask = attn_mask.masked_fill(
        attn_mask != 0, float(0.0)).masked_fill(attn_mask == 0, float(1.0)
    )  # nW, ws[0]*ws[1]*ws[2], ws[0]*ws[1]*ws[2]
    D_, H_, W_ = window_size
    attn_mask = attn_mask.view(-1, H_ * W_ * D_, D_, H_, W_)
    return attn_mask

class PositionEmbeddingSine(nn.Module):
    """ I believe this is correct, but it would be worth to check it (again)
    TODO
    """
    def __init__(self):
        super().__init__()

    def forward(self, x, mask):
        assert mask is not None
        z_embed = mask.cumsum(2, dtype=torch.float32) * mask / math.pi
        y_embed = mask.cumsum(3, dtype=torch.float32) * mask / math.pi
        x_embed = mask.cumsum(4, dtype=torch.float32) * mask / math.pi
        embed = mask * (x_embed.sin() + (math.pi * y_embed).sin() + z_embed)
        embed = embed.flatten(2)
        return embed, torch.diagonal(embed, dim1=1, dim2=2)

class WindowAttention3D(nn.Module):
    """Window based multi-head self attention (W-MSA) module with relative
    position bias.
    It supports both of shifted and non-shifted window.
    Args:
        dim (int): Number of input channels.
        window_size (tuple[int]): The temporal length, height and width of
                                  the window.
        num_heads (int): Number of attention heads.
        num_points (int | None, optional): Number of points to sample for the
                                           attention.
        attn_drop (float, optional): Dropout ratio of attention weight.
                                     Default: 0.0
        proj_drop (float, optional): Dropout ratio of output. Default: 0.0
    """

    def __init__(
        self,
        dim,
        window_size,
        num_heads,
        num_points=4,
        attn_drop=0.0,
        proj_drop=0.0,
    ):

        super().__init__()
        self.dim = dim
        self.window_size = window_size  # Wd, Wh, Ww
        self.num_heads = num_heads

        self.self_attn = MS3DDeformAttn(
            dim, num_heads, num_points, reduce(operator.mul, window_size, 1)) # math.prod(window_size)
        self.attn_drop = nn.Dropout(attn_drop)
        self.proj = nn.Linear(dim, dim)
        self.proj_drop = nn.Dropout(proj_drop)
        self.pos_embedd = PositionEmbeddingSine()
        self.norm = nn.LayerNorm(dim)

    @staticmethod
    def with_pos_embed(tensor, pos):
        if pos is None:
            return tensor
        Nw, S = pos.shape
        _, _, D = tensor.shape
        tensor_ = tensor.view(-1, Nw, S, D)
        return (tensor_ + pos[None, :, :, None]).view(tensor.shape)

    @staticmethod
    def get_reference_points(spatial_shapes, device):
        # Get reference points from all the video.
        D_, H_, W_ = spatial_shapes
        ref_z, ref_y, ref_x = torch.meshgrid(
            torch.linspace(
                0.5, D_ - 0.5, D_, dtype=torch.float32, device=device),
            torch.linspace(
                0.5, H_ - 0.5, H_, dtype=torch.float32, device=device),
            torch.linspace(
                0.5, W_ - 0.5, W_, dtype=torch.float32, device=device))
        ref_z = ref_z.reshape(-1)[None] / D_
        ref_y = ref_y.reshape(-1)[None] / H_
        ref_x = ref_x.reshape(-1)[None] / W_

        # 1, DxHxW, 3
        reference_points = torch.stack((ref_x, ref_y, ref_z), -1)
        return reference_points

    def get_valid_ratio(self, mask, shape):
        # Not gonna need this.
        D, H, W = shape
        mask = mask.view(-1, *shape)
        valid_D = torch.sum(1 - mask[:, :, 0, 0], 1)
        valid_H = torch.sum(1 - mask[:, 0, :, 0], 1)
        valid_W = torch.sum(1 - mask[:, 0, 0, :], 1)
        valid_ratio_d = valid_D.float() / D
        valid_ratio_h = valid_H.float() / H
        valid_ratio_w = valid_W.float() / W
        valid_ratio = torch.stack(
            [valid_ratio_w, valid_ratio_h, valid_ratio_d], -1)  # DxHxW, 3
        return valid_ratio

    def forward(self, x, mask=None):
        """Forward function.
        Args:
            x: input features with shape of (num_windows*B, N, C)
            mask: (0/-inf) mask with shape of (num_windows, N, N) or None
        """
        # The center of every patch is a point
        reference_points = self.get_reference_points(
            self.window_size, device=x.device)
        matrix_embed, embed = self.pos_embedd(x, mask)
        # attn
        attn = self.self_attn(
            self.with_pos_embed(x, embed),
            reference_points,
            x,
            self.window_size,
            0,  # level_start_index
            mask,
            matrix_embed
        )

        attn = self.attn_drop(attn)
        x = self.proj_drop(self.proj(self.norm(x + attn)))
        return x

class SwinTransformerBlock3D(nn.Module):
    """Swin Transformer Block.

    Args:
        dim (int): Number of input channels.
        num_heads (int): Number of attention heads.
        window_size (tuple[int]): Window size.
        shift_size (tuple[int]): Shift size for SW-MSA.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
        num_points (int | None, optional): Number of points to sample for the
                                           attention.
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float, optional): Stochastic depth rate. Default: 0.0
        act_layer (nn.Module, optional): Activation layer. Default: nn.GELU
        norm_layer (nn.Module, optional): Normalization layer.
                                          Default: nn.LayerNorm
    """

    def __init__(
        self,
        dim,
        num_heads,
        window_size=(2, 7, 7),
        shift_size=(0, 0, 0),
        mlp_ratio=4.0,
        num_points=4,
        drop=0.0,
        attn_drop=0.0,
        drop_path=0.0,
        act_layer=nn.GELU,
        norm_layer=nn.LayerNorm,
        use_checkpoint=False,
    ):
        super().__init__()
        self.dim = dim
        self.num_heads = num_heads
        self.window_size = window_size
        self.shift_size = shift_size
        self.mlp_ratio = mlp_ratio
        self.use_checkpoint = use_checkpoint

        assert (
            0 <= self.shift_size[0] < self.window_size[0]
        ), "shift_size must in 0-window_size"
        assert (
            0 <= self.shift_size[1] < self.window_size[1]
        ), "shift_size must in 0-window_size"
        assert (
            0 <= self.shift_size[2] < self.window_size[2]
        ), "shift_size must in 0-window_size"

        self.norm1 = norm_layer(dim)
        self.attn = WindowAttention3D(
            dim,
            window_size=self.window_size,
            num_heads=num_heads,
            num_points=num_points,
            attn_drop=attn_drop,
            proj_drop=drop,
        )

        self.drop_path = DropPath(drop_path) if drop_path > 0.0 else nn.Identity()
        self.norm2 = norm_layer(dim)
        mlp_hidden_dim = int(dim * mlp_ratio)
        self.mlp = Mlp(
            in_features=dim,
            hidden_features=mlp_hidden_dim,
            act_layer=act_layer,
            drop=drop,
        )

    def forward_part1(self, x, mask_matrix):
        B, D, H, W, C = x.shape
        window_size, shift_size = get_window_size(
            (D, H, W), self.window_size, self.shift_size
        )

        x = self.norm1(x)
        # pad feature maps to multiples of window size
        pad_l = pad_t = pad_d0 = 0
        pad_d1 = (window_size[0] - D % window_size[0]) % window_size[0]
        pad_b = (window_size[1] - H % window_size[1]) % window_size[1]
        pad_r = (window_size[2] - W % window_size[2]) % window_size[2]
        x = F.pad(x, (0, 0, pad_l, pad_r, pad_t, pad_b, pad_d0, pad_d1))
        _, Dp, Hp, Wp, _ = x.shape
        # cyclic shift
        if any(i > 0 for i in shift_size):
            shifted_x = torch.roll(
                x,
                shifts=(-shift_size[0], -shift_size[1], -shift_size[2]),
                dims=(1, 2, 3),
            )
            attn_mask = mask_matrix
        else:
            shifted_x = x
            attn_mask = mask_matrix
        # partition windows  (B*nW, Wd*Wh*Ww, C)
        x_windows = window_partition(shifted_x, window_size)
        # W-MSA/SW-MSA  (B*nW, Wd*Wh*Ww, C)
        attn_windows = self.attn(x_windows, mask=attn_mask)
        # merge windows
        attn_windows = attn_windows.view(-1, *(window_size + (C,)))
        shifted_x = window_reverse(
            attn_windows, window_size, B, Dp, Hp, Wp
        )  # B D' H' W' C
        # reverse cyclic shift
        if any(i > 0 for i in shift_size):
            x = torch.roll(
                shifted_x,
                shifts=(shift_size[0], shift_size[1], shift_size[2]),
                dims=(1, 2, 3),
            )
        else:
            x = shifted_x

        if pad_d1 > 0 or pad_r > 0 or pad_b > 0:
            x = x[:, :D, :H, :W, :].contiguous()
        return x

    def forward_part2(self, x):
        return self.drop_path(self.mlp(self.norm2(x)))

    def forward(self, x, mask_matrix):
        """Forward function.

        Args:
            x: Input feature, tensor size (B, D, H, W, C).
            mask_matrix: Attention mask for cyclic shift.
        """

        shortcut = x
        if self.use_checkpoint:
            x = checkpoint.checkpoint(self.forward_part1, x, mask_matrix)
        else:
            x = self.forward_part1(x, mask_matrix)
        x = shortcut + self.drop_path(x)

        if self.use_checkpoint:
            x = x + checkpoint.checkpoint(self.forward_part2, x)
        else:
            x = x + self.forward_part2(x)

        return x

class BasicLayer(nn.Module):
    """A basic Swin Transformer layer for one stage.

    Args:
        dim (int): Number of feature channels
        depth (int): Depths of this stage.
        num_heads (int): Number of attention head.
        window_size (tuple[int]): Local window size. Default: (1,7,7).
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
                           Default: 4.
        num_points (int | None, optional): Number of points to sample for the
                                           attention.
        drop (float, optional): Dropout rate. Default: 0.0
        attn_drop (float, optional): Attention dropout rate. Default: 0.0
        drop_path (float | tuple[float], optional): Stochastic depth rate.
                                                    Default: 0.0
        norm_layer (nn.Module, optional): Normalization layer.
                                          Default: nn.LayerNorm
        downsample (nn.Module | None, optional): Downsample layer at the
                                                 end of the layer.
                                                 Default: None
    """

    def __init__(
        self,
        dim,
        depth,
        num_heads,
        window_size=(1, 7, 7),
        mlp_ratio=4.0,
        num_points=4,
        drop=0.0,
        attn_drop=0.0,
        drop_path=0.0,
        norm_layer=nn.LayerNorm,
        downsample=None,
        use_checkpoint=False,
    ):
        super().__init__()
        self.window_size = window_size
        self.shift_size = tuple(i // 2 for i in window_size)
        self.depth = depth
        self.use_checkpoint = use_checkpoint

        # build blocks
        self.blocks = nn.ModuleList(
            [
                SwinTransformerBlock3D(
                    dim=dim,
                    num_heads=num_heads,
                    window_size=window_size,
                    shift_size=(0, 0, 0) if (i % 2 == 0) else self.shift_size,
                    mlp_ratio=mlp_ratio,
                    num_points=num_points,
                    drop=drop,
                    attn_drop=attn_drop,
                    drop_path=drop_path[i]
                    if isinstance(drop_path, list)
                    else drop_path,
                    norm_layer=norm_layer,
                    use_checkpoint=use_checkpoint,
                )
                for i in range(depth)
            ]
        )

        self.downsample = downsample
        if self.downsample is not None:
            self.downsample = downsample(dim=dim, norm_layer=norm_layer)

    def forward(self, x):
        """Forward function.

        Args:
            x: Input feature, tensor size (B, C, D, H, W).
        """
        # calculate attention mask for SW-MSA
        B, C, D, H, W = x.shape
        window_size, shift_size = get_window_size(
            (D, H, W), self.window_size, self.shift_size
        )
        x = rearrange(x, "b c d h w -> b d h w c")
        Dp = int(np.ceil(D / window_size[0])) * window_size[0]
        Hp = int(np.ceil(H / window_size[1])) * window_size[1]
        Wp = int(np.ceil(W / window_size[2])) * window_size[2]
        attn_mask = compute_mask(Dp, Hp, Wp, window_size, shift_size, x.device)
        for blk in self.blocks:
            x = blk(x, attn_mask)
        x = x.view(B, D, H, W, -1)

        if self.downsample is not None:
            x = self.downsample(x)
        x = rearrange(x, "b d h w c -> b c d h w")
        return x

@BACKBONES.register_module()
class DeformableSwinTransformer3D(nn.Module):
    """Swin Transformer backbone.
        A PyTorch impl of : `Swin Transformer: Hierarchical Vision Transformer
        using Shifted Windows`  -  https://arxiv.org/pdf/2103.14030

    Args:
        patch_size (int | tuple(int)): Patch size. Default: (4,4,4).
        in_chans (int): Number of input image channels. Default: 3.
        embed_dim (int): Number of linear projection output channels.
                         Default: 96.
        depths (tuple[int]): Depths of each Swin Transformer stage.
        num_heads (tuple[int]): Number of attention head of each stage.
        window_size (int): Window size. Default: 7.
        mlp_ratio (float): Ratio of mlp hidden dim to embedding dim.
                           Default: 4.
        num_points (int | None, optional): Number of points to sample for the
                                           attention.
        drop_rate (float): Dropout rate.
        attn_drop_rate (float): Attention dropout rate. Default: 0.
        drop_path_rate (float): Stochastic depth rate. Default: 0.2.
        norm_layer: Normalization layer. Default: nn.LayerNorm.
        patch_norm (bool): If True, add normalization after patch embedding.
                           Default: False.
        frozen_stages (int): Stages to be frozen (stop grad and set eval mode).
            -1 means not freezing any parameters.
    """

    def __init__(
        self,
        pretrained=None,
        pretrained2d=True,
        clap=False,
        patch_size=(4, 4, 4),
        in_chans=3,
        embed_dim=96,
        depths=[2, 2, 6, 2],
        num_heads=[3, 6, 12, 24],
        window_size=(2, 7, 7),
        mlp_ratio=4.0,
        num_points=4,
        drop_rate=0.0,
        attn_drop_rate=0.0,
        drop_path_rate=0.2,
        norm_layer=nn.LayerNorm,
        patch_norm=False,
        frozen_stages=-1,
        use_checkpoint=False,
        qkv_bias=True,  # Cann't delete this because of the swin config
        qk_scale=None,  # Cann't delete this because of the swin config
    ):
        super().__init__()

        self.pretrained = pretrained
        self.pretrained2d = pretrained2d
        self.clap = clap
        self.num_layers = len(depths)
        self.embed_dim = embed_dim
        self.patch_norm = patch_norm
        self.frozen_stages = frozen_stages
        self.window_size = window_size
        self.patch_size = patch_size

        # split image into non-overlapping patches
        self.patch_embed = PatchEmbed3D(
            patch_size=patch_size,
            in_chans=in_chans,
            embed_dim=embed_dim,
            norm_layer=norm_layer if self.patch_norm else None,
        )

        self.pos_drop = nn.Dropout(p=drop_rate)

        # stochastic depth
        dpr = [
            x.item() for x in torch.linspace(0, drop_path_rate, sum(depths))
        ]  # stochastic depth decay rule

        # build layers
        self.layers = nn.ModuleList()
        for i_layer in range(self.num_layers):
            layer = BasicLayer(
                dim=int(embed_dim * 2**i_layer),
                depth=depths[i_layer],
                num_heads=num_heads[i_layer],
                window_size=window_size,
                mlp_ratio=mlp_ratio,
                num_points=num_points,
                drop=drop_rate,
                attn_drop=attn_drop_rate,
                drop_path=dpr[
                    sum(depths[:i_layer]): sum(depths[: i_layer + 1])],
                norm_layer=norm_layer,
                downsample=PatchMerging if i_layer < self.num_layers - 1 else None,
                use_checkpoint=use_checkpoint,
            )
            self.layers.append(layer)

        self.num_features = int(embed_dim * 2 ** (self.num_layers - 1))

        # add a norm layer for each output
        self.norm = norm_layer(self.num_features)

        self._freeze_stages()

    def _freeze_stages(self):
        if self.frozen_stages >= 0:
            self.patch_embed.eval()
            for param in self.patch_embed.parameters():
                param.requires_grad = False

        if self.frozen_stages >= 1:
            self.pos_drop.eval()
            for i in range(0, self.frozen_stages):
                m = self.layers[i]
                m.eval()
                for param in m.parameters():
                    param.requires_grad = False

    def inflate_weights(self, logger):
        """Inflate the swin2d parameters to swin3d.

        The differences between swin3d and swin2d mainly lie in an extra
        axis. To utilize the pretrained parameters in 2d model,
        the weight of swin2d models should be inflated to fit in the shapes of
        the 3d counterpart.

        Args:
            logger (logging.Logger): The logger used to print
                debugging infomation.
        """
        checkpoint = torch.load(self.pretrained, map_location="cpu")
        state_dict = checkpoint["model"]

        # delete relative_position_index since we always re-init it
        relative_position_index_keys = [
            k for k in state_dict.keys() if "relative_position_index" in k
        ]
        for k in relative_position_index_keys:
            del state_dict[k]

        # delete attn_mask since we always re-init it
        attn_mask_keys = [k for k in state_dict.keys() if "attn_mask" in k]
        for k in attn_mask_keys:
            del state_dict[k]

        state_dict["patch_embed.proj.weight"] = (
            state_dict["patch_embed.proj.weight"]
            .unsqueeze(2)
            .repeat(1, 1, self.patch_size[0], 1, 1)
            / self.patch_size[0]
        )

        msg = self.load_state_dict(state_dict, strict=False)
        logger.info(msg)
        logger.info(f"=> loaded successfully '{self.pretrained}'")
        del checkpoint
        torch.cuda.empty_cache()

    def init_weights(self, pretrained=None):
        """Initialize the weights in backbone.

        Args:
            pretrained (str, optional): Path to pre-trained weights.
                Defaults to None.
        """

        def _init_weights(m):
            if isinstance(m, nn.Linear):
                trunc_normal_(m.weight, std=0.02)
                if isinstance(m, nn.Linear) and m.bias is not None:
                    nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.LayerNorm):
                nn.init.constant_(m.bias, 0)
                nn.init.constant_(m.weight, 1.0)

        if pretrained:
            self.pretrained = pretrained
        if isinstance(self.pretrained, str):
            self.apply(_init_weights)
            logger = get_root_logger()
            logger.info(f"load model from: {self.pretrained}")

            if self.pretrained2d:
                # Inflate 2D model into 3D model.
                self.inflate_weights(logger)
            elif self.clap:
                state_dict = torch.load(self.pretrained)['model_state']
                for key in list(state_dict.keys()):
                    if 'video_encoder' in key:
                        state_dict[key[21:]] = state_dict.pop(key)
                    else:
                        del state_dict[key]
                msg = self.load_state_dict(state_dict, strict=False)
                logger.info(msg)
                logger.info(f"=> loaded successfully '{self.pretrained}'")
                del state_dict
                torch.cuda.empty_cache()
            else:
                # Directly load 3D model.
                load_checkpoint(
                    self, self.pretrained, strict=False, logger=logger)
        elif self.pretrained is None:
            self.apply(_init_weights)
        else:
            raise TypeError("pretrained must be a str or None")

    def forward(self, x):
        """Forward function."""
        x = self.patch_embed(x)

        x = self.pos_drop(x)

        for layer in self.layers:
            x = layer(x.contiguous())

        x = rearrange(x, "n c d h w -> n d h w c")
        x = self.norm(x)
        x = rearrange(x, "n d h w c -> n c d h w")

        return x

    def train(self, mode=True):
        """Convert the model into training mode while keep layers freezed."""
        super(DeformableSwinTransformer3D, self).train(mode)
        self._freeze_stages()


#!/usr/bin/python

from mininet.net import Mininet
from mininet.node import Controller, RemoteController, Node
from mininet.cli import CLI
from mininet.log import setLogLevel, info
from mininet.link import Link, Intf

"""
THis is from https://haryachyy.wordpress.com/2014/06/14/learning-pox-openflow-controller-proactive-approach/. To save time added
    h1.cmd( 'dhclient h1-eth0 ')
    h2.cmd( 'dhclient h2-eth0' )
This is staticlly setting IPs. Don't really sure if this works fine (for proactive approch).

!!!POX must started for this to work!!!

"""
def aggNet():

    CONTROLLER_IP='192.168.56.1'

    net = Mininet( topo=None,
                build=False)

    net.addController( 'c0',
                    controller=RemoteController,
                    ip=CONTROLLER_IP,
                    port=6633)

    h1 = net.addHost( 'h1', ip='0.0.0.0' )
    h2 = net.addHost( 'h2', ip='0.0.0.0' )
    leftSwitch = net.addSwitch( 's1' )
    rightSwitch = net.addSwitch( 's2' )
    midSwitch = net.addSwitch( 's3' )
    uplSwitch = net.addSwitch( 's4' )
    uprSwitch = net.addSwitch( 's5' )

    # Add links
    net.addLink( h1, leftSwitch )
    net.addLink( leftSwitch, midSwitch )
    net.addLink( midSwitch, rightSwitch )
    net.addLink( rightSwitch, h2 )
    net.addLink( rightSwitch, uprSwitch )
    net.addLink( leftSwitch, uplSwitch )
    net.addLink( uprSwitch, uplSwitch )

    net.start()
    #print h1.cmd( 'ping -c1', h2.IP() )

    h1.cmd( 'dhclient h1-eth0 ')
    h2.cmd( 'dhclient h2-eth0' )
    CLI( net )

    net.stop()

if __name__ == '__main__':
    setLogLevel( 'info' )
    aggNet()


import subprocess
import itertools

import click

@click.command()
@click.option('--cmd_path', type=str,
              help='location of the data corpus')
@click.option('--data_path', type=str,
              help='location of the data corpus')
def test_params(cmd_path: str, data_path: str):
    nhid_ = [50, 100, 300]
    nlayers_ = [1, 2, 4]
    #lr_ = [0.00001, 0.0001]
    lr_ = [1.e-4]
    #clip_ = [0.2, 0.6]
    clip_ = [0.5]
    epochs = 300
    #batch_size_ = [5, 20, 40]
    batch_size_ = [5, 10]
    #bptt_ = [35, 70, 300]
    bptt_ = [35, 70]
    dropout = {50: 0.5, 100: 0.5, 300: 0.5}

    log_level = 'info'

    num_runs = len(nhid_)\
               *len(nlayers_)\
               *len(lr_)\
               *len(clip_)\
               *len(batch_size_)\
               *len(bptt_)
    for i, (nhid, nlayers, lr, clip, batch_size, bptt) \
            in enumerate(itertools.product(nhid_,
                                           nlayers_,
                                           lr_,
                                           clip_,
                                           batch_size_,
                                           bptt_)):
        log_interval = 50000 // (batch_size*bptt)
        if log_interval < 0:
            log_interval = 10
        print(f'Doing run {i}/{num_runs}')
        call = ['python', str(cmd_path),
                '--data_path', str(data_path),
                '--nhid', str(nhid),
                '--nlayers', str(nlayers),
                '--lr', str(lr),
                '--clip', str(clip),
                '--epochs', str(epochs),
                '--batch_size', str(batch_size),
                '--bptt', str(bptt),
                '--dropout', str(dropout[nhid] if nlayers > 1 else 0),
                '--tied', str(nhid == 300),
                '--log-interval', str(log_interval),
                '--log-level', str(log_level)]
        print(f'call: {call}')
        subprocess.run(call)

if __name__ == '__main__':
    test_params()


from django.urls import path
from .views import *

urlpatterns = [
	path('', carro_inicio, name="carro_inicio"),
	path('crear', carro_crear, name="carro_crear"),
	path('vaciar', carro_vaciar, name="carro_vaciar"),
	path('quitar-de-carro/<int:id>', carro_quitar, name="carro_quitar"),
	path('modificar-cantidad-carro/<int:id>/<int:cantidad>', carro_modificar_cantidad, name="carro_modificar_cantidad"),
	path('pagar', carro_pagar, name="carro_pagar"),
	path('webpay', carro_webpay, name="carro_webpay"),
	path('webpay-respuesta', carro_webpay_respuesta, name="carro_webpay_respuesta"),
]


import tkinter as tk
from tkinter import filedialog, LabelFrame
import cv2
from PIL import ImageTk, Image
from preprocessing import Video
import os

class Runner:

    class Statuses:
        def __init__(self):
            self.video = None
            self.bracket = None
            self.arena = None
            self.beetle = None
            self.start = None
            self.end = None

    def updateStartEnds(self, *args):
        self.statuses.start = self.startFrameVar.get()
        self.statuses.end = self.endFrameVar.get()
        try:
            self.currentVideo.startFrame = int(self.statuses.start)
            self.currentVideo.videoEndFrame = int(self.statuses.end)
        except:
            print("Failure to interpret frame range")

    def __init__(self):
        root = tk.Tk()
        root.title("Beetle Tracker v0.1.2")
        self.currentVideo = Video()
        self.statuses = self.Statuses()
        self.savePath = os.getcwd()
        title = tk.Label(text="Beetle Tracker GUI", padx=80, pady=20)

        self.newVideoBtn = tk.Button(text="Select Video", command=lambda: self.currentVideo.initialize(self.newVideo()))
        videoTxt = tk.Label(text="Video: ", pady=8)
        self.videoStatus = tk.Label(text="None", fg="Red")

        self.selectBracketBtn = tk.Button(root, text="Select Bracket", state="disabled", command=self.selectBracketBtnFn)
        bracketTxt = tk.Label(text="Bracket: ", pady=8)
        self.bracketStatus = tk.Label(text="None", fg="Red")

        self.selectArenaBtn = tk.Button(text="Select Arena", state="disabled", command=self.selectArenaBtnFn)
        arenaTxt = tk.Label(text="Arena: ", pady=8)
        self.arenaStatus = tk.Label(text="None", fg="Red")

        self.selectBeetleBtn = tk.Button(text="Select Beetle", state="disabled", command=self.getBeetleSelectWrapperFn)
        beetleTxt = tk.Label(text="Black beetle: ", pady=8)
        self.beetleStatus = tk.Label(text="None", fg="Red")

        self.startFrameVar = tk.StringVar("")
        self.endFrameVar = tk.StringVar("")
        self.startFrameVar.trace('w', self.updateStartEnds)
        self.endFrameVar.trace('w', self.updateStartEnds)

        self.selectStartBtn = tk.Button(text="Set Start", state="disabled", command=self.getFirstFrameWrapperFn)
        startTxt = tk.Label(text="Start Frame: ", pady=8)
        self.startStatus = tk.Entry(text="None", fg="Red", width=4, textvariable=self.startFrameVar)

        self.selectEndBtn = tk.Button(text="Set End", state="disabled", command=self.getLastFrameWrapperFn)
        endTxt = tk.Label(text="End Frame: ", pady=8)
        self.endStatus = tk.Entry(text="None", fg="Red", width=4, textvariable=self.endFrameVar)

        instructions = tk.Label(text="Select a video file to start")

        self.startButton = tk.Button(text="Save Files", state="disabled", padx=10, pady=10, command=lambda: self.startFn(self.savePath))

        self.savePathBtn = tk.Button(text="Output", command=self.changeSavePathFn)
        self.savePathTxt = tk.Label(text="{}".format(self.savePath), pady=8)

        title.grid(columnspan=3)

        self.newVideoBtn.grid(column=0, row=1)
        videoTxt.grid(sticky = tk.W, column=1, row=1)
        self.videoStatus.grid(sticky = tk.W, column=2, row=1)

        self.selectBracketBtn.grid(column=0, row=2)
        bracketTxt.grid(sticky = tk.W, column=1, row=2)
        self.bracketStatus.grid(sticky = tk.W, column=2, row=2)

        self.selectArenaBtn.grid(column=0, row=3)
        arenaTxt.grid(sticky = tk.W, column=1, row=3)
        self.arenaStatus.grid(sticky = tk.W, column=2, row=3)

        self.selectStartBtn.grid(column=0, row=4)
        startTxt.grid(sticky = tk.W, column=1, row=4)
        self.startStatus.grid(sticky = tk.W, column=2, row=4)

        self.selectEndBtn.grid(column=0, row=5)
        endTxt.grid(sticky = tk.W, column=1, row=5)
        self.endStatus.grid(sticky = tk.W, column=2, row=5)

        self.selectBeetleBtn.grid(column=0, row=6)
        beetleTxt.grid(sticky = tk.W, column=1, row=6)
        self.beetleStatus.grid(sticky = tk.W, column=2, row=6)

        self.startButton.grid(columnspan=3, row = 7)
        instructions.grid(columnspan=3, row = 8)

        self.savePathBtn.grid(column=0, row = 9)
        self.savePathTxt.grid(column=1, columnspan=2, row=9)
        root.mainloop()

    def selectBracketBtnFn(self):
        res = self.currentVideo.getBracketROIWrapper()
        if(res):
            self.statuses.bracket = "Done"
        else:
            self.statuses.bracket = None
        self.updateStatuses()

    def selectArenaBtnFn(self):
        res = self.currentVideo.getArenaROIWrapper()
        if(res):
            self.statuses.arena = "Done"
        else:
            self.statuses.arena = None
        self.updateStatuses()

    def getFirstFrameWrapperFn(self):
        res = self.currentVideo.getFirstFrameWrapper()
        if res:
            self.statuses.start = str(res)
            self.startFrameVar.set(str(res))
        else:
            self.statuses.start = None
        self.updateStatuses()

    def getLastFrameWrapperFn(self):
        res = self.currentVideo.getLastFrameWrapper()
        if res:
            self.statuses.end = str(res)
            self.endFrameVar.set(str(res))
        else:
            self.statuses.end = None
        self.updateStatuses()

    def getBeetleSelectWrapperFn(self):
        res = self.currentVideo.getBeetleSelectWrapper()
        if res:
            self.statuses.beetle = str(res)
        else:
            self.statuses.beetle = None
        self.updateStatuses()

    def changeSavePathFn(self):
        dirname = tk.filedialog.askdirectory(initialdir="../",title='Please select a directory')
        self.savePath = dirname
        self.updateStatuses()

    def newVideo(self):
        def pickFile():
            path =  tk.filedialog.askopenfilename(initialdir = "../",title = "Select file",filetypes = (("movie files","*.mp4"),("all files","*.*")))
            testCapture = cv2.VideoCapture(path)
            if not testCapture.isOpened():
                return pickFile()
            else:
                ret, frame = testCapture.read()
                if not ret:
                    return pickFile()

            print("Loaded in video {} successfully.".format(path))
            return path
        f = pickFile()
        print(f)
        self.statuses.video = os.path.basename(f)
        self.updateStatuses()
        return f

    def updateStatuses(self):
        if(self.statuses.video):
            self.videoStatus["text"] = self.statuses.video
            self.videoStatus["fg"] = "Green"

            self.selectBracketBtn["state"] = "normal"
            self.selectArenaBtn["state"] = "normal"
        else:
            self.videoStatus["fg"] = "red"
            self.videoStatus["text"] = "None"
            self.selectBracketBtn["state"] = "disabled"
            self.selectArenaBtn["state"] = "disabled"
            self.selectStartBtn["state"] = "disabled"
            self.selectEndBtn["state"] = "disabled"

        if(self.statuses.bracket):
            self.bracketStatus["fg"] = "green"
            self.bracketStatus["text"] = "Done"
        else:
            self.bracketStatus["fg"] = "red"
            self.bracketStatus["text"] = "None"

        if(self.statuses.arena):
            self.arenaStatus["fg"] = "green"
            self.arenaStatus["text"] = "Done"
            self.selectStartBtn["state"] = "normal"
            self.selectEndBtn["state"] = "normal"
        else:
            self.arenaStatus["fg"] = "red"
            self.arenaStatus["text"] = "None"
            self.selectStartBtn["state"] = "disabled"
            self.selectEndBtn["state"] = "disabled"

        if(self.statuses.start):
            self.startStatus["fg"] = "green"
            self.startFrameVar.set(str(self.statuses.start))
            self.selectBeetleBtn["state"] = "normal"
        else:
            self.startStatus["fg"] = "red"
            self.startFrameVar.set("0")
            self.selectBeetleBtn["state"] = "disabled"

        if(self.statuses.end):
            self.endStatus["fg"] = "green"
            self.endFrameVar.set(str(self.statuses.end))
        else:
            self.endStatus["fg"] = "red"
            self.endFrameVar.set("0")

        if(self.statuses.beetle):
            self.beetleStatus["fg"] = "green"
            self.beetleStatus["text"] = self.statuses.beetle
        else:
            self.beetleStatus["fg"] = "red"
            self.beetleStatus["text"] = "None"

        if(self.statuses.video and
        self.statuses.bracket and
        self.statuses.arena and
        self.statuses.start and
        self.statuses.end and
        self.statuses.beetle ):
            self.startButton["state"] = "normal"
        else:
            self.startButton["state"] = "disabled"

        self.savePathTxt["text"] = self.savePath + "/" + self.statuses.video

    def startFn(self, savePath):
        path = self.currentVideo.savePostProcData(savePath)
        print("Directory generated at {}".format(path))
        os.startfile(path)

    # def getBeetleBracketBtnFn(self):

if __name__ == '__main__' :
    r = Runner()


from django.views.generic import View
from django.shortcuts import render, redirect
from django.utils import translation

from branch.models import Branch
from menu.models import MenuCategory
from seo.models import MetaInformation

class HomeView(View):
    def get(self, request, code=None):
        if Branch.objects.count() > 0:
            if not code:
                return redirect('home', Branch.objects.all()[0].code)
        context = {}

        context['branches'] = Branch.objects.all()
        context['categories'] = MenuCategory.objects.filter(branch__code=code)
        context['current_branch'] = Branch.objects.get(code=code)

        language = request.GET.get('language')
        if language:
            translation.activate(language)
            request.session[translation.LANGUAGE_SESSION_KEY] = \
                language

        current_language = translation.get_language()

        context['current_language'] = current_language
        context['next_language'] = 'en' if current_language == 'nl' \
            else 'nl'

        infos = MetaInformation.objects.filter(enabled=True)
        if infos.count() > 0:
            context['meta_information'] = infos[0]
            context['meta_keywords'] = [
                k.keyword for k in infos[0].metakeyword_set.all()
                if k.enabled
            ]
        else:
            context['meta_information'] = None

        return render(request, 'home.html', context)