import asyncio
import concurrent.futures
import subprocess
import threading

from . import selector, socket as _socket
from .exceptions import SolipsismError

__all__ = ('EventLoop', 'stream_pairs')

class EventLoop(asyncio.selector_events.BaseSelectorEventLoop):
    def __init__(self):
        super().__init__(selector=selector.Selector())
        self._selector = selector.Selector()
        self._clock_resolution = self._selector.clock.resolution
        # Map from (host, port) pair to ListenSocket
        self.__listening_sockets = {}
        self.__next_port = 1

    def time(self):
        return self._selector.clock.time()

    def call_soon_threadsafe(self, callback, *args, context=None):
        if self._thread_id == threading.get_ident():
            return self.call_soon(callback, *args, context=context)
        raise SolipsismError("call_soon_threadsafe is not supported")

    async def run_in_executor(self, executor, func, *args):
        # Mostly copies the base class code, but runs synchronously
        self._check_closed()
        if self._debug:
            self._check_callback(func, 'run_in_executor')
        if executor is None:
            executor = self._default_executor
            if executor is None:
                executor = concurrent.futures.ThreadPoolExecutor()
                self._default_executor = executor
        return executor.submit(func, *args).result()

    async def getaddrinfo(self, host, port, *,
                          family=0, type=0, proto=0, flags=0):
        raise SolipsismError("getaddrinfo is not supported")

    async def getnameinfo(self, sockaddr, flags=0):
        raise SolipsismError("getnameinfo is not supported")

    async def create_connection(
            self, protocol_factory, host=None, port=None,
            *, ssl=None, sock=None, **kwargs):
        if ssl:
            raise SolipsismError("create_connection with SSL is not supported")
        if sock is None:
            if host is None and port is None:
                raise ValueError('host and port was not specified and no sock specified')
            addr = (host, port, 0, 0)
            try:
                listener = self.__listening_sockets[addr]
            except KeyError:
                raise ConnectionRefusedError(f'No socket listening on {host}:{port}') from None
            port = self.__next_port
            self.__next_port += 1
            sock = await listener.make_connection(('::1', port, 0, 0))
        return await super().create_connection(
            protocol_factory, None, None,
            ssl=ssl, sock=sock, **kwargs
        )

    async def start_tls(self, transport, protocol, sslcontext, *,
                        server_side=False,
                        server_hostname=None,
                        ssl_handshake_timeout=None):
        raise SolipsismError("start_tls is not supported")

    async def create_datagram_endpoint(self, protocol_factory,
                                       local_addr=None, remote_addr=None, *,
                                       family=0, proto=0, flags=0,
                                       reuse_address=None, reuse_port=None,
                                       allow_broadcast=None, sock=None):
        raise SolipsismError("create_datagram_endpoint is not supported")

    async def create_server(
            self, protocol_factory, host=None, port=None,
            *,
            sock=None,
            ssl=None,
            reuse_address=None,
            reuse_port=None,
            **kwargs):
        if ssl is not None:
            raise SolipsismError("create_server with ssl is not supported")
        if sock is None:
            if host is None and port is None:
                raise ValueError('Neither host/port nor sock were specified')
            # TODO: what if host is actually a list?
            addr = (host, port, 0, 0)
            sock = _socket.ListenSocket(addr)
        addr = sock.getsockname()
        if addr[1] == 0:  # Port 0: pick a free port
            addr_list = list(addr)
            addr_list[1] = 60000
            while tuple(addr_list) in self.__listening_sockets:
                addr_list[1] += 1
            addr = tuple(addr_list)
            sock._sockname = addr
        if addr in self.__listening_sockets:
            raise SolipsismError("Reuse of listening addresses is not supported")
        self.__listening_sockets[addr] = sock
        return await super().create_server(
            protocol_factory, None, None,
            sock=sock,
            ssl=ssl,
            reuse_address=False,
            reuse_port=False,
            **kwargs
        )

    async def connect_read_pipe(self, protocol_factory, pipe):
        raise SolipsismError("connect_read_pipe is not supported")

    async def connect_write_pipe(self, protocol_factory, pipe):
        raise SolipsismError("connect_write_pipe is not supported")

    async def subprocess_shell(self, protocol_factory, cmd, *,
                               stdin=subprocess.PIPE,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE,
                               universal_newlines=False,
                               shell=True, bufsize=0,
                               encoding=None, errors=None, text=None,
                               **kwargs):
        raise SolipsismError("subprocess_shell is not supported")

    async def subprocess_exec(self, protocol_factory, program, *args,
                              stdin=subprocess.PIPE, stdout=subprocess.PIPE,
                              stderr=subprocess.PIPE, universal_newlines=False,
                              shell=False, bufsize=0,
                              encoding=None, errors=None, text=None,
                              **kwargs):
        raise SolipsismError("subprocess_exec is not supported")

    async def sock_connect(self, sock, address):
        raise SolipsismError("sock_connect is not supported")

    async def sock_accept(self, sock):
        raise SolipsismError("sock_accept is not supported")

    def add_signal_handler(self, sig, callback, *args):
        raise SolipsismError("add_signal_handler is not supported")

    def remove_signal_handler(self, sig):
        raise SolipsismError("remove_signal_handler is not supported")

    async def create_unix_connection(
            self, protocol_factory, path=None, *,
            ssl=None, sock=None,
            server_hostname=None,
            ssl_handshake_timeout=None):
        raise SolipsismError("create_unix_connection is not supported")

    async def create_unix_server(
            self, protocol_factory, path=None, *,
            sock=None, backlog=100, ssl=None,
            ssl_handshake_timeout=None,
            start_serving=True):
        raise SolipsismError("create_unix_server is not supported")

    # Methods in base class that we need to implement/override

    def _make_self_pipe(self):
        pass

    def _close_self_pipe(self):
        pass

    def _stop_serving(self, sock):
        addr = sock.getsockname()
        self.__listening_sockets.pop(addr)
        super()._stop_serving(sock)

async def stream_pairs(capacity=None):
    sock1, sock2 = _socket.socketpair(capacity=capacity)
    streams1 = await asyncio.open_connection(sock=sock1)
    streams2 = await asyncio.open_connection(sock=sock2)
    return streams1, streams2


#!/usr/bin/env python
# Given a string, sort it based on the decreasing frequency of its characters.

from collections import defaultdict
from heapq import *

def sort( arr ):
   count = defaultdict( int )
   for a in arr:
      count[ a ] += 1

   maxHeap = []
   for char, freq in count.items():
      heappush( maxHeap, ( -freq, char ) )

   result = ''
   while maxHeap:
      freq, char = heappop( maxHeap )
      for i in range( -freq ):
         result += char

   return result

testCases = [
      {
         'input' : "Programming",
         'output' : "rrggmmPiano",
      },
      {
         'input' : "abcbab",
         'output' : "bbbaac",
      },
]

for test in testCases:
   i = test[ 'input' ]
   o = test[ 'output' ]
   print( sort( i ) )


from flask import Flask, request, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('base.html')

@app.route('/upload', methods=['POST'])
def upload():
    file = request.files['file']
    file.save('uploads/' + file.filename)  # Сохраняем файл в папке uploads
    return render_template('index.html')

if __name__ == '__main__':
    app.run(port=8000, host="127.0.0.1", debug=True)


#!/usr/bin/env python
import os
import sys
import numpy as np
import pandas as pd
from pathlib import Path
import matplotlib.pyplot as plt
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
import tensorflow as tf
from keras.layers import Dense, Dropout, BatchNormalization, LeakyReLU, Conv1D, MaxPooling1D, Flatten, Input
from keras.optimizers import Adam
from keras.losses import Huber
from keras.callbacks import EarlyStopping
from keras.regularizers import l2
from keras.models import Sequential, Model
import joblib

params = {
    'results_path': 'results',
    'data_path': 'data',
    'nfp': 2,
    'n_data_subset': 10000,
    'model': 'nn', # 'cnn' or 'nn'
    'optimizer': Adam,
    'learning_rate': 0.005,
    'epochs': 100,
    'batch_size': 64,
    'early_stopping_patience': 20,
    'test_size': 0.2,
    'random_state': 42,
    'reg_strength': 1e-7,
    'dropout_rate': 1e-3,
    'validation_split': 0.2,
    'decay_steps': 1000,
    'decay_rate': 0.9,
}

def build_neural_network(input_shape, output_shape, reg_strength=1e-7, dropout_rate=3e-3):
    model = Sequential([
        Dense(256, activation='relu', input_shape=(input_shape,), kernel_regularizer=l2(reg_strength)),
        Dropout(dropout_rate),
        Dense(128, activation='relu', kernel_regularizer=l2(reg_strength)),
        Dropout(dropout_rate),
        Dense(64, activation='relu', kernel_regularizer=l2(reg_strength)),
        Dropout(dropout_rate),
        Dense(32, activation='relu', kernel_regularizer=l2(reg_strength)),
        Dropout(dropout_rate),
        Dense(output_shape)
    ])
    return model

def build_cnn(input_shape, output_shape, reg_strength=1e-7, dropout_rate=3e-3):
    input_layer = Input(shape=input_shape)

    x = Conv1D(64, kernel_size=3, activation='relu', padding='same', kernel_regularizer=l2(reg_strength))(input_layer)
    x = BatchNormalization()(x)
    x = Dropout(dropout_rate)(x)

    x = Conv1D(128, kernel_size=3, activation='relu', padding='same', kernel_regularizer=l2(reg_strength))(x)
    x = BatchNormalization()(x)
    x = Dropout(dropout_rate)(x)

    x = Flatten()(x)

    x = Dense(128, activation='relu', kernel_regularizer=l2(reg_strength))(x)
    x = Dropout(dropout_rate)(x)

    output_layer = Dense(output_shape, activation='linear')(x)

    return Model(input_layer, output_layer)

def preprocess_data(X_train, X_test, Y_train, Y_test, params):
    scaler_x = StandardScaler().fit(X_train)
    X_train = scaler_x.transform(X_train)
    X_test = scaler_x.transform(X_test)
    scaler_y = StandardScaler().fit(Y_train)
    Y_train = scaler_y.transform(Y_train)
    Y_test = scaler_y.transform(Y_test)

    if params['model'] == 'cnn':
        X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1)
        X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1)
        input_shape = (X_train.shape[1], 1)
    else:
        input_shape = X_train.shape[1]

    output_shape = Y_train.shape[1]

    return X_train, X_test, input_shape, output_shape, scaler_x, Y_train, Y_test, scaler_y

def create_dataset(X_train, Y_train, params):
    train_dataset = tf.data.Dataset.from_tensor_slices((X_train, Y_train))
    train_dataset = train_dataset.shuffle(buffer_size=1024).batch(params['batch_size']).prefetch(tf.data.experimental.AUTOTUNE)

    return train_dataset

# Set the number of field periods and model type
print('Usage: python use_nn_qsc.py [nfp] [model], where nfp=2, 3 or 4 and model=nn or cnn. Defaults to nfp=2 and model=nn.')
if len(sys.argv) > 1:
    if sys.argv[1] in ['2','3','4']:
        params['nfp'] = int(sys.argv[1])
    else:
        raise ValueError('NFP must be either 2, 3 or 4')
    if len(sys.argv) > 2:
        if sys.argv[2] in ['nn', 'cnn']:
            params['model'] = sys.argv[2]
        else:
            raise ValueError('Model must be either "nn" or "cnn"')

this_path = str(Path(__file__).parent.resolve())
general_results_path = os.path.join(this_path, params['results_path'])
results_path = os.path.join(general_results_path, f'nfp{params["nfp"]}')
os.makedirs(results_path, exist_ok=True)

filename = os.path.join(this_path, params['data_path'], f'qsc_out.random_scan_nfp{params["nfp"]}.csv')
df = pd.read_csv(filename)

# Only use a subset of parameters
for column in df.columns:
    if df[column].dtype.byteorder == '>':
        df[column] = df[column].values.byteswap().newbyteorder()
df['ysum'] = df.loc[:, df.columns.str.startswith('y')].sum(axis=1)
df = df.sort_values(by='ysum', ascending=True).head(params['n_data_subset'])
df = df.drop(columns='ysum')

x_columns = [col for col in df.columns if col.startswith('x')]
y_columns = [col for col in df.columns if col.startswith('y')]

## ACTUALLY SOLVING THE INVERSE PROBLEM
Y = df[x_columns].values
X = df[y_columns].values

X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=params['test_size'], random_state=params['random_state'])

X_train, X_test, input_shape, output_shape, scaler_x, Y_train, Y_test, scaler_y = preprocess_data(X_train, X_test, Y_train, Y_test, params)

if params['model'] == 'cnn':
    model = build_cnn(input_shape, output_shape, reg_strength=params['reg_strength'], dropout_rate=params['dropout_rate'])
else:
    model = build_neural_network(input_shape, output_shape, reg_strength=params['reg_strength'], dropout_rate=params['dropout_rate'])

learning_rate = tf.keras.optimizers.schedules.ExponentialDecay(
    initial_learning_rate=params['learning_rate'], decay_steps=params['decay_steps'], decay_rate=params['decay_rate']
)

model.compile(optimizer=params['optimizer'](learning_rate=learning_rate), loss=Huber(), metrics=['mae'])

early_stopping = EarlyStopping(monitor='val_loss', patience=params['early_stopping_patience'], restore_best_weights=True)

train_dataset = create_dataset(X_train, Y_train, params)
validation_dataset = create_dataset(X_test, Y_test, params)

model.fit(train_dataset, epochs=params['epochs'], validation_data=validation_dataset, validation_split=params['validation_split'], verbose=1, callbacks=[early_stopping])

loss, mae = model.evaluate(X_test, Y_test, verbose=0)
print(f"Test MAE: {mae}")
print(f"Test Loss: {loss}")

predictions = model(X_test)

# Save the model and scaler
model.save(os.path.join(results_path, f"nn_qsc_nfp{params['nfp']}_model{params['model']}.h5"))
joblib.dump(scaler_x, os.path.join(results_path, f"nn_qsc_nfp{params['nfp']}_scaler_x.pkl"))
joblib.dump(scaler_y, os.path.join(results_path, f"nn_qsc_nfp{params['nfp']}_scaler_y.pkl"))
print(f"Model and scaler saved in {results_path}")

plt.figure(figsize=(8, 8))
plt.scatter(Y_test, predictions, label='Predicted values', alpha=0.5)
min_x = np.min([np.min(Y_test), np.min(predictions)])
max_x = np.max([np.max(Y_test), np.max(predictions)])
plt.plot([min_x, max_x], [min_x, max_x], 'r', label='Perfect predictions')
plt.xlabel('True values')
plt.ylabel('Predicted values')
plt.title(f'nfp={params["nfp"]}, model={params["model"]}, metric={mae:.3f}, loss={loss:.3f}, epochs={params["epochs"]}, batch_size={params["batch_size"]}')
plt.legend()
plt.grid(True)
plt.savefig(os.path.join(results_path, f"nn_qsc_nfp{params['nfp']}_model{params['model']}.png"))
plt.show()


"""Video Generation with TGAN."""
import torch
import torch.nn as nn
import numpy as np
from moviepy.editor import ImageSequenceClip

class TemporalGenerator(nn.Module):
    def __init__(self):
        super().__init__()
        # Create a sequential model to turn one vector into 16
        self.model = nn.Sequential(
            nn.ConvTranspose1d(100, 512, kernel_size=1, stride=1, padding=0),
            nn.BatchNorm1d(512),
            nn.ReLU(),
            nn.ConvTranspose1d(512, 256, kernel_size=4, stride=2, padding=1),
            nn.BatchNorm1d(256),
            nn.ReLU(),
            nn.ConvTranspose1d(256, 128, kernel_size=4, stride=2, padding=1),
            nn.BatchNorm1d(128),
            nn.ReLU(),
            nn.ConvTranspose1d(128, 128, kernel_size=4, stride=2, padding=1),
            nn.BatchNorm1d(128),
            nn.ReLU(),
            nn.ConvTranspose1d(128, 100, kernel_size=4, stride=2, padding=1),
            nn.Tanh()
        )

        # initialize weights according to paper
        self.model.apply(self.init_weights)

    def init_weights(self, m):
        if type(m) == nn.ConvTranspose1d:
            nn.init.xavier_uniform_(m.weight, gain=2 ** 0.5)

    def forward(self, x):
        # reshape x so that it can have convolutions done
        x = x.view(-1, 100, 1)
        # apply the model and flip the
        x = self.model(x).transpose(1, 2)
        return x

class VideoGenerator(nn.Module):
    def __init__(self):
        super().__init__()
        # instantiate the temporal generator
        self.temp = TemporalGenerator()

        # create a transformation for the temporal vectors
        self.fast = nn.Sequential(
            nn.Linear(100, 256 * 4 ** 2, bias=False),
            nn.BatchNorm1d(256 * 4 ** 2),
            nn.ReLU()
        )

        # create a transformation for the content vector
        self.slow = nn.Sequential(
            nn.Linear(100, 256 * 4 ** 2, bias=False),
            nn.BatchNorm1d(256 * 4 ** 2),
            nn.ReLU()
        )

        # define the image generator
        self.model = nn.Sequential(
            nn.ConvTranspose2d(512, 256, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(256),
            nn.ReLU(),
            nn.ConvTranspose2d(256, 128, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(128),
            nn.ReLU(),
            nn.ConvTranspose2d(128, 64, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.ConvTranspose2d(64, 32, kernel_size=4, stride=2, padding=1, bias=False),
            nn.BatchNorm2d(32),
            nn.ReLU(),
            nn.ConvTranspose2d(32, 3, kernel_size=3, stride=1, padding=1),
            nn.Tanh()
        )

        # initialize weights according to the paper
        self.fast.apply(self.init_weights)
        self.slow.apply(self.init_weights)
        self.model.apply(self.init_weights)

    def init_weights(self, m):
        if type(m) == nn.ConvTranspose2d or type(m) == nn.Linear:
            nn.init.uniform_(m.weight, a=-0.01, b=0.01)

    def forward(self, x):
        # pass our latent vector through the temporal generator and reshape
        z_fast = self.temp(x).contiguous()
        z_fast = z_fast.view(-1, 100)

        # transform the content and temporal vectors
        z_fast = self.fast(z_fast).view(-1, 256, 4, 4)
        z_slow = self.slow(x).view(-1, 256, 4, 4).unsqueeze(1)
        # after z_slow is transformed and expanded we can duplicate it
        z_slow = torch.cat([z_slow] * 16, dim=1).view(-1, 256, 4, 4)

        # concatenate the temporal and content vectors
        z = torch.cat([z_slow, z_fast], dim=1)

        # transform into image frames
        out = self.model(z)

        return out.view(-1, 16, 3, 64, 64).transpose(1, 2)

class VideoDiscriminator(nn.Module):
    def __init__(self):
        super().__init__()
        self.model3d = nn.Sequential(
            nn.Conv3d(3, 64, kernel_size=4, padding=1, stride=2),
            nn.LeakyReLU(0.2),
            nn.Conv3d(64, 128, kernel_size=4, padding=1, stride=2),
            nn.BatchNorm3d(128),
            nn.LeakyReLU(0.2),
            nn.Conv3d(128, 256, kernel_size=4, padding=1, stride=2),
            nn.BatchNorm3d(256),
            nn.LeakyReLU(0.2),
            nn.Conv3d(256, 512, kernel_size=4, padding=1, stride=2),
            nn.BatchNorm3d(512),
            nn.LeakyReLU(0.2)
        )

        self.conv2d = nn.Conv2d(512, 1, kernel_size=4, stride=1, padding=0)

        # initialize weights according to paper
        self.model3d.apply(self.init_weights)
        self.init_weights(self.conv2d)

    def init_weights(self, m):
        if type(m) == nn.Conv3d or type(m) == nn.Conv2d:
            nn.init.xavier_normal_(m.weight, gain=2 ** 0.5)

    def forward(self, x):
        h = self.model3d(x)
        # turn a tensor of R^NxTxCxHxW into R^NxCxHxW
        h = torch.reshape(h, (32, 512, 4, 4))
        h = self.conv2d(h)
        return h

# update discriminator
pr = dis(real)
fake = gen(torch.rand((batch_size, 100), device='cuda') * 2 - 1)
pf = dis(fake)
dis_loss = torch.mean(-pr) + torch.mean(pf)
dis_loss.backward()
disOpt.step()

# update generator
genOpt.zero_grad()
fake = gen(torch.rand((batch_size, 100), device='cuda') * 2 - 1)
pf = dis(fake)
gen_loss = torch.mean(-pf)
gen_loss.backward()
genOpt.step()

# instantiate the generator, load the weights, and create a sample
gen = VideoGenerator().cuda()
gen.load_state_dict(torch.load('state_normal81000.ckpt')['model_state_dict'][0])
genSamples(gen)


import nltk
from nltk.translate import AlignedSent
from nltk.translate.ibm1 import IBMModel1

# 示例双语语料库
bitext = []
bitext.append(AlignedSent(['I', 'love', 'machine', 'learning'], ['我', '喜欢', '机器学习']))
bitext.append(AlignedSent(['Statistical', 'models', 'are', 'useful'], ['统计', '模型', '很', '有用']))

# 训练IBM Model 1模型
ibm1 = IBMModel1(bitext, 5)

# 测试翻译
source_sentence = ['I', 'love', 'machine', 'learning']
target_sentence = ibm1.align(source_sentence)
print('Source Sentence:', ' '.join(source_sentence))
print('Translated Sentence:', ' '.join(target_sentence))

Statistical Machine Translation SMT/example.py


import logging

from asgiref.sync import sync_to_async

logger = logging.getLogger(__name__)

from kocherga.graphql import g, helpers
from kocherga.graphql.permissions import check_permissions

from .. import permissions, channels

c = helpers.Collection()

WatchmenScheduleUpdateNotification = g.ObjectType(
    'WatchmenScheduleUpdateNotification', g.fields({'updated': bool})
)

@c.field
def watchmenScheduleUpdates(_):
    async def subscribe(obj, info):
        # check permissions
        await sync_to_async(permissions.manage_watchmen, thread_sensitive=True)(
            obj, info
        )

        async for msg in channels.watchmen_updates_group.subscribe():
            logger.info('yielding True')
            yield True

    @check_permissions([permissions.manage_watchmen])
    def resolve(msg, info):
        logger.info('returning updated')
        return {'updated': True}

    return g.Field(
        g.NN(WatchmenScheduleUpdateNotification), resolve=resolve, subscribe=subscribe
    )

subscriptions = c.as_dict()


from aiogram import types
from aiogram.dispatcher import FSMContext
from aiogram.dispatcher.filters.builtin import Command
from aiogram.types import ReplyKeyboardRemove
from aiogram.utils.markdown import hcode, hlink

from filters.is_private import IsPrivate
from handlers.users.profile_creating.profile import show_profile
from keyboards.default.likes import like_or_not, LIKE, DISLIKE, SLEEP
from loader import dp
from states.search_states import SearchState
from utils.db_api import quick_commands as db
from utils.db_api.quick_commands import delete_love
from utils.db_api.schemas.love import Love

@dp.message_handler(IsPrivate(), Command("see_love"))
async def im_liked(message: types.Message, state: FSMContext):
    user_id = message.from_user.id
    try:
        love = await Love.query.where(Love.liked == user_id).gino.first()
    except Exception:
        return await message.answer("Пока что ты никому не понравился(\n"
                                    "Смотреть анкеты: /search")

    if love:
        await show_profile(profile_owner_id=love.likes, receiver_id=love.liked, reply_markup=like_or_not)
        await state.update_data(user_id=love.likes)
        await SearchState.Answer.set()
    else:
        return await message.answer("Пока что ты никому не понравился(\n"
                                    "Смотреть анкеты: /search")

@dp.message_handler(IsPrivate(), state=SearchState.Answer, text=LIKE)
async def match_like(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        user_id = data.get("user_id")

    user = await db.select_user(user_id)
    await message.answer("Общаться:\n" +
                         hlink(f"{user.name}", f"tg://user?id={user_id}"))

    await my_mismatch(message, state)

@dp.message_handler(IsPrivate(), state=SearchState.Answer, text=DISLIKE)
async def my_mismatch(message: types.Message, state: FSMContext):
    async with state.proxy() as data:
        user_id = data.get("user_id")

    await delete_love(message.from_user.id, user_id)
    await im_liked(message, state)

@dp.message_handler(IsPrivate(), state=SearchState.Answer, text=SLEEP)
async def my_missleep(message: types.Message, state: FSMContext):

    await message.answer("Я устал", reply_markup=ReplyKeyboardRemove())
    await state.finish()


import matplotlib.pyplot as plt
import xarray as xr
import tempfile
import dask
from dask.diagnostics import ProgressBar
import os
import numpy as np
import pandas as pd
import matplotlib.gridspec as gridspec
from cartopy import crs as ccrs
import lib_added_value as lav
import argparse
import gc

def addedValueStatMSE(X_dict):

    ress = ['LR', 'HRd']
    av = av_norm = 0
    for res in ress:
        av       += lav.AVmse(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
        av_norm  += lav.AVmse_norm(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
    avs = (av/av_norm)
    return avs

def addedValueStatCorr(X_dict):

    ress = ['LR', 'HRd']
    av = av_norm = 0
    for res in ress:
        av       += lav.AVcorr(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
        av_norm  += lav.AVcorr_norm(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
    avs = (av/av_norm)
    return avs

def addedValueStatBias(X_dict):

    ress = ['LR', 'HRd']
    av = av_norm = 0
    for res in ress:
        av       += lav.AVbias(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
        av_norm  += lav.AVbias_norm(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
    avs = (av/av_norm)
    return avs

def addedValueStatStd(X_dict):

    ress = ['LR', 'HRd']
    av = av_norm = 0
    for res in ress:
        av       += lav.AVstd(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
        av_norm  += lav.AVstd_norm(X_dict['obs{}'.format(res)], X_dict['gdd{}'.format(res)], X_dict['rcm{}'.format(res)])
    avs = (av/av_norm)
    return avs

def corrCommonBias(X_dict):

    ress = ['LR'] #, 'HRd']
    Xgdd = Xrcm = Xobs = 0
    for res in ress:
        Xgdd += X_dict['gdd{}'.format(res)]
        Xrcm += X_dict['rcm{}'.format(res)]
        Xobs += X_dict['obs{}'.format(res)]

    r = lav.correlation(Xgdd-Xobs, Xrcm-Xobs, dim=['lat','lon'])

    return r

def boxPlotHelper(arrList, nameList, title='', ylabel='', ofile=None):

    fig = plt.figure(figsize=(5, 3.7))
    leg = []
    xx = 0
    yy = []

    lss = []
    for i, dummy in enumerate(arrList):
        x, y  = zip(*sorted(dummy.items()))
        ls = []
        if len(y) > 1: # Only plot if there is more than one entry for this (e.g. don't plot gdds if there is only one gdd)
            for p in range(len(y)):
                if np.isnan(y[p]): #< Skip if correlation is nan
                    continue
                l, = plt.plot(xx+(0.1*(p+1)/len(y)), y[p], marker='o', label=x[p])
                ls.append(l)
            lss.append(ls)
            xx += 1
            yy.append(nameList[i])

    plt.xticks(range(xx), yy, rotation=20, weight='bold')  # Set text labels and properties.
    plt.ylim([-0.5, 1])
    plt.yticks([-0.5, 0, 0.5, 1], weight='bold')
    plt.gca().axhline(c='grey', lw=2, linestyle='--')

    #< legend
    xx = 0
    locs, labels = plt.yticks()            # Get locations and labels
    dloc = locs[1]-locs[0]
    for i, dummy in enumerate(arrList):
        x, y  = zip(*sorted(dummy.items()))
        if len(y) > 1:
            leg.append(plt.gca().legend(lss[xx], x, loc='upper center', bbox_to_anchor=(xx-0.25,locs[0]-0.75*dloc, 0.5, 0.1), bbox_transform=plt.gca().transData))
            xx += 1
    ax = plt.gca()
    [ax.add_artist(l) for l in leg]
    ax.set_title(title, size='large', weight='bold')
    ax.set_ylabel(ylabel, weight='bold')

    plt.savefig(ofile, bbox_inches='tight')

# Parse input arguments
def parse_args(parser):
    parser.add_argument("--ipath", dest='ipath', type=str, help="Path to input data.")
    parser.add_argument("-o", "--outpath", default='', type=str, help="Comma-separated list of input files. (The first file will be the reference)")
    parser.add_argument("--op", default='mse', type=str, help="What statistic should be used to summarise the added value (mse, corr, bias, var, commbias)")
    parser.add_argument("--gdds", nargs='?', help="Comma-separated list of input driving models (e.g. ACCESS1-0)")
    parser.add_argument("--varnames", nargs='?', help="Comma-separated list of input variable names (in the order of gdd, rcm, obs)")
    parser.add_argument("--yrStart", type=int, help="Year to start processing.")
    parser.add_argument("--yrEnd", type=int, help="Year to end processing.")
    parser.add_argument("--quantiles", dest='quantiles', type=str, nargs='?', help="Quantiles to calculate added value for.")
    parser.add_argument("--seasons", nargs='?', default='annual', help="Comma-separated list of seasons (annual, DJF, etc.)")
    parser.add_argument("--interp_method", dest='interp_method', type=str, default="nearest", help="Interpolation method used to interpolate to high-res")
    parser.add_argument("--resolution", dest='resolution', type=str, default='', help="Resolution (i.e. 0p05deg or 0p11deg)")
    parser.add_argument("--prefix", dest='prefix', type=str, default='', help="Prefix for output files")
    parser.add_argument("--project", dest='project', type=str, default='', help="Project (e.g. barpa, narclim) used for filename")
    parser.add_argument("--regions", dest='regions', type=str, default='', help="Regions input file.")
    parser.add_argument("--debug", dest='debug', type=lav.str2bool, const=True, nargs='?', default=False, help="Debugging plots")
    return parser.parse_args()

def main():

        #< Increase garbage threshold
        g0, g1, g2 = gc.get_threshold()
        gc.set_threshold(g0 * 3, g1 * 3, g2 * 3)

        # User argument input
        parser    = argparse.ArgumentParser(description='Plot some overview plots of the added value analysis.')
        args      = parse_args(parser)
        ipath     = args.ipath
        gdds      = list(filter(None, args.gdds.split(",")))
        varnames  = list(filter(None, args.varnames.split(",")))
        outpath   = args.outpath
        op        = args.op
        yrStart   = args.yrStart
        yrEnd     = args.yrEnd
        quantiles = [i for i in list(filter(None, args.quantiles.split(",")))]
        seasons   = list(filter(None,args.seasons.split(",")))
        interp_method = args.interp_method
        res         = args.resolution
        prefix    = args.prefix
        project   = args.project
        ifile_regions = args.regions
        l_debug_first = args.debug

        ifiles_dummy = ipath + '/' + 'X.{}_{}.{}.0p11deg.q{}.{}.{}-{}.interp_{}.nc'
        oplot  = outpath + '/' + prefix + '.boxplot.added_value.{}.{}.q{}.EASTAUS.{}.{}.png'

        #< Read the regions files
        print('Read in the added value regions definition...')
        print(ifile_regions)
        regions = xr.load_dataset(ifile_regions)['regions']
        regions['lat'] = regions['lat'].astype('float32')
        regions['lon'] = regions['lon'].astype('float32')

        qDummy  = {}
        for gdd in gdds:
            varDummy  = {}
            for q in quantiles:
                if lav.isfloat(q):
                    q = float(q)

                if isinstance(q, float):
                    print(f'{q*100} quantile...')
                    qstr = '{}'.format(q).replace('.','p')
                elif isinstance(q, str):
                    print(f'{q}...')
                    qstr = q
                else:
                    print(f'Type {type(q)} of q not supported')

                seasonDummy  = {}
                for var in varnames:

                    #< read data
                    ifiles      = ifiles_dummy.format(project, gdd, var, qstr, '{}', yrStart, yrEnd, interp_method)
                    print(ifiles)
                    X           = {}
                    regionDummy = {}
                    for season in seasons:
                        avs     = {}
                        for region in ['coast', 'topo', 'flat']:
                            if region == 'coast':
                                iregion = 1
                            elif region == 'topo':
                                iregion = 2
                            elif region == 'flat':
                                iregion = 3

                            for model in ['obs', 'gdd', 'rcm']:
                                for res in ['LR', 'HRd']:
                                    ifile = ifiles.format(season)
                                    X[model, res] = xr.open_dataset(ifile)['{}{}'.format(model,res)]

                            # #< Just for testing the script!!!!
                            # ##################################
                            # # RCM = GDD -> AV = 0
                            # # X['rcm', 'LR']  = X['gdd', 'LR']
                            # # X['rcm', 'HRd'] = X['gdd', 'HRd']
                            # # RCM = OBS -> AV = 1
                            # # X['rcm', 'LR']  = X['obs', 'LR']
                            # # X['rcm', 'HRd'] = X['obs', 'HRd']
                            # # RCM = (GCM + OBS) / 2 -> AV = 0.6
                            # X['rcm', 'LR']  = (X['obs', 'LR'] + X['gdd', 'LR']) / 2.
                            # X['rcm', 'HRd'] = (X['obs', 'HRd'] + X['gdd', 'HRd']) / 2.
                            # ##################################

                            #< Cut overlap
                            regions, X['obs', 'LR'], X['obs', 'HRd'], X['gdd', 'LR'], X['gdd', 'HRd'], X['rcm', 'LR'], X['rcm', 'HRd'] = lav.cut_overlap(regions, X['obs', 'LR'], X['obs', 'HRd'], X['gdd', 'LR'], X['gdd', 'HRd'], X['rcm', 'LR'], X['rcm', 'HRd'], dims=['lat', 'lon'])

                            #< Group by region
                            lav.check_coordinates_match(regions, X['obs', 'LR'], X['obs', 'HRd'], X['gdd', 'LR'], X['gdd', 'HRd'], X['rcm', 'LR'], X['rcm', 'HRd'], dims=['lat','lon'])
                            X_dict = {'obsLR': X['obs', 'LR'].where(regions==iregion),   'gddLR': X['gdd', 'LR'].where(regions==iregion),   'rcmLR': X['rcm', 'LR'].where(regions==iregion),
                                      'obsHRd': X['obs', 'HRd'].where(regions==iregion), 'gddHRd': X['gdd', 'HRd'].where(regions==iregion), 'rcmHRd': X['rcm', 'HRd'].where(regions==iregion)}

                            if l_debug_first:
                                plt.figure()
                                X_dict['obsLR'].plot.pcolormesh()
                                plt.figure()
                                X_dict['obsHRd'].plot.pcolormesh()
                                plt.figure()
                                X_dict['gddLR'].plot.pcolormesh()
                                plt.figure()
                                X_dict['gddHRd'].plot.pcolormesh()
                                plt.figure()
                                X_dict['rcmLR'].plot.pcolormesh()
                                plt.figure()
                                X_dict['rcmHRd'].plot.pcolormesh()
                                plt.show()

                            #< Select the operation in which added value is measured
                            if op == 'mse':
                                avs[region] = addedValueStatMSE(X_dict)
                            elif op == 'corr':
                                avs[region] = addedValueStatCorr(X_dict)
                            elif op == 'bias':
                                avs[region] = addedValueStatBias(X_dict)
                            elif op == 'var':
                                avs[region] = addedValueStatStd(X_dict)
                            elif op == 'commbias':
                                avs[region] = corrCommonBias(X_dict)

                            print(q, var, season, region)
                            print(avs[region].values)
                        l_debug_first = False

            #< Combine the added values in dictionaries and convert to xarray in the end
                        regionDummy[season] = xr.concat([avs[key] for key in avs], dim=pd.Index(avs.keys(), name='region'), coords='minimal')
                    seasonDummy[var] = xr.concat([regionDummy[key] for key in regionDummy], dim=pd.Index(regionDummy.keys(), name='season'), coords='minimal')
                varDummy[q] = xr.concat([seasonDummy[key] for key in seasonDummy], dim=pd.Index(seasonDummy.keys(), name='var'), coords='minimal')
            qDummy[gdd] = xr.concat([varDummy[key] for key in varDummy], dim=pd.Index([str(k) for k in varDummy.keys()], name='q'), coords='minimal')
        avs = xr.concat([qDummy[key] for key in qDummy], dim=pd.Index(qDummy.keys(), name='gdd'), coords='minimal')

        #< Calculate mean over every other dimension
        avsregion = avs.mean(['var', 'q', 'season', 'gdd']).to_dict()
        avsseason = avs.mean(['var', 'q', 'region', 'gdd']).to_dict()
        avsvar    = avs.mean(['region', 'q', 'season', 'gdd']).to_dict()
        avsq      = avs.mean(['var', 'region', 'season', 'gdd']).to_dict()
        avsgdd    = avs.mean(['var', 'region', 'season', 'q']).to_dict()

        #< Combine in dict
        regionDummy = dict(zip(avsregion['coords']['region']['data'], avsregion['data']))
        seasonDummy = dict(zip(avsseason['coords']['season']['data'], avsseason['data']))
        varDummy    = dict(zip(avsvar['coords']['var']['data'], avsvar['data']))
        qDummy      = dict(zip(avsq['coords']['q']['data'], avsq['data']))
        gddDummy    = dict(zip(avsgdd['coords']['gdd']['data'], avsgdd['data']))

        #< Select the operation in which added value is measured
        if op == 'mse':
            title  = 'Added value (MSE) summary'
            ofile  = oplot.format('av.mse.summary', '{}', '{}', '{}', '{}').replace('.{}','').replace('.q{}','')
            ylabel = 'AV'
        elif op == 'corr':
            title  = 'Added value (Corr) summary'
            ofile  = oplot.format('av.corr.summary', '{}', '{}', '{}', '{}').replace('.{}','').replace('.q{}','')
            ylabel = 'AV'
        elif op == 'bias':
            title  = 'Added value (Bias) summary'
            ofile  = oplot.format('av.bias.summary', '{}', '{}', '{}', '{}').replace('.{}','').replace('.q{}','')
            ylabel = 'AV'
        elif op == 'var':
            title  = 'Added value (Standard deviation) summary'
            ofile  = oplot.format('av.variance.summary', '{}', '{}', '{}', '{}').replace('.{}','').replace('.q{}','')
            ylabel = 'AV'
        elif op == 'commbias':
            title  = 'Common large-scale Bias\nR(GDD-Obs,RCM-Obs) summary'
            ofile  = oplot.format('av.bias-corr.summary', '{}', '{}', '{}', '{}').replace('.{}','').replace('.q{}','')
            ylabel = 'Corr'

        boxPlotHelper(arrList=[regionDummy, seasonDummy, varDummy, gddDummy, qDummy],
                      nameList=['region', 'season', 'var', 'gdd', 'q'], title=title,
                      ylabel=ylabel, ofile=ofile)

################################################################################

if __name__ == '__main__':
    import dask.distributed
    import sys

    #< Print the script name
    print(sys.argv[0])

    # Get the number of CPUS in the job and start a dask.distributed cluster
    threads      = int(os.environ.get('THREADS_PER_WORKER','1'))
    n_workers    = 2 if os.environ["HOSTNAME"].startswith("gadi-login") else max(int(os.environ["PBS_NCPUS"]) // threads,1)
    memory_limit = '1000mb' if os.environ["HOSTNAME"].startswith("gadi-login") else int(os.environ["PBS_VMEM"]) / n_workers
    client       = dask.distributed.Client(n_workers=n_workers, threads_per_worker=threads, memory_limit=memory_limit, local_dir=tempfile.mkdtemp())

    #< Print client summary
    print('### Client summary')
    print(client)
    print('\n\n')

    #< Call the main function
    main()

    #< Close the client
    client.shutdown()


from django.contrib import admin
from .models import Goods
from django.contrib.auth.models import User, Group

admin.site.unregister(User)
admin.site.unregister(Group)

@admin.register(Goods)
class GoodsAdmin(admin.ModelAdmin):
    list_display = ('image_tag', 'slug', 'sale_price', 'created_date', 'sales')
    list_filter = ('author', 'created_date', 'sale_price', 'sales')
    fields = ['author', 'slug', 'title', 'description', ('pln_price', 'uah_price', 'sale_price'), ('sales', 'image')]
    search_fields = ('slug', 'title', 'author')
    readonly_fields = ["image_tag"]


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

lst = deque()
def push(n):
    lst.append(n)

def pop():
    if len(lst) == 0:
        print(-1)
    else:
        print(lst.popleft())

def size():
    print(len(lst))

def empty():
    if len(lst) == 0:
        print(1)
    else:
        print(0)

def front():
    if len(lst) == 0:
        print(-1)
    else:
        print(lst[0])

def back():
    if len(lst) == 0:
        print(-1)
    else:
        print(lst[-1])

i = int(input())
for _ in range(i):
    com = input().rsplit()
    if com[0] == 'pop':
        pop()
    elif com[0]  == 'front':
        front()
    elif com[0]  == 'back':
        back()
    elif com[0]  == 'size':
        size()
    elif com[0]  == 'empty':
        empty()
    else:
        push(com[1])


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

# prepapre data
data1=np.genfromtxt('recipe_loss_posterior8.csv',delimiter=',')
data1=np.hstack((data1[:,0].reshape(-1,1),data1[:,3].reshape(-1,1),data1[:,5].reshape(-1,1)))

df=pd.DataFrame(data1)
df=df.sort_values(by=[2])
df=df.drop_duplicates(subset=[0,1], keep='first')
data1=df.values

x=data1[:,0]
y=data1[:,1]
z=data1[:,2]

# plotting
import matplotlib.pyplot as plt
import matplotlib.tri as tri
import numpy as np

np.random.seed(19680801)
npts = 200
ngridx = 200
ngridy = 200
'''
x = np.random.uniform(-2, 2, npts)
y = np.random.uniform(-2, 2, npts)
z = x * np.exp(-x**2 - y**2)
'''

import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (5,4.1)

fig, (ax1) = plt.subplots(nrows=1)
# -----------------------
# Interpolation on a grid
# -----------------------
# A contour plot of irregularly spaced data coordinates
# via interpolation on a grid.

# Create grid values first.
xi = np.linspace(0, 45, ngridx)
yi = np.linspace(0.5, 20, ngridy)

# Perform linear interpolation of the data (x,y)
# on a grid defined by (xi,yi)
triang = tri.Triangulation(x, y)
interpolator = tri.LinearTriInterpolator(triang, z)
Xi, Yi = np.meshgrid(xi, yi)
zi = interpolator(Xi, Yi)

# Note that scipy.interpolate provides means to interpolate data on a grid
# as well. The following would be an alternative to the four lines above:
#from scipy.interpolate import griddata
#zi = griddata((x, y), z, (xi[None,:], yi[:,None]), method='linear')

ax1.contour(xi, yi, zi,levels=14,linestyles='dashed',linewidths=0.6,colors='white')
cntr1 = ax1.contourf(xi, yi, zi, levels=np.linspace(0,1,100), cmap="plasma")

#fig.colorbar(cntr1, ax=ax1)
#fig.colorbar(cntr1, boundaries=np.linspace(0, 1, 10),ticks=[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1],)
a=fig.colorbar(cntr1, boundaries=np.linspace(0, 1, 10),ticks=[0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1],)
a.ax.get_yaxis().labelpad = 10
a.ax.set_ylabel('Loss', rotation=90)

#ax1.plot(x, y, 'ko', ms=2,color='r')
ax1.set(xlim=(4, 45), ylim=(0.5, 20))

plt.setp(ax1.get_yticklabels(), visible=False)
#plt.setp(ax1.get_xticklabels(), visible=False)

plt.yticks([])

plt.xticks([10,20,30,40])

ax1.set(xlabel='QAgNO3(%)')

#ax1.set_title('Run 8')

plt.show()


import xml.etree.ElementTree as ET
import numpy as np
import os.path
import pickle

# XML wird geladen
positionsRAW = ET.parse(os.path.dirname(__file__) + '/../Data_STS/DFL_04_02_positions_raw_DFL-COM-000001_DFL-MAT-X03BWS.xml')
matchInformation = ET.parse(os.path.dirname(__file__) + '/../Data_STS/DFL_02_01_matchinformation_DFL-COM-000001_DFL-MAT-X03BWS.xml')
root = positionsRAW.getroot()
rootMatchInfo = matchInformation.getroot()

#<FrameSet GameSection="firstHalf" MatchId="DFL-MAT-X03BWS" TeamId="DFL-CLU-000N9A" PersonId="DFL-OBJ-002G6R">
#<Object ObjectId="DFL-OBJ-002G6N" Type="player" Name="Frenkie de Jong" FirstName="Frenkie" LastName="de Jong" BirthDate="12.05.1997" CountryOfBirthGerman="Niederlande" CountryOfBirthEnglish="Netherlands" CountryOfBirthSpanish="Holanda" NationalityGerman="Niederländisch" NationalityEnglish="Dutch" NationalitySpanish="neerlandés" Height="180" Weight="74" ShirtNumber="21" PlayingPositionGerman="Mittelfeld" PlayingPositionEnglish="midField" PlayingPositionSpanish="medio campo" ClubId="DFL-CLU-000N9A" ClubName="Niederlande Nationalmannschaft"/>
#<Objects FeedType="player">
#<Object ObjectId="DFL-OBJ-0000O3" Type="player" Name="Marco Reus" FirstName="Marco" LastName="Reus" BirthDate="31.05.1989" BirthPlace="Dortmund" CountryOfBirthGerman="Deutschland" CountryOfBirthEnglish="Germany" CountryOfBirthSpanish="Alemania" NationalityGerman="Deutsch" NationalityEnglish="German" NationalitySpanish="alemán" Height="180" Weight="71" ShirtNumber="11" PlayingPositionGerman="Mittelfeld" PlayingPositionEnglish="midField" PlayingPositionSpanish="medio campo" ClubId="DFL-CLU-000N99" ClubName="Deutschland Nationalmannschaft"/>

playerPositionsFH = {}
playerPositionsSH = {}

for frameset in root.iter('FrameSet'):
    positionsX, positionsY = [], []
    for frame in frameset:
        positionsX.append(frame.get('X'))
        positionsY.append(frame.get('Y'))

    # String in Float umwandeln
    positionsX, positionsY = np.array(positionsX).astype(np.float), np.array(positionsY).astype(np.float)

    if (frameset.get('GameSection') == 'firstHalf'):
        playerPositionsFH[frameset.get('PersonId')] = {}
        playerPositionsFH[frameset.get('PersonId')]['Shortname'] = 'Ball'
        playerPositionsFH[frameset.get('PersonId')]['TeamId'] = frameset.get('TeamId')
        playerPositionsFH[frameset.get('PersonId')]['meanX'] = np.mean(positionsX)
        playerPositionsFH[frameset.get('PersonId')]['meanY'] = np.mean(positionsY)
    elif (frameset.get('GameSection') == 'secondHalf'):
        playerPositionsSH[frameset.get('PersonId')] = {}
        playerPositionsSH[frameset.get('PersonId')]['Shortname'] = 'Ball'
        playerPositionsSH[frameset.get('PersonId')]['TeamId'] = frameset.get('TeamId')
        playerPositionsSH[frameset.get('PersonId')]['meanX'] = np.mean(positionsX)
        playerPositionsSH[frameset.get('PersonId')]['meanY'] = np.mean(positionsY)
    else:
        print('Error: ', frameset.get('GameSection'))

for player in rootMatchInfo.iter('Player'):
    try:
        playerPositionsFH[player.get('PersonId')]['Shortname'] = player.get('Shortname')
        playerPositionsSH[player.get('PersonId')]['Shortname'] = player.get('Shortname')
        playerPositionsFH[player.get('PersonId')]['ShirtNumber'] = player.get('ShirtNumber')
        playerPositionsSH[player.get('PersonId')]['ShirtNumber'] = player.get('ShirtNumber')
    except KeyError:
        print('KeyError: ' + player.get('Shortname') + ' hat nicht gespielt.')
    except:
        print('Error', player.get('PersonId'), player.get('Shortname'))

with open(os.path.dirname(__file__) + '/obj/playerPositionsFH.pkl', 'wb') as output:
    pickle.dump(playerPositionsFH, output, pickle.HIGHEST_PROTOCOL)
with open(os.path.dirname(__file__) + '/obj/playerPositionsSH.pkl', 'wb') as output:
    pickle.dump(playerPositionsSH, output, pickle.HIGHEST_PROTOCOL)


from tkinter import filedialog
from tkinter import *
import cv2
import os
root = Tk()

root.title('아스키코드로 변환')

root.geometry('1000x800')

def img_path():
    root.file = filedialog.askopenfile(title='파일을 선택하세요')
    txt.configure(text='경로: ' + root.file.name)

def img_ascll():
    chars = ' .,-~:;=!*#%@'
    nw = 100
    img = cv2.imread(root.file.name)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    h, w = img.shape
    nh = int(h / w * nw)
    img = cv2.resize(img, (nw * 2, nh))
    del_path = str(root.file.name).split('/')

    for i in del_path:
        del_path = i

    re_img = open('/Users/dotslashdash/Downloads/'+del_path[:-3]+'txt', 'w')
    for row in img:
        for pixel in row:
            index = int(pixel / 256 * len(chars))
            re_img.write(chars[index])
        re_img.write('\n')

# 아스키코드 변환 버튼
path_button = Button(root, text='아스키코드로 변환', width=15, command=img_ascll)
path_button.pack(side='bottom')

# 파일 버튼 생성
path_button = Button(root, text='파일 선택', width=15, command=img_path)
path_button.pack(side='bottom')

# 파일 경로
txt = Label(root, text="경로:")
txt.pack(side='bottom')

# GUI 실행
root.mainloop()


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

# Built-in imports
import itertools

# 3rd party imports
import numpy as np
import xarray as xr

__author__ = "Louis Richard"
__email__ = "louisr@irfu.se"
__copyright__ = "Copyright 2020-2023"
__license__ = "MIT"
__version__ = "2.4.2"
__status__ = "Prototype"

def _idx_closest(lst0, lst1):
    return [(np.abs(np.asarray(lst0) - k)).argmin() for k in lst1]

def eis_spec_combine_sc(omni_vars, method: str = "mean"):
    r"""Combines omni-directional energy spectrogram variable from EIS on
    multiple MMS spacecraft.

    Parameters
    ----------
    omni_vars : list of xarray.DataArray
        Omni-directional energy spectrograms of all spacecraft.
    method : str, Optional
        Method to combine spectra, "mean" or "sum"

    Returns
    -------
    omni_spec : xarray.DataArray
        Combined omni-directional energy spectrogram.

    See Also
    --------
    pyrfu.mms.get_eis_allt, pyrfu.mms.eis_omni, pyrfu.mms.eis_pad_combine_sc

    Examples
    --------
    >>> from pyrfu.mms import get_eis_allt, eis_omni, eis_spec_combine_sc

    Define time interval

    >>> tint = ["2017-07-23T16:10:00", "2017-07-23T18:10:00"]

    Load EIS ExTOF flux spectrograms for all 6 telescopes for all spacecraft

    >>> extof_allt_mms = []
    >>> for ic in range(2, 5):
    ...     extof_allt_mms.append(get_eis_allt("flux_extof_proton_srvy_l2",
    ...                             tint, ic))

    Compute the omni-direction flux spectrogram for all spacecraft

    >>> extof_omni_mms = []
    >>> for extof_allt in extof_allt_mms:
    ...     extof_omni_mms.append(eis_omni(extof_allt))

    Combine spectrograms of all spacecraft

    >>> extof_omni_mmsx = eis_spec_combine_sc(extof_omni_mms)

    """

    assert method.lower() in ["mean", "sum"]

    reftime_sc_loc = np.argmin([len(x_.time.data) for x_ in omni_vars])
    refener_sc_loc = np.argmin([len(x_.energy.data) for x_ in omni_vars])

    time_refprobe = omni_vars[reftime_sc_loc]
    ener_refprobe = omni_vars[refener_sc_loc]

    nt_ref, ne_ref = [time_refprobe.shape[0], ener_refprobe.shape[1]]

    # time x energy x spacecraft
    omni_spec_data = np.empty([nt_ref, ne_ref, len(omni_vars)])
    omni_spec_data[:] = np.nan
    # time x energy
    omni_spec = np.empty([nt_ref, ne_ref])
    omni_spec[:] = np.nan

    # energy_data = np.zeros([ne_ref, len(omni_vars)])

    # Average omni flux over all spacecraft and define common energy grid
    for i_p, flux_ in enumerate(omni_vars):
        idx_closest = _idx_closest(
            flux_.energy.data,
            ener_refprobe.energy.data,
        )
        # energy_data[:, pp] = flux_.energy.data[0:ne_ref]
        omni_spec_data[0:nt_ref, :, i_p] = flux_.data[0:nt_ref, idx_closest]

    # Average omni flux over all spacecraft
    for i_t, i_e in itertools.product(range(nt_ref), range(ne_ref)):
        if method.lower() == "mean":
            omni_spec[i_t, i_e] = np.nanmean(
                omni_spec_data[i_t, i_e, :],
                axis=0,
            )
        else:
            omni_spec[i_t, i_e] = np.nansum(
                omni_spec_data[i_t, i_e, :],
                axis=0,
            )

    omni_spec = xr.DataArray(
        omni_spec,
        coords=[time_refprobe.time.data, ener_refprobe.energy.data],
        dims=["time", "energy"],
    )
    omni_spec.attrs["energy_dplus"] = ener_refprobe.attrs["energy_dplus"]
    omni_spec.attrs["energy_dminus"] = ener_refprobe.attrs["energy_dminus"]

    return omni_spec


import uuid
import logging

from board import Board
from board_status import BoardStatus
from board_type import BoardType

logger = logging.getLogger()
logger.setLevel(logging.INFO)

from board_db import connection
db_conn = connection.Connection()

def get_boards_for_user(cognito_username):
	with db_conn.get_cursor() as cursor:
		cursor.execute('''
						SELECT b.board_id, b.owner_id, b.board_name, BIN_TO_UUID(b.join_code), b.board_status_id, b.board_type_id, b.start_date, b.end_date
						FROM board b
						JOIN person p ON b.owner_id = p.person_id
						WHERE p.cognito_username = UUID_TO_BIN(%s)''',
						(cognito_username,))
		results = cursor.fetchall()
		db_conn.conn.commit()
		return [_board_tuple_to_board(board) for board in results]

def get_board_by_join_code(join_code):
	with db_conn.get_cursor() as cursor:
		board = _get_board_by_join_code(cursor, join_code)
		db_conn.conn.commit()
		return board

def create_board(cognito_username, board_name, board_status, board_type):
	with db_conn.get_cursor() as cursor:
		owner_id = _get_person_id_for_username(cursor, cognito_username)
		new_uuid = uuid.uuid4()
		cursor.execute(	'''
						INSERT INTO board (owner_id, board_name, join_code, board_status_id, board_type_id)
						VALUES (%s, %s, UUID_TO_BIN(%s), %s, %s);
						''',
						(owner_id, board_name, new_uuid, board_status.value, board_type.value))
		db_conn.conn.commit()
		return _get_board_by_join_code(cursor, new_uuid)

def update_board(board):
	start_date = board.start_date.strftime('%Y-%m-%d %H:%M:%S') if board.start_date else None
	end_date = board.end_date.strftime('%Y-%m-%d %H:%M:%S') if board.end_date else None
	with db_conn.get_cursor() as cursor:
		cursor.execute( '''
						UPDATE board
						SET
							board_status_id = %s,
							start_date = %s,
							end_date = %s
						WHERE
							join_code=UUID_TO_BIN(%s)
						''',
						(board.board_status.value, start_date, end_date, board.join_code))
		updated_board = _get_board_by_join_code(cursor, board.join_code)
		db_conn.conn.commit()
		return updated_board

def create_photo_for_board(cognito_username,
						   photo_key,
						   s3_bucket_name,
						   s3_object_key,
						   join_code,
						   board_photo_status):
	with db_conn.get_cursor() as cursor:
		try:
			person_id = _get_person_id_for_username(cursor, cognito_username)
			board = _get_board_by_join_code(cursor, join_code)
			new_photo_id = _create_photo(cursor, person_id, photo_key, s3_bucket_name, s3_object_key)
			_create_mapping(cursor, board, new_photo_id, board_photo_status)
			db_conn.conn.commit()
			cursor.close()
		except:
			logging.exception(f'Could not insert photo {url} for user {cognito_username}')
			db_conn.conn.rollback()
			raise Exception('Could not insert photo.')

def set_board_photo_status(photo_key, join_code, board_photo_status):
	with db_conn.get_cursor() as cursor:
		cursor.execute(	'''
						UPDATE board_photo_map m
						JOIN photo p ON p.photo_id = m.photo_id
						JOIN board b ON b.board_id = m.board_id
						SET m.board_photo_map_status_id = %s
						WHERE p.photo_key = UUID_TO_BIN(%s)
							AND b.join_code = UUID_TO_BIN(%s)
						''',
						(board_photo_status.value, str(photo_key), str(join_code)))
		db_conn.conn.commit()

def get_photos_for_board(join_code):
	with db_conn.get_cursor() as cursor:
		cursor.execute(	'''
						SELECT BIN_TO_UUID(p.photo_key) FROM board b
						JOIN board_photo_map bp ON b.board_id = bp.board_id
						JOIN photo p ON bp.photo_id = p.photo_id
						WHERE b.join_code=UUID_TO_BIN(%s)
						''',
						str(join_code))
		results = cursor.fetchall()
		detupled_results = [photo_key for photo_key, in results]
		db_conn.conn.commit()
		return detupled_results

def get_board_owner_username(join_code):
	with db_conn.get_cursor() as cursor:
		cursor.execute(	'''
						SELECT BIN_TO_UUID(p.cognito_username) FROM board b
						JOIN person p ON b.owner_id = p.person_id
						WHERE b.join_code = UUID_TO_BIN(%s)
						''',
						(join_code))
		results = cursor.fetchone()
		db_conn.conn.commit()
		if not results:
			return None
		else:
			return results[0]

def get_connections_for_board(join_code):
	with db_conn.get_cursor() as cursor:
		cursor.execute(	'''
			SELECT bc.ws_connection_id FROM board b
			JOIN board_connection bc ON bc.board_id = b.board_id
			WHERE
				b.join_code = UUID_TO_BIN(%s)
				AND bc.board_connection_status_id = 1 # CONNECTED
			''',
			join_code)

		results = cursor.fetchall()
		detupled_results = [photo_key for photo_key, in results]
		db_conn.conn.commit()
		return detupled_results

def get_first_succeeded_payment_id_for_user(cognito_username):
	with db_conn.get_cursor() as cursor:
		person_id = _get_person_id_for_username(cursor, cognito_username)
		cursor.execute(	'''
						SELECT payment_id FROM payment
						WHERE person_id=%s
							AND payment_status_id=2 -- SUCCEEDED
						LIMIT 1
						''',
						(person_id))
		results = cursor.fetchone()
		db_conn.conn.commit()
		if not results:
			return None
		else:
			return results[0]

def update_payment_status(payment_id, new_status):
	with db_conn.get_cursor() as cursor:
		cursor.execute(	'''
						UPDATE payment
						SET payment_status_id=%s
						WHERE payment_id=%s
						''',
						(new_status.value, payment_id))
		db_conn.conn.commit()

def _create_photo(cursor, person_id, photo_key, s3_bucket_name, s3_object_key):
	cursor.execute(	'''
					INSERT INTO photo (uploader_id, photo_key, s3_bucket_name, s3_object_key, upload_date)
					VALUES (%s, UUID_TO_BIN(%s), %s, %s, NOW());
					''',
					(person_id, photo_key, s3_bucket_name, s3_object_key))
	return cursor.lastrowid

def _create_mapping(cursor, board, photo_id, board_photo_status):
	cursor.execute(	'''
					INSERT INTO board_photo_map (board_id, photo_id, board_photo_map_status_id, add_date)
					VALUES (%s, %s, %s, NOW())
					''',
					(board.board_id, photo_id, board_photo_status.value))

def _get_board_by_join_code(cursor, join_code):
	cursor.execute(	'''
					SELECT board_id, owner_id, board_name, BIN_TO_UUID(join_code), board_status_id, board_type_id, start_date, end_date
					FROM board
					WHERE join_code=UUID_TO_BIN(%s)
					''',
					(join_code,))
	board = cursor.fetchone()
	if not board:
		logger.error('No board found for join code: ' + str(join_code))
		return None
	else:
		return _board_tuple_to_board(board)

def _get_person_id_for_username(cursor, cognito_username):
	if not cognito_username:
		return None

	cursor.execute(	'''
					SELECT person_id
					FROM person
					WHERE person.cognito_username = UUID_TO_BIN(%s)''',
					(cognito_username,))
	person_id = cursor.fetchone()
	return person_id

def _board_tuple_to_board(board_tuple):
	board_id, owner_id, board_name, join_code, board_status_id, board_type_id, start_date, end_date = board_tuple
	return Board(board_id, owner_id, board_name, join_code, BoardStatus(board_status_id), BoardType(board_type_id), start_date, end_date)


import requests
import random
import json
import pickle

from fastapi_utils.tasks import repeat_every
from requests_oauthlib import OAuth1Session, OAuth1

from app.managers.instructions_manager import instructions_manager
from app.managers.users_manager import UserManager
from app.managers.transaction_manager import transaction_manager
from app.managers.redis_manager import redis_manager
from app.config import POLL_DURATION
from app.logger import get_logger

log = get_logger()

async def create_cross_connect(item_details):
    '''
    This function send request to the south side to order cross connect
    '''
    log.info("Sending order to equinix to create cross connect")

    # create fictitious Order ID as equinix responds NULL
    with open('db/equinix/order_status.json', 'r') as orders_list:
            order_ids = json.load(orders_list)
    while(True):
        o_id = "CC_ORDER_ID_" + str(random.randint(1000,9999))
        if o_id in order_ids.keys():
            continue
        else:
            with open('db/equinix/order_status.json', 'w') as orders_list:
                order_ids[o_id] = ""
                json.dump(order_ids, orders_list)
                log.info("Generated order ID")
                return o_id

async def ons_mark_complete(po_id, auth):
    '''
    This function updates the PO status in ONS
    '''
    BASE_URL = transaction_manager.north_details["base_url"]
    url = f"{BASE_URL}/services/rest/record/v1/purchaseOrder/{po_id}/!transform/itemReceipt"
    return requests.post(url, auth=auth)

async def update_po_status(po_id, status, user_manager):
    data = {
                "memo" : status[:-2]
            }
    BASE_URL = transaction_manager.north_details["base_url"]
    po_url = f"{BASE_URL}/services/rest/record/v1/purchaseorder/{po_id}"
    response = requests.patch(po_url, json=data, auth=user_manager.user_oauth1)
    if response.status_code == 200:
        log.info("Successfully updated status in ONS")
    else:
        log.error(f"Failed to update status in ONS. Status code: {response.status_code}")

async def process_po_item(item_details):
    if item_details['item']['refName'] == "CrossConnect":
        log.info("Found item cross connect")
        order_id = await create_cross_connect(item_details)
        return f"Order sent to Equinix. ID: {order_id}", order_id
    else:
        return "Item '" + item_details['item']['refName'] + "' Not registered with Lattice, please check with admin.", -1

async def get_ons_details(po_url, user_auth):
    '''
    This function takes ONS endpoint as input,
    makes API call to ONS and returns the response.
    '''
    log.info(f"[{transaction_manager.transaction_id}] Making API call to ONS to get details")
    response = requests.get(po_url,auth=user_auth)
    if response.status_code == 200:
        log.info(f"[{transaction_manager.transaction_id}] API call to ONS successful")
        return response.json()
    else:
        log.error(f"[{transaction_manager.transaction_id}] API call to ONS unsuccessful.")
        log.error(f"Response code: {response.status_code}, message: {response.content}")

async def add_po_to_db(user_id, po_id, item_status):
    '''
    Add PO details to redis.
    '''
    po_details = pickle.loads(redis_manager.redis.get("po_details"))
    # if user data not in redis
    if user_id not in po_details.keys():
         po_details[user_id] = {}
         po_details[user_id][po_id] = {
                                        "items" : item_status,
                                        "transaction_id" : transaction_manager.transaction_id
                                    }
    else:
        po_details[user_id][po_id] = {
                                        "items" : item_status,
                                        "transaction_id" : transaction_manager.transaction_id
                                    }
    redis_manager.redis.set("po_details", pickle.dumps(po_details))

async def execute_api(api_data):
     '''
     This function takes API data as input,
     generates the end point and body parameters and
     makes the API call.
     Return value is response from the API call.
     '''
     api_method = api_data["method"]
     url = api_data["BASE_URL"] + api_data["route"]
     if api_method == "GET":
        response = requests.get(url,auth=api_data["AUTH"])
        return response.json()

@repeat_every(seconds=POLL_DURATION)
async def Poll_PurchaseOrder():
    '''
    This function polls the purchase orders from north.
    '''
    log.info("Polling  PO")
    user_manager = UserManager("vidatt")
    north_id = transaction_manager.north_details["north_id"]

    # get api details from redis
    api_data = pickle.loads(redis_manager.redis.get("north_data"))[north_id]['api_details']['polling']['purchase_order']['get_details']
    api_data["BASE_URL"] = transaction_manager.north_details["base_url"]
    api_data["AUTH"] = user_manager.user_oauth1

    # get PO list
    po_list = await execute_api(api_data)
    log.info("Successfully fetched PO list.")
    new_po  = False

    # check if number of PO is more than 0
    if po_list['totalResults'] == 0:
        log.info("No purchase orders found in the list")
        return
    else:
        log.info("Iterating PO list")
        # process PO
        for po in po_list['items']:
            # if it is a new PO
            if int(po['id']) not in user_manager.processed_po:
                new_po = True
                log.info("Found new PO")
                await transaction_manager.new_transaction_id()
                log.info(f"Created new transaction {transaction_manager.transaction_id}")
                log.info(f"[{transaction_manager.transaction_id}] Get PO details")
                po_details = await get_ons_details(po['links'][0]['href'], user_manager.user_oauth1)
                log.info(f"[{transaction_manager.transaction_id}] Get items list")
                items_list = await get_ons_details(po_details['item']['links'][0]['href'], user_manager.user_oauth1)
                po_status = "Order Status: \n"
                item_count = 0
                items_status = {}
                # process items
                log.info(f"[{transaction_manager.transaction_id}] Iterating items list")
                for item in items_list['items']:
                    item_count += 1
                    log.info(f"[{transaction_manager.transaction_id}] Get item details")
                    item_details = await get_ons_details(item['links'][0]['href'], user_manager.user_oauth1)
                    log.info(f"[{transaction_manager.transaction_id}] Processing item")
                    item_status, south_order_id = await process_po_item(item_details)
                    po_status += f"Item {item_count}: " + item_status + ", \n"
                    items_status[item_count] = {
                                                    "status" : item_status,
                                                    "south_order_id" : south_order_id
                                                }

                (user_manager.processed_po).append(int(po['id']))
                log.info(f"[{transaction_manager.transaction_id}] Update PO status to ONS")
                await update_po_status(int(po['id']), po_status, user_manager)
                log.info(f"[{transaction_manager.transaction_id}] Add PO details to redis")
                await add_po_to_db(user_manager.user_id, int(po['id']), items_status)

        if new_po == False:
             log.info("No new PO found")
        else:
            # update PO list in redis
            log.info("Updating user's PO list in redis")
            await user_manager.update_po_list()

    # clear user variables
    await user_manager.clean_up()
    del user_manager
    log.info("Cleared user's details.")
    log.info("Polling PO completed.")

@repeat_every(seconds=POLL_DURATION)
async def Poll_OrderStatus():
    '''
    This function polls the order status from south
    '''
    log.info("Polling order status")
    user_manager = UserManager('vidatt')
    log.info("Get PO details of user")
    # with open('db/po_details.json', 'r') as po_details_list:
    #         po_details_lst = json.load(po_details_list)
    #         po_details = po_details_lst[user_manager.user_id]

    with open('db/equinix/order_status.json', 'r') as order_status_list:
            order_status_data = json.load(order_status_list)
    po_details_lst = pickle.loads(redis_manager.redis.get("po_details"))
    po_details = po_details_lst[user_manager.user_id]
    log.info("Checking status of items in equinix data.")
    for po_id, po_data in po_details.items():
        status_updated = False
        po_status = "Order Status: \n"
        transaction_id = po_data["transaction_id"]
        item_count = 0
        item_completed = 0
        for item_id, item_data in po_data['items'].items():
            south_order_id = item_data['south_order_id']
            if south_order_id == -1:
                continue
            item_count += 1
            if order_status_data[south_order_id] == "Order completed":
                item_completed += 1
            if item_data['status'] == order_status_data[south_order_id] or order_status_data[south_order_id] == "":
                po_status += f"Item {item_id}: " + item_data['status'] + ', '
            else:
                po_status += f"Item {item_id}: Status in Equinix({south_order_id}) - " + order_status_data[south_order_id] + ','
                status_updated = True
                po_details_lst[user_manager.user_id][po_id]['items'][item_id]['status'] = order_status_data[south_order_id]

        # if all item orders are completed, update PO status in ONS
        if item_count == item_completed:
            log.info(f"All items for transaction {transaction_id} are completed from south")
            ons_status_code = await ons_mark_complete(po_id, user_manager.user_oauth1)
            if ons_status_code == 200:
                log.info("Updated PO status in ONS")
            else:
                log.error("Failed to update PO status in ONS. Response")

        # check if status was updated
        if status_updated:
             await update_po_status(po_id, po_status, user_manager)
             log.info(f"Updating new status in ONS for transaction {transaction_id}")
        else:
             log.info(f"No updates for transaction {transaction_id}")
    # with open('db/po_details.json', 'w') as po_detail_list:
    #             json.dump(po_details_lst, po_detail_list)
    redis_manager.redis.set("po_details", pickle.dumps(po_details_lst))
    log.info("Polling order status completed.")


#python videoPlayBackFromFiles.py --folderPath ZakiBashakha

import numpy as np
import os
import six.moves.urllib as urllib
import sys
import tarfile
import zipfile

from collections import defaultdict
from io import StringIO
from matplotlib import  pyplot  as plt
from PIL import Image
import cv2
import argparse

def  showVideofromFrames():
    		frameNum=1
    		for filename in imgFiles:
    			print(filename)
    			img = cv2.imread(os.path.join(folderPath,filename))
    			#img = cv2.resize(img, (width, height))
    			if (img is None):
    				frameNum=frameNum+1
    				continue
    			img=cv2.resize(img,(width,height))
    			video_creator.write(img)
    			cv2.imshow(folderPath,img)
				#if (frameNum==1):
					#raw_input("press any key to continue")
    			cv2.waitKey(1)
    			frameNum=frameNum+1
    			#out.write(img)
    			if cv2.waitKey(1) & 0xFF == ord('q'):
    				break

#fourcc = cv2.VideoWriter_fourcc(*'XVID')
#out = cv2.VideoWriter("Detect_HardHat.m4v",fourcc, 5, (1152,648))
    #read the arguments

if __name__ == "__main__":

    ap = argparse.ArgumentParser()
    ap.add_argument("--folderPath", required=True,help="path to frames  of video")

    args = vars(ap.parse_args())
    folderPath=args["folderPath"]

    scaleFactor=0.6
    width=1280
    height=720
    width=int(width*scaleFactor)
    height=int(height*scaleFactor)
    filenamesList=os.listdir(folderPath)
    fourcc = cv2.VideoWriter_fourcc(*'XVID')
    fileName="demo.mp4"

    video_creator = cv2.VideoWriter(fileName,fourcc, 2, (width,height))
    imgFiles=os.listdir(folderPath)
    imgFiles.sort()
    imgFiles=sorted(os.listdir(folderPath))

    showVideofromFrames()
    video_creator.release()
    print("[INFO] Video file created  and saved to {}".format(fileName))


import uuid
import typing as t
from fastapi import status
from tortoise.expressions import Q
from fermerce.core.enum.sort_type import SortOrder
from fermerce.core.schemas.response import ITotalCount
from fermerce.core.services.base import filter_and_list
from fermerce.lib.errors import error
from fermerce.app.status import schemas, models
from fastapi import Response

# create permission
async def create(
    data_in: schemas.IStatusIn,
) -> models.Status:
    check_status = await models.Status.get_or_none(name=data_in.name)
    if check_status:
        raise error.DuplicateError("status already exists")
    new_type = await models.Status.create(**data_in.dict())
    if not new_type:
        raise error.ServerError("Internal server error")
    return new_type

async def get(
    status_id: uuid.UUID,
) -> models.Status:
    perm = await models.Status.get_or_none(id=status_id)
    if not perm:
        raise error.NotFoundError("status not found")
    return perm

# # get all permissions
async def filter(
    filter_string: str,
    per_page: int = 10,
    page: int = 0,
    select: str = "",
    sort_by: SortOrder = SortOrder.asc,
    order_by: str = None,
) -> t.List[models.Status]:
    query = models.Status.filter(Q(name__icontains=filter_string))
    result = await filter_and_list(
        model=models.Status,
        query=query,
        per_page=per_page,
        page=page,
        order_by=order_by,
        select=select,
        sort_by=sort_by,
    )
    return result

async def get_total_count() -> ITotalCount:
    total = await models.Status.all().count()
    return ITotalCount(count=total).dict()

# # update permission
async def update(
    status_id: uuid.UUID,
    data_in: schemas.IStatusIn,
) -> models.Status:
    check_status = await models.Status.get_or_none(id=status_id)
    if not check_status:
        raise error.NotFoundError("status does not exist")
    check_name = await models.Status.get_or_none(name=data_in.name)
    if check_name and check_name.id != status_id:
        raise error.DuplicateError("status already exists")
    elif check_name and check_name.id == status_id:
        return check_status
    check_status.update_from_dict(data_in.dict())
    await check_status.save()
    return check_status

# # delete permission
async def delete(
    status_id: uuid.UUID,
) -> None:
    deleted_status = await models.Status.filter(id=status_id).delete()
    if not deleted_status:
        raise error.NotFoundError("status does not exist")
    return Response(status_code=status.HTTP_204_NO_CONTENT)


import cv2
import numpy as np
import numpy

image1 = cv2.imread("/home/wang_shuai/Assignment-4-Material/Left.jpg")
image2 = cv2.imread("/home/wang_shuai/Assignment-4-Material/Right.jpg")

# kp1 = np.array([kp1[g.queryIdx].pt for g in good])
# kp2 = np.array([kp2[g.trainIdx].pt for g in good])

def perpare2d(path):
    x,y = [],[]
    with open(path, "r") as file:
        x = file.readline().split(", ")
        y = file.readline().split(", ")
    x = [float(x_) for x_ in x]
    y = [float(y_) for y_ in y]
    x = numpy.array(x, dtype=numpy.float)
    y = numpy.array(y, dtype=numpy.float)

    return numpy.stack([x,y],axis=1)
kp1 = perpare2d("Homopoint2d_Left.txt")
kp2 = perpare2d("Homopoint2d_Right.txt")
# 可视化
h,w,c= image1.shape
img3 = numpy.zeros([h,w*2,c], dtype=np.uint8)
img3[:, 0:w] = image1
img3[:,w:2*w] = image2

for i in range(6):
    x1 = int(kp1[i][0])
    y1 = int(kp1[i][1])
    x2 = int(kp2[i][0])+w
    y2 = int(kp2[i][1])
    cv2.line(img3, (x1,y1), (x2,y2), (100,200,100), 2)

cv2.imshow("match", img3)
cv2.waitKey()
#

def solve(kp1, kp2):
    n,_ = kp1.shape
    A = np.zeros([n*2,9])
    for i in range(n):
        A[2*i,0:2] = kp1[i]
        A[2*i,2] = 1
        A[2*i,6:8] = -kp1[i]*kp2[i,0]
        A[2*i,8] = -kp2[i][0]

        A[2*i+1,3:5] = kp1[i]
        A[2*i+1,5] = 1
        A[2*i+1,6:8] = -kp1[i]*kp2[i,1]
        A[2*i+1,8] = -kp2[i][1]
    ATA = np.matmul(np.transpose(A), A)
    eig, eigx = np.linalg.eig(ATA)
    eigx = eigx[:,eig.argmin()]
    eigx = eigx / eigx[-1]
    return eigx.transpose()

x = solve(kp1, kp2)

x = x.reshape(3,3)
print("using my:")
print(x)
# print(kp2[0])

t =  np.array([kp1[0][0],kp1[0][1],1])
y = np.matmul(x,t)
# print(y / y[2])

homo,_  = cv2.findHomography(kp1,kp2,0)
print("using opencv:")
print(homo)
# y = np.matmul(homo,t)
# print(y/y[-1])


# STEP4: TSR FINDING ALGORITHM from Rocky which I have modified slightly

from collections import defaultdict

def run_step_four(step_three_file, window_size, chromosome_sizes, output_filename):
    fi = open(step_three_file, 'r')

    DDCHRSIZE = chromosome_sizes

    id_to_process = '1'
    lines_to_process = []
    OFILE = open(output_filename, 'w')
    STEP = window_size

    def TSRF(LIST, STEPSIZE):
        k = 0
        TSR = []

        append_last = True

        while repr(k) != repr(len(LIST)):
            DDL = defaultdict(list)
            for f in LIST:
                DATA = f
                TMP = DATA[0].strip() + ':' + DATA[1].strip() + '-' + DATA[2].strip()
                DDL[TMP] = DATA
            REMOVE = set()
            try:
                MAX = LIST[0]
            except IndexError:
                append_last = False
                break

            for l in LIST[1:]:
                if len(range(max(int(l[1]), int(MAX[1])), min(int(l[2]), int(MAX[2])))) > 0 and int(l[4]) > int(MAX[4]):
                    MAX = l
                elif len(range(max(int(l[1]), int(MAX[1])), min(int(l[2]), int(MAX[2])))) < 1:
                    TSR.append(MAX)
                    MAX = l
            TSR.append(MAX)
            REMOVE = [rn[0].strip() + ':' + '-'.join([repr(nr), repr(nr + STEPSIZE)]).strip() for rn in TSR for nr in
                      range((int(rn[1]) + 1) - STEPSIZE, int(rn[2]))]
            k = len(LIST)
            LIST = [[int(DDL[ls][1]), DDL[ls]] for ls in set(DDL.keys()).difference(REMOVE)]
            LIST.sort(key=lambda x: x[0])
            LIST = [sl[1] for sl in LIST]

        if append_last:
            try:
                TSR.append(MAX)
            except UnboundLocalError:
                pass

        TSR = set(['\t'.join(ts).strip() for ts in TSR])
        TSR = [[int(srrt.strip().split('\t')[1]), srrt.strip()] for srrt in list(TSR)]
        TSR.sort(key=lambda x: x[0])
        TSR = [w[1].strip() for w in TSR]
        return TSR

    while True:
        raw_line = fi.readline()
        # check whether we're at eof
        if not raw_line:
            break
        # get line
        line = raw_line.rstrip().split("\t")
        id = line[0].strip()
        strand = line[-1].strip()
        # same id
        if id == id_to_process.strip():
            lines_to_process.append(line)
        # a new id is coming
        else:
            # do something with your lines
            if len(lines_to_process) > 0:
                for tsrf in TSRF(lines_to_process, STEP):
                    CHECKTSRBUNDRY = tsrf.strip().split('\t')
                    if DDCHRSIZE[CHECKTSRBUNDRY[0].strip()] > 0 and int(CHECKTSRBUNDRY[2]) <= DDCHRSIZE[
                        CHECKTSRBUNDRY[0].strip()]:
                        OFILE.write(tsrf.strip() + '\n')
            # now proceed with next id
            id_to_process = id.strip()
            lines_to_process = [line]

    for tsrl in TSRF(lines_to_process, STEP):
        CHECKTSRBUNDRY = tsrl.strip().split('\t')
        if DDCHRSIZE[CHECKTSRBUNDRY[0].strip()] > 0 and int(CHECKTSRBUNDRY[2]) <= DDCHRSIZE[CHECKTSRBUNDRY[0].strip()]:
            OFILE.write(tsrl.strip() + '\n')
    OFILE.close()


import os
import sys

import requests

print(sys.executable)
print(sys.version)

def greetings(who_to_greet):
    greeting = "Hello, {}".format(who_to_greet)
    return greeting

r = requests.get("https://www.google.com")
print(r.status_code)
print("hello")


import os
import sys
import json

from collections import OrderedDict

EMOJI_MODIFIER_BASE = {
  '1f590', '1f468', '1f46e', '1f595', '1f3c3', '1f935', '1f646', '1f449',
  '1f477', '1f91c', '1f486', '1f6b6', '1f919', '1f930', '1f44b', '1f933',
  '1f6b5', '270b', '1f483', '1f64b', '1f470', '270a', '1f443', '1f918',
  '1f448', '1f471', '1f474', '1f467', '26f9', '1f44f', '1f93e', '1f6cc',
  '1f481', '1f485', '1f4aa', '1f596', '1f47c', '1f487', '1f44c', '1f476',
  '261d', '1f934', '1f385', '270c', '1f3c4', '1f64f', '1f645', '1f91e',
  '1f926', '270d', '1f647', '1f3c2', '1f6a3', '1f574', '1f3cc', '1f44a',
  '1f57a', '1f3ca', '1f450', '1f442', '1f91a', '1f93d', '1f472', '1f64d',
  '1f482', '1f3c7', '1f64c', '1f6b4', '1f938', '1f3cb', '1f936', '1f44d',
  '1f469', '1f937', '1f64e', '1f91b', '1f478', '1f447', '1f466', '1f44e',
  '1f575', '1f446', '1f6c0', '1f473', '1f939', '1f475', '1f93c'}

class EmojiDictionary:

  def __init__(self):
    self.emoji = self.__load()

  def search(self, search_term, max_items=None):
    term = search_term.lower()

    if term:
      matches = []
      for emoji in self.emoji:
        if term in emoji['description']:
          matches.append(emoji)

          if max_items and len(matches) >= max_items:
            break

      return matches
    else:
      if max_items:
        return self.emoji[:max_items]
      else:
        return self.emoji

  def __load(self):

      with open(os.path.join(os.path.dirname(__file__), 'emoji.json')) as emoji_json:
        emoji_raw = json.loads(
          emoji_json.read(), object_pairs_hook=OrderedDict)

      emojis = []

      base_props = {}
      for emoji in emoji_raw:
        category = emoji_raw[emoji]['category']
        if emoji in EMOJI_MODIFIER_BASE:
          base_props[emoji] = emoji_raw[emoji]

        if '-' in emoji:
          main_codepoint = emoji.split('-')[0]

          if main_codepoint in EMOJI_MODIFIER_BASE:
            shortname = base_props[main_codepoint]['shortname']
            description = (base_props[main_codepoint]['name']
                    + '. Keywords:'
                    + ' '.join(
                      base_props[main_codepoint]['keywords']))
          else:
            shortname = emoji_raw[emoji]['shortname']
            description = (emoji_raw[emoji]['name']
                    + '. Keywords: '
                    + ' '.join(emoji_raw[emoji]['keywords']))
        else:
          shortname = emoji_raw[emoji]['shortname']
          description = (emoji_raw[emoji]['name']
                  + '. Keywords: '
                  + ' '.join(emoji_raw[emoji]['keywords']))

        path = os.path.join(
            os.path.dirname(__file__),
            'emojitwo/png/' +
            emoji + '.png')

        if os.access(path, os.F_OK):
          emojis.append({
            'path': path,
            'name': shortname,
            'category': category,
            'emoji': emoji,
            'description': description
          })

      return emojis


from django_auth_ldap.backend import LDAPBackend, _LDAPUser
from django.contrib.auth.models import User

class LDAPSyncBackend(LDAPBackend):

    def get_or_create_user(self, username, ldap_user):
        """
        Overriding get_or_create_user to perform our own Django/Nadine User
        lookup.
        django-auth-ldap assumes we would want to create Django/Nadine users if
        they don't exist but we don't want to do this. Instead we throw a
        _LDAPUser.AuthenticationFailed exception.
        """
        try:
            # Use 'nadine.backends.EmailOrUsernameModelBackend' strategy to
            # look up a user. First by email, then by username.
            if '@' in username:
                user = User.helper.by_email(username)
            else:
                user = User.objects.get(username=username)

        except User.DoesNotExist:
            # If we can't match against a user in the database then we bail.
            # LDAP users are created & managed FROM Nadine; we don't want to be
            # creating Django users for existing LDAP accounts.
            user = None

        if (user):
            return (user, False)
        else:
            raise _LDAPUser.AuthenticationFailed(
                "User exists in LDAP but doesn't exist in Nadine"
            )

# Copyright 2021 Office Nomads LLC (https://officenomads.com/) Licensed under the AGPL License, Version 3.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.gnu.org/licenses/agpl-3.0.html. Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


from problem12 import get_factors
from collections import Counter
from itertools import product
import numpy as np

amicable_nums = []
l = [2, 3]
# print(get_factors(1))

def sum_divisors(factors):
    # 由素因子列表得出因子列表，包括1，再计算其和
    sub_factors = []
    for k, v in Counter(factors).items():
        # 比如k = 2, v = 3，就生成[1, 2, 4, 8]
        sub_factors.append([k ** i for i in range(v + 1)])  # 0的0次方居然不报错，会被记为1
    # 对sub_factors计算笛卡尔积，将得到的结果(列表的列表)中最内层列表求连乘积，即得到divisors列表，
    # 去掉外层列表最后一个元素，求和，即得结果
    return sum([np.prod(i) for i in product(*sub_factors)][:-1])  # 不计算最后一个元素（自己本身）

for n in range(2, 10000):
    if n in amicable_nums:
        continue
    l, factors = get_factors(n, l)
    # print('f1', factors)
    m = sum_divisors(factors)  # 8128自己和自己相等
    if m != n:
        l, factors = get_factors(m, l)
        # print('f2', factors)
        if sum_divisors(factors) == n:
            amicable_nums.extend([m, n])
            print(m, n)

# print(sum_divisors([0]))  # 会等于1
print(amicable_nums)
print(sum(amicable_nums))


from django.db import models
# from django.contrib.auth import get_user_model
# from django_cleanup import cleanup
from user.models import UserModel

class Board(models.Model):
    author = models.ForeignKey(UserModel(), on_delete=models.CASCADE)
    board_id = models.AutoField(primary_key=True)
    # title = models.CharField(max_length=50)
    img = models.FileField(null=True, upload_to="", blank=True)
    content = models.TextField(max_length=300)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)
    likes = models.ManyToManyField(UserModel, related_name='likes', blank=True)
    likes_count = models.PositiveIntegerField(default=0)

    class Meta:
        db_table = 'board'

    #좋아요 저장
    def update_likes_count(self):
        self.likes_count = self.likes.count()
        self.save()

    # def delete(self, *args, **kargs):
    #     os.remove(os.path.join(settings.MEDIA_ROOT, self.upload_file.name))
    #     super(Board, self).delete(*args, **kargs)