# -*- coding: utf-8 -*-
# (c) 2009-2010 Ruslan Popov <ruslan.popov@gmail.com>

from django.conf.urls.defaults import *

#автоматическое подключение необходимых приложений
from django.contrib import admin
admin.autodiscover()

handler404 = 'views.handler404'
handler500 = 'views.handler500'

# карта сайта
from django.contrib.sitemaps import Sitemap, FlatPageSitemap, GenericSitemap
from shop.models import Item

sitemap_dict = {
    'queryset': Item.objects.all(),
    'date_field': 'reg_date',
}

sitemaps = {
    'flatpages': FlatPageSitemap,
    'items': GenericSitemap(sitemap_dict, priority=0.6),
}

class ItemSitemap(Sitemap):
    changefreq = 'daily'
    priority = 0.5

    def items(self):
        return Item.objects.filter(is_present=True)

    def lastmod(self, obj):
        return obj.last_modification

    def location(self, obj):
        return obj.get_absolute_url_by_title()

sitemaps = {
    'items': ItemSitemap(),
}

urlpatterns = patterns(
    '',
    # Интерфейс администратора
    (r'^admin/doc/', include('django.contrib.admindocs/urls')),
    (r'^admin/(.*)', admin.site.root),

    # карта сайта, robots.txt
    (r'^sitemap.xml$', 'django.contrib.sitemaps.views.sitemap', {'sitemaps': sitemaps}),
    (r'^robots.txt$', include('robots.urls')),

    # интерфейс менеджера
    (r'^manager/', include('manager.urls')),

    # ajax
    (r'^ajax/cart/add/$', 'shop.ajax.add_to_cart'),
    (r'^ajax/cart/remove/$', 'shop.ajax.cart_remove_item'),
    (r'^ajax/cart/recalculate/$', 'shop.ajax.cart_recalculate'),
    (r'^ajax/cart/clean/$', 'shop.ajax.clean_cart'),
    (r'^ajax/jabber/message/$', 'shop.ajax.jabber_message'),
    (r'^ajax/jabber/poll/$', 'shop.ajax.jabber_poll'),
    (r'^ajax/advice/random/$', 'advice.views.get_random_advice'),
    url(r'^ajax/search/addon/$', 'shop.ajax.get_search_addon'),

    # основное
    (r'^$', 'views.flatpage', {'title': 'index'}),
    (r'^category/(?P<title>[\w_]+)/((?P<page>\d+)/)?$', 'views.category'),
    (r'^collection/(?P<id>\d+)/((?P<page>\d+)/)?$', 'views.collection'),
    (r'^tag/(?P<tag>\w+)/$', 'views.tag_search'),
    (r'^search/$', 'views.search_query'),
    (r'^result/((?P<page>\d+)/)?$', 'views.search_results'),
    (r'^item/(?P<id>\d+)/$', 'views.item'),
    (r'^item/(?P<id>[\w\d\-]+)/$', 'views.item'),

    # сортировка
    (r'^sort/(?P<mode>\d)/', 'views.set_sort_mode'),

    # процесс покупки
    (r'^cart/$', 'views.show_cart'),
    (r'^order/$', 'views.show_order'),
    (r'^profit/$', 'views.show_profit'),

    # отображение текстов
    (r'^.*/$', 'views.flatpage'),
)


import csv

filename = "demo.csv"

# initializing the titles and rows list
fields = []
rows = []

with open(filename, 'r') as csvfile:
    csvreader = csv.reader(csvfile)
    fields = next(csvreader)
    for row in csvreader:
        rows.append(row)

    # get total number of rows
    print("Total no. of rows: %d"%(csvreader.line_num))

# printing the field names
print('Field names are:' + ', '.join(field for field in fields))
print('\nFirst 5 rows are:\n')
for row in rows[:5]:
    for col in row:
        print("%10s"%col,end=" "),
    print('\n')


import pandas
import networkx as nx
import json
import matplotlib.pyplot as plt

#read JSON file
jsondata = open('hnsw.json', 'r')
data = jsondata.read()

#parse
obj = json.loads(data)

#Create an empty undirected graph
#use nx.Digraph() for directed graph
G = nx.Graph()

for i in obj:
    #add node if it does not exist
    if i['id'] not in G:
        G.add_node(i['id'])
    #connect id and its friends
    for j in i['friends']:
        G.add_node(j)
        G.add_edge(i['id'], j)

nx.set_node_attributes(G, {item["id"]:item["level"] for item in obj}, name="level")
nx.set_node_attributes(G, {item["id"]:len(item["friends"]) for item in obj}, name="friends")
color_size = []
for i in obj:
    if i['level'] == 0: color_size.append('red')
    else: color_size.append('green')
nx.draw(G, node_color = color_size, font_size = 5, node_size = 100, alpha = 0.3, with_labels = True)
plt.show()
nx.write_graphml(G,f'g2.xml')


import nltk
from nltk.chat.util import Chat, reflections

# Define the chat pairs for greetings
pairs = [
    ['hi|hello|hey', ['Hello!', 'Hi there!', 'Hey!']],
    ['how are you', ['I\'m just a chatbot, but I\'m here to help! How can I assist you today?']],
    ['what is your name', ['I am a chatbot created by OpenAI.', 'I am your friendly chatbot.']],
    ['bye|goodbye', ['Goodbye!', 'Have a great day!', 'See you later!']],
    ['how do you feel',['awesome as always']],
    ['quotes',['everything happens for a reason  it might be hard to accept but its the reality']],
['goodnight',['have a sweet dream']],
 ]

# Create a chatbot instance
chatbot = Chat(pairs, reflections)

# Start the conversation
print("Hello! I'm your chatbot. Type 'bye' to exit.")
while True:
    user_input = input("You: ")
    if user_input.lower() == 'bye':
        print("Chatbot: Goodbye!")
        break
    response = chatbot.respond(user_input)
    print("Chatbot:", response)


from __future__ import unicode_literals
from django import forms
from django.db import models
from django.forms import ModelForm
from django.core.validators import MinValueValidator, MaxValueValidator

class Schedule(models.Model):
    MONDAY ='MON'
    TUESDAY = 'TUE'
    WEDNESDAY= 'WED'
    THURSDAY = 'THU'
    FRIDAY ='FRI'
    SATURDAY='SAT'
    SUNDAY= 'SUN'
    DAY_CHOICES =(
        (MONDAY, 'Monday'),
        (TUESDAY, 'Tuesday'),
        (WEDNESDAY, 'Wednesday'),
        (THURSDAY, 'Thursday'),
        (FRIDAY, 'Friday'),
        (SATURDAY, 'Saturday'),
        (SUNDAY, 'Sunday'),
    )

    #wide_range= range(7, 24, 1)
    #WIND_SPEED_CHOICE =[(i,i) for i in wide_range]

    employee_ID = models.CharField(max_length=120, default='', blank=True, null=False)
    day=models.CharField(max_length=7, choices=DAY_CHOICES)
    start_Time =models.IntegerField(validators=[MinValueValidator(7), MaxValueValidator(23)], blank=True)
    end_Time =models.IntegerField(validators=[MinValueValidator(8), MaxValueValidator(23)], blank=True)
    #end_Time =models.CharField(max_length=3, default='9', choices=WIND_SPEED_CHOICE)

    def __unicode__(self):
        return self.day
# Create your models here.


from itertools import izip

from jinja2.utils import escape

from templatefilters import escapejs, timesince_ago
from models import Exercise, UserExerciseGraph

def class_progress_report_graph_context(user_data, list_students):
    if not user_data:
        return {}

    list_students = sorted(list_students, key=lambda student: student.nickname)

    student_email_pairs = [(escape(s.email), (s.nickname[:14] + '...') if len(s.nickname) > 17 else s.nickname) for s in list_students]
    emails_escapejsed = [escapejs(s.email) for s in list_students]

    exercises_all = Exercise.get_all_use_cache()
    user_exercise_graphs = UserExerciseGraph.get(list_students)

    exercises_found = []

    for exercise in exercises_all:
        for user_exercise_graph in user_exercise_graphs:
            graph_dict = user_exercise_graph.graph_dict(exercise.name)
            if graph_dict and graph_dict["total_done"]:
                exercises_found.append(exercise)
                break

    exercise_names = [(e.name, e.display_name, escapejs(e.name)) for e in exercises_found]
    exercise_list = [{'name': e.name, 'display_name': e.display_name} for e in exercises_found]

    exercise_data = {}

    for (student, student_email_pair, escapejsed_student_email, user_exercise_graph) in izip(list_students, student_email_pairs, emails_escapejsed, user_exercise_graphs):

        student_email = student.email

        student_review_exercise_names = user_exercise_graph.review_exercise_names()

        for (exercise, (_, exercise_display, exercise_name_js)) in izip(exercises_found, exercise_names):

            exercise_name = exercise.name
            graph_dict = user_exercise_graph.graph_dict(exercise_name)

            status = ""

            if graph_dict["proficient"]:

                if exercise_name in student_review_exercise_names:
                    status = "Review"
                else:
                    status = "Proficient"
                    if not graph_dict["explicitly_proficient"]:
                        status = "Proficient (due to proficiency in a more advanced module)"

            elif graph_dict["struggling"]:
                status = "Struggling"
            elif graph_dict["total_done"] > 0:
                status = "Started"

            if student_email not in exercise_data:
                exercise_data[student_email] = {
                    'email': student.email,
                    'nickname': student.nickname,
                    'exercises': []
                }

            if len(status) > 0:
                exercise_data[student_email]['exercises'].append({
                    "status": status,
                    "progress": graph_dict["progress"],
                    "total_done": graph_dict["total_done"],
                    "last_done": graph_dict["last_done"] if graph_dict["last_done"] and graph_dict["last_done"].year > 1 else '',
                    "last_done_ago": timesince_ago(graph_dict["last_done"]) if graph_dict["last_done"] and graph_dict["last_done"].year > 1 else ''
                })
            else:
                exercise_data[student_email]['exercises'].append({
                    "name": exercise_name,
                    "status": status,
                })

    student_row_data = [data for key, data in exercise_data.iteritems()]

    return {
        'exercise_names': exercise_list,
        'exercise_data': student_row_data,
        'coach_email': user_data.email,
        'c_points': reduce(lambda a, b: a + b, map(lambda s: s.points, list_students), 0)
    }


import time
import numpy as np
import random

train = []
test = []

MAX_AGE = 90.0
WORKCLASS = ['Private', 'Self-emp-not-inc', 'Self-emp-inc', 'Federal-gov', 'Local-gov', 'State-gov', 'Without-pay', 'Never-worked', '?']
MAX_FNLWGT = 1484705
EDUCATION = ['Bachelors', 'Some-college', '11th', 'HS-grad', 'Prof-school', 'Assoc-acdm', 'Assoc-voc', '9th',
'7th-8th', '12th', 'Masters', '1st-4th', '10th', 'Doctorate', '5th-6th', 'Preschool', '?']
MAX_EDUCATION_NUM = 16.0
MARTIAL_STATUS = ['Married-civ-spouse', 'Divorced', 'Never-married', 'Separated', 'Widowed', 'Married-spouse-absent', 'Married-AF-spouse', '?']
OCCUPATION = ['Tech-support', 'Craft-repair', 'Other-service', 'Sales', 'Exec-managerial', 'Prof-specialty', 'Handlers-cleaners',
'Machine-op-inspct', 'Adm-clerical', 'Farming-fishing', 'Transport-moving', 'Priv-house-serv', 'Protective-serv', 'Armed-Forces', '?']
RELATIONSHIP = ['Wife', 'Own-child', 'Husband', 'Not-in-family', 'Other-relative', 'Unmarried', '?']
RACE = ['White', 'Asian-Pac-Islander', 'Amer-Indian-Eskimo', 'Other', 'Black', '?']
SEX = ['Female', 'Male', '?']
MAX_CAPITAL_GAIN = 9999.0
MAX_CAPITAL_LOSS = 4356.0
MAX_HOURS_PER_WEEK = 99.0
NATIVE_COUNTRY = ['United-States', 'Cambodia', 'England', 'Puerto-Rico', 'Canada', 'Germany', 'Outlying-US(Guam-USVI-etc)',
'India', 'Japan', 'Greece', 'South', 'China', 'Cuba', 'Iran', 'Honduras', 'Philippines', 'Italy', 'Poland', 'Jamaica',
'Vietnam', 'Mexico', 'Portugal', 'Ireland', 'France', 'Dominican-Republic', 'Laos', 'Ecuador', 'Taiwan', 'Haiti',
'Columbia', 'Hungary', 'Guatemala', 'Nicaragua', 'Scotland', 'Thailand', 'Yugoslavia', 'El-Salvador', 'Trinadad&Tobago',
'Peru', 'Hong', 'Holand-Netherlands', '?']

DATA_NORMALIZER = [MAX_AGE, WORKCLASS, MAX_FNLWGT, EDUCATION, MAX_EDUCATION_NUM, MARTIAL_STATUS, OCCUPATION, RELATIONSHIP, RACE, SEX,
MAX_CAPITAL_GAIN, MAX_CAPITAL_LOSS, MAX_HOURS_PER_WEEK, NATIVE_COUNTRY]

def normalize(l):
	try:
		l_ = []
		for i in range(15):
			if i == 0 or i == 2 or i == 4 or i == 10 or i == 11 or i == 12:
				l_.append(float(l[i]) / DATA_NORMALIZER[i])
			elif i == 14:
				if '<' in l[i]:
					l_.append(0)
				else:
					l_.append(1)
			else:
				l_.append(DATA_NORMALIZER[i].index(l[i]) / len(DATA_NORMALIZER[i]))
	except:
		pass
	return l_

t = time.clock_gettime(0)
f = open("train", "r")
lines = f.readlines()
for l in lines:
	l_ = l.split(', ')
	train.append(normalize(l_))

X = []
y = []

for i in range(len(train)):
	if len(train[i]) != 15:
		continue
	X.append(train[i][:14])
	y.append([train[i][14]])

X = np.array(X)
y = np.array(y)

test = []

f = open("test", "r")
lines = f.readlines()
for l in lines:
	l_ = l.split(', ')
	test.append(normalize(l_))

X_val = []
y_val = []

for i in range(len(test)):
	if len(test[i]) != 15:
		continue
	X_val.append(test[i][:14])
	y_val.append([test[i][14]])

X_val = np.array(X_val)
y_val = np.array(y_val)

# X = X + X_val
# y = y + y_val

# X = np.array(X)
# y = np.array(y)

print("Time spent to load test data: " + str(time.clock_gettime(0) - t))

import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Flatten, Dense, Activation, Dropout
from tensorflow.keras import optimizers
from tensorflow.keras.callbacks import TensorBoard

# n_layers = [1, 2, 3]
n_layers = [2]
# n_nodes = [256, 512, 1024]
n_nodes = [256]
# learning_rates = [0.01, 0.001, 0.0001]
learning_rates = [0.001]

for n_layer in n_layers:
	for n_node in n_nodes:
		for lr in learning_rates:

			# NAME = 'Adult-{}x{}-{}-{}'.format(n_node, n_layer, lr, int(time.time()))

			# print(NAME)

			# tb = TensorBoard(log_dir = 'logs/{}'.format(NAME))

			model = Sequential()
			model.add(Flatten())

			for _ in range(n_layer):
				model.add(Dense(n_node))
				model.add(Activation('tanh'))
				model.add(Dropout(0.1))

			model.add(Dense(1))
			model.add(Activation('sigmoid'))

			opt = optimizers.Adam(lr = lr)

			model.compile(optimizer = opt, loss = 'mean_squared_error', metrics = ['accuracy'])

			model.fit(X, y, epochs = 30, batch_size = 32, validation_data = (X_val, y_val))
			# model.fit(X, y, epochs = 15, batch_size = 64, validation_split = 0.5, callbacks = [tb])
			# model.evaluate(X_val, y_val)


#!/usr/bin/env python3
"""
This folder contains basic objects for FateZ.

author: jy
"""
from fatez.lib.database import FateZ_Dataset, collate_fn
from fatez.lib.sparse_mat import get_sparse_coo, get_dense, get_dense_adjs

__all__ = [
    'GRN_Basic',
    'FateZ_Dataset',
    'collate_fn',
    'get_sparse_coo',
    'get_dense',
    'get_dense_adjs',
]

class Error(Exception):
    pass

class GRN_Basic(object):
	"""
	Basic object for GRN components.
	"""

	def __init__(self, id:str = None, **kwargs):
		super(GRN_Basic, self).__init__()
		self.id = id
        # if there are other args
		for key in kwargs: setattr(self, key, kwargs[key])

	def as_dict(self):
		"""
		Cast object into dict type.

		:return: <class 'dict'>
		"""
		return self.__dict__

	def add_attr(self, key, value):
		"""
		Add new attribute to the object.

		:param key: <str>
			The key of new attribute.

		:param value: <>
			The value of new attribute.
		"""
		setattr(self, key, value)
		return


class MarginPair:

    def __init__(self):
        self.id = None
        self.symbol = ""
        self.base = ""
        self.quote = ""
        self.isMarginTrade = False
        self.isBuyAllowed = False
        self.isSellAllowed = False

    @staticmethod
    def json_parse(json_data):
        asset = MarginPair()
        asset.id = json_data.get_int("id")
        asset.symbol = json_data.get_string("symbol")
        asset.base = json_data.get_string("base")
        asset.quote = json_data.get_string("quote")
        asset.isMarginTrade = json_data.get_boolean("isMarginTrade")
        asset.isBuyAllowed = json_data.get_boolean("isBuyAllowed")
        asset.isSellAllowed = json_data.get_boolean("isSellAllowed")
        return asset


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jun 26 16:46:09 2018

@author: pt
"""
from skimage.io import imread
from skimage.transform import resize
import numpy as np
import os
import pandas as pd
import keras
import cv2

data_dir = '/home/pt/Desktop/debug_data'
img_dir = data_dir + '/IMG'
driving_log_csv = data_dir + '/' + 'driving_log.csv'
#driving_log = update_driving_log(data_dir, driving_log_csv, debug = True)

import os
files = os.listdir(data_dir + '/IMG')
from os import listdir
from os.path import isfile, join

driving_log_pd = pd.read_csv(driving_log_csv, header= None)
driving_log_pd.columns = ['center','left', 'right', 'steering','throttle','brake','speed']
max_index = 0
filenames = listdir(img_dir)

for f in filenames:
    file_name = f.split('.jpg')[0]
    camera = file_name[0]
    file_index = file_name[1:]
    file_index = int(file_index)

    if(file_index > max_index):
        max_index = file_index

    full_file_path = img_dir + '/' + f

    if camera == 'L':
        driving_log_pd.loc[file_index, 'left'] = full_file_path
    elif camera == 'C':
        driving_log_pd.loc[file_index, 'center'] = full_file_path
    elif camera == 'R':
        driving_log_pd.loc[file_index, 'right'] = full_file_path
    else:
        print('error')
        break

    driving_log_pd.loc[file_index, 'steering'] = file_index
    driving_log_pd.loc[file_index, 'throttle'] = file_index*2
    driving_log_pd.loc[file_index, 'brake'] = file_index*3
    driving_log_pd.loc[file_index, 'speed'] = file_index*4

driving_log_pd = driving_log_pd[0:max_index]
driving_log_pd.to_csv(driving_log_csv, index = False, header = False)


import sys, re
from math import ceil, floor, sqrt, pi, factorial, gcd,sin,cos,tan,asin,acos,atan2,exp,log,log10
from collections import deque, Counter, defaultdict
from itertools import product, accumulate
from functools import reduce,lru_cache
from bisect import bisect, bisect_left
from heapq import heapify, heappop, heappush
sys.setrecursionlimit(5 * 10 ** 5)
try:
    from pypyjit import set_param
    set_param('max_unroll_recursion=-1')
except ModuleNotFoundError:
    pass
input = lambda: sys.stdin.readline().rstrip()
ii = lambda: int(input())
mi = lambda: map(int, input().split())
li = lambda: list(mi())
inf = 2 ** 63 - 1
tokens = (i for line in iter(input, "") for i in line.split())

def solve(N: int, L: "List[int]"):
    L.sort()
    ans = 0
    for a in range(N-2):
        for b in range(a+1,N-1):
            c1 = L[a]+L[b]
            i = bisect_left(L[b+1:], c1)
            ans += i
    print(ans)

def main():
    N = int(next(tokens))  # type: int
    L = [int(next(tokens)) for _ in range(N)]  # type: "List[int]"
    solve(N, L)
    return

main()


from __future__ import absolute_import

import collections
import logging
import time
import uuid
from threading import Thread, Lock

import yaml
from k8s.client import NotFound
from k8s.models.common import ObjectMeta
from k8s.models.deployment import Deployment
from prometheus_client import Counter, Gauge
from .rbac import deploy_rbac

LOG = logging.getLogger(__name__)
NAME = 'fiaas-deploy-daemon'
DEPLOY_INTERVAL = 30

last_deploy_gauge = Gauge("last_triggered_deployment", "Timestamp for when last deployment was performed")
deploy_counter = Counter("deployments_triggered", "Number of deployments triggered and performed")
fiaas_enabled_namespaces_gauge = Gauge("fiaas_enabled_namespaces", "Number of namespaces that are FIAAS enabled")

Status = collections.namedtuple('Status', ['summary', 'description'])

class DeploymentStatus(object):
    def __init__(self, name, namespace, status, description, version, channel=None):
        self.name = name
        self.namespace = namespace
        self.status = status
        self.description = description
        self.version = version
        self.channel = channel

class Deployer(object):
    def __init__(self, cluster, release_channel_factory, bootstrap, spec_config_extension=None,
                 deploy_interval=DEPLOY_INTERVAL, rbac=False):
        self._cluster = cluster
        self._release_channel_factory = release_channel_factory
        self._bootstrap = bootstrap
        self._spec_extension = spec_config_extension
        self._deploy_interval = deploy_interval
        self.rbac = rbac

    def deploy(self, namespaces=None, force_bootstrap=False):
        deploy_counter.inc()
        last_deploy_gauge.set_to_current_time()
        deployment_configs = self._cluster.find_deployment_configs(NAME)
        fiaas_enabled_namespaces_gauge.set(len(deployment_configs))
        for deployment_config in deployment_configs:
            if namespaces and deployment_config.namespace not in namespaces:
                continue
            try:
                channel = self._release_channel_factory(deployment_config.name, deployment_config.tag)
                spec_config = self._load_spec(channel)
                LOG.debug(spec_config)
                if self.rbac:
                    deploy_rbac(deployment_config.namespace)
                self._deploy(deployment_config, channel, spec_config)
                if force_bootstrap or requires_bootstrap(deployment_config):
                    self._bootstrap(deployment_config, channel, spec_config, rbac=self.rbac)
            except Exception:
                LOG.exception("Failed to deploy %s in %s", deployment_config.name, deployment_config.namespace)
            time.sleep(self._deploy_interval)

    def _deploy(self, deployment_config, channel, spec_config):
        raise NotImplementedError("Subclass must override _deploy")

    def _load_spec(self, channel):
        spec_config = yaml.safe_load(channel.spec)
        return self._merge_extensions(spec_config)

    def _merge_extensions(self, spec_config):
        """This naively overwrites the value of the given key if present
        We may choose to do some smart merging supporting nested dictionaries at a later
        point but for now this simple behavior is sufficient
        """
        if not self._spec_extension:
            return spec_config
        self._log_changes(spec_config)
        spec_config.update(self._spec_extension)
        return spec_config

    def _log_changes(self, spec_config):
        for key in self._spec_extension:
            if key in spec_config:
                LOG.debug("Overwriting spec: " + key +
                          "=" + str(self._spec_extension[key]) +
                          " originally: " + key + "=" + str(spec_config[key]))
            else:
                LOG.debug("Extending spec with key: " + key +
                          "=" + str(self._spec_extension[key]))

    @staticmethod
    def _create_metadata(deployment_config):
        labels = {
            "app": deployment_config.name,
            "heritage": "FIAAS-Skipper",
            "fiaas/bootstrap": "true",
            "fiaas/deployment_id": str(uuid.uuid4())
        }
        return ObjectMeta(name=deployment_config.name,
                          namespace=deployment_config.namespace,
                          labels=labels)

def requires_bootstrap(deployment_config):
    try:
        Deployment.get(name=deployment_config.name, namespace=deployment_config.namespace)
        return False
    except NotFound:
        return True
    except Exception as e:
        LOG.warning(e, exc_info=True)

def _get_version(dep):
    return None if dep is None else dep.spec.template.spec.containers[0].image.split(":")[-1]

def _get_status(dep, app):
    if dep is None:
        return Status('NOT_FOUND', 'No deployment found')
    if app is None:
        return Status('VERSION_MISMATCH', 'Application is not defined')
    if not app or dep.spec.template.spec.containers[0].image != app.spec.image:
        return Status('VERSION_MISMATCH', 'Deployment does not match application version')
    try:
        if dep.status.availableReplicas < dep.spec.replicas:
            return Status('FAILED', 'Available replicas does not match the number of replicas in spec')
        # TODO the k8s deployment model can be extended to include ready replicas and status
    except TypeError:
        return Status('UNAVAILABLE', 'Unable to determine available/ready replicas from k8s server')
    return Status('OK', '')

class StatusTracker(Thread):
    def __init__(self, cluster, application, interval):
        Thread.__init__(self)
        self.daemon = True
        self._cluster = cluster
        self._status = {}
        self._application = application
        self._statuslock = Lock()
        self._interval = interval

    def __call__(self):
        with self._statuslock:
            return tuple(self._status.values())

    def _get_status(self, namespace=None):
        deployment_configs = self._cluster.find_deployment_configs(NAME, namespace=namespace)
        deployments = {d.metadata.namespace: d for d in Deployment.find(NAME, namespace=namespace)}
        applications = {d.metadata.namespace: d for d in self._application.find(NAME, namespace=namespace)}
        res = []
        for c in deployment_configs:
            dep = deployments.get(c.namespace)
            app = applications.get(c.namespace)
            version = _get_version(dep)
            status = _get_status(dep, app)
            res.append(DeploymentStatus(name=NAME,
                                        namespace=c.namespace,
                                        status=status.summary,
                                        description=status.description,
                                        version=version or '',
                                        channel=c.tag or ''))
        return res

    def _update_status(self):
        new_status = self._get_status()
        with self._statuslock:
            self._status = {status.namespace: status for status in new_status}

    def run(self):
        while True:
            self._update_status()
            time.sleep(self._interval)


import sys
import pprint as pp
import itertools as it

grid = [line.strip() for line in sys.stdin]

def evolve(grid: list[str]) -> list[str]:
    h, w = len(grid), len(grid[0])

    east = [["." for _ in range(w)] for _ in range(h)]
    for i, row in enumerate(grid):
        for j, c in enumerate(row):
            if c == ">":
                if grid[i][(j + 1) % w] == ".":
                    east[i][(j + 1) % w] = ">"
                else:
                    east[i][j] = ">"
            elif c == "v":
                east[i][j] = "v"

    south = [["." for _ in range(w)] for _ in range(h)]
    for i, row in enumerate(east):
        for j, c in enumerate(row):
            if c == "v":
                if east[(i + 1) % h][j] == ".":
                    south[(i + 1) % h][j] = "v"
                else:
                    south[i][j] = "v"
            elif c == ">":
                south[i][j] = ">"

    return ["".join(line) for line in south]

evolved = grid
for i in it.count():
    new = evolve(evolved)
    if new == evolved:
        print(i + 1)
        break
    evolved = new


from node import Node

class ArbolBinarioBalanceado:
    def __init__(self,nodos=None) -> None:
        '''
        Iniciamos el arbol binario balanceado con una raíz
        '''
        self.root = None
        if nodos is not None:
            self.agregar_nodos(nodos)

    def agregar_nodo(self, value: int):
        '''
        Permite agregar un nodo al arbol

        Args:
            value (int) : [Value of a node]
        '''
        # Le agrega a la raíz el siguiente nodo el cual lo agregaremos de manera recursiva en la funcion "agregar_nodo_recursivamente"
        self.root = self.agregar_nodo_recursivamente(self.root, value)
        # print(f'Se acaba de agregar {value}')

    def agregar_nodos(self,nodos):
        """
        Permite agregar varios nodos al tiempo

        Args:
            nodos(list) : [lista de valores a insertar]
        """
        for x in nodos:
            self.root = self.agregar_nodo_recursivamente(self.root,x)

    def agregar_nodo_recursivamente(self, current: int, value: int) -> Node:
        '''
        Permite agregar de manera recursiva un nodo al arbol

        Args:
            current (int) : [Current node]
            value   (int) : [Vale of the node we want to add]

        Returns:
            Node : Node we're going to add
        '''

        # Preguntamos que si el nodo actual es distinto de None, que me retorne el nodo con el valor que
        # queremos agregar (recordar que retorna un nodo porque lo queremos usar en el método de arriba llamado
        # agregar_nodo)
        if not current:
            return Node(value)

        # Si el valor es menor al valor del nodo actual, ira a la izquierda
        elif value < current.value:
            current.left = self.agregar_nodo_recursivamente(current.left, value)
        # Misma lógica para el lado derecho
        else:
            current.right = self.agregar_nodo_recursivamente(current.right, value)

        # Vamos a asignarle la altura al nodo
        current.height = 1 + max(self.get_hight(current.left), self.get_hight(current.right))

        # Falculamos el factor de equilibrio de los nodos a los caules estamos recorriendo para verificar
        # de inmediato si se deben realizar rotaciones o no
        factor_equilibrio = self.balanced_factor(current)

        # Aqui entra la lógica para que se autobalancee

        # Aqui considero si el factor de equilibrio es 2 o más y que el valor del nodo que este agregando
        # sea menor que la hoja (creo que todos saben que es una hoja), si va a la izquierda es que se va a desbalancear
        # hacia la izq así que hacemos una rotación derecha

        # Definición de Hoja: Nodo sin hijos

        if factor_equilibrio > 1 and value < current.left.value:
            return self.rotacion_derecha(current)

        # Aquí lo mismo pero cuando se va a desbalancear hacia la derecha
        if factor_equilibrio < -1 and value > current.right.value:
            return self.rotacion_izquierda(current)

        # Se realiza una rotación doble derecha (condiciones que me dijo chatgpt)
        if factor_equilibrio > 1 and value > current.left.value:
            current.left = self.rotacion_izquierda(current.left)
            return self.rotacion_derecha(current)

        # Se realiza una rotación doble izquierda (condiciones que me dijo chatgpt)
        if factor_equilibrio < -1 and value < current.right.value:
            current.right = self.rotacion_derecha(current.right)
            return self.rotacion_izquierda(current)

        return current

    def eliminar_nodo(self,root,value):
        '''
        Permite agregar de manera recursiva un nodo al arbol

        Args:
            root (int) : [Current node]
            value   (int) : [Vale of the node we want to delete]

        '''
        # Borrado de un BST tradicional
        if root is None:
            return root
        if value < root.value: #Avanzamos por el arbol
            root.left = self.eliminar_nodo(root.left,value)
        elif value>root.value:
            root.right = self.eliminar_nodo(root.right,value)
        else: # cuando llegamos al que tenga el value
        #se remplaza con algun hijo o tenga o None si no tiene
            if root.left is None: #hijo único derecho
                temp = root.right
                root = None
                return temp

            elif root.right is None: #hijo único izquierdo
                temp = root.left
                root = None
                return temp
            #si tiene dos hijos
            temp = self.leftmost(root.right)
            # replace root with smallest in right subtree
            root.value = temp.value
            root.right = self.eliminar_nodo(root.right,temp.value)

        #Se actualiza la altura
        root.height = 1 + max(self.get_hight(root.left),
                            self.get_hight(root.right))
        # Se calcula el factor de equilibrio
        factor = self.balanced_factor(root)

        # desbalanceado a la derecha
        if factor<-1 and self.balanced_factor(root.right)<=0:
            return self.rotacion_izquierda(root)
        if factor<-1 and  self.balanced_factor(root.right)>0:
            root.right = self.rotacion_derecha(root.right)
            return self.rotacion_izquierda(root)

        #desbalanceado a la izquierda
        if factor>1 and  self.balanced_factor(root.left)>=0:
            return self.rotacion_derecha(root)
        if factor>1 and self.balanced_factor(root.left)<0:
            root.left = self.rotacion_izquierda(root.left)
            return self.rotacion_derecha(root)

        return root

    # Calculamos el factor de equilibrio
    def balanced_factor(self, current: Node) -> int:
        '''
        Retorna el factor de equilibrio de un nodo

        Args:
            current (Node) : [Node for which we're trying to find the balance factor]

        Returns:
            Node : Returns the balanced factor of the node
        '''
        if not current:
            return 0
        return self.get_hight(current.left) - self.get_hight(current.right)

    def get_hight(self, current: Node) -> int:
        '''
        Devuelve la altura del arbol/subarbol de donde estemos tomando la raíz

        Args:
            current (Node) : [Node for which we're trying to find the height]
        '''
        if not current:
            return 0
        return current.height

    def levelOrderPrint(self, root: Node) -> None:
        '''
        Imprime el recorrido por niveles

        Args:
            root (Node) : [Our tree's root]
        '''
        height = self.get_hight(root)

        for level in range(1, height+1):
            print(f'Level {level}', end=': ')
            self.levelOrderTravel(root, level)
            print('\n')

    def levelOrderTravel(self, root: Node, level: int) -> None:
        '''
        Recorre el arbol por niveles

        Args:
            root  (Node) : [Node from where we're going to start the moving]
            level (int)  : [Respective level of the node where we started to move]
        '''
        if root is None:
            return
        if level == 1:
            print(f'{root.value}', end=' ')
        elif level > 1:
            self.levelOrderTravel(root.left, level-1)
            self.levelOrderTravel(root.right, level-1)

    def rotacion_derecha(self, current: Node) -> Node:
        '''
        Rotación simple derecha de un arbol balanceado

        Args:
            current (Node) : [Node where there're unbalanced factor]
        '''
        nueva_raiz = current.left
        current.left = nueva_raiz.right
        nueva_raiz.right = current

        # Arreglamos las respectivas alturas de los nodos que estamos moviendo
        current.height = 1 + max(self.get_hight(current.left), self.get_hight(current.right))
        nueva_raiz.height = 1 + max(self.get_hight(nueva_raiz.left), self.get_hight(nueva_raiz.right))

        return nueva_raiz

    def rotacion_izquierda(self, current: Node) -> Node:
        '''
        Rotación simple izquierda de un arbol balanceado

        Args:
            current (Node) : [Node where there're unbalanced factor]
        '''
        nueva_raiz = current.right
        current.right = nueva_raiz.left
        nueva_raiz.left = current

        # Arreglamos las respectivas alturas de los nodos que estamos moviendo
        current.height = 1 + max(self.get_hight(current.left), self.get_hight(current.right))
        nueva_raiz.height = 1 + max(self.get_hight(nueva_raiz.left), self.get_hight(nueva_raiz.right))

        return nueva_raiz

    def existe_nodo(self,value)->bool:
        """
        Busca un nodo, avisando si no es hallado

        Args:
            value:[value of node to find]

        Returns:
            True [If there is a node with value]
            False [if there is not ]
        """
        node = self.buscar_nodo_recursivo(self.root,value)
        # Usa llamado recursivo para guardar el resultado
        if node is None:
            return False
        else:
            return True

    def buscar_nodo(self,value):
        """
        Busca un nodo, avisando si no es hallado

        Args:
            value:[value of node to find]
        """
        node = self.buscar_nodo_recursivo(self.root,value)
        # Usa llamado recursivo para guardar el resultado
        if node is None:
            print(f"{value} no fue hallado")

    def buscar_nodo_recursivo(self,root,value):
        """
        Busca recursivamente un nodo
        y muestra la altura e hijos

        Args:
            root(Node): [current node]
            value(int/str): [value of node we search]
        """
        if root is None:
            return None
        else:
            if value<root.value:
                return self.buscar_nodo_recursivo(root.left,value)
            elif value>root.value:
                return self.buscar_nodo_recursivo(root.right,value)
            elif value == root.value:
                print(f"{root} height {root.height} left:{root.left} right {root.right}")
                return root

    def leftmost(self,root)->Node:
        """
        Regresa el nodo mas pequeño
        en un (sub)árbol

        Args:
            root(Node): [root of tree]
        """
        P = root
        lvl = 0
        while P.left is not None:
            lvl += 1
            P = P.left
        return P

    def buscar_padre(self,value)->Node:
        """
        Busca el padre de nodo con value

        Args:
            value:[value whose father we look for]

        Returns:
            Node:[if there is a father]
            None:[if there cannot be a father]
        """
        if self.root is None:
            print("None")
            return
        if self.root.value == value:
            return None
        else:
            traversed = []
            traversed.append(self.root)
            if self.root.value == value:
                self.root = None
            else:
                while len(traversed) !=0:
                    x = traversed.pop(0)
                    if x.left is not None:
                        if x.left.value == value:
                            return x
                        else:
                            traversed.append(x.left)
                    if x.right is not None:
                        if x.right.value == value:
                            return x
                        else:
                            traversed.append(x.right)

    def uncle(self,value):
        """
        Muestra (si lo tiene) el tío
        de un nodo

        Args:
            value:[value of node whose uncle we search]
        """
        father = self.buscar_padre(value) #  buscar papá
        if father is None:
            print(f"{value} has no father, therefore no uncle")
        elif father is self.root:
            print("father is root so there is no uncle")
        else:
            traversed = []
            traversed.append(self.root)
            if self.root.value == value: # find grandad select non father-child
                self.root = None
            else:
                while len(traversed) !=0:
                    x = traversed.pop(0)
                    if x.left is not None:
                        if x.left.value == father.value:
                            if x.right is not None:
                                print(f"uncle of {value} is {x.right}")
                                return
                        else:
                            traversed.append(x.left)
                    if x.right is not None:
                        if x.right.value == father.value:
                            if x.left is not None:
                                print(f"uncle of {value} is {x.left}")
                                return
                        else:
                            traversed.append(x.right)

    def grandad(self,value):
        """
        Muestra (si lo tiene) el abuelo de un nodo

        Args:
            value:[value of node whose uncle we search]
        """
        father = self.buscar_padre(value) # determino padre
        if father is None:
            print(f"{value} has no father, therefore no grandad")
        elif father is self.root:
            print("father is root, so there is no grandad")
        else:
            grandad = self.buscar_padre(father.value) # abuelo = padre de padre
            print(f"grandad of {value} is {grandad}")

# Instanciamos el arbol binario balanceado
#arbol = ArbolBinarioBalanceado([10,5,15,3,7,13,18,4,2,1])
arbol = ArbolBinarioBalanceado([10,7,14,5,12,15,8,4,11,13,6,9,16])

#arbol = ArbolBinarioBalanceado([3,5,2,4])
#arbol.root = arbol.eliminar_nodo(arbol.root,2)

# Probando el recorrido por niveles
arbol.levelOrderPrint(arbol.root)
arbol.root = arbol.eliminar_nodo(arbol.root,10)
arbol.levelOrderPrint(arbol.root)
'''
Referencias:

    - https://openai.com/blog/chatgpt/
    - https://www.utm.mx/~jahdezp/archivos%20estructuras/Arboles%20AVL.pdf
    - https://es.wikipedia.org/wiki/Rotaci%C3%B3n_de_%C3%A1rboles
    - https://www.geeksforgeeks.org/level-order-tree-traversal/

'''


import asyncio

from bot.utils import logger as KatLogger
from bot.utils import constants

MAX_EVENT_TIMER = constants.EventManager.MAX_EVENT_TIMER

class EventManager:
    """Managed event caller for Kat.

    Events are registered with `create_event` and are called every `seconds`.

    event information is stored in `self._events`:

    ```
        self._events = {
            "event-name": ()
        }

    """

    def __init__(self, bot, cog=None):
        """Creates new instance of EventManager

        arguments:
            bot: Kat - Bot that the event manager should run on.
            cog: extension.KatCog - KatCog instance which owns the event manager.
        """

        if cog is not None:
            # If we are not owned by a cog, then create a new logger.
            self.log = KatLogger.get_logger(
                "{}.EventManager".format(cog.qualified_name)
            )

        else:
            self.log = KatLogger.get_logger("EventManager")

        self.bot = bot
        self._events = {}

    def create_event(self, name, seconds):
        """Register an event `name` to loop every `seconds`."""

        if not name.startswith("kat"):
            # ensure our events start with a prefix as to not interfer with internal ones.
            name = "kat_" + name

        if "on_" + name in self.bot.extra_events:
            # If we have already registered this event.
            self.log.warning(
                "Tried to create event `{}` that already exists!".format(name)
            )
        elif seconds > MAX_EVENT_TIMER:
            self.log.warning(
                "Tried to create event `{}` with a wait period longer than {} seconds.".format(
                    name, MAX_EVENT_TIMER
                )
            )
        else:

            event = self.bot.loop.create_task(self._event(name, seconds))
            self._events[name] = event
            self.log.info(
                f"Registered new event `{name}` for every `{seconds}` seconds"
            )

    def create_events(self, event_map: dict):
        """Create multiple events.

        `event_map`: Dict - {'event_name': int}
        """

        for k, v in event_map.items():
            self.create_event(k, v)

    def remove_event(self, name):
        """Unregister an event.

        `name`: str - Event name to unregister.
        """

        if name in self._events:
            try:
                self._events[name].cancel()
                del self._events[name]
                self.log.info("Deleted event `{}`".format(name))

            except Exception as e:
                self.log.exception(
                    "Exception caught whilst trying to delete event `{}` ".format(name),
                    exc_info=e,
                )
                return -1
        else:
            self.log.warning(
                "Tried to delete event that doesn't exist in this EventManager instance."
            )
            return -2

    def destroy(self):
        """Safely stops all running events and ends the instance.

        Should be called whenever a KatCog unloads.
        """

        for name in self._events:
            try:
                self.log.debug("Attempting to delete event `{}`".format(name))
                self._events[name].cancel()
            except Exception as e:
                self.log.exception(
                    "Exception caught whilst trying to delete event `{}` ".format(name),
                    exc_info=e,
                )
        del self

    async def _event(self, name, seconds):
        """Calls event and waits."""
        while name in self._events:
            self.bot.dispatch(name)
            await asyncio.sleep(seconds)


import shutil
import os
import sys
import myconto

"""Тестируем функции из проекта Леонилдва Орлова"""

def filenames():
    result = []
    for item in os.listdir():
        if os.path.isfile(item):
            result.append(item)
    return result

def copy_file_or_directory(name, new_name):
    if os.path.isdir(name):
        shutil.copytree(name, new_name)
    else:
        shutil.copyfile(name, new_name)

#Тестируем не ЧИСТУЮ функцию:
def test_copy_file_or_directory():
    file_list = filenames()
    file_name = str(file_list[0])
    copy_file_or_directory(file_name,file_name+"01")
    file_list = filenames()
    assert file_name+"01" in file_list

def author_info():
    return 'Leonid Orlov'

#Тестируем ЧИСТУЮ функцию:
def test_author_info():
    assert author_info() == 'Leonid Orlov'

# соответствие месяца и его названия
months = {
    '01': 'января',
    '02': 'февраля',
    '06': 'июня'
}

# соответствие дня и его названия
days = {
    '01': 'первое',
    '02': 'второе',
    '03': 'третье',
    '04': 'четвертое',
    '12': 'двенадцатое',
    '26': 'двадцать шестое'
}

def date_to_str(date):
    """
    Функция приводит дату к текстовому виду
    :param date: дата в формате dd.mm.yyyy
    :return: дата в текстовом виде
    """
    day, month, year = date.split('.')
    result = f'{days[day]} {months[month]} {year} года'
    return result

def test_date_to_str():
    assert date_to_str("04.02.1799") == "четвертое февраля 1799 года"

def separator(count=30):
    """
    Функция разделитель
    :param count: количество звездочек
    :return: красивый разделитель
    """
    return '*' * count

#nтестируем простую функцию
def test_separator():
    assert separator(5) == "*****"
    assert separator() == 30*"*"

#естируем новыt функции дяя myconto
def test_myconto():
    myconto.save_acc(12.345, 'conto.bin')
    assert myconto.restore_acc('conto.bin') == 12.345

def test_log():
    myconto.save_log([["AAA", 12.34], ["BBB", 43.21]], 'purch.log')
    assert myconto.restore_log('purch.log') == [["AAA", 12.34], ["BBB", 43.21]]


import arcade
import Settings

class ArtificialPlayer(arcade.Sprite):
    def __init__(self, map_obj, row, col):
        super().__init__("graphics/adventurer/robot_stand.png", Settings.SPRITE_SCALING)
        self.map = map_obj
        self.row = row
        self.col = col

        self.right = (self.col * Settings.SCALED_PIXEL_SIZE) - 6
        self.bottom = -(self.row + 1) * Settings.SCALED_PIXEL_SIZE

        self.score = 0

        # AI stuff
        self.move_timer_length = 0.3
        self.move_timer = self.move_timer_length
        self.instruction_list = []
        self.map_array = self.map.get_map(self.map.map_file_name)

        self.generate_instruction_list()
        # self.visited = self.map_array

    def generate_instruction_list(self):
        start = None
        end = None

        if self.map.map_file_name == "map_3.csv":
            start = [4, 2]
            end = [20, 9]
        if self.map.map_file_name == "map_2.csv":
            start = [1, 1]
            end = [13, 5]
        if self.map.map_file_name == "map_1.csv":
            start = [1, 1]
            end = [7, 5]

        self.instruction_list = self.bfs(self.map_array, start, end)
        self.instruction_list.reverse()

    def update_ai(self, delta_time):
        self.move_timer -= delta_time
        if self.move_timer <= 0:
            self.move_timer += self.move_timer_length

            if self.map_array[self.row+1][self.col] == 35:
                self.dig_down()
                return

            if len(self.instruction_list) > 0:
                instruction1 = self.instruction_list[len(self.instruction_list) - 1]
                instruction2 = self.instruction_list[len(self.instruction_list) - 2]

                if instruction1[0] == instruction2[0] and instruction1[1] < instruction2[1]:
                    self.move_right()
                elif instruction1[0] == instruction2[0] and instruction1[1] > instruction2[1]:
                    self.move_left()

                elif instruction1[0] > instruction2[0] and instruction1[1] > instruction2[1]:
                    self.move_left()
                elif instruction1[0] > instruction2[0] and instruction1[1] < instruction2[1]:
                    self.move_right()

                elif instruction1[0] < instruction2[0] and instruction1[1] == instruction2[1]:
                    self.dig_down()

                self.instruction_list.pop()

            else:
                self.map.game.end_game()

    def bfs(self, maze, start, end):

        queue = [start]
        visited = []

        while len(queue) != 0:
            if queue[0] == start:
                path = [queue.pop(0)]  # Required due to a quirk with tuples in Python
            else:
                path = queue.pop(0)
            front = path[-1]
            if front[0] == end[0] and front[1] == end[1]:
                return path
            elif front not in visited:
                adjacent_spaces = self.get_adjacent_spaces(maze, front, visited)
                for adjacent_space in adjacent_spaces:
                    new_path = list(path)
                    new_path.append(adjacent_space)
                    queue.append(new_path)
                visited.append(front)
        return None

    def get_adjacent_spaces(self, maze, space, visited):
        # Returns all legal spaces surrounding the current space
        # :param space: tuple containing coordinates (row, col)
        # :return: all legal spaces
        spaces = list()
        # spaces.append((space[0]-1, space[1]+1))# Climb
        # spaces.append((space[0]+1, space[1]-1))# Climb
        spaces.append((space[0]+1, space[1]))  # Down
        spaces.append((space[0], space[1]-1))  # Left
        spaces.append((space[0], space[1]+1))  # Right

        final = list()
        for i in spaces:
            if maze[i[0]][i[1]] != 34 and maze[i[0]][i[1]] != 32 and maze[i[0]][i[1]] != 40 and maze[i[0]][i[1]] != 57 and i not in visited:
                final.append(i)
        return final

    def move_left(self):
        # Check if we can move into the space to the left of us
        target_block = self.map.get_block(self.row, self.col - 1)

        if target_block is not None:

            if target_block.block_type is "air" or target_block.block_type is "gold_nugget":

                if target_block.block_type is "gold_nugget":
                    target_block.destroy_block()
                    self.score += 1

                self.col -= 1
                self.update_player_position()
                self.check_if_player_should_fall()

            else:
                # Check if we can climb up what's blocking us
                climb_block_check = self.map.get_block(self.row - 1, self.col - 1)

                if climb_block_check is not None and (climb_block_check.block_type is "air" or climb_block_check.block_type is "gold_nugget"):

                    if climb_block_check.block_type is "gold_nugget":
                        climb_block_check.destroy_block()
                        self.score += 1

                    self.row -= 1
                    self.col -= 1
                    self.update_player_position()

    def move_right(self):
        # Check if we can move into the space to the right of us
        target_block = self.map.get_block(self.row, self.col + 1)

        # Only None if we're out of bounds
        if target_block is not None:

            if target_block.block_type is "air" or target_block.block_type is "gold_nugget":

                if target_block.block_type is "gold_nugget":
                    target_block.destroy_block()
                    self.score += 1

                self.col += 1
                self.update_player_position()
                self.check_if_player_should_fall()

            else:
                # Check if we can climb up what's blocking us
                climb_block_check = self.map.get_block(self.row - 1, self.col + 1)

                if climb_block_check is not None and (climb_block_check.block_type is "air" or climb_block_check.block_type is "gold_nugget"):

                    if climb_block_check.block_type is "gold_nugget":
                        climb_block_check.destroy_block()
                        self.score += 1

                    self.row -= 1
                    self.col += 1
                    self.update_player_position()

    def dig_down(self):
        block_to_dig = self.map.get_block(self.row + 1, self.col)

        if block_to_dig is not None:

            if block_to_dig.block_type is "stone":
                self.map.destroy_map_block(self.row + 1, self.col)
                self.row += 1
                self.update_player_position()
                self.check_if_player_should_fall()

            elif block_to_dig.block_type is "stone_gold":
                self.map.destroy_map_block(self.row + 1, self.col)
                self.score += 5
                self.row += 1
                self.update_player_position()
                self.check_if_player_should_fall()

    def check_if_player_should_fall(self):
        block_to_check = self.map.get_block(self.row + 1, self.col)

        if block_to_check is not None:
            if block_to_check.block_type is "air" or block_to_check.block_type is "gold_nugget":
                self.make_player_fall()

    def make_player_fall(self):
        next_block = self.map.get_block(self.row + 1, self.col)

        while next_block is not None and (next_block.block_type is "air" or next_block.block_type is "gold_nugget"):

            if next_block.block_type is "gold_nugget":
                next_block.destroy_block()
                self.score += 1

            self.row += 1
            self.update_player_position()
            next_block = self.map.get_block(self.row + 1, self.col)

    # This function updates the robot's sprite to their new position
    def update_player_position(self):
        self.right = (self.col * Settings.SCALED_PIXEL_SIZE) - 6
        self.bottom = -(self.row + 1) * Settings.SCALED_PIXEL_SIZE


import os
import json
from setuptools import setup

with open("README.md", "r", encoding="utf8") as fh:
    long_description = fh.read()

with open(
    os.path.join("webviz_subsurface_components", "package.json"), encoding="utf8"
) as f:
    package = json.load(f)

package_name = (
    package["name"]
    .replace(" ", "_")
    .replace("-", "_")
    .replace("/", "_")
    .replace("@", "")
)

INSTALL_REQUIRES = [
    "dash>=2.0",
    "numpy>=1.14",
    "pandas>=1.0",
]

TESTS_REQUIRE = [
    "bandit",
    "black>=20.8b1",
    "dash[testing]",
    "jsonpatch>=1.32",
    "jsonpointer>=2.1",
    "matplotlib>=3.0",
    "Pillow>=6.0",
    "pylint>=2.4",
    "scipy>=1.2",
    "selenium>=3.141",
    "webviz-core-components>=0.6.0",
]

setup(
    name=package_name,
    author=package["author"],
    packages=[package_name],
    include_package_data=True,
    license=package["license"],
    description=package["description"],
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/equinor/webviz-subsurface-components",
    install_requires=INSTALL_REQUIRES,
    tests_require=TESTS_REQUIRE,
    extras_require={"tests": TESTS_REQUIRE, "dependencies": INSTALL_REQUIRES},
    setup_requires=["setuptools_scm~=7.0"],
    python_requires="~=3.8",
    use_scm_version=True,
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent",
        "Natural Language :: English",
        "Environment :: Web Environment",
        "Framework :: Dash",
        "Framework :: Flask",
        "Topic :: Multimedia :: Graphics",
        "Topic :: Scientific/Engineering",
        "Topic :: Scientific/Engineering :: Visualization",
        "License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)",
    ],
)


from django.core.mail import EmailMessage
from rest_framework import viewsets

from contact.api import serializers
from contact.models import Email
from rest_framework.permissions import AllowAny

from sahyog_settings import settings

def send_email(receiver_email):
    email = EmailMessage(
        settings.CONTACT_US_SUBJECT_CONTENT,
        settings.CONTACT_US_MESSAGE_BODY,
        settings.CONTACT_US_SENDER_EMAIL,
        [receiver_email]
    )
    email.send()

class EmailViewSet(viewsets.ModelViewSet):
    permission_classes = (AllowAny,)
    serializer_class = serializers.EmailSerializer
    queryset = Email.objects.all()

    def create(self, request, *args, **kwargs):
        response = super(EmailViewSet, self).create(request, *args, **kwargs)
        send_email(self.request.data.get('email'))  # sending mail
        return response


"""
Thuật toán bubble sort
"""
import random as rd
import time
import  copy
import matplotlib.pyplot as plt
import sys
sys.setrecursionlimit(4002)
def bubbleSort(key):
    n = len(key)
    for i in range(n -1 ):
        for j in range(0,n-i- 1):
            if key[j] > key[j+1]:
                key[j] , key[j+1] = key[j+1], key[j]
"""
Thuật toán selection sort
"""
def SelectionSort(key):
    n = len(key)
    for i in range(n-1):
        k = i
        for j in range(i+1 ,n):
            if(key[k] > key[j]):
                k = j
        if (k!= i):
            key[i], key[k] = key[k] , key[i]
"""
Thuật toán insert Sort
"""
def InsertSort(key):
    n = len(key)
    for i in range(1,n):
        vt = i -1
        x = key[i]
        while(vt>=0 and key[vt] > x):
            key[vt +1] = key[vt]
            vt -= 1
        key[vt+1] = x
"""
Thuat toan merge sort
"""

def Merge(key, left, mid, right):
    i = left
    j = mid +1
    key1 = list()
    while (i <= mid and j <= right):
        if (key[i] > key[j]):
            key1.append(key[j])
            j += 1
        else:
            key1.append(key[i])
            i += 1
    if (i > mid):
        for a in range(j, right +1):
            key1.append(key[a])
    else:
        for a in range(i,mid+1):
            key1.append(key[a])
    key[left:right+1] = key1

def MergeSort(key, left, right):
    if left < right:
        mid = int((left + right) / 2)
        MergeSort(key, left, mid)
        MergeSort(key, mid + 1, right)
        Merge(key, left, mid, right)
"""
Thuat toan heap sort
"""
def heapify(key, n, i):
    largest = i
    left = 2 * i
    right = 2 * i + 1
    if left < n and key[left] > key[largest]:
        largest = left
    if right < n and key[right] > key[largest]:
        largest = right
    if largest is not i:
        key[i], key[largest] = key[largest], key[i]
        heapify(key, n, largest)

def heapSort(key, n):
    i = int(n / 2 - 1)
    while i >= 0:
        heapify(key, n, i)
        i = i - 1
    j = n - 1
    while j > 0:
        key[j], key[0] = key[0], key[j]
        heapify(key, j, 0)
        j = j - 1
"""
thuat toan quick sort
"""
def partition(key, left , right):
    j = rd.randint(left, right)
    key[j], key[right] = key[right], key[j]
    pos = left
    pivot = key[right]
    for i in range(left ,right) :
        if key[i] <= pivot:
            key[i] , key [pos] = key[pos], key[i]
            pos +=1
    key[pos], key[right] = key[right] , key[pos]
    return pos

def quickSort(key , left ,right) :
    if left < right :
        pos = partition(key , left , right)
        quickSort(key , left , pos -1)
        quickSort(key , pos+1 , right)
"""
Ham ve do thi
"""
print(sys.getrecursionlimit())
def graphic():
    nPoints = 15
    timesBubble = list()
    timesSelection = list()
    timesInsert = list()
    timesMerge = list()
    timesQuick = list()
    n = 5000
    listPoints = list()
    key = list()
    for i in range(nPoints):
        key = list(range(n))
        #key = rd.sample(range(n), n)
        key1 = copy.copy(key)
        key2 = copy.copy(key)
        key3 = copy.copy(key)
        key4 = copy.copy(key)
        key5 = copy.copy(key)
        start = time.time()
        bubbleSort(key1)
        end = time.time()
        timesBubble.append(end - start)
        start = time.time()
        SelectionSort(key2)
        end = time.time()
        timesSelection.append(end - start)
        start = time.time()
        InsertSort(key3)
        end = time.time()
        timesInsert.append(end - start)
        start = time.time()
        MergeSort(key4, 0, len(key4) -1 )
        end = time.time()
        timesMerge.append(end - start)
        start = time.time()
        quickSort(key5,0, len(key5) -1)
        end = time.time()
        timesQuick.append(end - start)
        listPoints.append(n)
        n = n + 100
    plt.figure(figsize= (10,10))
    plt.plot(listPoints, timesBubble, 'go-', label='Bubble Sort')
    plt.plot(listPoints, timesSelection, 'ro-', label='Selection Sort')
    plt.plot(listPoints, timesInsert, 'bD-', label='Insert Sort')
    plt.plot(listPoints, timesMerge, 'g^-', label='Merge Sort')
    #plt.plot(listPoints, timesHeap, 'ro-', label='Heap Sort')
    plt.plot(listPoints, timesQuick, '-', label='Quick Sort')
    plt.legend(loc = 'best')
    plt.title('Investigate the runtime of sorting algorithms')
    plt.xlabel('The size of data')
    plt.ylabel('Running time (s)')
    plt.show()
graphic()


import dash
import dash_core_components as dcc
import dash_html_components as html
from dash.dependencies import Input, Output
import pandas as pd
import plotly.express as px
import plotly
import plotly.graph_objects as go
from plotly.subplots import make_subplots

from tabs.utils import line_plot, heat_plot
from app import app

date_dict = {
    'all_weekday':'วันธรรมดา (จ - ศ)',
    'normal_weekend':'วันหยุด (ส - อา)',
    'normal_monday':'วันจันทร์',
    'normal_friday':'วันศุกร์',
    'mother_day':'วันแม่'
}

date_dropdown = [{'label': date_dict[k],'value': k } for k in date_dict]

df_date = {}

def load_data(date):
    f = 'https://storage.googleapis.com/speed_csv/speed_%s.csv'%(date)
    df = pd.read_csv(f)
    df.sort_values(by=['round_min','lon3'], inplace = True)
    return df

def init_data():
    for k in date_dict:
        df_date[k] = load_data(k)

init_data()

#######################################################################################
# df = load_data()

layout = html.Div(children=[
    html.H1(
        children='พระราม 4 Dashboard',
        style={
            'textAlign': 'center',
        }
    ),

    html.Div(children='ความเร็วเฉลี่ยบนถนนพระรามที่ 4', style={
        'textAlign': 'center',
    }),

    html.Div(children = [dcc.Dropdown(
        id='date-dropdown',
        options=date_dropdown,
        value='all_weekday'
        )],style={'textAlign': 'center','padding' : 20}
    ),

    # html.Div(id='dd-output-container'),

    dcc.Loading(id = 'loading-speed',
        children = [
            html.Div([dcc.Graph(
                id='speed-line',
            # figure= plot_line(df)
            )],style={'padding' : 20})
        ]
    ),

    dcc.Loading(id = 'loading-heat',
        children = [
            html.Div([dcc.Graph(
                id='speed-heat',
                # figure= plot_heat(df)
            )], style={'padding' : 20})
        ]
    ),

])

@app.callback(
    dash.dependencies.Output('speed-line', 'figure'),
    [dash.dependencies.Input('date-dropdown', 'value')])
def update_speed(value):
    return line_plot.plot_line_csv(df_date[value],date_dict[value])

@app.callback(
    dash.dependencies.Output('speed-heat', 'figure'),
    [dash.dependencies.Input('date-dropdown', 'value')])
def update_heat(value):
    # df = load_data(value)
    return heat_plot.plot_heat(df_date[value],date_dict[value])

# @app.callback(
#     dash.dependencies.Output('dd-output-container', 'children'),
#     [dash.dependencies.Input('date-dropdown', 'value')])
# def update_output(value):
#     return 'You have selected "{}"'.format(value)


from django.shortcuts import render,redirect

# Create your views here.
from pulses.models import snacks,vendor

def h1(request):
    a=snacks.objects.all()
    return render(request,'master/h1.html',{'b':a})

def login(request):
    return render(request,'master/login.html')
def start(request):

    if request.method == 'POST' and request.FILES['product_image']:
        q = request.FILES['product_image']
        w = request.POST.get('product_name')
        e = request.POST.get('product_code')
        r = request.POST.get('price')
        t = request.POST.get('description')
        y = request.POST.get('health_benefits')
        snacks.objects.create(product_image=q,product_name=w,product_code=e,price=r,description=t,health_benefits=y)
        return redirect('view_p')
    return render(request,'master/start.html')

def view_p(request):
    w=snacks.objects.all()
    return render(request,'master/view_p.html',{'b':w})

def update_p(request,pk):
    w= snacks.objects.filter(id=pk)
    if request.method == 'POST' and request.FILES['product_image']:
        q = request.FILES['product_image']
        w = request.POST.get('product_name')
        e = request.POST.get('product_code')
        r = request.POST.get('price')
        t = request.POST.get('description')
        y = request.POST.get('health_benefits')
        snacks.objects.filter(id=pk).update(product_image=q, product_name=w, product_code=e, price=r,description=t,health_benefits=y)
        return redirect('view_p')
    return render(request,'master/update_p.html',{'b':w})

def delete_p(request,pk):
    snacks.objects.filter(id=pk).delete()
    w = snacks.objects.all()
    return render(request,'master/delete_p.html',{'b':w})


from django.shortcuts import render
from django.contrib.auth import logout as django_logout
from django.http import HttpResponseRedirect
from decouple import config
import json
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect, HttpResponse
from django.views.decorators.csrf import csrf_protect
from django.db import models
from dynamic_models.models import ModelSchema, FieldSchema
from django.urls import clear_url_caches
from importlib import import_module, reload
from django.contrib import admin
from django.conf import settings
from .models import Modelnames

# Create your views here.

def base2(request):
    return render(request, 'base2.html')

def addModelEntries(request):
    return redirect('/admin')

def createModels(request):
    modelExists = False
    modelCreated = False
    modelName = ''
    if request.POST:
        modelName = request.POST['modelname']
        try:
            model_schema = ModelSchema.objects.create(
                name=request.POST['modelname'])
            modelCreated = True
        except Exception as e:
            modelExists = True
            return render(request, 'createModels.html', context={'modelExists': modelExists, 'modelCreated': modelCreated, 'modelName': modelName})
        len_req = (len(request.POST) - 2) // 5
        count = 0
        for x in range(len_req):
            count = count + 1
            field_schema = FieldSchema.objects.create(
                name=request.POST['field' + str(count)],
                data_type=request.POST['datatype' + str(count)],
                model_schema=model_schema,
                max_length=request.POST['maxlen' + str(count)],
                null=request.POST['null' + str(count)],
                unique=request.POST['unique' + str(count)]
            )
        model_create = Modelnames.objects.create(
            modelname=request.POST['modelname'])
        reg_model = model_schema.as_model()
        admin.site.register(reg_model)
        reload(import_module(settings.ROOT_URLCONF))
        clear_url_caches()
    return render(request, 'createModels.html', context={'modelExists': modelExists, 'modelCreated': modelCreated, 'modelName': modelName})

def showObjectLists(request):
    modelNamesQuerySet = Modelnames.objects.all()
    modelNames = list()
    for model in modelNamesQuerySet:
        modelNames.append(model.modelname)
    cont_dict = {
        'modelNames': modelNames,
        'get': True
    }
    if request.POST:
        model = ModelSchema.objects.get(
            name=request.POST['modelname']).as_model()
        objList = model.objects.all().values()
        fieldNames = list()
        noEntry = False
        try:
            for x in objList[0]:
                fieldNames.append(x)
        except Exception as e:
            noEntry = True
        cont_dict = {
            'modelNames': modelNames,
            'objects': objList,
            'noEntry': noEntry,
            'fieldNames': fieldNames,
            'objectType': request.POST['modelname'],
            'get': False
        }
    return render(request, 'displayObjects.html', context=cont_dict)

# Create your views here.

def index(request):
    return render(request,'index.html')

def profile(request):
    user=request.user

    auth0_user=user.social_auth.get(provider='auth0')

    user_data={
        'user_id':auth0_user.uid,
        'name':user.first_name,
        'picture':auth0_user.extra_data['picture']
    }

    context={
        'user_data':json.dumps(user_data,indent=4),
        'auth0_user':auth0_user
    }

    return render(request,'profile.html',context)

#logout
# https://{domain}/v2/logout?client_id={client_id}&returnTo={return_to}

def logout(request):
    django_logout(request)

    domain=config('APP_DOMAIN')
    client_id=config('APP_CLIENT_ID')
    return_to='http://127.0.0.1:8000/'

    return HttpResponseRedirect(f"https://{domain}/v2/logout?client_id={client_id}&returnTo={return_to}")


import pycalibtic
import pywrapstdvector
import pylogging
import os
import getpass
import copy
import time
import numpy as np

import pyhalco_hicann_v2 as Coordinate
from pyhalbe.HICANN import neuron_parameter, shared_parameter
from pycake.helpers.units import DAC, Volt, Ampere, Unit, Second

def create_pycalibtic_transformation(coefficients, domain=None, trafo_type=pycalibtic.Polynomial):
    """Create a pycalibtic.Polynomial from a list of coefficients.

    Order: [c0, c1, c2, ...] resulting in c0*x^0 + c1*x^1 + c2*x^2 + ...

    Domain should be a tuple wit min and max possible hardware value"""
    # Make standard python list to have the right order
    if coefficients is None:
        return None
    coefficients = list(coefficients)
    data = pywrapstdvector.Vector_Double(coefficients)
    if domain is None:
        return trafo_type(data)
    return trafo_type(data, domain[0], domain[1])

class Calibtic(object):
    logger = pylogging.get("pycake.calibtic")

    def __setstate__(self, dic):
        # For old pickles: just set bigcap and speedup to default values
        # Otherwise, unpickling of old calibtic helpers does not work
        if 'pll' not in dic:
            dic['pll'] = 0.0
        if 'ideal_nc' not in dic:
            dic['ideal_nc'] = pycalibtic.NeuronCollection()
            dic['ideal_nc'].setDefaults()
        if 'ideal_bc' not in dic:
            dic['ideal_bc'] = pycalibtic.BlockCollection()
            dic['ideal_bc'].setDefaults()
        if not ('bigcap' in dic and 'speedup' in dic):
            dic['bigcap'] = True
            dic['speedup'] = 'normal'
            dic['hc'] = None
        if 'hc' not in dic:
            self.hc = self.load_calibration()

    def __init__(self, path, wafer, hicann, pll=125e6, backend_type='xml'):
        self.path = self.make_path(path)
        self.wafer = wafer
        self.hicann = hicann
        self.pll = pll

        self.ideal_nc = pycalibtic.NeuronCollection()
        self.ideal_nc.setDefaults()
        self.ideal_bc = pycalibtic.BlockCollection()
        self.ideal_bc.setDefaults()
        self.hc = self.load_calibration(backend_type)

    def get_backend(self, type='xml'):
        if type == 'xml':
            lib = pycalibtic.loadLibrary('libcalibtic_xml.so')
            backend = pycalibtic.loadBackend(lib)
            backend.config('path', self.path)
            backend.init()
            return backend
        elif type == 'binary':
            lib = pycalibtic.loadLibrary('libcalibtic_binary.so')
            backend = pycalibtic.loadBackend(lib)
            backend.config('path', self.path)
            backend.init()
            return backend
        else:
            raise ValueError("unknown backend type")

    @staticmethod
    def make_path(path):
        path = os.path.expanduser(path)
        if not os.path.isdir(path):
            Calibtic.logger.INFO("Creating backend path {}".format(path))
            os.makedirs(path)
        return path

    def clear_calibration(self):
        """ Clears all calibration data.
        """
        name = self.get_calibtic_name()
        fullname = name + ".xml"
        fullpath = os.path.join(self.path, fullname)
        if os.path.isfile(fullpath):
            msg = "Clearing calibration data by removing file {}"
            self.logger.INFO(msg.format(fullpath))
            os.rename(fullpath, fullpath + time.strftime('.%y%m%d_%H%M%S.bak'))

    def clear_one_calibration(self, parameter):
        """ Only clears the calibration for one parameter.
        """
        if isinstance(parameter, shared_parameter):
            collection = self.bc
            ids = list(range(4))
        else:
            collection = self.nc
            ids = list(range(512))

        for i in ids:
            self.logger.TRACE("Resetting calibration for parameter {} for id {}".format(parameter.name, i))
            collection.at(i).reset(parameter, None)

    def get_calibtic_name(self):
        wafer_id = self.wafer.value()
        hicann_id = self.hicann.toEnum().value()
        name = "w{}-h{}".format(int(wafer_id), int(hicann_id))
        return name

    def load_calibration(self, backend_type='xml'):
        """ Load existing calibration data from backend.
        """

        hc = pycalibtic.HICANNCollection()
        md = pycalibtic.MetaData()

        # load existing calibration
        try:
            name = self.get_calibtic_name()
            backend = self.get_backend(backend_type)
            backend.load(name, md, hc)
            calibration_existed = True
        except RuntimeError as e:
            if "data set not found" not in str(e):
                raise

            # Delete all standard entries.
            #TODO: fix calibtic to use proper standard entries

            nc = hc.atNeuronCollection()
            for nid in range(512):
                nc.erase(nid)
            bc = hc.atBlockCollection()
            for bid in range(4):
                bc.erase(bid)
            hc.setPLLFrequency(int(self.pll))

        if hc.getPLLFrequency() != self.pll:
            msg  = "PLL stored in HICANNCollection {} MHz != {} MHz set here"
            self.logger.ERROR(
                msg.format(hc.getPLLFrequency()/1e6, self.pll/1e6))
        return hc

    @property
    def nc(self):
        """Returns a pycalibtic.NeuronCollection"""
        return self.hc.atNeuronCollection()

    @property
    def bc(self):
        """Returns a pycalibtic.BlockCollection"""
        return self.hc.atBlockCollection()

    def get_calib_id(self, param_name,
                     target_bigcap,
                     target_I_gl_speedup,
                     target_I_gladapt_speedup,
                     target_I_radapt_speedup):
        """ try to access the calibration id by the same name,
            if it fails, try with speedup and bigcap suffix

            Args:
                 target_bigcap: True/False
                 target_*_speedup: "slow"/"fast"

            works only for neuron_parameter
        """

        calibs = pycalibtic.NeuronCalibrationParameters.Calibrations

        try:
            calib_id = getattr(calibs, param_name)
        except AttributeError:
            slow = locals()["target_{}_speedup".format(param_name)] == "slow"
            fast = locals()["target_{}_speedup".format(param_name)] == "fast"
            suffix = "slow{}_fast{}_bigcap{}".format(int(slow), int(fast), int(target_bigcap))
            calib_id = getattr(calibs, "{}_{}".format(param_name, suffix))
        return calib_id

    def write_calibration(self, parameter, trafos,
                          target_bigcap,
                          target_I_gl_speedup,
                          target_I_gladapt_speedup,
                          target_I_radapt_speedup,
                          backend_type='xml'):
        """ Writes calibration data to backend

            Args:
                parameter: which neuron or hicann parameter
                trafos: dict { coord : pycalibtic.transformation }
        """
        name = self.get_calibtic_name()

        for coord, trafo in trafos.items():

            if trafo is None:
                continue

            if isinstance(parameter, shared_parameter) and isinstance(coord, Coordinate.FGBlockOnHICANN):
                collection = self.bc
                cal = pycalibtic.SharedCalibration()
                calib_id = parameter
                param_name = parameter.name
            elif isinstance(parameter, neuron_parameter) and isinstance(coord, Coordinate.NeuronOnHICANN):
                collection = self.nc
                cal = pycalibtic.NeuronCalibration()
                param_name = parameter.name
                calib_id = self.get_calib_id(param_name, target_bigcap, target_I_gl_speedup, target_I_gladapt_speedup, target_I_radapt_speedup)
            elif parameter == 'readout_shift':
                collection = self.nc
                cal = pycalibtic.NeuronCalibration()
                calib_id = pycalibtic.NeuronCalibrationParameters.Calibrations.ReadoutShift
                param_name = parameter
            else:
                raise RuntimeError("Cannot write calibration for parameter {} of coordinate {}".format(parameter, coord))

            index = coord.toEnum().value()

            if not collection.exists(index):
                collection.insert(index, cal)
            collection.at(index).reset(calib_id, trafo)
            self.logger.TRACE("Resetting coordinate {} parameter {} to {}".format(coord, param_name, trafo))
        md = pycalibtic.MetaData()
        backend = self.get_backend(backend_type)
        backend.store(name, md, self.hc)

    def get_calibration(self, coord, use_ideal=False):
        """ Returns NeuronCalibration or SharedCalibration object for one coordinate.

            If a collection is not found und use_ideal is set to True, returns an ideal calibration
            This is turned off by default.
            If no calibration is found for a coordinate, it returns an empty calibration.
        """
        c_id = coord.toEnum().value()

        if isinstance(coord, Coordinate.FGBlockOnHICANN):
            collection = self.bc
            calibration = pycalibtic.SharedCalibration
        else:
            collection = self.nc
            calibration = pycalibtic.NeuronCalibration

        if collection.exists(c_id) and not use_ideal:
            self.logger.TRACE("Found Calibration for {}".format(coord))
            return collection.at(c_id)
        elif use_ideal:
            self.logger.WARN("No calibration dataset found for {}. Returning ideal calibration.".format(coord))
            if isinstance(coord, Coordinate.FGBlockOnHICANN):
                return self.ideal_bc.at(c_id)
            else:
                return self.ideal_nc.at(c_id)
        else:
            # return empty calibration if none exists
            self.logger.WARN("No calibration dataset found for {}. Returning empty calibration".format(coord))
            if calibration == pycalibtic.NeuronCalibration:
                return calibration(False)
            else:
                return calibration()

    def get_readout_shift(self, neuron):
        """
        """
        calib = self.get_calibration(neuron)
        if not calib:
            return 0.0

        if calib.exists(pycalibtic.NeuronCalibration.Calibrations.ReadoutShift):
            shift = calib.at(pycalibtic.NeuronCalibration.Calibrations.ReadoutShift).apply(0.0)
            self.logger.TRACE("Readout shift for neuron {0}:{1:.2f}".format(neuron, shift))
        else:
            shift = 0.0
            self.logger.WARN("No readout shift found for neuron {}.".format(neuron))

        return shift

    def apply_calibration(self, value, parameter, coord,
                          bigcap,
                          speedup_I_gl,
                          speedup_I_gladapt,
                          speedup_I_radapt,
                          use_ideal=False, report=False,
                          outside_domain_behaviour="CLIP"):
        """ Apply calibration to one value. If no calibration is found, use ideal calibration.
            Also, if parameter value is given in a unit that does not support calibration, e.g.
            I_pl given in Ampere instead of microseconds, apply direct translation to DAC.

            Args:
                value: Value in Hardware specific units (e.g. volt, ampere, seconds)
                parameter: neuron_parameter or shared_parameter type
                coord: neuron coordinate
                outside_domain_behaviour: "CLIP"/"IGNORE"/"THROW"
                                          (see calibtic/trafo/Transformation.h)
            Returns:
                Calibrated DAC value
                If the calibrated value exceeds the boundaries, it is clipped.

                If report_status is set, also a integer is retured, discribing the
                actuale transformation used: 0 ok, 1 ideal, 2 none, and a bool
                indicating if the value is clipped
        """
        if not isinstance(value, Unit):
            value = Unit(value)

        calib = self.get_calibration(coord, use_ideal)
        status = 0
        clipped = False

        if parameter in [neuron_parameter.I_pl,
                         neuron_parameter.I_gl,
                         neuron_parameter.V_syntcx,
                         neuron_parameter.V_syntci]:
            if not isinstance(value, Second):
                raise TypeError("Calibration for {} only valid for seconds.".format(parameter))

        calib_id = parameter if isinstance(parameter,
                                           shared_parameter) else self.get_calib_id(parameter.name,
                                                                                bigcap,
                                                                                speedup_I_gl,
                                                                                speedup_I_gladapt,
                                                                                speedup_I_radapt)

        if calib.exists(calib_id):
            # Apply calibration
            calib_dac_value = calib.to_dac(value.value, calib_id,
                                           getattr(pycalibtic.Transformation,
                                                   outside_domain_behaviour))
            self.logger.TRACE("Calibrated {} parameter {}: {} --> {} DAC".format(coord, parameter.name, value, calib_dac_value))
        else:
            ideal = self.get_calibration(coord, True)
            calib_dac_value = ideal.to_dac(value.value, calib_id,
                                           getattr(pycalibtic.Transformation,
                                                   outside_domain_behaviour))
            self.logger.WARN("Calibration for {} parameter {} not found. Using ideal transformation -> DAC value {}".format(coord, parameter.name, calib_dac_value))
            status = 2

        calib_dac_value = np.clip(calib_dac_value + value.dac_offset, 0, 1023)

        if report:
            return calib_dac_value, status, clipped
        else:
            return calib_dac_value

    def set_neuron_parameters(self, parameters, neuron, floating_gates, bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt):
        """Writes floating gate parameters for a single neuron into a sthal
        FloatingGates container. This includes calibration and transformation
        from V or nA to DAC values.

        Parameters:
            parameters: dictionary containg the parameters to be written,
                neuron specific parameters are consumed
            neuron: neuron to be updated
            floating_gates: pysthal.FloatingGates to be updated

        Returns:
            pysthal.FloatingGates with given parameters
        """
        # We take only a shallow copy, because this is faster. The values
        # are copied in the loop below
        neuron_params = parameters.copy()
        # Use pop to consume neuron specific parameters
        neuron_params.update(parameters.pop(neuron, {}))
        for param, value in neuron_params.items():
            if (not isinstance(param, neuron_parameter)) or param.name[0] == '_':
                # e.g. __last_neuron
                continue

            value = copy.deepcopy(value)  # Copy of value, see comment above
            if value.apply_calibration:
                self.logger.TRACE("Applying calibration to coord {} value {}".format(neuron, value))
                value_dac, status, clipped  = self.apply_calibration(
                    value, param, neuron,
                    bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt,
                    report=True)
            else:
                # special case for unit second and no calibration applied
                if isinstance(value, Second):
                    value_dac, status, clipped  = self.apply_calibration(value, param, neuron,
                                                                         bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt,
                                                                         use_ideal=True, report=True)
                else:
                    value_dac = value.toDAC().value
            self.logger.TRACE("Setting FGValue of {} parameter {} to {}.".format(neuron, param, value_dac))
            floating_gates.setNeuron(neuron, param, int(value_dac))

    def set_shared_parameters(self, parameters, block, floating_gates, bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt):
        """Writes shared floating gate parameters for a single floating gate
        block into a sthal FloatingGates container. This includes calibration
        and transformation from V or nA to DAC values.

        Parameters:
            parameters: dictionary containg the parameters to be written
            block: shared floating gate block to be updated
            floating_gates: pysthal.FloatingGates to be updated

        Returns:
            pysthal.FloatingGates with given parameters
        """
        block_parameters = copy.deepcopy(parameters)
        for param, value in block_parameters.items():
            if (not isinstance(param, shared_parameter)) or param.name[0] == '_':
                # e.g. __last_*
                continue
            # Check if parameter exists for this block
            even = block.toEnum().value() % 2
            if even and param.name in ['V_clra', 'V_bout']:
                continue
            if not even and param.name in ['V_clrc', 'V_bexp']:
                continue

            if value.apply_calibration:
                self.logger.TRACE("Applying calibration to coord {} value {}".format(block, value))
                value_dac = self.apply_calibration(value, param, block, bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt)
            else:
                if type(value) in [Ampere, Volt, DAC]:
                    value_dac = value.toDAC().value
                else:
                    value_dac = self.apply_calibration(value.value, param, block, bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt, use_ideal=True)

            self.logger.TRACE("Setting FGValue of {} parameter {} to {}.".format(block, param, value))
            floating_gates.setShared(block, param, int(value_dac))

    def set_calibrated_parameters(self, parameters, neurons, blocks, floating_gates,
                                  bigcap,
                                  speedup_I_gl,
                                  speedup_I_gladapt,
                                  speedup_I_radapt):
        """Writes floating gate parameters into a sthal FloatingGates container.
            This includes calibration and transformation from V or nA to DAC values.

        Parameters:
            parameters: dictionary containg the parameters to be written
            floating_gates: pysthal.FloatingGates to be updated

        Returns:
            pysthal.FloatingGates with given parameters
        """

        for neuron in neurons:
            self.set_neuron_parameters(parameters, neuron, floating_gates, bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt)
        for block in blocks:
            self.set_shared_parameters(parameters, block, floating_gates, bigcap, speedup_I_gl, speedup_I_gladapt, speedup_I_radapt)


from telebot import TeleBot
from telebot.util import antiflood
from telebot.apihelper import ApiException

import hashlib

LOWER_LETTERS = 'абвгдеёжзийклмнопрстуфхцчшщъыьэюя'
UPPER_LETTERS = 'АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ'
EMPTY_SYMB = ' '
CONNECT_SYMB = '-'
UTF = 'utf-8'

def send_text(bot: TeleBot, chat_id: int, text: str) -> bool:
    result = True
    # Send text to chat_id
    try:
        antiflood(bot.send_message, chat_id, text)
    except ApiException:
        result = False
    return result

# _______________________________________________________________

def check_team_name(name: str) -> bool:
    result = True
    should_upper = True
    if len(name) < 3 or len(name) > 20:
        return False

    for symb in name:
        if should_upper:
            if not (symb in UPPER_LETTERS):
                return False
        elif symb == CONNECT_SYMB or symb == EMPTY_SYMB:
            should_upper = True
            continue
        elif symb in UPPER_LETTERS:
            return False
        elif not symb in LOWER_LETTERS:
            return False
        should_upper = False
    return result

def check_point_name(name: str) -> bool:
    result = True
    if len(name) < 2 or len(name) > 30:
        return False

    if not name[0] in UPPER_LETTERS:
        result = False
    for symb in name[1:]:
        if (not symb in LOWER_LETTERS) and symb != CONNECT_SYMB:
            return False
    return result

def get_hash(user_input: str) -> str:
    result = hashlib.sha256(bytes(user_input, UTF)).hexdigest()
    return result

def check_admin_password(password_hash: str, user_input: str) -> bool:
    result = True
    input_hash = get_hash(user_input)
    if input_hash != password_hash:
        result = False
    return result

def check_manager_password(password_hash: str, user_input: str) -> bool:
    result = True
    input_hash = get_hash(user_input)
    if input_hash != password_hash:
        result = False
    return result

def assign_starting_point_messages(teams: dict[int, dict], points: list[str], base_message: str) -> dict[int, str]:
    result = {}

    try:
        if (len(teams.keys()) > len(points)):
            raise ValueError

        c1 = 0

        for i in teams.keys():
            c2 = 0
            team_chat = teams[i]['chat_id']
            message = points[c1]
            for j in range(len(points) - 1):
                c2 += 1
                message = message + ', ' + points[(c1 + c2) % len(points)]
            result[team_chat] = base_message.format(message)
            c1 += 1

    except ValueError:
        print('You have less points than you have teams :skull:')

    return result

def broadcast_starting_points(bot: TeleBot, messages: dict[int, str]) -> dict[int, bool]:
    result = {}

    for i in messages.keys():
        msgreturn = bot.send_message(i, messages[i])
        if msgreturn.message_id:
            result[i] = True
        else:
            result[i] = False

    return result


from mlcalcdriver import Posinp
import numpy as np
import os
from copy import copy
import matplotlib.pyplot as plt

pos_folder = "positions/"

positions = [
    Posinp.from_file(pos_folder + file)
    for file in os.listdir(pos_folder)
    if file.endswith(".xyz")
]

n = 200000
npzfile = np.load("prob_32at_3d.npz")
probability = npzfile["probability"]
assert len(positions) == len(probability)

distances, angles = [], []

for _ in range(n):
    i = int(np.random.choice(len(positions), 1, p=probability))
    posinp = positions[i]
    az_idx = [i for i, at in enumerate(posinp) if at.type == "N"]
    if len(az_idx) == 2:
        distances.append(posinp.distance(az_idx[0], az_idx[1]))
        angles.append(np.pi)
    elif len(az_idx) == 3:
        mid = np.array(posinp.cell) / 2
        d = np.array([np.linalg.norm(posinp[idx].position - mid) for idx in az_idx])
        mid_idx = az_idx[np.argmin(d)]
        other_idx = copy(az_idx)
        del other_idx[np.argmin(d)]

        distances.append(posinp.distance(mid_idx, other_idx[0]))
        distances.append(posinp.distance(mid_idx, other_idx[1]))
        angles.append(posinp.angle(other_idx[0], mid_idx, other_idx[1]))
    else:
        raise NotImplementedError

# Uncomment for visual

fig, ax = plt.subplots(ncols=2, figsize=[15, 11])
ax1, ax2 = ax.flatten()

ax1.set_xlim(0, 7)
ax1.hist(distances, bins=20)
ax1.set_title("Distance distribution")

ax2.set_xlim(0, np.pi)
ax2.hist(angles, bins=20)
ax2.set_title("Angle distribution")
plt.show()


"""
A small collection of mathematical functions
"""

def _is_iteratable(i):
    try:
        iter(i)
    except TypeError:
        return False
    else:
        return True

def sum_of_iteratable(iteratable):
    total = 0
    iteratable = iteratable.values() if type(iteratable) == dict else iteratable
    for i in iteratable:
        if type(i) == str:
            continue  # skip strings
        elif _is_iteratable(i):
            total += sum_of_iteratable(i)  # recursive call
        else:  # must be numeric or complex type...
            try:  # try to add, if exception occurs, just continue
                total += iteratable[i]
            except TypeError:
                continue
    return total

def factorial(n):
    assert type(n) == int, "Type of 'n' must be integer."
    result = 1
    for i in range(2, n+1):
        result *= i
    return result

def factorial_recursive(n):
    assert type(n) == int, "Type of 'n' must be integer."
    return 1 if n <= 1 else n*factorial_recursive(n-1)

def sum_of_first_n(n):
    assert type(n) == int, "Type of 'n' must be integer."
    result = 0
    for i in range(1, n+1):
        result += i
    return result

def sum_of_first_n_recursive(n):
    assert type(n) == int, "Type of 'n' must be integer."
    return 0 if n <= 0 else n+sum_of_first_n_recursive(n-1)

def _pascal_recursive(n=10, prev=None):
    prev = list() if prev is None else prev
    if n >= 0:
        nextt = [1]
        for i in range(len(prev)-1):
            nextt.append(prev[i]+prev[i+1])
        nextt.append(1)
        return prev + (_pascal_recursive(n-1, nextt))
    else:
        return []

def pascals_triangle(n=10):
    assert type(n) == int, "Type of 'n' must be integer."
    res = _pascal_recursive(n)
    last = 0
    rows = [[1]]
    for i in range(n):
        rows.append(res[last:last+len(rows[-1])+1])
        # indexing[from:to] with 'to' excluded, result is sub-list
        # index -1 means the last element
        last += len(rows[-1])
    return rows

if __name__ == "__main__":
    for row in pascals_triangle():
        print(row)


import requests

testUrl = "http://127.0.0.1:5000/ahi/api/v1.0/add_patient"

patientTest = {
        'patient_id': '340000',
        'firstname': 'example55',
        'lastname': 'example66',
        'inpatient': True
    }

apiRequest = requests.post(testUrl, json=patientTest)

apiRequest.status_code

testUrl = "http://127.0.0.1:5000/ahi/api/v1.0/patients"
apiRequest = requests.get(testUrl)
print(apiRequest.text)


# coding: UTF-8
import torch
import torch.nn as nn
from pytorch_pretrained_bert import BertModel, BertTokenizer
import json

class FGM():
    def __init__(self, model):
        self.model = model
        self.backup = {}

    def attack(self, epsilon=1., emb_name='bert.embedding'):
        # emb_name这个参数要换成你模型中embedding的参数名
        for name, param in self.model.named_parameters():
            if param.requires_grad and emb_name in name:
                self.backup[name] = param.data.clone()
                norm = torch.norm(param.grad)
                if norm != 0:
                    r_at = epsilon * param.grad / norm
                    param.data.add_(r_at)

    def restore(self, emb_name='bert.embedding'):
        # emb_name这个参数要换成你模型中embedding的参数名
        for name, param in self.model.named_parameters():
            if param.requires_grad and emb_name in name:
                assert name in self.backup
                param.data = self.backup[name]
        self.backup = {}

class bert_RNN(nn.Module):

    def __init__(self, config):
        super(bert_RNN, self).__init__()
        self.bert = BertModel.from_pretrained(config.bert_path)
        for param in self.parameters():
            param.requires_grad = True
        self.lstm = nn.LSTM(config.hidden_size, config.rnn_hidden, config.num_layers,
                            bidirectional=True, batch_first=True, dropout=config.dropout)
        self.dropout = nn.Dropout(config.dropout)
        self.fc_rnn = nn.Linear(config.rnn_hidden * 2, config.num_classes)  # 这里是rnn_hidden * 2是因为使用了BiLSTM

    def forward(self, x):
        context = x[0]  # 输入句子
        mask = x[2]  # 对padding部分进行mask，和句子一个size，padding部分用0表示，如：[1, 1, 1, 1, 0, 0]
        # 因为我选择了参数output_all_encoded_layers=True，12层Transformer的结果全返回了，存在第一个列表中，
        # 每个encoder_output的大小为[batch_size, sequence_length, hidden_size]
        context = torch.squeeze(context, dim=1)
        mask = torch.squeeze(mask, dim=1)
        # output_all_encoded_layers 取 bert 最后一层
        encoder_out, text_cls = self.bert(context, attention_mask=mask, output_all_encoded_layers=False)
        out, _ = self.lstm(encoder_out)
        out = self.dropout(out)
        logits = self.fc_rnn(out[:, -1, :])  # 句子最后时刻的 hidden state
        return logits