from __future__ import division
import os,time
import numpy as np
import pdb
import glob
from network import *
import cv2
from prefetch_queue_shuffle import *
import tensorflow as tf
from vgg import *
import math

data_dir = './DRV/'

train_ids = [line.rstrip('\n') for line in open(data_dir+'train_list.txt')]
val_ids = [line.rstrip('\n') for line in open(data_dir+'val_list.txt')]
test_ids = [line.rstrip('\n') for line in open(data_dir+'test_list.txt')]

in_image=tf.placeholder(tf.float32,[None,None,None,3])
gt_image=tf.placeholder(tf.float32,[None,None,None,3])

out_image=Unet(in_image)

sess=tf.Session()
saver=tf.train.Saver(max_to_keep=1000)
sess.run(tf.global_variables_initializer())
ckpt=tf.train.get_checkpoint_state("checkpoint")
if ckpt:
    print('loaded '+ckpt.model_checkpoint_path)
    saver.restore(sess,ckpt.model_checkpoint_path)

if not os.path.isdir("result/final"):
    os.makedirs("result/final")

for test_id in test_ids:
    gt_files = glob.glob(data_dir + '/long/%s/half0001*.png'%test_id)
    gt_path = gt_files[0]
    im = cv2.imread(gt_path, cv2.IMREAD_UNCHANGED)
    gt_np = np.float32(im/65535.0)

    in_files = sorted(glob.glob(data_dir + '/VBM4D_rawRGB/%s/*.png'%test_id))

    # run the 5-th frame of each video. Can be revised to run more frames.
    for k in range(4,len(in_files)-3, 500):
        print('running %s-th sequence %d-th frame...'%(test_id,k))
        in_path = in_files[k]
        im = cv2.imread(in_path, cv2.IMREAD_UNCHANGED)
        in_np = np.expand_dims(np.float32(im/65535.0),axis = 0)

        out_np =sess.run(out_image,feed_dict={in_image: in_np})

        cv2.imwrite("result/final/%s_out.png"%(test_id),np.uint8(np.clip(out_np[0,:,:,:]*255,0,255)))
        cv2.imwrite("result/final/%s_gt.png"%(test_id),np.uint8(np.clip(gt_np*255,0,255)))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 10 08:53:22 2022

@author: eo
"""

# Solution for: https://adventofcode.com/2022/day/10

#%% Load/parse data

in_path = "input.txt"
#in_path = "test.txt"
with open(in_path, "r") as in_file:
    raw_data = in_file.read()

"""
data looks like:

addx 15
addx -11
addx 6
addx -3
addx 5
addx -1
addx -8
addx 13
addx 4
noop
addx -1
etc.

"""

#%% Calculate register values

str_rows = raw_data.strip().splitlines()

register_values_list = [1]
for each_str in str_rows:

    prev_value = register_values_list[-1]

    if each_str.startswith("noop"):
        new_value = prev_value
        register_values_list.append(new_value)
    else:
        _, amount_to_add_str = each_str.split(" ")

        new_value = prev_value + int(amount_to_add_str)
        register_values_list.append(prev_value)
        register_values_list.append(new_value)

    pass

#%% Part 1

# Calculate signal strength at 20 + 40*k register indexes
idx_list = [20 + 40 * k for k in range(6)]
signal_strengths_list = [idx * register_values_list[idx-1] for idx in idx_list]

answer_1 = sum(signal_strengths_list)
print("Solution 1:", answer_1)

#%% Part 2

disp_strs_list = []

# Loop over display rows & columns, we'll manually increment our register indexing
reg_idx = 0
for row_idx in range(6):

    # Decide what character to draw for each column
    row_strs_list = []
    for col_idx in range(40):

        # Check if the sprite is centered near the current column
        sprite_position = register_values_list[reg_idx]
        is_overlapped = abs(sprite_position - col_idx) < 2

        # Draw appropriate character, depending on sprite overlap, as given in question
        new_char = "#" if is_overlapped else "."
        row_strs_list.append(new_char)

        # Update indexing after check, as-per ordering given in the question
        reg_idx += 1

    # Concatenate all characters in the row into a single string for printing
    disp_strs_list.append("".join(row_strs_list))

answer_2 = "\n".join(disp_strs_list)
print("Solution 2:", "", answer_2, sep = "\n")


# input

start_number = int(input())
end_number = int(input())
magic_number = int(input())

# variables

counter = 0
is_found = False

# loop

for first_number in range(start_number, end_number + 1):
    for second_number in range(start_number, end_number + 1):
        counter += 1
        if first_number + second_number == magic_number:
            print(f'Combination N:{counter} ({first_number} + {second_number} = {magic_number})')
            is_found = True
            break
    if is_found:
        break
if not is_found:
    print(f'{counter} combinations - neither equals {magic_number}')


import pygame
import Animation
from Assets.Attack import Normal

class Player:
    level = 1
    exp = 0
    god = False
    maxHealth = 0
    inventory = list()
    group=pygame.sprite.Group()
    facing = True
    transform = None

    def __init__(self, health, attack, defend):
        self.health = health
        self.maxHealth = health
        self.attack = attack
        self.defend=defend
        self.image = pygame.transform.scale(pygame.image.load('Assets\Player\player.png'), (180, 180))
        self.rect = self.image.get_rect()
        self.rect.midbottom = (100, 600)
        self.vel_y = 0
        self.jumped = False
        self.still = Animation.importFrames("Assets\Player\BlueWizard\\2BlueWizardIdle\\", 180, 180, 19)
        self.last_time=0

    def update(self,screen):
        x_move = 0
        y_move = 0
        key = pygame.key.get_pressed()

        if key[pygame.K_SPACE] and self.jumped is False:
            self.vel_y = -40
            self.jumped = True
        if key[pygame.K_a]:
            x_move -= 8
            if self.facing:
                self.facing = False
        if key[pygame.K_d]:
            x_move += 8
            if not self.facing:
                self.facing = True
        if key[pygame.K_f]:
            self.Attack(screen)

        self.vel_y += 5  # falling speed
        if self.vel_y > 10:  # maximum falling speed
            self.vel_y = 10
        y_move += self.vel_y
        self.rect.x += x_move
        self.rect.y += y_move
        if self.rect.bottom > 600:
            self.jumped = False
            self.rect.bottom = 600
        self.still.update(pygame.time.get_ticks())
        self.image = self.still.image
        self.group.update()
        self.group.draw(screen)
        if not self.facing:
            self.image = pygame.transform.flip(self.image, True, False)

    def Attack(self, screen):
        current_time=pygame.time.get_ticks()
        if current_time < self.last_time + 100:
            return
        self.last_time=current_time
        if(self.facing):
            bullet=Normal(self.attack,1000,'bullet1.png',50,50,20,1,self.rect.center)
        else:
            bullet = Normal(self.attack, 1000, 'bullet1.png', 50, 50, 20,-1, self.rect.center)
        self.group.add(bullet)

    def Defend(self):
        # put animation here

        pass

    def AddInventory(self, equipment):
        self.inventory.append(equipment)

    def Equipt(self, weapon):
        self.attack += weapon.attack
        self.defend += weapon.defend

    def Levelup(self):
        if self.exp == self.level * self.level * 10:
            self.level += 1
            self.maxHealth += 10
            self.health = self.maxHealth

    def GodMode(self):
        self.health = 1000000000
        self.maxHealth = self.health


def binary_search(number, sorted_list):
    """Perform binary search on pre-sorted list  of numbers
    for given element and return its index of None
    if element is absent.

    Parameters
    ----------
    number : int, float
        Desired number.
    sorted_list : list of int or list of float
        Pre-sorted number list.

    Returns
    -------
    int or None
        Index of desired element in list.
    """
    length = len(sorted_list)
    middle_idx = length // 2
    if sorted_list[middle_idx] == number:
        return middle_idx
    elif length == 1:
        return None
    elif sorted_list[middle_idx] > number:
        return binary_search(number, sorted_list[:middle_idx])
    else:
        result = binary_search(number, sorted_list[middle_idx:])
        if result:
            return middle_idx + result
        return result

assert binary_search(42, [12, 13, 15, 20, 34, 42, 56, 70]) == 5
assert binary_search(42, [12, 13, 15, 20, 34, 41, 56, 70]) is None


"""WebSiTi URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/1.8/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  url(r'^$', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  url(r'^$', Home.as_view(), name='home')
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""

from django.conf.urls import patterns, url, include
from . import views

urlpatterns = patterns('',
        url(r'^$', views.index, name='index'),

        url(r'^blog/', include('blog.urls')),
        url(r'^cms/', include('cms.urls')),

)
from django.conf import settings # New Import
from django.conf.urls.static import static # New Import

if not settings.DEBUG:
        urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)

from django.conf import settings

# UNDERNEATH your urlpatterns definition, add the following two lines:
if settings.DEBUG:
    urlpatterns += patterns(
        'django.views.static',
        (r'^media/(?P<path>.*)',
        'serve',
        {'document_root': settings.MEDIA_ROOT}), )


from hangman import Hangman
from word_pick import Word_Picker

def start():
    choose_word = Word_Picker()

    next_word = choose_word.get_next_word()
    word = Hangman(next_word.decode())
    word.show()

    while True:
        letter = input("\nEnter a letter: ")
        word.check_guess(letter.upper())

        if(word.check_win_condition()):
            print(f"Congrulation! You Won\n")
            break

        if(word.get_guess_count() == 0):
            print("You have reached the total guess count. Sorry! Better luck next time\n")
            print(f"Correct word was {word.word}")
            break

if __name__ == "__main__":
    while True:
        choice = input("Press 'S' to start and E to exit the game:")
        if(choice.upper() == 'S'):
            start()
        else:
            exit()


from colorama import init
from colorama import Fore, Back, Style
from loggingModule import Logging
import keyboard
import os

init()

class MenuField():
    '''Класс  реализующий поле в меню консоли

    Необходим для закрепления за полем имени и цвета фона поля'''

    def __init__(self, name:str) -> None:
        '''Метод инициализации

        При создании экземпляра класса передается имя экземпляра,
        которое будет выводится на экран при визуализации меню'''

        self.name = name

        self.push_func = None

    def __str__(self) -> str:
        return self.name

    def getName(self) -> str:
        return self.name

    def settingFuncion(self, func) -> None:
        '''Привязка функции к полю меню

        Входящие данные: функция, которая будет исполняться при нажатии на поле меню'''
        self.push_func = func

    def performFunction(self) -> None:
        '''Выполнение присвоенной этой функции

        Входящие данные: None'''
        self.push_func()

class ConsoleMenu():
    '''Класс  реализующий функции управления меню в консоли

    Собирает поля меню (кнопки) из экземпляров класса MenuField'''

    def __init__(self, name="Menu") -> None:
        '''Метод инициализации'''

        self.log = Logging(__file__).getLogger()

        self.menu_name = name
        # Список полей (кнопок)
        self.field_list = []
        # Выделенное поле
        self.target_field = None
        # Функция, срадатывающая при нажатии клавиши Esc
        self.esc_func = None

        # Переменная определяющая непрерывный процесс
        # обработки и изображения полей меню
        self.click_processing = True

        self.log.info(f"Создание эземпляра класса ConsoleMenu")

    def __str__(self) -> str:
        return self.menu_name

    def addField(self, name_field:str) -> MenuField:
        '''Метод создающий новое поле меню

        Входящие данные: имя поля (str)
        Возвращает: экземпляр класса MenuField с полученным именем'''

        new_field = MenuField(name_field)
        if len(self.field_list)==0:
            self.target_field = new_field
        self.field_list.append(new_field)

        self.log.info(f"Создан экземпляр класса MenuField с именем {name_field}")

        return new_field

    def keyProcessing(self):
        '''Обработка нажатия клавиш

        Метод реагирует на нажатие клавишь. При нажатии одной из нужных,
        вызывает функцию перемещения или обработку нажатия клавиши.
        Входящиее данные: None
        Возвращает: None'''

        key_input = keyboard.record("enter")
        if len(key_input)>1:
            last_input = key_input[-2].name
            if last_input=='up':self.moveCursor(mode=-1)
            elif last_input=='down':self.moveCursor()
            elif last_input=='esc':self.moveEsc()
        else:
            self.moveEnter()

    def settingEsc(self, func=None) -> None:
        '''Настройка функции Esc

        Клавише esc присваивается передаваемая функция.
        Если функия не передавалась, то будет использована функция
        по умолчанию - escFuncion().
        Она будет вызываться при нажатии клавиши Esc
        Входящиее данные: Функция (funcion), которая будет вызываться
        при нажатии клавиши Esc
        Возвращает: None'''
        if func==None:
            self.esc_func=self.escFuncion
        else:
            self.esc_func = func
            self.log.debug(f"Клавище Esc присвоена функция {func}")

    def escFuncion(self):
        '''Функция выхода

        Функция выхода из цикла в processStarting.
        При нажатии клавиши esc будет срабатывать эта функция.
        Входящиее данные: None
        Возвращает: None'''
        self.log.debug(f"Вызвана стандартная функция выхода из меню")
        self.click_processing = False

    def moveEsc(self) -> None:
        '''Вызов функции присвоенной клавище Esc

        Входящиее данные: None
        Возвращает: None'''
        self.log.debug(f"Вызвана функция присвоенная клавище Esc")
        self.esc_func()

    def moveEnter(self) -> None:
        '''Выполнение функции присвоенной к полю,
        которое находится в таргете

        Входящиее данные: None
        Возвращает: None'''

        self.log.debug(f"Запущена функция на поле {self.target_field.name}")
        self.target_field.performFunction()

    def moveCursor(self, mode = 1) -> None:
        '''Переместить курсор

        Метод перемещает курсор "вверх" или "вниз", то есть назад или вперед по списку
        в зависимости от знака mode (-1 - спускаемся, 1 - поднимаемся), заменяя значение
        переменной в таргете (MenuField)
        Входящиее данные: None
        Возвращает: None'''
        self.log.debug(f"Запущена функция moveCursorUP")
        number = self.removeCursor()
        if number!=None:
            if number+mode < len(self.field_list)*(mode):
                self.changeCursor(0)
            else:
                self.changeCursor(number+mode)

    def removeCursor(self) -> int:
        '''Получение индекса поля в таргете

        Данный метод вызывается для получения поля, которое находится в таргете.
        Входящиее данные: None
        Возвращает: индекс поля, который сейчас находится в таргете'''
        if self.target_field!=None:
            self.log.debug(f"Запущена функция remobeCursor")
            index = self.field_list.index(self.target_field)
            self.log.debug(f"Функция removeCursor возвращает индекс поля, находящегося в таргете: {index}")
            self.log.debug(f"Сейчас в таргете находится поле {self.target_field.getName()}")
            return index
        return None

    def changeCursor(self, index:int) -> None:
        '''Сменить таргет

        Данный метод меняет значение в переменной target_field текущего экземпляра класса на
        экземпляр класса MenuField из списка field_list с заданным индексом.
        Входящиее данные: индекс нового таргета (int)
        Возвращает: None'''
        self.log.debug(f"Запущена функция changeCursor (смена таргета) c новым индеком {index}")
        self.log.debug(f"Таргет перешел от поля - {self.target_field.getName} на поле  - {self.field_list[index].getName}")
        self.target_field = self.field_list[index]
        self.log.debug(f"В тарегете теперь находится поле: {self.target_field.getName()}")

    def outputOnDisplay(self) -> None:
        '''Вывод полей меню на консоль

        Входящиее данные: None
        Возвращает: None'''

        self.log.debug(f"Запущен вывод меню в консоль")
        print(self)
        for field in self.field_list:
            self.outputFieldOnDisplay(field)

    def outputFieldOnDisplay(self, field:MenuField) -> None:
        '''Вывод поля на консоль

        Входящиее данные: поле (MenuField), которое нужно вывести в консоль
        Возвращает: None'''
        if self.target_field==field:
            print(Back.GREEN + str(field))
        else:
            print(Back.BLACK + str(field))

    def cleaning(self) -> None:
        '''Очистка консоли

        Входящиее данные: None
        Возвращает: None'''
        self.log.debug(f"Запущена очистка консоли")
        os.system(['clear','cls'][os.name == 'nt'])

    def processStarting(self):
        '''Метод запускающий процесс изображения полей и реагирования
        на нажатие клавиш

        Входящиее данные: None
        Возвращает: None'''
        self.log.info(f"Запущена функция processStarting запускающая процесс отображения полей меню и считывания нажатых клавиш")
        self.click_processing = True
        while self.click_processing:
            self.cleaning()
            self.outputOnDisplay()
            self.keyProcessing()
        self.log.info(f"Функция processStarting прекратила работу")


year=input("what is the year of the book?")
century=year[:2]
decade=year[2]

if century=='18':
    output_century="Eighteenth Century"
elif century=='19':
    output_century="ninteenth Century"

decades=['00s','tens','twenties','thirties','forties','fifties','sixties','seventies','eighties','ninties']
output_decade=decades[int(decade)]
print(output_century+", "+output_decade)


from django.contrib.auth import get_user_model
from django.urls import reverse
from django.test import TestCase

from rest_framework import status
from rest_framework.test import APIClient

from core.models import Project, Organization

from projects.serializers import ProjectSerializer

PROJECT_URL = reverse('projects:project-list')

def detail_url(project_id):
    """Create the detail URL for a project"""
    return reverse('projects:project-detail', args=[project_id])

class PublicProjectApiTest(TestCase):
    """Test the publicly available projects API"""

    def setUp(self):
        self.client = APIClient()

    def test_retrieve_projects_list(self):
        """Test retrieving a list of projects by unauthenticated user"""
        self.user = get_user_model().objects.create_user(
            'test@xemob.com',
            'password123'
        )
        ngo = Organization.objects.create(user=self.user,
                                          name='NGO-1',
                                          country='Spain')
        Project.objects.create(user=self.user,
                               name='Project 1',
                               organization=ngo)
        Project.objects.create(user=self.user,
                               name='Project 2',
                               organization=ngo)

        res = self.client.get(PROJECT_URL)

        projects = Project.objects.all().order_by('-id')
        serializer = ProjectSerializer(projects, many=True)
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(len(res.data), 2)
        self.assertEqual(res.data, serializer.data)

class PrivateProjectsApiTests(TestCase):
    """Test the authorized user projects API"""

    def setUp(self):
        self.user = get_user_model().objects.create_user(
            'test@xemob.com',
            'password123'
        )
        self.client = APIClient()
        self.client.force_authenticate(self.user)
        self.ngo = Organization.objects.create(user=self.user,
                                               name='NGO-1',
                                               country='Spain')
        self.user2 = get_user_model().objects.create_user('other@xemob.com',
                                                          'testpass')
        self.ngo2 = Organization.objects.create(user=self.user2,
                                                name='NGO-2',
                                                country='Wonderland')

    def test_create_project_successful(self):
        """Test creating a new project"""
        payload = {'name': 'Test project',
                   'organization': self.ngo.id,
                   'user': self.user.id}
        self.client.post(PROJECT_URL, payload)

        exists = Project.objects.filter(
            user=self.user,
            name=payload['name']
        ).exists()
        self.assertTrue(exists)

    def test_create_project_invalid(self):
        """Create a project with invalid payload"""
        payload = {'name': '', 'organization': self.ngo}
        res = self.client.post(PROJECT_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_partial_update_project_successful(self):
        """Test updating a project by owner successful"""
        project = Project.objects.create(user=self.user,
                                         name='Project 1',
                                         organization=self.ngo)
        payload = {'name': 'Updated project'}
        url = detail_url(project.id)
        res = self.client.patch(url, payload)

        project.refresh_from_db()
        self.assertEqual(project.name, payload['name'])
        self.assertEqual(res.status_code, status.HTTP_200_OK)

    def test_partial_update_by_not_owner_invalid(self):
        """Test updating a project by not owner return not authorized"""
        project = Project.objects.create(user=self.user2,
                                         name='Project 1',
                                         organization=self.ngo)
        payload = {'name': 'Updated project'}
        url = detail_url(project.id)
        res = self.client.patch(url, payload)

        project.refresh_from_db()
        self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
        self.assertNotEqual(project.name, payload['name'])

    def test_full_update_project_successful(self):
        """Test full updating a project by owner successful"""
        project = Project.objects.create(user=self.user,
                                         name='Project 1',
                                         organization=self.ngo)
        payload = {'name': 'Test project',
                   'organization': self.ngo.id,
                   'user': self.user.id}

        url = detail_url(project.id)
        res = self.client.put(url, payload)

        project.refresh_from_db()
        self.assertEqual(res.status_code, status.HTTP_200_OK)
        self.assertEqual(project.name, payload['name'])

    def test_full_update_by_not_owner_invalid(self):
        """Test updating a project by not owner return not authorized"""

        project = Project.objects.create(user=self.user2,
                                         name='Project 1',
                                         organization=self.ngo)
        payload = {'user': self.user.id,
                   'name': 'Updated project',
                   'organiztion': self.ngo.id}
        url = detail_url(project.id)
        res = self.client.put(url, payload)

        project.refresh_from_db()
        self.assertEqual(res.status_code, status.HTTP_403_FORBIDDEN)
        self.assertNotEqual(project.name, payload['name'])

    def test_create_project_with_not_owned_organization_invalid(self):
        """Test that user should be owner of the organization related with
        the project. Otherwise, it raise an error"""
        payload = {'user': self.user.id,
                   'name': 'Rapped Organization',
                   'organization': self.ngo2.id}
        res = self.client.post(PROJECT_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)

    def test_create_project_for_another_user_is_invalid(self):
        """Test that a user can't create a project posting on
        behalf of anther user"""
        payload = {'user': self.user2.id,
                   'name': 'Rapped Organization',
                   'organization': self.ngo2.id}
        res = self.client.post(PROJECT_URL, payload)

        self.assertEqual(res.status_code, status.HTTP_400_BAD_REQUEST)


coefficients = input().split()

A, B, C = coefficients

def Bhaskara(val1, val2, val3):
    delta = val2**2 - 4*val1*val3

    if delta < 0 or val1 == 0:
        return print('Impossivel calcular')
    else:
        R1 = (-val2 + delta**0.5)/(2*val1)
        R2 = (-val2 - delta**0.5)/(2*val1)

        return print('R1 = %.5f'%R1), print('R2 = %.5f'%R2)

Bhaskara(float(A), float(B), float(C))


import torch

class CNN(torch.nn.Module):

    def __init__(self, channels, conv_kernels, conv_strides, conv_padding, pool_padding, num_classes=15):
        assert len(conv_kernels) == len(channels) == len(conv_strides) == len(conv_padding)
        super(CNN, self).__init__()

        # create conv blocks
        self.conv_blocks = torch.nn.ModuleList()
        prev_channel = 1

        for i in range(len(channels)):
            # add stacked conv layer
            block = []
            for j, conv_channel in enumerate(channels[i]):
                block.append(torch.nn.Conv1d(in_channels=prev_channel, out_channels=conv_channel, kernel_size=conv_kernels[i], stride=conv_strides[i], padding=conv_padding[i]))
                prev_channel = conv_channel
                # add batch norm layer
                block.append(torch.nn.BatchNorm1d(prev_channel))
                # adding ReLU
                block.append(torch.nn.ReLU())
            self.conv_blocks.append(torch.nn.Sequential(*block))

        # create pooling blocks
        self.pool_blocks = torch.nn.ModuleList()
        for i in range(len(pool_padding)):
            # adding Max Pool (drops dims by a factor of 4)
            self.pool_blocks.append(torch.nn.MaxPool1d(kernel_size=4, stride=4, padding=pool_padding[i]))

        # global pooling
        self.global_pool = torch.nn.AdaptiveAvgPool1d(1)
        self.linear = torch.nn.Linear(prev_channel, num_classes)

    def forward(self, inwav):
        for i in range(len(self.conv_blocks)):
            # apply conv layer
            inwav = self.conv_blocks[i](inwav)
            # apply max_pool
            if i < len(self.pool_blocks): inwav = self.pool_blocks[i](inwav)
        # apply global pooling
        out = self.global_pool(inwav).squeeze() # [batch_size, 256, 1] [batch_size, 256]
        out = self.linear(out) #[batch_size, 15]
        return out

class ResBlock(torch.nn.Module):

    def __init__(self, prev_channel, channel, conv_kernel, conv_stride, conv_pad):
        super(ResBlock, self).__init__()
        self.res = torch.nn.Sequential(
            torch.nn.Conv1d(in_channels = prev_channel, out_channels=channel, kernel_size=conv_kernel, stride=conv_stride, padding=conv_pad),
            torch.nn.BatchNorm1d(channel),
            torch.nn.ReLU(),
            torch.nn.Conv1d(in_channels=channel, out_channels=channel, kernel_size=conv_kernel, stride=conv_stride, padding=conv_pad),
            torch.nn.BatchNorm1d(channel),
        )
        self.bn = torch.nn.BatchNorm1d(channel)
        self.relu = torch.nn.ReLU()

    def forward(self, x):
        identity = x
        x = self.res(x)
        if x.shape[1] == identity.shape[1]:
            x += identity
        # repeat the smaller block till it reaches the size of the bigger block
        elif x.shape[1] > identity.shape[1]:
            if x.shape[1] % identity.shape[1] == 0:
                x += identity.repeat(1, x.shape[1]//identity.shape[1], 1)
            else:
                raise RuntimeError("Dims in ResBlock needs to be divisible on the previous dims!!")
        else:
            if identity.shape[1] % x.shape[1] == 0:
                identity += x.repeat(1, identity.shape[1]//x.shape[1], 1)
            else:
                raise RuntimeError("Dims in ResBlock needs to be divisible on the previous dims!!")
            x = identity
        x = self.bn(x)
        x = self.relu(x)
        return x

class CNNRes(torch.nn.Module):

    def __init__(self, channels, conv_kernels, conv_strides, conv_padding, pool_padding, num_classes=15):
        assert len(conv_kernels) == len(channels) == len(conv_strides) == len(conv_padding)
        super(CNNRes, self).__init__()

        # create conv block
        prev_channel = 1
        self.conv_block = torch.nn.Sequential(
            torch.nn.Conv1d(in_channels=prev_channel, out_channels=channels[0][0], kernel_size=conv_kernels[0], stride=conv_strides[0], padding=conv_padding[0]),
            # add batch norm layer
            torch.nn.BatchNorm1d(channels[0][0]),
            # adding ReLU
            torch.nn.ReLU(),
            # adding max pool
            torch.nn.MaxPool1d(kernel_size = 4, stride = 4, padding = pool_padding[0]),
        )

        # create res
        prev_channel = channels[0][0]
        self.res_blocks = torch.nn.ModuleList()
        for i in range(1, len(channels)):
            # add stacked res layer
            block = []
            for j, conv_channel in enumerate(channels[i]):
                block.append(ResBlock(prev_channel, conv_channel, conv_kernels[i], conv_strides[i], conv_padding[i]))
                prev_channel = conv_channel
            self.res_blocks.append(torch.nn.Sequential(*block))

        # create pool blocks
        self.pool_blocks = torch.nn.ModuleList()
        for i in range(1, len(pool_padding)):
            # adding Max Pool (drops dims by a factor of 4)
            self.pool_blocks.append( torch.nn.MaxPool1d(kernel_size = 4, stride = 4, padding = pool_padding[i]) )

        # global pooling
        self.global_pool = torch.nn.AdaptiveAvgPool1d(1)
        self.linear = torch.nn.Linear(prev_channel, num_classes)

    def forward(self, inwav):
        inwav = self.conv_block(inwav)
        for i in range(len(self.res_blocks)):
            # apply conv layer
            inwav = self.res_blocks[i](inwav)
            # apply max_pool
            if i < len(self.pool_blocks): inwav = self.pool_blocks[i](inwav)
        # apply global pooling
        out = self.global_pool(inwav).squeeze()
        out = self.linear(out)
        return out

m6_res = CNNRes(channels = [[128], [128]*2],
         conv_kernels = [80, 3],
         conv_strides = [4, 1],
         conv_padding = [38, 1],
         pool_padding = [0, 0])


#!/usr/bin/python3
import csv,re
from argparse import ArgumentParser

COMMENT_REGEX = r';.+|;'
NOTHING = ""
LABEL_REGEX = r'\.[A-za-z]+:'
TRAILING_REGEX = r'^\s+'
INSTRUCTION_REGEX = r'[A-z]+\s'
INSTR_COL_LAYOUT = "#instr"
PIN_COL_LAYOUT = "pin"
ARG0_COL_LAYOUT = "arg0"
ARG1_COL_LAYOUT = "arg1"
ARG2_COL_LAYOUT = "arg2"
ARGCOUNT_COL_LAYOUT = "argCount"
PIN = 0
DEST = 1
SRC0 = 2
SRC1 = 3
ARGS = 4
BIN_DELIMINATOR = 238                   # Use EE as deliminiator

def loadMapFile(mapFile):
        with open(mapFile, newline='') as csvfile:
                layout = csv.DictReader(csvfile)
                output = dict()
                for row in layout:
                        output[row[INSTR_COL_LAYOUT]] =  (
                                        row[PIN_COL_LAYOUT],
                                        row[ARG0_COL_LAYOUT],
                                        row[ARG1_COL_LAYOUT],
                                        row[ARG2_COL_LAYOUT],
                                        row[ARGCOUNT_COL_LAYOUT]
                                )
        return output

def loadAssembly(input):
        assembly = open(input,"r")
        assembly = assembly.read().split("\n")
        assembly = [re.sub(COMMENT_REGEX, NOTHING, line) for line in assembly]
        assembly = [line for line in assembly if line]
        return assembly

def convertLabelsToPAddr(assembly):
        labels = dict()
        for ln, line in enumerate(assembly):
                if re.search(LABEL_REGEX, line):
                        label = str(re.search(LABEL_REGEX, line).group(0))
                        labels[label.strip(':')] = ln

        asmString = '\n'.join(assembly)

        for key in labels.keys():
                asmString = asmString.replace(f'{key}:', " "*(len(key)+1))

        del labels['.main']

        for label, ln in labels.items():
                asmString = asmString.replace(label, str(ln))

        assembly = asmString.split('\n')

        return [re.sub(TRAILING_REGEX, NOTHING, line) for line in assembly]

def determineLiteralType(instr,layout, argID):
        typeDescriptor = layout[instr][argID]

        pinStart = int(re.findall(r'\d+', typeDescriptor)[0])
        pinEnd = int(re.findall(r'\d+', typeDescriptor)[1])

        bits = pinEnd - pinStart+1
        flipRequire = True if typeDescriptor.find("[^") == -1 else False
        return (pinStart, pinEnd, bits, flipRequire)

def parseArgs(instr, args, layout,ln):
        output = 0
        for i in range(int(layout[instr][ARGS])):
                typeParameters = determineLiteralType(instr, layout, i+1)
                try:
                        literal = int(re.search(r'\d+',args[i]).group(0))
                except IndexError:
                        print(f'{ln: >2}: At {instr + " " +", ".join(args)} -> Not enough arguments supplied. Probably missing source and dest address?')
                        quit()
                if literal > pow(2, typeParameters[2]):   #       If literal is oversized
                        print(f'{ln: >2}: At {instr + " " +", ".join(args)} -> The literal {literal} is too big. At most {typeParameters[2]} is accepted.')
                        quit()

                argBinary = str(bin(literal)).replace("0b", NOTHING)            # Replace 0b suffix
                argBinary = f"{argBinary:0>{typeParameters[2]}}"                # Add padding

                if typeParameters[3]:                                           # Flip if required
                        argBinary = argBinary[::-1]

                for offset, n in enumerate(argBinary):
                        output += int(n) * pow(2,(offset + typeParameters[0]))

        return output

def assembleArgs(instr, args, layout,ln):
        args = args.replace(" ","").split(',')
        return parseArgs(instr, args, layout,ln)

def assembleInstruction(assembly, layout, output='', showPins=False):

        if showPins:
                print(f'{" Pin configuration ":-^45}')
        else:
                print(" "*4+"0"*72)

        code = list()
        for ln, line in enumerate(assembly):
                instr = re.search(INSTRUCTION_REGEX, line).group(0).strip(' ')
                pins = tuple(map(int,layout[instr][PIN].split(',')))
                opcode = 0
                for n in pins:
                        opcode += pow(2,n)
                opcode += assembleArgs(instr, line.replace(instr + ' ',''),layout,ln)
                binCode = f'{str(bin(opcode)).replace("0b",NOTHING)[::-1]:0<68}'

                if showPins:
                        print(f"{ln: >2}: {', '.join(map(str, [m.start() for m in re.finditer('1', binCode)]))}") # Show pins
                else:
                        print(f'{ln: >2}: 0000{binCode} ({hex(int(binCode,2))})')

                code.append(bytearray([m.start() for m in re.finditer('1', binCode)] + [BIN_DELIMINATOR]))

        if output == '':
                quit()
        else:
                file = open(output, "wb")
                for line in code:
                        data = line
                        file.write(data)
                file.close()
        return

def assemble(input, output, mapFile, pin):
        layout = loadMapFile(mapFile)
        assembly = loadAssembly(input)
        assembly = convertLabelsToPAddr(assembly)
        [print(f'{ln: >2}: {line}') for ln, line in enumerate(assembly)]
        assembleInstruction(assembly, layout, output, showPins=pin)
        return

def showHelp():
        HELP_MSG_1 = '-'*60 + "\n" + "| " + f'{"H831 Minecraft CPU Assembler tool": ^56}' + " |\n| " + " "*56 + " |"
        HELP_MSG_2 = f'{"| Author: HyperXraft": <58}' + " |"
        HELP_MSG_3 = f'{"| Date  : 2020-09-02": <58}' + " |"
        HELP_MSG_4 = '-'*60

        print(HELP_MSG_1)
        print(HELP_MSG_2)
        print(HELP_MSG_3)
        print(HELP_MSG_4)

        parser = ArgumentParser()
        parser.add_argument(help="File for assembly program", dest="IN_FILENAME", default="", type=str)
        parser.add_argument(help="Microcode descriptor file", dest="MAPFILE", default="", type=str)
        parser.add_argument("-p", "--pin", action="store_true", help="Show pin code instead of binary")
        parser.add_argument("-o", help="File for assembler output", dest="OUT_FILENAME", default="", type=str)

        args = parser.parse_args()

        inputFile = args.IN_FILENAME
        outputFile = args.OUT_FILENAME
        mapFile = args.MAPFILE
        showPins = args.pin

        if inputFile == NOTHING or mapFile == NOTHING:
                parser.print_help()
                quit()

        print(f'{"Input:": <30}{inputFile}')
        print(f'{"Mapfile:": <30}{mapFile}')
        print(f'{"Output:": <30}{outputFile}')

        assemble(inputFile, outputFile, mapFile, showPins)

showHelp()


#!/usr/bin/env python

from django.db import models
from django.utils.translation import ugettext_lazy as _

from panda.models.category import Category
from panda.models.dataset import Dataset
from panda.models.user_proxy import UserProxy

class SearchSubscription(models.Model):
    """
    A log of a user search.
    """
    user = models.ForeignKey(UserProxy, related_name='search_subscriptions',
        help_text=_('The user who subscribed to the search.'),
        verbose_name=_('user'))
    dataset = models.ForeignKey(Dataset, related_name='search_subscriptions', null=True, default=None,
        help_text=_('The dataset to be searched or null if all are to be searched.'),
        verbose_name=_('dataset'))
    category = models.ForeignKey(Category, related_name='search_subscriptions', null=True, default=None,
        help_text=_('A category to be searched or null if all are to be searched.'),
        verbose_name=_('category'))
    query = models.CharField(_('query'), max_length=256,
        help_text=_('The search query to executed.'))
    query_url = models.CharField(_('query_url'), max_length=256,
        help_text=_('Query encoded for URL.'))
    query_human = models.TextField(_('query_human'),
        help_text=_('Human-readable description of the query being run.'))
    last_run = models.DateTimeField(_('last_run'), auto_now=True,
        help_text=_('The last time this search this was run.'))

    class Meta:
        app_label = 'panda'
        verbose_name = _('SearchSubscription')
        verbose_name_plural = _('SearchSubscriptions')

    def __unicode__(self):
        if self.dataset:
            return _('%(user)s is searching for %(query)s in %(dataset)s') \
                % {'user': self.user, 'query': self.query, 'dataset': self.dataset}
        else:
            return _('%(user)s is searching for %(query)s in all datasets') \
                % {'user': self.user, 'query': self.query}


import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from typing import Optional

class FocalLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(FocalLoss, self).__init__()

    def forward(
        self,
        y_pred: torch.Tensor,
        y_true: torch.Tensor,
        alpha: Optional[float] = 0.8,
        gamma: Optional[float] = 2.0,
        smooth: Optional[int] = 1,
    ) -> torch.Tensor:
        y_pred = F.sigmoid(y_pred)
        y_pred = y_pred.view(-1)
        y_true = y_true.view(-1)

        logpt = F.binary_cross_entropy(y_pred, y_true, reduction="mean")
        pt = torch.exp(-logpt)
        focal_term = (1.0 - pt).pow(gamma)
        focal_loss = alpha * focal_term * logpt

        return focal_loss

class DiceLoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(DiceLoss, self).__init__()

    def forward(
        self, y_pred: torch.Tensor, y_true: torch.Tensor, smooth: Optional[int] = 1
    ) -> torch.Tensor:
        y_pred = F.sigmoid(y_pred)

        y_pred = y_pred.view(-1)
        y_true = y_true.view(-1)

        intersection = (y_pred * y_true).sum()
        dice = (2.0 * intersection + smooth) / (y_pred.sum() + y_true.sum() + smooth)
        return 1 - dice

class DiceBCELoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(DiceBCELoss, self).__init__()

    def forward(
        self, y_pred: torch.Tensor, y_true: torch.Tensor, smooth: Optional[int] = 1
    ) -> torch.Tensor:
        y_pred = F.sigmoid(y_pred)

        y_pred = y_pred.view(-1)
        y_true = y_true.view(-1)
        intersection = (y_pred * y_true).sum()
        dice = 1 - (2.0 * intersection + smooth) / (
            y_pred.sum() + y_true.sum() + smooth
        )
        BCE = F.binary_cross_entropy(y_pred, y_true, reduction="mean")
        dice_bce = BCE + dice

        return dice_bce

class IoULoss(nn.Module):
    def __init__(self, weight=None, size_average=True):
        super(IoULoss, self).__init__()

    def forward(
        self, y_pred: torch.Tensor, y_true: torch.Tensor, smooth: Optional[int] = 1
    ) -> torch.Tensor:
        y_pred = F.sigmoid(y_pred)

        y_pred = y_pred.view(-1)
        y_true = y_true.view(-1)

        intersection = (y_pred * y_true).sum()
        union = (y_pred + y_true).sum() - intersection
        IoU = (intersection + smooth) / (union + smooth)
        return 1 - IoU

# Note when alpha and beta = 0.5 this is the same as Dice Loss
class TverskyLoss(nn.Module):
    def __init__(self, weights=None, size_average=True):
        super(TverskyLoss, self).__init__()

    def forward(
        self,
        y_pred: torch.Tensor,
        y_true: torch.Tensor,
        smooth: Optional[int] = 1,
        alpha: Optional[float] = 0.5,
        beta: Optional[float] = 0.5,
    ) -> torch.Tensor:
        y_pred = F.sigmoid(y_pred)

        y_pred = y_pred.view(-1)
        y_true = y_true.view(-1)

        TP = (y_pred * y_true).sum()
        FP = ((1 - y_true) * y_pred).sum()
        FN = (y_true * (1 - y_pred)).sum()

        tversky = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth)

        return 1 - tversky

class FocalTverskyLoss(nn.Module):
    pass

class LovaszHingeLoss(nn.Module):
    pass

class ComboLoss(nn.Module):
    pass


# 회문 1
import sys
sys.stdin = open('input.txt')

def solution(word):     # 팰린드롬인지 확인하는 함수
    length = len(word)      # 단어의 길이
    check = 0       # 양 끝 값이 일치하는 횟수
    is_pal = False      # 회문 확인

    for k in range(length // 2):       # 홀수 일 때 가운데 확인X
        if word[k] == word[length - 1 - k]:
            check += 1

    if check == (length // 2):     # 회문일 때
        is_pal = True       # True 반환

    return is_pal

T = 10
for t in range(1, T+1):
    N = 8   # 8*8 크기의 글자판
    M = int(input())    # 찾아야 할 회문의 길이
    str_ls = [list(map(str, input().rstrip())) for _ in range(N)] # 입력값 리스트로 받아줌
    cnt = 0     # 회문 갯수 변수 선언
    # 가로, 세로 한번에 탐색
    for i in range(N):     # i는 탐색을 할 행 또는 열
        for j in range(N-M+1):  # N에서 M을 뺀 만큼만 이동
            word_w = []     # 가로 단어를 넣어줄 빈 리스트 선언
            word_h = []     # 세로 단어를 넣어줄 빈 리스트 선언

            for wh in range(j, j+M):    # M 길이만큼
                word_w.append(str_ls[i][wh])    # 가로
                word_h.append(str_ls[wh][i])    # 세로

            cnt += solution(word_w)     # 가로 회문 횟수 카운팅
            cnt += solution(word_h)     # 세로 회문 횟수 카운팅

    print(f'#{t}', cnt)


from flask import request
from flask_socketio import emit,Namespace
from datetime import datetime

online_list = {}

class Chat(Namespace):

    def on_connect(self):
        print("有个小子{}连接上了".format(request.sid))

    def on_disconnect(self):
        # 翻转后删除key
        new_dict = {v: k for k, v in online_list.items()}
        keys = new_dict[request.sid]
        del online_list[keys]
        emit('broad', online_list, namespace='/chat', broadcast=True)
        print("有个小子{}断开了连接".format(request.sid))

    def on_private_message(self,data):
        print('sid is {}'.format(request.sid))
        print("收到有个小子发来的信息{}".format(data))
        data['time'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        to_sid = online_list[data['to']]
        emit('private_message', data, room=to_sid)

    def on_bind(self,data):
        print('sid is {}'.format(request.sid))
        uid = data['uid']
        online_list[uid] = request.sid
        emit('broad', online_list , namespace='/chat' , broadcast=True) # 给所有用户
        print("在线用户 {}".format(online_list))


"""
Detect and remove mux scans (for non-Flongles)
"""

from collections import Counter
from pathlib import Path
from typing import List, Tuple
import numpy as np
import pandas as pd
import tqdm
from simreaduntil.seqsum_tools.seqsum_preprocessing import sort_and_clean_seqsum_df

from simreaduntil.shared_utils.utils import is_sorted

def find_mux_scans(start_times, end_times, muxes, max_block_gap=1, max_intv_gap=20, min_mux_frac=0.95) -> List[Tuple[float, float]]:
    """
    Find mux scan windows when the channel is scanning all the wells (muxes) to determine the best well

    **Note**: This does not work for Flongle runs because they only have a single mux.

    The mux scans are characterized by the mux changing from 1, 2, 3, 4 in this order.
    Although they should occur at 90 minutes intervals, this is not always exactly the case.
    We refer to a mux scan as a consecutive set of windows (of reads at most max_block_gap apart), where the dominant
    fraction of muxes (according to min_mux_frac) of window i is i.

    This method works best with many channels because muxes are performed simultaneously
    across all channels and this way, we can detect whether all channels are scanning the same mux at a time.
    Assumes that the sequencing starts at time 0.

    This code was refactored from sim_utils.py in UNCALLED, mostly by documenting the code and renaming variables.
    The code does not seem very robust, but we don't want to modify it too much.

    Args:
        start_times: start times of reads
        end_times: end times of reads
        muxes: muxes, i.e. which pore in the channel is used
        max_block_gap: maximum distance between reads in windows that will be tested for mux scan segment (for a fixed mux 1, 2, 3, 4),
            if two reads are more than max_block_gap apart, they are in different blocks

        max_intv_gap: if two mux scan windows are more than max_intv_gap apart, they are in different mux scan windows
        min_mux_frac: minimum fraction to classify a region as scanning a certain mux (1, 2, 3 or 4)

    Returns:
        2d np.array of shape (m, 2) of (start, end) times of mux scans
"""
    # pd.Series does not work because of indexing (probably)
    assert isinstance(start_times, np.ndarray)
    assert isinstance(end_times, np.ndarray)
    assert isinstance(muxes, np.ndarray)

    order = np.argsort(start_times)
    start_times = start_times[order] # start times of reads
    end_times = end_times[order] # end times of reads
    muxes = muxes[order] # muxes, i.e. which pore in the channel is used

    # first find blocks within which reads are at most max_block_gap apart

    active_blocks = list() # set of (t_start, t_end) describing active periods
    window_start = start_times[0] # start time of current window
    window_end = end_times[0] # end time of current window

    for (rst, ren) in zip(start_times[1:], end_times[1:]):
        if rst - window_end > max_block_gap:
            active_blocks.append( (window_start, window_end) )
            window_start = rst
            window_end = ren
        else:
            window_end = max(ren, window_end)
            #cur_window_end = ren
    active_blocks.append((window_start, window_end))

    # given the blocks, find mux scan windows
    # they are characterized by the mux changing from 1, 2, 3, 4 in this order, so we only record a mux scan window when there are exactly four elements with increasing muxes
    # for the mux=1 window, we merge it with the previous mux=1 window if they are less than max_intv_gap apart; if they are more apart, we discard the previous mux=1 window
    # finally, the mux window is the window preceding the first mux=1 window to the window following the end of the last mux=4 window
    # whenever two windows are more than max_intv_gap apart, they are in different mux scan windows

    mux_scan_windows = list() # list of mux scans, each entry is a scan of four elements
    scan_gaps = list() # list of (float, float) tuples denoting gaps to the previous and next window for the mux=1 window and mux=4 window
    cur_scan_segments = list() # running list of four (start, end) tuples, corresponding to muxes 1,2,3,4 respectively

    prev_window_end = 0
    for (window_start, window_end) in active_blocks:

        if len(cur_scan_segments) > 0 and window_start - cur_scan_segments[-1][1] > max_intv_gap:
            if len(cur_scan_segments) == 4:
                mux_scan_windows.append(cur_scan_segments)
                # todo2: bug? scan_gaps not appended to
                raise Exception("Should not happen")
            cur_scan_segments = list()

        mux_counts = Counter(muxes[(start_times >= window_start) & (start_times < window_end)]) # count muxes in current window across all channels and see if all channels are predominantly using one mux
        mux_counts = [(c, m) for (m, c) in mux_counts.items()]
        top_count, top_mux = max(mux_counts)

        if top_count / sum((c for (c, m) in mux_counts)) >= min_mux_frac:
            # if the window has a dominant mux (>= min_mux_frac = 0.95)

            if top_mux != 4 and len(cur_scan_segments) == 4:
                # out-of-order, but since we went from 1 to 4, we can finish the mux scan window
                mux_scan_windows.append(cur_scan_segments)

                scan_gaps.append((gap_before_scan,
                                  window_start - cur_scan_segments[-1][1]))

                cur_scan_segments = list()

            if len(cur_scan_segments) > 0 and top_mux == len(cur_scan_segments):
                # window has same mux as previous window
                if window_end - cur_scan_segments[-1][1] < max_intv_gap:
                    # merge windows by modifying scan window
                    cur_scan_segments[-1] = (cur_scan_segments[-1][0], window_end)

                elif top_mux == 1:
                    # if it is mux=1 and above max_intv_gap, discard the old window
                    cur_scan_segments[0] = (window_start, window_end)
                    gap_before_scan = window_start - prev_window_end # gap before mux=1 window
                # otherwise: don't take window into account, todo2: should discard window?

            elif top_mux-1 == len(cur_scan_segments):
                # window has mux one higher than previous window
                cur_scan_segments.append( (window_start, window_end) )
                if len(cur_scan_segments) == 1:
                    # mux=1 window in mux scan
                    gap_before_scan = window_start - prev_window_end

            else:
                # in a mux scan, the mux only increases sequentially
                # since this was not the case, discard current scan
                cur_scan_segments = list()
        else:
            if len(cur_scan_segments) == 4:
                mux_scan_windows.append(cur_scan_segments)
                scan_gaps.append((gap_before_scan,
                                  window_start - cur_scan_segments[-1][1]))
            cur_scan_segments = list()

        prev_window_end = window_end

    # enlargen windows to include gaps
    scans = list()
    for (segs, gaps) in zip(mux_scan_windows, scan_gaps):
        scans.append((segs[0][0]-gaps[0], segs[-1][1]+gaps[1]))

    return np.array(scans) if len(scans) > 0 else np.zeros(shape=(0, 2), dtype=np.float64)

def check_mux_scan_windows(seqsum_df, mux_scan_windows):
    """
    Check that each read is either entirely outside or entirely inside a mux scan,
    """
    assert all(np.diff(mux_scan_windows.flatten()) > 0), "windows should have positive length"

    for (start, end) in tqdm.tqdm(mux_scan_windows, "Checking no read partially intersects mux scan window"):
        # check each element either is before mux scan, inside, or after
        assert all(
            ((seqsum_df["start_time"] <= start) & (seqsum_df["end_time"] <= start)) |
            ((seqsum_df["start_time"] >= start) & (seqsum_df["end_time"] <= end)) |
            ((seqsum_df["start_time"] >= end) & (seqsum_df["end_time"] >= end))
        )

def plot_mux_scans(mux_scan_windows, ax):
    """
    Add mux scans as gray regions (axvspan)

    Args:
        mux_scan_windows: list of tuples (start_time, end_time)
        ax: matplotlib axis
    """
    for (start_time, end_time) in mux_scan_windows: # [(10, 20), (25,30)]
        ax.axvspan(start_time, end_time, facecolor='gray', alpha=0.5)
        ax.axvline(start_time, color="black")
        ax.axvline(end_time, color="black")

def _remove_reads_inside_mux_scans(seqsum_df, mux_scan_windows):
    """
    Remove reads that are entirely inside mux scans

    Args:
        seqsum_df: seqsum dataframe
        mux_scan_windows: list of tuples (start_time, end_time)
    """

    # build mask of elements that are not inside mux scans
    removal_mask = np.zeros(len(seqsum_df), dtype=bool)
    for (start, end) in mux_scan_windows:
        removal_mask |= (seqsum_df["start_time"] >= start) & (seqsum_df["end_time"] <= end)
    # remove reads inside a mux scan

    return seqsum_df[~removal_mask]

def remove_mux_scans(seqsum_df, mux_scan_windows):
    """
    Remove the mux scans from the sequencing summary by shifting times

    Removes reads that are entirely inside mux scans
    Adds a column "nb_scans_before", i.e. how many mux scans have been performed before this read

    Args:
        seqsum_df: sequencing summary
        mux_scan_windows: list of (start, end) tuples of mux scan windows

    Returns:
        Tuple of (the modified sequencing summary, mux scan boundaries)
    """

    seqsum_df = seqsum_df.copy()
    mux_scan_windows = mux_scan_windows.copy()

    seqsum_df = _remove_reads_inside_mux_scans(seqsum_df, mux_scan_windows)
    seqsum_df["nb_scans_before"] = 0

    assert is_sorted(mux_scan_windows.flatten()), "mux scan windows should be sorted"

    for i in range(len(mux_scan_windows)):
        start, end = mux_scan_windows[i]
        # remove ith mux scan from times
        window_length = end - start

        mux_scan_windows[mux_scan_windows > start] -= window_length

        seqsum_df.loc[seqsum_df["start_time"] > start, "start_time"] -= window_length
        seqsum_df.loc[seqsum_df["end_time"] > start, "end_time"] -= window_length
        seqsum_df.loc[seqsum_df["template_start"] > start, "template_start"] -= window_length

        seqsum_df.loc[seqsum_df["start_time"] > start, "nb_scans_before"] += 1

    assert np.allclose(mux_scan_windows[:, 0], mux_scan_windows[:, 1]), "mux scan windows should now have length 0"

    return seqsum_df, mux_scan_windows[:, 0]

def get_seqsum_filename_with_removed_mux_scans(seqsum_filename):
    """Filename to remove sequencing summary with removed mux scans, in same directory"""
    seqsum_filename = Path(seqsum_filename)
    return seqsum_filename.parent / ("no_mux_scans_" + seqsum_filename.name)

def remove_mux_scans_from_file(sequencing_summary_file, save_filename=None):
    """
    Remove mux scans from sequencing summary file and write it back to a new file

    Args:
        sequencing_summary_file: path to sequencing summary file
        save_filename: filename to save to; if None, don't save

    Returns:
        Tuple of (original sequencing summary, mux scan boundaries, path to new sequencing summary file)
    """

    df_read = pd.read_csv(sequencing_summary_file, sep="\t")
    seqsum_df = sort_and_clean_seqsum_df(df_read, min_gap_duration=None)#, min_gap_duration=0.05)

    mux_scan_windows = find_mux_scans(seqsum_df["start_time"].values, seqsum_df["end_time"].values, seqsum_df["mux"].values)
    check_mux_scan_windows(seqsum_df, mux_scan_windows)
    print("Removing mux scans")
    seqsum_df_new, mux_scan_boundaries = remove_mux_scans(seqsum_df, mux_scan_windows)

    if save_filename is not None:
        print(f"Saving to '{save_filename}'")
        seqsum_df_new.to_csv(save_filename, sep="\t", index=False)

    return seqsum_df, mux_scan_boundaries


import logging
import threading
from collections import deque
from typing import List

import weewx
from user.weatherlink_live.callback import PacketCallback
from user.weatherlink_live.davis_broadcast import WllBroadcastReceiver
from user.weatherlink_live.davis_http import start_broadcast, request_current
from user.weatherlink_live.mappers import AbstractMapping
from user.weatherlink_live.packets import DavisConditionsPacket

log = logging.getLogger(__name__)

class DataHost(object):
    """Base host class for polled as well as broadcasted data"""

    def __init__(self, mappers: List[AbstractMapping], data_event: threading.Event):
        self._mappers = mappers
        self._data_event = data_event

        self.packets = deque()
        self.error = None

    @property
    def has_error(self):
        return self.error is not None

    def raise_error(self):
        if self.has_error:
            raise self.error

    def _create_record(self, packet: DavisConditionsPacket):
        record = dict()

        for mapper in self._mappers:
            mapper.map(packet, record)
        self.packets.append(record)

        record['dateTime'] = packet.timestamp
        record['usUnits'] = weewx.US

        self._data_event.set()

    def notify_error(self, e):
        self.error = e
        self._data_event.set()

class WllPollHost(DataHost):
    """Host object for polling data from WLL"""

    def __init__(self,
                 host: str,
                 mappers: List[AbstractMapping],
                 data_event: threading.Event,
                 http_timeout: float = 20):
        super().__init__(mappers, data_event)
        self.host = host
        self.http_timeout = http_timeout

    def poll(self):
        packet = request_current(self.host, timeout=self.http_timeout)
        log.debug("Polled current conditions")

        self._create_record(packet)

    def close(self):
        pass

class WLLBroadcastHost(DataHost, PacketCallback):
    """Class for triggering UDP broadcasts and receiving them"""

    def __init__(self,
                 host: str,
                 mappers: List[AbstractMapping],
                 data_event: threading.Event,
                 http_timeout: float = 20):
        super().__init__(mappers, data_event)
        self.host = host
        self.http_timeout = http_timeout

        self._receiver = None
        self._port = 22222

    def refresh_broadcast(self, request_duration: float):
        log.debug("Re-requesting UDP broadcast")
        packet = start_broadcast(self.host, request_duration, timeout=self.http_timeout)
        port = packet.broadcast_port

        if self._port != port:
            log.info("Broadcast port changed from %s to %s" % (self._port, port))
            self._port = port

        log.debug("Restarting broadcast reception")
        self._stop_broadcast_reception()
        self._start_broadcast_reception()

    def _start_broadcast_reception(self):
        self._receiver = WllBroadcastReceiver(self.host, self._port, self)

    def _stop_broadcast_reception(self):
        if self._receiver is None:
            return
        self._receiver.close()

    def on_packet_received(self, packet: DavisConditionsPacket):
        log.debug("Received new broadcast packet")
        try:
            self._create_record(packet)
        except Exception as e:
            self.notify_error(e)
            self.close()

    def on_packet_receive_error(self, e: BaseException):
        self.notify_error(e)
        self.close()

    def close(self):
        self._stop_broadcast_reception()


# newplots.py
"""Volume 1A: Data Visualization. Plotting file."""

from __future__ import print_function
import matplotlib
matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')

# Decorator ===================================================================

from matplotlib import colors, pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
from functools import wraps
from sys import stdout
import os

def _save(filename):
    """Decorator for saving, clearing, and closing figures automatically."""
    try:
        name, extension = filename.split(".")
    except (ValueError, TypeError) as e:
        raise ValueError("Invalid file name '{}'".format(filename))
    if extension not in {"pdf", "png"}:
        raise ValueError("Invalid file extension '{}'".format(extension))
    if not os.path.isdir("figures"):
        os.mkdir("figures")

    def decorator(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            try:
                print("{:.<40}".format(filename), end='')
                stdout.flush()
                plt.clf()
                out = func(*args, **kwargs)
                plt.savefig("figures/"+filename, format=extension)
                print("done.")
                return out
            except Exception as e:
                print("\n\t", e, sep='')
            finally:
                plt.clf()
                plt.close('all')
        return wrapper
    return decorator

# Plots =======================================================================

import numpy as np

# Problem 1 -------------------------------------------------------------------

def anscombe_data(save=False):
    data = np.array([[10.0,  8.04, 10.0, 9.14, 10.0,  7.46,  8.0,  6.58],
                     [ 8.0,  6.95,  8.0, 8.14,  8.0,  6.77,  8.0,  5.76],
                     [13.0,  7.58, 13.0, 8.74, 13.0, 12.74,  8.0,  7.71],
                     [ 9.0,  8.81,  9.0, 8.77,  9.0,  7.11,  8.0,  8.84],
                     [11.0,  8.33, 11.0, 9.26, 11.0,  7.81,  8.0,  8.47],
                     [14.0,  9.96, 14.0, 8.10, 14.0,  8.84,  8.0,  7.04],
                     [ 6.0,  7.24,  6.0, 6.13,  6.0,  6.08,  8.0,  5.25],
                     [ 4.0,  4.26,  4.0, 3.10,  4.0,  5.39, 19.0, 12.50],
                     [12.0, 10.84, 12.0, 9.13, 12.0,  8.15,  8.0,  5.56],
                     [ 7.0,  4.82,  7.0, 7.26,  7.0,  6.42,  8.0,  7.91],
                     [ 5.0,  5.68,  5.0, 4.74,  5.0,  5.73,  8.0,  6.89]])
    if save:
        np.save("anscombe.npy", data)
    return data

# Problem 2 -------------------------------------------------------------------

# Line Plots / Small Multiples (Chebyshev Polynomials) - - - - - - - - - - - -

@_save("chebyshev_bad.pdf")
def line_bad():
    x = np.linspace(-1, 1, 200)
    for n in range(9):
        plt.plot(x, np.polynomial.Chebyshev.basis(n)(x), lw=1,
                                                label=r"$n = {}$".format(n))
    plt.axis([-1.1, 1.1, -1.1, 1.1])
    plt.legend()

@_save("chebyshev_good.pdf")
def line_good():
    x = np.linspace(-1, 1, 200)
    for n in range(9):
        plt.subplot(3,3,n+1)
        plt.plot(x, np.polynomial.Chebyshev.basis(n)(x))
        plt.axis([-1.1, 1.1, -1.1, 1.1])

        # Turn off extra tick marks and axis labels.
        plt.tick_params(which="both", top="off", right="off")
        if n < 6:
            plt.tick_params(labelbottom="off")
        if n % 3:
            plt.tick_params(labelleft="off")
        plt.title(r"$T_{}$".format(n))

# Scatter Plots - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

@_save("scatter_1_bad.pdf")
def scat_1_bad():
    data = anscombe_data()
    x, y = data[:,2], data[:,3]
    plt.scatter(x, y, c='b', s=500)
    return x, y

@_save("scatter_1_good.pdf")
def scat_1_good(x, y):
    plt.scatter(x, y, s=.5*y**4, alpha=.8)
    return x, y

@_save("scatter_2_bad.pdf")
def scat_2_bad():
    data = anscombe_data()
    x, y = data[:,4], data[:,5]
    plt.scatter(x, y, c='b', s=500)
    return x, y

@_save("scatter_2_good.pdf")
def scat_2_good(x, y):
    plt.scatter(x, y, s=500, c=y, alpha=.8)
    cbar = plt.colorbar()
    cbar.set_label("y")

def prob2():
    line_bad()
    line_good()
    scat_1_good(*scat_1_bad())
    scat_2_good(*scat_2_bad())

# Problem 3 -------------------------------------------------------------------

@_save("hist_1_bad.pdf")
def hist_1_bad(N):
    data = np.random.normal(size=N)
    plt.plot(data)
    return data

@_save("hist_1_good.pdf")
def hist_1_good(data):
    plt.hist(data, bins=30)

@_save("hist_2_bad.pdf")
def hist_2_bad(N):
    data = np.random.exponential(size=N)
    plt.hist(data, bins=30)
    return data

@_save("hist_2_good.pdf")
def hist_2_good(data):
    plt.hist(data, bins=30, lw=0, histtype="stepfilled")
    plt.tick_params(axis="y", which="both", labelcolor='white', left='off',
                                                                right="off")
    plt.tick_params(axis="x", which="both", top='off')

def hist_3(N):
    data = np.random.beta(a=5, b=2, size=N)
    freq, bin_edges = np.histogram(data, bins=50)
    bin_centers = (bin_edges[:-1] + bin_edges[1:])/2.
    plt.plot(bin_centers, freq, 'b-', lw=4)
    plt.hist(data, bins=50, alpha=.1)
    plt.tick_params(axis="both", which="both", labelleft='off',
                                left="off", top="off", right="off")

# Problem Statement - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

@_save("earthquake.pdf")
def earthquake():
    years, magnitudes, longitude, latitude = np.load("earthquakes.npy").T
    plt.plot(years, magnitudes, '.')
    plt.xlabel("Year")
    plt.ylabel("Magnitude")

def prob3():

    hist_1_good(hist_1_bad(10000))
    hist_2_good(hist_2_bad(10000))
    _save("hist_3_bad.pdf")(hist_3)(10000)
    _save("hist_3_good.pdf")(hist_3)(10000000)

    earthquake()

# Problem 4 -------------------------------------------------------------------

@_save("rosenbrock.pdf")
def rosenbrock():
    fig = plt.figure()
    ax = Axes3D(fig, azim = -128, elev = 43)
    x = np.linspace(-2, 2, 50)
    y = np.linspace(-1, 3, 50)
    X, Y = np.meshgrid(x, y)
    Z = (1.-X)**2 + 100.*(Y-X**2)**2
    ax.plot_surface(X, Y, Z, rstride = 1, cstride = 1, cmap="viridis", linewidth=0, edgecolor='none', norm=colors.LogNorm())

    ax.set_xlim([-2, 2.0])
    ax.set_ylim([-1, 3.0])
    ax.set_zlim([0, 2500])

    plt.xlabel("x")
    plt.ylabel("y")

def save_all():
    prob2()
    # prob3()
    # rosenbrock()

if __name__ == '__main__':
    save_all()


def coder(message: str, number_of_tracks: int) -> str:
    if number_of_tracks < 2:
        raise Exception("Number of tracks must be greater than 2")
    track = 0
    direction = 1
    coded_message = ['' for _ in range(number_of_tracks)]
    for sign in message:
        coded_message[track] += sign
        track += direction
        if track == number_of_tracks - 1 or track == 0:
            direction = -direction

    return ''.join([item for sublist in coded_message for item in sublist])

def decoder(message: str, number_of_tracks: int) -> str:
    if number_of_tracks < 2:
        raise Exception("Number of tracks must be greater than 2")
    track = 0
    direction = 1
    tracks = ['' for _ in range(number_of_tracks)]
    for _ in message:
        tracks[track] += "-"
        track += direction
        if track == number_of_tracks - 1 or track == 0:
            direction = -direction

    counter = 0
    index = 0
    decoded_tracks = ['' for _ in range(number_of_tracks)]
    for t in tracks:
        decoded_tracks[index] = message[counter:(counter + len(t))]
        counter += len(t)
        index += 1

    decoded_message = ""
    track = 0
    direction = 1
    for _ in message:
        decoded_message += decoded_tracks[track][0]
        decoded_tracks[track] = decoded_tracks[track][1:]
        track += direction
        if track == number_of_tracks - 1 or track == 0:
            direction = -direction

    return decoded_message

def main():
    print(decoder("WYADIZSBRRETSTHDECEAWKCZSZIMION", 5), coder("WITAMWSZYSTKICHBARDZOSERDECZNIE", 5))

if __name__ == "__main__":
    main()


db_user = {
    'jackson' : 'London',
    'jack' : 'Norway',
    '1': '1',
    '5': '5'
}

def removeUserDb():
    name = input("Pls user")

    if name in db_user:
        db_user.pop(name)
        print(db_user)
    else:
        print("User hasnt been found")

def PrintUser():
    for key, value in db_user.items():
        print(f"name: {key} and city {value}")

def addUser():
    name = input("Please person")
    city = input("Please city")
    db_user[name] = city

def Updater():
    name = input("Please User")
    if name in db_user:
        Value = db_user[name]
        ac = input("Please city")
        if ac == Value:
            ad = input("Please enter new city")
            db_user[name] = ad
        else:
            print("City isn't correct")
    else:
        print("User doesnt exist")
def Clear():
    db_user.clear()
def FindCityPersons():
    city = input("city -> ")
    for key, value in db_user.items():
        if value.lower() == city.lower():
            print(f"name: {key}")
def main():

    while True:
        print("1 - removeUserDb\n2 - PrintUser\n0 - exit\n3 - AddUser\n4 - Updater-*5* - Clear - *6* - Findallcityperson")
        check = int(input("---> "))
        if check == 1:
            removeUserDb()
        elif check == 2:
            PrintUser()
        elif check == 3:
            addUser()
        elif check == 4:
            Updater()
        elif check == 5:
            Clear()
        elif check == 6:
            FindCityPersons()
        elif check == 0:
            print("Closing program...")
            break
        else:
            print("You havent putten any of the current working numbers. Try again.")

main()


from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
from django.shortcuts import render

from exam.models import Exam, ExamDate, ExamCutoff

def get_exams(request):
    """Get the exams."""
    page = request.GET.get('page', 1)
    search_string = request.GET.get('q', None)
    if search_string:
        exam_list = Exam.objects.filter(
            full_name__icontains=search_string
        ).order_by('full_name')
    else:
        exam_list = Exam.objects.all().order_by('full_name')

    paginator = Paginator(exam_list, 9)
    try:
        exams = paginator.page(page)
    except PageNotAnInteger:
        exams = paginator.page(1)
    except EmptyPage:
        exams = paginator.page(paginator.num_pages)
    return render(
        request,
        'pages/exams.html',
        {
            'exams': exams
        }
    )

def get_single_exam(request, exam_slug):
    """Get single exam."""
    exam = Exam.objects.filter(slug=exam_slug).first()
    dates = ExamDate.objects.filter(
        exam=exam
    )
    cutoffs = ExamCutoff.objects.filter(
        exam=exam
    )
    return render(
        request,
        'pages/individual-exam.html',
        {
            'exam': exam,
            'dates': dates,
            'cutoffs': cutoffs
        }
    )


#16章分析csv中的文件数据

import csv                              # 用于分析CSV文件中的数据行

filename = 'C:\\Users\\huangshixin\\Desktop\sikta_weather_07_2020.csv'
with open(filename) as f:               # 打开文件，并将结果文件对象存储在f中
    reader = csv.reader(f)              # 创建与该文件相关联的阅读器对象，并存储在reader中
    header_row = next(reader)           # 第一行
    print(header_row)                   # 输出显示第一行

"""这里有一些模块待补充"""


# This is a sample Duppy server, using custom logic and an in-memory
# database of records.
#
# This is mostly useful for testing Duppy itself, but it nicely
# demonstrates how you would implement support for backends that don't
# fit our simplistic SQL defaults.
#
# See the examples/ folder for more examples.
#
import duppy
import logging

TEST_KEYS = {
    'example.com' : [
        'FM4d4LDAs9jP/N8EkvhhayqtqcO4tUJzvxsPyG20fkCE7g2IizVaTdeAwudLkwvhVECo50te6gJKhoxJkqUMOA==',
        'QlRlQTl4OA46nPX0/QEk65AECEbreeF8K7guyr5bAsk=',
        '+fnQhoAij/FNM0yCANXkKnxZCNIL7XI2yYRJokvTn+U='],
    'example.org' : ['+fnQhoAij/FNM0yCANXkKnxZCNIL7XI2yYRJokvTn+U='],
}

MOCK_ZONE = []

class MockServer(duppy.Server):

    # App settings
    listen_on = '127.0.0.2'

    # No database, we're writing our own Python code!
    sql_db_driver = None

    # We don't support transactions, so we don't implement these
    #   - transaction_start
    #   - transaction_commit
    #   - transaction_rollback

    async def get_keys(self, zone):
        while zone[-1:] == '.':
            zone = zone[:-1]
        if zone in TEST_KEYS:
            return TEST_KEYS[zone]
        else:
            logging.debug('Zone %s unavailable for updates' % zone)
            return []

    async def delete_all_rrsets(self, dbT, zone, dns_name):
        global MOCK_ZONE
        MOCK_ZONE = [rr for rr in MOCK_ZONE if rr[0] == dns_name]
        return True

    async def delete_rrset(self, dbT, zone, dns_name, rtype):
        global MOCK_ZONE
        MOCK_ZONE = [rr for rr in MOCK_ZONE
            if rr[0] == dns_name
            and rr[1] == rtype]
        return True

    async def delete_from_rrset(self, dbT, zone, dns_name, rtype, rdata):
        global MOCK_ZONE
        MOCK_ZONE = [rr for rr in MOCK_ZONE
            if rr[0] == dns_name
            and rr[1] == rtype
            and rr[-1] == rdata]
        return True

    async def add_to_rrset(self, dbT, zone, dns_name, rtype, ttl, i1, i2, i3, rdata):
        global MOCK_ZONE
        rr = [dns_name, rtype, ttl, i1, i2, i3, rdata]
        if rr not in MOCK_ZONE:
            MOCK_ZONE.append(rr)
        return True

    async def notify_changed(self, dbT, zone):
        print('*** Zone changed %s ***' % zone)
        print('%s' % '\n'.join('%s' % rr for rr in MOCK_ZONE))
        print('***')
        return True

try:
    MockServer().run()
finally:
    print('\nMock zone:\n%s' % '\n'.join('%s' % rr for rr in MOCK_ZONE))