text
stringlengths
38
1.54M
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models # Create your models here. class signup(models.Model): email = models.EmailField() fullname = models.CharField(max_length=120,blank=True,null=True) timestamp = models.DateTimeField(auto_now_add=True,auto_now=False) update =models.DateTimeField(auto_now_add=False,auto_now=True) def __unicode__(self): return self.email class company(models.Model): fullname = models.CharField(max_length=120) position = models.CharField(max_length=120) userid = models.CharField(max_length=120) salary = models.CharField(max_length=120) def __unicode__(self): return self.fullname class apply(models.Model): email = models.EmailField() fullname = models.CharField(max_length=120) userid = models.CharField(max_length=120) def __unicode__(self): return self.email class appliedd(models.Model): email = models.EmailField() def __unicode__(self): return self.email
A= int(input("enter a 5 digit no:")) addition = 0 while(A>0): B = A % 10 addition = addition + B A = A //10 print("sum of digits are:"+str(addition))
import sys _module = sys.modules[__name__] del sys main = _module models = _module densenet = _module googlenet = _module inceptionv4 = _module mobilenetv2 = _module nasnet = _module preactresnet = _module resnet = _module resnet_tiny = _module resnext = _module senet = _module swin = _module vgg = _module vit = _module xception = _module registry = _module tools = _module evaluator = _module metrics = _module utils = _module engine = _module evaluator = _module metrics = _module densenet = _module googlenet = _module inceptionv4 = _module mobilenetv2 = _module preactresnet = _module resnet = _module resnet_tiny = _module resnext = _module swin = _module vgg = _module vit = _module prune = _module prune_cifar = _module train = _module cifar_resnet = _module prune_resnet18_cifar10 = _module train_with_pruning = _module setup = _module test_convnext = _module test_customized_layer = _module test_dependency_graph = _module test_dependency_lenet = _module test_fully_connected_layers = _module test_importance = _module test_metrics = _module test_multiple_inputs_and_outputs = _module test_pruner = _module test_pruning_fn = _module test_rounding = _module test_torchvision_models = _module torch_pruning = _module dependency = _module functional = _module structured = _module unstructured = _module helpers = _module importance = _module metric = _module pruner = _module basepruner = _module batchnorm_scale_pruner = _module magnitude_based_pruner = _module structural_dropout_pruner = _module structural_reg_pruner = _module strategy = _module utils = _module from _paritybench_helpers import _mock_config, patch_functional from unittest.mock import mock_open, MagicMock from torch.autograd import Function from torch.nn import Module import abc, collections, copy, enum, functools, inspect, itertools, logging, math, matplotlib, numbers, numpy, pandas, queue, random, re, scipy, sklearn, string, tensorflow, time, torch, torchaudio, torchtext, torchvision, types, typing, uuid, warnings import numpy as np from torch import Tensor patch_functional() open = mock_open() yaml = logging = sys = argparse = MagicMock() ArgumentParser = argparse.ArgumentParser _global_config = args = argv = cfg = config = params = _mock_config() argparse.ArgumentParser.return_value.parse_args.return_value = _global_config yaml.load.return_value = _global_config sys.argv = _global_config __version__ = '1.0.0' xrange = range wraps = functools.wraps import torch import torch.nn as nn import torch.nn.functional as F import time import math from torch import nn from torch import einsum import numpy as np from typing import Callable from abc import ABC from abc import abstractmethod from typing import Union from typing import Any from typing import Mapping from typing import Sequence import numbers import logging import copy import random import warnings import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.distributed as dist import torch.optim import torch.multiprocessing as mp import torch.utils.data import torch.utils.data.distributed from torchvision.datasets import CIFAR10 from torchvision import transforms from copy import deepcopy import torch.optim as optim import torch.optim.lr_scheduler as lr_scheduler from torch.cuda import amp from torch.nn.parallel import DistributedDataParallel as DDP from torch.utils.tensorboard import SummaryWriter from torchvision.models.convnext import convnext_tiny from torchvision.models.convnext import convnext_small from torchvision.models.convnext import convnext_base from torchvision.models.convnext import convnext_large from torchvision.models import resnet18 from torchvision.models import densenet121 as entry from torchvision.models import alexnet from torchvision.models.resnet import resnet50 from torchvision.models.vision_transformer import vit_b_16 from torchvision.models.vision_transformer import vit_b_32 from torchvision.models.vision_transformer import vit_l_16 from torchvision.models.vision_transformer import vit_l_32 from torchvision.models.vision_transformer import vit_h_14 from torchvision.models.alexnet import alexnet from torchvision.models.densenet import densenet121 from torchvision.models.densenet import densenet169 from torchvision.models.densenet import densenet201 from torchvision.models.densenet import densenet161 from torchvision.models.efficientnet import efficientnet_b0 from torchvision.models.efficientnet import efficientnet_b1 from torchvision.models.efficientnet import efficientnet_b2 from torchvision.models.efficientnet import efficientnet_b3 from torchvision.models.efficientnet import efficientnet_b4 from torchvision.models.efficientnet import efficientnet_b5 from torchvision.models.efficientnet import efficientnet_b6 from torchvision.models.efficientnet import efficientnet_b7 from torchvision.models.efficientnet import efficientnet_v2_s from torchvision.models.efficientnet import efficientnet_v2_m from torchvision.models.efficientnet import efficientnet_v2_l from torchvision.models.googlenet import googlenet from torchvision.models.inception import inception_v3 from torchvision.models.mnasnet import mnasnet0_5 from torchvision.models.mnasnet import mnasnet0_75 from torchvision.models.mnasnet import mnasnet1_0 from torchvision.models.mnasnet import mnasnet1_3 from torchvision.models.mobilenetv2 import mobilenet_v2 from torchvision.models.mobilenetv3 import mobilenet_v3_large from torchvision.models.mobilenetv3 import mobilenet_v3_small from torchvision.models.regnet import regnet_y_400mf from torchvision.models.regnet import regnet_y_800mf from torchvision.models.regnet import regnet_y_1_6gf from torchvision.models.regnet import regnet_y_3_2gf from torchvision.models.regnet import regnet_y_8gf from torchvision.models.regnet import regnet_y_16gf from torchvision.models.regnet import regnet_y_32gf from torchvision.models.regnet import regnet_y_128gf from torchvision.models.regnet import regnet_x_400mf from torchvision.models.regnet import regnet_x_800mf from torchvision.models.regnet import regnet_x_1_6gf from torchvision.models.regnet import regnet_x_3_2gf from torchvision.models.regnet import regnet_x_8gf from torchvision.models.regnet import regnet_x_16gf from torchvision.models.regnet import regnet_x_32gf from torchvision.models.resnet import resnet18 from torchvision.models.resnet import resnet34 from torchvision.models.resnet import resnet101 from torchvision.models.resnet import resnet152 from torchvision.models.resnet import resnext50_32x4d from torchvision.models.resnet import resnext101_32x8d from torchvision.models.resnet import wide_resnet50_2 from torchvision.models.resnet import wide_resnet101_2 from torchvision.models.segmentation import fcn_resnet50 from torchvision.models.segmentation import fcn_resnet101 from torchvision.models.segmentation import deeplabv3_resnet50 from torchvision.models.segmentation import deeplabv3_resnet101 from torchvision.models.segmentation import deeplabv3_mobilenet_v3_large from torchvision.models.segmentation import lraspp_mobilenet_v3_large from torchvision.models.squeezenet import squeezenet1_0 from torchvision.models.squeezenet import squeezenet1_1 from torchvision.models.vgg import vgg11 from torchvision.models.vgg import vgg13 from torchvision.models.vgg import vgg16 from torchvision.models.vgg import vgg19 from torchvision.models.vgg import vgg11_bn from torchvision.models.vgg import vgg13_bn from torchvision.models.vgg import vgg16_bn from torchvision.models.vgg import vgg19_bn import typing from enum import IntEnum from numbers import Number from numpy import isin from functools import reduce from abc import abstractstaticmethod from typing import Tuple from typing import Dict import abc from abc import abstractclassmethod class Bottleneck(nn.Module): expansion = 4 def __init__(self, in_planes, planes, stride=1): super(Bottleneck, self).__init__() self.conv1 = nn.Conv2d(in_planes, 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, self.expansion * planes, kernel_size=1, bias=False) self.bn3 = nn.BatchNorm2d(self.expansion * planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential(nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion * planes)) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = F.relu(self.bn2(self.conv2(out))) out = self.bn3(self.conv3(out)) out += self.shortcut(x) out = F.relu(out) return out class Transition(nn.Module): def __init__(self, in_channels, out_channels): super().__init__() self.down_sample = nn.Sequential(nn.BatchNorm2d(in_channels), nn.Conv2d(in_channels, out_channels, 1, bias=False), nn.AvgPool2d(2, stride=2)) def forward(self, x): return self.down_sample(x) class DenseNet(nn.Module): def __init__(self, block, nblocks, growth_rate=12, reduction=0.5, num_classes=100): super().__init__() self.growth_rate = growth_rate inner_channels = 2 * growth_rate self.conv1 = nn.Conv2d(3, inner_channels, kernel_size=3, padding=1, bias=False) self.features = nn.Sequential() for index in range(len(nblocks) - 1): self.features.add_module('dense_block_layer_{}'.format(index), self._make_dense_layers(block, inner_channels, nblocks[index])) inner_channels += growth_rate * nblocks[index] out_channels = int(reduction * inner_channels) self.features.add_module('transition_layer_{}'.format(index), Transition(inner_channels, out_channels)) inner_channels = out_channels self.features.add_module('dense_block{}'.format(len(nblocks) - 1), self._make_dense_layers(block, inner_channels, nblocks[len(nblocks) - 1])) inner_channels += growth_rate * nblocks[len(nblocks) - 1] self.features.add_module('bn', nn.BatchNorm2d(inner_channels)) self.features.add_module('relu', nn.ReLU(inplace=True)) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.linear = nn.Linear(inner_channels, num_classes) def forward(self, x): output = self.conv1(x) output = self.features(output) output = self.avgpool(output) output = output.view(output.size()[0], -1) output = self.linear(output) return output def _make_dense_layers(self, block, in_channels, nblocks): dense_block = nn.Sequential() for index in range(nblocks): dense_block.add_module('bottle_neck_layer_{}'.format(index), block(in_channels, self.growth_rate)) in_channels += self.growth_rate return dense_block class Inception(nn.Module): def __init__(self, input_channels, n1x1, n3x3_reduce, n3x3, n5x5_reduce, n5x5, pool_proj): super().__init__() self.b1 = nn.Sequential(nn.Conv2d(input_channels, n1x1, kernel_size=1), nn.BatchNorm2d(n1x1), nn.ReLU(inplace=True)) self.b2 = nn.Sequential(nn.Conv2d(input_channels, n3x3_reduce, kernel_size=1), nn.BatchNorm2d(n3x3_reduce), nn.ReLU(inplace=True), nn.Conv2d(n3x3_reduce, n3x3, kernel_size=3, padding=1), nn.BatchNorm2d(n3x3), nn.ReLU(inplace=True)) self.b3 = nn.Sequential(nn.Conv2d(input_channels, n5x5_reduce, kernel_size=1), nn.BatchNorm2d(n5x5_reduce), nn.ReLU(inplace=True), nn.Conv2d(n5x5_reduce, n5x5, kernel_size=3, padding=1), nn.BatchNorm2d(n5x5, n5x5), nn.ReLU(inplace=True), nn.Conv2d(n5x5, n5x5, kernel_size=3, padding=1), nn.BatchNorm2d(n5x5), nn.ReLU(inplace=True)) self.b4 = nn.Sequential(nn.MaxPool2d(3, stride=1, padding=1), nn.Conv2d(input_channels, pool_proj, kernel_size=1), nn.BatchNorm2d(pool_proj), nn.ReLU(inplace=True)) def forward(self, x): return torch.cat([self.b1(x), self.b2(x), self.b3(x), self.b4(x)], dim=1) class GoogleNet(nn.Module): def __init__(self, num_classes=100): super().__init__() self.prelayer = nn.Sequential(nn.Conv2d(3, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True), nn.Conv2d(64, 192, kernel_size=3, padding=1, bias=False), nn.BatchNorm2d(192), nn.ReLU(inplace=True)) self.a3 = Inception(192, 64, 96, 128, 16, 32, 32) self.b3 = Inception(256, 128, 128, 192, 32, 96, 64) self.maxpool = nn.MaxPool2d(3, stride=2, padding=1) self.a4 = Inception(480, 192, 96, 208, 16, 48, 64) self.b4 = Inception(512, 160, 112, 224, 24, 64, 64) self.c4 = Inception(512, 128, 128, 256, 24, 64, 64) self.d4 = Inception(512, 112, 144, 288, 32, 64, 64) self.e4 = Inception(528, 256, 160, 320, 32, 128, 128) self.a5 = Inception(832, 256, 160, 320, 32, 128, 128) self.b5 = Inception(832, 384, 192, 384, 48, 128, 128) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.dropout = nn.Dropout2d(p=0.4) self.linear = nn.Linear(1024, num_classes) def forward(self, x): x = self.prelayer(x) x = self.maxpool(x) x = self.a3(x) x = self.b3(x) x = self.maxpool(x) x = self.a4(x) x = self.b4(x) x = self.c4(x) x = self.d4(x) x = self.e4(x) x = self.maxpool(x) x = self.a5(x) x = self.b5(x) x = self.avgpool(x) x = self.dropout(x) x = x.view(x.size()[0], -1) x = self.linear(x) return x class BasicConv2d(nn.Module): def __init__(self, input_channels, output_channels, **kwargs): super().__init__() self.conv = nn.Conv2d(input_channels, output_channels, bias=False, **kwargs) self.bn = nn.BatchNorm2d(output_channels) self.relu = nn.ReLU(inplace=True) def forward(self, x): x = self.conv(x) x = self.bn(x) x = self.relu(x) return x class Inception_Stem(nn.Module): def __init__(self, input_channels): super().__init__() self.conv1 = nn.Sequential(BasicConv2d(input_channels, 32, kernel_size=3), BasicConv2d(32, 32, kernel_size=3, padding=1), BasicConv2d(32, 64, kernel_size=3, padding=1)) self.branch3x3_conv = BasicConv2d(64, 96, kernel_size=3, padding=1) self.branch3x3_pool = nn.MaxPool2d(3, stride=1, padding=1) self.branch7x7a = nn.Sequential(BasicConv2d(160, 64, kernel_size=1), BasicConv2d(64, 64, kernel_size=(7, 1), padding=(3, 0)), BasicConv2d(64, 64, kernel_size=(1, 7), padding=(0, 3)), BasicConv2d(64, 96, kernel_size=3, padding=1)) self.branch7x7b = nn.Sequential(BasicConv2d(160, 64, kernel_size=1), BasicConv2d(64, 96, kernel_size=3, padding=1)) self.branchpoola = nn.MaxPool2d(kernel_size=3, stride=1, padding=1) self.branchpoolb = BasicConv2d(192, 192, kernel_size=3, stride=1, padding=1) def forward(self, x): x = self.conv1(x) x = [self.branch3x3_conv(x), self.branch3x3_pool(x)] x = torch.cat(x, 1) x = [self.branch7x7a(x), self.branch7x7b(x)] x = torch.cat(x, 1) x = [self.branchpoola(x), self.branchpoolb(x)] x = torch.cat(x, 1) return x class InceptionA(nn.Module): def __init__(self, input_channels): super().__init__() self.branch3x3stack = nn.Sequential(BasicConv2d(input_channels, 64, kernel_size=1), BasicConv2d(64, 96, kernel_size=3, padding=1), BasicConv2d(96, 96, kernel_size=3, padding=1)) self.branch3x3 = nn.Sequential(BasicConv2d(input_channels, 64, kernel_size=1), BasicConv2d(64, 96, kernel_size=3, padding=1)) self.branch1x1 = BasicConv2d(input_channels, 96, kernel_size=1) self.branchpool = nn.Sequential(nn.AvgPool2d(kernel_size=3, stride=1, padding=1), BasicConv2d(input_channels, 96, kernel_size=1)) def forward(self, x): x = [self.branch3x3stack(x), self.branch3x3(x), self.branch1x1(x), self.branchpool(x)] return torch.cat(x, 1) class ReductionA(nn.Module): def __init__(self, input_channels, k, l, m, n): super().__init__() self.branch3x3stack = nn.Sequential(BasicConv2d(input_channels, k, kernel_size=1), BasicConv2d(k, l, kernel_size=3, padding=1), BasicConv2d(l, m, kernel_size=3, stride=2)) self.branch3x3 = BasicConv2d(input_channels, n, kernel_size=3, stride=2) self.branchpool = nn.MaxPool2d(kernel_size=3, stride=2) self.output_channels = input_channels + n + m def forward(self, x): x = [self.branch3x3stack(x), self.branch3x3(x), self.branchpool(x)] return torch.cat(x, 1) class InceptionB(nn.Module): def __init__(self, input_channels): super().__init__() self.branch7x7stack = nn.Sequential(BasicConv2d(input_channels, 192, kernel_size=1), BasicConv2d(192, 192, kernel_size=(1, 7), padding=(0, 3)), BasicConv2d(192, 224, kernel_size=(7, 1), padding=(3, 0)), BasicConv2d(224, 224, kernel_size=(1, 7), padding=(0, 3)), BasicConv2d(224, 256, kernel_size=(7, 1), padding=(3, 0))) self.branch7x7 = nn.Sequential(BasicConv2d(input_channels, 192, kernel_size=1), BasicConv2d(192, 224, kernel_size=(1, 7), padding=(0, 3)), BasicConv2d(224, 256, kernel_size=(7, 1), padding=(3, 0))) self.branch1x1 = BasicConv2d(input_channels, 384, kernel_size=1) self.branchpool = nn.Sequential(nn.AvgPool2d(3, stride=1, padding=1), BasicConv2d(input_channels, 128, kernel_size=1)) def forward(self, x): x = [self.branch1x1(x), self.branch7x7(x), self.branch7x7stack(x), self.branchpool(x)] return torch.cat(x, 1) class ReductionB(nn.Module): def __init__(self, input_channels): super().__init__() self.branch7x7 = nn.Sequential(BasicConv2d(input_channels, 256, kernel_size=1), BasicConv2d(256, 256, kernel_size=(1, 7), padding=(0, 3)), BasicConv2d(256, 320, kernel_size=(7, 1), padding=(3, 0)), BasicConv2d(320, 320, kernel_size=3, stride=2, padding=1)) self.branch3x3 = nn.Sequential(BasicConv2d(input_channels, 192, kernel_size=1), BasicConv2d(192, 192, kernel_size=3, stride=2, padding=1)) self.branchpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=1) def forward(self, x): x = [self.branch3x3(x), self.branch7x7(x), self.branchpool(x)] return torch.cat(x, 1) class InceptionC(nn.Module): def __init__(self, input_channels): super().__init__() self.branch3x3stack = nn.Sequential(BasicConv2d(input_channels, 384, kernel_size=1), BasicConv2d(384, 448, kernel_size=(1, 3), padding=(0, 1)), BasicConv2d(448, 512, kernel_size=(3, 1), padding=(1, 0))) self.branch3x3stacka = BasicConv2d(512, 256, kernel_size=(1, 3), padding=(0, 1)) self.branch3x3stackb = BasicConv2d(512, 256, kernel_size=(3, 1), padding=(1, 0)) self.branch3x3 = BasicConv2d(input_channels, 384, kernel_size=1) self.branch3x3a = BasicConv2d(384, 256, kernel_size=(3, 1), padding=(1, 0)) self.branch3x3b = BasicConv2d(384, 256, kernel_size=(1, 3), padding=(0, 1)) self.branch1x1 = BasicConv2d(input_channels, 256, kernel_size=1) self.branchpool = nn.Sequential(nn.AvgPool2d(kernel_size=3, stride=1, padding=1), BasicConv2d(input_channels, 256, kernel_size=1)) def forward(self, x): branch3x3stack_output = self.branch3x3stack(x) branch3x3stack_output = [self.branch3x3stacka(branch3x3stack_output), self.branch3x3stackb(branch3x3stack_output)] branch3x3stack_output = torch.cat(branch3x3stack_output, 1) branch3x3_output = self.branch3x3(x) branch3x3_output = [self.branch3x3a(branch3x3_output), self.branch3x3b(branch3x3_output)] branch3x3_output = torch.cat(branch3x3_output, 1) branch1x1_output = self.branch1x1(x) branchpool = self.branchpool(x) output = [branch1x1_output, branch3x3_output, branch3x3stack_output, branchpool] return torch.cat(output, 1) class InceptionV4(nn.Module): def __init__(self, A, B, C, k=192, l=224, m=256, n=384, num_classes=100): super().__init__() self.stem = Inception_Stem(3) self.inception_a = self._generate_inception_module(384, 384, A, InceptionA) self.reduction_a = ReductionA(384, k, l, m, n) output_channels = self.reduction_a.output_channels self.inception_b = self._generate_inception_module(output_channels, 1024, B, InceptionB) self.reduction_b = ReductionB(1024) self.inception_c = self._generate_inception_module(1536, 1536, C, InceptionC) self.avgpool = nn.AvgPool2d(7) self.dropout = nn.Dropout2d(1 - 0.8) self.linear = nn.Linear(1536, num_classes) def forward(self, x): x = self.stem(x) x = self.inception_a(x) x = self.reduction_a(x) x = self.inception_b(x) x = self.reduction_b(x) x = self.inception_c(x) x = self.avgpool(x) x = self.dropout(x) x = x.view(-1, 1536) x = self.linear(x) return x @staticmethod def _generate_inception_module(input_channels, output_channels, block_num, block): layers = nn.Sequential() for l in range(block_num): layers.add_module('{}_{}'.format(block.__name__, l), block(input_channels)) input_channels = output_channels return layers class InceptionResNetA(nn.Module): def __init__(self, input_channels): super().__init__() self.branch3x3stack = nn.Sequential(BasicConv2d(input_channels, 32, kernel_size=1), BasicConv2d(32, 48, kernel_size=3, padding=1), BasicConv2d(48, 64, kernel_size=3, padding=1)) self.branch3x3 = nn.Sequential(BasicConv2d(input_channels, 32, kernel_size=1), BasicConv2d(32, 32, kernel_size=3, padding=1)) self.branch1x1 = BasicConv2d(input_channels, 32, kernel_size=1) self.reduction1x1 = nn.Conv2d(128, 384, kernel_size=1) self.shortcut = nn.Conv2d(input_channels, 384, kernel_size=1) self.bn = nn.BatchNorm2d(384) self.relu = nn.ReLU(inplace=True) def forward(self, x): residual = [self.branch1x1(x), self.branch3x3(x), self.branch3x3stack(x)] residual = torch.cat(residual, 1) residual = self.reduction1x1(residual) shortcut = self.shortcut(x) output = self.bn(shortcut + residual) output = self.relu(output) return output class InceptionResNetB(nn.Module): def __init__(self, input_channels): super().__init__() self.branch7x7 = nn.Sequential(BasicConv2d(input_channels, 128, kernel_size=1), BasicConv2d(128, 160, kernel_size=(1, 7), padding=(0, 3)), BasicConv2d(160, 192, kernel_size=(7, 1), padding=(3, 0))) self.branch1x1 = BasicConv2d(input_channels, 192, kernel_size=1) self.reduction1x1 = nn.Conv2d(384, 1154, kernel_size=1) self.shortcut = nn.Conv2d(input_channels, 1154, kernel_size=1) self.bn = nn.BatchNorm2d(1154) self.relu = nn.ReLU(inplace=True) def forward(self, x): residual = [self.branch1x1(x), self.branch7x7(x)] residual = torch.cat(residual, 1) residual = self.reduction1x1(residual) * 0.1 shortcut = self.shortcut(x) output = self.bn(residual + shortcut) output = self.relu(output) return output class InceptionResNetC(nn.Module): def __init__(self, input_channels): super().__init__() self.branch3x3 = nn.Sequential(BasicConv2d(input_channels, 192, kernel_size=1), BasicConv2d(192, 224, kernel_size=(1, 3), padding=(0, 1)), BasicConv2d(224, 256, kernel_size=(3, 1), padding=(1, 0))) self.branch1x1 = BasicConv2d(input_channels, 192, kernel_size=1) self.reduction1x1 = nn.Conv2d(448, 2048, kernel_size=1) self.shorcut = nn.Conv2d(input_channels, 2048, kernel_size=1) self.bn = nn.BatchNorm2d(2048) self.relu = nn.ReLU(inplace=True) def forward(self, x): residual = [self.branch1x1(x), self.branch3x3(x)] residual = torch.cat(residual, 1) residual = self.reduction1x1(residual) * 0.1 shorcut = self.shorcut(x) output = self.bn(shorcut + residual) output = self.relu(output) return output class InceptionResNetReductionA(nn.Module): def __init__(self, input_channels, k, l, m, n): super().__init__() self.branch3x3stack = nn.Sequential(BasicConv2d(input_channels, k, kernel_size=1), BasicConv2d(k, l, kernel_size=3, padding=1), BasicConv2d(l, m, kernel_size=3, stride=2)) self.branch3x3 = BasicConv2d(input_channels, n, kernel_size=3, stride=2) self.branchpool = nn.MaxPool2d(kernel_size=3, stride=2) self.output_channels = input_channels + n + m def forward(self, x): x = [self.branch3x3stack(x), self.branch3x3(x), self.branchpool(x)] return torch.cat(x, 1) class InceptionResNetReductionB(nn.Module): def __init__(self, input_channels): super().__init__() self.branchpool = nn.MaxPool2d(3, stride=2) self.branch3x3a = nn.Sequential(BasicConv2d(input_channels, 256, kernel_size=1), BasicConv2d(256, 384, kernel_size=3, stride=2)) self.branch3x3b = nn.Sequential(BasicConv2d(input_channels, 256, kernel_size=1), BasicConv2d(256, 288, kernel_size=3, stride=2)) self.branch3x3stack = nn.Sequential(BasicConv2d(input_channels, 256, kernel_size=1), BasicConv2d(256, 288, kernel_size=3, padding=1), BasicConv2d(288, 320, kernel_size=3, stride=2)) def forward(self, x): x = [self.branch3x3a(x), self.branch3x3b(x), self.branch3x3stack(x), self.branchpool(x)] x = torch.cat(x, 1) return x class InceptionResNetV2(nn.Module): def __init__(self, A, B, C, k=256, l=256, m=384, n=384, num_classes=100): super().__init__() self.stem = Inception_Stem(3) self.inception_resnet_a = self._generate_inception_module(384, 384, A, InceptionResNetA) self.reduction_a = InceptionResNetReductionA(384, k, l, m, n) output_channels = self.reduction_a.output_channels self.inception_resnet_b = self._generate_inception_module(output_channels, 1154, B, InceptionResNetB) self.reduction_b = InceptionResNetReductionB(1154) self.inception_resnet_c = self._generate_inception_module(2146, 2048, C, InceptionResNetC) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) self.dropout = nn.Dropout2d(1 - 0.8) self.linear = nn.Linear(2048, num_classes) def forward(self, x): x = self.stem(x) x = self.inception_resnet_a(x) x = self.reduction_a(x) x = self.inception_resnet_b(x) x = self.reduction_b(x) x = self.inception_resnet_c(x) x = self.avgpool(x) x = self.dropout(x) x = x.view(-1, 2048) x = self.linear(x) return x @staticmethod def _generate_inception_module(input_channels, output_channels, block_num, block): layers = nn.Sequential() for l in range(block_num): layers.add_module('{}_{}'.format(block.__name__, l), block(input_channels)) input_channels = output_channels return layers class LinearBottleNeck(nn.Module): def __init__(self, in_channels, out_channels, stride, t=6, num_classes=100): super().__init__() self.residual = nn.Sequential(nn.Conv2d(in_channels, in_channels * t, 1), nn.BatchNorm2d(in_channels * t), nn.ReLU6(inplace=True), nn.Conv2d(in_channels * t, in_channels * t, 3, stride=stride, padding=1, groups=in_channels * t), nn.BatchNorm2d(in_channels * t), nn.ReLU6(inplace=True), nn.Conv2d(in_channels * t, out_channels, 1), nn.BatchNorm2d(out_channels)) self.stride = stride self.in_channels = in_channels self.out_channels = out_channels def forward(self, x): residual = self.residual(x) if self.stride == 1 and self.in_channels == self.out_channels: residual += x return residual class MobileNetV2(nn.Module): def __init__(self, num_classes=100): super().__init__() self.pre = nn.Sequential(nn.Conv2d(3, 32, 1, padding=1), nn.BatchNorm2d(32), nn.ReLU6(inplace=True)) self.stage1 = LinearBottleNeck(32, 16, 1, 1) self.stage2 = self._make_stage(2, 16, 24, 2, 6) self.stage3 = self._make_stage(3, 24, 32, 2, 6) self.stage4 = self._make_stage(4, 32, 64, 2, 6) self.stage5 = self._make_stage(3, 64, 96, 1, 6) self.stage6 = self._make_stage(3, 96, 160, 1, 6) self.stage7 = LinearBottleNeck(160, 320, 1, 6) self.conv1 = nn.Sequential(nn.Conv2d(320, 1280, 1), nn.BatchNorm2d(1280), nn.ReLU6(inplace=True)) self.conv2 = nn.Conv2d(1280, num_classes, 1) def forward(self, x): x = self.pre(x) x = self.stage1(x) x = self.stage2(x) x = self.stage3(x) x = self.stage4(x) x = self.stage5(x) x = self.stage6(x) x = self.stage7(x) x = self.conv1(x) x = F.adaptive_avg_pool2d(x, 1) x = self.conv2(x) x = x.view(x.size(0), -1) return x def _make_stage(self, repeat, in_channels, out_channels, stride, t): layers = [] layers.append(LinearBottleNeck(in_channels, out_channels, stride, t)) while repeat - 1: layers.append(LinearBottleNeck(out_channels, out_channels, 1, t)) repeat -= 1 return nn.Sequential(*layers) class SeperableConv2d(nn.Module): def __init__(self, input_channels, output_channels, kernel_size, **kwargs): super().__init__() self.depthwise = nn.Conv2d(input_channels, input_channels, kernel_size, groups=input_channels, bias=False, **kwargs) self.pointwise = nn.Conv2d(input_channels, output_channels, 1, bias=False) def forward(self, x): x = self.depthwise(x) x = self.pointwise(x) return x class SeperableBranch(nn.Module): def __init__(self, input_channels, output_channels, kernel_size, **kwargs): """Adds 2 blocks of [relu-separable conv-batchnorm].""" super().__init__() self.block1 = nn.Sequential(nn.ReLU(), SeperableConv2d(input_channels, output_channels, kernel_size, **kwargs), nn.BatchNorm2d(output_channels)) self.block2 = nn.Sequential(nn.ReLU(), SeperableConv2d(output_channels, output_channels, kernel_size, stride=1, padding=int(kernel_size / 2)), nn.BatchNorm2d(output_channels)) def forward(self, x): x = self.block1(x) x = self.block2(x) return x class Fit(nn.Module): """Make the cell outputs compatible Args: prev_filters: filter number of tensor prev, needs to be modified filters: filter number of normal cell branch output filters """ def __init__(self, prev_filters, filters): super().__init__() self.relu = nn.ReLU() self.p1 = nn.Sequential(nn.AvgPool2d(1, stride=2), nn.Conv2d(prev_filters, int(filters / 2), 1)) self.p2 = nn.Sequential(nn.ConstantPad2d((0, 1, 0, 1), 0), nn.ConstantPad2d((-1, 0, -1, 0), 0), nn.AvgPool2d(1, stride=2), nn.Conv2d(prev_filters, int(filters / 2), 1)) self.bn = nn.BatchNorm2d(filters) self.dim_reduce = nn.Sequential(nn.ReLU(), nn.Conv2d(prev_filters, filters, 1), nn.BatchNorm2d(filters)) self.filters = filters def forward(self, inputs): x, prev = inputs if prev is None: return x elif x.size(2) != prev.size(2): prev = self.relu(prev) p1 = self.p1(prev) p2 = self.p2(prev) prev = torch.cat([p1, p2], 1) prev = self.bn(prev) elif prev.size(1) != self.filters: prev = self.dim_reduce(prev) return prev class NormalCell(nn.Module): def __init__(self, x_in, prev_in, output_channels): super().__init__() self.dem_reduce = nn.Sequential(nn.ReLU(), nn.Conv2d(x_in, output_channels, 1, bias=False), nn.BatchNorm2d(output_channels)) self.block1_left = SeperableBranch(output_channels, output_channels, kernel_size=3, padding=1, bias=False) self.block1_right = nn.Sequential() self.block2_left = SeperableBranch(output_channels, output_channels, kernel_size=3, padding=1, bias=False) self.block2_right = SeperableBranch(output_channels, output_channels, kernel_size=5, padding=2, bias=False) self.block3_left = nn.AvgPool2d(3, stride=1, padding=1) self.block3_right = nn.Sequential() self.block4_left = nn.AvgPool2d(3, stride=1, padding=1) self.block4_right = nn.AvgPool2d(3, stride=1, padding=1) self.block5_left = SeperableBranch(output_channels, output_channels, kernel_size=5, padding=2, bias=False) self.block5_right = SeperableBranch(output_channels, output_channels, kernel_size=3, padding=1, bias=False) self.fit = Fit(prev_in, output_channels) def forward(self, x): x, prev = x prev = self.fit((x, prev)) h = self.dem_reduce(x) x1 = self.block1_left(h) + self.block1_right(h) x2 = self.block2_left(prev) + self.block2_right(h) x3 = self.block3_left(h) + self.block3_right(h) x4 = self.block4_left(prev) + self.block4_right(prev) x5 = self.block5_left(prev) + self.block5_right(prev) return torch.cat([prev, x1, x2, x3, x4, x5], 1), x class ReductionCell(nn.Module): def __init__(self, x_in, prev_in, output_channels): super().__init__() self.dim_reduce = nn.Sequential(nn.ReLU(), nn.Conv2d(x_in, output_channels, 1), nn.BatchNorm2d(output_channels)) self.layer1block1_left = SeperableBranch(output_channels, output_channels, 7, stride=2, padding=3) self.layer1block1_right = SeperableBranch(output_channels, output_channels, 5, stride=2, padding=2) self.layer1block2_left = nn.MaxPool2d(3, stride=2, padding=1) self.layer1block2_right = SeperableBranch(output_channels, output_channels, 7, stride=2, padding=3) self.layer1block3_left = nn.AvgPool2d(3, 2, 1) self.layer1block3_right = SeperableBranch(output_channels, output_channels, 5, stride=2, padding=2) self.layer2block1_left = nn.MaxPool2d(3, 2, 1) self.layer2block1_right = SeperableBranch(output_channels, output_channels, 3, stride=1, padding=1) self.layer2block2_left = nn.AvgPool2d(3, 1, 1) self.layer2block2_right = nn.Sequential() self.fit = Fit(prev_in, output_channels) def forward(self, x): x, prev = x prev = self.fit((x, prev)) h = self.dim_reduce(x) layer1block1 = self.layer1block1_left(prev) + self.layer1block1_right(h) layer1block2 = self.layer1block2_left(h) + self.layer1block2_right(prev) layer1block3 = self.layer1block3_left(h) + self.layer1block3_right(prev) layer2block1 = self.layer2block1_left(h) + self.layer2block1_right(layer1block1) layer2block2 = self.layer2block2_left(layer1block1) + self.layer2block2_right(layer1block2) return torch.cat([layer1block2, layer1block3, layer2block1, layer2block2], 1), x class NasNetA(nn.Module): def __init__(self, repeat_cell_num, reduction_num, filters, stemfilter, num_classes=100): super().__init__() self.stem = nn.Sequential(nn.Conv2d(3, stemfilter, 3, padding=1, bias=False), nn.BatchNorm2d(stemfilter)) self.prev_filters = stemfilter self.x_filters = stemfilter self.filters = filters self.cell_layers = self._make_layers(repeat_cell_num, reduction_num) self.relu = nn.ReLU() self.avg = nn.AdaptiveAvgPool2d(1) self.fc = nn.Linear(self.filters * 6, num_classes) def _make_normal(self, block, repeat, output): """make normal cell Args: block: cell type repeat: number of repeated normal cell output: output filters for each branch in normal cell Returns: stacked normal cells """ layers = [] for r in range(repeat): layers.append(block(self.x_filters, self.prev_filters, output)) self.prev_filters = self.x_filters self.x_filters = output * 6 return layers def _make_reduction(self, block, output): """make normal cell Args: block: cell type output: output filters for each branch in reduction cell Returns: reduction cell """ reduction = block(self.x_filters, self.prev_filters, output) self.prev_filters = self.x_filters self.x_filters = output * 4 return reduction def _make_layers(self, repeat_cell_num, reduction_num): layers = [] for i in range(reduction_num): layers.extend(self._make_normal(NormalCell, repeat_cell_num, self.filters)) self.filters *= 2 layers.append(self._make_reduction(ReductionCell, self.filters)) layers.extend(self._make_normal(NormalCell, repeat_cell_num, self.filters)) return nn.Sequential(*layers) def forward(self, x): x = self.stem(x) prev = None x, prev = self.cell_layers((x, prev)) x = self.relu(x) x = self.avg(x) x = x.view(x.size(0), -1) x = self.fc(x) return x class PreActBasic(nn.Module): expansion = 1 def __init__(self, in_channels, out_channels, stride): super().__init__() self.residual = nn.Sequential(nn.BatchNorm2d(in_channels), nn.ReLU(inplace=True), nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=stride, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels * PreActBasic.expansion, kernel_size=3, padding=1)) self.shortcut = nn.Sequential() if stride != 1 or in_channels != out_channels * PreActBasic.expansion: self.shortcut = nn.Conv2d(in_channels, out_channels * PreActBasic.expansion, 1, stride=stride) def forward(self, x): res = self.residual(x) shortcut = self.shortcut(x) return res + shortcut class PreActBottleNeck(nn.Module): expansion = 4 def __init__(self, in_channels, out_channels, stride): super().__init__() self.residual = nn.Sequential(nn.BatchNorm2d(in_channels), nn.ReLU(inplace=True), nn.Conv2d(in_channels, out_channels, 1, stride=stride), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, 3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels * PreActBottleNeck.expansion, 1)) self.shortcut = nn.Sequential() if stride != 1 or in_channels != out_channels * PreActBottleNeck.expansion: self.shortcut = nn.Conv2d(in_channels, out_channels * PreActBottleNeck.expansion, 1, stride=stride) def forward(self, x): res = self.residual(x) shortcut = self.shortcut(x) return res + shortcut class PreActResNet(nn.Module): def __init__(self, block, num_block, num_classes=100): super().__init__() self.input_channels = 64 self.pre = nn.Sequential(nn.Conv2d(3, 64, 3, padding=1), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.stage1 = self._make_layers(block, num_block[0], 64, 1) self.stage2 = self._make_layers(block, num_block[1], 128, 2) self.stage3 = self._make_layers(block, num_block[2], 256, 2) self.stage4 = self._make_layers(block, num_block[3], 512, 2) self.linear = nn.Linear(self.input_channels, num_classes) def _make_layers(self, block, block_num, out_channels, stride): layers = [] layers.append(block(self.input_channels, out_channels, stride)) self.input_channels = out_channels * block.expansion while block_num - 1: layers.append(block(self.input_channels, out_channels, 1)) self.input_channels = out_channels * block.expansion block_num -= 1 return nn.Sequential(*layers) def forward(self, x): x = self.pre(x) x = self.stage1(x) x = self.stage2(x) x = self.stage3(x) x = self.stage4(x) x = F.adaptive_avg_pool2d(x, 1) x = x.view(x.size(0), -1) x = self.linear(x) return x class BasicBlock(nn.Module): expansion = 1 def __init__(self, in_planes, planes, stride=1): super(BasicBlock, self).__init__() self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(planes) self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=1, bias=False) self.bn2 = nn.BatchNorm2d(planes) self.shortcut = nn.Sequential() if stride != 1 or in_planes != self.expansion * planes: self.shortcut = nn.Sequential(nn.Conv2d(in_planes, self.expansion * planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(self.expansion * planes)) def forward(self, x): out = F.relu(self.bn1(self.conv1(x))) out = self.bn2(self.conv2(out)) out += self.shortcut(x) out = F.relu(out) return out class ResNet(nn.Module): def __init__(self, block, num_blocks, num_classes=10): super(ResNet, self).__init__() self.in_planes = 64 self.conv1 = nn.Conv2d(3, 64, kernel_size=3, stride=2, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(64) self.layer1 = self._make_layer(block, 64, num_blocks[0], stride=1) self.layer2 = self._make_layer(block, 128, num_blocks[1], stride=1) self.layer3 = self._make_layer(block, 256, num_blocks[2], stride=2) self.layer4 = self._make_layer(block, 512, num_blocks[3], stride=2) self.linear = nn.Linear(512 * block.expansion, num_classes) for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu') elif isinstance(m, (nn.BatchNorm2d, nn.GroupNorm)): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, num_blocks, stride): strides = [stride] + [1] * (num_blocks - 1) layers = [] for stride in strides: layers.append(block(self.in_planes, planes, stride)) self.in_planes = planes * block.expansion return nn.Sequential(*layers) def forward(self, x, out_feature=False): out = F.relu(self.bn1(self.conv1(x))) out = self.layer1(out) out = self.layer2(out) out = self.layer3(out) out = self.layer4(out) out = F.avg_pool2d(out, 4) feature = out.view(out.size(0), -1) out = self.linear(feature) if out_feature == False: return out else: return out, feature BASEWIDTH = 64 CARDINALITY = 32 DEPTH = 4 class ResNextBottleNeckC(nn.Module): def __init__(self, in_channels, out_channels, stride): super().__init__() C = CARDINALITY D = int(DEPTH * out_channels / BASEWIDTH) self.split_transforms = nn.Sequential(nn.Conv2d(in_channels, C * D, kernel_size=1, groups=C, bias=False), nn.BatchNorm2d(C * D), nn.ReLU(inplace=True), nn.Conv2d(C * D, C * D, kernel_size=3, stride=stride, groups=C, padding=1, bias=False), nn.BatchNorm2d(C * D), nn.ReLU(inplace=True), nn.Conv2d(C * D, out_channels * 4, kernel_size=1, bias=False), nn.BatchNorm2d(out_channels * 4)) self.shortcut = nn.Sequential() if stride != 1 or in_channels != out_channels * 4: self.shortcut = nn.Sequential(nn.Conv2d(in_channels, out_channels * 4, stride=stride, kernel_size=1, bias=False), nn.BatchNorm2d(out_channels * 4)) def forward(self, x): return F.relu(self.split_transforms(x) + self.shortcut(x)) class ResNext(nn.Module): def __init__(self, block, num_blocks, num_classes=100): super().__init__() self.in_channels = 64 self.conv1 = nn.Sequential(nn.Conv2d(3, 64, 3, stride=1, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.conv2 = self._make_layer(block, num_blocks[0], 64, 1) self.conv3 = self._make_layer(block, num_blocks[1], 128, 2) self.conv4 = self._make_layer(block, num_blocks[2], 256, 2) self.conv5 = self._make_layer(block, num_blocks[3], 512, 2) self.avg = nn.AdaptiveAvgPool2d((1, 1)) self.fc = nn.Linear(512 * 4, num_classes) def forward(self, x): x = self.conv1(x) x = self.conv2(x) x = self.conv3(x) x = self.conv4(x) x = self.conv5(x) x = self.avg(x) x = x.view(x.size(0), -1) x = self.fc(x) return x def _make_layer(self, block, num_block, out_channels, stride): """Building resnext block Args: block: block type(default resnext bottleneck c) num_block: number of blocks per layer out_channels: output channels per block stride: block stride Returns: a resnext layer """ strides = [stride] + [1] * (num_block - 1) layers = [] for stride in strides: layers.append(block(self.in_channels, out_channels, stride)) self.in_channels = out_channels * 4 return nn.Sequential(*layers) class SqueezeExcitationLayer(nn.Module): def __init__(self, channel, reduction=16): super(SqueezeExcitationLayer, self).__init__() self.avg_pool = nn.AdaptiveAvgPool2d(1) self.fc = nn.Sequential(nn.Linear(channel, channel // reduction, bias=False), nn.ReLU(inplace=True), nn.Linear(channel // reduction, channel, bias=False), nn.Sigmoid()) def forward(self, x): b, c, _, _ = x.size() y = self.avg_pool(x).view(b, c) y = self.fc(y).view(b, c, 1, 1) return x * y.expand_as(x) BN_momentum = 0.1 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 SEBasicBlock(nn.Module): expansion = 1 def __init__(self, inplanes, planes, stride=1, reduction=16, new_resnet=False): super(SEBasicBlock, self).__init__() self.new_resnet = new_resnet self.conv1 = conv3x3(inplanes, planes, stride) self.bn1 = nn.BatchNorm2d(inplanes if new_resnet else planes, momentum=BN_momentum) self.relu = nn.ReLU(inplace=True) self.conv2 = conv3x3(planes, planes, 1) self.bn2 = nn.BatchNorm2d(planes, momentum=BN_momentum) self.se = SqueezeExcitationLayer(planes, reduction) if inplanes != planes: self.downsample = nn.Sequential(nn.Conv2d(inplanes, planes, kernel_size=1, stride=stride, bias=False), nn.BatchNorm2d(planes, momentum=BN_momentum)) else: self.downsample = lambda x: x self.stride = stride self.output = planes * self.expansion def _old_resnet(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.se(out) if self.downsample is not None: residual = self.downsample(x) out += residual out = self.relu(out) return out def _new_resnet(self, x): residual = x out = self.bn1(x) out = self.relu(out) out = self.conv1(out) out = self.bn2(out) out = self.relu(out) out = self.conv2(out) out = self.se(out) if self.downsample is not None: residual = self.downsample(x) out += residual return out def forward(self, x): if self.new_resnet: return self._new_resnet(x) else: return self._old_resnet(x) class CifarNet(nn.Module): """ This is specially designed for cifar10 """ def __init__(self, block, n_size, num_classes=10, reduction=16, new_resnet=False, dropout=0.0): super(CifarNet, self).__init__() self.inplane = 16 self.new_resnet = new_resnet self.dropout_prob = dropout self.conv1 = nn.Conv2d(3, self.inplane, kernel_size=3, stride=1, padding=1, bias=False) self.bn1 = nn.BatchNorm2d(self.inplane, momentum=BN_momentum) self.relu = nn.ReLU(inplace=True) self.layer1 = self._make_layer(block, 16, blocks=n_size, stride=1, reduction=reduction) self.layer2 = self._make_layer(block, 32, blocks=n_size, stride=2, reduction=reduction) self.layer3 = self._make_layer(block, 64, blocks=n_size, stride=2, reduction=reduction) self.avgpool = nn.AdaptiveAvgPool2d(1) if self.dropout_prob > 0: self.dropout_layer = nn.Dropout(p=self.dropout_prob, inplace=True) self.fc = nn.Linear(self.inplane, num_classes) self.initialize() def initialize(self): for m in self.modules(): if isinstance(m, nn.Conv2d): nn.init.kaiming_normal_(m.weight) elif isinstance(m, nn.BatchNorm2d): nn.init.constant_(m.weight, 1) nn.init.constant_(m.bias, 0) def _make_layer(self, block, planes, blocks, stride, reduction): strides = [stride] + [1] * (blocks - 1) layers = [] for stride in strides: layers.append(block(self.inplane, planes, stride, reduction, new_resnet=self.new_resnet)) self.inplane = layers[-1].output return nn.Sequential(*layers) def forward(self, x): x = self.conv1(x) x = self.bn1(x) x = self.relu(x) x = self.layer1(x) x = self.layer2(x) x = self.layer3(x) x = self.avgpool(x) x = x.view(x.size(0), -1) if self.dropout_prob > 0: x = self.dropout_layer(x) x = self.fc(x) return x class CyclicShift(nn.Module): def __init__(self, displacement): super().__init__() self.displacement = displacement def forward(self, x): return torch.roll(x, shifts=(self.displacement, self.displacement), dims=(1, 2)) class Residual(nn.Module): def __init__(self, fn): super().__init__() self.fn = fn def forward(self, x, **kwargs): return self.fn(x, **kwargs) + x class PreNorm(nn.Module): def __init__(self, dim, fn): super().__init__() self.norm = nn.LayerNorm(dim) self.fn = fn def forward(self, x, **kwargs): return self.fn(self.norm(x), **kwargs) class FeedForward(nn.Module): def __init__(self, dim, hidden_dim, dropout=0.0): super().__init__() self.net = nn.Sequential(nn.Linear(dim, hidden_dim), nn.GELU(), nn.Dropout(dropout), nn.Linear(hidden_dim, dim), nn.Dropout(dropout)) def forward(self, x): return self.net(x) def create_mask(window_size, displacement, upper_lower, left_right): mask = torch.zeros(window_size ** 2, window_size ** 2) if upper_lower: mask[-displacement * window_size:, :-displacement * window_size] = float('-inf') mask[:-displacement * window_size, -displacement * window_size:] = float('-inf') if left_right: mask = rearrange(mask, '(h1 w1) (h2 w2) -> h1 w1 h2 w2', h1=window_size, h2=window_size) mask[:, -displacement:, :, :-displacement] = float('-inf') mask[:, :-displacement, :, -displacement:] = float('-inf') mask = rearrange(mask, 'h1 w1 h2 w2 -> (h1 w1) (h2 w2)') return mask def get_relative_distances(window_size): indices = torch.tensor(np.array([[x, y] for x in range(window_size) for y in range(window_size)])) distances = indices[None, :, :] - indices[:, None, :] return distances class WindowAttention(nn.Module): def __init__(self, dim, heads, head_dim, shifted, window_size, relative_pos_embedding): super().__init__() inner_dim = head_dim * heads self.heads = heads self.scale = head_dim ** -0.5 self.window_size = window_size self.relative_pos_embedding = relative_pos_embedding self.shifted = shifted if self.shifted: displacement = window_size // 2 self.cyclic_shift = CyclicShift(-displacement) self.cyclic_back_shift = CyclicShift(displacement) self.upper_lower_mask = nn.Parameter(create_mask(window_size=window_size, displacement=displacement, upper_lower=True, left_right=False), requires_grad=False) self.left_right_mask = nn.Parameter(create_mask(window_size=window_size, displacement=displacement, upper_lower=False, left_right=True), requires_grad=False) self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False) if self.relative_pos_embedding: self.relative_indices = get_relative_distances(window_size) + window_size - 1 self.pos_embedding = nn.Parameter(torch.randn(2 * window_size - 1, 2 * window_size - 1)) else: self.pos_embedding = nn.Parameter(torch.randn(window_size ** 2, window_size ** 2)) self.to_out = nn.Linear(inner_dim, dim) def forward(self, x): if self.shifted: x = self.cyclic_shift(x) b, n_h, n_w, _, h = *x.shape, self.heads qkv = self.to_qkv(x).chunk(3, dim=-1) nw_h = n_h // self.window_size nw_w = n_w // self.window_size q, k, v = map(lambda t: rearrange(t, 'b (nw_h w_h) (nw_w w_w) (h d) -> b h (nw_h nw_w) (w_h w_w) d', h=h, w_h=self.window_size, w_w=self.window_size), qkv) dots = einsum('b h w i d, b h w j d -> b h w i j', q, k) * self.scale if self.relative_pos_embedding: dots += self.pos_embedding[self.relative_indices[:, :, 0], self.relative_indices[:, :, 1]] else: dots += self.pos_embedding if self.shifted: dots[:, :, -nw_w:] += self.upper_lower_mask dots[:, :, nw_w - 1::nw_w] += self.left_right_mask attn = dots.softmax(dim=-1) out = einsum('b h w i j, b h w j d -> b h w i d', attn, v) out = rearrange(out, 'b h (nw_h nw_w) (w_h w_w) d -> b (nw_h w_h) (nw_w w_w) (h d)', h=h, w_h=self.window_size, w_w=self.window_size, nw_h=nw_h, nw_w=nw_w) out = self.to_out(out) if self.shifted: out = self.cyclic_back_shift(out) return out class SwinBlock(nn.Module): def __init__(self, dim, heads, head_dim, mlp_dim, shifted, window_size, relative_pos_embedding): super().__init__() self.attention_block = Residual(PreNorm(dim, WindowAttention(dim=dim, heads=heads, head_dim=head_dim, shifted=shifted, window_size=window_size, relative_pos_embedding=relative_pos_embedding))) self.mlp_block = Residual(PreNorm(dim, FeedForward(dim=dim, hidden_dim=mlp_dim))) def forward(self, x): x = self.attention_block(x) x = self.mlp_block(x) return x class PatchMerging(nn.Module): def __init__(self, in_channels, out_channels, downscaling_factor): super().__init__() self.downscaling_factor = downscaling_factor self.patch_merge = nn.Unfold(kernel_size=downscaling_factor, stride=downscaling_factor, padding=0) self.linear = nn.Linear(in_channels * downscaling_factor ** 2, out_channels) def forward(self, x): b, c, h, w = x.shape new_h, new_w = h // self.downscaling_factor, w // self.downscaling_factor x = self.patch_merge(x).view(b, -1, new_h, new_w).permute(0, 2, 3, 1) x = self.linear(x) return x class StageModule(nn.Module): def __init__(self, in_channels, hidden_dimension, layers, downscaling_factor, num_heads, head_dim, window_size, relative_pos_embedding): super().__init__() assert layers % 2 == 0, 'Stage layers need to be divisible by 2 for regular and shifted block.' self.patch_partition = PatchMerging(in_channels=in_channels, out_channels=hidden_dimension, downscaling_factor=downscaling_factor) self.layers = nn.ModuleList([]) for _ in range(layers // 2): self.layers.append(nn.ModuleList([SwinBlock(dim=hidden_dimension, heads=num_heads, head_dim=head_dim, mlp_dim=hidden_dimension * 4, shifted=False, window_size=window_size, relative_pos_embedding=relative_pos_embedding), SwinBlock(dim=hidden_dimension, heads=num_heads, head_dim=head_dim, mlp_dim=hidden_dimension * 4, shifted=True, window_size=window_size, relative_pos_embedding=relative_pos_embedding)])) def forward(self, x): x = self.patch_partition(x) for regular_block, shifted_block in self.layers: x = regular_block(x) x = shifted_block(x) return x.permute(0, 3, 1, 2) class SwinTransformer(nn.Module): def __init__(self, *, hidden_dim, layers, heads, channels=3, num_classes=1000, head_dim=32, window_size=7, downscaling_factors=(4, 2, 2, 2), relative_pos_embedding=True): super().__init__() self.stage1 = StageModule(in_channels=channels, hidden_dimension=hidden_dim, layers=layers[0], downscaling_factor=downscaling_factors[0], num_heads=heads[0], head_dim=head_dim, window_size=window_size, relative_pos_embedding=relative_pos_embedding) self.stage2 = StageModule(in_channels=hidden_dim, hidden_dimension=hidden_dim * 2, layers=layers[1], downscaling_factor=downscaling_factors[1], num_heads=heads[1], head_dim=head_dim, window_size=window_size, relative_pos_embedding=relative_pos_embedding) self.stage3 = StageModule(in_channels=hidden_dim * 2, hidden_dimension=hidden_dim * 4, layers=layers[2], downscaling_factor=downscaling_factors[2], num_heads=heads[2], head_dim=head_dim, window_size=window_size, relative_pos_embedding=relative_pos_embedding) self.stage4 = StageModule(in_channels=hidden_dim * 4, hidden_dimension=hidden_dim * 8, layers=layers[3], downscaling_factor=downscaling_factors[3], num_heads=heads[3], head_dim=head_dim, window_size=window_size, relative_pos_embedding=relative_pos_embedding) self.mlp_head = nn.Sequential(nn.LayerNorm(hidden_dim * 8), nn.Linear(hidden_dim * 8, num_classes)) def forward(self, img): x = self.stage1(img) x = self.stage2(x) x = self.stage3(x) x = self.stage4(x) x = x.mean(dim=[2, 3]) return self.mlp_head(x) class VGG(nn.Module): def __init__(self, cfg, batch_norm=False, num_classes=1000): super(VGG, self).__init__() self.block0 = self._make_layers(cfg[0], batch_norm, 3) self.block1 = self._make_layers(cfg[1], batch_norm, cfg[0][-1]) self.block2 = self._make_layers(cfg[2], batch_norm, cfg[1][-1]) self.block3 = self._make_layers(cfg[3], batch_norm, cfg[2][-1]) self.block4 = self._make_layers(cfg[4], batch_norm, cfg[3][-1]) self.pool0 = nn.MaxPool2d(kernel_size=2, stride=2) self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) self.pool2 = nn.MaxPool2d(kernel_size=2, stride=2) self.pool3 = nn.MaxPool2d(kernel_size=2, stride=2) self.pool4 = nn.AdaptiveAvgPool2d((1, 1)) self.classifier = nn.Linear(512, num_classes) self._initialize_weights() def get_feat_modules(self): feat_m = nn.ModuleList([]) feat_m.append(self.block0) feat_m.append(self.pool0) feat_m.append(self.block1) feat_m.append(self.pool1) feat_m.append(self.block2) feat_m.append(self.pool2) feat_m.append(self.block3) feat_m.append(self.pool3) feat_m.append(self.block4) feat_m.append(self.pool4) return feat_m def get_bn_before_relu(self): bn1 = self.block1[-1] bn2 = self.block2[-1] bn3 = self.block3[-1] bn4 = self.block4[-1] return [bn1, bn2, bn3, bn4] def forward(self, x, return_features=False): h = x.shape[2] x = F.relu(self.block0(x)) x = self.pool0(x) x = self.block1(x) x = F.relu(x) x = self.pool1(x) x = self.block2(x) x = F.relu(x) x = self.pool2(x) x = self.block3(x) x = F.relu(x) if h == 64: x = self.pool3(x) x = self.block4(x) x = F.relu(x) x = self.pool4(x) features = x.view(x.size(0), -1) x = self.classifier(features) if return_features: return x, features else: return x @staticmethod def _make_layers(cfg, batch_norm=False, in_channels=3): layers = [] for v in cfg: if v == 'M': layers += [nn.MaxPool2d(kernel_size=2, stride=2)] else: conv2d = nn.Conv2d(in_channels, v, kernel_size=3, padding=1) if batch_norm: layers += [conv2d, nn.BatchNorm2d(v), nn.ReLU(inplace=True)] else: layers += [conv2d, nn.ReLU(inplace=True)] in_channels = v layers = layers[:-1] return nn.Sequential(*layers) def _initialize_weights(self): 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.0 / n)) if m.bias is not None: m.bias.data.zero_() elif isinstance(m, nn.BatchNorm2d): m.weight.data.fill_(1) m.bias.data.zero_() elif isinstance(m, nn.Linear): n = m.weight.size(1) m.weight.data.normal_(0, 0.01) m.bias.data.zero_() class Attention(nn.Module): def __init__(self, dim, heads=8, dim_head=64, dropout=0.0): super().__init__() inner_dim = dim_head * heads project_out = not (heads == 1 and dim_head == dim) self.heads = heads self.scale = dim_head ** -0.5 self.attend = nn.Softmax(dim=-1) self.dropout = nn.Dropout(dropout) self.to_qkv = nn.Linear(dim, inner_dim * 3, bias=False) self.to_out = nn.Sequential(nn.Linear(inner_dim, dim), nn.Dropout(dropout)) if project_out else nn.Identity() def forward(self, x): qkv = self.to_qkv(x).chunk(3, dim=-1) q, k, v = map(lambda t: rearrange(t, 'b n (h d) -> b h n d', h=self.heads), qkv) dots = torch.matmul(q, k.transpose(-1, -2)) * self.scale attn = self.attend(dots) attn = self.dropout(attn) out = torch.matmul(attn, v) out = rearrange(out, 'b h n d -> b n (h d)') return self.to_out(out) class Transformer(nn.Module): def __init__(self, dim, depth, heads, dim_head, mlp_dim, dropout=0.0): super().__init__() self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append(nn.ModuleList([PreNorm(dim, Attention(dim, heads=heads, dim_head=dim_head, dropout=dropout)), PreNorm(dim, FeedForward(dim, mlp_dim, dropout=dropout))])) def forward(self, x): for attn, ff in self.layers: x = attn(x) + x x = ff(x) + x return x def pair(t): return t if isinstance(t, tuple) else (t, t) repeat = 100 class ViT(nn.Module): def __init__(self, *, image_size, patch_size, num_classes, dim, depth, heads, mlp_dim, pool='cls', channels=3, dim_head=64, dropout=0.0, emb_dropout=0.0): super().__init__() image_height, image_width = pair(image_size) patch_height, patch_width = pair(patch_size) assert image_height % patch_height == 0 and image_width % patch_width == 0, 'Image dimensions must be divisible by the patch size.' num_patches = image_height // patch_height * (image_width // patch_width) patch_dim = channels * patch_height * patch_width assert pool in {'cls', 'mean'}, 'pool type must be either cls (cls token) or mean (mean pooling)' self.to_patch_embedding = nn.Sequential(Rearrange('b c (h p1) (w p2) -> b (h w) (p1 p2 c)', p1=patch_height, p2=patch_width), nn.Linear(patch_dim, dim)) self.pos_embedding = nn.Parameter(torch.randn(1, num_patches + 1, dim)) self.cls_token = nn.Parameter(torch.randn(1, 1, dim)) self.dropout = nn.Dropout(emb_dropout) self.transformer = Transformer(dim, depth, heads, dim_head, mlp_dim, dropout) self.pool = pool self.to_latent = nn.Identity() self.mlp_head = nn.Sequential(nn.LayerNorm(dim), nn.Linear(dim, num_classes)) def forward(self, img): x = self.to_patch_embedding(img) b, n, _ = x.shape cls_tokens = repeat(self.cls_token, '1 1 d -> b 1 d', b=b) x = torch.cat((cls_tokens, x), dim=1) x += self.pos_embedding[:, :n + 1] x = self.dropout(x) x = self.transformer(x) x = x.mean(dim=1) if self.pool == 'mean' else x[:, 0] x = self.to_latent(x) return self.mlp_head(x) class EntryFlow(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Sequential(nn.Conv2d(3, 32, 3, padding=1, bias=False), nn.BatchNorm2d(32), nn.ReLU(inplace=True)) self.conv2 = nn.Sequential(nn.Conv2d(32, 64, 3, padding=1, bias=False), nn.BatchNorm2d(64), nn.ReLU(inplace=True)) self.conv3_residual = nn.Sequential(SeperableConv2d(64, 128, 3, padding=1), nn.BatchNorm2d(128), nn.ReLU(inplace=True), SeperableConv2d(128, 128, 3, padding=1), nn.BatchNorm2d(128), nn.MaxPool2d(3, stride=2, padding=1)) self.conv3_shortcut = nn.Sequential(nn.Conv2d(64, 128, 1, stride=2), nn.BatchNorm2d(128)) self.conv4_residual = nn.Sequential(nn.ReLU(inplace=True), SeperableConv2d(128, 256, 3, padding=1), nn.BatchNorm2d(256), nn.ReLU(inplace=True), SeperableConv2d(256, 256, 3, padding=1), nn.BatchNorm2d(256), nn.MaxPool2d(3, stride=2, padding=1)) self.conv4_shortcut = nn.Sequential(nn.Conv2d(128, 256, 1, stride=2), nn.BatchNorm2d(256)) self.conv5_residual = nn.Sequential(nn.ReLU(inplace=True), SeperableConv2d(256, 728, 3, padding=1), nn.BatchNorm2d(728), nn.ReLU(inplace=True), SeperableConv2d(728, 728, 3, padding=1), nn.BatchNorm2d(728), nn.MaxPool2d(3, 1, padding=1)) self.conv5_shortcut = nn.Sequential(nn.Conv2d(256, 728, 1), nn.BatchNorm2d(728)) def forward(self, x): x = self.conv1(x) x = self.conv2(x) residual = self.conv3_residual(x) shortcut = self.conv3_shortcut(x) x = residual + shortcut residual = self.conv4_residual(x) shortcut = self.conv4_shortcut(x) x = residual + shortcut residual = self.conv5_residual(x) shortcut = self.conv5_shortcut(x) x = residual + shortcut return x class MiddleFLowBlock(nn.Module): def __init__(self): super().__init__() self.shortcut = nn.Sequential() self.conv1 = nn.Sequential(nn.ReLU(inplace=True), SeperableConv2d(728, 728, 3, padding=1), nn.BatchNorm2d(728)) self.conv2 = nn.Sequential(nn.ReLU(inplace=True), SeperableConv2d(728, 728, 3, padding=1), nn.BatchNorm2d(728)) self.conv3 = nn.Sequential(nn.ReLU(inplace=True), SeperableConv2d(728, 728, 3, padding=1), nn.BatchNorm2d(728)) def forward(self, x): residual = self.conv1(x) residual = self.conv2(residual) residual = self.conv3(residual) shortcut = self.shortcut(x) return shortcut + residual class MiddleFlow(nn.Module): def __init__(self, block): super().__init__() self.middel_block = self._make_flow(block, 8) def forward(self, x): x = self.middel_block(x) return x def _make_flow(self, block, times): flows = [] for i in range(times): flows.append(block()) return nn.Sequential(*flows) class ExitFLow(nn.Module): def __init__(self): super().__init__() self.residual = nn.Sequential(nn.ReLU(), SeperableConv2d(728, 728, 3, padding=1), nn.BatchNorm2d(728), nn.ReLU(), SeperableConv2d(728, 1024, 3, padding=1), nn.BatchNorm2d(1024), nn.MaxPool2d(3, stride=2, padding=1)) self.shortcut = nn.Sequential(nn.Conv2d(728, 1024, 1, stride=2), nn.BatchNorm2d(1024)) self.conv = nn.Sequential(SeperableConv2d(1024, 1536, 3, padding=1), nn.BatchNorm2d(1536), nn.ReLU(inplace=True), SeperableConv2d(1536, 2048, 3, padding=1), nn.BatchNorm2d(2048), nn.ReLU(inplace=True)) self.avgpool = nn.AdaptiveAvgPool2d((1, 1)) def forward(self, x): shortcut = self.shortcut(x) residual = self.residual(x) output = shortcut + residual output = self.conv(output) output = self.avgpool(output) return output class Xception(nn.Module): def __init__(self, block, num_classes=100): super().__init__() self.entry_flow = EntryFlow() self.middel_flow = MiddleFlow(block) self.exit_flow = ExitFLow() self.fc = nn.Linear(2048, num_classes) def forward(self, x): x = self.entry_flow(x) x = self.middel_flow(x) x = self.exit_flow(x) x = x.view(x.size(0), -1) x = self.fc(x) return x class CustomizedLayer(nn.Module): def __init__(self, in_dim): super().__init__() self.in_dim = in_dim self.scale = nn.Parameter(torch.Tensor(self.in_dim)) self.bias = nn.Parameter(torch.Tensor(self.in_dim)) def forward(self, x): norm = x.pow(2).sum(dim=1, keepdim=True).sqrt() x = torch.div(x, norm) return x * self.scale + self.bias def __repr__(self): return 'CustomizedLayer(in_dim=%d)' % self.in_dim class FullyConnectedNet(nn.Module): """https://github.com/VainF/Torch-Pruning/issues/21""" def __init__(self, input_sizes, output_sizes): super().__init__() self.fc1 = nn.Linear(input_sizes[0], output_sizes[0]) self.fc2 = nn.Linear(input_sizes[1], output_sizes[1]) self.fc3 = nn.Linear(sum(output_sizes), 1000) def forward(self, x1, x2): x1 = F.relu(self.fc1(x1)) x2 = F.relu(self.fc2(x2)) x3 = F.relu(self.fc3(torch.cat([x1, x2], dim=1))) return x1, x2, x3 class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.conv1 = nn.Conv2d(1, 6, 5) self.relu1 = nn.ReLU() self.pool1 = nn.MaxPool2d(2) self.conv2 = nn.Conv2d(6, 16, 5) self.relu2 = nn.ReLU() self.pool2 = nn.MaxPool2d(2) self.fc1 = nn.Linear(256, 120) self.relu3 = nn.ReLU() self.fc2 = nn.Linear(120, 84) self.relu4 = nn.ReLU() self.fc3 = nn.Linear(84, 10) self.relu5 = nn.ReLU() def forward(self, x): y = self.conv1(x) y = self.relu1(y) y = self.pool1(y) y = self.conv2(y) y = self.relu2(y) y = self.pool2(y) y = y.view(y.shape[0], -1) y = self.fc1(y) y = self.relu3(y) y = self.fc2(y) y = self.relu4(y) y = self.fc3(y) y = self.relu5(y) return y class _CustomizedOp(nn.Module): def __init__(self, op_class): self.op_cls = op_class def __repr__(self): return 'CustomizedOp({})'.format(str(self.op_cls)) class _ConcatOp(nn.Module): def __init__(self): super(_ConcatOp, self).__init__() self.offsets = None def __repr__(self): return '_ConcatOp({})'.format(self.offsets) class DummyMHA(nn.Module): def __init__(self): super(DummyMHA, self).__init__() class _SplitOp(nn.Module): def __init__(self): super(_SplitOp, self).__init__() self.offsets = None def __repr__(self): return '_SplitOp({})'.format(self.offsets) class _ElementWiseOp(nn.Module): def __init__(self, grad_fn): super(_ElementWiseOp, self).__init__() self._grad_fn = grad_fn def __repr__(self): return '_ElementWiseOp({})'.format(self._grad_fn) class GConv(nn.Module): def __init__(self, gconv): super(GConv, self).__init__() self.groups = gconv.groups self.convs = nn.ModuleList() oc_size = gconv.out_channels // self.groups ic_size = gconv.in_channels // self.groups for g in range(self.groups): self.convs.append(nn.Conv2d(in_channels=oc_size, out_channels=ic_size, kernel_size=gconv.kernel_size, stride=gconv.stride, padding=gconv.padding, dilation=gconv.dilation, groups=1, bias=gconv.bias is not None, padding_mode=gconv.padding_mode)) group_size = gconv.out_channels // self.groups gconv_weight = gconv.weight for i, conv in enumerate(self.convs): conv.weight.data = gconv_weight.data[oc_size * i:oc_size * (i + 1)] if gconv.bias is not None: conv.bias.data = gconv.bias.data[oc_size * i:oc_size * (i + 1)] def forward(self, x): split_sizes = [conv.in_channels for conv in self.convs] xs = torch.split(x, split_sizes, dim=1) out = torch.cat([conv(xi) for conv, xi in zip(self.convs, xs)], dim=1) return out class StructrualDropout(nn.Module): def __init__(self, p): super(StructrualDropout, self).__init__() self.p = p self.mask = None def forward(self, x): C = x.shape[1] if self.mask is None: self.mask = (torch.FloatTensor(C, device=x.device).uniform_() > self.p).view(1, -1, 1, 1) res = x * self.mask return res def reset(self, p): self.p = p self.mask = None import torch from torch.nn import MSELoss, ReLU from _paritybench_helpers import _mock_config, _mock_layer, _paritybench_base, _fails_compile TESTCASES = [ # (nn.Module, init_args, forward_args, jit_compiles) (BasicBlock, lambda: ([], {'in_planes': 4, 'planes': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (BasicConv2d, lambda: ([], {'input_channels': 4, 'output_channels': 4, 'kernel_size': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (Bottleneck, lambda: ([], {'in_planes': 4, 'planes': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (CustomizedLayer, lambda: ([], {'in_dim': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (CyclicShift, lambda: ([], {'displacement': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (EntryFlow, lambda: ([], {}), lambda: ([torch.rand([4, 3, 64, 64])], {}), True), (ExitFLow, lambda: ([], {}), lambda: ([torch.rand([4, 728, 64, 64])], {}), True), (FeedForward, lambda: ([], {'dim': 4, 'hidden_dim': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (Fit, lambda: ([], {'prev_filters': 4, 'filters': 4}), lambda: ([(torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]))], {}), False), (FullyConnectedNet, lambda: ([], {'input_sizes': [4, 4], 'output_sizes': [4, 4]}), lambda: ([torch.rand([4, 4]), torch.rand([4, 4])], {}), True), (GoogleNet, lambda: ([], {}), lambda: ([torch.rand([4, 3, 64, 64])], {}), False), (Inception, lambda: ([], {'input_channels': 4, 'n1x1': 4, 'n3x3_reduce': 4, 'n3x3': 4, 'n5x5_reduce': 4, 'n5x5': 4, 'pool_proj': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), False), (InceptionA, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionB, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionC, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionResNetA, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionResNetB, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionResNetC, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionResNetReductionA, lambda: ([], {'input_channels': 4, 'k': 4, 'l': 4, 'm': 4, 'n': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionResNetReductionB, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (InceptionResNetV2, lambda: ([], {'A': 4, 'B': 4, 'C': 4}), lambda: ([torch.rand([4, 3, 64, 64])], {}), True), (InceptionV4, lambda: ([], {'A': 4, 'B': 4, 'C': 4}), lambda: ([torch.rand([4, 3, 64, 64])], {}), True), (Inception_Stem, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (LinearBottleNeck, lambda: ([], {'in_channels': 4, 'out_channels': 4, 'stride': 1}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (MiddleFLowBlock, lambda: ([], {}), lambda: ([torch.rand([4, 728, 64, 64])], {}), True), (MiddleFlow, lambda: ([], {'block': _mock_layer}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (MobileNetV2, lambda: ([], {}), lambda: ([torch.rand([4, 3, 64, 64])], {}), True), (PatchMerging, lambda: ([], {'in_channels': 4, 'out_channels': 4, 'downscaling_factor': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (PreActBasic, lambda: ([], {'in_channels': 4, 'out_channels': 4, 'stride': 1}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (PreActBottleNeck, lambda: ([], {'in_channels': 4, 'out_channels': 4, 'stride': 1}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (PreNorm, lambda: ([], {'dim': 4, 'fn': _mock_layer()}), lambda: ([torch.rand([4, 4, 4, 4])], {}), False), (ReductionA, lambda: ([], {'input_channels': 4, 'k': 4, 'l': 4, 'm': 4, 'n': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (ReductionB, lambda: ([], {'input_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (ReductionCell, lambda: ([], {'x_in': 4, 'prev_in': 4, 'output_channels': 4}), lambda: ([(torch.rand([4, 4, 4, 4]), torch.rand([4, 4, 4, 4]))], {}), False), (Residual, lambda: ([], {'fn': _mock_layer()}), lambda: ([torch.rand([4, 4, 4, 4])], {}), False), (SEBasicBlock, lambda: ([], {'inplanes': 4, 'planes': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), False), (SeperableBranch, lambda: ([], {'input_channels': 4, 'output_channels': 4, 'kernel_size': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (SeperableConv2d, lambda: ([], {'input_channels': 4, 'output_channels': 4, 'kernel_size': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (SqueezeExcitationLayer, lambda: ([], {'channel': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (StructrualDropout, lambda: ([], {'p': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (Transition, lambda: ([], {'in_channels': 4, 'out_channels': 4}), lambda: ([torch.rand([4, 4, 4, 4])], {}), True), (Xception, lambda: ([], {'block': _mock_layer}), lambda: ([torch.rand([4, 3, 64, 64])], {}), True), ] class Test_VainF_Torch_Pruning(_paritybench_base): def test_000(self): self._check(*TESTCASES[0]) def test_001(self): self._check(*TESTCASES[1]) def test_002(self): self._check(*TESTCASES[2]) def test_003(self): self._check(*TESTCASES[3]) def test_004(self): self._check(*TESTCASES[4]) def test_005(self): self._check(*TESTCASES[5]) def test_006(self): self._check(*TESTCASES[6]) def test_007(self): self._check(*TESTCASES[7]) def test_008(self): self._check(*TESTCASES[8]) def test_009(self): self._check(*TESTCASES[9]) def test_010(self): self._check(*TESTCASES[10]) def test_011(self): self._check(*TESTCASES[11]) def test_012(self): self._check(*TESTCASES[12]) def test_013(self): self._check(*TESTCASES[13]) def test_014(self): self._check(*TESTCASES[14]) def test_015(self): self._check(*TESTCASES[15]) def test_016(self): self._check(*TESTCASES[16]) def test_017(self): self._check(*TESTCASES[17]) def test_018(self): self._check(*TESTCASES[18]) def test_019(self): self._check(*TESTCASES[19]) def test_020(self): self._check(*TESTCASES[20]) def test_021(self): self._check(*TESTCASES[21]) def test_022(self): self._check(*TESTCASES[22]) def test_023(self): self._check(*TESTCASES[23]) def test_024(self): self._check(*TESTCASES[24]) def test_025(self): self._check(*TESTCASES[25]) def test_026(self): self._check(*TESTCASES[26]) def test_027(self): self._check(*TESTCASES[27]) def test_028(self): self._check(*TESTCASES[28]) def test_029(self): self._check(*TESTCASES[29]) def test_030(self): self._check(*TESTCASES[30]) def test_031(self): self._check(*TESTCASES[31]) def test_032(self): self._check(*TESTCASES[32]) def test_033(self): self._check(*TESTCASES[33]) def test_034(self): self._check(*TESTCASES[34]) def test_035(self): self._check(*TESTCASES[35]) def test_036(self): self._check(*TESTCASES[36]) def test_037(self): self._check(*TESTCASES[37]) def test_038(self): self._check(*TESTCASES[38]) def test_039(self): self._check(*TESTCASES[39]) def test_040(self): self._check(*TESTCASES[40]) def test_041(self): self._check(*TESTCASES[41])
from pydub import AudioSegment from pydub.utils import make_chunks song = AudioSegment.from_wav("file.wav") chunk_length_ms = 1000 # pydub calculates in millisec chunks = make_chunks(song, chunk_length_ms) #Make chunks of one sec #Export all of the individual chunks as wav files for i, chunk in enumerate(chunks): chunk_name = "file.wav".format(i) chunk.export(chunk_name, format="wav", parameters=['-f', 'pcm_f32le', '-ar', '48000'])
"""Tests for `panels.FigureSizeLocator`.""" # Copyright 2016 Andrew Dawson # # This file is part of panel-plots. # # panel-plots is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # panel-plots is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with panel-plots. If not, see <http://www.gnu.org/licenses/>. from __future__ import (absolute_import, division, print_function) from hypothesis import given, assume import pytest from panels import FigureSizeLocator from panels.tests import (almost_equal, gridsize_st, length_st, offset_st) #: Length units to generate test cases for. TEST_UNITS = ['mm', 'cm', 'inches'] #----------------------------------------------------------------------- # Tests specifications (full, width, and height) without padding or # separation. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec(rows, columns, figwidth, figheight, units): """Full specification (width and height) only.""" l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec(rows, columns, figwidth, units): """Width specification only.""" l = FigureSizeLocator(rows, columns, figwidth=figwidth, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec(rows, columns, figheight, units): """Height specification only.""" l = FigureSizeLocator(rows, columns, figheight=figheight, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) #----------------------------------------------------------------------- # Tests specifications (width and height) with a specified aspect ratio. #----------------------------------------------------------------------- @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_ratio_gives_warning(units): """Full specification with aspect ratio should generate a warning.""" expected_msg = ('the "panelratio" keyword is ignored when both the ' '"figwidth" and "figheight" keywords are used') with pytest.warns(UserWarning) as record: l = FigureSizeLocator(1, 1, figwidth=10, figheight=10, panelratio=1, units=units) assert len(record) == 1 assert record[0].message.args[0] == expected_msg @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, panelratio=length_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_ratio(rows, columns, figwidth, panelratio, units): """Width specification with aspect ratio.""" l = FigureSizeLocator(rows, columns, figwidth=figwidth, panelratio=panelratio, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, (figwidth * rows) / (panelratio * columns)) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, panelratio=length_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_ratio(rows, columns, figheight, panelratio, units): """Height specification with aspect ratio.""" l = FigureSizeLocator(rows, columns, figheight=figheight, panelratio=panelratio, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, columns * panelratio * figheight / rows) #----------------------------------------------------------------------- # Tests full specifications with horizonal and vertical separation. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, hsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_hsep(rows, columns, figwidth, figheight, hsep, units): """Full specification with horizontal separation.""" assume(figwidth > hsep * (columns - 1)) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, hsep=hsep, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, vsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_vsep(rows, columns, figwidth, figheight, vsep, units): """Full specification with vertical separation.""" assume(figheight > vsep * (rows - 1)) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, vsep=vsep, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, hsep=offset_st, vsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_hsep_and_vsep(rows, columns, figwidth, figheight, hsep, vsep, units): """Full specification with horizontal and vertical separation.""" assume(figwidth > hsep * (columns - 1)) assume(figheight > vsep * (rows - 1)) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, hsep=hsep, vsep=vsep, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) #----------------------------------------------------------------------- # Tests width specifications with horizonal and vertical separation. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, hsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_hsep(rows, columns, figwidth, hsep, units): """Width specification with horizontal separation.""" assume(figwidth > hsep * (columns - 1)) l = FigureSizeLocator(rows, columns, figwidth=figwidth, hsep=hsep, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, vsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_vsep(rows, columns, figwidth, vsep, units): """Width specification with vertical separation.""" l = FigureSizeLocator(rows, columns, figwidth=figwidth, vsep=vsep, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, hsep=offset_st, vsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_hsep_and_vsep(rows, columns, figwidth, hsep, vsep, units): """Width specification with horizontal and vertical separation.""" assume(figwidth > hsep * (columns - 1)) l = FigureSizeLocator(rows, columns, figwidth=figwidth, hsep=hsep, vsep=vsep, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) #----------------------------------------------------------------------- # Tests height specifications with horizonal and vertical separation. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, hsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_hsep(rows, columns, figheight, hsep, units): """Height specification with horizontal separation.""" l = FigureSizeLocator(rows, columns, figheight=figheight, hsep=hsep, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, vsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_vsep(rows, columns, figheight, vsep, units): """Height specification with vertical separation.""" assume(figheight > vsep * (rows - 1)) l = FigureSizeLocator(rows, columns, figheight=figheight, vsep=vsep, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, hsep=offset_st, vsep=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_hsep_and_vsep(rows, columns, figheight, hsep, vsep, units): """Height specification with horizontal and vertical separation.""" assume(figheight > vsep * (rows - 1)) l = FigureSizeLocator(rows, columns, figheight=figheight, hsep=hsep, vsep=vsep, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) #----------------------------------------------------------------------- # Tests full specifications with padding. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, padleft=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_padleft(rows, columns, figwidth, figheight, padleft, units): """Full specification with left side padding.""" assume(figwidth > padleft) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, padleft=padleft, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, padright=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_padright(rows, columns, figwidth, figheight, padright, units): """Full specification with right side padding.""" assume(figwidth > padright) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, padright=padright, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, padtop=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_padtop(rows, columns, figwidth, figheight, padtop, units): """Full specification with top edge padding.""" assume(figheight > padtop) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, padtop=padtop, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_padbottom(rows, columns, figwidth, figheight, padbottom, units): """Full specification with bottom edge padding.""" assume(figheight > padbottom) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, padbottom=padbottom, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, padleft=offset_st, padright=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_pad(rows, columns, figwidth, figheight, padleft, padright, padtop, padbottom, units): """Full specification with padding on all sides.""" assume(figwidth > padleft + padright) assume(figheight > padbottom + padtop) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, padleft=padleft, padright=padright, padtop=padtop, padbottom=padbottom, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) #----------------------------------------------------------------------- # Tests width specifications with padding. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, padleft=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_padleft(rows, columns, figwidth, padleft, units): """Width specification with left side padding.""" assume(figwidth > padleft) l = FigureSizeLocator(rows, columns, figwidth=figwidth, padleft=padleft, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, padright=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_padright(rows, columns, figwidth, padright, units): """Width specification with right side padding.""" assume(figwidth > padright) l = FigureSizeLocator(rows, columns, figwidth=figwidth, padright=padright, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, padtop=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_padtop(rows, columns, figwidth, padtop, units): """Width specification with top edge padding.""" l = FigureSizeLocator(rows, columns, figwidth=figwidth, padtop=padtop, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_padbottom(rows, columns, figwidth, padbottom, units): """Width specification with bottom edge padding.""" l = FigureSizeLocator(rows, columns, figwidth=figwidth, padbottom=padbottom, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, padleft=offset_st, padright=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_pad(rows, columns, figwidth, padleft, padright, padtop, padbottom, units): """Width specification with padding on all sides.""" assume(figwidth > padleft + padright) l = FigureSizeLocator(rows, columns, figwidth=figwidth, padleft=padleft, padright=padright, padtop=padtop, padbottom=padbottom, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) #----------------------------------------------------------------------- # Tests height specifications with padding. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, padleft=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_padleft(rows, columns, figheight, padleft, units): """Height specification with left side padding.""" l = FigureSizeLocator(rows, columns, figheight=figheight, padleft=padleft, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, padright=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_padright(rows, columns, figheight, padright, units): """Height specification with right side padding.""" l = FigureSizeLocator(rows, columns, figheight=figheight, padright=padright, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, padtop=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_padtop(rows, columns, figheight, padtop, units): """Height specification with top edge padding.""" assume(figheight > padtop) l = FigureSizeLocator(rows, columns, figheight=figheight, padtop=padtop, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_padbottom(rows, columns, figheight, padbottom, units): """Height specification with bottom edge padding.""" assume(figheight > padbottom) l = FigureSizeLocator(rows, columns, figheight=figheight, padbottom=padbottom, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, padleft=offset_st, padright=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_pad(rows, columns, figheight, padleft, padright, padtop, padbottom, units): """Height specification with padding on all sides.""" assume(figheight > padtop + padbottom) l = FigureSizeLocator(rows, columns, figheight=figheight, padleft=padleft, padright=padright, padtop=padtop, padbottom=padbottom, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) #----------------------------------------------------------------------- # Test specifications (full, width, and height) with both padding and # separation. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, hsep=offset_st, vsep=offset_st, padleft=offset_st, padright=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_with_all(rows, columns, figwidth, figheight, hsep, vsep, padleft, padright, padtop, padbottom, units): """Full specification with separation and padding.""" assume(figwidth > padleft + (columns - 1) * hsep + padright) assume(figheight > padtop + (rows - 1) * vsep + padbottom) l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, hsep=hsep, vsep=vsep, padleft=padleft, padright=padright, padtop=padtop, padbottom=padbottom, units=units) figwidth_c, figheight_c = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) assert almost_equal(figheight_c, figheight) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, hsep=offset_st, vsep=offset_st, padleft=offset_st, padright=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_with_all(rows, columns, figwidth, hsep, vsep, padleft, padright, padtop, padbottom, units): """Width specification with separation and padding.""" assume(figwidth > padleft + (columns - 1) * hsep + padright) l = FigureSizeLocator(rows, columns, figwidth=figwidth, hsep=hsep, vsep=vsep, padleft=padleft, padright=padright, padtop=padtop, padbottom=padbottom, units=units) figwidth_c, _ = l.figsize_in(units) assert almost_equal(figwidth_c, figwidth) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, hsep=offset_st, vsep=offset_st, padleft=offset_st, padright=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_with_all(rows, columns, figheight, hsep, vsep, padleft, padright, padtop, padbottom, units): """Height specification with separation and padding.""" assume(figheight > padtop + (rows - 1) * vsep + padbottom) l = FigureSizeLocator(rows, columns, figheight=figheight, hsep=hsep, vsep=vsep, padleft=padleft, padright=padright, padtop=padtop, padbottom=padbottom, units=units) _, figheight_c = l.figsize_in(units) assert almost_equal(figheight_c, figheight) #----------------------------------------------------------------------- # Test error conditions. #----------------------------------------------------------------------- @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, figheight=length_st, hsep=offset_st, vsep=offset_st, padleft=offset_st, padright=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_full_spec_ill_conditioned(rows, columns, figwidth, figheight, hsep, vsep, padleft, padright, padtop, padbottom, units): """An error message if the full spec is not large enough.""" assume (figwidth <= padleft + (columns - 1) * hsep + padright or figheight <= padtop + (rows - 1) * vsep + padbottom) with pytest.raises(ValueError) as excinfo: l = FigureSizeLocator(rows, columns, figwidth=figwidth, figheight=figheight, hsep=hsep, vsep=vsep, padleft=padleft, padright=padright, padtop=padtop, padbottom=padbottom, units=units) assert 'not large enough' in str(excinfo.value) @given(rows=gridsize_st, columns=gridsize_st, figwidth=length_st, hsep=offset_st, padleft=offset_st, padright=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_width_spec_ill_conditioned(rows, columns, figwidth, hsep, padleft, padright, units): """An error if the width spec is not large enough.""" assume (figwidth <= padleft + (columns - 1) * hsep + padright) with pytest.raises(ValueError) as excinfo: l = FigureSizeLocator(rows, columns, figwidth=figwidth, hsep=hsep, padleft=padleft, padright=padright, units=units) assert 'not wide enough' in str(excinfo.value) @given(rows=gridsize_st, columns=gridsize_st, figheight=length_st, vsep=offset_st, padtop=offset_st, padbottom=offset_st) @pytest.mark.parametrize('units', TEST_UNITS) def test_height_spec_ill_conditioned(rows, columns, figheight, vsep, padtop, padbottom, units): """An error if the height spec is not large enough.""" assume (figheight <= padtop + (rows - 1) * vsep + padbottom) with pytest.raises(ValueError) as excinfo: l = FigureSizeLocator(rows, columns, figheight=figheight, vsep=vsep, padtop=padtop, padbottom=padbottom, units=units) assert 'not tall enough' in str(excinfo.value)
# Question 5:<br> # Write a program to accept customer details such as : Account_no, Name, Balance in Account, # Assume Maximum 20 Customer In the bank. # Write a function to print the account no and name of each customer with balance below rs 100. class Bank_Account: def __init__(self,account_no, name, balance): self.account_no = account_no self.name = name self.balance = balance def balance_less(self): if self.balance < 100: return (f"""account no.={self.account_no} name= {self.name} balance= {self.balance}""") accounts = [Bank_Account(123, "khushboo", 99), Bank_Account(124, "harsh", 200), Bank_Account(122, "prachi", 88), Bank_Account(125, "sanjana", 120)] for bank in accounts: print(bank.balance_less())
#coding=utf8 import sys reload(sys) sys.setdefaultencoding("utf8") import httplib import hashlib import urllib import random import json appid = '20160313000015392' secretKey = 'MCmBwJkXJRqswDFwv2I5' urlPrefix = '/api/trans/vip/translate' def BaiduTrans(input,fromLang='en',toLang='zh'): httpClient = None salt = random.randint(1, 655360000) try: sign = appid+input+str(salt)+secretKey sign = hashlib.new('md5',sign).hexdigest() myurl = urlPrefix+'?appid='+appid+'&q='+urllib.quote(input)+'&from='+fromLang+'&to='+toLang+'&salt='+str(salt)+'&sign='+sign httpClient = httplib.HTTPConnection('api.fanyi.baidu.com') httpClient.request('GET', myurl) #response是HTTPResponse对象 response = httpClient.getresponse() decodeStr=json.loads(response.read()) return decodeStr['trans_result'][0]['dst'] except Exception, e: print e finally: if httpClient: httpClient.close() if __name__ == '__main__': BaiduTrans('amazon')
# Copyright 2016 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from __future__ import absolute_import import sys import os from telemetry.testing import serially_executed_browser_test_case from telemetry.core import util from telemetry.testing import fakes from typ import json_results def ConvertPathToTestName(url): return url.replace('.', '_') class BrowserTest( serially_executed_browser_test_case.SeriallyExecutedBrowserTestCase): @classmethod def GenerateTestCases_JavascriptTest(cls, options): del options # unused for path in ['page_with_link.html', 'page_with_clickables.html']: yield 'add_1_and_2_' + ConvertPathToTestName(path), (path, 1, 2, 3) @classmethod def SetUpProcess(cls): super(cls, BrowserTest).SetUpProcess() cls.SetBrowserOptions(cls._finder_options) cls.StartBrowser() cls.action_runner = cls.browser.tabs[0].action_runner cls.SetStaticServerDirs( [os.path.join(os.path.abspath(__file__), '..', 'pages')]) def JavascriptTest(self, file_path, num_1, num_2, expected_sum): url = self.UrlOfStaticFilePath(file_path) self.action_runner.Navigate(url) actual_sum = self.action_runner.EvaluateJavaScript( '{{ num_1 }} + {{ num_2 }}', num_1=num_1, num_2=num_2) self.assertEquals(expected_sum, actual_sum) def TestClickablePage(self): url = self.UrlOfStaticFilePath('page_with_clickables.html') self.action_runner.Navigate(url) self.action_runner.ExecuteJavaScript('valueSettableByTest = 1997') self.action_runner.ClickElement(text='Click/tap me') self.assertEqual( 1997, self.action_runner.EvaluateJavaScript('valueToTest')) def TestAndroidUI(self): if self.platform.GetOSName() != 'android': self.skipTest('The test is for android only') url = self.UrlOfStaticFilePath('page_with_clickables.html') # Nativgate to page_with_clickables.html self.action_runner.Navigate(url) # Click on history self.platform.system_ui.WaitForUiNode( resource_id='com.google.android.apps.chrome:id/menu_button') self.platform.system_ui.GetUiNode( resource_id='com.google.android.apps.chrome:id/menu_button').Tap() self.platform.system_ui.WaitForUiNode(content_desc='History') self.platform.system_ui.GetUiNode(content_desc='History').Tap() # Click on the first entry of the history (page_with_clickables.html) self.action_runner.WaitForElement('#id-0') self.action_runner.ClickElement('#id-0') # Verify that the page's js is interactable self.action_runner.WaitForElement(text='Click/tap me') self.action_runner.ExecuteJavaScript('valueSettableByTest = 1997') self.action_runner.ClickElement(text='Click/tap me') self.assertEqual( 1997, self.action_runner.EvaluateJavaScript('valueToTest')) class ImplementsGetPlatformTags( serially_executed_browser_test_case.SeriallyExecutedBrowserTestCase): @classmethod def SetUpProcess(cls): finder_options = fakes.CreateBrowserFinderOptions() finder_options.browser_options.platform = fakes.FakeLinuxPlatform() finder_options.output_formats = ['none'] finder_options.suppress_gtest_report = True finder_options.output_dir = None finder_options.upload_bucket = 'public' finder_options.upload_results = False cls._finder_options = finder_options cls.platform = None cls.browser = None cls.SetBrowserOptions(cls._finder_options) cls.StartBrowser() @classmethod def GetPlatformTags(cls, browser): return cls.browser.GetTypExpectationsTags() @classmethod def GenerateTestCases__RunsFailingTest(cls, options): del options yield 'FailingTest', () def _RunsFailingTest(self): assert False class ImplementsExpectationsFiles( serially_executed_browser_test_case.SeriallyExecutedBrowserTestCase): @classmethod def GenerateTestCases__RunsFailingTest(cls, options): del options yield 'a/b/fail-test.html', () def _RunsFailingTest(self): assert False @classmethod def GetJSONResultsDelimiter(cls): return '/' @classmethod def ExpectationsFiles(cls): return [os.path.join(util.GetTelemetryDir(), 'examples', 'browser_tests', 'example_test_expectations.txt')] class FlakyTest( serially_executed_browser_test_case.SeriallyExecutedBrowserTestCase): _retry_count = 0 @classmethod def GenerateTestCases__RunFlakyTest(cls, options): del options # Unused. yield 'a\\b\\c\\flaky-test.html', () def _RunFlakyTest(self): cls = self.__class__ if cls._retry_count < 3: cls._retry_count += 1 self.fail() return @staticmethod def GetJSONResultsDelimiter(): return '\\' class TestsWillBeDisabled( serially_executed_browser_test_case.SeriallyExecutedBrowserTestCase): @classmethod def GenerateTestCases__RunTestThatSkips(cls, options): del options yield 'ThisTestSkips', () @classmethod def GenerateTestCases__RunTestThatSkipsViaCommandLineArg(cls, options): del options yield 'SupposedToPass', () def _RunTestThatSkipsViaCommandLineArg(self): pass def _RunTestThatSkips(self): self.skipTest('SKIPPING TEST') class GetsExpectationsFromTyp( serially_executed_browser_test_case.SeriallyExecutedBrowserTestCase): @classmethod def GenerateTestCases__RunsWithExpectationsFile(cls, options): del options yield 'HasExpectationsFile', () @classmethod def GenerateTestCases__RunsWithoutExpectationsFile(cls, options): del options yield 'HasNoExpectationsFile', () def _RunsWithExpectationsFile(self): if (self.GetExpectationsForTest()[:2] == ({json_results.ResultType.Failure}, True)): return self.fail() def _RunsWithoutExpectationsFile(self): if (self.GetExpectationsForTest()[:2] == ({json_results.ResultType.Pass}, False)): return self.fail() def load_tests(loader, tests, pattern): # pylint: disable=invalid-name del loader, tests, pattern # Unused. return serially_executed_browser_test_case.LoadAllTestsInModule( sys.modules[__name__])
from segmentmodel import getSegModel from utils import vocabulary from PIL import Image import numpy as np import cv2 import os from scipy.misc import imsave from adjustTextPosition import adjust from ocrModel import getOCRModel from PIL import Image, ImageFont, ImageDraw, ImageOps im_heigth = 8*40 im_width = 16*40 input_shape = (im_heigth, im_width, 1) max_angle = 45 maskModel = getSegModel(input_shape) maskModel.load_weights('checkpoints/segmenter_vl0.0163.hdf5') ocrModel = getOCRModel() ocrModel.load_weights('checkpoints/OCRmodel_vl0.7638.hdf5') imgs = [os.path.join(root, f) for root, _, files in os.walk('./tmp1') for f in files if f.lower().endswith('.jpg')] def readLabel(label): vin = '' for charprobs in label: charid = np.argmax(charprobs) vin += vocabulary[charid] return vin for imgpath in imgs: savepath = imgpath.replace('tmp1', 'finalResults') img = Image.open(imgpath) img = img.resize((im_width, im_heigth)) img = np.array(img.convert('L')) np_img = img / 127.5 - 1 np_img = np.reshape(np_img, (1, im_heigth, im_width, 1)) mask = maskModel.predict(np_img)[0] mask *= 255 mask = mask.astype(np.uint8)[:, :, 0] res, newmask = adjust(img, mask) cropVin = np.expand_dims(np.array([cv2.resize(res,(32*16, 32)).astype(np.float)/127.5 -1]),axis=-1) label = ocrModel.predict(cropVin)[0] vin = readLabel(label) p = savepath.split('/')[:-1] p.append(vin + '.jpg') savepath = '/'.join(p) text_image = Image.new('L', (cropVin.shape[2], cropVin.shape[1]*2)) draw = ImageDraw.Draw(text_image) font = ImageFont.truetype('fonts/roboto/Roboto-Regular.ttf', 32) draw.text((0, 0), vin, font=font, fill=255) trueVin = imgpath.split('/')[-1].split('_')[0] draw.text((0, 32), trueVin, font=font, fill=200) res = np.vstack((cv2.resize(res, (cropVin.shape[2], cropVin.shape[1])), np.array(text_image))) imsave(savepath, res) print(savepath)
def create_pattern(length): uppercase_chars = 'ABCDEFGHIJKLMNOPQRSTUVXYZ' lowercase_chars = 'abcdefghijklmnopqrstuvxyz' number_chars = '0123456789' x = y = z = 0 pattern = '' while True: if len(pattern) < length: pattern += uppercase_chars[x] if len(pattern) < length: pattern += lowercase_chars[y] if len(pattern) < length: pattern += number_chars[z] if len(pattern) == length: return pattern z += 1 if x is 24: print ('[!] Maximum number of characters. Returning ' + str(len(pattern)) + ' characters!') return pattern if y is 24: y = 0 x += 1 if z is 10: z = 0 y += 1 def find_offset(string): pattern = create_pattern(17286) if string in pattern: index = pattern.index(string) return index else: return False
class Solution(object): def replaceElements(self, arr): j=0 if len(arr) == 1: arr[0]=-1 else: for j in range(len(arr)-1): print("j",j) if j == len(arr)-2: maxnum = arr[j+1] print(maxnum) for i in arr[j+1:]: if i>maxnum: maxnum = i arr[j] = maxnum arr[j+1] = -1 else: maxnum = arr[j+1] print(maxnum) for i in arr[j+1:]: if i>maxnum: maxnum = i arr[j] = maxnum print(maxnum) print("==========") print(arr) return arr def main(): s=Solution() array = [17,18,5,4,6,1] array2 = [400] array3 =[0,3,2,1] array4 =[0,1,2,3,4,5,6,7,8,9] s.replaceElements(array) s.replaceElements(array2) # s.replaceElements(array3) # s.replaceElements(array4) if __name__ == '__main__': main()
#!/usr/bin/env python3 """Extract reads from FASTA based on IDs in file""" import argparse import os import sys from Bio import SeqIO # -------------------------------------------------- def get_args(): """get args""" parser = argparse.ArgumentParser( description='Argparse Python script', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-r', '--reads', help='FASTA reads file', metavar='FILE', type=str, required=True) parser.add_argument('-i', '--ids', help='IDs file', metavar='FILE', type=str, required=True) parser.add_argument('-o', '--out', help='Output file', metavar='DIR', type=str, required=True) return parser.parse_args() # -------------------------------------------------- def main(): """main""" args = get_args() reads_file = args.reads ids_file = args.ids out_file = args.out if not os.path.isfile(reads_file): print('--reads "{}" is not a file'.format(reads_file)) sys.exit(1) if not os.path.isfile(ids_file): print('--ids "{}" is not a file'.format(ids_file)) sys.exit(1) out_dir = os.path.dirname(os.path.abspath(out_file)) if not os.path.isdir(out_dir): os.makedirs(out_dir) take_id = set() for line in open(ids_file): take_id.add(line.rstrip().split(' ')[0]) # remove anything after " " checked = 0 took = 0 with open(out_file, "wt") as out_fh: for record in SeqIO.parse(reads_file, "fasta"): checked += 1 if record.id in take_id: SeqIO.write(record, out_fh, "fasta") took += 1 print('Done, checked {} took {}, see {}'.format(checked, took, out_file)) # -------------------------------------------------- if __name__ == '__main__': main()
__author__ = 'wing' from clip_main import * def test_copy_bmp(): cit3 = ClipContentItem() cit3.cl_type = CL_IMAGE im = Image.open('2.png') cit3.cl_data = get_bmp_data(im) with open('a.bmp', 'wb') as f: f.write(cit3.cl_data) Mypb.copy(cit3) def test_copy_png(): cit3 = ClipContentItem() cit3.cl_type = CL_IMAGE im = Image.open('2.png') op = StringIO.StringIO() im.save(op,'PNG') cit3.cl_data=op.getvalue() Mypb.copy(cit3) def test_paste_img(): cit2 = Mypb.paste() print cit2.cl_type, cit2.cl_data if cit2.cl_type == CL_TEXT: print cit2.cl_data else: with open('b.png', 'wb') as f: f.write(cit2.cl_data) mointer = ClipMoniter() mointer.check()
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for `atkinson.pungi.depends` package.""" import copy import os import pytest from toolchest.genericargs import GenericArgs from atkinson.pungi.depends import rpmdep_to_dep, dep_to_tuple, dep_to_nevr from atkinson.pungi.depends import dep_to_rpmdep, nevr_to_dep, transmogrify_met from atkinson.pungi.depends import transmogrify_unmet, DependencySet def test_rpmdep_to_dep(): """Tests for rpmdep_to_dep""" with pytest.raises(ValueError): rpmdep_to_dep('foo 1.0') with pytest.raises(ValueError): rpmdep_to_dep('foo > 1.0-1-1') expected = {'name': 'foo'} assert rpmdep_to_dep('foo') == expected expected = {'name': 'foo', 'comparison': '>', 'version': '2.0'} assert rpmdep_to_dep('foo > 2.0') == expected expected = {'name': 'foo', 'comparison': '>=', 'release': '7', 'epoch': 1, 'version': '2.0'} assert rpmdep_to_dep('foo >= 1:2.0-7') == expected def test_dep_to_tuple(): """Test dep_to_tuple""" with pytest.raises(ValueError): dep_to_tuple('Hello') with pytest.raises(ValueError): dep_to_tuple({}) assert dep_to_tuple({'version': '1.0', 'release': '7'}) == (0, '1.0', '7') assert dep_to_tuple({'epoch': '2', 'version': '1.0', 'release': '7'}) == (2, '1.0', '7') def test_dep_to_nevr(): """Tests for dep_to_nevr function""" with pytest.raises(ValueError): dep_to_nevr({}) val = {'name': 'test', 'version': '1.0', 'release': '1.el7ost'} for key in val: val_copy = copy.copy(val) del val_copy[key] print(val_copy) with pytest.raises(ValueError): dep_to_nevr(val_copy) assert dep_to_nevr(val) == 'test-1.0-1.el7ost' val['epoch'] = 1 assert dep_to_nevr(val) == 'test-1:1.0-1.el7ost' def test_dep_to_rpmdep(): """Tests for dep_to_rpmdep function""" assert dep_to_rpmdep({'name': 'foo'}) == 'foo' assert dep_to_rpmdep({'name': 'foo', 'comparison': '>', 'version': '2.0'}) == 'foo > 2.0' assert dep_to_rpmdep({'name': 'foo', 'comparison': '>=', 'release': '7', 'epoch': '1', 'version': '2.0'}) == 'foo >= 1:2.0-7' def test_nevr_to_dep(): """Tests for nevr_to_dep function""" with pytest.raises(ValueError): nevr_to_dep('1.0-1') val = {'name': 'test', 'version': '1.0', 'release': '1.el7ost', 'comparison': '=='} assert nevr_to_dep('test-1.0-1.el7ost') == val val['epoch'] = 1 assert nevr_to_dep('test-1:1.0-1.el7ost') == val def test_transmogrify_met(): """Tests for transmogrify_met function""" val_one = GenericArgs() val_two = GenericArgs() val_one.sourcerpm = 'foo-1.2-1.src.rpm' val_one.epoch = 0 val_one.name = 'foo' val_one.version = '1.2' val_one.release = '1' val_two.sourcerpm = 'test-0.3-4.src.rpm' val_two.epoch = 1 val_two.name = 'test' val_two.version = '0.3' val_two.release = '4' vals = [val_one, val_two] deps = transmogrify_met(vals) assert dep_to_nevr(deps[0]) == 'foo-1.2-1' assert dep_to_nevr(deps[1]) == 'test-1:0.3-4' def test_transmogrify_unmet(): """Tests for transmogrify_unmet function""" deps_nevr = ['test-1:0.3-4', 'foo-1.2-1'] deps = [] expected = [] for dep in deps_nevr: expected.append(nevr_to_dep(dep)) deps.append(dep_to_rpmdep(nevr_to_dep(dep))) with pytest.raises(ValueError): transmogrify_unmet('') ret = transmogrify_unmet(deps) assert expected == ret def test_dependency_set_base(): """ Test the DependencySet class """ depset = DependencySet() assert depset.met == [] assert depset.unmet == [] assert depset.met == [] # Config injection conf = {'build_sources': {'koji-tag-1': ['http://localhost/1', 'http://localhost/1.1'], 'koji-tag-2': ['http://localhost/2']}} conf_copy = copy.copy(conf) depset = DependencySet(config={'build_sources': {'koji-tag-1': ['http://localhost/1', 'http://localhost/1.1'], 'koji-tag-2': ['http://localhost/2']}}) assert depset.config == conf_copy def test_dependency_set(datadir): """ Test loading a configuration file """ depset = DependencySet(config_file='test_build_sources.yml', config_path=datadir) print(depset.config) assert depset.config == {'build_sources': {'koji-tag-1': ['http://localhost/1', 'http://localhost/1.1'], 'koji-tag-2': ['http://localhost/2']}} # Invalid version with pytest.raises(ValueError): specfile = os.path.join(datadir, 'openstack-swift.spec') depset.get_spec_build_deps(specfile, 'invalid-version') # File not fount with pytest.raises(OSError): specfile = os.path.join(datadir, 'nonexistent') depset.get_spec_build_deps(specfile, 'koji-tag-1') # Don't load a directory with pytest.raises(ValueError): depset.get_spec_build_deps(datadir, 'koji-tag-1')
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os import sys import time import torch import logging cur_path = os.path.abspath(__file__) cur_dir = os.path.dirname(cur_path) par_dir = os.path.dirname(cur_dir) gra_dir = os.path.dirname(par_dir) grg_dir = os.path.dirname(gra_dir) sys.path.append(cur_dir) sys.path.append(par_dir) sys.path.append(gra_dir) sys.path.append(grg_dir) from pytorch_pretrained_xbert import RobertaConfig from pytorch_pretrained_xbert import RobertaTokenizer from baseline_cosmosqa_mask.run_mask_roberta_all_attn.config import parse_args from baseline_cosmosqa_mask.run_mask_roberta_all_attn.roberta_adamw import train from baseline_cosmosqa_mask.run_mask_roberta_all_attn.roberta_adamw import set_seed from baseline_cosmosqa_mask.run_mask_roberta_all_attn.util_feature import read_features from baseline_cosmosqa_mask.run_mask_roberta_all_attn.util_feature import InputFeatures from baseline_cosmosqa_mask.run_mask_roberta_all_attn.util_feature import CommonsenseFeatures from baseline_cosmosqa_mask.run_mask_roberta_all_attn.util_feature import DependencyFeatures from baseline_cosmosqa_mask.run_mask_roberta_all_attn.util_feature import EntityFeatures from baseline_cosmosqa_mask.run_mask_roberta_all_attn.util_feature import SentimentFeatures logging.basicConfig(format='%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt='%m/%d/%Y %H:%M:%S', level=logging.INFO) logger = logging.getLogger(__name__) def main(): args = parse_args() args.n_gpu = torch.cuda.device_count() set_seed(args) if args.model_choice == "large": args.per_gpu_train_batch_size = 1 args.per_gpu_eval_batch_size = 2 args.model_name_or_path = os.path.join(grg_dir, "pretrained_model/roberta-large") elif args.model_choice == "base": args.per_gpu_train_batch_size = 3 args.per_gpu_eval_batch_size = 4 args.model_name_or_path = os.path.join(grg_dir, "pretrained_model/roberta-base") else: raise ValueError args.train_batch_size = args.per_gpu_train_batch_size * max(1, args.n_gpu) args.eval_batch_size = args.per_gpu_eval_batch_size * max(1, args.n_gpu) os.makedirs(args.output_dir, exist_ok=True) if args.model_choice == "base": if args.bert_model_choice == "fusion_head": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_base_attn import \ RobertaForMultipleChoice_Fusion_Head as RobertaForMultipleChoice elif args.bert_model_choice == "fusion_layer": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_base_attn import \ RobertaForMultipleChoice_Fusion_Layer as RobertaForMultipleChoice elif args.bert_model_choice == "fusion_all": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_base_attn import \ RobertaForMultipleChoice_Fusion_All as RobertaForMultipleChoice elif args.bert_model_choice == "fusion_head_bert_attn": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_base_attn import \ RobertaForMultipleChoice_Fusion_Head_Bert_Self_Attn as RobertaForMultipleChoice else: raise ValueError elif args.model_choice == "large": if args.bert_model_choice == "fusion_head": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_large_attn import \ RobertaForMultipleChoice_Fusion_Head as RobertaForMultipleChoice elif args.bert_model_choice == "fusion_layer": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_large_attn import \ RobertaForMultipleChoice_Fusion_Layer as RobertaForMultipleChoice elif args.bert_model_choice == "fusion_all": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_large_attn import \ RobertaForMultipleChoice_Fusion_All as RobertaForMultipleChoice elif args.bert_model_choice == "fusion_head_bert_attn": from baseline_cosmosqa_mask.model.model_mask_roberta_all.model_large_attn import \ RobertaForMultipleChoice_Fusion_Head_Bert_Self_Attn as RobertaForMultipleChoice else: raise ValueError else: raise ValueError config_class, model_class, tokenizer_class = RobertaConfig, RobertaForMultipleChoice, RobertaTokenizer config = config_class.from_pretrained(args.config_name if args.config_name else args.model_name_or_path, num_labels=4, finetuning_task=args.task_name) tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path, do_lower_case=args.do_lower_case) model = model_class.from_pretrained(args.model_name_or_path) train_dataset, dev_dataset = read_features(args) # Training if args.do_train: print("[TIME] --- time: {} ---, start train".format(time.ctime(time.time()))) global_step, tr_loss, best_step = train(args, train_dataset, dev_dataset, model) logger.info(" global_step = %s, average loss = %s, best_step = %s", global_step, tr_loss, best_step) if __name__ == "__main__": main()
# Global variable section STANDARD_ARABIC_TO_ROMAN = ((1000, "M"), (900, "CM"), (500, "D"), (400, "CD"),(100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I")) # Maximum arabic number to convert to to roman MAX_NUM_TO_CONVERT = 3999 def convert_arabic_to_roman(arabic_number, is_negative=False): # Initiating list for resulting roman number result_roman = [] # Case 1: Check if the number is not an integer try: int_arab = int(arabic_number) except ValueError: raise ValueError("Provided Arabic number is not an " "integer, Please provide integer") # Case 2: Check if the number is Negative if int_arab < 0: # Check if is_negative parameter is true if is_negative: # If user set the parameter is_negative is true and # Want to convert negative number to roman then it is a valid case # for this reason, get the absolute value of the number # The number should be below than the 3999 # Convert the arabic number to roman and append "-" in front of it if abs(int_arab) <= MAX_NUM_TO_CONVERT: result_roman.append("-") int_arab = abs(int_arab) else: raise ValueError("Provided number should be below 3999") else: # If the user didn't set the is_negative parameter as True # Then it will be a invalid case. User should get notified # regarding the error and rerun with correct parameter raise ValueError("Provided number is negative, please rerun" " with \"is_negative = True\" as parameter") # Case 3: Check if the number is in the allowed limit # If the number is equal to zero or it exceeds the maximum number # Then raise an error to show to the user if int_arab == 0 or int_arab > MAX_NUM_TO_CONVERT: raise ValueError("Provided value should be inside the range of 1 and 3999") else: # Main code block to convert arabic to roman number # here the processing will be done in below steps # Step 1. Loop through the tuple of STANDARD_ARABIC_TO_ROMAN # and get the arabic number # for each arabic number in the tuple, # Step 2. Divide the provided number with arabic number and # get the result(no_of_times) # Step 3. Add corresponding roman character to the result, # that many times with the result in previous step. # Step 4. Once addition of roman number is done, then # deduct the value of no_of_time* arabic number from the provided number # As example, if the provided number is 127, then first divisible arabic number # will be 100, whose roman character is C. as 127 is divisible by 100 # for 1 time, so append the resulting list with C for one time # and once appending of roman number is done, then deduct 100*1 from # 127. So, the resulting number will be 127 -100 = 27. # Then in the next iteration, once 10 comes from the Tuple, it will work # in the same way. # Continue the first loop, till it reaches the end of tuple # Step 5: Join every roman character in the result list and return # Step 1 for arabic, roman in STANDARD_ARABIC_TO_ROMAN: # Step 2 no_of_time = int_arab//arabic # print(no_of_time) # Step 3 for unused_var in range(no_of_time): result_roman.append(roman) # Step 4 int_arab -= no_of_time*arabic # Step 5 return "".join(result_roman)
# 상속 : 클래스를 정의할때 부모 클래스를 지정하는 것 from turtle import* class MyTurtle(Turtle): def glow(self, x, y): self.fillcolor("red") turtle = MyTurtle() turtle.shape("turtle") turtle.onclick(turtle.glow) # 거북이 클릭하면 색상이 빨강색으로 변경 # class Person: def greeting(self): print("안녕하세요") class Student(Person): def study(self): print("공부하기") jk = Person() jg = Student() jg.greeting() jg.study() jk.greeting() jk.study() # 오류 # 정보은닉 (구현의 세부 사항을 클래스 안에 감추는 것) : __어쩌구 class Person: def __init__(self, name, age, address, wallet): self.hello = "안녕하세요" self.name = name self.age = age self.address = address self.__wallet = wallet def getWallet(self): return jg.__wallet jg = Person("신짱구", 5, "떡잎마을", 10000) print(jg.name) #print(jg.__wallet) print(jg.getWallet()) # 접근자 : 인스턴스 변수값을 반환 (get으로 시작) # 설정자 : 인스턴스 변수값을 설정 (set으로 시작) class Student: def __init__(self, name = None, age=0): self.__name = name self.__age = age def getAge(self): return self.__age def getName(self): return self.__name def setAge(self, age): self.__age = age def setName(self, name): self.__name = name obj = Student("Hong", 20) print(obj.getName()) # 터틀그래픽보기 # 상위 클래스 : super()
a=[] length=int(input("no of elements")) def insert(): global length for i in range(0,length): element=int(input(" ")) a.append(element) def search(): global length j=0 element=int(input(" element to search")) while(j<length): if(element==a[j]): print("element found %d" % (a[j]) ) break else: j=j+1 print("value not found") def display(): global length for i in range(0,length): print(a[i]) insert() search() display()
# -*- coding: utf-8 -*- from __future__ import unicode_literals import os from django.db import models from django.utils import timezone EIGENSCHAFTEN = dict( {"GE": "Gewandheit", "KK": "Körperkraft", "KO": "Konstitution", "KL": "Klugheit", "MU": "Mut", "CH": "Charisma", "FF": "Fingerfertigkeit", "IN": "Intuition"} ) UNITS = dict( {"SK": "Stück", "ST": "Stein", "UZ": "Unze", "SR": "Skrupel", "MS": "Maß", "SN": "Schank", "FX": "Flux"} ) class Race(models.Model): name = models.TextField(default="Mensch") def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name class HeroType(models.Model): name = models.CharField(max_length=200, default="Krieger") knowsMagic = models.BooleanField(default=False) def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name # Create your models here. class Character(models.Model): GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) id = models.AutoField(primary_key=True) gender = models.CharField( max_length=1, choices=GENDER_CHOICES, default="M") avatar = models.ImageField(upload_to='', blank=True, null=True) avatar_small = models.ImageField(upload_to='', blank=True, null=True) name = models.CharField(max_length=200, default="tbd") race = models.ForeignKey("Race") type = models.ForeignKey("HeroType") money_dukaten = models.SmallIntegerField(default=0) money_silbertaler = models.SmallIntegerField(default=0) money_heller = models.SmallIntegerField(default=0) money_kreuzer = models.SmallIntegerField(default=0) armor = models.SmallIntegerField(default=1) culture = models.CharField(max_length=200, default="") social_rank = models.SmallIntegerField(default=0) size = models.SmallIntegerField(default=175) # eigenschaften MU = models.SmallIntegerField(default=0) KL = models.SmallIntegerField(default=0) IN = models.SmallIntegerField(default=0) CH = models.SmallIntegerField(default=0) FF = models.SmallIntegerField(default=0) GE = models.SmallIntegerField(default=0) KO = models.SmallIntegerField(default=0) KK = models.SmallIntegerField(default=0) experience = models.SmallIntegerField(default=0) experience_used = models.SmallIntegerField(default=0) life = models.SmallIntegerField(default=30) life_lost = models.SmallIntegerField(default=0) magic_energy = models.SmallIntegerField(default=30) magic_energy_lost = models.SmallIntegerField(default=30) magic_energy = models.SmallIntegerField(default=30) magic_energy_lost = models.SmallIntegerField(default=0) hair_color = models.CharField(max_length=200, default="") eye_color = models.CharField(max_length=200, default="") weight = models.SmallIntegerField(default=70) created_date = models.DateTimeField( default=timezone.now) def publish(self): self.created_date = timezone.now() self.save() def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name def setAttribute(self, attribute, value): setattr(self, attribute, value) def __getitem__(self, key): return getattr(self, key) class WeaponSkillDistribution(models.Model): attack = models.SmallIntegerField(default=0) parade = models.SmallIntegerField(default=0) character = models.ForeignKey("Character", default=1) skill = models.ForeignKey("Skill", default=1) def __str__(self): return self.character.name + " - " + self.skill.name class ActualSkill(models.Model): value = models.SmallIntegerField(default=0) skill = models.ForeignKey("Skill") character = models.ForeignKey("Character", default=1) def __str__(self): return self.character.name + " - " + self.skill.name + " - " + str(self.value) class ActualSpellSkill(models.Model): value = models.SmallIntegerField(default=0) spell = models.ForeignKey("Spell") character = models.ForeignKey("Character", default=1) def __str__(self): return self.character.name + " - " + self.spell.name + " - " + str(self.value) class Weapon(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) skill = models.ForeignKey("Skill") hit_dices = models.SmallIntegerField(default=1) hit_add_points = models.SmallIntegerField(default=2) hit_extra_from_kk = models.SmallIntegerField(default=14) def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name class CharacterHasWeapon(models.Model): character = models.ForeignKey("Character") weapon = models.ForeignKey("Weapon") def __str__(self): return self.character.name + " / " + self.weapon.name class Armor(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) ruestungs_schutz = models.SmallIntegerField(default=1) behinderung = models.SmallIntegerField(default=2) def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name class CharacterHasArmor(models.Model): character = models.ForeignKey("Character") armor = models.ForeignKey("Armor") def __str__(self): return self.character.name + " / " + self.armor.name class Skill(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, default="") type = models.ForeignKey("SkillType") behinderung = models.CharField(max_length=4, default="") weaponSkill = models.BooleanField(default=False) dice1 = models.CharField( max_length=2, choices=EIGENSCHAFTEN.items(), default="") dice2 = models.CharField( max_length=2, choices=EIGENSCHAFTEN.items(), default="") dice3 = models.CharField( max_length=2, choices=EIGENSCHAFTEN.items(), default="") basis = models.BooleanField() def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name class SkillType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, default="") skill_group = models.ForeignKey("SkillGroup") def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name class SkillGroup(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=1, default="D") title = models.CharField(max_length=50, default="") cost_per_increase = models.SmallIntegerField(default=5) def __str__(self): return self.name + ": " + self.title def __unicode__(self): # You have __str__ return self.name class Spell(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200, default="") type = models.ForeignKey("SpellType") dice1 = models.CharField( max_length=2, choices=EIGENSCHAFTEN.items(), default="") dice2 = models.CharField( max_length=2, choices=EIGENSCHAFTEN.items(), default="") dice3 = models.CharField( max_length=2, choices=EIGENSCHAFTEN.items(), default="") basis = models.BooleanField() def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name class SpellType(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=50, default="") def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name class InventoryItem(models.Model): id = models.AutoField(primary_key=True) character = models.ForeignKey("Character") name = models.CharField(max_length=200, default="") amount = models.SmallIntegerField(default=1) unit = models.CharField( max_length=2, choices=UNITS.items(), default="SK") weight = models.SmallIntegerField(default=1) def __str__(self): return self.name def __unicode__(self): # You have __str__ return self.name
from urllib.request import urlopen as uReq from bs4 import BeautifulSoup as soup dal_InstituteCentres_url = 'https://www.dal.ca/research/centres_and_institutes.html' #opening up connection and grabbing the pages uClient = uReq(dal_InstituteCentres_url) page_html = uClient.read() uClient.close() #html parser page_soup = soup(page_html, "html.parser") InstituteCentre_container = page_soup.findAll("div", attrs={"class":"text parbase section"}) #num_iCenters = print(len(instituteCenter_container)) #icentres = instituteCenter_container[1] f = open("Dal_ResearchInstitute.xml", "w+", encoding = 'utf-8') # .write("<?xml version= "1.0" endcoding = \"utf-8\"?>") f.write("<table name = \"Dal_Institute_Centre\">") i = 0 for centres in InstituteCentre_container[1:]: InstituteCentreName = centres.findAll('li') for centreNames in InstituteCentreName: i = i+1 f.write("<record><column name=\"InstituteCentreId\">" + str(i) + "</column>") f.write("<column name=\"InstituteCentreName\">" + centreNames.text.replace('&', '') + "</column></record>") #print(centerNames.text) f.write("</table>")
# Generated by Django 3.1.1 on 2020-10-05 08:46 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('events', '0002_password'), ] operations = [ migrations.CreateModel( name='Programme', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('date', models.DateField(default=None)), ('time', models.TimeField(default=None)), ('title', models.CharField(default=None, max_length=50)), ('speaker', models.CharField(default=None, max_length=50)), ('presenter', models.CharField(default=None, max_length=50)), ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='events.event')), ], ), ]
import time import numpy as np import aesara y = aesara.tensor.type.fvector() x = aesara.shared(np.zeros(1, dtype="float32")) f1 = aesara.function([y], updates={x: y}) f2 = aesara.function([], x.transfer("cpu")) print(f1.maker.fgraph.toposort()) print(f2.maker.fgraph.toposort()) for i in (1, 10, 100, 1000, 10000, 100000, 1000000, 10000000): o = np.zeros(i, dtype="float32") t0 = time.perf_counter() f1(o) t1 = time.perf_counter() tf1 = t1 - t0 t0 = time.perf_counter() f2() t1 = time.perf_counter() print("%8i %6.1f ns %7.1f ns" % (i, tf1 * 1e6, (t1 - t0) * 1e6))
import os, shutil import json import random import cv2 import numpy as np from utils import get_path from grad_cam import get_net, get_img_and_mask def get_word_img_map(): with open(get_path('params/synsets.json'), 'r', encoding='utf-8') as f: context = f.read() synsets = json.loads(context) with open(get_path('params/word_list.json'), 'r', encoding='utf-8') as f: context = f.read() word_list = json.loads(context) # 筛选可以用到的图片 word_img_map = {} img_class_map = {} with open(get_path('img_datasets/caffe_ilsvrc12/val.txt'), 'r') as file: lines = file.readlines() for line in lines: ptr = line.index(' ') fn = line[:ptr] idx = int(line[ptr + 1:].strip()) if os.path.exists(get_path('img_datasets/ILSVRC2012_img_val/' + fn)): flag = False for w in synsets[idx]: if w in word_list: if w not in word_img_map: word_img_map[w] = [] word_img_map[w].append(fn) flag = True if flag: img_class_map[fn] = idx return word_img_map, img_class_map # 对word_img_map进行压缩,每个词随机挑选k张图片 def random_sample_word_img_map(word_img_map, k): for w in word_img_map: word_img_map[w] = random.sample(word_img_map[w], k) # 生成图片与cam mask def process_cam(net, img_path, class_id, output_dir): img, mask = get_img_and_mask(net, img_path, class_id) # 拼接图片 pic = np.concatenate([img, mask], axis=1) pic = np.uint8(pic * 255) path = os.path.join(output_dir, os.path.basename(img_path)) cv2.imwrite(path, pic, [int(cv2.IMWRITE_JPEG_QUALITY), 50]) def process_img(): print('生成插图中...') if not os.path.exists(get_path('img_datasets/ILSVRC2012_img_val')) or not os.path.exists(get_path('img_datasets/caffe_ilsvrc12')): print('生成插图跳过') return net = get_net() word_img_map, img_class_map = get_word_img_map() print(list(word_img_map.keys())) random_sample_word_img_map(word_img_map, 5) with open(get_path('params/word_img_map.json'), 'w', encoding='utf-8') as file: file.write(json.dumps(word_img_map, ensure_ascii=False)) output_dir = get_path('imgs') if not os.path.exists(output_dir): os.mkdir(output_dir) imgs = set(fn for w in word_img_map for fn in word_img_map[w]) i = 0 for fn in imgs: if not os.path.exists(get_path('imgs/' + fn)): process_cam(net, get_path('img_datasets/ILSVRC2012_img_val/' + fn), img_class_map[fn], output_dir) i += 1 print(f'({i}/{len(imgs)})') print('插图生成完成') if __name__ == '__main__': process_img()
# -*- coding: utf-8 -*- from django import forms from .models import * from django.conf import settings class RegistroRepositorForm (forms.Form): nombres = forms.CharField(max_length=100,required=True) apellidos = forms.CharField(max_length=100, required=True) email = forms.CharField(required= False) legajo = forms.CharField(max_length=100, required= False) username = forms.CharField(max_length=100, required=True) class RegistroSupervisorForm (forms.Form): nombres = forms.CharField(max_length=100,required=True) apellidos = forms.CharField(max_length=100, required=True) email = forms.CharField(required= True) username = forms.CharField(max_length=100, required=True) class EditarRepositorForm (forms.ModelForm): class Meta: model = Usuario fields = '__all__' #exclude = ('usuario',)
# Searching for an element in the list. # IN operator # Linear search my_list = [10,20,30,40,50,60,70,80,90] print(f"My list: {my_list}") # IN operator print("\nSearching a value by IN operator:") value = 20 if value in my_list: print(f"- The index of {value} value is {my_list.index(value)}.") else: print("- The value does not exist in the list.") # Linear search print("\nSearching a value by linear search:") def searching_list(list, value): for i in list: if i == value: return f"- The index of {value} value is {my_list.index(value)}." return "- The value does not exist in the list." value = 50 print(searching_list(my_list, value)) value = 100 print(searching_list(my_list, value))
import shelve import os def save_game(player, entities, game_map, log, game_state): with shelve.open('save_game', 'n') as file: file['player_index'] = entities.index(player) file['entities'] = entities file['game_map'] = game_map file['log'] = log file['game_state'] = game_state def load_game(): if not os.path.isfile('save_game.dat') and not ('save_game'): raise FileNotFoundError with shelve.open('save_game', 'r') as file: player_index = file['player_index'] entities = file['entities'] game_map = file['game_map'] log = file['log'] game_state = file['game_state'] #needed to ensure that all references are correct internally player = entities[player_index] game_map.player = player game_map.entities = entities return (player, entities, game_map, log, game_state)
import json import logging from multiprocessing import Process from threading import Thread from logging_utils.generator import generate_logger, generate_writer_logger from src.exchangeconnector import ExchangeConnector from src.storage import Storage from src.static import * import time class Executor(Thread): def __init__(self, ctx: AppContext, exchange_connector: ExchangeConnector, storage: Storage): Thread.__init__(self) self.ctx = ctx self.exchange_connector = exchange_connector self.storage = storage self.logger = generate_logger('executor') self.writer_logger = generate_writer_logger('executor-writer') def _execute(self): # removing positions with low size for pos in self.storage.get_positions_by_state(state=State.READY_TO_OPEN)[:]: if pos.amount < self.exchange_connector.min_sizes[pos.ticker]: self.storage.data.remove(pos) self.logger.critical('Position was removed due to the low amount:\n {pos}'.format(pos=pos)) self.writer_logger.critical(json.dumps({'result': 'removed_low_amount', 'position:': pos.__dict__})) self.storage.dump() # executing positions for pos in self.storage.data: if pos.state == State.READY_TO_OPEN: self.logger.debug('found position to OPEN:\n {pos}'.format(pos=pos)) result = self.exchange_connector.place_order(pos.ticker, pos.side, pos.amount) if result is not None: pos.amount = result['amount'] pos.order_id = result['order_id'] pos.timestamp = result['timestamp'] pos.state = State.OPENED self.logger.warning('Position successfully opened:\n {pos}'.format(pos=pos)) self.writer_logger.critical(json.dumps({'result': 'opened', 'position:': pos.__dict__})) else: self.logger.critical('Position was not opened!:\n {pos}'.format(pos=pos)) self.writer_logger.critical(json.dumps({'result': 'not_opened', 'position:': pos.__dict__})) self.storage.dump() if pos.state == State.READY_TO_CLOSE: self.logger.debug('found position to CLOSE:\n {pos}'.format(pos=pos)) result = self.exchange_connector.place_order(pos.ticker, Action.invert(pos.side), pos.amount) if result is not None: pos.state = State.CLOSED self.logger.warning( 'Position successfully closed (state changed to CLOSED:\n {pos}'.format(pos=pos)) self.writer_logger.critical(json.dumps({'result': 'closed', 'position:': pos.__dict__})) else: self.logger.critical('Position was not closed!:\n {pos}'.format(pos=pos)) self.writer_logger.critical(json.dumps({'result': 'not_closed', 'position:': pos.__dict__})) self.storage.dump() # removing positions with state=CLOSED for pos in self.storage.get_positions_by_state(state=State.CLOSED)[:]: self.storage.data.remove(pos) self.logger.warning('Position(state=CLOSED) successfully removed:\n {pos}'.format(pos=pos)) self.writer_logger.critical(json.dumps({'result': 'removed_closed', 'position:': pos.__dict__})) self.storage.dump() def execute(self): return self._execute() def run(self): self.logger.critical('Executor started') while True: if self.ctx.app_exit: return time.sleep(0.1) try: with self.storage.lock: start_time = datetime.datetime.now() self._execute() execution_time = datetime.datetime.now() - start_time self.ctx.info['executor_latency'] = execution_time.total_seconds() except Exception as e: self.logger.critical('EXECUTOR IS DOWN!') self.ctx.executor_fault = True raise e
import pymongo import scrapy from weibotest.items import BaseInfoItem from weibotest.items import WeiboInfoItem import re import datetime import json import traceback from weibotest.settings import MONGO_HOST, MONGO_PORT, MONGO_DB_NAME, SCHOOL_BASE_INFO class WeiboSpider(scrapy.Spider): name = "weibo" # url 组成 url_1="https://weibo.cn/" # 用户 id: 现从文件读取 url_2 = [ # 'nju1902' ] url_3 = "?page=" # 起始页面 url_4 = 2202 # 当前高校下标(0~107) url_5 = 88 # TODO: 起始高校位置 # 当前高校总微博数 weiboNum = 3058 # 模拟请求相关 headers = { 'user-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50' } meta = { 'dont_redirect': True, # 禁止网页重定向 'handle_httpstatus_list': [301, 302] # 对哪些异常返回进行处理 } cookies = { '_T_WM': '43586327469', 'ALF': '1572708198', 'SCF': 'Ath3LGFZX0FTfy5B1hPlXwqPBhTi85tlI__-vO50T-QtwVFOA8qTZQHnYu9WvdPwQ3zfeo07OVpU2CoVH7jE3Lw.', 'SUB': '_2A25wkmIoDeRhGedI7lER9i_Jzj6IHXVQfQ5grDV6PUJbktAKLWn8kW1NVzqyC3OH20h5draiHZcnyiIbKjKFDlcg', 'SUBP': '0033WrSXqPxfM725Ws9jqgMF55529P9D9Whnyn0O9rOclhlg5fY2Qk5O5JpX5K-hUgL.Fo2cSKe7So2fSKz2dJLoIpH1IgUQU8iyIg4KdNHV9GSFdNiDdJMt', 'SUHB': '06ZUp17PgQTv88', 'SSOLoginState': '1570116217' } def parse(self, response): if self.url_4 == 1: name = self.url_2[self.url_5] wb = response.xpath('/html/body/div[@ class="u"]/div/span/text()').extract() wb = wb[0][3:len(wb[0])-1] fans = response.xpath('/ html / body / div[@ class="u"] / div / a[2] / text()').extract() fans = fans[0][3:len(fans[0])-1] follows = response.xpath('/ html / body / div[@ class="u"] / div / a[1] / text()').extract() follows = follows[0][3:len(follows[0])-1] # self.weiboNum = int(wb)/10 item = BaseInfoItem() item['id'] = name # 名称 item['wb'] = wb # 微博数 item['fans'] = fans # 粉丝数 item['follows'] = follows # 关注数 yield item print(name) print("微博数: "+wb) print("粉丝数: "+fans) print("关注数: "+follows) # 获取下一个要爬取的 url url = self.get_next_url() if len(url) != 0: yield scrapy.Request(url, callback=self.parse, headers=self.headers, cookies=self.cookies) def start_requests(self): # 重写了start_requests方法,可以按照自定义顺序爬取界面 with open('weibotest/schools.js', 'r', encoding='UTF-8') as f: sch_array = json.loads(f.read()) for sch in sch_array["university_list"]: self.url_2.append(sch['id']) print(sch['id']) return [ scrapy.Request(self.get_next_url(), callback=self.sub_parse, headers=self.headers, cookies=self.cookies) ] def get_next_url(self): if self.url_5 < 90: # TODO: 结束高校位置 url = self.url_1 + self.url_2[self.url_5] + self.url_3 if self.url_4 < self.weiboNum: url = url+str(self.url_4) self.url_4 = self.url_4+1 else: self.url_5 = self.url_5+1 if self.url_5 == len(self.url_2) or self.url_5 ==90: # TODO: 结束高校位置 return '' self.url_4 = 1 url = self.url_1 + self.url_2[self.url_5] + self.url_3 url = url + str(self.url_4) self.url_4 = self.url_4 + 1 return url else: return "" def sub_parse(self,response): if self.url_4 == 2: # print(self.weiboNum) wbPage = response.xpath('/html/body/div[@ id="pagelist"]/form/div/text()').extract() self.weiboNum = wbPage[-1][str(wbPage[-1]).index('/')+1:len(wbPage[-1])-1] # print(wbPage) self.weiboNum = int(self.weiboNum) print(self.weiboNum) for i in range(1, len(response.xpath('/html/body/div[@ class="c"]'))-1): try: item = WeiboInfoItem() repost = response.xpath( '/html/body/div[@ class="c"][' + str(i) + ']/div[1]/span[1][@ class="cmt"]/a/text()').extract() if len(repost) == 0: # 原创微博 content = '' contents = response.xpath('/html/body/div[@ class="c"][' + str(i) + ']/div[last()]').css( '*::text').extract() contents2 = response.xpath('/html/body/div[@ class="c"][' + str(i) + ']/div[1]').css( '*::text').extract() # print(contents) # print(contents[-2][-2:-1]) if contents[-2][-2:-1] == '来': contents = contents[0:len(contents)-1] # print(contents) # print(contents2) if contents[1] != '原图': imgs = 0 contents2 = contents2[0:len(contents2)-10] else: if len(contents2) == 1: imgs = 1 elif contents2[-2][0:2] == '组图': imgs = contents2[-2][3] else: imgs = 1 item['id'] = self.url_2[self.url_5] item['repost'] = '' item['tag'] = [] item['at'] = [] item['imgNum'] = imgs item['likeNum'] = contents[-9][2:len(contents[-9]) - 1] item['repostNum'] = contents[-7][3:len(contents[-7]) - 1] item['commentNum'] = contents[-5][3:len(contents[-5]) - 1] item['time'] = self.get_time(contents[-1]) temp = response.xpath('/html/body/div[@ class="c"][' + str(i) + ']/div[1]/span/a[last()]') if len(temp.xpath('text()').extract()) == 0: if len(contents2) >= 3: if contents2[-3] == '收藏': for j in range(0, len(contents2) - 11): content = content + contents2[j] else: if contents2[-1] == ']': for j in range(0, len(contents2) - 3): content = content + contents2[j] else: for j in range(0, len(contents2)): content = content + contents2[j] elif contents2[-1] == ']': for j in range(0, len(contents2) - 3): content = content + contents2[j] else: for j in range(0, len(contents2)): content = content + contents2[j] item['content'] = content item['tag'] = self.get_tags(item['content']) item['at'] = self.get_ats(item['content']) # self.print_weibo_info_item(item) yield item elif (temp.xpath('text()').extract())[0] == '全文': # 如果需要访问全文 # 有备无患,用于在无法访问详情界面时得到大致内容 if len(contents2) >= 3: if contents2[-3] == '收藏': for j in range(0, len(contents2) - 11): content = content + contents2[j] else: if contents2[-1] == ']': for j in range(0, len(contents2) - 3): content = content + contents2[j] else: for j in range(0, len(contents2)): content = content + contents2[j] elif contents2[-1] == ']': for j in range(0, len(contents2) - 3): content = content + contents2[j] else: for j in range(0, len(contents2)): content = content + contents2[j] item['content'] = content item['tag'] = self.get_tags(item['content']) item['at'] = self.get_ats(item['content']) # 访问具体内容 mRequest = scrapy.Request('https://weibo.cn' + (temp.xpath('@href').extract())[0], callback=self.get_content, headers=self.headers, cookies=self.cookies, priority=1) mRequest.meta['item'] = item yield mRequest else: # 不需要访问全文 if len(contents2) >= 3: if contents2[-3] == '收藏': for j in range(0, len(contents2) - 11): content = content + contents2[j] else: if contents2[-1] == ']': for j in range(0, len(contents2) - 3): content = content + contents2[j] else: for j in range(0, len(contents2)): content = content + contents2[j] elif contents2[-1] == ']': for j in range(0, len(contents2) - 3): content = content + contents2[j] else: for j in range(0, len(contents2)): content = content + contents2[j] item['content'] = content item['tag'] = self.get_tags(item['content']) item['at'] = self.get_ats(item['content']) # self.print_weibo_info_item(item) yield item else: # 转发的微博 contents = response.xpath('/html/body/div[@ class="c"][' + str(i) + ']/div[last()]').css( '*::text').extract() content = '' if contents[-2][-2:-1] == '来': contents = contents[0:len(contents)-1] for i in range(1, len(contents) - 9): content = content + contents[i] item['id'] = self.url_2[self.url_5] item['repost'] = repost[0] item['imgNum'] = 0 item['likeNum'] = contents[-9][2:len(contents[-9]) - 1] item['repostNum'] = contents[-7][3:len(contents[-7]) - 1] item['commentNum'] = contents[-5][3:len(contents[-5]) - 1] item['time'] = self.get_time(contents[-1]) item['content'] = content item['tag'] = self.get_tags(item['content']) item['at'] = self.get_ats(item['content']) # self.print_weibo_info_item(item) yield item except Exception as e: # print(e) print(traceback.format_exc()) pass continue url = self.get_next_url() if len(url) != 0: yield scrapy.Request(url, callback=self.sub_parse, headers=self.headers, cookies=self.cookies) def get_content(self, response): item = response.meta['item'] contents = response.xpath('/html/body/div[@ id="M_"]/div').css('*::text').extract() content = '' if contents[-11] == '原图': if contents[-14][0:2] == '组图': for i in range(4, len(contents) - 15): content = content + contents[i] else: for i in range(4, len(contents) - 13): content = content + contents[i] else: for i in range(4, len(contents) - 10): content = content + contents[i] item['content'] = content item['tag'] = self.get_tags(item['content']) item['at'] = self.get_ats(item['content']) # self.print_weibo_info_item(item) yield item def print_weibo_info_item(self,item): # 打印类,可解开注释使用 print("大学id: " + item['id']) print("转发: " + item['repost']) print("内容: " + item['content']) print("点赞数: " + item['likeNum']) print("转发数: " + item['repostNum']) print("评论数: " + item['commentNum']) print("发博时间: " + item['time']) print(item['tag']) print(item['at']) print("图片数: "+str(item['imgNum'])) def get_tags(self, content): pattern = re.compile(r'\#[^\#]*\#') result = pattern.findall(content) return result def get_ats(self, content): pattern=re.compile(r'\@[^ ]*') result = pattern.findall(content) return result def get_time(self, mTime): # print(mTime) result = '' mTime = mTime.split() if mTime[0][-1] == '前': m=int(mTime[0][0:len(mTime[0])-3]) result=(datetime.datetime.now()-datetime.timedelta(minutes=m)).strftime('%Y-%m-%d %H:%M') return result if mTime[0] == '今天': result = datetime.datetime.now().strftime('%Y-%m-%d') elif mTime[0][2:3] == '月': result = datetime.datetime.now().strftime('%Y')+'-'+mTime[0][0:2]+'-'+mTime[0][3:5] else: result = mTime[0] result = result + ' ' + mTime[1][0:5] return result
def negativo (numero): resultado = "" for digito in numero: if digito == "1": resultado += "0" elif digito == "0": resultado += "1" return resultado def rotar_izq (numero): inicial = numero[:1] resultado = numero[1:] + inicial return resultado def rotar_der (numero): final = numero[-1] resultado = final + numero[:-1] return resultado def desp_izq (numero): resultado = numero[1:] + "0" return resultado def desp_der (numero): resultado = "0" + numero[:-1] return resultado def sumar_int (a, b): carry = "0" a = a[::-1] b = b[::-1] resultado = "" for i in range(len(a)): if carry == "1": if a[i] == "1" and b[i] == "1": resultado += "1" elif a[i] == "0" and b[i] == "0": resultado += "1" carry = "0" else: resultado += "0" else: if a[i] == "1" and b[i] == "1": resultado += "0" carry = "1" elif a[i] == "0" and b[i] == "0": resultado += "0" else: resultado += "1" resultado += carry return resultado[::-1] def sumar_restar_float (a, b, operacion): cero = "0" if a[1:6] == "00000": return b elif b[1:6] == "00000": return a a_mant = "1" + a[6:16] b_mant = "1" + b[6:16] if menor(a[1:6], b[1:6]): exp = b[1:6] mover = bin_to_dec(restar_int(b[1:6], a[1:6])[1:]) for i in range(mover): a_mant = desp_der(a_mant) else: exp = a[1:6] mover = bin_to_dec(restar_int(a[1:6], b[1:6])[1:]) for i in range(mover): b_mant = desp_der(b_mant) if operacion == "sumar": res = sumar_int(a_mant, b_mant) else: res = restar_int(a_mant, b_mant) if menor(a[1:6], b[1:6]): cero = "1" while len(res) > 11: if res[0] == "1": exp = restar_int(exp, "00001")[1:] if res[11] == "1": res = sumar_int(res, "0"* 11 + "1")[:12] else: res = res[1:12] if res[0] == "0": res = res[1:] if len(res) == 10: res += "0" return cero + exp + res[1:] def restar_int (a, b): b = negativo(b) uno = "0" * (len(a) - 1) + "1" b = sumar_int(b, uno)[1:] return sumar_int(a, b) def AND (a, b): resultado = "" for i in range(len(a)): if a[i] == "1" and b[i] == "1": resultado += "1" else: resultado += "0" return resultado def OR (a, b): resultado = "" for i in range(len(a)): if a[i] == "0" and b[i] == "0": resultado += "0" else: resultado += "1" return resultado def XOR (a, b): resultado = "" for i in range(len(a)): if a[i] == b[i]: resultado += "0" else: resultado += "1" return resultado def menor(a, b): for i in range(len(a)): if a[i] == "1" and b[i] == "0": return False elif a[i] == "0" and b[i] == "1": return True return False def bin_to_dec(binario): binario = binario[::-1] numero = 0 for i in range(len(binario)): if binario[i] == "1": numero += 2**(i) return numero
#!/usr/bin/env python3 import hashlib, io, struct, sys from os import path from libyaz0 import decompress UNCOMPRESSED_SIZE = 0x2F00000 def as_word(b, off=0): return struct.unpack(">I", b[off:off+4])[0] def as_word_list(b): return [i[0] for i in struct.iter_unpack(">I", b)] def calc_crc(rom_data, cic_type): start = 0x1000 end = 0x101000 unsigned_long = lambda i: i & 0xFFFFFFFF rol = lambda i, b: unsigned_long(i << b) | (i >> (-b & 0x1F)) if cic_type == 6101 or cic_type == 6102: seed = 0xF8CA4DDC elif cic_type == 6103: seed = 0xA3886759 elif cic_type == 6105: seed = 0xDF26F436 elif cic_type == 6106: seed = 0x1FEA617A else: assert False , f"Unknown cic type: {cic_type}" t1 = t2 = t3 = t4 = t5 = t6 = seed for pos in range(start, end, 4): d = as_word(rom_data, pos) r = rol(d, d & 0x1F) t6d = unsigned_long(t6 + d) if t6d < t6: t4 = unsigned_long(t4 + 1) t6 = t6d t3 ^= d t5 = unsigned_long(t5 + r) if t2 > d: t2 ^= r else: t2 ^= t6 ^ d if cic_type == 6105: t1 = unsigned_long(t1 + (as_word(rom_data, 0x0750 + (pos & 0xFF)) ^ d)) else: t1 = unsigned_long(t1 + (t5 ^ d)) chksum = [0,0] if cic_type == 6103: chksum[0] = unsigned_long((t6 ^ t4) + t3) chksum[1] = unsigned_long((t5 ^ t2) + t1) elif cic_type == 6106: chksum[0] = unsigned_long((t6 * t4) + t3) chksum[1] = unsigned_long((t5 * t2) + t1) else: chksum[0] = t6 ^ t4 ^ t3 chksum[1] = t5 ^ t2 ^ t1 return struct.pack(">II", chksum[0], chksum[1]) def read_dmadata_entry(addr): return as_word_list(fileContent[addr:addr+0x10]) def read_dmadata(start): dmadata = [] addr = start entry = read_dmadata_entry(addr) i = 0 while any([e != 0 for e in entry]): # print(f"0x{addr:08X} " + str([f"{e:08X}" for e in entry])) dmadata.append(entry) addr += 0x10 i += 1 entry = read_dmadata_entry(addr) # print(f"0x{addr:08X} " + str([f"{e:08X}" for e in entry])) return dmadata def update_crc(decompressed): print("Recalculating crc...") new_crc = calc_crc(decompressed.getbuffer(), 6105) decompressed.seek(0x10) decompressed.write(new_crc) return decompressed def decompress_rom(dmadata_addr, dmadata): rom_segments = {} # vrom start : data s.t. len(data) == vrom_end - vrom_start new_dmadata = bytearray() # new dmadata: {vrom start , vrom end , vrom start , 0} decompressed = io.BytesIO(b"") for v_start, v_end, p_start, p_end in dmadata: if p_start == 0xFFFFFFFF and p_end == 0xFFFFFFFF: new_dmadata.extend(struct.pack(">IIII", v_start, v_end, p_start, p_end)) continue if p_end == 0: # uncompressed rom_segments.update({v_start : fileContent[p_start:p_start + v_end - v_start]}) else: # compressed rom_segments.update({v_start : decompress(fileContent[p_start:p_end])}) new_dmadata.extend(struct.pack(">IIII", v_start, v_end, v_start, 0)) # write rom segments to vaddrs for vrom_st,data in rom_segments.items(): decompressed.seek(vrom_st) decompressed.write(data) # write new dmadata decompressed.seek(dmadata_addr) decompressed.write(new_dmadata) # pad to size decompressed.seek(UNCOMPRESSED_SIZE-1) decompressed.write(bytearray([0])) # re-calculate crc return update_crc(decompressed) correct_compressed_str_hash = "2a0a8acb61538235bc1094d297fb6556" correct_str_hash = "f46493eaa0628827dbd6ad3ecd8d65d6" def get_str_hash(byte_array): return str(hashlib.md5(byte_array).hexdigest()) # If the baserom exists and is correct, we don't need to change anything if path.exists("baserom_uncompressed.z64"): with open("baserom_uncompressed.z64", mode="rb") as file: fileContent = bytearray(file.read()) if get_str_hash(fileContent) == correct_str_hash: print("Found valid baserom - exiting early") sys.exit(0) # Determine if we have a ROM file romFileName = "" if path.exists("baserom.mm.us.rev1.z64"): romFileName = "baserom.mm.us.rev1.z64" elif path.exists("baserom.mm.us.rev1.n64"): romFileName = "baserom.mm.us.rev1.n64" elif path.exists("baserom.mm.us.rev1.v64"): romFileName = "baserom.mm.us.rev1.v64" else: print("Error: Could not find baserom.mm.us.rev1.z64/baserom.mm.us.rev1.n64/baserom.mm.us.rev1.v64.") sys.exit(1) # Read in the original ROM print("File '" + romFileName + "' found.") with open(romFileName, mode="rb") as file: fileContent = bytearray(file.read()) fileContentLen = len(fileContent) # Check if ROM needs to be byte/word swapped # Little-endian if fileContent[0] == 0x40: # Word Swap ROM print("ROM needs to be word swapped...") words = str(int(fileContentLen/4)) little_byte_format = "<" + words + "I" big_byte_format = ">" + words + "I" tmp = struct.unpack_from(little_byte_format, fileContent, 0) struct.pack_into(big_byte_format, fileContent, 0, *tmp) print("Word swapping done.") # Byte-swapped elif fileContent[0] == 0x37: # Byte Swap ROM print("ROM needs to be byte swapped...") halfwords = str(int(fileContentLen/2)) little_byte_format = "<" + halfwords + "H" big_byte_format = ">" + halfwords + "H" tmp = struct.unpack_from(little_byte_format, fileContent, 0) struct.pack_into(big_byte_format, fileContent, 0, *tmp) print("Byte swapping done.") # Check to see if the ROM is a compressed "vanilla" ROM compressed_str_hash = get_str_hash(bytearray(fileContent)) if compressed_str_hash != correct_compressed_str_hash: print("Error: Expected a hash of " + correct_compressed_str_hash + " but got " + compressed_str_hash + ". " + "The baserom has probably been tampered, find a new one") sys.exit(1) # Decompress FILE_TABLE_OFFSET = 0x1A500 # 0x1C110 for JP1.0, 0x1C050 for JP1.1, 0x24F60 for debug if any([b != 0 for b in fileContent[FILE_TABLE_OFFSET + 0x9C:FILE_TABLE_OFFSET + 0x9C + 0x4]]): print("Decompressing rom...") fileContent = decompress_rom(FILE_TABLE_OFFSET, read_dmadata(FILE_TABLE_OFFSET)).getbuffer() # FF Padding (TODO is there an automatic way we can find where to start padding from? Largest dmadata file end maybe?) for i in range(0x2EE8000,UNCOMPRESSED_SIZE): fileContent[i] = 0xFF # Check to see if the ROM is a "vanilla" ROM str_hash = get_str_hash(bytearray(fileContent)) if str_hash != correct_str_hash: print("Error: Expected a hash of " + correct_str_hash + " but got " + str_hash + ". " + "The baserom has probably been tampered, find a new one") sys.exit(1) # Write out our new ROM print("Writing new ROM 'baserom_uncompressed.z64'.") with open("baserom_uncompressed.z64", "wb") as file: file.write(bytes(fileContent)) print("Done!")
#You are given a string. Split the string on a " " (space) delimiter and join using a - hyphen. def split_and_join(line): list = line.split(" ") new_line = "-".join(list) return new_line s= "This is Sparta" print(split_and_join(s))
#!/usr/bin/env python __author__ = "John Kirkham <kirkhamj@janelia.hhmi.org>" __date__ = "$May 05, 2015 13:31:12 EDT$" from splauncher.core import main if __name__ == "__main__": import sys sys.exit(main(*sys.argv))
import time import numpy as np import common import pupper import sim def main(use_imu=False, default_velocity=np.zeros(2), default_yaw_rate=0.0): # Create config config = pupper.config.Configuration() config.z_clearance = 0.02 simulator = sim.sim.Sim(xml_path="sim/pupper_pybullet.xml") hardware_interface = sim.hardware_interface.HardwareInterface(simulator.model, simulator.joint_indices) # Create imu handle if use_imu: imu = sim.imu.IMU() # Create controller and user input handles controller = common.controller.Controller(config, pupper.kinematics.four_legs_inverse_kinematics) state = common.state.State() state.behavior_state = common.state.BehaviorState.DEACTIVATED state.quat_orientation = np.array([1, 0, 0, 0]) command = common.command.Command() # Emulate the joystick inputs required to activate the robot command.activate_event = 1 controller.run(state, command) command.activate_event = 0 command.trot_event = 1 controller.run(state, command) command = common.command.Command() # zero it out # Apply a constant command. # TODO Add support for user input or an external commander command.horizontal_velocity = default_velocity command.yaw_rate = default_yaw_rate # The joystick service is linux-only, so commenting out for mac # print("Creating joystick listener...") # joystick_interface = JoystickInterface(config) # print("Done.") print("Summary of gait parameters:") print("overlap time: ", config.overlap_time) print("swing time: ", config.swing_time) print("z clearance: ", config.z_clearance) print("x shift: ", config.x_shift) # Run the simulation timesteps = 240 * 60 * 10 # simulate for a max of 10 minutes # Sim seconds per sim step sim_steps_per_sim_second = 240 sim_dt = 1.0 / sim_steps_per_sim_second last_control_update = 0 for steps in range(timesteps): sim_time_elapsed = sim_dt * steps if sim_time_elapsed - last_control_update > config.dt: last_control_update = sim_time_elapsed # Get IMU measurement if enabled state.quat_orientation = ( imu.read_orientation() if use_imu else np.array([1, 0, 0, 0]) ) # Step the controller forward by dt controller.run(state, command) # Update the pwm widths going to the servos hardware_interface.set_actuator_postions(state.joint_angles) # Simulate physics for 1/240 seconds (the default timestep) simulator.step() if __name__ == "__main__": main(default_velocity=np.array([0.15, 0]))
{ "cells": [ { "cell_type": "code", "execution_count": 20, "id": "b40f9af8", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[2, 4, 6, 8, 10]\n" ] } ], "source": [ "# map\n", "\n", "def dobro(x):\n", " return x*2\n", "\n", "valor = [1, 2, 3, 4, 5]\n", "valorDobrado = list(map(dobro, valor))\n", "\n", "print (valorDobrado)" ] }, { "cell_type": "code", "execution_count": null, "id": "33f62d21", "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.8" } }, "nbformat": 4, "nbformat_minor": 5 }
''' Tiernan Watson Arduino Coursework ''' import pygame import serial import g_settings class Player(pygame.sprite.Sprite): def __init__(self, width, height, color): super().__init__() self.width = width self.height = height self.move_speed = g_settings.PLAYER_MOVE_VEL self.image = pygame.Surface([width, height]) self.image.fill(color) self.rect = self.image.get_rect() self.vel_x = 0 self.vel_y = 0 ''' Controls movement and collisions ''' def update(self): self.do_gravity() self.rect.x += self.vel_x # Stops player walking through platforms block_hit_list = pygame.sprite.spritecollide(self, self.level.platforms, False) for block in block_hit_list: if self.vel_x > 0: self.rect.right = block.rect.left elif self.vel_x < 0: self.rect.left = block.rect.right self.rect.y += self.vel_y # Stops player falling through platforms block_hit_list = pygame.sprite.spritecollide(self, self.level.platforms, False) for block in block_hit_list: if self.vel_y > 0: self.rect.bottom = block.rect.top elif self.vel_y < 0: self.rect.top = block.rect.bottom self.vel_y = 0 self.check_collisions_window() def jump(self): # Checks player is on a platform self.rect.y += 2 platform_hit_list = pygame.sprite.spritecollide(self, self.level.platforms, False) self.rect.y -= 2 if len(platform_hit_list) > 0 or self.rect.bottom >= g_settings.SCREEN_HEIGHT: self.vel_y = -10 def do_gravity(self): if self.vel_y == 0: # Stops player sticking to platforms by their head self.vel_y = 1 else: self.vel_y += .32 if self.rect.y >= g_settings.SCREEN_HEIGHT - self.rect.height and self.vel_y >= 0: self.vel_y = 0 self.rect.y = g_settings.SCREEN_HEIGHT - self.rect.height ''' Stops player going out of window ''' def check_collisions_window(self): if self.rect.right > g_settings.SCREEN_WIDTH: self.rect.right = g_settings.SCREEN_WIDTH if self.rect.left < 0: self.rect.left = 0 def move(self, move_x): self.vel_x = move_x * self.move_speed class Platform(pygame.sprite.Sprite): def __init__(self, width, height, x, y, color): super().__init__() self.image = pygame.Surface([width, height]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.x = x self.rect.y = y class Level: def __init__(self, player, platforms, end_flag): self.platforms = pygame.sprite.Group() self.player = player self.end_flag = end_flag for p in platforms: block = Platform(p[0], p[1], p[2], p[3], p[4]) block.player = self.player self.platforms.add(block) def draw(self, screen, light_level): screen.fill(light_level) self.platforms.draw(screen) class Game_Serial: def __init__(self, port): self.ser = serial.Serial(port, baudrate = 9600, timeout = 1) # Fixes issue with jumbled data at the start of game for n in range(0, 80, 1): self.serial_line = self.ser.readline().decode('ascii') def read(self): self.serial_line = self.ser.readline().decode('ascii') def get_move_x(self): # [0] is right button state, [1] is left return int(self.serial_line[0]) - int(self.serial_line[1]) def get_move_y(self): # [2] is up button state return int(self.serial_line[2]) def get_light(self): # Returns strength 0-1 of light for multiplying in game return int(self.serial_line[3]) / g_settings.MAX_LIGHT
class Setting: def __init__(self) -> None: self.BASE_URL = 'https://www.hao4k.cn/' self.LOGIN_URL = 'https://www.hao4k.cn/member.php?mod=logging&action=login' self.SIGN_URL = 'https://www.hao4k.cn/qiandao/' self.USERNAME = '18697998680' self.PASSWORD = 'q529463245'
#!/usr/bin/python # # Test Suite For furnishings.py # test_furnishings.py # # Created by: Jason M Wolosonovich # 6/04/2015 # # Lesson 7 - Project Attempt 1 """ test_furnishings.py: Test suite for furnishings.py @author: Jason M. Wolosonovich """ import unittest from furnishings import Sofa, Bookshelf, Bed, Table, map_the_home, counter class TestFurnishings(unittest.TestCase): def test_map_the_home(self): """ Tests functionality of map_the_home function """ self.home = [Bed('Bedroom'), Sofa('Living Room'), Table('Living Room'), Bookshelf('Living Room'), Table('Kitchen')] self.home_map = map_the_home(self.home) for item in self.home: self.assertTrue(item.room in self.home_map, "'{0}' is missing".format(item.room)) def test_counter(self): """ Tests the functionality of the counter function """ self.home = [Bed('Bedroom'), Sofa('Living Room'), Table('Living Room'), Bookshelf('Living Room'), Table('Kitchen'), Table('Patio'), Bookshelf('Bedroom')] self.item_counts = counter(self.home) self.assertTrue(('Bookshelf', 2) in self.item_counts) self.assertTrue(('Bed', 1) in self.item_counts) self.assertTrue(('Sofa', 1) in self.item_counts) self.assertTrue(('Table', 3) in self.item_counts) if __name__=="__main__": unittest.main()
"""MCMC Test Rig for COVID-19 UK model""" # pylint: disable=E402 import sys import h5py import xarray import tqdm import yaml import numpy as np import tensorflow as tf import tensorflow_probability as tfp from tensorflow_probability.python.internal import unnest from tensorflow_probability.python.internal import dtype_util from tensorflow_probability.python.experimental.stats import sample_stats from gemlib.util import compute_state from gemlib.mcmc import Posterior from gemlib.mcmc import GibbsKernel from covid19uk.inference.mcmc_kernel_factory import make_hmc_base_kernel from covid19uk.inference.mcmc_kernel_factory import make_hmc_fast_adapt_kernel from covid19uk.inference.mcmc_kernel_factory import make_hmc_slow_adapt_kernel from covid19uk.inference.mcmc_kernel_factory import ( make_event_multiscan_gibbs_step, ) import covid19uk.model_spec as model_spec tfd = tfp.distributions tfb = tfp.bijectors DTYPE = model_spec.DTYPE def get_weighted_running_variance(draws): """Initialises online variance accumulator""" prev_mean, prev_var = tf.nn.moments(draws[-draws.shape[0] // 2 :], axes=[0]) num_samples = tf.cast( draws.shape[0] / 2, dtype=dtype_util.common_dtype([prev_mean, prev_var], tf.float32), ) weighted_running_variance = sample_stats.RunningVariance.from_stats( num_samples=num_samples, mean=prev_mean, variance=prev_var ) return weighted_running_variance def _get_window_sizes(num_adaptation_steps): slow_window_size = num_adaptation_steps // 21 first_window_size = 3 * slow_window_size last_window_size = ( num_adaptation_steps - 15 * slow_window_size - first_window_size ) return first_window_size, slow_window_size, last_window_size @tf.function # (autograph=False, jit_compile=False) def _fast_adapt_window( num_draws, joint_log_prob_fn, initial_position, hmc_kernel_kwargs, dual_averaging_kwargs, event_kernel_kwargs, trace_fn=None, seed=None, ): """ In the fast adaptation window, we use the `DualAveragingStepSizeAdaptation` kernel to wrap an HMC kernel. :param num_draws: Number of MCMC draws in window :param joint_log_prob_fn: joint log posterior function :param initial_position: initial state of the Markov chain :param hmc_kernel_kwargs: `HamiltonianMonteCarlo` kernel keywords args :param dual_averaging_kwargs: `DualAveragingStepSizeAdaptation` keyword args :param event_kernel_kwargs: EventTimesMH and Occult kernel args :param trace_fn: function to trace kernel results :param seed: optional random seed. :returns: draws, kernel results, the adapted HMC step size, and variance accumulator """ kernel_list = [ ( 0, make_hmc_fast_adapt_kernel( hmc_kernel_kwargs=hmc_kernel_kwargs, dual_averaging_kwargs=dual_averaging_kwargs, ), ), (1, make_event_multiscan_gibbs_step(**event_kernel_kwargs)), ] kernel = GibbsKernel( target_log_prob_fn=joint_log_prob_fn, kernel_list=kernel_list, name="fast_adapt", ) pkr = kernel.bootstrap_results(initial_position) @tf.function(jit_compile=True) def sample(current_state, previous_kernel_results): return tfp.mcmc.sample_chain( num_draws, current_state=current_state, kernel=kernel, previous_kernel_results=previous_kernel_results, return_final_kernel_results=True, trace_fn=trace_fn, seed=seed, ) draws, trace, fkr = sample(initial_position, pkr) weighted_running_variance = get_weighted_running_variance(draws[0]) step_size = unnest.get_outermost(fkr.inner_results[0], "step_size") return draws, trace, step_size, weighted_running_variance @tf.function # (autograph=False, jit_compile=False) def _slow_adapt_window( num_draws, joint_log_prob_fn, initial_position, initial_running_variance, hmc_kernel_kwargs, dual_averaging_kwargs, event_kernel_kwargs, trace_fn=None, seed=None, ): """In the slow adaptation phase, we adapt the HMC step size and mass matrix together. :param num_draws: number of MCMC iterations :param joint_log_prob_fn: the joint posterior density function :param initial_position: initial Markov chain state :param initial_running_variance: initial variance accumulator :param hmc_kernel_kwargs: `HamiltonianMonteCarlo` kernel kwargs :param dual_averaging_kwargs: `DualAveragingStepSizeAdaptation` kwargs :param event_kernel_kwargs: EventTimesMH and Occults kwargs :param trace_fn: result trace function :param seed: optional random seed :returns: draws, kernel results, adapted step size, the variance accumulator, and "learned" momentum distribution for the HMC. """ kernel_list = [ ( 0, make_hmc_slow_adapt_kernel( initial_running_variance, hmc_kernel_kwargs, dual_averaging_kwargs, ), ), (1, make_event_multiscan_gibbs_step(**event_kernel_kwargs)), ] kernel = GibbsKernel( target_log_prob_fn=joint_log_prob_fn, kernel_list=kernel_list, name="slow_adapt", ) pkr = kernel.bootstrap_results(initial_position) @tf.function(jit_compile=True) def sample(current_state, previous_kernel_results): return tfp.mcmc.sample_chain( num_draws, current_state=current_state, kernel=kernel, previous_kernel_results=pkr, return_final_kernel_results=True, trace_fn=trace_fn, ) draws, trace, fkr = sample(initial_position, pkr) step_size = unnest.get_outermost(fkr.inner_results[0], "step_size") momentum_distribution = unnest.get_outermost( fkr.inner_results[0], "momentum_distribution" ) weighted_running_variance = get_weighted_running_variance(draws[0]) return ( draws, trace, step_size, weighted_running_variance, momentum_distribution, ) def make_fixed_window_sampler( num_draws, joint_log_prob_fn, hmc_kernel_kwargs, event_kernel_kwargs, trace_fn=None, seed=None, jit_compile=False, ): """Fixed step size and mass matrix HMC. :param num_draws: number of MCMC iterations :param joint_log_prob_fn: joint log posterior density function :param initial_position: initial Markov chain state :param hmc_kernel_kwargs: `HamiltonianMonteCarlo` kwargs :param event_kernel_kwargs: Event and Occults kwargs :param trace_fn: results trace function :param seed: optional random seed :returns: (draws, trace, final_kernel_results) """ kernel_list = [ (0, make_hmc_base_kernel(**hmc_kernel_kwargs)), (1, make_event_multiscan_gibbs_step(**event_kernel_kwargs)), ] kernel = GibbsKernel( target_log_prob_fn=joint_log_prob_fn, kernel_list=kernel_list, name="fixed", ) @tf.function(jit_compile=jit_compile) def sample_fn(current_state, previous_kernel_results=None): return tfp.mcmc.sample_chain( num_draws, current_state=current_state, kernel=kernel, return_final_kernel_results=True, previous_kernel_results=previous_kernel_results, trace_fn=trace_fn, seed=seed, ) return sample_fn, kernel def trace_results_fn(_, results): """Packs results into a dictionary""" results_dict = {} root_results = results.inner_results step_size = tf.convert_to_tensor( unnest.get_outermost(root_results[0], "step_size") ) results_dict["hmc"] = { "is_accepted": unnest.get_innermost(root_results[0], "is_accepted"), "target_log_prob": unnest.get_innermost( root_results[0], "target_log_prob" ), "step_size": step_size, } def get_move_results(results): return { "is_accepted": results.is_accepted, "target_log_prob": results.accepted_results.target_log_prob, "proposed_delta": tf.stack( [ results.accepted_results.m, results.accepted_results.t, results.accepted_results.delta_t, results.accepted_results.x_star, ] ), } res1 = root_results[1].inner_results results_dict["move/S->E"] = get_move_results(res1[0]) results_dict["move/E->I"] = get_move_results(res1[1]) results_dict["occult/S->E"] = get_move_results(res1[2]) results_dict["occult/E->I"] = get_move_results(res1[3]) return results_dict def draws_to_dict(draws): num_locs = draws[1].shape[1] num_times = draws[1].shape[2] return { "psi": draws[0][:, 0], "sigma_space": draws[0][:, 1], "beta_area": draws[0][:, 2], "gamma0": draws[0][:, 3], "gamma1": draws[0][:, 4], "alpha_0": draws[0][:, 5], "alpha_t": draws[0][:, 6 : (6 + num_times - 1)], "spatial_effect": draws[0][ :, (6 + num_times - 1) : (6 + num_times - 1 + num_locs) ], "seir": draws[1], } def run_mcmc( joint_log_prob_fn, current_state, param_bijector, initial_conditions, config, output_file, ): first_window_size = 200 last_window_size = 50 slow_window_size = 25 num_slow_windows = 6 warmup_size = int( first_window_size + slow_window_size * ((1 - 2 ** num_slow_windows) / (1 - 2)) # sum geometric series + last_window_size ) hmc_kernel_kwargs = { "step_size": 0.1, "num_leapfrog_steps": 16, "momentum_distribution": None, "store_parameters_in_results": True, } dual_averaging_kwargs = { "target_accept_prob": 0.75, # "decay_rate": 0.80, } event_kernel_kwargs = { "initial_state": initial_conditions, "t_range": [ current_state[1].shape[-2] - 21, current_state[1].shape[-2], ], "config": config, } # Set up posterior print("Initialising output...", end="", flush=True, file=sys.stderr) draws, trace, _ = make_fixed_window_sampler( num_draws=1, joint_log_prob_fn=joint_log_prob_fn, hmc_kernel_kwargs=hmc_kernel_kwargs, event_kernel_kwargs=event_kernel_kwargs, trace_fn=trace_results_fn, )[0](current_state) posterior = Posterior( output_file, sample_dict=draws_to_dict(draws), results_dict=trace, num_samples=warmup_size + config["num_burst_samples"] * config["num_bursts"], ) offset = 0 print("Done", flush=True, file=sys.stderr) # Fast adaptation sampling print(f"Fast window {first_window_size}", file=sys.stderr, flush=True) dual_averaging_kwargs["num_adaptation_steps"] = first_window_size draws, trace, step_size, running_variance = _fast_adapt_window( num_draws=first_window_size, joint_log_prob_fn=joint_log_prob_fn, initial_position=current_state, hmc_kernel_kwargs=hmc_kernel_kwargs, dual_averaging_kwargs=dual_averaging_kwargs, event_kernel_kwargs=event_kernel_kwargs, trace_fn=trace_results_fn, ) current_state = [s[-1] for s in draws] draws[0] = param_bijector.inverse(draws[0]) posterior.write_samples( draws_to_dict(draws), first_dim_offset=offset, ) posterior.write_results(trace, first_dim_offset=offset) offset += first_window_size # Slow adaptation sampling hmc_kernel_kwargs["step_size"] = step_size for slow_window_idx in range(num_slow_windows): window_num_draws = slow_window_size * (2 ** slow_window_idx) dual_averaging_kwargs["num_adaptation_steps"] = window_num_draws print(f"Slow window {window_num_draws}", file=sys.stderr, flush=True) ( draws, trace, step_size, running_variance, momentum_distribution, ) = _slow_adapt_window( num_draws=window_num_draws, joint_log_prob_fn=joint_log_prob_fn, initial_position=current_state, initial_running_variance=running_variance, hmc_kernel_kwargs=hmc_kernel_kwargs, dual_averaging_kwargs=dual_averaging_kwargs, event_kernel_kwargs=event_kernel_kwargs, trace_fn=trace_results_fn, ) hmc_kernel_kwargs["step_size"] = step_size hmc_kernel_kwargs["momentum_distribution"] = momentum_distribution current_state = [s[-1] for s in draws] draws[0] = param_bijector.inverse(draws[0]) posterior.write_samples( draws_to_dict(draws), first_dim_offset=offset, ) posterior.write_results(trace, first_dim_offset=offset) offset += window_num_draws # Fast adaptation sampling print(f"Fast window {last_window_size}", file=sys.stderr, flush=True) dual_averaging_kwargs["num_adaptation_steps"] = last_window_size draws, trace, step_size, _ = _fast_adapt_window( num_draws=last_window_size, joint_log_prob_fn=joint_log_prob_fn, initial_position=current_state, hmc_kernel_kwargs=hmc_kernel_kwargs, dual_averaging_kwargs=dual_averaging_kwargs, event_kernel_kwargs=event_kernel_kwargs, trace_fn=trace_results_fn, ) current_state = [s[-1] for s in draws] draws[0] = param_bijector.inverse(draws[0]) posterior.write_samples( draws_to_dict(draws), first_dim_offset=offset, ) posterior.write_results(trace, first_dim_offset=offset) offset += last_window_size # Fixed window sampling print("Sampling...", file=sys.stderr, flush=True) hmc_kernel_kwargs["step_size"] = tf.reduce_mean( trace["hmc"]["step_size"][-last_window_size // 2 :] ) fixed_sample, kernel = make_fixed_window_sampler( config["num_burst_samples"], joint_log_prob_fn=joint_log_prob_fn, hmc_kernel_kwargs=hmc_kernel_kwargs, event_kernel_kwargs=event_kernel_kwargs, trace_fn=trace_results_fn, jit_compile=True, ) pkr = kernel.bootstrap_results(current_state) for i in tqdm.tqdm( range(config["num_bursts"]), unit_scale=config["num_burst_samples"] * config["thin"], ): draws, trace, pkr = fixed_sample(current_state, pkr) current_state = [state_part[-1] for state_part in draws] draws[0] = param_bijector.inverse(draws[0]) posterior.write_samples( draws_to_dict(draws), first_dim_offset=offset, ) posterior.write_results( trace, first_dim_offset=offset, ) offset += config["num_burst_samples"] return posterior def mcmc(data_file, output_file, config, use_autograph=False, use_xla=True): """Constructs and runs the MCMC""" if tf.test.gpu_device_name(): print("Using GPU") else: print("Using CPU") data = xarray.open_dataset(data_file, group="constant_data") cases = xarray.open_dataset(data_file, group="observations")[ "cases" ].astype(DTYPE) dates = cases.coords["time"] # Impute censored events, return cases # Take the last week of data, and repeat a further 3 times # to get a better occult initialisation. extra_cases = tf.tile(cases[:, -7:], [1, 3]) cases = tf.concat([cases, extra_cases], axis=-1) events = model_spec.impute_censored_events(cases).numpy() # Initial conditions are calculated by calculating the state # at the beginning of the inference period # # Imputed censored events that pre-date the first I-R events # in the cases dataset are discarded. They are only used to # to set up a sensible initial state. state = compute_state( initial_state=tf.concat( [ tf.constant(data["N"], DTYPE)[:, tf.newaxis], tf.zeros_like(events[:, 0, :]), ], axis=-1, ), events=events, stoichiometry=model_spec.STOICHIOMETRY, ) start_time = state.shape[1] - cases.shape[1] initial_state = state[:, start_time, :] events = events[:, start_time:-21, :] # Clip off the "extra" events ######################################################## # Construct the MCMC kernels # ######################################################## model = model_spec.CovidUK( covariates=data, initial_state=initial_state, initial_step=0, num_steps=events.shape[1], ) param_bij = tfb.Invert( # Forward transform unconstrains params tfb.Blockwise( [ tfb.Softplus(low=dtype_util.eps(DTYPE)), tfb.Identity(), tfb.Identity(), tfb.Identity(), ], block_sizes=[2, 4, events.shape[1] - 1, events.shape[0]], ) ) def joint_log_prob(unconstrained_params, events): params = param_bij.inverse(unconstrained_params) return model.log_prob( dict( psi=params[0], sigma_space=params[1], beta_area=params[2], gamma0=params[3], gamma1=params[4], alpha_0=params[5], alpha_t=params[6 : (6 + events.shape[1] - 1)], spatial_effect=params[ (6 + events.shape[1] - 1) : ( 6 + events.shape[1] - 1 + events.shape[0] ) ], seir=events, ) ) + param_bij.inverse_log_det_jacobian( unconstrained_params, event_ndims=1 ) # MCMC tracing functions ############################### # Construct bursted MCMC loop # ############################### current_chain_state = [ tf.concat( [ np.array([0.0, 0.0, 0.0, 0.0, 0.0], dtype=DTYPE), np.full( events.shape[1] + events.shape[0], 0.0, dtype=DTYPE, ), ], axis=0, ), events, ] print("Initial logpi:", joint_log_prob(*current_chain_state), flush=True) # Output file posterior = run_mcmc( joint_log_prob_fn=joint_log_prob, current_state=current_chain_state, param_bijector=param_bij, initial_conditions=initial_state, config=config, output_file=output_file, ) posterior._file.create_dataset("initial_state", data=initial_state) posterior._file.create_dataset( "time", data=np.array(dates).astype(str).astype(h5py.string_dtype()), ) print(f"Acceptance theta: {posterior['results/hmc/is_accepted'][:].mean()}") print( f"Acceptance move S->E: {posterior['results/move/S->E/is_accepted'][:].mean()}" ) print( f"Acceptance move E->I: {posterior['results/move/E->I/is_accepted'][:].mean()}" ) print( f"Acceptance occult S->E: {posterior['results/occult/S->E/is_accepted'][:].mean()}" ) print( f"Acceptance occult E->I: {posterior['results/occult/E->I/is_accepted'][:].mean()}" ) del posterior if __name__ == "__main__": from argparse import ArgumentParser parser = ArgumentParser(description="Run MCMC inference algorithm") parser.add_argument( "-c", "--config", type=str, help="Config file", required=True ) parser.add_argument( "-o", "--output", type=str, help="Output file", required=True ) parser.add_argument("data_file", type=str, help="Data NetCDF file") args = parser.parse_args() with open(args.config, "r") as f: config = yaml.load(f, Loader=yaml.FullLoader) mcmc(args.data_file, args.output, config["Mcmc"])
""" project = 'Code', file_name = 'main.py', author = 'AI悦创' time = '2020/5/19 8:16', product_name = PyCharm, 公众号:AI悦创 code is far away from bugs with the god animal protecting I love animals. They taste delicious. """ import cv2 def drawing(src, id=None): image_rgb = cv2.imread(src) image_gray = cv2.cvtColor(image_rgb, cv2.COLOR_BGR2GRAY) image_blur = cv2.GaussianBlur(image_gray, ksize=(21, 21), sigmaX=0, sigmaY=0) image_blend = cv2.divide(image_gray, image_blur, scale=255) cv2.imwrite(f'Drawing_images/result-{id}.jpg', image_blend) if __name__ == '__main__': src = 'images/image_1.jpg' drawing(src)
import argparse ### TODO: Load the necessary libraries import os from inference import Network from openvino.inference_engine.ie_api import IENetLayer import numpy as np import cv2 CPU_EXTENSION = "/home/aswin/Documents/Courses/Udacity/Intel-Edge-Phase2/Projects/People-Counter-App/Repository/nd131-openvino-people-counter-newui/custom_layers/arcface/cl_pnorm/user_ie_extensions/cpu/build/libpnorm_cpu_extension.so" VPU_EXTENSION = "/opt/intel/openvino_2019.3.376/deployment_tools/inference_engine/lib/intel64/libmyriadPlugin.so" def get_args(): ''' Gets the arguments from the command line. ''' parser = argparse.ArgumentParser("Load an IR into the Inference Engine") # -- Create the descriptions for the commands m_desc = "The location of the model XML file" # -- Create the arguments parser.add_argument("-m", help=m_desc) parser.add_argument('-l', required=False, type=str) parser.add_argument('-xp', required=False, type=str) parser.add_argument('-d', required=False, type=str) parser.add_argument('--img', required=False, type=str) parser.add_argument('--batch_size', required=False, type=int, default=1) parser.add_argument('--factor', required=False, type=float, default=1e-2) args = parser.parse_args() return args def preprocessing(network, img_path, args): input_shape = network.get_input_shape() img = cv2.imread(img_path) img = cv2.resize(img, (input_shape[3],input_shape[2])) img = img.transpose((2,0,1)) img = img.reshape(1, *img.shape) img = img.astype(np.float64) - img.min()*args.factor img = img.astype(np.uint8) return img def load_to_IE(args, model_xml, img_path): ### TODO: Load the Inference Engine API # plugin = IECore() network = Network() CPU_EXTENSION = args.l def exec_f(l): pass network.load_core(model_xml, args.d, cpu_extension=CPU_EXTENSION, args=args) if "MYRIAD" in args.d: network.feed_custom_layers(args, {'xml_path': args.xp}, exec_f) if "CPU" in args.d: network.feed_custom_parameters(args, exec_f) network.load_model(model_xml, args.d, cpu_extension=CPU_EXTENSION, args=args) img = preprocessing(network, img_path, args) network.sync_inference(img) print(network.extract_output().shape) network.check_layers(args) return def main(): args = get_args() load_to_IE(args, args.m, args.img) if __name__ == "__main__": main()
# -*- coding: utf-8 -*- from pymongo import MongoClient import os import pandas as pd import numpy as np import matplotlib.pyplot as plt from pandas.io.json import json_normalize client = MongoClient('mongodb://localhost:27017/') db = client['idioms'] with open('/home/josejm/a.txt', 'r') as f: for line in f: print db.v3.remove({'repositoryPath': line.strip()})
print("Probando paquetes") from mipaquete import pruebas from mipaquete import herramientas pruebas.Probando() herramientas.nombreCompleto("Flavio", "Scheck")
''' Task 1 The cyber security department for Blooming Cafe wants to know the temperature of Canberra in immutable list for a specific purpose. They have certain criterions to solve this problem. The criterions are given below: SL NO Requirement Specification 1 Provide an option where they can take temperature in either Fahrenheit or Celsius scale 2 Need to collect five temperature from user and add them to the immutable list 3 Convert the temperature from the Celsius to Fahrenheit or vice versa 4 Delete the last value. You can convert the tuple to list to do this. 5 Display the result in tuple The Conversion Formula for Fahrenheit to Celsius is given below: T(°C) = (T(°F) - 32) × 5/9 Here T(°C) refers to the temperature in Celsius and T(°F) is defined for Fahrenheit temperature. The Conversion formula for Celsius to Fahrenheit is given below: T(°F) = T(°C) × 9/5 + 32 Here T(°C) refers to the temperature in Celsius and T(°F) is defined for Fahrenheit temperature. ''' temp=() degree=input("Enter the type of scale you are using to measure temperature - F/C: ") for i in range(0,5): temperature=float(input("Enter the temperature: ")) if(degree=='F' or degree=='f'): temp_C=(temperature-32)*5/9 temp=temp+(temp_C,) else: temp_F=(temperature*(9/5))+32 temp=temp+(temp_F,) list_temp=list(temp) list_temp.pop(4) print(tuple(list_temp)) ''' Task 2 # Write a python program to find the factors of a given number. # The factors of a number are those, which are divisible by the number itself and 1. # For example, the factors of 15 are 1, 3, 5. # Please follow the below steps to complete this task: # Define a function which will take the number as parameter and perform the task. # Use for loops and if expression to perform the factorization. # Python Program to find the factors of a number # This function computes the factor of the argument passed ''' def print_factors(x): print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) num = int(input("Enter the number to find it's factors")) print_factors(num) ''' Task 3 Widget ''' def main(): print(" ") print("=========================================================") print("Main Menu. Choose one of the options as 1, 2, 3, 4, 5: ") print("1. Enter Personal Data") print("2. Salary Calculator") print("3. Gadget Inventory") print("4. Gadget Cost Calculator") print("5. Exit") option = int(input("Choose an option to proceed: ")) if option == 1: personalData() elif option == 2: salaryCalculator() elif option == 3: gadgetInventory() elif option == 4: gadgetsCostCalculator() elif option == 5: print("Exited the program") else: print("Incorrect selection") main() def personalData(): global emp keys=['Name','Phone','Designation'] for i in range (0, 3): values=[] name = input("Enter the name of cyber security expert: ") values.insert(i, name) phone = int(input("Enter the phone number of employee: ")) values.insert(i+1, phone) designation = input("Enter the designation of employee: ") values.insert(i+2, designation) emp.insert(i,values) print("_________________________________________________") print(" ") print("Details of all employees below: ") for j in range (0, 3): print(dict(zip(keys,emp[j]))) main() def salaryCalculator(): name = input("Enter employee name: ") wage = int(input("Enter wage per hour: ")) hours = int(input("Enter hours worked by employee: ")) totalSalary = wage * hours print("----------------------------------") print("Total Salary of " + name + " is: ", totalSalary) main() def gadgetInventory(): print("Gadget Inventory") global routers global switches global laptops global mainframe print("Inventory: Routers: ", routers, ", Switches: ", switches, ", Laptops: ", laptops, ",Mainframe: ",mainframe) print(" ") choice = input("What do you want to add? Press “R” for router, “S” for switch, “L” forLaptop, “M” for Mainframe: ") if choice == "r" or choice == "R": addRouters = int(input("How many routers do you want to add: ")) routers = routers + addRouters elif choice == "s" or choice == "S": addSwitches = int(input("How many switches do you want to add: ")) switches = switches + addSwitches elif choice == "l" or choice == "L": addLaptops = int(input("How many laptops do you want to add: ")) laptops = laptops + addLaptops elif choice == "m" or choice == "M": addMainframe = int(input("How many mainframe do you want to add: ")) mainframe = mainframe + addMainframe else: print(" ") print("Invalid choice") gadgetInventory() print(" ") print("Gadget Inventory Updated. Inventory: Routers: ", routers, ", Switches: ", switches, ",Laptops: ",laptops,", Mainframe: ",mainframe) main() def gadgetsCostCalculator(): print("Gadgets Cost Calculator") item = input("Enter the item name to calculate price: ") price = int(input("Enter the price of the item: ")) noOfItems = int(input("Number of items required: ")) print("Total price of", item, ":", price * noOfItems) print(" ") main() emp = [] routers = 3 switches = 2 laptops = 16 mainframe = 1 main()
# Generated by Django 2.1.4 on 2019-01-04 08:50 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Room', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, verbose_name='채팅방 이름')), ('group_name', models.SlugField(unique=True, verbose_name='채팅방 그룹 이름')), ], ), migrations.CreateModel( name='RoomMessage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('message', models.TextField(verbose_name='메세지')), ('created', models.DateTimeField(auto_now_add=True, db_index=True, verbose_name='생성 날짜')), ('room', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='messages', to='chat.Room')), ], ), ]
''' 1.import All the webScrape Files 2.import the sqlite DB 3.import all priceStruct files 4.get all price Strut dictionaries 5.compare values from sqlite DB to price struct Dictionaries 6.cost retrived from step 6 to be added to a new dictionary of price struct 7.from new priceStructDictionaries/new sqlite DB echo values to php ''' #Dummy scrape-SQLite import sqlite3 dbData=[] d1={'DR':{'mumbai':{'dadar':{'HondaActiva':[10,500] } } } } print(d1['DR']) #Two things to work on connect(),cursor() connection=sqlite3.connect('database2.db') c=connection.cursor() def createDB(): c.execute('''CREATE TABLE IF NOT EXISTS t1(id INTEGER PRIMARY KEY AUTOINCREMENT, provider TEXT, city TEXT, sublocation TEXT, bikeName TEXT, pickUpDate TEXT, dropDate TEXT, Availability TEXT, pID INTEGER, bID INTEGER)''') connection.commit() #Provider,city,sublocation,bikeName,pickUpDate,dropDate,Availability,pID,bID,aID #DB types INTEGER,REAL,TEXT,CHAR,BLOB def insertDB(): #c.execute('INSERT INTO t1 VALUES(1,"sau","sajskjasd",82391893289389)') c.execute('INSERT INTO t1 VALUES(?,?,?,?,?,?,?,?,?,?)', (1,"bykeMania","mumbai","thane","HondaActiva","09-03-2017","09-03-2017","a",1,1)) c.execute('INSERT INTO t1 VALUES(?,?,?,?,?,?,?,?,?,?)', (2,"RoadPanda","mumbai","dadar","HondaBike","09-03-2017","09-03-2017","a",2,1)) c.execute('INSERT INTO t1 VALUES(?,?,?,?,?,?,?,?,?,?)', (3,"bykeMania","mumbai","thane","HondaNavi","09-03-2017","09-03-2017","u",2,1)) c.execute('INSERT INTO t1 VALUES(?,?,?,?,?,?,?,?,?,?)', (4,"WR","bangalore","thane","CBZ","09-03-2017","09-03-2017","u",2,1)) c.execute('INSERT INTO t1 VALUES(?,?,?,?,?,?,?,?,?,?)', (5,"DR","mumbai","thane","Pulsur","09-03-2017","09-03-2017","a",1,1)) connection.commit() def selectDB(): c.execute("SELECT * FROM t1 ") dbData=c.fetchall() for row in c.fetchall(): #print(row[0],str(row[1]),str(row[2]),str(row[3]),str(row[4]),str(row[5]),str(row[6]),str(row[7]),row[8],row[9]) pass def updateDB(): c.execute("UPDATE t1 SET name='bubu' WHERE name='sau' ") connection.commit() def deleteDB(): c.execute("DELETE FROM T1 WHERE name='bubu' ") connection.commit() def compareDbToDict(): for row in dbData: #print(row[0],str(row[1]),str(row[2]),str(row[3]),str(row[4]),str(row[5]),str(row[6]),str(row[7]),row[8],row[9]) for row1 in d1: if(row[1]==d1): ##createDB() ##insertDB() ## ##selectDB() ##compareDbToDict() ##updateDB() ##print('#'*100) ##selectDB() c.close() connection.close()
import json import operator import Tweet from sklearn import metrics from NaiveBayesClassifier import NaiveBayesCascadeClassifier from RandomForestClassifier import RandomForestCascadeClassifier from SVMClassifier import SvmCascadeClassifier from KnnClassifier import KnnClassifier class CascadeClassifier(): _TAG_COUNT = 2 # Positive Negative _WEIGHTS = [0.11412911847966915, 0.068686571202402555, 0.30587798598576543, 0.40258393686078336, 0.34015527541750068, 0.18918154971629764, 0.2398376201170648, 0.33954794222051654] _CLASSIFIERS = [NaiveBayesCascadeClassifier, RandomForestCascadeClassifier, KnnClassifier, SvmCascadeClassifier] def __init__(self, train_dataset, k): self._classifiers = [] for classifier in self._CLASSIFIERS: print("initializing {0}".format(classifier.__name__)) self._classifiers.append(classifier(train_dataset, k)) print("classifiers loaded") self.classifer_and_weights = list(zip(self._classifiers, [self._WEIGHTS[i:i + self._TAG_COUNT] for i in range(0, len(self._WEIGHTS) * self._TAG_COUNT, self._TAG_COUNT)])) def _adjust_scores(self, result, pos_weight, neg_weight): result["positive"] = result["positive"] * pos_weight result["negative"] = result["negative"] * neg_weight return result def _calculate_final_score(self, results): final_score = {"positive": 0, "negative": 0, "neutral": 0} for result in results: for key, value in result.items(): final_score[key] += value return final_score def _metrics(self, results): print(metrics.classification_report(results['actual'], results['prediction'])) def classify(self, tweet): results = [] for classifier, (pos_weight, neg_weight) in self.classifer_and_weights: result = classifier.classify_prob(tweet) result = self._adjust_scores(result, pos_weight, neg_weight) results.append(result) final_score = self._calculate_final_score(results) final_score = sorted(final_score.items(), key=operator.itemgetter(1)) return final_score[-1][0] def classify_tweets(self, test_dataset): results = {"prediction": [], "actual": []} for cascade in test_dataset: result = self.classify(cascade) actual = cascade['label'] results["prediction"].append(result) results["actual"].append(actual) self._metrics(results) def classify_tweets_export(self, test_dataset, export="testing_online_prediction.json"): cascade_results = {} results = {"prediction": [], "actual": []} for cascade in test_dataset: result = self.classify(cascade) actual = cascade['label'] and "positive" or "negative" cascade_results[cascade['url']] = cascade['cascade'] cascade_results[cascade['url']].update({"predicted_label" : result is "positive" and "+1" or "-1"}) results["prediction"].append(result) results["actual"].append(actual) export_file = open(export, 'w') export_file.write(json.dumps(cascade_results)) self._metrics(results) if __name__ == '__main__': train_dataset, test_dataset = Tweet.get_flattened_data('dataset/k2/training.json', 'dataset/k2/testing.json', 'dataset/k2/root_tweet.json', 2) cc = CascadeClassifier(train_dataset, 2) cc.classify_tweets_export(test_dataset) # k = 2 # precision recall f1-score support # negative 0.86 0.97 0.91 1088 # positive 0.85 0.54 0.66 365 # avg / total 0.86 0.86 0.85 1453 # k = 4 # precision recall f1-score support # negative 0.83 0.93 0.88 1022 # positive 0.76 0.53 0.63 421 # avg / total 0.81 0.82 0.80 1443
# # @lc app=leetcode.cn id=1360 lang=python3 # # [1360] 日期之间隔几天 # # @lc code=start class Solution: def daysBetweenDates(self, date1: str, date2: str) -> int: maxDate = minDate = "" if (date1 >= date2): maxDate = date1 minDate = date2 else: maxDate = date2 minDate = date1 year1 = int(maxDate[:4]) year2 = int(minDate[:4]) # @lc code=end
from django.contrib import admin from dictionary.models import Dictionary admin.site.register(Dictionary)
def sendmail(From, To, Subject, Content): print('From:', From) print('To:', To) print('Subject:', Subject) print('') print(Content) sendmail('gabor@szabgab.com', 'szabgab@gmail.com', 'self message', 'Has some content too')
#!/usr/bin/env python import Geant4 as g4 from Geant4.hepunit import * import numpy as np # energies = (30.0 * MeV) * 2**np.arange(6)/32 # print(energies/MeV) # [ 0.9375 1.875 3.75 7.5 15. 30. ] def electron_spray(): energies = (30.0 * MeV) * 2**np.arange(6)/32 for energy in energies: yield 'e-', g4.G4ThreeVector(), g4.G4ThreeVector(0,0,1), energy def gamma_spray(): energy = 1*MeV y0 = 0*mm while 1: yield 'gamma', g4.G4ThreeVector(0, y0,-25*mm), g4.G4ThreeVector(0,0,1), energy
from django.conf.urls.defaults import * #@UnusedWildImport # Uncomment the next two lines to enable the admin: from django.contrib import admin admin.autodiscover() urlpatterns = patterns('', url(r'^_static/(?P<path>.*)$', 'django.views.static.serve', {'document_root': 'static'}, name='static'), url(r'^$', 'backoffice.views.home', name='home'), url(r'^beta_invitation_export', 'backoffice.views.beta_invitation_export', name='beta_invitation_export'), url(r'^log_info', 'backoffice.views.log_info', name='log_info'), url(r'^control_panel$', 'backoffice.views.control_panel', name='control_panel'), url(r'^biz_stats$', 'backoffice.views.biz_stats', name='biz_stats'), url(r'^biz_stats.json$', 'backoffice.views.biz_stats_json', name='biz_stats_json'), url(r'^biz_stats.json.daily$', 'backoffice.views.biz_stats_json_daily', name='biz_stats_json_daily'), url(r'^accounts_info', 'backoffice.views.accounts_info', name='accounts_info'), url(r'^resource_map', 'backoffice.views.resource_map', name='resource_map'), url(r'^beta_requests$', 'backoffice.views.beta_requests_list', name='beta_requests'), url(r'^beta_invitations$', 'backoffice.views.beta_invitations', name='beta_invitations'), url(r'^beta_request_invite/(?P<request_id>.*)$', 'backoffice.views.beta_request_invite', name='beta_request_invite'), url(r'^worker_resource_map/(?P<worker_id>.*)$', 'backoffice.views.worker_resource_map', name='worker_resource_map'), url(r'^manage_worker/(?P<worker_id>.*)$', 'backoffice.views.manage_worker', name='manage_worker'), url(r'^mount_history/(?P<worker_id>[^/]*)/(?P<mount>.*)$', 'backoffice.views.mount_history', name='mount_history'), url(r'^index_history/(?P<worker_id>[^/]*)/(?P<index_id>.*)$', 'backoffice.views.index_history', name='index_history'), url(r'^load_history/(?P<worker_id>[^/]*)', 'backoffice.views.load_history', name='load_history'), url(r'^operations', 'backoffice.views.operations', name='operations'), url(r'^login$', 'backoffice.views.login', name='login'), url(r'^logout$', 'backoffice.views.logout', name='logout'), )
from django.urls import path from . import views from django.conf.urls import url app_name = "users" urlpatterns = [ url( regex=r'^top100/$', view=views.ListTop100.as_view(), name = 'view_top100' ), url( regex=r'^list/$', view=views.ListView.as_view(), name = 'List_View' ), url( regex=r'^feed/$', view=views.Feed.as_view(), name = 'Play_Lists' ), url( regex=r'^makeList/$', view=views.MakeTop300List.as_view(), name='make_Lists' ), url( regex=r'^saveImg/$', view=views.Applyimg.as_view(), name='save_Img' ), url( regex=r'^search/$', view=views.Search.as_view(), name = 'Search' ) ]
# coding=utf-8 # -------------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License. See License.txt in the project root for # license information. # # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from msrest.serialization import Model class Serialization(Model): """Describes how data from an input is serialized or how data is serialized when written to an output. You probably want to use the sub-classes and not this class directly. Known sub-classes are: AvroSerialization, JsonSerialization, CsvSerialization All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Avro': 'AvroSerialization', 'Json': 'JsonSerialization', 'Csv': 'CsvSerialization'} } def __init__(self, **kwargs) -> None: super(Serialization, self).__init__(**kwargs) self.type = None class AvroSerialization(Serialization): """Describes how data from an input is serialized or how data is serialized when written to an output in Avro format. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param properties: The properties that are associated with the Avro serialization type. Required on PUT (CreateOrReplace) requests. :type properties: object """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'object'}, } def __init__(self, *, properties=None, **kwargs) -> None: super(AvroSerialization, self).__init__(**kwargs) self.properties = properties self.type = 'Avro' class OutputDataSource(Model): """Describes the data source that output will be written to. You probably want to use the sub-classes and not this class directly. Known sub-classes are: AzureDataLakeStoreOutputDataSource, PowerBIOutputDataSource, ServiceBusTopicOutputDataSource, ServiceBusQueueOutputDataSource, DocumentDbOutputDataSource, AzureSqlDatabaseOutputDataSource, EventHubOutputDataSource, AzureTableOutputDataSource, BlobOutputDataSource All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Microsoft.DataLake/Accounts': 'AzureDataLakeStoreOutputDataSource', 'PowerBI': 'PowerBIOutputDataSource', 'Microsoft.ServiceBus/Topic': 'ServiceBusTopicOutputDataSource', 'Microsoft.ServiceBus/Queue': 'ServiceBusQueueOutputDataSource', 'Microsoft.Storage/DocumentDB': 'DocumentDbOutputDataSource', 'Microsoft.Sql/Server/Database': 'AzureSqlDatabaseOutputDataSource', 'Microsoft.ServiceBus/EventHub': 'EventHubOutputDataSource', 'Microsoft.Storage/Table': 'AzureTableOutputDataSource', 'Microsoft.Storage/Blob': 'BlobOutputDataSource'} } def __init__(self, **kwargs) -> None: super(OutputDataSource, self).__init__(**kwargs) self.type = None class AzureDataLakeStoreOutputDataSource(OutputDataSource): """Describes an Azure Data Lake Store output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param refresh_token: A refresh token that can be used to obtain a valid access token that can then be used to authenticate with the data source. A valid refresh token is currently only obtainable via the Azure Portal. It is recommended to put a dummy string value here when creating the data source and then going to the Azure Portal to authenticate the data source which will update this property with a valid refresh token. Required on PUT (CreateOrReplace) requests. :type refresh_token: str :param token_user_principal_name: The user principal name (UPN) of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain the refresh token. :type token_user_principal_name: str :param token_user_display_name: The user display name of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain the refresh token. :type token_user_display_name: str :param account_name: The name of the Azure Data Lake Store account. Required on PUT (CreateOrReplace) requests. :type account_name: str :param tenant_id: The tenant id of the user used to obtain the refresh token. Required on PUT (CreateOrReplace) requests. :type tenant_id: str :param file_path_prefix: The location of the file to which the output should be written to. Required on PUT (CreateOrReplace) requests. :type file_path_prefix: str :param date_format: The date format. Wherever {date} appears in filePathPrefix, the value of this property is used as the date format instead. :type date_format: str :param time_format: The time format. Wherever {time} appears in filePathPrefix, the value of this property is used as the time format instead. :type time_format: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'refresh_token': {'key': 'properties.refreshToken', 'type': 'str'}, 'token_user_principal_name': {'key': 'properties.tokenUserPrincipalName', 'type': 'str'}, 'token_user_display_name': {'key': 'properties.tokenUserDisplayName', 'type': 'str'}, 'account_name': {'key': 'properties.accountName', 'type': 'str'}, 'tenant_id': {'key': 'properties.tenantId', 'type': 'str'}, 'file_path_prefix': {'key': 'properties.filePathPrefix', 'type': 'str'}, 'date_format': {'key': 'properties.dateFormat', 'type': 'str'}, 'time_format': {'key': 'properties.timeFormat', 'type': 'str'}, } def __init__(self, *, refresh_token: str=None, token_user_principal_name: str=None, token_user_display_name: str=None, account_name: str=None, tenant_id: str=None, file_path_prefix: str=None, date_format: str=None, time_format: str=None, **kwargs) -> None: super(AzureDataLakeStoreOutputDataSource, self).__init__(**kwargs) self.refresh_token = refresh_token self.token_user_principal_name = token_user_principal_name self.token_user_display_name = token_user_display_name self.account_name = account_name self.tenant_id = tenant_id self.file_path_prefix = file_path_prefix self.date_format = date_format self.time_format = time_format self.type = 'Microsoft.DataLake/Accounts' class FunctionBinding(Model): """The physical binding of the function. For example, in the Azure Machine Learning web service’s case, this describes the endpoint. You probably want to use the sub-classes and not this class directly. Known sub-classes are: JavaScriptFunctionBinding, AzureMachineLearningWebServiceFunctionBinding All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Microsoft.StreamAnalytics/JavascriptUdf': 'JavaScriptFunctionBinding', 'Microsoft.MachineLearning/WebService': 'AzureMachineLearningWebServiceFunctionBinding'} } def __init__(self, **kwargs) -> None: super(FunctionBinding, self).__init__(**kwargs) self.type = None class AzureMachineLearningWebServiceFunctionBinding(FunctionBinding): """The binding to an Azure Machine Learning web service. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param endpoint: The Request-Response execute endpoint of the Azure Machine Learning web service. Find out more here: https://docs.microsoft.com/en-us/azure/machine-learning/machine-learning-consume-web-services#request-response-service-rrs :type endpoint: str :param api_key: The API key used to authenticate with Request-Response endpoint. :type api_key: str :param inputs: The inputs for the Azure Machine Learning web service endpoint. :type inputs: ~azure.mgmt.streamanalytics.models.AzureMachineLearningWebServiceInputs :param outputs: A list of outputs from the Azure Machine Learning web service endpoint execution. :type outputs: list[~azure.mgmt.streamanalytics.models.AzureMachineLearningWebServiceOutputColumn] :param batch_size: Number between 1 and 10000 describing maximum number of rows for every Azure ML RRS execute request. Default is 1000. :type batch_size: int """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'endpoint': {'key': 'properties.endpoint', 'type': 'str'}, 'api_key': {'key': 'properties.apiKey', 'type': 'str'}, 'inputs': {'key': 'properties.inputs', 'type': 'AzureMachineLearningWebServiceInputs'}, 'outputs': {'key': 'properties.outputs', 'type': '[AzureMachineLearningWebServiceOutputColumn]'}, 'batch_size': {'key': 'properties.batchSize', 'type': 'int'}, } def __init__(self, *, endpoint: str=None, api_key: str=None, inputs=None, outputs=None, batch_size: int=None, **kwargs) -> None: super(AzureMachineLearningWebServiceFunctionBinding, self).__init__(**kwargs) self.endpoint = endpoint self.api_key = api_key self.inputs = inputs self.outputs = outputs self.batch_size = batch_size self.type = 'Microsoft.MachineLearning/WebService' class FunctionRetrieveDefaultDefinitionParameters(Model): """Parameters used to specify the type of function to retrieve the default definition for. You probably want to use the sub-classes and not this class directly. Known sub-classes are: AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters, JavaScriptFunctionRetrieveDefaultDefinitionParameters All required parameters must be populated in order to send to Azure. :param binding_type: Required. Constant filled by server. :type binding_type: str """ _validation = { 'binding_type': {'required': True}, } _attribute_map = { 'binding_type': {'key': 'bindingType', 'type': 'str'}, } _subtype_map = { 'binding_type': {'Microsoft.MachineLearning/WebService': 'AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters', 'Microsoft.StreamAnalytics/JavascriptUdf': 'JavaScriptFunctionRetrieveDefaultDefinitionParameters'} } def __init__(self, **kwargs) -> None: super(FunctionRetrieveDefaultDefinitionParameters, self).__init__(**kwargs) self.binding_type = None class AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters(FunctionRetrieveDefaultDefinitionParameters): """The parameters needed to retrieve the default function definition for an Azure Machine Learning web service function. All required parameters must be populated in order to send to Azure. :param binding_type: Required. Constant filled by server. :type binding_type: str :param execute_endpoint: The Request-Response execute endpoint of the Azure Machine Learning web service. Find out more here: https://docs.microsoft.com/en-us/azure/machine-learning/machine-learning-consume-web-services#request-response-service-rrs :type execute_endpoint: str :param udf_type: The function type. Possible values include: 'Scalar' :type udf_type: str or ~azure.mgmt.streamanalytics.models.UdfType """ _validation = { 'binding_type': {'required': True}, } _attribute_map = { 'binding_type': {'key': 'bindingType', 'type': 'str'}, 'execute_endpoint': {'key': 'bindingRetrievalProperties.executeEndpoint', 'type': 'str'}, 'udf_type': {'key': 'bindingRetrievalProperties.udfType', 'type': 'UdfType'}, } def __init__(self, *, execute_endpoint: str=None, udf_type=None, **kwargs) -> None: super(AzureMachineLearningWebServiceFunctionRetrieveDefaultDefinitionParameters, self).__init__(**kwargs) self.execute_endpoint = execute_endpoint self.udf_type = udf_type self.binding_type = 'Microsoft.MachineLearning/WebService' class AzureMachineLearningWebServiceInputColumn(Model): """Describes an input column for the Azure Machine Learning web service endpoint. :param name: The name of the input column. :type name: str :param data_type: The (Azure Machine Learning supported) data type of the input column. A list of valid Azure Machine Learning data types are described at https://msdn.microsoft.com/en-us/library/azure/dn905923.aspx . :type data_type: str :param map_to: The zero based index of the function parameter this input maps to. :type map_to: int """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'data_type': {'key': 'dataType', 'type': 'str'}, 'map_to': {'key': 'mapTo', 'type': 'int'}, } def __init__(self, *, name: str=None, data_type: str=None, map_to: int=None, **kwargs) -> None: super(AzureMachineLearningWebServiceInputColumn, self).__init__(**kwargs) self.name = name self.data_type = data_type self.map_to = map_to class AzureMachineLearningWebServiceInputs(Model): """The inputs for the Azure Machine Learning web service endpoint. :param name: The name of the input. This is the name provided while authoring the endpoint. :type name: str :param column_names: A list of input columns for the Azure Machine Learning web service endpoint. :type column_names: list[~azure.mgmt.streamanalytics.models.AzureMachineLearningWebServiceInputColumn] """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'column_names': {'key': 'columnNames', 'type': '[AzureMachineLearningWebServiceInputColumn]'}, } def __init__(self, *, name: str=None, column_names=None, **kwargs) -> None: super(AzureMachineLearningWebServiceInputs, self).__init__(**kwargs) self.name = name self.column_names = column_names class AzureMachineLearningWebServiceOutputColumn(Model): """Describes an output column for the Azure Machine Learning web service endpoint. :param name: The name of the output column. :type name: str :param data_type: The (Azure Machine Learning supported) data type of the output column. A list of valid Azure Machine Learning data types are described at https://msdn.microsoft.com/en-us/library/azure/dn905923.aspx . :type data_type: str """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'data_type': {'key': 'dataType', 'type': 'str'}, } def __init__(self, *, name: str=None, data_type: str=None, **kwargs) -> None: super(AzureMachineLearningWebServiceOutputColumn, self).__init__(**kwargs) self.name = name self.data_type = data_type class AzureSqlDatabaseDataSourceProperties(Model): """The properties that are associated with an Azure SQL database data source. :param server: The name of the SQL server containing the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type server: str :param database: The name of the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type database: str :param user: The user name that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type user: str :param password: The password that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type password: str :param table: The name of the table in the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type table: str """ _attribute_map = { 'server': {'key': 'server', 'type': 'str'}, 'database': {'key': 'database', 'type': 'str'}, 'user': {'key': 'user', 'type': 'str'}, 'password': {'key': 'password', 'type': 'str'}, 'table': {'key': 'table', 'type': 'str'}, } def __init__(self, *, server: str=None, database: str=None, user: str=None, password: str=None, table: str=None, **kwargs) -> None: super(AzureSqlDatabaseDataSourceProperties, self).__init__(**kwargs) self.server = server self.database = database self.user = user self.password = password self.table = table class AzureSqlDatabaseOutputDataSource(OutputDataSource): """Describes an Azure SQL database output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param server: The name of the SQL server containing the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type server: str :param database: The name of the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type database: str :param user: The user name that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type user: str :param password: The password that will be used to connect to the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type password: str :param table: The name of the table in the Azure SQL database. Required on PUT (CreateOrReplace) requests. :type table: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'server': {'key': 'properties.server', 'type': 'str'}, 'database': {'key': 'properties.database', 'type': 'str'}, 'user': {'key': 'properties.user', 'type': 'str'}, 'password': {'key': 'properties.password', 'type': 'str'}, 'table': {'key': 'properties.table', 'type': 'str'}, } def __init__(self, *, server: str=None, database: str=None, user: str=None, password: str=None, table: str=None, **kwargs) -> None: super(AzureSqlDatabaseOutputDataSource, self).__init__(**kwargs) self.server = server self.database = database self.user = user self.password = password self.table = table self.type = 'Microsoft.Sql/Server/Database' class AzureTableOutputDataSource(OutputDataSource): """Describes an Azure Table output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param account_name: The name of the Azure Storage account. Required on PUT (CreateOrReplace) requests. :type account_name: str :param account_key: The account key for the Azure Storage account. Required on PUT (CreateOrReplace) requests. :type account_key: str :param table: The name of the Azure Table. Required on PUT (CreateOrReplace) requests. :type table: str :param partition_key: This element indicates the name of a column from the SELECT statement in the query that will be used as the partition key for the Azure Table. Required on PUT (CreateOrReplace) requests. :type partition_key: str :param row_key: This element indicates the name of a column from the SELECT statement in the query that will be used as the row key for the Azure Table. Required on PUT (CreateOrReplace) requests. :type row_key: str :param columns_to_remove: If specified, each item in the array is the name of a column to remove (if present) from output event entities. :type columns_to_remove: list[str] :param batch_size: The number of rows to write to the Azure Table at a time. :type batch_size: int """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'account_name': {'key': 'properties.accountName', 'type': 'str'}, 'account_key': {'key': 'properties.accountKey', 'type': 'str'}, 'table': {'key': 'properties.table', 'type': 'str'}, 'partition_key': {'key': 'properties.partitionKey', 'type': 'str'}, 'row_key': {'key': 'properties.rowKey', 'type': 'str'}, 'columns_to_remove': {'key': 'properties.columnsToRemove', 'type': '[str]'}, 'batch_size': {'key': 'properties.batchSize', 'type': 'int'}, } def __init__(self, *, account_name: str=None, account_key: str=None, table: str=None, partition_key: str=None, row_key: str=None, columns_to_remove=None, batch_size: int=None, **kwargs) -> None: super(AzureTableOutputDataSource, self).__init__(**kwargs) self.account_name = account_name self.account_key = account_key self.table = table self.partition_key = partition_key self.row_key = row_key self.columns_to_remove = columns_to_remove self.batch_size = batch_size self.type = 'Microsoft.Storage/Table' class BlobDataSourceProperties(Model): """The properties that are associated with a blob data source. :param storage_accounts: A list of one or more Azure Storage accounts. Required on PUT (CreateOrReplace) requests. :type storage_accounts: list[~azure.mgmt.streamanalytics.models.StorageAccount] :param container: The name of a container within the associated Storage account. This container contains either the blob(s) to be read from or written to. Required on PUT (CreateOrReplace) requests. :type container: str :param path_pattern: The blob path pattern. Not a regular expression. It represents a pattern against which blob names will be matched to determine whether or not they should be included as input or output to the job. See https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-input or https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for a more detailed explanation and example. :type path_pattern: str :param date_format: The date format. Wherever {date} appears in pathPattern, the value of this property is used as the date format instead. :type date_format: str :param time_format: The time format. Wherever {time} appears in pathPattern, the value of this property is used as the time format instead. :type time_format: str """ _attribute_map = { 'storage_accounts': {'key': 'storageAccounts', 'type': '[StorageAccount]'}, 'container': {'key': 'container', 'type': 'str'}, 'path_pattern': {'key': 'pathPattern', 'type': 'str'}, 'date_format': {'key': 'dateFormat', 'type': 'str'}, 'time_format': {'key': 'timeFormat', 'type': 'str'}, } def __init__(self, *, storage_accounts=None, container: str=None, path_pattern: str=None, date_format: str=None, time_format: str=None, **kwargs) -> None: super(BlobDataSourceProperties, self).__init__(**kwargs) self.storage_accounts = storage_accounts self.container = container self.path_pattern = path_pattern self.date_format = date_format self.time_format = time_format class BlobOutputDataSource(OutputDataSource): """Describes a blob output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param storage_accounts: A list of one or more Azure Storage accounts. Required on PUT (CreateOrReplace) requests. :type storage_accounts: list[~azure.mgmt.streamanalytics.models.StorageAccount] :param container: The name of a container within the associated Storage account. This container contains either the blob(s) to be read from or written to. Required on PUT (CreateOrReplace) requests. :type container: str :param path_pattern: The blob path pattern. Not a regular expression. It represents a pattern against which blob names will be matched to determine whether or not they should be included as input or output to the job. See https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-input or https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for a more detailed explanation and example. :type path_pattern: str :param date_format: The date format. Wherever {date} appears in pathPattern, the value of this property is used as the date format instead. :type date_format: str :param time_format: The time format. Wherever {time} appears in pathPattern, the value of this property is used as the time format instead. :type time_format: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'storage_accounts': {'key': 'properties.storageAccounts', 'type': '[StorageAccount]'}, 'container': {'key': 'properties.container', 'type': 'str'}, 'path_pattern': {'key': 'properties.pathPattern', 'type': 'str'}, 'date_format': {'key': 'properties.dateFormat', 'type': 'str'}, 'time_format': {'key': 'properties.timeFormat', 'type': 'str'}, } def __init__(self, *, storage_accounts=None, container: str=None, path_pattern: str=None, date_format: str=None, time_format: str=None, **kwargs) -> None: super(BlobOutputDataSource, self).__init__(**kwargs) self.storage_accounts = storage_accounts self.container = container self.path_pattern = path_pattern self.date_format = date_format self.time_format = time_format self.type = 'Microsoft.Storage/Blob' class ReferenceInputDataSource(Model): """Describes an input data source that contains reference data. You probably want to use the sub-classes and not this class directly. Known sub-classes are: BlobReferenceInputDataSource All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Microsoft.Storage/Blob': 'BlobReferenceInputDataSource'} } def __init__(self, **kwargs) -> None: super(ReferenceInputDataSource, self).__init__(**kwargs) self.type = None class BlobReferenceInputDataSource(ReferenceInputDataSource): """Describes a blob input data source that contains reference data. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param storage_accounts: A list of one or more Azure Storage accounts. Required on PUT (CreateOrReplace) requests. :type storage_accounts: list[~azure.mgmt.streamanalytics.models.StorageAccount] :param container: The name of a container within the associated Storage account. This container contains either the blob(s) to be read from or written to. Required on PUT (CreateOrReplace) requests. :type container: str :param path_pattern: The blob path pattern. Not a regular expression. It represents a pattern against which blob names will be matched to determine whether or not they should be included as input or output to the job. See https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-input or https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for a more detailed explanation and example. :type path_pattern: str :param date_format: The date format. Wherever {date} appears in pathPattern, the value of this property is used as the date format instead. :type date_format: str :param time_format: The time format. Wherever {time} appears in pathPattern, the value of this property is used as the time format instead. :type time_format: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'storage_accounts': {'key': 'properties.storageAccounts', 'type': '[StorageAccount]'}, 'container': {'key': 'properties.container', 'type': 'str'}, 'path_pattern': {'key': 'properties.pathPattern', 'type': 'str'}, 'date_format': {'key': 'properties.dateFormat', 'type': 'str'}, 'time_format': {'key': 'properties.timeFormat', 'type': 'str'}, } def __init__(self, *, storage_accounts=None, container: str=None, path_pattern: str=None, date_format: str=None, time_format: str=None, **kwargs) -> None: super(BlobReferenceInputDataSource, self).__init__(**kwargs) self.storage_accounts = storage_accounts self.container = container self.path_pattern = path_pattern self.date_format = date_format self.time_format = time_format self.type = 'Microsoft.Storage/Blob' class StreamInputDataSource(Model): """Describes an input data source that contains stream data. You probably want to use the sub-classes and not this class directly. Known sub-classes are: IoTHubStreamInputDataSource, EventHubStreamInputDataSource, BlobStreamInputDataSource All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Microsoft.Devices/IotHubs': 'IoTHubStreamInputDataSource', 'Microsoft.ServiceBus/EventHub': 'EventHubStreamInputDataSource', 'Microsoft.Storage/Blob': 'BlobStreamInputDataSource'} } def __init__(self, **kwargs) -> None: super(StreamInputDataSource, self).__init__(**kwargs) self.type = None class BlobStreamInputDataSource(StreamInputDataSource): """Describes a blob input data source that contains stream data. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param storage_accounts: A list of one or more Azure Storage accounts. Required on PUT (CreateOrReplace) requests. :type storage_accounts: list[~azure.mgmt.streamanalytics.models.StorageAccount] :param container: The name of a container within the associated Storage account. This container contains either the blob(s) to be read from or written to. Required on PUT (CreateOrReplace) requests. :type container: str :param path_pattern: The blob path pattern. Not a regular expression. It represents a pattern against which blob names will be matched to determine whether or not they should be included as input or output to the job. See https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-input or https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for a more detailed explanation and example. :type path_pattern: str :param date_format: The date format. Wherever {date} appears in pathPattern, the value of this property is used as the date format instead. :type date_format: str :param time_format: The time format. Wherever {time} appears in pathPattern, the value of this property is used as the time format instead. :type time_format: str :param source_partition_count: The partition count of the blob input data source. Range 1 - 256. :type source_partition_count: int """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'storage_accounts': {'key': 'properties.storageAccounts', 'type': '[StorageAccount]'}, 'container': {'key': 'properties.container', 'type': 'str'}, 'path_pattern': {'key': 'properties.pathPattern', 'type': 'str'}, 'date_format': {'key': 'properties.dateFormat', 'type': 'str'}, 'time_format': {'key': 'properties.timeFormat', 'type': 'str'}, 'source_partition_count': {'key': 'properties.sourcePartitionCount', 'type': 'int'}, } def __init__(self, *, storage_accounts=None, container: str=None, path_pattern: str=None, date_format: str=None, time_format: str=None, source_partition_count: int=None, **kwargs) -> None: super(BlobStreamInputDataSource, self).__init__(**kwargs) self.storage_accounts = storage_accounts self.container = container self.path_pattern = path_pattern self.date_format = date_format self.time_format = time_format self.source_partition_count = source_partition_count self.type = 'Microsoft.Storage/Blob' class CloudError(Model): """CloudError. """ _attribute_map = { } class CsvSerialization(Serialization): """Describes how data from an input is serialized or how data is serialized when written to an output in CSV format. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param field_delimiter: Specifies the delimiter that will be used to separate comma-separated value (CSV) records. See https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-input or https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for a list of supported values. Required on PUT (CreateOrReplace) requests. :type field_delimiter: str :param encoding: Specifies the encoding of the incoming data in the case of input and the encoding of outgoing data in the case of output. Required on PUT (CreateOrReplace) requests. Possible values include: 'UTF8' :type encoding: str or ~azure.mgmt.streamanalytics.models.Encoding """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'field_delimiter': {'key': 'properties.fieldDelimiter', 'type': 'str'}, 'encoding': {'key': 'properties.encoding', 'type': 'str'}, } def __init__(self, *, field_delimiter: str=None, encoding=None, **kwargs) -> None: super(CsvSerialization, self).__init__(**kwargs) self.field_delimiter = field_delimiter self.encoding = encoding self.type = 'Csv' class DiagnosticCondition(Model): """Condition applicable to the resource, or to the job overall, that warrant customer attention. Variables are only populated by the server, and will be ignored when sending a request. :ivar since: The UTC timestamp of when the condition started. Customers should be able to find a corresponding event in the ops log around this time. :vartype since: str :ivar code: The opaque diagnostic code. :vartype code: str :ivar message: The human-readable message describing the condition in detail. Localized in the Accept-Language of the client request. :vartype message: str """ _validation = { 'since': {'readonly': True}, 'code': {'readonly': True}, 'message': {'readonly': True}, } _attribute_map = { 'since': {'key': 'since', 'type': 'str'}, 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } def __init__(self, **kwargs) -> None: super(DiagnosticCondition, self).__init__(**kwargs) self.since = None self.code = None self.message = None class Diagnostics(Model): """Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. Variables are only populated by the server, and will be ignored when sending a request. :ivar conditions: A collection of zero or more conditions applicable to the resource, or to the job overall, that warrant customer attention. :vartype conditions: list[~azure.mgmt.streamanalytics.models.DiagnosticCondition] """ _validation = { 'conditions': {'readonly': True}, } _attribute_map = { 'conditions': {'key': 'conditions', 'type': '[DiagnosticCondition]'}, } def __init__(self, **kwargs) -> None: super(Diagnostics, self).__init__(**kwargs) self.conditions = None class DocumentDbOutputDataSource(OutputDataSource): """Describes a DocumentDB output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param account_id: The DocumentDB account name or ID. Required on PUT (CreateOrReplace) requests. :type account_id: str :param account_key: The account key for the DocumentDB account. Required on PUT (CreateOrReplace) requests. :type account_key: str :param database: The name of the DocumentDB database. Required on PUT (CreateOrReplace) requests. :type database: str :param collection_name_pattern: The collection name pattern for the collections to be used. The collection name format can be constructed using the optional {partition} token, where partitions start from 0. See the DocumentDB section of https://docs.microsoft.com/en-us/rest/api/streamanalytics/stream-analytics-output for more information. Required on PUT (CreateOrReplace) requests. :type collection_name_pattern: str :param partition_key: The name of the field in output events used to specify the key for partitioning output across collections. If 'collectionNamePattern' contains the {partition} token, this property is required to be specified. :type partition_key: str :param document_id: The name of the field in output events used to specify the primary key which insert or update operations are based on. :type document_id: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'account_id': {'key': 'properties.accountId', 'type': 'str'}, 'account_key': {'key': 'properties.accountKey', 'type': 'str'}, 'database': {'key': 'properties.database', 'type': 'str'}, 'collection_name_pattern': {'key': 'properties.collectionNamePattern', 'type': 'str'}, 'partition_key': {'key': 'properties.partitionKey', 'type': 'str'}, 'document_id': {'key': 'properties.documentId', 'type': 'str'}, } def __init__(self, *, account_id: str=None, account_key: str=None, database: str=None, collection_name_pattern: str=None, partition_key: str=None, document_id: str=None, **kwargs) -> None: super(DocumentDbOutputDataSource, self).__init__(**kwargs) self.account_id = account_id self.account_key = account_key self.database = database self.collection_name_pattern = collection_name_pattern self.partition_key = partition_key self.document_id = document_id self.type = 'Microsoft.Storage/DocumentDB' class ErrorResponse(Model): """Describes the error that occurred. Variables are only populated by the server, and will be ignored when sending a request. :ivar code: Error code associated with the error that occurred. :vartype code: str :ivar message: Describes the error in detail. :vartype message: str """ _validation = { 'code': {'readonly': True}, 'message': {'readonly': True}, } _attribute_map = { 'code': {'key': 'code', 'type': 'str'}, 'message': {'key': 'message', 'type': 'str'}, } def __init__(self, **kwargs) -> None: super(ErrorResponse, self).__init__(**kwargs) self.code = None self.message = None class ServiceBusDataSourceProperties(Model): """The common properties that are associated with Service Bus data sources (Queues, Topics, Event Hubs, etc.). :param service_bus_namespace: The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type service_bus_namespace: str :param shared_access_policy_name: The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_name: str :param shared_access_policy_key: The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_key: str """ _attribute_map = { 'service_bus_namespace': {'key': 'serviceBusNamespace', 'type': 'str'}, 'shared_access_policy_name': {'key': 'sharedAccessPolicyName', 'type': 'str'}, 'shared_access_policy_key': {'key': 'sharedAccessPolicyKey', 'type': 'str'}, } def __init__(self, *, service_bus_namespace: str=None, shared_access_policy_name: str=None, shared_access_policy_key: str=None, **kwargs) -> None: super(ServiceBusDataSourceProperties, self).__init__(**kwargs) self.service_bus_namespace = service_bus_namespace self.shared_access_policy_name = shared_access_policy_name self.shared_access_policy_key = shared_access_policy_key class EventHubDataSourceProperties(ServiceBusDataSourceProperties): """The common properties that are associated with Event Hub data sources. :param service_bus_namespace: The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type service_bus_namespace: str :param shared_access_policy_name: The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_name: str :param shared_access_policy_key: The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_key: str :param event_hub_name: The name of the Event Hub. Required on PUT (CreateOrReplace) requests. :type event_hub_name: str """ _attribute_map = { 'service_bus_namespace': {'key': 'serviceBusNamespace', 'type': 'str'}, 'shared_access_policy_name': {'key': 'sharedAccessPolicyName', 'type': 'str'}, 'shared_access_policy_key': {'key': 'sharedAccessPolicyKey', 'type': 'str'}, 'event_hub_name': {'key': 'eventHubName', 'type': 'str'}, } def __init__(self, *, service_bus_namespace: str=None, shared_access_policy_name: str=None, shared_access_policy_key: str=None, event_hub_name: str=None, **kwargs) -> None: super(EventHubDataSourceProperties, self).__init__(service_bus_namespace=service_bus_namespace, shared_access_policy_name=shared_access_policy_name, shared_access_policy_key=shared_access_policy_key, **kwargs) self.event_hub_name = event_hub_name class EventHubOutputDataSource(OutputDataSource): """Describes an Event Hub output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param service_bus_namespace: The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type service_bus_namespace: str :param shared_access_policy_name: The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_name: str :param shared_access_policy_key: The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_key: str :param event_hub_name: The name of the Event Hub. Required on PUT (CreateOrReplace) requests. :type event_hub_name: str :param partition_key: The key/column that is used to determine to which partition to send event data. :type partition_key: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'service_bus_namespace': {'key': 'properties.serviceBusNamespace', 'type': 'str'}, 'shared_access_policy_name': {'key': 'properties.sharedAccessPolicyName', 'type': 'str'}, 'shared_access_policy_key': {'key': 'properties.sharedAccessPolicyKey', 'type': 'str'}, 'event_hub_name': {'key': 'properties.eventHubName', 'type': 'str'}, 'partition_key': {'key': 'properties.partitionKey', 'type': 'str'}, } def __init__(self, *, service_bus_namespace: str=None, shared_access_policy_name: str=None, shared_access_policy_key: str=None, event_hub_name: str=None, partition_key: str=None, **kwargs) -> None: super(EventHubOutputDataSource, self).__init__(**kwargs) self.service_bus_namespace = service_bus_namespace self.shared_access_policy_name = shared_access_policy_name self.shared_access_policy_key = shared_access_policy_key self.event_hub_name = event_hub_name self.partition_key = partition_key self.type = 'Microsoft.ServiceBus/EventHub' class EventHubStreamInputDataSource(StreamInputDataSource): """Describes an Event Hub input data source that contains stream data. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param service_bus_namespace: The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type service_bus_namespace: str :param shared_access_policy_name: The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_name: str :param shared_access_policy_key: The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_key: str :param event_hub_name: The name of the Event Hub. Required on PUT (CreateOrReplace) requests. :type event_hub_name: str :param consumer_group_name: The name of an Event Hub Consumer Group that should be used to read events from the Event Hub. Specifying distinct consumer group names for multiple inputs allows each of those inputs to receive the same events from the Event Hub. If not specified, the input uses the Event Hub’s default consumer group. :type consumer_group_name: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'service_bus_namespace': {'key': 'properties.serviceBusNamespace', 'type': 'str'}, 'shared_access_policy_name': {'key': 'properties.sharedAccessPolicyName', 'type': 'str'}, 'shared_access_policy_key': {'key': 'properties.sharedAccessPolicyKey', 'type': 'str'}, 'event_hub_name': {'key': 'properties.eventHubName', 'type': 'str'}, 'consumer_group_name': {'key': 'properties.consumerGroupName', 'type': 'str'}, } def __init__(self, *, service_bus_namespace: str=None, shared_access_policy_name: str=None, shared_access_policy_key: str=None, event_hub_name: str=None, consumer_group_name: str=None, **kwargs) -> None: super(EventHubStreamInputDataSource, self).__init__(**kwargs) self.service_bus_namespace = service_bus_namespace self.shared_access_policy_name = shared_access_policy_name self.shared_access_policy_key = shared_access_policy_key self.event_hub_name = event_hub_name self.consumer_group_name = consumer_group_name self.type = 'Microsoft.ServiceBus/EventHub' class SubResource(Model): """The base sub-resource model definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :param name: Resource name :type name: str :ivar type: Resource type :vartype type: str """ _validation = { 'id': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } def __init__(self, *, name: str=None, **kwargs) -> None: super(SubResource, self).__init__(**kwargs) self.id = None self.name = name self.type = None class Function(SubResource): """A function object, containing all information associated with the named function. All functions are contained under a streaming job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :param name: Resource name :type name: str :ivar type: Resource type :vartype type: str :param properties: The properties that are associated with a function. :type properties: ~azure.mgmt.streamanalytics.models.FunctionProperties """ _validation = { 'id': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'FunctionProperties'}, } def __init__(self, *, name: str=None, properties=None, **kwargs) -> None: super(Function, self).__init__(name=name, **kwargs) self.properties = properties class FunctionInput(Model): """Describes one input parameter of a function. :param data_type: The (Azure Stream Analytics supported) data type of the function input parameter. A list of valid Azure Stream Analytics data types are described at https://msdn.microsoft.com/en-us/library/azure/dn835065.aspx :type data_type: str :param is_configuration_parameter: A flag indicating if the parameter is a configuration parameter. True if this input parameter is expected to be a constant. Default is false. :type is_configuration_parameter: bool """ _attribute_map = { 'data_type': {'key': 'dataType', 'type': 'str'}, 'is_configuration_parameter': {'key': 'isConfigurationParameter', 'type': 'bool'}, } def __init__(self, *, data_type: str=None, is_configuration_parameter: bool=None, **kwargs) -> None: super(FunctionInput, self).__init__(**kwargs) self.data_type = data_type self.is_configuration_parameter = is_configuration_parameter class FunctionOutput(Model): """Describes the output of a function. :param data_type: The (Azure Stream Analytics supported) data type of the function output. A list of valid Azure Stream Analytics data types are described at https://msdn.microsoft.com/en-us/library/azure/dn835065.aspx :type data_type: str """ _attribute_map = { 'data_type': {'key': 'dataType', 'type': 'str'}, } def __init__(self, *, data_type: str=None, **kwargs) -> None: super(FunctionOutput, self).__init__(**kwargs) self.data_type = data_type class FunctionProperties(Model): """The properties that are associated with a function. You probably want to use the sub-classes and not this class directly. Known sub-classes are: ScalarFunctionProperties Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar etag: The current entity tag for the function. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str :param type: Required. Constant filled by server. :type type: str """ _validation = { 'etag': {'readonly': True}, 'type': {'required': True}, } _attribute_map = { 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Scalar': 'ScalarFunctionProperties'} } def __init__(self, **kwargs) -> None: super(FunctionProperties, self).__init__(**kwargs) self.etag = None self.type = None class Input(SubResource): """An input object, containing all information associated with the named input. All inputs are contained under a streaming job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :param name: Resource name :type name: str :ivar type: Resource type :vartype type: str :param properties: The properties that are associated with an input. Required on PUT (CreateOrReplace) requests. :type properties: ~azure.mgmt.streamanalytics.models.InputProperties """ _validation = { 'id': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'properties': {'key': 'properties', 'type': 'InputProperties'}, } def __init__(self, *, name: str=None, properties=None, **kwargs) -> None: super(Input, self).__init__(name=name, **kwargs) self.properties = properties class InputProperties(Model): """The properties that are associated with an input. You probably want to use the sub-classes and not this class directly. Known sub-classes are: ReferenceInputProperties, StreamInputProperties Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param serialization: Describes how data from an input is serialized or how data is serialized when written to an output. Required on PUT (CreateOrReplace) requests. :type serialization: ~azure.mgmt.streamanalytics.models.Serialization :ivar diagnostics: Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. :vartype diagnostics: ~azure.mgmt.streamanalytics.models.Diagnostics :ivar etag: The current entity tag for the input. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str :param type: Required. Constant filled by server. :type type: str """ _validation = { 'diagnostics': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'required': True}, } _attribute_map = { 'serialization': {'key': 'serialization', 'type': 'Serialization'}, 'diagnostics': {'key': 'diagnostics', 'type': 'Diagnostics'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, } _subtype_map = { 'type': {'Reference': 'ReferenceInputProperties', 'Stream': 'StreamInputProperties'} } def __init__(self, *, serialization=None, **kwargs) -> None: super(InputProperties, self).__init__(**kwargs) self.serialization = serialization self.diagnostics = None self.etag = None self.type = None class IoTHubStreamInputDataSource(StreamInputDataSource): """Describes an IoT Hub input data source that contains stream data. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param iot_hub_namespace: The name or the URI of the IoT Hub. Required on PUT (CreateOrReplace) requests. :type iot_hub_namespace: str :param shared_access_policy_name: The shared access policy name for the IoT Hub. This policy must contain at least the Service connect permission. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_name: str :param shared_access_policy_key: The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_key: str :param consumer_group_name: The name of an IoT Hub Consumer Group that should be used to read events from the IoT Hub. If not specified, the input uses the Iot Hub’s default consumer group. :type consumer_group_name: str :param endpoint: The IoT Hub endpoint to connect to (ie. messages/events, messages/operationsMonitoringEvents, etc.). :type endpoint: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'iot_hub_namespace': {'key': 'properties.iotHubNamespace', 'type': 'str'}, 'shared_access_policy_name': {'key': 'properties.sharedAccessPolicyName', 'type': 'str'}, 'shared_access_policy_key': {'key': 'properties.sharedAccessPolicyKey', 'type': 'str'}, 'consumer_group_name': {'key': 'properties.consumerGroupName', 'type': 'str'}, 'endpoint': {'key': 'properties.endpoint', 'type': 'str'}, } def __init__(self, *, iot_hub_namespace: str=None, shared_access_policy_name: str=None, shared_access_policy_key: str=None, consumer_group_name: str=None, endpoint: str=None, **kwargs) -> None: super(IoTHubStreamInputDataSource, self).__init__(**kwargs) self.iot_hub_namespace = iot_hub_namespace self.shared_access_policy_name = shared_access_policy_name self.shared_access_policy_key = shared_access_policy_key self.consumer_group_name = consumer_group_name self.endpoint = endpoint self.type = 'Microsoft.Devices/IotHubs' class JavaScriptFunctionBinding(FunctionBinding): """The binding to a JavaScript function. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param script: The JavaScript code containing a single function definition. For example: 'function (x, y) { return x + y; }' :type script: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'script': {'key': 'properties.script', 'type': 'str'}, } def __init__(self, *, script: str=None, **kwargs) -> None: super(JavaScriptFunctionBinding, self).__init__(**kwargs) self.script = script self.type = 'Microsoft.StreamAnalytics/JavascriptUdf' class JavaScriptFunctionRetrieveDefaultDefinitionParameters(FunctionRetrieveDefaultDefinitionParameters): """The parameters needed to retrieve the default function definition for a JavaScript function. All required parameters must be populated in order to send to Azure. :param binding_type: Required. Constant filled by server. :type binding_type: str :param script: The JavaScript code containing a single function definition. For example: 'function (x, y) { return x + y; }'. :type script: str :param udf_type: The function type. Possible values include: 'Scalar' :type udf_type: str or ~azure.mgmt.streamanalytics.models.UdfType """ _validation = { 'binding_type': {'required': True}, } _attribute_map = { 'binding_type': {'key': 'bindingType', 'type': 'str'}, 'script': {'key': 'bindingRetrievalProperties.script', 'type': 'str'}, 'udf_type': {'key': 'bindingRetrievalProperties.udfType', 'type': 'UdfType'}, } def __init__(self, *, script: str=None, udf_type=None, **kwargs) -> None: super(JavaScriptFunctionRetrieveDefaultDefinitionParameters, self).__init__(**kwargs) self.script = script self.udf_type = udf_type self.binding_type = 'Microsoft.StreamAnalytics/JavascriptUdf' class JsonSerialization(Serialization): """Describes how data from an input is serialized or how data is serialized when written to an output in JSON format. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param encoding: Specifies the encoding of the incoming data in the case of input and the encoding of outgoing data in the case of output. Required on PUT (CreateOrReplace) requests. Possible values include: 'UTF8' :type encoding: str or ~azure.mgmt.streamanalytics.models.Encoding :param format: This property only applies to JSON serialization of outputs only. It is not applicable to inputs. This property specifies the format of the JSON the output will be written in. The currently supported values are 'lineSeparated' indicating the output will be formatted by having each JSON object separated by a new line and 'array' indicating the output will be formatted as an array of JSON objects. Default value is 'lineSeparated' if left null. Possible values include: 'LineSeparated', 'Array' :type format: str or ~azure.mgmt.streamanalytics.models.JsonOutputSerializationFormat """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'encoding': {'key': 'properties.encoding', 'type': 'str'}, 'format': {'key': 'properties.format', 'type': 'str'}, } def __init__(self, *, encoding=None, format=None, **kwargs) -> None: super(JsonSerialization, self).__init__(**kwargs) self.encoding = encoding self.format = format self.type = 'Json' class OAuthBasedDataSourceProperties(Model): """The properties that are associated with data sources that use OAuth as their authentication model. :param refresh_token: A refresh token that can be used to obtain a valid access token that can then be used to authenticate with the data source. A valid refresh token is currently only obtainable via the Azure Portal. It is recommended to put a dummy string value here when creating the data source and then going to the Azure Portal to authenticate the data source which will update this property with a valid refresh token. Required on PUT (CreateOrReplace) requests. :type refresh_token: str :param token_user_principal_name: The user principal name (UPN) of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain the refresh token. :type token_user_principal_name: str :param token_user_display_name: The user display name of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain the refresh token. :type token_user_display_name: str """ _attribute_map = { 'refresh_token': {'key': 'refreshToken', 'type': 'str'}, 'token_user_principal_name': {'key': 'tokenUserPrincipalName', 'type': 'str'}, 'token_user_display_name': {'key': 'tokenUserDisplayName', 'type': 'str'}, } def __init__(self, *, refresh_token: str=None, token_user_principal_name: str=None, token_user_display_name: str=None, **kwargs) -> None: super(OAuthBasedDataSourceProperties, self).__init__(**kwargs) self.refresh_token = refresh_token self.token_user_principal_name = token_user_principal_name self.token_user_display_name = token_user_display_name class Operation(Model): """A Stream Analytics REST API operation. Variables are only populated by the server, and will be ignored when sending a request. :ivar name: The name of the operation being performed on this particular object. :vartype name: str :ivar display: Contains the localized display information for this particular operation / action. :vartype display: ~azure.mgmt.streamanalytics.models.OperationDisplay """ _validation = { 'name': {'readonly': True}, 'display': {'readonly': True}, } _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, 'display': {'key': 'display', 'type': 'OperationDisplay'}, } def __init__(self, **kwargs) -> None: super(Operation, self).__init__(**kwargs) self.name = None self.display = None class OperationDisplay(Model): """Contains the localized display information for this particular operation / action. Variables are only populated by the server, and will be ignored when sending a request. :ivar provider: The localized friendly form of the resource provider name. :vartype provider: str :ivar resource: The localized friendly form of the resource type related to this action/operation. :vartype resource: str :ivar operation: The localized friendly name for the operation. :vartype operation: str :ivar description: The localized friendly description for the operation. :vartype description: str """ _validation = { 'provider': {'readonly': True}, 'resource': {'readonly': True}, 'operation': {'readonly': True}, 'description': {'readonly': True}, } _attribute_map = { 'provider': {'key': 'provider', 'type': 'str'}, 'resource': {'key': 'resource', 'type': 'str'}, 'operation': {'key': 'operation', 'type': 'str'}, 'description': {'key': 'description', 'type': 'str'}, } def __init__(self, **kwargs) -> None: super(OperationDisplay, self).__init__(**kwargs) self.provider = None self.resource = None self.operation = None self.description = None class Output(SubResource): """An output object, containing all information associated with the named output. All outputs are contained under a streaming job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :param name: Resource name :type name: str :ivar type: Resource type :vartype type: str :param datasource: Describes the data source that output will be written to. Required on PUT (CreateOrReplace) requests. :type datasource: ~azure.mgmt.streamanalytics.models.OutputDataSource :param serialization: Describes how data from an input is serialized or how data is serialized when written to an output. Required on PUT (CreateOrReplace) requests. :type serialization: ~azure.mgmt.streamanalytics.models.Serialization :ivar diagnostics: Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. :vartype diagnostics: ~azure.mgmt.streamanalytics.models.Diagnostics :ivar etag: The current entity tag for the output. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str """ _validation = { 'id': {'readonly': True}, 'type': {'readonly': True}, 'diagnostics': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'datasource': {'key': 'properties.datasource', 'type': 'OutputDataSource'}, 'serialization': {'key': 'properties.serialization', 'type': 'Serialization'}, 'diagnostics': {'key': 'properties.diagnostics', 'type': 'Diagnostics'}, 'etag': {'key': 'properties.etag', 'type': 'str'}, } def __init__(self, *, name: str=None, datasource=None, serialization=None, **kwargs) -> None: super(Output, self).__init__(name=name, **kwargs) self.datasource = datasource self.serialization = serialization self.diagnostics = None self.etag = None class PowerBIOutputDataSource(OutputDataSource): """Describes a Power BI output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param refresh_token: A refresh token that can be used to obtain a valid access token that can then be used to authenticate with the data source. A valid refresh token is currently only obtainable via the Azure Portal. It is recommended to put a dummy string value here when creating the data source and then going to the Azure Portal to authenticate the data source which will update this property with a valid refresh token. Required on PUT (CreateOrReplace) requests. :type refresh_token: str :param token_user_principal_name: The user principal name (UPN) of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain the refresh token. :type token_user_principal_name: str :param token_user_display_name: The user display name of the user that was used to obtain the refresh token. Use this property to help remember which user was used to obtain the refresh token. :type token_user_display_name: str :param dataset: The name of the Power BI dataset. Required on PUT (CreateOrReplace) requests. :type dataset: str :param table: The name of the Power BI table under the specified dataset. Required on PUT (CreateOrReplace) requests. :type table: str :param group_id: The ID of the Power BI group. :type group_id: str :param group_name: The name of the Power BI group. Use this property to help remember which specific Power BI group id was used. :type group_name: str """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'refresh_token': {'key': 'properties.refreshToken', 'type': 'str'}, 'token_user_principal_name': {'key': 'properties.tokenUserPrincipalName', 'type': 'str'}, 'token_user_display_name': {'key': 'properties.tokenUserDisplayName', 'type': 'str'}, 'dataset': {'key': 'properties.dataset', 'type': 'str'}, 'table': {'key': 'properties.table', 'type': 'str'}, 'group_id': {'key': 'properties.groupId', 'type': 'str'}, 'group_name': {'key': 'properties.groupName', 'type': 'str'}, } def __init__(self, *, refresh_token: str=None, token_user_principal_name: str=None, token_user_display_name: str=None, dataset: str=None, table: str=None, group_id: str=None, group_name: str=None, **kwargs) -> None: super(PowerBIOutputDataSource, self).__init__(**kwargs) self.refresh_token = refresh_token self.token_user_principal_name = token_user_principal_name self.token_user_display_name = token_user_display_name self.dataset = dataset self.table = table self.group_id = group_id self.group_name = group_name self.type = 'PowerBI' class ReferenceInputProperties(InputProperties): """The properties that are associated with an input containing reference data. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param serialization: Describes how data from an input is serialized or how data is serialized when written to an output. Required on PUT (CreateOrReplace) requests. :type serialization: ~azure.mgmt.streamanalytics.models.Serialization :ivar diagnostics: Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. :vartype diagnostics: ~azure.mgmt.streamanalytics.models.Diagnostics :ivar etag: The current entity tag for the input. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str :param type: Required. Constant filled by server. :type type: str :param datasource: Describes an input data source that contains reference data. Required on PUT (CreateOrReplace) requests. :type datasource: ~azure.mgmt.streamanalytics.models.ReferenceInputDataSource """ _validation = { 'diagnostics': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'required': True}, } _attribute_map = { 'serialization': {'key': 'serialization', 'type': 'Serialization'}, 'diagnostics': {'key': 'diagnostics', 'type': 'Diagnostics'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'datasource': {'key': 'datasource', 'type': 'ReferenceInputDataSource'}, } def __init__(self, *, serialization=None, datasource=None, **kwargs) -> None: super(ReferenceInputProperties, self).__init__(serialization=serialization, **kwargs) self.datasource = datasource self.type = 'Reference' class Resource(Model): """The base resource model definition. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :ivar type: Resource type :vartype type: str :param location: Resource location. Required on PUT (CreateOrReplace) requests. :type location: str :param tags: Resource tags :type tags: dict[str, str] """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, } def __init__(self, *, location: str=None, tags=None, **kwargs) -> None: super(Resource, self).__init__(**kwargs) self.id = None self.name = None self.type = None self.location = location self.tags = tags class ResourceTestStatus(Model): """Describes the status of the test operation along with error information, if applicable. Variables are only populated by the server, and will be ignored when sending a request. :ivar status: The status of the test operation. :vartype status: str :ivar error: Describes the error that occurred. :vartype error: ~azure.mgmt.streamanalytics.models.ErrorResponse """ _validation = { 'status': {'readonly': True}, 'error': {'readonly': True}, } _attribute_map = { 'status': {'key': 'status', 'type': 'str'}, 'error': {'key': 'error', 'type': 'ErrorResponse'}, } def __init__(self, **kwargs) -> None: super(ResourceTestStatus, self).__init__(**kwargs) self.status = None self.error = None class ScalarFunctionProperties(FunctionProperties): """The properties that are associated with a scalar function. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :ivar etag: The current entity tag for the function. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str :param type: Required. Constant filled by server. :type type: str :param inputs: A list of inputs describing the parameters of the function. :type inputs: list[~azure.mgmt.streamanalytics.models.FunctionInput] :param output: The output of the function. :type output: ~azure.mgmt.streamanalytics.models.FunctionOutput :param binding: The physical binding of the function. For example, in the Azure Machine Learning web service’s case, this describes the endpoint. :type binding: ~azure.mgmt.streamanalytics.models.FunctionBinding """ _validation = { 'etag': {'readonly': True}, 'type': {'required': True}, } _attribute_map = { 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'inputs': {'key': 'properties.inputs', 'type': '[FunctionInput]'}, 'output': {'key': 'properties.output', 'type': 'FunctionOutput'}, 'binding': {'key': 'properties.binding', 'type': 'FunctionBinding'}, } def __init__(self, *, inputs=None, output=None, binding=None, **kwargs) -> None: super(ScalarFunctionProperties, self).__init__(**kwargs) self.inputs = inputs self.output = output self.binding = binding self.type = 'Scalar' class ServiceBusQueueOutputDataSource(OutputDataSource): """Describes a Service Bus Queue output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param service_bus_namespace: The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type service_bus_namespace: str :param shared_access_policy_name: The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_name: str :param shared_access_policy_key: The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_key: str :param queue_name: The name of the Service Bus Queue. Required on PUT (CreateOrReplace) requests. :type queue_name: str :param property_columns: A string array of the names of output columns to be attached to Service Bus messages as custom properties. :type property_columns: list[str] """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'service_bus_namespace': {'key': 'properties.serviceBusNamespace', 'type': 'str'}, 'shared_access_policy_name': {'key': 'properties.sharedAccessPolicyName', 'type': 'str'}, 'shared_access_policy_key': {'key': 'properties.sharedAccessPolicyKey', 'type': 'str'}, 'queue_name': {'key': 'properties.queueName', 'type': 'str'}, 'property_columns': {'key': 'properties.propertyColumns', 'type': '[str]'}, } def __init__(self, *, service_bus_namespace: str=None, shared_access_policy_name: str=None, shared_access_policy_key: str=None, queue_name: str=None, property_columns=None, **kwargs) -> None: super(ServiceBusQueueOutputDataSource, self).__init__(**kwargs) self.service_bus_namespace = service_bus_namespace self.shared_access_policy_name = shared_access_policy_name self.shared_access_policy_key = shared_access_policy_key self.queue_name = queue_name self.property_columns = property_columns self.type = 'Microsoft.ServiceBus/Queue' class ServiceBusTopicOutputDataSource(OutputDataSource): """Describes a Service Bus Topic output data source. All required parameters must be populated in order to send to Azure. :param type: Required. Constant filled by server. :type type: str :param service_bus_namespace: The namespace that is associated with the desired Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type service_bus_namespace: str :param shared_access_policy_name: The shared access policy name for the Event Hub, Service Bus Queue, Service Bus Topic, etc. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_name: str :param shared_access_policy_key: The shared access policy key for the specified shared access policy. Required on PUT (CreateOrReplace) requests. :type shared_access_policy_key: str :param topic_name: The name of the Service Bus Topic. Required on PUT (CreateOrReplace) requests. :type topic_name: str :param property_columns: A string array of the names of output columns to be attached to Service Bus messages as custom properties. :type property_columns: list[str] """ _validation = { 'type': {'required': True}, } _attribute_map = { 'type': {'key': 'type', 'type': 'str'}, 'service_bus_namespace': {'key': 'properties.serviceBusNamespace', 'type': 'str'}, 'shared_access_policy_name': {'key': 'properties.sharedAccessPolicyName', 'type': 'str'}, 'shared_access_policy_key': {'key': 'properties.sharedAccessPolicyKey', 'type': 'str'}, 'topic_name': {'key': 'properties.topicName', 'type': 'str'}, 'property_columns': {'key': 'properties.propertyColumns', 'type': '[str]'}, } def __init__(self, *, service_bus_namespace: str=None, shared_access_policy_name: str=None, shared_access_policy_key: str=None, topic_name: str=None, property_columns=None, **kwargs) -> None: super(ServiceBusTopicOutputDataSource, self).__init__(**kwargs) self.service_bus_namespace = service_bus_namespace self.shared_access_policy_name = shared_access_policy_name self.shared_access_policy_key = shared_access_policy_key self.topic_name = topic_name self.property_columns = property_columns self.type = 'Microsoft.ServiceBus/Topic' class Sku(Model): """The properties that are associated with a SKU. :param name: The name of the SKU. Required on PUT (CreateOrReplace) requests. Possible values include: 'Standard' :type name: str or ~azure.mgmt.streamanalytics.models.SkuName """ _attribute_map = { 'name': {'key': 'name', 'type': 'str'}, } def __init__(self, *, name=None, **kwargs) -> None: super(Sku, self).__init__(**kwargs) self.name = name class StartStreamingJobParameters(Model): """Parameters supplied to the Start Streaming Job operation. :param output_start_mode: Value may be JobStartTime, CustomTime, or LastOutputEventTime to indicate whether the starting point of the output event stream should start whenever the job is started, start at a custom user time stamp specified via the outputStartTime property, or start from the last event output time. Possible values include: 'JobStartTime', 'CustomTime', 'LastOutputEventTime' :type output_start_mode: str or ~azure.mgmt.streamanalytics.models.OutputStartMode :param output_start_time: Value is either an ISO-8601 formatted time stamp that indicates the starting point of the output event stream, or null to indicate that the output event stream will start whenever the streaming job is started. This property must have a value if outputStartMode is set to CustomTime. :type output_start_time: datetime """ _attribute_map = { 'output_start_mode': {'key': 'outputStartMode', 'type': 'str'}, 'output_start_time': {'key': 'outputStartTime', 'type': 'iso-8601'}, } def __init__(self, *, output_start_mode=None, output_start_time=None, **kwargs) -> None: super(StartStreamingJobParameters, self).__init__(**kwargs) self.output_start_mode = output_start_mode self.output_start_time = output_start_time class StorageAccount(Model): """The properties that are associated with an Azure Storage account. :param account_name: The name of the Azure Storage account. Required on PUT (CreateOrReplace) requests. :type account_name: str :param account_key: The account key for the Azure Storage account. Required on PUT (CreateOrReplace) requests. :type account_key: str """ _attribute_map = { 'account_name': {'key': 'accountName', 'type': 'str'}, 'account_key': {'key': 'accountKey', 'type': 'str'}, } def __init__(self, *, account_name: str=None, account_key: str=None, **kwargs) -> None: super(StorageAccount, self).__init__(**kwargs) self.account_name = account_name self.account_key = account_key class StreamingJob(Resource): """A streaming job object, containing all information associated with the named streaming job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :ivar name: Resource name :vartype name: str :ivar type: Resource type :vartype type: str :param location: Resource location. Required on PUT (CreateOrReplace) requests. :type location: str :param tags: Resource tags :type tags: dict[str, str] :param sku: Describes the SKU of the streaming job. Required on PUT (CreateOrReplace) requests. :type sku: ~azure.mgmt.streamanalytics.models.Sku :ivar job_id: A GUID uniquely identifying the streaming job. This GUID is generated upon creation of the streaming job. :vartype job_id: str :ivar provisioning_state: Describes the provisioning status of the streaming job. :vartype provisioning_state: str :ivar job_state: Describes the state of the streaming job. :vartype job_state: str :param output_start_mode: This property should only be utilized when it is desired that the job be started immediately upon creation. Value may be JobStartTime, CustomTime, or LastOutputEventTime to indicate whether the starting point of the output event stream should start whenever the job is started, start at a custom user time stamp specified via the outputStartTime property, or start from the last event output time. Possible values include: 'JobStartTime', 'CustomTime', 'LastOutputEventTime' :type output_start_mode: str or ~azure.mgmt.streamanalytics.models.OutputStartMode :param output_start_time: Value is either an ISO-8601 formatted time stamp that indicates the starting point of the output event stream, or null to indicate that the output event stream will start whenever the streaming job is started. This property must have a value if outputStartMode is set to CustomTime. :type output_start_time: datetime :ivar last_output_event_time: Value is either an ISO-8601 formatted timestamp indicating the last output event time of the streaming job or null indicating that output has not yet been produced. In case of multiple outputs or multiple streams, this shows the latest value in that set. :vartype last_output_event_time: datetime :param events_out_of_order_policy: Indicates the policy to apply to events that arrive out of order in the input event stream. Possible values include: 'Adjust', 'Drop' :type events_out_of_order_policy: str or ~azure.mgmt.streamanalytics.models.EventsOutOfOrderPolicy :param output_error_policy: Indicates the policy to apply to events that arrive at the output and cannot be written to the external storage due to being malformed (missing column values, column values of wrong type or size). Possible values include: 'Stop', 'Drop' :type output_error_policy: str or ~azure.mgmt.streamanalytics.models.OutputErrorPolicy :param events_out_of_order_max_delay_in_seconds: The maximum tolerable delay in seconds where out-of-order events can be adjusted to be back in order. :type events_out_of_order_max_delay_in_seconds: int :param events_late_arrival_max_delay_in_seconds: The maximum tolerable delay in seconds where events arriving late could be included. Supported range is -1 to 1814399 (20.23:59:59 days) and -1 is used to specify wait indefinitely. If the property is absent, it is interpreted to have a value of -1. :type events_late_arrival_max_delay_in_seconds: int :param data_locale: The data locale of the stream analytics job. Value should be the name of a supported .NET Culture from the set https://msdn.microsoft.com/en-us/library/system.globalization.culturetypes(v=vs.110).aspx. Defaults to 'en-US' if none specified. :type data_locale: str :param compatibility_level: Controls certain runtime behaviors of the streaming job. Possible values include: '1.0' :type compatibility_level: str or ~azure.mgmt.streamanalytics.models.CompatibilityLevel :ivar created_date: Value is an ISO-8601 formatted UTC timestamp indicating when the streaming job was created. :vartype created_date: datetime :param inputs: A list of one or more inputs to the streaming job. The name property for each input is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual input. :type inputs: list[~azure.mgmt.streamanalytics.models.Input] :param transformation: Indicates the query and the number of streaming units to use for the streaming job. The name property of the transformation is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual transformation. :type transformation: ~azure.mgmt.streamanalytics.models.Transformation :param outputs: A list of one or more outputs for the streaming job. The name property for each output is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual output. :type outputs: list[~azure.mgmt.streamanalytics.models.Output] :param functions: A list of one or more functions for the streaming job. The name property for each function is required when specifying this property in a PUT request. This property cannot be modify via a PATCH operation. You must use the PATCH API available for the individual transformation. :type functions: list[~azure.mgmt.streamanalytics.models.Function] :ivar etag: The current entity tag for the streaming job. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str """ _validation = { 'id': {'readonly': True}, 'name': {'readonly': True}, 'type': {'readonly': True}, 'job_id': {'readonly': True}, 'provisioning_state': {'readonly': True}, 'job_state': {'readonly': True}, 'last_output_event_time': {'readonly': True}, 'created_date': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'location': {'key': 'location', 'type': 'str'}, 'tags': {'key': 'tags', 'type': '{str}'}, 'sku': {'key': 'properties.sku', 'type': 'Sku'}, 'job_id': {'key': 'properties.jobId', 'type': 'str'}, 'provisioning_state': {'key': 'properties.provisioningState', 'type': 'str'}, 'job_state': {'key': 'properties.jobState', 'type': 'str'}, 'output_start_mode': {'key': 'properties.outputStartMode', 'type': 'str'}, 'output_start_time': {'key': 'properties.outputStartTime', 'type': 'iso-8601'}, 'last_output_event_time': {'key': 'properties.lastOutputEventTime', 'type': 'iso-8601'}, 'events_out_of_order_policy': {'key': 'properties.eventsOutOfOrderPolicy', 'type': 'str'}, 'output_error_policy': {'key': 'properties.outputErrorPolicy', 'type': 'str'}, 'events_out_of_order_max_delay_in_seconds': {'key': 'properties.eventsOutOfOrderMaxDelayInSeconds', 'type': 'int'}, 'events_late_arrival_max_delay_in_seconds': {'key': 'properties.eventsLateArrivalMaxDelayInSeconds', 'type': 'int'}, 'data_locale': {'key': 'properties.dataLocale', 'type': 'str'}, 'compatibility_level': {'key': 'properties.compatibilityLevel', 'type': 'str'}, 'created_date': {'key': 'properties.createdDate', 'type': 'iso-8601'}, 'inputs': {'key': 'properties.inputs', 'type': '[Input]'}, 'transformation': {'key': 'properties.transformation', 'type': 'Transformation'}, 'outputs': {'key': 'properties.outputs', 'type': '[Output]'}, 'functions': {'key': 'properties.functions', 'type': '[Function]'}, 'etag': {'key': 'properties.etag', 'type': 'str'}, } def __init__(self, *, location: str=None, tags=None, sku=None, output_start_mode=None, output_start_time=None, events_out_of_order_policy=None, output_error_policy=None, events_out_of_order_max_delay_in_seconds: int=None, events_late_arrival_max_delay_in_seconds: int=None, data_locale: str=None, compatibility_level=None, inputs=None, transformation=None, outputs=None, functions=None, **kwargs) -> None: super(StreamingJob, self).__init__(location=location, tags=tags, **kwargs) self.sku = sku self.job_id = None self.provisioning_state = None self.job_state = None self.output_start_mode = output_start_mode self.output_start_time = output_start_time self.last_output_event_time = None self.events_out_of_order_policy = events_out_of_order_policy self.output_error_policy = output_error_policy self.events_out_of_order_max_delay_in_seconds = events_out_of_order_max_delay_in_seconds self.events_late_arrival_max_delay_in_seconds = events_late_arrival_max_delay_in_seconds self.data_locale = data_locale self.compatibility_level = compatibility_level self.created_date = None self.inputs = inputs self.transformation = transformation self.outputs = outputs self.functions = functions self.etag = None class StreamInputProperties(InputProperties): """The properties that are associated with an input containing stream data. Variables are only populated by the server, and will be ignored when sending a request. All required parameters must be populated in order to send to Azure. :param serialization: Describes how data from an input is serialized or how data is serialized when written to an output. Required on PUT (CreateOrReplace) requests. :type serialization: ~azure.mgmt.streamanalytics.models.Serialization :ivar diagnostics: Describes conditions applicable to the Input, Output, or the job overall, that warrant customer attention. :vartype diagnostics: ~azure.mgmt.streamanalytics.models.Diagnostics :ivar etag: The current entity tag for the input. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str :param type: Required. Constant filled by server. :type type: str :param datasource: Describes an input data source that contains stream data. Required on PUT (CreateOrReplace) requests. :type datasource: ~azure.mgmt.streamanalytics.models.StreamInputDataSource """ _validation = { 'diagnostics': {'readonly': True}, 'etag': {'readonly': True}, 'type': {'required': True}, } _attribute_map = { 'serialization': {'key': 'serialization', 'type': 'Serialization'}, 'diagnostics': {'key': 'diagnostics', 'type': 'Diagnostics'}, 'etag': {'key': 'etag', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'datasource': {'key': 'datasource', 'type': 'StreamInputDataSource'}, } def __init__(self, *, serialization=None, datasource=None, **kwargs) -> None: super(StreamInputProperties, self).__init__(serialization=serialization, **kwargs) self.datasource = datasource self.type = 'Stream' class SubscriptionQuota(SubResource): """Describes the current quota for the subscription. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :param name: Resource name :type name: str :ivar type: Resource type :vartype type: str :ivar max_count: The max permitted usage of this resource. :vartype max_count: int :ivar current_count: The current usage of this resource. :vartype current_count: int """ _validation = { 'id': {'readonly': True}, 'type': {'readonly': True}, 'max_count': {'readonly': True}, 'current_count': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'max_count': {'key': 'properties.maxCount', 'type': 'int'}, 'current_count': {'key': 'properties.currentCount', 'type': 'int'}, } def __init__(self, *, name: str=None, **kwargs) -> None: super(SubscriptionQuota, self).__init__(name=name, **kwargs) self.max_count = None self.current_count = None class SubscriptionQuotasListResult(Model): """Result of the GetQuotas operation. It contains a list of quotas for the subscription in a particular region. Variables are only populated by the server, and will be ignored when sending a request. :ivar value: List of quotas for the subscription in a particular region. :vartype value: list[~azure.mgmt.streamanalytics.models.SubscriptionQuota] """ _validation = { 'value': {'readonly': True}, } _attribute_map = { 'value': {'key': 'value', 'type': '[SubscriptionQuota]'}, } def __init__(self, **kwargs) -> None: super(SubscriptionQuotasListResult, self).__init__(**kwargs) self.value = None class Transformation(SubResource): """A transformation object, containing all information associated with the named transformation. All transformations are contained under a streaming job. Variables are only populated by the server, and will be ignored when sending a request. :ivar id: Resource Id :vartype id: str :param name: Resource name :type name: str :ivar type: Resource type :vartype type: str :param streaming_units: Specifies the number of streaming units that the streaming job uses. :type streaming_units: int :param query: Specifies the query that will be run in the streaming job. You can learn more about the Stream Analytics Query Language (SAQL) here: https://msdn.microsoft.com/library/azure/dn834998 . Required on PUT (CreateOrReplace) requests. :type query: str :ivar etag: The current entity tag for the transformation. This is an opaque string. You can use it to detect whether the resource has changed between requests. You can also use it in the If-Match or If-None-Match headers for write operations for optimistic concurrency. :vartype etag: str """ _validation = { 'id': {'readonly': True}, 'type': {'readonly': True}, 'etag': {'readonly': True}, } _attribute_map = { 'id': {'key': 'id', 'type': 'str'}, 'name': {'key': 'name', 'type': 'str'}, 'type': {'key': 'type', 'type': 'str'}, 'streaming_units': {'key': 'properties.streamingUnits', 'type': 'int'}, 'query': {'key': 'properties.query', 'type': 'str'}, 'etag': {'key': 'properties.etag', 'type': 'str'}, } def __init__(self, *, name: str=None, streaming_units: int=None, query: str=None, **kwargs) -> None: super(Transformation, self).__init__(name=name, **kwargs) self.streaming_units = streaming_units self.query = query self.etag = None
# Generated by Django 3.2.4 on 2021-06-18 03:55 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Tokens', fields=[ ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('token', models.CharField(max_length=250)), ], options={ 'verbose_name': 'token', }, ), ]
from feature_selector.models.taskonomydecoder import TaskonomyDecoder from feature_selector.utils import SINGLE_IMAGE_TASKS, TASKS_TO_CHANNELS, FEED_FORWARD_TASKS import torch import torch.nn.functional as F def heteroscedastic_normal(mean_and_scales, target, weight=None, eps=1e-2): mu, scales = mean_and_scales loss = (mu - target)**2 / (scales**2 + eps) + torch.log(scales**2 + eps) # return torch.sum(weight * loss) / torch.sum(weight) if weight is not None else loss.mean() return torch.mean(weight * loss) / weight.mean() if weight is not None else loss.mean() def heteroscedastic_double_exponential(mean_and_scales, target, weight=None, eps=5e-2): mu, scales = mean_and_scales loss = torch.abs(mu - target) / (scales + eps) + torch.log(2.0 * (scales + eps)) return torch.mean(weight * loss) / weight.mean() if weight is not None else loss.mean() def weighted_mse_loss(inputs, target, weight=None): if weight is not None: # sq = (inputs - target) ** 2 # weightsq = torch.sum(weight * sq) return torch.mean(weight * (inputs - target) ** 2)/torch.mean(weight) else: return F.mse_loss(inputs, target) def weighted_l1_loss(inputs, target, weight=None): if weight is not None: return torch.mean(weight * torch.abs(inputs - target))/torch.mean(weight) return F.l1_loss(inputs, target) def perceptual_l1_loss(decoder_path, bake_decodings): task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0] decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS) checkpoint = torch.load(decoder_path) decoder.load_state_dict(checkpoint['state_dict']) decoder.cuda() decoder.eval() print(f'Loaded decoder from {decoder_path} for perceptual loss') def runner(inputs, target, weight=None, cache={}): # the last arguments are so we can 'cache' and pass the decodings outside inputs_decoded = decoder(inputs) targets_decoded = target if bake_decodings else decoder(target) cache['inputs_decoded'] = inputs_decoded cache['targets_decoded'] = targets_decoded if weight is not None: return torch.mean(weight * torch.abs(inputs_decoded - targets_decoded))/torch.mean(weight) return F.l1_loss(inputs_decoded, targets_decoded) return runner def perceptual_cross_entropy_loss(decoder_path, bake_decodings): task = [t for t in SINGLE_IMAGE_TASKS if t in decoder_path][0] decoder = TaskonomyDecoder(TASKS_TO_CHANNELS[task], feed_forward=task in FEED_FORWARD_TASKS) checkpoint = torch.load(decoder_path) decoder.load_state_dict(checkpoint['state_dict']) decoder.cuda() decoder.eval() print(f'Loaded decoder from {decoder_path} for perceptual loss') def runner(inputs, target, weight=None, cache={}): # the last arguments are so we can 'cache' and pass the decodings outside inputs_decoded = decoder(inputs) targets_decoded = target if bake_decodings else decoder(target) cache['inputs_decoded'] = inputs_decoded cache['targets_decoded'] = targets_decoded batch_size, _ = targets_decoded.shape return -1. * torch.sum(torch.softmax(targets_decoded, dim=1) * F.log_softmax(inputs_decoded, dim=1)) / batch_size return runner
import pandas as pd from psycopg2 import pool import math import numpy as np import os import time start_time = time.time() # use connection pool for single threaded apps. replace credentials with Timescale user pool settings postgres_pool = pool.SimpleConnectionPool(1, 5, user='root', password='password', host="localhost", port="5432", database="defaultdb") with postgres_pool.getconn() as conn: conn.set_session(autocommit=True) # need this line to avoid idle_in_transaction in Postgres cursor = conn.cursor() # get all devices from shadow that are active in the last month. We can remove this filter if needed. sql_regular = """ INSERT INTO status.device_shadow SELECT NOW() as timestamp_utc, CONCAT('device',n) as device_id, CONCAT('beacon',n) as beacon_rcpn, CONCAT('host_rcpn',n) as host_rcpn, 'INVERTER' as device_type, 10 as st FROM generate_series(1,100000,1) as n ON CONFLICT (device_id,host_rcpn) DO UPDATE SET timestamp_utc = now()+INTERVAL '10 minutes'; """ sql_hyper = """ BEGIN; DELETE FROM status.device_shadow_hyper; INSERT INTO status.device_shadow_hyper SELECT NOW() + INTERVAL '10 minute' as timestamp_utc, CONCAT('device',n) as device_id, CONCAT('beacon',n) as beacon_rcpn, CONCAT('host_rcpn',n) as host_rcpn, 'INVERTER' as device_type, 10 as st FROM generate_series(1,100000,1) as n; COMMIT; """ while(1==1): cursor.execute(sql_hyper) conn.commit() # <- We MUST commit to reflect the inserted data time.sleep(1) #select * from status.device_shadow where device_id='device1'
from controllers.course.deliverables import deliverable_controller from controllers.relations.student_group_relation import StudentGroupRelationController from flask_restful import Resource, reqparse import werkzeug from flask import jsonify from methods.errors import * from methods.auth import * controller_object = deliverable_controller() group_controller = StudentGroupRelationController() # /deliverables/<deliverable_id> class Deliverable_view(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('deliverable_name', type=str, location='json') self.reqparse.add_argument('deadline', type=str, location='json') #date time not str self.reqparse.add_argument('course_deliverables', type=str, location='json') self.reqparse.add_argument('students_number', type=int, location='json') self.reqparse.add_argument('students_number', type=int, location='json') self.reqparse.add_argument('description', type=str, location='json') self.reqparse.add_argument('mark', type=int, location='json') def get(self, deliverable_id): try: deliverable = controller_object.get_deliverable(deliverable_id) except ErrorHandler as e: return e.error return deliverable def put(self, deliverable_id): args = self.reqparse.parse_args() deliverable = { "deliverable_id": deliverable_id, "deliverable_name": args["deliverable_name"], "deadline": args["deadline"], "course_deliverables": args["course_deliverables"], "students_number": args["students_number"], "description": args["description"], "mark": args["mark"] } try: controller_object.update_deliverable(deliverable_id, deliverable) except ErrorHandler as e: return e.error return jsonify({ 'message': 'deliverable updated successfully', 'status_code': 200 }) def delete(self, deliverable_id): try: controller_object.delete_deliverable(deliverable_id) except ErrorHandler as e: return e.error return jsonify({ 'message': 'deliverable deleted successfully', 'status_code': 200 }) # /deliverables class All_Deliverables(Resource): method_decorators = {'get': [requires_auth_identity("")]} def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('deliverable_name', type=str, location='json') self.reqparse.add_argument('deadline', type=str, location='json') self.reqparse.add_argument('course_deliverables', type=str, location='json') self.reqparse.add_argument('students_number', type=int, location='json') self.reqparse.add_argument('description', type=str, location='json') self.reqparse.add_argument('mark', type=int, location='json') def get(self, user_id, role): try: if role == 'student': specific_deliverables = controller_object.get_one_student_all_deliverables(user_id) else: specific_deliverables = controller_object.get_one_professor_all_deliverables(user_id) except ErrorHandler as e: return e.error return specific_deliverables def post(self): args = self.reqparse.parse_args() deliverable = { "deliverable_name": args["deliverable_name"], "deadline": args["deadline"], "course_deliverables": args["course_deliverables"], "students_number": args["students_number"], "description": args['description'], "mark": args["mark"] } try: deliverable_id = controller_object.post_deliverable(deliverable) controller_object.create_groups_for_deliverable(deliverable_id,args["course_deliverables"]) controller_object.create_deliverable_event(args["course_deliverables"],deliverable) except ErrorHandler as e: return e.error return jsonify({ 'message': 'deliverable added successfully', 'status_code': 200 }) # /students_deliverables/<deliverable_id> class Students_Deliverables(Resource): def get(self, deliverable_id): try: student_deliverables = controller_object.get_all_deliverables_by_deliverable_id(deliverable_id) except ErrorHandler as e: return e.error return student_deliverables #/course/<course_code>deliverables class Course_Deliverables(Resource): method_decorators = {'get': [requires_auth_identity("")]} def get(self,user_id, role,course_code): try: course_deliverables = controller_object.get_all_course_deliverables(course_code,user_id,role) except ErrorHandler as e: return e.error return jsonify({ 'status_code':200, 'deliverables':course_deliverables }) #/deliverable_groups/<deliv> class getGroups(Resource): def __init__(self): self.reqparse = reqparse.RequestParser() self.reqparse.add_argument('user_id', type=int, location='json') self.reqparse.add_argument('group_id', type=int, location='json') def get(self, deliv): try: groups = controller_object.get_groups(deliv) except ErrorHandler as e: return e.error return jsonify({ 'status_code':200, 'groups':groups }) def post(self, deliv): args = self.reqparse.parse_args() try: group_controller.enroll_in_group(args['user_id'], args['group_id']) except ErrorHandler as e: return e.error return jsonify({ 'status_code':200, 'message':"Success" })
from pathlib import Path import torch import torchvision from torchvision import models, transforms, utils import argparse from utils import * import numpy as np from tqdm import tqdm # + # import functions and classes from qatm_pytorch.py print("import qatm_pytorch.py...") import ast import types import sys from qatm_pytorch import * # with open("qatm_pytorch.py") as f: # p = ast.parse(f.read()) # # for node in p.body[:]: # if not isinstance(node, (ast.FunctionDef, ast.ClassDef, ast.Import, ast.ImportFrom)): # p.body.remove(node) # # module = types.ModuleType("mod") # code = compile(p, "mod.py", 'exec') # sys.modules["mod"] = module # exec(code, module.__dict__) # # from mod import * # - if __name__ == '__main__': parser = argparse.ArgumentParser(description='QATM Pytorch Implementation') parser.add_argument('--cuda', action='store_true') parser.add_argument('-s', '--sample_image', default=r'E:\AIschool\data_full\data2\data\data\OK_Orgin_Images\OK_Orgin_Images\part3\Image_11.bmp') parser.add_argument('-t', '--template_images_dir', default=r'E:\AIschool\data_full\data2\data\data\TC_Images\TC_Images\part3\TC_Images') # parser.add_argument('-t', '--template_images_dir', default=r'E:\AIschool\QATM_pytorch_bak\t') parser.add_argument('--alpha', type=float, default=25) parser.add_argument('--thresh_csv', type=str, default='thresh_template.csv') args = parser.parse_args() template_dir = args.template_images_dir image_path = args.sample_image dataset = ImageDataset(Path(template_dir), image_path, resize_scale=1/4, thresh_csv='thresh_template.csv') save_path = r'E:\AIschool\QATM_pytorch_bak\save_path\part2\show' print("define model...") model = CreateModel(model=models.vgg19(pretrained=True).features, alpha=args.alpha, use_cuda=args.cuda) print("calculate score...") # scores, w_array, h_array, thresh_list = run_multi_sample(model, dataset) # print("nms...") # template_list = list(Path(template_dir).iterdir()) # for idx in range(len(scores)): # template_path = str(template_list[idx]) # score = np.array([scores[idx]]) # w = np.array([w_array[idx]]) # h = np.array([h_array[idx]]) # thresh = np.array([thresh_list[idx]]) # boxes, indices = nms_multi(score, w, h, thresh) # compare_show(boxes[0], template_path, image_path, 1/4, save_path) for data in tqdm(dataset): template_path = data['template_name'] score = run_one_sample(model, data['template'], data['image'], data['image_name']) w = np.array([data['template_w']]) h = np.array([data['template_h']]) thresh = np.array([data['thresh']]) boxes, indices = nms_multi(score, w, h, thresh) compare_show(boxes[0], template_path, image_path, 1/4, save_path) _ = plot_result_multi(dataset.image_raw, boxes, indices, show=False, save_name='result.png') print("result.png was saved")
num_lines = int(input()) for _ in range(num_lines): text = input() name = text[text.index("@") + 1:text.index("|")] age = text[text.index("#") + 1:text.index("*")] print(f"{name} is {age} years old.")
# -*- coding:UTF-8 -*- """ 计算圆周率可以根据公式: 利用Python提供的itertools模块,我们来计算这个序列的前N项和: """ import itertools def pi(N): '计算pi的值' # step 1: 创建一个奇数序列: 1, 3, 5, 7, 9 ... count(start, step) # step 2: 取该序列的前N项: 1, 3, 5, 7, 9, ..., 2*N-1. # step 3: 添加正负号并用4除: 4/1, -4/3, 4/5, -4/7, 4/9, ... cycle(list) # step 4: 求和 next()/next() 求和 odd = itertools.count(1, 2) cs = itertools.cycle([4, -4]) sum = 0 for i in range(N): sum = sum + (next(cs)/next(odd)) return sum print(pi(10)) print(pi(100)) print(pi(1000)) print(pi(10000))
import pygame from constants import * from icon import * from panel import * __all__ = ['Lineicon', 'Coalicon', 'Sellicon', 'Windfarmicon', 'Loadicon', 'Syncicon', 'Swingicon', 'Renameicon'] class Baseicon(): def __init__(self, panel, obj, num_pics, left_click, type): build = Buildicon(obj, num_pics, left_click, type) mypanel = self.makepanel() mypanel.add_icon((5,50), build) panel.add_dynamic_panel((2,218), mypanel, self.name) def makepanel(self): mypanel = Panel([], pos = (0,0), size = (PANEL_SIZE[0] - 4, 180)) mypanel.make_heading((5,10), self.name) return mypanel class Windfarmicon(Icon, Baseicon): def __init__(self, panel, mesh): default_init(self, 'windfarm.png', (1,1), \ 'blip.wav', 'Windfarm', panel, mesh.build_tile) class Coalicon(Icon, Baseicon): def __init__(self, panel, mesh): default_init(self, 'coal.png', (1,1), 'blip.wav', 'Coal', panel, \ mesh.build_tile) class Lineicon(Icon, Baseicon): def __init__(self, panel, mesh): default_init(self, 'line.png', (1,1), 'blip.wav', 'Line', panel, mesh.build_tile) class Loadicon(Icon, Baseicon): def __init__(self, panel, mesh): default_init(self, 'load.png', (1,1), 'blip.wav', 'Load', panel, mesh.build_tile) class Syncicon(Icon, Baseicon): def __init__(self, panel, mesh): default_init(self, 'syncon.png', (1,1), 'blip.wav', 'Sync', panel, mesh.build_tile) class Buildicon(Icon): def __init__(self, object, num_pics, left_click, type): Icon.__init__(self, (0,0), [], object, padding=(5,5), sound=None, num_pics = num_pics) self.set_leftaction(left_click, type) class Sellicon(Buildicon): def __init__(self, panel, mesh, host): Buildicon.__init__(self, 'sell.png', (1,1), mesh.sell_tile, host) class Swingicon(Buildicon): def __init__(self, callback, name): Buildicon.__init__(self, 'make swing', (1,1), callback, name) class Renameicon(Buildicon): def __init__(self, callback, name): Buildicon.__init__(self, 'rename', (1,1), callback, name) def default_init(self, image, num_pics, sound, arg, panel, callback): Icon.__init__(self, (0,0), [], obj = image,\ sound = sound, num_pics = num_pics) self.set_leftaction(panel.show_panel, arg) Baseicon.__init__(self, panel, image, num_pics, callback, arg)
import sys sys.path.append("/usr/local/web/d.suishoubei.com") from app import app as application
# -*- coding: utf-8 -*- import copy import datetime import dateutil import arrow from unittest.mock import patch, call from gitlint.tests.base import BaseTestCase from gitlint.git import GitContext, GitCommit, GitContextError, LocalGitCommit, StagedLocalGitCommit, GitCommitMessage from gitlint.shell import ErrorReturnCode class GitCommitTests(BaseTestCase): # Expected special_args passed to 'sh' expected_sh_special_args = { '_tty_out': False, '_cwd': "fåke/path" } @patch('gitlint.git.sh') def test_get_latest_commit(self, sh): sample_sha = "d8ac47e9f2923c7f22d8668e3a1ed04eb4cdbca9" sh.git.side_effect = [ sample_sha, "test åuthor\x00test-emåil@foo.com\x002016-12-03 15:28:15 +0100\x00åbc\n" "cömmit-title\n\ncömmit-body", "#", # git config --get core.commentchar "file1.txt\npåth/to/file2.txt\n", "foöbar\n* hürdur\n" ] context = GitContext.from_local_repository("fåke/path") # assert that commit info was read using git command expected_calls = [ call("log", "-1", "--pretty=%H", **self.expected_sh_special_args), call("log", sample_sha, "-1", "--pretty=%aN%x00%aE%x00%ai%x00%P%n%B", **self.expected_sh_special_args), call('config', '--get', 'core.commentchar', _ok_code=[0, 1], **self.expected_sh_special_args), call('diff-tree', '--no-commit-id', '--name-only', '-r', '--root', sample_sha, **self.expected_sh_special_args), call('branch', '--contains', sample_sha, **self.expected_sh_special_args) ] # Only first 'git log' call should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:1]) last_commit = context.commits[-1] self.assertIsInstance(last_commit, LocalGitCommit) self.assertEqual(last_commit.sha, sample_sha) self.assertEqual(last_commit.message.title, "cömmit-title") self.assertEqual(last_commit.message.body, ["", "cömmit-body"]) self.assertEqual(last_commit.author_name, "test åuthor") self.assertEqual(last_commit.author_email, "test-emåil@foo.com") self.assertEqual(last_commit.date, datetime.datetime(2016, 12, 3, 15, 28, 15, tzinfo=dateutil.tz.tzoffset("+0100", 3600))) self.assertListEqual(last_commit.parents, ["åbc"]) self.assertFalse(last_commit.is_merge_commit) self.assertFalse(last_commit.is_fixup_commit) self.assertFalse(last_commit.is_squash_commit) self.assertFalse(last_commit.is_revert_commit) # First 2 'git log' calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:3]) self.assertListEqual(last_commit.changed_files, ["file1.txt", "påth/to/file2.txt"]) # 'git diff-tree' should have happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:4]) self.assertListEqual(last_commit.branches, ["foöbar", "hürdur"]) # All expected calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls) @patch('gitlint.git.sh') def test_from_local_repository_specific_refspec(self, sh): sample_refspec = "åbc123..def456" sample_sha = "åbc123" sh.git.side_effect = [ sample_sha, # git rev-list <sample_refspec> "test åuthor\x00test-emåil@foo.com\x002016-12-03 15:28:15 +0100\x00åbc\n" "cömmit-title\n\ncömmit-body", "#", # git config --get core.commentchar "file1.txt\npåth/to/file2.txt\n", "foöbar\n* hürdur\n" ] context = GitContext.from_local_repository("fåke/path", refspec=sample_refspec) # assert that commit info was read using git command expected_calls = [ call("rev-list", sample_refspec, **self.expected_sh_special_args), call("log", sample_sha, "-1", "--pretty=%aN%x00%aE%x00%ai%x00%P%n%B", **self.expected_sh_special_args), call('config', '--get', 'core.commentchar', _ok_code=[0, 1], **self.expected_sh_special_args), call('diff-tree', '--no-commit-id', '--name-only', '-r', '--root', sample_sha, **self.expected_sh_special_args), call('branch', '--contains', sample_sha, **self.expected_sh_special_args) ] # Only first 'git log' call should've happened at this point self.assertEqual(sh.git.mock_calls, expected_calls[:1]) last_commit = context.commits[-1] self.assertIsInstance(last_commit, LocalGitCommit) self.assertEqual(last_commit.sha, sample_sha) self.assertEqual(last_commit.message.title, "cömmit-title") self.assertEqual(last_commit.message.body, ["", "cömmit-body"]) self.assertEqual(last_commit.author_name, "test åuthor") self.assertEqual(last_commit.author_email, "test-emåil@foo.com") self.assertEqual(last_commit.date, datetime.datetime(2016, 12, 3, 15, 28, 15, tzinfo=dateutil.tz.tzoffset("+0100", 3600))) self.assertListEqual(last_commit.parents, ["åbc"]) self.assertFalse(last_commit.is_merge_commit) self.assertFalse(last_commit.is_fixup_commit) self.assertFalse(last_commit.is_squash_commit) self.assertFalse(last_commit.is_revert_commit) # First 2 'git log' calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:3]) self.assertListEqual(last_commit.changed_files, ["file1.txt", "påth/to/file2.txt"]) # 'git diff-tree' should have happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:4]) self.assertListEqual(last_commit.branches, ["foöbar", "hürdur"]) # All expected calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls) @patch('gitlint.git.sh') def test_from_local_repository_specific_commit_hash(self, sh): sample_hash = "åbc123" sh.git.side_effect = [ sample_hash, # git log -1 <sample_hash> "test åuthor\x00test-emåil@foo.com\x002016-12-03 15:28:15 +0100\x00åbc\n" "cömmit-title\n\ncömmit-body", "#", # git config --get core.commentchar "file1.txt\npåth/to/file2.txt\n", "foöbar\n* hürdur\n" ] context = GitContext.from_local_repository("fåke/path", commit_hash=sample_hash) # assert that commit info was read using git command expected_calls = [ call("log", "-1", sample_hash, "--pretty=%H", **self.expected_sh_special_args), call("log", sample_hash, "-1", "--pretty=%aN%x00%aE%x00%ai%x00%P%n%B", **self.expected_sh_special_args), call('config', '--get', 'core.commentchar', _ok_code=[0, 1], **self.expected_sh_special_args), call('diff-tree', '--no-commit-id', '--name-only', '-r', '--root', sample_hash, **self.expected_sh_special_args), call('branch', '--contains', sample_hash, **self.expected_sh_special_args) ] # Only first 'git log' call should've happened at this point self.assertEqual(sh.git.mock_calls, expected_calls[:1]) last_commit = context.commits[-1] self.assertIsInstance(last_commit, LocalGitCommit) self.assertEqual(last_commit.sha, sample_hash) self.assertEqual(last_commit.message.title, "cömmit-title") self.assertEqual(last_commit.message.body, ["", "cömmit-body"]) self.assertEqual(last_commit.author_name, "test åuthor") self.assertEqual(last_commit.author_email, "test-emåil@foo.com") self.assertEqual(last_commit.date, datetime.datetime(2016, 12, 3, 15, 28, 15, tzinfo=dateutil.tz.tzoffset("+0100", 3600))) self.assertListEqual(last_commit.parents, ["åbc"]) self.assertFalse(last_commit.is_merge_commit) self.assertFalse(last_commit.is_fixup_commit) self.assertFalse(last_commit.is_squash_commit) self.assertFalse(last_commit.is_revert_commit) # First 2 'git log' calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:3]) self.assertListEqual(last_commit.changed_files, ["file1.txt", "påth/to/file2.txt"]) # 'git diff-tree' should have happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:4]) self.assertListEqual(last_commit.branches, ["foöbar", "hürdur"]) # All expected calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls) @patch('gitlint.git.sh') def test_get_latest_commit_merge_commit(self, sh): sample_sha = "d8ac47e9f2923c7f22d8668e3a1ed04eb4cdbca9" sh.git.side_effect = [ sample_sha, "test åuthor\x00test-emåil@foo.com\x002016-12-03 15:28:15 +0100\x00åbc def\n" "Merge \"foo bår commit\"", "#", # git config --get core.commentchar "file1.txt\npåth/to/file2.txt\n", "foöbar\n* hürdur\n" ] context = GitContext.from_local_repository("fåke/path") # assert that commit info was read using git command expected_calls = [ call("log", "-1", "--pretty=%H", **self.expected_sh_special_args), call("log", sample_sha, "-1", "--pretty=%aN%x00%aE%x00%ai%x00%P%n%B", **self.expected_sh_special_args), call('config', '--get', 'core.commentchar', _ok_code=[0, 1], **self.expected_sh_special_args), call('diff-tree', '--no-commit-id', '--name-only', '-r', '--root', sample_sha, **self.expected_sh_special_args), call('branch', '--contains', sample_sha, **self.expected_sh_special_args) ] # Only first 'git log' call should've happened at this point self.assertEqual(sh.git.mock_calls, expected_calls[:1]) last_commit = context.commits[-1] self.assertIsInstance(last_commit, LocalGitCommit) self.assertEqual(last_commit.sha, sample_sha) self.assertEqual(last_commit.message.title, "Merge \"foo bår commit\"") self.assertEqual(last_commit.message.body, []) self.assertEqual(last_commit.author_name, "test åuthor") self.assertEqual(last_commit.author_email, "test-emåil@foo.com") self.assertEqual(last_commit.date, datetime.datetime(2016, 12, 3, 15, 28, 15, tzinfo=dateutil.tz.tzoffset("+0100", 3600))) self.assertListEqual(last_commit.parents, ["åbc", "def"]) self.assertTrue(last_commit.is_merge_commit) self.assertFalse(last_commit.is_fixup_commit) self.assertFalse(last_commit.is_squash_commit) self.assertFalse(last_commit.is_revert_commit) # First 2 'git log' calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:3]) self.assertListEqual(last_commit.changed_files, ["file1.txt", "påth/to/file2.txt"]) # 'git diff-tree' should have happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:4]) self.assertListEqual(last_commit.branches, ["foöbar", "hürdur"]) # All expected calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls) @patch('gitlint.git.sh') def test_get_latest_commit_fixup_squash_commit(self, sh): commit_types = ["fixup", "squash"] for commit_type in commit_types: sample_sha = "d8ac47e9f2923c7f22d8668e3a1ed04eb4cdbca9" sh.git.side_effect = [ sample_sha, "test åuthor\x00test-emåil@foo.com\x002016-12-03 15:28:15 +0100\x00åbc\n" f"{commit_type}! \"foo bår commit\"", "#", # git config --get core.commentchar "file1.txt\npåth/to/file2.txt\n", "foöbar\n* hürdur\n" ] context = GitContext.from_local_repository("fåke/path") # assert that commit info was read using git command expected_calls = [ call("log", "-1", "--pretty=%H", **self.expected_sh_special_args), call("log", sample_sha, "-1", "--pretty=%aN%x00%aE%x00%ai%x00%P%n%B", **self.expected_sh_special_args), call('config', '--get', 'core.commentchar', _ok_code=[0, 1], **self.expected_sh_special_args), call('diff-tree', '--no-commit-id', '--name-only', '-r', '--root', sample_sha, **self.expected_sh_special_args), call('branch', '--contains', sample_sha, **self.expected_sh_special_args) ] # Only first 'git log' call should've happened at this point self.assertEqual(sh.git.mock_calls, expected_calls[:-4]) last_commit = context.commits[-1] self.assertIsInstance(last_commit, LocalGitCommit) self.assertEqual(last_commit.sha, sample_sha) self.assertEqual(last_commit.message.title, f"{commit_type}! \"foo bår commit\"") self.assertEqual(last_commit.message.body, []) self.assertEqual(last_commit.author_name, "test åuthor") self.assertEqual(last_commit.author_email, "test-emåil@foo.com") self.assertEqual(last_commit.date, datetime.datetime(2016, 12, 3, 15, 28, 15, tzinfo=dateutil.tz.tzoffset("+0100", 3600))) self.assertListEqual(last_commit.parents, ["åbc"]) # First 2 'git log' calls should've happened at this point self.assertEqual(sh.git.mock_calls, expected_calls[:3]) # Asserting that squash and fixup are correct for type in commit_types: attr = "is_" + type + "_commit" self.assertEqual(getattr(last_commit, attr), commit_type == type) self.assertFalse(last_commit.is_merge_commit) self.assertFalse(last_commit.is_revert_commit) self.assertListEqual(last_commit.changed_files, ["file1.txt", "påth/to/file2.txt"]) self.assertListEqual(last_commit.changed_files, ["file1.txt", "påth/to/file2.txt"]) # 'git diff-tree' should have happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls[:4]) self.assertListEqual(last_commit.branches, ["foöbar", "hürdur"]) # All expected calls should've happened at this point self.assertListEqual(sh.git.mock_calls, expected_calls) sh.git.reset_mock() @patch("gitlint.git.git_commentchar") def test_from_commit_msg_full(self, commentchar): commentchar.return_value = "#" gitcontext = GitContext.from_commit_msg(self.get_sample("commit_message/sample1")) expected_title = "Commit title contåining 'WIP', as well as trailing punctuation." expected_body = ["This line should be empty", "This is the first line of the commit message body and it is meant to test a " + "line that exceeds the maximum line length of 80 characters.", "This line has a tråiling space. ", "This line has a trailing tab.\t"] expected_full = expected_title + "\n" + "\n".join(expected_body) expected_original = expected_full + ( "\n# This is a cömmented line\n" "# ------------------------ >8 ------------------------\n" "# Anything after this line should be cleaned up\n" "# this line appears on `git commit -v` command\n" "diff --git a/gitlint/tests/samples/commit_message/sample1 " "b/gitlint/tests/samples/commit_message/sample1\n" "index 82dbe7f..ae71a14 100644\n" "--- a/gitlint/tests/samples/commit_message/sample1\n" "+++ b/gitlint/tests/samples/commit_message/sample1\n" "@@ -1 +1 @@\n" ) commit = gitcontext.commits[-1] self.assertIsInstance(commit, GitCommit) self.assertFalse(isinstance(commit, LocalGitCommit)) self.assertEqual(commit.message.title, expected_title) self.assertEqual(commit.message.body, expected_body) self.assertEqual(commit.message.full, expected_full) self.assertEqual(commit.message.original, expected_original) self.assertEqual(commit.author_name, None) self.assertEqual(commit.author_email, None) self.assertEqual(commit.date, None) self.assertListEqual(commit.parents, []) self.assertListEqual(commit.branches, []) self.assertFalse(commit.is_merge_commit) self.assertFalse(commit.is_fixup_commit) self.assertFalse(commit.is_squash_commit) self.assertFalse(commit.is_revert_commit) self.assertEqual(len(gitcontext.commits), 1) def test_from_commit_msg_just_title(self): gitcontext = GitContext.from_commit_msg(self.get_sample("commit_message/sample2")) commit = gitcontext.commits[-1] self.assertIsInstance(commit, GitCommit) self.assertFalse(isinstance(commit, LocalGitCommit)) self.assertEqual(commit.message.title, "Just a title contåining WIP") self.assertEqual(commit.message.body, []) self.assertEqual(commit.message.full, "Just a title contåining WIP") self.assertEqual(commit.message.original, "Just a title contåining WIP") self.assertEqual(commit.author_name, None) self.assertEqual(commit.author_email, None) self.assertListEqual(commit.parents, []) self.assertListEqual(commit.branches, []) self.assertFalse(commit.is_merge_commit) self.assertFalse(commit.is_fixup_commit) self.assertFalse(commit.is_squash_commit) self.assertFalse(commit.is_revert_commit) self.assertEqual(len(gitcontext.commits), 1) def test_from_commit_msg_empty(self): gitcontext = GitContext.from_commit_msg("") commit = gitcontext.commits[-1] self.assertIsInstance(commit, GitCommit) self.assertFalse(isinstance(commit, LocalGitCommit)) self.assertEqual(commit.message.title, "") self.assertEqual(commit.message.body, []) self.assertEqual(commit.message.full, "") self.assertEqual(commit.message.original, "") self.assertEqual(commit.author_name, None) self.assertEqual(commit.author_email, None) self.assertEqual(commit.date, None) self.assertListEqual(commit.parents, []) self.assertListEqual(commit.branches, []) self.assertFalse(commit.is_merge_commit) self.assertFalse(commit.is_fixup_commit) self.assertFalse(commit.is_squash_commit) self.assertFalse(commit.is_revert_commit) self.assertEqual(len(gitcontext.commits), 1) @patch("gitlint.git.git_commentchar") def test_from_commit_msg_comment(self, commentchar): commentchar.return_value = "#" gitcontext = GitContext.from_commit_msg("Tïtle\n\nBödy 1\n#Cömment\nBody 2") commit = gitcontext.commits[-1] self.assertIsInstance(commit, GitCommit) self.assertFalse(isinstance(commit, LocalGitCommit)) self.assertEqual(commit.message.title, "Tïtle") self.assertEqual(commit.message.body, ["", "Bödy 1", "Body 2"]) self.assertEqual(commit.message.full, "Tïtle\n\nBödy 1\nBody 2") self.assertEqual(commit.message.original, "Tïtle\n\nBödy 1\n#Cömment\nBody 2") self.assertEqual(commit.author_name, None) self.assertEqual(commit.author_email, None) self.assertEqual(commit.date, None) self.assertListEqual(commit.parents, []) self.assertListEqual(commit.branches, []) self.assertFalse(commit.is_merge_commit) self.assertFalse(commit.is_fixup_commit) self.assertFalse(commit.is_squash_commit) self.assertFalse(commit.is_revert_commit) self.assertEqual(len(gitcontext.commits), 1) def test_from_commit_msg_merge_commit(self): commit_msg = "Merge f919b8f34898d9b48048bcd703bc47139f4ff621 into 8b0409a26da6ba8a47c1fd2e746872a8dab15401" gitcontext = GitContext.from_commit_msg(commit_msg) commit = gitcontext.commits[-1] self.assertIsInstance(commit, GitCommit) self.assertFalse(isinstance(commit, LocalGitCommit)) self.assertEqual(commit.message.title, commit_msg) self.assertEqual(commit.message.body, []) self.assertEqual(commit.message.full, commit_msg) self.assertEqual(commit.message.original, commit_msg) self.assertEqual(commit.author_name, None) self.assertEqual(commit.author_email, None) self.assertEqual(commit.date, None) self.assertListEqual(commit.parents, []) self.assertListEqual(commit.branches, []) self.assertTrue(commit.is_merge_commit) self.assertFalse(commit.is_fixup_commit) self.assertFalse(commit.is_squash_commit) self.assertFalse(commit.is_revert_commit) self.assertEqual(len(gitcontext.commits), 1) def test_from_commit_msg_revert_commit(self): commit_msg = "Revert \"Prev commit message\"\n\nThis reverts commit a8ad67e04164a537198dea94a4fde81c5592ae9c." gitcontext = GitContext.from_commit_msg(commit_msg) commit = gitcontext.commits[-1] self.assertIsInstance(commit, GitCommit) self.assertFalse(isinstance(commit, LocalGitCommit)) self.assertEqual(commit.message.title, "Revert \"Prev commit message\"") self.assertEqual(commit.message.body, ["", "This reverts commit a8ad67e04164a537198dea94a4fde81c5592ae9c."]) self.assertEqual(commit.message.full, commit_msg) self.assertEqual(commit.message.original, commit_msg) self.assertEqual(commit.author_name, None) self.assertEqual(commit.author_email, None) self.assertEqual(commit.date, None) self.assertListEqual(commit.parents, []) self.assertListEqual(commit.branches, []) self.assertFalse(commit.is_merge_commit) self.assertFalse(commit.is_fixup_commit) self.assertFalse(commit.is_squash_commit) self.assertTrue(commit.is_revert_commit) self.assertEqual(len(gitcontext.commits), 1) def test_from_commit_msg_fixup_squash_commit(self): commit_types = ["fixup", "squash"] for commit_type in commit_types: commit_msg = f"{commit_type}! Test message" gitcontext = GitContext.from_commit_msg(commit_msg) commit = gitcontext.commits[-1] self.assertIsInstance(commit, GitCommit) self.assertFalse(isinstance(commit, LocalGitCommit)) self.assertEqual(commit.message.title, commit_msg) self.assertEqual(commit.message.body, []) self.assertEqual(commit.message.full, commit_msg) self.assertEqual(commit.message.original, commit_msg) self.assertEqual(commit.author_name, None) self.assertEqual(commit.author_email, None) self.assertEqual(commit.date, None) self.assertListEqual(commit.parents, []) self.assertListEqual(commit.branches, []) self.assertEqual(len(gitcontext.commits), 1) self.assertFalse(commit.is_merge_commit) self.assertFalse(commit.is_revert_commit) # Asserting that squash and fixup are correct for type in commit_types: attr = "is_" + type + "_commit" self.assertEqual(getattr(commit, attr), commit_type == type) @patch('gitlint.git.sh') @patch('arrow.now') def test_staged_commit(self, now, sh): # StagedLocalGitCommit() sh.git.side_effect = [ "#", # git config --get core.commentchar "test åuthor\n", # git config --get user.name "test-emåil@foo.com\n", # git config --get user.email "my-brånch\n", # git rev-parse --abbrev-ref HEAD "file1.txt\npåth/to/file2.txt\n", ] now.side_effect = [arrow.get("2020-02-19T12:18:46.675182+01:00")] # We use a fixup commit, just to test a non-default path context = GitContext.from_staged_commit("fixup! Foōbar 123\n\ncömmit-body\n", "fåke/path") # git calls we're expexting expected_calls = [ call('config', '--get', 'core.commentchar', _ok_code=[0, 1], **self.expected_sh_special_args), call('config', '--get', 'user.name', **self.expected_sh_special_args), call('config', '--get', 'user.email', **self.expected_sh_special_args), call("rev-parse", "--abbrev-ref", "HEAD", **self.expected_sh_special_args), call("diff", "--staged", "--name-only", "-r", **self.expected_sh_special_args) ] last_commit = context.commits[-1] self.assertIsInstance(last_commit, StagedLocalGitCommit) self.assertIsNone(last_commit.sha, None) self.assertEqual(last_commit.message.title, "fixup! Foōbar 123") self.assertEqual(last_commit.message.body, ["", "cömmit-body"]) # Only `git config --get core.commentchar` should've happened up until this point self.assertListEqual(sh.git.mock_calls, expected_calls[0:1]) self.assertEqual(last_commit.author_name, "test åuthor") self.assertListEqual(sh.git.mock_calls, expected_calls[0:2]) self.assertEqual(last_commit.author_email, "test-emåil@foo.com") self.assertListEqual(sh.git.mock_calls, expected_calls[0:3]) self.assertEqual(last_commit.date, datetime.datetime(2020, 2, 19, 12, 18, 46, tzinfo=dateutil.tz.tzoffset("+0100", 3600))) now.assert_called_once() self.assertListEqual(last_commit.parents, []) self.assertFalse(last_commit.is_merge_commit) self.assertTrue(last_commit.is_fixup_commit) self.assertFalse(last_commit.is_squash_commit) self.assertFalse(last_commit.is_revert_commit) self.assertListEqual(last_commit.branches, ["my-brånch"]) self.assertListEqual(sh.git.mock_calls, expected_calls[0:4]) self.assertListEqual(last_commit.changed_files, ["file1.txt", "påth/to/file2.txt"]) self.assertListEqual(sh.git.mock_calls, expected_calls[0:5]) @patch('gitlint.git.sh') def test_staged_commit_with_missing_username(self, sh): # StagedLocalGitCommit() sh.git.side_effect = [ "#", # git config --get core.commentchar ErrorReturnCode('git config --get user.name', b"", b""), ] expected_msg = "Missing git configuration: please set user.name" with self.assertRaisesMessage(GitContextError, expected_msg): ctx = GitContext.from_staged_commit("Foōbar 123\n\ncömmit-body\n", "fåke/path") [str(commit) for commit in ctx.commits] @patch('gitlint.git.sh') def test_staged_commit_with_missing_email(self, sh): # StagedLocalGitCommit() sh.git.side_effect = [ "#", # git config --get core.commentchar "test åuthor\n", # git config --get user.name ErrorReturnCode('git config --get user.name', b"", b""), ] expected_msg = "Missing git configuration: please set user.email" with self.assertRaisesMessage(GitContextError, expected_msg): ctx = GitContext.from_staged_commit("Foōbar 123\n\ncömmit-body\n", "fåke/path") [str(commit) for commit in ctx.commits] def test_gitcommitmessage_equality(self): commit_message1 = GitCommitMessage(GitContext(), "tëst\n\nfoo", "tëst\n\nfoo", "tēst", ["", "föo"]) attrs = ['original', 'full', 'title', 'body'] self.object_equality_test(commit_message1, attrs, {"context": commit_message1.context}) @patch("gitlint.git._git") def test_gitcommit_equality(self, git): # git will be called to setup the context (commentchar and current_branch), just return the same value # This only matters to test gitcontext equality, not gitcommit equality git.return_value = "foöbar" # Test simple equality case now = datetime.datetime.utcnow() context1 = GitContext() commit_message1 = GitCommitMessage(context1, "tëst\n\nfoo", "tëst\n\nfoo", "tēst", ["", "föo"]) commit1 = GitCommit(context1, commit_message1, "shä", now, "Jöhn Smith", "jöhn.smith@test.com", None, ["föo/bar"], ["brånch1", "brånch2"]) context1.commits = [commit1] context2 = GitContext() commit_message2 = GitCommitMessage(context2, "tëst\n\nfoo", "tëst\n\nfoo", "tēst", ["", "föo"]) commit2 = GitCommit(context2, commit_message1, "shä", now, "Jöhn Smith", "jöhn.smith@test.com", None, ["föo/bar"], ["brånch1", "brånch2"]) context2.commits = [commit2] self.assertEqual(context1, context2) self.assertEqual(commit_message1, commit_message2) self.assertEqual(commit1, commit2) # Check that objects are unequal when changing a single attribute kwargs = {'message': commit1.message, 'sha': commit1.sha, 'date': commit1.date, 'author_name': commit1.author_name, 'author_email': commit1.author_email, 'parents': commit1.parents, 'changed_files': commit1.changed_files, 'branches': commit1.branches} self.object_equality_test(commit1, kwargs.keys(), {"context": commit1.context}) # Check that the is_* attributes that are affected by the commit message affect equality special_messages = {'is_merge_commit': "Merge: foöbar", 'is_fixup_commit': "fixup! foöbar", 'is_squash_commit': "squash! foöbar", 'is_revert_commit': "Revert: foöbar"} for key in special_messages: kwargs_copy = copy.deepcopy(kwargs) clone1 = GitCommit(context=commit1.context, **kwargs_copy) clone1.message = GitCommitMessage.from_full_message(context1, special_messages[key]) self.assertTrue(getattr(clone1, key)) clone2 = GitCommit(context=commit1.context, **kwargs_copy) clone2.message = GitCommitMessage.from_full_message(context1, "foöbar") self.assertNotEqual(clone1, clone2) @patch("gitlint.git.git_commentchar") def test_commit_msg_custom_commentchar(self, patched): patched.return_value = "ä" context = GitContext() message = GitCommitMessage.from_full_message(context, "Tïtle\n\nBödy 1\näCömment\nBody 2") self.assertEqual(message.title, "Tïtle") self.assertEqual(message.body, ["", "Bödy 1", "Body 2"]) self.assertEqual(message.full, "Tïtle\n\nBödy 1\nBody 2") self.assertEqual(message.original, "Tïtle\n\nBödy 1\näCömment\nBody 2")
"""Provide email notification support""" import smtplib import logging import json class Emailer: """Class which handles sending notification emails.""" def __init__(self, config): self._config = config['smtp'] self._logging_level = config['logging_level'] self._logger = logging.getLogger(__name__) def _get_emails(self): """Get a dictionary of email addresses and names. Read email addresses (and names) from a text file and import them into a dictionary (keyed by email address). It's possible, though, that the dictionary is already inline in our config structure, in which case we just copy it. """ emails = {} # The way we check for an inline dictionary is if the first # character of the supposed filename is '{'. If it's any other # character, we treat it as a filename. if self._config['datafile'][0] == '{': emails = json.loads(self._config['datafile']) else: try: with open(self._config['datafile'], 'r') as email_file: for line in email_file: (name, email) = line.split(',') emails[email.strip()] = name.strip() except FileNotFoundError as err: print(err) return emails def send_emails(self, subject, body): """Send emails to a list of recipients. Use an SMTP email account to send an email to each address in the emails dictionary. Subject and email body are passed in to this function, but the email is personalized with the receiver's name. """ emails = self._get_emails() # Connect to the mail server server = smtplib.SMTP(self._config['smtp_server'], self._config['smtp_port']) if self._config['tls'] is True: server.starttls() server.login(self._config['account_username'], self._config['account_password']) # If the logging level is set to INFO or below (e.g. DEBUG), we # turn on debug messages for the SMTP connection. Above INFO # means that the user wants fewer messages, so we don't turn on # debug messages. if self._logging_level <= logging.INFO: server.set_debuglevel(1) else: server.set_debuglevel(0) # Compose and send the mail sender = self._config['sender_email_address'] for (receiver_email, receiver_name) in emails.items(): message = 'From: ' + self._config['sender_display_name'] + '\n' message += 'To: ' + receiver_name + ' <' + receiver_email + '>\n' message += 'Subject: ' + subject + '\n\n' message += 'Hi ' + receiver_name + ',\n\n' message += body server.sendmail(sender, receiver_email, message) server.quit() # TODO: Received email doesn't have a received time in Outlook (Gmail ok)
import requests subscription_key = "cbf2b70a2d8649079256eae159c848f8" assert subscription_key def analyze_image(image_path): vision_base_url = "https://eastus2.api.cognitive.microsoft.com/vision/v1.0/" vision_analyze_url = vision_base_url + "analyze" image_url = image_path headers = {'Ocp-Apim-Subscription-Key': subscription_key } params = {'visualFeatures': 'Categories,Description,Color'} data = {'url': image_url} response = requests.post(vision_analyze_url, headers=headers, params=params, json=data) response.raise_for_status() analysis = response.json() image_tags_u = analysis["description"]["tags"] image_tags = [tag.encode('ascii') for tag in image_tags_u] print(image_tags) if ("person" in image_tags and "tattoo" in image_tags or "food" in image_tags or "fruit" in image_tags or "pink" in image_tags or "red" in image_tags or "brown" in image_tags or "white" in image_tags or "close" in image_tags): return True return False #image_url = "https://upload.wikimedia.org/wikipedia/commons/thumb/1/12/Broadway_and_Times_Square_by_night.jpg/450px-Broadway_and_Times_Square_by_night.jpg" #print analyze_image(image_url)
print("Append Content To Files") content = input("Enter Content To Append to A file: ") path = input("Enter the Path of the file: ") File = open(str(path), "a") File.write(str(content)) input("Press Enter to Exit: ")
import sys sys.path.append("/usr/lib/python2.6/site-packages") from cloudbot.interface.ttypes import * from cloudbot.utils import OpenLdap,utility import threading import copy import vmEngineUtility import vmEngine00 import vmEngine11 from vmEngineType import * #import vmEngine10 #import vmEngine01 #import vmEngine00 logger = utility.init_log() g_user_thread_lock={} # user lock to change global g_clientinfo_user g_node_thread_lock={} # node lock to change global g_instance_clc def p_get_vmconfig_type(vmconfig): vmconfigType = -1 if vmconfig.user!='any': if vmconfig.image_id!='any': if vmconfig.is_assign_node: vmconfigType = VM_ENGINE.TYPE_111 else: #not is_assign_node: vmconfigType = VM_ENGINE.TYPE_110 else: #image_id=='any' if vmconfig.is_assign_node: vmconfigType = VM_ENGINE.TYPE_101 else: #not is_assign_node: vmconfigType = VM_ENGINE.TYPE_100 else: #user=='any': if vmconfig.image_id!='any': if vmconfig.is_assign_node: vmconfigType = VM_ENGINE.TYPE_011 else: #not is_assign_node: vmconfigType = VM_ENGINE.TYPE_010 else: #image_id=='any' if vmconfig.is_assign_node: vmconfigType = VM_ENGINE.TYPE_001 else: #not is_assign_node: vmconfigType = VM_ENGINE.TYPE_000 return vmconfigType #order the vmconfig list def p_order_vmconfig_list(vmconfigs): vmconfigList = [] type_111_list = [] type_110_list = [] type_101_list = [] type_100_list = [] type_011_list = [] type_010_list = [] type_001_list = [] type_000_list = [] for vmconfig in vmconfigs: if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_111: type_111_list.append(vmconfig) else : if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_110: type_110_list.append(vmconfig) else: if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_101: type_101_list.append(vmconfig) else: if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_100: type_100_list.append(vmconfig) else: if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_011: type_011_list.append(vmconfig) else: if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_010: type_010_list.append(vmconfig) else: if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_001: type_001_list.append(vmconfig) else: if p_get_vmconfig_type(vmconfig)==VM_ENGINE.TYPE_000: type_000_list.append(vmconfig) vmconfigList = type_111_list + type_110_list + type_101_list + type_100_list + type_011_list + type_010_list + type_001_list + type_000_list logger.debug('order vmconfig: %s' %str(vmconfigList)) return vmconfigList #create the client info from the vmconfig #old:p_init_client_info_from_vmconfig def p_init_client_info(vmConfigList, imageList, userList, nodeList, clientDataList): logger.debug('p_init_clientInfo vmConfigList: %s' %str(vmConfigList)) for vmconfig in vmConfigList: vmconfigType = p_get_vmconfig_type(vmconfig) logger.debug('init_client_info vmtype: %s' %str(vmconfigType)) if vmconfigType==VM_ENGINE.TYPE_111 or vmconfigType==VM_ENGINE.TYPE_110: #g_clientinfo_user vmEngine11.add_vmconfig(vmconfig, imageList, nodeList, clientDataList) # elif vmconfig.user!='any' and vmconfig.image_id=='any': # vmEngine10.p_get_clientInfo_from_vmconfig_set_user(vmConfigList,nodeList,clientDataList) # elif vmconfig.user=='any' and vmconfig.image_id!='any': # vmEngine01.p_get_clientInfo_from_vmconfig_set_image(vmConfigList,imageList,nodeList,clientDataList) elif vmconfigType==VM_ENGINE.TYPE_001 or vmconfigType==VM_ENGINE.TYPE_000: logger.debug('init_client_info 00 vmconfig is: %s' %str(vmconfig)) vmEngine00.add_vmconfig(vmconfig,imageList,userList,nodeList,clientDataList) logger.debug('init_client_info 00 clientDataList is: %s' %str(clientDataList)) else: pass # init the clc global clientdata def init_client_info(vmEngineData, clientDataList): if vmEngineData.nodeList!=None and len(vmEngineData.nodeList)>0: for nodeInfo in vmEngineData.nodeList: if not g_node_thread_lock.has_key(nodeInfo.hostIp): g_node_thread_lock[nodeInfo.hostIp] = threading.Lock() if vmEngineData.userList!=None: for userInfo in vmEngineData.userList: if not g_user_thread_lock.has_key(userInfo.userName): g_user_thread_lock[userInfo.userName]=threading.Lock() #order the vmconfig vmEngineData.vmconfigs = p_order_vmconfig_list(vmEngineData.vmconfigs) #do init p_init_client_info(vmEngineData.vmconfigs, vmEngineData.images,vmEngineData.userList, vmEngineData.nodeList, clientDataList) #change the global instance list #old:p_update_global_state_instances def p_update_global_instances_state(clientData,nodeList,instanceList): if clientData.user==None or clientData.image_id==None or clientData.node_ip==None: logger.warn('p_update_global_instances_state : user imageID or nodeIp is none!') return clusterName = None nodeInfo = vmEngineUtility.get_nodeinfo(clientData.node_ip,nodeList) if nodeInfo!=None: logger.debug('p_update_global_instances_state : the node is %s' %str(nodeInfo)) clusterName = nodeInfo.clusterName logger.debug('p_update_global_instances_state : the clusterName %s' %clusterName) if clusterName!=None: if not g_node_thread_lock.has_key(clientData.node_ip): g_node_thread_lock[clientData.node_ip]=threading.Lock() g_node_thread_lock[clientData.node_ip].acquire() if instanceList.has_key(clusterName): logger.debug('p_update_global_instances_state : has cluster key' ) p_cluster = instanceList[clusterName] if p_cluster.has_key(clientData.node_ip): instances = p_cluster[clientData.node_ip] hasIns = False for insClient in instances: if insClient.image_id ==clientData.image_id and insClient.user == clientData.user : hasIns = True insClient.instance_state.state = clientData.instance_state.state break if not hasIns: instances.append(clientData) else: instances=[] instances.append(clientData) instanceList[clusterName][clientData.node_ip]=instances else: logger.debug('p_update_global_instances_state : no cluster key' ) instances=[] instances.append(clientData) nodeIns = {} nodeIns[clientData.node_ip] = instances instanceList[clusterName]=nodeIns g_node_thread_lock[clientData.node_ip].release() logger.debug('p_update_global_instances_state : the instanceList is %s' %str(instanceList)) return # delete the instance : the clientinfo homologous instance def p_delete_global_instances(clientinfo,nodeInfo,instanceList): if clientinfo.user==None or clientinfo.image_id==None or clientinfo.node_ip==None or nodeInfo==None or nodeInfo.clusterName==None: logger.warn('p_delete_global_instances : user imageID or nodeIp is none!') return if not g_node_thread_lock.has_key(clientinfo.node_ip): g_node_thread_lock[clientinfo.node_ip]=threading.Lock() g_node_thread_lock[clientinfo.node_ip].acquire() if instanceList.has_key(nodeInfo.clusterName): if instanceList[nodeInfo.clusterName].has_key(clientinfo.node_ip): insClients =instanceList[nodeInfo.clusterName][clientinfo.node_ip][:] for insclient in insClients: if insclient.user == clientinfo.user and insclient.image_id==clientinfo.image_id: instanceList[nodeInfo.clusterName][clientinfo.node_ip].remove(insclient) break g_node_thread_lock[clientinfo.node_ip].release() return # change the state of clientdata #old p_update_global_state_clientdatas def p_update_global_clientdatas_state(runInstanceData,images,nodeList,clientDataList,instanceList,state): logger.debug('p_update_global_clientdatas_state start') user = runInstanceData.user imageID = runInstanceData.image_id nodeIp = runInstanceData.node_ip strinfo = 'user: '+user+' imageID: '+imageID+' nodeIp: '+nodeIp logger.debug('p_update_global_clientdatas_state:%s' %str(strinfo)) nodeInfo = vmEngineUtility.get_nodeinfo(nodeIp,nodeList) if nodeInfo.isLocal: if clientDataList.has_key(user) and clientDataList[user].has_key('local') and clientDataList[user]['local'].has_key(nodeIp) : clientinfos = clientDataList[user]['local'][nodeIp] for cl in clientinfos: if cl.image_id == imageID: g_user_thread_lock[user].acquire() cl.node_ip = nodeIp cl.instance_state.state = state g_user_thread_lock[user].release() p_update_global_instances_state(cl,nodeList,instanceList) break else: if clientDataList.has_key(user) and clientDataList[user].has_key('remote'): clientinfos = clientDataList[user]['remote'] for cl in clientinfos: if cl.image_id == imageID: g_user_thread_lock[user].acquire() cl.node_ip = nodeIp cl.instance_state.state = state g_user_thread_lock[user].release() clInfo = copy.deepcopy(cl) p_update_global_instances_state(clInfo,nodeList,instanceList) logger.debug('p_update_global_clientdatas_state : %s' %str(cl)) break # when start instance , change the clc global state def update_global_by_startvm(runInstanceData,images,nodeList,clientDataList,instanceList): p_update_global_clientdatas_state(runInstanceData,images,nodeList,clientDataList,instanceList,thd_TRANSACT_STATE.DOWNLOADING) # get the transaction fron cc , update the clc global clientData and instance info def update_global_by_transactions(transmitData,nodeList,clientDataList,instanceList): logger.debug('update_global_by_transactions :%s' %str(transmitData)) nodeInfo = vmEngineUtility.get_nodeinfo(transmitData.node_ip,nodeList) if nodeInfo==None: logger.error('the node not register: %s' %transmitData.node_ip) return logger.debug('clientData :%s' %str(clientDataList)) for user in clientDataList.keys(): p_clientinfos=None if nodeInfo.isLocal!=None and nodeInfo.isLocal: if clientDataList[user].has_key('local') and clientDataList[user]['local'].has_key(transmitData.node_ip): p_clientinfos = clientDataList[user]['local'][transmitData.node_ip] else: if clientDataList[user].has_key('remote'): p_clientinfos = clientDataList[user]['remote'] if p_clientinfos!=None: for clientinfo in p_clientinfos: if clientinfo.node_ip ==transmitData.node_ip : clientHasTrac = False if len(transmitData.transactions)>0: for transaction in transmitData.transactions: if(transaction.user==clientinfo.user and transaction.imageID==clientinfo.image_id): clientHasTrac = True if not g_user_thread_lock.has_key(user): g_user_thread_lock[user]=threading.Lock() g_user_thread_lock[user].acquire() if clientinfo.instance_state.state==thd_TRANSACT_STATE.DOWNLOADING : if transaction.state!=thd_TRANSACT_STATE.TERMINATED : clientinfo.instance_state.state = transaction.state else: if clientinfo.instance_state.state==thd_TRANSACT_STATE.SHUTTING_DOWN : #instance from shuitingdown to terminated,the transit state not set to client data if transaction.state == thd_TRANSACT_STATE.TERMINATED: clientinfo.instance_state.state = transaction.state else: clientinfo.instance_state.state = transaction.state clientinfo.vm_info.vm_port = transaction.instancePort clientinfo.vm_info.vm_password = transaction.instancePassword clientinfo.instance_state.download_progress = transaction.downloadProgress g_user_thread_lock[user].release() logger.debug('clientInfo: %s' %str(clientinfo)) p_update_global_instances_state(clientinfo,nodeList,instanceList) if not clientHasTrac: if not g_user_thread_lock.has_key(user): g_user_thread_lock[user]=threading.Lock() g_user_thread_lock[user].acquire() clientinfo.instance_state.state = thd_TRANSACT_STATE.TERMINATED clientinfo.vm_info.vm_port = -1 clientinfo.vm_info.vm_password = None clientinfo.instance_state.download_progress = -1 g_user_thread_lock[user].release() p_delete_global_instances(clientinfo,nodeInfo,instanceList) logger.debug(' clientdata info:%s' %str(clientDataList)) def add_image(imageInfo,clientDataList): vmEngine11.add_image(imageInfo,clientDataList) # delete the image ,update the clc global clientData and instance info def delete_image(imageId,clientDataList): vmEngine11.delete_image(imageId,clientDataList) # change the image ,update the clc global clientData info and global instance info def change_image(newImage,clientDataList,instanceList): vmEngine11.change_image(newImage,clientDataList,instanceList) # add vmconfig ,update the clc global clientData info and global instance info def add_vmconfig(newVmConfig,images,nodeList,userList,clientDataList): vmconfigType = p_get_vmconfig_type(newVmConfig) if vmconfigType==VM_ENGINE.TYPE_111 or vmconfigType==VM_ENGINE.TYPE_110: vmEngine11.add_vmconfig(newVmConfig,images,nodeList,clientDataList) elif vmconfigType==VM_ENGINE.TYPE_001 or vmconfigType==VM_ENGINE.TYPE_000: vmEngine00.add_vmconfig(newVmConfig,images,userList,nodeList,clientDataList) return # delete vmconfig ,update the clc global clientData info and global instance info def delete_vmconfig(vmconfigId,clientDataList): vmEngine11.delete_vmconfig(vmconfigId,clientDataList) # change vmconfig ,update the clc global clientData info and global instance info def change_vmconfig(newVmConfig,images,nodeList,userList,clientDataList): vmconfigType = p_get_vmconfig_type(newVmConfig) if vmconfigType==VM_ENGINE.TYPE_111 or vmconfigType==VM_ENGINE.TYPE_110: vmEngine11.change_vmconfig(newVmConfig,images,nodeList,userList,clientDataList) elif vmconfigType==VM_ENGINE.TYPE_001 or vmconfigType==VM_ENGINE.TYPE_000: vmEngine00.change_vmconfig(newVmConfig,images,nodeList,userList,clientDataList) else: pass return def add_user(user,vmconfigs,clientDataList): for vmconfig in vmconfigs: vmconfigType = p_get_vmconfig_type(vmconfig) if vmconfigType==VM_ENGINE.TYPE_111 or vmconfigType==VM_ENGINE.TYPE_110: vmEngine11.add_user(user,vmconfig,clientDataList) elif vmconfigType==VM_ENGINE.TYPE_001 or vmconfigType==VM_ENGINE.TYPE_000: vmEngine00.add_user(user,vmconfig,clientDataList) def delete_user(user,clientDataList): vmEngine11.delete_user(user,clientDataList)
import sys sys.setrecursionlimit(100000) def min_perm(N, K): P = [1] * N need = K - N i = 0 while i < N and need > 0: P[i] = min(need+1, N) need = need + 1 - P[i] i += 1 return list(reversed(P)) def assign(P, N, i, j, v): P[i, j] = frozenset([v]) nbs = [(i, k) for k in range(N) if k != j] + [(k, j) for k in range(N) if k != i] if all(eliminate(P, N, i, j, v) for i, j in nbs): return P return False def eliminate(P, N, i, j, v): if v not in P[i, j]: return P # already eliminated P[i, j] = P[i, j] - {v} if not P[i, j]: return False # out of options if len(P[i, j]) == 1: w = next(iter(P[i, j])) if not assign(P, N, i, j, w): return False return P def search(P, N): if P is False: return False if all(len(vs) == 1 for _, vs in P.items()): return P # win try: n, i, j = min((len(P[i, j]), i, j) for i in range(N) for j in range(N) if len(P[i, j]) > 1) except ValueError: return False return some(search(assign(P.copy(), N, i, j, v), N) for v in P[i, j]) def some(seq): for e in seq: if e: return e return False def fill(M, N): P = {(i, j): frozenset(range(1, N+1)) for i in range(N) for j in range(N)} for i in range(N): for j in range(N): if M[i][j] != 0: assign(P, N, i, j, M[i][j]) R = search(P, N) if R: for i, j in R: M[i][j] = next(iter(R[i, j])) return M def solve_p(N, p): M = [[0] * N for _ in range(N)] for i in range(N): M[i][i] = p[i] return fill(M, N) def solve(N, K): mp = min_perm(N, K) sol = solve_p(N, mp) if sol: return sol S = set(mp) if len(S) == 2: m = max(S) i = mp.index(m) mp[i-1] += 1 mp[i] -= 1 return solve_p(N, mp) T = int(input()) for x in range(1, T+1): N, K = map(int, input().split()) M = solve(N, K) if M: print('Case #{}: POSSIBLE'.format(x)) for row in M: print(' '.join(map(str, row))) else: print('Case #{}: IMPOSSIBLE'.format(x))
from unetpy import * modem = UnetGateway('192.168.0.11') phy = modem.agentForService(Services.PHYSICAL) print(phy[0][0])
import boto3 import json import yaml from aws_organized_policies import helper import os from datetime import datetime import click import os from datetime import datetime from betterboto import client as betterboto_client from pathlib import Path import time STATE_FILE = "state.yaml" client = boto3.client("sts") org = boto3.client("organizations") SERVICE_CONTROL_POLICY = "SERVICE_CONTROL_POLICY" ORGANIZATIONAL_UNIT = "ORGANIZATIONAL_UNIT" service_control_policies_path = "environment/Policies/SCPs" SEP = os.path.sep ATTACH_POLICY = "ATTACH_POLICY" DETACH_POLICY = "DETACH_POLICY" policies_migration_path = "environment/policies_migration" make_individual_migration_policies_path = ( "environment/policies_migration/migrations_to_apply" ) def read_policies() -> None: # Reads + Returns a list {'SERVICE_CONTROL_POLICIEs': ['c', 'd', 'e']} path = "organization/Policies/" name = "policy_sample" + ".yml" with open(path + name) as file: # The FullLoader parameter handles the conversion from YAML # scalar values to Python the dictionary format policies_list = yaml.load(file, Loader=yaml.FullLoader) scp_list = policies_list.get("SERVICE_CONTROL_POLICIES") # get an array of all accounts in the Organisation def get_accounts() -> dict: accounts = dict() paginator = org.get_paginator("list_accounts") # use paginator for efficiency page_iterator = paginator.paginate() for page in page_iterator: for acct in page["Accounts"]: # get all accounts in org accounts[acct.get("Id")] = acct.get("Name") return accounts # map every account + corresponding SCPs in ORG as [target_id]:{policy} def get_service_control_policies_for_target(policies_target_list, root_id) -> dict: policies_for_each_target = dict() policies_name_for_each_target = dict() policies_target_IDs = list(policies_target_list.keys()) print("policies_target_list", policies_target_list) for target_id in policies_target_IDs: list_service_control_policies = org.list_policies_for_target( TargetId=target_id, Filter=SERVICE_CONTROL_POLICY ) describe_service_control_policies = ( [ # for every PolicyId get readable description org.describe_policy(PolicyId=target.get("Id")) for target in list_service_control_policies.get("Policies") ] ) policies_for_each_target[policies_target_list[target_id]] = [ policy.get("Policy") for policy in describe_service_control_policies ] policies_name_for_each_target[ policies_target_list[target_id] if policies_target_list[target_id] != "Root" else root_id ] = [ helper.get_valid_filename( policy.get("Policy").get("PolicySummary").get("Name") ) for policy in describe_service_control_policies ] print("policies_name_for_each_target", policies_name_for_each_target) return policies_for_each_target, policies_name_for_each_target # get an array of all OUs as a list including route using recursion # https://stackoverflow.com/questions/57012709/aws-boto3-how-to-list-of-all-the-org-idseven-nested-under-organization def list_organizational_units(parent_id, ou_list) -> list: ou_list.append(parent_id) paginator = org.get_paginator("list_children") iterator = paginator.paginate(ParentId=parent_id, ChildType=ORGANIZATIONAL_UNIT) for page in iterator: for ou in page["Children"]: list_organizational_units(ou["Id"], ou_list) return ou_list def get_organizational_units(root_id) -> dict: ou_list = list_organizational_units(root_id, list())[1:] all_ous = { # map ou_id to ou_name as {"OU_Id":"OU_Name"} ou_Id: org.describe_organizational_unit(OrganizationalUnitId=ou_Id)[ "OrganizationalUnit" ]["Name"] for ou_Id in ou_list } all_ous[root_id] = root_id return all_ous def write_all_policies_to_json(path, policies_dict) -> None: for policy in policies_dict.values(): policy_file_name = helper.get_valid_filename( policy.get("PolicySummary").get("Name") ) helper.write_to_file(policy, path, policy_file_name + ".json") # TODO extend to other policies by adding policy_type parameter def write_policies_to_individual_target_yaml( all_policies_for_target, path, file_name ) -> None: data = {"Policies_Attached": all_policies_for_target} Path(path).mkdir(parents=True, exist_ok=True) with open(path + file_name, "w") as outfile: yaml.dump(data, outfile, default_flow_style=False) def write_policies_to_target_yaml(target_SCPs, target_name_path) -> dict: policies_per_target = dict() for target_id, policies_attached_to_target in target_SCPs.items(): policies_name = [ helper.get_valid_filename(policy["PolicySummary"]["Name"]) for policy in policies_attached_to_target ] target_path = target_name_path[target_id] + "/" policies_per_target[target_id] = policies_name # saved initial state policies policy_file_name = "_service_control_policies.yaml" write_policies_to_individual_target_yaml( policies_name, target_path, policy_file_name ) return policies_per_target def get_unique_policies(policies_dic) -> dict: common_policies = {} for policies_list in policies_dic.values(): for policy in policies_list: common_policies[policy.get("PolicySummary").get("Id")] = policy return common_policies def get_org_structure(org_path) -> dict: file_list = helper.getListOfFiles(org_path) accounts_path = helper.get_account_paths(file_list) ous_path = { path[0].split("/")[-1]: path[0] + "/" for path in os.walk(org_path) if path[0][-9:] != "_accounts" } return accounts_path, ous_path def get_id_from_name(target_name, id_name_map) -> str: for id, name in id_name_map.items(): if target_name == name: return id def get_all_policies_in_account(): org_policies = org.list_policies(Filter="SERVICE_CONTROL_POLICY").get("Policies") all_SCPs = dict() for policy in org_policies: policy_id = policy.get("Id") # policy_name = helper.get_valid_filename(policy.get('Name')) policy_full = org.describe_policy(PolicyId=policy_id) if ( policy_full.get("Policy").get("PolicySummary").get("Type") == "SERVICE_CONTROL_POLICY" ): all_SCPs[policy_id] = policy_full.get("Policy") return all_SCPs def import_organization_policies(role_arn) -> None: click.echo("Updating state file") with betterboto_client.CrossAccountClientContextManager( "organizations", role_arn, f"organizations", ) as organizations: list_accounts_details = organizations.list_accounts_single_page() list_roots_response = organizations.list_roots_single_page() root_id = list_roots_response.get("Roots")[0].get("Id") org_path = SEP.join(["environment", root_id]) all_files_in_environment_list = helper.getListOfFiles(org_path) # Step 0 get all policies in org all_service_control_policies_in_org = org.list_policies( Filter=SERVICE_CONTROL_POLICY ).get("Policies") all_service_control_policies_in_org_with_policy_summary = [ org.describe_policy(PolicyId=policy.get("Id")).get("Policy") for policy in all_service_control_policies_in_org ] [ helper.write_to_file( { "PolicySummary": policy.get("PolicySummary"), "Content": json.loads(policy.get("Content")), }, service_control_policies_path, helper.get_valid_filename(policy.get("PolicySummary").get("Name")) + ".json", ) for policy in all_service_control_policies_in_org_with_policy_summary ] # Step 1 Save Attached policies accounts = { account.get("Id"): account.get("Name") for account in list_accounts_details.get("Accounts") } ous = get_organizational_units(root_id) # list all OUs in org service_control_policies_path_for_target = helper.map_scp_path_for_target_name( all_files_in_environment_list, root_id ) ( service_control_policies_for_target, scp_name_for_each_target, ) = get_service_control_policies_for_target(ous | accounts, root_id) write_policies_to_target_yaml( service_control_policies_for_target, service_control_policies_path_for_target ) # Step 2 Save Inherited policies for file_path in all_files_in_environment_list: if "_service_control_policies.yaml" in file_path: current_scp_path_list = file_path.split("/") root_org_scp_path = org_path + "/_service_control_policies.yaml" local_policy = [ policy for policy in helper.read_yaml(root_org_scp_path)["Policies_Attached"] ] for i in range(len(current_scp_path_list)): # go through every OU in org structure if "_organizational_units" in current_scp_path_list[i]: current_organizational_unit_index = current_scp_path_list.index( current_scp_path_list[i + 1] ) current_policy_path = ( SEP.join( current_scp_path_list[:-current_organizational_unit_index] ) + "/_service_control_policies.yaml" ) # TODO change this to save as policy_name ===> source: Org_source local_policy.extend( [ attached_policy for attached_policy in helper.read_yaml( current_policy_path )["Policies_Attached"] if attached_policy not in local_policy ] ) if ( file_path != root_org_scp_path and "_service_control_policies.yaml" in current_scp_path_list[i] ): helper.write_inherited_yaml(local_policy, file_path) # save initial set up helper.write_to_file( scp_name_for_each_target, policies_migration_path, "initial_state.yaml" ) def map_policy_name_to_id(org_ids_map, attached_Policies, policy_ids_map) -> dict: policies_to_apply = dict() for id, name in org_ids_map.items(): if name in attached_Policies.keys(): policies_to_apply[id] = [policy_ids_map[x] for x in attached_Policies[name]] return policies_to_apply def write_migrations(attach_policies, detach_policies): policies_migration_path + "/migrations_to_apply" # target: policies for target, policy_list in attach_policies.items(): # data, path, file_name for policy in policy_list: file_name = f"{ATTACH_POLICY}_{target}_{policy}" helper.write_to_file( "a", policies_migration_path + "/migrations_to_apply", file_name ) def make_migration_policies(role_arn) -> None: # 0 get initial state # 0.1 read for org state # 0.2 read for account state # 1. read current state by looking through _policies folders in organization # 1.1 read for org state # 1.2 read for account state with betterboto_client.CrossAccountClientContextManager( "organizations", role_arn, f"organizations", ) as organizations: list_accounts_response = organizations.list_accounts_single_page() list_roots_response = organizations.list_roots_single_page() root_id = list_roots_response.get("Roots")[0].get("Id") org_path = SEP.join(["environment", root_id]) all_files_in_environment_list = helper.getListOfFiles(org_path) # read initial setup initial_scp_per_target_state = helper.read_yaml( policies_migration_path + "/initial_state.yaml" ) current_policies_state = dict() attach_policies = dict() detach_policies = dict() print("all_files_in_environment_list", all_files_in_environment_list) for file_path in all_files_in_environment_list: if "_service_control_policies.yaml" in file_path: target_name = file_path.split("/")[-2] print(target_name) policies_list = helper.read_yaml(file_path)["Policies_Attached"] current_policies_state[target_name] = policies_list # 2 Compare migration state to current state for key, value in current_policies_state.items(): print("key", key) print("value", value) print("initial_scp_per_target_state", initial_scp_per_target_state) # find diff policy if value != initial_scp_per_target_state[key]: detached_policy_list = [ item for item in initial_scp_per_target_state[key] if item not in current_policies_state[key] ] attach_policies_list = [ item for item in current_policies_state[key] if item not in initial_scp_per_target_state[key] ] # make sure non empty values are not saved if detached_policy_list: detach_policies[key] = detached_policy_list if attach_policies_list: attach_policies[key] = attach_policies_list # 3 Create migration document summary helper.write_to_file( { "Attached_Policies": attach_policies, "Detached_Policies": detach_policies, }, policies_migration_path, "migration_state_summary.yaml", ) # 3 Create migration folder # map policy name to policy content policies_map = dict() for policy in os.listdir(service_control_policies_path): policies_map[policy.replace(".json", "")] = helper.read_json( SEP.join([service_control_policies_path, policy]) ) for target, policy_list in attach_policies.items(): print(attach_policies.items()) print("\n") print("target", target) print("\n") # data, path, file_name for policy in policy_list: file_name = f"{ATTACH_POLICY}_SCP_{policy}_TARGET_{target}.json" policies_map[policy]["Migration"] = { "Migration_Type": ATTACH_POLICY, "Target": target, "Policy_Name": policy, "Policy_Id": policies_map[policy].get("PolicySummary").get("Id"), } helper.write_to_file( policies_map[policy], policies_migration_path + "/migrations_to_apply", file_name, ) for target, policy_list in detach_policies.items(): # data, path, file_name for policy in policy_list: file_name = f"{DETACH_POLICY}_SCP_{policy}_TARGET_{target}.json" policies_map[policy]["Migration"] = { "Migration_Type": DETACH_POLICY, "Target": target, "Policy_Name": policy, "Policy_Id": policies_map[policy].get("PolicySummary").get("Id"), } helper.write_to_file( policies_map[policy], policies_migration_path + "/migrations_to_apply", file_name, ) return def apply_migration_policies(role_arn): click.echo("Updating state file") with betterboto_client.CrossAccountClientContextManager( "organizations", role_arn, f"organizations", ) as organizations: list_accounts_response = organizations.list_accounts_single_page() list_roots_response = organizations.list_roots_single_page() root_id = list_roots_response.get("Roots")[0].get("Id") org_path = SEP.join(["environment", root_id]) all_files_in_environment_list = helper.getListOfFiles(org_path) # Step 1 Save Attached policies accounts = { account.get("Id"): account.get("Name") for account in list_accounts_response.get("Accounts") } ous = get_organizational_units(root_id) # list all OUs in org org_ids_map = accounts | ous policy_ids_map = dict() # map SCP name to Ids for file_path in os.listdir(service_control_policies_path): policy = helper.read_json(SEP.join([service_control_policies_path, file_path]))[ "PolicySummary" ] policy_ids_map[helper.get_valid_filename(policy["Name"])] = policy["Id"] # TODO make this in accordance with Eamonn's AWS Organized general way of doing things # so the user will be able to type in the file name and the migration wil be applied reverse_org_ids_map = dict((v, k) for k, v in org_ids_map.items()) for migration_policy in os.listdir(make_individual_migration_policies_path): policy = helper.read_json( SEP.join([make_individual_migration_policies_path, migration_policy]) ).get("Migration") policy_id = policy.get("Policy_Id") policy_name = policy.get("Policy_Name") target_name = policy.get("Target") target_id = reverse_org_ids_map[target_name] policy_type = policy.get("Migration_Type") try: org.attach_policy( PolicyId=policy_id, TargetId=target_id ) if policy_type == ATTACH_POLICY else org.detach_policy( PolicyId=policy_id, TargetId=target_id ) except: print( f"Error when attempting to {policy_type} {policy_name} on target {target_name}." ) else: print( f"Successfully performed {policy_type} {policy_name} on target {target_name}." ) # Write history file # with open(policies_migration_path + "migration_history.yaml", "w") as outfile: # yaml.dump( # { # f"Attached_Policies {datetime.now()}": attached_Policies, # f"Detached_Policies {datetime.now()}": detached_Policies, # }, # outfile, # default_flow_style=False, # ) def clean_up(): for file_path in helper.getListOfFiles(policies_migration_path): if "policies.yaml" in file_path: print(f"Deleted {file_path} policy descriptions files") os.remove(file_path) # TO DO List # TODO add source on inherited policies # extra features: # SCPs add new # TODO Extend to other policy types # Important for functionality: # TODO Add Unattached Policies # TODO Add Inherited policies?
#!/usr/bin/python # -*- coding: utf-8 -*- """ __author__ = "Ananda S. Kannan" __copyright__ = "Copyright 2017, pyFy project" __license__ = "GPL" __version__ = "1.0" __maintainer__ = "Ananda S. Kannan" __email__ = "ansubru@gmail.com" """ ################################################################################ LAMINAR FLOW SOLVER ################################################################################################ import os import numpy as np import re import sys import IO import Interpolate import pprint from Discretize2 import Discretize2 disc_obj2 = Discretize2() from gaussSeidel2 import gaussSiedel2 gs_obj = gaussSiedel2() from solFunc import solFunc solFunc_obj = solFunc() from IO import IO IO_obj = IO("random") from Corr2 import Corr2 corr_obj = Corr2() from plotResults import plotResults plt_obj = plotResults() from rhieChow2 import rhieChow2 rc_obj = rhieChow2() from calcResiduals import calcResiduals res_obj = calcResiduals() ################################################################ INPUT TO SOLVER ########################################################################################################################### grid = IO_obj.grid_nodes #generate a base grid node layout NU = IO_obj.nu #viscosity nu (constant viscosity model) alpha = IO_obj.alpha #Under relaxation rho = IO_obj.rho #Density in Kg/m3 mu = NU*rho #constant for all nodes #Boundary conditions (for u-velocity) UA = IO_obj.UA UB = IO_obj.UB UC = IO_obj.UC UD = IO_obj.UD #Boundary conditions (for v-velocity) VA = IO_obj.VA VB = IO_obj.VB VC = IO_obj.VC VD = IO_obj.VD #Initialize all variables U = 0.0*grid V = 0.0*grid P = 0.0*grid Pset = 0.0*grid mdotw, mdote, mdotn, mdots = 0.0*grid, 0.0*grid, 0.0*grid, 0.0*grid k, omega, mut = 0.0*grid, 0.0*grid, 0.0*grid resU, resV, resP, resB = 1.0 ,1.0 ,1.0 , 1.0 resplotU, resplotV, resplotP, resplotB = [1.0] ,[1.0],[1.0] ,[1.0] outerIters = 0 eps = 1 #Apply BCs U = solFunc_obj.applyBCs(U,UA,UB,UC,UD) #Apply U bcs V = solFunc_obj.applyBCs(V,VA,VB,VC,VD) #Apply V bcs ######################################################################################################################################################################################################## caseType = "Laminar" ############################################################### Controls for iterations ################################################################################################################### iters = 20 #number of gauss seidel sweeps resInp = 1e-3 #residual for gauss seidel residual = 1e-8 #residual for equations interinp = 40 #number of outer iterations ################################################################################## SOLVER ################################################################################################################## #Step 1 : Solve for U,V using interpolated pressure using Discretize class obj # Discretize U velocity using FOU --> P is checkerboarded (no rhie-chow interpolation) # --> Calculates co-eff aP, aW, aW, aN, aS, and Sources # --> Implicit under-relaxation due to non-linearity in pde's # --> Returns face values of flux and velocities along with A and b matrices while (outerIters < interinp): mdotwPrev, mdotePrev, mdotnPrev, mdotsPrev = mdotw, mdote, mdotn, mdots #mdot from previous iteration outerIters += 1 print "Solving iteration %i"%(outerIters) aW, aE, aN, aS,aWp, aEp, aNp, aSp, aP, aPmod, SUxmod, SUymod, aWpp, aEpp, aNpp, aSpp, aPpp = disc_obj2.FOU_disc2( U, V, mdotwPrev, mdotePrev, mdotnPrev, mdotsPrev , P) # #Step 1a : Solve for U using gauss seidel method # # --> Returns U* (newU) which will be corrected using rhie-chow interpolatio Ustar = gs_obj.gaussSeidel3u(U, aW, aE, aN, aS, aPmod,SUxmod, iters) #print Ustar # # #Step 1b : Solve for V using gauss seidel method # # # --> Returns V* (newV) which will be corrected using rhie-chow interpolation # Vstar = gs_obj.gaussSeidel3u(V, aW, aE, aN, aS, aPmod,SUymod, iters) # # # print ("APMOD AT %i iteration" %(outerIters)) # # print Ustar # # print ("APMOD AT %i iteration" %(outerIters)) # #Step 2 : RHIE-CHOW INTERPOLATION # # --> correct face velocities (EAST AND NORTH FACES ALONE) # pcorre, pcorrn = rc_obj.rcInterp2(U, V, mdotw, mdote, mdotn, mdots, P, k, omega, mut, 'U', caseType) # # # Step 2a : Correct face fluxes with rhie chow mstare, mstarn = solFunc_obj.calcFaceMassFlux(Ustar,Vstar) # --> Get east and north face mass fluxes for Ustar and Vstar mdote,mdotn = solFunc_obj.correctFaceMassFlux(mstare,mstarn,pcorre,pcorrn) # --> Correct with rhie-chow to get corrected mdote and motn mdotw, mdots = solFunc_obj.getFaceMassFluxWS(mdote,mdotn) #--> Get corrected mdotw and mdots # # #Step 3 : Solve P' equation using U velocities # # --> Calculates co-eff aP, aW, aW, aN, aS, at faces # # --> Calculates b matrix (Fw - Fe + Fs - Fn) # # --> Solve P' using gauss seidel # # #Step 3a : Create B term (error in continuity) b = solFunc_obj.calcBterm(mdotw, mdote,mdotn ,mdots) # # #Step 3b #Solve P' using co-eff for Pprime equation # Pprime = gs_obj.gaussSeidel3u(Pset, aWpp, aEpp, aNpp, aSpp, aPpp, b, iters) # # #Step 4 : Set pressure based on value at cell (2,2) # #Set P' level x = 1; y = 1; # Grid cell where P is fixed to zero Pset = solFunc_obj.setPress(Pprime,x,y) # # #COPY Pset TO BOUNDARY Pset = solFunc_obj.setPsetbcs(Pset) # # # #Step 5 : Pressure straddling # mdoteNew, mdotnNew = corr_obj.massFluxcorr(Pset,mdote, mdotn, aEpp, aNpp) # mdotwNew, mdotsNew = solFunc_obj.getFaceMassFluxWS(mdoteNew, mdotnNew) # --> Get new mdotw and mdots # uNew, vNew = corr_obj.velcorr(Ustar,Vstar,Pset, aPmod) # --> Correct u and v velcoities # # # #Step 7 : Under relax P' Pnew = solFunc_obj.rlxP(P, Pset, alpha) # # #Step 8 : Calculate residual # Step 10 : Calculate residual resU = res_obj.calcRes(U, aW, aE, aN, aS, SUxmod, aPmod) resV = res_obj.calcRes(V, aW, aE, aN, aS, SUymod, aPmod) resB = res_obj.calcResB(b) eps = max(resU, resV, resB) resplotU.append(resU) resplotV.append(resV) resplotB.append(resB) # # #Replace U,V, mdotw, mdote, mdotn, mdots and P U = uNew V = vNew mdotw = mdotwNew; mdote = mdoteNew; mdotn = mdotnNew; mdots = mdotsNew P = Pnew # # # #Plot residuals print U xpt, ypt = plt_obj.genGrid(U) plt_obj.plotdata2(U,V,ypt,resplotU, resplotV, resplotB,outerIters)
a = "萨达萨达" from functools import wraps import pickle import openpyxl import xlrd, xlwt from xlutils.copy import copy file_path = os.path.dirname(os.path.abspath(__file__)) base_path = os.path.join(file_path, 'demo.xlsx') print(base_path) book = xlrd.open_workbook(base_path) sheet = book.sheet_by_index(0) xfile = openpyxl.load_workbook(base_path) sheet1 = xfile.get_sheet_by_name("Sheet1") for i in range(sheet.nrows): for j in range(sheet.ncols): if i == 0: continue else: value = sheet.cell_value(i, j) print(value) sheet1["D"+str(i+1)] = 2 xfile.save(base_path) # def done(level): # def decorator(one): # @wraps(one) # def wrapper(): # if level == 3: # print("这世界很酷") # one() # return wrapper # return decorator # # @done(level=3) # def one(): # print("我的世界") # # # one() # class Request(): # def __init__(self,one,url,method): # self.one = one # self.url = url # self.method = method # def __call__(self, *args, **kwargs): # print("哈哈") # self.one() # # def one(): # print("呵呵") # # one()
# -*- coding: utf-8 -*- from odoo import http # class CookBook(http.Controller): # @http.route('/cook_book/cook_book/', auth='public') # def index(self, **kw): # return "Hello, world" # @http.route('/cook_book/cook_book/objects/', auth='public') # def list(self, **kw): # return http.request.render('cook_book.listing', { # 'root': '/cook_book/cook_book', # 'objects': http.request.env['cook_book.cook_book'].search([]), # }) # @http.route('/cook_book/cook_book/objects/<model("cook_book.cook_book"):obj>/', auth='public') # def object(self, obj, **kw): # return http.request.render('cook_book.object', { # 'object': obj # })
def binary_array_to_number(arr): s = '' for element in arr: s += str(element) return int(s, 2)
import json, datetime from domino.core import log from sqlalchemy import Column, Integer, String, JSON, DateTime, and_, or_ from sqlalchemy.dialects.oracle import RAW, NUMBER from domino.databases.oracle import Oracle, RawToHex class DominoUser(Oracle.Base): __tablename__ = 'domino_user' id = Column(RAW(8), primary_key=True) pid = Column(RAW(8)) CLASS = Column('class', NUMBER(10,0)) TYPE = Column('type', NUMBER(10,0)) disabled = Column(NUMBER(10,0)) name = Column(String) full_name = Column(String) staffer_id = Column('f15859713', RAW(8)) # Сотрудник @property def ID(self): return RawToHex(self.id) @property def PID(self): return RawToHex(self.pid) @property def staffer_ID(self): return RawToHex(self.staffer_id) def __repr__(self): return f'<DominoUser(id={self.id}, class={self.CLASS}, type={self.TYPE}, name={self.name}>' DominoUserTable = DominoUser.__table__ DominoUser.ClassType = and_(DominoUser.CLASS == 1, DominoUser.TYPE == 1)
#! /usr/bin/env python file_name = 'covid19.fasta' data = dict() # data = {} with open(file_name,'r') as handle: for line in handle: if line.startswith(">"): #헤더부분은 그냥 넘어감. continue for base in line.strip(): #\n 날리기. if base not in data: #base: A, G, C, T data[base] = 0 #base가 없으면 0 data[base] += 1 #있으면 +1 print(data)
def solution(array, commands): answer = [] for s in commands: i = s[0] j = s[1] k = s[2] new_ar = array[i-1:j] new_ar.sort() answer.append(new_ar[k-1]) return answer array = [1, 5, 2, 6, 3, 7, 4] commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]] solution(array, commands)
from flask import Flask, jsonify, request from flask_pymongo import PyMongo, ObjectId from flask_cors import CORS from os import environ # initialization app = Flask(__name__) CORS(app) #Mongo Connection app.config["MONGO_URI"] = environ.get("MONGO_URI", "mongodb://localhost:27017/student") mongo = PyMongo(app) db = mongo.db base_route = '/api/v1/' @app.route(base_route+'students', methods=['GET']) def get_all_students(): _students = db.student.find() item = {} data = [] for student in _students: item = { 'id': str(student['_id']), 'student': student['student'] } data.append(item) return jsonify(data), 200 @app.route(base_route+'students/<string:id>', methods=['GET']) def get_student_by_id(id:str): _student = db.student.find_one({"_id": ObjectId(id)}) item = { 'id': str(_student['_id']), 'student': _student['student'] } return jsonify(item), 200 @app.route(base_route+'students', methods=['POST']) def create_new_student(): data = request.get_json(force=True) item ={ "student": data.copy() } test = db.student.insert_one(item) id = str(test.inserted_id) return jsonify(location=base_route+"students/"+id), 201 @app.route(base_route+'/students/<string:id>', methods=['PUT']) def update_student(id:str): data = request.get_json(force=True) db.student.update_one({"_id": ObjectId(id)}, {"$set": data}) return "", 204 @app.route(base_route+'/students/<string:id>', methods=['DELETE']) def delete_student(id: str): db.student.delete_one({"_id": ObjectId(id)}) return "", 204 if __name__ == "__main__": app.run(host="0.0.0.0", port=8080)
def remove_duplicates(A, key): """ Implement a function which takes as input an array and a key and updates the array such that all occurances of the input key have been removed and the remaining elements have been shifted to fill the emptied indices. Return the number of remaining elements. There are no requirements as to the values stored beyond the last valid element. """ if not A or key not in A: return insert_pos = 0 for num in A: if num != key: A[insert_pos] = num insert_pos += 1 return insert_pos if __name__ == '__main__': print(remove_duplicates([0, 1, 0, 3, 12], 0)) #3
import unittest from functions.funtionLibrary import * class TestGetActionSelection(unittest.TestCase): """Test for getting action solution""" def testGetActionSolution(self): """This a True test to see if the action is selected""" actionlist = [1,2,3,4,5] for action in actionlist: if action == 1: val = getActionSelection(action) self.assertEqual(val,"Show All Books") if action == 2: val = getActionSelection(action) self.assertEqual(val,"Add a book") if action == 3: val = getActionSelection(action) self.assertEqual(val,"Edit a book") if action == 4: val = getActionSelection(action) self.assertEqual(val,"Remove a book") if action == 5: val = getActionSelection(action) self.assertEqual(val,"Exit Program") def testBadGetActionSolution(self): """This a False test to see if the action is selected""" actionlist = ["Add a book",7,8,100,"5","","@1"] for action in actionlist: val = getActionSelection(action) self.assertFalse(val)
""" NeuralWOZ Copyright (c) 2021-present NAVER Corp. Apache License v2.0 """ import json from copy import deepcopy from itertools import chain import h5py import torch from torch.utils.data import Dataset from .data_utils import make_dst_target, split_slot, pad_ids, pad_id_of_matrix from .constants import EXPERIMENT_DOMAINS, SYS, USER, NONE, SLOT, BOS, EOS, NONE, UNK, DOMAIN_DESC def build_labeler_data(path, slot_meta, tokenizer, slot_desc, ontology, rng, n_choice=5, unk="<unk>", valid_key=[]): data = json.load(open(path, "r", encoding="utf-8")) instances = [] for d in data: did = d["dialogue_idx"] if valid_key and did not in valid_key: continue logs = [] pool, labels = [], [] for log in d["dialogue"]: label = make_dst_target(log["belief_state"], slot_meta) labels.append(label) for l in label: v = split_slot(l) if v not in pool: pool.append(v) value_pool = list(set([p[-1] for p in pool])) for tid, log in enumerate(d["dialogue"]): if log["domain"] not in EXPERIMENT_DOMAINS: continue turn_log = [] if tid > 0 and logs: turn_log.append([SYS] + tokenizer.tokenize(log["system_transcript"])) context = deepcopy(logs[-1]) else: context = [] turn_log.append([USER] + tokenizer.tokenize(log["transcript"])) turn_log = context + turn_log logs.append(turn_log) turn_log = list(chain(*turn_log)) label = labels[tid] for li, (dom, slot, value) in enumerate(pool): if dom not in EXPERIMENT_DOMAINS: continue l = "-".join([dom, slot, value]) if l in label: choices = [value, NONE] else: choices = [NONE] description = rng.choice(slot_desc[dom + "-" + slot][:-1]) hard = [c[-1] for i, c in enumerate(pool) if i != li and c[:2] == (dom, slot)] if hard: choices.extend(hard) n_negatives = n_choice - len(choices) rest = sorted(list(set(value_pool) - set(choices))) while n_negatives > len(rest): n = rng.choice(ontology.get(dom + "-" + slot, [unk])) if n not in choices: rest.append(n) else: rest.append(unk) if n_negatives > 0: negatives = rng.sample(rest, n_negatives) choices.extend(negatives) ins = LabelerInstance(turn_log, f"{did}_{tid}", description, choices[:n_choice], 0, tokenizer.pad_token_id, "dst") ins.processing(tokenizer) instances.append(ins) # active domain description = rng.choice(DOMAIN_DESC) rest_domain = sorted(list(set(EXPERIMENT_DOMAINS) - set([log["domain"]]))) choices = [log["domain"]] + rest_domain ins = LabelerInstance(turn_log, f"{did}_{tid}_domain", description, choices[:n_choice], 0, tokenizer.pad_token_id, "domain_cls") ins.processing(tokenizer) instances.append(ins) return instances class LabelerInstance: def __init__(self, logs, did, description, choices, label=None, pad_token_id=1, task_name="dst", max_seq_length=512): self.did = did self.logs = logs self.description = description self.choices = choices self.label = label self.pad_token_id = pad_token_id self.task_name = task_name self.max_seq_length = max_seq_length def processing(self, tokenizer): ys = [BOS] + self.logs + [EOS] + tokenizer.tokenize(self.description) inputs = [] target_mask = [] for idx, choice in enumerate(self.choices): tokenized_choice = [EOS] + tokenizer.tokenize(choice) + [EOS] input_id = tokenizer.convert_tokens_to_ids(ys + tokenized_choice) # truncation if len(input_id) > self.max_seq_length: gap = len(input_id) - self.max_seq_length input_id = tokenizer.convert_tokens_to_ids([BOS]) + input_id[gap+1:] inputs.append(input_id) if choice == UNK: target_mask.append(0) else: target_mask.append(1) self.input_id = pad_ids(inputs, self.pad_token_id) self.target_mask = target_mask if self.label is not None: not_none_mask = 0. if self.choices[self.label] != NONE: not_none_mask = 1. self.not_none_mask = not_none_mask self.target_id = self.label else: self.target_id = None self.not_none_mask = None def to_dict(self): dic = {} dic["did"] = self.did dic["logs"] = self.logs dic["label"] = self.label dic["choices"] = self.choices dic["description"] = self.description dic["input_id"] = self.input_id dic["target_mask"] = self.target_mask dic["target_id"] = self.target_id dic["not_none_mask"] = self.not_none_mask return dic @classmethod def from_dict(cls, dic): obj = cls(dic["logs"], dic["did"], dic["description"], dic["choices"], dic["label"]) obj.input_id = dic["input_id"] obj.target_mask = dic["target_mask"] obj.target_id = dic["target_id"] obj.not_none_mask = dic["not_none_mask"] return obj class Labelerdataset(Dataset): def __init__(self, data, tokenizer): self.data = data self.pad_id = tokenizer.pad_token_id self.tokenizer = tokenizer self.length = len(data) def __getitem__(self, idx): return self.data[idx] def __len__(self): return self.length def collate_fn(self, batch): input_ids = [torch.LongTensor(b.input_id) for b in batch] target_ids = [b.target_id for b in batch] target_mask = [b.target_mask for b in batch] input_ids = pad_id_of_matrix(input_ids, self.pad_id) target_ids = torch.LongTensor(target_ids) input_mask = input_ids.ne(self.pad_id).float() target_mask = torch.FloatTensor(target_mask) return input_ids, input_mask, target_ids, target_mask class H5Labelerdataset(Dataset): def __init__(self, file_path, tokenizer): self.file_path = file_path self.h5_file = None self.h5_dataset = None with h5py.File(self.file_path, "r") as f: self.length = len(f["data"]) self.pad_id = tokenizer.pad_token_id self.tokenizer = tokenizer def init_hdf5(self): self.h5_file = h5py.File(self.file_path, "r") self.h5_dataset = self.h5_file["data"] def __getitem__(self, idx): if not self.h5_dataset: self.init_hdf5() ins = self.h5_dataset[idx] return LabelerInstance.from_dict(json.loads(ins)) def __len__(self): return self.length def collate_fn(self, batch): input_ids = [torch.LongTensor(b.input_id) for b in batch] target_ids = [b.target_id for b in batch] input_ids = pad_id_of_matrix(input_ids, self.pad_id) target_ids = torch.LongTensor(target_ids) input_mask = input_ids.ne(self.pad_id).float() not_none_mask = torch.FloatTensor([b.not_none_mask for b in batch]) target_mask = [b.target_mask for b in batch] target_mask = torch.FloatTensor(target_mask) return input_ids, input_mask, target_ids, not_none_mask, target_mask
import sys import os import spotipy import spotipy.util as util scope = 'user-top-read' client_id = os.environ['SPOTIPY_CLIENT_ID'] client_secret = os.environ['SPOTIPY_CLIENT_SECRET'] if len(sys.argv) > 1: username = sys.argv[1] else: print("Usage: %s username" % (sys.argv[0],)) sys.exit() token = util.prompt_for_user_token(username, scope, client_id=client_id, client_secret=client_secret, redirect_uri="http://localhost:8888/callback") if token: sp = spotipy.Spotify(auth=token) results = sp.current_user_top_tracks() for item in results['items']: print(item['name'] + ' - ' + item['artists'][0]['name']) else: print("Can't get token for", username)
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np import fastavro from sbsearch import util def define_points(ra, dec, half_size): """Points for SBSearch.add_observations. ra, dec, half_size in radians Returns: [ra_center, dec_center, ra1, dec1, ra2, dec2, ra3, dec3, ra4, dec4] """ d = dec + np.r_[1, 1, -1, -1] * half_size r = ra + np.r_[1, -1, -1, 1] * half_size * np.cos(d) points = [ra, dec, r[0], d[0], r[1], d[1], r[2], d[2], r[3], d[3]] return points def avro2dict(filename): '''read avro data into dictionary''' with open(filename, 'rb') as inf: reader = fastavro.reader(inf) candidate = next(reader, None) return candidate
import os from pathlib import Path import argparse from datetime import timedelta import numpy as np import pandas as pd import matplotlib import matplotlib.pyplot as plt import seaborn as sns import graphviz from sklearn import tree from sklearn.cluster import KMeans from sklearn.metrics import adjusted_rand_score, accuracy_score, confusion_matrix, r2_score from sklearn.metrics import log_loss,auc,classification_report,roc_auc_score, roc_curve from sklearn.model_selection import KFold from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler, label_binarize from sklearn.ensemble import AdaBoostClassifier, ExtraTreesClassifier, BaggingClassifier from sklearn.ensemble import GradientBoostingClassifier, RandomForestClassifier from sklearn.tree import DecisionTreeClassifier, export_graphviz import gbm pd.set_option('display.max_columns', None) def write_to_pickle(dataframe, name): dataframe.to_pickle(data_path + name + ".pickle") def read_from_pickle(name): return pd.read_pickle(data_path + name + ".pickle") data_path = str(Path(os.getcwd())) + "/data/" results_path = str(Path(os.getcwd())) + "/results/random_forests/" #.parents[0] # Args Parser parser = argparse.ArgumentParser(description='Random forests script') # Not sure for labels if I have to say str parser.add_argument('-d','--dataset', nargs="?", type=str, help='Path for dataset to use (csv)',required=True) parser.add_argument('-l','--labels', nargs="+", type=str, help='The exact labels required for splitting the expectancy variable, i.e. 1.5years 4years, more for 3 categories',required=True) parser.add_argument('-v','--values', nargs="+", type=int, help='Values where to split the dataset (in days, i.e. 500 ~ 1.5 years )',required=True) parser.add_argument('-lr','--learning_rate', nargs="?", type=float, help='Learning rate for rf',required=True) parser.add_argument('-o','--output', nargs="+", type=str, help='Output files',required=True) args = parser.parse_args() dataset = args.dataset labels = args.labels cut_points = args.values learning_rate = args.learning_rate output = args.output # Clean up from the imputation df = pd.read_csv(data_path+dataset) df.drop("Unnamed: 0", axis = 1, inplace=True) # Try with three classes first df.loc[:,"life_expectancy_bin"] = gbm.helper.binning(df.life_expectancy, cut_points, labels) #print(pd.value_counts(df_amelia.life_expectancy_bin, sort=False)) print(df.life_expectancy_bin.values) print("\n") # Print the data in the output for column in df: unique_vals = np.unique(df[column]) nr_vals = len(unique_vals) if nr_vals < 20: print('Number of values for attribute {}: {} -- {}'.format(column, nr_vals, unique_vals)) else: print('Number of values for attribute {}: {}'.format(column, nr_vals)) print("\n") non_dummy_cols = ['Tumor_grade','IDH_TERT','life_expectancy','life_expectancy_bin','Gender','IK','Age_surgery'] dummy_cols = list(set(df.columns) - set(non_dummy_cols)) df = pd.get_dummies(df,columns=dummy_cols) df.Gender.replace(to_replace={'M':1, 'F':0},inplace=True) X = df.drop(["life_expectancy","life_expectancy_bin"], axis=1) Y = df.life_expectancy_bin X_train, X_test, Y_train, Y_test = train_test_split(X,Y,train_size=0.8, test_size=0.2, random_state=1332) # Random forests n_estimators based on validation set estimators_range = [5, 10, 20, 50, 100, 200, 300, 400, 500, 1000, 2000] accuracies = [] errors = [] roc_auc = [] cm = [] l = np.array(labels) i=0 for n_estimators in estimators_range: rfc = RandomForestClassifier(criterion='entropy', n_estimators=n_estimators, max_features = 30, max_depth =100, n_jobs = -1, random_state = 1123) rfc.fit(X_train, Y_train) # Accuracy accuracies.append(rfc.score(X_test,Y_test)) # XEntropy Error probas = rfc.predict_proba(X_test) y_pred = np.argmax(probas, axis=1) error = log_loss(Y_test,probas) errors.append(error) # Confusion matrix cfm = confusion_matrix(Y_test, l[y_pred]) cm.append(cfm) # ROC-AUC - I think this is wrong Y_test_binary = label_binarize(Y_test, classes=labels) y_pred_binary = label_binarize(l[y_pred],classes =labels) auc_curve = gbm.evaluation.multi_class_auc(len(l),Y_test_binary,y_pred_binary) roc_auc.append(auc_curve) i+=1 print("Logloss {} --Random Forest Classifier with features = {}, max_depth = {}, estimators = {} -- {}/{}".format(error,rfc.max_features,rfc.max_depth,n_estimators,i,len(estimators_range))) n_estimators_optimal_accuracies = estimators_range[np.argmax(accuracies)] n_estimators_optimal_errors = estimators_range[np.argmin(errors)] print("\n") if not os.path.isdir(results_path): os.mkdir(results_path) fig, ax = plt.subplots(1, 3, figsize=(15,10)) ax[0].scatter(estimators_range, errors) ax[0].set_ylabel('Log-loss error on validation set') ax[0].set_xlabel('Number of estimators for Random Forest Classifier'); ax[1].scatter(estimators_range, accuracies) ax[1].set_ylabel('Accuracies on validation set') ax[1].set_xlabel('Number of estimators for Random Forest Classifier'); ax[2].scatter(estimators_range, roc_auc) ax[2].set_ylabel('AUC on validation set') ax[2].set_xlabel('Number of estimators for Random Forest Classifier'); plt.savefig(results_path + output[0]) print("Saved Results for RF") plt.figure() gbm.evaluation.plot_confusion_matrix(cm[8], norm=True, classes=labels) plt.xlabel('Interpreted cluster label') plt.savefig(results_path + output[1]) print("Saved Confusion Matrix for RF") ''' # Gradient Boosting classifiers based on validation/test estimators_range = [100, 200, 300, 400, 500, 1000, 2000] accuracies = [] errors = [] roc_auc = [] cm = [] l = np.array(labels) i = 0 for n_estimators in estimators_range: gbc = GradientBoostingClassifier(learning_rate = learning_rate, n_estimators=n_estimators, max_depth =30, random_state = 1123) gbc.fit(X_train, Y_train) # Accuracy accuracies.append(gbc.score(X_test,Y_test)) # XEntropy Error probas = gbc.predict_proba(X_test) y_pred = np.argmax(probas, axis=1) errors.append(log_loss(Y_test,probas)) # Confusion matrix cfm = confusion_matrix(Y_test, l[y_pred]) cm.append(cfm) i+=1 print("Gradient Boosting Classifier with lr = {0}, depth = {1}, estimators = {3} -- {4}/7".format(learning_rate,max_depth,n_estimators,i)) # ROC - AUC '''
# from rest_framework.views import APIView from rest_framework import viewsets from rest_framework.response import Response from rest_framework import status from method10.serializers import School, Subject, Teacher, Student, SchoolSerializer, SubjectSerializer, TeacherSerializer,StudentSerializer class StudentNestedViewSet(viewsets.ModelViewSet): queryset = Student.objects.all() serializer_class = StudentSerializer lookup_field = 'id' class TeacherNestedViewSet(viewsets.ModelViewSet): queryset = Teacher.objects.all() serializer_class = TeacherSerializer lookup_field = 'id'
''' ------------------------------------------------------------------------ This module contains utility functions that do not naturally fit with any of the other modules. This Python module defines the following function(s): print_time() compare_args() create_graph_aux() ------------------------------------------------------------------------ ''' # Import packages import numpy as np import os import matplotlib.pyplot as plt from matplotlib.ticker import MultipleLocator ''' ------------------------------------------------------------------------ Functions ------------------------------------------------------------------------ ''' def print_time(seconds, type): ''' -------------------------------------------------------------------- Takes a total amount of time in seconds and prints it in terms of more readable units (days, hours, minutes, seconds) -------------------------------------------------------------------- INPUTS: seconds = scalar > 0, total amount of seconds type = string, either "SS" or "TPI" OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None OBJECTS CREATED WITHIN FUNCTION: secs = scalar > 0, remainder number of seconds mins = integer >= 1, remainder number of minutes hrs = integer >= 1, remainder number of hours days = integer >= 1, number of days FILES CREATED BY THIS FUNCTION: None RETURNS: Nothing -------------------------------------------------------------------- ''' if seconds < 60: # seconds secs = round(seconds, 4) print(type + ' computation time: ' + str(secs) + ' sec') elif seconds >= 60 and seconds < 3600: # minutes mins = int(seconds / 60) secs = round(((seconds / 60) - mins) * 60, 1) print(type + ' computation time: ' + str(mins) + ' min, ' + str(secs) + ' sec') elif seconds >= 3600 and seconds < 86400: # hours hrs = int(seconds / 3600) mins = int(((seconds / 3600) - hrs) * 60) secs = round(((seconds / 60) - hrs * 60 - mins) * 60, 1) print(type + ' computation time: ' + str(hrs) + ' hrs, ' + str(mins) + ' min, ' + str(secs) + ' sec') elif seconds >= 86400: # days days = int(seconds / 86400) hrs = int(((seconds / 86400) - days) * 24) mins = int(((seconds / 3600) - days * 24 - hrs) * 60) secs = round( ((seconds / 60) - days * 24 * 60 - hrs * 60 - mins) * 60, 1) print(type + ' computation time: ' + str(days) + ' days, ' + str(hrs) + ' hrs, ' + str(mins) + ' min, ' + str(secs) + ' sec') def compare_args(contnr1, contnr2): ''' -------------------------------------------------------------------- Determine whether the contents of two tuples are equal -------------------------------------------------------------------- INPUTS: contnr1 = length n tuple contnr2 = length n tuple OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: None OBJECTS CREATED WITHIN FUNCTION: len1 = integer >= 1, number of elements in contnr1 len2 = integer >= 1, number of elements in contnr2 err_msg = string, error message same_vec = (len1,) boolean vector, =True for elements in contnr1 and contnr2 that are the same elem = integer >= 0, element number in contnr1 same = boolean, =True if all elements of contnr1 and contnr2 are equal FILES CREATED BY THIS FUNCTION: None RETURNS: same -------------------------------------------------------------------- ''' len1 = len(contnr1) len2 = len(contnr2) if not len1 == len2: err_msg = ('ERROR, compare_args(): Two tuples have different ' + 'lengths') print(err_msg) same = False else: same_vec = np.zeros(len1, dtype=bool) for elem in range(len1): same_vec[elem] = np.min(contnr1[elem] == contnr2[elem]) same = np.min(same_vec) return same def create_graph_aux(vector, vector_name): ''' -------------------------------------------------------------------- Plot steady-state equilibrium results -------------------------------------------------------------------- INPUTS: vector = (S,) vector, steady-state vector to be plotted OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: OBJECTS CREATED WITHIN FUNCTION: cur_path = string, path name of current directory output_fldr = string, folder in current path to save files output_dir = string, total path of images folder output_path = string, path of file name of figure to be saved S = integer in [3, 80], number of periods an individual lives vector_full = (S+1,) vector, vector with zero appended on end. age_pers_b = (S+1,) vector, ages from 1 to S+1 FILES CREATED BY THIS FUNCTION: vector_name.png RETURNS: None -------------------------------------------------------------------- ''' # Create directory if images directory does not already exist cur_path = os.path.split(os.path.abspath(__file__))[0] output_fldr = 'images' output_dir = os.path.join(cur_path, output_fldr) if not os.access(output_dir, os.F_OK): os.makedirs(output_dir) # Plot steady-state consumption and savings distributions S = vector.shape[0] vector_full = np.append(vector, 0) age_pers_b = np.arange(1, S + 2) fig, ax = plt.subplots() plt.plot(age_pers_b, vector_full, marker='D') # for the minor ticks, use no labels; default NullFormatter minorLocator = MultipleLocator(1) ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.xlim((20, S + 1)) output_path = os.path.join(output_dir, vector_name) plt.savefig(output_path) # plt.show() plt.close() def create_graph_calib(vector, vector_name): ''' -------------------------------------------------------------------- Plot calibration data results -------------------------------------------------------------------- INPUTS: vector = (S,) vector, calibration vector to be plotted vector_name = string, name of image to be saved OTHER FUNCTIONS AND FILES CALLED BY THIS FUNCTION: OBJECTS CREATED WITHIN FUNCTION: cur_path = string, path name of current directory images_fldr = string, folder in current path to save files images_dir = string, total path of images folder images_path = string, path of file name of figure to be saved S = integer in [3, 80], number of periods an individual lives age_pers = (S,) vector, ages from 1 to S FILES CREATED BY THIS FUNCTION: vector_name.png RETURNS: None -------------------------------------------------------------------- ''' # Create directory if images directory does not already exist cur_path = os.path.split(os.path.abspath(__file__))[0] images_fldr = 'images/calibration' images_dir = os.path.join(cur_path, images_fldr) if not os.access(images_dir, os.F_OK): os.makedirs(images_dir) # Plot steady-state consumption and savings distributions S = vector.shape[0] age_pers = np.arange(21, 21 + S) fig, ax = plt.subplots() plt.plot(age_pers, vector, marker='D') # for the minor ticks, use no labels; default NullFormatter minorLocator = MultipleLocator(1) ax.xaxis.set_minor_locator(minorLocator) plt.grid(b=True, which='major', color='0.65', linestyle='-') plt.xlim((20, 20 + S + 1)) images_path = os.path.join(images_dir, vector_name) plt.savefig(images_path) # plt.show() plt.close()
import cPickle import numpy as np import sys from collections import OrderedDict def format_chars(chars_sent_ls): max_leng = max([len(l) for l in chars_sent_ls]) to_pads = [max_leng - len(l) for l in chars_sent_ls] for i, to_pad in enumerate(to_pads): if to_pad % 2 == 0: chars_sent_ls[i] = [0] * (to_pad / 2) + chars_sent_ls[i] + [0] * (to_pad / 2) else: chars_sent_ls[i] = [0] * (1 + (to_pad / 2)) + chars_sent_ls[i] + [0] * (to_pad / 2) return chars_sent_ls def load_bin_vec(fname, vocab): """ Loads word vecs from word2vec bin file """ word_vecs = OrderedDict() with open(fname, "rb") as f: header = f.readline() vocab_size, layer1_size = map(int, header.split()) binary_len = np.dtype('float32').itemsize * layer1_size for line in xrange(vocab_size): word = [] while True: ch = f.read(1) if ch == ' ': word = ''.join(word) break if ch != '\n': word.append(ch) if word in vocab: idx = vocab[word] word_vecs[idx] = np.fromstring(f.read(binary_len), dtype='float32') else: f.read(binary_len) return word_vecs def add_unknown_words(word_vecs, vocab, min_df=1, k=200): """ For words that occur in at least min_df documents, create a separate word vector. 0.25 is chosen so the unknown vectors have (approximately) same variance as pre-trained ones """ for word in vocab: if word not in word_vecs: idx = vocab[word] word_vecs[idx] = np.random.uniform(-0.25,0.25,k) def is_number(s): try: float(s) return True except ValueError: return False def is_user(s): if len(s)>1 and s[0] == "@": return True else: return False def is_url(s): if len(s)>4 and s[:5] == "http:": return True else: return False def digits(n): digit_str = '' for i in range(n): digit_str = digit_str + 'DIGIT' return digit_str def establishdic(fname, gname, hname, binfile): data = open(fname, "rb").readlines() + open(gname, "rb").readlines() + open(hname, "rb").readlines() char_dict = OrderedDict() vocab_dict = OrderedDict() tag_dict = OrderedDict() char_count = 0 vocab_count = 0 tag_count = 0 for line in data: line = line.replace('\n', '').replace('\r', '') line = line.split("\t") if line == ['', ''] or line == [''] or line[0].isdigit() != True: continue vocab = line[1] tag = line[3] if is_number(vocab): # check if the term is a number vocab = digits(len(vocab)) if is_url(vocab): vocab = "URL" if is_user(vocab): vocab = "USR" if vocab not in vocab_dict: vocab_dict[vocab] = vocab_count vocab_count += 1 if tag not in tag_dict: tag_dict[tag] = tag_count tag_count += 1 # generate char dictionary chars = list(vocab) for char in chars: if char not in char_dict: char_dict[char] = char_count char_count += 1 pos_dictionary = OrderedDict() pos_dictionary['words2idx'] = vocab_dict pos_dictionary['labels2idx'] = tag_dict pos_dictionary['chars2idx'] = char_dict wordvec_dict = load_bin_vec(binfile, vocab_dict) add_unknown_words(wordvec_dict, vocab_dict) pos_dictionary['idx2vec'] = wordvec_dict return pos_dictionary def sepdata(fname, gname, hname, pos_dictionary): vocab_dict = pos_dictionary['words2idx'] tag_dict = pos_dictionary['labels2idx'] char_dict = pos_dictionary['chars2idx'] # of all sets dataset_words = [] dataset_labels = [] dataset_chars = [] for f in [fname, gname, hname]: data = open(f, "rb").readlines() # of a whole set words_set = [] tag_labels_set = [] chars_set = [] # of a whole sentence example_words = [] example_tag_labels = [] example_char = [] count = 0 for line in data: line = line.replace('\n', '').replace('\r', '') line = line.split("\t") if (not line[0].isdigit()) and (line != ['']): continue # this is the heading line # this means a example finishes if (line == ['', ''] or line == ['']) and (len(example_words) > 0): words_set.append(np.array(example_words, dtype = "int32")) tag_labels_set.append(np.array(example_tag_labels, dtype = "int32")) chars_set.append(np.array(example_char, dtype = "int32")) # restart a new example after one finishes example_words = [] example_tag_labels = [] example_char = [] count += 1 else: # part of an example vocab = line[1] tag = line[3] if is_number(vocab): # check if the term is a number vocab = digits(len(vocab)) if is_url(vocab): vocab = "URL" if is_user(vocab): vocab = "USR" example_words.append(vocab_dict[vocab]) example_tag_labels.append(tag_dict[tag]) char_word_list = map(lambda u: char_dict[u], list(vocab)) example_char.append(char_word_list) example_char = format_chars(example_char) # for each example do a padding dataset_words.append(words_set) dataset_labels.append(tag_labels_set) dataset_chars.append(chars_set) train_pos= [dataset_words[0], dataset_chars[0], dataset_labels[0]] valid_pos = [dataset_words[1], dataset_chars[1], dataset_labels[1]] test_pos = [dataset_words[2], dataset_chars[2], dataset_labels[2]] assert len(dataset_words[0]+dataset_words[1]+dataset_words[2]) == len(train_pos[0]) + len(valid_pos[0]) + len(test_pos[0]) return train_pos, valid_pos, test_pos def main(): if len(sys.argv) != 6: sys.exit("file paths not specified") binfile = sys.argv[1] fname = sys.argv[2] # train file gname = sys.argv[3] # validation file hname = sys.argv[4] # test file outfilename = sys.argv[5] pos_dictionary = establishdic(fname, gname, hname, binfile) train_pos, valid_pos, test_pos = sepdata(fname, gname, hname, pos_dictionary) print "train pos examples", len(train_pos[0]) print "valid pos examples", len(valid_pos[0]) print "test pos examples", len(test_pos[0]) with open(outfilename + ".pkl", "wb") as f: cPickle.dump([train_pos, valid_pos, test_pos, pos_dictionary], f) print "data %s is generated." % (outfilename + ".pkl") if __name__ == '__main__': main()
#!/usrbin/python #encoding:utf-8 ''' Author: wangxu Email: wangxu@oneniceapp.com 任务更新 ''' import sys reload(sys) sys.setdefaultencoding("utf-8") import logging import tornado.web import json import os import time import datetime import traceback CURRENTPATH = os.path.dirname(os.path.abspath(__file__)) sys.path.append(os.path.join(CURRENTPATH, '../../')) from job_define import Job from generate_files import generate_files,get_session_id from azkaban_api import schedule_flow,execute_flow,fetchexec_flow #web接口类 class JobApiHandler(tornado.web.RequestHandler): #统一调用post方法 def get(self): self.post() #action为操作类型 def post(self): self.username = 'azkaban_api' self.password = 'azkaban_pwd' self.session_id = get_session_id(self.username,self.password) action = self.get_argument('action') method = getattr(self,action) #查询类 get_action = set(['get_alljobs']) if action in get_action: method() else: resp = {'status':200,'message':''} try: result = method() if result!=None: resp = result except Exception,e: logging.info(traceback.format_exc()) resp['status'] = 400 resp['message'] = str(e) logging.info(str(resp)) self.write(json.dumps(resp)) def upload_project(self): #上传结果 project_name = self.get_argument('project_name') result_list = generate_files(self.username,self.session_id,project_name) logging.info(str(result_list)) if len(result_list) == 0: raise Exception('unexist project_name') result = result_list[0] if result['upload_flag'] == 'false': raise Exception(str(result_list)) logging.info('[%s] upload jobs' % (self.username)) def schedule_flow(self): project_name = self.get_argument('project_name') flow_name = self.get_argument('flow_name') schedule_time = self.get_argument('schedule_time') period = self.get_argument('period') result = schedule_flow(self.session_id,project_name,flow_name,schedule_time,period) logging.info(str(result)) def get_alljobs(self): job_list = Job.get_alljobs() jobs = map(lambda x:{'name':x.name,'project_name':x.project_name}, job_list) self.write(json.dumps(jobs)) def delete_job(self): login_user = self.username name = self.get_argument('name') try: job = Job.get_job_fromdb(name) except: raise Exception('not fonud job[%s]' % name) job.updater = login_user flag,mes = job.has_job_permission() logging.info('check job permission [%s] [%s]' % (flag,mes)) if not flag: raise Exception(mes) job.unschedule_flow(self.session_id) job.delete_dependencies() job.delete_job() logging.info('[%s]delete job [%s]' % (login_user,name)) def execute_flow(self): project_name = self.get_argument('project_name') flow_name = self.get_argument('flow_name') param_dict = self.request.arguments del param_dict['action'] result = execute_flow(self.session_id,project_name,flow_name,param_dict) return result def fetchexec_flow(self): execid = self.get_argument('execid') result = fetchexec_flow(self.session_id,execid) return result def update_job(self): login_user = self.username #必需参数 required_args = ['name','project_name','server_host','server_user','server_script','server_dir'] for arg in required_args: self.get_argument(arg) #生成job attr_list = Job.get_attr_list() #dependencies_box = self.get_argument('dependencies_box','') job = Job() #动态加载字段,默认均为字符串 for attr in attr_list: value = str(self.get_argument(attr,'')).strip() if value!='': setattr(job,attr,value) logging.info(attr+':'+value) #默认设置 job.name = job.name.replace('.','-') job.updater = login_user job.update_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) if job.creator == '': job.creator = job.updater job.create_time = job.update_time #更新 flag,mes = job.has_job_permission() logging.info('check job permission [%s] [%s]' % (flag,mes)) if not flag: raise Exception(mes) job.update_job() logging.info('[%s] update job [%s]' % (login_user,job.name))
import unittest class Testing(unittest.TestCase): def test_string(self): a = 'vinod' b = 'vinod' self.assertEqual(a, b) def test_string(self): a = 'vinod' b = 'vinodh' self.assertNotEqual(a, b) if __name__ == '__main__': unittest.main()
# -*- coding: utf-8 -*- from django.http import HttpResponse def home(request): return HttpResponse('olá') def contact(request): return HttpResponse('contact')
import re string = input() pattern = r"(#|\|){1}(?P<item>[a-zA-Z\s]+)\1(?P<date>\d{2}/\d{2}/\d{2})\1(?P<calories>\d{1,5})\1" total_calories = 0 matches = re.finditer(pattern, string) for match in matches: total_calories += int(match['calories']) days = total_calories // 2000 print(f"You have food to last you for: {days} days!") matches = re.finditer(pattern, string) for match in matches: print(f"Item: {match['item']}, Best before: {match['date']}, Nutrition: {match['calories']}")
""" The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. (Please note that the palindromic number, in either base, may not include leading zeros.) """ from pip._vendor.urllib3.connectionpool import xrange def reverse(num): return num[::-1] def isPalindrome(num): rev = reverse(num) if (num == rev): return True return False def doubleBasePalindromes(n): sumOfPal = 0 for num in xrange(11,n): binary = bin(num)[2:] if str(num)[0] == str(num)[len(str(num))-1] and str(binary)[0] == str(binary)[len(str(binary))-1]: if isPalindrome(str(num)) and isPalindrome(str(binary)): sumOfPal += num else: continue return sumOfPal print(doubleBasePalindromes(1000000))
#!/usr/bin/env python # tested with: # - Flask-0.11-py2.py3-none-any.whl on Python 2.7 (OS X 10.10) # - python-flask-0.9-7.el6.noarch on Python 2.6 (CentOS 6) ''' Integration stub / mock DCM API endpoint. ''' from flask import Flask, Response, request import json # `sr.py` can fail with status code 400,404,500 SR_FAIL_WITH=None # `ur.py` can fail with 500; but more likely by not responding UR_FAIL_WITH=None # pydoc doesn't support docstrings for module variables app = Flask(__name__) @app.route('/') def idx(): ''' index page with message pointing to useful urls ''' return 'Mock DCM endpoint is running; you want /ur.py or /sr.py' @app.route('/ur.py', methods=['POST']) def upload_request(): ''' request creation of an upload script. ''' if None != UR_FAIL_WITH: return Response('',status=UR_FAIL_WITH) xdat = json.loads( request.data ) #print('debug: recieved request for creation of transfer script for dataset "%s" for user "%s"' % ( xdat['datasetIdentifier'], xdat['userId'] ) ) data = {} data['status'] = 'OK' resp = Response(response=json.dumps(data), # 202 "accepted" would be more appropriate, but non-200 breaks things status=200, \ mimetype="application/json") return(resp) @app.route('/sr.py', methods=['POST']) def script_request(): ''' request the upload script. "Happy path" only - 404 will be returned in normal use if the script is not available. ''' if None != SR_FAIL_WITH: return Response('',status=SR_FAIL_WITH) dset_id = request.form['datasetIdentifier'] print('debug: recieved script request for dataset "%s" ' % dset_id) with open('rsync.sh', 'r') as myfile: script=myfile.read() data = { 'script' : script ,"datasetIdentifier":dset_id ,"userId":'42' } resp = Response(response=json.dumps(data), status=200, \ mimetype="application/json") return(resp) if __name__ == "__main__": app.run(host='0.0.0.0')
from flask_wtf import FlaskForm from wtforms import StringField, IntegerField, PasswordField, SelectField, HiddenField, FloatField, FormField, FieldList from wtforms.validators import DataRequired, InputRequired, NumberRange, ValidationError from .models import currencies, currency_choices_form def validate_currency(form, field): if field.data == "": raise ValidationError("Sorry, you haven't chosen a currency!") def validate_stock_option(form, field): if(field.data != 0 and field.data != 1): raise ValidationError("Sorry, you haven't chosen an option!") class LoginForm(FlaskForm): team_name = StringField("Team Name", validators=[DataRequired()] ) password = PasswordField("Password", validators=[DataRequired()]) class AdminLoginForm(FlaskForm): user = StringField("Username", validators=[DataRequired()]) password = PasswordField("Password", validators=[DataRequired()]) class ForexForm(FlaskForm): from_currency = SelectField('From', coerce=int, choices=currency_choices_form, validators=[validate_currency]) to_currency = SelectField('To', coerce=int, choices=currency_choices_form, validators=[validate_currency]) amount = FloatField("Amount", validators=[InputRequired(), NumberRange(min=0)]) round = HiddenField() started_at = HiddenField() stonk_options=[ (0, "Buy"), (1, "Sell")] class StockForm(FlaskForm): option = SelectField("Option", coerce=int, choices=stonk_options, validators=[validate_stock_option]) qty = IntegerField("Amount", validators=[InputRequired(), NumberRange(min=0)]) class StockForm_Full(FlaskForm): stox = FieldList(FormField(StockForm), min_entries=2, max_entries=2) round = HiddenField() started_at = HiddenField()
from enum import Enum, IntEnum from itertools import chain from dash.orgs.models import Org from dash.utils import intersection from django_redis import get_redis_connection from django.contrib.auth.models import User from django.core.exceptions import PermissionDenied from django.db import models from django.db.models import Count, Prefetch, Q from django.utils.translation import gettext_lazy as _ from casepro.contacts.models import Contact from casepro.msgs.models import Label, Message, Outgoing from casepro.utils import TimelineItem from casepro.utils.export import BaseSearchExport CASE_LOCK_KEY = "org:%d:case_lock:%s" class CaseFolder(Enum): open = 1 closed = 2 all = 3 class AccessLevel(IntEnum): """ Case access level """ none = 0 read = 1 update = 2 class Partner(models.Model): """ Corresponds to a partner organization """ org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="partners", on_delete=models.PROTECT) name = models.CharField(verbose_name=_("Name"), max_length=128, help_text=_("Name of this partner organization")) description = models.CharField(verbose_name=_("Description"), null=True, blank=True, max_length=255) primary_contact = models.ForeignKey( User, verbose_name=_("Primary Contact"), related_name="partners_primary", null=True, blank=True, on_delete=models.PROTECT, ) is_restricted = models.BooleanField( default=True, verbose_name=_("Restricted Access"), help_text=_("Whether this partner's access is restricted by labels"), ) labels = models.ManyToManyField( Label, verbose_name=_("Labels"), related_name="partners", help_text=_("Labels that this partner can access") ) users = models.ManyToManyField(User, related_name="partners", help_text=_("Users that belong to this partner")) logo = models.ImageField(verbose_name=_("Logo"), upload_to="partner_logos", null=True, blank=True) is_active = models.BooleanField(default=True, help_text="Whether this partner is active") @classmethod def create(cls, org, name, description, primary_contact, restricted, labels, logo=None): if labels and not restricted: raise ValueError("Can't specify labels for a partner which is not restricted") partner = cls.objects.create( org=org, name=name, description=description, primary_contact=primary_contact, logo=logo, is_restricted=restricted, ) if restricted: partner.labels.add(*labels) return partner @classmethod def get_all(cls, org): return cls.objects.filter(org=org, is_active=True) def get_labels(self): return self.labels.filter(is_active=True) if self.is_restricted else Label.get_all(self.org) def get_users(self): return self.users.all() def get_managers(self): return self.get_users().filter(org_editors=self.org_id) def get_analysts(self): return self.get_users().filter(org_viewers=self.org_id) def release(self): self.is_active = False self.save(update_fields=("is_active",)) def as_json(self, full=True): result = {"id": self.pk, "name": self.name} if full: result["restricted"] = self.is_restricted return result def __str__(self): return self.name class case_action(object): """ Helper decorator for case action methods that should check the user is allowed to update the case """ def __init__(self, require_update=True, become_watcher=False): self.require_update = require_update self.become_watcher = become_watcher def __call__(self, func): def wrapped(case, user, *args, **kwargs): access = case.access_level(user) if (access == AccessLevel.update) or (not self.require_update and access == AccessLevel.read): result = func(case, user, *args, **kwargs) if self.become_watcher: case.watchers.add(user) return result else: raise PermissionDenied() return wrapped class Case(models.Model): """ A case between a partner organization and a contact """ org = models.ForeignKey(Org, verbose_name=_("Organization"), related_name="cases", on_delete=models.PROTECT) labels = models.ManyToManyField(Label, help_text=_("Labels assigned to this case")) assignee = models.ForeignKey(Partner, related_name="cases", on_delete=models.PROTECT) user_assignee = models.ForeignKey( User, null=True, on_delete=models.SET_NULL, related_name="cases", help_text="The (optional) user that this case is assigned to", ) contact = models.ForeignKey(Contact, related_name="cases", on_delete=models.PROTECT) initial_message = models.OneToOneField(Message, null=True, related_name="initial_case", on_delete=models.PROTECT) summary = models.CharField(verbose_name=_("Summary"), max_length=255) opened_on = models.DateTimeField(auto_now_add=True, help_text="When this case was opened") closed_on = models.DateTimeField(null=True, help_text="When this case was closed") watchers = models.ManyToManyField( User, related_name="watched_cases", help_text="Users to be notified of case activity" ) @classmethod def get_all(cls, org, user=None, label=None): queryset = cls.objects.filter(org=org) if user: # if user is not an org admin, we should only return cases with partner labels or assignment user_partner = user.get_partner(org) if user_partner and user_partner.is_restricted: queryset = queryset.filter(Q(labels__in=list(user_partner.get_labels())) | Q(assignee=user_partner)) if label: queryset = queryset.filter(labels=label) return queryset.distinct() @classmethod def get_open(cls, org, user=None, label=None): return cls.get_all(org, user, label).filter(closed_on=None) @classmethod def get_closed(cls, org, user=None, label=None): return cls.get_all(org, user, label).exclude(closed_on=None) @classmethod def get_for_contact(cls, org, contact): return cls.get_all(org).filter(contact=contact) @classmethod def get_open_for_contact_on(cls, org, contact, dt): qs = cls.get_for_contact(org, contact) return qs.filter(opened_on__lt=dt).filter(Q(closed_on=None) | Q(closed_on__gt=dt)).first() @classmethod def search(cls, org, user, search): """ Search for cases """ folder = search.get("folder") assignee_id = search.get("assignee") user_assignee_id = search.get("user_assignee") after = search.get("after") before = search.get("before") if folder == CaseFolder.open: queryset = Case.get_open(org, user) elif folder == CaseFolder.closed: queryset = Case.get_closed(org, user) elif folder == CaseFolder.all: queryset = Case.get_all(org, user) else: # pragma: no cover raise ValueError("Invalid folder for cases") if assignee_id: queryset = queryset.filter(assignee__pk=assignee_id) if user_assignee_id: queryset = queryset.filter(user_assignee__pk=user_assignee_id) if after: queryset = queryset.filter(opened_on__gte=after) if before: queryset = queryset.filter(opened_on__lte=before) queryset = queryset.select_related("contact", "assignee", "user_assignee") queryset = queryset.prefetch_related(Prefetch("labels", Label.objects.filter(is_active=True))) return queryset.order_by("-opened_on") @classmethod def get_or_open(cls, org, user, message, summary, assignee, user_assignee=None, contact=None): """ Get an existing case, or open a new case if one doesn't exist. If message=None, then contact is required, and any open case for that contact will be returned. If no open cases exist for the contact, a new case will be created. """ if not message and not contact: raise ValueError("Opening a case requires a message or contact") from casepro.profiles.models import Notification r = get_redis_connection() contact = message.contact if message else contact with r.lock(CASE_LOCK_KEY % (org.pk, contact.uuid), timeout=60): if message: message.refresh_from_db() case = message.case else: message = None case = contact.cases.filter(closed_on=None).first() # if there is already an associated case, return that if case: case.is_new = False return case # suspend from groups, expire flows and archive messages contact.prepare_for_case() case = cls.objects.create( org=org, assignee=assignee, user_assignee=user_assignee, initial_message=message, contact=contact, summary=summary, ) if message: case.labels.add(*list(message.labels.all())) # copy labels from message to new case # attach message and subsequent messages to this case contact.incoming_messages.filter(case=None, created_on__gte=message.created_on).update(case=case) case.is_new = True case.watchers.add(user) action = CaseAction.create(case, user, CaseAction.OPEN, assignee=assignee, user_assignee=user_assignee) notify_users = [user_assignee] if user_assignee else assignee.get_users() for notify_user in notify_users: if notify_user != user: Notification.new_case_assignment(org, notify_user, action) return case def get_timeline(self, after, before, merge_from_backend): local_outgoing = self.outgoing_messages.filter(created_on__gte=after, created_on__lte=before) local_outgoing = local_outgoing.select_related("case", "contact", "created_by").order_by("-created_on") local_incoming = self.incoming_messages.filter(created_on__gte=after, created_on__lte=before) local_incoming = local_incoming.select_related("case", "contact").prefetch_related("labels") local_incoming = local_incoming.order_by("-created_on") # merge local incoming and outgoing timeline = [TimelineItem(msg) for msg in chain(local_outgoing, local_incoming)] if merge_from_backend: # if this is the initial request, fetch additional messages from the backend backend = self.org.get_backend() backend_messages = backend.fetch_contact_messages(self.org, self.contact, after, before) # add any backend messages that don't exist locally if backend_messages: local_backend_ids = {o.backend_id for o in local_outgoing if o.backend_id} local_broadcast_ids = {o.backend_broadcast_id for o in local_outgoing if o.backend_broadcast_id} for msg in backend_messages: if msg.backend_id not in local_backend_ids and msg.backend_broadcast_id not in local_broadcast_ids: timeline.append(TimelineItem(msg)) # fetch and append actions actions = self.actions.filter(created_on__gte=after, created_on__lte=before) actions = actions.select_related("assignee", "user_assignee", "created_by") timeline += [TimelineItem(a) for a in actions] # sort timeline by reverse chronological order return sorted(timeline, key=lambda item: item.get_time()) def add_reply(self, message): message.case = self message.is_archived = True message.save(update_fields=("case", "is_archived")) self.notify_watchers(reply=message) @case_action() def update_summary(self, user, summary): self.summary = summary self.save(update_fields=("summary",)) CaseAction.create(self, user, CaseAction.UPDATE_SUMMARY, note=None) @case_action(require_update=False, become_watcher=True) def add_note(self, user, note): action = CaseAction.create(self, user, CaseAction.ADD_NOTE, note=note) self.notify_watchers(action=action) @case_action() def close(self, user, note=None): if not (self.contact.is_blocked or self.contact.is_stopped): self.contact.restore_groups() action = CaseAction.create(self, user, CaseAction.CLOSE, note=note) self.closed_on = action.created_on self.save(update_fields=("closed_on",)) self.notify_watchers(action=action) # if this is first time this case has been closed, trigger the followup flow if not self.actions.filter(action=CaseAction.REOPEN).exists(): followup = self.org.get_followup_flow() if followup and not (self.contact.is_blocked or self.contact.is_stopped): extra = { "case": { "id": self.id, "assignee": {"id": self.assignee.id, "name": self.assignee.name}, "opened_on": self.opened_on.isoformat(), } } self.org.get_backend().start_flow(self.org, followup, self.contact, extra=extra) @case_action(become_watcher=True) def reopen(self, user, note=None, update_contact=True): self.closed_on = None self.save(update_fields=("closed_on",)) action = CaseAction.create(self, user, CaseAction.REOPEN, note=note) if update_contact: # suspend from groups, expire flows and archive messages self.contact.prepare_for_case() self.notify_watchers(action=action) @case_action() def reassign(self, user, partner, note=None, user_assignee=None): from casepro.profiles.models import Notification self.assignee = partner self.user_assignee = user_assignee self.save(update_fields=("assignee", "user_assignee")) action = CaseAction.create( self, user, CaseAction.REASSIGN, assignee=partner, note=note, user_assignee=user_assignee ) self.notify_watchers(action=action) # also notify users in the assigned partner that this case has been assigned to them notify_users = [user_assignee] if user_assignee else partner.get_users() for notify_user in notify_users: if notify_user != user: Notification.new_case_assignment(self.org, notify_user, action) @case_action() def label(self, user, label): self.labels.add(label) CaseAction.create(self, user, CaseAction.LABEL, label=label) @case_action() def unlabel(self, user, label): self.labels.remove(label) CaseAction.create(self, user, CaseAction.UNLABEL, label=label) @case_action(become_watcher=True) def reply(self, user, text): return Outgoing.create_case_reply(self.org, user, text, self) def update_labels(self, user, labels): """ Updates all this cases's labels to the given set, creating label and unlabel actions as necessary """ current_labels = self.labels.all() add_labels = [l for l in labels if l not in current_labels] rem_labels = [l for l in current_labels if l not in labels] for label in add_labels: self.label(user, label) for label in rem_labels: self.unlabel(user, label) def watch(self, user): if self.access_level(user) != AccessLevel.none: self.watchers.add(user) else: raise PermissionDenied() def unwatch(self, user): self.watchers.remove(user) def is_watched_by(self, user): return user in self.watchers.all() def notify_watchers(self, reply=None, action=None): from casepro.profiles.models import Notification for watcher in self.watchers.all(): if reply: Notification.new_case_reply(self.org, watcher, reply) elif action and watcher != action.created_by: Notification.new_case_action(self.org, watcher, action) def access_level(self, user): """ A user can view a case if one of these conditions is met: 1) they're a superuser 2) they're a non-partner user from same org 3) they're a partner user in partner which is not restricted 4) their partner org is assigned to the case 5) they are specifically assigned to the case 6) their partner org can view a label assigned to the case They can additionally update the case if one of 1-4 is true """ if not user.is_superuser and not self.org.get_user_org_group(user): return AccessLevel.none user_partner = user.get_partner(self.org) if ( user.is_superuser or not user_partner or not user_partner.is_restricted or user_partner == self.assignee or user == self.user_assignee ): return AccessLevel.update elif user_partner and intersection(self.labels.filter(is_active=True), user_partner.get_labels()): return AccessLevel.read else: return AccessLevel.none @property def is_closed(self): return self.closed_on is not None def as_json(self, full=True): if full: return { "id": self.pk, "assignee": self.assignee.as_json(full=False), "user_assignee": self.user_assignee.as_json(full=False) if self.user_assignee else None, "contact": self.contact.as_json(full=False), "labels": [l.as_json(full=False) for l in self.labels.all()], "summary": self.summary, "opened_on": self.opened_on, "is_closed": self.is_closed, } else: return { "id": self.pk, "assignee": self.assignee.as_json(full=False), "user_assignee": self.user_assignee.as_json(full=False) if self.user_assignee else None, } def __str__(self): return "#%d" % self.pk class Meta: indexes = [models.Index(fields=["org", "-opened_on"])] class CaseAction(models.Model): """ An action performed on a case """ OPEN = "O" UPDATE_SUMMARY = "S" ADD_NOTE = "N" REASSIGN = "A" LABEL = "L" UNLABEL = "U" CLOSE = "C" REOPEN = "R" ACTION_CHOICES = ( (OPEN, _("Open")), (ADD_NOTE, _("Add Note")), (REASSIGN, _("Reassign")), (LABEL, _("Label")), (UNLABEL, _("Remove Label")), (CLOSE, _("Close")), (REOPEN, _("Reopen")), ) TIMELINE_TYPE = "A" org = models.ForeignKey(Org, related_name="actions", on_delete=models.PROTECT) case = models.ForeignKey(Case, related_name="actions", on_delete=models.PROTECT) action = models.CharField(max_length=1, choices=ACTION_CHOICES) created_by = models.ForeignKey(User, related_name="case_actions", on_delete=models.PROTECT) created_on = models.DateTimeField(db_index=True, auto_now_add=True) assignee = models.ForeignKey(Partner, null=True, related_name="case_actions", on_delete=models.PROTECT) user_assignee = models.ForeignKey( User, null=True, on_delete=models.SET_NULL, related_name="case_assigned_actions", help_text="The (optional) user that the case was assigned to.", ) label = models.ForeignKey(Label, null=True, on_delete=models.PROTECT) note = models.CharField(null=True, max_length=1024) @classmethod def create(cls, case, user, action, assignee=None, label=None, note=None, user_assignee=None): return CaseAction.objects.create( org=case.org, case=case, action=action, created_by=user, assignee=assignee, label=label, note=note, user_assignee=user_assignee, ) def as_json(self): return { "id": self.pk, "action": self.action, "created_by": self.created_by.as_json(full=False), "created_on": self.created_on, "assignee": self.assignee.as_json() if self.assignee else None, "user_assignee": self.user_assignee.as_json() if self.user_assignee else None, "label": self.label.as_json() if self.label else None, "note": self.note, } class Meta: indexes = [models.Index(fields=["org", "-created_on"])] class CaseExport(BaseSearchExport): """ An export of cases """ directory = "case_exports" download_view = "cases.caseexport_read" def get_search(self): search = super(CaseExport, self).get_search() search["folder"] = CaseFolder[search["folder"]] return search def render_search(self, book, search): from casepro.contacts.models import Field base_fields = [ "Message On", "Opened On", "Closed On", "Assigned Partner", "Labels", "Summary", "Messages Sent", "Messages Received", "Contact", ] contact_fields = Field.get_all(self.org, visible=True) all_fields = base_fields + [f.label for f in contact_fields] # load all messages to be exported items = Case.search(self.org, self.created_by, search) items = items.select_related("initial_message") # need for "Message On" items = items.annotate( incoming_count=Count("incoming_messages", distinct=True), outgoing_count=Count("outgoing_messages", distinct=True), ) def add_sheet(num): sheet = book.add_sheet(str(_("Cases %d" % num))) self.write_row(sheet, 0, all_fields) return sheet sheet = None sheet_number = 0 row = 1 for item in items: if not sheet or row > self.MAX_SHEET_ROWS: sheet_number += 1 sheet = add_sheet(sheet_number) row = 1 values = [ item.initial_message.created_on if item.initial_message else "", item.opened_on, item.closed_on, item.assignee.name, ", ".join([l.name for l in item.labels.all()]), item.summary, item.outgoing_count, # subtract 1 for the initial messages item.incoming_count - 1 if item.initial_message else item.incoming_count, item.contact.uuid, ] fields = item.contact.get_fields() for field in contact_fields: values.append(fields.get(field.key, "")) self.write_row(sheet, row, values) row += 1
# https://www.urionlinejudge.com.br/judge/pt/problems/view/ import unittest from desrugenstein import desrugenstein """ N S O L 4 |0 1 0 1 (0, 3)| 0 0 1 0 (1, 3) | 0 0 0 1 (2, 3) | 0 1 0 0 (3, 3) |0 0 0 0 (0, 2)| 1 0 0 1 (1, 2) | 0 0 0 1 (2, 2) | 0 1 0 0 (3, 2) |1 0 0 0 (0, 1)| 1 0 1 0 (1, 1) | 1 1 0 0 (2, 1) | 0 1 1 0 (3, 1) |0 0 0 0 (0, 0)| 0 0 1 0 (1, 0) | 0 0 1 0 (2, 0) | 0 0 0 0 (3, 0) 5 x y x y 1 3 0 3 2 3 3 0 2 3 0 0 3 1 3 2 0 3 0 0 0 """ class DesrugensteinTestCase(unittest.TestCase): def test_custo_impossible(self): cidade = [ [[0, 1, 0, 1], [0, 0, 0, 0]], ] rotas = [ [[1, 0],[0, 0]], ] self.assertEqual(desrugenstein(cidade, rotas), "Impossible") def test_custo_1(self): cidade = [ [[0, 1, 0, 1], [0, 0, 1, 0]], ] rotas = [ [[1, 0], [0, 0]], ] self.assertEqual(desrugenstein(cidade, rotas), 1) def test_custo_2(self): cidade = [ [[0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 1, 0]], ] rotas = [ [[2, 0],[0, 0]], ] self.assertEqual(desrugenstein(cidade, rotas), 2) def test_custo_3(self): cidade = [ [[0, 1, 0, 1], [0, 0, 1, 0], [0, 0, 1, 0], [0, 0, 1, 0]] ] rotas = [ [[3, 0],[0, 0]], ] self.assertEqual(desrugenstein(cidade, rotas), 3) def test_custo_2_no_meio(self): cidade = [ [[0, 1, 0, 1], [0, 0, 0, 1], [0, 0, 1, 0]] ] rotas = [ [[1, 0],[2, 0]], ] self.assertEqual(desrugenstein(cidade, rotas), 1) if __name__ == '__main__': unittest.main()
import threading import socket import sys import time from drone import drone # このプログラムを実行するPCのアドレス host = '192.168.11.2' # droneA との通信でのPC側のアドレス portA = int(9000) locaddrA = (host,portA) # droneB との通信でのPC側のアドレス portB = int(9001) locaddrB = (host,portB) # droneA/droneB のアドレス addressA = '192.168.11.65' addressB = '192.168.11.64' # droneを制御するためのオブジェクトを作成 droneA = drone(addressA, host, portA) droneB = drone(addressB, host, portB) # コマンドの送信先としてdroneを配列に格納 drones = {droneA, droneB} # droneに送信するコマンドの配列※順番に実行 command_dict = [ 'takeoff', 'forward 50', 'right 50', 'back 70', 'left 50', 'land', ] print ('formation flight start\n') # コマンド配列の中の実行対象を特定するindex command_index = 0 # command コマンドを全droneに送信、コマンドを受け付ける状態にする for drone in drones: drone.connect() drone.send_command('command') while True: try: #次に実行するコマンド step_command = command_dict[command_index] accepted = 0 #全機がコマンド送信可能状態になるまで待つ for drone in drones: if drone.is_accept_command: accepted += 1 if accepted == len(drones): break if accepted == len(drones): for drone in drones: #全機にコマンド送信 drone.send_command(step_command) #コマンド位置を進め次のコマンドに command_index += 1 # コマンド送信後に固定の待ち時間を追加 time.sleep(2) # 離陸コマンドを実行したあとは長めのインターバル if step_command == 'takeoff': time.sleep(6) # 着陸コマンドを実行したあとは抜ける if step_command == 'land': break # accept検査のインターバル time.sleep(0.1) except Exception as e: tb = sys.exc_info()[2] print (e.with_traceback(tb)) # droneとの通信を終了 for drone in drones: drone.disconnect() print ('\nformation flight end')
from marshmallow import fields, Schema __all__ = [ "Event", "InstalledAppRequest", "InstalledApp" ] class Event(Schema): id = fields.UUID(required=True) created = fields.DateTime(required=True) updated = fields.DateTime(required=True) event_time = fields.DateTime(required=True) event_type_slug = fields.String(required=True) data = fields.Dict(required=True) class InstalledAppRequest(Schema): app_slug = fields.String(required=True) config = fields.Dict(allow_none=True) scopes = fields.List(fields.String()) class InstalledApp(InstalledAppRequest): id = fields.UUID(required=True) created = fields.DateTime() updated = fields.DateTime() _links = fields.Dict(keys=fields.String(), values=fields.Url())
import numpy as np import matplotlib.pyplot as plt from time import time import boss_problems, boss_embed, boss_bayesopt np.random.seed(0) #problem = 'motif' problem = 'tfbind' #problem = 'tfbind-small' if problem == 'motif': seq_len = 8 noise = 0.1 oracle, oracle_batch, Xall, yall, Xtrain, ytrain, train_ndx = boss_problems.motif_problem( seq_len, noise) hparams = {'epochs': 10, 'nlayers': 2, 'nhidden': 10, 'embed_dim': 5, 'seq_len': seq_len} if problem == 'tfbind': oracle, oracle_batch, Xall, yall, Xtrain, ytrain, train_ndx = boss_problems.tfbind_problem( lower_bin=50, upper_bin=99) seq_len = np.shape(Xall)[1] hparams = {'epochs': 30, 'nlayers': 4, 'nhidden': 100, 'embed_dim': 64, 'seq_len': seq_len} if problem == 'tfbind-small': max_nseq=20000 # Use a subset of the data for rapid prototyping oracle, oracle_batch, Xall, yall, Xtrain, ytrain, train_ndx = boss_problems.tfbind_problem( lower_bin=50, upper_bin=99, max_nseq=max_nseq) seq_len = np.shape(Xall)[1] hparams = {'epochs': 10, 'nlayers': 3, 'nhidden': 50, 'embed_dim': 32, 'seq_len': seq_len} # Plot the GT function nseq = np.shape(Xall)[0] plt.figure() plt.plot(range(nseq), yall, 'b') plt.plot(train_ndx, ytrain, 'r') m = np.max(yall) s = np.std(yall) maxima = np.where(yall >= m-1*s)[0] plt.title('{} seq, {} maxima of value {:0.3f}'.format(len(yall), len(maxima), m)) plt.show() # Fit a supervised predictor time_start = time() np.random.seed(1) predictor = boss_embed.learn_supervised_model(Xtrain, ytrain, hparams) print('time spent training {:0.3f}\n'.format(time() - time_start)) ypred = predictor.predict(Xall) plt.figure() plt.scatter(yall, ypred) plt.xlabel('True Values') plt.ylabel('Predictions') plt.show() # Extract embedding function and visualize embedding space embedder = boss_embed.convert_supervised_to_embedder(predictor, hparams) Z = embedder.predict(Xtrain) plt.figure() plt.scatter(Z[:,0], Z[:,1], c=ytrain) plt.title('embeddings of training set') plt.colorbar() plt.show() # Are distances in embedding space correalted with differences in the target? from sklearn.metrics.pairwise import pairwise_distances sources = np.arange(4) dist_matrix = pairwise_distances(Z[sources], Z) nearest = np.argsort(dist_matrix, axis=1) knn = min(nseq, 100) fig, ax = plt.subplots(2,2,figsize=(10,10)) for i, source in enumerate(sources): ysource = oracle(Xall[source]) nbrs = nearest[source, 0:knn]; dst = dist_matrix[source, nbrs]; ytargets = oracle_batch(Xall[nbrs]) #plt.figure() r = i // 2 c = i % 2 ax[r,c].plot(dst, ytargets-ysource, 'o') ax[r,c].set_title('s={}'.format(source)) plt.xlabel('distance(s,t) in embedding space vs t') plt.ylabel('f(s)-f(t)') plt.show() ######## from boss_bayesopt import BayesianOptimizerEmbedEnum, RandomDiscreteOptimizer, expected_improvement from sklearn.gaussian_process import GaussianProcessRegressor from sklearn.gaussian_process.kernels import ConstantKernel, Matern noise = 1e-5 # np.std(yinit) # We tell EI the objective is noise free so that it trusts # the current best value, rather than re-evaluating previous queries. def EI(X, X_sample, Y_sample, surrogate): X = np.atleast_2d(X) return expected_improvement(X, X_sample, Y_sample, surrogate, improvement_thresh=0.01, trust_incumbent=True) # Different embedding functions before applying kernel # Ground truth z(x) = f*(x) def oracle_embed_fn(X): return np.reshape(oracle_batch(X), (-1,1)) # Proxy z(x) = f-hat(x) def predictor_embed_fn(X): return predictor.predict(X, batch_size=1000) # MLP features z(x) = h(x) from MLP def super_embed_fn(X): return embedder.predict(X, batch_size=1000) # One-hot encode integers before passing to kernel from sklearn.preprocessing import OneHotEncoder alpha_size = 4 cat = np.array(range(alpha_size)); cats = [cat]*seq_len enc = OneHotEncoder(sparse=False, categories=cats) enc.fit(Xall) # One-hot embedding def onehot_embed_fn(X): return enc.transform(X) #Xhot = enc.transform(X) #Xcold = enc.inverse_transform(Xhot) #assert (Xcold==X).all() n_bo_iter = 5 n_bo_init = 10 # # Before starting BO, we perform N random queries nseq = np.shape(Xall)[0] def do_expt(seed): np.random.seed(seed) perm = np.random.permutation(nseq) perm = perm[:n_bo_init] Xinit = Xall[perm] yinit = yall[perm] rnd_solver = RandomDiscreteOptimizer(Xall, n_iter=n_bo_iter+n_bo_init) # We use Matern kernel 1.5 since this only assumes first-orer differentiability. kernel = ConstantKernel(1.0) * Matern(length_scale=1.0, nu=1.5) # The GPR object gets mutated by the solver so we need to create # new instances gpr = GaussianProcessRegressor(kernel=kernel, alpha=noise**2) acq_fn = EI # These methods embed all strings in Xall using specified embedder # and apply kernel and pick best according to EI gpr = GaussianProcessRegressor(kernel=kernel, alpha=noise**2) bo_oracle_embed_solver = BayesianOptimizerEmbedEnum( Xall, oracle_embed_fn, Xinit, yinit, gpr, acq_fn, n_iter=n_bo_iter) gpr = GaussianProcessRegressor(kernel=kernel, alpha=noise**2) bo_predictor_embed_solver = BayesianOptimizerEmbedEnum( Xall, predictor_embed_fn, Xinit, yinit, gpr, acq_fn, n_iter=n_bo_iter) gpr = GaussianProcessRegressor(kernel=kernel, alpha=noise**2) bo_super_embed_solver = BayesianOptimizerEmbedEnum( Xall, super_embed_fn, Xinit, yinit, gpr, acq_fn, n_iter=n_bo_iter) gpr = GaussianProcessRegressor(kernel=kernel, alpha=noise**2) bo_onehot_embed_solver = BayesianOptimizerEmbedEnum( Xall, onehot_embed_fn, Xinit, yinit, gpr, acq_fn, n_iter=n_bo_iter) methods = [] methods.append((bo_oracle_embed_solver, 'BO-oracle-embed-enum')) methods.append((bo_predictor_embed_solver, 'BO-predictor_embed-enum')) methods.append((bo_super_embed_solver, 'BO-super-embed-enum')) methods.append((bo_onehot_embed_solver, 'BO-onehot-enum')) methods.append((rnd_solver, 'RndSolver')) # Always do random last ytrace = dict() for solver, name in methods: print("Running {}".format(name)) time_start = time() solver.maximize(oracle) print('time spent by {} = {:0.3f}\n'.format(name, time() - time_start)) ytrace[name] = np.maximum.accumulate(solver.val_history) plt.figure() styles = ['k-o', 'r:o', 'b--o', 'g-o', 'c:o', 'm--o', 'y-o'] for i, tuple in enumerate(methods): style = styles[i] name = tuple[1] plt.plot(ytrace[name], style, label=name) plt.axvline(n_bo_init) plt.legend() plt.title("seed = {}".format(seed)) plt.show() seeds = [0, 1, 2] #seeds = [0] for seed in seeds: do_expt(seed)
from django.db.models import Q from django.shortcuts import render, redirect from django.http import HttpResponse, Http404, HttpResponseRedirect from django.views.generic import TemplateView, UpdateView, View, DetailView, CreateView from django.core.urlresolvers import reverse from django.contrib import messages from django.shortcuts import redirect, get_object_or_404 from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from django.contrib.auth.decorators import login_required, user_passes_test from django.utils.decorators import method_decorator from statuses import * from datetime import datetime import re from .models import * class PantryView(TemplateView): """ This view displays the user's pantry """ template_name = "lists/pantry.html" @method_decorator(login_required) def dispatch(self, request, *args, **kwargs): """ Ensures that only authenticated users can access the view. """ return super(PantryView, self).dispatch(request, *args, **kwargs) def get_context_data(self, **kwargs): context = super(PantryView, self).get_context_data(**kwargs) user = UserProfile.objects.get(user=self.request.user) party = Party.objects.get(name=user.name+"'s Personal Party") pantry = Pantry.objects.get(party=party) context['party'] = party context['pantry'] = pantry context['pantry_items'] = pantry.items.all() return context class PartyPantryView(TemplateView): """ This view displays the pantry for a party """ template_name = "lists/pantry.html" @method_decorator(login_required) def dispatch(self, *args, **kwargs): user = self.request.user.profile party_id = kwargs['party_id'] try: party_obj = Party.objects.get(id=party_id) party_users = party_obj.users.all() party_owner = party_obj.owner except : return redirect("/") # Only allow access to page if user is owner or user of party if party_owner == user or user in party_users: return super(PartyPantryView, self).dispatch(*args, **kwargs) else: messages.add_message(self.request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>:&nbsp;&nbsp;Sorry, you aren't allowed to access that pantry." + ALERT_CLOSE) return redirect("/") def get_context_data(self, **kwargs): context = super(PartyPantryView, self).get_context_data(**kwargs) party_id = kwargs['party_id'] party = Party.objects.get(id=party_id) pantry = Pantry.objects.get(party=party) context['party'] = party context['pantry'] = pantry context['pantry_items'] = pantry.items.all() return context class AddItemToPantryView(View): """ This view adds an item from a shopping list to a user's Pantry """ def post(self, request, *args, **kwargs): item_name = request.POST.get('add-item-to-pantry-name', False).title() item_description = request.POST.get('add-item-to-pantry-desc', False).capitalize() list_id = request.POST.get('list_id', False) from_url = request.POST.get('from_url', False) party_id = request.POST.get('party-id', False) if from_url == "/pantry/" or from_url == "/pantry/" + str(party_id) + "/": list_id = str(-1) # Don't allow blank item names if item_name == "": messages.add_message(request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>&nbsp;: You must supply a name to add an item to your pantry!" + ALERT_CLOSE, extra_tags=int(list_id)) return redirect(from_url + "#" + list_id) try: item_detail_obj, c = ItemDetail.objects.get_or_create(name=item_name, description=item_description) # User's pantry object user_userprofile = UserProfile.objects.get(name=request.user.username) user_party = Party.objects.get(id=party_id) pantry_obj = Pantry.objects.get(party=user_party) # don't add duplicate items if item_detail_obj.name in [x.name for x in pantry_obj.items.all()]: messages.add_message(request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>&nbsp;: That item already exists in your pantry!" + ALERT_CLOSE, extra_tags=int(list_id)) return redirect(from_url + "#" + list_id) pantry_obj.items.add(item_detail_obj) # successful, return to lists page with success message messages.add_message(request, messages.SUCCESS, ALERT_SUCCESS_OPEN + "<strong>SUCCESS:&nbsp;" + str(item_name) + "</strong>&nbsp;&nbsp;has been added to your pantry!" + ALERT_CLOSE, extra_tags=int(list_id)) return redirect(from_url + "#" + list_id) # Something went wront creating the Item Detail, give them an error except: messages.add_message(request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>&nbsp;: Unable to create ItemDetail for that item. Please let a developer know!" + ALERT_CLOSE, extra_tags=int(list_id)) return redirect(from_url + "#" + list_id) class EditItemInPantryView(View): def post(self, request, *args, **kwargs): item_name = request.POST.get('edit-item-in-pantry-name', False) item_description = request.POST.get('edit-item-in-pantry-desc', False) amount = request.POST.get('edit-item-in-pantry-stock', False) units = request.POST.get('edit-item-in-pantry-unit', False) cost = request.POST.get('edit-item-in-pantry-cost', False) location_purchased = request.POST.get('edit-item-in-pantry-location-purchased', False) list_id = request.POST.get('list_id', False) from_url = request.POST.get('from_url', False) party_id = request.POST.get('party-id', False) date_pattern = re.compile('(0[1-9]|1[012])[- \/.](0[1-9]|[12][0-9]|3[01])[- \/.](19|20)\d\d') last_purchased_str = request.POST.get('edit-item-in-pantry-last-purchased', False) expiration_date_str = request.POST.get('edit-item-in-pantry-expiration-date', False) # If coming from pantry, we don't need to un-collapse a list or show message in specific place if from_url == "/pantry/" or from_url == "/pantry/" + str(party_id) + "/": list_id = str(-1) # convert empty values to zero for non-required data if amount == "": amount = float(0) else: amount = float(amount) if cost == "" or cost == "---": cost = float(0) else: cost = float(cost) # Don't let user supply zero amount if amount == float(0): messages.add_message(request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>&nbsp;: You must fill out the amount field to add <strong>&nbsp;" + item_name + "</strong>&nbsp;&nbsp;to your pantry. Try again!" + ALERT_CLOSE, extra_tags=int(list_id)) return redirect(from_url + "#" + list_id) # If last_purchased and expiration_date are proper dates, make datetime objects for them # else, create minimum datetime objects if date_pattern.match(last_purchased_str): month, day, year = map(int,last_purchased_str.split("/")) last_purchased = datetime(month=month, day=day, year=year) else: last_purchased = datetime.min if date_pattern.match(expiration_date_str): month, day, year = map(int,expiration_date_str.split("/")) expiration_date = datetime(month=month, day=day, year=year) else: expiration_date = datetime.min # Get ItemDetail object from pantry and update the values try: # User's pantry object user_userprofile = UserProfile.objects.get(name=request.user.username) user_party = Party.objects.get(id=party_id) pantry_obj = Pantry.objects.get(party=user_party) pantry_items = pantry_obj.items.all() item_detail_obj = pantry_items.filter(name=item_name, description=item_description) item_detail_obj.update(name=item_name, description=item_description, cost=cost, last_purchased=last_purchased, location_purchased=location_purchased, barcode=-1, unit=units, amount=amount, expiration_date=expiration_date) # successful, return to lists page with success message messages.add_message(request, messages.SUCCESS, ALERT_SUCCESS_OPEN + "<strong>SUCCESS</strong>&nbsp;: " + str(amount) + " " + str(units) + " of " + str(item_name) + " has been added to your pantry!" + ALERT_CLOSE, extra_tags=int(list_id)) return redirect(from_url + "#" + list_id) # Something went wront creating the Item Detail, give them an error except: messages.add_message(request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>&nbsp;: Unable to update the values for <strong>&nbsp;" + item_name + "</strong>&nbsp;. Please let a developer know!" + ALERT_CLOSE, extra_tags=int(list_id)) return redirect(from_url + "#" + list_id) class RemoveItemFromPantryView(View): def post(self, request, *args, **kwargs): item_id = request.POST.get('item_id', False) from_url = request.POST.get('from_url', False) party_id = request.POST.get('party-id', False) # Get the user's pantry object party_obj = Party.objects.get(id=party_id) pantry_obj = Pantry.objects.get(party=party_obj) item_obj = pantry_obj.items.get(id=item_id) # remove the item from the pantry try: pantry_obj.items.remove(item_obj) if 'Personal' in party_obj.name: messages.add_message(request, messages.SUCCESS, ALERT_SUCCESS_OPEN + "<strong>SUCCESS</strong>&nbsp;: Removed <strong>&nbsp;" + item_obj.name + "</strong>&nbsp; from " + pantry_obj.party.owner.name + "'s pantry." + ALERT_CLOSE, extra_tags=int(item_id)) else: messages.add_message(request, messages.SUCCESS, ALERT_SUCCESS_OPEN + "<strong>SUCCESS</strong>&nbsp;: Removed <strong>&nbsp;" + item_obj.name + "</strong>&nbsp; from " + pantry_obj.party.name + "'s pantry." + ALERT_CLOSE, extra_tags=int(item_id)) return redirect(from_url + "#" + item_id) except: if 'Personal' in party_obj.name: messages.add_message(request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>&nbsp;: Unable to remove <strong>&nbsp;" + item_obj.name + "</strong>&nbsp; from " + pantry_obj.party.owner.name + "'s pantry. Please let a developer know!" + ALERT_CLOSE, extra_tags=int(item_id)) else: messages.add_message(request, messages.ERROR, ALERT_ERROR_OPEN + "<strong>ERROR</strong>&nbsp;: Unable to remove <strong>&nbsp;" + item_obj.name + "</strong>&nbsp; from " + pantry_obj.party.name + "'s pantry. Please let a developer know!" + ALERT_CLOSE, extra_tags=int(item_id)) return redirect(from_url + "#" + item_id)