from typing import Callable, Iterable, List, Optional, Protocol, Sequence, Tuple, Union
import manim as mn
import numpy as np

PointType = Union[Sequence[float], np.ndarray]
PointTransformFunction = Callable[[PointType], PointType]

class SpaceManager(Protocol):

  def get_mobjects(self) -> List[mn.Mobject]:
    ...

  def anime_apply_function_to_plane(
      self, func: PointTransformFunction) -> List[mn.Animation]:
    ...

class Basic2DSpaceManager:
  background_plane: mn.NumberPlane
  plane: mn.NumberPlane

  def __init__(self,
               background_plane: Optional[mn.NumberPlane] = None,
               plane: Optional[mn.NumberPlane] = None):
    if background_plane is None:
      background_plane = mn.NumberPlane(
          color=mn.GRAY,
          axis_config={
              'color': mn.GRAY,
          },
          background_line_style={
              'stroke_color': mn.GRAY,
              'stroke_width': 1,
          },
      )
      background_plane.add_coordinates()

    if plane is None:
      plane = mn.NumberPlane(
          x_range=np.array([-10, 10, 1.0]),
          y_range=np.array([-10, 10, 1.0]),
          faded_line_ratio=1,
      )

    self.background_plane = background_plane
    self.plane = plane

  def get_mobjects(self) -> List[mn.Mobject]:
    return [
        self.background_plane,
        self.plane,
    ]

  def anime_apply_function_to_plane(
      self, func: PointTransformFunction) -> List[mn.Animation]:
    new_plane = self.plane.copy()
    new_plane.apply_function(func)
    return [mn.Transform(self.plane, new_plane)]

class Basic3DSpaceManager:
  background_space: mn.ThreeDAxes

  def __init__(self, background_space: Optional[mn.ThreeDAxes] = None):
    if background_space is None:
      background_space = mn.ThreeDAxes(
          num_axis_pieces=1,
          axis_config={
              'color': mn.GRAY,
              'unit_size': 1,
              'numbers_with_elongated_ticks': [0, 1, 2],
              'stroke_width': 2,
          },
      )
      background_space.add_coordinates()

    self.background_space = background_space

  def get_mobjects(self) -> List[mn.Mobject]:
    return [
        self.background_space,
    ]

  def anime_apply_function_to_plane(
      self, func: PointTransformFunction) -> List[mn.Animation]:
    _ = func
    return []

class LabelManager(Protocol):

  def get_label(self) -> List[mn.Mobject]:
    ...

  def anime_apply_matrix(
      self,
      matrix: np.ndarray,
      matrix_display: Iterable | None = None,
  ) -> Tuple[List[mn.Animation], List[mn.Animation]]:
    '''return: (create_matrix_animes, apply_matrix_animes)
    '''

class Label2DManager:
  xy_label: mn.Matrix

  def __init__(self, label: mn.Matrix | None = None):
    if label is None:
      label = mn.Matrix(
          [['x'], ['y']],
          left_bracket='(',
          right_bracket=')',
      )
    self.xy_label = label
    self.xy_label.to_corner(mn.RIGHT + mn.UP)

  def get_label(self):
    return [self.xy_label]

  def anime_apply_matrix(self,
                         matrix: np.ndarray,
                         matrix_display: Iterable | None = None):
    matrix_mobject = mn.Matrix(
        matrix_display if matrix_display else matrix,
        left_bracket='(',
        right_bracket=')',
    ).next_to(self.xy_label, mn.LEFT)
    create_anime = mn.Write(matrix_mobject)
    created_label = mn.Group(matrix_mobject, self.xy_label)
    apply_anime = mn.Transform(created_label, self.xy_label)
    self.xy_label = created_label
    return [create_anime], [apply_anime]

class Label3DManager:
  xyz_label: mn.Matrix
  camera_inv_matrix: np.ndarray

  def __init__(self,
               camera_rotation_matrix: np.ndarray,
               label: mn.Matrix | None = None):
    self.camera_inv_matrix = np.linalg.inv(camera_rotation_matrix)
    if label is None:
      label = mn.Matrix(
          [['x'], ['y'], ['z']],
          left_bracket='(',
          right_bracket=')',
      )
    self.xyz_label = label
    self.xyz_label.to_corner(mn.RIGHT + mn.UP)
    self.xyz_label.apply_matrix(self.camera_inv_matrix)

  def get_label(self):
    return [self.xyz_label]

  def anime_apply_matrix(self,
                         matrix: np.ndarray,
                         matrix_display: Iterable | None = None):
    matrix_mobject = mn.Matrix(
        matrix_display if matrix_display else matrix,
        left_bracket='(',
        right_bracket=')',
    )
    fake_label = self.xyz_label.copy()
    fake_label.apply_matrix(np.linalg.inv(self.camera_inv_matrix))
    matrix_mobject.next_to(fake_label, mn.LEFT)
    matrix_mobject.apply_matrix(self.camera_inv_matrix)
    # matrix_mobject.next_to(self.xyz_label, self.camera_inv_matrix @ mn.LEFT)
    create_anime = mn.Create(matrix_mobject)

    created_label = mn.Group(matrix_mobject, self.xyz_label)
    apply_anime = mn.Transform(created_label, self.xyz_label)
    self.xyz_label = created_label

    return [create_anime], [apply_anime]

class LinearTransformManager:
  space_manager: SpaceManager
  moving_vectors: List[mn.Vector] = []
  transformable_mobjects: List[mn.Mobject] = []

  def __init__(self, dimension: int):
    if dimension == 2:
      self.space_manager = Basic2DSpaceManager()
    elif dimension == 3:
      self.space_manager = Basic3DSpaceManager()
    else:
      raise ValueError('Dimension must be 2 or 3')

  def setup(self) -> List[mn.Mobject]:
    return self.space_manager.get_mobjects()

  def add_vector(self, vector: List | np.ndarray, color=mn.RED):
    v = mn.Vector(vector, color=color)
    self.moving_vectors.append(v)
    return v

  def add_transformable_mobject(self, mobject: mn.Mobject):
    self.transformable_mobjects.append(mobject)
    return mobject

  def anime_apply_matrix(self, matrix: np.ndarray):
    f = self.get_matrix_apply_function(matrix)
    animes = [
        *self.anime_apply_function_to_plane(f),
        *self.anime_apply_function_to_vector(f),
        *self.anime_apply_function_to_moving_mobjects(f),
    ]
    return animes

  def anime_apply_function_to_vector(self, func: PointTransformFunction):
    new_vectors = [
        mn.Vector(func(v.get_end()), color=v.color) for v in self.moving_vectors
    ]
    return [
        mn.Transform(old_v, new_v)
        for (old_v, new_v) in zip(self.moving_vectors, new_vectors)
    ]

  def anime_apply_function_to_plane(self, func: PointTransformFunction):
    return self.space_manager.anime_apply_function_to_plane(func)

  def anime_apply_function_to_moving_mobjects(self,
                                              func: PointTransformFunction):
    return [
        mn.ApplyPointwiseFunction(func, mobj)
        for mobj in self.transformable_mobjects
    ]

  def get_matrix_apply_function(self,
                                matrix: np.ndarray) -> PointTransformFunction:
    if matrix.shape == (2, 2):
      new_matrix = np.identity(3)
      new_matrix[:2, :2] = matrix
      matrix = new_matrix

    if matrix.shape == (3, 3):
      return lambda p: matrix @ p

    if matrix.shape == (4, 4):

      def func(p):
        point_4d = np.append(p, 1)
        point_4d = matrix @ point_4d
        return np.array(point_4d[:3]) / point_4d[3]

      return func

    raise ValueError('Matrix has bad dimensions')

class BasicLinearSpaceScene(mn.ThreeDScene):

  mobj_manager: LinearTransformManager
  label_manager: LabelManager

  def setup(self):
    self.mobj_manager = LinearTransformManager(2)
    default_mobj = self.mobj_manager.setup()
    self.add(*default_mobj)
    self.label_manager = Label2DManager()
    # label_group = mn.VGroup(label)
    self.add(*self.label_manager.get_label())

  def play_2d_to_3d(self):
    '''animate 2d space to 3d space, moving xy plane to w = 1
    '''
    old_2d_space = self.mobj_manager.space_manager
    old_2d_label = self.label_manager
    assert isinstance(old_2d_space, Basic2DSpaceManager)
    assert isinstance(old_2d_label, Label2DManager)

    self.mobj_manager.space_manager = Basic3DSpaceManager()
    self.mobj_manager.add_transformable_mobject(old_2d_space.plane)
    new_axis_animes = [
        mn.Create(axis_mobj)
        for axis_mobj in self.mobj_manager.space_manager.get_mobjects()
    ]

    f = self.mobj_manager.get_matrix_apply_function(
        np.array([
            [1, 0, 0, 0],
            [0, 1, 0, 0],
            [0, 0, 1, 1],
            [0, 0, 0, 1],
        ]))
    animes = [
        *new_axis_animes,
        mn.FadeOut(old_2d_space.background_plane),
        *self.mobj_manager.anime_apply_function_to_vector(f),
        *self.mobj_manager.anime_apply_function_to_moving_mobjects(f),
    ]
    self.move_camera(
        phi=2 * mn.PI / 5, theta=-mn.PI / 3, run_time=2, added_anims=animes)

    self.label_manager = Label3DManager(self.camera.get_rotation_matrix())
    new_xyz_label = self.label_manager.xyz_label

    self.play(mn.Transform(old_2d_label.xy_label, new_xyz_label), run_time=1)
    self.label_manager.xyz_label = old_2d_label.xy_label

  def add_vector(self, vector: List | np.ndarray, color=mn.RED):
    vector_mobjs = self.mobj_manager.add_vector(vector, color=color)
    self.add(*vector_mobjs)

  def add_transformable_mobject(self, mobjects: mn.Mobject):
    res_mobjs = self.mobj_manager.add_transformable_mobject(mobjects)
    self.add(*res_mobjs)

  def apply_matrix(self,
                   matrix: np.ndarray,
                   matrix_display: Optional[Iterable] = None):
    '''play anime for applying matrix to mobjects

    1. create matrix label
    2. apply matrix to mobjects and combine matrix label
    '''
    (create_label_anime,
     apply_label_anime) = self.label_manager.anime_apply_matrix(
         matrix, matrix_display)

    # create matrix label
    self.play(*create_label_anime, run_time=0.5)
    self.wait(0.5)

    # apply matrix to mobjects and combine matrix label
    apply_matrix_animes = self.mobj_manager.anime_apply_matrix(matrix)
    self.play(
        *apply_matrix_animes,
        *apply_label_anime,
        run_time=0.5,
    )
    self.wait(0.5)

class OnOneLineWillStillOneLine(BasicLinearSpaceScene):
  '''图：在同一直线上的点，经过同一线性变换后还在同一直线上
  '''

  def add_vectors_on_line(self, line_fn: Callable[[int], int], start_x: int,
                          end_x: int, color: str):
    to_point = lambda x: [x, line_fn(x)]
    for x in range(start_x, end_x):
      self.add_vector(to_point(x), color=color)

    vec_line = mn.Line(
        start=[*to_point(-10), 0], end=[*to_point(10), 0], color=color)
    self.add_transformable_mobject(vec_line)

  def construct(self):
    self.add_vectors_on_line(lambda x: 2, -1, 3, mn.RED)
    self.add_vectors_on_line(lambda x: x - 2, -1, 3, mn.GREEN)

    matrix1 = np.array([[2, -1], [0, 1]])
    self.apply_matrix(matrix1)

    matrix2 = np.array([[1 / 2, 1 / 2], [-1 / 2, 1 / 2]])
    self.apply_matrix(matrix2)

    matrix3 = np.linalg.inv(matrix2 @ matrix1)
    self.apply_matrix(matrix3)

class SliceScaleRotateForOrigin(BasicLinearSpaceScene):
  '''动图：切边、伸缩、旋转以及其逆变换变回原样
  '''

  def construct(self):
    self.add_vector([1, 0], color=mn.RED)
    self.add_vector([0, 1], color=mn.GREEN)

    matrix1 = np.array([[1, 1], [0, 1]])
    self.apply_matrix(matrix1)
    self.apply_matrix(np.linalg.inv(matrix1))

    matrix2 = np.array([[2, 0], [0, 1 / 2]])
    self.apply_matrix(matrix2)
    self.apply_matrix(np.linalg.inv(matrix2))

    angle = np.pi / 3
    matrix3 = np.array([[np.sin(angle), -np.cos(angle)],
                        [np.cos(angle), np.sin(angle)]])
    self.apply_matrix(
        matrix3,
        matrix_display=[[r'\frac{\sqrt{3}}{2}', r'-\frac{1}{2}'],
                        [r'\frac{1}{2}', r'\frac{\sqrt{3}}{2}']])
    self.apply_matrix(
        np.linalg.inv(matrix3),
        matrix_display=[[r'\frac{\sqrt{3}}{2}', r'\frac{1}{2}'],
                        [r'-\frac{1}{2}', r'\frac{\sqrt{3}}{2}']])

class HomogeneousTransform(BasicLinearSpaceScene):
  '''图：三位坐标w=1平面，三角形
  '''

  def construct(self):
    # ax = mn.ThreeDAxes()
    # lab = ax.get_z_axis_label(mn.Tex('$z$-label'))
    # self.set_camera_orientation(phi=0, theta=-mn.PI / 2)
    triangle = mn.Polygon([-2, 0, 0], [2, 0, 0], [0, 2, 0], color=mn.RED)
    self.add_transformable_mobject(triangle)
    self.play_2d_to_3d()
    self.add_vector([0, 0, 1], color=mn.GREEN)
    self.apply_matrix(np.array([[1, 0, 1], [0, 1, 0], [0, 0, 1]]))
    self.apply_matrix(np.array([[1, 0, -1], [0, 1, -1], [0, 0, 1]]))
    self.apply_matrix(np.array([[1, 0, 0], [0, 1, 1], [0, 0, 1]]))

class SliceOnHomogeneousWithGraph(BasicLinearSpaceScene):
  '''图：还是三维空间上切变，平面上有图案
  '''

  def construct(self):
    circle = mn.Circle(
        radius=1, color=mn.RED).move_to([2, -2, 0]).set_fill(
            color=mn.RED_C, opacity=0.5)
    triangle = mn.Polygon([-2, 0, 0], [-1, 0, 0], [-2, 1, 0],
                          color=mn.GREEN).set_fill(
                              color=mn.GREEN_C, opacity=0.5)
    square = mn.Polygon([2, 2, 0], [2, 1, 0], [3, 1, 0], [3, 2, 0],
                        color=mn.BLUE).set_fill(
                            color=mn.BLUE_C, opacity=0.5)
    star = mn.Star(color=mn.PURPLE).move_to([-2, -2, 0]).set_fill(
        color=mn.PURPLE_C, opacity=0.5)
    self.add_transformable_mobject(circle)
    self.add_transformable_mobject(triangle)
    self.add_transformable_mobject(square)
    self.add_transformable_mobject(star)
    self.play_2d_to_3d()
    self.add_vector([0, 0, 1], color=mn.GREEN)
    self.apply_matrix(np.array([[1, 0, 1], [0, 1, 0], [0, 0, 1]]))
    self.apply_matrix(np.array([[1, 0, -1], [0, 1, -1], [0, 0, 1]]))
    self.apply_matrix(np.array([[1, 0, 0], [0, 1, 1], [0, 0, 1]]))


"""
Application: Agent Simulation
Author: Roy Burgess
Date : 09/07/2023
"""

import pygame as pg
from random import randint, uniform
from operator import sub

vec = pg.math.Vector2

WANDER_CIRCLE_DIST = 150
WANDER_CIRCLE_RADIUS = 50
ARRIVE_RADIUS = 50
FLEE_DISTANCE = 50

class Agent(pg.sprite.Sprite):
    """Class to describe an agent."""
    def __init__(self, pos, size, colour, speed, force, state, bounds, type,wb):
        self.pos = pos
        self.size = size
        self.colour = colour
        self.max_speed = speed
        self.max_force = force
        self.acceleration = vec(0, 0)
        self.vel = vec(1, 0).rotate(uniform(0, 360))
        self.rect = pg.Rect(pos,(size,size))
        self.state = state
        self.bounds = bounds
        self.type = type
        self.wb = wb

    def seek(self, target):
        self.desired = tuple(map(sub,target,self.pos))
        self.desired = vec(self.desired)
        self.desired = self.desired.normalize() * self.max_speed
        steer = (self.desired - self.vel)
        if steer.length() > self.max_force:
            steer.scale_to_length(self.max_force)
        self.acceleration += steer
        self.update()

    def arrive(self, target):
        self.desired = tuple(map(sub,target,self.pos))
        self.desired = vec(self.desired)
        dist = self.desired.length()
        self.desired.normalize_ip()
        if dist < ARRIVE_RADIUS:
            self.desired *= dist / ARRIVE_RADIUS * self.max_speed
        else:
            self.desired *= self.max_speed
        steer = (self.desired - self.vel)
        if steer.length() > self.max_force:
            steer.scale_to_length(self.max_force)
        self.acceleration += steer
        self.update()

    def flee(self, target):
        # Create a new vector from the target to overcome the vector subtraction
        # problem.
        d = vec(target[0], target[1])
        dist = (self.pos - d)
        if dist.length() < FLEE_DISTANCE and dist.length() > 0:
            self.desired = dist.normalize() * self.max_speed
        else:
            self.desired = self.vel.normalize() * self.max_speed
        steer = (self.desired - self.vel)
        if steer.length() > self.max_force:
            steer.scale_to_length(self.max_force)
        self.acceleration += steer
        self.update()

    def wander(self):
        future = self.pos + self.vel.normalize() * WANDER_CIRCLE_DIST
        target = future + vec(WANDER_CIRCLE_RADIUS, 0).rotate(uniform(0, 360))
        self.seek(target)

    def sense(self, things):
        for thing in things:
            if not thing == self:
                if thing.type == "Worker" and self.type == "Grazer":
                    dist = (self.rect.center + vec(FLEE_DISTANCE,FLEE_DISTANCE)) - (thing.rect.center + vec(FLEE_DISTANCE,FLEE_DISTANCE))
                    if dist.length() < FLEE_DISTANCE:
                        self.state = "Flee"
                        self.flee(thing.rect.center)
                    else:
                        self.state = "Wander"
                if thing.type =="Resource":
                    if self.type == "Worker" or self.type == "Grazer":
                        dist = (self.rect.center + vec(FLEE_DISTANCE,FLEE_DISTANCE)) - (thing.rect.center + vec(FLEE_DISTANCE,FLEE_DISTANCE))
                        if dist.length() < 50:
                            self.seek(thing.pos)

    def detect_collision(self, obsticles):
        for obsticle in obsticles:
            if self != obsticle and self.rect.colliderect(obsticle.rect):
                if obsticle.type == "Grazer" and self.type == "Worker":
                    obsticle.state = "Dead"
                elif obsticle.type == "Resource":
                    obsticle.number -= 1
                    if self.type == "Grazer":
                        self.flee(obsticle.rect.center)
                    elif self.type == "Worker":
                        self.target = self.wb
                        self.arrive(self.wb)
                        self.state = "Arrive"
                elif obsticle.type == "WB" and self.type == "Worker":
                    self.target = None
                    self.state = "Wander"
                else:
                    if self.acceleration.x > 0:
                        self.rect.right = obsticle.rect.left
                    if self.acceleration.x < 0:
                        self.rect.left = obsticle.rect.right
                    if self.acceleration.y > 0:
                        self.rect.bottom = obsticle.rect.top
                    if self.acceleration.y < 0:
                        self.rect.top = obsticle.rect.bottom
                    self.pos = self.rect.center

    def update(self):
        self.vel += self.acceleration
        if self.acceleration.length() == 0:
            self.vel.scale_to_length(self.max_speed)
        if self.vel.length() > self.max_speed:
            self.vel.scale_to_length(self.max_speed)

        self.pos += self.vel

        # Update the rectangle position
        self.rect.center = self.pos

        # Keep the agent within the window
        if self.rect.right > self.bounds[0]:
            self.rect.right = self.bounds[0]
            self.pos = self.rect.center
        if self.rect.left <= 0:
            self.rect.left = 1
            self.pos = self.rect.center
        if self.rect.bottom > self.bounds[1]:
            self.rect.bottom = self.bounds[1]
            self.pos = self.rect.center
        if self.rect.top <= 0:
            self.rect.top = 1
            self.pos = self.rect.center


#!/usr/bin/env python3
"""mapper.py"""

import sys
lno = 0
matrices = []
m1 = 0
m2 = 0
m = 0
n = 0
p = 0
mat1 = []
mat2 = []
inp = []
for line in sys.stdin:
    line = line.strip()
    line = list(map(int, line.split()))
    if(line[-1] == 0):
        for i in range(line[1]):
            it = "A "+str(line[3])+" "+str(line[4])
            st = str(line[2]).zfill(4)+" "+str(i).zfill(4)
            print('%s\t%s' % (st, it))
    else:
        for i in range(line[0]):
            it = "B "+str(line[2])+" "+str(line[4])
            st = str(i).zfill(4)+" "+str(line[3]).zfill(4)
            # if(i==82):
            print('%s\t%s' % (st, it))


# -*- coding=utf8 -*-
"""
    公共模块：生成训练数据，画曲线...
"""

import numpy as np
import sklearn.datasets
import matplotlib.pyplot as plt

np.random.seed(0)
data, model = sklearn.datasets.make_moons(200, noise=0.30)

def gen_train_data():
    """生成训练数据"""
    global data, model
    return data, model

def plot_decision_boundary(predict_func, data, label):
    """画出结果图

    Args:
        pred_func (callable): 预测函数
        data (numpy.ndarray): 训练数据集合
        label (numpy.ndarray): 训练数据标签
    """
    x_min, x_max = data[:, 0].min() - .5, data[:, 0].max() + .5
    y_min, y_max = data[:, 1].min() - .5, data[:, 1].max() + .5
    h = 0.01

    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))

    Z = predict_func(np.c_[xx.ravel(), yy.ravel()])
    Z = Z.reshape(xx.shape)

    plt.contourf(xx, yy, Z, cmap=plt.cm.Spectral)
    plt.scatter(data[:, 0], data[:, 1], c=label, cmap=plt.cm.Spectral)
    plt.show()

# if __name__ == '__main__':
#     import sklearn.linear_model
#
#     X, y = gen_train_data()
#     clf = sklearn.linear_model.LogisticRegressionCV()
#     clf.fit(X, y)
#     plot_decision_boundary(lambda x: clf.predict(x), X, y)


from django.shortcuts import render, get_object_or_404, redirect
from django.http import HttpResponseRedirect
from django.db import connection

from django.contrib.auth import login, authenticate, logout

def dictfetchall(cursor):
    "Return all rows from a cursor as a dict"
    columns = [col[0] for col in cursor.description]
    return [dict(zip(columns, row)) for row in cursor.fetchall()]

def fetch_students():
    students = connection.cursor()
    students.cursor.execute(
        """SELECT a.root, s.student_id, a.photo, u.first_name, u.last_name, s.current_year, s.major, a.gender, a.address, a.date_of_birth, a.phone, u.email, s.status
            FROM accounts_CustomUser u
            INNER JOIN accounts_UserAttributes a ON CAST(a.root AS INT) = u.id
            INNER JOIN accounts_Student s ON s.root = u.id
            WHERE u.user_type = 'student'
            Order By u.id Desc
        """
    )
    return dictfetchall(students)

def fetch_notifications(className):
    notifications = connection.cursor()
    notifications.cursor.execute(
        """SELECT  an.date, an.notification_title, an.notification_rating, an.notify_class, an.assignment
            FROM lecturers_AssignmentNotification an
            WHERE an.notify_class = %s
        """,
        [className],
    )
    notification_list = dictfetchall(notifications)
    total_notifications = len(notification_list)
    return notification_list, total_notifications

def fetch_lessons(user_id):
    lesson_allocation = connection.cursor()
    lesson_allocation.cursor.execute(
        """SELECT  ol.course_name, ol.online_title, ol.lesson_date, ol.lesson_start_time, ol.lesson_end_time, ol.lecturer, ol.online_platform_link
            FROM classes_OnlineLesson ol
            WHERE ol.course_name = %s
            Order By ol.id Desc
        """,
        [user_id],
    )
    lesson_allocation = dictfetchall(lesson_allocation)
    total_lesson_allocations = len(lesson_allocation)
    return lesson_allocation, total_lesson_allocations


import nltk
import re
from colorama import Fore, Back, Style,init
from termcolor import colored, cprint

# _________________  (colors)  ____________________
def prRed(skk): print("\033[91m {}\033[00m" .format(skk))
def prGreen(skk): print("\033[92m {}\033[00m" .format(skk))
def prYellow(skk): print("\033[93m {}\033[00m" .format(skk))
def prLightPurple(skk): print("\033[94m {}\033[00m" .format(skk))
def prPurple(skk): print("\033[95m {}\033[00m" .format(skk))
def prCyan(skk): print("\033[96m {}\033[00m" .format(skk))
def prLightGray(skk): print("\033[97m {}\033[00m" .format(skk))
def prBlack(skk): print("\033[98m {}\033[00m" .format(skk))

intro="""

   _____                              _____ _       _
  / ____|                            / ____(_)     | |
 | |     __ _  ___  ___  __ _ _ __  | |     _ _ __ | |__   ___ _ __
 | |    / _` |/ _ \/ __|/ _` | '__| | |    | | '_ \| '_ \ / _ \ '__|
 | |___| (_| |  __/\__ \ (_| | |    | |____| | |_) | | | |  __/ |
  \_____\__,_|\___||___/\__,_|_|     \_____|_| .__/|_| |_|\___|_|
                                             | |
                                             |_|

"""

def encrypt(text, key):
    test_list = []
    alpha = 'a'
    for i in range(0, 26):
        test_list.append(alpha)
        alpha = chr(ord(alpha) + 1)
    # print (test_list)

    regex = r"[A-z]+"

    matches = re.findall(regex,text)
    # print(separator.join(matches))# abc  acb
    # print(matches)   #  ['abc', 'acb']

    # num = key % 26
    # one_word_result =[]
    final_text_result =[]

    for single_word in matches:
        one_word=''
        for char in single_word.lower():
            index = test_list.index(char)
            index += key
            # index = index % 26
            new_index = index % 26

            # new_index=num+index
            # one_word_result.append(test_list[new_index])
            one_word+=test_list[new_index]
        final_text_result.append(one_word)

    # return final_text_result   #[bcd, fgh]

    new_word=' '.join(final_text_result)
    return new_word #bcd fgh

# ________________________________________

def decrypt(text, key):
    test = []
    alpha = 'a'
    for i in range(0, 26):
        test.append(alpha)
        alpha = chr(ord(alpha) + 1)
    test_list =test[::-1]

    regex = r"[A-z]+"
    matches = re.findall(regex,text)

    final_text_result =[]
    for single_word in matches:
        one_word=''
        for char in single_word.lower():
            index = test_list.index(char)
            index += key
            new_index = index % 26
            one_word+=test_list[new_index]
        final_text_result.append(one_word)

    new_word=' '.join(final_text_result)
    return new_word

 # ________________________________________
 #DEMO
nltk.download('words')

original_words_list = nltk.corpus.words.words()
words_list = [word.lower() for word in original_words_list]

 # ________________________________________

def count_words(sentence):
    sentence_words = sentence.split()
    en_word_count = 0

    for word in sentence_words:
        if word.lower() in words_list:
            en_word_count += 1

    return en_word_count

 # ________________________________________

def most_likely(sentences):
    _max = 0
    _max_sentence = ''

    for sentence in sentences:
        if count_words(sentence) > _max:
            _max_sentence = sentence
            _max = count_words(sentence)
    return _max_sentence

## ____________________________________________________

if __name__ == "__main__":
#   print(encrypt('It was the best of times, it was the worst of times.', 1))#ju xbt uif cftu pg ujnft ju xbt uif xpstu pg ujnft

  prCyan(intro)

  assert encrypt('abc', 1)=='bcd'
  prYellow(f"encrypt'abc'----> {encrypt('abc', 1)}")
  prPurple('='*50)
# ___________________________________
  assert encrypt('acb', 10)=='kml'
  prYellow(f"encrypt'acb'----> {encrypt('acb', 10)}")
  prPurple('='*50)
# ___________________________________

  assert decrypt('bcd', 1)=='abc'
  prGreen(f"decrypt'bca'----> {decrypt('bcd', 1)}")
  prPurple('='*50)
# ___________________________________

  assert encrypt('ABC::,   ,EfG::', 1)=="bcd fgh"
  prGreen(f"encrypt'ABC::,   ,EfG::'----> {encrypt('ABC::,   ,EfG::', 1)}")
  prPurple('='*50)
# ___________________________________

  assert decrypt('BcD::,   ,fGh::', 1)=="abc efg"
  prGreen(f"decrypt'BcD::,   ,fGh::''----> {decrypt('BcD::,   ,fGh::', 1)}")
  prPurple('='*50)

  # ++++++++++++++++++++++++++
  #prepare data for most_likely test
  sentence = 'It was the best of times, it was the worst of times.'
  test_sentences=[]
  for i in range(1,27):
        test_sentences.append(encrypt(sentence, i))
  print(test_sentences)

  for i in range(len(test_sentences)):
        print(count_words(test_sentences[i]))
  # ++++++++++++++++++++++++++

  assert most_likely(test_sentences)=="it was the best of times it was the worst of times"
  prCyan(f"most_likely ----> {most_likely(test_sentences)}")
  prPurple('='*50)
  prRed('All tests passed!!!!')


import random

# function to draw board
def drawBoard(board):
    print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])
    print('-----------')
    print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])
    print('-----------')
    print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])

# function to take input from user
def inputPlayerLetter():
    letter = ''
    while not (letter == 'X' or letter == 'O'):
        print('Do you want to be X or O?')
        letter = input().upper()
    if letter == 'X':
        return ['X', 'O']
    else:
        return ['O', 'X']

# randomly decide who goes first
def whoGoesFirst():
    if random.randint(0, 1) == 0:
        return 'computer'
    else:
        return 'player'

# restart game?
def playAgain():
    print('Do you want to play again? (yes or no)')
    return input().lower().startswith('y')

# reflect move on board
def makeMove(board, letter, move):
    board[move] = letter

# decide who is the winner
def isWinner(bo, le):
    return ((bo[7] == le and bo[8] == le and bo[9] == le) or        # top row
    (bo[4] == le and bo[5] == le and bo[6] == le) or                # middle row
    (bo[1] == le and bo[2] == le and bo[3] == le) or                # bottom row
    (bo[7] == le and bo[4] == le and bo[1] == le) or                # left column
    (bo[8] == le and bo[5] == le and bo[2] == le) or                # middle column
    (bo[9] == le and bo[6] == le and bo[3] == le) or                # right column
    (bo[7] == le and bo[5] == le and bo[3] == le) or                # diagonal from top-left
    (bo[9] == le and bo[5] == le and bo[1] == le))                  # diagonal form top-right

# copy board
def getBoardCopy(board):
    dupeBoard = []
    for i in board:
        dupeBoard.append(i)
    return dupeBoard

# check which space is free
def isSpaceFree(board, move):
    return board[move] == ' '

# get which move player chooses
def getPlayerMove(board):
    move = ' '
    while move not in '1 2 3 4 5 6 7 8 9'.split() or not isSpaceFree(board, int(move)):
        print('What is your next move? (1-9)')
        move = input()
    return int(move)

# choose a random move from the remaining
def chooseRandomMoveFromList(board, movesList):
    possibleMoves = []
    for i in movesList:
        if isSpaceFree(board, i):
            possibleMoves.append(i)
    if len(possibleMoves) != 0:
        return random.choice(possibleMoves)
    else:
        return None

# decide a move for the computer based on empty spaces and the user's moves
def getComputerMove(board, computerLetter):
    if computerLetter == 'X':
        playerLetter = 'O'
    else:
        playerLetter = 'X'
    for i in range(1, 10):
        copy = getBoardCopy(board)
        if isSpaceFree(copy, i):
            makeMove(copy, computerLetter, i)
            if isWinner(copy, computerLetter):
                return i
    for i in range(1, 10):
        copy = getBoardCopy(board)
        if isSpaceFree(copy, i):
            makeMove(copy, playerLetter, i)
            if isWinner(copy, playerLetter):
                return i
    move = chooseRandomMoveFromList(board, [1, 3, 7, 9])
    if move != None:
        return move
    if isSpaceFree(board, 5):
        return 5
    return chooseRandomMoveFromList(board, [2, 4, 6, 8])

# check if board is full - its a tie
def isBoardFull(board):
    for i in range(1, 10):
        if isSpaceFree(board, i):
            return False
    return True

print('Welcome to Tic Tac Toe!')

# main game
while True:
    theBoard = [' '] * 10
    playerLetter, computerLetter = inputPlayerLetter()
    turn = whoGoesFirst()
    print('The ' + turn + ' will go first.')
    gameIsPlaying = True
    while gameIsPlaying:
        # player's turn
        if turn == 'player':
            drawBoard(theBoard)
            move = getPlayerMove(theBoard)
            makeMove(theBoard, playerLetter, move)
            if isWinner(theBoard, playerLetter):
                drawBoard(theBoard)
                print('Hooray! You have won the game!')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('The game is a tie!')
                    break
                else:
                    turn = 'computer'

        # computer's turn
        else:
            move = getComputerMove(theBoard, computerLetter)
            makeMove(theBoard, computerLetter, move)
            if isWinner(theBoard, computerLetter):
                drawBoard(theBoard)
                print('The computer has beaten you! You lose.')
                gameIsPlaying = False
            else:
                if isBoardFull(theBoard):
                    drawBoard(theBoard)
                    print('The game is a tie!')
                    break
                else:
                    turn = 'player'

    # if user dont wabt to continue - stop the game
    if not playAgain():
        break


import tensorflow as tf

import keras
from keras.layers import Input, Conv2D, Flatten, Dense
from keras.layers import Reshape, Concatenate, Add
from keras.models import Model
import random
import keras.layers as layers
import sherpa
import sys

import numpy as np
import os
import matplotlib.pyplot as plt
#from ssim_loss import *

from keras.initializers import Initializer, Constant
import keras.backend as K

os.environ["CUDA_VISIBLE_DEVICES"]="2"

class AlphaInit(Initializer):
    def __init__(self, alpha, **kwargs):
        super(AlphaInit, self).__init__(**kwargs)
        self.constant = alpha
    def __call__(self):
        return K.constant(self.constant)

class Mult(layers.Layer):
    def __init__(self, init, **kwargs):
        super(Mult, self).__init__(**kwargs)
        self.init = init

    def build(self, input_shape):
        output_dim = input_shape
        if self.init == "constant":
            self.kernel = self.add_weight(
                shape=[1],
                initializer=Constant(0.5),
                name="kernel",
                trainable=True,
            )
        else:
            self.kernel = self.add_weight(
                shape=[1],
                initializer=keras.initializers.get("he_normal"),
                name="kernel",
                trainable=True,
            )
    def call(self, inputs):
        out = inputs*self.kernel
        return out

    def get_config(self):
        # Implement get_config to enable serialization. This is optional.
        config = super(Mult, self).get_config()
        config.update({"init": self.init})
        return dict(list(config.items()))

def build_model(ssim=False):
    """
    Build Keras model with different hyperparameters
    """

    input_prev = Input(shape=(48, 48, 1))

    input_next = Input(shape=(48, 48, 1))

    x_prev = Mult("he")(input_prev)
    x_next = Mult("he")(input_next)

    h = Add()([x_prev, x_next])

    model = Model([input_prev, input_next], h)
    # add loss function
    if ssim:
        model.compile(optimizer='adam', loss=ssim_loss, metrics=[ssim_loss, 'mse'])
    else:
        model.compile(optimizer='adam', loss='mse')

    return model

def train(model, x_train, y_train, model_name):
    #model.fit(x_train, y_train, epochs=100, batch_size=64, validation_data=(x_val, y_val))
    x_prev = x_train[:,:,:, 0]
    x_next = x_train[:,:,:, 1]

    history = model.fit([x_prev, x_next], y_train, epochs=25, batch_size=64)
    model.save(model_name)

if __name__=="__main__":
    import h5py

    train_file = sys.argv[1]

    model_name = "lin_reg.h5"

    f  = h5py.File(train_file, 'r')
    x_train = f['x_train']
    x_train = np.array(x_train)
    shape_train = x_train.shape[0]
    shape_train = int(shape_train/64.)*64 # ssim needs to have the same batch size for all the mini batches
    x_train = x_train[:shape_train,:,:,:]
    y_train = f['y_train']
    y_train = np.array(y_train)
    y_train = y_train[:shape_train,:,:]

    model = build_model()
    train(model, x_train, y_train, model_name)


import pandas as pd
import numpy as np
from tqdm.auto import tqdm
import rasterio
from pyproj import Proj, transform
from os import listdir
from datetime import datetime
import json
import math
from math import atan,degrees,sqrt
from shapely import geometry
from multiprocessing import Pool

from PIL import Image, ImageDraw
import scipy.misc as smp
import imageio

from GeoLibrary import *
from utilfunc import *

GRID_WIDTH = 512
GRID_HEIGHT = 512

with open("FullSugar.geojson") as f:
	features = json.load(f)["features"]

# generate latlon coordinates for each grid in the tile
def generate_positions(filepath):
	width,height = get_size(filepath)

	# absolute latlon for the tile
	latlon_tile = [(147.95529899839866, -19.893321306080015), \
			   (149.01671779369045, -19.893321306080015), \
			   (149.01671779369045, -20.876176661128618), \
				(147.95529899839866, -20.876176661128618)]

	top_left_lat_long, top_right_lat_long, bottom_right_lat_long, bottom_left_lat_long = latlon_tile[0], latlon_tile[1],\
																		latlon_tile[2], latlon_tile[3]

	fullImageWidth, fullImageHeight = width,height

	numOfXSquares=fullImageWidth//GRID_WIDTH
	numOfYSquares=fullImageHeight//GRID_HEIGHT
	grid_latlon_dict = {}
	for x in list(range(numOfXSquares)):
		for y in list(range(numOfYSquares)):
			fourLatLongPositions = [GetLatLongForCoords(r[0],r[1], top_left_lat_long, top_right_lat_long,\
												bottom_right_lat_long, bottom_left_lat_long, \
												fullImageWidth, fullImageHeight) for r in GetFourPositions(x,y)]
			grid_latlon_dict["{}-{}".format(x,y)] = fourLatLongPositions

	return grid_latlon_dict

# get sugarcane xy positions in a given tile
# only need to run once for each tile
# store it in disk
def generate_sugarcane_position(filepath):
	grid_latlon_dict = generate_positions(filepath)

	# absolute coordinate for the tile

	latlon_tile = [(147.95529899839866, -19.893321306080015), \
			   (149.01671779369045, -19.893321306080015), \
			   (149.01671779369045, -20.876176661128618), \
				(147.95529899839866, -20.876176661128618)]

	top_left_lat_long, top_right_lat_long, bottom_right_lat_long, bottom_left_lat_long = latlon_tile[0], latlon_tile[1],\
																		latlon_tile[2], latlon_tile[3]

	fullImageWidth = 10980
	fullImageHeight = 10980

	cnt = 0
	total_sugarcane_positions = []
	for key, value in grid_latlon_dict.items():
		# top_left_lat_long, top_right_lat_long,  bottom_right_lat_long, bottom_left_lat_long = list(value[0]), list(value[1]), list(value[2]), list(value[3])
		# fullImageWidth = GRID_WIDTH
		# fullImageHeight = GRID_HEIGHT

		gridGeo = { "type": "Polygon", "coordinates": [[ list(value[0]), \
													 list(value[1]), \
													 list(value[2]), \
													 list(value[3]), \
													 list(value[0]) ]]  }

		gridGeo_go = geometry.GeometryCollection([geometry.shape(gridGeo).buffer(0)])

		result=geometry.GeometryCollection()
		for k in features:
			if geometry.shape(k["geometry"]).intersects(gridGeo_go):
				result=result.union(geometry.shape(k["geometry"]).intersection(gridGeo_go))

		if gridGeo_go.intersects(result):
			cnt+=1
			# print(True)
			print("############## This iteration is for the {}th grid, key {} ##############".format(cnt, key))
			print(value)
			needed_ij_list = []
			# find the mask in the input region
			print(top_left_lat_long, top_right_lat_long,  bottom_right_lat_long, bottom_left_lat_long )

			xy_pair = key.split('-') # relative position
			grid_x, grid_y = int(xy_pair[0]), int(xy_pair[1])
			print( GetFourPositions(grid_x,grid_y) )

			grid_x_abs, grid_y_abs = grid_x * GRID_WIDTH, grid_y * GRID_HEIGHT

			print(grid_x_abs, grid_y_abs)

			for i in tqdm(list(range( grid_x_abs, grid_x_abs + GRID_WIDTH ))):
				for j in list(range( grid_y_abs, grid_y_abs + GRID_HEIGHT )):

					lat_long=GetLatLongForCoords(i,j, top_left_lat_long, top_right_lat_long,  bottom_right_lat_long, bottom_left_lat_long, fullImageWidth, fullImageHeight)
					if result.intersects(geometry.Point(lat_long)):
						# this coordinate is needed

						needed_ij_list.append((i,j))
						# print(True)

			total_sugarcane_positions += needed_ij_list
			# print(needed_ij_list)

			# data = np.zeros( (512,512,3), dtype=np.uint8 )

			# for pair in needed_ij_list:
			# 	i = pair[0]
			# 	j = pair[1]
			# 	newi = i - grid_x * GRID_WIDTH
			# 	newj = j - grid_y * GRID_HEIGHT

			# 	data[newj,newi] = (255,255,255)
			# imageio.imwrite("test.png", data)

		# else:
			# print(False)

		# if cnt == 1:
		# 	break

	print(cnt)
	return total_sugarcane_positions

if __name__ == '__main__':
	filepath = "/mnt/volume_sgp1_01/pepsL2A_processed_img/T55KFT/split_dates/"
	tile_filepath = filepath+"20161222.tif"

	# grid_latlon_dict = generate_positions(tile_filepath)
	# print(grid_latlon_dict)

	total_sugarcane_positions = generate_sugarcane_position(tile_filepath)
	tile1_dict = { "sugarcane_positions": total_sugarcane_positions }
	with open("tile1_sugarcane_positions.json", "w") as fp:
		json.dump(tile1_dict, fp)


import cv2,time
import scipy.fftpack as fft
import numpy as np

indata = (np.random.random((8,8))-0.5)*255

iters = 100000

st = time.time()
for i in range(iters):
	cv2.dct(indata)
cvtime = time.time()-st

st = time.time()
for i in range(iters):
	fft.dct(fft.dct(indata,axis=0,norm="ortho"),axis=1,norm="ortho")
scitime = time.time()-st

print("Scipy time is %f (%f per iter)"%(scitime,scitime/iters))
print("CV2 time is %f (%f per iter)"%(cvtime,cvtime/iters))


#!/usr/bin/env python3

import argparse
import glob
import os
import os.path
import re
import shutil
import subprocess
import sys
import tempfile

def get_config(modes, engine, top, srcs, depth, params):
  config_str = ''
  config_str = '[tasks]\n'
  tasks = ['task_{:s}'.format(m) for m in modes]
  config_str += '\n'.join(tasks)
  config_str += '\n\n'

  config_str += '[options]\n'
  options = ['task_{:s}: mode {:s}'.format(m, m) for m in modes]
  config_str += '\n'.join(options)
  config_str += '\n'
  options = ['task_{:s}: depth {:d}'.format(m, depth) for m in modes]
  config_str += '\n'.join(options)
  config_str += '\n\n'

  config_str += '[engines]\n'
  config_str += '{:s}\n'.format(engine)
  config_str += '\n'

  config_str += '[script]\n'
  for f in srcs:
    _, extension = os.path.splitext(f)
    sv_flag = ' -sv' if extension == '.sv' else ''
    config_str += 'read -formal{:s} -D{:s} {:s}\n'.format(sv_flag, top.upper(), os.path.basename(f))

  for k, v in params.items():
    config_str += 'chparam -set {:s} {} {:s}\n'.format(k, v, top)

  config_str += 'prep -top {:s}\n'.format(top)
  config_str += '\n'

  config_str += '[files]\n'
  config_str += '\n'.join(srcs)

  return config_str

class ParamAction(argparse.Action):
  def __call__(self, parser, namespace, values, option_string=None):
    setattr(namespace, self.dest, dict())
    for value in values:
      parts = value.split('=')

      if len(parts) == 1:
        parser.error('Argument "{}" contains no "=".'.format(value))
      if len(parts) > 2:
        parser.error('Argument "{}" contains multiple "=".'.format(value))

      getattr(namespace, self.dest)[parts[0]] = parts[1]

def main():
  parser = argparse.ArgumentParser(description='Configure and run symbiyosys.')
  parser.add_argument('--sby_path', required=True, help='Path to sby executable.')
  parser.add_argument('--yosys_path', required=True, help='Path to yosys executable.')
  parser.add_argument('--abc_path', required=True, help='Path to yosys-abc executable.')
  parser.add_argument('--smtbmc_path', required=True, help='Path to yosys-smtbmc executable.')
  parser.add_argument('--solver_paths', nargs='*', help='Solver paths to make available to Yosys.')
  parser.add_argument('--modes', nargs='+', required=True, help='Task modes.')
  parser.add_argument('--engine', default='smtbmc', help='Proof engine.')
  parser.add_argument('--top', required=True, help='Top module name.')
  parser.add_argument('--params', nargs='*', action=ParamAction, default={},
      help='Params for top module. e.g. key=value')
  parser.add_argument('--depth', type=int, default=20, help='Solver depth.')
  parser.add_argument('--vcd_dir', help='Directory for output trace files.')
  parser.add_argument('--ignore_failure', action='store_true',
      help='Do not report error code from Symbiyosys.')
  parser.add_argument('srcs', nargs='+', help='(System) verilog sources.')

  args = parser.parse_args()

  with tempfile.TemporaryDirectory() as directory:
    with open(os.path.join(directory, 'config.sby'), 'w') as f:
      config = get_config(args.modes, args.engine, args.top, args.srcs, args.depth, args.params)
      f.write(config)

    sby_args = [
        os.path.abspath(args.sby_path),
        '--yosys',
        os.path.abspath(args.yosys_path),
        '--abc',
        os.path.abspath(args.abc_path),
        '--smtbmc',
        os.path.abspath(args.smtbmc_path),
        os.path.join(directory, 'config.sby'),
    ]

    env = os.environ.copy()
    paths = ':'.join([os.path.abspath(path) for path in args.solver_paths])
    if paths:
      env['PATH'] = paths + ':' + env['PATH']

    completed = subprocess.run(sby_args, env=env)

    if args.vcd_dir:
      try:
        os.mkdir(args.vcd_dir)
      except FileExistsError:
        pass

      traces = glob.glob(os.path.join(directory, 'config_task_*/engine_0/*.vcd'))

      for trace in traces:
        match = re.search(r'config_task_(\w+)', trace)
        if not match:
          raise RuntimeError('Malformed trace file: {:s}'.format(trace))

        mode = match.group(1)
        name = '{:s}_{:s}'.format(mode, os.path.basename(trace))
        shutil.copyfile(trace, os.path.join(args.vcd_dir, name))

    if not args.ignore_failure:
      sys.exit(completed.returncode)

if __name__ == '__main__':
  main()


#!/bin/env python
#-*- encoding:utf-8 -*-

import numpy as np
import functools
import pandas as pd
import tensorflow as tf
from tensorflow.contrib.learn import MetricSpec

def create_evaluation_metrics():
    eval_metrics = {}
    for k in [1, 3, 5, 10]:
        recall_metric_spec = MetricSpec(
            metric_fn = functools.partial(tf.metrics.recall_at_k, k = k),
            prediction_key = 'probabilities',
            label_key = 'recall_labels')
        precision_metric_spec = MetricSpec(
            metric_fn = functools.partial(tf.metrics.sparse_precision_at_k, k = k),
            prediction_key = 'probabilities',
            label_key = 'recall_labels')
        eval_metrics['recall_at_%d' % k] = recall_metric_spec
        eval_metrics['precision_at_%d' % k ] = precision_metric_spec
    eval_metrics['accuracy'] = MetricSpec(
        metric_fn = tf.metrics.accuracy,
        prediction_key = 'classes',
        label_key = 'labels')

    return eval_metrics


from typing import Any, Mapping

from official.vision.serving import detection

class DetectionModule(detection.DetectionModule):
  """A serving detection module for exporting the model.

  This module overrides the tensorflow_models DetectionModule by only outputting
    the pre-nms detection_boxes and detection_scores.
  """

  def serve(self, images) -> Mapping[str, Any]:
    result = super().serve(images)
    final_outputs = {
        'detection_boxes': result['detection_boxes'],
        'detection_scores': result['detection_scores'],
    }
    return final_outputs


import numpy as np
import pandas as pd
from sklearn import metrics
from sklearn.model_selection import train_test_split
from tensorflow import keras
import matplotlib.pyplot as plt
import json

# Split the dataframe into test and train data

def prepare_data(data_df):
    # Define columns to dump
    col_dum = ['SHUTDOWN_SELECTED','ALARM_SELECTED','WARNING_SELECTED',
            'BU2700_RUN','FD2791_IN','IGT2793_ON',
            'BL2501_RUN']
    my_frame = data_df.drop('MNT_DAT_PK',axis=1) # removing the columns feature
    data = my_frame.drop('DATA_TIME',axis=1)

# Replace the boolean values with the binary values.
    for v in col_dum:
        # print(data[v].shape)
        dummies = pd.get_dummies(data[v], prefix=v)
        # print(dummies)
        data=pd.concat([data,dummies],axis=1) # concatenating two data frames horizontally
        # print(dummies.shape)
        # print(modified_data.shape)
        data.drop(v,axis=1,inplace=True)    # dropping the original columns, inplace is set true in order if dont need to reassign df again.
        # print(data[v])
    return data

def split_data(df, test_size, target):
    # df = prepare_data(data_df)
    x = df.drop(target,axis=1)
    y = df.loc[:, target]
    x_train, x_test, y_train, y_test = train_test_split(x, y, test_size = test_size,shuffle = False)
    dataset = {"train" : {"X" : x_train, "y" : y_train},
    "test" : {"X" : x_test, "y" : y_test}}
    return dataset

def train_model(dataset, args):
    # ② 모델 정의
    x_train, y_train = dataset["train"]["X"], dataset["train"]["y"]
    model = keras.models.Sequential()
    # ③ 블록 준비
    model.add(keras.layers.Dense(100, input_shape = (x_train.shape[1],), activation='relu'))
    model.add(keras.layers.Dense(40, input_shape = (100,), activation='relu'))
    model.add(keras.layers.Dense(20, input_shape = (40,), activation='relu'))
    model.add(keras.layers.Dense(1))

    # ⑤ Compile
    model.compile(loss = args["loss"], optimizer = args["optimizer"])
    model.fit(x_train, y_train, epochs = args["epochs"])
    return model

def feature_selection(dataframe):
    with open("feature_dict.json") as f:
        features = json.load(f)
    selected_features = []
    for feats in features["features"]:
        if feats not in dataframe.columns.tolist():
            white_space_removed = feats.split(" ")[-1]
            if white_space_removed != "IGT2793_ON":
                selected_features.append(white_space_removed)
    return dataframe[selected_features]

def get_model_metrics(model, data):
    x_test, y_test = data["test"]["X"], data["test"]["y"]
    x_train, y_train = data["train"]["X"], data["train"]["y"]
    data_shape = x_train.shape[0] + x_test.shape[0]

    # Predict using the trained model
    pred_arr = model.predict(x_test)
    # abb = y_train.values()
    y_test_arr = np.expand_dims(y_test, axis = 1)
    # print(y_test_arr)
    # arr = y_test.values()

    fig=plt.figure(facecolor='white',figsize=(14,14))
    ax=fig.add_subplot(1,1,1)
    # ax.set(xlim=[0,44052],ylim=[-10000,10000],title='Temperature Prediction',xlabel='time',ylabel='Temperature')
    ax.set(xlim=[0,int(data_shape*0.2)],ylim=[0,400],title='Temperature Prediction',xlabel='time',ylabel='Temperature')
    ax.plot(y_test_arr,'r',label='True')
    ax.plot(pred_arr,'b',label='Prediction')
    ax.legend()
    plt.show()

    y_test_arr_final=y_test_arr.reshape((x_test.shape[0],1))
    # Get the error value between predicted and real data
    error=((y_test_arr_final-pred_arr)/y_test_arr_final)*100
    model_metrics = {"error" : error}
    return model_metrics


import json
import os
import boto3

# Connect to the database

rdsData = boto3.client('rds-data')
parameters = boto3.client('ssm')

stage = os.environ['STAGE']
cluster_arn = os.environ['CLUSTERARN']
secret_arn = os.environ['SECRETARN']
dbname_param = parameters.get_parameter(Name='/school-vue-db-serverless/'+stage+'/database/name')

def lambda_handler(event, context):

    school_id = event['pathParameters']['school_id']
    course_id = event['pathParameters']['course_id']
    sql1 = f'SELECT Teacher_ID, Firstname, Lastname, Email FROM teachers WHERE School_ID={school_id} AND Level="{course_id}"'
    sql2 = f'SELECT Student_ID, Firstname, Lastname, Email FROM students WHERE School_ID={school_id} AND Level="{course_id}"'
    teacher = rdsData.execute_statement(
            resourceArn = cluster_arn,
            secretArn = secret_arn,
            database = dbname_param['Parameter']['Value'],
            sql = sql1)
    students = rdsData.execute_statement(
            resourceArn = cluster_arn,
            secretArn = secret_arn,
            database = dbname_param['Parameter']['Value'],
            sql = sql2)

    return {
        "statusCode": 200,
        "headers": {"Access-Control-Allow-Origin": "*"},
        "body": json.dumps({
            "teacher": teacher['records'],
            "students": students['records']
        })
    }


# subtitle
print ("This project is for Radius of the circle. \n")

# variable
p = 3.14

# input value
x = int(input("Enter a number for radius "))

# the operation
a=x*2
b=2*p*x
c=p*x*x

# output
print ("diameter= " , a , "\n Environment= " , b , "\n Area= " , c)


# coding : utf-8
# create by htb on 2020

### 简易金融量化框架

import pandas as pd
import matplotlib.pyplot as plt
import tushare as ts
import datetime

# 交易日历
try:
    f = open('./data2local/trade_cal.csv', 'r')
    # trade_cal = pd.read_csv(f, parse_dates=['calendarDate']) # 将“calendarDate”列解析为时间索引
    trade_cal = pd.read_csv(f)
except FileNotFoundError:
    trade_cal = ts.trade_cal()

# trade_cal = ts.trade_cal()

class G:
    """
    存储用户自定义的全局变量
    """
    pass

class Contex:
    """
    框架全局变量
    """
    def __init__(self, cash, start_date, end_date):
        self.cash = cash                # 账户余额
        self.start_date = start_date    # 起始时间
        self.end_date = end_date        # 终止时间
        self.positions = {}             # 持仓数据：持仓股票代码：持股数目
        self.benchmark = None           # 基准
        self.date_range = trade_cal[(trade_cal.calendarDate >= start_date)\
                                    & (trade_cal.calendarDate <= end_date)\
                                    & (trade_cal.isOpen == 1)]['calendarDate'].values # 执行回测时间范围

# 用户需要根据自身需求自定义的全局变量
cash = 100000.0         # 起始现金
s_date = '2019-01-01'   # 起始时间
e_date = '2020-01-01'   # 终止时间
# 框架全局变量初始化
context = Contex(cash, s_date, e_date)
# 用户全局变量初始化
g = G()

def attribute_history(security, count,
                      fields=('open', 'close', 'high', 'low', 'volume')):
    """
    获取股票指定数量（天数）的历史数据
    :param security: 股票
    :param count:   获取多少天的历史数据
    :param fields:  返回数据列索引
    :return: dataframe格式数据
    """
    # 运行策略日期为context.dt, 历史数据截止日期为昨天：end_date
    end_date = (context.dt - datetime.timedelta(days=1)).strftime('%Y-%m-%d')
    start_date = trade_cal[(trade_cal.calendarDate <= end_date) & (trade_cal.isOpen == 1)]\
                            [-count:].iloc[0]['calendarDate'] # 起始交易日
    return attrbute_daterange_history(security, start_date, end_date, fields)

def attrbute_daterange_history(security, start_date, end_date,
                               fields=('open', 'close', 'high', 'low', 'volume')):
    """
    获取股票指定日期范围内日的历史数据
    :param security: 股票代码
    :param start_date: 起始时间
    :param end_date:   结束时间
    :param fields:     需要数据类型
    :return: dataframe格式数据
    """
    try:
        f = open('./data2local/' + security + '.csv', 'r')
        df = pd.read_csv(f, index_col='date', parse_dates=['date']).loc[start_date:end_date, :]
    except FileNotFoundError:
        df = ts.get_h_data(security, start=start_date, end=end_date, autype=None) # 获取历史无复权数据
    return df[list(fields)].sort_index() # 返回索引升序排序后的数据

def get_today_data(security):
    """
    获取当日股票无复权数据
    :param security: 股票代码
    :return: 当日（回测执行日期）无复权数据
    """
    today = context.dt.strftime('%Y-%m-%d')
    try: # 行情数据本地化
        f = open('./data2local/' + security + '.csv', 'r')
        df = pd.read_csv(f, index_col='date', parse_dates=['date']).loc[today:today]
    except FileNotFoundError:
        df = ts.get_h_data(security, start=today, end=today, autype=None) # 获取历史无复权数据
    return df

def set_benchmark(benchmark):
    """
    设置基准
    :param benchmark: 基准股票代码
    :return:
    """
    context.benchmark = benchmark

def _order(today_data, security, amount):
    """
    交易函数
    :param today_data:当天日期
    :param security:股票代码
    :param amount:数量（多少股）
    :return:
    """
    if today_data.empty:
        print("股市今天停牌，无法买卖")
        return False

    if security not in context.positions:
        context.positions[security] = 0

    # 最低佣金：5元（不做判断）
    if context.cash - amount * today_data['close'][0] * 1.0003 < 0:
        amount = int(context.cash / today_data['close'][0] / 1.0003)
        print("现金不足，已调整为%d" % amount)

    if amount % 100 != 0:
        # if amount != -context.positions[security]:
        amount = int(amount / 100) * 100
        print("交易必须为100的整数倍，已调整为%d" % amount)

    if context.positions[security] + amount < 0:
        amount = -context.positions[security]
        print("卖出股票必须不超过持仓数，已调整为%d" % amount)

    action = "买入" if amount > 0 else "卖出"
    print("%s: %s%s股票%d股，价格%.2f" % (context.dt.strftime('%Y-%m-%d'), action, security, amount, today_data['close'][0]))
    new_amount = context.positions[security] + amount
    context.positions[security] = new_amount
    if amount > 0:
        context.cash -= amount * today_data['close'][0] * 1.0003
    else:
        """
        佣金：万3
        印花税：千分之一
        最低佣金：5元（不做处理）
        """
        context.cash -= amount * today_data['close'][0] * 0.9987

    if context.positions[security] == 0:
        del context.positions[security]

def order(security, amount):
    """
    买|卖多少股票
    :param security: 股票代码
    :param amount:   买入|卖出数量
    :return:
    """
    today_data = get_today_data(security)
    return _order(today_data, security, amount)

def order_value(security, value):
    """
    买|卖多少钱的股票
    :param security: 股票代码
    :param value: 买入|卖出 金额
    :return:
    """
    today_data = get_today_data(security)
    commission_ratio = 0.9987 if value < 0 else 1.0003 # 不考虑最低佣金限制
    amount = int(value / today_data['close'][0] / commission_ratio) # 根据买入|卖出计算对应金额的股票数量
    return _order(today_data, security, amount)

def order_target(security, amount):
    """
    买|卖到多少股股票
    :param security: 股票代码
    :param amount:   买入|卖出 数量
    :return:
    """
    if amount < 0:
        print("目标股数不能为负，已调整为0")
        amount = 0
    today_data = get_today_data(security)
    hold_amount = context.positions[security] if security in context.positions else 0
    delta_amount = amount - hold_amount
    return _order(today_data, security, delta_amount)

def order_target_value(security, value):
    """
    买|卖到多少钱的股票
    :param security: 股票代码
    :param value:    买入|卖出 金额
    :return:
    """
    if value < 0:
        print("目标价值不能为负，已调整为0")
        value = 0
    today_data = get_today_data(security)
    hold_value = context.positions[security] * today_data['close'][0]
    delta_value = value - hold_value
    commission_ratio = 0.9987 if delta_value < 0 else 1.0003
    delta_amount = int(delta_value / today_data['close'][0] / commission_ratio)
    return _order(today_data, security, delta_amount)


import numpy as np
import torch

# Functions that convert pybind11 objects to serializable formats

def torchify(obj):
    r"""
    Convert to nested dictionary of torch tensors for use with
    torch.save. Roughly 6.3x file size of original Parasolid .x_t
    """

    if torch.is_tensor(obj):
        return obj

    primitive = (int, str, bool, float)
    number = (int, float)
    if isinstance(obj, primitive):
        return obj
    if isinstance(obj, np.ndarray):
        return torch.from_numpy(obj)
    if isinstance(obj, list):
        if len(obj) > 0:
            if isinstance(obj[0], number):
                return torch.tensor(obj)
            if isinstance(obj[0], np.ndarray):
                return torch.tensor(np.stack(obj))
            if isinstance(obj[0], list):
                if len(obj[0]) > 0:
                    if isinstance(obj[0][0], np.ndarray):
                        return torch.tensor(
                            np.stack([
                                np.stack(l) for l in obj
                            ])
                        )
                else:
                    return [[]]
        return [torchify(x) for x in obj]

    keys = [x for x in dir(obj) if not x.startswith('__')]

    if 'name' in keys and 'value' in keys: # this is an enum
        return {
            'value': getattr(obj, 'value'),
            'name': getattr(obj, 'name'),
            'enum_size': len(keys) - 2 # the other keys are all enum opts
        }

    return dict(zip(
        keys,
        [torchify(getattr(obj, key)) for key in keys]
    ))

def jsonify(obj):
    r"""
    Convert to nested dictionary of python primitives for use with
    json.dump. Roughly 10x file size of original Parasolid .x_t
    """
    primitive = (int, str, bool, float)
    if isinstance(obj, primitive):
        return obj
    if isinstance(obj, np.ndarray):
        return obj.tolist()
    if isinstance(obj, list):
        return [jsonify(x) for x in obj]

    keys = [x for x in dir(obj) if not x.startswith('__')]

    if 'name' in keys and 'value' in keys: # this is an enum
        return {
            'value': getattr(obj, 'value'),
            'name': getattr(obj, 'name'),
            'enum_size': len(keys) - 2 # the other keys are all enum opts
        }

    return dict(zip(
        keys,
        [jsonify(getattr(obj, key)) for key in keys]
    ))


'''
Databases for battleball
'''

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save

class UserProfile(models.Model):
    ''' elements of the user profile '''
    user = models.OneToOneField(User, unique=True)

    picture = models.ImageField(upload_to='profile_images', blank=True)

    def __str__(self):
        return self.user.username

def create_profile(sender, instance, created, **kwargs):
    ''' created profile '''
    if created:
        profile, created = UserProfile.objects.get_or_create(user=instance)

post_save.connect(create_profile, sender=User)

class Piece(models.Model):
    ''' piece on the team '''
    def __init__(self, *args, **kwargs):
        return super(Piece, self).__init__(*args, **kwargs)
    name = models.CharField(max_length=30)
    piece_size = models.IntegerField(default=1)
    has_ball = models.BooleanField(default=False)
    injury = models.IntegerField(default='0')
    str_position = models.CharField(max_length=20, default='{"xpos":-1, "ypos":-1}')
    roll_size = models.IntegerField(default=20)

    def __unicode__(self):
        return self.name

class Game(models.Model):
    ''' crucial items for game board '''
    title = models.CharField("Title", max_length=100, default='untitled')
    url = models.URLField("URL", max_length=250, blank=True)
    boardFile = models.CharField(max_length=30, default=0)
    homeTeam = models.CharField(max_length=30)
    awayTeam = models.CharField(max_length=30)
    turn = models.BooleanField(default=True)
    homeScore = models.IntegerField(default=0)
    awayScore = models.IntegerField(default=0)

    def instatiate_pieces():
        '''
        All 20 pieces for full game
        '''
        heavy_tackle_h = Piece(roll_size=6, piece_size=2, name='heavy tackle')
        tackle_h = Piece(roll_size=6, piece_size=1, name='tackle')
        lineman1_h = Piece(roll_size=8, piece_size=1, name='lineman 1')
        lineman2_h = Piece(roll_size=8, piece_size=1, name='lineman 2')
        linebacker1_h = Piece(roll_size=10, piece_size=1, name='linebacker 1')
        linebacker2_h = Piece(roll_size=10, piece_size=1, name='linebacker 2')
        safety1_h = Piece(roll_size=12, piece_size=1, name='safety 1')
        safety2_h = Piece(roll_size=12, piece_size=1, name='safety 2')
        running_back1_h = Piece(roll_size=20, piece_size=1, name='running back 1')
        running_back2_h = Piece(roll_size=20, piece_size=1, name='running back 2')
        running_back3_h = Piece(roll_size=20, piece_size=1, name='running back 3')

        heavy_tackle_a = Piece(roll_size=6, piece_size=2, name='heavy tackle')
        tackle_a = Piece(roll_size=6, piece_size=1, name='tackle')
        lineman1_a = Piece(roll_size=8, piece_size=1, name='lineman 1')
        lineman2_a = Piece(roll_size=8, piece_size=1, name='lineman 2')
        linebacker1_a = Piece(roll_size=10, piece_size=1, name='linebacker 1')
        linebacker2_a = Piece(roll_size=10, piece_size=1, name='linebacker 2')
        safety1_a = Piece(roll_size=12, piece_size=1, name='safety 1')
        safety2_a = Piece(roll_size=12, piece_size=1, name='safety 2')
        running_back1_a = Piece(roll_size=20, piece_size=1, name='running back 1')
        running_back2_a = Piece(roll_size=20, piece_size=1, name='running back 2')
        running_back3_a = Piece(roll_size=20, piece_size=1, name='running back 3')

        player_dict = {'home': [heavy_tackle_h, tackle_h, lineman1_h, lineman2_h,
                                linebacker1_h, linebacker2_h, safety1_h, safety2_h,
                                running_back1_h, running_back2_h, running_back3_h],

                       'away': [heavy_tackle_a, tackle_a, lineman1_a, lineman2_a,
                                linebacker1_a, linebacker2_a, safety1_a, safety2_a,
                                running_back1_a, running_back2_a, running_back3_a]}

        return player_dict

    pieces = instatiate_pieces()

    def __unicode__(self):
        return self.title

class Coach(models.Model):
    ''' users can create a coach '''
    name = models.CharField(max_length=30)
    user = models.OneToOneField(User, unique=True)

    def __unicode__(self):
        return self.name

# These blocks of code is added by Tenzin
class Team(models.Model):
    ''' Team name and stats '''
    teamName = models.CharField(max_length=30)
    gamesPlayed = models.IntegerField(default=0)
    gamesWon = models.IntegerField(default=0)
    rank = models.IntegerField(default=0)
    def __str__(self):
        return self.teamName


from __future__ import print_function
import copy
import subprocess
import os
import yaml
import math
import pickle
import random

import numpy as np
import numpy.ma as ma
import pandas as pd

from sklearn.decomposition import PCA, FastICA, NMF
from sklearn.preprocessing import normalize

import pyclass
import pgutils
from sicparse import OptionParser

def main():

    # Input parameters
    parser = OptionParser()
    parser.add_option("-n", "--n_components",
                      dest="number_components", nargs=1, default=5)

    try:
        (options, args) = parser.parse_args()
    except:
        pyclass.message(pyclass.seve.e, "PCA", "Invalid option")
        pyclass.sicerror()
        return
    if (not pyclass.gotgdict()):
        pyclass.get(verbose=False)

    # Setup parameters
    number_components = int(options.number_components)+1

    redo_index = True
    if input_file:
        pyclass.comm('file in "{}"'.format(input_file))
        pyclass.comm('find')
        modification_times_yaml_file = ".{}_modification_times_pca.yaml".format(input_file.replace("/", "_"))
        modification_time = os.path.getmtime(input_file)

        if os.path.exists(modification_times_yaml_file):
            previous_modification_times = yaml.safe_load(
                open(modification_times_yaml_file))
        else:
            previous_modification_times = {}
        if previous_modification_times is None:
            previous_modification_times = {}
        if input_file in previous_modification_times.keys():
            previous_modification_time = previous_modification_times[
                input_file]
            if (round(previous_modification_time, 0) >= round(
                    modification_time, 0)):
                redo_index = False

        previous_modification_times[input_file] = modification_time
        with open(modification_times_yaml_file, 'w') as outfile:
            yaml.dump(previous_modification_times, outfile)

    idx_list = []
    idx_list.append(pyclass.gdict.idx.num)
    idx_list.append(pyclass.gdict.idx.teles)
    idx_list.append(pyclass.gdict.idx.scan)
    idx_list.append(pyclass.gdict.idx.subscan)
    idx_list.append(pyclass.gdict.idx.sourc)
    idx_list.append(pyclass.gdict.idx.line)
    idx_list.append(pyclass.gdict.idx.boff)
    idx_list.append(pyclass.gdict.idx.loff)
    idx_list.append(pyclass.gdict.idx.ver)
    idx_list = np.asarray(idx_list)
    df = pd.DataFrame(
        idx_list.T,
        columns=["number", "telescope", "scan", "subscan",
                 "source", "line", "boff", "loff", "version"]
    )

    pyclass.comm("set var user")
    pyclass.comm("import sofia")
    scan_group = df.groupby(["scan"])
    df["mission_id"] = None
    for name, group in scan_group:
        number = group.number.iloc[0]
        pyclass.comm("get {}".format(number))
        mission_id = copy.deepcopy(
            pyclass.gdict.r.user.sofia.mission_id.__sicdata__)
        df.loc[df["scan"] == group.scan.iloc[0],
               "mission_id"] = str(mission_id).strip()

    df.source = df.source.astype(str).str.strip()
    with open(pca_index_file, "wb") as filehandler:
        pickle.dump(df, filehandler)

main()


#!/usr/bin/env python3

from classes import Window, DbHandler  # , LoginInfo
import pytermgui as ptg
from typing import Dict
# import datetime

class AlbumsWindow(Window.Window):
    def __init__(self, manager: ptg.window_manager.manager.WindowManager):
        self.db: DbHandler.DbHandler = DbHandler.DbHandler.instance()
        self.manager = manager
        # self.loginInstance = LoginInfo.LoginInfo.instance()
        self._buttons: Dict[str, ptg.Label] = {}
        self.namespace = ptg.Window()

    def getNamespace(self) -> ptg.Window:
        return self.namespace

    def setAlbum(self, id_spotify: str):
        self.album = self.db.fetchOne(
            "SELECT * FROM album WHERE id_spotify = %s;",
            [id_spotify]
        )
        self.namespace = ptg.Window(
            ptg.Label("[title]" + self.album["nome"]),
            ptg.Container(
                ptg.Splitter(
                    ptg.Label("Ano:"),
                    ptg.Label(f"{self.album['ano'].year}")
                ),
                ptg.Splitter(
                    ptg.Label("Duração:"),
                    ptg.Label(f"{self.album['duracao']}")
                ),
                ptg.Splitter(
                    ptg.Label("ID Spotify:"),
                    ptg.Label(f"{self.album['id_spotify']}")
                ),
            ),
            ptg.Button(label="Sair", id="btnQuitAlbum")
        )
        self.buttons["btnQuitAlbum"] = ptg.get_widget("btnQuitAlbum")
        self.buttons["btnQuitAlbum"].on_click = lambda _: \
            self.getNamespace().close()

    @property
    def buttons(self) -> Dict[str, ptg.Widget]:
        return self._buttons


import numpy as np
import cv2
cnt=0
cap = cv2.VideoCapture('/Users/abhaydoke/Documents/HTN/object-detection/video_data/AVSS_AB_Easy_Divx.avi')
while(cap.isOpened()):
    ret, frame = cap.read()
    if cnt%30==0:
    	cv2.imwrite('../frame'+str(cnt)+'.jpg',frame)
    cnt+=1
    if cnt==100:
    	break
cap.release()
   # save frame as JPEG file


class Robot:

    def __init__(self,given_name,given_color,given_weight):
        self.name=given_name
        self.color=given_color
        self.weight=given_weight

    def introduce_self(self):
        print (f"my name is {self.name}")

r1=Robot("Tom", "red", 40)
r2=Robot("Jerry", "blue", 30)
# print(r1.introduce_self())

class Person:
    def __init__(self, name, personality, isSitting, robotOwned) -> None:
        self.name = name
        self.personality = personality
        self.isSitting = isSitting
        self.robotOwned = robotOwned

    def sit_down(self):
        self.isSitting = True

    def stand_up(self):
        self.isSitting = False

p1 = Person("Alice", "Aggressive", False, r2)
p2 = Person("Becky", "Talkative", True, r1)

print(f"Hello {p1.name}, are you sitting?  : {p1.isSitting}")
p1.sit_down()
print(f"How about now? : {p1.isSitting}")
p2.robotOwned.introduce_self()

print("")

print(f"Hello {p2.name}, are you standing?  : {p2.isSitting}")
p2.stand_up()
print(f"How about now? : {p2.isSitting}")

p1.robotOwned.introduce_self()


from selenium import webdriver
from selenium.webdriver.common.by import By
import time
class calender2:

    def test(self):

        driver = webdriver.Chrome()
        driver.maximize_window()
        driver.get("https://www.expedia.co.in")
        driver.implicitly_wait(4)

        #Click on Flight Tab
        flightTab = driver.find_element(By.XPATH,"//a[@id='tab-flight-tab']")
        flightTab.click()

        time.sleep(5)

        #Click on flight Departure text box
        departingtxt = driver.find_element(By.XPATH,"//input[@id='flight-departing']")
        departingtxt.click()
        time.sleep(2)
       # if driver.find_element(By.XPATH,"//div[@class='datepicker-cal-month'][position()=1]") is True:
        #    print("the date picker is diaplayed ")
        pickedDt = driver.find_element(By.XPATH,"//div[@class='datepicker-cal-month'][position()=1]//button[text()='9']")
        pickedDt.click()

        time.sleep(10)

        departingtxt.click()
        dateList = driver.find_elements(By.XPATH,"//div[@class='datepicker-cal-month'][position()=1]//button[@class ='datepicker-cal-date']")

        for dt in dateList:
            if dt.text == "10":
                dt.click()
                print("Clicked the date" )
                break

        time.sleep(5)
cc = calender2()
cc.test()


import argparse
from pathlib import Path
import functools as f
import multiprocessing

import cv2
import pickle
import numpy as np
import pandas as pd
import lmdb
import tqdm

# https://community.drivendata.org/t/python-code-to-find-the-roi/4499
def get_rect(row, root, mode):
    _, item = row
    frames = []
    cap = cv2.VideoCapture(str(root / mode / item.filename))
    xs, ys, ws, hs = [], [], [], []
    v_len = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
    for i in range(v_len):
        success, image = cap.read()

        mask = cv2.inRange(image, (9, 13, 104), (98, 143, 255))
        points = np.where(mask > 0)
        p2 = [p for p in zip(points[0], points[1])]
        x, y, w, h = cv2.boundingRect(np.float32(p2))
        xs.append(x)
        ys.append(y)
        ws.append(w)
        hs.append(h)
        frames.append(image[..., -1])

    cap.release()

    frames = np.array(frames)
    x = min(xs)
    y = min(ys)
    w = max(ws)
    h = max(hs)

    frames = frames[:, x:x + w, y:y + h]
    out = {'frames': np.array(frames).transpose(1, 2, 0)}

    if 'stalled' in item:
        out.update({'label': item.stalled})

    return item.filename.split('.')[0], out

def parse_args():
    parser = argparse.ArgumentParser()

    parser.add_argument('mode', choices=['test', 'micro'])
    parser.add_argument('--data', type=str, required=True)
    parser.add_argument('--save', type=str, required=True)

    return parser.parse_args()

def main():
    args = parse_args()

    data_root = Path(args.data)
    args.save = Path(args.save)
    mode = args.mode

    if mode == 'test':
        meta = pd.read_csv(data_root / 'test_metadata.csv')
    else:
        meta = pd.read_csv(data_root / 'train_metadata.csv')
        meta = meta[meta[mode]].copy()
        meta = pd.merge(
            meta[meta[mode]].copy(),
            pd.read_csv(data_root / 'train_labels.csv'),
            on='filename',
        )

    with tqdm.tqdm(meta.iterrows(), total=len(meta)) as pbar:
        with multiprocessing.Pool(40) as p:
            features = dict(p.imap_unordered(func=f.partial(get_rect, root=data_root, mode=mode), iterable=pbar))

    map_size = sum(features[f]['frames'].nbytes for f in features)
    map_size = int(1.1*map_size)

    env = lmdb.open(
        str(args.save / f'{mode}_croped2.lmdb'),
        map_size=map_size,
    )

    with env.begin(write=True) as txn:
        txn.put(('keys').encode(), pickle.dumps(list(features.keys())))

        with tqdm.tqdm(features) as pbar:
            for key in pbar:
                txn.put(key.encode(), pickle.dumps(features[key]))

if __name__ == '__main__':
    main()


def get_reward_1(sig, sig_back, goal):
    if goal != 0:
        if goal > 0:
            return 50 * goal
        else:
            return -40

    # 앞에 우리 골대
    for i in range(7):
        if sig[i][1] == 1:
            return -15
    ## ## ##

    # 뒤에 상대 골대
    for i in range(3):
        if sig_back[i][2] == 1:
            return -15
    ## ## ##

    #뒤에 다 바로 벽
    if sig_back[0][3] == 1 and sig_back[1][3] == 1 and sig_back[2][3] == 1:
            if sig_back[0][7] < 0.1 and sig_back[1][7] < 0.1 and sig_back[2][7] < 0.1:
                return -2
    ## ## ##

    # 볼이 앞에 있을 시
    ball_s = -1
    ball_dis = -1

    for i in range(11):
        if sig[i][0] == 1:
            ball_s = i
            ball_dis = sig[ball_s][7]

    if ball_s != -1 and ball_dis < 0.3:
        if ball_s == 0:
            return 10
        elif ball_s < 5:
            return 5
        elif ball_s < 7:
            return 4
        else:
            return 1
    ## ## ##

    # 뒤에 볼 감지 시
    if sig_back[0][0] == 1:
        return -15

    for i in range(1,3):
        if sig_back[i][0] == 1:
            return -5
    ## ## ##

    return 0

def get_reward_2(obs, obs_back, goal):
    if goal != 0:
        if goal > 0:
            return 50 * goal
        else:
            return -40

    reward = 0
    b_ext = -1
    b_dis = 0
    gp_ext = 0
    gp_dis = 0

    for i in range(11):
        if obs[10-i][0]==1:
            b_dis = obs[10-i][7]
            if 10-i < 7:
                b_ext = 2
            elif 10-i > 6:
                b_ext = 1

    # for i in range(3):
    #     if obs_back[2-i][0] == 1:
    #         b_dis = obs[2-i][7]
    #         b_ext = -1

    for i in range(11):
        if obs[10-i][2] == 1:
            gp_dis = obs[10-i][7]
            if 10-i < 7:
                gp_ext = 1
            elif 10-i > 6:
                gp_ext = 0.8

    for i in range(3):
        if obs_back[2-i][2] == 1:
            gp_dis = obs[2-i][7]
            gp_ext = 0.1

    if b_ext > 0:
        reward = b_ext * (100**(1-b_dis)/10) + gp_ext * b_ext * (100**(1-b_dis)/10) * (30**(1-gp_dis)/10)
    else:
        reward = -4

    return reward

def get_reward_striker(signal, signal_back, goal):
    if goal > 0:
        return 50 * goal

    if goal < 0:
        return -20

    re = 0
    # 공이 시야에 있을때
    ball_insight = True if signal[0][0] == 1 or signal[1][0] == 1 or signal[2][0] == 1 or signal[3][0] == 1 or signal[4][0] == 1 or signal[5][0] == 1 or signal[6][0] == 1 else False
    if ball_insight:
        re += 0.05

    #서서히 공을 바라보도록
    if signal[0][0] == 1:
        re += 0.1
    if signal[1][0] == 1 or signal[2][0] == 1:
        re += 0.03
    if signal[3][0] == 1 or signal[4][0] == 1:
        re += 0.01
    if signal[5][0] == 1 or signal[6][0] == 1:
        re += 0.001

    # 공이 안보일 경우 적당히 뒤로 가도록
    if not ball_insight and signal_back[0][1] == 1:
        re += 0.1 * 1 / (signal_back[0][7] + 1) # 최대값 0.1

    # 공이 가까울수록, 하지만 더 공격적으로
    if signal[0][0] == 1:
        re += 2 * 1 / (signal[0][7] + 0.1) # 최대값 20

    return re

def get_reward_keeper(signal, signal_back, goal):
    if goal < 0:
        return -50

    if goal > 0:
        return 20

    re = 0
    #공이 시야에 있을때
    ball_insight = True if signal[0][0]==1 or signal[1][0]==1 or signal[2][0]==1 or signal[3][0]==1 or signal[4][0]==1 or signal[5][0]==1 or signal[6][0]==1 else False
    if ball_insight:
        re += 0.05

    #서서히 공을 바라보도록
    if signal[0][0] == 1:
        re += 0.1
    if signal[1][0] == 1 or signal[2][0] == 1:
        re += 0.03
    if signal[3][0] == 1 or signal[4][0] == 1:
        re += 0.01
    if signal[5][0] == 1 or signal[6][0] == 1:
        re += 0.001

    #공이 안보일 경우 많이 뒤로 가도록
    if not ball_insight and signal_back[0][1]==1:
        re += 0.1 * 1 / (signal_back[0][7] + 0.5) #최대값 0.2
    if not ball_insight and signal_back[1][1]==1 or not ball_insight and signal_back[1][1]==1:
        re += 0.05 * 1 / (signal_back[0][7] + 0.5) # 최대값 0.1

    #공이 가까울수록, 하지만 덜 공격적으로
    if signal[0][0]==1:
        re += 0.5 * 1 / (signal[0][7] + 0.1) #최대값 5

    #자책골 방지
    if signal_back[0][0]==1:
        re -= 0.1 * 1 / (signal_back[0][7] + 0.5) # 최대값 0.2

    return re


#! /usr/bin/env python3
import rospy
from torchvision import transforms
import torch
import cv2 as cv
# from std_msgs.msg import String
from anney_melodic_pkg.msg import Order

# Load the model
model = torch.load("/home/mustar/anney-robot-melodic/src/anney_melodic_pkg/model_080622.pth",map_location=torch.device("cpu"))
model.eval()

def create_list(orders,units):
    ''' This function is to create the order list based on its respective quantity '''

    order_temp = []
    for i in range(len(orders)):
        for j in range(units[i]):
            if(orders[i] == "mi_goreng"):
                order_temp.append("mee_goreng")
            elif(orders[i] == "sate"):
                order_temp.append("satay")
            else:
                order_temp.append(orders[i])

    return order_temp

def callback(data):
    rospy.loginfo(f'Table_num: {data.table_num} {data.orders} {data.units}')

    order_temp = create_list(data.orders,data.units) # Create full foods list
    rospy.loginfo(f'This is temp list: {order_temp}')
    train_transforms = transforms.Compose([transforms.ToTensor()])
    classes = ["mee_goreng", "nasi_goreng", "nasi_lemak", "roti_canai", "satay"]

    can_remove = True

    capture = cv.VideoCapture(2) # Initialize video capturing object with camera device index as the parameter

    # The initial tracker and global variables
    tracker = cv.TrackerKCF_create()
    tracked_bounding_box = None
    label = None

    while (len(order_temp) != 0):
        isTrue, frame = capture.read()

        # If there is an existing object, update and track the object.
        if tracked_bounding_box is not None:
            (success, box) = tracker.update(frame)

            if success:
                if(can_remove and label in order_temp):
                    rospy.loginfo(f'{label} for table {data.table_num} is done!')
                    order_temp.remove(label)
                    rospy.loginfo(f'This is temp list: {order_temp}')
                    can_remove = False

                (x, y, w, h) = [int(v) for v in box]
                cv.rectangle(frame, (x, y), (x + w, y + h),(0, 255, 0), 2)
                cv.putText(frame, label, (x, y),cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

            # If the object has disappeared from the frame, remove the previous tracker and create a new one.
            else:
                del tracker
                tracker = cv.TrackerKCF_create()
                tracked_bounding_box = None
                can_remove = True

        # If there are no current objects, use the model to detect possible food images in the capture.
        else:
            frame_transformed = train_transforms(cv.cvtColor(frame, cv.COLOR_BGR2RGB))
            prediction = model([frame_transformed])[0] # The model detects from the frame

            if len(prediction["scores"]) > 0:
                highest_confidence = torch.argmax(prediction["scores"], axis=0)
                label_idx = prediction["labels"][highest_confidence].item()
                label = classes[label_idx]
                box = prediction["boxes"][highest_confidence]

                # Initialise the tracker with the predicted bounding box.
                tracked_bounding_box = [round(i.item()) for i in box]
                tracker.init(frame, tracked_bounding_box)

                print(f"{label} detected. Attempting to track the object.")

                start_point = (round(box[0].item()), round(box[1].item()))
                end_point = (round(box[2].item()), round(box[3].item()))

                cv.rectangle(frame, start_point, end_point, (0, 255, 0), 2)
                cv.putText(frame, label, start_point,
                        cv.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)

        cv.imshow("Video", frame)

        if cv.waitKey(20) & 0xFF == ord("d"):
            break

    rospy.loginfo(f'All orders are done, can start to serve to table {data.table_num} now!')
    capture.release()
    cv.destroyAllWindows()

def listener():
    # Initialize subscriber node and let it subscribe to a topic
    rospy.init_node("Subscriber_Node", anonymous=True)
    rospy.Subscriber("order_topic", Order, callback)
    rospy.spin()

if __name__ == "__main__":
    try:
        listener()
    except rospy.ROSInterruptException:
        pass


"""
Given a string s which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters.

https://leetcode.com/problems/longest-palindrome/discuss/89604/Simple-HashSet-solution-Java

Input: s = "abccccdd"
Output: 7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
"""

class Solution:
    def longestPalindrome(self, s: str) -> int:
        counts = {}  # dict not required, set would just do

        max_len = 0
        for i in s:
            counts[i] = counts.get(i, 0) + 1
            if counts[i] == 2:
                max_len += 1
                del counts[i]

        if len(counts.keys()) > 0: return max_len + 1

        return max_len

# print(Solution().longestPalindrome('abccccdd'))
# print(Solution().longestPalindrome('abcd'))
print(Solution().longestPalindrome('bb'))


from tool.runners.python import SubmissionPy

max_coor = 4000000

class RemicalixteSubmission(SubmissionPy):
    def run(self, s: str):
        sensors = []
        beacons = []
        for line in s.split('\n'):
            sensor, beacon = line.split(':')
            sensor = sensor.removeprefix('Sensor at ')
            beacon = beacon.removeprefix(' closest beacon is at ')
            sensors.append(parse_coor_str(sensor))
            beacons.append(parse_coor_str(beacon))

        intervalss = [[] for i in range(max_coor+1)]
        for i in range(len(sensors)):
            d_beacon = manhattan_distance(sensors[i], beacons[i])
            populate_intervalss(intervalss, sensors[i], d_beacon)

        (x,y) = find_spot(intervalss)

        return x * max_coor + y

def populate_intervalss(intervalss: list[list], sensor: tuple[int], d_beacon: int):
    sx, sy = sensor
    min_y = sy - d_beacon
    max_y = sy + d_beacon
    for y in range(max(0,min_y), sy):
        delta = y - min_y
        intervalss[y].append((sx-delta, sx+delta+1))
    for y in range(sy, min(max_y,max_coor)+1):
        delta = max_y - y
        intervalss[y].append((sx-delta, sx+delta+1))

def find_spot(intervalss: list[list]):
        for y, intervals in enumerate(intervalss):
            intervals.sort(key=lambda interval: interval[0])
            x = 0
            for interval in intervals:
                start, end = interval
                if x < start:
                    break
                if end > x:
                    x = end
            if x <= max_coor:
                break
        return (x,y)

def manhattan_distance(p1, p2):
    x1, y1 = p1
    x2, y2 = p2
    return abs(x1-x2) + abs(y1-y2)

def parse_coor_str(s: str):
    sx, sy = s.split(', ')
    x = int(sx.removeprefix('x='))
    y = int(sy.removeprefix('y='))

    return (x,y)

def test_remicalixte():
    """
    Run `python -m pytest ./day-15/part-1/remicalixte.py` to test the submission.
    """
    assert (
        RemicalixteSubmission().run(
            """
""".strip()
        )
        == None
    )


import cv2 as cv
import csv
from datetime import datetime
import time

# The purpose of this function is to scan qr code.....
def scan():
    timeout = 100             # seconds  # to stop scanning after 10 seconds of inactivity
    triggered_time = time.time()
    uid = ""
    scanned = False
    cap = cv.VideoCapture(0)
    detector = cv.QRCodeDetector()
    print("Reading qr code using raspberry pi")

    while scanned == False:
        if (time.time()<triggered_time+timeout):
            isTrue, frame = cap.read()
            data,bbox,retr = detector.detectAndDecode(frame)
            cv.imshow("video",frame)
            if bbox is not None:
                if data:
                    print("Data found "+data)
                    uid = data
                    scanned=True
                    cap.release()
                    cv.destroyAllWindows()
                    return uid
            if cv.waitKey(20) & 0xFF == ord('d'):
                break
        else:
            return

# the purpose of this function is to change the encoding of the rows from csv file from utf-8 to ascii..
def convert_row( row ):
    row_dict = {}
    for key, value in row.items():
        keyAscii = key.encode('ascii', 'ignore' ).decode()
        valueAscii = value.encode('ascii','ignore').decode()
        row_dict[ keyAscii ] = valueAscii
    return row_dict

# The purpose of this function is to verify the scanned UID with the existing database..
def verify(uid):
    details = {}
    with open("database.csv",mode="r") as database:
        reader = csv.DictReader(database)
        for row in reader:
            row  = convert_row(row)
            if (row['uid'] == uid):
                details['name'] = row['name']
                details['uid'] = uid
                details['roll no'] = row['roll_no']
                details['email'] = row['email']
                details['verification status'] = True
                return details
        else:
            details['verification status'] = False

    return details

# The purpose of this function is to detect the face and store the image in the current working directory..
def face_detect():
    haar_cascades = cv.CascadeClassifier("haar_cascades.xml")
    # The purpose of this function is to detect any faces that are appearing in front of the camera...
    def detect_face(img):
        gray = cv.cvtColor(img,cv.COLOR_BGR2GRAY)
        face_rect = haar_cascades.detectMultiScale(gray,scaleFactor = 1.1, minNeighbors = 10)
        if len(face_rect) == 1:
            return True
        return False

    video = cv.VideoCapture(0)
    count = 0
    while count != 2:
        isTrue, frames = video.read()
        cv.imshow("video",frames)
        if (detect_face(frames)):
            time.sleep(0.5)
            count += 1    # here i'm waiting for the next to frames to get a clear image without any noises..
            if (count == 2):
                cv.imwrite("DetectedImage.jpg",frames)  # saving the image....
                return (True,"DetectedImage.jpg")   # It return true after the successful detection of face detection
                #returning image location also for email attachment
        if cv.waitKey(20) & 0xFF == ord('d'):
            break
    video.release()
    video.destroyAllWindows()

# The purpose of this function is to get the current date and time.....
def getDateAndTime():
    today = datetime.now()
    today = today.strftime("%d/%m/%Y %H:%M:%S")
    date_time = {'date':today.split(' ')[0],'time': today.split(" ")[1]}
    # print(date_time)
    return date_time

# The purpose of this function is to log the attendance in the separate excel sheet locally...
def logInTime(details):
    with open("log.csv", mode = "a", newline="\n") as file:
        keys = ['date','name','status','uid','roll no','in time','out time']
        writer = csv.DictWriter(file,keys,delimiter = ",")
        # assuming that the file already has the headers so I'm leaving the part of assigning them..
        dateAndTime = getDateAndTime()
        date = dateAndTime['date']
        time_now = dateAndTime['time']
        values = {'date':date,'name':details['name'],'status':'in','uid':details['uid'],'roll no': details['roll no'],'in time':time_now,'out time':""}
        writer.writerow(values)
        return (date,time_now)       #returning entry time and date for email use

# The purpose of this function is to update the status and assign out time for the user...
def logOutTime(uid):
    temp = []  # temp array to copy the data and rewriting them in the same file with the updation of out time....
    with open('log.csv', mode='r') as file:
        reader = csv.DictReader(file)
        for row in reader:
            if ((row['status'] == 'in') & (row['uid'] == uid)):
                row['status'] = 'out'
                dateAndTime = getDateAndTime()
                date = dateAndTime['date']
                time_now = dateAndTime['time']
                row['out time'] = time_now
                temp.append(row)

            else:
                temp.append(row)
    with open("log.csv",mode="w", newline="\n") as file:
        keys = ['date','name','status','uid','roll no','in time','out time']
        writer = csv.DictWriter(file, fieldnames=keys, delimiter = ",")
        writer.writeheader()
        writer.writerows(temp)
    return(date,time_now)       #returning exit time and date for email use

def check_status(uid):
    with open('log.csv', mode='r') as file:
        ct = 0
        reader = csv.DictReader(file)
        for row in reader:
            if row['uid'] == uid:
                ct += 1
                if row['status'] == 'in':
                    return True

        else:
            return False

# read data continuously from Ultrasonic sensor
# once the distance becomes less trigger scan function
# msg in lcd
# if qr code is scanned successfully then verify the qr code
# msg in lcd
# After verification take the photo of the user
# msg in lcd
# log in time in the csv file if the user enters the club for the first time..
# msg in lcd
# send mail
# log the out time in the csv file once the user leaves the club
# msg in lcd
# send mail

# Main code