from django.shortcuts import render,redirect
from customer.models import *
from adminpanel.models import *

def customerauthentication(data_fun):
    def check(request):
        if request.session.has_key('customer-id'):
            return data_fun(request)
        else:
            return redirect('/')
    return check

def sessioncreation(data_fun):
    def check(request):
        if request.session.has_key('customer-id'):
            customerid = 'custo-'+str(request.session['customer-id'])
            current_sessionid = request.session['guest-session']
            value = CartList.objects.filter(session=current_sessionid).values_list('productid__id')
            idlist = [i for j in value for i in j]
            if idlist:
                for item in idlist:
                    product_exist = CartList.objects.filter(session=customerid,productid__id=item)
                    if not product_exist:
                        product_details = ProductSize.objects.get(id=item)
                        value2 = CartList.objects.filter(productid__id=item).values_list('quantity','price')
                        prqty = [i for j in value2 for i in j]
                        CartList.objects.create(session=customerid,productid=product_details,quantity=prqty[0],price=prqty[1])

            request.session['customer-session'] = customerid
            return data_fun(request)
        else:
            if request.session.has_key('guest-session'):
                return data_fun(request)
            else:
                lastguest = CartList.objects.all().last()
                if lastguest:
                    lastguestid = lastguest.session
                    questid = f'guest-{int(lastguestid[6:])+1}'
                else:
                    questid = 'guest-1'
                request.session['guest-session'] = questid
                return data_fun(request)
    return check

def checkoutauthentication(function):
    def check(request):
        if request.session.has_key('customer-id'):
            sessionid = request.session['customer-session']
            cart_item = CartList.objects.filter(session=sessionid)
            if cart_item:
                value = CartList.objects.filter(session=sessionid).values_list('id')
                cartids = [i for j in value for i in j]
                price = 0
                for item in cartids:
                    pro_details = CartList.objects.get(id=item)
                    price += int(pro_details.productid.price)*(pro_details.quantity)
                value = CartList.objects.filter(session=sessionid).values_list('quantity')
                qty = [i+i for j in value for i in j]
                count = 0
                for item in qty:
                    count += item           #here creating token for unautherized access.
                tokenno = count+price       #token will delete after order placed

                check = CheckoutToken.objects.filter(customerid=sessionid,tokenno=tokenno)
                if check:
                    return function(request)
                else:
                    return redirect('/shoppingcart/')
            else:
                return redirect('/')

        else:
            return redirect('/shoppingcart/')
    return check


# What this code does:
# Write a simple linear equation that only includes the '+' and '-' symbols, and the unknown varibale is x.
# This code will solve for x

class Solve:
    def __init__(self,equation):
        self.equation = list(equation)

    def equationtidy(self):
        equationtidy=[]
        for i in self.equation:
            if ' ' != i:
                equationtidy.append(i)
        return equationtidy

    def seperate(self):
        global equationleft,equationright
        for i in range(len(self.equationtidy())):
            if '=' == self.equationtidy()[i]:
                equationleft = self.equationtidy()[:i]
                equationright = self.equationtidy()[i+1:]
                break
        return [equationleft,equationright]

    def symbolfinder(self):
        global symbollistleft,symbollistright
        symbols = ['+','-']
        symbollistleft , symbollistright = [] , []
        symbollist = [symbollistleft,symbollistright]
        for i,j in enumerate(self.seperate()):
            for s,t in enumerate(j):
                if t in symbols:
                    symbollist[i].append(s)
        return symbollist

    def identify(self):
        allist=[]
        for i,symbollists in enumerate(self.seperate()):
            smalllist=[]
            for j in range(len(symbollists)):
                if j==0:
                    minilist=[]
                    minilist.append(self.seperate()[i][j])
                elif j in self.symbolfinder()[i]:
                    if minilist[0]!= '+' and minilist[0]!='-':
                        minilist.insert(0,'+')
                    smalllist.append(minilist)
                    minilist=[]
                    minilist.append(self.seperate()[i][j])
                else:
                    minilist.append(self.seperate()[i][j])

            if minilist[0]!= '+' and minilist[0]!='-':
                minilist.insert(0,'+')
            smalllist.append(minilist)
            allist.append(smalllist)
        return allist

    def simplify(self):
        allist = self.identify()

        leftintegers , rightintegers = [] , []
        leftcoefficents, rightcoefficents = [] , []

        for i,leftright in enumerate(allist):
            for j in leftright:
                coefficent=0
                jwithoutx = []
                #identifing whether it is a coef or int
                #also removes x from coef after idetifing since we know it has an x
                for k in j:
                    if 'x' == k:
                        coefficent=1
                    else:
                        jwithoutx.append(k)
                #accounting for the special case of just writng x which is assumed to be 1x
                if jwithoutx==['-']: jwithoutx=['-','1']
                elif jwithoutx==['+']: jwithoutx=['+','1']

                if coefficent:
                    if i==0:
                        leftcoefficents.append(jwithoutx)
                    else:
                        rightcoefficents.append(jwithoutx)
                else:
                    if i==0:
                        leftintegers.append(j)
                    else:
                        rightintegers.append(j)

        def numbify(bringtoside,leaveside):
            outputlist=[]
            outputnumber=0
            for i in bringtoside:
                outputlist.append(i)
            for i in leaveside:
                reverse=[]
                for j in i:
                    if '+' == j:
                        reverse.append('-')
                    elif '-' == j:
                        reverse.append('+')
                    else:
                        reverse.append(j)
                outputlist.append(reverse)

            for i in range(len(outputlist)):
                outputnumber += int(''.join(outputlist[i]))

            return outputnumber

        global intright, coefleft
        intright = numbify(rightintegers,leftintegers)
        coefleft = numbify(leftcoefficents,rightcoefficents)

        return f'{coefleft} x = {intright}'

    def solve(self):
        return f'x = {intright/coefleft}'

problem = Solve(input())

#print(problem.equation)
#print(problem.equationtidy())
#print(problem.seperate())
#print(problem.symbolfinder())
print(problem.identify())
print(problem.simplify())
print(problem.solve())


import array
from math import sqrt

import numpy
from . import Cell, Row, Column, Box

class Puzzle:
    def __init__(self, size: int = None, grid: numpy.array = None, candidates: array = None):
        if size is None and grid is None:
            raise ValueError('Size or grid must be supplied')

        if size is None:
            size = len(grid)
        if not sqrt(size).is_integer():
            raise ValueError(f'{size} is not a square')
        self.size = size

        if grid is None:
            self.grid = numpy.array(
                [[None for _ in range(size)] for _ in range(size)])
        else:
            if True in (len(row) != size for row in grid):
                raise ValueError('Grid is malformed')
            self.grid = grid

        if candidates is None:
            self.candidates = range(1, self.size + 1)
        else:
            self.candidates = candidates

        self.constraints = [Cell(self.grid, self.candidates),
                            Row(self.grid, self.candidates),
                            Column(self.grid, self.candidates),
                            Box(self.grid, self.candidates)]

    def is_valid(self, column: int, row: int, value: int):
        self.__validate_value(value)

        for constraint in self.constraints:
            if not constraint.is_valid(column, row, value):
                return False

        return True

    def has_value(self, column: int, row: int):
        return not self.value(column, row) is None

    def value(self, column: int, row: int):
        return self.grid[row, column]

    def try_set(self, column: int, row: int, value: int):
        self.__validate_value(value)

        if self.is_valid(column, row, value):
            self.grid[row, column] = value
            return True

        return False

    def set(self, column: int, row: int, value: int):
        if not self.try_set(column, row, value):
            raise ValueError(
                f'{value} is not valid at location ({column},{row})')

    def clear(self, column: int, row: int):
        self.grid[row, column] = None

    def update_from(self, other):
        for row in range(0, self.size):
            for column in range(0, self.size):
                self.grid[column, row] = other.grid[column, row]

    def __validate_value(self, value):
        if not value in self.candidates:
            raise ValueError(f'{value} must be one of {self.candidates}')


import pygame
import time
import random
from pygame.locals import *

# start Py_Game
pygame.init()

# load a music
crash_sound = pygame.mixer.Sound("Crash1.wav")
pygame.mixer.music.load("Action_Sport_Rock_Trailer .mp3")

# init game display size
display_width = 800
display_height = 600

# init colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
persian_green = (0, 166, 147)

car_image = pygame.image.load('redCar.png')
car_width = 45
game_display = pygame.display.set_mode((display_width, display_height))
# make a Caption 2
pygame.display.set_caption('Race Car')
# make a frame per second
clock = pygame.time.Clock()

def game_intro():
    intro = True
    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit_game()
        # game_display.fill(white)
        game_display.blit(pygame.image.load("img.png"), (0, 0))
        large_text = pygame.font.Font('freesansbold.ttf', 90)
        text_surf, text_rect = text_objects("Let's Play Game", large_text, red)
        text_rect.center = ((display_width / 2), (display_height / 5))
        game_display.blit(text_surf, text_rect)

        button("Play", 150, 450, 100, 50, white, persian_green, "play")         # make start button
        button("Quit", 550, 450, 100, 50, red, persian_green, "quit")           # make quit button

        pygame.display.update()

def button(message, x, y, width, height, inactive_color, active_color, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    if x + width > mouse[0] > x and y + height > mouse[1] > y:
        pygame.draw.rect(game_display, active_color, (x, y, width, height))
        if click[0] == 1:
            if action == "play":
                game_loop()
            elif action == "quit":
                quit_game()
    else:
        pygame.draw.rect(game_display, inactive_color, (x, y, width, height))

    small_text = pygame.font.Font("freesansbold.ttf", 20)
    text_surf, text_rect = text_objects(message, small_text, black)
    text_rect.center = ((x + (width / 2)), (y + (height / 2)))
    game_display.blit(text_surf, text_rect)

def quit_game():
    pygame.quit()
    quit()

# display score
def score(count):
    font = pygame.font.SysFont(None, 25)
    text = font.render("Score: " + str(count), True, red)
    game_display.blit(text, (0, 0))

# init stuff
def stuff_rect(x, y, width, height, my_color):
    pygame.draw.rect(game_display, my_color, [x, y, width, height])

# put a car in the middle
def car(x, y):
    game_display.blit(car_image, (x, y))

def text_objects(text, font, txt_color):
    text_surface = font.render(text, True, txt_color)
    text_rect = text_surface.get_rect()
    return text_surface, text_rect

def message_display(text):
    large_text = pygame.font.Font('freesansbold.ttf', 80)
    text_surf, text_rect = text_objects(text, large_text, black)
    text_rect.center = ((display_width/2), (display_height/2))
    game_display.blit(text_surf, text_rect)
    pygame.display.update()

    time.sleep(2)
    game_loop()

def crash():

    # stop music
    pygame.mixer.music.stop()
    pygame.mixer.Sound.play(crash_sound)
    large_text = pygame.font.Font('freesansbold.ttf', 80)
    text_surf, text_rect = text_objects("YOU CRASHED", large_text, white)
    text_rect.center = ((display_width / 2), (display_height / 2))
    game_display.blit(pygame.image.load("crash.jpg"), (0, 20))
    game_display.blit(text_surf, text_rect)
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                quit_game()
        button("Try Again", 150, 450, 100, 50, white, persian_green, "play")  # make start button
        button("Quit", 550, 450, 100, 50, red, persian_green, "quit")  # make quit button
        pygame.display.update()

def game_loop():
    # music load
    pygame.mixer.music.play(-1)
    # init car location
    y = (display_height * 0.8)
    x = (display_width * 0.45)
    # get a car location change
    x_change = 0

    stuff_start_x = random.randrange(0, display_width)
    stuff_start_y = -600
    circle_start_x = random.randrange(0, display_width)
    circle_start_y = random.randrange(500, 1000) * -1
    circle_radius = 25
    stuff_speed = 7
    stuff_width = 100
    stuff_height = 100
    stuff_color = red
    dodged = 0

    game_exit = False
    # get events until quit
    while not game_exit:

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                game_exit = True
                quit_game()
            # get a key to move
            keys = pygame.key.get_pressed()
            if keys[K_a] or keys[K_LEFT] and not keys[K_d]:
                x_change -= 5
            if keys[K_d] or keys[K_RIGHT] and not keys[K_a]:
                x_change += 5
            if event.type == pygame.KEYUP and (event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT):
                x_change = 0
            if event.type == pygame.KEYUP and (event.key == pygame.K_a or event.key == pygame.K_d):
                x_change = 0
            if keys[K_UP]:
                x_change = 0

        x += x_change

        game_display.fill(white)
        # game_display.blit(pygame.image.load("disp.jpg"), (0, 0))

        # x, y, width, height, color
        stuff_rect(stuff_start_x, stuff_start_y, stuff_width, stuff_height, stuff_color)
        if dodged <= 5:
            circle_start_x = display_width
        if dodged > 5:
            pygame.draw.circle(game_display, black, (circle_start_x, circle_start_y), circle_radius)
            if circle_start_y > display_height:
                circle_start_y = 0 - circle_radius
                circle_start_x = random.randrange(0, display_width - 100)
                dodged += 1
                if dodged % 5 == 0:
                    circle_radius += 5
        stuff_start_y += stuff_speed
        circle_start_y += stuff_speed

        car(x, y)

        # Repeat stuff
        if stuff_start_y > display_height:
            stuff_start_y = 0 - stuff_height
            stuff_start_x = random.randrange(0, display_width - 100)
            dodged += 1
            if dodged % 5 == 0:
                stuff_speed += 1
                stuff_width += 5

        # Display player score
        score(dodged)
        stuff_location = stuff_start_x + stuff_width
        if y < stuff_start_y + stuff_height:
            if stuff_start_x < x < stuff_location or stuff_start_x < x + car_width < stuff_location:
                crash()
        circle_location = circle_start_x + circle_radius
        if y < circle_start_y + 25:
            if circle_start_x < x < circle_location or circle_start_x < x + car_width < circle_location:
                crash()

        # crash if impact with wall
        if x > display_width - car_width or x < 0:
            crash()

        pygame.display.update()     # display what happens in underground
        clock.tick(60)

game_intro()
game_loop()
quit_game()


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

__author__ = "Hoàng Văn Khoa"

import os

__data_path__ = os.path.join(os.path.dirname(__file__), "data")

import dongdu_native

def segment(args):
	"""
	Tiến hành tách các từ có trong câu đầu vào
	:param args:
	:return: câu gồm các từ đã được tách
	"""
	if not isinstance(args, str):
		raise TypeError("Input args must be in str!")
	return dongdu_native.segment(args)

def hello(args):
	dongdu_native.hello(args)


"""
    Goblin monster sub-class of parents Monster and NPC.
"""

from monster import Monster
from npc import NPC

class Goblin(Monster, NPC):

    NAME = 'Goblin'

    STATS = {
        'STR': 10,
        'AGI': 7,
        'INT': 4,
        'CHA': 0,
        'LCK': 5,
        'max_hp': 12,
        'max_ap': 0,
        'level': 6,
        'exp': 10,
        'gold': 15,
        }


# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.shortcuts import render, HttpResponse
from django.shortcuts import get_object_or_404

from django.views.generic import CreateView, ListView, UpdateView
from django.views.generic.edit import ModelFormMixin, FormMixin, DeleteView, UpdateView
from django.core.urlresolvers import reverse, reverse_lazy
from vsa.genericviews import *
from .models import *
from .forms import *

from .models import User_Host
from .tasks import *
from django.contrib.auth.decorators import login_required
from .forms import *
from vsa.genericviews import GenericUpdateView

# Create your views here.

def user_add_perm(request):
    form = PermForm()
    if request.method == "POST":
        form = PermForm(request)
        return render(request, 'user_add_perm.html', locals())
    return render(request, 'user_add_perm.html', locals())

@login_required()
def operate_user_perm(request, pk):
    perm = get_object_or_404(User_Host, pk=pk)
    username = perm.user.username
    for host in list_user_hosts(perm_id=perm.id):
        add_perm.delay(username=username, ip=host)
    return HttpResponse("<script> alert('" + u'主机授权中!' + "');window.location.href='/permission/perm'</script>")

@login_required()
def user_perm_info(request, pk):
    user_perm = get_object_or_404(User_Host, pk=pk)
    return render(request, 'users_perm.html', locals())

@login_required()
def refresh_user_perm(request, pk):
    perm = get_object_or_404(User_Host, pk=pk)
    x = refresh_key.delay(perm.id)
    return HttpResponse("<script> alert('" + u'授权刷新中!' + "');window.location.href='/permission/perm'</script>")

@login_required()
def refresh_host_key(request, pk):
    perm = get_object_or_404(User_Host, pk=pk)
    username = perm.user.username
    for host in list_user_hosts(perm_id=perm.id):
        SyncKey.delay(username=username, ip=host)
    return HttpResponse("<script> alert('" + u'授权刷新中!' + "');window.location.href='/permission/perm'</script>")

class userpermupdateview(GenericUpdateView):
    template_name = 'userpermupdate.html'

    def post(self, request, *args, **kwargs):
        perm = request.POST.get()

@login_required()
def multadduserperm(request):
    '''
    多用户，多机器同时授权
    :param request:
    :return:
    '''
    form = MuitiAddPerm()
    if request.method == 'POST':
        form = MuitiAddPerm(request.POST)
        if form.is_valid():
            hostlist = Host.objects.filter(pk__in=request.POST.getlist('hosts'))
            for userid in request.POST.getlist('userlist'):
                perm, status = User_Host.objects.get_or_create(user_id=userid)
                for h in hostlist:
                    perm.host.add(h)
                    add_perm.delay(username=perm.user.username, ip=h.ip)
            return HttpResponse("<script> alert('" + u'批量授权中!' + "');window.location.href='/permission/perm'</script>")
    return render(request, 'multadduserperm.html', locals())

class UserPermIndexView(ListView):
    model = User
    template_name = 'userpermindex.html'

    # def get_context_data(self, **kwargs):
    #     context = super(UserPermIndexView,self).get_context_data(**kwargs)
    #     return  context

class UserPermListView(ListView):
    model = UserPerm
    template_name = 'userpermlist.html'

    def get_context_data(self, **kwargs):
        context = super(UserPermListView, self).get_context_data(**kwargs)
        userid = self.kwargs.get('userid', None)
        if userid:
            self.user = User.objects.get(id=userid)
            context['user'] = self.user
        return context

    def get_queryset(self):
        user_id = self.kwargs.get('userid', None)
        if user_id:
            queryset = self.model.objects.filter(user_id=self.kwargs['userid'])
        else:
            queryset = self.model.objects.all()
        return queryset

def remote_add_perm(request, pk):
    perm = get_object_or_404(UserPerm, pk=pk)
    add_perm.delay(perm.user.username, perm.host.ip)
    return HttpResponse("<script> alert('" + u'授权中!' + "');window.location.href=''</script>")

class PermCreateView(SuperuserRequiredMixin, CreateView):
    # model = Records
    form_class = UserPermForm
    template_name = 'userpermform.html'
    success_url = reverse_lazy('userpermlist')

    def get_initial(self):
        userid = self.kwargs.get('userid', None)
        if userid:
            self.user = get_object_or_404(UserPerm, pk=userid)
            return {'user': self.user}

    def get_context_data(self, **kwargs):
        context = super(PermCreateView, self).get_context_data(**kwargs)
        context['zone'] = self.user
        context['success_url'] = reverse('userpermlist', kwargs={'pk': self.user.id})

        return context

    def get_success_url(self):
        return reverse_lazy('userpermlist', kwargs={'pk': self.user.id})

@login_required()
def add_permission(request):
    '''
    多用户，多机器同时授权
    :param request:
    :return:
    '''
    form = UserPermform1()
    if request.method == 'POST':
        form = UserPermform1(request.POST)
        if form.is_valid():
            hostlist = virtualhost.objects.filter(pk__in=request.POST.getlist('hosts'))
            for userid in request.POST.getlist('userlist'):
                for h in hostlist:
                    perm, status = UserPerm.objects.get_or_create(user_id=userid, host=h)
                    add_perm.delay(username=perm.user.username, ip=h.ip)

            return HttpResponse("<script> alert('" + '授权中!' + "');window.location.href='/permission/index'</script>")
    return render(request, 'multadduserperm.html', locals())

def multi_add_permission(request):
    pass


import detectron2
from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
from detectron2.data import MetadataCatalog

import cv2
import numpy as np

import pickle

BBOX_SCORE_THRESH = .5

class VehicleDetectorDetectron:
  wantsRGB = False
  def __init__(self):
    cfg = get_cfg()

    #cfg.MODEL.DEVICE = 'cpu'

    # See https://github.com/facebookresearch/detectron2/blob/master/MODEL_ZOO.md
    cfg.merge_from_file(model_zoo.get_config_file("COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml"))
    cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url("COCO-InstanceSegmentation/mask_rcnn_R_101_FPN_3x.yaml")
    self.predictor = DefaultPredictor(cfg)

  # Returns torch.tensor of bounding boxes for frame
  def getFeatures(self, frame):
    vehicleFeatures = self.predictor(frame)
    # See https://detectron2.readthedocs.io/tutorials/models.html#model-output-format
    instances = vehicleFeatures['instances']

    keepScores = instances.scores > BBOX_SCORE_THRESH

    boxes = instances.pred_boxes[keepScores]
    scores = instances.scores[keepScores]
    classes = instances.pred_classes[keepScores]
    masks = instances.pred_masks[keepScores]

    # envelopes = self._getEnvelopes(masks)
    envelopes = []

    boxes = boxes.tensor.cpu().numpy()
    boxes = [boxes[i] for i in range(len(boxes))]
    classes = classes.cpu().numpy()
    classes = [classes[i] for i in range(len(classes))]
    return boxes, envelopes, scores

  def _getEnvelopes(self, masks):
    envelopes = []
    for mask in masks:
      contour, hierarchy = cv2.findContours(np.uint8(mask.cpu().numpy()), cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
      envelopes.append(contour)
    return envelopes


import unittest

try:
    from mathml import mathdom
except ImportError:
    mathdom = None

try:
    from mathml import lmathdom
except ImportError:
    lmathdom = None

def mathdom_test(function, module):
    if module is None:
        return None
    else:
        def new_function(self):
            function(self, module, module.MathDOM())
        new_function.__name__ = function.__name__
        new_function.__doc__  = function.__doc__
        new_function.__dict__ = function.__dict__
        return new_function

def for_mathdom(function):
    return mathdom_test(function, mathdom)

def for_lmathdom(function):
    return mathdom_test(function, lmathdom)

class MathdomTestCase(unittest.TestCase):
    @for_mathdom
    def test_math(self, mathdom, doc):
        self.assertEquals( doc.firstChild.localName,
                           'math' )
    @for_lmathdom
    def test_lmath(self, lmathdom, doc):
        self.assertEquals( doc.getroot().localName,
                           'math' )

    @for_mathdom
    def test_create_constant(self, mathdom, doc):
        c = doc.createConstant(3)
        self.assertEquals(c.serialize('infix'),
                          '3')
    @for_lmathdom
    def test_lcreate_constant(self, lmathdom, doc):
        c = doc.createConstant(3)
        self.assertEquals(c.serialize('infix'),
                          '3')

    @for_mathdom
    def test_constant(self, mathdom, doc):
        c = mathdom.Constant(doc, 3)
        self.assertEquals(doc.serialize('infix'),
                          '3')
    @for_lmathdom
    def test_lconstant(self, lmathdom, doc):
        c = lmathdom.Constant(doc, 3)
        self.assertEquals(doc.serialize('infix'),
                          '3')

    @for_mathdom
    def test_create_identifier(self, mathdom, doc):
        i = doc.createIdentifier('bla')
        self.assertEquals(i.serialize('infix'),
                          'bla')
    @for_lmathdom
    def test_lcreate_identifier(self, lmathdom, doc):
        i = doc.createIdentifier('bla')
        self.assertEquals(i.serialize('infix'),
                          'bla')

    @for_mathdom
    def test_identifier(self, mathdom, doc):
        i = mathdom.Identifier(doc, 'bla')
        self.assertEquals(doc.serialize('infix'),
                          'bla')
    @for_lmathdom
    def test_lconstant(self, lmathdom, doc):
        i = lmathdom.Identifier(doc, 'bla')
        self.assertEquals(doc.serialize('infix'),
                          'bla')

    @for_mathdom
    def test_create_apply(self, mathdom, doc):
        c = map(doc.createConstant, (1,2,3))
        a = doc.createApply('plus', c)
        self.assertEquals(a.serialize('infix'),
                          '1 + 2 + 3')
    @for_lmathdom
    def test_lcreate_apply(self, lmathdom, doc):
        c = map(doc.createConstant, (1,2,3))
        a = doc.createApply('plus', c)
        self.assertEquals(a.serialize('infix'),
                          '1 + 2 + 3')

    @for_mathdom
    def test_apply(self, mathdom, doc):
        c = map(doc.createConstant, (1,2,3))
        a = mathdom.Apply(doc, 'plus', c)
        self.assertEquals(doc.serialize('infix'),
                          '1 + 2 + 3')
    @for_lmathdom
    def test_lapply(self, lmathdom, doc):
        c = map(doc.createConstant, (1,2,3))
        a = lmathdom.Apply(doc, 'plus', c)
        self.assertEquals(doc.serialize('infix'),
                          '1 + 2 + 3')

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


import networkx as nx
from matplotlib import pyplot as plt
def players_to_graph(evaluations):
    g = nx.Graph()
    agents = []
    for roomIndex, room in enumerate(evaluations):
        g.add_node((roomIndex, 'r'), bipartite=1)
        agents.append((roomIndex, 'r'))

    for playerIndex, player in enumerate(evaluations[0]):
        g.add_node((playerIndex, 'p'),  bipartite=0)

    for roomIndex, room in enumerate(evaluations):
        for playerIndex, playerValue in enumerate(room):
            g.add_edge((playerIndex, 'p'), (roomIndex, 'r'), weight=playerValue)

    return g, agents

def draw_graph(g, agents):
    pos1 = nx.bipartite_layout(g, agents)
    edge_labels = nx.get_edge_attributes(g, "weight")
    nx.draw_networkx_edge_labels(g, pos=pos1,edge_labels=edge_labels, label_pos=0.2)
    nx.draw_networkx(g, pos=pos1)
    plt.show()

def powerset(iterable):
    from itertools import chain, combinations
    s = list(iterable)
    return chain.from_iterable(combinations(s, r) for r in range((len(s)+1)))

def brute_force_max_matching(g: nx.Graph(), agents):
    # find a max weight matching and sum the weight of this max weight matching
    res = nx.max_weight_matching(g)
    sumTarget = 0
    for edge in res:
        data = g.get_edge_data(edge[0], edge[1])
        sumTarget += data['weight']
    results = []

    # brute force over all the matchings, if the sum of weight equalts to sumTarget, append the result to a list
    for i in powerset(g.edges()):
        if len(i) != len(agents) or not nx.is_matching(g, i):
            continue
        sum = 0
        for edge in i:
            data = g.get_edge_data(edge[0], edge[1])
            sum += data['weight']
        if sum == sumTarget:
            results.append(i)
    return results

v = [[35,40,25],
[35,60,40],
[25,40,20]]

g, agents = players_to_graph(v)
#draw_graph(g, agents)

results = brute_force_max_matching(g, agents)
print(results)
z = 0
maxMin = -1
for i in results:
    currMin = 999999
    for edge in i:
        currWeight = g.get_edge_data(edge[0], edge[1])['weight']
        if currWeight < currMin:
            currMin = currWeight
    if currMin > maxMin:
        maxMin = currMin
        z = i
print(z)


#define your function here:
from bs4 import BeautifulSoup

def ismissing(tree):
    # 将tree转换为BeautifulSoup对象
    soup = BeautifulSoup(str(tree), 'html.parser')
    # 查找所有的元素
    elems = soup.find_all()

    # 创建一个和elems长度相同的逻辑数组
    tf = [1] * len(elems)

    # 检查每个元素是否引用了HTML树，若是则对对应的tf数组进行置0操作
    for i in range(len(elems)):
        if elems[i].parent is None:
            tf[i] = 0

    return tf


import sys
from preprocess_data import Question

que = Question()
# 处理问题的方法
def dealquestion(question):
    # 查询知识图谱
    answer=que.question_process(question)
    # answer=12
    return answer

if __name__ == '__main__':
    question = input("请输入问题:")
    print("接收到的问题:", question)
    print("开始寻找答案!")

    answer = dealquestion(question)

    print("得到的答案是：", answer)
    if len(str(answer).strip()) == 0:
        answer = "我也还不知道呢！"
    print("答案已返回!")


import numpy as np
import torch
from typing import Optional, Dict, Iterable

def torch_one_hot(target: torch.Tensor, num_classes: Optional[int] = None) -> torch.Tensor:
    """source: https://github.com/PhoenixDL/rising. Computes one-hot encoding of input tensor.

    Args:
        target (torch.Tensor): tensor to be converted
        num_classes (Optional[int], optional): number of classes. If None, the maximum value of target is used.

    Returns:
        torch.Tensor: one-hot encoded tensor of the target
    """
    if num_classes is None:
        num_classes = int(target.max().detach().item() + 1)
    dtype, device = target.dtype, target.device
    target_onehot = torch.zeros(*target.shape, num_classes, dtype=dtype, device=device)
    return target_onehot.scatter_(1, target.unsqueeze_(1), 1.0)

def one_hot_batch(target: torch.Tensor,
                  num_classes: Optional[int] = None,
                  dtype: Optional[torch.dtype] = None) -> torch.Tensor:
    """Source: https://github.com/PhoenixDL/rising
    Computes one hot for the input tensor (assumed to a be batch and thus saved
    into first dimension -> input should only have one channel).

    Args:
        target (torch.Tensor): long tensor to be converted.
        num_classes (Optional[int], optional): number of classes. If None, the maximum of target is used.
        dtype (Optional[torch.dtype], optional): optionally changes the dtype of the onehot encoding.

    Raises:
        TypeError: when the input tensor is not of long type.
    Returns:
        torch.Tensor: one hot encoded tensor
    """
    if target.dtype != torch.long:
        raise TypeError(
            f"Target tensor needs to be of type torch.long, found {target.dtype}")

    if target.ndim in [0, 1]:
        return torch_one_hot(target, num_classes)
    else:
        if num_classes is None:
            num_classes = int(target.max().detach().item() + 1)
        _dtype, device, shape = target.dtype, target.device, target.shape
        if dtype is None:
            dtype = _dtype
        target_onehot = torch.zeros(shape[0], num_classes, *shape[2:],
                                    dtype=dtype, device=device)
        return target_onehot.scatter_(1, target, 1.0)

def reduce(tensor: torch.Tensor, reduction: str) -> torch.Tensor:
    """Reduces the given tensor using a specific criterion.

    Args:
        tensor (torch.Tensor): input tensor
        reduction (str): string with fixed values [elementwise_mean, none, sum]

    Raises:
        ValueError: when the reduction is not supported

    Returns:
        torch.Tensor: reduced tensor, or the tensor itself
    """
    if reduction in ("elementwise_mean", "mean"):
        return torch.mean(tensor)
    if reduction == 'sum':
        return torch.sum(tensor)
    if reduction is None or reduction == 'none':
        return tensor
    raise ValueError('Reduction parameter unknown.')

def mask_to_rgb(mask: np.ndarray, palette: Dict[int, Iterable]) -> np.ndarray:
    """Given an input batch, or single picture with dimensions [B, H, W] or [H, W], the utility generates
    an equivalent [B, H, W, 3] or [H, W, 3] array corresponding to an RGB version.
    The conversion uses the given palette, which should be provided as simple dictionary of indices and tuples, lists
    or arrays indicating a single RGB color. (e.g. {0: (255, 255, 255)})

    Args:
        mask (np.ndarray): input mask of indices. Each index should be present in the palette
        palette (Dict[int, Iterable]): dictionary of pairs <index - color>, where colors can be provided in RGB tuple format

    Returns:
        np.ndarray: tensor containing the RGB version of the input index tensor
    """
    lut = np.zeros((256, 3), dtype=np.uint8)
    for index, color in palette.items():
        lut[index] = np.array(color, dtype=np.uint8)
    return lut[mask]


## 함수
def isStackFull():
    global SIZE, stack, top
    if (top == SIZE-1):
        return True
    else:
        return False

def isStackEmpty():
    global SIZE,stack,top
    if(top<=-1):
        return True
    else:
        return False

def push(data):
    global SIZE, stack,top
    if isStackFull():
        print('스택 꽉 찼음')
        return
    top+=1
    stack[top]=data
    return

def pop():
    global SIZE,stack,top
    if isStackEmpty():
        print('스택 비었음')
        return None
    data=stack[top]
    stack[top]=None
    top-=1
    return data

def peek(): # pop하기 전 pop하면 나올 데이터 확인
    global SIZE,stack,top
    if isStackEmpty():
        print('스택 비었음')
        return None
    return stack[top]

## 변수
SIZE=5  # 상수
stack=[None for _ in range(SIZE)]# 오버플로우(넘치다) 주의!
top=-1

## 메인
print('바닥',stack)
push('커피')
push('녹차')
# push('꿀물')
# push('콜라')
# push('환타')
# print('바닥',stack)
# push('게토레이')
print('바닥',stack)

returnData=pop()
print('pop---> ',returnData)
print('다음예정 ==>',peek())
returnData=pop()
print('pop---> ',returnData)
returnData=pop()
print('바닥',stack)
print('pop---> ',returnData)


n = int(input())
arr = list(map(int, input().split()))

arr.sort()
# group = 0
# for i in arr:
#     print(n , i)
#     if n - i > 0:
#         n -= i
#         group += 1
#     else:
#         break;
#
# print(group)

result = 0
count = 0

for i in arr:

    count += 1
    print(count, i)
    if count >= i:
        print("add")
        result += 1
        count = 0
print(result)


#!/usr/bin/env python3

import os, sys
import shutil
import signal
from datetime import datetime
#add other imports as needed by your script
# The purpose of this script is to give you simple functions for locating an executable program in common locations in the Linux path

# Simple shell
# COMMANDS          ERRORS CHECKED
# 1. info XX         - check file/dir exists
# 2. files
# ... omitted for simplicity
# 8. Default is to run the program

# Here the path is hardcoded, but you can easily optionally get your PATH environ variable
# by using: path = os.environ['PATH'] and then splitting based on ':' such as the_path = path.split(':')
THE_PATH = ["/bin/", "/usr/bin/", "/usr/local/bin/", "./"]

# ========================
#    Run command
#    Run an executable somewhere on the path
#    Any number of arguments
# ========================
def runCmd(fields):
    global PID, THE_PATH

    cmd = fields[0]
    count = 0
    args = []
    while count < len(fields):
        args.append(fields[count])
        count += 1

    execname = add_path(cmd, THE_PATH)

    # run the executable
    if not execname:
        print ("Executable file", cmd, "not found")
        return
    else:
      # execute the command
      print(execname)
#signal handler has to be in the parent
    PID = os.fork()
    # Wait if we're in parent, execute command if in child.
    if PID:
        os.waitpid(PID, 0)
    else:
    # execv executes a new program, replacing the current process; on success, it does not return.
    # On Linux systems, the new executable is loaded into the current process, and will have the same process id as the caller.
        os.execv(execname, args)

# ========================
#    Constructs the full path used to run the external command
#    Checks to see if the file is executable. Returns False on failure.
# ========================
def add_path(cmd, path):
    if cmd[0] not in ['#!/', '#!.']:
        for d in path:
            execname = d + cmd
            if os.path.isfile(execname) and os.access(execname, os.X_OK):
                return execname
        return False
    else:
        return cmd

# ========================
#    files command
#    List file and directory names
#    No arguments
# ========================
def filesCmd(fields):
    target = os.path.realpath(os.path.expanduser(fields[1]))
    print(target)
    if checkArgs(fields, 1):
        for filename in os.listdir(target):
            if os.path.isdir(os.path.abspath(filename)):
                print("dir:", filename)
            else:
                print("file:", filename)

# ========================
#  info command
#     List file information
#     1 argument: file name
# ========================
def infoCmd(fields):
    arg = 1
    if len(fields) > 1:
        while arg < len(fields):
            name = fields[arg]
            path = os.path.realpath(os.path.expanduser(name))

            print("\npath  | ", path)
            if os.path.islink(name):
                print("type  | link -> " + os.path.basename(os.readlink(name)))
            elif os.path.isfile(name):
                print("type  | file")
            elif os.path.isdir(name):
                print("type  | directory")
            else:
                print("type  | other")
            if not os.path.exists(path):
                print("The path above does not exist.")
                arg = arg + 1
                continue
            print("owner | ", Path(path).owner())
            if os.path.isfile(name):
                print("bytes | ", os.path.getsize(name))
            print("executable   |", os.access(path, os.X_OK))
            print("last_changed | ", datetime.fromtimestamp(os.path.getctime(path)).strftime('%b %d %Y %H:%M:%S'))

            arg = arg + 1
    else:
        print("Incorrect number of arguments for command:", fields[0])

# ========================
#  delete command
#     Delete file
#     1 argument: file name
# ========================
def del_cmd(fields):
    path = os.path.realpath(os.path.expanduser(fields[1]))
    if checkArgs(fields, 1):
        os.remove(path)
        if not os.path.exists(path):
            print("The file was deleted.")

# ========================
#  copy command
#     Copy and paste file
#     2 argument: file name, new file name
# ========================
def copy_cmd(fields):
    src = os.path.realpath(os.path.expanduser(fields[1]))
    dst = os.path.realpath(os.path.expanduser(fields[2]))

    if checkArgs(fields, 2):
        if os.path.exists((dst)) & os.path.isfile(dst):
            ans = input("This path already exists. Do you want to overwrite it with your copy? (Y/n)\n")
            while (not ans == "Y") and (not ans == "n"):
                ans = input("This path already exists. Do you want to overwrite it with your copy? (Y/n)\n")

            if ans == "Y":
                result = shutil.copy2(src, dst)
                print("Your file is at ", result + ".")
            else:
                print("Your file wasn't copied.")
        else:
            result = shutil.copy2(src, dst)
            print("Your file is at ", result + ".")

# ========================
#  where command
#     Show current directory
#     0 argument
#=========================
def where_cmd(fields):
    if checkArgs(fields, 0):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        print(dir_path)

# ========================
#  down command
#     Move down to a directory
#     1 argument: directory name
#=========================
def down_cmd(fields):
    if checkArgs(fields, 1):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        dst = dir_path + "/" + fields[1]

        os.chdir(dst)
        print("Directory changed.")

# ========================
#  up command
#     Move up to a directory
#     0 argument
#=========================
def up_cmd(fields, current):
    if checkArgs(fields, 0):
        dst = os.path.dirname(os.path.realpath(current))

        os.chdir(dst)
        print("Directory changed.")

        return current

# ----------------------
# Other functions
# ----------------------
def checkArgs(fields, num):
    numArgs = len(fields) - 1
    if numArgs == num:
        return True
    if numArgs > num:
        unexpected = ""
        for arg in fields[num+1:]:
            unexpected = unexpected  + " " + arg
        print("Unexpected argument" + unexpected + " for command:", fields[0])
    else:
        print("Missing argument for command:", fields[0])

    return False

def sigint_handler(signum, frame):
    os.kill(PID, signal.SIGKILL)
    print(" Process:", str(PID) + " was killed.")

# ----------------------------------------------------------------------------------------------------------------------
signal.signal(signal.SIGINT, sigint_handler)

while True:
    try:

        line = input("PShell>")
        fields = line.split()

        if fields[0] == "files":
            filesCmd(fields)
        elif fields[0] == "info":
            infoCmd(fields)
        elif fields[0] == "delete":
            del_cmd(fields)
        elif fields[0] == "copy":
            copy_cmd(fields)
        elif fields[0] == "where":
            where_cmd(fields)
        elif fields[0] == "down":
            down_cmd(fields)
        elif fields[0] == "up":
            current = os.getcwd()
            if not current == "/":
                current = up_cmd(fields, current)
            else:
                print("No higher directory.")
        elif fields[0] == "finish" or fields[0] == "x":
            break
        else:
            runCmd(fields)
    except FileExistsError:
        print("File already exists.")
    except FileNotFoundError:
        print("The path above does not exist.")
    except IndexError:
        print("Incorrect number of arguments for command:", fields[0])
    except IsADirectoryError:
        print("This is a directory.")
    except NotADirectoryError:
        print("This isn't a directory.")


#!/usr/bin/env python3

import sys, os, urllib

from bs4 import BeautifulSoup

url             = sys.argv[1]
directory       = sys.argv[2]

content         = urllib.request.urlopen(url).read()
soup            = BeautifulSoup(content, 'html.parser')

table = soup.find('table', attrs={'class':'contenttable'})

for table_entry in table.tbody.find_all('tr'):
    for a in table_entry.td.find_all('a'):

        link = a['href']
        filename = directory + '/' + os.path.basename(link)

        urllib.request.urlretrieve(link, filename)


# Do not delete any line
# Please adjust filtering criterion with use of example values
# If criterion should not be taken into consideration in scraping process please assign None to it
#  as in the example at the end of this file

from datetime import datetime
topics_date_from = None
topics_date_to = None
posts_date_from = None
posts_date_to = None
topic_authors = None
post_authors = None
topic_keywords = None
post_keywords = None

# EXAMPLE VALUES
# topics_date_from = datetime(2002, 1, 1)
# topics_date_to = datetime(2017, 1, 1)
# posts_date_from = datetime(2014, 1, 1)
# posts_date_to = datetime(2015, 1, 1)
# topic_authors = ["Marek", "Darek"]
# post_authors = ["Andrzej", "Piotr", "Marek"]
# topic_keywords = ["olej", "cylinder", "uszczelka", "pompa"]
# post_keywords = ["olej", "cylinder", "uszczelka", "pompa"]

# NO FILTERING CONFIG
# topics_date_from = datetime(2002, 1, 1)
# topics_date_to = datetime(2017, 1, 1)
# posts_date_from = datetime(2014, 1, 1)
# posts_date_to = datetime(2015, 1, 1)
# topic_authors = ["Marek", "Darek"]
# post_authors = ["Andrzej", "Piotr", "Marek"]
# topic_keywords = ["olej", "cylinder", "uszczelka", "pompa"]
# post_keywords = ["olej", "cylinder", "uszczelka", "pompa"]


from datetime import date
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

data = date.today()
meses = ['janeiro', 'fevereiro', 'março', 'abril', 'maio', 'junho', 'julho', 'agosto', 'setembro', 'outubro',
         'novembro', 'dezembro']
ano, mes, dia = str(data).split("-")
mes = meses[int(mes) - 1]

for i in meses:
    exec(f"estoque{i}=open(f\"C:/Users/User/Desktop/estoque/estoque de {i}.txt\",\"a\")")
    exec(f"vendas{i}=open(f\"C:/Users/User/Desktop/estoque/vendas de {i}.txt\",\"a\")")

janela = Tk()

janela.title("mercado")

janela.geometry('350x200')

data2 = Label(janela, text=f"{dia} {mes} {ano}")
data2.grid(column=0, row=0)

lbl = Label(janela, text="-MERCADO-")
lbl.grid(column=0, row=1)

estoque = {}
fim = False
produtos = []

def salvarestoque(nome, qtde, preco):
    global estoque
    global janela
    estoque[nome.get()] = [qtde.get(), preco.get()]
    for i in meses:
        if i == mes:
            return exec(rf'estoque{i}.write(f"produto:{nome.get()}\npreço: R${preco.get()}\nestoque:{qtde.get()}\n\n")')

def defestoque():
    global produtos
    global estoque
    global janela
    estoque1 = Tk()

    estoque1.title(" ADD estoque")

    estoque1.geometry('350x200')

    data2 = Label(estoque1, text=f"{dia} {mes} {ano}", )
    data2.grid(column=0, row=1)

    addestoquejanela = Label(estoque1, text="ADD Estoque")
    addestoquejanela.grid(column=1, row=1)

    produto = Label(estoque1, text="PRODUTO")
    produto.grid(column=0, row=3, sticky=W, padx=5, pady=5)

    produtoentry = Entry(estoque1)
    produtoentry.grid(column=1, row=3, sticky=E, padx=5, pady=5)

    produtos.append(produtoentry.get())

    quantidade = Label(estoque1, text="QUANTIDADE")
    quantidade.grid(column=0, row=4, sticky=E, padx=5, pady=5)
    quantidadeentry = Entry(estoque1)
    quantidadeentry.grid(column=1, row=4, sticky=E, padx=5, pady=5)

    preco = Label(estoque1, text="PREÇO")
    preco.grid(column=0, row=5, sticky=E, padx=5, pady=5)
    precoentry = Entry(estoque1)
    precoentry.grid(column=1, row=5, sticky=E, padx=5, pady=5)

    blank1 = Label(estoque1, text="")
    blank1.grid(column=0, row=6)

    salvar = Button(estoque1, text="Salvar",
                    command=lambda: salvarestoque(produtoentry, precoentry, quantidadeentry))

    salvar.grid(column=0, row=7)

    estoque1.mainloop()

btn_estoque = Button(janela, text="ADD Estoque",command=defestoque)
btn_estoque.grid(column=0, row=2)

btn_vendas = Button(janela, text="Vender", width=10, height=1)
btn_vendas.grid(column=0, row=3)

btn_verestoque = Button(janela, text="Ver estoque", width=10, height=1)
btn_verestoque.grid(column=0, row=4)

btn_vervendas = Button(janela, text="Ver vendas", width=10, height=1)
btn_vervendas.grid(column=0, row=5)

btn_fechar = Button(janela, text="fechar", width=10, height=1, command=lambda: janela.quit())
btn_fechar.grid(column=0, row=6)

janela.mainloop()


import time
import traceback
from typing import TYPE_CHECKING

import cherrypy
from marshmallow import ValidationError

from tortuga.node.manager import NodeStoreManager, NodeStatusStoreManager
from tortuga.web_service.auth.decorators import authentication_required
from .base import Controller, HttpError, HttpNotFoundError

if TYPE_CHECKING:
    from tortuga.node.types import Node

class NodeController(Controller):
    """
    Node web service controller class.

    """
    name = 'nodes'
    type_store = NodeStoreManager.get()
    methods = ['GET', 'PUT']

class NodeStatusController(Controller):
    name = 'node-status'
    type_store = NodeStatusStoreManager.get()
    methods = ['GET', 'PUT']

    def marshall(self, obj: 'Node') -> dict:
        schema_class = self.type_store.status_type_class.schema_class
        marshalled = schema_class().dump(obj)
        return marshalled.data

    def unmarshall(self, obj_dict: dict) -> 'Node':
        """
        Unmarshalls an obj dict into an obj class instance.
        We override the base class unmarshalling to add validation, which is
        not presently compatible with several schemas.
        """
        schema_class = self.type_store.type_class.get_schema_class()
        unmarshalled = schema_class().load(obj_dict)
        if unmarshalled.errors:
            raise ValidationError(unmarshalled.errors)
        return self.type_store.type_class(**unmarshalled.data)

    @authentication_required()
    @cherrypy.tools.json_in()
    @cherrypy.tools.json_out()
    def update(self, obj_id: str) -> dict:
        try:
            # Get full Node object
            obj_current = self.type_store.get(obj_id)
            if not obj_current:
                raise HttpNotFoundError('Not found: {}'.format(obj_id))

            # Convert request to Node object (will be incomplete)
            obj = self.unmarshall(cherrypy.request.json)

            # NOTE: we don't check that the object IDs match since the
            # user may be doing the update by name and would not provide
            # the ID in the data.

            # Update the current object with the state from the request;
            # if state is not provided, keep the current state
            obj_current.state = obj.state or obj_current.state
            obj_current.last_update = time.strftime(
                '%Y-%m-%d %H:%M:%S',
                time.gmtime(time.time())
            )
            obj = self.type_store.save(obj_current)
            response = self.marshall(obj)
        except HttpError as ex:
            response = self.error_response(str(ex), http_status=ex.status_code)
        except Exception as ex:
            self._logger.error(traceback.format_exc())
            response = self.error_response(str(ex))
        return self.format_response(response)


import numpy as np
import scipy.optimize
from scipy.special import erf
import matplotlib.pyplot as plt
from scipy.signal import find_peaks, peak_widths

# This file contains several fit routines and functions

def Linear(x, M, N):
    # Linear function
    # M: slope
    # N: intercept
    return M * x + N

def Gaussian(x, A, MU, SIGMA):
    # Gaussian function
    # A: amplitude
    # MU: mean
    # SIGMA: standard deviation
    return A * np.exp(-(x-MU)**2 / (2*SIGMA**2))

def SkewedGaussian(X,A,MU,SIGMA, GAMMA):
    return (A / (np.sqrt(2*np.pi) * SIGMA)) * np.exp(-(X-MU)**2 / (2*SIGMA**2)) * (1+erf((GAMMA*(X-MU)) / (SIGMA*np.sqrt(2))))

def Linear_fit(x,y, plot=False):
    x = np.array(x)
    y = np.array(y)
    init = [(y[2]-y[1]) / (x[2]-x[1]), 0]                                 # initial guess of the parameters
    fit = scipy.optimize.curve_fit(Linear, x, y, init)                    # fit
    opt_param = fit[0]                                                    # optimal parameters that fit the data
    opt_param_cov = fit[1]                                                # matrix of covariance
    opt_param_error = np.sqrt(np.diag(opt_param_cov))                     # errors are in the diagonal of the matrix
    M = opt_param[0]                                                      # slope of the fit
    N = opt_param[1]                                                      # intercept of the fit
    delta_M = opt_param_error[0]                                          # error of the slope
    delta_N = opt_param_error[1]                                          # error of the intercept
    residuals = y - Linear(x, M, N)                                       # calculate residuals
    ss_res = np.sum(residuals ** 2)                                       # sum of the squared residuals
    ss_tot = np.sum((y - np.mean(y)) ** 2)                                # total sum of squares
    r_squared = 1 - (ss_res / ss_tot)                                     # r^2 (goodness of fit)
    values = {'slope': M, 'delta_slope': delta_M,                         # the fit is returned in a dictionary
              'intercept': N, 'delta_intercept': delta_N,
              'r_squared': r_squared
              }
    if plot:                                                              # plots the regression line and data
        new_x = np.linspace(x[0], x[-1])                                  # x for the regression line
        fig = plt.figure(1)
        plt.plot(x, y, "kx", zorder=1)
        plt.plot(new_x, Linear(new_x, values.get("slope"), values.get("intercept")), "r--", zorder=0)
        plt.xlabel("x")
        plt.ylabel("y")
        plt.title("Calibration")
        M = values.get("slope")
        M_err = values.get("delta_slope")
        N = values.get("intercept")
        N_err = values.get("delta_intercept")
        r_2 = values.get("r_squared")
        text = "m = " + "%.3f" % M + " $\pm$ " + "%.3f" % M_err + "\n" + "n = " + "%.3f" % N + " $\pm$ " + "%.3f" % N_err + "\n" + "$r^2$ = " + "%.4f" % r_2
        plt.text(0.15, 0.83, text, transform=fig.transFigure, bbox=dict(facecolor="white"))
        plt.tight_layout()
        plt.show()
    return values

def Gaussian_fit(x,y):
    init = [max(y), x[np.argmax(y)], (x[1] - x[0]) * 5]                     # initial guess of the parameters
    fit = scipy.optimize.curve_fit(Gaussian, x, y, init)                    # fit
    opt_param = fit[0]                                                      # optimal parameters that fit the data
    opt_param_cov = fit[1]                                                  # matrix of covariance
    opt_param_error = np.sqrt(np.diag(opt_param_cov))                       # errors are in the diagonal of the matrix
    A = opt_param[0]                                                        # amplitude of the fit
    MU = opt_param[1]                                                       # mean of the fit
    SIGMA = abs(opt_param[2])                                               # std dev of the fit (abs value)
    delta_A = opt_param_error[0]                                            # error of the amplitude
    delta_MU = opt_param_error[1]                                           # error of the mean
    delta_SIGMA = opt_param_error[2]                                        # error of the std dev
    FWHM = 2 * SIGMA * np.sqrt(2 * np.log(2))                               # Full Width at Half Maximum
    delta_FWHM = 2 * np.sqrt(2 * np.log(2)) * delta_SIGMA                   # error of FWHM
    R = 100 * FWHM / MU                                                     # Resolution
    delta_R = R * np.sqrt((delta_FWHM / FWHM) ** 2 + (delta_MU / MU) ** 2)  # error of R
    values = {'amplitude': A, 'delta_amplitude': delta_A,                   # the fit is returned in a dictionary
              'mean': MU, 'delta_mean': delta_MU,
              'sigma': SIGMA, 'delta_sigma': delta_SIGMA,
              'FWHM': FWHM, 'delta_FWHM': delta_SIGMA,
              'R[%]': R, 'delta_R[%]': delta_R
              }
    return values

def SkewedGaussian_fit(x,y):
    init = [max(y), x[np.argmax(y)], (x[np.argmax(y)] - x[0])/3, 1]         # initial guess of the parameters
    fit = scipy.optimize.curve_fit(SkewedGaussian, x, y, init)              # fit
    opt_param = fit[0]                                                      # optimal parameters that fit the data
    opt_param_cov = fit[1]                                                  # matrix of covariance
    opt_param_error = np.sqrt(np.diag(opt_param_cov))                       # errors are in the diagonal of the matrix
    A = opt_param[0]                                                        # amplitude of the fit
    MU = opt_param[1]                                                       # mean of the fit
    SIGMA = abs(opt_param[2])                                               # std dev of the fit (abs value)
    GAMMA = opt_param[3]                                                    # skewness
    delta_A = opt_param_error[0]                                            # error of the amplitude
    delta_MU = opt_param_error[1]                                           # error of the mean
    delta_SIGMA = opt_param_error[2]                                        # error of the std dev
    delta_GAMMA = opt_param_error[3]                                        # error of skewness
    values = {'amplitude': A, 'delta_amplitude': delta_A,                   # the fit is returned in a dictionary
              'mean': MU, 'delta_mean': delta_MU,
              'sigma': SIGMA, 'delta_sigma': delta_SIGMA,
              'gamma': GAMMA, 'delta_gamma': delta_GAMMA
              }
    return values


# coding: utf-8

"""
    ExtremeCloud IQ API

    ExtremeCloud IQ RESTful API for external and internal applications.  # noqa: E501

    The version of the OpenAPI document: 23.6.0.46
    Contact: support@extremenetworks.com
    Generated by: https://openapi-generator.tech
"""

import pprint
import re  # noqa: F401

import six

from extremecloudiq.configuration import Configuration

class XiqAuthLog(object):
    """NOTE: This class is auto generated by OpenAPI Generator.
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    """
    Attributes:
      openapi_types (dict): The key is attribute name
                            and the value is attribute type.
      attribute_map (dict): The key is attribute name
                            and the value is json key in definition.
    """
    openapi_types = {
        'id': 'str',
        'auth_type': 'str',
        'sn': 'str',
        'vhm_id': 'str',
        'username': 'str',
        'reply': 'str',
        'called_station_id': 'str',
        'calling_station_id': 'str',
        'auth_date': 'int',
        'ssid': 'str',
        'identity': 'str',
        'nas_port_type': 'str',
        'reject_reason': 'str',
        'nas_identifier': 'str',
        'mgmt_mac_address': 'str',
        'org_id': 'int',
        'timestamp': 'int'
    }

    attribute_map = {
        'id': 'id',
        'auth_type': 'auth_type',
        'sn': 'sn',
        'vhm_id': 'vhm_id',
        'username': 'username',
        'reply': 'reply',
        'called_station_id': 'called_station_id',
        'calling_station_id': 'calling_station_id',
        'auth_date': 'auth_date',
        'ssid': 'ssid',
        'identity': 'identity',
        'nas_port_type': 'nas_port_type',
        'reject_reason': 'reject_reason',
        'nas_identifier': 'nas_identifier',
        'mgmt_mac_address': 'mgmt_mac_address',
        'org_id': 'org_id',
        'timestamp': 'timestamp'
    }

    def __init__(self, id=None, auth_type=None, sn=None, vhm_id=None, username=None, reply=None, called_station_id=None, calling_station_id=None, auth_date=None, ssid=None, identity=None, nas_port_type=None, reject_reason=None, nas_identifier=None, mgmt_mac_address=None, org_id=None, timestamp=None, local_vars_configuration=None):  # noqa: E501
        """XiqAuthLog - a model defined in OpenAPI"""  # noqa: E501
        if local_vars_configuration is None:
            local_vars_configuration = Configuration()
        self.local_vars_configuration = local_vars_configuration

        self._id = None
        self._auth_type = None
        self._sn = None
        self._vhm_id = None
        self._username = None
        self._reply = None
        self._called_station_id = None
        self._calling_station_id = None
        self._auth_date = None
        self._ssid = None
        self._identity = None
        self._nas_port_type = None
        self._reject_reason = None
        self._nas_identifier = None
        self._mgmt_mac_address = None
        self._org_id = None
        self._timestamp = None
        self.discriminator = None

        self.id = id
        if auth_type is not None:
            self.auth_type = auth_type
        if sn is not None:
            self.sn = sn
        if vhm_id is not None:
            self.vhm_id = vhm_id
        if username is not None:
            self.username = username
        if reply is not None:
            self.reply = reply
        if called_station_id is not None:
            self.called_station_id = called_station_id
        if calling_station_id is not None:
            self.calling_station_id = calling_station_id
        if auth_date is not None:
            self.auth_date = auth_date
        if ssid is not None:
            self.ssid = ssid
        if identity is not None:
            self.identity = identity
        if nas_port_type is not None:
            self.nas_port_type = nas_port_type
        if reject_reason is not None:
            self.reject_reason = reject_reason
        if nas_identifier is not None:
            self.nas_identifier = nas_identifier
        if mgmt_mac_address is not None:
            self.mgmt_mac_address = mgmt_mac_address
        if org_id is not None:
            self.org_id = org_id
        if timestamp is not None:
            self.timestamp = timestamp

    @property
    def id(self):
        """Gets the id of this XiqAuthLog.  # noqa: E501

        The auth log id  # noqa: E501

        :return: The id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._id

    @id.setter
    def id(self, id):
        """Sets the id of this XiqAuthLog.

        The auth log id  # noqa: E501

        :param id: The id of this XiqAuthLog.  # noqa: E501
        :type: str
        """
        if self.local_vars_configuration.client_side_validation and id is None:  # noqa: E501
            raise ValueError("Invalid value for `id`, must not be `None`")  # noqa: E501

        self._id = id

    @property
    def auth_type(self):
        """Gets the auth_type of this XiqAuthLog.  # noqa: E501

        The auth type  # noqa: E501

        :return: The auth_type of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._auth_type

    @auth_type.setter
    def auth_type(self, auth_type):
        """Sets the auth_type of this XiqAuthLog.

        The auth type  # noqa: E501

        :param auth_type: The auth_type of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._auth_type = auth_type

    @property
    def sn(self):
        """Gets the sn of this XiqAuthLog.  # noqa: E501

        The serial number  # noqa: E501

        :return: The sn of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._sn

    @sn.setter
    def sn(self, sn):
        """Sets the sn of this XiqAuthLog.

        The serial number  # noqa: E501

        :param sn: The sn of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._sn = sn

    @property
    def vhm_id(self):
        """Gets the vhm_id of this XiqAuthLog.  # noqa: E501

        The vhm id  # noqa: E501

        :return: The vhm_id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._vhm_id

    @vhm_id.setter
    def vhm_id(self, vhm_id):
        """Sets the vhm_id of this XiqAuthLog.

        The vhm id  # noqa: E501

        :param vhm_id: The vhm_id of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._vhm_id = vhm_id

    @property
    def username(self):
        """Gets the username of this XiqAuthLog.  # noqa: E501

        The username  # noqa: E501

        :return: The username of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._username

    @username.setter
    def username(self, username):
        """Sets the username of this XiqAuthLog.

        The username  # noqa: E501

        :param username: The username of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._username = username

    @property
    def reply(self):
        """Gets the reply of this XiqAuthLog.  # noqa: E501

        The reply  # noqa: E501

        :return: The reply of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._reply

    @reply.setter
    def reply(self, reply):
        """Sets the reply of this XiqAuthLog.

        The reply  # noqa: E501

        :param reply: The reply of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._reply = reply

    @property
    def called_station_id(self):
        """Gets the called_station_id of this XiqAuthLog.  # noqa: E501

        The called station id  # noqa: E501

        :return: The called_station_id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._called_station_id

    @called_station_id.setter
    def called_station_id(self, called_station_id):
        """Sets the called_station_id of this XiqAuthLog.

        The called station id  # noqa: E501

        :param called_station_id: The called_station_id of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._called_station_id = called_station_id

    @property
    def calling_station_id(self):
        """Gets the calling_station_id of this XiqAuthLog.  # noqa: E501

        The calling station id  # noqa: E501

        :return: The calling_station_id of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._calling_station_id

    @calling_station_id.setter
    def calling_station_id(self, calling_station_id):
        """Sets the calling_station_id of this XiqAuthLog.

        The calling station id  # noqa: E501

        :param calling_station_id: The calling_station_id of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._calling_station_id = calling_station_id

    @property
    def auth_date(self):
        """Gets the auth_date of this XiqAuthLog.  # noqa: E501

        The authentication date  # noqa: E501

        :return: The auth_date of this XiqAuthLog.  # noqa: E501
        :rtype: int
        """
        return self._auth_date

    @auth_date.setter
    def auth_date(self, auth_date):
        """Sets the auth_date of this XiqAuthLog.

        The authentication date  # noqa: E501

        :param auth_date: The auth_date of this XiqAuthLog.  # noqa: E501
        :type: int
        """

        self._auth_date = auth_date

    @property
    def ssid(self):
        """Gets the ssid of this XiqAuthLog.  # noqa: E501

        The ssid  # noqa: E501

        :return: The ssid of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._ssid

    @ssid.setter
    def ssid(self, ssid):
        """Sets the ssid of this XiqAuthLog.

        The ssid  # noqa: E501

        :param ssid: The ssid of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._ssid = ssid

    @property
    def identity(self):
        """Gets the identity of this XiqAuthLog.  # noqa: E501

        The identity  # noqa: E501

        :return: The identity of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._identity

    @identity.setter
    def identity(self, identity):
        """Sets the identity of this XiqAuthLog.

        The identity  # noqa: E501

        :param identity: The identity of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._identity = identity

    @property
    def nas_port_type(self):
        """Gets the nas_port_type of this XiqAuthLog.  # noqa: E501

        The nas port type  # noqa: E501

        :return: The nas_port_type of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._nas_port_type

    @nas_port_type.setter
    def nas_port_type(self, nas_port_type):
        """Sets the nas_port_type of this XiqAuthLog.

        The nas port type  # noqa: E501

        :param nas_port_type: The nas_port_type of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._nas_port_type = nas_port_type

    @property
    def reject_reason(self):
        """Gets the reject_reason of this XiqAuthLog.  # noqa: E501

        The reject reason  # noqa: E501

        :return: The reject_reason of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._reject_reason

    @reject_reason.setter
    def reject_reason(self, reject_reason):
        """Sets the reject_reason of this XiqAuthLog.

        The reject reason  # noqa: E501

        :param reject_reason: The reject_reason of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._reject_reason = reject_reason

    @property
    def nas_identifier(self):
        """Gets the nas_identifier of this XiqAuthLog.  # noqa: E501

        The nas identifier  # noqa: E501

        :return: The nas_identifier of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._nas_identifier

    @nas_identifier.setter
    def nas_identifier(self, nas_identifier):
        """Sets the nas_identifier of this XiqAuthLog.

        The nas identifier  # noqa: E501

        :param nas_identifier: The nas_identifier of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._nas_identifier = nas_identifier

    @property
    def mgmt_mac_address(self):
        """Gets the mgmt_mac_address of this XiqAuthLog.  # noqa: E501

        The management mac address  # noqa: E501

        :return: The mgmt_mac_address of this XiqAuthLog.  # noqa: E501
        :rtype: str
        """
        return self._mgmt_mac_address

    @mgmt_mac_address.setter
    def mgmt_mac_address(self, mgmt_mac_address):
        """Sets the mgmt_mac_address of this XiqAuthLog.

        The management mac address  # noqa: E501

        :param mgmt_mac_address: The mgmt_mac_address of this XiqAuthLog.  # noqa: E501
        :type: str
        """

        self._mgmt_mac_address = mgmt_mac_address

    @property
    def org_id(self):
        """Gets the org_id of this XiqAuthLog.  # noqa: E501

        The org id  # noqa: E501

        :return: The org_id of this XiqAuthLog.  # noqa: E501
        :rtype: int
        """
        return self._org_id

    @org_id.setter
    def org_id(self, org_id):
        """Sets the org_id of this XiqAuthLog.

        The org id  # noqa: E501

        :param org_id: The org_id of this XiqAuthLog.  # noqa: E501
        :type: int
        """

        self._org_id = org_id

    @property
    def timestamp(self):
        """Gets the timestamp of this XiqAuthLog.  # noqa: E501

        The audit log timestamp  # noqa: E501

        :return: The timestamp of this XiqAuthLog.  # noqa: E501
        :rtype: int
        """
        return self._timestamp

    @timestamp.setter
    def timestamp(self, timestamp):
        """Sets the timestamp of this XiqAuthLog.

        The audit log timestamp  # noqa: E501

        :param timestamp: The timestamp of this XiqAuthLog.  # noqa: E501
        :type: int
        """

        self._timestamp = timestamp

    def to_dict(self):
        """Returns the model properties as a dict"""
        result = {}

        for attr, _ in six.iteritems(self.openapi_types):
            value = getattr(self, attr)
            if isinstance(value, list):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value

        return result

    def to_str(self):
        """Returns the string representation of the model"""
        return pprint.pformat(self.to_dict())

    def __repr__(self):
        """For `print` and `pprint`"""
        return self.to_str()

    def __eq__(self, other):
        """Returns true if both objects are equal"""
        if not isinstance(other, XiqAuthLog):
            return False

        return self.to_dict() == other.to_dict()

    def __ne__(self, other):
        """Returns true if both objects are not equal"""
        if not isinstance(other, XiqAuthLog):
            return True

        return self.to_dict() != other.to_dict()


# see README.md

from flask import Flask, request
from flask_cors import CORS
import lib
import pandas
import json

app = Flask(__name__)
CORS(app)

@app.route('/')
def root():
    return "see README.md"

@app.route('/view/<path:data>')
def testing(data):

    fileNames = ["Group_340", "Group_342",
                 "Group_343", "Group_349", "Group_416"]

    fileValues = []
    for fileName in fileNames:
        df = pandas.read_csv(f'csvfiles/{data}/{fileName}.csv')
        keys = []
        longvalues = []

        for name in df.columns:
            keys.append(name)

        for index, row in df.iterrows():
            value = []
            for key in keys:
                value.append(row[key])
            longvalues.append(value)

        fileValues.append(longvalues)

    # simulating ticks and retrieving snapshots every 0.1 sec
    # c++ backend
    snapshots = lib.testing(fileValues)

    # save the snapshots file to 'data'.json
    with open(f'csvfiles/{data}/data.json', 'w') as outfile:
        json.dump(snapshots, outfile)

    print("done")

    return snapshots

@app.route('/view_ft/<path:data>')
def view_ft(data):
    # open the json file
    with open(f'csvfiles/{data}/data.json') as json_file:
        data = json.load(json_file)
        return data


import redis
import threading
class quote_cache:
    def __init__(self):
        self.load_env()
        self.r = redis.Redis(host=self.redis_host, port=self.redis_port)
        self.mutex = threading.Lock()

    def load_env(self):
        import os
        from dotenv import load_dotenv
        load_dotenv()
        self.redis_host = os.environ.get("redis_host")
        self.redis_port = int(os.environ.get("redis_port"))

    def sanitize_byte_keys_and_vals(self, response):
        sanitized_dict = {}
        keys = response.keys()
        for key in keys:
            sanitized_dict[str(key, encoding="utf-8")] = str(response[key], encoding="utf-8")
        return sanitized_dict

    def cache_quote(self, data):
        stock_symbol = data["stock_symbol"]
        dollars = data["dollars"]
        cents = data["cents"]
        quote_time = data["quote_time"]
        cryptokey = data["cryptokey"]
        response = {}

        self.mutex.acquire()

        try:
            bool_result = self.r.hmset(stock_symbol, {"dollars": dollars, "cents": cents, "quote_time": quote_time, "cryptokey": cryptokey})
            if (bool_result):
                response["status"] = "SUCCESS"
            else:
                response["status"] = "ERROR"

        finally:
            self.mutex.release()

        return response

    def get_quote(self, stock_symbol):
        response = {"status": "ERROR"}
        response["data"] = self.sanitize_byte_keys_and_vals(self.r.hgetall(stock_symbol))
        if (response["data"] != None and len(response["data"]) != 0):
            response["status"] = "SUCCESS"
        return response


def f01_14_charListIndex(inputList,e):
    """
    Creating a list of index where particular 'element' is located in inputList.
    E.g.
        ['e','x','a','m','l','e'], 'e'
        returns: [0,5]

    Parameters
    ----------
    l : list
        List of chars (can be empty)
    e : char

    Returns
    -------
    r : list
        List of indexes.
    """
    outputList = []
    for i in range(0,len(inputList)):
        if (inputList[i] == e):
            outputList.append(i)
    return outputList


# -*- coding: utf-8 -*-
from odoo import api, fields, models, _
from odoo.exceptions import ValidationError

class StockMove(models.Model):
    _inherit = 'stock.move'

    quantity_remaining = fields.Float('Quantity Remaining', compute='_quantity_remaining_compute',
                                      digits='Product Unit of Measure')

    @api.depends('quantity_done', 'product_uom_qty')
    def _quantity_remaining_compute(self):
        for data in self:
            data.quantity_remaining = data.product_uom_qty - data.quantity_done

class StockPicking(models.Model):
    _inherit = 'stock.picking'

    mo_quantity = fields.Float('M/O Quantity', compute='_compute_mo_quantity')
    mo_name = fields.Many2one('mrp.production', 'MO', compute='_compute_mo_quantity')

    @api.depends('group_id')
    def _compute_mo_quantity(self):
        for picking in self:
            picking.mo_quantity = 0
            picking.mo_name = False
            if picking.group_id:
                mo = self.env['mrp.production'].search([(
                    'procurement_group_id', '=', picking.group_id.id
                )])
                if mo:
                    picking.mo_quantity = mo[0].product_qty
                    picking.mo_name = mo[0].id


from copy import copy
import sys
import traceback

class State(object):
    name = ''
    human_name = ''

    def __init__(self, name='', human_name='', check=None):
        super().__init__()
        self.name = name or self.name or self.__class__.__name__
        self.human_name = human_name or self.human_name
        if check:
            self.check = check

    def get_states(self):
        pass

    def check(self, data):
        pass

    def get_text(self):
        return self.human_name or self.name

    def __repr__(self, *args, **kwargs):
        return self.get_text()

class Action(object):
    name = ''
    human_name = ''

    def __init__(self, name='', human_name='', action=None):
        super().__init__()
        if action:
            self.do = action
        self.name = name or self.name or (self.do and self.do.__name__) or ''
        self.human_name = human_name or self.human_name

    def do(self, data):
        pass

    def get_text(self):
        return self.human_name or self.name

    def __repr__(self, *args, **kwargs):
        return self.get_text()

class Pipeline(object):

    def __init__(self, config_actions, actions_list, start_state, data):
        super().__init__()
        # because deepcopy regenerate all class instances
        self.config_actions = {k: copy(v) for k, v in config_actions.items()}
        self.actions_list = actions_list
        self.start_state = start_state
        self.current_state = start_state
        self.data = data

    def get_next_state(self, current_state, action):
        return self.config_actions[current_state][action]

    def set_next_state(self, action):
        self.current_state = self.get_next_state(self.current_state, action)

    def run(self):
        text = '\nState: {}'.format(self.current_state.get_text())
        error_text = ''
        try:
            for action in self.actions_list:
                text += '\nDo: {} ... '.format(action.get_text())
                action.do(self.data)
                text += 'OK'
                self.set_next_state(action)
                text += '\nState: {} ... '.format(self.current_state.get_text())
                self.current_state.check(self.data)
                text += 'OK'
        except Exception as e:
            etype, value, tb = sys.exc_info()
            if any([etype, value, tb]):
                error_text = ''.join([str(el) for el in traceback.format_exception(etype, value, tb)])

        if error_text:
            text += '\n' + error_text
            raise Exception(text)

    def get_text(self):
        result = '*' * 20
        result += '\nstart state: {}'.format(self.start_state.get_text())
        current_state = self.start_state
        for action in self.actions_list:
            current_state = self.get_next_state(current_state, action)
            result += '\n{} (next state: {})'.format(action.get_text(), current_state.get_text())
        result += '\n' + '*' * 20
        return result


from django.urls import include, path

from backend.core import views as v

app_name = 'core'

url_coreui = [
    path('colors', v.colors, name='colors'),
    path('typography', v.typography, name='typography'),
    path('accordion', v.accordion, name='accordion'),
    path('breadcrumb', v.breadcrumb, name='breadcrumb'),
    path('cards', v.cards, name='cards'),
    path('carousel', v.carousel, name='carousel'),
    path('collapse', v.collapse, name='collapse'),
    path('list-group', v.list_group, name='list_group'),
    path('navs-tabs', v.navs_tabs, name='navs_tabs'),
    path('pagination', v.pagination, name='pagination'),
    path('placeholders', v.placeholders, name='placeholders'),
    path('popovers', v.popovers, name='popovers'),
    path('progress', v.progress, name='progress'),
    path('spinners', v.spinners, name='spinners'),
    path('tables', v.tables, name='tables'),
    path('tooltips', v.tooltips, name='tooltips'),
    path('buttons', v.buttons, name='buttons'),
    path('button-group', v.button_group, name='button_group'),
    path('dropdowns', v.dropdowns, name='dropdowns'),
    path('charts', v.charts, name='charts'),
    path('form-control', v.form_control, name='form_control'),
    path('select', v.select, name='select'),
    path('checks-radios', v.checks_radios, name='checks_radios'),
    path('range', v.range, name='range'),
    path('input-group', v.input_group, name='input_group'),
    path('floating-labels', v.floating_labels, name='floating_labels'),
    path('layout', v.layout, name='layout'),
    path('validation', v.validation, name='validation'),
    path('coreui-icons-free', v.coreui_icons_free, name='coreui_icons_free'),
    path('coreui-icons-brand', v.coreui_icons_brand, name='coreui_icons_brand'),
    path('coreui-icons-flag', v.coreui_icons_flag, name='coreui_icons_flag'),
    path('alerts', v.alerts, name='alerts'),
    path('badge', v.badge, name='badge'),
    path('modals', v.modals, name='modals'),
    path('toasts', v.toasts, name='toasts'),
    path('widgets', v.widgets, name='widgets'),
    path('login', v.login, name='login'),
    path('register', v.register, name='register'),
    path('page404', v.page404, name='page404'),
    path('page500', v.page500, name='page500'),
]

urlpatterns = [
    path('', v.index, name='index'),
    path('list/', v._list, name='list'),
    path('detail/', v._detail, name='detail'),
    path('add/', v._create, name='create'),
    path('blank/', v.blank, name='blank'),
    path('coreui/', include(url_coreui)),
]


from fastapi import FastAPI
from pydantic import BaseModel
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
import joblib
from fastapi import FastAPI

app = FastAPI()

# Load the pre-trained SVM model and TF-IDF vectorizer
svm_classifier = joblib.load("svm_model.pkl")
tfidf_vectorizer = joblib.load("tfidf_vectorizer.pkl")

# Create a templates object for rendering HTML
templates = Jinja2Templates(directory="templates")

class TextRequest(BaseModel):
    text: str

@app.get("/", response_class=HTMLResponse)
async def read_item(request):
    # Render the HTML page
    return templates.TemplateResponse("index.html", {"request": request})

@app.post("/predict/")
async def predict_emotion(request_data: TextRequest):  # Update the parameter name here
    text = request_data.text  # Use request_data
    # Vectorize the input text
    text_vectorized = tfidf_vectorizer.transform([text])
    # Make predictions
    prediction = svm_classifier.predict(text_vectorized)
    return {"emotion": prediction[0]}


"""Typing test implementation"""

from utils import *
from ucb import main, interact, trace
from datetime import datetime

###########
# Phase 1 #
###########

def choose(paragraphs, select, k):
    """Return the Kth paragraph from PARAGRAPHS for which SELECT called on the
    paragraph returns true. If there are fewer than K such paragraphs, return
    the empty string.
    """
    # BEGIN PROBLEM 1
    "*** YOUR CODE HERE ***"
    true_choose = []
    for i in paragraphs:
        if select(i):
            true_choose.append(i)

    if len(true_choose) <= k:
            return ''

    return true_choose[k]
    # END PROBLEM 1

def about(topic):
    """Return a select function that returns whether a paragraph contains one
    of the words in TOPIC.

    >>> about_dogs = about(['dog', 'dogs', 'pup', 'puppy'])
    >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup!'], about_dogs, 0)
    'Cute Dog!'
    >>> choose(['Cute Dog!', 'That is a cat.', 'Nice pup.'], about_dogs, 1)
    'Nice pup.'
    """
    assert all([lower(x) == x for x in topic]), 'topics should be lowercase.'
    # BEGIN PROBLEM 2
    "*** YOUR CODE HERE ***"
    def topic_in_paragraph(paragraph):
        remove = remove_punctuation(paragraph)
        low = lower(remove)
        split_para = split(low)
        for i in split_para:
            if i in topic:
                return True
        return False
    return topic_in_paragraph
    # END PROBLEM 2

def accuracy(typed, reference):
    """Return the accuracy (percentage of words typed correctly) of TYPED
    when compared to the prefix of REFERENCE that was typed.

    >>> accuracy('Cute Dog!', 'Cute Dog.')
    50.0
    >>> accuracy('A Cute Dog!', 'Cute Dog.')
    0.0
    >>> accuracy('cute Dog.', 'Cute Dog.')
    50.0
    >>> accuracy('Cute Dog. I say!', 'Cute Dog.')
    50.0
    >>> accuracy('Cute', 'Cute Dog.')
    100.0
    >>> accuracy('', 'Cute Dog.')
    0.0
    """
    typed_words = split(typed)
    reference_words = split(reference)
    # BEGIN PROBLEM 3
    "*** YOUR CODE HERE ***"
    correct_words, max_index = 0, min(len(typed_words), len(reference_words))

    if max_index == 0:
        return 0.0

    for i in range(max_index):
        if typed_words[i] == reference_words[i]:
            correct_words += 1

    return correct_words / len(typed_words) * 100
    # END PROBLEM 3

def wpm(typed, elapsed):
    """Return the words-per-minute (WPM) of the TYPED string."""
    assert elapsed > 0, 'Elapsed time must be positive'
    # BEGIN PROBLEM 4
    "*** YOUR CODE HERE ***"
    return 60 * len(typed) / (5 * elapsed)
    # END PROBLEM 4

def autocorrect(user_word, valid_words, diff_function, limit):
    """Returns the element of VALID_WORDS that has the smallest difference
    from USER_WORD. Instead returns USER_WORD if that difference is greater
    than LIMIT.
    """
    # BEGIN PROBLEM 5
    "*** YOUR CODE HERE ***"
    if user_word in valid_words:
        return user_word

    d = {}
    for word in valid_words:
        difference = diff_function(user_word, word, limit)
        d[word] = difference

    min_word = min(d, key=d.get)

    if d[min_word] <= limit:
        return min_word
    else:
        return user_word
    # END PROBLEM 5

def swap_diff(start, goal, limit):
    """A diff function for autocorrect that determines how many letters
    in START need to be substituted to create GOAL, then adds the difference in
    their lengths.
    """

    if goal == "":
        if len(start) <= limit:
            return len(start)
        else:
            return limit+1

    if start == "":

        if len(goal) <= limit:
            return len(goal)
        else:
            return limit+1

    if start[0] == goal[0]:
        return swap_diff(start[1:],goal[1:], limit)
    if limit == 0:
        return 1

    if start[0] != goal[0]:
        return 1+swap_diff(start[1:],goal[1:], limit-1)

    # END PROBLEM 6

def edit_diff(start, goal, limit):
    """A diff function that computes the edit distance from START to GOAL."""

    def helper(start, counter, index):

        if counter>limit:
            return counter+1

        if index>=len(start) or index>=len(goal):
            return counter+abs(len(start)-len(goal))

        def remove():
            newStart = start[:index]+start[index+1:]
            return newStart
        def add():
            newStart = start[:index]+goal[index]+start[index:]
            return newStart
        def replace():
            newStart = start[:index]+goal[index]+start[index+1:]
            return newStart

        if(start[index]==goal[index]):
            return helper(start, counter, index+1)
        else:
            return min(helper(add(), counter+1, index+1), helper(remove(), counter+1, index), helper(replace(), counter+1, index+1))

    return helper(start, 0, 0)

def final_diff(start, goal, limit):
    """A diff function. If you implement this function, it will be used."""
    assert False, 'Remove this line to use your final_diff function'

###########
# Phase 3 #
###########

def report_progress(typed, prompt, id, send):
    """Send a report of your id and progress so far to the multiplayer server."""
    # BEGIN PROBLEM 8
    "*** YOUR CODE HERE ***"
    index = 0
    progress = 0

    while index < len(typed):
        if typed[index] !=  prompt[index]:
            progress = index/len(prompt)
            index = len(typed)
            data =	{
              'id': id,
              'progress': progress
            }
            send(data)
            return progress
        index = index+ 1

    progress = len(typed)/len(prompt)
    data =	{
      'id': id,
      'progress': progress
    }
    send(data)

    return progress

    # END PROBLEM 8

def fastest_words_report(word_times):
    """Return a text description of the fastest words typed by each player."""
    fastest = fastest_words(word_times)
    report = ''
    for i in range(len(fastest)):
        words = ','.join(fastest[i])
        report += 'Player {} typed these fastest: {}\n'.format(i + 1, words)
    return report

def fastest_words(word_times, margin=1e-5):
    """A list of which words each player typed fastest."""
    n_players = len(word_times)
    n_words = len(word_times[0]) - 1
    assert all(len(times) == n_words + 1 for times in word_times)
    assert margin > 0
    # BEGIN PROBLEM 9
    "*** YOUR CODE HERE ***"
    fastestTyped=[]
    for player in word_times: # 3 empty lists, one for each player
        fastestTyped.append([])

    players = len(word_times)
    numberOfWords = len(word_times[0])
    for wordIndex in range(1, numberOfWords):
        minValue = -1

        for playerIndex in range(players):
            difference = elapsed_time(word_times[playerIndex][wordIndex]) - elapsed_time(word_times[playerIndex][wordIndex-1])
            if minValue == -1 or difference < minValue:
                minValue = difference

        for playerIndex in range(players):
            difference = elapsed_time(word_times[playerIndex][wordIndex]) - elapsed_time(word_times[playerIndex][wordIndex-1])
            if difference <= minValue+margin and difference >= minValue-margin:
                fastestTyped[playerIndex].append(word(word_times[playerIndex][wordIndex]))

    return fastestTyped

    # END PROBLEM 9

def word_time(word, elapsed_time):
    """A data abstrction for the elapsed time that a player finished a word."""
    return [word, elapsed_time]

def word(word_time):
    """An accessor function for the word of a word_time."""
    return word_time[0]

def elapsed_time(word_time):
    """An accessor function for the elapsed time of a word_time."""
    return word_time[1]

enable_multiplayer = True  # Change to True when you

##########################
# Command Line Interface #
##########################

def run_typing_test(topics):
    """Measure typing speed and accuracy on the command line."""
    paragraphs = lines_from_file('data/sample_paragraphs.txt')
    select = lambda p: True
    if topics:
        select = about(topics)
    i = 0
    while True:
        reference = choose(paragraphs, select, i)
        if not reference:
            print('No more paragraphs about', topics, 'are available.')
            return
        print('Type the following paragraph and then press enter/return.')
        print('If you only type part of it, you will be scored only on that part.\n')
        print(reference)
        print()

        start = datetime.now()
        typed = input()
        if not typed:
            print('Goodbye.')
            return
        print()

        elapsed = (datetime.now() - start).total_seconds()
        print("Nice work!")
        print('Words per minute:', wpm(typed, elapsed))
        print('Accuracy:        ', accuracy(typed, reference))

        print('\nPress enter/return for the next paragraph or type q to quit.')
        if input().strip() == 'q':
            return
        i += 1

@main
def run(*args):
    """Read in the command-line argument and calls corresponding functions."""
    import argparse
    parser = argparse.ArgumentParser(description="Typing Test")
    parser.add_argument('topic', help="Topic word", nargs='*')
    parser.add_argument('-t', help="Run typing test", action='store_true')

    args = parser.parse_args()
    if args.t:
        run_typing_test(args.topic)


import torch
import torch.nn as nn
import numpy as np
import MinkowskiEngine as ME

def make_pointwise_mlp_sparse(dims, doLastRelu=False):
    """
    Make poinwise MLP layers based on MinkowskiEngine
    """
    layers = []
    for i in range(len(dims) - 1):
        layers.append(
            ME.MinkowskiLinear(dims[i], dims[i + 1], bias=True)
        )
        if i != len(dims) - 2 or doLastRelu:
            layers.append(ME.MinkowskiReLU(inplace=True))
    return torch.nn.Sequential(*layers)

class MlpDecoderSparse(nn.Module):
    """
    MLP decoder implemented with MinkowskiEngine
    """

    def __init__(self, net_config, **kwargs):
        super(MlpDecoderSparse, self).__init__()
        self.num_points = net_config['num_points']
        dims = net_config['dims']
        self.mlp = make_pointwise_mlp_sparse(dims + [3 * self.num_points], doLastRelu=False) # the MLP layers

    def forward(self, x):
        out = self.mlp(x) # BatchSize X PointNum X 3
        return out


def func(path: str):
    f = open(path)
    # первая строка со старой валютой
    old_cource = [int(x) for x in f.readline().split()[1:]]

    # вторая строка с несчастливыми числам
    old_numbers = [int(x) for x in f.readline().split()[1:]]

    # третья строка с новой валютой
    new_cource = [int(x) for x in f.readline().split()[1:]]

    # четвёртая строка с несчастливыми чисами новой валюты
    new_numbers = [int(x) for x in f.readline().split()[1:]]

    # пятая строка с количеством старой валюты
    old_cource_value = [int(x) for x in f.readline().split()]

    # количество новой валюты
    new_cource_value = [0] * (len(new_cource) + 1)

    old_numbers.sort(reverse = 1)
    new_numbers.sort()

    # убирание несчастливых чисел
    for i in range(len(old_cource_value)):
        for j in range(len(old_numbers)):
            if old_numbers[j] <= old_cource_value[i]:
                old_cource_value[i] -= 1

    # перевод из одной валюты в другую 1
    for i in range(len(old_cource_value) - 1):
        old_cource_value[i + 1] += old_cource_value[i]*old_cource[i]

    new_cource_value[-1] = old_cource_value[-1]

    # перевод из одной валюты в другую 2
    for i in range(len(new_cource_value) - 1, 0, -1):
        new_cource_value[i - 1] = new_cource_value[i] // new_cource[i - 1]
        new_cource_value[i] = new_cource_value[i] % new_cource[i - 1]

    # убирание несчастливых чисел
    for i in range(len(new_cource_value)):
        for j in range(len(new_numbers)):
            if new_numbers[j] <= new_cource_value[i]:
                new_cource_value[i] += 1

    # вывод
    for value in new_cource_value:
        print(value, end = ' ')
    print()

for i in range(1,15):
    print(f'{i})')
    func(f'exchange money\Обмен денег\input{i}.txt')
    f = open(f'exchange money\Обмен денег\output{i}.txt')
    print(f.readline())

Олимпиадные задачи/обмен денег/program.py


import logging

# if cp_test_nn is imported, make sure the importer doesn't see
#  any logs by default, but can choose to enable them by calling
#  cp_test_nn.logging_setup()
log = logging.getLogger(__name__)
log.setLevel(logging.DEBUG)
log.addHandler(logging.NullHandler())

def logging_setup(level=logging.INFO):
    handler = logging.StreamHandler()
    handler.setLevel(level)
    log.addHandler(handler)