#!/usr/bin/env python3
# Copyright (C) Alibaba Group Holding Limited.

""" Transformations. """

import torch
import math

import torchvision.transforms._functional_video as F
from torchvision.transforms import Lambda, Compose
import random
import numbers

class ColorJitter(object):
    """
    Modified from https://github.com/TengdaHan/DPC/blob/master/utils/augmentation.py.
    Randomly change the brightness, contrast and saturation of an image.
    Args:
        brightness (float or tuple of float (min, max)): How much to jitter brightness.
            brightness_factor is chosen uniformly from [max(0, 1 - brightness), 1 + brightness]
            or the given [min, max]. Should be non negative numbers.
        contrast (float or tuple of float (min, max)): How much to jitter contrast.
            contrast_factor is chosen uniformly from [max(0, 1 - contrast), 1 + contrast]
            or the given [min, max]. Should be non negative numbers.
        saturation (float or tuple of float (min, max)): How much to jitter saturation.
            saturation_factor is chosen uniformly from [max(0, 1 - saturation), 1 + saturation]
            or the given [min, max]. Should be non negative numbers.
        hue (float or tuple of float (min, max)): How much to jitter hue.
            hue_factor is chosen uniformly from [-hue, hue] or the given [min, max].
            Should have 0<= hue <= 0.5 or -0.5 <= min <= max <= 0.5.
        grayscale (float): possibility to transform the video to grayscale.
            Should have a value range of [0, 1]
        consistent  (bool): indicates whether or not to keep all the color transformations consistent for all the frames.
        shuffle     (bool): indicates whether or not to shuffle the sequence of the augmentations.
        gray_first  (bool): indicates whether or not to put grayscale transform first.
    """
    def __init__(
        self, brightness=0, contrast=0, saturation=0, hue=0, grayscale=0, color=0., consistent=False, shuffle=True, gray_first=True
    ):
        self.brightness = self._check_input(brightness, 'brightness')
        self.contrast = self._check_input(contrast, 'contrast')
        self.saturation = self._check_input(saturation, 'saturation')
        self.hue = self._check_input(hue, 'hue', center=0, bound=(-0.5, 0.5),
                                     clip_first_on_zero=False)

        self.color = color
        self.grayscale = grayscale
        self.consistent = consistent
        self.shuffle = shuffle
        self.gray_first = gray_first

    def _check_input(self, value, name, center=1, bound=(0, float('inf')), clip_first_on_zero=True):
        if isinstance(value, numbers.Number):
            if value < 0:
                raise ValueError("If {} is a single number, it must be non negative.".format(name))
            value = [center - float(value), center + float(value)]
            if clip_first_on_zero:
                value[0] = max(value[0], 0.0)
        elif isinstance(value, (tuple, list)) and len(value) == 2:
            if not bound[0] <= value[0] <= value[1] <= bound[1]:
                raise ValueError("{} values should be between {}".format(name, bound))
        else:
            raise TypeError("{} should be a single number or a list/tuple with lenght 2.".format(name))

        # if value is 0 or (1., 1.) for brightness/contrast/saturation
        # or (0., 0.) for hue, do nothing
        if value[0] == value[1] == center:
            value = None
        return value

    def _get_transform(self, T, device):
        """Get a randomized transform to be applied on image.
        Arguments are same as that of __init__.
        Arg:
            T (int): number of frames. Used when consistent = False.
        Returns:
            Transform which randomly adjusts brightness, contrast and
            saturation in a random order.
        """
        transforms = []
        if random.uniform(0, 1) < self.color:
            if self.brightness is not None:
                if self.consistent:
                    brightness_factor = random.uniform(self.brightness[0], self.brightness[1])
                else:
                    brightness_factor = torch.empty([1, T, 1, 1], device=device).uniform_(self.brightness[0], self.brightness[1])
                transforms.append(Lambda(lambda frame: adjust_brightness(frame, brightness_factor)))

            if self.contrast is not None:
                if self.consistent:
                    contrast_factor = random.uniform(self.contrast[0], self.contrast[1])
                else:
                    contrast_factor = torch.empty([1, T, 1, 1], device=device).uniform_(self.contrast[0], self.contrast[1])
                transforms.append(Lambda(lambda frame: adjust_contrast(frame, contrast_factor)))

            if self.saturation is not None:
                if self.consistent:
                    saturation_factor = random.uniform(self.saturation[0], self.saturation[1])
                else:
                    saturation_factor = torch.empty([1, T, 1, 1], device=device).uniform_(self.saturation[0], self.saturation[1])
                transforms.append(Lambda(lambda frame: adjust_saturation(frame, saturation_factor)))

            if self.hue is not None:
                if self.consistent:
                    hue_factor = random.uniform(self.hue[0], self.hue[1])
                else:
                    hue_factor = torch.empty([T, 1, 1], device=device).uniform_(self.hue[0], self.hue[1])
                transforms.append(Lambda(lambda frame: adjust_hue(frame, hue_factor)))

            if self.shuffle:
                random.shuffle(transforms)

        if random.uniform(0, 1) < self.grayscale:
            gray_transform = Lambda(lambda frame: rgb_to_grayscale(frame))
            if self.gray_first:
                transforms.insert(0, gray_transform)
            else:
                transforms.append(gray_transform)

        transform = Compose(transforms)

        return transform

    def __call__(self, clip):
        """
        Args:
            clip (torch.tensor): Size is (C, T, H, W)
        Return:
            clip (torch.tensor): Size is (C, T, H, W)
        """

        raw_shape = clip.shape #(C, T, H, W)
        device = clip.device
        T = raw_shape[1]
        transform = self._get_transform(T, device)
        clip = transform(clip)
        assert clip.shape == raw_shape
        return clip #(C, T, H, W)

    def __repr__(self):
        format_string = self.__class__.__name__ + '('
        format_string += 'brightness={0}'.format(self.brightness)
        format_string += ', contrast={0}'.format(self.contrast)
        format_string += ', saturation={0}'.format(self.saturation)
        format_string += ', hue={0})'.format(self.hue)
        format_string += ', grayscale={0})'.format(self.grayscale)
        return format_string

def _is_tensor_a_torch_image(input):
    return input.ndim >= 2

def _blend(img1, img2, ratio):
    # type: (Tensor, Tensor, float) -> Tensor
    bound = 1 if img1.dtype in [torch.half, torch.float32, torch.float64] else 255
    return (ratio * img1 + (1 - ratio) * img2).clamp(0, bound).to(img1.dtype)

def rgb_to_grayscale(img):
    # type: (Tensor) -> Tensor
    """Convert the given RGB Image Tensor to Grayscale.
    For RGB to Grayscale conversion, ITU-R 601-2 luma transform is performed which
    is L = R * 0.2989 + G * 0.5870 + B * 0.1140
    Args:
        img (Tensor): Image to be converted to Grayscale in the form [C, H, W].
    Returns:
        Tensor: Grayscale image.
        Args:
            clip (torch.tensor): Size is (T, H, W, C)
        Return:
            clip (torch.tensor): Size is (T, H, W, C)
    """
    orig_dtype = img.dtype
    rgb_convert = torch.tensor([0.299, 0.587, 0.114])

    assert img.shape[0] == 3, "First dimension need to be 3 Channels"
    if img.is_cuda:
        rgb_convert = rgb_convert.to(img.device)

    img = img.float().permute(1,2,3,0).matmul(rgb_convert).to(orig_dtype)
    return torch.stack([img, img, img], 0)

def _rgb2hsv(img):
    r, g, b = img.unbind(0)

    maxc, _ = torch.max(img, dim=0)
    minc, _ = torch.min(img, dim=0)

    eqc = maxc == minc
    cr = maxc - minc
    s = cr / torch.where(eqc, maxc.new_ones(()), maxc)
    cr_divisor = torch.where(eqc, maxc.new_ones(()), cr)
    rc = (maxc - r) / cr_divisor
    gc = (maxc - g) / cr_divisor
    bc = (maxc - b) / cr_divisor

    hr = (maxc == r) * (bc - gc)
    hg = ((maxc == g) & (maxc != r)) * (2.0 + rc - bc)
    hb = ((maxc != g) & (maxc != r)) * (4.0 + gc - rc)
    h = (hr + hg + hb)
    h = torch.fmod((h / 6.0 + 1.0), 1.0)
    return torch.stack((h, s, maxc))

def _hsv2rgb(img):
    l = len(img.shape)
    h, s, v = img.unbind(0)
    i = torch.floor(h * 6.0)
    f = (h * 6.0) - i
    i = i.to(dtype=torch.int32)

    p = torch.clamp((v * (1.0 - s)), 0.0, 1.0)
    q = torch.clamp((v * (1.0 - s * f)), 0.0, 1.0)
    t = torch.clamp((v * (1.0 - s * (1.0 - f))), 0.0, 1.0)
    i = i % 6

    if l == 3:
        tmp = torch.arange(6)[:, None, None]
    elif l == 4:
        tmp = torch.arange(6)[:, None, None, None]

    if img.is_cuda:
        tmp = tmp.to(img.device)

    mask = i == tmp #(H, W) == (6, H, W)

    a1 = torch.stack((v, q, p, p, t, v))
    a2 = torch.stack((t, v, v, q, p, p))
    a3 = torch.stack((p, p, t, v, v, q))
    a4 = torch.stack((a1, a2, a3)) #(3, 6, H, W)

    if l == 3:
        return torch.einsum("ijk, xijk -> xjk", mask.to(dtype=img.dtype), a4) #(C, H, W)
    elif l == 4:
        return torch.einsum("itjk, xitjk -> xtjk", mask.to(dtype=img.dtype), a4) #(C, T, H, W)

def adjust_brightness(img, brightness_factor):
    # type: (Tensor, float) -> Tensor
    if not _is_tensor_a_torch_image(img):
        raise TypeError('tensor is not a torch image.')

    return _blend(img, torch.zeros_like(img), brightness_factor)

def adjust_contrast(img, contrast_factor):
    # type: (Tensor, float) -> Tensor
    if not _is_tensor_a_torch_image(img):
        raise TypeError('tensor is not a torch image.')

    mean = torch.mean(rgb_to_grayscale(img).to(torch.float), dim=(-4, -2, -1), keepdim=True)

    return _blend(img, mean, contrast_factor)

def adjust_saturation(img, saturation_factor):
    # type: (Tensor, float) -> Tensor
    if not _is_tensor_a_torch_image(img):
        raise TypeError('tensor is not a torch image.')

    return _blend(img, rgb_to_grayscale(img), saturation_factor)

def adjust_hue(img, hue_factor):
    """Adjust hue of an image.
    The image hue is adjusted by converting the image to HSV and
    cyclically shifting the intensities in the hue channel (H).
    The image is then converted back to original image mode.
    `hue_factor` is the amount of shift in H channel and must be in the
    interval `[-0.5, 0.5]`.
    See `Hue`_ for more details.
    .. _Hue: https://en.wikipedia.org/wiki/Hue
    Args:
        img (Tensor): Image to be adjusted. Image type is either uint8 or float.
        hue_factor (float):  How much to shift the hue channel. Should be in
            [-0.5, 0.5]. 0.5 and -0.5 give complete reversal of hue channel in
            HSV space in positive and negative direction respectively.
            0 means no shift. Therefore, both -0.5 and 0.5 will give an image
            with complementary colors while 0 gives the original image.
    Returns:
         Tensor: Hue adjusted image.
    """
    if isinstance(hue_factor, float) and  not(-0.5 <= hue_factor <= 0.5):
        raise ValueError('hue_factor ({}) is not in [-0.5, 0.5].'.format(hue_factor))
    elif isinstance(hue_factor, torch.Tensor) and not ((-0.5 <= hue_factor).sum() == hue_factor.shape[0] and (hue_factor <= 0.5).sum() == hue_factor.shape[0]):
        raise ValueError('hue_factor ({}) is not in [-0.5, 0.5].'.format(hue_factor))

    if not _is_tensor_a_torch_image(img):
        raise TypeError('tensor is not a torch image.')

    orig_dtype = img.dtype
    if img.dtype == torch.uint8:
        img = img.to(dtype=torch.float32) / 255.0

    img = _rgb2hsv(img)
    h, s, v = img.unbind(0)
    h += hue_factor
    h = h % 1.0
    img = torch.stack((h, s, v))
    img_hue_adj = _hsv2rgb(img)

    if orig_dtype == torch.uint8:
        img_hue_adj = (img_hue_adj * 255.0).to(dtype=orig_dtype)

    return img_hue_adj

class AutoResizedCropVideo(object):
    def __init__(
            self,
            size,
            scale=(0.08, 1.0),
            interpolation_mode="bilinear",
            mode = "cc"
    ):
        # mode how many clips return
        if isinstance(size, tuple):
            assert len(size) == 2, "size should be tuple (height, width)"
            self.size = size
        else:
            self.size = (size, size)

        self.interpolation_mode = interpolation_mode
        self.scale = scale
        self.mode = mode
        self.idx = 0

    def set_spatial_index(self, idx):
        self.idx = idx

    def get_crop(self, clip):
        crop_mode = self.mode[self.idx:self.idx+2]

        scale = random.uniform(*self.scale)

        # Get the crop size for the scale cropping
        _, _, image_height, image_width = clip.shape

        min_length = min(image_width, image_height)
        crop_size = int(min_length * scale)

        center_x = image_width // 2
        center_y = image_height // 2
        box_half = crop_size // 2
        th = crop_size
        tw = crop_size

        if crop_mode == "cc":
            x1 = center_x - box_half
            y1 = center_y - box_half
            x2 = center_x + box_half
            y2 = center_y + box_half
        elif crop_mode == "ll":
            x1 = 0
            y1 = center_y - box_half
            x2 = crop_size
            y2 = center_y + box_half
        elif crop_mode == "rr":
            x1 = image_width - crop_size
            y1 = center_y - box_half
            x2 = image_width
            y2 = center_y + box_half
        elif crop_mode == "tl":
            x1 = 0
            y1 = 0
            x2 = crop_size
            y2 = crop_size
        elif crop_mode == "tr":
            x1 = image_width - crop_size
            y1 = 0
            x2 = image_width
            y2 = crop_size
        elif crop_mode == "bl":
            x1 = 0
            y1 = image_height - crop_size
            x2 = crop_size
            y2 = image_height
        elif crop_mode == "br":
            x1 = image_width - crop_size
            y1 = image_height - crop_size
            x2 = image_width
            y2 = image_height

        crop = F.resized_crop(clip, y1, x1, th, tw, self.size, self.interpolation_mode)
        return crop

    def __call__(self, clip):
        """
        Args:
            clip (torch.tensor): Video clip to be cropped. Size is (C, T, H, W)
        Returns:
            torch.tensor: randomly cropped/resized video clip.
                size is (C, T, H, W)
        """
        if self.idx == -1:
            # return self.get_random_crop(clip)
            pass
        else:
            return self.get_crop(clip)

class KineticsResizedCrop(object):
    def __init__(
        self,
        short_side_range,
        crop_size,
        num_spatial_crops=1,
    ):
        self.idx = -1
        self.short_side_range = short_side_range
        self.crop_size = int(crop_size)
        self.num_spatial_crops = num_spatial_crops

    def _get_controlled_crop(self, clip):
        _, _, clip_height, clip_width = clip.shape

        length = self.short_side_range[0]

        if clip_height < clip_width:
            new_clip_height = int(length)
            new_clip_width = int(clip_width / clip_height * new_clip_height)
            new_clip = torch.nn.functional.interpolate(
                clip, size=(new_clip_height, new_clip_width), mode="bilinear"
            )
        else:
            new_clip_width = int(length)
            new_clip_height = int(clip_height / clip_width * new_clip_width)
            new_clip = torch.nn.functional.interpolate(
                clip, size=(new_clip_height, new_clip_width), mode="bilinear"
            )
        x_max = int(new_clip_width - self.crop_size)
        y_max = int(new_clip_height - self.crop_size)
        if self.num_spatial_crops == 1:
            x = x_max // 2
            y = y_max // 2
        elif self.num_spatial_crops == 3:
            if self.idx == 0:
                if new_clip_width == length:
                    x = x_max // 2
                    y = 0
                elif new_clip_height == length:
                    x = 0
                    y = y_max // 2
            elif self.idx == 1:
                x = x_max // 2
                y = y_max // 2
            elif self.idx == 2:
                if new_clip_width == length:
                    x = x_max // 2
                    y = y_max
                elif new_clip_height == length:
                    x = x_max
                    y = y_max // 2
        return new_clip[:, :, y:y+self.crop_size, x:x+self.crop_size]

    def _get_random_crop(self, clip):
        _, _, clip_height, clip_width = clip.shape

        if clip_height < clip_width:
            new_clip_height = int(random.uniform(*self.short_side_range))
            new_clip_width = int(clip_width / clip_height * new_clip_height)
            new_clip = torch.nn.functional.interpolate(
                clip, size=(new_clip_height, new_clip_width), mode="bilinear"
            )
        else:
            new_clip_width = int(random.uniform(*self.short_side_range))
            new_clip_height = int(clip_height / clip_width * new_clip_width)
            new_clip = torch.nn.functional.interpolate(
                clip, size=(new_clip_height, new_clip_width), mode="bilinear"
            )
        x_max = int(new_clip_width - self.crop_size)
        y_max = int(new_clip_height - self.crop_size)
        x = int(random.uniform(0, x_max))
        y = int(random.uniform(0, y_max))
        return new_clip[:, :, y:y+self.crop_size, x:x+self.crop_size]

    def set_spatial_index(self, idx):
        self.idx = idx

    def __call__(self, clip):
        if self.idx == -1:
            return self._get_random_crop(clip)
        else:
            return self._get_controlled_crop(clip)


from collections import defaultdict
import sys

def parse_args(typ):
  args = sys.argv[1:]
  if (typ == "b"):
    args = args[1:]

  if len(args) > 0:
    filein = args[0]
  else:
    filein = input("Enter filename to transform: ")
  if len(args) > 1:
    fileout = args[1]
  else:
    fileout = "new_" + filein

  return filein, fileout

def get_max_dim(filein, typ=""):
  # determine max dimension
  midx = 0

  with open(filein, "r") as f:
    for line in f:
      if typ == "b":
        midx = max(midx, max([int(item) for item in line.strip().split()]))
      else:
        midx = max(midx, max([int(item.split(":")[0]) for item in line.strip().split()]))
  return midx

def transform(filein, fileout):
  midx = get_max_dim(filein)
  # print("max dim = ", midx)
  with open(fileout, "w") as fout:
    with open(filein, "r") as f:
      for line in f:
        dense_v = defaultdict(int)
        for pair in line.strip().split():
          idx, val = pair.split(":")
          dense_v[int(idx)] = float(val)

        outline = " ".join([str(dense_v[i]) for i in range(midx)])
        fout.write(outline + "\n")

def transform_binary(filein, fileout):
  midx = get_max_dim(filein, "b")
  with open(fileout, "w") as fout:
    with open(filein, "r") as f:
      for line in f:
        dense_v = defaultdict(int)
        for idx in line.strip().split():
          idx = int(idx)
          dense_v[idx] = 1

        outline = " ".join([str(dense_v[i]) for i in range(midx)])
        fout.write(outline + "\n")

def main():
  if len(sys.argv) > 1:
    typ = sys.argv[1]

  filein, fileout = parse_args(typ)

  if typ == "b":
    transform_binary(filein, fileout)
  else:
    transform(filein, fileout)

main()


from w13.num import num
from w13.sym import sym
from w13.sample import sample
from texttable import Texttable
import re,csv

class table:

    def __init__(self):
        """
        A table object to represent rows that holds and works with
        both num and sym instance
        """
        self.use = {}
        self.w={}
        self.syms = {}
        self.nums = {}
        self.clazz = None
        self.rows = {}
        self.name = {}
        self. indeps = {}

    def row(self,cells):
          """
         Adds a row to this table instance
          :param cells:
          :return:
          """
          r= len(self.rows) + 1
          self.rows[r] = {}
          for c,c0 in self.use.items():
            x = cells[c0]
            if x != '?':
              if c0 in self.nums.keys():
                x = float(x)
                self.nums[c].numInc(x)
              else:
                self.syms[c].symInc(x)
            self.rows[r][c] = x

    def dep(self, c):
        """
        Check if this column is a dependent column
        :param c:
        :return: True/False
        """
        return not self.indep(c)

    def indep(self,c):
        """
        Check if this column is an independent column
        :param c:
        :return: True/False
        """
        return not self.w[c] and self.clazz != c

    def printReport(self, fileName):
        """
        Pretty print the table instance for a given csv input
        :param fileName:
        :return:
        """

        t = Texttable()
        t.add_rows([[' ', ' ', 'n' , 'mode' ,'frequency']])
        print("-------------- ",str(fileName)," ---------------------------\n")
        for key, symVal in self.syms.items():
            t.add_row([str(key), self.name[key], symVal.n, symVal.mode, symVal.most])

        print (t.draw())

        t = Texttable()
        t.add_rows([[' ', ' ', 'n', 'mu', 'sd']])

        for key, numVal in self.nums.items():
            t.add_row([str(key), self.name[key], numVal.n, numVal.mu, numVal.sd])

        print(t.draw())

def header(cells):
  """
   To read and process special symbols for input rows
  :param cells:
  :return:
  """

  t = table()
  for c0,x in enumerate(cells):
    if "?" not in x:
      c = len(t.use)
      t.use[c] = c0
      t.name[c] = x
      if re.search("[<>$]", x):
        t.nums[c] = num(1000)
      else :
          t.syms[c] = sym()
      if     "<" in x :
         t.w[c]  = -1
      elif ">" in x:
        t.w[c]  =  1
      elif "!" in x:
        t.clazz =  c
      else:
          t.indeps[ len(t.indeps) + 1 ] = c

  return t

def createTable(fileName):
    """
    Reads csv from disk using fileName
    :param fileName: csv relative file path
    :return: a table object with only header or all data rows.
    """

    newTable = table()
    lineNumber = 1
    with open(fileName) as csv_file:
        csvRows = ''
        readerElements = csv.reader(csv_file, delimiter=',')
        for row in readerElements:
            cells = row #row.split(",")
            if lineNumber > 1:
                 newTable.row(cells)
            else :
                lineNumber += 1
                newTable = header(cells)

    return newTable

if __name__ == "__main__":

    """
    Prints the statistics for each csv
    """
    autoTable = createTable("data/auto.csv")
    autoTable.printReport("auto.csv")

    weatherTable = createTable("data/weather.csv")
    weatherTable.printReport("weather.csv")

    weatherLongTable = createTable("data/weatherLong.csv")
    weatherLongTable.printReport("weatherLong.csv")


class Random1:
    x = 6
    y = 12
    m = 0b1011
    n = 0xad4

print(type(Random1.x),"\n",type(Random1.y),"\n",type(Random1.m),"\n",type(Random1.n))

# for i in range(5):
#     print(i)
#

# X = (input("Enter an Integer:\n "))
# print(X)
# print(type(X))

import  math
x=6;y=12
print(x==y,"\n",x!=y,"\n",x>=y,"\n",x>y,"\n",x<=y,"\n",x<y)

v=10.6452348
print(v.__round__(2))

x =  float('inf')
y = float('-inf')
print(x ," \n",y)
#print(math.isinf(x),"\n",math.isinf(y))

print(bool(0))


# 定义一个空类
class Student():
    pass

class PythonStudent():
    name = None
    age = 18
    # self 相当于 this 函数

    def myfun(self):
        print("do homework")
        self.age = 23
        return None

wang = PythonStudent()
print(wang.age)
print(PythonStudent.__dict__)
print(" ")
# 创建对象的时候内部无成员
print(wang.__dict__)

# 赋值的时候有相应成员
wang.age = 19
print(wang.__dict__)

wang.myfun()
print(wang.age)

# self 表示对象本身 ，其为函数的第一个参数，将对象作为第一个参数进行传入
# 其并不是一个关键字

class Teacher():
    name = "nina"

    def sayhello(selff):
        selff.name = "ffffff"
        print("HELLO {0}".format(selff.name))

    def sayAgain( ):
        print("jjjjj")

nnn = Teacher()
nnn.sayhello()
# 仅当其为对象时才会自动被传入
Teacher.sayAgain()

class A():

    name = "liu"
    age = 18

    def __init__(self):
        self.age = 19
        self.name = "zhang"

    def say(self):
        print("*"*20)
        print(self.name)
        print(self.age)

class B():
    name = "liuuuuu"
    age = 18888

a = A()
a.say()
#　此时，self被a 替换
A.say(a)
# 同样，可以将A传入
A.say(A)

# 鸭子类型
A.say(B)


#프로그래머스 lv.1, 명예의 전당 (1)
def solution(k, score):
    mj = []
    result = []

    for i in score:
        mj.append(i)
        if (len(mj) > k):
            mj.remove(min(mj))
        result.append(min(mj))
    return result


def run():
	t = int(input().strip())
	for _ in range(t):
		n = int(input().strip())
		b = list(map(int, input().split()))
		print(max_cost(b))

def max_cost(b):
	f = [0 for i in b]
	g = [0 for i in b]
	for i in range(len(b)-2, -1, -1):
		f[i] = max(f[i+1], g[i+1] + (b[i] - 1))
		g[i] = max(f[i+1] + (b[i+1] - 1), g[i+1])
	return max(g[0], f[0])

run()


import logging

from users.models import GitHubProfile, User

LOGGER = logging.getLogger(__name__)

def update_or_create_githubprofile(profile_data, user=None):
    """
    Accepts any mapping object that has field names of GitHubProfile in the keys
    """
    # Ensure that is a editable object and that `profile_data` is a mapping object
    profile_data = dict(profile_data)

    profile_id = profile_data.pop('id')
    profile_data['user'] = user or User.objects.get_or_create(username=profile_data['login'])[0]
    profile_data['name'] = profile_data['name'] or ''

    profile, profile_created = GitHubProfile.objects.update_or_create(
        github_id=profile_id,
        defaults=profile_data
    )

    LOGGER.info(f'GitHub profile "{profile}" {"created" if profile_created else "updated"}.')
    return profile


# I wrote this code

from django.test import TestCase
from rest_framework.test import APITestCase

from .model_factories import *
from .serializers import *

from django.shortcuts import get_object_or_404

class ProteinsSerializerTest(APITestCase):

    protein1 = None
    proteinSerializer = None

    def setUp(self) -> None:
        self.protein1 = ProteinFactory.create(proteinId="A0A014PQC0")
        self.proteinsSerializer = ProteinSerializer(instance=self.protein1)

        self.validated_data = {
            'protein_id': 'A0A014PQC0',
            'sequence': 'SAMPLE_SEQUENCE',
            'length': 100
        }

    def tearDown(self) -> None:
        Protein.objects.all().delete()
        ProteinFactory.reset_sequence(0)

    def test_proteinsListSerializer(self):
        data = self.proteinsSerializer.data
        self.assertEqual(set(data.keys()), set(['protein_id', 'sequence', 'length']))

    def test_proteinSerializer_create(self):
        serializer = ProteinSerializer(data=self.validated_data)

        is_valid = serializer.is_valid()
        if not is_valid:
            print(serializer.errors)
        self.assertTrue(is_valid)

class ProteinGetSerializerTest(APITestCase):
    '''
    Part of ProteinGetSerializerTest:
        ProteinGetSerializer
        TaxonomyProteinSerializer
        ProteinDomainLinkGetSerializer

    '''
    protein1 = None
    protein2 = None
    proteinSerializer = None
    domain1= None
    domain2=None
    domain_link1 = None
    domain_link2 = None
    taxonomy = None
    taxaonmoylink1 = None
    taxaonmoylink2 = None

    def setUp(self):

        self.taxonomy = TaxonomyFactory.create(taxaId='55661')
        self.protein1 = ProteinFactory.create(proteinId='A0A014PQC0')
        # self.protein2 = ProteinFactory.create(proteinId='A0A134567')

        self.taxaonmoylink1 = TaxonomyProteinLinkFactory.create(protein=self.protein1, taxonomy=self.taxonomy)
        # self.taxaonmoylink2 = TaxonomyProteinLinkFactory.create(protein=self.protein2, taxonomy=self.taxonomy)

        self.domain1 = PfamFactory(domainId='PF01650', domain_description='PeptidaseC13family')
        self.domain2 = PfamFactory(domainId='PF12345', domain_description='AnotherDomain')

        self.domain_link1 = ProteinDomainLinkFactory(protein=self.protein1, pfam=self.domain1)
        self.domain_link2 = ProteinDomainLinkFactory(protein=self.protein1, pfam=self.domain2)

        self.proteinSerializer = ProteinGetSerializer(self.protein1)

    def tearDown(self):
        Protein.objects.all().delete()
        ProteinDomainLink.objects.all().delete()
        TaxonomyProteinLink.objects.all().delete()
        ProteinFactory.reset_sequence(0)
        ProteinDomainLinkFactory.reset_sequence(0)
        TaxonomyProteinLinkFactory.reset_sequence(0)

    def test_proteinGetSerializer(self):
        data = self.proteinSerializer.data
        self.assertEqual(set(data.keys()), set(['protein_id', 'sequence', 'taxonomy', 'length', 'domains']))

    def test_proteinGetSerializerHasCorrectData(self):
        data = self.proteinSerializer.data
        self.assertEqual(data['protein_id'], 'A0A014PQC0')

        # Additional assertions for the fields 'sequence', 'length', 'taxonomy', and 'domains'
        self.assertEqual(data['sequence'], self.protein1.sequence)
        self.assertEqual(data['length'], self.protein1.length)
        self.assertEqual(len(data['taxonomy']), 4)
        self.assertEqual(len(data['domains']), 2)  # Assuming 2 domain entries for this protein

class TaxonomyProteinSerializerTest(TestCase):

    taxonomy_data = None

    def setUp(self):
        ''' not using factory boy, this serializer is part of create protein '''
        self.taxonomy_data = {
            'taxaId': '55661',
            'clade': 'Sample Clade',
            'genus': 'Sample Genus',
            'species': 'Sample Species'
        }

    def tearDown(self):
        Taxonomy.objects.all().delete()
        ProteinDomainLink.objects.all().delete()
        TaxonomyProteinLink.objects.all().delete()
        ProteinFactory.reset_sequence(0)
        ProteinDomainLinkFactory.reset_sequence(0)
        TaxonomyProteinLinkFactory.reset_sequence(0)

    def test_taxonomyProteinSerializer(self):

        protein_data = {
            'taxonomy': self.taxonomy_data
        }

        serializer = TaxonomyProteinSerializer(protein_data)

        self.assertEqual(set(serializer.data.keys()), set(['taxa_id', 'clade', 'genus', 'species']))
        self.assertEqual(serializer.data['taxa_id'], '55661')
        self.assertEqual(serializer.data['clade'], 'Sample Clade')
        self.assertEqual(serializer.data['genus'], 'Sample Genus')
        self.assertEqual(serializer.data['species'], 'Sample Species')

class TaxonomyProteinLinkSerializerTest(TestCase):

    def setUp(self):
        self.taxonomy = TaxonomyFactory.create(taxaId='55661')
        self.protein1 = ProteinFactory.create(proteinId='A0A014PQC0')
        self.taxaonmoylink1 = TaxonomyProteinLinkFactory.create(protein=self.protein1, taxonomy=self.taxonomy)
        self.serializer = TaxonomyProteinLinkSerializer(instance=self.taxaonmoylink1)

    def tearDown(self):
        Taxonomy.objects.all().delete()
        ProteinDomainLink.objects.all().delete()
        TaxonomyProteinLink.objects.all().delete()
        ProteinFactory.reset_sequence(0)
        ProteinDomainLinkFactory.reset_sequence(0)
        TaxonomyProteinLinkFactory.reset_sequence(0)

    def test_taxonomyProteinLinkSerializer(self):
        data = self.serializer.data
        self.assertEqual(set(data.keys()), set(['taxonomy', 'protein']))

class GetPfamOnTaxaIdSerializerTest(TestCase):

    def setUp(self):
        self.domain1 = PfamFactory(domainId='PF01650', domain_description='PeptidaseC13family')
        self.protein1 = ProteinFactory.create(proteinId='A0A04PQC0')
        self.domain_link1 = ProteinDomainLinkFactory(protein=self.protein1, pfam=self.domain1)

        self.serializer = GetPfamOnTaxaIdSerializer(instance=self.domain_link1)

    def tearDown(self):
        Taxonomy.objects.all().delete()
        ProteinDomainLink.objects.all().delete()
        TaxonomyProteinLink.objects.all().delete()
        ProteinFactory.reset_sequence(0)
        ProteinDomainLinkFactory.reset_sequence(0)
        TaxonomyProteinLinkFactory.reset_sequence(0)

    def test_getPfamOnTaxaIdSerializer(self):
        data = self.serializer.data
        self.assertEqual(set(data.keys()), set(['id', 'pfam_id']))
        self.assertEqual(data['id'], str(self.domain_link1.pk))
        self.assertEqual(data['pfam_id']['domain_id'], self.domain1.domainId)
        self.assertEqual(data['pfam_id']['domain_description'], self.domain1.domain_description)

class ProteinDomainLinkGetSerializerTest(TestCase):

    def setUp(self):
        self.domain1 = PfamFactory(domainId='PF01650', domain_description='PeptidaseC13family')
        self.protein1 = ProteinFactory(proteinId='A0A04PQC0')
        self.domain_link1 = ProteinDomainLinkFactory(protein=self.protein1, pfam=self.domain1)

        self.serializer = ProteinDomainLinkGetSerializer(instance=self.domain_link1)

    def tearDown(self):
        Taxonomy.objects.all().delete()
        ProteinDomainLink.objects.all().delete()
        TaxonomyProteinLink.objects.all().delete()
        ProteinFactory.reset_sequence(0)
        ProteinDomainLinkFactory.reset_sequence(0)
        TaxonomyProteinLinkFactory.reset_sequence(0)

    def test_proteinDomainLinkGetSerializer(self):
        data = self.serializer.data

        self.assertEqual(set(data.keys()), set(['pfam_id', 'description', 'start', 'stop']))
        self.assertEqual(data['pfam_id']['domain_id'], self.domain1.domainId)
        self.assertEqual(data['pfam_id']['domain_description'], self.domain1.domain_description)

class ProteinDomainLinkSerializerTest(TestCase):

    def setUp(self):
        self.protein1 = ProteinFactory(proteinId='A0A04PQC0')
        self.data = {
            'protein': self.protein1.pk,
            'pfam_id': {
                'domain_id': 'PF01650',
                'domain_description': 'self.pfam.domain_description'
            },
            'description': 'Sample description',
            'start': 1,
            'stop': 10
        }
        self.serializer = ProteinDomainLinkSerializer(data=self.data)

    def tearDown(self):
        Taxonomy.objects.all().delete()
        ProteinDomainLink.objects.all().delete()
        TaxonomyProteinLink.objects.all().delete()
        ProteinFactory.reset_sequence(0)
        ProteinDomainLinkFactory.reset_sequence(0)
        TaxonomyProteinLinkFactory.reset_sequence(0)

    def test_proteinDomainLinkSerializer_create(self):
        is_valid = self.serializer.is_valid()
        if not is_valid:
            print(self.serializer.errors)
        self.assertTrue(is_valid)

        link = self.serializer.save()

        self.assertEqual(link.protein, self.protein1)

class TaxonomySerializerTest(TestCase):

    def setUp(self):
        self.data = {
            'taxa_id': '55661',
            'clade': 'Sample Clade',
            'genus': 'Sample Genus',
            'species': 'Sample Species'
        }
        self.serializer = TaxonomySerializer(data=self.data)

    def tearDown(self):
        Taxonomy.objects.all().delete()
        ProteinDomainLink.objects.all().delete()
        TaxonomyProteinLink.objects.all().delete()
        ProteinFactory.reset_sequence(0)
        ProteinDomainLinkFactory.reset_sequence(0)
        TaxonomyProteinLinkFactory.reset_sequence(0)

    def test_taxonomySerializer(self):
        self.assertTrue(self.serializer.is_valid())
        data = self.serializer.data

        self.assertEqual(set(data.keys()), set(['taxa_id', 'clade', 'genus', 'species']))
        self.assertEqual(data['taxa_id'], '55661')
        self.assertEqual(data['clade'], 'Sample Clade')
        self.assertEqual(data['genus'], 'Sample Genus')
        self.assertEqual(data['species'], 'Sample Species')

#end of code I wrote


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

from absl.testing import parameterized

import tensorflow as tf
from tensorflow_privacy.privacy.estimators import test_utils
from tensorflow_privacy.privacy.estimators.v1 import head as head_lib
from tensorflow_privacy.privacy.optimizers.dp_optimizer import DPGradientDescentGaussianOptimizer

def make_model_fn(head, optimizer, feature_columns):
  """Constructs and returns a model_fn using supplied head."""

  def model_fn(features, labels, mode, params, config=None):  # pylint: disable=unused-argument
    feature_layer = tf.keras.layers.DenseFeatures(feature_columns)
    inputs = feature_layer(features)
    hidden_layer = tf.keras.layers.Dense(units=3, activation='relu')
    hidden_layer_values = hidden_layer(inputs)
    logits_layer = tf.keras.layers.Dense(
        units=head.logits_dimension, activation=None)
    logits = logits_layer(hidden_layer_values)
    return head.create_estimator_spec(
        features=features,
        labels=labels,
        mode=mode,
        logits=logits,
        optimizer=optimizer)

  return model_fn

class DPHeadTest(tf.test.TestCase, parameterized.TestCase):
  """Tests for DP-enabled heads."""

  # Parameters for testing: n_classes.
  @parameterized.named_parameters(
      ('Binary', 2),
      ('MultiClass 3', 3),
      ('MultiClass 4', 4),
  )
  def testCreateTPUEstimatorSpec(self, n_classes):
    """Tests that an Estimator built with a binary head works."""

    train_features, train_labels = test_utils.make_input_data(256, n_classes)
    feature_columns = []
    for key in train_features:
      feature_columns.append(tf.feature_column.numeric_column(key=key))

    head = head_lib._binary_logistic_or_multi_class_head(
        n_classes=n_classes,
        weight_column=None,
        label_vocabulary=None,
        loss_reduction=tf.compat.v1.losses.Reduction.NONE)
    optimizer = DPGradientDescentGaussianOptimizer(
        learning_rate=0.5,
        l2_norm_clip=1.0,
        noise_multiplier=0.0,
        num_microbatches=2)
    model_fn = make_model_fn(head, optimizer, feature_columns)
    classifier = tf.estimator.Estimator(model_fn=model_fn)

    classifier.train(
        input_fn=test_utils.make_input_fn(train_features, train_labels, True),
        steps=4)

    test_features, test_labels = test_utils.make_input_data(64, n_classes)
    classifier.evaluate(
        input_fn=test_utils.make_input_fn(test_features, test_labels, False),
        steps=4)

    predict_features, predict_labels = test_utils.make_input_data(64, n_classes)
    classifier.predict(
        input_fn=test_utils.make_input_fn(predict_features, predict_labels,
                                          False))

if __name__ == '__main__':
  tf.test.main()


from django.http import HttpResponse, JsonResponse
from .models import Weapon
from django.forms.models import model_to_dict
from .db_script import push_all_weapons

def weapon_search(request):
    weapon_list = request.GET.get('weapon')
    weapon_obj = request.GET.get('object')
    payload = list()

    if weapon_list:
        query_result = Weapon.objects.filter(name__icontains=weapon_list)

        for weapon_result in query_result:
            payload.append(weapon_result.name)
        return JsonResponse({'status':200, 'data' : payload})
    elif weapon_obj:
        try:
            query_result = Weapon.objects.get(name=weapon_obj)
        except Weapon.DoesNotExist:
            return JsonResponse({'status':404, 'data' : 'Weapon not found'})
        return JsonResponse({'status':200, 'data' : model_to_dict(query_result)})
    else:
        return JsonResponse({'status':404, 'data' : 'Weapon not found'})

def push_db(request):
    if not Weapon.objects.exists():
        push_all_weapons(push_db=True)
    return HttpResponse('')


# -*- coding: utf-8 -*-
"""
Created on Thu Feb 11 18:20:25 2021

@author: Tarandeep
"""

import pandas as pd
import glob
import os
#from tkinter.filedialog import askdirectory

"""
This function will take a folder of order lines from SAP and compile
It will return one final dataframe with pick frequency of each SKU
"""

def orderLineComp(orderLinesLocation):
    #filename = askdirectory()

    # ref: https://stackoverflow.com/questions/11295917/how-to-select-a-directory-and-store-the-location-using-tkinter-in-python
    # use your path
    # advisable to use os.path.join as this makes concatenation OS independent
    all_files = glob.glob(os.path.join(orderLinesLocation, "*.xlsx"))

    # for f in all_files:
    #    df_from_each_file = []
    #    df = pd.read_excel(f)
    #    df_from_each_file.append(df)
    #    print ("complete")

    print("Compiling Files...")
    df_from_each_file = (pd.read_excel(f) for f in all_files)
    concatenated_df = pd.concat(df_from_each_file, ignore_index=True)
    print("File Compilation Complete!")

    num_years = 2.0

    count_df = concatenated_df.groupby(
        ["Article"], as_index=False).size().reset_index(name='counts')
    count_df["average"] = round(count_df["counts"]/num_years, 0)
    return count_df


# -*- coding: utf-8 -*-
"""
Created on Wed Jun 13 11:07:08 2018

@author: Peeyush Goyal
"""

import pandas as pd
import matplotlib.pyplot as plt

data=pd.read_csv("crime_data.csv")
df=data.iloc[:,[1,2,4]]
"""from sklearn.preprocessing import LabelEncoder
labelencoder=LabelEncoder()
df["State"]=labelencoder.fit_transform(df["State"])

from sklearn.preprocessing import StandardScaler
sc=StandardScaler()
df=sc.fit_transform(df)
"""
from sklearn.decomposition import PCA
pca= PCA(n_components=2)
df= pca.fit_transform(df)

from sklearn.cluster import KMeans
"""wcss=[]
for i in range(3):
    kmeans=KMeans(n_clusters=i, init='k-means++',random_state=0)
    kmeans.fit(df)
    wcss.append(kmaens.inertia_)
"""
kmeans=KMeans(n_clusters=3, init='k-means++',random_state=0)
y_kmeans=kmeans.fit_predict(df)

plt.scatter(df[y_kmeans==0,0],df[y_kmeans==0,1],s=100,c='red')
plt.scatter(df[y_kmeans==1,0],df[y_kmeans==1,1],s=100,c='blue')
plt.scatter(df[y_kmeans==2,0],df[y_kmeans==2,1],s=100,c='green')
plt.legend()
plt.xlabel('Crimes')
plt.ylabel('cities')
plt.show()


import sys
import threading
from concurrent.futures import ThreadPoolExecutor

def dfs(vertex, vertex_adj, num, cut):
    num[vertex] = cut + 1
    for n in vertex_adj[vertex]:
        if not num[n]:
            dfs(n, vertex_adj, num, cut)

def main():
    # Input
    n, m = map(int, sys.stdin.readline().rstrip().split())
    my_dict = dict()
    num = [0 for i in range(n)]

    for i in range(0, n):
        my_dict[i] = set()
    for _ in range(0, m):
        a, b = map(int, sys.stdin.readline().rstrip().split())
        my_dict[a - 1].add(b - 1)
        my_dict[b - 1].add(a - 1)

    # Solve
    cut = 0
    for v in range(n):
        if not num[v]:
            dfs(v, my_dict, num, cut)
            cut += 1
    print(cut)
    print(*num)

if __name__ == '__main__':
    sys.setrecursionlimit(100000)
    threading.stack_size(100000000)

    with ThreadPoolExecutor(max_workers=1) as executor:
        future = executor.submit(main)
        future.result()


# -*- coding: utf-8 -*-
from sys import stdin
stdin = open("../../stdin.txt")
nonfat_ms, mfat = map(int, stdin.readline().split())
ms = nonfat_ms + mfat

if ms >= 15 and mfat >= 8:
    output = 1
elif ms >= 10 and mfat >= 3:
    output = 2
elif ms >= 3:
    output = 3
else:
    output = 4

print(output)


import os
from argparse import ArgumentParser
from ASRCAISim1.viewer.GodViewLoader import GodViewLoader

def parse_args():
    parser = ArgumentParser()
    parser.add_argument('--movie-dir', default='./log')
    parser.add_argument('--as-video', type=int, default=1)

    return parser.parse_args()

def main():
    args = parse_args()
    matches = os.listdir(args.movie_dir)
    for match in matches:
        ext = os.path.splitext(match)[-1]
        if ext == ".dat":
            print(match)
            loader=GodViewLoader({
                "globPattern":os.path.join(args.movie_dir, match),
                "outputPrefix":os.path.join(args.movie_dir, "movie"),
                "asVideo":args.as_video, # Trueだと動画(mp4)、Falseだと連番画像（png）として保存
                "fps":60
            })
            loader.run()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
"""
Created on Sun Dec  3 21:31:21 2017

@author: gxk19
"""

import matplotlib.pyplot as plt
import numpy as np

a=np.arange(10)

plt.ylabel('y')
plt.xlabel('x')
plt.title("Grade")

plt.plot(a,a*1,'go-',a,a*2,'rx',a,a*3,'*',a,a*4,'b-.')
plt.savefig("4",dpi=600)
plt.show()


H, W, K = map( int, input().split() )

grid = [ [ 0 ] * W for _ in range( H ) ]

c_dict = { "R" : 1, "D" : 2, "X": 3 }
for _ in range( K ):
    h, w, c = input().split()
    h, w = int( h ), int( w )
    grid[ h - 1 ][ w - 1 ] = c_dict[ c ]

# print( "\n".join( [ " ".join( grid[ h ] ) for h in range( H ) ] ) )

MOD = 998244353
inv = [ 1, 1 ]
fact = [ 1, 1 ]
inv_fact = [ 1, 1 ]
for k in range( 2, 4 ):
    inv_k = ( -inv[ MOD % k ] * ( MOD // k ) ) % MOD
    inv.append( inv_k )
    fact.append( fact[ -1 ] * k % MOD )
    inv_fact.append( inv_fact[ -1 ] * inv[ k ] % MOD )
inv3 = inv[ 3 ]

dp = [ [ 0 ] * W for _ in range( H ) ]
dp[ 0 ][ 0 ] = pow( 3, H * W - K, MOD )
for i in range( H ):
    for j in range( W ):
        c = grid[ i ][ j ]
        dp[ i ][ j ] %= MOD
        p = dp[ i ][ j ]
        if i < H - 1:
            if c == 0:
                dp[ i + 1 ][ j ] += p * 2 * inv3
            elif c == 3 or c == 2:
                dp[ i + 1 ][ j ] += p

        if j < W - 1:
            if c == 0:
                dp[ i ][ j + 1 ] += p * 2 * inv3
            elif c == 3 or c == 1:
                dp[ i ][ j + 1 ] += p

print( dp[ H - 1 ][ W - 1 ] )


class CircularQueue:

    def __init__(self, k: int):
        """
        Initialize your data structure here. Set the size of the queue to be k.
        """
        "print k"
        self.len = k
        self.currlen = 0
        self.queue = [None] * k
        self.head = -1
        self.tail = -1

    def enQueue(self, value: int):
        """
        Insert an element into the circular queue. Return true if the operation is successful.
        """
        if self.isFull():
            return False

        tail = (self.tail+1) % self.len
        self.queue[tail] = value
        self.tail = tail
        self.currlen += 1
        if self.currlen == 1:
            self.head = 0

        return True

    def deQueue(self) -> bool:
        """
        Delete an element from the circular queue. Return true if the operation is successful.
        """

        if self.isEmpty():
            return False

        self.head = (self.head+1) % self.len
        self.currlen -= 1
        if self.isEmpty():
            self.head = -1
            self.tail = -1

        return True

    def Front(self) -> int:
        """
        Get the front item from the queue.
        """
        if self.isEmpty():
            return -1

        return self.queue[self.head]

    def Rear(self) -> int:
        """
        Get the last item from the queue.
        """
        if self.isEmpty():
            return -1

        return self.queue[self.tail]

    def isEmpty(self) -> bool:
        """
        Checks whether the circular queue is empty or not.
        """
        return self.currlen == 0

    def isFull(self) -> bool:
        """
        Checks whether the circular queue is full or not.
        """
        return self.currlen == self.len

obj = CircularQueue(5)
param_1 = obj.enQueue(4)
print(param_1)
param_11 = obj.enQueue(5)
param_12 = obj.enQueue(6)
param_13 = obj.enQueue(3)
print(param_13)
param_2 = obj.deQueue()
print(param_2)
param_3 = obj.Front()
print(param_3)
param_4 = obj.Rear()
print(param_4)
param_5 = obj.isEmpty()
print(param_5)
param_6 = obj.isFull()
print(param_6)


import pandas as pd
import numpy as np
import random
import matplotlib.pyplot as plt

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def logistic_loss(y_true, y_pred):
    return - (y_true * np.log(y_pred) + (1 - y_true) * np.log(1 - y_pred))

def train_newton(X, y, theta):
    losses = []
    while True:
        p = np.array(sigmoid(X.dot(theta[:, 0])), ndmin=2).T
        W = np.diag((p * (1 - p))[:, 0])
        hessian = X.T.dot(W).dot(X)
        grad = X.T.dot(y - p)
        step = np.dot(np.linalg.inv(hessian), grad)

        if np.linalg.norm(grad) < 0.01:
            break
        theta = theta + step

        loss = logistic_loss(y, p)
        losses.append(loss[0])

    return losses

def train_gd(X, y, theta, learning_rate=0.001):
    losses = []
    while True:
        p = np.array(sigmoid(X.dot(theta[:, 0])), ndmin=2).T
        grad = X.T.dot(y - p)
        if np.linalg.norm(grad) < 0.1:
            break
        step = learning_rate * grad
        theta = theta + step

        loss = logistic_loss(y, p)
        losses.append(loss[0])

    return losses

def main():
    data = pd.read_csv("q4data.csv")

    X = data.iloc[:, :-1]
    y = data.iloc[:, -1]

    X = np.c_[np.ones((X.shape[0], 1)), X]
    y = y[:, np.newaxis]

    theta = np.zeros((4,1))

    gd_losses = train_gd(X, y, theta)
    newton_losses = train_newton(X, y, theta)

    fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

    ax1.plot(gd_losses, label="Gradient Descent Loss")
    ax1.set_xlabel("Iteration")
    ax1.set_ylabel("Loss")
    ax1.set_title("Gradient Descent")
    ax1.legend()

    ax2.plot(newton_losses, label="Newton's Method Loss")
    ax2.set_xlabel("Iteration")
    ax2.set_ylabel("Loss")
    ax2.set_title("Newton's Method")
    ax2.legend()

    plt.tight_layout()
    plt.show()

main()


import numpy as np
import cv2
import pygame
import time

# pygame color values
white = (255,255,255)
black = (0,0,0)

# establishing width and height for pygame screen
width = 800
height = 800

# establishing starting position for the ball
x_ball = width/2
y_ball = height/2

#initiating steps for ball
a = True
b, c, d, e, f, g = False, False, False, False, False, False

# initiating pygame
pygame.init()
screen = pygame.display.set_mode((width,height)) #creating screen
pygame.draw.circle(screen, white, (x_ball,y_ball), 5) #drawing ball
pygame.display.update()

#classifier for face detector
face_cascade = cv2.CascadeClassifier('/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml')

#starts video capture
cap = cv2.VideoCapture(0)

# Init video
ret, frame = cap.read()

faces = face_cascade.detectMultiScale(frame, scaleFactor=1.2, minSize=(20,20))
for (x,y,w,h) in faces:
	cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255))

# Display the resulting frame
cv2.imshow('frame',frame)

while(True):

	# update ball location
	screen.fill(black)
	pygame.draw.circle(screen, white, (x_ball,y_ball), 5)
	pygame.display.update()

	# Capture frame-by-frame
	ret, frame = cap.read()

	# Face detecting and drawing rectangle around face
	faces = face_cascade.detectMultiScale(frame, scaleFactor=1.2, minSize=(20,20))
	for (x,y,w,h) in faces:
		cv2.rectangle(frame,(x,y),(x+w,y+h),(0,0,255))

	# Display the resulting frame
	cv2.imshow('frame',frame)
	if cv2.waitKey(1) & 0xFF == ord('q'):
		break

	# move ball for next round
	if a:
		if x_ball < width:
			x_ball+= 1
		else:
			a =False
			b = True
	if b:
		if x_ball>0:
			x_ball-=1
		else:
			b = False
			c = True
	if c:
		if x_ball < width/2:
			x_ball+=1
		else:
			c= False
			d = True
	if d:
		if y_ball < height:
			y_ball+= 1
		else:
			d =False
			e = True
	if e:
		if y_ball>0:
			y_ball-=1
		else:
			d = False
			f = True
	if g:
		if y_ball < height/2:
			y_ball+=1
		else:
			g= False
			a = True

# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()


from mmengine import Config

from mmagic.registry import MODELS
from mmagic.utils import register_all_modules

import os
import torch
from pathlib import Path
import datetime
from mmagic.models.editors.animatediff import save_videos_grid

register_all_modules()

cfg = Config.fromfile('configs/animatediff/animatediff_ToonYou.py')
animatediff = MODELS.build(cfg.model).cuda()
prompts = ["(masterpiece, best quality), wasteland, wrecked train, moss, scenery, landscape, nature"
]

negative_prompts = [
    "worst quality, low quality, letterboxed",
    "badhandv4,easynegative,ng_deepnegative_v1_75t,verybadimagenegative_v1.3, bad-artist, bad_prompt_version2-neg, teeth",
    "",
    "",
]

sample_idx = 0
random_seeds = cfg.randomness['seed']
random_seeds = [random_seeds] if isinstance(random_seeds, int) else list(random_seeds)
samples = []
time_str = datetime.datetime.now().strftime("%Y-%m-%dT%H-%M-%S")
savedir = f"samples/{Path(cfg.model['dream_booth_lora_cfg']['type']).stem}-{time_str}"
os.makedirs(savedir)
for prompt_idx, (prompt, n_prompt, random_seed) in enumerate(zip(prompts, negative_prompts, random_seeds)):
    output_dict = animatediff.infer(prompt,negative_prompt=n_prompt, video_length=16, height=256, width=256, seed=random_seed,num_inference_steps=cfg.model['dream_booth_lora_cfg']['steps'])
    sample = output_dict['samples']
    prompt = "-".join((prompt.replace("/", "").split(" ")[:10]))
    save_videos_grid(sample, f"{savedir}/sample/{sample_idx}-{prompt}.gif")
    print(f"save to {savedir}/sample/{prompt}.gif")
    samples.append(sample)
    sample_idx += 1

samples = torch.concat(samples)
save_videos_grid(samples, f"{savedir}/sample.gif", n_rows=4)


# Loading useful libraries/packages
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from amplpy import AMPL,Environment

# Plotting the VMC capacity envelope
print('Plotting the VMC  and the IMC capacity envelopes...')
x_vmc = [0,17,24,28,28] # Intersecting points in x
y_vmc = [30,30,24,15,0] # Intersecting points in y
plt.plot(x_vmc,y_vmc)

# Plotting the IMC capacity envelope
x_imc = [0,12,17,20,20] # Intersecting points in x
y_imc = [22,22,17,11,0] # Intersecting points in y
plt.plot(x_imc,y_imc)
plt.legend(['VMC','IMC'])
plt.xlabel('Arrivals')
plt.ylabel('Departures')
plt.show()
print('Done.\n')

# Loading data
print('Loading data...')
demand_data = pd.read_excel("demand.xlsx", index_col = 0) # Demand information
print('Done.')

# Total number of time slots
N = len(demand_data)

# Arrival priority
alpha = 2

# Initial queue
a_0 = 0 # Initial arrival queue
d_0 = 0 # Initial departure queue

# Optimal values list
opt_values = []

# Optimization for different scenarios
episodes = 1000

for eps in range(episodes):

    a_t = a_0
    d_t = d_0
    z = 0
    arr = {}
    dep = {}
    plt.plot(x_vmc,y_vmc)
    plt.plot(x_imc,y_imc)
    plt.legend(['VMC','IMC'])
    plt.xlabel('Arrivals')
    plt.ylabel('Departures')

    for t in range(N):

        # Updating the demand queue
        a_t += demand_data['Arrival Demand'][t]
        d_t += demand_data['Departure Demand'][t]

        # Probability of IMC
        IMC_prob = demand_data['IMC Probability'][t]

        # Determining the current state
        wc = np.random.choice(['IMC','VMC'],p = [IMC_prob,1 - IMC_prob])

        # Determining the constraints
        p = []
        q = []
        r = []
        if wc == 'VMC':
            p.append(1)
            q.append(0)
            r.append(np.max(y_vmc))
            for i in range(1,len(x_vmc)-2):
                dy = y_vmc[i+1] - y_vmc[i]
                dx = x_vmc[i+1] - x_vmc[i]
                p.append(1)
                q.append(-dy/dx)
                r.append(y_vmc[i] - dy/dx*x_vmc[i])
            p.append(0)
            q.append(1)
            r.append(np.max(x_vmc))
        elif wc == 'IMC':
            p.append(1)
            q.append(0)
            r.append(np.max(y_imc))
            for i in range(1,len(x_imc)-2):
                dy = y_imc[i+1] - y_imc[i]
                dx = x_imc[i+1] - x_imc[i]
                p.append(1)
                q.append(-dy/dx)
                r.append(y_imc[i] - dy/dx*x_imc[i])
            p.append(0)
            q.append(1)
            r.append(np.max(x_imc))

        # Solving with AMPL
        ampl = AMPL(Environment(r'C:\Users\lucas\Desktop\ampl.mswin64'))
        ampl.eval(r"""
            param a_t;
            param d_t;
            param alpha;
            param p{i in 1..4};
            param q{i in 1..4};
            param r{i in 1..4};
            var u integer >= 0;
            var v integer >= 0;
            minimize delay:
                alpha*(a_t - u)^2 + (d_t - v)^2;
            s.t. c1:
                p[1]*v + q[1]*u <= r[1];
            s.t. c2:
                p[2]*v + q[2]*u <= r[2];
            s.t. c3:
                p[3]*v + q[3]*u <= r[3];
            s.t. c4:
                p[4]*v + q[4]*u <= r[4];
            s.t. c5:
                u <= a_t;
            s.t. c6:
                v <= d_t;
        """)
        ampl.param['alpha'] = alpha
        ampl.param['a_t'] = int(a_t)
        ampl.param['d_t'] = int(d_t)
        ampl.param['p'] = p
        ampl.param['q'] = q
        ampl.param['r'] = r
        ampl.option['solver'] = 'knitro'
        ampl.option['knitro_options'] = 'ms_enable=1 ms_num_to_save=5 ms_savetol=0.01 ms_maxsolves=10'
        ampl.solve()
        #assert ampl.get_value('solve_result') == 'solved'
        sol = ampl.get_value('alpha*(a_t - u)^2 + (d_t - v)^2')
        arr[t] = round(ampl.get_value('u'))
        dep[t] = round(ampl.get_value('v'))
        print('Optimal solution for episode '+str(eps+1)+', step '+str(t+1)+': '+str(round(sol,2))+', x = ['+str(arr[t])+', '+str(dep[t])+']')
        plt.plot(arr[t],dep[t],'o',color='grey')

        # Updating the queues
        a_t -= arr[t]
        d_t -= dep[t]

        # Calculating the total solution
        z += sol

    opt_values.append(round(z,2))
    print('Optimal value for episode '+str(eps+1)+': '+str(round(z,2)))
    plt.show()

# Plotting the results
plt.plot([i+1 for i in range(episodes)],opt_values,'o')
plt.plot([i+1 for i in range(episodes)],[round(np.average(opt_values),2) for i in range(episodes)],'--')
plt.xlabel('Episodes')
plt.ylabel('Delay/Cost')
plt.show()
print('Optimal value (average): '+str(round(np.average(opt_values),2)))


import db
from flask_restful import Resource
from utils import get_jwt, return_auth_err

class CurrentUser(Resource):
    def get(self):
        try:
            jwt = get_jwt()
            role = jwt['role']
            person_id = jwt['id']
        except Exception:
            return return_auth_err()
        if role in ['manager', 'admin']:
            manager = db.Manager.query \
                .filter(db.Manager.id == person_id) \
                .one_or_none()
            manager_schema = db.ManagerSchema()
            return manager_schema.dump(manager)
        elif role == 'student':
            student = db.Student.query \
                .filter(db.Student.id == person_id) \
                .one_or_none()
            student_schema = db.StudentSchema()
            return student_schema.dump(student)
        return None


""" Add pitch accent indicators to Anki cards.

    Below script makes use of data from Wadoku by Ulrich Apel.
    (See file wadoku_parse.py for more details.)
    Wadoku license information is available on the web:

    http://www.wadoku.de/wiki/display/WAD/Wörterbuch+Lizenz
    http://www.wadoku.de/wiki/display/WAD/%28Vorschlag%29+Neue+Wadoku-Daten+Lizenz
"""

import json
import re
import sqlite3
import sys
import time
from draw_pitch import pitch_svg
from util import select_deck, select_note_fields, get_note_ids

def get_accent_dict(path):
    acc_dict = {}
    with open(path) as f:
        for line in f:
            orths_txt, hira, hz, accs_txt, patts_txt = line.strip().split('\u241e')
            orth_txts = orths_txt.split('\u241f')
            if clean_orth(orth_txts[0]) != orth_txts[0]:
                orth_txts = [clean_orth(orth_txts[0])] + orth_txts
            patts = patts_txt.split(',')
            patt_common = patts[0]  # TODO: extend to support variants?
            if is_katakana(orth_txts[0]):
                hira = hira_to_kata(hira)
            for orth in orth_txts:
                if not orth in acc_dict:
                    acc_dict[orth] = []
                new = True
                for patt in acc_dict[orth]:
                    if patt[0] == hira and patt[1] == patt_common:
                        new = False
                        break
                if new:
                    acc_dict[orth].append((hira, patt_common))
    return acc_dict

def get_acc_patt(expr_field, reading_field, dicts):
    def select_best_patt(reading_field, patts):
        best_pos = 9001
        best = patts[0]  # default
        for patt in patts:
            hira, p = patt
            try:
                pos = reading_field.index(hira)
                if pos < best_pos:
                    best = patt
                    best_pos = pos
            except ValueError:
                continue
        return best
    expr_field = expr_field.replace('[\d]', '')
    expr_field = expr_field.replace('[^\d]', '')
    expr_field = expr_field.strip()
    for dic in dicts:
        patts = dic.get(expr_field, False)
        if patts:
            return select_best_patt(reading_field, patts)
        guess = expr_field.split(' ')[0]
        patts = dic.get(guess, False)
        if patts:
            return select_best_patt(reading_field, patts)
        guess = re.sub('[<&]', ' ', expr_field).split(' ')[0]
        patts = dic.get(guess, False)
        if patts:
            return select_best_patt(reading_field, patts)
    return False

def hira_to_kata(s):
    return ''.join(
        [chr(ord(ch) + 96) if ('ぁ' <= ch <= 'ゔ') else ch for ch in s]
        )

def is_katakana(s):
    num_ktkn = 0
    for ch in s:
        if ch == 'ー' or ('ァ' <= ch <= 'ヴ'):
            num_ktkn += 1
    return num_ktkn / max(1, len(s)) > .5

def clean_orth(orth):
    orth = re.sub('[()△×･〈〉{}]', '', orth)  #
    orth = orth.replace('…', '〜')  # change depending on what you use
    return orth

if len(sys.argv) < 2:
    print('usage: python3 anki_add_pitch.py /path/to/collection.anki2')
    sys.exit()

# load pitch data
print('loading pitch data')
acc_dict = get_accent_dict('wadoku_pitchdb.csv')
# with open('accdb.js', 'w') as f:
#     f.write(json.dumps(acc_dict))
# sys.exit()

# open Anki DB
coll_path = sys.argv[1]
conn = sqlite3.connect(coll_path)
c = conn.cursor()

# figure out collection structure
deck_id = select_deck(c, 'Which deck would you like to extend?')
note_ids = get_note_ids(c, deck_id)
expr_idx, reading_idx = select_note_fields(c, note_ids[0])

# extend notes
not_found_list = []
num_updated = 0
num_already_done = 0
num_svg_fail = 0
for nid in note_ids:
    row = c.execute('SELECT flds FROM notes WHERE id = ?', (nid,)).fetchone()
    flds_str = row[0]
    if '' in flds_str:
        # already has pitch accent image
        num_already_done += 1
        continue
    fields = flds_str.split('\x1f')
    expr_field = fields[expr_idx].strip()
    reading_field = fields[reading_idx].strip()
    patt = get_acc_patt(expr_field, reading_field, [acc_dict])
    if not patt:
        not_found_list.append([nid, expr_field])
        continue
    hira, LlHh_patt = patt
    LH_patt = re.sub(r'[lh]', '', LlHh_patt)
    svg = pitch_svg(hira, LH_patt)
    if not svg:
        num_svg_fail += 1
        continue
    fields[reading_idx] = (
        '{}

{}'
        ).format(fields[reading_idx], svg)  # add svg
    new_flds_str = '\x1f'.join(fields)
    mod_time = int(time.time())
    c.execute('UPDATE notes SET usn = ?, mod = ?, flds = ? WHERE id = ?',
              (-1, mod_time, new_flds_str, nid))
    num_updated += 1
conn.commit()

print('\n- - - done - - -')
print('skipped {} already annotated notes'.format(num_already_done))
print('updated {} notes'.format(num_updated))
print('failed to generate {} annotations'.format(num_svg_fail))
print('could not find {} expressions'.format(len(not_found_list)))
if len(not_found_list) > 0:
    with open('not_found_{}'.format(int(time.time())), 'w') as f:
        for nid, expr in not_found_list:
            f.write('{}: {}\n'.format(nid, expr))


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

import gettext
import config
import web

translations = web.storage()
supported_languages = ['ko', 'en', 'ru']
def get_translations(lang='ko'):
    if translations.has_key(lang):
        translation = translations[lang]
    elif lang is None:
        translation = gettext.NullTranslations()
    else:
        try:
            translation = gettext.translation('messages',
                    config.i18n_path, languages=[lang],)
        except IOError:
            translation = gettext.NullTranslations()
    return translation

def load_translations(lang):
    lang = str(lang)
    translation = translations.get(lang)
    if translation is None:
        translation = get_translations(lang)
        translations[lang] = translation

        for lk in translations.keys():
            if lk != lang:
                del translations[lk]
    return translation

def get_language():
    # 로그인한 경우에는 사용자가 선호하는 언어로 변경.
    # 로그인하지 않은 경우에는 Accept-Language 헤더의 가장 높은 q 언어를 사용.
    # 둘 다 해당하지 않으면 한국어.
    lang_header = ''
    lang = web.ctx.session.get('lang')
    if lang:
        return lang
    try:
        lang_header = web.ctx.environ.get('HTTP_ACCEPT_LANGUAGE')
        lang_header = [x.split(';q=') for x in lang_header.split(',')]
        for x in lang_header:
            if len(x) == 1:
                x.append(1)
            else:
                x[1] = float(x[1])
        lang_header.sort(key = lambda x: x[1], reverse = True)
        ret = lang_header[0][0]
        if ret in supported_languages:
            return ret
        if ret[0:ret.find('-')] in supported_languages:
            return ret[0:ret.find('-')]
        return lang
    except:
        pass
    return 'ko'

def custom_gettext(string):
    translation = load_translations(get_language())
    if translation is None:
        return unicode(string)
    return translation.ugettext(string)

def custom_ngettext(single, plural, n):
    translation = load_translations(get_language())
    if translation is None:
        if n:
            return unicode(plural)
        return unicode(single)
    return translation.ungettext(single, plural, n)


import random
import re
import time
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.keys import Keys

from Board import Board

class WebOperator(object):
    def __init__(self):
        options = Options()
        options.add_argument("--disable-notifications")#--headless
        self.chrome = webdriver.Chrome('./chromedriver', chrome_options=options)
        self.chrome.get("https://play2048.co/")
        self.newNum = {2: 0, 4: 0}

    def IsGameOver(self):
        isGameOver=self.chrome.find_elements_by_css_selector(".game-over")
        return True if len(isGameOver)>0 else False

    def ResetGame(self):
        restartButton=self.chrome.find_element_by_css_selector(".restart-button")
        restartButton.click()

    def GetScore(self):
        scoreInfo = self.chrome.find_element_by_css_selector(".score-container")
        matches = re.match(r".*", scoreInfo.text)
        return (matches.group(0))

    def GetRawInfo(self):
        rawInfo = self.chrome.find_elements_by_css_selector(".tile-container .tile")
        return rawInfo

    def GetBoardInfo(self):
        rawInfo = self.GetRawInfo()
        board = Board()
        for r in rawInfo:
            className = str(r.get_attribute("class"))
            matches = re.match(r"tile tile-(?P<num>\d+) tile-position-(?P<px>\d)-(?P<py>\d)( (?P<misc>.+))?", className)
            misc = ""
            if matches.group("misc") is not None:
                misc = str(matches.group("misc"))
                if "tile-new" == misc:
                    self.newNum[int(matches.group("num"))] += 1
            # print(misc)
            board.title[int(matches.group("py")) - 1][int(matches.group("px")) - 1] = int(matches.group("num"))
        return board

    def RandomMove(self):
        d = random.randint(0, 4)
        actions = ActionChains(self.chrome)
        if (0 == d):
            actions.send_keys(Keys.ARROW_UP).perform()
        elif (1 == d):
            actions.send_keys(Keys.ARROW_DOWN).perform()
        elif (2 == d):
            actions.send_keys(Keys.ARROW_LEFT).perform()
        elif (3 == d):
            actions.send_keys(Keys.ARROW_RIGHT).perform()

    def Move(self,cmd):
        actions = ActionChains(self.chrome)
        if ("UP" == cmd):
            actions.send_keys(Keys.ARROW_UP).perform()
        elif ("DOWN" == cmd):
            actions.send_keys(Keys.ARROW_DOWN).perform()
        elif ("LEFT" == cmd):
            actions.send_keys(Keys.ARROW_LEFT).perform()
        elif ("RIGHT" == cmd):
            actions.send_keys(Keys.ARROW_RIGHT).perform()

        #

if __name__ == "__main__":
    webOperator = WebOperator()
    i = 0
    while ("Game over!" not in webOperator.chrome.page_source):
        time.sleep(1)
        webOperator.GetBoardInfo()
        webOperator.RandomMove()
        i += 1
    print(webOperator.newNum)


import os
import torch

import torch.optim as optim
import matplotlib.pyplot as plt

from tqdm import tqdm
from torch.nn import BCEWithLogitsLoss
from torch.optim.lr_scheduler import CosineAnnealingLR

from torch.nn import functional as F

def mkdict(state_dict, model_dict, vocab, validation_losses, epoch, optimizer, scheduler=None):
    ''' makes a simple dictionary of the given inputs '''
    out = {
        'state_dict': state_dict,
        'model_dict': model_dict,
        'vocab': vocab,
        'validation_losses': validation_losses,
        'epoch': epoch,
        'optimizer': optimizer,
        'scheduler': scheduler,
    }
    return out

def mkdir_model(model_name):
    ''' makes the necessary folders for saving the model states '''
    models_dir = './trained_models'
    pth_dir = os.path.join(models_dir, model_name)
    if not os.path.isdir(models_dir):
        os.mkdir(models_dir)
    if not os.path.isdir(pth_dir):
        os.mkdir(pth_dir)

def train_model(model_list: list, train_loader, valid_loader, vocab, device, criterion=None, optimizer=None, scheduler=None, epoch=100, epoch_s=0, lr=1e-3, patience=30):
    ''' trains a model '''

    # extracting model and model name
    model = model_list[0]
    model_name = model_list[1]

    # extracting model information
    model_dict = {
            'lstm_layers': model.LSTM_layers,
            'hidden_dim': model.hidden_dim,
            'embedding_dim': model.embedding_dim,
            'vocab_size': model.input_size,
            'num_classes': model.num_classes,
            'batch_size': model.batch_size
            }

    # transferring model to the given device
    model = model.to(device)

    # initializing values
    stale = 0
    best_valid_loss = 10000
    break_point = 0

    # initializing optimizer, scheduler and the criterion
    if not optimizer:
        optimizer = optim.RAdam(model.parameters(), lr=lr)
    if not scheduler:
        scheduler = CosineAnnealingLR(optimizer, T_max=epoch)
    if not criterion:
        criterion = BCEWithLogitsLoss()

    # making required folders
    mkdir_model(model_name)

    # creating lists of losses to return
    Loss_list = []
    Valid_Loss_list = []
    learning_rate_list = []

    # iterating epochs
    for i in range(epoch_s, epoch):
        # training
        print(f'TRAINING [{i + 1:03d}/{epoch:03d}]')
        model.train()
        train_losses = []

        for _, batch in enumerate(tqdm(train_loader)):
            inputs, labels = batch
            outputs = model(inputs.to(device))

            loss = criterion(labels.to(device), outputs)
            optimizer.zero_grad()
            loss.backward()
            optimizer.step()
            train_losses.append(loss.item())

        train_loss = sum(train_losses) / len(train_losses)
        Loss_list.append(train_loss)
        print(f"\t[ Train | {i + 1:03d}/{epoch:03d} ] Loss = {train_loss:.5f}")

        scheduler.step()
        for param_group in optimizer.param_groups:
            learning_rate_list.append(param_group["lr"])
            print('\tlearning rate %f' % param_group["lr"])

    # validation
        print(f'VALIDATION [{i + 1:03d}/{epoch:03d}]')
        model.eval()
        valid_losses = []
        for batch in tqdm(valid_loader):
            inputs, labels = batch

            with torch.no_grad():
                outputs = model(inputs.to(device))
                loss = criterion(outputs, labels.to(device))
            valid_losses.append(loss.item())

        valid_loss = sum(valid_losses) / len(valid_losses)
        Valid_Loss_list.append(valid_loss)

        break_point = i + 1

        # checking model performance and saving improvements
        if valid_loss < best_valid_loss:
            print(f"\t[ Valid | {i + 1:03d}/{epoch:03d} ]", end=' ')
            print(f"Loss = {valid_loss:.5f} -> New best performance!")
            print(
                f"\t\tSaving this model in './trained_models/{model_name}/best_model.pth'")

            net = mkdict(model.state_dict(), model_dict, vocab,  Valid_Loss_list,
                         epoch, optimizer, scheduler)
            torch.save(net, f'trained_models/{model_name}/best_model.pth')

            best_valid_loss = valid_loss
            stale = 0
        else:
            print(f"\t[ Valid | {i + 1:03d}/{epoch:03d} ]", end=' ')
            print(f"Loss = {valid_loss:.5f}")
            stale += 1
            if stale > patience:
                print(
                    f'\n\t\t[No improvement for {patience} consecutive epochs, stopping early.]')
                break

        # saving the latest model
        net = mkdict(model.state_dict(), model_dict, vocab, Valid_Loss_list,
                     epoch, optimizer, scheduler)
        torch.save(net, f'trained_models/{model_name}/last_model.pth')

    result = {
        'break_point': break_point,
        'Valid_Loss_list': Valid_Loss_list,
        'learning_rate_list': learning_rate_list,
        'Loss_list': Loss_list,
    }

    return result

def keep_keys(dictionary, keys):
    ''' removes any unnecessary keys from the given dictionary '''
    d = {}
    for key in keys:
        d[key] = dictionary[key]
    return d

def plot_loss(break_point, Valid_Loss_list, learning_rate_list, Loss_list):
    ''' plots the evaluations of our training '''

    plt.figure(dpi=500)

    plt.subplot(311)
    x = range(break_point)
    y = Loss_list
    plt.plot(x, y, 'ro-', label='Train Loss')
    plt.ylabel('Train Loss')
    plt.xlabel('epochs')

    plt.subplot(312)
    plt.plot(range(break_point), Valid_Loss_list, 'bs-', label='Valid Loss')
    plt.ylabel('Validation Loss')
    plt.xlabel('epochs')

    plt.subplot(313)
    plt.plot(x, learning_rate_list, 'ro-', label='Learning rate')
    plt.ylabel('Learning rate')
    plt.xlabel('epochs')

    plt.legend()
    plt.show()

def model_inference(model, input, device, thresh=.5):
    model = model.to(device)
    model.eval()

    with torch.no_grad():
        output = model(input.to(device))
        output = F.sigmoid(output)
        labels = (output > thresh).type(torch.int)
    return labels


import numpy as np
import scipy
from typing import Callable, Optional
from .methods import InducingPointInitializer

class RLS(InducingPointInitializer):
    """
    Implements a modified version of the "fixed size" variant of the (approximate)
    RLS algorithm given in Musco and Musco 2017
    @inproceedings{musco2017recursive,
                   title={Recursive sampling for the nystrom method},
                   author={Musco, Cameron and Musco, Christopher},
                   booktitle={Advances in Neural Information Processing Systems},
                   pages={3833--3845},
                   year={2017}
                   }
    """

    def __init__(self, seed: Optional[int] = 0, **kwargs):
        super().__init__(seed=seed, randomized=True, **kwargs)

    def compute_initialisation(self, training_inputs: np.ndarray, M: int,
                               kernel: Callable[[np.ndarray, Optional[np.ndarray], Optional[bool]], np.ndarray]):
        indices, _, _ = recursive_rls(training_inputs, M, kernel, np.arange(training_inputs.shape[0]))
        return training_inputs[indices], indices

def approximate_rls(training_inputs, kernel, regularization, subset_to_predict, subset_used, column_weights):
    X = training_inputs[subset_to_predict]
    Z = training_inputs[subset_used]
    regularization_matrix = np.diag(np.square(1. / column_weights) * regularization)
    regularized_Kuu = kernel(Z) + regularization_matrix
    L = np.linalg.cholesky(regularized_Kuu)
    kuf = kernel(Z, X)
    Linvkuf = scipy.linalg.solve_triangular(L, kuf, lower=True)
    posterior_variance = kernel(X, full_cov=False) - np.sum(np.square(Linvkuf), axis=0)

    return 1 / regularization * posterior_variance

def get_indices_and_weights(weighted_leverage, active_indices, k, top_level, M):
    probs = np.minimum(1., weighted_leverage * np.log(2*k))
    if not top_level:
        random_nums = np.random.rand(len(probs))
        indices = np.where(random_nums < probs)[0]
        # in cases where to few (potentially no) weights are sampled
        num_additional_indices = M - len(indices)
        if num_additional_indices > 0:
            candidate_indices = np.where(random_nums >= probs)[0]
            additional_indices = np.random.choice(candidate_indices, size=num_additional_indices,
                                                  replace=False)
            indices = np.append(indices, additional_indices)
        indices_to_include = active_indices[indices]
        column_weights = np.sqrt(1. / probs[indices])
    else:
        probs = probs * M / np.sum(probs)
        random_nums = np.random.rand(len(probs))
        indices_to_include = active_indices[random_nums < probs]
        column_weights = np.sqrt(1. / probs[random_nums < probs])
        # If we sample too few inducing points, resample
        while len(indices_to_include) < M:
            random_nums = np.random.rand(len(probs))  # resample if not enough
            indices_to_include = active_indices[random_nums < probs]
            column_weights = np.sqrt(1. / probs[random_nums < probs])
            probs = np.clip(probs * M / np.sum(np.clip(probs, 0, 1)), 0, 1)
            probs *= 1.01
        inds = np.random.choice(len(indices_to_include), size=M, replace=False)
        indices_to_include, column_weights = indices_to_include[inds], column_weights[inds]
    return indices_to_include, column_weights, probs

def recursive_rls(training_inputs: np.ndarray,
                  M: int,
                  kernel: Callable[[np.ndarray, Optional[np.ndarray], Optional[bool]], np.ndarray],
                  active_indices: np.ndarray):
    num_data = training_inputs.shape[0]
    top_level = len(active_indices) == num_data   # boolean indicating we are at top level of recursion
    c = .25
    k = np.minimum(num_data, int(np.ceil(c * M / np.log(M+1))))

    if len(active_indices) <= M:  # Base case of recursion, see l 1,2 in Musco and Musco, alg 3
        return active_indices, np.ones_like(active_indices), np.ones_like(active_indices)
    s_bar = np.random.randint(0, 2, len(active_indices)).nonzero()[0]  # points sampled into Sbar, l4
    if len(s_bar) == 0:
        active_indices = np.random.choice(active_indices, (1+len(active_indices))//2, replace=False)
        return active_indices, np.ones_like(active_indices), np.ones_like(active_indices)

    indices_to_include, column_weights, probs = recursive_rls(training_inputs, M, kernel,
                                                              active_indices=active_indices[s_bar])
    Z = training_inputs[indices_to_include]
    SKS = kernel(Z) * column_weights[None, :] * column_weights[:, None]  # sketched kernel matrix
    eigvals = scipy.sparse.linalg.eigsh(SKS.numpy(), k=k, which='LM', return_eigenvectors=False)

    lam = 1 / k * (np.sum(np.diag(SKS)) - np.sum(eigvals))
    lam = np.maximum(1e-12, lam)

    weighted_leverage = approximate_rls(training_inputs, kernel, lam, subset_to_predict=active_indices,
                                        subset_used=indices_to_include, column_weights=column_weights)
    indices_to_include, column_weights, probs = get_indices_and_weights(weighted_leverage, active_indices, k,
                                                                        top_level, M)

    return indices_to_include, column_weights, probs


# coding:utf8
"""
参考django进行日志配置, 利用LOGGERS来添加日志配置
"""

import logging
import logging.config
import os

BASE_DIR = os.path.dirname(os.path.dirname(os.path.realpath(__file__)))
# 是否DEBUG
DEBUG = False

# 日志配置
LOGGING = {
    'version': 1,
    'disable_existing_loggers': True,
    'formatters': {
        'verbose': {
            'format': ("%(levelname)s %(asctime)s %(module)s "
                       "%(filename)s:%(lineno)s "
                       "%(process)d %(thread)d %(message)s")
        },
    },
    'filters': {},
    'handlers': {},
    'loggers': {},
}

# 自定义 Logger 配置, 之后可以在代码的任何地方添加如下代码进行日志记录:
# my_logger = logging.getLogger('name-1')
# my_logger.error('message')
LOGGERS = ["common", "error", "info"]
for name in LOGGERS:
    handler = {
        'level': 'INFO',
        # 利用TimedRotatingFileHandler来按照日期切割
        'class': 'logging.handlers.TimedRotatingFileHandler',
        'filename': os.path.join(BASE_DIR, 'logs/%s.log' % name),
        'formatter': 'verbose',
        'when': 'M',
    }
    logger = {
        'handlers': [name],
        'level': 'INFO',
        'propagate': True,
    }
    LOGGING['handlers'][name] = handler
    LOGGING['loggers'][name] = logger

# 是否开启调试
if DEBUG:
    LOGGING['handlers']['console'] = {
        'level': 'DEBUG',
        'class': 'logging.StreamHandler',
        'formatter': 'verbose'
    }
    for logger in LOGGING['loggers']:
        LOGGING['loggers'][logger]['handlers'] = ['console']

# 启动配置
logging.config.dictConfig(LOGGING)
logger_error = logging.getLogger('error')
logger_info = logging.getLogger('info')


# System imports
from distutils.core import setup

# Version number
major = 0
minor = 1

setup(name="waterscape",
      version = "{0}.{1}".format(major, minor),
      description = """
      An adjointable multiple-network poroelasticity solver
      """,
      author = "Eleonora Piersanti, Marie E. Rognes",
      author_email = "eleonora@simula.no",
      packages = ["mpet"],
      package_dir = {"mpet": "mpet"},
      )


def menu():
    menu_opcoes = """
    [1] Álcool
    [2] Gasolina
    [3] Sair

    """
    return input(menu_opcoes)

def abastecer_gasolina(litros):
    GASOLINA_ESTOQUE = 1000
    gasolina_preco = 5.2

    if litros <= GASOLINA_ESTOQUE:
        valor = litros * gasolina_preco
        GASOLINA_ESTOQUE -= litros

        print(f'Abastecido com sucesso! Valor a pagar: R${valor}')

    else:
        print('Desculpe, não há gasolina suficiente no estoque.')

def abastecer_alcool(litros):
    ALCOOL_ESTOQUE = 800
    alcool_preco = 4.8

    if litros <= ALCOOL_ESTOQUE:
        valor = litros * alcool_preco
        ALCOOL_ESTOQUE -= litros
        print(f'Abastecido com sucesso! Valor a pagar: R$ {valor}')
    else:
        print('Desculpe, não há álcool suficiente no estoque.')

def main():
    while True:
        opcao = menu()

        if opcao == '1':
            litros = int(input('Informe a quantidade de litros que deseja colocar: '))

            litros = abastecer_alcool(litros)

        elif opcao == '2':
            litros = int(input('Informe a quantidade de litros que deseja colocar: '))

            litros = abastecer_gasolina(litros)

        elif opcao == '3':
            break

        else:
            print('Informe uma opção existente!')

main()


import pygame

from tilegamelib.basic_boxes import ImageBox
from tilegamelib.config import config
from tilegamelib.event_listener import AnyKeyListener, TextEnteringListener
from tilegamelib.events import EventGenerator
from tilegamelib.frame import Frame
from tilegamelib.vector import Vector

class HighscoreList:
    """Model for the highscores."""
    def __init__(self, filename, length=10):
        self.filename = filename
        self.length = length
        self.scores = []
        self.load_scores()

    def load_scores(self):
        self.scores = []
        for line in open(self.filename):
            score, name = line.strip().split()
            self.scores.append((int(score), name))

    def write_scores(self):
        out = []
        for score, name in self.scores:
            out.append('%i\t%s\n' % (score, name))
        open(self.filename, 'w').writelines(out)

    def is_in_highscores(self, score):
        """Returns true if the given score gets into the list."""
        if score > self.scores[-1][0]:
            return True

    def insert_entry(self, name, score):
        if name.strip() == '':
            name = 'ANONYMOUS'
        self.scores.append((score, name))
        self.scores.sort()
        self.scores.reverse()
        self.scores = self.scores[:self.length]
        self.write_scores()

class HighscoreBox:
    """
    View for high scores.
    This class manages entering names
    and storing the high scores in a file.
    """
    def __init__(self, frame, egen, highscores, highscore_image, textpos):
        """
        frame - Frame instance
        egen - EventGenerator instance
        """
        self.frame = frame
        self.egen = egen

        self.textpos = Vector(textpos)
        self.highscores = highscores
        self.image = ImageBox(frame, highscore_image)

        # for entering new entries
        self.entering = False
        self.name = ""
        self.score = 0

    def draw(self):
        """Draws the highscore list."""
        self.image.draw()
        i = 0
        for score, name in self.highscores.scores:
            y_offset = i * 30
            text = "%8i - %s" % (score, name)
            self.frame.print_text(text, self.textpos + Vector(0, y_offset),
                    config.DEMIBOLD_BIG, config.BLUE)
            i += 1
        if self.entering:
            self.frame.print_text("High Score! Please enter your name:",
                    self.textpos + Vector(0, y_offset + 50),
                    config.DEMIBOLD_BIG, config.BLUE)
            self.frame.print_text(self.name,
                    self.textpos + Vector(0, y_offset + 80),
                    config.DEMIBOLD_BIG, config.BLUE)

    def enter_score(self, score):
        """
        If the given score fits into the list,
        a name will be requested.
        """
        if self.highscores.is_in_highscores(score):
            self.entering = True
            self.entered_score = score
            self.text = ''

    def entered(self, text):
        self.name = text

    def update(self):
        self.draw()
        pygame.display.update()

    def done(self, text=None):
        self.entering = False
        self.egen.listeners = []

    def activate(self):
        self.egen.add_callback(self)
        if self.entering:
            # add new score
            elis = TextEnteringListener(self.entered, self.done)
            self.egen.add_listener(elis)
            self.egen.event_loop()
            self.highscores.insert_entry(self.name, self.entered_score)
        # display highscores and wait for a key
        elis = AnyKeyListener(self.done)
        self.egen.add_listener(elis)
        self.egen.event_loop()
        self.egen.remove_listener(elis)
        self.egen.remove_callback(self)

def show_highscores(new_score, screen, rect, filename, image, textpos):
    """
    Display high score list and gets a name if the score is high enough.
    """
    screen.clear()
    frame = Frame(screen, rect)
    events = EventGenerator()
    hs = HighscoreList(filename)
    hs = HighscoreBox(frame, events, hs, image, textpos)
    hs.enter_score(new_score)
    hs.activate()
    screen.clear()
    pygame.display.update()


from PyQt5.QtWidgets import QApplication, QWidget, QInputDialog, QLineEdit, QFileDialog

class dialogsGUI(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'Choose File'
        self.left = 10
        self.top = 10
        self.width = 640
        self.height = 480
        self.initUI()

    def initUI(self):
        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)

    def openFileNameDialog(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getOpenFileName(self, "Open File", "",
                                                  "PCAP (*.pcap);;PCAPNG (*.pcapng)", options=options)
        self.hide()
        return fileName,_

    def saveFileDialog(self):
        options = QFileDialog.Options()
        fileName, _ = QFileDialog.getSaveFileName(self, "Save As", "",
                                                  "PCAP (*.pcap);;PCAPNG (*.pcapng)", options=options)
        self.hide()
        return fileName,_


def solve(arr):
    from collections import Counter

    def smallest_set(start, end, counter):
        d = {start - 1: []}
        for i in range(start, end + 1):
            d[i] = []
            prev_len = len(d[i - 1])
            new_lists = counter[i] - prev_len
            if new_lists > 0:
                d[i] = [1] * new_lists
            if prev_len > 0:
                num_appends = min(prev_len, new_lists + prev_len)
                d[i - 1].sort()
                d[i] += [j + 1 for j in d[i - 1][:num_appends]]
                d[i - 1] = d[i - 1][num_appends:]
        ans = d[end][0]
        for i in range(start, end + 1):
            if len(d[i]) > 0:
                ans = min(ans, min(d[i]))
                if ans == 1:
                    return 1
        return ans

    def find_lowest_range(a, start):
        counter = Counter(a)
        i = 0
        res = start
        while i < len(a):
            end = i
            while end < start and (a[i] == a[end] or (a[end] - a[end - 1]) <= 1):
                end += 1
            end -= 1
            if end == i:
                return 1
            res = min(res, smallest_set(a[i], a[end], counter))
            if res == 1:
                return 1
            i = end + 1
        return res

    if arr[0] == 0:  # For some weird reason 0 is a value
        return 0
    first = arr[0]
    new_arr = sorted(arr[1:])
    return find_lowest_range(new_arr, first)

if __name__ == '__main__':
    t = int(input())
    for _ in range(t):
        x = list(map(int, input().split()))
        print(solve(x))


import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
# With DFS

n = int(input())
board = [list(map(int, input().split())) for _ in range(n)]
Min = min([min(board[i]) for i in range(n)])
Max = max([max(board[i]) for i in range(n)])
answer = 0
moves = [[0, 1], [1, 0], [0, -1], [-1, 0]]
isVisited = [[None] * n for _ in range(n)]

def dfs(p):
    cnt = 0

    def search(i, j, p):
        global isVisited
        isVisited[i][j] = True
        for r, c in moves:
            row, col = r+i, c+j
            if 0 <= row < n and 0 <= col < n and not isVisited[row][col] and board[row][col] > p:
                search(row, col, p)
        return

    for i in range(n):
        for j in range(n):
            if board[i][j] > p and not isVisited[i][j]:
                cnt += 1
                search(i, j, p)
    return cnt
    # i마다 dfs를 돌아 안전한 영역의 개수를 찾는다.

for p in range(Max+1):
    answer = max(answer, dfs(p))
    isVisited = [[None] * n for _ in range(n)]
print(answer)


import os
import base64

# import mock while in development/debug mode
if ("DEBUGMODE" in os.environ):
  import sys
  import fake_rpi
  sys.modules['picamera'] = fake_rpi.picamera
else:
  from picamera import PiCamera

class CameraModule:

  """
  CameraModule class interfaces camera component and includes:
  - functionality to capture with specifications
  - get base64 format of the image
  """

  def __init__(self, resolution="MAX", rotate=0, capturefile="capture.jpg"):
    self.camera = PiCamera()

    # check for resolution
    if (resolution == "MAX"):
      self.camera.resolution = self.camera.MAX_RESOLUTION
    elif (type(resolution) is tuple):
      self.camera.resolution = resolution
    else:
      raise ValueError("invalid resolution value supplied. expecting MAX or tuple of (width, height) value in pixels")

    # check for rotate value
    if (type(rotate) is not int):
      raise ValueError("value of rotate must be int")
    elif(rotate < 0 or rotate > 360):
      raise ValueError("value of rotate must be between 0 and 360")
    else:
      self.camera.rotation = rotate

    # check for capturefile
    if((type(capturefile) is not str)):
      raise ValueError("check the value of capturefile")
    elif(not capturefile.endswith(".jpg") and not capturefile.endswith(".png")):
      raise ValueError("capturefile extension must be either .png or .jpg")
    else:
      self.capturefile = capturefile

  # method to capture from camera
  def capture(self, capturefile=None):
    if(capturefile is None):
      capturefile = self.capturefile

    self.camera.capture(capturefile)

  # method to get base64 form of the captured image
  def get_base64_image(self):
    return str(base64.b64encode(open(self.capturefile,"rb").read()).decode("ascii"))

  # method to close and cleanup camera resource
  def cleanup(self):
    self.camera.close()


# Написати програму, яка виводить сама себе

# Так же добавил encoding 3-м параметром в ф-ю open() чтобы небыло крякозябликов
# P.S. прогр. работает и в таком виде (как было дано в лекции)
# f = open(filename, 'r')

import sys
filename = sys.argv[0]
# далі відкриваємо файл для читання (опція 'r')
f = open(filename, 'r', encoding='utf-8') # в файлі тепер file descriptor
for line in f: # для кожного рядка у файлі
	print(line)
f.close() # закриття файлу

HW #3/1. Practic/2. A program that prints itself/progr_display_itself(1).py


def canSum(n, list, memo={}):
	if n in memo: return memo[n]
	if n == 0: return True
	if n < 0: return False

	for i in list:
		target = n - i
		if canSum(target, list, memo) == True:
			memo[n] = True
			return True
	memo[n] = False
	return False

print(canSum(300, [3, 5]))


n = int(input())
s = input()
cnt1, cnt2, cnt3 = 0, 0, 0
s = s[::-1]

for el in s:
	if el == 'E':
		cnt1 += 1
	if el == 'S':
		cnt2 += cnt1
	if el == "H":
		cnt3 += cnt2

print(cnt3)


import re

pattern = r"(\w+):(\d+)"
s = "张:2018,李:2019"

# #直接用re调用
# l=re.findall(pattern,s)
# print(l)

#compile 对象调用
regex = re.compile(pattern,)
l = regex.findall(s,pos=0,endpos=8)
print(l)

#split用法
l = re.split(r'\s+','Hello   world   nihao  Kitty')
print(l)

#sub用法
s = re.sub(r'\s+','##','hello world    nihao Kitty',2)
print(s)

#subn用法
s = re.subn(r'\s+','##','hello world    nihao Kitty',2)
print(s)