from Player import *

# Minimax class that inherits the Player class.
# Will go through all possible moves on the board for each player depending on
# whether they're the maximizing player or the minimizing player.
class MiniMax(Player):
    def __init__(self, player):
        Player.__init__(self, player)

    def minimax(self, ttt, player):
        if ttt.testForWin(self.player):
            return (1, 1)
        elif ttt.testForWin(self.opponent):
            return (-1, -1)
        elif (ttt.testBoardFull()):
            return (0, 0)
        possibleMoves = ttt.possibleNextMoves()
        if self.player == player:
            bestMove = -1
            bestScore = -1000
            for m in possibleMoves:
                ttt.placeMove(m, player)
                minimax = self.minimax(ttt, self.opponent)
                if bestScore < minimax[1]:
                    bestMove = m
                    bestScore = minimax[1]
                ttt.removeMove(m)
        else:
            bestMove = -1
            bestScore = 1000
            for m in possibleMoves:
                ttt.placeMove(m, player)
                minimax = self.minimax(ttt, self.player)
                if bestScore > minimax[1]:
                    bestMove = m
                    bestScore = minimax[1]
                ttt.removeMove(m)
        return (bestMove, bestScore)

    def move(self, ttt):
        return self.minimax(ttt, self.player)[0]


# -*- coding:utf-8 -*-
import json
from robot.api import logger
from JiaseLibrary.utils.http import check_json_response

class _LambdaTransferKeywords():
    """
    移交管理
    """

    def transfer_manager(self, cust_name, cust_manager_name, new_cust_manager_name):
        """
        管户经理变更
        :return:
        http://lambda-web-test.ronaldinho.svc.cluster.local/transfer/cust/manager/record/updateCustManager
        """

        # 查询管户经理
        old_cust_manager_name, old_cust_manager_id, old_cust_manager_orgid = self.get_cust_manager(cust_manager_name)
        cust = self.cust_infos_queryByName(cust_name)
        cust_id = cust['id']
        new_cust_manager_name, new_cust_manager_id, new_cust_manager_orgid = self.get_cust_manager(new_cust_manager_name)
        params = {
            "custIds":cust_id,
            "oldCustManagerId": old_cust_manager_id,
            "oldCustOrgId": old_cust_manager_orgid,
            "newCustManagerId": new_cust_manager_id,
            "newCustOrgId":new_cust_manager_orgid,
        }
        url = '%s/transfer/cust/manager/record/updateCustManager' % self._lambda_url
        res = self._request.post(url, data = params)
        ret = check_json_response(res)

    def get_cust_manager(self, name):
        """
        查询管户经理
        :param name:
        :return:

        "http://lambda-web-test.ronaldinho.svc.cluster.local/transfer/cust/manager/record/selectCustManager?_ukey=5381&r=0.13963574590581307&custManagerName=admin"
        """
        params = {
            "custManagerName": name,
        }
        url = '%s/transfer/cust/manager/record/selectCustManager' % self._lambda_url
        res = self._request.get(url, params=params)
        ret = check_json_response(res)
        if len(ret['data']) == 0:
            raise AssertionError("没有找到名为 %s 的管户经理 ！" % name)
        elif len(ret['data']) > 1:
            logger.warn("%s 对应不止一个管户经理，暂时只选择第一个！")
        c = ret['data'][0]
        return c['custManagerName'], c['custManagerId'], c['custOrgId']


import re

from rest_framework import serializers
from rest_framework.validators import UniqueValidator

from users.models import USERNAMEVALIDATORSET, User

class SignupSerializer(serializers.Serializer):
    """Регистрация пользователя."""
    email = serializers.EmailField(
        max_length=254, allow_blank=False, allow_null=False,
        validators=[UniqueValidator(queryset=User.objects.all())])
    username = serializers.CharField(
        max_length=150, allow_blank=False, allow_null=False,
        validators=[UniqueValidator(queryset=User.objects.all()), ])

    class Meta:
        model = User
        fields = ('username', 'email')

    def create(self, validated_data):
        return User.objects.create(**validated_data)

    def validate_username(self, value):
        pattern = r'^[\w.@+-]+'
        match = re.fullmatch(pattern, value)

        if not match:
            raise serializers.ValidationError(
                'Необходимо использовать допустимые символы!')
        if value == 'me':
            raise serializers.ValidationError(
                'Необходимо указать настоящее имя!')
        return value

class UserSerializer(serializers.ModelSerializer):
    """Ресурс users."""
    email = serializers.EmailField(
        allow_blank=False, allow_null=False, max_length=254,
        validators=[UniqueValidator(queryset=User.objects.all())])
    username = serializers.CharField(
        allow_blank=False, allow_null=False, max_length=150,
        validators=[
            UniqueValidator(queryset=User.objects.all()),
            USERNAMEVALIDATORSET])

    class Meta:
        model = User
        fields = ('username', 'email', 'first_name',
                  'last_name', 'bio', 'role')

class UserCheckSelfAccountSerializer(serializers.ModelSerializer):
    """Ресурс users/me"""
    username = serializers.CharField(
        required=True, max_length=150, validators=[USERNAMEVALIDATORSET, ])
    email = serializers.EmailField(required=True, max_length=254)
    role = serializers.CharField(read_only=True)

    class Meta:
        model = User
        fields = ['username', 'email', 'first_name',
                  'last_name', 'bio', 'role']

class CustomJWTSerializer(serializers.Serializer):
    """Работа с Токеном."""
    username = serializers.CharField(required=True)
    confirmation_code = serializers.CharField(required=True)


"""
Chapter 2 - Problem 2.1 - Remove Dups
Problem:
Write code to remove duplicates from an unsorted linked list.
FOLLOW UP
How would you solve this problem if a temporary buffer is not allowed?

Solution:
1. Clarify the question:
Repeat the question: We are given a linked list which is unsorted. And we need to remove duplicate nodes from it.
Clarify assumptions: - Does the linked list have loops? (We will assume no.)
                     - Is it a singly or doubly linked list? (We will assume singly.)

2. Inputs and outputs:
So we're taking in the head node of a singly linked list and returning a linked list with duplicates removed.

3. Test and edge cases:
edge: We can also take in an empty head or None object as an input.
test: We can also have regular input like this: 4->3->10->4->2->9->2 should convert to 4->3->10->2->9.

4. Brainstorm solution:
If the linked list has zero or only one node, or none object, we can just return the linked list as there would be no
duplicates for sure.
We can iterate through the list and keep track of the values we see in each node in a hashtable or in python a dictionary
or set. When we encounter a value that we have seen before (meaning we need to do a lookup in hashtable, which takes
constant time), we remove it by rearranging the references of the previous node. The time complexity would be O(N) in
always case as we need to iterate through the list. The space complexity would be O(N) in worse case to store N keys in the set.
In the best case where we have only 1 unique element, it would be O(1).

If not using a buffer, we can compare all values with all other values by running two loops. The time complexity would
become O(N2) in always case. The space complexity would be constant in always case.

5. Runtime analysis:
time complexity: O(N) in always case for solution 1, O(N2) in always case for solution 2.
space complexity: - O(N) for solution 1
                  - O(1) for solution 2.

6. Code
"""
import unittest
from linkedlist import Node

# Solution
def remove_duplicates1(head):

    if not isinstance(head, Node):
        return -1

    if head.next is None:
        return head

    if head is not None:
        current = head
        seen = {current.value: 1}
        while current.next is not None:
            if current.next.value in seen:
                # remove node:
                current.next = current.next.next
            else:
                seen[current.next.value] = 1
                current = current.next

    return head

# Solution 2
def remove_duplicates2(head):
    if not isinstance(head, Node):
        return -1

    if head.next is None:
        return head

    current = head
    while current is not None:
        runner = current
        while runner.next is not None:
            if runner.next.value == current.value:
                runner.next = runner.next.next
            else:
                runner = runner.next
        current = current.next

    return head

# Test and debug
class Test(unittest.TestCase):
    def setUp(self):
        self.head = Node(1)
        self.head.next = Node(3)
        self.head.next.next = Node(1)

        self.head2 = Node(0)

        self.head3 = None

    def test_remove_duplicates1(self):
        remove_duplicates1(self.head)
        self.assertEqual(self.head.value, 1)
        self.assertEqual(self.head.next.value, 3)
        self.assertEqual(self.head.next.next, None)

        remove_duplicates1(self.head2)
        self.assertEqual(self.head2.value, 0)
        self.assertEqual(self.head2.next, None)

        remove_duplicates1(self.head3)
        self.assertEqual(self.head3, None)

    def test_remove_duplicates2(self):
        remove_duplicates2(self.head)
        self.assertEqual(self.head.value, 1)
        self.assertEqual(self.head.next.value, 3)
        self.assertEqual(self.head.next.next, None)

        remove_duplicates2(self.head2)
        self.assertEqual(self.head2.value, 0)
        self.assertEqual(self.head2.next, None)

        remove_duplicates2(self.head3)
        self.assertEqual(self.head3, None)

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


from networcks.deeplab.model.deeplab import DeepLab
from networcks.linknet import DinkNet50
from networcks.linknet import LinkNet50
from networcks.linknet import DinkNet34
from networcks.linknet import MDinkNet50
from networcks.linknet import MDinkNet_xception
from networcks.linknet import DinkNet_xception
from networcks.unet import Unet_resnet
from networcks.fcn import Resnet_FCN8s
from networcks.segnet import SegNet
import torch
from torch.utils.data import DataLoader
from torch import autograd, optim
from torchvision.transforms import transforms
import cv2
import numpy as np
import os
import time

testpath = 'data/xunlian/imagesyingyong'
predimgs = 'predimgs/'
modelloadpath = 'weights/liexi/DinkNet34_weights_42_0.5057716637145223.pth'
n_class = 1
imgsize = 1024
modelname = 'DinkNet34'
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
x_transforms = transforms.Compose([
    transforms.ToTensor(),  # -> [0,1]
    transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])  # ->[-1,1]
])
#model = eval(modelname)(backbone='xception', output_stride=16, num_classes=n_class).to(device)#deeplab
model = eval(modelname)(num_classes=n_class).to(device)  # else
model.load_state_dict(torch.load(modelloadpath))
model.eval()
torch.no_grad()
imglist = os.listdir(testpath)
print('开始')
if os.path.exists(predimgs + modelname) is not True:
    os.mkdir(predimgs + modelname)

times = []
for i in imglist:
    imgpath = os.path.join(testpath, i)
    predpath = os.path.join(predimgs + modelname + '/', i.split('.')[0] + '.png')
    img = cv2.imread(imgpath, -1)
    (w, h, c) = img.shape
    # print(img.shape)
    img = cv2.resize(img, (imgsize, imgsize))
    img = x_transforms(img).cuda()
    img = img.unsqueeze(0)
    # print(img.shape)
    T1 = time.time()
    pred = model(img)
    T2 = time.time()
    pred = pred.detach().cpu()
    pred = torch.where(pred > 0.5, torch.tensor(255), torch.tensor(0))
    # print(pred.shape)
    pred = pred.squeeze(0)
    pred = pred.squeeze(0)
    # print(pred.shape)
    pred = pred.numpy()
    # pred = cv2.resize(pred, (w, h))
    T = T2 - T1
    times.append(T)
    cv2.imwrite(predpath, pred)

seglist = os.listdir(predimgs + modelname + '/')
for i in seglist:
    path = os.path.join(predimgs + modelname + '/', i)
    imgpath = os.path.join(testpath, i.split('.')[0] + '.jpg')
    img = cv2.imread(imgpath, -1)
    (w, h, c) = img.shape
    seg = cv2.imread(path, 0)
    seg = cv2.resize(seg,(h, w))
    cv2.imwrite(path, seg)

time_sum = 0
for i in times:
    time_sum += i
print('fps:%f'%(1.0/(time_sum/len(times))))
print('完成')


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

# In[29]:

get_ipython().system('pip install pyPDF2')
get_ipython().system('pip install regex')

# In[30]:

import re
import PyPDF2 as pdf

# In[3]:

file=open('C:\\Users\\Maria sanjai\\Desktop\\The_Living_World.pdf','rb')

# In[4]:

file

# In[5]:

pdf_reader=pdf.PdfFileReader(file)

# In[6]:

pdf_reader

# In[7]:

pdf_reader.getIsEncrypted()

# In[8]:

pdf_reader.getNumPages()

# In[47]:

text1=" "

# In[48]:

for x in range(0,17):
    page=pdf_reader.getPage(x)
    text=page.extractText()
    text1=text1+text
print(text1)

# In[50]:

question=re.compile("\d{1,2}.[A-Za-z]")

# In[51]:

for line in text1.split('\n'):
    if question.match(line):
        print(line)

# In[74]:

options=re.compile("\(\d{1}\)[A-Z]{1}[a-z]{1,30}")

# In[75]:

for line in text1.split('\n'):
    if options.match(line):
        print(line)

# In[63]:

answer=re.compile("Sol.[A-Za-z]")

# In[64]:

for line in text1.split('\n'):
    if answer.match(line):
        print(line)

# In[ ]:


#!/usr/bin/env python3

"""
@author:    M. Garbellini
@email:     matteo.garbellini@studenti.unimi.it

* FORCE MODULE *
Contains force calculations (and potential energies) using known potentials.

Latest update: June 25th 2021
"""
import system
import numpy as np
import math
import matplotlib.pyplot as plt
from scipy import special
from numba import jit, njit, vectorize
from concurrent.futures import ThreadPoolExecutor
from itertools import repeat

"""Parameters needed in the force calculations routines"""
epsilon = None
epsilon_wall = None
sigma = None
sigma_wall = None
cutoff = None
cutoff_wall = None
Rc = None
c_shift = None
potential_shift = None
epsilon_not = 8.854E-12
electrostatic = True

@njit
def mic(xi, xj, L):
    """Computes shortest distance based on minimum-image-convention (MIC).

    Args:
        xi -- position of i particle
        xj -- position of j particle
        L -- dimension of enclosing box

    Returns:
        rij -- the distance between particle i and j

    Note:
        -- the routine runs using Numba @njit decorator for faster run time
    """
    rij = xi - xj
    if abs(rij) > 0.5 * L:
        rij = rij - np.sign(rij) * L

    return rij

@njit(nogil=True)
def lennard_jones_parallel_istance(index, force, pos, L):
    """Computes the force on all particles given a Lennard-Jones potential

    Args:
        force -- np.zeros([N, 3]) array for force storage (N = number of particles)
        pos -- np.array([N,3]) array of current positions
        L -- dimension of enclosing box

    Parameters:
        sigma -- parameter from the Lennard-Jones potential
        epsilon -- parameter from the Lennard-Jones potential

    Returns:
        force -- np.array([N, 3]) containing the net force on each particle
        potential -- value of the potential energy of the system

    Note:
        -- the routine runs using Numba @njit decorator for faster run time
    """
    potential = 0
    virial = 0

    for i in range(index[0], index[1]):
        for j in range(i+1, pos.shape[0]):

            # X AXIS
            distx = pos[i,0] - pos[j,0]
            if abs(distx) > 0.5 * L[0]:
                distx = distx - np.sign(distx) * L[0]

            # Y AXIS
            disty = pos[i,1] - pos[j,1]
            if abs(disty) > 0.5 * L[1]:
                disty = disty - np.sign(disty) * L[1]

            # Z AXIS
            distz = pos[i,2] - pos[j,2]
            if abs(distz) > 0.5 * L[2]:
                distz = distz - np.sign(distz) * L[2]

            r = distx * distx + disty * disty + distz * distz

            if(r < cutoff**2):
                fx = 48 * epsilon * (sigma**12 * distx / r**7 - 0.5 * sigma**6 * distx / r**4)
                fy = 48 * epsilon * (sigma**12 * disty / r**7 - 0.5 * sigma**6 * disty / r**4)
                fz = 48 * epsilon * (sigma**12 * distz / r**7 - 0.5 * sigma**6 * distz / r**4)

                force[i, 0] += fx
                force[i, 1] += fy
                force[i, 2] += fz

                force[j, 0] -= fx
                force[j, 1] -= fy
                force[j, 2] -= fz

                virial += distx * fx
                virial += disty * fy
                virial += distz * fz

                potential += 2 * 4 * epsilon * (sigma**12 / r**6 - sigma**6 / r**3) - potential_shift

    return force, potential, virial

@njit
def lennard_jones_serial_istance(force, pos, L, charge):
    """Computes the force on all particles given a Lennard-Jones potential

    Args:
        force -- np.zeros([N, 3]) array for force storage (N = number of particles)
        pos -- np.array([N,3]) array of current positions
        L -- dimension of enclosing box
        charge -- np.array(N) containing particles charges

    Parameters:
        sigma -- parameter from the Lennard-Jones potential
        epsilon -- parameter from the Lennard-Jones potential

    Returns:
        force -- np.array([N, 3]) containing the net force on each particle
        potential -- value of the potential energy of the system

    Note:
        -- the routine runs using Numba @njit decorator for faster run time
    """
    potential = 0
    virial = 0

    for i in range(pos.shape[0]):
        for j in range(i+1, pos.shape[0]):

            # X AXIS
            distx = pos[i,0] - pos[j,0]
            if abs(distx) > 0.5 * L[0]:
                distx = distx - np.sign(distx) * L[0]

            # Y AXIS
            disty = pos[i,1] - pos[j,1]
            if abs(disty) > 0.5 * L[1]:
                disty = disty - np.sign(disty) * L[1]

            # Z AXIS
            distz = pos[i,2] - pos[j,2]
            if abs(distz) > 0.5 * L[2]:
                distz = distz - np.sign(distz) * L[2]

            r = distx * distx + disty * disty + distz * distz

            """Lennard Jones Potential Cutoff"""
            if(np.sqrt(r) < cutoff):
                fx = 48 * epsilon * (sigma**12 * distx / r**7 - 0.5 * sigma**6 * distx / r**4)
                fy = 48 * epsilon * (sigma**12 * disty / r**7 - 0.5 * sigma**6 * disty / r**4)
                fz = 48 * epsilon * (sigma**12 * distz / r**7 - 0.5 * sigma**6 * distz / r**4)

                force[i, 0] += fx
                force[i, 1] += fy
                force[i, 2] += fz

                force[j, 0] -= fx
                force[j, 1] -= fy
                force[j, 2] -= fz

                virial += distx * fx
                virial += disty * fy
                virial += distz * fz

                potential += 2 * 4 * epsilon * (sigma**12 / r**6 - sigma**6 / r**3) - potential_shift

                """Coulomb Potential Cutoff"""
                if electrostatic == True:

                    k = charge[i]*charge[j]/4/np.pi/epsilon_not
                    rij = np.sqrt(r)

                    fx = k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*distx/r + c_shift*distx/rij)
                    fy = k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*disty/r + c_shift*disty/rij)
                    fz = k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*distz/r + c_shift*distz/rij)

                    force[i, 0] += fx
                    force[i, 1] += fy
                    force[i, 2] += fz

                    force[j, 0] -= fx
                    force[j, 1] -= fy
                    force[j, 2] -= fz

                    potential += 2*k*(math.erfc(rij/Rc)/rij - math.erfc(1)/Rc + c_shift*(rij - Rc))

    return force, potential, virial

def lennard_jones(force, pos, L, parallel = False):
    """Parallelization of lennard_jones calculation over 4 cores
    """

    potential = 0
    virial = 0

    if parallel == True:

        size = force.shape[0] // 4 + (force.shape[0] % 4 > 0)
        index = [np.array([0,size]),np.array([size, 2*size]),np.array([2*size, 3*size]),np.array([3*size, force.shape[0]-1])]

        with ThreadPoolExecutor(4) as ex:
            output = list(ex.map(lennard_jones_parallel_istance, index, repeat(force), repeat(pos), repeat(L)))

        pool1 = output[0]
        pool2 = output[1]
        pool3 = output[2]
        pool4 = output[3]

        force = pool1[0] + pool2[0] + pool3[0] + pool4[0]
        potential = pool1[1] + pool2[1] + pool3[1] + pool4[1]
        virial = pool1[2] + pool2[2] + pool3[2] + pool4[2]

    else:

        force, potential, virial = lennard_jones_serial_istance(force, pos, L, system.charge)

    return force, potential, virial

@njit
def lennard_jones_wall(force, pos, L,potential, axis = 2):
    """Computes contribution to the force on the particles due to the interactions
    with the wall using a 9-3 LJ potential

    Args:
        pos -- np.array([N,3]) array of current positions
        L -- dimension of enclosing box
        force -- np.array([N, 3]) containing forces (N = number of particles)
        potential -- value of potential energy of the system
        axis -- (default = 2) direction of the force, default is z-axis

    Parameters:
        sigma_wall -- parameter from the Lennard-Jones wall-interaction potential
        epsilon_wall -- parameter from the Lennard-Jones wall-interaction potential

    Returns:
        force -- updated array containing the net force of all particles
        potential -- updated value of the potential energy of the system

    Note:
        -- the routine runs using Numba @njit decorator for faster run time
        -- the routine is usually called after lennard_jones() -> force, potential already initialized
    """
    const = 3 * 0.5 * np.sqrt(3) * epsilon_wall * sigma_wall**3

    for i in range(pos.shape[0]):
        if(pos[i, axis] < cutoff_wall):
            z = pos[i, axis]
            potential += const * (sigma_wall**6/z**9 - 1/z**3)
            force[i, axis] -= const * (-9*sigma_wall**6/z**10 + 3/z**4)

        if(pos[i, axis] > (L[axis] - cutoff_wall)):
            z = L[axis] - pos[i, axis]
            potential += const * (sigma_wall**6/z**9 - 1/z**3)
            force[i, axis] += const * (-9*sigma_wall**6/z**10 + 3/z**4)

    return force, potential

@njit
def coulombic_wall(force, pos, pos_discrete, charge, discrete_surface_q, L):
    """Computes electrostatic force contribution due to the interactions of the particles
    inside the box with the charges on the charged surfaces
    """

    """Surface charges at z = 0"""
    surface = 0
    for i in range(pos.shape[0]):
        for j in range(pos_discrete.shape[0]):

            distx = pos[i,0] - pos_discrete[j,0, surface]
            if abs(distx) > 0.5 * L[0]:
                distx = distx - np.sign(distx) * L[0]

            disty = pos[i,1] - pos_discrete[j,1, surface]
            if abs(disty) > 0.5 * L[1]:
                disty = disty - np.sign(disty) * L[1]

            distz = pos[i,2] - 0.
            r = distx * distx + disty * disty + distz * distz
            k = charge[i]*discrete_surface_q/4/np.pi/epsilon_not
            rij = np.sqrt(r)

            if rij < Rc:
                force[i,0] -= k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*distx/r + c_shift*distx/rij)
                force[i,1] -= k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*disty/r + c_shift*disty/rij)
                force[i,2] -= k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*distz/r + c_shift*distz/rij)

    """Surface charges at z = Lz """
    surface = 1
    for i in range(pos.shape[0]):
        for j in range(pos_discrete.shape[0]):

            distx = pos[i,0] - pos_discrete[j,0, surface]
            if abs(distx) > 0.5 * L[0]:
                distx = distx - np.sign(distx) * L[0]

            disty = pos[i,1] - pos_discrete[j,1, surface]
            if abs(disty) > 0.5 * L[1]:
                disty = disty - np.sign(disty) * L[1]

            distz = pos[i,2] - L[2]
            r = distx * distx + disty * disty + distz * distz

            k = charge[i]*discrete_surface_q/4/np.pi/epsilon_not
            rij = np.sqrt(r)

            if rij < Rc:
                force[i,0] += k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*distx/r + c_shift*distx/rij)
                force[i,1] += k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*disty/r + c_shift*disty/rij)
                force[i,2] += k * (-2*np.exp(-(rij/Rc)**2)/rij/Rc/np.sqrt(np.pi) -math.erfc(rij/Rc)*distz/r + c_shift*distz/rij)

    return force

@njit
def external_force(force, k, axis = 2):
    """Computes contribution to the force on the particles due to an external force
    directed on a given axis (default z-axis)

    Args:
        force -- np.array([N, 3]) containing forces
        k -- parameter for force strenght
        axis -- (default = 2) direction of the force, default is z-axis

    Parameters:
        sigma -- parameter from the Lennard-Jones potential
        epsilon -- parameter from the Lennard-Jones potential

    Returns:
        force -- updated array containing the net force of all particles
    Notes:
        -- the routine runs using Numba @njit decorator for faster run time
    """
    for i in range(force.shape[0]):
        force[i, axis] -= k * epsilon / sigma

    return force

def LJ_potential_shift():
    """Computes the LJ potential shift

    Parameters:
        cutoff -- radius at which the potential is truncated and shifted

    Notes:
        -- this is done once at the beginning of each simulation
    """
    global potential_shift
    potential_shift = 4*epsilon*(np.power(sigma/cutoff, 12) - np.power(sigma/cutoff, 6))


# Version clara

# with open("names.csv") as file:
    # for line in file:
        # row = line.rstrip().split(",")     # corta y separa en cada coma
        # print(f"{row[0]} is in {row[1]}")

# version que almacena en variables distintas

with open("names.csv") as file:
    for line in file:
        name, house = line.rstrip().split(",")     # corta, separa en cada coma y almacena en cada variable
        print(f"{name} is in {house}")


from tensorflow.keras.models import Sequential #cnn
from tensorflow.keras.layers import Conv2D,Activation,MaxPooling2D,Dropout,Flatten,Dense
import numpy
from tensorflow.keras.optimizers import Adam
from sklearn.model_selection import train_test_split
from tensorflow.keras.callbacks import ModelCheckpoint

images=numpy.load('images.npy')
labels=numpy.load('labels.npy')

model=Sequential()

#build model
model.add(Conv2D(256,kernel_size=(3,3),input_shape=images.shape[1:]))
model.add(Activation('relu'))
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Conv2D(128,kernel_size=(3,3)))
model.add(Activation('relu')) #rectified linear unit removes negetive pixels
model.add(MaxPooling2D(pool_size=(2,2)))

model.add(Flatten())
model.add(Dense(60,activation="relu"))
model.add(Dense(2,activation="softmax")) #output layer

#compilation
model.compile(loss="categorical_crossentropy",optimizer=Adam(lr=0.00001,decay=0.000001),metrics=['accuracy'])

#training
X_train,X_test,y_train,y_test=train_test_split(images,labels,test_size=0.2)

ch=ModelCheckpoint("Maskdata.hdf5",verbose=0,monitor="val_loss",save_best_only=True,mode="auto")

model.fit(X_train,y_train,epochs=10,callbacks=[ch],validation_split=0.2)

print("training done....")


import keras
import pandas as pd

# 读取文件数据 返回 训练数据 以及标签
from kashgari.embeddings import BERTEmbedding, WordEmbeddings
from kashgari.tasks.classification import BLSTMModel, CNNModel
import thulac

tf_board_callback = keras.callbacks.TensorBoard(log_dir='./logs', update_freq=1000)

thu = thulac.thulac(user_dict="../dictionary/THUOCL_medical.txt", seg_only=True)

class MedicalClassification:
    def f(self):
        pass

    @staticmethod
    def read_message(filename):
        # 原文
        x_items = []
        # 标签
        train_y = []
        file = open(filename, 'r', encoding='utf-8')
        for line in file:
            message = line.split('\t')
            # 已经分词文件 空格切分
            q_a = str(message[0] + ' ' + message[1] + ' ' + message[2])
            # 移除所有空格
            q_a = q_a.replace(" ", '')
            # 按字进行分割
            waiting_q_a = list(q_a)
            x_items.append(waiting_q_a)
            answer = message[3]
            # 移除标签中的\n
            answer = answer.replace("\n", "")

            train_y.append(answer)
        return x_items, train_y

    # 训练模型
    def train(self):
        x_train, train_y = self.read_message('../data/西药执业药师/train.txt')
        x_dev, dev_y = self.read_message('../data/西药执业药师/test.txt')
        x_test, test_y = self.read_message('../data/西药执业药师/dev.txt')
        # 获取bert字向量
        bert = BERTEmbedding('bert-base-chinese', sequence_length=100)
        # 获取词向量
        # embedding = WordEmbeddings('sgns.weibo.bigram.bz2', 50)

        long_model = CNNModel(bert)
        # 输入模型训练数据 标签 步数
        long_model.fit(x_train,
                       train_y,
                       x_dev,
                       dev_y,
                       epochs=20,
                       batch_size=128,
                       fit_kwargs={'callbacks': [tf_board_callback]})
        # 保存模型
        long_model.save("../classification-model")
        result = long_model.evaluate(x_test, test_y)
        return result

    def pre_train(self):
        bilstm_model = BLSTMModel.load_model('../classification-model')
        x_items, _ = self.read_message('../data/西药执业药师/dev.txt')
        for i in x_items:
            result = bilstm_model.predict(i)
            print("\n" + result)

if __name__ == '__main__':
    model = MedicalClassification()
    model.train()


from datetime import datetime
from collections import defaultdict
from pathlib import Path
import pickle
import tensorflow as tf

import numpy as np

from energypy import json_util, registry, utils
from energypy.agent import memory

from energypy.init import init_nets, init_optimizers, init_writers

def save(
    hyp,
    nets,
    optimizers,
    buffer,
    episode,
    rewards,
    counters,
    paths=None,
    path=None

):
    if paths:
        path = paths['run'] / 'checkpoints' / f'test-episode-{episode}'
    else:
        assert path is not None

    path = Path(path)
    path.mkdir(exist_ok=True, parents=True)
    for name, net in nets.items():
        if 'alpha' not in name:
            net.save_weights(path / f'{name}.h5')

    #  save alpha!
    log_alpha = nets['alpha'].numpy()
    np.save(path / 'alpha.npy', log_alpha)

    for name, optimizer in optimizers.items():
        wts = optimizer.get_weights()
        if wts:
            opt_path = path / f'{name}.pkl'
            with opt_path.open('wb') as fi:
                pickle.dump(wts, fi)

    if memory:
        memory.save(buffer, path / 'buffer.pkl')

    if rewards:
        rewards = dict(rewards)
        rewards['time'] = datetime.utcnow().isoformat()
        json_util.save(
            rewards,
            path / 'rewards.json'
        )
    if counters:
        json_util.save(
            dict(counters),
            path / 'counters.json'
        )
    json_util.save(
        hyp,
        path / 'hyperparameters.json'
    )

def get_checkpoint_paths(run):
    checkpoints = Path(run) / 'checkpoints'
    return [p for p in checkpoints.iterdir() if p.is_dir()]

def load(run, full=False):
    """loads all checkpoints, only loading some checkpoint elements"""
    checkpoints = get_checkpoint_paths(run)
    return [load_checkpoint(p, full) for p in checkpoints]

def load_hyp(path):
    return json_util.load(path / 'hyperparameters.json')

def load_checkpoint(path, full=True):
    """full mode loads everything, other mode loads only rewards & counters
    idea is to have a way to quickly evaluate checkpoints without loading what we don't need"""

    path = Path(path)

    hyp = load_hyp(path)

    rewards = json_util.load(path / 'rewards.json')
    rewards.pop('time')
    rewards = defaultdict(list, rewards)
    counters = defaultdict(int, json_util.load(path / 'counters.json'))

    results = {
        'path': path,
        'hyp': hyp,
        'rewards': rewards,
        'counters': counters,
    }

    if full:
        #  catch a wierd error when we load old buffers
        try:
            buffer = memory.load(path / 'buffer.pkl')
        except ModuleNotFoundError:
            print('failed to load buffer due to ModuleNotFoundError')
            buffer = None

        env = registry.make(**hyp['env'])
        nets = init_nets(env, hyp)

        #  awkward
        nets.pop('target_entropy')
        for name, net in nets.items():
            #  awkward
            if 'alpha' not in name:
                net.load_weights(path / f'{name}.h5')
                print(f'loaded {name}')

        log_alpha = nets['alpha']
        saved_log_alpha = np.load(path / 'alpha.npy')
        log_alpha.assign(saved_log_alpha)

        optimizers = init_optimizers(hyp)
        for name, opt in optimizers.items():
            opt_path = path / f'{name}.pkl'

            if opt_path.exists():
                # https://stackoverflow.com/questions/49503748/save-and-load-model-optimizer-state
                model = nets[name]
                #  single var
                if 'alpha' in name:
                    wts = [model, ]
                else:
                    wts = model.trainable_variables
                zero_grads = [tf.zeros_like(w) for w in wts]
                opt.apply_gradients(zip(zero_grads, wts))

                with opt_path.open('rb') as fi:
                    opt.set_weights(pickle.load(fi))

        results['env'] = env
        results['nets'] = nets
        results['optimizers'] = optimizers
        results['buffer'] = buffer

    return results

def init_checkpoint(checkpoint_path):
    point = load_checkpoint(checkpoint_path)
    hyp = point['hyp']
    paths = utils.get_paths(hyp)
    counters = point['counters']

    writers = init_writers(counters, paths)

    transition_logger = utils.make_logger('transitions.data', paths['run'])
    c = point

    rewards = point['rewards']
    return {
        'hyp': hyp,
        'paths': paths,
        'counters': counters,
        'env': c['env'],
        'buffer': c['buffer'],
        'nets': c['nets'],
        'writers': writers,
        'optimizers': c['optimizers'],
        'transition_logger': transition_logger,
        'rewards': rewards
    }


"""Submission file for a SAM optimizer with warmup+cosine LR in Jax."""

import functools
from typing import Dict, Iterator, List, Optional, Tuple

from flax import jax_utils
import jax
from jax import lax
import jax.numpy as jnp
import optax

from algorithmic_efficiency import spec

_GRAD_CLIP_EPS = 1e-6

# Copied from the official SAM GitHub repository. Note how it doesn't add an
# epsilon to the gradient norm before normalizing the gradients.
def dual_vector(y: jnp.ndarray) -> jnp.ndarray:
  """Returns the solution of max_x y^T x s.t.
  ||x||_2 <= 1.
  Args:
    y: A pytree of numpy ndarray, vector y in the equation above.
  """
  gradient_norm = jnp.sqrt(
      sum(jnp.sum(jnp.square(e)) for e in jax.tree_util.tree_leaves(y)))
  normalized_gradient = jax.tree_map(lambda x: x / gradient_norm, y)
  return normalized_gradient

# github.com/google/init2winit/blob/master/init2winit/optimizer_lib/
# sharpness_aware_minimization.py
def sharpness_aware_minimization(
    rho: float,
    grad_clip: Optional[float],
    batch_axis_name: str,
    base_opt_init_fn,
    base_opt_update_fn,
) -> optax.GradientTransformation:
  """Implementation of Sharpness Aware Minimization (SAM).
  Paper: https://arxiv.org/abs/2010.01412
  Code: https://github.com/google-research/sam
  References:
    Foret et al, 2021: https://arxiv.org/abs/2010.01412
  Args:
    rho: The size of the neighborhood for the sharpness aware minimization
      gradient updates. Defaults to 0.1.
    grad_clip: The optional value to clip the updates by. Defaults to None.
    batch_axis_name: the name of the axis to pmap over. Used to run a pmean
      before applying the optimizer update.
    base_opt_init_fn: The initialization function for the base optimizer used to
      generate updates given the total gradient.
    base_opt_update_fn: The update function for the base optimizer used to
      generate updates given the total gradient.
  Returns:
    The corresponding `GradientTransformation`.
  """

  def init_fn(params):
    return base_opt_init_fn(params)

  def update_fn(updates, state, grad_fn_params_tuple):
    (grad_fn, params) = grad_fn_params_tuple

    # Updates here have been synced (mean) across devices before being sent to
    # the optimizer. We again take the correct mean of the gradients computed on
    # the noised parameters in the same order as on the original gradients and
    # with the same 1e-6 epsilon that is used when clipping the gradients.
    updates = dual_vector(updates)
    noised_params = jax.tree_util.tree_map(
        lambda p, u: p + rho * u, params, updates)
    (_, (n_valid_examples, _)), updates = grad_fn(noised_params)
    # Get correct global mean grad.
    (n_valid_examples, updates) = lax.psum((n_valid_examples, updates),
                                           axis_name=batch_axis_name)
    updates = jax.tree_map(lambda x: x / n_valid_examples, updates)

    if grad_clip:
      updates_norm = jnp.sqrt(
          sum(jnp.sum(g**2) for g in jax.tree_util.tree_leaves(updates)))
      scaled_updates = jax.tree_map(
          lambda x: x / (updates_norm + _GRAD_CLIP_EPS) * grad_clip, updates)
      updates = jax.lax.cond(updates_norm > grad_clip,
                             lambda _: scaled_updates,
                             lambda _: updates,
                             None)
    updates, state = base_opt_update_fn(updates, state, params)

    return updates, state

  return optax.GradientTransformation(init_fn, update_fn)

def init_optimizer_state(workload: spec.Workload,
                         model_params: spec.ParameterContainer,
                         model_state: spec.ModelAuxiliaryState,
                         hyperparameters: spec.Hyperparameters,
                         rng: spec.RandomState) -> spec.OptimizerState:
  """Creates a SAM optimizer (with AdamW base) and a learning rate schedule."""
  del model_params
  del model_state
  del rng

  def jax_cosine_warmup(step_hint: int, hyperparameters):
    # Create learning rate schedule.
    warmup_steps = int(hyperparameters.warmup_factor * step_hint)
    warmup_fn = optax.linear_schedule(
        init_value=0.,
        end_value=hyperparameters.learning_rate,
        transition_steps=warmup_steps)
    cosine_steps = max(step_hint - warmup_steps, 1)
    cosine_fn = optax.cosine_decay_schedule(
        init_value=hyperparameters.learning_rate, decay_steps=cosine_steps)
    schedule_fn = optax.join_schedules(
        schedules=[warmup_fn, cosine_fn], boundaries=[warmup_steps])
    return schedule_fn

  # Create base optimizer + LR schedule.
  lr_schedule_fn = jax_cosine_warmup(workload.step_hint, hyperparameters)
  opt_init_fn, opt_update_fn = optax.adamw(
      learning_rate=lr_schedule_fn,
      b1=1.0 - hyperparameters.one_minus_beta1,
      b2=hyperparameters.beta2,
      eps=1e-8,
      weight_decay=hyperparameters.weight_decay)

  # Create SAM update fn.
  grad_clip = (
      hyperparameters.grad_clip
      if hasattr(hyperparameters, 'grad_clip') else None)
  opt_init_fn, opt_update_fn = sharpness_aware_minimization(
      rho=hyperparameters.rho,
      grad_clip=grad_clip,
      batch_axis_name='batch',
      base_opt_init_fn=opt_init_fn,
      base_opt_update_fn=opt_update_fn)

  # Initialize optimizer state.
  params_zeros_like = jax.tree_map(lambda s: jnp.zeros(s.shape_tuple),
                                   workload.param_shapes)
  optimizer_state = opt_init_fn(params_zeros_like)

  return jax_utils.replicate(optimizer_state), opt_update_fn

@functools.partial(
    jax.pmap,
    axis_name='batch',
    in_axes=(None, None, 0, 0, 0, 0, 0, None, None),
    static_broadcasted_argnums=(0, 1),
    donate_argnums=(2, 3, 4))
def pmapped_train_step(workload,
                       opt_update_fn,
                       model_state,
                       optimizer_state,
                       current_param_container,
                       batch,
                       rng,
                       grad_clip,
                       label_smoothing):

  def _loss_fn(params, update_batch_norm=True):
    """Loss function used for training."""
    logits, new_model_state = workload.model_fn(
        params,
        batch,
        model_state,
        spec.ForwardPassMode.TRAIN,
        rng,
        update_batch_norm=update_batch_norm)
    loss_dict = workload.loss_fn(
        label_batch=batch['targets'],
        logits_batch=logits,
        mask_batch=batch.get('weights'),
        label_smoothing=label_smoothing)
    summed_loss = loss_dict['summed']
    n_valid_examples = loss_dict['n_valid_examples']
    return summed_loss, (n_valid_examples, new_model_state)

  grad_fn = jax.value_and_grad(_loss_fn, has_aux=True)
  second_grad_fn = jax.value_and_grad(
      functools.partial(_loss_fn, update_batch_norm=False), has_aux=True)
  (summed_loss, (n_valid_examples, new_model_state)), grad = grad_fn(
      current_param_container)
  # Get correct global mean loss and grad.
  (summed_loss, n_valid_examples, grad) = lax.psum(
      (summed_loss, n_valid_examples, grad), axis_name='batch')
  loss = summed_loss / n_valid_examples
  grad = jax.tree_map(lambda x: x / n_valid_examples, grad)

  grad_norm = jnp.sqrt(
      sum(jnp.sum(g**2) for g in jax.tree_util.tree_leaves(grad)))

  updates, new_optimizer_state = opt_update_fn(
      grad, optimizer_state, (second_grad_fn, current_param_container))
  updated_params = optax.apply_updates(current_param_container, updates)
  return new_optimizer_state, updated_params, new_model_state, loss, grad_norm

def update_params(workload: spec.Workload,
                  current_param_container: spec.ParameterContainer,
                  current_params_types: spec.ParameterTypeTree,
                  model_state: spec.ModelAuxiliaryState,
                  hyperparameters: spec.Hyperparameters,
                  batch: Dict[str, spec.Tensor],
                  loss_type: spec.LossType,
                  optimizer_state: spec.OptimizerState,
                  eval_results: List[Tuple[int, float]],
                  global_step: int,
                  rng: spec.RandomState) -> spec.UpdateReturn:
  """Return (updated_optimizer_state, updated_params, updated_model_state)."""
  del current_params_types
  del loss_type
  del eval_results

  optimizer_state, opt_update_fn = optimizer_state
  per_device_rngs = jax.random.split(rng, jax.local_device_count())
  if hasattr(hyperparameters, 'label_smoothing'):
    label_smoothing = hyperparameters.label_smoothing
  else:
    label_smoothing = 0.0
  if hasattr(hyperparameters, 'grad_clip'):
    grad_clip = hyperparameters.grad_clip
  else:
    grad_clip = None
  outputs = pmapped_train_step(workload,
                               opt_update_fn,
                               model_state,
                               optimizer_state,
                               current_param_container,
                               batch,
                               per_device_rngs,
                               grad_clip,
                               label_smoothing)
  new_optimizer_state, new_params, new_model_state, loss, grad_norm = outputs

  # Log loss, grad_norm.
  if global_step % 100 == 0 and workload.metrics_logger is not None:
    workload.metrics_logger.append_scalar_metrics(
        {
            'loss': loss[0],
            'grad_norm': grad_norm[0],
        }, global_step)
  return (new_optimizer_state, opt_update_fn), new_params, new_model_state

def get_batch_size(workload_name):
  # Return the global batch size.
  if workload_name == 'criteo1tb':
    return 262_144
  elif workload_name == 'fastmri':
    return 32
  elif workload_name == 'imagenet_resnet':
    return 1024
  elif workload_name == 'imagenet_vit':
    return 1024
  elif workload_name == 'librispeech_conformer':
    return 256
  elif workload_name == 'librispeech_deepspeech':
    return 256
  elif workload_name == 'ogbg':
    return 512
  elif workload_name == 'wmt':
    return 128
  elif workload_name == 'mnist':
    return 16
  else:
    raise ValueError(f'Unsupported workload name: {workload_name}.')

def data_selection(
    workload: spec.Workload,
    input_queue: Iterator[Dict[str, spec.Tensor]],
    optimizer_state: spec.OptimizerState,
    current_param_container: spec.ParameterContainer,
    model_state: spec.ModelAuxiliaryState,
    hyperparameters: spec.Hyperparameters,
    global_step: int,
    rng: spec.RandomState) -> Tuple[spec.Tensor, spec.Tensor, spec.Tensor]:
  """Select data from the infinitely repeating, pre-shuffled input queue.
  Each element of the queue is a batch of training examples and labels.
  """
  del workload
  del optimizer_state
  del current_param_container
  del model_state
  del hyperparameters
  del global_step
  del rng
  batch = next(input_queue)
  return batch


from flask import Flask, render_template, request, redirect, url_for
import sqlite3 as sq
from math import floor
from random import choice, choices
from logging import info, basicConfig, INFO, warning

basicConfig(level=INFO)
info('Config Set')

db = sq.connect('db.sqlite3')
cur = db.cursor()
try:
    cur.execute("""CREATE TABLE polls (
	pollid INTEGER PRIMARY KEY,
	length INTEGER NOT NULL,
	done INTEGER NOT NULL,
	winner TEXT
);""")#0 means not done, 1 means done
    info('Database Created')
except:
    info('Database already created')

db.commit()
cur.close()
db.close()

app = Flask(__name__)

@app.route('/results/<int:id>', methods=['POST', 'GET'])
def results(id):
    if request.method == 'POST':
        warning('Someone POSTed to results?')
        # change the 'done' status
        # make a new template
        # implement the randomisation bit
        return 'results, post'
    else:
        db = sq.connect('db.sqlite3')
        cur = db.cursor()

        cur.execute('SELECT done FROM polls WHERE pollid = {}'.format(str(id)))
        done = cur.fetchall()[0][0]

        ip = request.remote_addr

        if done == 1:
            info('{} is viewing the results of poll {}'.format(ip, id))
            # fetch the winner

            cur.execute('SELECT winner FROM polls WHERE pollid = {}'.format(str(id)))
            winner = cur.fetchall()[0][0]

            cur.execute('SELECT * FROM {}'.format('poll'+str(id)))
            results = cur.fetchall()

            results = [[p[x] for x in range(1, len(p))] for p in results]
            voters = len(results)
            results = [sum(i) for i in zip(*results)]

            cur.execute('SELECT name FROM PRAGMA_TABLE_INFO("{}");'.format('poll' + str(id)))
            columns = cur.fetchall()
            columns = [x[0] for x in columns[1:]]

            cur.close()
            db.close()

            matched = [x for x in zip(results, columns)]
            matched = sorted(matched, key= lambda x: x[0], reverse=True)
            results = [x[0] for x in matched]
            columns = [x[1] for x in matched]

            return render_template('finalised.html', winner=winner, films=columns, results=results, voteramount=voters)

            # display the finalised results
        else:
            pass
            # if not, we continue to do things normally

        # do the dodgy js stuff to live update amount of people who have voted
        #print(request.form)
        finalising=0
        try:
            finalising = request.args['finished']
        except:
            pass

        if finalising == 'yes':
            info('Poll {} is being finalised'.format(str(id)))

            cur.execute('UPDATE polls SET done=1 WHERE pollid = {}'.format(str(id)))
            db.commit()

            cur.execute('SELECT * FROM {}'.format('poll'+str(id)))
            results = cur.fetchall()

            results = [[p[x] for x in range(1, len(p))] for p in results]
            voters = len(results)
            results = [sum(i) for i in zip(*results)]

            info('The results of poll {0} are: {1}'.format(str(id), ', '.join([str(x) for x in results])))

            cur.execute('SELECT name FROM PRAGMA_TABLE_INFO("{}");'.format('poll' + str(id)))
            columns = cur.fetchall()
            columns = [x[0] for x in columns[1:]]

            mx = max(results)
            indices = []
            for index, x in enumerate(results):
                if x==mx:
                    indices.append(index)

            thresh = floor(0.7*mx)

            for index, x in enumerate(results):
                if x>thresh and index not in indices:
                    indices.append(index)

            winner = choices([columns[x] for x in indices], weights = [results[x] for x in indices], k=1)[0]

            if mx<0:
                winner = columns[choice(indices)]

            info('The winner of poll {0} is {1}'.format(str(id), winner))

            # update the table with the winner

            #print(winner)
            #print(str(id))
            cur.execute('UPDATE polls SET "winner"="{1}" WHERE "pollid"={0};'.format(str(id), winner))
            db.commit()
            cur.close()
            db.close()

            matched = [x for x in zip(results, columns)]
            matched = sorted(matched, key= lambda x: x[0], reverse=True)
            results = [x[0] for x in matched]
            columns = [x[1] for x in matched]

            return render_template('finalised.html', winner=winner, films=columns, results=results, voteramount=voters)
        else:
            cur.close()
            db.close()
            info('{} is waiting for finalisation'.format(request.remote_addr))
            return render_template('results.html')

@app.route('/vote/<int:id>', methods=['POST', 'GET'])
def vote(id):
    if request.method == 'POST':
        #IP adding?

        db = sq.connect('db.sqlite3')
        cur=db.cursor()

        cur.execute('SELECT "voterip" FROM {0}'.format('poll'+str(id)))

        ips = cur.fetchall()

        ip = request.remote_addr

        if ip in ips:
            info('{} tried to vote twice'.format(ip))
            return redirect(url_for('results', id=id))

        info('{} POSTed to vote'.format(ip))

        f = request.form

        name = 'poll'+str(id)
        columns = [x for x in f][:-1]
        values = [f[x] for x in columns]

        command = 'INSERT INTO {0} ("voterip", "{1}") VALUES ("{2}", {3});'.format(name, '","'.join(columns), ip,
                                                                                ','.join(values))

        cur.execute(command)
        db.commit()
        info('{} had vote added to table'.format(ip))

        cur.close()
        db.close()

        return redirect(url_for('results', id=id))
    else:

        db = sq.connect('db.sqlite3')
        cur = db.cursor()

        cur.execute('SELECT "voterip" FROM {0}'.format('poll'+str(id)))

        ips = cur.fetchall()
        #print('-'*20)
        #print(ips)
        #print('-' * 20)
        ips = [x[0] for x in ips]

        ip = request.remote_addr

        info('{0} is attempting to vote in poll number {1}. Votes have already been made by: {2}'.format(ip, str(id),', '.join(ips)))

        if ip in ips:
            info('Voter {0} has been turned away from poll number {1} to prevent duplicates'.format(ip, str(id)))
            return "You've already voted!!!"

        cur.execute('SELECT "done" from polls WHERE pollid={}'.format(str(id)))
        z = cur.fetchall()[0][0]
        if z==1:
            info('Voter {0} has been turned away because poll number {1} has concluded'.format(ip, str(id)))
            return 'This poll has finished'

        cur.execute('SELECT name FROM PRAGMA_TABLE_INFO("{}");'.format('poll'+str(id)))
        films = cur.fetchall()
        #print(films)
        films = films[1:]
        #print(films)
        films = [x[0] for x in films]
        #print(films)

        cur.close()
        db.close()

        return render_template('pollbox.html', films=films)

@app.route('/')
def index():
    info('Someone redirected from / to /create')
    return redirect(url_for('create'))

# @app.route('/submit/<int:id>', methods=['POST', 'GET'])
# def submit():
#     if request.method == 'POST':
#         f = request.form
#         return f['StudioGhibli']
#     else:
#         return redirect(url_for('vote'))

@app.route('/create', methods=['POST','GET'])
def create():
    if request.method == 'POST':

        f = request.form
        films = f['films']
        z=films.split('\n')
        for x in range(len(z)-1):
            z[x] = (z[x])[:len(z[x])-1]
            z[x] = z[x].strip()
        z = [x for x in z if x != '']

        db = sq.connect('db.sqlite3')
        cur = db.cursor()
        cur.execute('INSERT INTO polls (length, done) VALUES ({}, 0);'.format(len(z)))
        db.commit()

        info('polls updated with new poll')

        c = [('"' + x + '" INTEGER NOT NULL') for x in z]
        c = ', '.join(c)

        cur.execute('SELECT pollid FROM polls ORDER BY pollid DESC LIMIT 1;')
        z = cur.fetchall()
        z=z[0][0]

        info('Number of the poll is {}'.format(str(z)))

        command = 'CREATE TABLE {0} ("voterip" TEXT, {1});'.format('"poll'+str(z)+'"', c)

        info('Poll {} has had its table created'.format(str(z)))

        cur.execute(command)
        db.commit()

        cur.close()
        db.close()

        return redirect(url_for('vote', id=z))
    else:
        return render_template('create.html')

if __name__ == '__main__':
    app.run(debug=True)


from math import floor

import cupy
import numpy as np
from numba import cuda
from numba import int32, float64, float32, void

from .._helpers import Ctx
from ..utils import cu_unravel_index_f, cu_ravel_index_f_pbc

class clist:
    def __init__(self, r_cut, r_buff=0.5):
        system = Ctx.get_active()
        if system is None:
            raise ValueError("No active system!")
        self.system = system
        self.r_cut = r_cut
        self.r_buff = r_buff
        self.ibox = np.asarray(np.floor(system.box / (r_cut + r_buff)), dtype=np.int32)
        self.n_cell = int(np.multiply.reduce(self.ibox))
        self.cell_adj = np.ones(system.n_dim, dtype=np.int32) * 3
        self.gpu = system.gpu
        self.tpb = 64
        self.bpg_part = int(system.N / self.tpb + 1)
        self.bpg_cell = int((self.n_cell + 1) // self.tpb + 1)
        self.cu_cell_list, self.cu_cell_map = self._gen_func()
        self.d_cell_list = None
        with cuda.gpus[self.gpu]:
            self.d_cells = cupy.empty((system.N,), dtype=np.int32)
            self.d_cell_map = cuda.device_array((self.n_cell, 3 ** system.n_dim), dtype=np.int32)
            self.d_ibox = cuda.to_device(self.ibox)
            self.d_cell_adj = cuda.to_device(self.cell_adj)
            self.cu_cell_map[self.bpg_cell, self.tpb](self.d_ibox, self.d_cell_adj, self.d_cell_map)
            self.d_cell_counts = cupy.zeros(self.n_cell + 1, dtype=np.int32)
            # cu_cell_list[self.bpg_part, self.tpb](system.d_x, system.d_box, self.d_ibox,
            #                                      self.d_cells, self.d_cell_counts)
            # cupy.cumsum(self.d_cell_counts, out=self.d_cell_counts)
            # self.d_cell_list = cupy.argsort(self.d_cells)
        self.update()

    def update(self):
        with cuda.gpus[self.gpu]:
            self.d_cell_counts.fill(0)
            self.cu_cell_list[self.bpg_part, self.tpb](self.system.d_x, self.system.d_box, self.d_ibox,
                                                       self.d_cells, self.d_cell_counts)
            cupy.cumsum(self.d_cell_counts, out=self.d_cell_counts)
            self.d_cell_list = cupy.argsort(self.d_cells)

    def _gen_func(self):
        nb_float = float64
        if self.system.dtype == np.dtype(np.float32):
            nb_float = float32
        n_dim = self.system.n_dim

        @cuda.jit(void(int32[:], int32[:], int32[:, :]))
        def cu_cell_map(ibox, dim, ret):
            cell_i = cuda.grid(1)
            if cell_i >= ret.shape[0]:
                return
            cell_vec_i = cuda.local.array(n_dim, int32)
            cell_vec_j = cuda.local.array(n_dim, int32)
            cu_unravel_index_f(cell_i, ibox, cell_vec_i)
            for j in range(ret.shape[1]):
                cu_unravel_index_f(j, dim, cell_vec_j)
                for k in range(n_dim):
                    cell_vec_j[k] = cell_vec_i[k] + cell_vec_j[k] - 1
                cell_j = cu_ravel_index_f_pbc(cell_vec_j, ibox)
                ret[cell_i, j] = cell_j

        def _gen_cell_list():
            @cuda.jit(int32(nb_float[:], nb_float[:], int32[:]), device=True)
            def cu_cell_index(x, box, ibox):
                ret = floor((x[0] / box[0] + 0.5) * ibox[0])
                n_cell = ibox[0]
                for i in range(1, x.shape[0]):
                    ret = ret + floor((x[i] / box[i] + 0.5) * ibox[i]) * n_cell
                    n_cell = n_cell * ibox[i]
                return ret

            @cuda.jit(void(nb_float[:, :], nb_float[:], int32[:], int32[:], int32[:]))
            def cu_cell_list(pos, box, ibox, cells, cell_counts):
                i = cuda.grid(1)
                if i < pos.shape[0]:
                    pi = pos[i]
                    ic = cu_cell_index(pi, box, ibox)
                    cells[i] = ic
                    cuda.atomic.add(cell_counts, ic + 1, 1)

            return cu_cell_list

        return _gen_cell_list(), cu_cell_map


from pynwb.spec import NWBDatasetSpec, NWBNamespaceBuilder, NWBGroupSpec, \
    NWBAttributeSpec

namespace = 'general'
ns_path = namespace + '.namespace.yaml'
ext_source = namespace + '.extensions.yaml'

values = NWBAttributeSpec(name='values',
                          dtype='text',
                          doc='values that the indices are indexing',
                          shape=(None,))

cat_cell_info = NWBGroupSpec(
    neurodata_type_def='CatCellInfo',
    doc='Categorical Cell Info',
    attributes=[NWBAttributeSpec(
        name='help',
        doc='help',
        dtype='text',
        value='Categorical information about cells. For most cases the units tables is more appropriate. This '
              'structure can be used if you need multiple entries per cell')],
    datasets=[
        NWBDatasetSpec(doc='global id for neuron',
                       shape=(None,),
                       name='cell_index', dtype='int', quantity='?'),
        NWBDatasetSpec(name='indices',
                       doc='list of indices for values',
                       shape=(None,), dtype='int',
                       attributes=[values])],
    neurodata_type_inc='NWBDataInterface')

cat_timeseries = NWBGroupSpec(
    neurodata_type_def='CatTimeSeries',
    neurodata_type_inc='TimeSeries',
    doc='Categorical data through time',
    datasets=[NWBDatasetSpec(name='data',
                             shape=(None,), dtype='int',
                             doc='timeseries of indicies for values',
                             attributes=[values])])

ns_builder = NWBNamespaceBuilder(doc=namespace + ' extensions', name=namespace,
                                 version='1.0', author='Ben Dichter',
                                 contact='bendichter@gmail.com')
for spec in (cat_cell_info, cat_timeseries):
    ns_builder.add_spec(ext_source, spec)
ns_builder.export(ns_path)


class Player(object):
    score = None
    age = None

    def __init__(self, name, last_name) -> None:
        self.name = name
        self.last_name = last_name

    def __repr__(self):
        if self.score is not None:
            return f"Player {self.name} {self.last_name} -> {self.score}.\n"
        else:
            return f"Player {self.name} {self.last_name}.\n"

    def __str__(self):
        if self.score is not None:
            return f"Player {self.name} {self.last_name} -> {self.score}.\n"
        else:
            return f"Player {self.name} {self.last_name}.\n"

    def set_score(self, value) -> bool:
        if value >= 0:
            self.score = value
            return True
        else:
            print("Invalid Value")
            return False

    def set_age(self, age) -> bool:
        if age >= 0:
            self.age = age
            return True
        else:
            print("Invalid Value")
            return False

    def get_dict_repr(self):
        return {
            "Name": self.name,
            "Last name": self.last_name,
            "Score": self.score
        }

if __name__ == "__main__":  # класс работает только в этом файле - уточнить! В телеге доп.инфа.
    a = Player("Sergey", "Bubka")
    a.set_score(615)
    print(a.score)
    print(dir(a))
    print(a)


#!/usr/bin/env python3
import argparse
from pathlib import Path

parser = argparse.ArgumentParser(description='Produce a set of predefined kilograms plots.')
parser.add_argument("data_path", help="File containing data to be plotted", type=Path)
parser.add_argument("-c", "--config", help="Config file, containing plot type definitions.", type=Path, required=True)
parser.add_argument("-n", "--names", help="Names of plots to be produced (comma-separated)", type=str, default=None)
parser.add_argument("-o", "--output", help="Output file path. Will display onscreen if omitted. \"?\" will be replaced by plot name (remember to bash-escape it).", type=str, default="plot-?.pdf")
parser.add_argument("-f", "--force", help="force overwriting of the target path if it exists", action='store_true')
args=parser.parse_args()

import math
import numpy as np
import toml
from matplotlib import pyplot as plt
import pandas
from dia_common.misc import pandas_read_table
import kilograms

config = toml.load(args.config)

if args.names is None:
    args.names = ','.join(config.keys())

data = pandas_read_table(args.data_path)
data_dct = {colname: data[colname] for colname in data}

for plot_name in args.names.split(","):
    plot = config[plot_name]
    out_p = Path(args.output.replace("?", plot_name))

    if not args.force:
        assert not out_p.exists()

    df = pandas.DataFrame()
    for colname, coldef in plot.items():
        df[colname] = eval(coldef, globals() | data_dct)

    with plt.style.context('dark_background'):
        fig, axes = kilograms.scatterplot_matrix(df, show=False)
        fig.set_size_inches(30, 30)
        plt.savefig(out_p, dpi=100, transparent=False)
        plt.close()