from unittest.mock import patch, DEFAULT
import pytest
import time
from faker import Faker
from xeddsa.implementations.xeddsa25519 import XEdDSA25519
from src.tom import Socket
from src.tom._mailbox.packet import PlainPacket, SecurePacket
from src.crypto.doubleratchet import DoubleRatchet
from ...socket_test_helper import SocketTestHelper

def test_simple(helper: SocketTestHelper):
    socket = helper.create_secure_connected_socket()
    socket.shutdown()
    dump = socket.dump()
    Socket.restore(helper.mailbox, dump)

def test_address_in_use(helper: SocketTestHelper):
    endpoints = helper.fake_endpoints()
    socket = helper.create_secure_connected_socket(*endpoints)
    socket.shutdown()
    dump = socket.dump()
    socket2 = helper.create_secure_connected_socket(*endpoints)
    with pytest.raises(Exception) as execinfo:
        socket = Socket.restore(helper.mailbox, dump)
    assert execinfo.match('address already in use')

def test_address_in_use2(helper: SocketTestHelper):
    endpoints = helper.fake_endpoints()
    socket = helper.create_secure_connected_socket(*endpoints)
    socket.shutdown()
    dump = socket.dump()
    socket = Socket.restore(helper.mailbox, dump)
    with pytest.raises(Exception) as execinfo:
        socket2 = helper.create_secure_connected_socket(*endpoints)
    assert execinfo.match('address already in use')

def test_ratchet(faker: Faker, helper: SocketTestHelper):
    ratchet_dump = faker.binary(100)
    endpoints = helper.fake_endpoints()
    with patch.multiple(DoubleRatchet, serialize=DEFAULT, fromSerialized=DEFAULT):
        DoubleRatchet.serialize.return_value = ratchet_dump
        socket = helper.create_secure_connected_socket(*endpoints)
        socket.shutdown()
        dump = socket.dump()
        DoubleRatchet.serialize.assert_called_once_with()
        socket = Socket.restore(helper.mailbox, dump)
        DoubleRatchet.fromSerialized.assert_called_once_with(ratchet_dump)

def test_xeddsa(faker: Faker, helper: SocketTestHelper):
    endpoints = helper.fake_endpoints()
    sign_key_pair = (faker.binary(32), faker.binary(32))
    with patch.object(XEdDSA25519, '__init__', return_value=None):
        socket = helper.create_secure_connected_socket(*endpoints, sign_key_pair)
        XEdDSA25519.__init__.assert_called_once_with(mont_priv=sign_key_pair[0], mont_pub=sign_key_pair[1])
        socket.shutdown()
        dump = socket.dump()
        XEdDSA25519.__init__.reset_mock()
        socket = Socket.restore(helper.mailbox, dump)
        XEdDSA25519.__init__.assert_called_once_with(mont_priv=sign_key_pair[0], mont_pub=sign_key_pair[1])

@pytest.mark.timeout(5)
def test_send_cursor(faker: Faker, helper: SocketTestHelper):
    payload = faker.binary(111)
    endpoints = helper.fake_endpoints()
    uid = faker.pyint()
    socket = helper.create_secure_connected_socket(*endpoints)
    # ack local (1, 0) to avoid uncertainty to ack remote (0, 0)
    socket.send(payload)
    helper.feed_messages({uid - 1: SecurePacket.encrypt(
        PlainPacket(*reversed(endpoints), -1, 0, {(1, 0)}, b''))})
    helper.assert_sent(SecurePacket.encrypt(
        PlainPacket(*endpoints, 1, 0, {(0, 0)}, payload)), 0)
    time.sleep(0.5)
    for i in range(100):
        socket.send(payload)
        helper.feed_messages({uid + i: SecurePacket.encrypt(
            PlainPacket(*reversed(endpoints), -1, 0, {(i + 2, 0)}, b''))})
    time.sleep(0.5)
    for i in range(100):
        helper.assert_sent(SecurePacket.encrypt(
            PlainPacket(*endpoints, i + 2, 0, set(), payload)), 0)
    socket.shutdown()
    dump = socket.dump()
    socket = Socket.restore(helper.mailbox, dump)

    payload = faker.binary(111)
    socket.send(payload)

    helper.assert_sent(SecurePacket.encrypt(
        PlainPacket(*endpoints, 102, 0, set(), payload, is_syn=True)), 0.5)

@pytest.mark.timeout(5)
def test_recv_cursor(faker: Faker, helper: SocketTestHelper):
    payload = faker.binary(111)
    endpoints = helper.fake_endpoints()
    uid = faker.pyint()
    socket = helper.create_secure_connected_socket(*endpoints)
    messages = {
        uid + i: SecurePacket.encrypt(
            PlainPacket(*reversed(endpoints), i + 1, 0, set(), payload)) for i in range(100)
    }
    helper.feed_messages(messages)
    time.sleep(0.5)
    socket.recv_exact(111 * 40 + 50)
    socket.shutdown()
    dump = socket.dump()
    socket = Socket.restore(helper.mailbox, dump)

    assert socket.recv_exact(111 * 60 - 50) == payload[50:] + payload * 59

@pytest.mark.timeout(5)
def test_retransmit(faker: Faker, helper: SocketTestHelper):
    payload = faker.binary(111)
    endpoints = helper.fake_endpoints()
    socket = helper.create_secure_connected_socket(*endpoints)
    socket.send(payload)
    socket.shutdown()
    helper.assert_sent(
        SecurePacket.encrypt(
            PlainPacket(*endpoints, 1, 0, {(0, 0)}, payload)), 0.5)
    dump = socket.dump()
    socket = Socket.restore(helper.mailbox, dump)

    helper.assert_sent(SecurePacket.encrypt(
        PlainPacket(*endpoints, 1, 0, {(0, 0)}, payload)), 0.5)  # secure packet has no attempt

@pytest.mark.timeout(5)
def test_send_ack(faker: Faker, helper: SocketTestHelper):
    payload = faker.binary(111)
    endpoints = helper.fake_endpoints()
    socket = helper.create_secure_connected_socket(*endpoints)
    helper.feed_messages({faker.pyint(): SecurePacket.encrypt(
        PlainPacket(*reversed(endpoints), 1, 0, set(), payload))})
    socket.recv_exact(111)
    socket.shutdown()
    dump = socket.dump()
    socket = Socket.restore(helper.mailbox, dump)

    helper.assert_sent(SecurePacket.encrypt(
        PlainPacket(*endpoints, -1, 0, {(0, 0), (1, 0)}, b'')), 1.5, 0.5)


# -*- coding: utf-8 -*-

# -------------------------------------------------------------------------------
# name          : default_box.py
# Description   :
# Author        : WaBiKong
# Date          : 2021/11/30
# -------------------------------------------------------------------------------
import itertools
from math import sqrt

import numpy as np
import torch

def dboxes300():
    figsize = 300  # 输入网络的图像大小
    feat_size = [38, 19, 10, 5, 3, 1]   # 每个预测层的feature map尺寸
    steps = [8, 16, 32, 64, 100, 300]   # 每个特征层上的一个cell在原图上的跨度
    scales = [21, 45, 99, 153, 207, 261, 315]  # 每个特征层上预测的default box的scale
    aspect_ratios = [[2], [2, 3], [2, 3], [2, 3], [2], [2]]  # 每个预测特征层上预测的default box的ratios
    dboxes = DefaultBoxes(figsize, feat_size, steps, scales, aspect_ratios)
    return dboxes

class DefaultBoxes(object):
    def __init__(self, fig_size, feat_size, steps, scales, aspect_ratios, scale_xy=0.1, scale_wh=0.2):
        self.fig_size = fig_size  # 输入网络的图像大小 300×300
        # [38, 19, 10, 5, 3, 1]
        self.feat_size = feat_size  # 每个预测层的feature map尺寸

        self.scale_xy_ = scale_xy
        self.scale_wh_ = scale_wh

        # [8, 16, 32, 64, 100, 300]
        self.steps = steps  # 每个特征层上的一个cell在原图上的跨度

        # [21, 45, 99, 153, 207, 261, 315]
        self.scales = scales  # 每个预测特征层上预测的default box的scale

        fk = fig_size / np.array(steps)  # 计算每层特征层的fk
        # [[2], [2, 3], [2, 3], [2, 3], [2], [2]]
        self.aspect_ratios = aspect_ratios  # 每个预测特征层上预测的default box的ratios

        self.default_boxes = []
        # size of feature amd number of feature
        # 遍历每层特征层，计算default box
        for idx, sfeat in enumerate(self.feat_size):
            sk1 = scales[idx] / fig_size  # scale转为相对值[0-1]
            sk2 = scales[idx + 1] / fig_size
            sk3 = sqrt(sk1 * sk2)
            # 先添加两个1:1比例的default box的高宽
            all_sizes = [(sk1, sk1), (sk3, sk3)]

            # 再将剩下不同比例的default box宽和高添加到all_szie中
            for alpha in aspect_ratios[idx]:
                w, h = sk1 * sqrt(alpha), sk1 / sqrt(alpha)
                all_sizes.append((w, h))
                all_sizes.append((h, w))

            # 计算当前特征层对应原图的所有default box
            for w, h in all_sizes:
                for i, j in itertools.product(range(sfeat), repeat=2):  # i->行(y), j->列(x)
                    # 计算每个default box的中心坐标(范围在0-1之间)
                    cx, cy = (j + 0.5) / fk[idx], (i + 0.5) / fk[idx]
                    self.default_boxes.append((cx, cy, w, h))

        # 将default box转为Tensor格式
        self.dboxes = torch.as_tensor(self.default_boxes, dtype=torch.float32)

        self.dboxes.clamp_(min=0, max=1)  # 将坐标(x, y, w, h)都限制在0-1之间

        # 将坐标(x, y, w, h)转换为(xmin, ymin, xmax, ymax)，方便后续正负样本匹配时计算IoU
        self.dboxes_ltrb = self.dboxes.clone()
        self.dboxes_ltrb[:, 0] = self.dboxes[:, 0] - 0.5 * self.dboxes[:, 2]  # xmin
        self.dboxes_ltrb[:, 1] = self.dboxes[:, 1] - 0.5 * self.dboxes[:, 3]  # xmin
        self.dboxes_ltrb[:, 2] = self.dboxes[:, 0] + 0.5 * self.dboxes[:, 2]  # xmin
        self.dboxes_ltrb[:, 3] = self.dboxes[:, 1] + 0.5 * self.dboxes[:, 3]  # xmin

    def __call__(self, order='ltrb'):
        # 根据需求返回相应格式的default box
        if order == 'ltrb':
            return self.dboxes_ltrb
        if order == 'xywh':
            return self.dboxes

    @property
    def scale_xy(self):
        return self.scale_xy_

    @property
    def scale_wh(self):
        return self.scale_wh_


import numpy as np
import torch
from absl import app, flags
from hydra.experimental import initialize, compose
from moviepy.editor import *
from moviepy.video.io.ImageSequenceClip import ImageSequenceClip
from omegaconf import OmegaConf, ListConfig
from rlbench.action_modes.action_mode import MoveArmThenGripper
from rlbench.action_modes.arm_action_modes import EndEffectorPoseViaPlanning
from rlbench.action_modes.gripper_action_modes import Discrete
from rlbench.backend.utils import task_file_to_task_class

from arm import c2farm, qte, lpr
from arm.custom_rlbench_env import CustomRLBenchEnv
from arm.lpr.trajectory_action_mode import TrajectoryActionMode
from launch import _create_obs_config
from tools.utils import RLBenchCinematic

FREEZE_DURATION = 2
FPS = 20

flags.DEFINE_string('logdir', '/path/to/log/dir', 'weight dir.')
flags.DEFINE_string('method', 'C2FARM', 'The method to run.')
flags.DEFINE_string('task', 'take_lid_off_saucepan', 'The task to run.')
flags.DEFINE_integer('episodes', 1, 'The number of episodes to run.')

FLAGS = flags.FLAGS

def _save_clips(clips, name):
    final_clip = concatenate_videoclips(clips)
    final_clip.write_videofile('%s.mp4' % name)

def visualise(logdir, task, method):
    config_path = os.path.join(logdir, task, method, '.hydra')
    weights_path = os.path.join(logdir, task, method, 'seed0', 'weights')

    if not os.path.exists(config_path):
        raise ValueError('No cofig in: ' + config_path)
    if not os.path.exists(weights_path):
        raise ValueError('No weights in: ' + weights_path)

    with initialize(config_path=os.path.relpath(config_path)):
        cfg = compose(config_name="config")
    print(OmegaConf.to_yaml(cfg))

    cfg.rlbench.cameras = cfg.rlbench.cameras if isinstance(
        cfg.rlbench.cameras, ListConfig) else [cfg.rlbench.cameras]

    obs_config = _create_obs_config(
        cfg.rlbench.cameras, cfg.rlbench.camera_resolution)
    task_class = task_file_to_task_class(task)

    gripper_mode = Discrete()
    if cfg.method.name == 'PathARM':
        arm_action_mode = TrajectoryActionMode(cfg.method.trajectory_points)
    else:
        arm_action_mode = EndEffectorPoseViaPlanning()
    action_mode = MoveArmThenGripper(arm_action_mode, gripper_mode)

    env = CustomRLBenchEnv(
        task_class=task_class, observation_config=obs_config,
        action_mode=action_mode, dataset_root=cfg.rlbench.demo_path,
        episode_length=cfg.rlbench.episode_length, headless=True,
        time_in_state=True)
    _ = env.observation_elements

    if cfg.method.name == 'C2FARM':
        agent = c2farm.launch_utils.create_agent(
            cfg, env, cfg.rlbench.scene_bounds,
            cfg.rlbench.camera_resolution)
    elif cfg.method.name == 'C2FARM+QTE':
        agent = qte.launch_utils.create_agent(
            cfg, env, cfg.rlbench.scene_bounds,
            cfg.rlbench.camera_resolution)
    elif cfg.method.name == 'LPR':
        agent = lpr.launch_utils.create_agent(
            cfg, env, cfg.rlbench.scene_bounds, cfg.rlbench.camera_resolution,
            cfg.method.trajectory_point_noise, cfg.method.trajectory_points,
            cfg.method.trajectory_mode, cfg.method.trajectory_samples)
    else:
        raise ValueError('Invalid method name.')

    agent.build(training=False, device=torch.device("cpu"))
    weight_folders = sorted(map(int, os.listdir(weights_path)))
    agent.load_weights(os.path.join(weights_path, str(weight_folders[-1])))

    env.launch()
    cinemtaic_cam = RLBenchCinematic()
    env.register_callback(cinemtaic_cam.callback)
    for ep in range(FLAGS.episodes):
        obs = env.reset()
        agent.reset()
        obs_history = {
            k: [np.array(v, dtype=_get_type(v))] * cfg.replay.timesteps for
            k, v in obs.items()}
        clips = []
        last = False
        for step in range(cfg.rlbench.episode_length):
            prepped_data = {k: torch.FloatTensor([v]) for k, v in obs_history.items()}
            act_result = agent.act(step, prepped_data, deterministic=True)
            transition = env.step(act_result)

            trajectory_frames = cinemtaic_cam.frames
            if len(trajectory_frames) > 0:
                cinemtaic_cam.empty()
                clips.append(ImageSequenceClip(trajectory_frames, fps=FPS))

            if last:
                break
            if transition.terminal:
                last = True
            for k in obs_history.keys():
                obs_history[k].append(transition.observation[k])
                obs_history[k].pop(0)
        _save_clips(clips, '%s_%s.mp4' % (method, task))

    print('Shutting down env...')
    env.shutdown()

def _get_type(x):
    if x.dtype == np.float64:
        return np.float32
    return x.dtype

def main(argv):
    del argv
    visualise(FLAGS.logdir, FLAGS.task, FLAGS.method)

if __name__ == '__main__':
    app.run(main)


# 딕셔너리 만들기
lunch1 = {
    '중국집' : '02'
}
lunch2 = dict(중국집='02')
print(lunch1)
print(lunch2)

# 딕셔너리 내용 추가하기
lunch1['분식집'] = '031'

# 딕셔너리 내용 가져오기
idol = {
    'bts' : {
        '지민' : 24,
        'RM' : 25
    }
}

# 랩몬스터의 나이는?
print(idol['bts']['RM'])

print('=======================')
# 딕셔너리 반복문 활용하기

# 기본 활용
for key in lunch1:
    print(key, lunch1[key])

# value만 가져오기
for value in lunch1.values():
    print(value)

# key만 가져오기
for key in lunch1.keys():
    print(key)

# .items() => key, value 가져오기
for key, value in lunch1.items():
    print(lunch1.items())
    print(key, value)


def binary(n):
    global only_one
    s= 0
    e = len(only_one)-1
    m = (s+e)//2
    while  only_one[m]!=n:
        if only_one[m]<n:
            s=m+1
            m = (s+e)//2
        else:
            e = m
            m = (s+e)//2
    return m
n = int(input())
number_list = list(map(int,input().split()))
only_one = sorted(list(set(number_list)))
answer = [str(binary(x)) for x in number_list]
print(" ".join(answer))
20


from esphome.components import sensor
import esphome.config_validation as cv
import esphome.codegen as cg
from esphome.const import CONF_ID, UNIT_CELSIUS, ICON_THERMOMETER
from .. import ht400_ns, CONF_HT400_ID, HT400

DEPENDENCIES = ['ht400']

HT400Sensor = ht400_ns.class_('HT400Sensor', sensor.Sensor, cg.PollingComponent)

CONFIG_SCHEMA = sensor.sensor_schema(
    unit_of_measurement=UNIT_CELSIUS,
    icon=ICON_THERMOMETER,
    accuracy_decimals=1).extend({
    cv.GenerateID(): cv.declare_id(HT400Sensor),
    cv.GenerateID(CONF_HT400_ID): cv.use_id(HT400),
}).extend(cv.polling_component_schema('2s'))

def to_code(config):
    var = cg.new_Pvariable(config[CONF_ID])
    yield cg.register_component(var, config)
    yield sensor.register_sensor(var, config)

    paren = yield cg.get_variable(config[CONF_HT400_ID])
    cg.add(var.set_ht400_parent(paren))


from django.shortcuts import render
from django.views.decorators.csrf import csrf_exempt
from rest_framework.parsers import JSONParser
from django.http.response import JsonResponse

from SisEduApp.models import Califica,Grupo,Tarea,Alumno
from SisEduApp.serializers import CalificaSerializer,GrupoSerializer,TareaSerializer,AlumnoSerializer

# Create your views here.
@csrf_exempt
def calificaApi(request,id=0):
    if request.method=='GET':
        califica = Califica.objects.all()
        califica_serializer = CalificaSerializer(califica, many=True)
        return JsonResponse(califica_serializer.data, safe=False)

    elif request.method=='POST':
        califica_data=JSONParser().parse(request)
        califica_serializer = CalificaSerializer(data=califica_data)
        if califica_serializer.is_valid():
            califica_serializer.save()
            return JsonResponse("Added Successfully!!" , safe=False)
        return JsonResponse("Failed to Add.",safe=False)

    elif request.method=='PUT':
        califica_data = JSONParser().parse(request)
        califica=Califica.objects.get(CalificaId=califica_data['CalificaId'])
        califica_serializer=CalificaSerializer(califica,data=califica_data)
        if califica_serializer.is_valid():
            califica_serializer.save()
            return JsonResponse("Updated Successfully!!", safe=False)
        return JsonResponse("Failed to Update.", safe=False)

    elif request.method=='DELETE':
        califica=Califica.objects.get(CalificaId=id)
        califica.delete()
        return JsonResponse("Deleted Succeffully!!", safe=False)

@csrf_exempt
def grupoApi(request,id=0):
    if request.method=='GET':
        grupo = Grupo.objects.all()
        grupo_serializer = GrupoSerializer(grupo, many=True)
        return JsonResponse(grupo_serializer.data, safe=False)

    elif request.method=='POST':
        grupo_data=JSONParser().parse(request)
        grupo_serializer = GrupoSerializer(data=grupo_data)
        if grupo_serializer.is_valid():
            grupo_serializer.save()
            return JsonResponse("Added Successfully!!" , safe=False)
        return JsonResponse("Failed to Add.",safe=False)

    elif request.method=='PUT':
        grupo_data = JSONParser().parse(request)
        grupo=Grupo.objects.get(GrupoId=grupo_data['GrupoId'])
        grupo_serializer=GrupoSerializer(grupo,data=grupo_data)
        if grupo_serializer.is_valid():
            grupo_serializer.save()
            return JsonResponse("Updated Successfully!!", safe=False)
        return JsonResponse("Failed to Update.", safe=False)

    elif request.method=='DELETE':
        grupo=Grupo.objects.get(GrupoId=id)
        grupo.delete()
        return JsonResponse("Deleted Succeffully!!", safe=False)

@csrf_exempt
def tareaApi(request,id=0):
    if request.method=='GET':
        tarea = Tarea.objects.all()
        tarea_serializer = TareaSerializer(tarea, many=True)
        return JsonResponse(tarea_serializer.data, safe=False)

    elif request.method=='POST':
        tarea_data=JSONParser().parse(request)
        tarea_serializer = TareaSerializer(data=tarea_data)
        if tarea_serializer.is_valid():
            tarea_serializer.save()
            return JsonResponse("Added Successfully!!" , safe=False)
        return JsonResponse("Failed to Add.",safe=False)

    elif request.method=='PUT':
        tarea_data = JSONParser().parse(request)
        tarea=Tarea.objects.get(TareaId=tarea_data['TareaId'])
        tarea_serializer=TareaSerializer(tarea,data=tarea_data)
        if tarea_serializer.is_valid():
            department_serializer.save()
            return JsonResponse("Updated Successfully!!", safe=False)
        return JsonResponse("Failed to Update.", safe=False)

    elif request.method=='DELETE':
        tarea=Tarea.objects.get(TareaId=id)
        tarea.delete()
        return JsonResponse("Deleted Succeffully!!", safe=False)

@csrf_exempt
def alumnoApi(request,id=0):
    if request.method=='GET':
        alumno = Alumno.objects.all()
        alumno_serializer = AlumnoSerializer(alumno, many=True)
        return JsonResponse(alumno_serializer.data, safe=False)

    elif request.method=='POST':
        alumno_data=JSONParser().parse(request)
        alumno_serializer = AlumnoSerializer(data=alumno_data)
        if alumno_serializer.is_valid():
            alumno_serializer.save()
            return JsonResponse("Added Successfully!!" , safe=False)
        return JsonResponse("Failed to Add.",safe=False)

    elif request.method=='PUT':
        alumno_data = JSONParser().parse(request)
        alumno=Alumno.objects.get(AlumnoId=alumno_data['AlumnoId'])
        alumno_serializer=AlumnoSerializer(alumno,data=alumno_data)
        if alumno_serializer.is_valid():
            alumno_serializer.save()
            return JsonResponse("Updated Successfully!!", safe=False)
        return JsonResponse("Failed to Update.", safe=False)

    elif request.method=='DELETE':
        alumno=Alumno.objects.get(AlumnoId=id)
        alumno.delete()
        return JsonResponse("Deleted Succeffully!!", safe=False)

@csrf_exempt
def SaveFile(request):
    file=request.FILES['myFile']
    file_name = default_storage.save(file.name,file)

    return JsonResponse(file_name,safe=False)


"""put_catalog_test.py"""

import unittest
import sys
import os
sys.path.insert(0,
  os.path.join(
    os.path.dirname(os.path.abspath(__file__)),
    os.path.join('..')
  )
)

import fpdf
import test
from test.utilities import relative_path_to, \
                           calculate_hash_of_file, \
                           set_doc_date_0

def document_operations(doc):
  set_doc_date_0(doc)
  doc.add_page()
  doc.set_font('Arial', size=12)
  doc.cell(w = 72, h = 0, border = 1, ln = 2,
           txt = "hello world", fill = 0, link = '')

known_good_hashes = {
  'zoom_fullpage'    : 'e8e2142ca350d826a595d76af6b43a18',
  'zoom_fullwidth'   : 'eccfd6346d72bf484dd04aa974a0452c',
  'zoom_real'        : '4fe8735f67e5ccfb646d8931e2097f34',
  'zoom_default'     : 'e8e2142ca350d826a595d76af6b43a18',
  'layout_single'    : '6028e1b1bbee49790978cb8fb0ec7cde',
  'layout_continuous': 'e8e2142ca350d826a595d76af6b43a18',
  'layout_two'       : '9d1ef647bb3604b57be27324320c8917',
  'layout_default'   : '747d91e99c9915e10c12719d20c525d9'
}

class CatalogDisplayModeTest(unittest.TestCase):
  """This test executes some possible inputs to FPDF#set_display_mode."""
  def test_setting_all_zoom(self):
    for zoom_input in ['fullpage', 'fullwidth', 'real', 'default']:
      doc = fpdf.FPDF()
      document_operations(doc)

      doc.set_display_mode(zoom=zoom_input, layout='continuous')

      output = relative_path_to('continuous ' + zoom_input + ' output.pdf')
      doc.output(output)
      # print(calculate_hash_of_file(output), 'zoom_' + zoom_input)
      known_good_hash = known_good_hashes['zoom_' + zoom_input]
      self.assertEqual(known_good_hash, calculate_hash_of_file(output))
      os.unlink(output)
      del doc

  def test_setting_all_layout(self):
    for layout_input in ['single', 'continuous', 'two', 'default']:
      doc = fpdf.FPDF()
      document_operations(doc)

      doc.set_display_mode(zoom='default', layout=layout_input)

      output = relative_path_to('default ' + layout_input + ' output.pdf')
      doc.output(output)
      # print(calculate_hash_of_file(output), 'layout_' + layout_input)
      known_good_hash = known_good_hashes['layout_' + layout_input]
      self.assertEqual(known_good_hash, calculate_hash_of_file(output))
      os.unlink(output)
      del doc

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

## Development of demo mostly done as written above.
# hashes were printed as above then manipulated into a dictionary with text
# editor wizardry.


#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
    Projet          : Editeur, Compilateur et Micro-Ordinateur pour
                      un langage assembleur.
    Nom du fichier  : 04-02-CPU.py

    Identification  : 04-02-CPU
    Titre           : CPU
    Auteurs         : Francis Emond, Malek Khattech,
                      Mamadou Dia, Marc-André Jean
    Date            : 16-04-2017
    Description     : CPU du Micro-Ordinateur.

    Le module ``CPU``
    ================================

    Ce module contient la classe CPU qui est la représentation du CPU du
    micro-ordinateur. C'est cette classe qui gère les calculs, le transfert
    de la mémoire et l'exécution des instructions d'un programme.

"""

__author__ = "Francis Emond, Malek Khattech, Mamadou Dia, Marc-Andre Jean"
__version__ = "1.0"
__status__ = "Production"

# Importation des modules nécessaires.
try:
    modEnum = __import__("05-Enum")
    modBus = __import__("04-01-Bus")
    modALU = __import__("04-03-ALU")
except ImportError:
    import importlib
    modEnum = importlib.import_module("Modules.05-Enum")
    modBus = importlib.import_module("Modules.04-01-Bus")
    modALU = importlib.import_module("Modules.04-03-ALU")
# Redéfinition.
OPCODE = modEnum.OPCODE
MODE = modEnum.MODE
REGISTRE = modEnum.REGISTRE
ADRESSAGE = modEnum.ADRESSAGE

# À partir du bit le moins significatif :
#  - Parity
#  - Sign
#  - Carry (overflow)
#  - Zero
#  - CND
# Enumération pour le registre STATUS.
STATUS = modEnum.enum(PARITY=0x0001,  # 0b 0000 0000 0000 0001
                      SIGN=0x0002,   # 0b 0000 0000 0000 0010
                      CARRY=0x0004,  # 0b 0000 0000 0000 0100
                      ZERO=0x0008,   # 0b 0000 0000 0000 1000
                      CND=0x0010)    # 0b 0000 0000 0001 0000

class CPU:
    """
        class CPU
        ========================

        Cette classe contient la classe cpu. Elle représente le CPU
        telle que présentée dans le document de
        spécification.

        :example:
        >>> test = CPU(modBus.Bus())

    """

    def __init__(self, bus):
        """
            Constructeur de la classe CPU.

            Le constructeur initialise les composants du CPU dont l'ALU.
            Elle s'occupe aussi de lier le CPU avec le bus en entrée.

            :example:
            >>> test = CPU(modBus.Bus())

            :param bus: Le bus du MicroOrdinateur.
            :type bus: Bus

        """
        self.event = False
        # Connexion avec le bus.
        self.bus = bus
        self.bus.register(self)
        # Création de l'ALU.
        self.alu = modALU.ALU()
        # Création des registres.
        self.regP = 0x0000  # Program counter.
        self.regI = 0x0000  # Instruction register.
        self.regS = 0x0000  # Status Register.
        # Registres A, B, C, D
        self.regA = 0x0000
        self.regB = 0x0000
        self.regC = 0x0000
        self.regD = 0x0000

        # Fin.
        return

    def _getReg(self, registre):
        """
            Lit le registre en argument avec la valeur.

            Cette fonction lit et retourne la valeur du registre en argument.

            :param registre: Registre à lire.
            :type registre: int (16 bits)
            :rtype: Valeur dudit registre.
            :rtype: int (16 bits)

        """
        if registre == REGISTRE.A:
            return self.regA
        elif registre == REGISTRE.B:
            return self.regB
        elif registre == REGISTRE.C:
            return self.regC
        elif registre == REGISTRE.D:
            return self.regD
        else:
            raise Exception()
        # Fin impossible.
        return

    def _setReg(self, registre, valeur):
        """
            Modifie le registre en argument avec la valeur.

            Cette fonction modifie la valeur du registre en argument avec
            la valeur en argument.

            :param registre: Registre à modifier.
            :type registre: int (16 bits)
            :param valeur: Valeur à assigner.
            :type valeur: int (16 bits)

        """
        if registre == REGISTRE.A:
            self.regA = valeur
        elif registre == REGISTRE.B:
            self.regB = valeur
        elif registre == REGISTRE.C:
            self.regC = valeur
        elif registre == REGISTRE.D:
            self.regD = valeur
        else:
            return None
        return

    def clock(self):
        """
            Récepteur pour le signal clock.

            Cette fonction est appelé lorsqu'un coup d'horloge est émit
            sur le bus. Elle gère la réinitialisation du CPU si le bus est
            en mode RESET. Sinon le CPU fetch la prochaine instruction.

            :example:
            >>> bus = modBus.Bus()
            >>> test = CPU(bus)
            >>> test.clock()
            >>> bus.clock()
            >>> bus.event()

        """
        # On réinitialise le CPU si le bus est en mode reset.
        if self.bus.mode == MODE.RESET:
            # Registres program.
            self.regP = 0x0000  # Program counter.
            self.regI = 0x0000  # Instruction register.
            self.regS = 0x0000  # Status Register.
            # Registres A, B, C, D
            self.regA = 0x0000
            self.regB = 0x0000
            self.regC = 0x0000
            self.regD = 0x0000
        # On fetch la prochaine instruction si le bus est en mode INERTE.
        elif self.bus.mode == MODE.INERTE:
            self._fetch()
            self._decode()
            self._execute()
        # Fin de la fonction.
        return

    def _readAddress(self):
        """
            Cette fonction fetch une valeur d'une adresse.

            Cette fonction va chercher la valeur à une adresse selon le
            mode d'adressage.

        """
        adressage = self.regI & 0x00F0
        self.bus.mode = MODE.READ

        # 1. L'argument est l'adresse d'un registre.
        if adressage == ADRESSAGE.ADDR_OF_REG:
            self.bus.data = self._getReg(self.bus.data)
            return

        # 2. L'argument est l'adresse d'un registre qui pointe vers une
        # adresse.
        elif adressage == ADRESSAGE.ADDR_FROM_REG:
            # On fetch l'adresse indiquer dans ce registre.
            self.bus.address = self._getReg(self.bus.data)

        # 3. L'argument est une adresse.
        elif adressage == ADRESSAGE.ADDR:
            # On retourne l'adresse.
            self.bus.address = self.bus.data

        # 4. L'argument est une adresse qui pointe vers une adresse.
        elif adressage == ADRESSAGE.ADDR_FROM_ADDR:
            # Double-fetch.
            self.bus.address = self.bus.data
            self.bus.event()
            self.bus.mode = MODE.READ
            self.bus.address = self.bus.data

        # Fetch la valeur à cette adresse.
        self.bus.event()
        return

    def _fetch(self):
        """
            Cette fonction fetch la prochaine instruction à exécuter.

            Cette fonction permet prépare le bus pour que la mémoire lit
            la prochaine instruction à exécuter.

        """
        # On place le bus en mode lecture pour la prochaine adresse.
        self.bus.mode = MODE.READ
        self.bus.address = self.regP
        # On envoie le signal au bus.
        self.bus.event()

        # On lit l'instruction dans le bus.
        self.regI = self.bus.data
        # Fin.
        return

    def _decode(self):
        """
            Cette fonction décode l'instruction courante.

            Cette fonction refait un fetch pour les commandes néccessitant
            l'argument de droite (16 bits), sinon elle peut exécuter
            celle-ci.

        """
        # On vérifie si l'opération n'a pas besoin d'argument droit:
        if {OPCODE.NOT: True,
            OPCODE.EZ: True,
            OPCODE.NZ: True,
            OPCODE.NOP: True,
                OPCODE.HLT: True}.get(self.regI, False):
            return  # On quitte pour aller à l'étape d'exécution.
        # Sinon on fetch l'argument de droit:
        else:
            # On place le bus en mode lecture.
            self.bus.mode = MODE.READ
            self.bus.address = self.regP + 1
            # On envoie le signal au bus.
            self.bus.event()
        # Fin.
        return

    def _execute(self):
        """
            Cette fonction exécute l'instruction courante.

            Cette fonction exécute l'instruction courante et retourne
            les résultats appropriés dans le bus ou dans les registres.

        """
        # On extrait les données pour travailler.
        opcode = self.regI & 0xFF00
        adressage = self.regI & 0x00F0
        regG = self.regI & 0x000F
        valD = self.bus.data
        result = 0x0000

        # NOP
        if opcode == OPCODE.NOP:
            pass
        # ADD, SUB, MUL, DIV
        # OR, AND, XOR, NOT
        elif opcode & 0xF000 == 0x1000 \
                or opcode & 0xF000 == 0x2000:
            # Reset regS 0x00FF to 0x0000.
            self.regS = 0x0000

            # Execute
            # ADD, SUB, MUL, DIV
            # Si le OPCODE est ADD:
            if opcode == OPCODE.ADD:
                result = self.alu.fonctionADD(self._getReg(regG),
                                              self._getReg(valD))
            # Si le OPCODE est SUB:
            elif opcode == OPCODE.SUB:
                result = self.alu.fonctionSUB(self._getReg(regG),
                                              self._getReg(valD))
            # Si le OPCODE est MUL:
            elif opcode == OPCODE.MUL:
                result = self.alu.fonctionMUL(self._getReg(regG),
                                              self._getReg(valD))
            # Si le OPCODE est DIV:
            elif opcode == OPCODE.DIV:
                result = self.alu.fonctionDIV(self._getReg(regG),
                                              self._getReg(valD))

            # Execute
            # OR, AND, XOR, NOT
            # Si le OPCODE est OR:
            elif opcode == OPCODE.OR:
                result = self.alu.fonctionOR(self._getReg(regG),
                                             self._getReg(valD))
            # Si le OPCODE est AND:
            elif opcode == OPCODE.AND:
                result = self.alu.fonctionAND(self._getReg(regG),
                                              self._getReg(valD))
            # Si le OPCODE est XOR:
            elif opcode == OPCODE.XOR:
                result = self.alu.fonctionXOR(self._getReg(regG),
                                              self._getReg(valD))
            # Si le OPCODE est NOT:
            elif opcode == OPCODE.NOT:
                result = self.alu.fonctionNOT(self._getReg(regG))

            # Vérification pour registre STATUS.
            # --Parité.
            self.regS |= (result & STATUS.PARITY)

            # --Sign
            if result < 0:
                # Si le résultat est négatif, Sign = True
                self.regS |= STATUS.SIGN
                result = abs(result)

            # --Carry
            if result > 0xFFFF:
                # Si on a un overflow, carry = True
                self.regS |= STATUS.CARRY
                result &= 0xFFFF

            # --Zero
            if result == 0x0000:
                # Si le résultat est égal à zéro, Zero = True
                self.regS |= STATUS.ZERO

            # On mets le résultat dans le registre A-D.
            self._setReg(regG, result)

        # LT, GT, LE, GE, EQ, EZ
        elif opcode & 0xF000 == 0x3000:
            # Reset regS 0x00FF to 0x0000.
            self.regS = 0x0000
            # Execute
            # Si le OPCODE est LT:
            if opcode == OPCODE.LT:
                result = self.alu.fonctionLT(self._getReg(regG),
                                             self._getReg(valD))
            # Si le OPCODE est GT:
            elif opcode == OPCODE.GT:
                result = self.alu.fonctionGT(self._getReg(regG),
                                             self._getReg(valD))
            # Si le OPCODE est LE:
            elif opcode == OPCODE.LE:
                result = self.alu.fonctionLE(self._getReg(regG),
                                             self._getReg(valD))
            # Si le OPCODE est GE:
            elif opcode == OPCODE.GE:
                result = self.alu.fonctionGE(self._getReg(regG),
                                             self._getReg(valD))
            # Si le OPCODE est EQ:
            elif opcode == OPCODE.EQ:
                result = self.alu.fonctionEQ(self._getReg(regG),
                                             self._getReg(valD))
            # Si le OPCODE est EZ:
            elif opcode == OPCODE.EZ:
                result = self.alu.fonctionEZ(self._getReg(regG))
            # Si le OPCODE est NZ:
            elif opcode == OPCODE.NZ:
                result = self.alu.fonctionNZ(self._getReg(regG))
            # On applique le résultat.
            if result:
                self.regS |= STATUS.CND
        # JMP, JMZ, JMO, JMC, HLT, SET, LD, ST, MV
        elif opcode & 0xF000 == 0x0000:
            # Execute : JM*
            # Si le OPCODE est JMP (résoudre l'adresse)
            if opcode == OPCODE.JMP:
                self._readAddress()
                self.regP = self.bus.address
                self.bus.mode = MODE.END
                return
            # Si le OPCODE est JMZ et flag ZERO ON (résoudre l'adresse)
            elif opcode == OPCODE.JMZ \
                    and self.regS & STATUS.ZERO == STATUS.ZERO:
                self._readAddress()
                self.regP = self.bus.address
                self.bus.mode = MODE.END
                return
            # Si le OPCODE est JMO et flag CARRY ON (résoudre l'adresse)
            elif opcode == OPCODE.JMO \
                    and self.regS & STATUS.CARRY == STATUS.CARRY:
                self._readAddress()
                self.regP = self.bus.address
                self.bus.mode = MODE.END
                return
            # Si le OPCODE est JMC et flag CND ON (résoudre l'adresse)
            elif opcode == OPCODE.JMC \
                    and self.regS & STATUS.CND == STATUS.CND:
                self._readAddress()
                self.regP = self.bus.address
                self.bus.mode = MODE.END
                return
            # Execute : ***
            # Si le OPCODE est SET
            if opcode == OPCODE.SET:
                self._setReg(regG, valD)
            # Si le OPCODE est LD (résoudre l'adresse)
            elif opcode == OPCODE.LD:
                self._readAddress()
                self.bus.mode = MODE.READ
                self.bus.event()
                self._setReg(regG, self.bus.data)

            # Si le OPCODE est ST (résoudre l'adresse)
            elif opcode == OPCODE.ST:
                self._readAddress()
                self.bus.data = self._getReg(regG)
                self.bus.mode = MODE.WRITE
                self.bus.event()

            # Si le OPCODE est MV
            elif opcode == OPCODE.MV:
                self._setReg(regG, self._getReg(valD))
            # Si le OPCODE est HALT
            elif opcode == OPCODE.HLT:
                # On empêche toute prochaine exécution
                self.bus.mode = MODE.HALT
                return

        # On incrémente le Program Counter.
        self.regP += 2
        # On place le bus en MODE END (sauf pour les OPCODE's qui
        # requisent de résoudre une adresse).
        self.bus.mode = MODE.END
        # On empêche toute prochaine exécution si le pc est illégal.
        if self.regP > 0xFFFF:
            self.bus.mode = MODE.HALT
        # Fin.
        return

# Activation des doctest
if __name__ == "__main__":
    import doctest
    doctest.testmod()


import sys
from collections import deque
sys_input=sys.stdin.readline

n=int(sys_input())
arr=deque(map(int,sys_input().rstrip().split()))
stack=deque()
idx=1
success=True

while idx<=n:
    p_idx=idx
    if len(stack)!=0 and stack[-1]==idx:
        stack.pop()
        idx+=1
    else:
        while len(arr)!=0:
            if arr[0]==idx:
                arr.popleft()
                idx+=1
                break
            else:
                stack.append(arr[0])
                arr.popleft()

    if p_idx==idx:
        success=False
        break

if success:
    print("Nice")
else:
    print("Sad")


def read_file(filename: str) -> list[str]:
    with open(filename, "r", encoding="utf-8") as the_file:
        return the_file.read().split("\n")[:-1]

def separate_commands_and_args(lines: list[str]) -> list[tuple]:
    return [tuple(entry.split(" ")) for entry in lines]

def run_commands(commands: list[tuple]) -> list[int]:
    x_register_values = [1]

    for command in commands:
        x_register_values.append(x_register_values[-1])
        if command[0] != "noop":
            x_register_values.append(x_register_values[-1] + int(command[1]))
    return x_register_values

def calculate_power(x_reg_over_time: list[int]) -> int:
    return sum(x_reg_over_time[i - 1] * i for i in range(20, len(x_reg_over_time), 40))

def render_screen(x_reg_over_time: list[int]) -> None:
    for row in range(0, 240, 40):
        print(
            "".join(
                [
                    pixel_value(pixel, x_reg_over_time[row + pixel])
                    for pixel in range(39)
                ]
            )
        )

def pixel_value(pixel: int, sprite_position: int):
    if pixel in [sprite_position, sprite_position - 1, sprite_position + 1]:
        return "#"
    return " "

def solve(filename: str, render: bool = False) -> int:
    command_lines = read_file(filename=filename)
    commands = separate_commands_and_args(lines=command_lines)
    x_reg_over_time = run_commands(commands=commands)
    if render:
        render_screen(x_reg_over_time=x_reg_over_time)
    return calculate_power(x_reg_over_time=x_reg_over_time)

if __name__ == "__main__":
    assert solve("day10/test_input_2.txt") == 13140
    assert solve("day10/puzzle_input_1.txt", render=True) == 15020


#!/usr/bin/env python

# import libraries
import sys
sys.path.append(r'/home/patrikb/wavyMini/wavyMini')
import numpy as np
from datetime import datetime, timedelta
from satmod import satellite_altimeter as sa
from validationmod import plot_sat
import argparse
from argparse import RawTextHelpFormatter
import os
from modelmod import get_model, check_date
from validationmod import comp_fig, validate
from collocmod import collocate
from  utils import disp_validation
from ncmod import dumptonc_sat

# parser
parser = argparse.ArgumentParser(
    description="""
Check availability of satellite altimetry data.

Example:
./check_sat.py -sat c2 -mod SWAN -reg Vietnam -sd 2019100118 -lt 30 -twin 30 -col --show
./check_sat.py -sat c2 -reg Vietnam -sd 2019100118 -ed 2019100318 --show
./check_sat.py -sat c2 -reg Vietnam -sd 2019100118 -ed 2019100318 -dump outpath/
    """,
    formatter_class = RawTextHelpFormatter
    )
parser.add_argument("-reg", metavar='region',
    help="region to check")
parser.add_argument("-sat", metavar='satellite',
    help="select source sat \\n pick one of s3a, s3b, c2, j3, al,\\n or use: -sat all,\\n or multi option to specify a list with -l:\\n -sat multi -l s3a,c2".decode('string_escape'))
parser.add_argument("-l", metavar="list of sat",
    help="list input for \\n comma separated satellite abbreviations".decode('string_escape'), type=str)
parser.add_argument("-sd", metavar='startdate',
    help="start date of time period to check")
parser.add_argument("-ed", metavar='enddate',
    help="end date of time period to check")
parser.add_argument("-mod", metavar='model',
    help="chosen wave model")
parser.add_argument("-lt", metavar='lead time', type=int,
    help="lead time from initialization")
parser.add_argument("-twin", metavar='time window', type=int,
    help="time window for collocation in minutes")
parser.add_argument("-dist", metavar='distance limit', type=int,
    help="distance limit for collocation in km")
parser.add_argument("-col",metavar="collocation",
    help="collocation",action='store_const',const=True)
parser.add_argument("--show",
    help="show figure",action='store_const',const=True)
parser.add_argument("-dump", metavar="outpath",
    help="dump data to .nc-file")

args = parser.parse_args()
print ("Parsed arguments: ",args)

flatten = lambda l: [item for sublist in l for item in sublist]

# setup
sdate = datetime(int(args.sd[0:4]),int(args.sd[4:6]),
                int(args.sd[6:8]),int(args.sd[8:10]))

if args.twin is None:
    timewin = 30
else:
    timewin = args.twin
if args.dist is None:
    dist = 10
else:
    dist = args.dist

if args.ed is None:
    edate = sdate
else:
    edate = datetime(int(args.ed[0:4]),int(args.ed[4:6]),
                    int(args.ed[6:8]),int(args.ed[8:10]))
    timewin = 0
if args.lt is None:
    args.lt = 0

# get data
if args.sat == 'all':
    satlist = ['s3a','s3b','j3','c2','al']
    loc0 = []
    loc1 = []
    Hs = []
    time = []
    dtime = []
    for sat in satlist:
        sa_obj = sa(sdate,sat=sat,edate=edate,
                    timewin=timewin,region=args.reg)
#                    timewin=timewin,polyreg=args.r)
        loc0.append(sa_obj.loc[0])
        loc1.append(sa_obj.loc[1])
        Hs.append(sa_obj.Hs)
        time.append(sa_obj.time)
        dtime.append(sa_obj.dtime)
    loc0 = flatten(loc0)
    loc1 = flatten(loc1)
    Hs = flatten(Hs)
    time = flatten(time)
    dtime = flatten(dtime)
    loc = [loc0,loc1]
    sa_obj.loc = np.array(loc)
    sa_obj.Hs = np.array(Hs)
    sa_obj.time = time
    sa_obj.dtime = dtime
    sa_obj.region = args.reg
    sa_obj.sat = str(satlist)
elif args.sat == 'multi':
    satlist = args.l.split(',')
    loc0 = []
    loc1 = []
    Hs = []
    time = []
    dtime = []
    for sat in satlist:
        sa_obj = sa(sdate,sat=sat,edate=edate,
                    timewin=timewin,region=args.reg)
#                    timewin=timewin,polyreg=args.r)
        loc0.append(sa_obj.loc[0])
        loc1.append(sa_obj.loc[1])
        Hs.append(sa_obj.Hs)
        time.append(sa_obj.time)
        dtime.append(sa_obj.dtime)
    loc0 = flatten(loc0)
    loc1 = flatten(loc1)
    Hs = flatten(Hs)
    sa_obj.time = flatten(time)
    sa_obj.dtime = flatten(dtime)
    loc = [loc0,loc1]
    sa_obj.loc = np.array(loc)
    sa_obj.Hs = np.array(Hs)
    sa_obj.region = args.reg
    sa_obj.sat = str(satlist)
else:
    sa_obj = sa(sdate,sat=args.sat,edate=edate,timewin=timewin,region=args.reg)
#    sa_obj = sa(sdate,sat=args.sat,edate=edate,timewin=timewin,polyreg=args.r)

# plot
if bool(args.show)==True:
    if args.mod is None:
        plot_sat(sa_obj)
    elif (args.mod is not None and args.col is True):
        # get model collocated values
        check_date(args.mod,fc_date=edate,leadtime=args.lt)
        #get_model
        init_date = edate - timedelta(hours=args.lt)
        model_Hs,model_lats,model_lons,model_time,model_time_dt = \
            get_model(simmode="fc",model=args.mod,fc_date=edate,
            leadtime=args.lt,init_date=init_date)
        #collocation
        results_dict = collocate(args.mod,model_Hs,model_lats,
            model_lons,model_time_dt,sa_obj,edate,distlim=dist)
        valid_dict=validate(results_dict)
        disp_validation(valid_dict)
        comp_fig(args.mod,sa_obj,model_Hs,model_lons,model_lats,results_dict)
    else:
        # get model collocated values
        check_date(args.mod,fc_date=edate,leadtime=args.lt)
        #get_model
        init_date = edate - timedelta(hours=args.lt)
        model_Hs,model_lats,model_lons,model_time,model_time_dt = \
            get_model(simmode="fc",model=args.mod,fc_date=edate,
            leadtime=args.lt,init_date=init_date)
        results_dict = {'valid_date':[edate],
                        'date_matches':[edate-timedelta(minutes=timewin),
                                        edate+timedelta(minutes=timewin)],
                        'model_lons_matches':sa_obj.loc[1],
                        'model_lats_matches':sa_obj.loc[0],
                        'sat_Hs_matches':sa_obj.Hs}
        comp_fig(args.mod,sa_obj,model_Hs,model_lons,model_lats,results_dict)

# dump to .ncfile
if args.dump is not None:
    dumptonc_sat(sa_obj,args.dump)


import os
import posixpath

import pytest

from dvc.cli import parse_args
from dvc.command.plots import CmdPlotsDiff, CmdPlotsShow

def test_plots_diff(dvc, mocker):
    cli_args = parse_args(
        [
            "plots",
            "diff",
            "--out",
            "result.extension",
            "-t",
            "template",
            "--targets",
            "datafile",
            "--show-vega",
            "-x",
            "x_field",
            "-y",
            "y_field",
            "--title",
            "my_title",
            "--x-label",
            "x_title",
            "--y-label",
            "y_title",
            "--experiment",
            "HEAD",
            "tag1",
            "tag2",
        ]
    )
    assert cli_args.func == CmdPlotsDiff

    cmd = cli_args.func(cli_args)
    m = mocker.patch(
        "dvc.repo.plots.diff.diff", return_value={"datafile": "filledtemplate"}
    )

    assert cmd.run() == 0

    m.assert_called_once_with(
        cmd.repo,
        targets=["datafile"],
        revs=["HEAD", "tag1", "tag2"],
        props={
            "template": "template",
            "x": "x_field",
            "y": "y_field",
            "title": "my_title",
            "x_label": "x_title",
            "y_label": "y_title",
        },
        experiment=True,
    )

def test_plots_show_vega(dvc, mocker):
    cli_args = parse_args(
        [
            "plots",
            "show",
            "-o",
            "result.extension",
            "-t",
            "template",
            "--show-vega",
            "--no-header",
            "datafile",
        ]
    )
    assert cli_args.func == CmdPlotsShow

    cmd = cli_args.func(cli_args)

    m = mocker.patch(
        "dvc.repo.plots.Plots.show",
        return_value={"datafile": "filledtemplate"},
    )

    assert cmd.run() == 0

    m.assert_called_once_with(
        targets=["datafile"], props={"template": "template", "header": False}
    )

def test_plots_diff_vega(dvc, mocker, capsys):
    cli_args = parse_args(
        [
            "plots",
            "diff",
            "HEAD~10",
            "HEAD~1",
            "--show-vega",
            "--targets",
            "plots.csv",
        ]
    )
    cmd = cli_args.func(cli_args)
    mocker.patch(
        "dvc.repo.plots.diff.diff", return_value={"plots.csv": "plothtml"}
    )
    assert cmd.run() == 0

    out, _ = capsys.readouterr()
    assert "plothtml" in out

def test_plots_diff_open(tmp_dir, dvc, mocker, capsys):
    mocked_open = mocker.patch("webbrowser.open", return_value=True)
    cli_args = parse_args(["plots", "diff", "--targets", "datafile", "--open"])
    cmd = cli_args.func(cli_args)
    mocker.patch(
        "dvc.repo.plots.diff.diff", return_value={"datafile": "filledtemplate"}
    )

    assert cmd.run() == 0
    mocked_open.assert_called_once_with("plots.html")

    expected_url = posixpath.join(tmp_dir.as_uri(), "plots.html")

    out, _ = capsys.readouterr()
    assert expected_url in out

def test_plots_diff_open_failed(tmp_dir, dvc, mocker, capsys):
    mocked_open = mocker.patch("webbrowser.open", return_value=False)
    cli_args = parse_args(["plots", "diff", "--targets", "datafile", "--open"])
    cmd = cli_args.func(cli_args)
    mocker.patch(
        "dvc.repo.plots.diff.diff", return_value={"datafile": "filledtemplate"}
    )

    assert cmd.run() == 1
    mocked_open.assert_called_once_with("plots.html")

    error_message = "Failed to open. Please try opening it manually."
    expected_url = posixpath.join(tmp_dir.as_uri(), "plots.html")

    out, err = capsys.readouterr()
    assert expected_url in out
    assert error_message in err

@pytest.mark.parametrize(
    "output, expected_url_path",
    [
        ("plots file with spaces.html", "plots%20file%20with%20spaces.html"),
        (os.path.join("dir", "..", "plots.html"), "plots.html"),
    ],
    ids=["quote", "resolve"],
)
def test_plots_path_is_quoted_and_resolved_properly(
    tmp_dir, dvc, mocker, capsys, output, expected_url_path
):
    cli_args = parse_args(
        ["plots", "diff", "--targets", "datafile", "--out", output]
    )
    cmd = cli_args.func(cli_args)
    mocker.patch(
        "dvc.repo.plots.diff.diff", return_value={"datafile": "filledtemplate"}
    )

    assert cmd.run() == 0
    expected_url = posixpath.join(tmp_dir.as_uri(), expected_url_path)

    out, _ = capsys.readouterr()
    assert expected_url in out


from django.urls import path, include
app_name = 'Freelancing'
from Freelancing.views import home, user_login, user_register, view_project, view_project_detail
from .import views
urlpatterns = [
    path('', views.home, name="home"),
    path('login/', views.user_login, name="login"),
    path('register/', views.user_register, name="register"),
    path('post-project/', views.post_project, name="post_project"),
    path('view-project/', views.view_project, name="view_project"),
    path('view-project-detail/<int:id>/', views.view_project_detail, name="view_project_detail"),
    path('batuwa/', views.batuwa, name="batuwa"),
    path('task/', views.task, name="task"),
    path('task-detail/', views.task_detail, name="task_detail"),

]


#!/usr/bin/env python
'''
Take screenshots for targeted url
Can be useful to eliminate results
from subdomain enumeration.
Can be used to locally clone a web application
to limit requests in exploration.
'''
import sys
import time

from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *

from PyQt5.QtWebEngineWidgets import QWebEngineView as QWebView,QWebEnginePage as QWebPage

class Screenshot(QWebView):
    def __init__(self):
        self.app = QApplication(sys.argv)
        QWebView.__init__(self)
        self._loaded = False
        self.loadFinished.connect(self._loadFinished)

    def wait_load(self, delay=0):
        while not self._loaded:
            self.app.processEvents()
            time.sleep(delay)
        self._loaded = False

    def _loadFinished(self, result):
        self._loaded = True

    def get_image(self, url):
        self.load(QUrl(url))
        self.wait_load()
        frame = self.page().mainFrame()
        self.page().setViewportSize(frame.contentsSize())
        image = QImage(self.page().viewportSize(),
                QImage.Format_ARGB32)
        painter = QPainter(image)
        frame.render(painter)
        painter.end()
        return image

if __name__ == '__main__':
    if len(sys.argv) == 2:
        target = sys.argv[1]
    else:
        print('Usage: python pyqt5_scrap.py <target_url>')
        sys.exit(1)
    s = Screenshot()
    image = s.get_image(target)
    image.save(target.replace('/', '_') + '_scrape.png')


# Command to build: python setup.py build

import sys
from cx_Freeze import setup, Executable

build_exe_options = {
    "excludes": [
        "tkinter", "numpy", "scipy", "unittest", "urllib", "http", "html",
        "unicodedata", "email", "pkg_resources", "xml", "pydoc_data",
        "pyexpat", "ctypes"]}

setup(
    name="Corax Engine",
    author="Lionel Brouyère",
    author_email="lionel.brouyere@gmail.com",
    options = {"build_exe": build_exe_options},
    executables=[Executable('corax/__main__.py')])

import os
import shutil

command = '"corax/corax.exe" data -o "overrides\\fight.ovr"'
current = os.path.dirname(__file__)
desktop = os.path.expanduser("~/Desktop")
gameroot = os.path.join(desktop, "whitecrowparrot")
src = os.path.join(current, "build/exe.win-amd64-3.10")
dst = os.path.join(gameroot, "corax")

os.makedirs(gameroot)
shutil.move(src, dst)
os.rename(os.path.join(dst, "__main__.exe"), os.path.join(dst, "corax.exe"))

shutil.copytree(
    src=os.path.join(current, "whitecrowparrot"),
    dst=os.path.join(gameroot, "data"))

with open(os.path.join(gameroot, "whitecrowparrot.bat"), "w") as f:
    f.write(command)


# 输入两个链表，找出它们的第一个公共节点。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode:
        # 用哈希集合存节点
        # HashSet = set()
        # cur = headA
        # while cur:
        #     HashSet.add(cur)
        #     cur = cur.next
        # cur = headB
        # while cur:
        #     if cur in HashSet:
        #         return cur
        #     cur = cur.next
        # return None

        # 双指针
        if not headA or not headB:
            return None
        p1, p2 = headA, headB
        while p1 != p2:
            p1 = p1.next if p1 else headB
            p2 = p2.next if p2 else headA
        return p1

链表/offer52.两个链表的第一个公共节点.py

offer52.两个链表的第一个公共节点.py


from argparse import ArgumentParser

import pytorch_lightning as pl

from deprecated.depth_map import UNet
from deprecated.data import DaVinciDataModule
from models.depth_model import DepthMap

class LeftRightDepthMap(DepthMap):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.net = UNet(num_classes=self.num_classes,
                        input_channels=2*self.input_channels,
                        num_layers=self.num_layers,
                        features_start=self.features_start,
                        bilinear=self.bilinear)

    def _log_images(self, *args, **kwargs):
        super()._log_images(*args, **kwargs, nrow=self.input_channels)

if __name__ == '__main__':
    # sets seed for numpy, torch, python.random and PYTHONHASHSEED
    pl.seed_everything(42)

    parser = ArgumentParser()

    # trainer args
    parser = pl.Trainer.add_argparse_args(parser)

    # model args
    parser = LeftRightDepthMap.add_model_specific_args(parser)
    args = parser.parse_args()

    # data
    dm = DaVinciDataModule(args.data_dir,
                           frames_per_sample=args.frames_per_sample,
                           frames_to_drop=args.frames_to_drop,
                           include_right_view=True,
                           extra_info=True,
                           batch_size=args.batch_size)
    # have to run setup to do splits/sliding window/etc
    dm.setup()

    # sanity check
    print("size of trainset:", len(dm.train_samples))
    print("size of validset:", len(dm.val_samples))
    print("size of testset:", len(dm.test_samples))

    # model
    model = LeftRightDepthMap(**args.__dict__)

    # train
    trainer = pl.Trainer().from_argparse_args(args)
    trainer.fit(model, dm.train_dataloader(), dm.val_dataloader())


import os

#if not os.path.exists(https://marko-knoebl.github.io/slides/python-beginner-en.html):
 #   print('path doesnt exist')
    #pass

a = 2+3+5+6+\
    3+4+5
#or in brackets ()
print(a)


"""
This file is meant to define the KroneckerModel object
that takes different function bases and combines them

"""

#Common imports
import pandas as pd
import numpy as np
from .function_bases import Basis
from typing import List, Union

class KroneckerModel():

    def __init__(self, basis_list: List[Basis]):
        """
        Initialize the object

        Keyword arguments:
        basis_list -- function bases that are going to be kronecker
                  producted together
        """
        #Store the basis list
        self.basis_list = basis_list

        #Store the number of basis that is provided
        self.num_basis = len(basis_list)

        #Store the names of the basis
        self.basis_names = [basis.var_name for basis in basis_list]

        #Store the shape of the output
        # the output array is the product of the size of all the functions
        self.output_size = np.product([basis.size for basis in basis_list])

        #self

    def get_basis_names(self):
        """
        Returns the names of the basis

        This is useful to remember the order if you save the basis and
        reload it later on
        """

        return self.basis_names

    def get_num_basis(self):
        """
        Returns the amount of basis

        This is useful to inform the size of the array when using
        evaluate with a numpy input
        """

        return self.num_basis

    def get_output_size(self):
        """
        Returns the size of the output vector

        This is useful to know the size of the output of
        the kronecker basis
        """

        return self.output_size

    def evaluate(self,dataset:
        Union[np.ndarray,pd.DataFrame],
        #derivatives:List[int]=None   #Have not implemented the derivative functionality
        ) -> np.ndarray:
        """
        Evaluate the basis with the corresponding dataset

        Keyword arguments:
        dataset -- Numpy array with data to evaluate.
                      shape (num_datapoints, num_basiss)

        dataset -- Data in pandas format. Expects the columns to
                      have the each basis name.

        Returns:
        output -- evaluation of the kronecker product
                  shape (num_datapoints, output_size)

        """

        #Invoke the corresponding function
        if(isinstance(dataset, np.ndarray) is True):
            return self._evaluate_numpy(dataset)

        elif (isinstance(dataset, pd.DataFrame) is True):
            return self._evaluate_pandas(dataset)

        else:
            raise TypeError(message="You need to input either dataset using either \
                                     np array or pandas dataframe")

    def _evaluate_numpy(self,np_dataset: np.ndarray) -> np.ndarray:
        """
        Evaluate the basis with a numpy input

        Keyword arguments:
        np_dataset -- numpy dataset with
                      shape (num_datapoints, num_basis)

        Returns:
        output -- evaluation of the kronecker product
                  shape (num_datapoints, output_size)
        """

        #Get the number of rows that we are evaluating
        num_datapoints = np_dataset.shape[0]

        #Make sure we only have the amount of states that correspond to our basis
        basis_variables = np_dataset[:,:self.num_basis]

        #Initialize the output variable that will be updated in the loop
        output = np.array(1).reshape(1,1,1)

        #Calculate the kronecker basis per state
        # Transpose since numpy iterates by rows and our features are in columns
        for func,state in zip(self.basis_list,basis_variables.T):

            #Reshape the state to a columns vector
            state_t = state.reshape(-1,1)

            #Evaluate the function at the current state
            eval_value = func.evaluate(state_t).reshape(num_datapoints,-1,1)

            #Aggregate the kronecker product
            output = (output * eval_value).reshape(num_datapoints,1,-1)

        return output.reshape(num_datapoints,-1)

    def _evaluate_pandas(self, pd_dataset : pd.DataFrame) -> np.ndarray:
        """
        Evaluate the basis with a pandas Dataframe

        Keyword arguments:
        pd_dataset -- Dataframe with the columns having the
                      names of each basis

        Returns:
        output -- evaluation of the kronecker product. Numpy array with
                  shape (num_datapoints, output_size)

        """

        #Get the rows to infer size
        num_datapoints = pd_dataset.shape[0]

        #Initialize the output of the basis that will be updated in the loop
        output = np.array(1).reshape(1,1,1)

        #Calculate the kronecker basis per state
        for func in self.basis_list:
            #Get data in numpy form
            var_data = pd_dataset[func.var_name].values.reshape(-1,1)

            #Calculate the specific function evaluated at the datapoints
            intermediary_output = func.evaluate(var_data)

            #Convert matrices to 3D to execute the kronecker product multiplication
            output = (output[:,np.newaxis,:]*intermediary_output[:,:,np.newaxis]).reshape(num_datapoints,-1)

        return output

    def evaluate_derivative(self,np_dataset : np.ndarray) -> np.ndarray:
        """
        This function calculates the jacobian of the model

        Keyword Arguments:
        np_dataset -- numpy dataset that will be evaluated. Expected
                      hape is (num_datapoints, num_basis)

        Returns:
        output -- evaluation of the kronecker product with a derivative.
                  shape(num_datapoints * num_basis, output_size)
        """

        derivative_list = []

        for i in range(self.num_basis):

            #Skip phase dot
            if i == 1:
                continue

            #Define the delta for the numerical derivative
            delta = 1e-7

            #Evaluate the kronecker model at the original state
            eval_at_state = self._evaluate_numpy(np_dataset)

            #Create the delta state
            # Need to make copy since np array is mutable
            delta_np_dataset = np_dataset.copy()
            delta_np_dataset[:,i] += delta

            #Evaluate the kronecker model at the state plus delta
            eval_at_delta = self._evaluate_numpy(delta_np_dataset)

            #Calculate the derivative
            derivative = (eval_at_delta - eval_at_state)/delta

            #Add to list
            derivative_list.append(derivative)

        #Stack all the derivatives
        derivative_output = np.concatenate(derivative_list,axis=0)

        return derivative_output


from typing import Any, Union

from core.backbones.resnet import ResNet
from core.backbones.utils import (
    OutputChannels,
    OutputFeatures,
    TensorTuple,
    dict_to_tensors,
    tensors_to_dict,
)
from torch import Tensor, rand
from torch.nn import Module
from torchvision.ops.feature_pyramid_network import FeaturePyramidNetwork

class ResnetFPN(Module):
    def __init__(
        self,
        output_channels: OutputChannels,
        image_channels: int,
        output_feature_sizes: OutputFeatures,
        fpn_out_channels: int = 256,  # FPN Spesific?
        extra_blocks: Union[Any, None] = None,
    ) -> None:
        super().__init__()
        self.output_channels = output_channels
        self.image_channels = image_channels
        self.output_feature_sizes = output_feature_sizes
        self.fpn_out_channels = fpn_out_channels
        self.extra_blocks = extra_blocks
        self.out_channels = [self.fpn_out_channels] * len(self.output_channels)

        self.backbone = ResNet(
            self.output_channels, self.image_channels, self.output_feature_sizes
        )
        self.fpn = FeaturePyramidNetwork(
            self.output_channels, self.fpn_out_channels, self.extra_blocks
        )

    def forward(self, x: Tensor) -> TensorTuple:
        out = self.backbone(x)
        out = tensors_to_dict(out)
        out = self.fpn(out)
        out = dict_to_tensors(out)
        return out

def main():

    batch_size = 10
    image_channels = 3
    image_size = (128, 1024)
    output_channels = [256, 512, 512, 1024, 1024, 256]
    output_feature_sizes = [[32, 256], [16, 128], [8, 64], [4, 32], [2, 16], [1, 8]]

    test_img = rand(batch_size, image_channels, *image_size)

    retina = ResnetFPN(
        output_channels=output_channels,
        image_channels=image_channels,
        output_feature_sizes=output_feature_sizes,
    )

    features = retina(test_img)

    print(test_img.shape)
    for fet in features:
        print(fet.shape)

if __name__ == "__main__":
    raise SystemExit(main())


import logging
from .exc import DatabaseUpgradeRequired

def migrate(conn, *, check_only):
    """
    New columns that might need to be added that don't require more complex migrations beyond simply
    adding the column.
    """

    from .. import db

    new_table_cols = {
        'messages': {
            'whisper': 'INTEGER REFERENCES users(id)',
            'whisper_mods': 'BOOLEAN NOT NULL DEFAULT FALSE',
            'filtered': 'BOOLEAN NOT NULL DEFAULT FALSE',
        },
        'rooms': {'active_users': 'BIGINT NOT NULL DEFAULT 0'},
    }

    added = False

    for table, cols in new_table_cols.items():
        for name, definition in cols.items():
            if name not in db.metadata.tables[table].c:
                logging.warning(f"DB migration: Adding new column {table}.{name}")
                if check_only:
                    raise DatabaseUpgradeRequired(f"new column {table}.{name}")
                conn.execute(f"ALTER TABLE {table} ADD COLUMN {name} {definition}")
                added = True

    return added


import re

def part_1(data):
    pattern = "(.)(?!" + "(.)(?!".join("|".join(f"\\{i+1}" for i in range(j)) + ")" for j in range(1, 4))
    return re.search(pattern, data).end()+1

def part_2(data):
    pattern = "(.)(?!" + "(.)(?!".join("|".join(f"\\{i+1}" for i in range(j)) + ")" for j in range(1, 14))
    return re.search(pattern, data).end()+1

if __name__ == "__main__":
    with open("day_06_input.txt", "r") as f:
        inp = f.read()
        print("Part 1: " + str(part_1(inp)))
        print("Part 2: " + str(part_2(inp)))


import argparse
import dataclasses
import datetime
import jax
import jax.numpy as jnp
import gymnasium as gym
import numpy as np
import optax
import random
import time
import flax.linen as nn
from typing import Sequence
from tqdm import tqdm
from models.lmu_jax import LMUCell
from flax.training.train_state import TrainState
import orbax
from orbax.checkpoint import CheckpointManagerOptions, Checkpointer, CheckpointManager
from flax.training.orbax_utils import restore_args_from_target
from ddpg_utils import Logger, DDPGTrainState, Experience, TemporalReplayBuffer
from models import control

class QNetwork(nn.Module):
    """Q Network: (state, action) -> Q-value."""

    @nn.compact
    def __call__(self, x: jnp.ndarray, a: jnp.ndarray):
        x = jnp.concatenate([x, a], -1)
        x = nn.Dense(256)(x)
        x = nn.relu(x)
        x = nn.Dense(256)(x)
        x = nn.relu(x)
        x = nn.Dense(1)(x)
        return x

class Actor(nn.Module):
    """Actor Network: state -> action."""

    action_dim: int
    action_scale: Sequence[float]
    action_bias: Sequence[float]

    @nn.compact
    def __call__(self, x):
        x = nn.Dense(256)(x)
        x = nn.relu(x)
        x = nn.Dense(256)(x)
        x = nn.relu(x)
        x = nn.Dense(self.action_dim)(x)
        x = nn.tanh(x)
        x = x * self.action_scale + self.action_bias
        return x

@jax.jit
def update_critic(
    actor_state: DDPGTrainState,
    qf_state: DDPGTrainState,
    states: np.ndarray,
    actions: np.ndarray,
    next_states: np.ndarray,
    rewards: np.ndarray,
    dones: np.ndarray,
    gamma: float,
):
    next_state_actions = actor_state.apply_fn(actor_state.target_params, next_states)
    next_state_actions = next_state_actions.clip(-1, 1)  # TODO: proper clip
    qf_next_target = qf_state.apply_fn(
        qf_state.target_params, next_states, next_state_actions
    ).reshape(-1)
    next_q_value = (
        rewards.squeeze(1) + (1 - dones.squeeze(1)) * gamma * (qf_next_target)
    ).reshape(-1)

    def mse_loss(params):
        qf_a_values = qf_state.apply_fn(params, states, actions).squeeze()
        return ((qf_a_values - next_q_value) ** 2).mean(), qf_a_values.mean()

    (qf_loss, qf_a), grads = jax.value_and_grad(mse_loss, has_aux=True)(qf_state.params)
    qf_state = qf_state.apply_gradients(grads=grads)
    return qf_state, qf_loss, qf_a

@jax.jit
def update_actor(
    actor_state: DDPGTrainState,
    qf_state: DDPGTrainState,
    states: np.ndarray,
    tau: float,
):
    # tau: step size for the optimizer
    def actor_loss(params):
        loss = -qf_state.apply_fn(
            qf_state.params, states, actor.apply(params, states)
        ).mean()
        return loss

    actor_loss_value, grads = jax.value_and_grad(actor_loss)(actor_state.params)
    actor_state = actor_state.apply_gradients(grads=grads)
    actor_state = actor_state.replace(
        target_params=optax.incremental_update(
            actor_state.params, actor_state.target_params, tau
        )
    )
    qf_state = qf_state.replace(
        target_params=optax.incremental_update(
            qf_state.params, qf_state.target_params, tau
        )
    )
    return actor_state, qf_state, actor_loss_value

if __name__ == "__main__":
    parser = argparse.ArgumentParser("DDPG training")
    parser.add_argument("--restore", type=str, default=None)
    args = parser.parse_args()

    seed = 0
    n_episodes = 1_000
    max_timesteps = 1_000
    buffer_size = 50_000
    learning_rate = 1e-3  # 3e-4
    batch_size = 128  # 256
    # discount factor
    gamma = 0.99
    # frequency of training the policy (delayed)
    policy_frequency = 2
    # target smoothing coefficient
    tau = 0.005
    # number of initial random steps
    learning_starts = 10_000  # 25_000 * 6 # 25_000  # avg 6 random steps / episode
    # scale of exploration noise
    exploration_noise = 1e-3

    # parameters for LMU to encode the state
    lmu_config = control.LMUConfig()

    # env_name = 'MountainCarContinuous-v0'
    env_name = "InvertedPendulum-v4"

    random.seed(seed)
    np.random.seed(seed)
    key = jax.random.PRNGKey(seed)
    key, actor_key, qf_key = jax.random.split(key, 3)

    logger = Logger(
        log_folder=f'logs/{env_name}/{time.strftime("%m%d_%H%M", time.gmtime())}'
    )

    # setup environment
    env = gym.make(env_name)
    env = gym.wrappers.RecordEpisodeStatistics(env)
    env.observation_space.seed(seed)
    env.action_space.seed(seed)
    dim_state = env.observation_space.shape[0]
    dim_action = env.action_space.shape[0]
    sample_state, _ = env.reset()
    sample_action = env.action_space.sample()

    # setup replay buffer
    replay_buffer = TemporalReplayBuffer(buffer_size=buffer_size)

    # setup networks
    scale_action = jnp.array((env.action_space.high - env.action_space.low) / 2.0)
    bias_action = jnp.array((env.action_space.high + env.action_space.low) / 2.0)
    actor = Actor(
        action_dim=dim_action, action_scale=scale_action, action_bias=bias_action
    )
    qf = QNetwork()
    lmu = LMUCell(
        input_size=dim_state,
        hidden_size=lmu_config.lmu_hidden,
        memory_size=lmu_config.lmu_memory,
        theta=lmu_config.lmu_theta,
        learn_a=False,
        learn_b=False,
    )

    # jit apply functions for speed
    # actor.apply = jax.jit(actor.apply)
    # qf.apply = jax.jit(qf.apply)
    # # lmu.apply = jax.vmap(jax.jit(lmu.apply))
    # lmu.apply = jax.jit(lmu.apply)

    # setup (custom) training states
    actor_state = DDPGTrainState.create(
        apply_fn=actor.apply,
        params=actor.init(actor_key, jnp.zeros(lmu_config.lmu_hidden)),
        target_params=actor.init(actor_key, jnp.zeros(lmu_config.lmu_hidden)),
        tx=optax.adam(learning_rate=learning_rate),
    )
    qf_state = DDPGTrainState.create(
        apply_fn=qf.apply,
        params=qf.init(qf_key, jnp.zeros(lmu_config.lmu_hidden), sample_action),
        target_params=qf.init(qf_key, jnp.zeros(lmu_config.lmu_hidden), sample_action),
        tx=optax.adam(learning_rate=learning_rate),
    )
    lmu_state = TrainState.create(
        apply_fn=lmu.apply,
        params=lmu.init(key, jnp.ones((1, dim_state))),
        tx=optax.adam(learning_rate=learning_rate),
    )

    # create checkpoint manager
    timestamp = datetime.datetime.today().strftime("%y%m%d_%H%M")
    chpt_dir = f"checkpoints/{timestamp}" if args.restore is None else args.restore
    mgr_options = CheckpointManagerOptions(
        create=True, max_to_keep=3, keep_period=2, step_prefix="train"
    )
    chptr = Checkpointer(orbax.checkpoint.PyTreeCheckpointHandler())
    ckpt_mgr = CheckpointManager(chpt_dir, chptr, mgr_options)
    # load training state from checkpoint
    if args.restore is not None:
        step = ckpt_mgr.latest_step()
        step = 0 if step is None else step
        ckpt_path = f"{chpt_dir}/train_{step}/default"
        empty_state = {"model": lmu_state, "config": dataclasses.asdict(lmu_config)}
        lmu_state = chptr.restore(ckpt_path, item=empty_state)

    print("exploration phase")
    ep_reward = 0
    last_ep_end = 0
    state, _ = env.reset()
    episode_experiences = []
    for step in tqdm(range(learning_starts)):
        # sample random action
        action = env.action_space.sample()
        # step the environment
        next_state, reward, done, trunc, info = env.step(action)
        ep_reward += reward
        # save experience for the temporal replay buffer later
        episode_experiences.append(Experience(state, action, reward, next_state, done))
        # update state
        state = next_state
        if done or trunc:
            # move to next episode (store episode statistics)
            state, _ = env.reset()
            logger.write_scalar(
                scalar=step - last_ep_end, filename="ep_timesteps", idx=0
            )
            logger.write_scalar(scalar=ep_reward, filename="ep_reward", idx=0)
            ep_reward = 0
            last_ep_end = step
            # add episode experiences to replay buffer
            replay_buffer.add(episode_experiences)
            episode_experiences = []

    print("training phase")
    with jax.profiler.trace("tmp/jaxtrace"):
        iterator = tqdm(range(n_episodes))

        for episode in iterator:
            ep_start_time = time.time()
            state, _ = env.reset()
            ep_reward = 0
            ep_experiences = []
            lmu_int_state = None

            for timestep in range(max_timesteps):
                # compute LMU encoding
                lmu_int_state = lmu.apply(
                    lmu_state.params, jnp.array(state), lmu_int_state
                )
                lmu_out, _ = lmu_int_state

                # sample action from actor, with noise
                # action = actor.apply(actor_state.params, jnp.concatenate([lmu_out, state]))
                action = actor.apply(actor_state.params, lmu_out)
                action_noise = jax.random.normal(key) * scale_action * exploration_noise
                action = (jax.device_get(action) + action_noise).clip(
                    env.action_space.low, env.action_space.high
                )

                # step the environment
                next_state, reward, done, trunc, info = env.step(action)
                ep_reward += reward

                # store experience for the temporal replay buffer later
                ep_experiences.append(
                    Experience(state, action, reward, next_state, done)
                )

                # update state (don't use the real next state?)
                state = next_state

                # TODO handle truncated better? for now just reset env
                if trunc or done:
                    break

            # add episode experiences to replay buffer
            replay_buffer.add(ep_experiences)
            ep_experiences = []

            # do learning step: sample, update critic, update actor (every N)
            s, a, r, n, d = replay_buffer.sample(batch_size)
            lmu_int_state = None
            for t in range(len(s)):
                # compute LMU encoding
                lmu_int_state = lmu.apply(lmu_state.params, s[t], lmu_int_state)
                lmu_out, _ = lmu_int_state

                qf_state, qf_loss, qf_a = update_critic(
                    actor_state, qf_state, s[t], a[t], n[t], r[t], d[t], gamma
                )
                if episode % policy_frequency == 0:
                    actor_state, qf_state, actor_loss = update_actor(
                        actor_state, qf_state, s[t], tau
                    )

            # store logs
            ep_dur = time.time() - ep_start_time
            logger.write_scalar(scalar=qf_loss, filename="qf_loss", idx=episode)
            logger.write_scalar(scalar=actor_loss, filename="actor_loss", idx=episode)
            logger.write_scalar(scalar=qf_a, filename="qf_a_values", idx=episode)
            logger.write_scalar(scalar=ep_dur, filename="ep_dur", idx=episode)

            # episode ended -> reset LMU
            lmu_params = lmu.init(key, jnp.ones((1, dim_state)))
            lmu_int_state = None

            # store number of timesteps
            logger.write_scalar(scalar=timestep, filename="ep_timesteps", idx=episode)
            logger.write_scalar(scalar=ep_reward, filename="ep_reward", idx=episode)


import numpy as np

from ..core import utils
from ..core.series import CoupledTimeAndFrequencySeries
from ..core.utils import PropertyAccessor
from .conversion import convert_to_lal_binary_black_hole_parameters

class WaveformGenerator(object):

    duration = PropertyAccessor('_times_and_frequencies', 'duration')
    sampling_frequency = PropertyAccessor('_times_and_frequencies', 'sampling_frequency')
    start_time = PropertyAccessor('_times_and_frequencies', 'start_time')
    frequency_array = PropertyAccessor('_times_and_frequencies', 'frequency_array')
    time_array = PropertyAccessor('_times_and_frequencies', 'time_array')

    def __init__(self, duration=None, sampling_frequency=None, start_time=0, frequency_domain_source_model=None,
                 time_domain_source_model=None, parameters=None,
                 parameter_conversion=None,
                 waveform_arguments=None):
        """ A waveform generator

    Parameters
    ==========
    sampling_frequency: float, optional
        The sampling frequency
    duration: float, optional
        Time duration of data
    start_time: float, optional
        Starting time of the time array
    frequency_domain_source_model: func, optional
        A python function taking some arguments and returning the frequency
        domain strain. Note the first argument must be the frequencies at
        which to compute the strain
    time_domain_source_model: func, optional
        A python function taking some arguments and returning the time
        domain strain. Note the first argument must be the times at
        which to compute the strain
    parameters: dict, optional
        Initial values for the parameters
    parameter_conversion: func, optional
        Function to convert from sampled parameters to parameters of the
        waveform generator. Default value is the identity, i.e. it leaves
        the parameters unaffected.
    waveform_arguments: dict, optional
        A dictionary of fixed keyword arguments to pass to either
        `frequency_domain_source_model` or `time_domain_source_model`.

        Note: the arguments of frequency_domain_source_model (except the first,
        which is the frequencies at which to compute the strain) will be added to
        the WaveformGenerator object and initialised to `None`.

        """
        self._times_and_frequencies = CoupledTimeAndFrequencySeries(duration=duration,
                                                                    sampling_frequency=sampling_frequency,
                                                                    start_time=start_time)
        self.frequency_domain_source_model = frequency_domain_source_model
        self.time_domain_source_model = time_domain_source_model
        self.source_parameter_keys = self.__parameters_from_source_model()
        if parameter_conversion is None:
            self.parameter_conversion = convert_to_lal_binary_black_hole_parameters
        else:
            self.parameter_conversion = parameter_conversion
        if waveform_arguments is not None:
            self.waveform_arguments = waveform_arguments
        else:
            self.waveform_arguments = dict()
        if isinstance(parameters, dict):
            self.parameters = parameters
        self._cache = dict(parameters=None, waveform=None, model=None)
        utils.logger.info(
            "Waveform generator initiated with\n"
            "  frequency_domain_source_model: {}\n"
            "  time_domain_source_model: {}\n"
            "  parameter_conversion: {}"
            .format(utils.get_function_path(self.frequency_domain_source_model),
                    utils.get_function_path(self.time_domain_source_model),
                    utils.get_function_path(self.parameter_conversion))
        )

    def __repr__(self):
        if self.frequency_domain_source_model is not None:
            fdsm_name = self.frequency_domain_source_model.__name__
        else:
            fdsm_name = None
        if self.time_domain_source_model is not None:
            tdsm_name = self.time_domain_source_model.__name__
        else:
            tdsm_name = None
        if self.parameter_conversion is None:
            param_conv_name = None
        else:
            param_conv_name = self.parameter_conversion.__name__

        return self.__class__.__name__ + '(duration={}, sampling_frequency={}, start_time={}, ' \
                                         'frequency_domain_source_model={}, time_domain_source_model={}, ' \
                                         'parameter_conversion={}, ' \
                                         'waveform_arguments={})'\
            .format(self.duration, self.sampling_frequency, self.start_time, fdsm_name, tdsm_name,
                    param_conv_name, self.waveform_arguments)

    def frequency_domain_strain(self, parameters=None):
        """ Wrapper to source_model.

        Converts self.parameters with self.parameter_conversion before handing it off to the source model.
        Automatically refers to the time_domain_source model via NFFT if no frequency_domain_source_model is given.

        Parameters
        ==========
        parameters: dict, optional
            Parameters to evaluate the waveform for, this overwrites
            `self.parameters`.
            If not provided will fall back to `self.parameters`.

        Returns
        =======
        array_like: The frequency domain strain for the given set of parameters

        Raises
        =======
        RuntimeError: If no source model is given

        """
        return self._calculate_strain(model=self.frequency_domain_source_model,
                                      model_data_points=self.frequency_array,
                                      parameters=parameters,
                                      transformation_function=utils.nfft,
                                      transformed_model=self.time_domain_source_model,
                                      transformed_model_data_points=self.time_array)

    def time_domain_strain(self, parameters=None):
        """ Wrapper to source_model.

        Converts self.parameters with self.parameter_conversion before handing it off to the source model.
        Automatically refers to the frequency_domain_source model via INFFT if no frequency_domain_source_model is
        given.

        Parameters
        ==========
        parameters: dict, optional
            Parameters to evaluate the waveform for, this overwrites
            `self.parameters`.
            If not provided will fall back to `self.parameters`.

        Returns
        =======
        array_like: The time domain strain for the given set of parameters

        Raises
        =======
        RuntimeError: If no source model is given

        """
        return self._calculate_strain(model=self.time_domain_source_model,
                                      model_data_points=self.time_array,
                                      parameters=parameters,
                                      transformation_function=utils.infft,
                                      transformed_model=self.frequency_domain_source_model,
                                      transformed_model_data_points=self.frequency_array)

    def _calculate_strain(self, model, model_data_points, transformation_function, transformed_model,
                          transformed_model_data_points, parameters):
        if parameters is not None:
            self.parameters = parameters
        if self.parameters == self._cache['parameters'] and self._cache['model'] == model and \
                self._cache['transformed_model'] == transformed_model:
            return self._cache['waveform']
        if model is not None:
            model_strain = self._strain_from_model(model_data_points, model)
        elif transformed_model is not None:
            model_strain = self._strain_from_transformed_model(transformed_model_data_points, transformed_model,
                                                               transformation_function)
        else:
            raise RuntimeError("No source model given")
        self._cache['waveform'] = model_strain
        self._cache['parameters'] = self.parameters.copy()
        self._cache['model'] = model
        self._cache['transformed_model'] = transformed_model
        return model_strain

    def _strain_from_model(self, model_data_points, model):
        return model(model_data_points, **self.parameters)

    def _strain_from_transformed_model(self, transformed_model_data_points, transformed_model, transformation_function):
        transformed_model_strain = self._strain_from_model(transformed_model_data_points, transformed_model)

        if isinstance(transformed_model_strain, np.ndarray):
            return transformation_function(transformed_model_strain, self.sampling_frequency)

        model_strain = dict()
        for key in transformed_model_strain:
            if transformation_function == utils.nfft:
                model_strain[key], _ = \
                    transformation_function(transformed_model_strain[key], self.sampling_frequency)
            else:
                model_strain[key] = transformation_function(transformed_model_strain[key], self.sampling_frequency)
        return model_strain

    @property
    def parameters(self):
        """ The dictionary of parameters for source model.

        Returns
        =======
        dict: The dictionary of parameter key-value pairs

        """
        return self.__parameters

    @parameters.setter
    def parameters(self, parameters):
        """
        Set parameters, this applies the conversion function and then removes
        any parameters which aren't required by the source function.

        (set.symmetric_difference is the opposite of set.intersection)

        Parameters
        ==========
        parameters: dict
            Input parameter dictionary, this is copied, passed to the conversion
            function and has self.waveform_arguments added to it.
        """
        if not isinstance(parameters, dict):
            raise TypeError('"parameters" must be a dictionary.')
        new_parameters = parameters.copy()
        new_parameters, _ = self.parameter_conversion(new_parameters)
        for key in self.source_parameter_keys.symmetric_difference(
                new_parameters):
            new_parameters.pop(key)
        self.__parameters = new_parameters
        self.__parameters.update(self.waveform_arguments)

    def __parameters_from_source_model(self):
        """
        Infer the named arguments of the source model.

        Returns
        =======
        set: The names of the arguments of the source model.
        """
        if self.frequency_domain_source_model is not None:
            model = self.frequency_domain_source_model
        elif self.time_domain_source_model is not None:
            model = self.time_domain_source_model
        else:
            raise AttributeError('Either time or frequency domain source '
                                 'model must be provided.')
        return set(utils.infer_parameters_from_function(model))


"""
Quiz. 문자열 뒤집기 (주어진 문자열을 뒤집어서 똑같은 수로 만들기 0001010 => 0000000 근데 이거 1번아님?
Page. 313
"""
import math

input_str = input()

root = int(input_str[0])  # 첫번째 기준 값 구하기
count = 0
for i in range(1, len(input_str)):
    if root == int(input_str[i]):  # 기준 값과 같으면 그대로 진행
        continue
    else:
        root = int(input_str[i])  # 기준값과 다르면 다른 값을 다시 기준값으로 넣기 + 변경 횟수 더하기
        count += 1

count = math.ceil(count / 2)  # 소수점이 있으면 무적권 반올림
print(count)

# 책 코드 (전부 0으로 바꾸는 경우, 전부 1로 바꾸는 경우 더 적은 횟수를 가지는것을 비교하여 계산)
data = input()
count0 = 0  # 전체 0
count1 = 0  # 전체 1

if data[0] == '1':  # 시작 데이터가 1이면
    count0 += 1  # 전체 0으로 변경하는 횟수 +1
else:
    count1 += 1

for i in range(len(data) - 1):
    if data[i] != data[i + 1]:
        if data[i + 1] == '1':
            count0 += 1
        else:
            count1 += 1

print(min(count0, count1))


import itertools
import time
from datetime import datetime

from src import graph
from src.backends import poeofficial as backend
from src.constants import currencies

def test():
    trading_currencies = list(currencies.keys())[:5]
    pf = PathFinder("Delve", trading_currencies, backend)
    pf.run(3)

def format_conversions(conversions):
    formatted_conversions = [format_conversion(c) for c in conversions]
    msg = "\n".join(formatted_conversions)
    return msg

def format_conversion(conversion):
    msg = "{} -> {} -- {} ({} transactions) ".format(
        conversion['from'], conversion['to'], conversion['winnings'], len(conversion['transactions']))
    return msg

class PathFinder:
    """
    A simple class to abstract away the internal library functions for fetching
    offers, constructing a graph and finding profitable paths along that graph.
    """

    def __init__(self, league, currencies, backend):
        self.league = league
        self.currencies = currencies
        self.backend = backend

        self.offers = []
        self.graph = {}
        self.results = {}

    def prepickle(self):
        return {
            "timestamp": self.timestamp,
            "league": self.league,
            "currencies": self.currencies,
            "offers": self.offers,
            "graph": self.graph,
            "results": self.results
        }

    def run(self, max_transaction_length=3, logging=True):
        self.timestamp = str(datetime.now()).split(".")[0]
        currency_combinations = list(
            itertools.permutations(self.currencies, 2))
        if len(self.offers) == 0:
            if logging:
                print("Fetching {} offers for {} currencies - {} pairs".format(
                    self.league, len(self.currencies), len(currency_combinations)))
                print("Backend: {}".format(self.backend.name()))
            t0 = time.time()
            self.offers = self.backend.fetch_offers(
                self.league, currency_combinations)
            t1 = time.time()
            if logging:
                print("Spent {}s fetching offers".format(round(t1 - t0, 1)))
        t1 = time.time()
        self.graph = graph.build_graph(self.offers)
        t2 = time.time()

        if logging:
            print("Spent {}s building the graph".format(round(t2 - t1, 1)))

        for c in self.currencies:
            # For currency @c, find all paths within the constructed path that are
            # at most @max_transaction_length long
            paths = graph.find_paths(self.graph, c, c, max_transaction_length)
            profitable_conversions = []
            for p in paths:
                conversion = graph.build_conversion(p)
                if conversion is not None:
                    profitable_conversions.append(conversion)
            if logging:
                print("Checking {} -> {} Conversions".format(c,
                                                             len(profitable_conversions)))
            profitable_conversions = sorted(
                profitable_conversions, key=lambda k: k['winnings'], reverse=True)
            self.results[c] = profitable_conversions

        t3 = time.time()
        if logging:
            print("Spent {}s finding paths".format(round(t3 - t2, 1)))


import os
import sys

#=================================================
def ParseGroupStructure(gs):
  #========== Check group structure
  valid_gs = [
    '1g', '3g', '5g', '6g', '31g',
    'lanl30g',  'lanl70g', 'lanl80g',
    'lanl187g', 'lanl618g', 'xmas172g'
  ]
  if gs not in valid_gs:
    raise ValueError("Invalid group structure.")

  #========== Return grp stucture info
  if gs in ['1g', '3g', '5g', '6g', '31g']:
    return 1, '../grp_structs/custom'+gs+'.txt'
  elif 'lanl30g' in gs:
    return 3, ''
  elif 'lanl70g' in gs:
    return 11, ''
  elif 'lanl80g' in gs:
    return 13, ''
  elif 'lanl187g' in gs:
    return 10, ''
  elif 'lanl618g' in gs:
    return 34, ''
  elif 'xmas172g' in gs:
    return 22, ''

#=================================================
def ParseTemperature(temp):
  if temp in [296.0,293.6]: return 'room'
  else: return str(temp)+'k'

#=================================================
def ThermScatInfo(isotope, molecule):
  if molecule == '':
    return None, None, None, None
  elif isotope == 'H1' and molecule == 'H2O':
    return 'H1_H2O', 222, None, 2
  elif isotope == 'H1' and molecule == 'ZrH':
    return 'H1_ZrH', 225, 226, 1
  elif isotope == 'Zrnat' and molecule == 'ZrH':
    return 'Zrnat_ZrH', 235, 236, 1
  elif isotope == 'Cnat' and molecule == 'graphite':
    return 'Cnat_graphite', 229, 230, 1


import os

import kscore.session

SESSION = kscore.session.get_session()
KNOWN_SERVICES = SESSION.get_available_services()

# For the services where the tag name doesn't match
# the name we use to create_client(), we need to maintain
# a map until we can get these changes pushed upstream.
TAG_TO_ENDPOINT_PREFIX = {
    'tag': 'endpoint',
}
REGION = 'cn-beijing-6'
REGION_OVERRIDES = {
    'global': 'cn-beijing-6',
}

SKIP_SERVICES = set([
    'kec',
])

def before_feature(context, feature):
    for tag in feature.tags:
        if tag in TAG_TO_ENDPOINT_PREFIX:
            service_name = TAG_TO_ENDPOINT_PREFIX[tag]
            break
        elif tag in KNOWN_SERVICES:
            service_name = tag
            break
    else:
        raise RuntimeError("Unable to create a client for "
                           "feature: %s" % feature)

    if service_name in SKIP_SERVICES:
        feature.mark_skipped()
        return
    region_name = _get_region_for_service(service_name)
    context.client = SESSION.create_client(service_name, region_name)

def _get_region_for_service(service_name):
    if os.environ.get('AWS_SMOKE_TEST_REGION', ''):
        region_name = os.environ['AWS_SMOKE_TEST_REGION']
    else:
        region_name = REGION_OVERRIDES.get(service_name, REGION)
    return region_name


#code
def solve(arr):
    result = [arr[0]]
    flag = False
    for x in range(1,len(arr)):
        print(arr[x],result[-1])
        if arr[x] == result[-1]:
            flag =  True
            continue
        else:
            if flag:
                print('del',result[-1])
                del result[-1]
            flag = False
            result.append(arr[x])
    if flag:
        del result[-1]
    curr = ''.join(result)
    if curr==arr:
        return curr
    else:
        return solve(curr)

test = int(input())

for x in range(0,test):
    arr = input().strip()
    print(solve(arr))