import torch
import torch.nn as nn
import torchvision
import torch.nn.functional as F
import torch.optim as optim
import torchvision.transforms as transforms
import time
import math
import torch.utils.model_zoo as model_zoo
from tensorboardX import SummaryWriter

# 超参数设置
EPOCH = 50   #遍历数据集次数
BATCH_SIZE = 4      #批处理尺寸(batch_size)
LR = 0.001        #学习率

__all__ = ['ResNet', 'resnet18', 'resnet34', 'resnet50', 'resnet101',
           'resnet152']

model_urls = {
    'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',
    'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',
    'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',
    'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',
    'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',
}

transform = transforms.Compose([
    transforms.Resize(224),
    transforms.ToTensor(),
    transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))
])

trainset = torchvision.datasets.CIFAR10(
    root='/media/mcislab/GaoXiangjun/Learn_Pytorch/data/', train=True, download=True, transform=transform)
trainloader = torch.utils.data.DataLoader(
    trainset, batch_size=BATCH_SIZE, shuffle=True)

testset = torchvision.datasets.CIFAR10(
    root='/media/mcislab/GaoXiangjun/Learn_Pytorch/data/', train=False, download=True, transform=transform)
testloader = torch.utils.data.DataLoader(
    testset, batch_size=BATCH_SIZE, shuffle=False)

classes = ('plane', 'car', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse',
           'ship', 'truck')

def conv3x3(in_planes, out_planes, stride=1):
    """3x3 convolution with padding"""
    return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,
                     padding=1, bias=False)

class BasicBlock(nn.Module):
    expansion = 1

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(BasicBlock, self).__init__()
        self.conv1 = conv3x3(inplanes, planes, stride)
        self.bn1 = nn.BatchNorm2d(planes)
        self.relu = nn.ReLU(inplace=True)
        self.conv2 = conv3x3(planes, planes)
        self.bn2 = nn.BatchNorm2d(planes)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class Bottleneck(nn.Module):
    expansion = 4

    def __init__(self, inplanes, planes, stride=1, downsample=None):
        super(Bottleneck, self).__init__()
        self.conv1 = nn.Conv2d(inplanes, planes, kernel_size=1, bias=False)
        self.bn1 = nn.BatchNorm2d(planes)
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=stride,
                               padding=1, bias=False)
        self.bn2 = nn.BatchNorm2d(planes)
        self.conv3 = nn.Conv2d(planes, planes * 4, kernel_size=1, bias=False)
        self.bn3 = nn.BatchNorm2d(planes * 4)
        self.relu = nn.ReLU(inplace=True)
        self.downsample = downsample
        self.stride = stride

    def forward(self, x):
        residual = x

        out = self.conv1(x)
        out = self.bn1(out)
        out = self.relu(out)

        out = self.conv2(out)
        out = self.bn2(out)
        out = self.relu(out)

        out = self.conv3(out)
        out = self.bn3(out)

        if self.downsample is not None:
            residual = self.downsample(x)

        out += residual
        out = self.relu(out)

        return out

class ResNet(nn.Module):

    def __init__(self, block, layers, num_classes=1000):
        self.inplanes = 64
        super(ResNet, self).__init__()
        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3,
                               bias=False)
        self.bn1 = nn.BatchNorm2d(64)
        self.relu = nn.ReLU(inplace=True)
        self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1)
        self.layer1 = self._make_layer(block, 64, layers[0])
        self.layer2 = self._make_layer(block, 128, layers[1], stride=2)
        self.layer3 = self._make_layer(block, 256, layers[2], stride=2)
        self.layer4 = self._make_layer(block, 512, layers[3], stride=2)
        self.avgpool = nn.AvgPool2d(7, stride=1)
        self.fc = nn.Linear(512 * block.expansion, num_classes)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

    def _make_layer(self, block, planes, blocks, stride=1):
        downsample = None
        if stride != 1 or self.inplanes != planes * block.expansion:
            downsample = nn.Sequential(
                nn.Conv2d(self.inplanes, planes * block.expansion,
                          kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(planes * block.expansion),
            )

        layers = []
        layers.append(block(self.inplanes, planes, stride, downsample))
        self.inplanes = planes * block.expansion
        for i in range(1, blocks):
            layers.append(block(self.inplanes, planes))

        return nn.Sequential(*layers)

    def forward(self, x):
        x = self.conv1(x)
        x = self.bn1(x)
        x = self.relu(x)
        x = self.maxpool(x)

        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.layer4(x)

        x = self.avgpool(x)
        x = x.view(x.size(0), -1)
        x = self.fc(x)

        return x

def resnet18(pretrained=False, **kwargs):
    """Constructs a ResNet-18 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [2, 2, 2, 2], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet18']))
    return model

def resnet34(pretrained=False, **kwargs):
    """Constructs a ResNet-34 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(BasicBlock, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet34']))
    return model

def resnet50(pretrained=False, **kwargs):
    """Constructs a ResNet-50 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 4, 6, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet50']))
    return model

def resnet101(pretrained=False, **kwargs):
    """Constructs a ResNet-101 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 4, 23, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet101']))
    return model

def resnet152(pretrained=False, **kwargs):
    """Constructs a ResNet-152 model.

    Args:
        pretrained (bool): If True, returns a model pre-trained on ImageNet
    """
    model = ResNet(Bottleneck, [3, 8, 36, 3], **kwargs)
    if pretrained:
        model.load_state_dict(model_zoo.load_url(model_urls['resnet152']))
    return model

def main():

    writer = SummaryWriter('ResNet_CIFAR')
    net =resnet101()
    net.cuda()
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(net.parameters(), lr=LR, momentum=0.9)

    for epoch in range(EPOCH):  # loop over the dataset multiple times
        t0 = time.time()
        running_loss = 0.0
        total_train = 0
        correct_train = 0
        for i, data in enumerate(trainloader, 0):
            # get the inputs
            inputs, labels = data

            inputs = inputs.cuda()
            labels = labels.cuda()

            # zero the parameter gradients
            optimizer.zero_grad()

            # forward + backward + optimize
            outputs = net(inputs)
            _, predicted = torch.max(outputs.detach(), 1)
            total_train += labels.size(0)
            correct_train += (predicted == labels).sum().item()

            # 计算loss    反向传播
            loss = criterion(outputs, labels)
            loss.backward()
            optimizer.step()

            # print statistics
            running_loss += loss.item()
            if i % 2000 == 1999:  # print every 2000 mini-batches
                print('[%d, %5d] loss: %.3f' % (epoch + 1, i + 1,
                                                running_loss / 2000))
                writer.add_scalar("train_loss", running_loss/2000, (epoch)*len(trainloader)/2000 + i/2000)
                running_loss = 0.0
                t1 = time.time()
                #print('epoch:%d     batch:%d    time per 2000 batches:%lf' %
                #      (epoch+1, i+1, t1 - t0))
                t0 = time.time()

        print('epoch:%d    train_acc：%d%%' % (epoch + 1, (100 * correct_train / total_train)))
        writer.add_scalar('train_acc', (100 * correct_train / total_train),epoch+1)

        with torch.no_grad():
            correct = 0
            total = 0
            for data in testloader:
                images, labels = data
                images = images.cuda()
                labels = labels.cuda()
                outputs = net(images)
                _, predicted = torch.max(outputs.detach(), 1)
                total += labels.size(0)
                correct += (predicted == labels).sum().item()

            print('epoch:%d    val_acc：%d%%' % (epoch + 1, (100 * correct / total)))
            writer.add_scalar('val_acc', (100 * correct / total),epoch + 1)

        # 保存每个epoch下的模型参数
        torch.save(net.state_dict(), './ResNet_CIFAR/ResNet_CIFAR_%03d_params.pkl' % (epoch + 1))

    print('Finished Training')
    writer.export_scalars_to_json("./ResNet_MNIST/ResNet_MNIST.json")
    writer.close()

    # 5. Test the network on the whole test data
    correct = 0
    total = 0
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            images = images.cuda()
            labels = labels.cuda()
            outputs = net(images)
            _, predicted = torch.max(outputs.detach(), 1)

            total += labels.size(0)
            correct += (predicted == labels).sum().item()

    print('Accuracy of the network on the 10000 test images: %d %%' %
                  (100 * correct / total))

    class_correct = list(0. for i in range(10))
    class_total = list(0. for i in range(10))
    with torch.no_grad():
        for data in testloader:
            images, labels = data
            images = images.cuda()
            labels = labels.cuda()
            outputs = net(images)
            _, predicted = torch.max(outputs.detach(), 1)
            c = (predicted == labels).squeeze()
            for i in range(4):
                label = labels[i]
                class_correct[label] += c[i].item()
                class_total[label] += 1

    for i in range(10):
        print('Accuracy of %5s : %2d %%' %
              (classes[i], 100 * class_correct[i] / class_total[i]))

if __name__ == '__main__':
    main()


from functools import cmp_to_key

def solve(left, right):
    for l, r in zip(left, right):

        if type(l) == list and type(r) == list:
            result = solve(l, r)
            if result == True or result == False:
                return result
        elif type(l) == int and type(r) == int:
            if l < r:
                return True
            elif l > r:
                return False
            else:
                pass
        elif type(l) == int and type(r) == list:
            result = solve([l], r)
            if result == True or result == False:
                return result
        elif type(r) == int and type(l) == list:
            result = solve(l, [r])
            if result == True or result == False:
                return result

    if len(left) > len(right):
        return False
    elif len(right) > len(left):
        return True

def part1(packets):
    sum = 0
    for idx, packet in enumerate(packets):
        left, right = packet
        if solve(left, right):
            sum += (idx + 1)
    return sum

def part2(packets):
    prod = 1
    all_packets = [[[2]], [[6]]]
    for packet in packets:
        left, right = packet
        all_packets.append(left)
        all_packets.append(right)

    all_packets.sort(key=cmp_to_key(lambda a, b: -1 if solve(a, b) else 1))         # handle return value of solve as -1 and 1 instead of True and False to satisfy the cmp_to_key function

    for idx, packet in enumerate(all_packets):
        if packet in [[[2]], [[6]]]:
            prod *= (idx + 1)
    return prod

if __name__ == "__main__":
    with open('day13/data.txt') as f:
        data = f.read().splitlines()

    packets = []

    for idx, line in enumerate(data):
        if idx % 3 == 0:
            left = eval(line)
        if idx % 3 == 1:
            right = eval(line)
        if idx % 3 == 2 or idx == len(data) - 1:
            packets.append([left, right])

    print(part1(packets))
    print(part2(packets))


import numpy as np

class SupportVectorMachine():
    def __init__(self, c: float = 1.0) -> None:
        self.train_X: np.ndarray
        self.train_Y: np.ndarray
        self.W: np.ndarray
        self.b: np.ndarray
        self.c = c

    def fit(self, X:np.ndarray, Y:np.ndarray, learning_rate: float, iterations: int) -> list[float]:

        self.train_X = X
        self.train_Y = Y

        self.W = np.zeros((self.train_Y.shape[0], self.train_X.shape[0]))
        self.b = np.zeros((self.train_Y.shape[0], 1))

        losses = []
        for iter in range(1, iterations+1):

            T = self.train_Y * (self.W @ self.train_X + self.b)
            hinge_loss = self.hinge_loss(self.train_X, self.train_Y, T)
            losses.append(hinge_loss)
            gradients = self.gradients(T)
            self.update_parameters(gradients, learning_rate)
            if iter %5 == 0:
                print(f"Loss @ iter{iter}= {hinge_loss}")
        return losses

    def predict(self, X) -> np.ndarray:
        Z = self.W @ X + self.b
        return np.sign(Z)

    def hinge_loss(self, X:np.ndarray, Y:np.ndarray, T:np.ndarray) -> float:
        reg_term = 0.5 * np.linalg.norm(self.W, ord=2)
        err_term = np.maximum(0, 1 - T)
        err_term = np.sum(err_term, axis=1)
        err_term = np.squeeze(err_term)
        loss = reg_term + self.c * err_term
        return loss

    def gradients(self, T:np.ndarray) -> tuple[np.ndarray, ...]:

        m = self.train_Y.shape[1]
        dW = np.zeros(self.W.shape)
        db = np.zeros(self.b.shape)
        for i in range(m):
            if T[:, i] <= 1:
                dW += - self.c * self.train_Y[:, i, None] @ self.train_X[:, i, None].T
                db += - self.c * self.train_Y[:, i, None]
        dW += self.W
        return dW, db

    def update_parameters(self, gradients: np.ndarray, learnig_rate: float) -> None:
        dW, db = gradients
        self.W -= learnig_rate * dW
        self.b -= learnig_rate * db


from bs4 import BeautifulSoup
import requests

urls = ["https://google.com", "https://www.youtube.com", "https://facebook.com"]
# taking respone from each and every url and printing out its title
# for row in urls:

for row in urls:

    response = requests.get(row)
    soup = BeautifulSoup(response.text, "html.parser")
    # printing the tile of the website
    print(soup.title.string)

'''
# We then parse the html page
soup = BeautifulSoup(response.text, "html.parser")

# title from the website
print(f"title: {soup.title.string}")
'''


import logging

from enso.commands.interfaces import CommandExpression, CommandObject
from enso.commands.interfaces import AbstractCommandFactory
from enso.commands.factories import GenericPrefixFactory

# ----------------------------------------------------------------------------
# The Command Manager
# ----------------------------------------------------------------------------

class CommandManager:
    """
    Provides an interface to register and retrieve all commands.

    Allows client code to register new command implementations, find
    suggestions, and retrieve command objects.
    """

    __instance = None

    @classmethod
    def get( cls ):
        if not cls.__instance:
            cls.__instance = cls()
        return cls.__instance

    CMD_KEY = CommandExpression( "{all named commands}" )

    def __init__( self ):
        """
        Initializes the command manager.
        """

        self.__cmdObjReg = CommandObjectRegistry()
        self.__cmdFactoryDict = {
            self.CMD_KEY : self.__cmdObjReg,
            }

    def registerCommand( self, cmdName, cmdObj ):
        """
        Called to register a new command with the command manager.
        """

        try:
            cmdExpr = CommandExpression( cmdName )
        except AssertionError as why:
            logging.error( "Could not register %s : %s "
                           % ( cmdName, why ) )
            raise

        if cmdExpr.hasArgument():
            # The command expression has an argument; it is a command
            # with an argument.
            assert isinstance( cmdObj, AbstractCommandFactory ), \
                "Command object with a parameter must be instance " \
                "of AbstractCommandFactory"
            assert cmdExpr not in self.__cmdFactoryDict,\
                "Command is already registered: %s" % cmdExpr
            self.__cmdFactoryDict[ cmdExpr ] = cmdObj
        else:
            # The command expression has no argument; it is a
            # simple command with an exact name.
            assert isinstance( cmdObj, CommandObject ), \
                   "Could not register %s. Object has not type CommandObject." % cmdName
            self.__cmdObjReg.addCommandObj( cmdObj, cmdExpr )

    def unregisterCommand( self, cmdName ):
        cmdFound = False
        for cmdExpr in list(self.__cmdFactoryDict.keys()):
            if str(cmdExpr) == cmdName:
                del self.__cmdFactoryDict[cmdExpr]
                cmdFound = True
                break

        if not cmdFound:
            self.__cmdObjReg.removeCommandObj( cmdName )
            cmdFound = True
        if not cmdFound:
            raise RuntimeError( "Command '%s' does not exist." % cmdName )

    def getCommandExpression( self, commandName ):
        """
        Returns the unique command expression that is associated with
        commandName.  For example, if commandName is 'open emacs', and
        the command expression was 'open {file}', then a command expression
        object for 'open {file}' will be returned.
        """

        commands = []

        for expr in self.__cmdFactoryDict.keys():
            if expr.matches( commandName ):
                # This expression matches commandName; try to fetch a
                # command object from the corresponding factory.
                cmd = self.__cmdFactoryDict[expr].getCommandObj( commandName )
                if expr == self.CMD_KEY and cmd != None:
                    commands.append( ( commandName, commandName ) )
                elif cmd != None:
                    # The factory returned a non-nil command object.
                    # Make sure that nothing else has matched this
                    # commandName.
                    commands.append( (expr.getPrefix(), expr) )

        if len(commands) == 0:
            return None
        else:
            # If there are several matching commands, return only
            # the alphabetically first.
            commands.sort( key = lambda a: a[0] )
            return commands[0][1]

    def getCommand( self, commandName ):
        """
        Returns the unique command with commandName, based on the
        registered CommandObjects and the registered CommandFactories.

        If no command matches, returns None explicitly.
        """

        commands = []

        for expr in self.__cmdFactoryDict.keys():
            if expr.matches( commandName ):
                # This expression matches commandName; try to fetch a
                # command object from the corresponding factory.
                cmd = self.__cmdFactoryDict[expr].getCommandObj( commandName )
                if cmd is not None:
                    # The factory returned a non-nil command object.
                    commands.append( ( expr, cmd ) )

        if len( commands ) == 0:
            # There is no match
            return None
        elif len( commands ) == 1:
            # There is exactly one match
            return commands[0][1]
        else:
            # There are more matches, choose the best one
            prefixes = dict( (expr.getPrefix(), cmd) for (expr, cmd) in commands )

            # This is the old approach, returning alphabetically first
            #return sorted(prefixes.items())[0][1]

            # Try to find longest possible exact match first:
            longest_name = commandName
            # If there is no space at the end, it is a parameter there
            if not longest_name.endswith(' '):
                # Strip parameter off
                longest_name = longest_name[:longest_name.rfind(" ")]
            else:
                longest_name = longest_name.rstrip(" ")

            cmd = None
            for _ in range(longest_name.count(" ") + 1):
                cmd = prefixes.get(longest_name+' ')
                if cmd:
                    print("Returning longest match: %s" % longest_name)
                    logging.debug("Longest match: '%s'", longest_name)
                    break
                longest_name = longest_name[:longest_name.rfind(" ")]

            return cmd

    def autoComplete( self, userText ):
        """
        Returns the best match it can find to userText, or None.
        """

        completions = []

        # Check each of the command factories for a match.
        for expr in self.__cmdFactoryDict.keys():
            if expr.matches( userText ):
                cmdFact = self.__cmdFactoryDict[expr]
                completion = cmdFact.autoComplete( userText )
                if completion != None:
                    completions.append( completion )

        if len( completions ) == 0:
            return None
        else:
            completions.sort( key = lambda a: a.toText() )
            return completions[0]

    def retrieveSuggestions( self, userText ):
        """
        Returns an unsorted list of suggestions.
        """

        suggestions = []
        # Extend the suggestions using each of the command factories
        for expr in self.__cmdFactoryDict.keys():
            if expr.matches( userText ):
                factory = self.__cmdFactoryDict[expr]
                suggestions += factory.retrieveSuggestions( userText )

        return suggestions

    def getCommands( self ):
        """
        Returns a dictionary of command expression strings and their
        associated implementations (command objects or factories).
        """

        # Get a dictionary form of the command object registry:
        cmdDict = self.__cmdObjReg.getDict()

        # Extend the dictionary to cover the command factories.
        for expr in list(self.__cmdFactoryDict.keys()):
            if expr == self.CMD_KEY:
                # This is the command object registry; pass.
                pass
            else:
                # Cast the expression as a string.
                cmdDict[ str(expr) ] = self.__cmdFactoryDict[expr]

        return cmdDict

# ----------------------------------------------------------------------------
# A CommandObject Registry
# ----------------------------------------------------------------------------

class CommandAlreadyRegisteredError( Exception ):
    """
    Error raised when someone tries to register two commands under
    the same name with the registry.
    """

    pass

class CommandObjectRegistry( GenericPrefixFactory ):
    """
    Class for efficiently storing and searching a large number of
    commands (where each command is an object with a corresponding
    command name).
    """

    PREFIX = ""

    # added to filter disabled commands
    NAME = "__commandObjectRegistry"

    def __init__( self ):
        """
        Initialize the command registry.
        """

        GenericPrefixFactory.__init__( self )

        self.__cmdObjDict = {}
        self.__dictTouched = False

    def update( self ):
        pass

    def getDict( self ):
        return self.__cmdObjDict

    def addCommandObj( self, command, cmdExpr ):
        """
        Adds command to the registry under the name str(cmdExpr).
        """

        assert isinstance( cmdExpr, CommandExpression ),\
            "addCommandObj(): cmdExpr arg is not CommandExpression type"
        assert not cmdExpr.hasArgument()

        cmdName = str(cmdExpr)
        if cmdName in self.__cmdObjDict:
            raise CommandAlreadyRegisteredError()

        self.__cmdObjDict[ cmdName ] = command
        self.__dictTouched = True

        self._addPostfix( cmdName )

    def removeCommandObj( self, cmdExpr ):
        cmdFound = False
        if cmdExpr in self.__cmdObjDict:
            del self.__cmdObjDict[cmdExpr]
            cmdFound = True
        if cmdFound:
            self.__dictTouched = True
            self._removePostfix( cmdExpr )
        else:
            raise RuntimeError( "Command object '%s' not found." % cmdExpr )

    def getCommandObj( self, cmdNameString ):
        """
        Returns the object corresponding to cmdNameString.

        NOTE: This will raise a KeyError if cmdNameString is not a
        valid command name.
        """

        try:
            return self.__cmdObjDict[ cmdNameString ]
        except KeyError:
            return None

if __name__ == "__main__":
    import doctest

    doctest.testmod()

# vim:set tabstop=4 shiftwidth=4 expandtab:


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

from pysignfe.xml_sped import *
from pysignfe.nfe.manifestacao_destinatario import ESQUEMA_ATUAL

#from pysignfe.nfe.manual_401 import cancnfe_evento as Evento
from pysignfe.nfe.manual_500.evento_base import DetEvento, InfEventoEnviado, Evento, EnvEvento, InfEventoRecebido, RetEvento, RetEnvEvento, ProcEventoNFe

import os
DIRNAME = os.path.dirname(__file__)

MD_CONFIRMACAO_OPERACAO     = u'210200'
MD_DESCONHECIMENTO_OPERACAO = u'210220'
MD_OPERACAO_NAO_REALIZADA   = u'210240'
MD_CIENCIA_OPERACAO         = u'210210'

MD_DESCEVENTO = {
    MD_CONFIRMACAO_OPERACAO: 'Confirmacao da Operacao',
    MD_CIENCIA_OPERACAO: 'Ciencia da Operacao',
    MD_DESCONHECIMENTO_OPERACAO: 'Desconhecimento da Operacao',
    MD_OPERACAO_NAO_REALIZADA: 'Operacao nao Realizada',
}

class DetEventoConfRecebimento(DetEvento):
    def __init__(self):
        super(DetEventoConfRecebimento, self).__init__()
        self.versao     = TagDecimal(nome=u'detEvento'  , codigo=u'HP18', propriedade=u'versao', valor=u'1.00', raiz=u'/')
        self.descEvento = TagCaracter(nome=u'descEvento', codigo=u'HP19', tamanho=[ 5,  60, 5], raiz=u'//infEvento/detEvento')
        self.xJust = TagCaracter(nome='xJust'  , codigo='HP20', tamanho=[15, 255]   , raiz='//detEvento', obrigatorio=False)

    def get_xml(self):
        xml = XMLNFe.get_xml(self)
        xml += self.versao.xml
        xml += self.descEvento.xml

        #
        # A justificativa só deve ser enviada no evento MD_OPERACAO_NAO_REALIZADA
        #
        if self.descEvento.valor == MD_DESCEVENTO[MD_OPERACAO_NAO_REALIZADA]:
            xml += self.xJust.xml

        xml += '</detEvento>'
        return xml

    def set_xml(self, arquivo):
        if self._le_xml(arquivo):
            self.versao.xml = arquivo
            self.descEvento.xml = arquivo
            self.xJust.xml = arquivo

    xml = property(get_xml, set_xml)

class InfEventoEnviadoConfRecebimento(InfEventoEnviado):
    def __init__(self):
        super(InfEventoEnviadoConfRecebimento, self).__init__()
        self.detEvento  = DetEventoConfRecebimento()

class EventoConfRecebimento(Evento):
    def __init__(self):
        super(EventoConfRecebimento, self).__init__()
        self.infEvento = InfEventoEnviadoConfRecebimento()
        self.caminho_esquema = os.path.join(DIRNAME, 'schema/', ESQUEMA_ATUAL + '/')
        self.arquivo_esquema = 'confRecebto_v1.00.xsd'

class  EnvEventoConfRecebimento(EnvEvento):
    def __init__(self):
        super(EnvEventoConfRecebimento, self).__init__()
        self.caminho_esquema = os.path.join(DIRNAME, u'schema/', ESQUEMA_ATUAL + u'/')
        self.arquivo_esquema = u'envConfRecebto_v1.00.xsd'

    def get_xml(self):
        xml = XMLNFe.get_xml(self)
        xml += ABERTURA
        xml += self.versao.xml
        xml += self.idLote.xml

        for ev in self.evento:
            xml += tira_abertura(ev.xml)

        xml += u'</envEvento>'

        return xml

    def set_xml(self, arquivo):
        if self._le_xml(arquivo):
            self.versao.xml = arquivo
            self.idLote.xml = arquivo
            self.evento     = self.le_grupo('//envEvento/evento', EventoConfRecebimento)

    xml = property(get_xml, set_xml)

class InfEventoRecebidoConfRecebimento(InfEventoRecebido):
    def __init__(self):
        super(InfEventoRecebidoConfRecebimento, self).__init__()

class RetEventoConfRecebimento(RetEvento):
    def __init__(self):
        super(RetEventoConfRecebimento, self).__init__()
        self.infEvento = InfEventoRecebidoConfRecebimento()

class RetEnvEventoConfRecebimento(RetEnvEvento):
    def __init__(self):
        super(RetEnvEventoConfRecebimento, self).__init__()
        self.caminho_esquema = os.path.join(DIRNAME, 'schema/', ESQUEMA_ATUAL + '/')
        self.arquivo_esquema = 'retEnvConfRecebto_v1.00.xsd'

    def get_xml(self):
        xml = XMLNFe.get_xml(self)

        xml += ABERTURA
        xml += self.versao.xml
        xml += self.idLote.xml
        xml += self.tpAmb.xml
        xml += self.verAplic.xml
        xml += self.cOrgao.xml
        xml += self.cStat.xml
        xml += self.xMotivo.xml

        for r in self.retEvento:
            xml += tira_abertura(r.xml)

        xml += u'</retEnvEvento>'

        return xml

    def set_xml(self, arquivo):
        if self._le_xml(arquivo):
            self.versao.xml = arquivo
            self.idLote.xml = arquivo
            self.tpAmb.xml = arquivo
            self.verAplic.xml = arquivo
            self.cOrgao.xml = arquivo
            self.cStat.xml = arquivo
            self.xMotivo.xml = arquivo
            self.retEvento = self.le_grupo('//retEnvEvento/retEvento', RetEventoConfRecebimento)

            # Monta o dicion?rio dos retornos
            for ret in self.retEvento:
                self.dic_retEvento[ret.infEvento.chNFe.valor] = ret

    xml = property(get_xml, set_xml)

class ProcEventoNFeConfRecebimento(ProcEventoNFe):
    def __init__(self):
        super(ProcEventoNFeConfRecebimento, self).__init__()
        self.evento = EventoConfRecebimento()
        self.retEvento = RetEventoConfRecebimento()
        self.caminho_esquema = os.path.join(DIRNAME, 'schema', ESQUEMA_ATUAL + '/')
        self.arquivo_esquema = 'procConfRecebtoNFe_v1.00.xsd'


from datetime import datetime, date

import pytz

def get_current_datetime():
    """
    Get the current datetime for America/Santiago
    :return: An datetime.Datetime object
    """
    tz = pytz.timezone("America/Santiago")
    dt = datetime.now(tz)
    return dt

def parse_day_to_date(day):
    """
    Parse a string day to datetime.Date
    :param day: An int that's represent a day
    :return: A datetime.Date object with the day parsed inside.
    """
    local_dt = get_current_datetime()
    current_day, current_month, current_year = (
        local_dt.day,
        local_dt.month,
        local_dt.year,
    )
    if day >= current_day:
        year, month = current_year, current_month
    elif day < current_day and current_month == 12:
        year, month = current_year + 1, 1
    else:
        year, month = current_year, current_month + 1
    return date(year=year, month=month, day=day)


#!/usr/bin/env python3

import paho.mqtt.client as mqtt
import sys,json, re, datetime

mqttServerAddress = "10.1.1.50" #e.g piserver.local or 192.168.1.100

def main():
    # Create an MQTT client and attach our routines to it.
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message

    client.connect(mqttServerAddress, 1883, 60)

    # Process network traffic and dispatch callbacks. This will also handle
    # reconnecting. Check the documentation at
    # https://github.com/eclipse/paho.mqtt.python
    # for information on how to use other loop*() functions
    client.loop_forever()

# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))

    # Subscribing in on_connect() - if we lose the connection and
    # reconnect then subscriptions will be renewed.
    # client.subscribe("#")  # subscribe to ALL MQTT topics
    client.subscribe("lego/#")

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    # print all messages that are subscribed to
    print(str(datetime.datetime.now()) +" "+msg.topic+" "+str(msg.payload))

main()


from Jumpscale import j

class ZDBAdminClientBase:
    def auth(self):
        assert self.admin
        if self.secret_:
            # authentication should only happen in zdbadmin client
            self._log_debug("AUTH in namespace %s" % (self.nsname))
            self.redis.execute_command("AUTH", self.secret_)

    def namespace_exists(self, name):
        assert self.admin
        self.auth()
        try:
            self.redis.execute_command("NSINFO", name)
            # self._log_debug("namespace_exists:%s" % name)
            return True
        except Exception as e:
            if not "Namespace not found" in str(e):
                raise j.exceptions.Base("could not check namespace:%s, error:%s" % (name, e))
            # self._log_debug("namespace_NOTexists:%s" % name)
            return False

    def namespaces_list(self):
        assert self.admin
        self.auth()
        res = self.redis.execute_command("NSLIST")
        return [i.decode() for i in res]

    def namespace_new(self, name, secret=None, maxsize=0, die=False):
        """
        check namespace exists & will return zdb client to that namespace

        :param name:
        :param secret:
        :param maxsize:
        :param die:
        :return:
        """
        assert self.admin
        self.auth()
        self._log_debug("namespace_new:%s" % name)
        if not self.namespace_exists(name):
            self._log_debug("namespace does not exists")
            self.redis.execute_command("NSNEW", name)
        else:
            if die:
                raise j.exceptions.Base("namespace already exists:%s" % name)

        if secret:
            self._log_debug("set secret")
            self.redis.execute_command("NSSET", name, "password", secret)
            self.redis.execute_command("NSSET", name, "public", "no")

        if maxsize is not 0:
            self._log_debug("set maxsize")
            self.redis.execute_command("NSSET", name, "maxsize", maxsize)

        self._log_debug("connect client")

        ns = j.clients.zdb.client_get(
            name="temp_%s" % name, addr=self.addr, port=self.port, mode=self.mode, secret=secret, namespace=name
        )

        assert ns.ping()
        if secret:
            assert ns.nsinfo["public"] == "no"
        else:
            assert ns.nsinfo["public"] == "yes"

        ns._data.delete()
        return ns

    def namespace_get(self, name, secret=""):
        assert self.admin
        self.auth()
        return self.namespace_new(name, secret)

    def namespace_delete(self, name):
        assert self.admin
        self.auth()
        if self.namespace_exists(name):
            self._log_debug("namespace_delete:%s" % name)
            self.redis.execute_command("NSDEL", name)

    def reset(self, ignore=[]):
        """
        dangerous, will remove all namespaces & all data
        :param: list of namespace names not to reset
        :return:
        """
        assert self.admin
        self.auth()
        for name in self.namespaces_list():
            if name not in ["default"] and name not in ignore:
                self.namespace_delete(name)


import h5py as hp
import numpy as np

from typing import List, Tuple, Dict, Any
from pathlib import Path

from yoyo66.handler import BaseFileHandler, mmfile_handler
from yoyo66.datastruct import phmImage, Layer, create_image

@mmfile_handler('h5', ['h5'])
class H5FileHandler(BaseFileHandler):

    __H5_FILEEXTENSION = '.h5'
    __PROP_PREFIX = 'prop_'
    __METRICS_PREFIX = 'metric_'
    __LAYERS_KEY = 'layers'
    __ORIG_KEY = 'original'

    def __init__(self, filter: List[str] = None) -> None:
        super().__init__(filter)

    def __read_metadata(self, handler) -> Tuple[Dict, Dict]:
        metrics = {}
        props = {}
        for k, v in handler.attrs.items():
            if k.startswith(self.__PROP_PREFIX):
                key = k.replace(self.__PROP_PREFIX, '')
                props[key] = v
            elif k.startswith(self.__METRICS_PREFIX):
                key = k.replace(self.__METRICS_PREFIX, '')
                metrics[key] = v

        return props, metrics

    def __write_metadata(self, handler,
        metrics : Dict[str, Any],
        props : Dict[str, Any]
    ):
        # Write the metrics
        for k, v in props.items():
            handler.attrs[f'{self.__PROP_PREFIX}{k}'] = v
        for k, v in metrics.items():
            handler.attrs[f'{self.__METRICS_PREFIX}{k}'] = v

    def __layer_path(self, clss : str):
        return f'{self.__LAYERS_KEY}/{clss}'

    def load(self, filepath: str, only_imgs : bool = False) -> phmImage:
        # Argument initialization and checking
        if not Path(filepath).is_file():
            raise ValueError(message=f'The file ({filepath}) does not exist!')
        if not filepath.endswith(self.__H5_FILEEXTENSION):
            raise ValueError(message=f'The file format ({filepath}) is not supported!')
        #####################
        img = None
        with hp.File(filepath, mode = 'r') as fin:
            # Load metrics and properties
            props = metrics = {}
            if not only_imgs:
                props, metrics = self.__read_metadata(fin)
            # Load original layer
            if not self.__ORIG_KEY in fin.keys():
                raise KeyError('original layer is missing!')
            orig = np.array(fin[self.__ORIG_KEY])
            # Load mask layers
            layers = []
            layers_group = fin[self.__LAYERS_KEY]
            for layer_name in layers_group.keys():
                class_id = self.init_class_id(layer_name)
                if class_id is None:
                    continue
                layer = np.array(layers_group[layer_name])
                layers.append(Layer(
                    name = layer_name,
                    class_id = class_id,
                    image = layer
                ))
            img = phmImage(
                filepath = filepath,
                properties = props,
                metrics = metrics,
                orig_image = orig,
                layers = layers
            )

        return img

    def save(self, img: phmImage, filepath: str):
        with hp.File(filepath, mode = 'w') as fout:
            # Write the metrics and properties
            self.__write_metadata(fout, img.metrics, img.properties)
            # Write the original image
            orig = img.orig_layer.image
            fout.create_dataset(
                name = self.__ORIG_KEY,
                shape = orig.shape,
                dtype = orig.dtype,
                compression = 'gzip',
                compression_opts = 9,
                data = orig
            )
            # Write the layers
            for layer in img.layers:
                lname = layer.name
                limg = create_image(layer)
                limg = np.array(limg)
                fout.create_dataset(
                    name = self.__layer_path(lname),
                    shape = limg.shape,
                    dtype = limg.dtype,
                    data = limg,
                    compression = 'gzip',
                    compression_opts = 9,
                )


import pygame
import os
from Item import *
from PIL import Image

def load_reasource(mapfilename):
    map_list = []
    img = Image.open(os.path.join("assets", mapfilename)).convert('RGB')

    imgpxls = img.load()

    for i in range(img.size[1]):
        map_list.append([])

    player_pos = (0, 0)

    for x in range(img.size[0]):
        for y in range(img.size[1]):
            r, g, b = imgpxls[x, y]
            if r == 255 and g == 255 and b == 255:
                map_list[y].append(0)
            elif r == 100 and g == 100 and b == 100:
                map_list[y].append(2)
            elif r == 0 and g == 0 and b == 255:
                map_list[y].append('player')
                player_pos = (x, y)
            else:
                map_list[y].append(1)

    resource = []

    for y in range(len(map_list)):
        for x in range(len(map_list[y])):
            if map_list[y][x] == 1:
                resource.append(('bright', x - player_pos[0], y - player_pos[1]))
            elif map_list[y][x] == 2:
                resource.append(('dim', x - player_pos[0], y - player_pos[1]))
            else:
                pass
    # print(resource)
    return resource

class Character:
    def __init__(self, asset, health, inventory=None):
        self.x = 1
        self.y = 1
        self.asset = pygame.image.load(os.path.join("assets", asset))
        self.health = health
        self.default_resource = load_reasource("default_rad.png")
        if inventory is None:
            self.inventory = {'item': Torch(), 'magic': None, 'weapon': None, 'armour': None}
        else:
            self.inventory = inventory

    def move_right(self, num):
        self.x += num

    def move_up(self, num):
        self.y += num


class Solution:
    def maxDistance(self, colors: List[int]) -> int:  # 13.32% 68.15 %
        n = len(colors)
        res = 0
        for i in range(n-1):
            for j in range(i+1, n):
                if colors[i] != colors[j]:
                    res = max(res, j-i)
        return res

    def maxDistance_v2(self, colors: List[int]) -> int:  # 96.16% 23.31%
        n = len(colors)
        res = 0
        i, j = 0, n-1
        while colors[i] == colors[j]:
            i += 1
        res = max(res, j-i)
        i = 0
        while colors[i] == colors[j]:
            j -= 1
        res = max(res, j-i)
        return res

    def maxDistance_best_speed(self, colors: List[int]) -> int:
        left, right = 0, len(colors) - 1
        if colors[left] != colors[right]:
            return len(colors) - 1
        for i in range(len(colors)):
            if colors[i] != colors[right]:
                break
        for j in range(len(colors)-1, -1, -1):
            if colors[j] != colors[left]:
                break
        return max(j, right - i)

    def maxDistance_best_memory(self, colors: List[int]) -> int:
        max_distance = 0
        for i in range(len(colors)):
            for j in range(1, len(colors)):
                if colors[i] != colors[j]:
                    distance = abs(j-i)
                    max_distance = max(max_distance, distance)
        return max_distance

2000 - 2099/2078 - Two Furthest Houses With Different Colors/2078 - Two Furthest Houses With Different Colors.py


# File: coin_changing.py
# COIN CHANGING PROBLEMS.

import sys
import time

sys.setrecursionlimit(1000000)

# Some coin systems:

lecture_coins = [1, 5, 7]

sterling_coins = [1, 2, 5, 10, 20, 50, 100, 200]

# Problem (1): Minimum number of coins (as in Lecture 17).

c_list = lecture_coins  # global variable, can set as desired

# Plain recursive implementation.
# fewest_coins should be implemented recursively, returning just smallest number of coins.

def fewest_coins(v: int) -> int:
    if v in c_list:
        return 1
    return 1 + min(fewest_coins(v - c_i) for c_i in c_list if c_i < v)

# slightly different method which returns a list of actual coins (which constitute a
# minimum-sized solution).

def fewest_coins_list(v: int) -> "list[int]":
    if v in c_list:
        return [v]
    return min(
        ([c_i] + fewest_coins_list(v - c_i) for c_i in c_list if c_i < v), key=len
    )

# Memoization operation, exactly as in our lecture:

def memoize(f):
    memo = {}

    def check(v):
        if v not in memo:
            memo[v] = f(v)
        return memo[v]

    return check

# memoize : (int->int) -> (int->int)
# f : int->int,  check : int->int

# To get the optimization of the recursion:

#   fewest_coins = memoize(fewest_coins)
#   fewest_coins_list = memoize(fewest_coins_list)

# NB. Can't change c_list after doing this!
# We would need to reload the file within the Python interpreter to use with new c_list.

# You should also implement and experiment with a dynamic programming solution,
# as given towards the end of slide-set 17.

INF = 1_000_000_000

def fewest_coins_dp(v):
    k = len(c_list)
    c = c_list  #
    C = [INF for _ in range(v + 1)]
    P = [INF for _ in range(v + 1)]
    C[0] = 0
    for w in range(1, v + 1):
        for i in range(1, k):
            if c[i] <= w and (C[w - c[i]] + 1) < C[w]:
                C[w] = 1 + C[w - c[i]]
                P[w] = i
    return C[v]

def fewest_coins_list_dp(v):
    k = len(c_list)
    c = c_list
    S = [0 for _ in range(k)]
    C = [INF for _ in range(v + 1)]
    P = [INF for _ in range(v + 1)]
    C[0] = 0
    for w in range(1, v + 1):
        for i in range(k):
            if c[i] <= w and (C[w - c[i]] + 1) < C[w]:
                C[w] = 1 + C[w - c[i]]
                P[w] = i
    while v > 0:
        i = P[v]
        S[i] = S[i] + 1
        v = v - c[i]
    return S

def fewest_coins_list_dp_traced(v):
    k = len(c_list)
    c = c_list
    S = [0 for _ in range(k)]
    # fewest coins needed for each v
    C = [INF for _ in range(v + 1)]
    # which coin is added here last (from this we can also find which cell in C is the predecessor of the corresponding cell in C)
    P = [INF for _ in range(v + 1)]
    C[0] = 0
    for w in range(1, v + 1):
        for i in range(k):
            if c[i] <= w and (C[w - c[i]] + 1) < C[w]:
                C[w] = 1 + C[w - c[i]]
                P[w] = i
                # the first cells of C and P are insignificant; only there to make the indexing nicer
                print("C", C)
                print("P", P)
    temp = v  # stores the quantity
    while v > 0:
        i = P[v]
        S[i] = S[i] + 1
        v = v - c[i]
    print("C", C[1:])
    print("P", P[1:])
    return S

if __name__ == "__main__":
    small_target = 50
    medium_target = 2_500
    target = 10_000_000
    start = time.time()
    sol = fewest_coins(small_target)
    print(f"naive counting {small_target} takes {time.time() - start:.2f} seconds.")
    print(f" ==> {sol} coins are needed.")
    # start = time.time()
    # print(fewest_coins_list(small_target))
    # print(f"naive listing {small_target} takes {time.time() - start:.2f} seconds.")

    fewest_coins = memoize(fewest_coins)
    # fewest_coins_list = memoize(fewest_coins_list)

    # start = time.time()
    # sol = fewest_coins(medium_target)
    # print(f"memoised counting {medium_target} takes {time.time() - start:.2f} seconds.")
    # print(f" ==> {sol} coins are needed.")
    # start = time.time()
    # print(fewest_coins_list(medium_target))
    # print(f"memoised listing {medium_target} takes {time.time() - start:.2f} seconds.")

    # start = time.time()
    # sol = fewest_coins_dp(target)
    # print(
    #     f"dynamic programming counting {target} takes {time.time() - start:.2f} seconds."
    # )
    # print(f" ==> {sol} coins are needed.")
    # start = time.time()
    # print(fewest_coins_list_dp(target))
    # print(f"dynamic programming listing {target} takes {time.time() - start:.2f} seconds.")

    start = time.time()
    sol = fewest_coins_list_dp_traced(small_target)
    print(
        f"dynamic programming counting {small_target} takes {time.time() - start:.2f} seconds."
    )
    print(f" ==> {sol} coins are needed.")


import re
import os
import sys
os.chdir("/Users/likaixuan/Documents/IBI1_2020-21/IBI1_2020-21/Practical8\\via")
file1 = open('Saccharomyces_cerevisiae.R64-1-1.cdna.all.fa','r')
file2 = open('unknown_function.fa','w')
line = next(file1,'0')
while True:
    if line.startswith('>'):
        if re.search(r'unknow function',line):
            m = re.findall(r'>(\S+)_',line)
            s = ''

            while True:
                line = next(file1,'0')
                if line.startswith('>') or (line == '0'):
                    break
                line1 = line.replace('\n','')
                s = s + line1
            f = ">>"+m[0]
            file2.write(f'{f:14}')
            file2.write(str(int(len(s))))
            file2.write('\n')
            file2.write(s)
            file2.write('\n')

    if line == '0':
        break
    line = next(file1,'0')
    file1.close()
    file2.close()


from collections import defaultdict
from heapq import heappop, heappush

class Solution:
    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        m, n = len(heights), len(heights[0])
        dist = defaultdict(lambda: defaultdict(lambda: float('inf')))

        for i in range(m*n):
            dist[i][i] = 0

        for i in range(m):
            for j in range(n):
                if i-1 >= 0:
                    dist[i*n+j][(i-1)*n+j] = abs(heights[i][j]-heights[i-1][j])
                    dist[(i-1)*n+j][i*n+j] = abs(heights[i][j]-heights[i-1][j])
                if i+1 < m:
                    dist[i*n+j][(i+1)*n+j] = abs(heights[i][j]-heights[i+1][j])
                    dist[(i+1)*n+j][i*n+j] = abs(heights[i][j]-heights[i+1][j])
                if j-1 >= 0:
                    dist[i*n+j][i*n+j-1] = abs(heights[i][j]-heights[i][j-1])
                    dist[i*n+j-1][i*n+j] = abs(heights[i][j]-heights[i][j-1])
                if j+1 < n:
                    dist[i*n+j][i*n+j+1] = abs(heights[i][j]-heights[i][j+1])
                    dist[i*n+j+1][i*n+j] = abs(heights[i][j]-heights[i][j+1])

        curr = (0, 0)
        pq = [(0, 0)]
        visited = set()
        while len(visited) < m*n:
            while curr[1] in visited:
                curr = heappop(pq)
            visited.add(curr[1])
            dist[0][curr[1]] = curr[0]
            for node in dist[curr[1]]:
                if node not in visited:
                    heappush(pq, (max(curr[0], dist[curr[1]][node]), node))

        return dist[0][m*n-1]


import string

files = ['./dataset/train.txt', './dataset/test.txt']
pfiles = ['./files/train.txt', './files/test.txt']

for k in range(len(files)):
	with open(files[k], 'r') as in_file:
		with open(pfiles[k], 'a') as out_file:
			data = in_file.readlines()
			for i in range(len(data)):
				splits = data[i].split('\t')
				if len(splits)==2:
					sentence = ' ' + splits[1] + ' '
					for ch in range(len(sentence)):
						if sentence[ch] == '<' and sentence[ch-1] != ' ':
							sentence = sentence[:ch] + ' ' + sentence[ch:]
						if sentence[ch] == '>' and sentence[ch+1] != ' ':
							sentence = sentence[:ch+1] + ' ' + sentence[ch+1:]

					label = data[i+1].strip()
					tokens = sentence.strip().split()

					for j in range(len(tokens)):
						tokens[j] = tokens[j].replace('<e1>',' <e1s> ')
						tokens[j] = tokens[j].replace('</e1>',' <e1e> ')
						tokens[j] = tokens[j].replace('<e2>',' <e2s> ')
						tokens[j] = tokens[j].replace('</e2>',' <e2e> ')

						tokens[j] = tokens[j].translate(None, string.punctuation)

						tokens[j] = tokens[j].replace('e1s','<e1s>')
						tokens[j] = tokens[j].replace('e1e','<e1e>')
						tokens[j] = tokens[j].replace('e2s','<e2s>')
						tokens[j] = tokens[j].replace('e2e','<e2e>')

					sentence = ' '.join(tokens)
					sentence = sentence.replace('    ',' ')
					sentence = sentence.replace('  ',' ')
					sentence = sentence.replace('  ',' ')

					final = label + '\t' + sentence + '\n'
					out_file.write(final)

	print("Succesfully created " + pfiles[k])


import errno

try:
    s = open("c:/users/user/Desktop/file.txt", "rt")
    # Processing goes here.
    s.close()
except Exception as exc:
    if exc.errno == errno.ENOENT:
        print("File does not exist.")
    elif exc.errno == errno.EMFILE:
        print("Too many open files.")
    else:
        print("The error number is:", exc.errno)


import vsketch
import numpy as np
import iso

# Ideas:
# - isometric grid with towers, bridges, slopes etc.
# - 3d tubes using circles

class RandomIsoSketch(vsketch.SketchClass):

    draw_axes = vsketch.Param(False)
    draw_grid = vsketch.Param(False)
    draw_debug = vsketch.Param(False)

    def draw(self, vsk: vsketch.Vsketch) -> None:
        vsk.size("a4", landscape=False)
        vsk.scale("cm")

        # DO NO OCCULT THINGS HERE

        if self.draw_axes: iso.draw_axes(vsk, x_axis_length=7, y_axis_length=7)
        if self.draw_grid: iso.draw_grid(vsk, x_size=6, y_size=6)

        # shape_0 = isoShape(2, 1, 0, 2, 1, 2)
        # shape_1 = isoShape(1, 2, 0, 3, 1, 1)
        # shape_2 = isoShape(1, 4, 0, 1, 1, 1)
        # shape_3 = isoShape(2, 3, 0, 1, 2, 1)
        # shapes = [shape_0, shape_1, shape_2, shape_3]
        # random.shuffle(shapes)

        N = 50
        draw_order = None
        while draw_order is None:  # this is really bad, but a quick way to avoid the occasional cycle
            try:
                shapes = []
                for i in range(N):
                    x = np.random.uniform(0, 10)
                    y = np.random.uniform(0, 10)
                    z = np.random.uniform(0, 19)
                    x_size = np.random.uniform(0.25, 3.0)
                    y_size = np.random.uniform(0.25, 3.0)
                    z_size = np.random.uniform(0.25, 3.0)
                    shapes.append(iso.isoShape(x, y, z, x_size, y_size, z_size))

                draw_order = iso.get_draw_order(shapes)
            except:
                pass

        for i in draw_order:
            shapes[i].draw(vsk, dx_shade=0.15, dy_shade=0.075)
            if self.draw_debug: shapes[i].draw_debug(vsk, offset=0.2*i)

        vsk.vpype("occult -i")

    def finalize(self, vsk: vsketch.Vsketch) -> None:
        vsk.vpype("linemerge linesimplify reloop linesort")

if __name__ == "__main__":
    RandomIsoSketch.display()


from typing import Optional, Tuple, Union
import enum
import warnings
import torch
from .base import Manifold
from .. import linalg

__all__ = ["SymmetricPositiveDefinite"]

EPS = {torch.float32: 1e-4, torch.float64: 1e-7}

class SPDMetric(enum.Enum):
    AIM = "AIM"
    SM = "SM"
    LEM = "LEM"

class SymmetricPositiveDefinite(Manifold):
    r"""Manifold of symmetric positive definite matrices.

    .. math::

        A = A^T\\
        \langle x, A x \rangle > 0 \quad , \forall x \in \mathrm{R}^{n}, x \neq 0 \\
        A \in \mathrm{R}^{n\times m}

    The tangent space of the manifold contains all symmetric matrices.

    References
    ----------
    - https://github.com/pymanopt/pymanopt/blob/master/pymanopt/manifolds/psd.py
    - https://github.com/dalab/matrix-manifolds/blob/master/graphembed/graphembed/manifolds/spd.py

    Parameters
    ----------
    default_metric: Union[str, SPDMetric]
        one of AIM, SM, LEM. So far only AIM is fully implemented.
    """

    __scaling__ = Manifold.__scaling__.copy()
    name = "SymmetricPositiveDefinite"
    ndim = 2
    reversible = False

    def __init__(self, default_metric: Union[str, SPDMetric] = "AIM"):
        super().__init__()
        self.default_metric = SPDMetric(default_metric)
        if self.default_metric != SPDMetric.AIM:
            warnings.warn(
                "{} is not fully implemented and results may be not as you expect".format(
                    self.default_metric
                )
            )

    _dist_doc = """
        Parameters
        ----------
        x : torch.Tensor
            point on the manifold
        y : torch.Tensor
            point on the manifold
        keepdim : bool
            keep the last dim?

        Returns
        -------
        torch.Tensor
            distance between two points
        """

    def _affine_invariant_metric(
        self, x: torch.Tensor, y: torch.Tensor, keepdim=False
    ) -> torch.Tensor:
        r"""Affine Invariant Metric distance.

        {}

        References
        ----------
        A Riemannian framework for tensor computing. 2006.
        """.format(
            self._dist_doc
        )
        inv_sqrt_x = linalg.sym_inv_sqrtm1(x)
        return torch.norm(
            linalg.sym_logm(inv_sqrt_x @ y @ inv_sqrt_x),
            dim=[-1, -2],
            keepdim=keepdim,
        )

    def _stein_metric(
        self, x: torch.Tensor, y: torch.Tensor, keepdim=False
    ) -> torch.Tensor:
        r"""Stein Metric distance.

        {}

        References
        ----------
        A new metric on the manifold of kernel matrices with application to matrix geometric means. 2012.
        """.format(
            self._dist_doc
        )

        def log_det(tensor: torch.Tensor) -> torch.Tensor:
            return torch.log(torch.det(tensor))

        ret = log_det((x + y) * 0.5) - 0.5 * log_det(x @ y)
        if keepdim:
            return torch.unsqueeze(torch.unsqueeze(ret, -1), -1)
        return ret

    def _log_eucliden_metric(
        self, x: torch.Tensor, y: torch.Tensor, keepdim=False
    ) -> torch.Tensor:
        r"""Log-Eucliden Metric distance.

        {}

        References
        ----------
        Log‐Euclidean metrics for fast and simple calculus on diffusion tensors. 2006.
        """.format(
            self._dist_doc
        )
        return torch.norm(
            linalg.sym_logm(x) - linalg.sym_logm(y),
            dim=[-1, -2],
            keepdim=keepdim,
        )

    def _check_point_on_manifold(
        self, x: torch.Tensor, *, atol=1e-5, rtol=1e-5
    ) -> Union[Tuple[bool, Optional[str]], bool]:
        ok = torch.allclose(x, x.transpose(-1, -2), atol=atol, rtol=rtol)
        if not ok:
            return False, "`x != x.transpose` with atol={}, rtol={}".format(atol, rtol)
        e, _ = torch.linalg.eigh(x, "U")
        ok = (e > -atol).min()
        if not ok:
            return False, "eigenvalues of x are not all greater than 0."
        return True, None

    def _check_vector_on_tangent(
        self, x: torch.Tensor, u: torch.Tensor, *, atol=1e-5, rtol=1e-5
    ) -> Union[Tuple[bool, Optional[str]], bool]:
        ok = torch.allclose(u, u.transpose(-1, -2), atol=atol, rtol=rtol)
        if not ok:
            return False, "`u != u.transpose` with atol={}, rtol={}".format(atol, rtol)
        return True, None

    def projx(self, x: torch.Tensor) -> torch.Tensor:
        symx = linalg.sym(x)
        return linalg.sym_funcm(symx, torch.abs)

    def proju(self, x: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
        return linalg.sym(u)

    def egrad2rgrad(self, x: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
        return x @ self.proju(x, u) @ x.transpose(-1, -2)

    _dist_metric = {
        SPDMetric.AIM: _affine_invariant_metric,
        SPDMetric.SM: _stein_metric,
        SPDMetric.LEM: _log_eucliden_metric,
    }

    def dist(
        self,
        x: torch.Tensor,
        y: torch.Tensor,
        keepdim=False,
    ) -> torch.Tensor:
        """Compute distance between 2 points on the manifold that is the shortest path along geodesics.

        Parameters
        ----------
        x : torch.Tensor
            point on the manifold
        y : torch.Tensor
            point on the manifold
        keepdim : bool, optional
            keep the last dim?, by default False

        Returns
        -------
        torch.Tensor
            distance between two points

        Raises
        ------
        ValueError
            if `mode` isn't in `_dist_metric`
        """
        return self._dist_metric[self.default_metric](self, x, y, keepdim=keepdim)

    def inner(
        self,
        x: torch.Tensor,
        u: torch.Tensor,
        v: Optional[torch.Tensor] = None,
        keepdim=False,
    ) -> torch.Tensor:
        """
        Inner product for tangent vectors at point :math:`x`.

        Parameters
        ----------
        x : torch.Tensor
            point on the manifold
        u : torch.Tensor
            tangent vector at point :math:`x`
        v : Optional[torch.Tensor]
            tangent vector at point :math:`x`
        keepdim : bool
            keep the last dim?

        Returns
        -------
        torch.Tensor
            inner product (broadcasted)

        Raises
        ------
        ValueError
            if `keepdim` sine `torch.trace` doesn't support keepdim
        """
        if v is None:
            v = u
        inv_x = linalg.sym_invm(x)
        ret = linalg.trace(inv_x @ u @ inv_x @ v)
        if keepdim:
            return torch.unsqueeze(torch.unsqueeze(ret, -1), -1)
        return ret

    def retr(self, x: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
        inv_x = linalg.sym_invm(x)
        return linalg.sym(x + u + 0.5 * u @ inv_x @ u)

    def expmap(self, x: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
        inv_sqrt_x, sqrt_x = linalg.sym_inv_sqrtm2(x)
        return sqrt_x @ linalg.sym_expm(inv_sqrt_x @ u @ inv_sqrt_x) @ sqrt_x

    def logmap(self, x: torch.Tensor, u: torch.Tensor) -> torch.Tensor:
        inv_sqrt_x, sqrt_x = linalg.sym_inv_sqrtm2(x)
        return sqrt_x @ linalg.sym_logm(inv_sqrt_x @ u @ inv_sqrt_x) @ sqrt_x

    def extra_repr(self) -> str:
        return "default_metric={}".format(self.default_metric)

    def transp(self, x: torch.Tensor, y: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
        inv_sqrt_x, sqrt_x = linalg.sym_inv_sqrtm2(x)
        exp_x_y = linalg.sym_expm(0.5 * linalg.sym_logm(inv_sqrt_x @ y @ inv_sqrt_x))
        return (
            sqrt_x
            @ exp_x_y
            @ linalg.sym(inv_sqrt_x @ v @ inv_sqrt_x)
            @ exp_x_y
            @ sqrt_x
        )

    def random(self, *size, dtype=None, device=None, **kwargs) -> torch.Tensor:
        tens = 0.5 * torch.randn(*size, dtype=dtype, device=device)
        tens = linalg.sym(tens)
        tens = linalg.sym_funcm(tens, torch.exp)
        return tens

    def origin(
        self,
        *size: Union[int, Tuple[int]],
        dtype=None,
        device=None,
        seed: Optional[int] = 42,
    ) -> torch.Tensor:
        return torch.diag_embed(torch.ones(*size[:-1], dtype=dtype, device=device))


#Напишите программу, которая позволяет считывать из файла вопрос, отвечать на него и отправлять ответ обратно пользователю

import telebot

token = "*********"
bot = telebot.TeleBot(token)

@bot.message_handler(commands=['start', 'help'])
def send_welcome(message):
	bot.reply_to(message,"Привет, чем могу помочь?")

@bot.message_handler(content_types=['text'])
def user_message(message):
    cur_id = str(message.from_user.id)
    data = open('first.text', 'w', encoding = 'utf-8')
    text = f'{cur_id}: {message.text}'
    data.writelines(f'{text}\n')
    data.close()
    data = open('first.text', 'r', encoding = 'utf-8')
    registration_list = data.readlines()
    data.close()
    for id in registration_list:
        print(id)
        answer = input('Введите ответ пользователю: ')
        bot.reply_to(message, answer)

bot.infinity_polling()


from __future__ import annotations
from dataclasses import dataclass
from typing import ClassVar, AsyncContextManager, ByteString
from struct import unpack as struct_unpack, pack as struct_pack
from contextlib import asynccontextmanager

from rpc.connection import Connection as RPCConnection
from ndr.structures.conformant_varying_string import ConformantVaryingString
from rpc.utils.client_protocol_message import ClientProtocolRequestBase, ClientProtocolResponseBase, obtain_response, \
    Win32ErrorCode
from ndr.utils import pad as ndr_pad

from ms_scmr.operations import Operation
from ms_scmr.operations.r_close_service_handle import r_close_service_handle, RCloseServiceHandleRequest
from ms_scmr.structures.service_access import ServiceAccessFlagMask

@dataclass
class ROpenServiceWRequest(ClientProtocolRequestBase):
    OPERATION: ClassVar[Operation] = Operation.R_OPEN_SERVICE_W

    sc_manager_handle: bytes
    service_name: str
    desired_access: ServiceAccessFlagMask

    @classmethod
    def from_bytes(cls, data: ByteString | memoryview) -> ROpenServiceWRequest:

        sc_manager_handle = data[:20]
        offset = 20

        service_name = ConformantVaryingString.from_bytes(data=data[offset:])
        service_name_len: int = len(service_name)
        offset += service_name_len + ((4 - (service_name_len % 4)) % 4)

        desired_access = ServiceAccessFlagMask.from_int(struct_unpack('<I', data[offset:offset+4])[0])

        return cls(
            sc_manager_handle=sc_manager_handle,
            service_name=service_name.representation,
            desired_access=desired_access
        )

    def __bytes__(self) -> bytes:

        service_name_bytes = bytes(ConformantVaryingString(representation=self.service_name))

        return b''.join([
            self.sc_manager_handle,
            ndr_pad(service_name_bytes),
            struct_pack('<I', int(self.desired_access))
        ])

@dataclass
class ROpenServiceWResponse(ClientProtocolResponseBase):
    service_handle: bytes

    @classmethod
    def from_bytes(cls, data: ByteString | memoryview) -> ROpenServiceWResponse:
        return cls(
            service_handle=data[:20],
            return_code=Win32ErrorCode(struct_unpack('<I', data[20:24])[0])
        )

    def __bytes__(self) -> bytes:
        return self.service_handle + struct_pack('<I', self.return_code.value)

ROpenServiceWResponse.REQUEST_CLASS = ROpenServiceWRequest
ROpenServiceWRequest.RESPONSE_CLASS = ROpenServiceWResponse

@asynccontextmanager
async def r_open_service_w(
    rpc_connection: RPCConnection,
    request: ROpenServiceWRequest,
    raise_exception: bool = True
) -> AsyncContextManager[ROpenServiceWResponse]:
    """
    Perform the ROpenServiceW operation.

    :param rpc_connection:
    :param request:
    :param raise_exception:
    :return:
    """

    r_open_service_w_response: ROpenServiceWResponse = await obtain_response(
        rpc_connection=rpc_connection,
        request=request,
        raise_exception=raise_exception
    )

    yield r_open_service_w_response

    await r_close_service_handle(
        rpc_connection=rpc_connection,
        request=RCloseServiceHandleRequest(
            service_handle=r_open_service_w_response.service_handle
        )
    )


from pytorch_lightning.utilities.types import TRAIN_DATALOADERS, EVAL_DATALOADERS
from torch.utils.data import random_split, Dataset, DataLoader
from torchvision.datasets import OxfordIIITPet
import torchvision.transforms as T

import pytorch_lightning as pl

def decrement_mask_squeeze(x):
    return (x - 1).squeeze()

class OxfordDataModule(pl.LightningDataModule):
    def __init__(self, data_dir, comp_name: str = 'oxford', image_size: int = 128, batch_size: int = 1024,
                 downsample_n: int = 1000, validation_split: float = 0.2,
                 num_workers: int = 2, pin_memory: bool = True):
        super().__init__()
        self.save_hyperparameters()

        # Define the image and mask transforms
        self.image_transform = T.Compose([
            T.Resize((self.hparams.image_size, self.hparams.image_size)),
            T.ToTensor()
        ])
        self.mask_transform = T.Compose([
            T.Resize((self.hparams.image_size, self.hparams.image_size)),
            T.PILToTensor(),
            T.Lambda(decrement_mask_squeeze)
        ])

        self.train_dataset: Dataset = None
        self.val_dataset: Dataset = None
        self.test_dataset: Dataset = None

    def prepare_data(self) -> None:
        # Just download the OxFord III Pet Dataset
        OxfordIIITPet(root=self.hparams.data_dir, target_types='segmentation', download=True,
                      transform=self.image_transform, target_transform=self.mask_transform)
        OxfordIIITPet(root=self.hparams.data_dir, target_types='segmentation', download=True, split='test',
                      transform=self.image_transform, target_transform=self.mask_transform)

    def setup(self, stage: str) -> None:
        # Assign training and validation based on stage.
        if stage == 'fit' or stage is None:
            oxford_full = OxfordIIITPet(root=self.hparams.data_dir, target_types='segmentation', download=True,
                                        transform=self.image_transform, target_transform=self.mask_transform)
            # Cut down some more if downsample is positive
            if self.hparams.downsample_n != -1:
                oxford_full, _ = random_split(oxford_full, lengths=[self.hparams.downsample_n,
                                                                    len(oxford_full) - self.hparams.downsample_n])
            self.train_dataset, self.val_dataset = random_split(oxford_full, lengths=[0.8, 0.2])
        if stage == 'test' or stage is None:
            self.test_dataset = OxfordIIITPet(root=self.hparams.data_dir, target_types='segmentation',
                                              download=True, split='test',
                                              transform=self.image_transform, target_transform=self.mask_transform)

    def train_dataloader(self) -> TRAIN_DATALOADERS:
        return DataLoader(self.train_dataset, batch_size=self.hparams.batch_size, shuffle=True,
                          num_workers=self.hparams.num_workers, pin_memory=self.hparams.pin_memory)

    def val_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.val_dataset, batch_size=self.hparams.batch_size, num_workers=self.hparams.num_workers,
                          pin_memory=self.hparams.pin_memory)

    def test_dataloader(self) -> EVAL_DATALOADERS:
        return DataLoader(self.test_dataset, batch_size=self.hparams.batch_size, num_workers=self.hparams.num_workers,
                          pin_memory=self.hparams.pin_memory)