import collections
import logging
import pdb

import numpy as np
import yaml
import yamlordereddictloader

from generator import *
from generator import Generator, get_mem_props
from synthesis import ai_utils
from utils.logger import create_logger
from utils.visualizer import *

eff = 0.5

class Mapper:
    def __init__(self, hwfile="default.yaml", stats_file="logs/stats.txt"):
        """Mapper Class that Provides Interface for Different Mappings on the Architecture

        Args:
            hwfile (str, optional): . Defaults to "default.yaml".
            stats_file (str, optional): . Defaults to "logs/stats.txt".
        """
        base_dir = "configs/"
        self.total_cycles = 0
        self.technology = [1, 1, 40]
        # maybe change this later to peripheral logic node or speed
        #     [wire_cap , sense_amp_time, plogic_node],
        self.logger = create_logger(stats_file=stats_file)
        self.config = self.complete_config(
            yaml.load(open(base_dir + hwfile), Loader=yamlordereddictloader.Loader)
        )

    def complete_config(self, config):
        """
        1. Completes the Config for Hardware Description by using Technology/Design Functions
        2. Adds State Variables as Args that are Tracked for ASAP Mapping

        Args:
            config ():

        Returns:
            :
        """

        self.logger.debug("Config Statistics : ")

        self.mle = config["memory_levels"]
        self.mem_energy = np.zeros((self.mle))
        self.compute_energy = 0
        self.mem_read_access = np.zeros((self.mle))
        self.mem_write_access = np.zeros((self.mle))
        self.mem_size = np.zeros((self.mle))
        self.mem_util = np.zeros((self.mle))
        self.mem_free = np.zeros((self.mle))
        self.mem_read_bw = np.zeros((self.mle))
        self.mem_write_bw = np.zeros((self.mle))
        self.internal_bandwidth_time = 0
        self.total_cycles = 0
        self.bandwidth_idle_time = 0
        self.compute_idle_time = 0
        self.mem_size_idle_time = 0

        self.force_connectivity = config["force_connectivity"]
        mm_compute = config["mm_compute"]
        vector_compute = config["vector_compute"]

        if mm_compute["class"] == "systolic_array":
            config["mm_compute_per_cycle"] = (
                ((mm_compute["size"]) ** 2) * mm_compute["N_PE"] / (4)
            )
            config["comp_bw"] = (
                mm_compute["size"]
                * mm_compute["N_PE"]
                * mm_compute["frequency"]
                * 2
                / 4
            )

            self.logger.debug(
                "MM Compute per cycle : %d", config["mm_compute_per_cycle"]
            )
            self.logger.debug("Compute Bandwidth Required : %d", config["comp_bw"])

        if config["mm_compute"]["class"] == "mac":
            config["mm_compute_per_cycle"] = (mm_compute["size"]) * mm_compute["N_PE"]
            config["comp_read_bw"] = (
                mm_compute["size"] * mm_compute["N_PE"] * mm_compute["frequency"]
            )

        for i in range(self.mle):
            memory = config["memory"]["level" + str(i)]
            self.mem_read_bw[i] = (
                memory["frequency"]
                * memory["banks"]
                * memory["read_ports"]
                * memory["width"]
            )
            self.mem_write_bw[i] = (
                memory["frequency"]
                * memory["banks"]
                * memory["write_ports"]
                * memory["width"]
            )
            self.mem_size[i] = memory["size"]

            self.logger.debug(
                "Memory at Level %d, Read Bandwidth %d Write Bandwidth %d",
                i,
                self.mem_read_bw[i],
                self.mem_write_bw[i],
            )
        # complete_functional_config
        # complete_performance_config
        # memory
        for i in range(self.mle - 1):
            memory = config["memory"]["level" + str(i)]
            read_energy, write_energy, leakage_power, area = get_mem_props(
                memory["size"], memory["width"], memory["banks"]
            )
            config["memory"]["level" + str(i)]["read_energy"] = str(read_energy)
            config["memory"]["level" + str(i)]["write_energy"] = str(write_energy)
            config["memory"]["level" + str(i)]["leakage_power"] = str(leakage_power)
            config["memory"]["level" + str(i)]["area"] = str(area)
        # compute
        # config["memory"] = mem_space(config["memory"], technology)
        # config["mm_compute"] = comp_space(config["mm_compute"], technology)
        return config


#!/usr/bin/env python
#-*- coding: utf-8 -*-
#If this code works, it was written by Seunghyun Lee(www.bluebaynetworks.co.kr).
#If not, I don't know who wrote it

"""Functions for downloading and reading Korean Font data."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import cv2
import numpy as np
import tensorflow as tf

class DataSet(object):

  def __init__(self, images, labels, font_cnt, dtype=tf.float32):
    dtype = tf.as_dtype(dtype).base_dtype
    if dtype not in (tf.uint8, tf.float32):
      raise TypeError('Invalid image dtype %r, expected uint8 or float32' %
                      dtype)
    assert images.shape[0] == labels.shape[0], (
        'images.shape: %s labels.shape: %s' % (images.shape,
                                                labels.shape))
    self._num_examples = images.shape[0]

    # Convert shape from [num examples, rows, columns, depth]
    # to [num examples, rows*columns] (assuming depth == 1)
    assert images.shape[3] == 1
    images = images.reshape(images.shape[0], images.shape[1] * images.shape[2])
    if dtype == tf.float32:
      # Convert from [0, 255] -> [0.0, 1.0].
      images = images.astype(np.float32)
      images = np.multiply(images, 1.0 / 255.0)

    self._images = images
    self._labels = labels
    self._epochs_completed = 0
    self._index_in_epoch = 0
    self._font_cnt = font_cnt

  @property
  def images(self):
    return self._images

  @property
  def labels(self):
    return self._labels

  @property
  def num_examples(self):
    return self._num_examples

  @property
  def epochs_completed(self):
    return self._epochs_completed

  def find_label_index(self, val):
    for i in range(0, self._font_cnt):
      if(self._labels[i] == val):
        return i
    return None

  def next_image(self):
    ret_label = np.zeros((1, self._font_cnt), dtype=np.uint8)
    start = self._index_in_epoch
    self._index_in_epoch += 1

    if self._index_in_epoch == self._num_examples:
      self._index_in_epoch = 0
      #print('********** all char trained --> reset **********')

    ret_label[0][start] = 1

    return self._images[start:start + 1], ret_label

  def next_batch(self, batch_size):
    start = self._index_in_epoch
    self._index_in_epoch += batch_size

    if self._index_in_epoch >= self._num_examples:
      end = self._num_examples
      self._index_in_epoch = 0
      #print('********** all char trained --> reset **********')
    else:
      end = start + batch_size

    ret_label = np.zeros((end - start, self._font_cnt), dtype=np.uint8)
    index = 0
    #print('********** start:%d  end:%d **********'%(start, end))
    for i in range(start, end):
      ret_label[index][i] = 1
      index += 1

    return self._images[start:end], ret_label

#파일 이름에 포함된 index 숫자와 파일 내용을 리턴
def extract_image(filename):
  #Open font jpg files
  img = cv2.imread(filename)
  img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
  base=os.path.basename(filename)
  os.path.splitext(base)
  index = int(os.path.splitext(base)[0])
  return index, img

"""
모든 폰트 이미지를 검색해 파일 내용을 읽는다.
항상 같은 순서로 읽어야 하기 때문에 파일을 소팅해서 읽는 것이 안전하다.
특히 플랫폼이 바뀔 경우에 필요하다.
"""
def extract_images(dir_name, font_cnt):
  data = None
  labels = np.zeros(font_cnt, dtype=np.int32)
  count = 0
  for subdir, dirs, files in sorted(os.walk(dir_name)):
    for file in sorted(files):
      filename = os.path.join(subdir, file)
      index, ret = extract_image(filename)
      label = np.zeros(font_cnt, dtype=np.int32)
      labels[count] = index
      count += 1
      if(data is None):
        data = ret
      else:
        data = np.append(data, ret)
  data = data.reshape(count, 28, 28, 1)
  print('Data shape:', data.shape, ' Label shape:', labels.shape )
  return data, labels

"""
label은 MNIST와 달리 바로 사용하지 못한다.
실시간으로 batch 사이즈에 맞게 만들어 줘야 한다.
"""
def read_data_sets(train_dir, font_cnt):
  VALIDATION_SIZE = 500

  class DataSets(object):
    pass

  data_sets = DataSets()
  basicdir = train_dir + 'basic'
  shiftdir = train_dir + 'shift'
  rotatedir = train_dir + 'rotate'

  print('--------------- Loading basic font image --------------------')
  images, labels = extract_images(basicdir, font_cnt)
  data_sets.basic = DataSet(images, labels, font_cnt)
  print('--------------- Loading Shift1 font image --------------------')
  sdir = shiftdir + "1"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.shift1 = DataSet(images, labels, font_cnt)
  print('--------------- Loading Shift2 font image --------------------')
  sdir = shiftdir + "2"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.shift2 = DataSet(images, labels, font_cnt)
  print('--------------- Loading Shift3 font image --------------------')
  sdir = shiftdir + "3"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.shift3 = DataSet(images, labels, font_cnt)
  print('--------------- Loading Shift4 font image --------------------')
  sdir = shiftdir + "4"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.shift4 = DataSet(images, labels, font_cnt)

  print('--------------- Loading Rotate1 font image --------------------')
  sdir = rotatedir + "1"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.rotate1 = DataSet(images, labels, font_cnt)
  print('--------------- Loading Rotate2 font image --------------------')
  sdir = rotatedir + "2"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.rotate2 = DataSet(images, labels, font_cnt)
  print('--------------- Loading Rotate3 font image --------------------')
  sdir = rotatedir + "3"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.rotate3 = DataSet(images, labels, font_cnt)
  print('--------------- Loading Rotate4 font image --------------------')
  sdir = rotatedir + "4"
  images, labels = extract_images(sdir, font_cnt)
  data_sets.rotate4 = DataSet(images, labels, font_cnt)

  return data_sets

08 machine learning/1.0 Version code/input_korean.py


"""
给定一个数组 nums 和一个目标值 k，找到和等于 k 的最长子数组长度。如果不存在任意一个符合要求的子数组，则返回 0。
注意:
 nums 数组的总和是一定在 32 位有符号整数范围之内的。
示例 1:
输入: nums = [1, -1, 5, -2, 3], k = 3
输出: 4
解释: 子数组 [1, -1, 5, -2] 和等于 3，且长度最长。
示例 2:
输入: nums = [-2, -1, 2, 1], k = 1
输出: 2
解释: 子数组 [-1, 2] 和等于 1，且长度最长。
进阶:
你能使时间复杂度在 O(n) 内完成此题吗?

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/maximum-size-subarray-sum-equals-k
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
"""
from collections import defaultdict

class Solution:
    def maxSubArrayLen(self, nums: List[int], k: int) -> int:
        # 统计前缀和，比如[1,-1,5,-2,3] k=3
        # 前缀和为[1,0,5,3,6] 此时如果直接发现有等于k的，那么就是一个，然后发现6-3=3，也就是num[i]-num[j]=k 那就说明j+1到i这段的和为k
        # [-2,-1,2,1] k=1
        # [-2,-3,-1,0]
        sum_set = defaultdict(int)
        max_len = 0
        tmp_sum = 0
        sum_array = [0] * len(nums)
        for i in range(len(nums)):
            tmp_sum += nums[i]
            sum_array[i] = tmp_sum
            if tmp_sum not in sum_set:  # 记录最长的，第一次的肯定会比较长
                sum_set[tmp_sum] = i
            if tmp_sum == k:
                max_len = max(max_len, i + 1)
            if (tmp_sum - k) in sum_set:  # num[i]-num[j]==k
                max_len = max(max_len, i - sum_set[tmp_sum - k])
        return max_len

# 第二次
from collections import defaultdict
class Solution2:
    def maxSubArrayLen(self, nums: List[int], k: int) -> int:
        # [1,-1,5,-2,3] k=3
        # [1,0,5,3,6]
        # [-2,-1,2,1] k=1
        # [-2,-3,-1,0] -1--2=1 nums[i]-nums[j]=k -> j+1到i的和为k
        left,right=0,0
        max_len=0
        tmp_sum=0
        sum_dict=defaultdict(int)
        while(right<len(nums)):
            tmp_sum+=nums[right]
            if tmp_sum not in sum_dict: #记录最开始的那个位置就好了，最近
                sum_dict[tmp_sum]=right
            if tmp_sum==k:
                max_len=max(max_len,right+1)
            if tmp_sum-k in sum_dict:
                max_len=max(max_len,right-sum_dict[tmp_sum-k])

            right+=1
        return max_len

分类/滑动窗口/325.和等于k的最长子数组长度（2次）.py

325.和等于k的最长子数组长度（2次）.py


"""Unittest of redis state."""
from unittest.mock import MagicMock

import pytest
from pytest_mock.plugin import MockerFixture

from Arbie import StateError
from Arbie.Actions import Action, RedisState, Store
from Arbie.Actions.action import Argument

@pytest.fixture
def local_store():
    return Store()

@pytest.fixture
def redis_store(redis_state):
    return Store(redis_state)

class MockAction(object):
    in_variable_name = "pools"
    in_constant_name = "amount"
    out_variable_name = "tokens"

    redis_item_key = "arbie.1.amount"
    redis_collection_key = "arbie.1.pools"
    redis_collection_item_key = "arbie.1.pools.0xA1cB32"

    in_settings = {in_variable_name: "uniswap", in_constant_name: 1337}
    out_settings = {out_variable_name: "good_tokens"}

    in_settings_parsed = {
        in_variable_name: Argument("uniswap"),
        in_constant_name: Argument(1337),
    }

    redis_in_settings_parsed = {
        in_variable_name: Argument("arbie.1.pools"),
        in_constant_name: Argument(1337),
    }

    out_settings_parsed = {out_variable_name: Argument("good_tokens")}

class TestAction(object):
    def test_get_input_output_settings(self, mocker: MockerFixture):
        mocker.patch(
            "Arbie.Actions.action.yaml.safe_load",
            return_value={
                Action.input_key: MockAction.in_settings,
                Action.output_key: MockAction.out_settings,
            },
        )
        action = Action()
        assert MockAction.in_settings_parsed == action.get_input_settings()
        assert MockAction.out_settings_parsed == action.get_output_settings()

    @pytest.mark.asyncio
    async def test_on_next(self):
        with pytest.raises(NotImplementedError):
            await Action().on_next(None)

@pytest.fixture
def mock_action():
    mock = MagicMock()
    mock.get_input_settings.return_value = MockAction.in_settings_parsed
    mock.get_output_settings.return_value = MockAction.out_settings_parsed
    return mock

@pytest.fixture
def mock_action_redis():
    mock = MagicMock()
    mock.get_input_settings.return_value = MockAction.redis_in_settings_parsed
    mock.get_output_settings.return_value = MockAction.out_settings_parsed
    return mock

class TestStore(object):
    def test_get_raises(self, local_store):
        with pytest.raises(KeyError):
            local_store.get("key")

    def test_get_add(self, local_store):
        local_store.add("key", 1)
        assert local_store.get("key") == 1

    def test_create_input_value_error(self, local_store, mock_action):
        with pytest.raises(ValueError):
            local_store.create_input(mock_action)

    def test_create_input(self, local_store, mock_action):
        local_store.add("uniswap", 1337)
        local_store.create_input(mock_action)

    def test_publish(self, local_store: Store):
        with pytest.raises(StateError):
            local_store.publish("random channel", "random message")

    def test_subscribe(self, local_store: Store):
        with pytest.raises(StateError):
            local_store.subscribe("random channel")

    def test_delete(self, local_store: Store):
        with pytest.raises(StateError):
            local_store.delete("random key")

class TestRedisStore(object):
    def test_get_raises(self, redis_store):
        with pytest.raises(KeyError):
            redis_store.get("key")

    def test_get_add(self, redis_store):
        redis_store.add("key", 1)
        assert redis_store.get("key") == 1

    def test_store_get(self, redis_state, mocker: MockerFixture):
        mock_get = mocker.patch.object(RedisState, "__getitem__")
        store = Store(redis_state)

        store[MockAction.redis_item_key]  # noqa: WPS428
        assert mock_get.called

    def test_store_add(self, redis_state, mocker: MockerFixture):
        mock_set = mocker.patch.object(RedisState, "__setitem__")
        store = Store(redis_state)

        store.add(MockAction.redis_collection_key, None)
        assert mock_set.called

    def test_create_input_value_error(self, redis_store, mock_action):
        with pytest.raises(ValueError):
            redis_store.create_input(mock_action)

    def test_create_input(self, redis_store, mock_action):
        redis_store.add("uniswap", 1337)
        redis_store.create_input(mock_action)

    def test_create_input_from_redis(self, redis_store, mock_action_redis, mocker):
        mocker.patch.object(RedisState, "__contains__", return_value=True)
        redis_store.create_input(mock_action_redis)


# OS imports
from multiprocessing import cpu_count

# QLoRA imports
import torch
from peft import (
    PeftModel,
    PeftConfig
)
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    LlamaTokenizer,
    StoppingCriteria,
    StoppingCriteriaList,
    TextIteratorStreamer
)

# Web imports
from flask import (
    Flask,
    render_template,
    request,
    redirect,
    url_for
)

app = Flask(__name__)
app.config['TEMPLATES_AUTO_RELOAD'] = True

experts = ['Default', 'Physics', 'Biology']

# Loading model and adapters
model_id = 'facebook/opt-1.3b'

m = AutoModelForCausalLM.from_pretrained(
    model_id,
    torch_dtype=torch.bfloat16
)

# Physics adapter
peft_config = PeftConfig.from_pretrained('./data/physics')
m.add_adapter(peft_config, adapter_name='Physics')

# Biology adapter
peft_config = PeftConfig.from_pretrained('./data/biology')
m.add_adapter(peft_config, adapter_name='Biology')

tok = AutoTokenizer.from_pretrained(model_id)

torch.set_num_threads(cpu_count())

@app.route('/')
def index():
    return redirect(url_for('chat', expert='Default'))

@app.post('/expert')
@app.post('/expert/')
def selectExpert():
    body = request.form
    expert_name = body.get('expert')
    if expert_name == None or not expert_name in experts:
        return redirect(url_for('index'))
    return redirect(url_for('chat', expert=expert_name))

@app.route('/chat/<expert>')
def chat(expert):
    return render_template('index.html', experts=experts, expert=expert)

@app.post('/message')
@app.post('/message/')
def genMessage():
    body = request.get_json()
    expert = body.get('expert')
    if not expert:
        m.disable_adapters()
    else:
        if expert != 'Default' and expert in experts:
            m.enable_adapters()
            m.set_adapter(expert)
        else:
            m.disable_adapters()

    prompt = body.get('message')
    if not prompt:
        return {'error': 'Message field is required'}

    response_msg = ''

    prompt = prompt + '\nA.'

    inputs = tok(prompt, return_tensors='pt').input_ids

    try:
        with torch.no_grad():
            outputs = m.generate(
                input_ids=inputs,
                do_sample=True,
                max_new_tokens=40
            )

            outputs = tok.batch_decode(
                outputs.detach().cpu().numpy()
            )
            outputs = outputs[0]

            outputs = outputs.split('\nA.')
            outputs = outputs[1]

            if outputs.find('.') > 0:
                outputs = outputs.split('.')[:-1]

            if len(outputs[-1].strip()) <= 1:
                outputs = outputs[:-1]

            if type(outputs) is list:
                outputs = list(map(lambda a: a.strip(), outputs))

            outputs = '. '.join(outputs)

            if not outputs[-1] in '!?.':
                outputs += '.'

            try:
                outputs = outputs.split('\n')[0]
            except:
                pass

            response_msg = outputs
    except:
        pass

    return {'message': response_msg}

print('--- App is ready! ---')


import pygame

# Function to check for collisions
def checkCollision(x,y,treasureX,treasureY, width, height):
  # Use global keyword to declare global variables
  global screen, textWin

  collisionState = False

  # Check if playerImage touches the treasureImage
  if (y >= treasureY and y <= treasureY + height):
    if (x >= treasureX and x <= treasureX + width):
      # Move playerImage back to original starting position
      y = 550
      x = 0
      collisionState = True
    elif (x + width >= treasureX and x + width <= treasureX + width):
      y = 550
      x = 0
      collisionState = True
  elif (y + height >= treasureY and y + height <= treasureY + height):
    if (x >= treasureX and x <= treasureX + width):
      y = 550
      x = 0
      collisionState = True
    elif (x + width >= treasureX and x + width <= treasureX + width):
      y = 550
      x = 0
      collisionState = True
  return collisionState, y, x

# Initialize Pygame Library
pygame.init()

# Display is an object inside Pygame
# Set Mode method creates a screen with the size inputted
screen = pygame.display.set_mode((1000,700))

# Variable to keep track if our game is finished
finished = False

# Set x & y coordinates
x = 0
y = 550

# Load player image to playerImage variable
playerImage = pygame.image.load("rocket.png")

# Scale and transform Image to fit rectangle
playerImage = pygame.transform.scale(playerImage, (40, 160))

# Make playerImage ready for game
playerImage = playerImage.convert_alpha()

# Load background image to backgroundImage variable
backgroundImage = pygame.image.load("space.jpg")

# Scale and transform Image to fit the screen
backgroundImage = pygame.transform.scale(backgroundImage, (1000,700))

# Put background image into the window
screen.blit(backgroundImage, (0,0))

# Load earth image to earthImage variable
earthImage = pygame.image.load("earth.png")

# Scale and transform Image to be smaller than the playerImage
earthImage = pygame.transform.scale(earthImage, (100, 100))

# Make earthImage ready for game
earthImage = earthImage.convert_alpha()

# Load treasure image to treasureImage variable
treasureImage = pygame.image.load("mars.png")

# Scale and transform Image to be smaller than the playerImage
treasureImage = pygame.transform.scale(treasureImage, (100, 100))

# Make treasureImage ready for game
treasureImage = treasureImage.convert_alpha()

# Load enemy image to enemyImage variable
enemyImage = pygame.image.load("asteroid.png")

# Scale and transform enemyImage
enemyImage = pygame.transform.scale(enemyImage, (35,40))

# Make enemyImage ready for game
enemyImage = enemyImage.convert_alpha()

# Set Earth coordinates
earthX = -40
earthY = 640

# Set treasure coordinates
treasureX = 890
treasureY = 10

# Set enemy coordinates
enemyX = 200
enemyY = 500

# Put treasure image into the window
screen.blit(treasureImage, (treasureX, treasureY))

# Get font from Pygame and store in font variable
font = pygame.font.Font("MuktaMahee.ttf", 60)

# Create Levels variable
level = 1

# Enemy Names Dictionary
enemyNames = {0:"Jeff",1:"Jeff",2:"Jeff",3:"Jeff",4:"Jeff",5:"Jeff",6:"Jeff",7:"Jeff",8:"Jeff"}

# Create a Clock and store in frame variable
frame = pygame.time.Clock()

# Define if the playerImage has collided with the treasure
collisionTreasure = False

# Define if the playerImage has collided with the enemy
collisionEnemy = False

# Determines the direction the enemy is moving
movingUp = True

# Empty string for collision enemy
name = ""

# Create list of enemies with each item in the list as a tuple
enemies = [(enemyX, enemyY, movingUp)]

# While our game is not finished
while (finished == False):
  # get() method gives us all of the events that have happened since last check
  for event in pygame.event.get():
    # Looking at Event type. If type is a Quit Event then finish the game
    if event.type == pygame.QUIT:
      finished = True

  # Check if key is pressed
  pressedKeys = pygame.key.get_pressed()

  enemyIndex = 0

  # For loop to move each enemy
  for enemyX,enemyY,movingUp in enemies:
    # If enemy is about to reach the bottle of the screen then movingUp equals true
    if (enemyY >= 665):
      movingUp = True
    # If enemy is about to reach the bottle of the screen then movingUp equals false
    elif (enemyY <= 10 ):
      movingUp = False

    # If movingUp is true then move enemy up
    if movingUp == True:
      # Scale movement depending on the level
      enemyY -= 10 * level
    # Else if movingUp is false then move enemy down
    else:
      # Scale movement depending on the level
      enemyY += 10 * level
    enemies[enemyIndex] = (enemyX, enemyY, movingUp)
    enemyIndex += 1

  # If Space Key is pressed then increase the y coordinate by 5
  if (pressedKeys[pygame.K_DOWN] == 1):
    y += 30
  elif (pressedKeys[pygame.K_UP] == 1):
    y -= 30
  elif (pressedKeys[pygame.K_LEFT] == 1):
    x -= 30
  elif (pressedKeys[pygame.K_RIGHT] == 1):
    x += 30

  # Store rectangle object in a variable
  # Define x, y, width, and height of rectangle
  # rectOne = pygame.Rect(x,y,30,30)

  # Create a tuple to hold a color
  color = (0,0,255)
  # Define the color black in a variable
  white = (255,255,255)

  # Overwrite the original blue rectangle to black before creating a new one
  # screen.fill((white))

  # Fill background image onto the screen
  screen.blit(backgroundImage, (0,0))

  # Put earth image onto the screen
  screen.blit(earthImage, (earthX, earthY))

  # Put treasure image onto the screen
  screen.blit(treasureImage, (treasureX, treasureY))

  # Put playerImage into window
  screen.blit(playerImage, (x, y))

  # Create enemy index counter
  enemyIndex = 0
  # For loop to load each enemy into the window
  for enemyX, enemyY, movingUp in enemies:
    # Put enemyImage into window
    screen.blit(enemyImage, (enemyX, enemyY))
    # Call checkCollision function and store in variables
    collisionEnemy, y, x = checkCollision(x,y,enemyX,enemyY,35,40)
    # Check if player collided with enemy
    if (collisionEnemy == True):
      # Assign name variable value from enemyNames dictionary
      name = enemyNames[enemyIndex]
      # Create text object and display that the player got destroyed
      textLose = font.render("You were destroyed by the asteroid "+name, True, (255,0,0))
      # Display textLose on the screen and center the text
      screen.blit(textLose, (500 - textLose.get_width()/2, 350 - textLose.get_height()/2))
      # Update the screen
      pygame.display.flip()
      # Slow down frame to make text appear slower
      frame.tick(1)
    # Create frame rate (frames per second)
    frame.tick(30)
    # Increment enemyIndex counter
    enemyIndex += 1

  # Call checkCollision function and store in variables
  collisionTreasure, y, x = checkCollision(x,y,treasureX,treasureY,100,100)

  # Refactor checkCollisions function to make it DRY (Don't Repeat Yourself)
  if (collisionTreasure == True):
    # Increment Level
    level += 1
    # Add new enemy to enemies list
    enemies.append((enemyX + 100, enemyY - 300, False))
    # Create text object and display level that user is on
    textWin = font.render("You've reached level " + str(level), True, (255,255,255))
    # Display textWin on the screen and center the text
    screen.blit(textWin, (500 - textWin.get_width()/2, 350 - textWin.get_height()/2))
    # Update the screen
    pygame.display.flip()
    # Slow down frame to make text appear slower
    frame.tick(1)

  # Draws rectangle onto the screen, need to input screen, color, and rectangle object
  # pygame.draw.rect(screen, color, rectOne)

  # Update the screen
  pygame.display.flip()

  # Create frame rate (frames per second)
  frame.tick(30)


import json
import os.path as pth
import base64
from io import BytesIO

import pandas as pd
import numpy as np

import matplotlib.pyplot as plt

import PIL
import PIL.ImageDraw

from jinja2 import Template

import torch
import torch.nn as nn
import torch.nn.functional as F

from torch.utils.data import DataLoader

import models.questioner
import models.answerer

import misc.utilities as utils
import misc.dataloader

# COCO meta-data
# TODO: not portable
coco_path = 'datasets/coco/'
vqa_s3_path = 'https://vqa_mscoco_images.s3.amazonaws.com'
with open(pth.join(coco_path, 'coco.json'), 'r') as f:
    cocoj = json.load(f)
cid_to_file = {d['id']: d['file_path'] for d in cocoj['images']}

# CUB meta-data
cub_meta_path = 'data/cub_meta.json'
with open(cub_meta_path, 'r') as f:
    cub_meta = json.load(f)
cub_img_id_to_idx = {im['img_id']: idx for idx, im in enumerate(cub_meta['images'])}

# AWA meta-data
awa_meta_path = 'data/awa_meta.json'
with open(awa_meta_path, 'r') as f:
    awa_meta = json.load(f)
awa_img_id_to_idx = {im['img_id']: idx for idx, im in enumerate(awa_meta['images'])}

def load_image_path(img_id, size=None, dataset_name='VQA', local=True):
    if dataset_name == 'VQA':
        coco_id = img_id
        fname = cid_to_file[coco_id]
        if local:
            file = pth.join(coco_path, 'images', fname)
        else:
            file = '/'.join([vqa_s3_path, fname.lstrip('/')])
    elif dataset_name == 'CUB':
        img_idx = cub_img_id_to_idx[img_id]
        file = cub_meta['images'][img_idx]['img_path']
    elif dataset_name == 'AWA':
        img_idx = awa_img_id_to_idx[img_id]
        file = awa_meta['images'][img_idx]['img_path']
    return file

def load_image(img_id, size=None, dataset_name='VQA'):
    file = load_image_path(img_id, size=size, dataset_name=dataset_name)
    img = PIL.Image.open(file).convert('RGB')
    if size is not None:
        img = img.resize(size)
    return img, file

def img_to_datauri(fname=None, pil_image=None, torch_image=None, size=None):
    if fname:
        assert fname[-3:] == 'jpg'
        with open(fname, 'rb') as f:
            data = base64.b64encode(f.read())
    elif pil_image:
        buffer = BytesIO()
        pil_image.save(buffer, format='jpeg')
        data = base64.b64encode(buffer.getvalue())
    elif torch_image is not None:
        pil_image = PIL.Image.fromarray(torch_image.numpy())
        if size is not None:
            pil_image = pil_image.resize(size)
        return img_to_datauri(pil_image=pil_image)
    return 'data:image/jpeg;base64,{}'.format(data.decode('utf-8'))

def get_questions(batch, qbot, z_source, inference, ind2word, nsamples=1,
                  manualz=None):
    imgs = batch['img_pool']
    #imgs, ques = batch['img_pool'], None
    output = []
    z_inference, dec_inference = inference
    if z_source is not None and z_source[:6] == 'manual':
        assert len(manualz) == nsamples
    qbot.tracking = True
    for ns in range(nsamples):
        qbot.reset()
        qbot.observe(images=batch['img_pool'])
        qbot.observe(start_question=True)
        qbot.observe(start_answer=True)
        if 'ques' in batch:
            qbot.observe(ques=batch['ques'],
                         ques_len=batch['ques_len'],
                         gt_ques=True)
        if z_source[:6] == 'manual':
            zs = manualz[ns]
        else:
            zs = z_source
        gen = qbot.forwardDecode(dec_inference=dec_inference,
                                 z_inference=z_inference,
                                 z_source=zs)

        qidx, qlen, _ = gen
        z = qbot.z
        gen_ques_str = utils.old_idx_to_str(ind2word, qidx, qlen,
                                            batch['img_id_pool'], 0, [])
        gen_ques_str = [q[0].strip('<START> ') for q in gen_ques_str]
        gen_ques_str = [q.strip(' <END>') for q in gen_ques_str]
        output.append((gen_ques_str, show_z(z, qbot)))
    return list(zip(*output))

def single_dim_manual_z(zs, qbot, dim):
    K = qbot.num_embeddings
    V = qbot.num_vars
    K = min(K, 10)
    newz = []
    assert len(zs) == 1, 'start with greedy version'
    for samplei in range(len(zs)):
        newz.append([])
        for exi in range(len(zs[samplei])):
            z = zs[samplei][exi][1]
            z = z.reshape([V, -1])
            _, ix = z.max(dim=1, keepdim=True)
            onehotz = torch.zeros_like(z).scatter_(1, ix, 1.0)
            onehotz = onehotz.reshape(-1)
            newz[samplei].append(onehotz)
        newz[samplei] = torch.stack(newz[samplei])
    # nsamples x nbatch x qbot._num_embeddings
    newz = torch.stack(newz)
    newz = newz.reshape(newz.shape[:2] + (V, K))
    newz = newz.repeat(K, 1, 1, 1)
    for k in range(K):
        newz[k, :, dim, :] = 0
        newz[k, :, dim, k] = 1.0
    newz = newz.reshape(newz.shape[:2] + (V * K,))
    return newz

def interp_manual_z(z, replications=1, max_len=200):
    assert len(z) == 1
    samplei = 0
    targeti = 0
    z_paths = []
    for exi in range(len(z[0])):
        zsource = z[samplei][exi][1]
        ztarget = z[samplei][targeti][1]

        change_idxs = (ztarget - zsource).nonzero().sort()[0]
        change_idxs.shape

        z_list = [zsource]
        z_len = change_idxs.shape[0] + 1

        if z_len > max_len:
            print('z_len {} exceeds max_len {}'.format(z_len, max_len))

        for i in change_idxs:
            newz = z_list[-1].clone()
            newz[i] = ztarget[i]
            for _ in range(replications):
                z_list.append(newz)

        z_list = z_list + z_list[-1:] * (max_len - len(z_list))
        z_exi_path = torch.stack(z_list[:max_len])
        z_paths.append(z_exi_path[:, None, :])

    z_paths = torch.cat(z_paths, dim=1)
    return z_paths

def show_z(z, qbot):
    number_of_vars_to_show = 10
    z, _ = z
    if qbot.varType == 'cont':
        return [('{:.3f}'.format(z[0][i, :].mean().item()), z[0][i]) for i in range(z[0].shape[0])]
        #return [('z', z[0][i]) for i in range(z[0].shape[0])]
    K = qbot.num_embeddings
    V = qbot.num_vars
    vs = []
    for v in range(V):
        _, v_idx = z[:, v*K:(v+1)*K].max(dim=1)
        vs.append(v_idx)
    vs = torch.stack(vs, dim=0).t().tolist()
    return [('_'.join(['{:0>2d}'.format(iv) for iv in i_vars][:number_of_vars_to_show]) + '...', z[i]) for i, i_vars in enumerate(vs)]

def pool_atten_uris(img_attn, side_length=30, cm=plt.get_cmap('viridis'), wrap_period=4):
    N, ps = img_attn.shape
    nrows = (ps-1) // wrap_period + 1
    ncols = ps if nrows == 1 else wrap_period

    imgs = []
    for exi in range(N):
        img = PIL.Image.new('RGB', (ncols * side_length, nrows * side_length), 'black')
        draw = PIL.ImageDraw.Draw(img)
        for i in range(ps):
            row = i // wrap_period
            col = i % wrap_period
            att_color = tuple([int(255 * t) for t in cm(float(img_attn[exi][i]))])
            top_left = (col * side_length, row * side_length)
            bottom_right = ((col+1) * side_length, (row+1) * side_length)
            draw.rectangle([top_left, bottom_right], fill=att_color)
        img = img_to_datauri(pil_image=img)
        imgs.append(img)
    return imgs

def bottomup_heatmap_image(img, att, spatial, cm=plt.get_cmap('viridis')):
    global hi1
    # color the background according to the colormap because everything's too small to see
    img[:] = 255.
    H, W, _ = img.shape
    n_obj, = att.shape
    att_img = torch.zeros(img.shape)
    left =   (spatial[:, 0] * W).to(torch.int).clamp(0, W-1)
    top =    (spatial[:, 1] * H).to(torch.int).clamp(0, H-1)
    right =  (spatial[:, 2] * W).to(torch.int).clamp(0, W-1)
    bottom = (spatial[:, 3] * H).to(torch.int).clamp(0, H-1)
    for k in range(n_obj):
        t, b, l, r = top[k], bottom[k], left[k], right[k]
        # this version is just black and white without using a color map
        att_img[t:b, l:r] += att[k] * img[t:b, l:r].to(att.dtype)
    att_img = att_img[:, :, 0].detach().numpy() / 255
    att_img = 255 * torch.tensor(cm(att_img))[:, :, :3]
    return att_img.to(img.dtype)

def region_att_images(img_pool_ids, region_attn, img_pool_spatial, dataset_name):
    aimgs = []
    N, pool_size = img_pool_ids.shape
    for exi in range(N):
        aimgs.append([])
        for pi in range(pool_size):
            img, _ = load_image(img_pool_ids[exi][pi].item(), size=(50, 50),
                                dataset_name=dataset_name)
            img = torch.tensor(np.array(img))
            att = region_attn[exi, pi]
            spatial = img_pool_spatial[exi, pi]
            aimg = bottomup_heatmap_image(img, att, spatial)
            aimg = img_to_datauri(torch_image=aimg)
            aimgs[-1].append(aimg)
    return aimgs


#!/usr/bin/python
from enum import Enum
import re
import argparse
import sys

class MatchedLineFormat(Enum):
    """Defines different formatting formats for printing pattern matching lines in files"""
    DEFAULT = 1
    UNDERSCORE = 2
    COLOR = 3
    MACHINE = 4

class MatchedLineFormatterFactory:
    """As the pattern matching lines can be presented in 4 different formats (default, underscored,
    colored and machine readable), we will use the factory pattern to instantiate a corresponding
    MatchedLineFormatter for each one.

    Note: this class is an adaptation of the example explained here:
    https://realpython.com/factory-method-python/#supporting-additional-formats
    """

    def __init__(self):
        self._formatters = {}

    def register_format(self, matched_line_format, formatter):
        """Registers a MatchingLineFormatter class for a MatchedLineFormat """
        self._formatters[matched_line_format] = formatter

    def get_formatter(self, matched_line_format):
        """Obtains a MatchingLineFormatter object for a MatchedLineFormat, or an error if not supported """
        formatter = self._formatters.get(matched_line_format)
        if not formatter:
            raise ValueError(matched_line_format)
        return formatter()

class DefaultMatchedLineFormatter:
    """Formats the information related to pattern matched lines in a file using the Default format
    (see details in the format method)
    """

    # noinspection PyMethodMayBeStatic
    def format(self, filename, line_number, line, pattern_match_intervals):
        """
        Returns a string containing the information provided by the input parameters (related to pattern matched
        lines in a file) using this formatting:

        filename:line_number:line

        In case of having multiple matches in the same line the resulting string will have just one line
        for all occurrences, as all are in the same line_number.

        :param filename: Filename of the file being parsed
        :param line_number: Line number
        :param line: String containing the actual line of the file being processed
        :param pattern_match_intervals: Set of tuples (start, end) where the pattern has been found in the line
        :return: Formatted string
        """

        formatted_line = filename + ":" + str(line_number) + ":" + line

        return formatted_line.strip()

class ColorMatchedLineFormatter:
    """Formats the information related to pattern matched lines in a file coloring the matching text
    (see details in the format method)
    """

    CHAR_FORMAT_START_PURPLE = '\033[95m'
    CHAR_FORMAT_END = '\033[0m'

    # noinspection PyMethodMayBeStatic
    def format(self, filename, line_number, line, pattern_match_intervals):
        """
           Returns a string containing the information provided by the input parameters (related to pattern matched
           lines in a file) using this formatting:

           filename:line_number:line (coloring the matching text)

           :param filename: Filename of the file being parsed
           :param line_number: Line number
           :param line: String containing the actual line of the file being processed
           :param pattern_match_intervals: Set of tuples (start, end) where the pattern has been found in the line
           :return: Formatted string
        """

        formatted_line = filename + ":" + str(line_number) + ":"

        last_match_end = 0
        for interval in pattern_match_intervals:
            formatted_line += line[last_match_end:interval[0]] + ColorMatchedLineFormatter.CHAR_FORMAT_START_PURPLE + \
                              line[interval[0]:interval[1]] + ColorMatchedLineFormatter.CHAR_FORMAT_END
            last_match_end = interval[1]
        formatted_line += line[last_match_end:]

        return formatted_line

class UnderscoreMatchedLineFormatter:
    """Formats the information related to pattern matched lines in a file underscoring ^^^ the matching text
      (see details in the format method)
    """

    # noinspection PyMethodMayBeStatic
    def format(self, filename, line_number, line, pattern_match_intervals):
        """
           Returns a string containing the information provided by the input parameters (related to pattern matched
           lines in a file) using this formatting:

            filename:line_number:line (with ^^^^ under the matching text)

           :param filename: Filename of the file being parsed
           :param line_number: Line number
           :param line: String containing the actual line of the file being processed
           :param pattern_match_intervals: Set of tuples (start, end) where the pattern has been found in the line
           :return: Formatted string
        """

        prefix = filename + ":" + str(line_number) + ":"
        formatted_line = prefix + line
        underscored_line = [' '] * len(formatted_line)

        for interval in pattern_match_intervals:
            for i in range(interval[0] + len(prefix), interval[1] + len(prefix)):
                underscored_line[i] = "^"

        return formatted_line + "\n" + "".join(underscored_line)

class MachineReadableMatchedLineFormatter:
    """Formats the information related to pattern matched lines in a file using a machine readable formatting
         (see details in the format method)
    """

    # noinspection PyMethodMayBeStatic
    def format(self, filename, line_number, line, pattern_match_intervals):
        """
        Returns a string containing the information provided by the input parameters (related to pattern matched
        lines in a file) using this formatting:
            filename:line_number:start_pos:matched_text

        In case there are multiple matches several lines will be added:
            filename:line_number:start_pos1:matched_text
            filename:line_number:start_pos2:matched_text

        :param filename: Filename of the file being parsed
        :param line_number: Line number
        :param line: String containing the actual line of the file being processed
        :param pattern_match_intervals: Set of tuples (start, end) where the pattern has been found in the line
        :return: Formatted string
        """
        formatted_line = ""
        prefix = filename + ":" + str(line_number) + ":"

        for interval in pattern_match_intervals:
            formatted_line = formatted_line + prefix + str(interval[0]) + ":" + line[interval[0]:interval[1]] + "\n"

        return formatted_line.strip()

def find_pattern_in_string(input_string, pattern):
    """
    Search for all non-overlapping matches of a pattern in a string

    :param input_string: String where to search the pattern
    :param pattern: Regular expression with the pattern to search
    :return: list of intervals (match start, match end) of input_string where the pattern has been found.
    """
    if not pattern:
        raise ValueError("pattern can't be empty")

    match_intervals = []
    cre = re.compile(pattern)

    for match in cre.finditer(input_string):
        match_intervals.append((match.start(), match.end()))

    return match_intervals

def find_pattern_in_files(files, pattern, print_line_format):
    """
    Search for a pattern in a list of files (or in stdin if none is provided) and print the
    matching lines using the format specified in print_line_format

    :param files: Files to be processed. stdin will be used if none is provided
    :param pattern: Regular expression with the pattern to search
    :param print_line_format: Format to use when printing the matching lines
    """
    factory = MatchedLineFormatterFactory()

    factory.register_format(MatchedLineFormat.DEFAULT, DefaultMatchedLineFormatter)
    factory.register_format(MatchedLineFormat.COLOR, ColorMatchedLineFormatter)
    factory.register_format(MatchedLineFormat.UNDERSCORE, UnderscoreMatchedLineFormatter)
    factory.register_format(MatchedLineFormat.MACHINE, MachineReadableMatchedLineFormatter)
    line_formatter = factory.get_formatter(print_line_format)

    if files is not None:
        for filename in files:
            with open(filename, 'r') as f:
                for line_number, line in enumerate(f, start=1):
                    match_intervals = find_pattern_in_string(line.strip(), pattern)
                    if len(match_intervals) > 0:
                        print(line_formatter.format(filename, line_number, line.strip(), match_intervals))
            f.close()
    else:
        line_number = 0
        for line in sys.stdin:
            line_number += 1
            match_intervals = find_pattern_in_string(line.strip(), pattern)
            if len(match_intervals) > 0:
                print(line_formatter.format("-", line_number, line.strip(), match_intervals))

if __name__ == '__main__':
    # Construct the argument parser
    ap = argparse.ArgumentParser()

    # Add the arguments to the parser
    ap.add_argument("-r", "--regex", required=True, help="regexp to search")
    ap.add_argument("-f", "--files", metavar='FILE', nargs='*', help='files to read, if empty, stdin is used')

    # Create a group for mutually exclusive arguments
    group = ap.add_mutually_exclusive_group()
    group.add_argument("-u", "--underscore", help="prints '^' under the matching text", action="store_true")
    group.add_argument("-c", "--color", help="highlight the matching text", action="store_true")
    group.add_argument("-m", "--machine", help="generate machine-readable output format:\n  "
                                               "file_name:no_line:start_pos:matched_text", action="store_true")
    args = ap.parse_args()

    if args.underscore:
        find_pattern_in_files(args.files, args.regex, MatchedLineFormat.UNDERSCORE)
    elif args.color:
        find_pattern_in_files(args.files, args.regex, MatchedLineFormat.COLOR)
    elif args.machine:
        find_pattern_in_files(args.files, args.regex, MatchedLineFormat.MACHINE)
    else:
        find_pattern_in_files(args.files, args.regex, MatchedLineFormat.DEFAULT)


import matplotlib.pyplot as plt

friends = [70,65,72,63,71,64,60, 64,67]
minuts = [175,170,205,120,220,130,105,145,190]
labels = ['a','b','c','d','e','f','g','h','i']

plt.scatter(friends,minuts)

for l,f,m in zip(labels,friends,minuts):
    plt.annotate(l,xy=(f,m), xytext=(5,-5), textcoords='offset points')
plt.ax
plt.show()


import numpy
from numba import njit
from The_Treachery_of_Whales import DATA

def partOne(data: list, minimum: int=None, maximum: int=None) -> int:
    if not minimum or not maximum:
        minimum: int = min(data) if not minimum else minimum
        maximum: int = max(data) if not maximum else maximum

    fuel_calc: dict = {}
    for endPoint in range(minimum, maximum + 1):
        fuel_calc[endPoint] = 0
        for startPoint in data:
            fuel_calc[endPoint] += abs(endPoint - startPoint)

    return min([position for position in fuel_calc.values()])

@njit
def partTwo(data: list, minimum: int=0, maximum: int=0) -> int:
    if not minimum or not maximum:
        minimum: int = min(data) if minimum == 0 else minimum
        maximum: int = max(data) if maximum == 0 else maximum

    fuel_calc: dict = {}
    for endPoint in numpy.arange(minimum, maximum + 1, dtype=numpy.int64):
        fuel_calc[endPoint] = 0
        for startPoint in data:
            difference: int = numpy.fabs(startPoint - endPoint)
            # Gauss Method: Sn = 1/2 * abs(begin-end) * (abs(begin-end) + 1)
            fuel_calc[endPoint] += int(0.5 * difference * (difference + 1))

    return min([position for position in fuel_calc.values()])

def main() -> None:
    print(partOne(DATA))

    partTwo(numpy.array([0], dtype=numpy.int64)) # partTwo Numba initialisation
    print(partTwo(numpy.array(DATA, dtype=numpy.int64)))

if __name__ == "__main__":
    main()

2021/Day 7/Day 7 - The Treachery of Whales.py


import sys
from bs4 import BeautifulSoup
import requests

BASE_URL = 'http://admission.cuas.or.th/%s/toppage.html'
MAJOR_URL = 'http://admission.cuas.or.th/%s/search_fac.php?q='

def extract_options(html):
    html.encoding = 'tis-620'
    soup = BeautifulSoup(html.text, 'html.parser')
    return soup.find('select').find_all('option')

def extract_major_name(str):
    items = str.split()
    return ' '.join(items[1:])

def main():
    if len(sys.argv) != 2:
        year_prefix = 'adm60maxmn'
    else:
        year_prefix = sys.argv[1]

    main_url = BASE_URL % (year_prefix,)

    html = requests.get(main_url)
    for opt in extract_options(html):
        uname = opt.text.strip()
        unumber = opt.attrs['value']

        if unumber == '000':
            continue

        major_query_url = (MAJOR_URL % (year_prefix,)) + unumber

        major_html = requests.get(major_query_url)
        majors = extract_options(major_html)
        for m in majors:
            mname = extract_major_name(m.text.strip())
            mnumber = m.attrs['value']

            if mnumber == '0000':
                continue

            items = [mnumber, mname, unumber, uname]
            print(','.join(['"%s"' % s for s in items]))

if __name__=='__main__':
    main()


from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.http import Http404
from django.core import serializers
from django.db.models import Sum

from shopping_registry import accountVerification
from shopping_registry import totalCalculations
from shopping_registry import graphGeneration

from .models import Purchase
from .forms import PurchaseForm

import json
import datetime

def index(request):
    """The home page for Registro-Super."""
    return render(request, 'shopping_registry/index.html')

@login_required
def dates(request):
    """Shows all dates."""
    dates = []

    purchases = Purchase.objects.filter(owner=request.user).order_by('-date_purchase')

    for purchase in purchases:
        if purchase.date_purchase not in dates:
            dates.append(purchase.date_purchase)

    context = {'dates': dates}
    return render(request, 'shopping_registry/dates.html', context)

@login_required
def date(request, date):
    """Shows all the information for a day's purchases."""

    date_string = date
    date = datetime.datetime.strptime(date, '%Y-%m-%d')

    purchases = Purchase.objects.filter(date_purchase=date, owner=request.user)

    total = totalCalculations.calculate_total(purchases)

    products = []

    quantities = []

    prices = []

    ind_prices = []

    # Stores the name of the product, its individual price and its bulk's boolean
    # value
    dictionary = {}

    categories = []

    categories_total = totalCalculations.total_categories(purchases)

    bulk = []

    for purchase in purchases:
        products.append(purchase.product)
        quantities.append(purchase.quantity)
        prices.append(purchase.price)
        bulk.append(purchase.bulk)

    for x in range(0, len(products)):
        if purchases[x].category.title() not in categories:
            categories.append(purchases[x].category.title())

        if bulk[x] == True:
            # If it was a bulk purchase, multiply by 100 to display the price per
            # 100 grams.
            ind_prices.append(float((prices[x] / quantities[x]) * 100))
        else:
            ind_prices.append(float((prices[x] / quantities[x])))

        ind_prices[x] = round(ind_prices[x], 2)

        dictionary[x] = {'Nombre': purchases[x], 'Categoria': purchases[x].category,
            'Bulk': bulk[x], 'Precio': ind_prices[x]}

    # Product and Price visualization

    # Convert the prices list QuerySet to a list of floats.
    prices_float = [float(price) for price in prices]

    # Generating the charts.
    # Bar chart.
    bar_graph = graphGeneration.generateBarGraph(products, prices_float)

    # Pie chart.
    pie_graph = graphGeneration.generatePieGraph(categories_total)

    context = {'date': date, 'date_string': date_string, 'purchases': purchases, 'total':total,
        'products':products, 'ind_prices':ind_prices, 'dictionary': dictionary,
        'categories': categories, 'categories_total': categories_total,
        'bar_graph': bar_graph, 'pie_graph': pie_graph}
    return render(request, 'shopping_registry/date.html', context)

@login_required
def edit_purchase(request, purchase_id):
    """Edit an existing purchase."""
    purchase = get_object_or_404(Purchase, id=purchase_id)

    # Checks if user is using demo account and is the owner of the object.
    accountVerification.check_account(request.user.username, purchase)

    date = purchase.date_purchase

    # Passes the data to the form template.
    formatedDate = date.strftime("%m/%d/%Y")

    initial_dict = {
        "date_purchase" : formatedDate,
        "bulk": True,
    }

    if request.method != 'POST':
        # Initial request; pre-fill form with the current purchase.
        form = PurchaseForm(instance=purchase, initial=initial_dict)
    else:
        # POST data submitted; process data.
        form = PurchaseForm(data=request.POST, instance=purchase)

        if form.is_valid():
            edited_purchase = form.save(commit=False)
            edited_purchase.owner = request.user
            edited_purchase.save()
            return redirect('shopping_registry:date', date=date)

    context = {'purchase': purchase, 'form': form, 'date': formatedDate}
    return render(request, 'shopping_registry/edit_purchase.html', context)

@login_required
def erase_date_confirmation(request, date_string):
    """Confirm the deletion of the purchases done on the selected date."""

    accountVerification.check_account(request.user.username)

    purchases = Purchase.objects.filter(date_purchase=date_string, owner=request.user)

    # Date is stored in string 'YYYY-MM-DD', converted to datetime value.
    date = datetime.datetime.strptime(date_string, '%Y-%m-%d')

    context = {'date': date, 'purchases': purchases, 'date_string': date_string}
    return render(request, 'shopping_registry/erase_date_confirmation.html', context)

@login_required
def erase_date(request, date_string):
    """Delete all the purchases done on the selected date."""

    accountVerification.check_account(request.user.username)

    # Date_string is stored in string format 'YYYY-MM-DD',
    # converted to datetime value.
    date = datetime.datetime.strptime(date_string, '%Y-%m-%d')

    purchases = Purchase.objects.filter(date_purchase=date_string, owner=request.user)

    purchases_erase = purchases.delete()

    context = {'date': date, 'purchase': purchases}
    return render(request, 'shopping_registry/erase_date.html', context)

@login_required
def delete_purchase_confirmation(request, purchase_id):
    """Confirms the deletion of a purchase."""
    purchase = get_object_or_404(Purchase, id=purchase_id)

    accountVerification.check_account(request.user.username, purchase)

    context = {'purchase': purchase}
    return render(request, 'shopping_registry/delete_purchase_confirmation.html',
        context)

@login_required
def delete_purchase(request, purchase_id):
    """Deletes a single purchase."""
    purchase = get_object_or_404(Purchase, id=purchase_id)

    accountVerification.check_account(request.user.username, purchase)

    purchase_erase = purchase.delete()

    context = {'purchase': purchase}
    return render(request, 'shopping_registry/delete_purchase.html', context)

@login_required
def MonthView(request, year, month):
    """Displays all shopping trips in a month."""

    purchases = Purchase.objects.filter(date_purchase__year=year,
        date_purchase__month=month, owner=request.user)

    total = totalCalculations.calculate_total(purchases)

    dates = []

    products_total = {}

    categories_total = totalCalculations.total_categories(purchases)

    for purchase in purchases:
        if purchase.product not in products_total:
            products_total[purchase.product] = 0
            products_total[purchase.product] += purchase.price
        else:
            products_total[purchase.product] += purchase.price

        if purchase.date_purchase not in dates:
            dates.append(purchase.date_purchase)

    date = datetime.datetime(year, month, 1)

    # Stores keys and values from dict to use as labels and values in the charts.
    # Bar chart.
    bar_labels = products_total.keys()
    bar_values = products_total.values()

    # Casts into list for chart compatibility.
    # Bar chart.
    bar_labels = list(bar_labels)
    bar_values = list(bar_values)

    # Generating the charts.
    # Bar chart.
    bar_graph = graphGeneration.generateBarGraph(bar_labels, bar_values)

    # Pie chart.
    pie_graph = graphGeneration.generatePieGraph(categories_total)

    context = {'date': date, 'dates': dates, 'total':total,
        'products_total': products_total, 'categories_total': categories_total,
        'bar_graph': bar_graph, 'pie_graph':pie_graph}
    return render(request, 'shopping_registry/month_view.html', context)

@login_required
def Years(request):
    """Shows all years with registered purchases."""

    purchases = Purchase.objects.filter(owner=request.user).order_by('date_purchase')

    years = []
    for purchase in purchases:
        if purchase.date_purchase.year not in years:
            years.append(purchase.date_purchase.year)
    context = {'years': years}
    return render(request, 'shopping_registry/years.html', context)

@login_required
def Months(request, year):
    """Shows all the months with registered purchases in the selected month."""
    purchases = Purchase.objects.filter(owner=request.user).order_by('date_purchase')

    months = []
    for purchase in purchases:
        if purchase.date_purchase.month not in months:
            months.append(purchase.date_purchase.month)

    datetimes = []
    for month in months:
        datetimes.append(datetime.datetime(year, month, 1).date())

    context = {'months': months, 'dates': datetimes, 'year': year}
    return render(request, 'shopping_registry/months.html', context)

@login_required
def registering_instructions(request):
    """Page that links to the PurchaseForm and includes instructions."""

    accountVerification.check_account(request.user.username)

    return render(request, 'shopping_registry/instrucciones_registro.html')

def demo_account_instructions(request):
    """Page that links to the log-in form and includes instructions regarding the
    use of the demo account."""

    return render(request, 'shopping_registry/instrucciones_demostracion.html')

@login_required
def new_purchase(request):
    """Add a new purchase."""
    username = request.user.username
    accountVerification.check_account(username)

    next = redirect('shopping_registry:dates')

    print("this works")

    if request.method != 'POST':
        # No data submitted; create a blank form.
        form = PurchaseForm()
    else:
        # POST data submitted; process data.
        form = PurchaseForm(data=request.POST)
        if form.is_valid():
            date = form['date_purchase'].value()
            new_purchase = form.save(commit=False)
            new_purchase.owner = request.user
            new_purchase.save()
            # Clears the form incase the user wants to register antoher purchase.
            form = PurchaseForm()
            if 'saveAnother' in request.POST:
                # Find way to store date value in form to display it again.
                next = redirect('shopping_registry:new_purchase')
            return next

    context = {'form': form}
    return render(request, 'shopping_registry/new_purchase.html', context)


import socket
import packet
import sys
import threading
import time
from socket import SOCK_DGRAM
from PyQt5 import QtCore
from PyQt5 import QtWidgets
from PyQt5.QtGui import QStandardItemModel, QStandardItem, QFont
from PyQt5.QtWidgets import QGridLayout, QScrollArea, QLabel, QListView, QProgressBar
from PyQt5.QtWidgets import QLineEdit, QComboBox, QGroupBox
from PyQt5.QtWidgets import QMainWindow, QApplication, QWidget, QPushButton
from PyQt5.QtWidgets import QVBoxLayout, QMessageBox, QTabWidget

FORMAT = "utf-8"

class Client(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        # connection
        self.conn = socket.socket()
        self.connected = False

        # tab settings
        self.layout = QVBoxLayout(self)
        self.tabs = QTabWidget()
        self.tabs.resize(300, 200)

        self.tabHome = QWidget()
        self.tabChat = QWidget()
        self.tabFiles = QWidget()

        self.tabs.addTab(self.tabHome, "Home")
        self.tabs.addTab(self.tabChat, "Chat Room")
        self.tabs.addTab(self.tabFiles, "Files")
        self.tabs.setTabEnabled(1, False)
        self.tabs.setTabEnabled(2, False)

        # Home Page
        gridHome = QGridLayout()
        self.tabHome.setLayout(gridHome)
        self.IPBox = QGroupBox("IP")
        self.IPLineEdit = QLineEdit()
        self.IPLineEdit.setText(socket.gethostbyname(socket.gethostname()))
        IPBoxLayout = QVBoxLayout()
        IPBoxLayout.addWidget(self.IPLineEdit)
        self.IPBox.setLayout(IPBoxLayout)
        self.portBox = QGroupBox("port")
        self.portLineEdit = QLineEdit()
        self.portLineEdit.setText("5050")
        portBoxLayout = QVBoxLayout()
        portBoxLayout.addWidget(self.portLineEdit)
        self.portBox.setLayout(portBoxLayout)
        self.nameBox = QGroupBox("Name")
        self.nameLineEdit = QtWidgets.QLineEdit()
        nameBoxLayout = QVBoxLayout()
        nameBoxLayout.addWidget(self.nameLineEdit)
        self.nameBox.setLayout(nameBoxLayout)
        self.connStatus = QLabel("Status", self)

        font = QFont()
        font.setPointSize(16)

        self.connStatus.setFont(font)
        self.connButton = QPushButton("Connect")
        self.connButton.clicked.connect(self.connect_server)
        self.disconnButton = QPushButton("Disconnect")
        self.disconnButton.clicked.connect(self.disconnect_server)

        gridHome.addWidget(self.IPBox, 0, 0, 1, 1)
        gridHome.addWidget(self.portBox, 0, 1, 1, 1)
        gridHome.addWidget(self.nameBox, 1, 0, 1, 1)
        gridHome.addWidget(self.connStatus, 1, 1, 1, 1)
        gridHome.addWidget(self.connButton, 2, 0, 1, 1)
        gridHome.addWidget(self.disconnButton, 2, 1, 1, 1)
        gridHome.setColumnStretch(0, 1)
        gridHome.setColumnStretch(1, 1)
        gridHome.setRowStretch(0, 0)
        gridHome.setRowStretch(1, 0)
        gridHome.setRowStretch(2, 9)

        # Chat Room
        gridChatRoom = QGridLayout()
        self.tabChat.setLayout(gridChatRoom)
        self.messageRecords = QLabel("Welcome to chat room!", self)
        self.messageRecords.setStyleSheet("background-color: white;")
        self.messageRecords.setAlignment(QtCore.Qt.AlignTop)
        self.messageRecords.setAutoFillBackground(True)
        self.scrollRecords = QScrollArea()
        self.scrollRecords.setWidget(self.messageRecords)
        self.scrollRecords.setWidgetResizable(True)
        self.sendTo = "ALL"
        self.sendChoice = QLabel("Send to :ALL", self)
        self.sendComboBox = QComboBox(self)
        self.sendComboBox.addItem("ALL")
        self.sendComboBox.activated[str].connect(self.send_choice)
        self.lineEdit = QLineEdit()
        self.lineEnterButton = QPushButton("Enter")
        self.lineEnterButton.clicked.connect(self.enter_line)
        self.lineEdit.returnPressed.connect(self.enter_line)
        self.friendList = QListView()
        self.friendList.setWindowTitle('Friends List')
        self.model = QStandardItemModel(self.friendList)
        self.friendList.setModel(self.model)

        gridChatRoom.addWidget(self.scrollRecords, 0, 0, 1, 3)
        gridChatRoom.addWidget(self.friendList, 0, 3, 1, 1)
        gridChatRoom.addWidget(self.sendComboBox, 1, 0, 1, 1)
        gridChatRoom.addWidget(self.sendChoice, 1, 2, 1, 1)
        gridChatRoom.addWidget(self.lineEdit, 2, 0, 1, 3)
        gridChatRoom.addWidget(self.lineEnterButton, 2, 3, 1, 1)
        gridChatRoom.setColumnStretch(0, 9)
        gridChatRoom.setColumnStretch(1, 9)
        gridChatRoom.setColumnStretch(2, 9)
        gridChatRoom.setColumnStretch(3, 1)
        gridChatRoom.setRowStretch(0, 9)

        # file page init
        FilePage = QGridLayout()
        self.tabFiles.setLayout(FilePage)
        self.dFile = QLabel("Download Files", self)
        self.dFile.setFont(font)
        self.download = QComboBox()
        self.start_download = QPushButton("Start download!")
        self.start_download.pressed.connect(self.getFileName)
        self.loadingbar = QProgressBar()
        self.start_download.clicked.connect(self.progressBarUI)
        self.start_download.clicked.connect(self.files_socket)

        FilePage.addWidget(self.dFile, 0, 0, 1, 1)
        FilePage.addWidget(self.download, 0, 1, 1, 1)
        FilePage.addWidget(self.start_download, 1, 1, 1, 1)
        FilePage.addWidget(self.loadingbar, 2, 0, 1, 3)
        FilePage.setRowStretch(0, 0)
        FilePage.setColumnStretch(0, 1)
        FilePage.setRowStretch(1, 0)
        FilePage.setColumnStretch(1, 1)

        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def files_socket(self):
        file_transfer_socket = socket.socket(socket.AF_INET, SOCK_DGRAM)
        file_transfer_socket.bind((socket.gethostbyname(socket.gethostname()), 8080))
        self.conn.send(("[FILEA]" + self.download.currentText()).encode())
        self.receiveFile(file_transfer_socket, self.download.currentText())

        file_transfer_socket.close()

    def receiveFile(self, sock, filename):
        # Open file for writing
        try:
            file = open(filename, 'wb')
        except IOError:
            print('Unable to open', filename)
            return
        expected_num = 0
        while True:
            # Get next packet from the sender
            pkt, addr = sock.recvfrom(1024)
            if not pkt:
                break
            seq_num, data = packet.extractPacket(pkt)
            print('Got packet', seq_num)

            # Send back an ACK
            if seq_num == expected_num:
                print('Got expected packet')
                print('Sending ACK', expected_num)
                pkt = packet.createPacket(expected_num)
                sock.sendto(pkt, addr)
                expected_num += 1
                file.write(data)
            else:
                print('Sending ACK', expected_num - 1)
                pkt = packet.createPacket(expected_num - 1)
                sock.sendto(pkt, addr)
        print('Downloaded!')

        file.close()
        sock.close()

    def progressBarUI(self):
        for i in range(101):
            time.sleep(0.05)
            self.loadingbar.setValue(i)

    def getFileName(self):
        content = self.download.currentText()
        print("--DOWNLOADING-- " + content)

    def enter_line(self):
        # before sending, check if the receiver is the room
        if self.sendTo != self.sendComboBox.currentText():
            self.message_append_to_screen("The person has left.\nThe message was not delivered")
            self.lineEdit.clear()
            return
        line = self.lineEdit.text()
        if line == "":  # prevent empty message
            return
        if self.sendTo != "ALL":  # private message, first send to myself
            send_msg = bytes("[" + self.userName + "]" + line, FORMAT)
            self.conn.send(send_msg)
            time.sleep(0.1)  # this is important for not overlapping two sending
        send_msg = bytes("[" + self.sendTo + "]" + line, FORMAT)
        self.conn.send(send_msg)
        self.lineEdit.clear()
        self.scrollRecords.verticalScrollBar().setValue(self.scrollRecords.verticalScrollBar().maximum())

    def message_append_to_screen(self, newMessage, textColor="black"):
        oldText = self.messageRecords.text()
        appendText = oldText + "
" + newMessage + ""
        self.messageRecords.setText(appendText)
        time.sleep(0.2)
        self.scrollRecords.verticalScrollBar().setValue(self.scrollRecords.verticalScrollBar().maximum())

    def updateRoom(self):
        counter = 0
        while self.connected:
            data = self.conn.recv(1024)
            data = data.decode(FORMAT)
            print(data)
            if data != "":
                if "[FILES]" in data:
                    names = data.split("[FILES]")
                    self.update_file_list(names[1])
                    counter += 1
                    continue
                if "[CLIENTS]" in data:
                    welcome = data.split("[CLIENTS]")
                    self.update_send_to_list(welcome[1])
                    self.update_room_list(welcome[1])
                    if not welcome[0][5:] == "":
                        self.message_append_to_screen(welcome[0][5:])
                        self.scrollRecords.verticalScrollBar().setValue(
                            self.scrollRecords.verticalScrollBar().maximum())
                elif data[:5] == "[MSG]":
                    self.message_append_to_screen(data[5:], "blue")
                    self.scrollRecords.verticalScrollBar().setValue(self.scrollRecords.verticalScrollBar().maximum())
                else:
                    self.message_append_to_screen("[private] " + data, "green")
                    self.scrollRecords.verticalScrollBar().setValue(self.scrollRecords.verticalScrollBar().maximum())
            # this is for saving thread cycle time
            time.sleep(0.1)

    def update_file_list(self, strList):
        L = strList.split(",")
        self.download.clear()
        for file in L:
            self.download.addItem(file)

    def connect_server(self):
        if self.connected:
            return
        name = self.nameLineEdit.text()
        if name == "":
            self.connStatus.setText("Status :" + "Please enter your name")
            return
        self.userName = name
        IP = self.IPLineEdit.text()
        if IP == "":
            IP = "127.0.0.1"
        port = self.portLineEdit.text()
        if port == "" or not port.isnumeric():
            self.portLineEdit.setText("5050")
            self.connStatus.setText("Status :" + "Port format invalid")
            return
        else:
            port = int(port)
        try:
            self.conn.connect((IP, port))
        except:
            self.connStatus.setText("Status :" + " Refused")
            self.conn = socket.socket()
            return
        send_msg = bytes("[REGISTER]" + name, FORMAT)
        self.conn.send(send_msg)
        self.connected = True
        self.connStatus.setText("Status :" + " Connected")
        self.nameLineEdit.setReadOnly(True)  # This setting is not functional well
        self.tabs.setTabEnabled(1, True)
        self.tabs.setTabEnabled(2, True)
        self.newThread = threading.Thread(target=self.updateRoom)
        self.newThread.start()

    def disconnect_server(self):
        if not self.connected:
            return
        send_msg = bytes("[QUIT]", FORMAT)
        self.conn.send(send_msg)
        self.connStatus.setText("Status :" + " Disconnected")
        self.nameLineEdit.setReadOnly(False)
        self.nameLineEdit.clear()
        self.tabs.setTabEnabled(1, False)
        self.tabs.setTabEnabled(2, False)
        self.connected = False
        self.newThread.join()
        self.conn.close()

    def update_room_list(self, strList):
        L = strList.split(",")
        self.model.clear()
        for person in L:
            item = QStandardItem(person)
            item.setCheckable(False)
            self.model.appendRow(item)

    def update_send_to_list(self, strList):
        L = strList.split(",")
        self.sendComboBox.clear()
        self.sendComboBox.addItem("ALL")
        for person in L:
            if person != self.userName:
                self.sendComboBox.addItem(person)
        previous = self.sendTo
        index = self.sendComboBox.findText(previous)
        if index != -1:
            self.sendComboBox.setCurrentIndex(index)  # updating, maintain receiver
        else:
            self.sendComboBox.setCurrentIndex(0)  # updating, the receiver left, default to "ALL"

    def send_choice(self, text):
        self.sendTo = text
        print(self.sendTo)
        self.sendChoice.setText("Send to: " + text)

class Window(QMainWindow):
    def __init__(self):
        super(Window, self).__init__()
        self.setGeometry(50, 50, 500, 300)
        self.setWindowTitle("Best-Chat-Ever")
        self.table_widget = Client(self)
        self.setCentralWidget(self.table_widget)
        self.show()

    def closeEvent(self, event):
        close = QMessageBox()
        close.setText("You sure?")
        close.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
        close = close.exec()
        if close == QMessageBox.Yes:
            self.table_widget.disconnect_server()  # disconnect to server before exit
            event.accept()
        else:
            event.ignore()

def run():
    app = QApplication(sys.argv)
    CLIENT = Window()
    sys.exit(app.exec_())

if __name__ == "__main__":
    run()


from post.models import PostModel
from post.api.serializers import PostDetailSerializer
from rest_framework import serializers

class MyPostsSerializer(PostDetailSerializer):
    image = serializers.SerializerMethodField(method_name='get_post_images', source='post_images')

    class Meta:
        model = PostModel
        fields = ('id', 'is_favourite', 'image', 'price', 'price_type', 'brand', 'auto_model', 'year', 'engine_volume', 'mileage', 'city', 'creation_date')

    def get_post_images(self, obj):
        return self.context['request'].build_absolute_uri(obj.post_images.first().image.url)


import math
import platform

import pygame
import Box2D
from Box2D import *

from game import SCREEN_WIDTH
from game import SCREEN_HEIGHT

VELOCITY_ITERATIONS = 6
POSITION_ITERATIONS = 2
PIXELS_PER_METER = 40

SYSTEM_FILE_PREFIX = "" if platform.system() == "Windows" else "../"

DRAW_DEBUG = False

# Sound from: https://freesound.org/people/ShaneF91/sounds/386572/

def rotate_point_list(origin, points, angle):
    s = math.sin(angle)
    c = math.cos(angle)
    r_points = []
    for p in points:
        px = p[0]
        py = p[1]
        px -= origin[0]
        py -= origin[1]
        rx = px * c - py * s
        ry = px * s + py * c
        nx = rx + origin[0]
        ny = ry + origin[1]
        r_points.append((nx, ny))
    return r_points

def convert_w2s(pos):
    return (PIXELS_PER_METER * (pos[0])) + (SCREEN_WIDTH / 2), PIXELS_PER_METER * (-1 * pos[1]) + SCREEN_HEIGHT

def distance(p, q):
    return math.sqrt((q[0] - p[0])**2 + (q[1] - p[1])**2)

class WorldInstance:
    def __init__(self):
        self.display_surface = pygame.display.get_surface()
        self.background = pygame.transform.scale(
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/background.png"),
            (SCREEN_WIDTH, SCREEN_HEIGHT))

        self.world_objects = []

        # Setup Box2d
        self.gravity = b2Vec2(0.0, -1.6)
        contact_listener = WorldContactListener()
        self.world = b2World(gravity=self.gravity, contactListener=contact_listener)

        # Create ground
        ground_width = SCREEN_WIDTH / PIXELS_PER_METER
        ground_height = SCREEN_HEIGHT / PIXELS_PER_METER
        print(ground_width, ground_height)
        # 1 / 8 ratio for height/width
        # 1280x160 for ground
        self.ground = DrawableWorldObject(
            self.world.CreateBody(
                position=(0.0, ground_height / 16),
                fixtures=b2FixtureDef(shape=b2PolygonShape(box=(ground_width / 2, ground_height / 16)))
            ),
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/ground.png")
        )

        # Create screen borders
        self.world.CreateBody(
            shapes=b2LoopShape(vertices=[
                ((SCREEN_WIDTH / PIXELS_PER_METER)/2, -(SCREEN_HEIGHT / PIXELS_PER_METER)),
                ((SCREEN_WIDTH / PIXELS_PER_METER)/2, (SCREEN_HEIGHT / PIXELS_PER_METER)),
                (-(SCREEN_WIDTH / PIXELS_PER_METER)/2, (SCREEN_HEIGHT / PIXELS_PER_METER)),
                (-(SCREEN_WIDTH / PIXELS_PER_METER)/2, -(SCREEN_HEIGHT / PIXELS_PER_METER))
            ])
        )

        # Create player
        self.player = Player(
            self.world.CreateDynamicBody(
                position=(0.0, 5.0),
                fixtures=b2FixtureDef(
                    shape=b2PolygonShape(box=(0.286, 0.5)),
                    density=50.0,
                    friction=1,
                    restitution=0.5
                ),
                fixedRotation=True
            ),
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/player.png")
        )

        self.platforms = []
        self.gen_platforms()

    def gen_platforms(self):
        self.platforms.append(DrawableWorldObject(
            self.world.CreateStaticBody(
                position=(0.0, 10.0),
                fixtures=b2FixtureDef(shape=b2PolygonShape(box=(1, .555)))
            ),
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/platform.png")
        ))
        self.platforms.append(DrawableWorldObject(
            self.world.CreateStaticBody(
                position=(8.0, 5.0),
                fixtures=b2FixtureDef(shape=b2PolygonShape(box=(1, .555)))
            ),
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/platform.png")
        ))
        self.platforms.append(DrawableWorldObject(
            self.world.CreateStaticBody(
                position=(-10.0, 7.0),
                fixtures=b2FixtureDef(shape=b2PolygonShape(box=(1, .555)))
            ),
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/platform.png")
        ))
        self.platforms.append(DrawableWorldObject(
            self.world.CreateStaticBody(
                position=(-5.0, 13.0),
                fixtures=b2FixtureDef(shape=b2PolygonShape(box=(1, .555)))
            ),
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/platform.png")
        ))
        self.platforms.append(DrawableWorldObject(
            self.world.CreateStaticBody(
                position=(14.0, 13.0),
                fixtures=b2FixtureDef(shape=b2PolygonShape(box=(1, .555)))
            ),
            pygame.image.load(f"{SYSTEM_FILE_PREFIX}resources/platform.png")
        ))

    def step(self, dt: float):
        self.process_inputs()
        self.process_updates(dt)
        self.process_outputs(dt)

    def process_inputs(self):
        keys = pygame.key.get_pressed()
        if keys[pygame.K_a]:
            if not self.player.jump_cooldown:
                self.player.body.ApplyLinearImpulse(b2Vec2(-2.0, 0.0), self.player.body.position, True)
        if keys[pygame.K_d]:
            if not self.player.jump_cooldown:
                self.player.body.ApplyLinearImpulse(b2Vec2(2.0, 0.0), self.player.body.position, True)
        if keys[pygame.K_SPACE]:
            if not self.player.jump_cooldown:
                self.player.remove_jump()
                self.player.body.ApplyLinearImpulse(b2Vec2(0.0, 75.0), self.player.body.position, True)
        if keys[pygame.K_LSHIFT]:
            if not self.player.smash_cooldown:
                self.player.remove_smash()
                self.player.body.ApplyLinearImpulse(b2Vec2(0.0, -75.0), self.player.body.position, True)

    def process_updates(self, dt: float):
        # Update physics engine
        self.world.Step(dt, VELOCITY_ITERATIONS, POSITION_ITERATIONS)

    def process_outputs(self, dt: float):
        self.draw()
        # print(self.player.body.position)

    def draw(self):
        self.display_surface.fill('black')
        self.display_surface.blit(self.background, self.background.get_rect())

        self.ground.draw()
        self.player.draw()
        for plat in self.platforms:
            plat.draw()
        if DRAW_DEBUG:
            for body in self.world.bodies:
                transform = body.transform
                for fixture in body.fixtures:
                    # rotate fixture vertices around transform's angle
                    r_verts = rotate_point_list((0, 0), fixture.shape.vertices, transform.angle)
                    # translate vertices to transform's world position
                    w_verts = [(v[0] + transform.position.x, v[1] + transform.position.y) for v in r_verts]
                    # translate vertices to screen coordinates
                    s_verts = [convert_w2s(v) for v in w_verts]
                    # draw shape
                    pygame.draw.polygon(self.display_surface, (255, 255, 255), s_verts, 1)
                    # print(s_verts)
        pygame.display.flip()

class DrawableWorldObject:
    def __init__(self, body, image):
        self.body = body
        self.image = image

        self.body_width = 0
        self.body_height = 0
        self.gen_dims()

    def gen_dims(self):
        for fixture in self.body.fixtures:
            transform = self.body.transform
            t_pos = (transform.position.x, transform.position.y)
            # rotate fixture vertices around transform's angle
            r_verts = rotate_point_list((0, 0), fixture.shape.vertices, transform.angle)
            # translate vertices to transform's world position
            w_verts = [(v[0] + t_pos[0], v[1] + t_pos[1]) for v in r_verts]
            # translate vertices to screen coordinates
            s_verts = [convert_w2s(v) for v in w_verts]

            # get width and height of box
            self.body_width = distance(s_verts[0], s_verts[1])
            self.body_height = distance(s_verts[0], s_verts[3])

    def draw(self):
        # box format:
        # tl tr br bl
        display_surface = pygame.display.get_surface()
        transform = self.body.transform
        t_pos = (transform.position.x, transform.position.y)
        # scale image to body size
        w_image = pygame.transform.scale(self.image, (self.body_width, self.body_height))
        # rotate image to body angle
        r_image = pygame.transform.rotate(w_image, transform.angle * (180 / math.pi))
        # move image to body screen position
        s_pos = convert_w2s(t_pos)
        s_rect = r_image.get_rect(center=w_image.get_rect(center=s_pos).center)
        # draw image
        display_surface.blit(r_image, s_rect)
        # pygame.draw.circle(display_surface, (255, 0, 0), s_pos, 3)
        # pygame.draw.rect(display_surface, (255, 0, 0), s_rect, 1)

class Player(DrawableWorldObject):
    def __init__(self, body, image):
        super().__init__(body, image)
        self.body.userData = self
        self.jump_cooldown = False
        self.smash_cooldown = False
        self.jump_sound = pygame.mixer.Sound(f"{SYSTEM_FILE_PREFIX}resources/jump.wav")
        self.smash_sound = pygame.mixer.Sound(f"{SYSTEM_FILE_PREFIX}resources/smash.wav")

    def start_contact(self):
        self.refresh_jump()
        self.refresh_smash()

    def end_contact(self):
        pass

    def refresh_smash(self):
        print("refresh_smash")
        self.smash_cooldown = False

    def refresh_jump(self):
        print("refresh_jump")
        self.jump_cooldown = False

    def remove_smash(self):
        print("remove_smash")
        self.smash_cooldown = True

    def remove_jump(self):
        print("remove_jump")
        self.jump_sound.play()
        self.jump_cooldown = True

# https://www.iforce2d.net/b2dtut/collision-callbacks
class WorldContactListener(b2ContactListener):
    """
    Calls contact methods for objects when colliding (if that object has a given method)
    """
    def BeginContact(self, contact):
        # check if fixture a was player
        bodyUserData = contact.fixtureA.body.userData
        if bodyUserData:
            bodyUserData.start_contact()

        bodyUserData = contact.fixtureB.body.userData
        if bodyUserData:
            bodyUserData.start_contact()

    def EndContact(self, contact):
        bodyUserData = contact.fixtureA.body.userData
        if bodyUserData:
            bodyUserData.end_contact()

        bodyUserData = contact.fixtureA.body.userData
        if bodyUserData:
            bodyUserData.end_contact()


import json

import dateutil.parser
from django.conf import settings
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt

from appl.models import AdmissionRound, Payment, Applicant
from .models import QRConfirmation

def health(request):
    return JsonResponse({ 'description': 'KU Admission Health Status',
                          'status': 'UP' })

def extract_national_id(ref1):
    return ref1[4:17]

def process_payment(ref1, ref2, amount, transaction_date_and_time):
    national_id = extract_national_id(ref1)
    if national_id == '':
        return None

    admission_round = AdmissionRound.get_available()
    if not admission_round:
        return None

    try:
        paid_at = dateutil.parser.parse(transaction_date_and_time, ignoretz=True)
    except:
        from datetime import datetime
        paid_at = datetime.now()

    applicants = Applicant.objects.filter(national_id=national_id)
    if len(applicants) >= 1:
        applicant = applicants[0]
    else:
        applicant = None

    payment = Payment(admission_round=admission_round,
                      applicant=applicant,
                      verification_number=ref2,
                      national_id=national_id,
                      amount=amount,
                      paid_at=paid_at)
    payment.save()

    return payment

@csrf_exempt
def sent(request):
    #if request.method != 'POST':
    #    return HttpResponseForbidden()

    confirm_id = settings.QR_CONFIG['CONFIRM_ID']
    if request.body:
        json_data = json.loads(request.body.decode('utf-8'))

        ref1 = json_data.get('billPaymentRef1', '')
        ref2 = json_data.get('billPaymentRef2', '')
        amount = json_data.get('amount', '0.00')
        transaction_date_and_time = json_data.get('transactionDateandTime', '')

        payment = process_payment(ref1, ref2, amount, transaction_date_and_time)

        confirmation = QRConfirmation(bill_payment_ref1=ref1,
                                      bill_payment_ref2=ref2,
                                      remote_addr=request.META.get('REMOTE_ADDR',''),
                                      body=request.body,
                                      payment=payment)

        if payment:
            confirmation.status = 0
        else:
            confirmation.status = 500

        confirmation.save()

        transaction_id = json_data.get('transactionId','')

        return JsonResponse({ 'resCode': '00',
                              'resDesc': 'success',
                              'transactionId': transaction_id,
                              'confirm_id': confirm_id })

    else:
        return JsonResponse({ 'resCode': '99',
                              'resDesc': 'failed',
                              'transactionId': '',
                              'confirm_id': confirm_id })

@csrf_exempt
def confirm(request, transaction_id):
    if request.body:
        json_data = json.loads(request.body.decode('utf-8'))

        bank_notification = json_data.get('bankNotification', None)

        if bank_notification:
            ref1 = bank_notification.get('billPaymentRef1', '')
            ref2 = bank_notification.get('billPaymentRef2', '')
            transaction_date_and_time = bank_notification.get('transactionDateandTime', '')

            amount = json_data.get('amount', '0.00')

            payment = process_payment(ref1, ref2, amount, transaction_date_and_time)
        else:
            ref1 = json_data.get('ref1Prefix','')
            ref2 = json_data.get('ref2Prefix','')
            amount = json_data.get('amount', '0.00')

            transaction_date_and_time = ''

            if ref1 != '':
                payment = process_payment(ref1, ref2, amount, transaction_date_and_time)
            else:
                payment = None

        confirmation = QRConfirmation(bill_payment_ref1=ref1,
                                      bill_payment_ref2=ref2,
                                      remote_addr=request.META.get('REMOTE_ADDR',''),
                                      body=request.body,
                                      payment=payment)

        if payment:
            confirmation.status = 0
        else:
            confirmation.status = 500

        confirmation.save()

        return HttpResponse('OK')
    else:
        return HttpResponse('Error')


import os
from pathlib import Path
import sys

import numpy as np
import pytorch_lightning as pl
import torch
from torch.utils.data import Dataset
from torch.utils.data.dataloader import DataLoader

from diffae.data_utilities.io import load_audio, log_mel_spectrogram

class MusicDataset(Dataset):
    def __init__(self,
                 split: str,
                 dataset_path: str,
                 sample_rate: int = 16_000,):
        # Store split
        assert split in ["train", "val", "test"]
        self.split = split

        path = Path(dataset_path)
        self.data_dir = path.parent.absolute()

        # Read data
        with open(dataset_path, "r") as f:
            lines = f.readlines()
        if split == "train":
            self.data = lines[:int(0.9*len(lines))]
        elif split == "val" or split == "test":
            self.data = lines[int(0.9*len(lines)):]
        else:
            raise ValueError()

        self.sample_rate = sample_rate

    def __len__(self):
        return len(self.data)

    def _random_cut(self, audio, max_length: int = 10):
        """ audio: audio waveform
            max_length: maximum length of the cut in seconds
        """
        max_length_sample = self.sample_rate*max_length
        if len(audio) < max_length_sample:
            return None
        start = np.random.randint(0, len(audio) - max_length_sample)
        return audio[start : start + max_length_sample]

    def __getitem__(self, idx):
        idx = idx % len(self.data)
        audio_path = os.path.join(self.data_dir, self.data[idx]).strip()

        try:
            audio = load_audio(audio_path)
            audio = self._random_cut(audio)
            mel = log_mel_spectrogram(audio)
        except Exception as e:
            print("Error processing audio file:", audio_path)
            return self.__getitem__(idx + 1)

        # Return if something is not ok
        if torch.isnan(mel).any():
            return self.__getitem__(idx + 1)

        # Spec augment
        return {
            "mel": mel,
        }

class MusicDatamodule(pl.LightningDataModule):
    def __init__(self,
                 dataset_path,
                 batch_size,
                 n_workers=4) -> None:
        super().__init__()
        self.dataset_path = dataset_path
        self.batch_size = batch_size
        self.n_workers = n_workers

    def train_dataloader(self):
        return DataLoader(
            MusicDataset(split="train",
                        dataset_path=self.dataset_path,),
                        n_workers=self.n_workers,
                        batch_size=self.batch_size,
                        shuffle=True,)

    def val_dataloader(self):
        return DataLoader(
            MusicDataset(split="val",
                        dataset_path=self.dataset_path,),
                        n_workers=self.n_workers,
                        batch_size=self.batch_size,
                        shuffle=True,)

    def test_dataloader(self):
        return self.val_dataloader()  # TODO(Oleguer): Test dataloader?

if __name__ == "__main__":
    # Test
    dataset = MusicDataset(split="train",
                           dataset_path="/home/mary/code/diffusion_autoencoder/data/data.lst",
                           sample_rate=16_000)
    dataloader = DataLoader(dataset,
                            batch_size=2,
                            shuffle=True,
                            num_workers=4)
    for batch in dataloader:
        print(batch["mel"].shape)
        break


from flask import Flask, render_template, request, redirect, url_for
from flask_wtf import FlaskForm
from wtforms import StringField, BooleanField
from wtforms.validators import DataRequired, Email
from contentful import Client
from trycourier import Courier
from flaskext.markdown import Markdown
import pendulum
import os
import uuid

app = Flask(__name__)
app.secret_key = os.environ.get("secret_key")
Markdown(app)

CTFLclient = Client(
    os.environ.get("CTFL_SpaceID"),
    os.environ.get("CTFL_CDA"),
    environment="master",
)

courierClient = Courier()

@app.template_filter("strftime")
def _jinja2_filter_datetime(date, fmt="dddd MMMM Do YYYY"):
    date = pendulum.parse(f"{date.year}-{date.month}-{date.day}", strict=False)
    return date.format(fmt)

class subscribeForm(FlaskForm):
    email = StringField(
        "Your email",
        render_kw={"class": "u-full-width"},
    )
    phoneNumber = StringField(
        "Your phone number",
        render_kw={"class": "u-full-width"},
    )
    digest = BooleanField("Digest?",
                            render_kw={"class": "u-full-width"})

    def validate(self, extra_validators=None):
        if super().validate(extra_validators):

            # your logic here e.g.
            if not (self.email.data or self.phoneNumber.data):
                self.email.errors.append('At least one field must have a value')
                return False
            else:
                return True

        return False

@app.route("/", methods=["GET", "POST"])
def home():
    form = subscribeForm()
    if request.method == "POST" and form.validate():
        recipient_id = uuid.uuid4()
        resp = courierClient.profiles.merge(
            recipient_id,
            {
                "phone_number": form.phoneNumber.data,
                "email": form.email.data
            }
        )
        list_id = "thing.each"
        if form.digest.data:
            list_id = "thing.digest"
        courierClient.lists.subscribe(list_id, recipient_id)
        return(list_id)
    posts = CTFLclient.entries({"content_type": "blogPost", "order": "-fields.publishDate"})
    return render_template("index.html", form=form, posts=posts)

@app.route("/post/<string:slug>")
def post(slug):
    post = CTFLclient.entries({"content_type": "blogPost", "fields.slug": slug})
    if post:
        return render_template("post.html", post=post[0])
    return redirect(url_for("home"))