import tensorflow as tf
import numpy as np

class MultiArmedBandit():
    def __init__(self, input_dimension=[], output_dimension=[], layer_sizes=[], learning_rate=1e-4, model_ckpt=None):

        if model_ckpt is None:
            self.input, self.output = _construct_network(input_dimension, output_dimension, layer_sizes)

            nrof_gpu = 0 # {0, 1}

            config = tf.ConfigProto( device_count = {'GPU': nrof_gpu} )

            self.sess = tf.Session( config = config )
            #self.sess = tf.Session()

            optimizer = tf.train.AdamOptimizer(learning_rate)

            self.pt_step, self.pt_target, self.pt_loss = _setup_pre_training(self.output, output_dimension, optimizer)

            self.update_step, self.action, self.target, self.loss = _setup_training(self.output, output_dimension, optimizer)

            self.sigmoid_output = tf.sigmoid( self.output )

            self.initialize()
        else:

            # Load model from checkpoint saved earlier
            self.sess = tf.Session()

            saver = tf.train.import_meta_graph(model_ckpt + "/model.ckpt.meta")

            saver.restore(self.sess, tf.train.latest_checkpoint( model_ckpt ) )

            print("Model restored from " + model_ckpt)

            graph = tf.get_default_graph()

            self.input = graph.get_tensor_by_name("input:0")

            self.output = graph.get_tensor_by_name("output:0")

            self.action = graph.get_tensor_by_name("action:0")

            self.target = graph.get_tensor_by_name("target:0")

            self.loss = graph.get_tensor_by_name("loss:0")

            self.update_step = graph.get_operation_by_name("update_step")

            self.sigmoid_output = tf.sigmoid( self.output )

    def initialize(self):
        self.sess.run(tf.global_variables_initializer())

    def pretrain_agent(self, pt_input, pt_target):
        self.sess.run(self.pt_step, feed_dict={self.input: pt_input, self.pt_target: pt_target})

    def pretrain_loss(self, pt_input, pt_target):
        return self.sess.run(self.pt_loss, feed_dict={self.input: pt_input, self.pt_target: pt_target})

    def calculate_output(self, input_):
        return self.sess.run(self.sigmoid_output, feed_dict={self.input: input_})

    def calculate_loss(self, input_, action, reward):
        action_selector = np.column_stack((np.arange(len(action)), np.array(action)))
        return self.sess.run(self.loss, feed_dict={self.input: input_, self.action: action_selector, self.target:reward})

    def update_agent(self, input_, action, reward):
        action_selector = np.column_stack((np.arange(len(action)), np.array(action)))
        self.sess.run(self.update_step, feed_dict={self.input: input_, self.action: action_selector, self.target: reward})

    def save_model(self, dirpath):
        saver = tf.train.Saver()

        save_path = saver.save(self.sess, dirpath + "/model.ckpt")
        print("Model saved to: %s" % save_path)

        #tf.saved_model.simple_save(self.sess,
        #                           dirpath,
        #                           inputs={'input':self.input, 'action':self.action},
        #                           outputs={'output':self.output, 'target':self.target})

    def close_session(self):
        tf.reset_default_graph()
        self.sess.close()

def _weight_variable(shape, name):
    return tf.Variable(tf.truncated_normal(shape, stddev=0.1), name=name)

def _bias_variable(shape, name):
    return tf.Variable(tf.constant(value=0.01, shape=shape), name=name)

def _leaky_relu(x):
    return tf.nn.relu(x) + 0.1 * tf.nn.relu(-x)

def _setup_pre_training(output, output_dimension, optimizer):
    pretrain_target = tf.placeholder(tf.float32, [None, output_dimension], name='pt_target')

    pretrain_loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=output, labels=pretrain_target)

    #pretrain_step = tf.train.AdamOptimizer(1e-6).minimize(pretrain_loss)
    pretrain_step = optimizer.minimize(pretrain_loss)

    return (pretrain_step, pretrain_target, pretrain_loss)

def _setup_training(output, output_dimension, optimizer):
    target = tf.placeholder(tf.float32, [None], name='target')
    action = tf.placeholder(tf.int32, [None, 2], name='action')

    out = tf.gather_nd(output, action)

#    loss = (tf.sigmoid(out) - target) ** 2
    loss = tf.nn.sigmoid_cross_entropy_with_logits(logits=out, labels=target, name='loss')

    update_step = optimizer.minimize(loss, name='update_step')

    return (update_step, action, target, loss)

def _construct_network(input_dimension, output_dimension, layer_sizes):
    input_= tf.placeholder(tf.float32, [None, input_dimension], name='input')

    nrof_layers = len(layer_sizes)

    # List of hidden layer variables
    W = []
    b = []
    h = []

    if nrof_layers > 0:
      # Define the first hidden layer
      with tf.name_scope('Hidden_Layer_0'):
          l = layer_sizes[0]
          W.append(_weight_variable([input_dimension, l], 'W0'))
          b.append(_bias_variable([l], 'b0'))

          h.append(tf.nn.relu(tf.matmul(input_, W[0]) + b))#, 'h0'))

      # Define the subsequent hidden layers
      for i in range(1, nrof_layers):
          with tf.name_scope('Hidden_Layer_%d'%(i)):
              l = layer_sizes[i]
              W.append(_weight_variable([layer_sizes[i-1], l], 'W%d'%(i)))
              b.append(_bias_variable([l], 'b%d'%(i)))

              h.append(tf.nn.relu(tf.matmul(h[i-1], W[i]) + b[i]))#, name='h%d'%(i)))

      # Define the output layer
      W.append(_weight_variable([layer_sizes[-1], output_dimension], 'W%d'%(nrof_layers)))
      b.append(_bias_variable([output_dimension], 'b%d'%(nrof_layers)))

      output_ = tf.add(tf.matmul(h[-1], W[-1]), b[-1], name='output')

    else:
          W.append(_weight_variable([input_dimension, output_dimension], 'W0'))
          b.append(_bias_variable([output_dimension], 'b0'))

          output_ = tf.add( tf.matmul(input_, W[-1]), b[-1], name='output' )

    return (input_, output_)


import profile
from django.urls import path
from . import views
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from .views import PostListView,PostDetailView,PostCreateView,PostUpdateView, PostDeleteView, ProfileView, AddFollower,RemoveFollower,CommentCreateView

urlpatterns = [

    # path('',PostListView.as_view(), name='home'),
    path('',views.index, name='home'),
    path('profile/<int:pk>',ProfileView.as_view(),name = 'profile'),
    path('post/<int:pk>/',PostDetailView.as_view(), name='post-detail'),
    path('post/<int:pk>/update/',PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/delete/',PostDeleteView.as_view(), name='post-delete'),
    path('post/new/',PostCreateView.as_view(), name='post-create'),
    path('user_registration/',views.register, name ='user_registration' ),
    path('accounts/login/',auth_views.LoginView.as_view(template_name = 'accounts/login.html'), name = 'login'),
    path('logout/', auth_views.LogoutView.as_view(template_name = 'accounts/logout.html'), name='logout'),
    path('profile/<int:pk>/followers/add', AddFollower.as_view(), name='add-follower'),
    path('profile/<int:pk>/followers/remove', RemoveFollower.as_view(), name='remove-follower'),
    path('post/<int:pk>/comment/',CommentCreateView.as_view(), name='add_comment'),
    path('search/', views.search_results, name='search_results')
]

if settings.DEBUG:
    urlpatterns+= static(settings.MEDIA_URL, document_root = settings.MEDIA_ROOT)


import numpy as np
import pandas as pd
import cv2
from PIL import Image
import joblib
import cv2
import numpy as np
import time
import pandas as pd
import imagehash
import multiprocessing as mp
import logging
import os
from dataclasses import dataclass, field
from typing import List, Dict

from slideextract.config import ocr_feature_names, ocr_new_slide_clf, DATA_FILE_PATH
from slideextract.comparator.docDiffBuilder import docDiffBuilder, doc_diff_comparator
from slideextract.processing.ffmpeg_sample_video import sample_video

logger = logging.getLogger('baseSlide')

@dataclass
class BaseSlideExtractor:
    """
    base class for slide extractor,
    all slide extractor should inherit from this class
    have general methods to extract images from video
    compare slides based on imagebased feature and ocr feature
    """
    name = "baseSlideExtractor"
    data_file_path = None

    def __init__(self, *args, **kwargs) -> None:
        pass

    def extract_slides(self, mp4_file_path: str):
        NotImplementedError

    def extract_slides_from_file(self, mp4_file_path: str, threads: int = 0):
        self.data_file_path = os.path.join(DATA_FILE_PATH, os.path.basename(mp4_file_path).split(".")[0], self.name)
        output_path = os.path.join(self.data_file_path, "frames")
        frames_data = sample_video(mp4_file_path, output_path=output_path, threads=threads)
        return self.extract_slides_from_frames(frames_data)

    def extract_slides_from_frames(self, frames_data: dict):
        NotImplementedError

    def _generate_ocr_doc_feature(self, ocr_paragraph1: str, ocr_paragraph2: str, doc_diff_comparator: docDiffBuilder=doc_diff_comparator):
        """
        generate feature feature based on ocr results
        """
        doc1 = ocr_paragraph1
        doc2 = ocr_paragraph2
        doc_compare_dict = doc_diff_comparator.compare(doc1, doc2)
        doc_compare_dict['frame_token_ct'] = max([len(doc1), len(doc2)])
        # need to test if dataframe results results
        feature_df = pd.DataFrame([doc_compare_dict])
        feature_df = feature_df.rename(columns={'letter_dis':'letter_dissim'})
        return feature_df[ocr_feature_names]

    def _compare_ocr_results(self, ocr_slide_indices: List, ocr_paragraphs: Dict, clf_model) -> pd.DataFrame:
        ocr_slide_record = []
        for index in ocr_slide_indices:
            if index > 0:
                feature_df = \
                    self._generate_ocr_doc_feature(
                        ocr_paragraph1=ocr_paragraphs[index], ocr_paragraph2=ocr_paragraphs[index-1])
                ocr_is_new_slide = ocr_new_slide_clf.predict(feature_df)[0]
                ocr_slide_record.append((index, ocr_is_new_slide))

        ocr_new_slide_df = pd.DataFrame(ocr_slide_record)
        ocr_new_slide_df.columns = ['index', 'ocr_is_new_slide']
        return ocr_new_slide_df

    def _classify_if_ocr_same(self, feature_df: pd.DataFrame, clf_model) -> bool:
        """
        classify if ocr results are the same
        """
        return clf_model.predict(feature_df)[0]

    @classmethod
    def compare_frames(frames, comparators):
        """
        Use the output of 1, and a list of python callable[(image1, image2), float],
        return the dataframe with the following columns:
        index: index of the frame
        phash: percetual hash of the image with previous frame (create phash comparater)
        dhash: dhash diff of the image with previous frame (create dhash comparater)
        """
        data = []
        prev_frame = None
        for index, frame in frames.items():
            row = {"index": index}
            if prev_frame is not None:
                for comparator, name in comparators:
                    row[name] = comparator(prev_frame, frame)
            data.append(row)
            prev_frame = frame
        return pd.DataFrame(data)


from flask import Flask, redirect, request, session, Response, jsonify
from flask_login import LoginManager
from flask_mail import Mail
from myapp.models.base import db

# 初始化 Loginmanager
login_manager = LoginManager()
mail = Mail()

def create_app():
    app = Flask(__name__)
    app.config.from_object('myapp.secure')
    app.config.from_object('myapp.setting')
    # 注册flask-login
    login_manager.init_app(app)
    # 登录页面
    login_manager.login_view = 'web.login'
    login_manager.login_message = '请先进行登陆'
    # 邮件注册
    mail.init_app(app)
    # 注册蓝图
    register_blueprint(app)
    # 注册SQLAlchemy
    db.init_app(app)
    db.create_all(app=app)
    app.response_class = AutoJsonifyResponse
    return app

def register_blueprint(app):
    # 注册book里web的蓝图
    from myapp.controller import api
    app.register_blueprint(api)

class AutoJsonifyResponse(Response):
    @classmethod
    def force_type(cls, response, environ=None):
        if isinstance(response, (list, dict)):
            response = jsonify(response)
        return super(Response, cls).force_type(response, environ)


import math

seznam = []

for i in range(0, 1000):
    stevilka = int(input("Vnesi število: "))
    seznam.append(stevilka)
    if stevilka == 0:  # ali je število enako 0
        break;

print("Najmanjše število je: ", min(stevilka))


import cv2 as cv
import numpy as np

def diferenca():
    captura = cv.VideoCapture(0)

    while True:
        ret, frame = captura.read()
        frame = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

        cv.imshow("Video", np.subtract(frame, quarto))

        k = cv.waitKey(30) & 0xff
        if k == 27:
            break

    captura.release()
    cv.destroyAllWindows()

if __name__ == '__main__':
    diferenca()


'''
Created by Han Xu
email:736946693@qq.com
'''
import xml.etree.ElementTree as ET

def read_configuration(xml_file):
    # 解析 XML 文件
    tree = ET.parse(xml_file)
    root = tree.getroot()

    # 获取camvid数据集路径
    camvid_path = root.find('camvid_path').text

    # 获取模型路径
    HANet_oneHAM_path = root.find('HANet_oneHAM_path').text
    HANet_twoHAM_path = root.find('HANet_twoHAM_path').text

    # 获取保存模型的路径
    save_path = root.find('save_path').text

    return camvid_path, HANet_oneHAM_path, HANet_twoHAM_path, save_path

# 用于测试的 XML 文件路径
xml_file_path = "conf.xml"

# 读取配置信息
import os

# 获取当前脚本所在的目录
current_directory = os.path.dirname(os.path.abspath(__file__))
# 切换到该目录
os.chdir(current_directory)

camvid_path, HANet_oneHAM_path, HANet_twoHAM_path, save_path = read_configuration(xml_file_path)

if __name__ == "__main__":
    # 打印读取到的信息
    print(f"camvid_path: {camvid_path}")
    print(f"HANet_oneHAM_path: {HANet_oneHAM_path}")
    print(f"HANet_twoHAM_path: {HANet_twoHAM_path}")
    print(f"save_path: {save_path}")


import gzip
import shutil
import os, sys

"""
This script compresses text file into gzip
"""

fpath = '/home/varsha/fl-proj/lingspam_public/lemm_stop/part9'
fl_list = os.listdir(fpath)

for fl in fl_list:
    if ".txt.gz" not in fl:
        print(fl)
        fop = os.path.join(fpath, fl)
        print(type(fop))

        with open(fop, 'rb') as f_in:
            fop += ".gz"
            with gzip.open(fop, 'wb') as f_out:
                shutil.copyfileobj(f_in, f_out)


from torchmetrics import Accuracy, F1Score, Precision, Recall, AUROC

class Configs:
    def __init__(self, dataset="EMG"):
        # preprocess configs
        if dataset == "EMG":
            self.dataset_config = EMGGestureConfig()
        elif dataset == "NINA":
            self.dataset_config = NinaproDB5Config()
        self.model_config = ModelConfig(self.dataset_config)
        self.training_config = TrainingConfig(self.dataset_config)

class EMGGestureConfig:
    def __init__(self):
        self.url = "https://archive.ics.uci.edu/ml/machine-learning-databases/00481/EMG_data_for_gestures-master.zip"
        self.save_dir = "dataset/EMGGesture"

        self.batch_size = 256
        self.partition = [0.8, 0., 0.2]

        self.sampling_freq = 1000
        self.pass_band = 200
        self.classes = [1, 2, 3, 4, 5, 6]
        self.window_length = 256
        self.window_padding = 32
        self.window_step = 64
        self.threshold = 0
        self.channels = 8
        self.num_classes = len(self.classes)

        self.jitter_ratio = 0.1
        self.scaling_ratio = 0.1
        self.num_permute = 8

class NinaproDB5Config:
    def __init__(self):
        self.url = [
            "http://ninapro.hevs.ch/download/file/fid/457",
            "http://ninapro.hevs.ch/download/file/fid/458",
            "http://ninapro.hevs.ch/download/file/fid/459",
            "http://ninapro.hevs.ch/download/file/fid/467",
            "http://ninapro.hevs.ch/download/file/fid/461",
            "http://ninapro.hevs.ch/download/file/fid/462",
            "http://ninapro.hevs.ch/download/file/fid/463",
            "http://ninapro.hevs.ch/download/file/fid/464",
            "http://ninapro.hevs.ch/download/file/fid/465",
            "http://ninapro.hevs.ch/download/file/fid/466",
        ]
        self.save_dir = "dataset/Ninapro_DB5"

        self.batch_size = 256
        self.partition = [0.6, 0, 0.4]

        self.sampling_freq = 200
        self.pass_band = None
        self.classes = [0, 6, 13, 14, 15, 16]
        self.window_length = 512
        self.window_padding = 32
        self.window_step = 64
        self.threshold = 0
        self.channels = 8
        self.num_classes = len(self.classes)

        self.jitter_ratio = 0.1
        self.scaling_ratio = 0.1
        self.num_permute = 8
        self.frequency_masking_ratio = 0.01
        self.frequency_masking_damp = 0.5

class ModelConfig:
    def __init__(self, dataset_config):
        # (B, C, T)
        self.span = dataset_config.window_length  # keeping up with window length

        self.input_channels = dataset_config.channels
        self.kernel_size = 8
        self.stride = 1
        self.final_out_channels = 128

        self.num_classes = dataset_config.num_classes
        self.dropout = 0.35
        self.conv_output_dim = self.span // 8
        self.feature_len = 128

        self.hidden_dim = 100
        self.timesteps = self.conv_output_dim // 4

        self.loss_temperature = 0.2

        self.classifier_hidden = [512, self.num_classes]
        self.classifier_dropout = 0.15

class TrainingConfig:
    def __init__(self, config):
        self.bag_of_metrics = {
            "accuracy": Accuracy(
                task="multiclass",
                num_classes=config.num_classes,
                average="micro",
            ),
            "f1": F1Score(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
            "precision": Precision(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
            "recall": Recall(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
            "auroc": AUROC(
                task="multiclass",
                num_classes=config.num_classes,
                average="macro",
            ),
        }
        self.log_save_dir = "run1"
        self.experiment_name = "TSTCC"

        self.mode = "pretrain_finetune"

        self.seed = 42
        self.pretrain_epoch = 100
        self.finetune_epoch = 100

        self.lr = 3e-4

        self.classifier_lr = 1e-4
        self.classifier_weight_decay = 3e-3

        self.per_class_samples = 100

        self.version = f"samples_{self.per_class_samples}_pe_{self.pretrain_epoch}_fe_{self.finetune_epoch}_seed_{self.seed}"


# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(A):
    if (len(A)) < 2:
        return 0
    else:
        MC = 0
        MS = 0
        for i,x in enumerate(A):
            DV = (x - A[i-1]) if i > 0 else 0
            MC = max(MC+DV,0)
            MS = max(MS, MC)

        return MS

print(solution([23171, 21011, 21123, 21366, 21013, 21367]))


# pylint: disable=redefined-outer-name
# pylint: disable=unused-argument

import json
from pathlib import Path
from typing import Any, Iterable
from unittest.mock import AsyncMock, call
from uuid import UUID, uuid4

import pytest
from models_library.projects import NodesDict, ProjectID
from models_library.projects_networks import NetworksWithAliases
from models_library.projects_nodes import Node
from pydantic import BaseModel, PositiveInt
from pytest_mock.plugin import MockerFixture
from simcore_service_director_v2.modules.projects_networks import (
    _get_networks_with_aliases_for_default_network,
    _send_network_configuration_to_dynamic_sidecar,
)

# UTILS

class MockedCalls(BaseModel):
    detach: list[Any]
    attach: list[Any]

class Example(BaseModel):
    existing_networks_with_aliases: NetworksWithAliases
    new_networks_with_aliases: NetworksWithAliases
    expected_calls: MockedCalls

    @classmethod
    def using(
        cls,
        existing: dict[str, Any],
        new: dict[str, Any],
        detach: list[Any],
        attach: list[Any],
    ) -> "Example":
        return cls(
            existing_networks_with_aliases=NetworksWithAliases.parse_obj(existing),
            new_networks_with_aliases=NetworksWithAliases.parse_obj(new),
            expected_calls=MockedCalls(detach=detach, attach=attach),
        )

def _node_id(number: int) -> str:
    return f"{UUID(int=number)}"

def _node_alias(number: int) -> str:
    return f"node_alias_{number}"

def _network_name(number: int) -> str:
    return f"network_{number}"

@pytest.fixture
def examples_factory(mock_scheduler: AsyncMock, project_id: ProjectID) -> list[Example]:
    return [
        # nothing exists
        Example.using(
            existing={},
            new={
                _network_name(1): {
                    _node_id(1): _node_alias(1),
                    _node_id(2): _node_alias(2),
                }
            },
            detach=[],
            attach=[
                call.attach_project_network(
                    node_id=UUID(_node_id(2)),
                    project_network=_network_name(1),
                    network_alias=_node_alias(2),
                ),
                call.attach_project_network(
                    node_id=UUID(_node_id(1)),
                    project_network=_network_name(1),
                    network_alias=_node_alias(1),
                ),
            ],
        ),
        # with existing network, remove node 2
        Example.using(
            existing={
                _network_name(1): {
                    _node_id(1): _node_alias(1),
                    _node_id(2): _node_alias(2),
                }
            },
            new={
                _network_name(1): {
                    f"{_node_id(1)}": _node_alias(1),
                }
            },
            detach=[
                call.detach_project_network(
                    node_id=UUID(_node_id(2)),
                    project_network=_network_name(1),
                ),
            ],
            attach=[],
        ),
        # remove node 2 and add node 2 with different alias
        Example.using(
            existing={
                _network_name(1): {
                    _node_id(1): _node_alias(1),
                    _node_id(2): _node_alias(2),
                }
            },
            new={
                _network_name(1): {
                    _node_id(1): _node_alias(1),
                    _node_id(2): _node_alias(3),
                }
            },
            detach=[
                call.detach_project_network(
                    node_id=UUID(_node_id(2)),
                    project_network=_network_name(1),
                ),
            ],
            attach=[
                call.attach_project_network(
                    node_id=UUID(_node_id(2)),
                    project_network=_network_name(1),
                    network_alias=_node_alias(3),
                ),
            ],
        ),
        # nothing happens when updates with the same content
        Example.using(
            existing={
                _network_name(1): {
                    _node_id(1): _node_alias(1),
                    _node_id(2): _node_alias(2),
                }
            },
            new={
                _network_name(1): {
                    _node_id(1): _node_alias(1),
                    _node_id(2): _node_alias(2),
                }
            },
            detach=[],
            attach=[],
        ),
    ]

@pytest.fixture
def mock_scheduler() -> AsyncMock:
    return AsyncMock()

@pytest.fixture
def mock_director_v0_client() -> AsyncMock:
    return AsyncMock()

@pytest.fixture
def rabbitmq_client() -> AsyncMock:
    return AsyncMock()

@pytest.fixture
def project_id() -> ProjectID:
    return uuid4()

@pytest.fixture
def dy_workbench_with_networkable_labels(mocks_dir: Path) -> NodesDict:
    dy_workbench_template = mocks_dir / "fake_dy_workbench_template.json"
    assert dy_workbench_template.exists()

    dy_workbench = json.loads(dy_workbench_template.read_text())

    parsed_workbench: NodesDict = {}

    for node_uuid, node_data in dy_workbench.items():
        node_data["label"] = f"label_{uuid4()}"
        parsed_workbench[node_uuid] = Node.parse_obj(node_data)

    return parsed_workbench

@pytest.fixture
def fake_project_id() -> ProjectID:
    return uuid4()

@pytest.fixture
def user_id() -> PositiveInt:
    return 1

@pytest.fixture
def mock_docker_calls(mocker: MockerFixture) -> Iterable[dict[str, AsyncMock]]:
    requires_dynamic_sidecar_mock = AsyncMock()
    requires_dynamic_sidecar_mock.return_value = True
    class_base = "simcore_service_director_v2.modules.dynamic_sidecar.scheduler._task.DynamicSidecarsScheduler"
    mocked_items = {
        "attach": mocker.patch(f"{class_base}.attach_project_network", AsyncMock()),
        "detach": mocker.patch(f"{class_base}.detach_project_network", AsyncMock()),
        "requires_dynamic_sidecar": mocker.patch(
            "simcore_service_director_v2.modules.projects_networks.requires_dynamic_sidecar",
            requires_dynamic_sidecar_mock,
        ),
    }

    yield mocked_items

async def test_send_network_configuration_to_dynamic_sidecar(
    mock_scheduler: AsyncMock,
    project_id: ProjectID,
    examples_factory: list[Example],
    mock_docker_calls: dict[str, AsyncMock],
) -> None:
    for example in examples_factory:
        await _send_network_configuration_to_dynamic_sidecar(
            scheduler=mock_scheduler,
            project_id=project_id,
            new_networks_with_aliases=example.new_networks_with_aliases,
            existing_networks_with_aliases=example.existing_networks_with_aliases,
        )

        mock_scheduler.assert_has_calls(example.expected_calls.attach, any_order=True)
        mock_scheduler.assert_has_calls(example.expected_calls.detach, any_order=True)

async def test_get_networks_with_aliases_for_default_network_is_json_serializable(
    mock_director_v0_client: AsyncMock,
    fake_project_id: ProjectID,
    dy_workbench_with_networkable_labels: dict[str, Any],
    user_id: PositiveInt,
    rabbitmq_client: AsyncMock,
    mock_docker_calls: dict[str, AsyncMock],
) -> None:
    assert await _get_networks_with_aliases_for_default_network(
        project_id=fake_project_id,
        user_id=user_id,
        new_workbench=dy_workbench_with_networkable_labels,
        director_v0_client=mock_director_v0_client,
        rabbitmq_client=rabbitmq_client,
    )


import pi_servo_hat
import time

# Function to rescale web interface controls
def scale(x, in_min, in_max, out_min, out_max):
	return (x - in_min)*(out_max - out_min)/(in_max - in_min) + out_min

########################################################################
# Main Function:
########################################################################

# Initialize Servo Hat
servohat = pi_servo_hat.PiServoHat()

# Restart Servo Hat
servohat.restart()

pan_setting_old = 0
tilt_setting_old = 0

while True:
	pipein = open("/var/www/html/FIFO_pipan", 'r')
	line = pipein.readline()
	line_array = line.split(' ')
	if line_array[0] == "servo":

		# Rescales Left/Right position values
		#	web controls:		Left = 250;	Right = 50
		#	library controls:	Left =  90;	Right =  0
		pan_setting = scale(int(line_array[1]), 50, 250, 0, 90)

		# Rescales Up/Down position values
		#	web controls:		Down = 220;	Up = 80
		#	library controls:	Down =  90;	Up =  0
		tilt_setting = scale(int(line_array[2]), 80, 220, 0, 90)

		if pan_setting != pan_setting_old:
			pan_setting_old = pan_setting
			servohat.move_servo_position(0, pan_setting, 90)
			time.sleep(.05)

		if tilt_setting != tilt_setting_old:
			tilt_setting_old = tilt_setting
			servohat.move_servo_position(1, tilt_setting, 90)
			time.sleep(.05)

pipein.close()


import seaborn as sns
from matplotlib import pyplot as plt
import tools
import numpy as np
import pandas as pd

def plot_missrate_comp():
    processed_row = tools.load_pkl('outputs/feature_explore[ards@origin]/row_missrate.pkl').flatten()
    processed_col = tools.load_pkl('outputs/feature_explore[ards@origin]/col_missrate.pkl').flatten()
    raw_row = tools.load_pkl('outputs/feature_explore[raw@version]/row_missrate.pkl').flatten()
    raw_col = tools.load_pkl('outputs/feature_explore[raw@version]/col_missrate.pkl').flatten()
    row_data = np.concatenate([processed_row, raw_row], axis=0)
    col_data = np.concatenate([processed_col, raw_col], axis=0)
    for data, label in zip([row_data, col_data], ['row', 'col']):
        df = pd.DataFrame(data, columns=['data'])
        df['source'] = 'raw'
        lens = len(processed_row) if label == 'row' else len(processed_col)
        df.loc[:lens, 'source'] = 'processed'
        sns.histplot(df, x='data', hue='source', bins=20, stat='proportion', common_norm=False, shrink=0.95, element='bars', edgecolor=None)
        plt.xlabel(f'{label} missrate')
        plt.savefig(f'test_plot/{label}_missrate.png')
        plt.close()

if __name__ == '__main__':
    plot_missrate_comp()


"""
A basic CNN model
/**
 * @author Xinping Wang
 * @email [x.wang3@student.tue.nl]
 * @create date 2021-09-11 09:32:41
 * @modify date 2021-09-11 09:32:41
 * @desc [description]
 */
"""

import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import torchvision
from torchvision import datasets, transforms
from torch.utils.data import DataLoader
import numpy as np

from imageio import imread

classes = ("W", "R", "N1", "N2", "N3")

class Passthrough(nn.Module):
    def __init__(self, n_channels=8, n_classes=5):
        super().__init__()

        self.conv1 = nn.Conv1d(8, 16, 15)
        self.conv2 = nn.Conv1d(16, 32, 9)
        self.conv3 = nn.Conv1d(32, 64, 5)
        self.conv4 = nn.Conv1d(64, 128, 3)
        self.conv5 = nn.Conv1d(128, 128, 3)

        self.flat = nn.Flatten(1, -1)
        self.fc = nn.Linear(128*5, 5)
        self.maxpool = nn.MaxPool1d(5, stride=5)
        self.leakyrelu = nn.LeakyReLU(0.01)
        self.dropout = nn.Dropout(p=0.1)
        self.softmax = nn.LogSoftmax()
        self.avgpool = nn.AdaptiveAvgPool1d(5)

    def forward(self, x):
        x = self.dropout(self.maxpool(self.leakyrelu(self.conv1(x))))
        x = self.dropout(self.maxpool(self.leakyrelu(self.conv2(x))))
        x = self.dropout(self.maxpool(self.leakyrelu(self.conv3(x))))
        x = self.dropout(self.maxpool(self.leakyrelu(self.conv4(x))))
        x = self.avgpool(self.conv5(x))
        x = self.softmax(self.fc(self.flat(x)))

        # x = nn.MaxPool1d(5,5)
        # x = F.relu(self.conv2(x))
        # x = F.relu(self.conv3(x))
        # x = F.relu(self.conv4(x))
        # x = F.relu(self.conv5(x))
        # x = F.softmax(self.fc(self.flat(x)), dim=1)

        return x


class Node:
    def __init__(self, value = None):
        self.val = value
        self.next = None
#mergesort na seriach naturalnych
def Merge(L1,L2):
    inv=0
    if L1 is None:
        return L2
    if L2 is None:
        return L1
    if L1.val>L2.val:
        L1,L2=L2,L1
        inv+=1
    head=L1
    L1=L1.next
    curr=head
    curr.next=None
    while L1 is not None and L2 is not None:
        if L1.val>L2.val:
            inv+=1
            L1,L2=L2,L1
        curr.next=L1
        L1=L1.next
        curr=curr.next
        curr.next=None
    if L1 is None:
        curr.next=L2
    else:
        curr.next=L1
    return head

def mergeSort(L):
    heads=[]
    while L is not None:
        head=L
        curr=L
        while curr.next is not None and curr.val<curr.next.val:
            curr=curr.next
        heads.append(head)
        L=curr.next
        curr.next=None
        print("idzie")

    heads2=[]
    inv=0
    while len(heads)>1:
        print("idzie do merga",len(heads))
        merged=Merge(heads[0],heads[1])

        # print(heads,heads2)
        heads2.append(merged)
        # print(heads,heads2)
        heads=heads[2:]
        # print(heads,heads2)
        heads2.extend(heads)
        # print(heads,heads2)
        heads=heads2[:]
        # print(heads,heads2)
        heads2=[]
    return heads[0],inv
arr = [1, 20, 6, 4, 5]
lista=Node(1)
lista2=Node(20)
lista3=Node(6)
lista4=Node(4)
lista5=Node(5)
lista.next=lista2
lista2.next=lista3
lista3.next=lista4
lista4.next=lista5
print(lista)
print(mergeSort(lista))


# Citations according to https://scicrunch.org/resources
"""
    NOTES:

    - scicrunch API ONLY recognizes RRIDs from SciCrunch registry of tools (i.e. with prefix "SCR")
    - scicrunch web search handles ALL RRIDs (see below example of citations from other)
    - scicrunch API does NOT uses 'RRID:' prefix in rrid request parameters

"""

import re

def split_citations(citations: list[str]) -> list[tuple[str, str]]:
    def _split(citation: str) -> tuple[str, str]:
        if "," not in citation:
            citation = citation.replace("(", "(,")
        name, rrid = re.match(r"^\((.*),\s*RRID:(.+)\)$", citation).groups()
        return name, rrid

    return list(map(_split, citations))

# http://antibodyregistry.org/AB_90755
ANTIBODY_CITATIONS = split_citations(["(Millipore Cat# AB1542, RRID:AB_90755)"])

# https://www.addgene.org/44362/
PLAMID_CITATIONS = split_citations(["(RRID:Addgene_44362)"])

#  MMRRC,
# catalog https://www.mmrrc.org/catalog/cellLineSDS.php?mmrrc_id=26409
#         https://scicrunch.org/resolver/RRID:MMRRC_026409-UCD.json
#
# As of May 2022, changed proper_citation change from
#  '(MMRRC Cat# 026409-UCD, RRID:MMRRC_026409-UCD)' to
#  'RRID:MMRRC_026409-UCD'
#
ORGANISM_CITATIONS = split_citations(["(RRID:MMRRC_026409-UCD)"])

# https://web.expasy.org/cellosaurus/CVCL_0033
# As of May 2022, name changed from 'ATCC Cat# HTB-30' to 'AddexBio Cat# C0006007/65'
CELL_LINE_CITATIONS = split_citations(["(AddexBio Cat# C0006007/65, RRID:CVCL_0033)"])

#
#  WARNING: Since Sep.2021, the order of the resolved hits list returned by
#  https://scicrunch.org/resolver/RRID:CVCL_0033.json changes per call and
#  sometimes (BCRJ Cat# 0226, RRID:CVCL_0033) appears as first hit instead

# https://scicrunch.org/resources/Tools/search?q=SCR_018315&l=SCR_018315
TOOL_CITATIONS = split_citations(
    [
        "(CellProfiler Image Analysis Software, RRID:SCR_007358)",
        "(Jupyter Notebook, RRID:SCR_018315)",
        "(Python Programming Language, RRID:SCR_008394)",
        "(GNU Octave, RRID:SCR_014398)",
        "(o²S²PARC, RRID:SCR_018997)",
    ]
)

NOT_TOOL_CITATIONS = (
    ANTIBODY_CITATIONS + PLAMID_CITATIONS + ORGANISM_CITATIONS + CELL_LINE_CITATIONS
)


import tensorflow as tf
import numpy as np
import os,glob,cv2
import sys,argparse

class Predictor(object):
    def __init__(self, graph_path, model_path):
        ## Let us restore the saved model
        sess = tf.Session()
        # Step-1: Recreate the network graph. At this step only graph is created.
        saver = tf.train.import_meta_graph(graph_path)
        # Step-2: Now let's load the weights saved using the restore method.
        saver.restore(sess, tf.train.latest_checkpoint(model_path))

        # Accessing the default graph which we have restored
        graph = tf.get_default_graph()

        # Now, let's get hold of the op that we can be processed to get the output.
        # In the original network y_pred is the tensor that is the prediction of the network
        y_pred = graph.get_tensor_by_name("y_pred:0")

        ## Let's feed the images to the input placeholders
        x= graph.get_tensor_by_name("x:0")
        y_true = graph.get_tensor_by_name("y_true:0")

        self._sess = sess
        self._y_pred = y_pred
        self._x = x
        self._y_true = y_true

    def predictClass(self, frame, num_classes):
        height, width, num_channels = frame.shape
        images = []
        images.append(frame)
        images = np.array(images, dtype=np.uint8)
        images = images.astype('float32')
        x_batch = images.reshape(1, height, width, num_channels)
        y_test_images = np.zeros((1, num_classes))

        ### Creating the feed_dict that is required to be fed to calculate y_pred
        feed_dict_testing = {self._x: x_batch, self._y_true: y_test_images}
        result=self._sess.run(self._y_pred, feed_dict=feed_dict_testing)
        result = np.argmax(result, axis=1)
        # result is of this format [probabiliy_of_rose probability_of_sunflower]
        return result[0]


import pygame
import random
import rospy
import math
from geometry_msgs.msg import TwistStamped
from geometry_msgs.msg import PoseStamped
from armf import armtakeoff

rospy.init_node('make_a_circle', anonymous=True)

current_pos = PoseStamped()

def main():
    pygame.init()
    screen = pygame.display.set_mode((640, 480))
    clock = pygame.time.Clock()

    x_curser1 = 160
    y_curser1 = 240
    x_curser2 = 480
    y_curser2 = 240
    mode= ''
    count = 0
    radius = 10
    screen.fill((0, 0, 0))

    color_curser1 = (0,255,0)
    color_curser2 = (0,255,0)
    pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius)
    pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius)

    arm = armtakeoff()
    arm.arm()
    arm.takeoff()

    while True:

        screen.fill((0, 0, 0))
        x_curser1 = 160
        y_curser1 = 240
        x_curser2 = 480
        y_curser2 = 240

        pressed = pygame.key.get_pressed()

        alt_held = pressed[pygame.K_LALT] or pressed[pygame.K_RALT]
        ctrl_held = pressed[pygame.K_LCTRL] or pressed[pygame.K_RCTRL]

        for event in pygame.event.get():

            # determin if X was clicked, or Ctrl+W or Alt+F4 was used
            if event.type == pygame.QUIT:
                return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_w and ctrl_held:
                    return
                if event.key == pygame.K_F4 and alt_held:
                    return
                if event.key == pygame.K_ESCAPE:
                    return

                # determine if a letter key was pressed
                if event.key == pygame.K_w:
                    mode = 'up'
                elif event.key == pygame.K_s:
                    mode = 'down'
                elif event.key == pygame.K_d:
                    mode = 'right'
                elif event.key == pygame.K_a:
                    mode = 'left'
                elif event.key == pygame.K_SPACE:
                    mode = 'jump'
                elif event.key == pygame.K_q:
                    mode = 'yaw'
                elif event.key == pygame.K_e:
                    mode = 'yawri8'
                elif event.key == pygame.K_LCTRL:
                    mode = 'low'
                elif event.key == pygame.K_h:
                    mode = 'hold'

        color_curser1 = (255,0,0)
        color_curser2 = (255,0,0)
        color_curser3 = (0,0,255)
        color_curser4 = (0,0,255)

        pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius)
        pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius)

        x_curser1,y_curser1,x_curser2,y_curser2 = curserControl(screen,x_curser1,y_curser1,x_curser2,y_curser2,mode,count,color_curser1,color_curser1,radius)

        pygame.draw.circle(screen, color_curser3, (x_curser1, y_curser1), radius)
        pygame.draw.circle(screen, color_curser4, (x_curser2, y_curser2), radius)

        pygame.display.flip()

        clock.tick(60)

def curserControl(screen,x_curser1,y_curser1,x_curser2,y_curser2,mode,count,color_curser1,color_curser2,radius):

    publish_velocity=rospy.Publisher('/mavros/setpoint_velocity/cmd_vel', TwistStamped,queue_size=20)
    vel=TwistStamped()

    if mode == 'up':

        vel.twist.linear.x= 0.8
        vel.twist.linear.z= 0
        publish_velocity.publish(vel)
        vel.twist.linear.x= 0
        y_curser1= y_curser1 -20
        pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius)
        print("up")
    elif mode == 'down':
        vel.twist.linear.x= -0.8
        vel.twist.linear.z= 0
        publish_velocity.publish(vel)
        vel.twist.linear.x= 0
        y_curser1= y_curser1 +20
        pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius)
        print("down")
    elif mode == 'right':
        vel.twist.linear.z= 0
        vel.twist.linear.y= -0.8
        publish_velocity.publish(vel)
        vel.twist.linear.y= 0
        x_curser1= x_curser1 +20
        pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius)
        print("right")
    elif mode == 'left':

        vel.twist.linear.y= 0.8
        vel.twist.linear.z= 0
        publish_velocity.publish(vel)
        vel.twist.linear.y= 0
        x_curser1= x_curser1 -20
        pygame.draw.circle(screen, color_curser1, (x_curser1, y_curser1), radius)
        print("left")
    elif mode == 'jump':

        vel.twist.linear.z= 1
        publish_velocity.publish(vel)
        vel.twist.linear.z= 0
        y_curser2= y_curser2 -20
        pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius)

        print("jump")
    elif mode == 'low':

        vel.twist.linear.z= -0.5
        publish_velocity.publish(vel)
        vel.twist.linear.z= 0
        y_curser2= y_curser2 +20
        pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius)
        print("low")

    elif mode == 'yaw':

        vel.twist.angular.z= 0.8
        vel.twist.linear.z= 0
        publish_velocity.publish(vel)
        vel.twist.linear.z= 0
        x_curser2= x_curser2 -20
        pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius)
        print("yawleft")

    elif mode == 'yawri8':

        vel.twist.angular.z= -0.8
        vel.twist.linear.z= 0
        publish_velocity.publish(vel)
        vel.twist.linear.z= 0
        x_curser2= x_curser2 +20
        pygame.draw.circle(screen, color_curser2, (x_curser2, y_curser2), radius)
        print("yawri8")
    elif mode == 'hold':

        vel.twist.angular.z= 0
        publish_velocity.publish(vel)
        print("hold")

    return x_curser1, y_curser1 ,x_curser2, y_curser2

main()


import random

from discord import Colour

"""
These are some presets configs, that are predefined
and normally dont need any changes (Thats why they are not in the config file
"""

bottest = True  # decides if the bot checks other bots messages

ignorfiles = ['image/gif', 'image/jpeg']  # Content types to ignor. Check out https://en.wikipedia.org/wiki/Media_type

checkorange = 1  # if more or equal than that checks are positive the embed will be orange

checkred = 3  # if more or equal than that checks are positive the embed will be red

helpembedcolour = Colour(random.randint(0, 16777215))


from nose.tools import *
import wntr
from os.path import abspath, dirname, join

testdir = dirname(abspath(__file__))
datadir = join(testdir,'..','..','..','examples','networks')

def test_isOpen():
    enData = wntr.pyepanet.ENepanet()
    enData.inpfile = join(datadir,'Net1.inp')
    assert_equal(0, enData.isOpen())
    enData.ENopen(enData.inpfile,'tmp.rpt')
    assert_equal(1, enData.isOpen())

def test_ENgetcount():
    enData = wntr.pyepanet.ENepanet()
    enData.inpfile = join(datadir,'Net1.inp')
    enData.ENopen(enData.inpfile,'tmp.rpt')
    nNodes = enData.ENgetcount(wntr.pyepanet.EN_NODECOUNT)
    assert_equal(11, nNodes)
    nLinks = enData.ENgetcount(wntr.pyepanet.EN_LINKCOUNT)
    assert_equal(13, nLinks)


import os
import sys
import mock
import unittest
import pkg_resources
from pybkick.kick import kick, main as kick_main, MissingSourceCode
from pybkick.pyboard import Pyboard

class TestKick(unittest.TestCase):
    """Test that we can kick code over to the PyBoard
    """

    def testBasicKick(self):
        test_data_path = pkg_resources.resource_filename(__name__, 'test_data')

        kick(
             port='/dev/ttyACM0',
             src=test_data_path,
             entry_point=None
        )

    def testKickFromCommandLine(self):
        test_data_path = pkg_resources.resource_filename(__name__, 'test_data')

        fake_argv = [sys.argv[0], '--src=%s' % test_data_path, '--dst=tmp']
        with mock.patch('sys.argv', fake_argv):
            fake_kick = mock.Mock()
            with mock.patch('pybkick.kick', fake_kick):
                kick_main()
                fake_kick.assert_called_once()

    def testKickMissingDirectory(self):
        missing_test_data_path = os.path.join(pkg_resources.resource_filename(__name__, 'test_data'), 'missing')

        with self.assertRaises(MissingSourceCode):
            kick(
                 port='/dev/ttyACM0',
                 src=missing_test_data_path,
                 dst='tmp',
                 entry_point=None
            )

    def testKickTestData(self):
        test_dir = pkg_resources.resource_filename(__name__, 'test_data')
        port = '/dev/ttyACM0'
        kick(port=port,
             src=test_dir
        )

        pb = Pyboard(port)
        with pb.raw_repl():
            for filename in ['a.txt', 'b.txt']:
                self.assertTrue(pb.file_exists(filename))
                pb.rm(filename)
                self.assertFalse(pb.file_exists(filename))


import pytumblr

class Tumblr:
    def __init__(
        self,
        consumer_key: str,
        consumer_secret: str,
        oauth_token: str,
        oauth_secret: str,
        blog_name: str,
    ):
        self.client = pytumblr.TumblrRestClient(
            consumer_key, consumer_secret, oauth_token, oauth_secret
        )
        self.blog_name = blog_name

    def post_photo(self, photo: str, description: str, tags: list):
        self.client.create_photo(
            self.blog_name, state="published", tags=tags, tweet=description, data=photo
        )


from layers.domain_layer.repositories import AccountRepository
from layers.domain_layer.repositories import TokenRepository
from libs.cutoms.singleton import Singleton

class AuthSystem(object):
    __metaclass__ = Singleton

    def token_to_user_id(self, access_token):
        account_id = self.token_to_account_username(access_token)
        return AccountRepository().get(account_id).user_id

    def token_to_account_username(self, access_token):
        return TokenRepository().get(access_token).account_username


from flask import request
from flask_restx import Resource, Namespace, abort
from marshmallow import ValidationError

from implemented import user_service
from tools.jwt_token import JwtSchema, JwtToken
from views.users import LoginValidator

auth_ns = Namespace('auth')

@auth_ns.route('/')
class AuthView(Resource):
    def post(self):
        try:
            data = LoginValidator().load(request.json)
            user = user_service.get_by_name(data["username"])
            if not user:
                abort(404)
            token_data = JwtSchema().load({"user_id": user.id, "role": user.role})
            return JwtToken(token_data).get_tokens(), 201
        except ValidationError:
            abort(400)

    def put(self):
        try:
            refresh_token = request.json["refresh_token"]
            data = JwtToken.decode_token(refresh_token)
            data.pop("exp", None)
            token_data = JwtSchema().load(data)
            user = user_service.get_one(token_data["user_id"])
            if not user:
                abort(404)
            token_data = JwtSchema().load({"user_id": user.id, "role": user.role})
            return JwtToken(token_data).get_tokens(), 201
        except Exception as e:
            abort(400)


import asyncio
from typing import *
from urllib.parse import urlencode
from datetime import datetime
from pprint import pformat as pf
import logging
logging.basicConfig(format='%(asctime)s %(message)s')
import jikanpy
from enum import Enum
from copy import copy, deepcopy
from pprint import pprint
import traceback

import aiohttp
import dotenv
import asyncio
from fuzzywuzzy import fuzz
from expiring_dict import ExpiringDict

from core import getLogger, stopwatch

log = getLogger(__name__)

class MALRatings(Enum):
    g = "G - All Ages"
    pg = "PG - Children"
    pg_13 = "PG-13 - Teens 13 or older"
    r = "R - 17+ (violence & profanity) "
    r_plus = "R+ - Mild Nudity 17+"
    rx = "Rx - Hentai 18+"

class MALTypes(Enum):
    ANIME = 1
    MANGA = 2

class MyAnimeListAIOClient:
    """Wrapper for MyAnimeList API Endpoint"""
    client_id: str = ""
    TTL = 60*60
    response_cache = ExpiringDict(ttl=TTL)

    def __init__(
        self,
        client_id: str = None,
    ):
        """A wrapper for the Non-user based mal api endpoints (-> no oauth needed)"""
        self.log = logging.getLogger(__name__)
        self.log.setLevel(logging.INFO)
        self._id = client_id or self.client_id or dotenv.dotenv_values()["ID"]
        if not self._id and not self.client_id:
            raise RuntimeError(
                "Client id has to be passed into the constructor or in the .env file under key `ID`. Consider calling `set_credentails`"
            )
        self._base_url = r"https://api.myanimelist.net/v2"
        self._session = None

    @classmethod
    def set_credentials(cls, client_id: str):
        """"set the client id"""
        cls.client_id = client_id

    @property
    def session(self) -> aiohttp.ClientSession:
        """Get AioHTTP session by creating it if it doesn't already exist"""
        if not self._session or self._session.closed:
            self._session = aiohttp.ClientSession()
        return self._session

    async def _make_request(
        self,
        endpoint: str,
        value: Optional[str] = None,
        optional_query: Dict[str, str] = None,
    ) -> Dict[str, Any]:
        query = None
        if value and not value.startswith("/"):
            value = "/" + value
        if optional_query:
            query = f"?{urlencode(optional_query)}"
        url = f"{self._base_url}/{endpoint}{value or ''}{query or ''}"
        async with self.session.get(url, headers=self.headers) as resp:
            json = await resp.json(encoding="utf-8")
        await self._session.close()
        self.log.debug(f"request: {url}")
        self.log.debug(f"response: {pf(json)}")
        if not resp.ok:
            raise RuntimeError(f"{url} returned status code {resp.status}")
        return json

    @property
    def headers(self) -> Dict[str, str]:
        if not self._id:
            raise RuntimeError("Client id has to be passed into the constructor or in the .env file under key `ID`")
        return {"X-MAL-CLIENT-ID": self._id}

    async def fetch_anime(
        self,
        id: int
    ) -> Dict[str, Any]:
        """fetch an Anime by it's ID

        Args:
        -----
        id : int
            the mal ID of that anime
        """
        fields = (
            "id,title,main_picture,alternative_titles,"
            "start_date,end_date,synopsis,mean,rank,popularity,"
            "num_list_users,num_scoring_users,nsfw,created_at,"
            "updated_at,media_type,status,genres,my_list_status,"
            "num_episodes,start_season,broadcast,source,"
            "average_episode_duration,rating,pictures,background,"
            "related_anime,related_manga,recommendations,studios,statistics,"
            "average_episode_duration,opening_themes,ending_themes"
        )
        resp = await self._make_request(
            endpoint="anime",
            value=str(id),
            optional_query={"fields": fields}
        )
        return resp

    async def _search(self):
        pass

    async def search_anime(self, query: str, include_nsfw=True, fallback: bool = False) -> Dict[str, Any]:
        """search for anime by name

        Args:
        -----
        query : str
            the query to search for
        include_nsfw : bool
            whether to include nsfw results
        fallback : bool
            whether or not to limit the query to 50 chars
        Returns:
        --------
        Dict[str, Any]
            the response json
        """
        try:
            resp = self.response_cache[query]
            return deepcopy(resp)
        except KeyError:
            pass
        fields = (
            "id,title,main_picture,alternative_titles,"
            "start_date,end_date,synopsis,mean,rank,popularity,"
            "num_list_users,num_scoring_users,nsfw,created_at,"
            "updated_at,media_type,status,genres,my_list_status,"
            "num_episodes,start_season,broadcast,source,"
            "average_episode_duration,rating,pictures,background,"
            "related_anime,related_manga,recommendations,studios,statistics,"
            "average_episode_duration,opening_themes,ending_themes"
        )
        a = datetime.now()
        kwargs = {"nsfw": "true" if include_nsfw else "false"}
        try:
            resp = await self._make_request(
                endpoint="anime",
                optional_query={
                    "q": query,
                    "fields":fields,
                    "limit":"50",
                    **kwargs
            })
        except RuntimeError as e:
            if fallback:
                log.warning(f"Error while fetching anime - title len = {len(query)}")
                log.warning(traceback.format_exc())
                return None
            else:
                log.warning(f"fallback search for title {query}")
                return await self.search_anime(query[:50], include_nsfw, True)
        log.info(f"fetched {len(resp['data'])} anime in {(datetime.now() - a).total_seconds():.2f}s")
        self.response_cache.ttl(query, deepcopy(resp), self.TTL)
        return deepcopy(resp)


import MSGrid
import time

def printgrid(arr):
	print("  ",end="")
	index = len(arr[0])
	for x in range(index):
		print(str(x)+" ", end="")
	print()
	index = 0
	for i in arr:
		print(index,end="")
		index+=1
		for j in i:
			print("|"+str(j), end="")
		print("|\n")

while(1):
	try:
		n = int(input("How tall should the grid be? >> "))
		m = int(input("How wide should the grid be? >> "))
		if(n<=0 or m<=0): raise IndexError
		break
	except IndexError:
		print("must be positive.")
	except ValueError:
		print("must be valid integers.")
numMines = int((n*m)/6)

grid = MSGrid.gridInitialize(n, m, numMines)
remainingBlocks = n*m

mask = MSGrid.maskInitialize(n, m)

def sweep(y, x):
	if( y < 0 or x < 0 or y >= n or x >= m):
		return 0
	if mask[y][x] != ' ':
		return 0
	if(grid[y][x] == 9):
		print("BOOM! YOU DIED")
		printgrid(grid)
		input("exit >>")
		exit(0)
	mask[y][x] = grid[y][x]
	if(grid[y][x] > 0):
		return 1
	retval = 1
	for horz1 in [-1, 0, 1]:
		retval += sweep(y-1, x+horz1)
	for horz2 in [-1, 1]:
		retval += sweep(y, x+horz2)
	for horz3 in [-1, 0, 1]:
		retval += sweep(y+1, x+horz3)
	return retval

print("top left corner is 0,0. Enter coordinates to check for mines.")
start = time.time()
while(1):
	print("time taken so far:", time.time()-start)
	try:
		printgrid(mask)
		x = int(input("Enter an x coordinate >> "))
		y = int(input("\nEnter a y coordinate >> "))
		if x >= m or y >= n: raise IndexError
		flagFlag = input("type F to toggle a flag or anything else to sweep the block: >>")
		if(flagFlag == "F" or flagFlag == "f"):
			if type(mask[y][x]) is not int:
				if mask[y][x] == 'F':
					mask[y][x] = ' '
					print("flag toggled off.")
				else:
					mask[y][x] = 'F'
					print("flag toggled on.")
			continue

	except IndexError:
		print("Input index too large. Try again.\n")
		continue
	except ValueError:
		print("Input must be a valid integer. Try again.\n")
		continue
	remainingBlocks -= sweep(y, x)
	if(remainingBlocks == numMines):
		print("all mines found!")
		end = time.time()
		timeTaken = int(end - start)
		print("total time taken:", timeTaken,"seconds")

		name = input("Enter your name to be entered into the scoreboard. >>")
		f = open("scores.txt", "a")
		f.write(name + ","+str(x)+"x"+str(y)+": "+str(timeTaken)+" seconds\n")

		f = open("scores.txt", "r")
		print("scores:")
		for line in f: print(line, end="")
		exit(0)


from flask import Flask
import os.path
app = Flask(__name__)

@app.route("/")
def hello():
    if os.path.exists('/volume/test'):
        return "Hello from pvc!"
    return "Hello World!"

if __name__ == "__main__":
    app.run()


from django.contrib import admin
app_name = 'admin'
# Register your models here.
#当前目录下models
from myapp.models import Grades, Students

#创建班级的时候同时创建2个学生
class StudentInfo(admin.TabularInline):
    model = Students
    extra = 2
@admin.register(Grades)
class GradesAdmin(admin.ModelAdmin):
    inlines = [StudentInfo,]
    list_display = ('pk', 'gname', 'gdate','ggirlnum','gboynum','isDelete',)
    list_filter = ('gname',)
    search_fields = ('gname',)
    list_per_page = 5
    #添加修改页属性
    fields = ('ggirlnum', 'gboynum', 'gname', 'gdate',)
   #fieldsets = []

@admin.register(Students)
class StudentsAdmin(admin.ModelAdmin):
    def gender(self):
        if self.sgender:
            return '男'
        else:
            return '女'
    #列名
    gender.short_description = '性别'
    list_display = ('pk', 'sname', 'sage',gender,'scontend', 'sgrade', 'isDelete',)
    list_per_page = 5
    #actions_on_top = Flase

#admin.site.register(Grades, GradesAdmin)
#admin.site.register(Students,StudentsAdmin)


from simple.PIL import Image

image = Image.open('strawberries.png')

for pixel in image:
    avg = (pixel.red + pixel.green + pixel.blue) / 3
    if pixel.red < pixel.blue + 40:
        pixel.red = avg
        pixel.green = avg
        pixel.blue = avg
    if pixel.red < pixel.green + 40:
        pixel.red = avg
        pixel.green = avg
        pixel.blue = avg

image.save('output.png')


import random
import math

num_teams = 32
country_list = {"england" : ["English", 4], "france" : ["French", 4],
                "spain" : ["Spanish", 4], "germany" : ["German", 4],
                "italy" : ["Italian", 4], "portugal" : ["Portuguese", 3],
                "russia" : ["Russian", 2], "dutch" : ["Dutch", 1],
                "turkey" : ["Turkish", 1], "scotland" : ["Scottish", 1],
                "greece" : ["Greek", 1], "poland" : ["Polish", 1],
                "belgium" : ["Belgian", 1]}
group_and_teams = {"GroupA" : {}, "groupB" : {}, "groupC" : {}, "groupD" : {},
                   "groupE" : {}, "groupF" : {}, "groupG" : {}, "groupH" : {}}

print("\tUEFA Champions League Draw Simulator\n")
print("Enter teams to make your very own UEFA Champions League.")
input("Press the enter key to begin.")
x = 0
for country in country_list:
    x += country_list[country][1]
x = math.ceil(x / len(group_and_teams))

list_teams = {}
for country in country_list:
    for x in range(country_list[country][1]):
        list_teams[input("Please enter an {} team: ".format(country_list[country][0]))] = country

def find_open_slot(new_team):
    good = True
    group_chosen = False
    rand = random.sample(list(group_and_teams), 1)[0]
    while group_chosen == False:
        if len(group_and_teams[rand]) > 0:
            for listed_team in group_and_teams[rand]:
                if new_team == listed_team or list_teams[new_team][1] == group_and_teams[rand][listed_team]:
                    good = False
        else:
            group_chosen = True
            return rand

        if good == False:
            rand = random.sample(list(group_and_teams), 1)[0]
        else:
            group_chosen = True
            return rand

for team in list_teams:
    group = find_open_slot(team)
    teams = group_and_teams[group]
    teams[team] = list_teams[team]

print("\nAssembling groups...\n")
input("Groups complete. Press the enter key to view.")

for group in group_and_teams:
    for teams in group_and_teams[group]:
        print("{}: team: {}, Country: {}".format(group,teams, group_and_teams[group][teams]))

input("\n\nPress the enter key to exit.")


"""If a number is equal to the sum of its factors,
the number is called the perfect number, for example, 6, because 6=1+2+3.
Program and print all the perfect numbers within 1000."""

for i in range(1, 1001):
    s = 0
    for j in range(1, i):
        if i % j == 0:
            s += j
    if s == i:
        print('\n', i, " ", end="")
        print("it's factors are ", end="")
        for j in range(1,i):
            if i % j == 0:
                print(j, end = " ")


import socket
import threading

bind_ip = '0.0.0.0'
bind_port = 9999

server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

server.bind((bind_ip,bind_port))

server.listen(5)

print("[*] Listening on %s: %d" % (bind_ip,bind_port))

def handle_client(client_socket):
    #exibe o que o cliente enviar
    request = client_socket.recv(1024)
    resposta = request.decode()
    print('[*] Received: %s ' % resposta)

    mensagem = "ACK!"
    msgByte = mensagem.encode()
    #envia um pacote de volta
    client_socket.send(msgByte)

    client_socket.close()

while True:
    client, addr = server.accept()
    print("[*] Accepted connection from %s:%d " % (addr[0],addr[1]))
    cliente_handler = threading.Thread(target=handle_client, args=(client,))
    cliente_handler.start()


from string import ascii_lowercase

from behave import given, then
from toolium.utils.dataset import map_param

from common.utils import assert_arrays_equal, payload_to_table_format, replace_param

@given("there is {chore_types:d} chore type")
@given("there are {chore_types:d} chore types")
def step_create_chore_types(context, chore_types):
    for i in range(chore_types):
        raw_data = {
            "id": f"ct-{ascii_lowercase[i]}",
            "name": f"ct-{ascii_lowercase[i]}",
            "description": f"description{i+1}",
        }
        context.execute_steps(
            f"""
            Given I use the admin API key
            When I send a request to the Api resource "createChoreType" with body params
            {payload_to_table_format(raw_data)}
            Then the response status code is "200"
            And I clear the token
            """
        )

@then('the response contains the chores "{ids}"')
def step_response_contains_chores(context, ids):
    ids = replace_param(ids)
    if not ids:
        ids = []
    elif isinstance(ids, str):
        ids = list(map(int, ids.replace(" ", "").split(",")))
    elif isinstance(ids, int):
        ids = [ids]

    original = map_param("[CONF:examples.simple_chore_types]")
    res_json = context.res.json()

    for field_name in ("completed_at", "created_at"):
        for item in res_json:
            del item[field_name]

    expected = [original[x - 1] for x in ids]

    assert_arrays_equal(expected, res_json)


import os
from pathlib import Path

def get_last_n_files_in_dir(dir_path, n, recurse=False, *args, **kwargs):
    method_str = "rglob" if recurse else "glob"
    p = Path(dir_path)
    fluid_glob = getattr(p, method_str)

    l = [(i, i.stat().st_mtime) for i in fluid_glob("*.*")]
    l.sort(key=lambda x: x[0], **kwargs)
    l_ = l[:n]

    return [i[0] for i in l_]

def delete_last_n_files_in_dir(dir_path, *args, **kwargs):
    fpaths = get_last_n_files_in_dir(dir_path, *args, **kwargs)
    for p in fpaths:
        os.remove(p)


def main():
    for i in range(int(input())):
        s = input()
        if len(s) > 10:
            print(f"{s[0]}{len(s)-2}{s[-1]}")
        else:
            print(s)

if __name__ == '__main__':
    main()


import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
# nodes=['A','B','C','D','E','F','1']

dataset = pd.read_csv("./topology.csv", header=None)
lenth = dataset.shape[0]
G=nx.Graph()
edges=[]
for i in range(lenth):
    edges.append((dataset.values[i, 0], dataset.values[i, 1]))

r=G.add_edges_from(edges)

# shortest_way=nx.shortest_path(G,"F","D")
# print(shortest_way)
#
# nx.draw(G, with_labels=True,node_color='r', node_size=50,)
# plt.show()

options = {"node_color": "red", "node_size": 300, "linewidths": 0, "width": 0.1, "with_labels": True}
pos = nx.spring_layout(G, random_state=1969)  # Seed for reproducible layout
nx.draw(G, pos, **options)
plt.show()


liste_mois = [
    ('janvier', 31),
    ('fevrier', 28),
    ('mars', 31),
    ('avril', 30),
    ('mai', 31),
    ('juin', 30),
    ('juillet', 31),
    ('aout', 31),
    ('septembre', 30),
    ('octobre', 31),
    ('novembre', 30),
    ('decembre', 31)
]

calendrier = []
for nom_mois, nb_jours in liste_mois:
    for numero_jour in range(1, nb_jours + 1):
        calendrier.append({
            'j': numero_jour,
            'm': nom_mois
        })

print(calendrier)


#유기농 배추
from collections import deque
def bfs(x,y):
    queue = deque()
    queue.append((x,y))
    graph[x][y] = 0
    while queue:
        x, y = queue.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if 0<=nx<n and 0<=ny<m and graph[nx][ny] == 1:
                queue.append((nx,ny))
                graph[nx][ny] = 0
    return

graph = []
dx = [-1,1, 0, 0]
dy = [0,0,-1,1]
t = int(input())
for _ in range(t):
    cnt = 0
    m, n, k = map(int, input().split())
    graph = [[0 for _ in  range(m)] for _ in range(n)]
    for _ in range(k):
        x, y =  map(int, input().split())
        graph[y][x] = 1
    for i in range(n):
        for j in range(m):
            if graph[i][j] == 1:
                bfs(i,j)
                cnt += 1
    print(cnt)


from project.hardware.heavy_hardware import HeavyHardware
from project.hardware.power_hardware import PowerHardware
from project.software.express_software import ExpressSoftware
from project.software.light_software import LightSoftware

class System:
    _hardware = []
    _software = []

    @staticmethod
    def register_power_hardware(name: str, capacity: int, memory: int):
        power_hardware = PowerHardware(name, capacity, memory)
        System._hardware.append(power_hardware)

    @staticmethod
    def register_heavy_hardware(name: str, capacity: int, memory: int):
        heavy_hardware = HeavyHardware(name, capacity, memory)
        System._hardware.append(heavy_hardware)

    @staticmethod
    def register_express_software(hardware_name: str, name: str, capacity_consumption: int, memory_consumption: int):
        hardware = [h for h in System._hardware if h.name == hardware_name]
        if not hardware:
            return "Hardware does not exist"

        hardware = hardware[0]
        software = ExpressSoftware(name, capacity_consumption, memory_consumption)

        hardware.install(software)
        System._software.append(software)

    @staticmethod
    def register_light_software(hardware_name: str, name: str, capacity_consumption: int, memory_consumption: int):
        hardware = [h for h in System._hardware if h.name == hardware_name]
        if not hardware:
            return "Hardware does not exist"

        hardware = hardware[0]
        software = LightSoftware(name, capacity_consumption, memory_consumption)

        hardware.install(software)
        System._software.append(software)

    @staticmethod
    def release_software_component(hardware_name: str, software_name: str):
        hardware = [h for h in System._hardware if h.name == hardware_name]
        software = [s for s in System._software if s.name == software_name]

        if not hardware or not software:
            return "Some of the components do not exist"

        hardware = hardware[0]
        software = software[0]

        hardware.uninstall(software)
        System._software.remove(software)

    @staticmethod
    def analyze():
        hardware_components_amount = len(System._hardware)
        software_components_amount = len(System._software)
        total_memory_consumption = sum([s.memory_consumption for s in System._software])
        total_memory = sum([h.memory for h in System._hardware])
        total_capacity_consumption = sum([s.capacity_consumption for s in System._software])
        total_capacity = sum([h.capacity for h in System._hardware])

        result = "System Analysis\n"
        result += f"Hardware Components: {hardware_components_amount}\n"
        result += f"Software Components: {software_components_amount}\n"
        result += f"Total Operational Memory: {total_memory_consumption} / {total_memory}\n"
        result += f"Total Capacity Taken: {total_capacity_consumption} / {total_capacity}"

        return result

    @staticmethod
    def system_split():
        result = ''

        for hardware in System._hardware:
            name = hardware.name
            express_software_amount = [s for s in hardware.software_components if s.__type__.__name__ == "Express"]
            light_software_amount = [s for s in hardware.software_components if s.__type__.__name__ == "Light"]
            total_memory_consumption = sum([s.memory_consumption for s in hardware.software_components])
            total_memory = hardware.memory
            total_capacity_consumption = sum([s.capacity_consumption for s in hardware.software_components])
            total_capacity = hardware.capacity
            hardware_type = hardware.__type__.__name__
            software_components_names = [s.name for s in hardware.software_components]
            if not software_components_names:
                software_components_names = "None"
            else:
                software_components_names = ", ".join(software_components_names)

            result += f"Hardware Component - {name}"
            result += f"Express Software Components: {express_software_amount}"
            result += f"Light Software Components: {light_software_amount}"
            result += f"Memory Usage: {total_memory_consumption} / {total_memory}"
            result += f"Capacity Usage: {total_capacity_consumption} / {total_capacity}"
            result += f"Type: {hardware_type}"
            result += f"Software Components: {software_components_names}"

        return result.strip()


from sqlite3 import IntegrityError, Connection

import schema
from flask import g
from flask import request
from flask import Blueprint
from flask.views import MethodView
from werkzeug.exceptions import abort

from flaskr import settings
from flaskr.utils.auth import login_required
from flaskr.utils.db import get_db, get_all_posts, get_post, get_all_comments

bp_index = Blueprint("index", __name__, url_prefix='/api')
bp = Blueprint("post", __name__, url_prefix="/api/post")
bp_comment = Blueprint("comment", __name__, url_prefix='/api/comment')

class Index(MethodView):
    def get(self):
        """
        Get posts.
        :return json 200: List[Post]
        """
        return dict(posts=get_all_posts())

class Post(MethodView):
    def get(self):
        """
        Get posts.
        :return json 200: List[Post]
        """
        return dict(posts=get_all_posts())

    @staticmethod
    def post_schema(from_dict: dict) -> dict:
        try:
            data = schema.Schema({
                "title": schema.And(str, lambda x: settings.POST_TITLE_MIN_WORDS_LENGTH <= len(x) <= settings.POST_TITLE_MAX_WORDS_LENGTH),
                "body": schema.And(str, lambda x: settings.POST_BODY_MIN_WORDS_LENGTH <= len(x) <= settings.POST_BODY_MAX_WORDS_LENGTH)
            }).validate(from_dict)
        except schema.SchemaError:
            raise abort(400, "Wrong args.")
        else:
            return data

    @login_required
    def post(self):
        """
        Create a post
        :param form title: post title
        :param form body: post content text
        :return json 201: Post
        """
        data = self.post_schema(dict(request.form))

        db: Connection = get_db()

        try:
            with db:
                cur = db.cursor()
                cur.execute(
                    "INSERT INTO post (title, body, author_id) VALUES (?, ?, ?)",
                    (data['title'], data['body'], g.user["id"]),
                )
        except IntegrityError:
            raise abort(400, "Duplicated data")

        post = get_post(post_id=cur.lastrowid)
        return dict(post), 201

class PostId(MethodView):
    def get(self, post_id: int):
        """
        Get post by specific id
        :param int post_id: id of post
        :return json 200: Post
        """
        post = get_post(post_id=post_id)

        if post is None:
            abort(404, f"Post id {post_id} doesn't exist.")

        return post

def comment_schema(form_dict: dict) -> dict:
    try:
        data = schema.Schema({
            "body": schema.And(
                str,
                lambda x: settings.COMMENT_BODY_MIN_WORDS_LENGTH <= len(x) <= settings.COMMENT_BODY_MAX_WORDS_LENGTH
            )
        }).validate(form_dict)
    except schema.SchemaError:
        raise abort(400, "Wrong args.")
    else:
        return data

class PostIdComment(MethodView):
    def get(self, post_id: int):
        """
        Get all comments of a post
        :param: int post_id:
        :return json 200: {"comments": List[Comment]}
        """
        return dict(comments=get_all_comments(post_id=post_id))

    @login_required
    def post(self, post_id: int):
        """
        Add a comment to post
        :param int post_id:
        :param form body:  comment content text
        :return json 201: Post
        """
        data = comment_schema(dict(request.form))
        db = get_db()
        with db:
            cur = db.cursor()
            cur.execute("INSERT INTO comment (author_id, body, parent_id, post_id) VALUES (?, ?, ?, ?)",
                        (g.user['id'], data['body'], None, post_id))

        return get_post(post_id), 201

class CommentId(MethodView):
    def get(self, comment_id: int):
        """
        Get a comment.
        :param int comment_id:
        :return json 200: Comment
        """
        row = get_db().execute("SELECT id, post_id, created, body FROM comment WHERE id=?", (comment_id, )).fetchone()
        if not row:
            raise abort(400, f'Comment {comment_id} not found.')
        return dict(row)

class CommentIdComment(MethodView):
    @login_required
    def post(self, comment_id: int):
        """
        Add a comment of a comment.
        Login required
        :param int comment_id: id of comment
        :param form body: comment content text
        :param form body: comment content text
        :raise 401 Login required:
        :return json 201: Post
        """
        data = comment_schema(dict(request.form))
        db = get_db()
        comment = db.execute(
            "SELECT post_id FROM comment WHERE id=?",
            (comment_id, )
        ).fetchone()
        if not comment:
            raise abort(400, f"Comment not found.")

        with db:
            cur = db.cursor()
            cur.execute("INSERT INTO comment (author_id, body, parent_id, post_id) VALUES (?, ?, ?, ?)",
                        (g.user['id'], data['body'], comment_id, comment['post_id']))

        return get_post(comment['post_id']), 201

bp_index.add_url_rule('/', view_func=Index.as_view('Index'))
bp.add_url_rule('/<int:post_id>/comment', view_func=PostIdComment.as_view('PostIdComment'))
bp.add_url_rule('/<int:post_id>', view_func=PostId.as_view('PostId'))
bp.add_url_rule('/', view_func=Post.as_view('Post'))

bp_comment.add_url_rule('/<int:comment_id>/comment',
                        view_func=CommentIdComment.as_view('PostIdCommentIdComment'))
bp_comment.add_url_rule('/<int:comment_id>', view_func=CommentId.as_view('PostIdCommentId'))


"""
https://leetcode.com/problems/maximum-ice-cream-bars/
1833. Maximum Ice Cream Bars

It is a sweltering summer day, and a boy wants to buy some ice cream bars.
At the store, there are n ice cream bars. You are given an array costs of length n, where costs[i] is the price of the ith ice cream bar in coins. The boy initially has coins coins to spend, and he wants to buy as many ice cream bars as possible.
Return the maximum number of ice cream bars the boy can buy with coins coins.
Note: The boy can buy the ice cream bars in any order.
"""
from typing import List

class Solution:
    def maxIceCream(self, costs: List[int], coins: int) -> int:
        answer = 0
        freq = [0] * (max(costs) + 1)

        # Fill in the list of frequency
        # (each index is cost of icecream)
        for cost in costs:
            freq[cost] += 1

        for cost, amount in enumerate(freq):
            # If frequency is 0, skip it
            if freq[cost] == 0:
                continue
            # If cost * amount is less than coins,
            # simply decrease the coins by cost * amount
            if amount * cost <= coins:
                coins -= amount * cost
                answer += amount
                continue
            # At this point we cannot buy amount * cost
            # So coins // cost should be the amount of icecream we can buy
            answer += coins // cost
            # And don't forget to exist loop
            # (we can't buy icecreams anymore)
            break

        return answer


import math

# 入力
A, B, H, M = map(float, input().split())

# 座標を求める
PI = 3.14159265358979
AngleH = 30.0 * H + 0.5 * M
AngleM = 6.0 * M
Hx = A * math.cos(AngleH * PI / 180.0)
Hy = A * math.sin(AngleH * PI / 180.0)
Mx = B * math.cos(AngleM * PI / 180.0)
My = B * math.sin(AngleM * PI / 180.0)

# 答えを出力
d = (((Hx - Mx) ** 2 + (Hy - My) ** 2) ** 0.5)
print("%.12f" % d)


# -*- coding:utf-8 -*-
my_name = "分数"
import pygame

pygame.init()
my_font = pygame.font.SysFont("simSun", 66)
name_surface = my_font.render(u'分数', True, (0, 0, 0), (255, 255, 255))

pygame.image.save(name_surface, "name.png")

enemy_hit_dict = dict()

score = 0

ENEMY_SCORE = 100

# enemy_hit_dict = pygame.sprite.groupcollide(enemy_group, hero.bullets, True, True)
# score += len(enemy_hit_dict) * ENEMY_SCORE;  # 计算得分
# enemy_hit_group.add(enemy_hit_dict)

screen = pygame.display.set_mode((480, 700))
bg = pygame.image.load("./images/background.png")
# 2、使用blit方法将背景绘制在屏幕的(0,0)位置
screen.blit(bg, (0, 0))
screen.blit(name_surface, (20, 20))
# 3、更新屏幕
pygame.display.update()


from urllib import request, parse
import json
from getAccessToken import getToken

def newNotification(filename, touser, key1, key2, key3, key4, first, remark):
    ACCESS_TOKEN = getToken()
    url = 'https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=ACCESS_TOKEN'
    url = url.replace('ACCESS_TOKEN', ACCESS_TOKEN)
    headers = {
        'Content-Type': 'application/json'
    }
    data = open(filename, 'rb').read(-1).decode()
    print(type(data))
    print(touser)
    data = data.format(touser, key1, key2, key3, key4, first, remark).encode()
    req = request.Request(url, data=data, headers=headers)
    res = request.urlopen(req)
    data = res.read().decode()
    return data


"""web URL Configuration"""

from django.conf.urls import include,url
from django.contrib import admin
from . import views

urlpatterns = [
    url(r'^admin/', admin.site.urls),

	url(r'^$', views.index, name='index'),
    url(r'^pdx/(?P<pk>\w{0,50})/$', views.pdx, name="pdx"),
    url(r'^search/', views.search, name="search"),
    #url(r'^search/', include('haystack.urls')),
    url(r'^resources/', views.resources, name="resources"),
]


"""
Запуск класса с датасетами твитов и генома ВИЧ
"""
import Hyperbolic
import numpy as np
import Levenshtein as Lev
import pandas as pd
from grad_descent import MSE
import draw

"""
ТВИТЫ
"""
positive = np.array(pd.read_csv(
    r'twitter_data/positive.csv', sep=';', usecols=[3], names=['text']))
negative = np.array(pd.read_csv(
    r'twitter_data/negative.csv', sep=';', usecols=[3], names=['text']))

# positive_90 = np.array(
#     positive[positive['text'].apply(lambda text: len(text) == 90)])
# negative_90 = np.array(
#     negative[negative['text'].apply(lambda text: len(text) == 90)])

size = 50
dataset = np.concatenate((positive[np.random.choice(
    len(positive), size)], negative[np.random.choice(len(negative), size)]))

perm = np.random.permutation(2*size)
ran = np.array(range(2*size))
map = {perm[i]: ran[i] for i in range(2*size)}

dataset = dataset[perm]

distance = np.zeros((2*size, 2*size), dtype=float)

for i in range(2*size):
    for j in range(2*size):
        distance[i, j] = Lev.distance(dataset[i, 0], dataset[j, 0])

distance = distance / 10.

H = Hyperbolic.Hyperbolic(graph=distance, dimension=2, maxiter=1000, batch=1.)
print("MSE %f" % MSE(H.point_coordinates, distance))

draw.draw(H.point_coordinates, distance,
          draw_edges=False, map=map, annotate=False)

"""
Геном вич
"""

# lst = np.array([]).reshape(0, 0)
# for i in range(100):
#     f = open(rf'data/sequence ({i}).txt', 'r')
#     string = f.read().replace("\n", "")
#     tmp = list(string.encode())
#     if i == 0:
#         lst = np.array(tmp).reshape(1, -1)
#     else:
#         lst = np.vstack((lst, np.array(tmp).reshape(1, -1)))
# # создал пустой интовый массив для расстояний
# distance = np.zeros((100, 100), dtype=float)
# # заполнил его правильными значениями
# for i in range(100):
#     for j in range(100):
#         distance[i, j] = (lst[i] != lst[j]).sum()

# distance = distance / 3.
# H = Hyperbolic.Hyperbolic(graph=distance, dimension=2, maxiter=100, batch=0.1)
# draw.draw(H.point_coordinates, distance, True, annotate=False)


import time

def isprime(n):
    mas = []
    d = 1
    while d * d < n:
        if n % d == 0:
            mas.append(d)
            mas.append(n // d)
        d += 1
    if d * d == n:
        mas.append(d)
    if len(mas) == 2:
        return mas[1]

def g(n):
    counter = 0
    mas = []
    d = 2
    while d * d < n:
        if n % d == 0:
            mas.append(d)
            mas.append(n // d)
        d += 1
    if d * d == n:
        mas.append(d)
    if len(mas) > 3:
        for j in range(len(mas)):
            if isprime(mas[j]) is not None:
                counter += 1
    if counter > 3:
        return n

start = time.time()
k = 0
for i in range(2, 20000 + 1):
    if g(i) is not None:
        k += 1
        print(k, g(i))
print(time.time() - start)


import math
import numpy as np
from scipy.special import expit

class LogReg():
    def __init__(self, lambda_1=0.0, lambda_2=1.0, gd_type='full',
                 tolerance=1e-4, max_iter=1000, w0=None, alpha=1e-3):
        """
        lambda_1: L1 regularization param
        lambda_2: L2 regularization param
        gd_type: 'full' or 'stochastic'
        tolerance: for stopping gradient descent
        max_iter: maximum number of steps in gradient descent
        w0: np.array of shape (d) - init weights
        alpha: learning rate
        """
        self.lambda_1 = lambda_1
        self.lambda_2 = lambda_2
        self.gd_type = gd_type
        self.tolerance = tolerance
        self.max_iter = max_iter
        self.w0 = w0
        self.alpha = alpha
        self.w = None
        self.loss_history = None

    def fit(self, X, y):
        """
        X: np.array of shape (l, d)
        y: np.array of shape (l)
        ---
        output: self
        """
        self.loss_history = []
        count = 0
        self.w = np.ones((len(X[0]),))
        while np.linalg.norm(self.w - self.w0) > self.tolerance or count < self.max_iter:
            count += 1
            self.w = self.w0
            if self.gd_type == 'stochastic':
                i = random.randint(0, len(y))
                grad = self.calc_gradient(X[i, :], np.array(y[i]))
            else:
                grad = self.calc_gradient(X, y)
            self.w = self.w0 - self.alpha * grad
            loss = self.calc_loss(X, y)
            self.loss_history.append(loss)
            self.w0 = self.w
        return self

    def predict_proba(self, X):
        """
        X: np.array of shape (l, d)
        ---
        output: np.array of shape (l, 2) where
        first column has probabilities of -1
        second column has probabilities of +1
        """
        if self.w is None:
            raise Exception('Not trained yet')
        pred = expit(np.dot(X, self.w))
        return pred

    def calc_gradient(self, X, y):
        """
        X: np.array of shape (l, d) (l can be equal to 1 if stochastic)
        y: np.array of shape (l)
        ---
        output: np.array of shape (d)
        """
        tm1 = expit(-y * np.dot(X, self.w))
        tm2 = y[:, np.newaxis] * X
        tm3 = tm1[:, np.newaxis] * tm2
        tm4 = -np.sum(tm3, axis=0)
        grad = tm4 / X.shape[0] + self.lambda_2 * self.w
        return grad

    def calc_loss(self, X, y):
        """
        X: np.array of shape (l, d)
        y: np.array of shape (l)
        ---
        output: float
        """
        n = X.shape[0]
        tm1 = np.logaddexp(0, -y * np.dot(X, self.w))
        reg = self.lambda_2 * np.sum(self.w ** 2) / 2
        loss = (1 / n) * np.sum(tm1, axis=0) + reg
        return loss


from . learningTasks import RandomForest

import os
import luigi
import numpy as np
import logging

# import the proper nifty version
try:
    import nifty.graph.rag as nrag
except ImportError:
    try:
        import nifty_with_cplex.graph.rag as nrag
    except ImportError:
        import nifty_with_gurobi.graph.rag as nrag

from .dataTasks import StackedRegionAdjacencyGraph, InputData
from .tools import config_logger, run_decorator
from .featureTasks import RegionNodeFeatures
from .customTargets import HDF5DataTarget, FolderTarget
from .pipelineParameter import PipelineParameter

# init the workflow logger
workflow_logger = logging.getLogger(__name__)
config_logger(workflow_logger)

class DefectNodeGroundtruth(luigi.Task):

    pathToSeg = luigi.Parameter()
    pathToDefectGt = luigi.Parameter()

    def requires(self):
        return{
            "rag": StackedRegionAdjacencyGraph(self.pathToSeg),
            "defect_gt": InputData(self.pathToDefectGt, dtype='uint8')
        }

    @run_decorator
    def run(self):
        inp = self.input()
        rag = inp['rag'].read()
        defect_gt = inp['defect_gt']
        defect_gt.open()

        node_labels = nrag.gridRagAccumulateLabels(rag, defect_gt.get())
        assert (np.unique(node_labels) == np.array([0, 1])).all(), str(np.unique(node_labels))
        self.output().write(node_labels)

    def output(self):
        seg_file = os.path.split(self.pathToSeg)[1][:-3]
        save_path = "DefectNodeGroundtruth_%s.h5" % seg_file
        return HDF5DataTarget(save_path)

class LearnDefectRandomForest(luigi.Task):

    pathsToSeg = luigi.ListParameter()
    pathsToDefectGt = luigi.ListParameter()

    def requires(self):
        assert len(self.pathsToSeg) == len(self.pathsToGt)
        n_inputs = len(self.pathsToSeg)
        inputs = PipelineParameter().inputs

        if n_inputs == 1:
            raw_path = inputs['data'][0]
            return {
                'gt': DefectNodeGroundtruth(self.pathsToSeg[0], self.pathsToDefectGt[0]),
                'feats': RegionNodeFeatures(self.pathsToSeg[0], raw_path)
            }
        else:
            inp_paths = inputs['data']
            assert n_inputs % inp_paths == 0
            inp_per_seg = len(inp_paths) // n_inputs
            return {
                'gt': [DefectNodeGroundtruth(self.pathsToSeg[i], self.pathsToDefectGt[i]) for i in range(n_inputs)],
                'feats': [RegionNodeFeatures(self.pathToSeg[i], inp_paths[inp_per_seg * i]) for i in range(n_inputs)]
            }

    @run_decorator
    def run(self):
        if(self.pathsToSeg) > 1:
            self._learn_defect_rf_multi_input()
        else:
            self._learn_defect_rf_single_input()

    def _learn_defect_rf_multi_input(self):
        inp = self.input()
        gts = inp['gt']
        feats = inp['feats']
        assert len(gts) == len(feats)
        features = []
        labels = []
        for i, gt in enumerate(gts):
            this_gt = gt.read()
            this_feats = feats[i].read([0, 0], feats[i].shape)
            assert len(this_gt) == len(this_feats), "%i, %i" % (len(this_gt), len(this_feats))
            features.append(this_feats)
            labels.append(this_gt)
        features = np.concatenate(features, axis=0)
        labels = np.concatenate(labels, axis=0)
        rf = RandomForest(
            features, labels,
            n_trees=PipelineParameter().nTrees,
            n_threads=PipelineParameter().nThreads
        )
        rf.write(str(self.output().path), 'rf')

    def _learn_defect_rf_single_input(self):
        inp = self.input()
        gt = inp['gt'].read()
        feats = inp['feats']
        feats = feats.readSubarray([0, 0], feats.shape)
        assert len(gt) == len(feats), "%i, %i" % (len(gt), len(feats))
        rf = RandomForest(
            feats, gt,
            n_trees=PipelineParameter().nTrees,
            n_threads=PipelineParameter().nThreads
        )
        rf.write(str(self.output().path), 'rf')

    def output(self):
        save_path = 'LearnDefectRandomForest_%s' % (
            'multi_input' if len(self.pathsToSeg) > 1 else 'single_input',
        )
        return FolderTarget(save_path)


#Long Short-Term Memory
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense, Dropout, LSTM
from sklearn.preprocessing import MinMaxScaler
from sklearn.metrics import mean_squared_error

dataset_train = pd.read_csv('files/Salestrain.csv')
plt.plot(dataset_train, color='blue', label='Vendas')
plt.title('Vendas')
plt.xlabel('Tempo')
plt.ylabel('Vendas')
plt.legend()
plt.show()

sc = MinMaxScaler(feature_range=(0, 1))
trainning_set_scaled = sc.fit_transform(dataset_train)

X_train = []
y_train = []

for i in range(90, len(trainning_set_scaled)):
    data = trainning_set_scaled[i-90:i, 0]
    X_train.append(data)
    y_train.append(trainning_set_scaled[i,0])

X_train = np.array(X_train.reshape(-1,90,1))
y_train = np.array(y_train)

model = Sequential()
model.add(LSTM(units=100, return_sequences=True, input_shape=(X_train.shape[1],1)))
model.add(Dropout(0.2))
model.add(LSTM(units=100, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=100, return_sequences=True))
model.add(Dropout(0.2))
model.add(LSTM(units=100))
model.add(Dropout(0.2))
model.add(Dense(units=1))

model.compile(optimizer='adam', loss='mean_squared_error')
model.fit(X_train, y_train, epochs=300, batch_size=1)

dataset_test = pd.read_csv('files/Salestest.csv')

train_values = dataset_train['data'].values
test_values = dataset_test['data'].values
total_values = np.concatenate((train_values, test_values), axis=0)
time_index = range(len(total_values))

plt.plot(time_index[:len(train_values)], color='blue', label='Vendas - Treinamento')
plt.plot(time_index[len(test_values):], color='red', label='Vendas - Teste')
plt.title('Vendas')
plt.xlabel('Tempo')
plt.ylabel('Vendas')
plt.legend()
plt.show()

dataset_test_anomalies = dataset_test.copy()
dataset_test_anomalies.loc[:9, 'data'] = 90
dataset_test_anomalies.loc[10:34, 'data'] = np.random.uniform(100,200,size=(25,))
dataset_test_anomalies.loc[35:, 'data'] = 90

plt.plot(dataset_test, color='blue', label='Vendas')
plt.plot(dataset_test_anomalies, color='red', label='Vendas com anomalias')
plt.title('Vendas')
plt.xlabel('Tempo')
plt.ylabel('Vendas')
plt.legend()
plt.show()

dataset_total = pd.concat((dataset_train['data'], dataset_test['data']), axis=0)
inputs = dataset_total[len(dataset_total)-len(dataset_test-90):]
inputs = pd.DataFrame(inputs, columns=['data'])
inputs = sc.transform(inputs)

dataset_total_anomalies = pd.concat((dataset_train['data'], dataset_test_anomalies['data']), axis=0)
inputs_anomalies = dataset_total_anomalies[len(dataset_total_anomalies)-len(dataset_test_anomalies-90):]
inputs_anomalies = pd.DataFrame(inputs_anomalies, columns=['data'])
inputs_anomalies = sc.transform(inputs_anomalies)

X_test = []
X_test_anomalies = []
for i in range(90, len(inputs)):
    X_test.append(inputs[i-90:i,0])
    X_test_anomalies.append(inputs_anomalies[i-90:i,0])

X_test, X_test_anomalies = np.array(X_test), np.array(X_test_anomalies)
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))
X_test_anomalies = np.reshape(X_test_anomalies, (X_test_anomalies.shape[0], X_test_anomalies.shape[1], 1))

prediced_sales = model.predict(X_test)
prediced_sales = sc.inverse_transform(prediced_sales)
prediced_sales_anomalies = model.predict(X_test_anomalies)
prediced_sales_anomalies = sc.inverse_transform(prediced_sales_anomalies)

mean_squared_error_test = mean_squared_error(test_values, prediced_sales)
mean_squared_error_anomalies = mean_squared_error(test_values, prediced_sales_anomalies)

print(f'MSE normal data: ', mean_squared_error_test)
print(f'MSE data with anomalies: ', mean_squared_error_anomalies)

plt.plot(test_values, color='blue', label='Valores reais')
plt.plot(prediced_sales_anomalies, colo='red', label='Previsões com anomalias')
plt.plot(prediced_sales, color='green', label='Previsões')
plt.title('Previsões com anomalias, sem anomalias e valores reais')
plt.xlabel('Tempo')
plt.ylabel('Vendas')
plt.legend()
plt.show()


from sklearn.preprocessing import StandardScaler
file_name2 = 'data2.csv'
df = pd.read_csv(file_name2)
df['race_date'] = pd.to_datetime(df['race_date']).dt.date
# 情報不足行を削除
df = df.dropna(subset=['past_time_sec1', 'past_time_sec2', 'past_time_sec3',
                       'past_time_sec4', 'past_time_sec5']).reset_index(drop=True)

# レースID付与

def set_race_id(params):
    param_list = params.split('_')
    race_date, place, race_num = param_list[0], param_list[1], param_list[2],
    return f'{race_date}{place}{race_num}'

df['tmp'] = df['race_date'].astype(
    str) + '_' + df['place'].astype(str) + '_' + df['race_num'].astype(str)
df['race_id'] = df['tmp'].map(set_race_id)
df = df.drop(columns=['tmp'])

# 予測に使用しない列を削除（必要に応じて変更）
df = df.drop(columns=['horse', 'jockey', 'race_num', 'stable',
                    'race_name', 'rank', 'pop',  'gap', 'tansho', 'win1', 'time_sec'])

# ダミー列定義（One-Hot変換対象）
dummy_columns = ['sex', 'place', 'course_type', 'course_lr', 'weather', 'ground', 'past_course_type1', 'past_course_lr1', 'past_weather1', 'past_ground1', 'past_gap1', 'past_course_type2', 'past_course_lr2', 'past_weather2', 'past_ground2', 'past_gap2',
                'past_course_type3', 'past_course_lr3', 'past_weather3', 'past_ground3', 'past_gap3', 'past_course_type4', 'past_course_lr4', 'past_weather4', 'past_ground4', 'past_gap4', 'past_course_type5', 'past_course_lr5', 'past_weather5', 'past_ground5', 'past_gap5']

# ダミー化
df_dummy = df[dummy_columns]
df_dummy = pd.get_dummies(df_dummy, dummy_na=True)
df_main = df.drop(columns=dummy_columns)

# 標準化前に必要な情報を退避
df_main['kitaichi'] = df_main['win3'] * df_main['fukusho']
train_kitaichi = df_main.pop('kitaichi')
train_labels = df_main.pop('win3')
train_date = df_main.pop('race_date')
train_raceids = df_main.pop('race_id')
df_main = df_main.drop(columns=['fukusho'])

df_main = df_main.astype(float)
standard_file = 'standard.csv'
df_main.to_csv(standard_file, index=False)
# 標準化

ss = StandardScaler()
df_main = pd.DataFrame(ss.fit_transform(
    df_main), columns=df_main.columns, index=df_main.index)

# ダミー列とマージ
df = pd.concat([df_main, df_dummy], axis=1)

df['kitaichi'] = train_kitaichi.values
df['win3'] = train_labels.values
df['race_date'] = train_date.values
df['race_id'] = train_raceids.values
file_name3 = 'data3.csv'
df.to_csv(file_name3, index=False)


A, K = map(int, input().split())

ans = A
for i in range(len(str(A))):
    for p in range(10):
        for q in range(10):
            s = str(A)[:i] + str(p) + str(q) * (len(str(A))-i-1)
            if (len(set(str(int(s)))) <= K):
                ans = min(ans, abs(A-int(s)))
print(ans)


# THIS FILE IS SAFE TO EDIT. It will not be overwritten when rerunning go-raml.

from flask import jsonify, request
import sqlite3

def books_postHandler():
    connection = sqlite3.connect("BookStore")
    cursor=connection.cursor()
    inputs = request.get_json()
    cursor.execute("CREATE TABLE IF NOT EXISTS BookStore (BookId INTEGER PRIMARY KEY AUTOINCREMENT,title TEXT,subTitle TEXT,authors TEXT)")
    cursor.execute("INSERT INTO BookStore VALUES(NULL,?,?,?)", (inputs["title"],inputs["subTitle"],inputs["authors"]))
    connection.commit()
    connection.close()
    return jsonify("successfully")


import pickle
import numpy as np

referrence_vec = {} ## list of numpy average vectors to compare with

synonym_dict={}
names=["safety","products and services","technical skills","soft skills","orientation","onboarding"]
synonym_dict["safety"] = ["safety", "wellbeing","welfare","security"]
synonym_dict["products and services"] = ["products","services","resource","utility","system","amenity"]
synonym_dict["technical skills"] = ["technical","technological","applied"]
synonym_dict["soft skills"] = ["soft","communication","interpersonal"]
synonym_dict["orientation"]= ["orientation","accommodation","familiarization","acclimatization","introduction","initiation"]
synonym_dict["onboarding"]= ["induction","integration","onboarding"]

EMBEDDING_DIM=100

with open('embeddings_index.p', 'rb') as fp:
   embeddings_index = pickle.load(fp)

for name in names:
   synonyms = synonym_dict[name]
   vec_list = [embeddings_index[x] for x in synonyms]
   referrence_vec[name] = vec_list

with open('referrence_vec.p', 'wb') as fp:
    pickle.dump(referrence_vec, fp, protocol=pickle.HIGHEST_PROTOCOL)


import geoip2.database
"""
Requirements:
    geoip2
    use this page to download the db:
      https://dev.maxmind.com/geoip/geolite2-free-geolocation-data?lang=en
"""
# This creates a Reader object. You should use the same object
# across multiple requests as creation of it is expensive.
with geoip2.database.Reader('/path/to/GeoLite2-City.mmdb') as reader:

    # Replace "city" with the method corresponding to the database
    # that you are using, e.g., "country".
    response = reader.city('203.0.113.0')
    print(
        response.country.iso_code +
        response.country.name +
        response.country.names['zh-CN'] +
        response.subdivisions.most_specific.name +
        response.subdivisions.most_specific.iso_code +
        response.city.name +
        response.postal.code +
        response.location.latitude +
        response.location.longitude +
        response.traits.network, sep="\n"
    )

""