#!python3
#lower = int(args.lower)

import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import sys
import argparse
import signal
import math
from scipy.stats import zscore
from bisect import bisect_left
parser = argparse.ArgumentParser(description='Creates normal heatmaps and creates bullseye plots which account for the manhattan distance between each site.')
parser.add_argument('-i', action = 'store', dest = 'input_file', required = True, type=str, help='input file')
parser.add_argument('-o', action = 'store', dest = 'output_file', required = True, type=str, help='prefix for output plots')
parser.add_argument('-c', action = 'store', dest = 'colorscheme', required = False, help='matplotlib_colors', default = "Red")
parser.add_argument('-z', dest='znorm', action='store_true', help='znorm each ring in bullseye plot', default = False)
parser.add_argument('-s', dest='squareBullseye', action='store_true', help='Trim edges to make a square bullseye plot', default = False)
parser.add_argument('-l', dest='lower', action='store', required = False, help='minvalue for color scale', type=float)
parser.add_argument('-u', dest='upper', action='store', required = False, help='maxvalue for color scale', type=float)
args = parser.parse_args()

spot = str(args.input_file)
outpre = str(args.output_file)
heatcol = str(args.colorscheme)

#lower = int(args.lower)
#upper = int(args.upper)
znorm = args.znorm
square = args.squareBullseye

def takeClosest(myList, myNumber):
    """
    Assumes myList is sorted. Returns closest value to myNumber.

    If two numbers are equally close, return the smallest number.
    """
    pos = bisect_left(myList, myNumber)
    if pos == 0:
        return 0
    if pos == len(myList):
        return -1
    before = myList[pos - 1]
    after = myList[pos]
    if after - myNumber < myNumber - before:
       return pos
    else:
       return pos - 1
mat = np.loadtxt(spot)

#this is the size of the starting matrix
matsize = len(mat)
if (matsize % 2) == 0:
    print("Bullseye requires a central bin, therefore the number of rows and columns in the input matrix should be odd")
    sys.exit(0)

#this is the number of rings in the plot which corresponds to the Manhattan distance
rings = math.floor(math.sqrt(((matsize//2)**2)/2))

#This is the maximum number of rings that will be needed if square is set to True.
maxrings = math.ceil(math.sqrt(rings**2 + rings**2))

#this is the number of radial slices the circle is divided in to. Too few and the segments will be distorted.
#slices = 2000
slices = (matsize-1)*100
#this toggles on z-score normalization of each ring.
#znorm = False

#this toggles between "closest-angle" mapping and "uniform segment length" mapping
uniform = True

#this makes a square plot by trimming the edges of the plot.
#square = False

#First we compute the Manhattan distance and arctan of every point in the starting matrix
arctan = np.zeros((matsize,matsize))
manhattandistance = np.zeros((matsize,matsize))
for i in range(0,len(manhattandistance)):
    for j in range(0,len(manhattandistance)):
        manhattandistance[i,j] = abs(j-int((matsize-1)/2)) + abs(i-((matsize-1)/2))
        arctan[i,j] = np.arctan2(((j-int((matsize-1)/2))),((i-((matsize-1)/2))))

#We rearrange the Manhattan distances and arctans into lists based on the Manhattan distances.
#This means each ring is now represented by a list of scores and arctans.
manhat_arctans = []
manhat_scores = []
for a in range(matsize):
    manhat_arctans.append([])
    manhat_scores.append([])
    for b in range(matsize):
        for c in range(matsize):
            if (manhattandistance[b,c] == a):
                manhat_scores[a].append(mat[b,c])
                manhat_arctans[a].append(arctan[b,c])

#Next we construct the meshgrid for the circular plot.
rad = np.linspace(0, maxrings, maxrings+1)
azm = np.linspace(0, 2 * np.pi, slices)
r, th = np.meshgrid(rad, azm)

#now we trim the edges of the meshgrid to make a square
if square:
    for i in range(slices):
        for j in range(maxrings+1):
            #compute the cartesian coordinates of each quad to see if they need trimming
            nrad = r[i,j]
            theta = th[i,j]
            cosine = math.cos(theta)
            x = nrad * cosine
            sine = math.sin(theta)
            y = nrad * sine
            if abs(x) > abs(y):
                if abs(x) > rings:
                    nrad = abs(rings/cosine)
            else:
                if abs(y) > rings:
                    nrad = abs(rings/sine)
            r[i,j] = nrad

#This will be the new matrix that will be plotted. We need to fill it with the appropriate values.

C = np.zeros([slices,int(maxrings)+1])

dscoretmp1 = 0
dscoretmp2 = 0
dscore = 0
#For each ring we convert the arctans into thetas by making them all positive
#and adjusting for the slices.
for ring in range(int(maxrings)):
    arctans = manhat_arctans[ring]
    thetas = [(x + np.pi) * ((slices/2)/np.pi) for x in arctans]
    scores = manhat_scores[ring]
    #Z-score normalization toggled by boolean value above.
    if znorm:
        if ring:
            scores = zscore(scores).tolist()
        else:
            scores = [0]

    #In order for the values to appropriately wrap around to 0 we need to add the last score to the beginning.
    thetas.append(0)
    scores.append(scores[0])
    #Here we sort the scores and thetas by the theta in order to help finding the closest one.
    sorted_scores = [x for _,x in sorted(zip(thetas,scores))]
    if len(sorted_scores) > 1:
        quatrang = int(float(len(sorted_scores)-1)/4)
        quatstart = quatrang+1
        quatend = quatrang+quatrang
        for hloc in sorted_scores:

            dscoretmp1+=1

        for hloc in sorted_scores[quatstart:quatend]:
            if hloc >= 1:
                dscoretmp2+=1
    sorted_thetas = sorted(thetas)
    #Here to produce a uniform map we map the actual angles to idealized angles.
    if uniform:
        if ring:
            slices_per_segment = slices/(len(scores)-1)
            for t in range(len(sorted_thetas)):
                sorted_thetas[t] = slices_per_segment * t

    #Now for each slice in the ring we find the score corresponding to the nearest theta
    #and assign it to the appropriate coordinate in our matrix to be plotted: C.
    for i in range(slices):
        idx = takeClosest(sorted_thetas,i)
        C[i,ring] = sorted_scores[idx]

#create a juicebox-like red to white colormap
if heatcol == "Red":
    br = LinearSegmentedColormap.from_list("bright_red",[(1,1,1),(1,0,0)])
else:
    br = heatcol

ax = plt.subplot(projection="polar")

if znorm:
    plt.pcolormesh(th,r,C,cmap="seismic",vmin=-4,vmax=4)
    if (dscoretmp1 > 0):
        dscore=float(dscoretmp2/dscoretmp1)*100
    print("ADA score is %s\n" % (str(round(dscore,2))))
else:
    if args.lower is not None and args.upper is not None:
        plt.pcolormesh(th,r,C,cmap=br,vmin=args.lower,vmax=args.upper)
    elif args.lower is not None:
        plt.pcolormesh(th,r,C,cmap=br,vmin=args.lower)
    elif  args.upper is not None:
        plt.pcolormesh(th,r,C,cmap=br,vmax=args.upper)
    else:
        plt.pcolormesh(th,r,C,cmap=br)
if square:
    ax.axis('off')
else:
    xlabels=["","","Left Anchor","","Right Anchor","","",""]
    ax.set_xticklabels(xlabels, rotation=40, ha="right")
    ax.set_yticklabels([])
    plt.colorbar()

#Rotate the plot so that the anchors go back to their original positions.
ax.set_theta_offset(np.pi/2)

plt.savefig(outpre + '_bullseye.png')

plt.clf()
center = (matsize-1)//2

left = center-rings

right = center+rings+1

newmat = (mat[int(left):int(right),int(left):int(right)])
if args.lower is not None and args.upper is not None:
    plt.imshow(newmat,cmap=br,vmin=args.lower,vmax=args.upper)
elif args.lower is not None:
    plt.imshow(newmat,cmap=br,vmin=args.lower)
elif  args.upper is not None:
    plt.imshow(newmat,cmap=br,vmax=args.upper)
else:
    plt.imshow(newmat,cmap=br)

plt.colorbar()
plt.savefig(outpre + '_normal.png')


import psutil
import platform
from pydantic import BaseModel
from sys import platform as pf

from .apscheduler import scheduler

if pf == "win32":
    import wmi
    from win32com.client import GetObject

class PlatformInfo(BaseModel):
    name: str
    struct: str
    type: str

class CpuInfo(BaseModel):
    name: str
    count: int
    max_freq: str
    current_freq: str
    percent: float
    process: int

class MemInfo(BaseModel):
    total: int
    available: int
    percent: float
    used: int
    free: int

    swap_total: int
    swap_used: int
    swap_free: int
    swap_percent: float
    swap_sin: int
    swap_sout: int

class DiskInfo(BaseModel):
    name: str
    total: int
    used: int
    free: int
    drive: int
    speed: list[int]

class NetInfo(BaseModel):
    speed: list[int]
    sent_total: int
    recv_total: int
    package_sent: int
    package_recv: int

def get_platform_info() -> PlatformInfo:
    return PlatformInfo(
        name=platform.platform(), struct=platform.architecture()[0], type=pf
    )

def get_cpu_info() -> CpuInfo:
    cpu_name = platform.processor()
    if pf == "win32":
        winm = GetObject("winmgmts:root\cimv2")
        cpus = winm.ExecQuery("SELECT * FROM Win32_Processor")
        cpu_name = cpus[0].Name.strip()

    cpu_count = psutil.cpu_count(False)
    _freq = psutil.cpu_freq()
    cpu_max_freq = f"{'%.2f'%(_freq.max / 1000)}"
    cpu_current_freq = f"{'%.2f'%(_freq.current / 1000)}"
    cpu_percent = psutil.cpu_percent(interval=0.1)
    process = len(psutil.pids())

    return CpuInfo(
        name=cpu_name,
        count=cpu_count,
        max_freq=cpu_max_freq,
        current_freq=cpu_current_freq,
        percent=cpu_percent,
        process=process,
    )

def get_mem_info() -> MemInfo:
    vm = psutil.virtual_memory()
    sm = psutil.swap_memory()
    return MemInfo(
        total=vm.total,
        available=vm.available,
        percent=vm.percent,
        used=vm.used,
        free=vm.free,
        swap_total=sm.total,
        swap_used=sm.used,
        swap_free=sm.free,
        swap_percent=sm.percent,
        swap_sin=sm.sin,
        swap_sout=sm.sout,
    )

last_disk_io = [0, 0]
now_disk_io = [0, 0]

@scheduler.scheduled_job("interval", seconds=1, misfire_grace_time=15)
async def _():
    global last_disk_io, now_disk_io

    disk_counters = psutil.disk_io_counters()
    now_disk_io = [
        disk_counters.write_bytes - last_disk_io[0],  # type: ignore
        disk_counters.read_bytes - last_disk_io[1],  # type: ignore
    ]
    last_disk_io = [disk_counters.write_bytes, disk_counters.read_bytes]  # type: ignore

def get_disk_info():
    disk_name = "ATRI Disk Pro Plus"
    disk_total = int()
    disk_used = int()
    disk_free = int()
    disk_drive = 1
    if pf == "win32":
        w = wmi.WMI()
        disk_list = [d.DeviceID for d in w.Win32_LogicalDisk()]
        for i in disk_list:
            disk = psutil.disk_usage(i)
            disk_total += disk.total
            disk_used += disk.used
            disk_free += disk.free

        disk_name = w.Win32_DiskDrive()[0].Model
        disk_drive = len(w.Win32_DiskDrive())
    else:
        disk = psutil.disk_usage("/")
        disk_total = disk.total
        disk_used = disk.used
        disk_free = disk.free

    return DiskInfo(
        name=disk_name,
        total=disk_total,
        used=disk_used,
        free=disk_free,
        drive=disk_drive,
        speed=now_disk_io,
    )

last_net_io = [0, 0]
now_net_io = [0, 0]

@scheduler.scheduled_job("interval", seconds=1, misfire_grace_time=15)
async def _():
    global last_net_io, now_net_io

    net_counters = psutil.net_io_counters()
    now_net_io = [
        net_counters.bytes_sent - last_net_io[0],
        net_counters.bytes_recv - last_net_io[1],
    ]
    last_net_io = [net_counters.bytes_sent, net_counters.bytes_recv]

def get_net_info():
    net = psutil.net_io_counters()
    return NetInfo(
        speed=now_net_io,
        sent_total=net.bytes_sent,
        recv_total=net.bytes_recv,
        package_sent=net.packets_sent,
        package_recv=net.packets_recv,
    )


import doctest
import re
import textwrap

import numpy as np

class _FloatExtractor(object):
  """Class for extracting floats from a string.

  For example:

  >>> text_parts, floats = _FloatExtractor()("Text 1.0 Text")
  >>> text_parts
  ["Text ", " Text"]
  >>> floats
  np.array([1.0])
  """

  # Note: non-capturing groups "(?" are not returned in matched groups, or by
  # re.split.
  _FLOAT_RE = re.compile(
      r"""
      (                          # Captures the float value.
        (?:
           [-+]|                 # Start with a sign is okay anywhere.
           (?:                   # Otherwise:
               ^|                # Start after the start of string
               (?<=[^\w.])       # Not after a word char, or a .
           )
        )
        (?:                      # Digits and exponent - something like:
          {digits_dot_maybe_digits}{exponent}?|   # "1.0" "1." "1.0e3", "1.e3"
          {dot_digits}{exponent}?|                # ".1" ".1e3"
          {digits}{exponent}|                     # "1e3"
          {digits}(?=j)                           # "300j"
        )
      )
      j?                         # Optional j for cplx numbers, not captured.
      (?=                        # Only accept the match if
        $|                       # * At the end of the string, or
        [^\w.]                   # * Next char is not a word char or "."
      )
      """.format(
          # Digits, a "." and optional more digits: "1.1".
          digits_dot_maybe_digits=r'(?:[0-9]+\.(?:[0-9]*))',
          # A "." with trailing digits ".23"
          dot_digits=r'(?:\.[0-9]+)',
          # digits: "12"
          digits=r'(?:[0-9]+)',
          # The exponent: An "e" or "E", optional sign, and at least one digit.
          # "e-123", "E+12", "e12"
          exponent=r'(?:[eE][-+]?[0-9]+)'),
      re.VERBOSE)

  def __call__(self, string):
    """Extracts floats from a string.

    >>> text_parts, floats = _FloatExtractor()("Text 1.0 Text")
    >>> text_parts
    ["Text ", " Text"]
    >>> floats
    np.array([1.0])

    Args:
      string: the string to extract floats from.

    Returns:
      A (string, array) pair, where `string` has each float replaced by "..."
      and `array` is a `float32` `numpy.array` containing the extracted floats.
    """
    texts = []
    floats = []
    for i, part in enumerate(self._FLOAT_RE.split(string)):
      if i % 2 == 0:
        texts.append(part)
      else:
        floats.append(float(part))

    return texts, np.array(floats)

class TfDoctestOutputChecker(doctest.OutputChecker, object):
  """Customizes how `want` and `got` are compared, see `check_output`."""

  def __init__(self, *args, **kwargs):
    super(TfDoctestOutputChecker, self).__init__(*args, **kwargs)
    self.extract_floats = _FloatExtractor()
    self.text_good = None
    self.float_size_good = None

  _ADDRESS_RE = re.compile(r'\bat 0x[0-9a-f]*?>')
  # TODO(yashkatariya): Add other tensor's string substitutions too.
  # tf.RaggedTensor doesn't need one.
  _NUMPY_OUTPUT_RE = re.compile(r'<tf.Tensor.*?numpy=(.*?)>', re.DOTALL)

  def _allclose(self, want, got, rtol=1e-3, atol=1e-3):
    return np.allclose(want, got, rtol=rtol, atol=atol)

  def _tf_tensor_numpy_output(self, string):
    modified_string = self._NUMPY_OUTPUT_RE.sub(r'\1', string)
    return modified_string, modified_string != string

  MESSAGE = textwrap.dedent("""\n
        #############################################################
        Check the documentation (https://www.tensorflow.org/community/contribute/docs_ref) on how to
        write testable docstrings.
        #############################################################""")

  def check_output(self, want, got, optionflags):
    """Compares the docstring output to the output gotten by running the code.

    Python addresses in the output are replaced with wildcards.

    Float values in the output compared as using `np.allclose`:

      * Float values are extracted from the text and replaced with wildcards.
      * The wildcard text is compared to the actual output.
      * The float values are compared using `np.allclose`.

    The method returns `True` if both the text comparison and the numeric
    comparison are successful.

    The numeric comparison will fail if either:

      * The wrong number of floats are found.
      * The float values are not within tolerence.

    Args:
      want: The output in the docstring.
      got: The output generated after running the snippet.
      optionflags: Flags passed to the doctest.

    Returns:
      A bool, indicating if the check was successful or not.
    """

    # If the docstring's output is empty and there is some output generated
    # after running the snippet, return True. This is because if the user
    # doesn't want to display output, respect that over what the doctest wants.
    if got and not want:
      return True

    if want is None:
      want = ''

    if want == got:
      return True

    # Replace python's addresses with ellipsis (`...`) since it can change on
    # each execution.
    want = self._ADDRESS_RE.sub('at ...>', want)

    # Replace tf.Tensor strings with only their numpy field values.
    want, want_changed = self._tf_tensor_numpy_output(want)
    if want_changed:
      got, _ = self._tf_tensor_numpy_output(got)

    # Separate out the floats, and replace `want` with the wild-card version
    # "result=7.0" => "result=..."
    want_text_parts, self.want_floats = self.extract_floats(want)
    # numpy sometimes pads floats in arrays with spaces
    # got: [1.2345, 2.3456, 3.0   ]  want:  [1.2345, 2.3456, 3.0001]
    # And "normalize whitespace" only works when there's at least one space,
    # so strip them and let the wildcard handle it.
    want_text_parts = [part.strip(' ') for part in want_text_parts]
    want_text_wild = '...'.join(want_text_parts)
    if '....' in want_text_wild:
      # If a float comes just after a period you'll end up four dots and the
      # first three count as the ellipsis. Replace it with three dots.
      want_text_wild = re.sub(r'\.\.\.\.+', '...', want_text_wild)

    # Find the floats in the string returned by the test
    _, self.got_floats = self.extract_floats(got)

    self.text_good = super(TfDoctestOutputChecker, self).check_output(
        want=want_text_wild, got=got, optionflags=optionflags)
    if not self.text_good:
      return False

    if self.want_floats.size == 0:
      # If there are no floats in the "want" string, ignore all the floats in
      # the result. "np.array([ ... ])" matches "np.array([ 1.0, 2.0 ])"
      return True

    self.float_size_good = (self.want_floats.size == self.got_floats.size)

    if self.float_size_good:
      return self._allclose(self.want_floats, self.got_floats)
    else:
      return False

  def output_difference(self, example, got, optionflags):
    got = [got]

    # If the some of the float output is hidden with `...`, `float_size_good`
    # will be False. This is because the floats extracted from the string is
    # converted into a 1-D numpy array. Hence hidding floats is not allowed
    # anymore.
    if self.text_good:
      if not self.float_size_good:
        got.append("\n\nCAUTION: tf_doctest doesn't work if *some* of the "
                   "*float output* is hidden with a \"...\".")

    got.append(self.MESSAGE)
    got = '\n'.join(got)
    return (super(TfDoctestOutputChecker,
                  self).output_difference(example, got, optionflags))


"""
Definition of events that can be sent on the game
"""

import enum

__author__ = "Benjamin Schubert <ben.c.schubert@gmail.com>"

@enum.unique
class Event(enum.IntEnum):
    """
    Enumeration of all events valid in the game
    """
    ERROR = 0
    TOKEN = 1
    GAME_INFO = 2
    STATE = 3
    FOOD = 4
    DEATH = 5
    BULLETS = 6
    BONUS = 7
    HOOK = 8
    ALIVE = 9
    FINISHED = 10

@enum.unique
class Error(enum.IntEnum):
    """
    Enumeration of all errors that the server can throw to a player
    """
    TOKEN_INVALID = 0
    MAX_CAPACITY = 1
    NO_TOKEN = 2
    DUPLICATE_USERNAME = 3


import numpy as np
from scipy.signal import convolve
from porespy.tools import ps_rect

__all__ = [
    "local_diff",
    "ramp",
]

def ramp(shape, inlet=1.0, outlet=0.0, axis=0):
    r"""
    Generates an array containing a linear ramp of greyscale values along the given
    axis.

    Parameter
    ---------
    shape : list
        The [X, Y, Z] dimension of the desired image. Z is optional.
    inlet : scalar
        The values to place the beginning of the specified axis
    outlet : scalar
        The values to place the end of the specified axis
    axis : scalar
        The axis along which the ramp should be directed

    Returns
    -------
    ramp : ndarray
        An array of the requested shape with greyscale values changing linearly
        from inlet to outlet in the direction specified.
    """
    vals = np.linspace(inlet, outlet, shape[axis])
    vals = np.reshape(vals, [shape[axis]]+[1]*len(shape[1:]))
    vals = np.swapaxes(vals, 0, axis)
    shape[axis] = 1
    ramp = np.tile(vals, shape)
    return ramp

def local_diff(vals, im, strel=None):
    r"""
    Computes the difference pixel and the average of it's neighbors.

    Parameters
    ----------
    vals : ndarray
        The array containing the values of interest
    im : ndarray
        A boolean image of the domain
    strel : ndarray, optional
        The struturing element to use when doing the convolution to find the
        neighbor values.  This defines the size and shape of the area searched.
        If not provided then a 3**ndim cube is used.

    Returns
    -------
    diff : ndarray
        An array containing the difference between each pixel and the average
        of it's neighbors.  The result is not normalized or squared so may
        contain negative values which might be of interest if the direction of the
        difference is relevant.
    """
    if strel is None:
        strel = ps_rect(w=3, ndim=im.ndim)
    numer = convolve(vals*im, strel, mode='same')
    denom = convolve(im*1.0, strel, mode='same')
    ave = numer/denom
    diff = ave - vals
    diff[~im] = 0
    return diff


# Q1. Remove Duplicates in a list
# List Version
def r_duplicates(a_list):
    result = []

    for value in a_list:
        if value not in result:
            result.append(value)
    return result
# end of r_duplicates(a_list)
print(r_duplicates([1,2,2,3,3,3,4,4,4,4]))

# Set Version
def r_duplicates2(a_list):
    #set_version = set(a_list)
    #return list(set_version)
    return list(set(a_list))
# end of r_duplicates2

print(r_duplicates2([1,2,2,3,3,3,4,4,4,4]))

# Q2. Unique Letters in Given Words
# Write a Python function that takes a list of words and returns a set containing all unique letters used in these words.
def unique_letters(a_list):
    # a_list will contain strings of words
    result_set = set() # set() is an empty set not {} ... because that is a dictionary
    for word in a_list:
        tmp_set = set(word) # convert the string word into a set
        result_set = result_set | (tmp_set) # | operator is union ... we can also use |= if we wished

    return result_set
# end of unique_letters

test = ["hello", "goodbye", "world", "mr. park!"]
print(unique_letters(test))

# Q3. Set Intersection Count

# Write a Python function that takes a list of sets and returns the count of elements that are common to all the sets.

def i_count(a_list):
    # a_list contains numerous sets
    if a_list:
        result_set = a_list[0] # grab the first value from a_list

        for example_set in a_list[1:]:
            result_set = result_set & example_set # & is the intersection operator

        return len(result_set) # len() will count how many values our result_set has.
# end of i_count
test = [{1,2,3,7}, {3,4,5,7}, {5,6,7,8}]
print(i_count(test))


from django.shortcuts import render
import json

def family(request, family_id):
    with open('info/animals.json') as file:
        data = json.load(file)
        animals = [animal for animal in data['animals'] if animal['family'] == family_id]
        family_name = next((family['name'] for family in data['families'] if family['id'] == family_id), '')
        context = {'animals': animals, 'family_name': family_name}
    return render(request, 'family.html', context)

def animal(request, animal_id):
    with open('info/animals.json') as file:
        data = json.load(file)
        animal = next((animal for animal in data['animals'] if animal['id'] == animal_id), {})
        context = {'animal': animal}
    return render(request, 'animal.html', context)


# https://leetcode.com/problems/evaluate-reverse-polish-notation/
class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        operators = ['+', '-', "/", "*"]
        stck = []
        ans = 0
        for i in range (len(tokens)):
            if len(tokens) == 1:
                    return eval(tokens[0])
            if tokens[i] not in operators:
                stck.append(eval(tokens[i]))

            else:
                temp1 = stck.pop(-1)
                temp2 = stck.pop(-1)
                if tokens[i] =='+':
                    ans = temp2 + temp1
                if tokens[i] =='-':
                    ans = temp2 - temp1
                if tokens[i] =='/':
                    ans = int(float(temp2) / temp1)
                if tokens[i] =='*':
                    ans = temp2 * temp1
                stck.insert(i-2, ans)
        return ans


import pytest
from imageMetrics import metrics
import numpy as np

class TestRelativeErrorImage:
    def testEqualImages(self):
        assert np.array_equal(metrics.RelativeErrorImage(
            np.ones(5), np.ones(5), epsilon=0
        ), np.zeros(5))

    def testTrueBigger(self):
        assert np.array_equal(metrics.RelativeErrorImage(
            2*np.ones(5), np.ones(5), epsilon=0
        ), -0.5*np.ones(5))

    def testPredictedBigger(self):
        assert np.array_equal(metrics.RelativeErrorImage(
            np.ones(5), 2*np.ones(5), epsilon=0
        ), np.ones(5))

    def testBothZero(self):
        assert np.array_equal(metrics.RelativeErrorImage(
            np.zeros(5), np.zeros(5)
        ), np.zeros(5))

    def testEpsilon(self):
        assert np.allclose(metrics.RelativeErrorImage(
            2*np.ones(5), np.ones(5)
        ), -0.5*np.ones(5))

    def testMask(self):
        mask = np.ones(5)
        mask[0], mask[-1] = 0, 0
        target = -.5*np.ones(5)
        target[0], target[-1] = 0, 0
        assert np.allclose(metrics.RelativeErrorImage(
            2*np.ones(5), np.ones(5), mask
        ), target)


# -*- coding: utf-8 -*-
from contextlib import contextmanager
from math import floor, log10
from timeit import default_timer as timer
from typing import Tuple

import torch
import torch.nn as nn
from torch.utils.data import DataLoader, SubsetRandomSampler, TensorDataset

# +
from torchvision.datasets import MNIST, CIFAR10
from torchvision.transforms import Compose, ConvertImageDtype, Normalize, ToTensor

from fastprogress.fastprogress import progress_bar

# -

def mnist_target_to_binary(target, B):
    """Convert target digits into a zeros (class A) and ones (class B)."""
    new_target = torch.zeros_like(target, dtype=torch.float)
    new_target[target == B] = 1.0
    return new_target.unsqueeze(-1)

def get_binary_mnist_dataloader(
    path: str, train: bool, A: int, B: int, bs: int
) -> Tuple[DataLoader, int]:
    """Helper method returning either a training or validation data loader."""

    # Convert images to normalized tensors with mean 0 and standard deviation 1
    image_xforms = Compose(
        [
            ConvertImageDtype(torch.float),  # ToTensor(),
            Normalize((0.1307,), (0.3081,)),
        ]
    )

    dataset = MNIST(root=path, train=train, download=True)  # , transform=image_xforms)

    # Grab indices for the two requested classes
    idx_classA = [i for i, t in enumerate(dataset.targets) if t == A]
    idx_classB = [i for i, t in enumerate(dataset.targets) if t == B]

    idxs = idx_classA + idx_classB
    size = len(idxs)

    if bs == 0:
        bs = size

    X = image_xforms(dataset.data[idxs])
    y = mnist_target_to_binary(dataset.targets[idxs], B)

    dataset = TensorDataset(X, y)

    dataset.classes = [A, B]
    dataset.data = X
    dataset.targets = y

    loader = DataLoader(dataset, batch_size=bs)

    return loader, size

def get_binary_mnist_dataloaders(
    path: str, A: int, B: int, bs_train: int = 0, bs_valid: int = 0
) -> Tuple[DataLoader, int, DataLoader, int]:
    """Return an MNIST dataloader for the two specified classes.

    Args:
        path (str): location in which to store downloaded data
        A (int): class A, a number in [0, 9] denoting a MNIST class/number
        B (int): class B, a number in [0, 9] denoting a MNIST class/number
        bs_train (int): batch size for training data loader
        bs_valid (int): batch size for validation data loader

    Returns:
        Tuple[DataLoader, int, DataLoader, int]: [description]
    """
    train_loader, train_size = get_binary_mnist_dataloader(path, True, A, B, bs_train)
    valid_loader, valid_size = get_binary_mnist_dataloader(path, False, A, B, bs_valid)
    return train_loader, train_size, valid_loader, valid_size

def get_binary_mnist_one_batch(path: str, A: int, B: int, flatten: bool):
    """Return entire MNIST training and validation partitions as single batches.

    Args:
        path (str): location in which to store downloaded data
        A (int): class A, a number in [0, 9] denoting a MNIST class/number
        B (int): class B, a number in [0, 9] denoting a MNIST class/number
    """
    train_dl, _, valid_dl, _ = get_binary_mnist_dataloaders(path, A, B)

    # Convenient method for turning a data loader into batch
    train_x, train_y = next(iter(train_dl))
    valid_x, valid_y = next(iter(valid_dl))

    if flatten:
        train_x = torch.flatten(train_x, start_dim=1)
        valid_x = torch.flatten(valid_x, start_dim=1)

    train_y = mnist_target_to_binary(train_y, B)
    valid_y = mnist_target_to_binary(valid_y, B)

    return train_x, train_y, valid_x, valid_y

def get_mnist_data_loaders(path, batch_size, valid_batch_size):

    # MNIST specific transforms
    image_xforms = Compose([ToTensor(), Normalize((0.1307,), (0.3081,))])

    # Training data loader
    train_dataset = MNIST(root=path, train=True, download=True, transform=image_xforms)

    tbs = len(train_dataset) if batch_size == 0 else batch_size
    train_loader = DataLoader(train_dataset, batch_size=tbs, shuffle=True)

    # Validation data loader
    valid_dataset = MNIST(root=path, train=False, download=True, transform=image_xforms)

    vbs = len(valid_dataset) if valid_batch_size == 0 else valid_batch_size
    valid_loader = DataLoader(valid_dataset, batch_size=vbs, shuffle=True)

    return train_loader, valid_loader

# +
def get_cifar10_data_loaders(path, batch_size, valid_batch_size):

#     std = (0.4941, 0.4870, 0.5232)
#     mean = (-0.0172, -0.0357, -0.1069)
    std = (0.2470, 0.2435, 0.2616)
    mean =(0.4914, 0.4822, 0.4465)
    image_xforms = Compose([ToTensor(), Normalize(mean, std)])

    train_dataset = CIFAR10(root=path, train=True, download=True, transform=image_xforms)

    tbs = len(train_dataset) if batch_size == 0 else batch_size
    train_loader = DataLoader(train_dataset, batch_size=tbs, shuffle=True)

    valid_dataset = CIFAR10(root=path, train=False, download=True, transform=image_xforms)

    vbs = len(valid_dataset) if valid_batch_size == 0 else valid_batch_size
    valid_loader = DataLoader(valid_dataset, batch_size=vbs, shuffle=True)

    return train_loader, valid_loader

# -

class NN_FC_CrossEntropy(nn.Module):
    def __init__(self, layer_sizes, activation=nn.ReLU):
        super(NN_FC_CrossEntropy, self).__init__()

        first_layer = nn.Flatten()
        middle_layers = [
            nn.Sequential(nn.Linear(nlminus1, nl), activation())
            for nl, nlminus1 in zip(layer_sizes[1:-1], layer_sizes)
        ]
        last_layer = nn.Linear(layer_sizes[-2], layer_sizes[-1])

        all_layers = [first_layer] + middle_layers + [last_layer]

        self.layers = nn.Sequential(*all_layers)

    def forward(self, X):
        return self.layers(X)

def compute_validation_accuracy_multi(dataloader, model, criterion, device, mb, epoch):

    model.eval()

    N = len(dataloader.dataset)
    num_batches = len(dataloader)

    valid_loss, num_correct = 0, 0

    with torch.no_grad():

        for X, Y in dataloader:

            X, Y = X.to(device), Y.to(device)
            output = model(X)

            valid_loss += criterion(output, Y).item()
            num_correct += (output.argmax(1) == Y).type(torch.float).sum().item()

        valid_loss /= num_batches
        valid_accuracy = num_correct / N

    mb.write(
        f"{epoch:>3}: validation accuracy={(100*valid_accuracy):5.2f}% and loss={valid_loss:.3f}"
    )
    return valid_loss, valid_accuracy

def train_one_epoch(dataloader, model, criterion, optimizer, device, mb):

    model.train()

    num_batches = len(dataloader)
    dataiter = iter(dataloader)

    for batch in progress_bar(range(num_batches), parent=mb):

        X, Y = next(dataiter)
        X, Y = X.to(device), Y.to(device)

        output = model(X)

        loss = criterion(output, Y)

        optimizer.zero_grad()
        loss.backward()
        optimizer.step()

def format_duration_with_prefix(duration, sig=2):
    # Round to significant digits
    duration = round(duration, -int(floor(log10(abs(duration)))) + (sig - 1))

    if duration < 1e-6:
        return f"{duration*1e9:.1f} ns"
    elif duration < 1e-3:
        return f"{duration*1e6:.1f} μs"
    elif duration < 1:
        return f"{duration*1e3:.1f} ms"
    else:
        return f"{duration:.1f} s"

@contextmanager
def stopwatch(label: str):
    start = timer()
    try:
        yield
    finally:
        print(f"{label}: {timer() - start:6.2f}s")

class DataLoaderProgress(object):
    def __init__(self, dataloader):
        self.dataloader = dataloader
        self.length = len(dataloader)

    def __iter__(self):
        return zip(range(self.length), self.dataloader)

    def __len__(self):
        return self.length


from sys import stdin

def check_all_0_or_1_or_m_1(table):
    all_0 = True
    all_1 = True
    all_m_1 = True
    for row in table:
        for cell in row:
            if cell != 0:
                all_0 = False
            if cell != 1:
                all_1 = False
            if cell != -1:
                all_m_1 = False
    if all_0:
        return 0
    if all_1:
        return 1
    if all_m_1:
        return -1
    return -2

def cut_paper(table, n):
    checker = check_all_0_or_1_or_m_1(table)
    if checker == 0:
        return (0, 1, 0)
    if checker == 1:
        return (0, 0, 1)
    if checker == -1:
        return (1, 0, 0)

    third = n // 3
    two_third = 2 * third

    lu = [row[:third] for row in table[:third]]
    mu = [row[third:two_third] for row in table[:third]]
    ru = [row[two_third:] for row in table[:third]]
    lc = [row[:third] for row in table[third:two_third]]
    mc = [row[third:two_third] for row in table[third:two_third]]
    rc = [row[two_third:] for row in table[third:two_third]]
    ld = [row[:third] for row in table[two_third:]]
    md = [row[third:two_third] for row in table[two_third:]]
    rd = [row[two_third:] for row in table[two_third:]]

    ans = [0, 0, 0]
    for part in [lu, mu, ru, lc, mc, rc, ld, md, rd]:
        part_ans = cut_paper(part, n // 3)
        ans[0] += part_ans[0]
        ans[1] += part_ans[1]
        ans[2] += part_ans[2]

    return ans

f_input = lambda : stdin.readline().rstrip()

N = int(f_input())
table = []
for _ in range(N):
    table.append(list(map(int, f_input().split())))
ans = cut_paper(table, N)
print(ans[0])
print(ans[1])
print(ans[2])

자료구조/트리/1780번 종이의 개수.py


from django.shortcuts import render,redirect
import requests
from .models import Article
# Create your views here.
def index(request):
    articles = Article.objects.all()
    context={
        'articles':articles
    }
    return render(request,'index.html',context)

def show(request,id):
    article = Article.objects.get(id=id)
    context={
        'article':article
    }
    return render(request,'show.html',context)

def new(request):
    return render(request,'new.html')

def create(request):
    title= request.GET['title']
    contents=request.GET['contents']
    creator=request.GET['creator']
    article=Article.objects.create(title=title,contents=contents,creator=creator)
    return redirect('/articles/')

def edit(request,id):
    article = Article.objects.get(id=id)
    context={
        'article':article
    }
    return render(request,'edit.html',context)

def update(request,id):
    article = Article.objects.get(id=id)
    title= request.GET['title']
    contents=request.GET['contents']
    article.title=title
    article.contents=contents
    article.save()
    return redirect('/articles/')

def destroy(request,id):
    article = Article.objects.get(id=id)
    article.delete()
    return redirect('/articles/')


import gzip
import json

from flask import Blueprint, Response, request, escape

from lib import db
from lib.gwpcc import consts
from lib.gwpcc.colonies.colony import Colony
from lib.gwpcc.consts import KEY_THING_LOCALE_THING_NAMES, USER_TYPES
from lib.gwpcc.things.thing import Thing

colony_module = Blueprint('v4_colony_module', __name__, url_prefix='/v4/colonies')

@colony_module.route('/create', methods=['PUT'])
def colony_create():
    incoming_data = request.json
    connection = db.get_redis_db_from_context()
    colony = new_colony_from_request(incoming_data, connection)
    print("Saving new colony to db")
    if not any(allowed_type == colony.OwnerType for allowed_type in USER_TYPES):
        print("Not allowed - not saving - sending error")
        return Response(consts.ERROR_INVALID, status=consts.HTTP_INVALID)

    colony.save_to_database(connection)

    colony.ping()
    print("Colony Saved")
    return Response(json.dumps({'Hash': colony.Hash}), status=201, mimetype='application/json')

def new_colony_from_request(incoming_data, connection):
    new_colony = {'BaseName': escape(incoming_data['BaseName']),
                  'FactionName': escape(incoming_data['FactionName']),
                  'Planet': escape(incoming_data['Planet']),
                  'OwnerType': escape(incoming_data['OwnerType']),
                  'OwnerID': escape(incoming_data['OwnerID']),
                  'LastGameTick': escape(incoming_data['LastGameTick'])}

    return Colony.from_dict(new_colony, connection=connection)

@colony_module.route('/<string:colony_hash>', methods=['PUT'])
def colony_update_data(colony_hash):
    connection = db.get_redis_db_from_context()
    colony = Colony.get_from_database_by_hash(colony_hash, connection)

    print("Saving colony data")
    incoming_data = request.json

    created = False

    if not colony or colony.OwnerID != incoming_data['OwnerID']:
        # If the Owner ID's don't match. Create a new colony.
        # And assign it a new ID. Might have happened if save sharing.
        colony = new_colony_from_request(incoming_data, connection)
        created = True
    else:
        colony.BaseName = escape(incoming_data['BaseName'])
        colony.FactionName = escape(incoming_data['FactionName'])
        colony.Planet = escape(incoming_data['Planet'])
        colony.LastGameTick = escape(incoming_data['LastGameTick'])
        if incoming_data['HasSpawned']:
            colony.Ban()

    pipe = connection.pipeline()

    if colony.IsBanned():
        return Response(consts.ERROR_BANNED, status=consts.HTTP_FORBIDDEN)

    # Make sure add the owners to the correct sets.
    if colony.OwnerType == 'Steam':
        key = consts.KEY_USER_INDEX_BY_STEAM_ID
    elif colony.OwnerType == 'Normal':
        key = consts.KEY_USER_INDEX_BY_NORMAL_ID
    else:
        return Response(consts.ERROR_INVALID, status=consts.HTTP_INVALID)

    pipe.sadd(key, colony.OwnerID)

    colony.save_to_database(pipe)

    pipe.execute()

    colony.ping()
    print("Sending colony hash")
    return Response(json.dumps({'Hash': colony.Hash}), status=201 if created else 200, mimetype='application/json')

@colony_module.route('/<string:colony_hash>', methods=['GET'])
def colony_get_data(colony_hash):
    print("Getting colony data")
    colony = Colony.get_from_database_by_hash(colony_hash, db.get_redis_db_from_context())

    if not colony:
        return Response(consts.ERROR_NOT_FOUND, status=consts.HTTP_NOT_FOUND)
    print("Sending colony data")
    return Response(json.dumps(colony.to_dict()), status=200, mimetype='application/json')

@colony_module.route('/<string:colony_hash>/thing_metadata', methods=['PUT'])
def colony_set_supported_things(colony_hash: str):
    print("Received Supported things list from colony")

    colony = Colony.get_from_database_by_hash(colony_hash, db.get_redis_db_from_context())
    if not colony:
        return Response(consts.ERROR_NOT_FOUND, status=consts.HTTP_NOT_FOUND)

    try:
        gz_post_data = request.files['things']

        # Decompress payload
        thing_file = gzip.GzipFile(fileobj=gz_post_data, mode='r')

        # Deserialize JSON back in to {'Locale': str, 'Things': List[Dict[str, str]]}
        payload = json.loads(thing_file.read().decode('UTF8'))

        # Set locale
        locale = payload['Locale'].lower()

        # This is a List[Dict[str, str]]
        supported_things_json = payload['Things']

        print("Supported things parsed")

    except json.JSONDecodeError:
        print("Error in things list found")
        return Response(consts.ERROR_INVALID, status=consts.HTTP_INVALID)

    # Need to construct things then add Localized name to index
    pipe = db.get_redis_db_from_context().pipeline()

    pipe.sadd(consts.KEY_THING_LOCALE_KNOWN_LANGUAGES, locale)

    for thing_json in supported_things_json:
        thing = Thing.from_dict(thing_json)
        pipe.zincrby(KEY_THING_LOCALE_THING_NAMES.format(locale, thing.Hash), 1, thing.LocalizedName)
    pipe.execute()

    # This is immediately saved.
    colony.SupportedThings = supported_things_json
    print("Supported things saved")
    return Response('OK', status=200, mimetype='application/json')

@colony_module.route('/<string:colony_hash>/mod_metadata', methods=['PUT'])
def colony_set_mods(colony_hash: str):
    print("Received List of Mods from colony")
    colony = Colony.get_from_database_by_hash(colony_hash, db.get_redis_db_from_context())
    if not colony:
        return Response(consts.ERROR_NOT_FOUND, status=consts.HTTP_NOT_FOUND)

    try:
        gz_post_data = request.files['mods']
        mod_file = gzip.GzipFile(fileobj=gz_post_data, mode='r')
        payload = json.loads(mod_file.read().decode('UTF8'))
        mod_list = payload['ModList']

    except json.JSONDecodeError:
        print("Error in mod list found")
        return Response(consts.ERROR_INVALID, status=consts.HTTP_INVALID)

    # This is immediately saved.
    colony.ModList = mod_list
    print("List of Mods Saved")
    return Response('OK', status=200, mimetype='application/json')


import os
import sys
from dataclasses import dataclass
from itertools import product

import kernel_explorer as ke
import numpy as np
import pytest
from utils import get_gemm_basic_sizes, get_gemm_bert_sizes, get_gemm_bound, matmul, transab_to_suffix

max_batch_size = int(os.environ.get("KERNEL_EXPLORER_BATCHED_GEMM_MAX_BATCH_SIZE", 64))

def dtype_to_suffix(dtype):
    return {
        "float32": "float",
        "float16": "half",
    }[dtype]

def _test_strided_batched_gemm(
    func, dtype: str, transa: bool, transb: bool, m: int, n: int, k: int, batch: int, alpha=1.0, beta=0.0
):
    assert dtype in ["float32", "float16"]

    a_shape = (k, m) if transa else (m, k)
    b_shape = (n, k) if transb else (k, n)

    np.random.seed(0)
    a = (np.random.rand(batch, *a_shape) + 0.5).astype(dtype).astype("float64")
    b = (np.random.rand(batch, *b_shape) + 0.5).astype(dtype).astype("float64")
    tmp_a = a.swapaxes(1, 2) if transa else a
    tmp_b = b.swapaxes(1, 2) if transb else b
    intermediate_c = matmul(tmp_a, tmp_b)
    if alpha == 1.0 and beta == 0.0:  # fast path
        ref_c = intermediate_c
    else:
        ref_c = alpha * intermediate_c + beta * np.ones_like(intermediate_c)

    bounds = [get_gemm_bound(dtype, a[i], b[i], ref_c[i], transa, transb, a_b_positive=True) for i in range(batch)]

    a = a.astype(dtype)
    b = b.astype(dtype)

    my_c = np.ones((batch, m, n), dtype=dtype)
    dev_a = ke.DeviceArray(a)
    dev_b = ke.DeviceArray(b)
    dev_c = ke.DeviceArray(my_c)

    opa = ke.blas_op.T if transa else ke.blas_op.N
    opb = ke.blas_op.T if transb else ke.blas_op.N
    lda = a_shape[1]
    ldb = b_shape[1]
    ldc = n
    stride_a = m * k
    stride_b = k * n
    stride_c = m * n
    my_gemm = func(
        opa, opb, m, n, k, alpha, dev_a, lda, stride_a, dev_b, ldb, stride_b, beta, dev_c, ldc, stride_c, batch
    )

    failures = {}
    print(
        f"dtype={dtype} {transab_to_suffix((transa, transb))} m={m:<5} n={n:<5} k={k:<5} batch={batch:<3} max bound: {max(bounds)}"
    )

    for impl in my_gemm.ListOps():
        if not my_gemm.SelectOp(impl):
            continue

        # Restore C Array
        my_c.fill(1.0)
        dev_c.UpdateDeviceArray()
        my_gemm.Run()
        dev_c.UpdateHostNumpyArray()

        for i in range(batch):
            try:
                np.testing.assert_allclose(my_c[i], ref_c[i], rtol=bounds[i])
            except Exception as err:
                header = "*" * 30 + impl + "*" * 30
                print(header, bounds[i])
                print(err)
                print("*" * len(header))
                failures[impl] = str(err)

    if failures:
        raise Exception(failures)

dtypes = ["float32", "float16"]
all_transabs = list(product([True, False], repeat=2))

@pytest.mark.parametrize("batch", [1, max_batch_size])
@pytest.mark.parametrize("m, n, k", get_gemm_basic_sizes(full=False) + get_gemm_bert_sizes(full=False))
@pytest.mark.parametrize("transa, transb", all_transabs)
@pytest.mark.parametrize("dtype", dtypes)
def test_rocblas_gemm_all_cases(dtype, transa, transb, m, n, k, batch):
    wrapper_name = "RocBlasStridedBatchedGemm_" + dtype_to_suffix(dtype)
    _test_strided_batched_gemm(getattr(ke, wrapper_name), dtype, transa, transb, m, n, k, batch)

@pytest.mark.skipif(not ke.is_composable_kernel_available(), reason="ck is not enabled")
@pytest.mark.parametrize("batch", [1, max_batch_size])
@pytest.mark.parametrize("m, n, k", get_gemm_basic_sizes(full=False) + get_gemm_bert_sizes(full=False))
@pytest.mark.parametrize("transa, transb", all_transabs)
@pytest.mark.parametrize("dtype", dtypes)
def test_ck_gemm_all_cases(dtype, transa, transb, m, n, k, batch):
    wrapper_name = f"CKStridedBatchedGemm_{dtype_to_suffix(dtype)}_{transab_to_suffix((transa, transb))}"
    _test_strided_batched_gemm(getattr(ke, wrapper_name), dtype, transa, transb, m, n, k, batch)

# Tunable is basically wrapped around of rocblas and ck gemm, so no need for full tests
@pytest.mark.parametrize("batch", [1, max_batch_size])
@pytest.mark.parametrize("m, n, k", get_gemm_bert_sizes(full=False))
@pytest.mark.parametrize("transa, transb", all_transabs)
@pytest.mark.parametrize("dtype", dtypes)
def test_gemm_tunable_bert_cases(dtype, transa, transb, m, n, k, batch):
    wrapper_name = f"StridedBatchedGemmTunable_{dtype_to_suffix(dtype)}_{transab_to_suffix((transa, transb))}"
    _test_strided_batched_gemm(getattr(ke, wrapper_name), dtype, transa, transb, m, n, k, batch)

@pytest.mark.parametrize("alpha, beta", [(0.5, 0.5)])
@pytest.mark.parametrize("transa, transb", all_transabs)
@pytest.mark.parametrize("dtype", dtypes)
def test_rocblas_gemm_alpha_beta(dtype, transa, transb, alpha, beta):
    wrapper_name = "RocBlasStridedBatchedGemm_" + dtype_to_suffix(dtype)
    _test_strided_batched_gemm(
        getattr(ke, wrapper_name), dtype, transa, transb, 128, 256, 768, 16, alpha=alpha, beta=beta
    )

@pytest.mark.skipif(not ke.is_composable_kernel_available(), reason="ck is not enabled")
@pytest.mark.parametrize("alpha, beta", [(0.5, 0.5)])
@pytest.mark.parametrize("transa, transb", all_transabs)
@pytest.mark.parametrize("dtype", dtypes)
def test_ck_gemm_alpha_beta(dtype, transa, transb, alpha, beta):
    wrapper_name = f"CKStridedBatchedGemm_{dtype_to_suffix(dtype)}_{transab_to_suffix((transa, transb))}"
    _test_strided_batched_gemm(
        getattr(ke, wrapper_name), dtype, transa, transb, 256, 128, 384, 8, alpha=alpha, beta=beta
    )

@pytest.mark.parametrize("alpha, beta", [(0.5, 0.5)])
@pytest.mark.parametrize("transa, transb", all_transabs)
@pytest.mark.parametrize("dtype", dtypes)
def test_gemm_tunable_alpha_beta(dtype, transa, transb, alpha, beta):
    wrapper_name = f"StridedBatchedGemmTunable_{dtype_to_suffix(dtype)}_{transab_to_suffix((transa, transb))}"
    _test_strided_batched_gemm(
        getattr(ke, wrapper_name), dtype, transa, transb, 128, 512, 384, 4, alpha=alpha, beta=beta
    )

@dataclass
class StridedBatchedGemmMetric(ke.ComputeMetric):
    transa: bool
    transb: bool
    m: int
    n: int
    k: int
    batch: int

    def report(self):
        common = (
            f"{self.dtype} {transab_to_suffix((self.transa, self.transb))} "
            f"m={self.m:<4} n={self.n:<4} k={self.k:<4} batch={self.batch:<3} {self.name}"
        )
        if self.duration <= 0:
            return "not supported          " + common

        return f"{self.duration:>6.2f} us {self.tflops:>5.2f} tflops " + common

def profile_gemm_func(f, dtype: str, transa: bool, transb: bool, m: int, n: int, k: int, batch: int):
    a_shape = (k, m) if transa else (m, k)
    b_shape = (n, k) if transb else (k, n)

    np.random.seed(0)
    a = (np.random.rand(batch, *a_shape) * 2 - 1).astype(dtype)
    b = (np.random.rand(batch, *b_shape) * 2 - 1).astype(dtype)
    my_c = np.zeros((batch, m, n), dtype=dtype)

    dev_a = ke.DeviceArray(a)
    dev_b = ke.DeviceArray(b)
    dev_c = ke.DeviceArray(my_c)

    opa = ke.blas_op.T if transa else ke.blas_op.N
    opb = ke.blas_op.T if transb else ke.blas_op.N
    lda = a_shape[1]
    ldb = b_shape[1]
    ldc = n
    stride_a = m * k
    stride_b = k * n
    stride_c = m * n
    alpha = 1.0
    beta = 0.0
    my_gemm = f(opa, opb, m, n, k, alpha, dev_a, lda, stride_a, dev_b, ldb, stride_b, beta, dev_c, ldc, stride_c, batch)
    for impl in my_gemm.ListOps():
        duration_ms = -1
        if my_gemm.SelectOp(impl):
            duration_ms = my_gemm.Profile()
        FLOPs = batch * m * k * n * 2  # noqa: N806
        ke.report(StridedBatchedGemmMetric(impl, dtype, duration_ms, FLOPs, transa, transb, m, n, k, batch))

def profile_with_args(dtype, transa, transb, m, n, k, batch, sort):
    dtype_suffix = "_" + dtype_to_suffix(dtype)
    transab_suffix = "_" + transab_to_suffix((transa, transb))
    fn_rocblas = getattr(ke, "RocBlasStridedBatchedGemm" + dtype_suffix)
    fn_ck = getattr(ke, "CKStridedBatchedGemm" + dtype_suffix + transab_suffix)
    fn_tunable = getattr(ke, "StridedBatchedGemmTunable" + dtype_suffix + transab_suffix)
    if ke.is_hipblaslt_available():
        fn_hipblaslt = getattr(ke, "StridedBatchedGemmHipBlasLt" + dtype_suffix + transab_suffix)
    with ke.benchmark(sort):
        profile_gemm_func(fn_rocblas, dtype, transa, transb, m, n, k, batch)
        profile_gemm_func(fn_ck, dtype, transa, transb, m, n, k, batch)
        profile_gemm_func(fn_tunable, dtype, transa, transb, m, n, k, batch)
        if ke.is_hipblaslt_available():
            profile_gemm_func(fn_hipblaslt, dtype, transa, transb, m, n, k, batch)
    print()

def profile():
    for dtype in dtypes:
        for m, n, k in get_gemm_bert_sizes(full=False):
            for batch in [1, 32, 64]:
                profile_with_args(dtype, False, False, m, n, k, batch, True)

if __name__ == "__main__":
    import argparse

    parser = argparse.ArgumentParser()
    group = parser.add_argument_group("profile with args")
    group.add_argument("dtype", choices=dtypes)
    group.add_argument("transa", choices="NT")
    group.add_argument("transb", choices="NT")
    group.add_argument("m", type=int)
    group.add_argument("n", type=int)
    group.add_argument("k", type=int)
    group.add_argument("batch", type=int)
    group.add_argument("--sort", action="store_true")

    if len(sys.argv) == 1:
        profile()
    else:
        args = parser.parse_args()
        profile_with_args(
            args.dtype, args.transa == "T", args.transb == "T", args.m, args.n, args.k, args.batch, args.sort
        )


import dlib
import pymongo
import numpy as np
import cv2

# Load the shape predictor model
predictor = dlib.shape_predictor("shape_predictor_68_face_landmarks.dat")

# Connect to the MongoDB database
client = pymongo.MongoClient("mongodb://localhost:27017/")
db = client["miranda"]
face_features = db["face_features"]

# Load the original image
img = cv2.imread("ante_side.jpeg")

# Get the landmarks for the face
x, y, w, h = [int(i) for i in [338.0, 204.0, 622.0, 585.0]]
landmarks = predictor(img, dlib.rectangle(x, y, x + w, y + h))

# Convert the landmarks to a numpy array
landmarks_np = np.zeros((landmarks.num_parts, 2), dtype=np.int32)
for i in range(landmarks.num_parts):
    landmarks_np[i, 0] = landmarks.part(i).x
    landmarks_np[i, 1] = landmarks.part(i).y

# Query the database for existing landmarks
existing_landmarks = face_features.find_one({"name": "some guy"})

# Convert the existing landmarks to a numpy array
existing_landmarks = np.array(existing_landmarks["landmarks"], dtype=np.int32)

for i in range(landmarks.num_parts):
    cv2.circle(img, (landmarks.part(i).x, landmarks.part(i).y), 2, (0, 0, 255), -1)
    cv2.circle(img, (existing_landmarks[i, 0], existing_landmarks[i, 1]), 2, (0, 255, 0), -1)
    # Bounding box
    cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)

    cv2.imshow("Transformed image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# Check if the new landmarks are different enough from the existing landmarks
if not np.allclose(landmarks_np, existing_landmarks, atol=5):
    # Transform the landmarks using the existing landmarks
    M, _ = cv2.estimateAffine2D(landmarks_np, existing_landmarks)
    # Transform the landmarks using the existing landmarks

    # Apply the affine transformation to the full image
    img[y:y+h, x:x+w] = cv2.warpAffine(img[y:y+h, x:x+w], M, (w, h))

    # Update the database with the transformed landmarks
    # landmarks_collection.update_one({"landmarks": {"$exists": True}}, {"$set": {"landmarks": landmarks_np.tolist()}})

    # Show the transformed image
    # Draw the original landmarks and the transformed landmarks
    for i in range(landmarks.num_parts):
        cv2.circle(img, (landmarks.part(i).x, landmarks.part(i).y), 2, (0, 0, 255), -1)
        cv2.circle(img, (existing_landmarks[i, 0], existing_landmarks[i, 1]), 2, (0, 255, 0), -1)

    cv2.imshow("Transformed image", img)
    cv2.waitKey(0)
    cv2.destroyAllWindows()


import csv
import math
import random
import operator

'''
K-NN utilizando o Iris dataset, apenas um teste para avaliar conhecimentos nesse algoritmo de classificação
'''

def euclidean_distance(vector1, vector2):
    if len(vector1) != len(vector2):
        return -1
    diff = 0
    for index in range(len(vector1)):
        diff += math.pow(vector2[index] - vector1[index], 2)

    distance = math.sqrt(diff)
    return distance

def load_dataset(filename, split):
    training_set = []
    test_set = []

    with open(filename, 'r') as csv_ds_file:
        lines = csv.reader(csv_ds_file)
        dataset = list(lines)
        for x in range(len(dataset) - 1):
            for y in range(4):
                dataset[x][y] = float(dataset[x][y])
            if random.random() < split:
                training_set.append(dataset[x])
            else:
                test_set.append(dataset[x])

    return training_set, test_set

def get_similarity(element_1, element_2):
    return euclidean_distance(element_1[:-1], element_2[:-1])

def get_neighbors(training_set, test_element, k):
    distances = []
    for x in range(len(training_set)):
        dist = get_similarity(test_element, training_set[x])
        distances.append((training_set[x], dist))
    distances.sort(key=operator.itemgetter(1))
    neighbors = []
    for x in range(k):
        neighbors.append(distances[x][0])
    return neighbors

def get_response(neighbors):
    class_votes = {}
    for x in range(len(neighbors)):
        response = neighbors[x][-1]
        if response in class_votes:
            class_votes[response] += 1
        else:
            class_votes[response] = 1
    sorted_votes = sorted(class_votes.items(), key=operator.itemgetter(1), reverse=True)
    return sorted_votes[0][0]

def get_accuracy(test_set, predictions):
    correct = 0
    for x in range(len(test_set)):
        if test_set[x][-1] == predictions[x]:
            correct += 1
    return (correct/float(len(test_set))) * 100.0

def main():
    # prepare data
    training, test = load_dataset('iris.csv', 0.67)
    print('Train set: ' + repr(len(training)))
    print('Test set: ' + repr(len(test)))
    # generate predictions
    predictions = []
    k = 11
    for x in range(len(test)):
        neighbors = get_neighbors(training, test[x], k)
        result = get_response(neighbors)
        predictions.append(result)
        print('> predicted=' + repr(result) + ', actual=' + repr(test[x][-1]))
    accuracy = get_accuracy(test, predictions)

    print('Accuracy: ' + repr(accuracy) + '%')

main()


import tensorflow as tf

from nn.modules import *
from nn.transformer.specific_modules import *

def encoder(inputs, hparams, is_training=False, reuse=False):
    with tf.variable_scope('encoder', reuse=reuse):
        ## Embedding
        enc = embedding(inputs, vocab_size=hparams.graphemes_num,
                        num_units=hparams.hidden_units,
                        scale=True,
                        scope="enc_embed")
        if hparams.positional_encoding:
            enc += positional_encoding(inputs,
                                       vocab_size=hparams.max_grapheme_seq_len,
                                       num_units=hparams.hidden_units,
                                       scale=False,
                                       scope="enc_pe")

        enc = tf.layers.dropout(enc, rate=hparams.dropout_rate,
                                training=tf.convert_to_tensor(is_training))

        for i in range(hparams.encoder_blocks):
            with tf.variable_scope("num_blocks_{}".format(i)):
                ### Multihead Attention
                enc = multihead_attention(queries=enc, keys=enc,
                                          num_units=hparams.hidden_units,
                                          num_heads=hparams.heads_num,
                                          dropout_rate=hparams.dropout_rate,
                                          is_training=is_training,
                                          causality=False, reuse=reuse)

                ### Feed Forward
                enc = feedforward(enc, num_units=[4 * hparams.hidden_units,
                                  hparams.hidden_units], reuse=reuse)
        return enc

def decoder(enc, decoder_inputs, hparams, is_training=False, reuse=False,
            embed_input=True):
    with tf.variable_scope('decoder', reuse=reuse):
        if embed_input:
            ## Embedding
            dec = embedding(decoder_inputs,
                            vocab_size=hparams.phonemes_num,
                            num_units=hparams.hidden_units,
                            scale=True,
                            scope="dec_embed")
        else:
            dec = decoder_inputs

        if hparams.positional_encoding:
            dec += positional_encoding(decoder_inputs,
                                       vocab_size=hparams.max_phoneme_seq_len,
                                       num_units=hparams.hidden_units,
                                       scale=False,
                                       scope="dec_pe")

        ## Dropout
        dec = tf.layers.dropout(dec, rate=hparams.dropout_rate,
                                training=tf.convert_to_tensor(is_training))

        for i in range(hparams.decoder_blocks):
            with tf.variable_scope("num_blocks_{}".format(i)):
                ## Multihead Attention ( self-attention)
                dec = multihead_attention(queries=dec,
                                          keys=dec,
                                          num_units=hparams.hidden_units,
                                          num_heads=hparams.heads_num,
                                          dropout_rate=hparams.dropout_rate,
                                          is_training=is_training,
                                          causality=True,
                                          scope="self_attention", reuse=reuse)

                ## Multihead Attention ( vanilla attention)
                dec = multihead_attention(queries=dec,
                                          keys=enc,
                                          num_units=hparams.hidden_units,
                                          num_heads=hparams.heads_num,
                                          dropout_rate=hparams.dropout_rate,
                                          is_training=is_training,
                                          causality=False,
                                          scope="vanilla_attention", reuse=reuse)

                ## Feed Forward
                dec = feedforward(dec, num_units=[4 * hparams.hidden_units,
                                                  hparams.hidden_units], reuse=reuse)

        # Project
        dec = tf.layers.dense(dec, hparams.phonemes_num)
        return dec

class G2PModel:
    def __init__(self, hparams, is_training=False, with_target=True, reuse=False):
        self.with_target = with_target
        self.is_training = is_training
        self.hparams = hparams
        self.inputs = tf.placeholder(tf.int32, (None, None), name='graphemes_ph')
        self.input_lengths = tf.placeholder(tf.int32, [None], name='grapeheme_seq_len_ph')
        if with_target:
            self.targets = tf.placeholder(tf.int32, (None, None), name='phonemes_ph')
            self.target_lengths = tf.placeholder(tf.int32, [None], name='phoneme_seq_len_ph')

        with tf.variable_scope('g2p', reuse=reuse):
            self.enc = encoder(self.inputs, self.hparams, is_training=is_training, reuse=reuse)

            if is_training:
                decoder_inputs = self.targets[:, :-1]
                self.logits = decoder(self.enc, decoder_inputs, self.hparams,
                                      is_training=is_training, reuse=reuse)
                self.decoded_best = tf.to_int32(tf.arg_max(self.logits, dimension=-1))
            else:
                batch_size = tf.shape(self.inputs)[0]
                arr = np.zeros((1, 1, self.hparams.phonemes_num))
                arr[0, 0, self.hparams.phonemes_num - 2] = 1
                arr = tf.convert_to_tensor(arr, dtype=tf.float32)
                decoder_inputs0 = tf.tile(arr, [batch_size, 1, 1])
                i_0 = tf.constant(0)

                condition = lambda i, inpts: i <  tf.reduce_max(self.input_lengths) + 3

                def body(i, inpts):
                    otpts = decoder(self.enc, tf.to_int32(tf.arg_max(inpts, dimension=-1)),
                                    self.hparams, is_training=False, reuse=reuse)
                    inpts = tf.concat([inpts, otpts[:, -1:, :]], 1)
                    return i+1, inpts

                _, dec = tf.while_loop(condition, body, loop_vars=[i_0, decoder_inputs0],
                        shape_invariants=[i_0.get_shape(), tf.TensorShape([None, None, self.hparams.phonemes_num])])
                self.decoded_best = tf.identity(tf.to_int32(tf.arg_max(dec[:, 1:], dimension=-1)),
                                                name='predicted_1best')
                self.probs = tf.nn.softmax(dec, name='probs')

    def add_loss(self):
        decoder_targets = self.targets[:, 1:]
        if self.hparams.label_smoothing:
            decoder_targets_sm = label_smoothing(tf.one_hot(decoder_targets,
                                                            self.hparams.phonemes_num))
            loss = tf.nn.softmax_cross_entropy_with_logits(logits=self.logits,
                                                           labels=decoder_targets_sm)
        else:
            loss = tf.nn.sparse_softmax_cross_entropy_with_logits(
                    labels=decoder_targets, logits=self.logits)
        max_target_len = tf.shape(decoder_targets)[1]
        mask = tf.sequence_mask(self.target_lengths, max_target_len,
                                                dtype=tf.float32)
        self.loss = tf.reduce_mean(loss * mask)

    def add_train_and_stats(self):
        with tf.variable_scope('training'):
            self.global_step = tf.Variable(0, name='global_step',
                                           trainable=False)
            lr = tf.train.exponential_decay(self.hparams.lr,
                                            self.global_step,
                                            self.hparams.lr_hl, 0.5)
            opt = tf.train.AdamOptimizer(learning_rate=lr)
            assert(hasattr(self, 'loss'))
            gradients, variables = zip(*opt.compute_gradients(self.loss))
            gradients, _ = tf.clip_by_global_norm(gradients,
                                                  self.hparams.grad_clip_ratio)
            with tf.control_dependencies(
                    tf.get_collection(tf.GraphKeys.UPDATE_OPS)):
                self.train_op = opt.apply_gradients(zip(gradients, variables),
                                                    global_step=self.global_step)

        with tf.variable_scope('stats'):
            tf.summary.histogram('phoneme_probs', self.logits)
            tf.summary.scalar('loss', self.loss)
            tf.summary.scalar('learning_rate', lr)
            gradient_norms = [tf.norm(grad) for grad in gradients]
            tf.summary.histogram('gradient_norm', gradient_norms)
            tf.summary.scalar('max_gradient_norm',
                              tf.reduce_max(gradient_norms))
            self.stats_op = tf.summary.merge_all()

    def create_feed_dict(self, batch):
        fd = {self.inputs: batch[0], self.input_lengths: batch[1]}
        if self.with_target:
            fd[self.targets] = batch[2]
            fd[self.target_lengths] = batch[3]
        return fd


import argparse
import configparser
import json
import re
from pathlib import Path

import pygit2

def format_component(submod):
    return {"component": {"type": "git", "git": {"commitHash": str(submod.head_id), "repositoryUrl": submod.url}}}

def lookup_submodule(repo, submodule_path):
    submodule = repo.lookup_submodule(submodule_path)
    try:
        # Some submodules have names which don't correspond to the actual path in the repo
        # (e.g. 'git submodule init' was called with the --name option, or the submodule
        # was moved and the old name was kept). listall_submodules() returns submodule paths,
        # but pygit up to 1.0.1 requires the submodule name (not the path) in lookup_submodule
        # to be able to access the URL and other properties.
        # This seems to be a bug in pygit2, since its documentation says the submodules can
        # be opened by path.
        # If accessing the URL throws a RuntimeError, we get the submodule name manually from
        # .gitmodules.
        _ = submodule.url
        return submodule
    except RuntimeError:
        pass

    config = configparser.ConfigParser()
    config.read(Path(repo.workdir, ".gitmodules"))
    for section in config.sections():
        if config[section]["path"] == submodule_path:
            name = re.fullmatch('submodule "(.*)"', section).group(1)
            submodule = repo.lookup_submodule(name)
            return submodule
    raise NotImplementedError()  # should not be reached

def process_component(repo):
    return [lookup_submodule(repo, submod) for submod in repo.listall_submodules()]

def recursive_process(base_repo):
    processed_subs = []
    repos_to_process = [base_repo]
    while repos_to_process:
        repo = repos_to_process.pop()
        submodules = process_component(repo)
        processed_subs.extend(submodules)
        repos_to_process.extend([mod.open() for mod in submodules])
    return {"Registrations": [format_component(component) for component in processed_subs]}

def main(repo_path, output_file):
    repo = pygit2.Repository(repo_path)
    registrations = recursive_process(repo)
    with open(output_file, "w") as f:
        json.dump(registrations, f, indent=4, sort_keys=True)

if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("base_repository", help="path to base repository to get registrations for.")
    parser.add_argument("-o", "--output", help="output file name.", default="cgmanifest.json")
    args = parser.parse_args()
    main(args.base_repository, args.output)


#!/usr/bin/env python3
import numpy as np

"""This module contains MISMIP constants and parameters, as well as functions
computing theoretical steady state profiles corresponding to various MISMIP
experiments.

It should not be cluttered with plotting or NetCDF output code.
"""

def secpera():
    "Number of seconds per year."
    return 3.15569259747e7

def L():
    "The length of the MISMIP domain."
    return 1800e3

def N(mode):
    "Number of grid spaces corresponding to a MISMIP 'mode.'"
    if mode == 1:
        return 150

    if mode == 2:
        return 1500

    raise ValueError("invalid mode (%s)" % mode)

def A(experiment, step):
    """Ice softness parameter for given experiment and step."""
    A1 = np.array([4.6416e-24,  2.1544e-24,  1.0e-24,
                   4.6416e-25,  2.1544e-25,  1.0e-25,
                   4.6416e-26,  2.1544e-26,  1.0e-26])
    # Values of A to be used in experiments 1 and 2.

    A3a = np.array([3.0e-25, 2.5e-25, 2.0e-25,
                    1.5e-25, 1.0e-25, 5.0e-26,
                    2.5e-26, 5.0e-26, 1.0e-25,
                    1.5e-25, 2.0e-25, 2.5e-25,
                    3.0e-25])
    # Values of A to be used in experiment 3a.

    A3b = np.array([1.6e-24, 1.4e-24, 1.2e-24,
                    1.0e-24, 8.0e-25, 6.0e-25,
                    4.0e-25, 2.0e-25, 4.0e-25,
                    6.0e-25, 8.0e-25, 1.0e-24,
                    1.2e-24, 1.4e-24, 1.6e-24])
    # Values of A to be used in experiment 3b.

    try:
        if experiment in ("1a", "1b", "2a", "2b"):
            return A1[step - 1]

        if experiment == "3a":
            return A3a[step - 1]

        if experiment == "3b":
            return A3b[step - 1]
    except:
        raise ValueError("invalid step (%s) for experiment %s" % (step, experiment))

    raise ValueError("invalid experiment (%s)" % experiment)

def run_length(experiment, step):
    """Returns the time interval for an experiment 3 step."""
    T3a = np.array([3.0e4, 1.5e4, 1.5e4,
                    1.5e4, 1.5e4, 3.0e4,
                    3.0e4, 1.5e4, 1.5e4,
                    3.0e4, 3.0e4, 3.0e4,
                    1.5e4])
    # Time intervals to be used in experiment 3a.

    T3b = np.array([3.0e4, 1.5e4, 1.5e4,
                    1.5e4, 1.5e4, 1.5e4,
                    1.5e4, 3.0e4, 1.5e4,
                    1.5e4, 1.5e4, 1.5e4,
                    1.5e4, 3.0e4, 1.5e4])
    # Time intervals to be used in experiment 3b.

    try:
        if experiment == "3a":
            return T3a[step - 1]

        if experiment == "3b":
            return T3b[step - 1]
    except:
        raise ValueError("invalid step (%s) for experiment %s" % (step, experiment))

    return 3e4

def rho_i():
    "Ice density"
    return 900.0

def rho_w():
    "Water density"
    return 1000.0

def g():
    """Acceleration due to gravity. (Table 2 on page 19 of mismip_4.pdf
    uses this value, i.e. g = 9.8 m s-2.)"""
    return 9.8

def n():
    "Glen exponent"
    return 3.0

def a():
    "Accumulation rate (m/s)"
    return 0.3 / secpera()

def m(experiment):
    "Sliding law exponent"
    if experiment in ("1a", "2a", "3a"):
        return 1 / 3.0

    if experiment in ("1b", "2b", "3b"):
        return 1.0

    raise ValueError("invalid experiment (%s)" % experiment)

def C(experiment):
    "Sliding law coefficient"
    if experiment in ("1a", "2a", "3a"):
        return 7.624e6

    if experiment in ("1b", "2b", "3b"):
        return 7.2082e10

    raise ValueError("invalid experiment (%s)" % experiment)

def b(experiment, x):
    "Bed depth below sea level. (-b(x) = topg(x))"

    if experiment in ("1a", "1b", "2a", "2b"):
        return -720. + 778.5 * (x / 7.5e5)

    if experiment in ("3a", "3b"):
        xx = x / 7.5e5
        return -(729. - 2184.8 * xx ** 2. + 1031.72 * xx ** 4. - 151.72 * xx ** 6.)

    raise ValueError("invalid experiment (%s)" % experiment)

def b_slope(experiment, x):
    """The x-derivative of b(experiment, x)."""

    if experiment in ("1a", "1b", "2a", "2b"):
        return 778.5 / 7.5e5

    if experiment in ("3a", "3b"):
        xx = x / 7.5e5
        return -(- 2184.8 * (2. / 7.5e5) * xx
                 + 1031.72 * (4. / 7.5e5) * xx ** 3.
                 - 151.72 * (6. / 7.5e5) * xx ** 5.)

    raise ValueError("invalid experiment (%s)" % experiment)

def cold_function(experiment, step, x, theta=0.0):
    """Evaluates function whose zeros define x_g in 'cold' steady marine sheet problem."""
    r = rho_i() / rho_w()
    h_f = r ** (-1.) * b(experiment, x)
    b_x = b_slope(experiment, x)
    s = a() * x
    rho_g = rho_i() * g()
    return (theta * a()
            + C(experiment) * s ** (m(experiment) + 1.0) / (rho_g * h_f ** (m(experiment) + 2.))
            - theta * s * b_x / h_f
            - A(experiment, step) * (rho_g * (1.0 - r) / 4.0) ** n() * h_f ** (n() + 1.0))

def x_g(experiment, step, theta=0.0):
    """Computes the theoretical grounding line location using Newton's method."""

    # set the initial guess
    if experiment in ("3a", "3b"):
        x = 800.0e3
    else:
        x = 1270.0e3

    delta_x = 10.  # Finite difference step size (metres) for gradient calculation
    tolf = 1.e-4  # Tolerance for finding zeros
    eps = np.finfo(float).eps
    normf = tolf + eps
    toldelta = 1.e1                     # Newton step size tolerance
    dx = toldelta + 1.0

    # this is just a shortcut
    def F(x):
        return cold_function(experiment, step, x, theta)

    while (normf > tolf) or (abs(dx) > toldelta):
        f = F(x)
        normf = abs(f)
        grad = (F(x + delta_x) - f) / delta_x
        dx = -f / grad
        x = x + dx

    return x

def thickness(experiment, step, x, theta=0.0):
    """Compute ice thickness for x > 0.
    """
    # compute the grounding line position
    xg = x_g(experiment, step, theta)

    def surface(h, x):
        b_x = b_slope(experiment, x)
        rho_g = rho_i() * g()
        s = a() * np.abs(x)
        return b_x - (C(experiment) / rho_g) * s ** m(experiment) / h ** (m(experiment) + 1)

    # extract the grounded part of the grid
    x_grounded = x[x < xg]

    # We will integrate from the grounding line inland. odeint requires that
    # the first point in x_grid be the one corresponding to the initial
    # condition; append it and reverse the order.
    x_grid = np.append(xg, x_grounded[::-1])

    # use thickness at the grounding line as the initial condition
    h_f = b(experiment, xg) * rho_w() / rho_i()

    import scipy.integrate
    thk_grounded = scipy.integrate.odeint(surface, [h_f], x_grid, atol=1.e-9, rtol=1.e-9)

    # now 'result' contains thickness in reverse order, including the grounding
    # line point (which is not on the grid); discard it and reverse the order.
    thk_grounded = np.squeeze(thk_grounded)[:0:-1]

    # extract the floating part of the grid
    x_floating = x[x >= xg]

    # compute the flux through the grounding line
    q_0 = a() * xg

    # Calculate ice thickness for shelf from van der Veen (1986)
    r = rho_i() / rho_w()
    rho_g = rho_i() * g()
    numer = h_f * (q_0 + a() * (x_floating - xg))
    base = q_0 ** (n() + 1) + h_f ** (n() + 1) * ((1 - r) * rho_g / 4) ** n() * A(experiment, step) \
        * ((q_0 + a() * (x_floating - xg)) ** (n() + 1) - q_0 ** (n() + 1)) / a()
    thk_floating = numer / (base ** (1.0 / (n() + 1)))

    return np.r_[thk_grounded, thk_floating]

def plot_profile(experiment, step, out_file):
    from pylab import figure, subplot, hold, plot, xlabel, ylabel, text, title, axis, vlines, savefig

    if out_file is None:
        out_file = "MISMIP_%s_A%d.pdf" % (experiment, step)

    xg = x_g(experiment, step)

    x = np.linspace(0, L(), N(2) + 1)
    thk = thickness(experiment, step, x)
    x_grounded, thk_grounded = x[x < xg],  thk[x < xg]
    x_floating, thk_floating = x[x >= xg], thk[x >= xg]

    figure(1)
    ax = subplot(111)
    hold(True)
    plot(x / 1e3, np.zeros_like(x), ls='dotted', color='red')
    plot(x / 1e3, -b(experiment, x), color='black')
    plot(x / 1e3, np.r_[thk_grounded - b(experiment, x_grounded),
                        thk_floating * (1 - rho_i() / rho_w())],
         color='blue')
    plot(x_floating / 1e3, -thk_floating * (rho_i() / rho_w()), color='blue')
    _, _, ymin, ymax = axis(xmin=0, xmax=x.max() / 1e3)
    vlines(xg / 1e3, ymin, ymax, linestyles='dashed', color='black')

    xlabel('distance from the summit, km')
    ylabel('elevation, m')
    text(0.6, 0.9, "$x_g$ (theory) = %4.0f km" % (xg / 1e3),
         color='black', transform=ax.transAxes)
    title("MISMIP experiment %s, step %d" % (experiment, step))
    savefig(out_file)

if __name__ == "__main__":
    from optparse import OptionParser

    parser = OptionParser()

    parser.usage = "%prog [options]"
    parser.description = "Plots the theoretical geometry profile corresponding to MISMIP experiment and step."
    parser.add_option("-e", "--experiment", dest="experiment", type="string",
                      default='1a',
                      help="MISMIP experiments (one of '1a', '1b', '2a', '2b', '3a', '3b')")
    parser.add_option("-s", "--step", dest="step", type="int", default=1,
                      help="MISMIP step number")
    parser.add_option("-o", dest="out_file", help="output file name")

    (opts, args) = parser.parse_args()

    plot_profile(opts.experiment, opts.step, opts.out_file)


# Import essential module for this project
import googletrans
import speech_recognition as sr
import gtts
import playsound
import re
import random

# Google Supported voices and languages link is below:
# https://cloud.google.com/text-to-speech/docs/voices

input_lang = 'bn-IN'
destination_lang = 'bn'

# Create instances
try:
    recognizer = sr.Recognizer()
    translator = googletrans.Translator()
except Exception as e:
    print("Exception:", e)

# Take command from speech
def take_command():
    with sr.Microphone() as source:
        print("Listening, Speak now...")
        voice = recognizer.listen(source)
        text = ''
        try:
            text = recognizer.recognize_google(voice, language=input_lang)
            # print(text)
        except Exception as ex:
            print('Exception:', ex)

    return text

def translate(text):
    translated = translator.translate(text, dest=destination_lang)
    converted_audio = gtts.gTTS(translated.text, lang=destination_lang)
    converted_audio.save('speak.mp3')
    playsound.playsound('speak.mp3')

# Asking question
bot_template = "রোবট: {0}"
user_template = "আপনি: {0}"

# Question and Answer
responses = {
    'question': ["আমি জানি না :(",
                 "তুমি আমাকে বলো!"],
    'statement': ['আমাকে আরও বলুন!',
                  'কেন তোমার এটা মনে হল?',
                  'কতদিন ধরে তুমি এভাবে অনুভব করছো?',
                  'আমি এটি অত্যন্ত আকর্ষণীয় মনে করি',
                  'আপনি কি এটা ব্যাক আপ করতে পারেন?',
                  'কি শান্তি!',
                  ':)']}

# Extracting key phrases
rules = {'আমি চাই (.*)': ['আপনি {0} পেলে এর অর্থ কী হবে',
                          'আপনি কেন চান {0}',
                          "আপনাকে {0} পেতে কি বাধা দিচ্ছে"],
         'তোমার কি মনে আছে (.*)': ['তুমি কি ভেবেছিলে আমি ভুলে যাবো {0}',
                                   "কেন তুমি ভুলতে পারনি {0}",
                                   '{0} সম্পর্কে কি',
                                   'হ্যাঁ এবং?'],
         'আপনি কি মনে করেন (.*)': ['যদি {0}? একেবারে।',
                                   'কোন সম্ভাবনা নেই'],
         'যদি (.*)': ["আপনি কি সত্যিই মনে করেন এটি সম্ভবত {0}",
                      'আপনি কি চান যে {0}',
                      'আপনি {0} সম্পর্কে কি মনে করেন',
                      'সত্যিই--যদি {0}']}

# Define match_rules
def match_rules(rules, message):
    for pattern, responses in rules.items():
        match = re.search(pattern, message)

        if match is not None:
            response = random.choice(responses)
            var = match.group(1) if '{0}' in response else None

            return response, var

    return "default", None

# Define Response
def respond(message):
    response, phrase = match_rules(rules, message)

    if '{0}' in response:
        phrase = replace_pronouns(phrase)
        response = response.format(phrase)

    return response

# Define Replace pronouns
def replace_pronouns(message):
    message = message.lower()

    if "আমি" in message:
        return re.sub("আমি", "তুমি", message)
    if "আমার" in message:
        return re.sub("আমার", "তোমার", message)
    if "তোমার" in message:
        return re.sub("তোমার", "আমার", message)
    if "তুমি" in message:
        return re.sub("তুমি", "আমি", message)

    return message

def send_message():
    message = take_command()
    print(user_template.format(message))
    response = respond(message)
    print(bot_template.format(response))
    translate(response)

send_message()