# Admin Social Network

# Django
from django.contrib import admin

# Local | Model
from .models import SocialNetwork

# Register your models here.
class SocialNetworkAdmin(admin.ModelAdmin):
    """
    Custom administrator: Social Network
    """

    list_display = (
        'name',
        'url',
        'key',
    )

    search_fields = (
        'name',
    )

    list_filter = (
        'created',
        'updated',
    )

    readonly_fields = (
        'created',
        'updated',
        )

# Register
admin.site.register(SocialNetwork, SocialNetworkAdmin)


'''
Given two strings s and t, write a function to determine if t is an anagram of s.

For example,
s = "anagram", t = "nagaram", return true.
s = "rat", t = "car", return false.

Note:
You may assume the string contains only lowercase alphabets.

Follow up:
What if the inputs contain unicode characters? How would you adapt your solution to such case?
'''
import string

def is_anagram(s, t):
    letters = list(string.ascii_lowercase)

    for l in letters:
        if s.count(l) != t.count(l):
            return False

    return True

'''
Given a string `s` and a non-empty string `p`, find all the start indices of `p's` anagram in `s`.

String consists of lowercase English letters only and the length of both strings `s` and `p`
will not be larger than 20,000

The order of output does not matter

Example 1:
Input:
    s: "cbaebabacd" p: "abc"

Output:
    [0,6]

Explanation:
    The substring with start index = 0 is "cba", which is an anagram of "abc"
    The substring with start index = 6 is "bac", which is an anagram of "abc"

Example 2:
Input:
    s: "abab" p: "ab"

Output:
    [0,1,2]

Explanation:
    The substring with start index = 0 is "ab", which is an anagram of "ab"
    The substring with start index = 1 is "ba", which is an anagram of "ab"
    The substring with start index = 2 is "ab", which is an anagram of "ab"
'''

from collections import Counter

class Solution:

    def find_anagrams(self, s, p):

        res = []
        p_counter = Counter(p)
        s_counter = Counter(s[:len(p)-1])

        for i in range(len(p) - 1, len(s)):
            s_counter[s[i]] += 1 # include the new char in the window

            if s_counter == p_counter: # This step is O(1), since there are at most 26 English letters
                res.append(i - len(p) + 1) # Append the starting index

            s_counter[s[i - len(p) + 1]] -= 1 # Decrease the count of oldest char in the window
            if s_counter[s[i - len(p) + 1]] == 0:
                del s_counter[s[i - len(p) + 1]] # Remove the count if it is 0

        return res


#Initial Commit
#This creates a base object of each class using my own information and
#will use that to test all of the functionallity
#@author A1C Jake Brower 12/31/2020

#this allows me to reference the objects made in classes.py
import classes
#A premade object that represents dates, used in some of my made classes
from datetime import date
#So i can make a list of every object ill be utilizing
from typing import List

#all of this information is from the excel sheet, DOES NOT PULL FROM THE GOOGLE SHEET
name = "Jake Brower"
rank = "A1C"
crewPos = "MSO"
isOnLeave = False
scheduledLeave = None
isoOrRom = False
hundredPercentContact = "Capt Wright"
zoom = "jacobbrower96@gmail.com"
lineSqd = None
dateArrived = date(2020, 7, 13)
classNumber = "20 LAT"
shift = 8
projStartDate = date(2020, 9, 24)
hasPolicyLit = True
cbts = [classes.cbt(True, "CBT 1"), classes.cbt(False, "CBT 2")]
afe = True
crm = True
sec = 2 #0 for bad 1 for s 2 for ts
hasLineBadge = True
hasRedBadge = True
hasRips = True
ipadStatus = 1 #0 for not submitted 1 for submitted 2 for has iPad
hasPHA = True
checkedInWithSarm = True
checkedInWithHarm = True
hasHeadset = True
hasPubs = True
hasGtc = True
updatedDogTags = True
hasFlightGear = True
completedFTAC = True
sereInfo = classes.sere(True, True, date(2020, 8, 31))
hasLOA = True
hasAuth = True
hasVoucher = True
obCBTestStatus = 0 #not sure what this is
completionRep = classes.completionReport(True, False, True, False, False, "This is a comment for A1C Jake Brower")
remarks = "This is a remark for A1C Jake Brower :) ME!!!"
#End of the variables to make 1 airmen object then I get to run tests :)

#This very long line is the test for making the airmen object
a1cJakeBrower = classes.airmen(name, rank, crewPos, isoOrRom, hundredPercentContact, dateArrived, sec, sereInfo, remarks)


"""This script defines the command line entry point for cell anneal and
implements a pipeline including identification of highly variable genes,
deconvolution of each bulk sample, ouput of deconvolution results and
production of a set of plots."""

import argparse
from pathlib import Path
import pandas as pd

from .pipelines import cellanneal_pipe

def init_parser(parser):
    """Initialize parser arguments."""
    parser.add_argument(
        'bulk_data_path', type=str,
        help=("""Path to bulk data file, csv format with sample names as
            columns and genes as rows.""")
    )

    parser.add_argument(
        'celltype_data_path', type=str,
        help=("""Path to celltype reference data file, csv format with sample
            names as columns and genes as rows. """)
    )

    parser.add_argument(
        'output_path', type=str,
        help=("""Path to folder in which to store the results. """)
    )

    parser.add_argument(
        '--bulk_min', type=float, default=1e-5,
        help=("""Minimum relative expression in the bulk sample for a gene
            to be considered.""")
    )

    parser.add_argument(
        '--bulk_max', type=float, default=0.01,
        help=("""Maximum relative expression in the bulk sample for a gene
            to be considered.""")
    )

    parser.add_argument(
        '--disp_min', type=float, default=0.5,
        help=("""Minimum scaled dispersion (var/mean) relative to other
            genes of similar expression for a gene to be considered.""")
    )

    parser.add_argument(
        '--maxiter', type=int, default=1000,
        help=("""Number of initial values from which to run simulated
            annealing.""")
    )

    return parser

def main():
    """ cellanneal. User-friendly deconvolution of bulk RNA-Seq data.

    Deconvovles bulk RNA-Seq data into single-cell populations based
    on Spearman's correlation between bulk sample gene expression and
    single-cell based mixture gene expression. Simulated annealing is
    used to find the optimal mixture.

    Input:
            bulk_data_path
            celltype_data_path
            output_path
            bulk_min
            bulk_max
            disp_min
            maxiter

    Output:

    Example:

    """
    # get a parser object, initialise the inputs and read them into args
    my_parser = argparse.ArgumentParser(
        description=('cellanneal deconvolves bulk RNA-Seq data.'))
    args = init_parser(my_parser).parse_args()

    # grab the individual inputs for further use
    bulk_data_path = Path(args.bulk_data_path)
    celltype_data_path = Path(args.celltype_data_path)
    output_path = Path(args.output_path)
    bulk_min = args.bulk_min
    bulk_max = args.bulk_max
    disp_min = args.disp_min
    maxiter = args.maxiter

    print("\nWelcome to cellanneal!\n")

    """ 1) Import bulk and cell type data """
    print('1A. Importing bulk data ...')
    try:
        bulk_df = pd.read_csv(bulk_data_path, index_col=0, header=0)
        # here, in order to make further course case insensitive,
        # change all gene names to uppercase only
        bulk_df.index = bulk_df.index.str.upper()
        # also, if there are duplicate genes, the are summed here
        bulk_df = bulk_df.groupby(bulk_df.index).sum()
        bulk_names = bulk_df.columns.tolist()
        print('{} bulk samples identified: {}\n'.format(len(bulk_names),
                                                        bulk_names))
    except:
        print("""Your bulk data file could not be imported.
        Please check the documentation for format requirements
        and look at the example bulk data files.""")

    print('1B. Importing celltype reference data ...')
    # import single cell based reference
    try:
        celltype_df = pd.read_csv(celltype_data_path, index_col=0, header=0)
        # here, in order to make further course case insensitive,
        # change all gene names to uppercase only
        celltype_df.index = celltype_df.index.str.upper()
        # also, if there are duplicate genes, the are summed here
        celltype_df = celltype_df.groupby(celltype_df.index).sum()
        celltypes = celltype_df.columns.tolist()
        print('{} cell types identified: {}\n'.format(len(celltypes), celltypes))
    except:
        print("""Your celltype data file could not be imported.
        Please check the documentation for format requirements
        and look at the example celltype data files.""")

    # start pipeline
    cellanneal_pipe(
        celltype_data_path,
        celltype_df,
        bulk_data_path,
        bulk_df,
        disp_min,
        bulk_min,
        bulk_max,
        maxiter,
        output_path)


from django.conf.urls import patterns, include, url
from django.contrib.auth import views as auth_views

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    # Examples:
    url(r'^$', 'Myton_Django.views.home', name='home'),
    # url(r'^blog/', include('blog.urls')),

    url(r'^staff/$', 'staff.views.home'),

    url(r'^admin/', include(admin.site.urls)),
   # url(r'^trade/$', 'trade.views.hello'),
    url(r'^trade/$', 'trade.views.home'),
    url(r'^trade/create/$', 'trade.views.create'),
    url(r'^latest-news/$', 'trade.views.articles'),
    url(r'^article/(\d+)/$', 'trade.views.article'),
   # url(r'^part-search/$', 'trade.views.partsearch'),
    url(r'^search/$', 'Myton_Django.views.search'),
    url(r'^downloads/$', 'trade.views.downloads'),
    url(r'^my-details/$', 'trade.views.details'),
    url(r'^my-orders/$', 'trade.views.orders'),
    url(r'^about/$', 'trade.views.about'),
    url(r'^login/$', 'trade.views.login'),
    url(r'^language/(?P<language>[a-z\-]+)/$', 'trade.views.language'),

    #user auth urls
    # url(r'^accounts/login/$', 'Myton_Django.views.login'),
    url(r'^accounts/login/$', auth_views.login,{'template_name': 'safe_login.html'}, name='auth_login'),
    url(r'^accounts/auth/$', 'Myton_Django.views.auth_view'),
    url(r'^accounts/logout/$', 'Myton_Django.views.logout'),
    url(r'^accounts/loggedin/$', 'Myton_Django.views.loggedin'),
    url(r'^accounts/invalid/$', 'Myton_Django.views.invalid_login'),
    url(r'^accounts/register/$', 'Myton_Django.views.register_user'),
    url(r'^accounts/register_success/$', 'Myton_Django.views.register_success'),

   # url(r'^latest-news/$', include('trade.urls')),

   #toms experiment - 03.07.2014
   url(r'^experiment/$', 'Myton_Django.views.ua_display_good1'),

)


# -*- coding:utf-8 -*-
# Coder: Yao Zhao
# Github: https://github.com/yyyzzzhao
# ==============================================================================
import torch
import torch.nn as nn
from torch.nn import init
import functools
from torch.optim import lr_scheduler
import torch.nn.functional as F
from models.normalization import SPADE
import torchvision
from torch.autograd import Variable

###############################################################################
# Helper Functions
###############################################################################

def get_norm_layer(norm_type='instance'):
    if norm_type == 'batch':
        norm_layer = functools.partial(nn.BatchNorm2d, affine=True)
    elif norm_type == 'instance':
        norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=True)
    elif norm_type == 'none':
        norm_layer = None
    else:
        raise NotImplementedError('normalization layer [%s] is not found' % norm_type)
    return norm_layer

def get_scheduler(optimizer, opt):
    """Return a learning rate scheduler

    Parameters:
        optimizer          -- the optimizer of the network
        opt (option class) -- stores all the experiment flags; needs to be a subclass of BaseOptions．
                              opt.lr_policy is the name of learning rate policy: linear | step | plateau | cosine

    For 'linear', we keep the same learning rate for the first <opt.niter> epochs
    and linearly decay the rate to zero over the next <opt.niter_decay> epochs.
    For other schedulers (step, plateau, and cosine), we use the default PyTorch schedulers.
    See https://pytorch.org/docs/stable/optim.html for more details.
    """
    if opt.lr_policy == 'linear':
        def lambda_rule(epoch):
            lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1)
            return lr_l
        scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)
    elif opt.lr_policy == 'step':
        scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)
    elif opt.lr_policy == 'plateau':
        scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)
    elif opt.lr_policy == 'cosine':
        scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.niter, eta_min=0)
    else:
        return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)
    return scheduler

def init_weights(net, init_type='normal', init_gain=0.02):
    """Initialize network weights.

    Parameters:
        net (network)   -- network to be initialized
        init_type (str) -- the name of an initialization method: normal | xavier | kaiming | orthogonal
        init_gain (float)    -- scaling factor for normal, xavier and orthogonal.

    We use 'normal' in the original pix2pix and CycleGAN paper. But xavier and kaiming might
    work better for some applications. Feel free to try yourself.
    """
    def init_func(m):  # define the initialization function
        classname = m.__class__.__name__
        if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):
            if init_type == 'normal':
                init.normal_(m.weight.data, 0.0, init_gain)
            elif init_type == 'xavier':
                init.xavier_normal_(m.weight.data, gain=init_gain)
            elif init_type == 'kaiming':
                init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')
            elif init_type == 'orthogonal':
                init.orthogonal_(m.weight.data, gain=init_gain)
            else:
                raise NotImplementedError('initialization method [%s] is not implemented' % init_type)
            if hasattr(m, 'bias') and m.bias is not None:
                init.constant_(m.bias.data, 0.0)
        elif classname.find('BatchNorm2d') != -1:  # BatchNorm Layer's weight is not a matrix; only normal distribution applies.
            if hasattr(m, 'weight') and m.weight is not None:
                init.normal_(m.weight.data, 1.0, init_gain)
            if hasattr(m, 'bias') and m.bias is not None:
                init.constant_(m.bias.data, 0.0)

    print('initialize network with %s' % init_type)
    net.apply(init_func)  # apply the initialization function <init_func>

def init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):
    if len(gpu_ids) > 0:
        assert(torch.cuda.is_available())
        net.to(gpu_ids[0])
        net = torch.nn.DataParallel(net, gpu_ids)
    init_weights(net, init_type, init_gain=init_gain)
    return net

def define_G(input_nc, output_nc, ngf, which_model_netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):
    netG = None
    norm_layer = get_norm_layer(norm_type=norm)

    if which_model_netG == 'resnet_9blocks':
        netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)
    elif which_model_netG == 'resnet_6blocks':
        netG = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)
    elif which_model_netG == 'unet_128':
        netG = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
    elif which_model_netG == 'unet_256':
        netG = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)
    elif which_model_netG == 'multi_9blocks':
        netG = MultiGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)
    elif which_model_netG == 'multi_6blocks':
        netG = MultiGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)
    else:
        raise NotImplementedError('Generator model name [%s] is not recognized' % which_model_netG)
    return init_net(netG, init_type, init_gain, gpu_ids)

def define_G_multi(input_nc, ngf, which_model_netG, norm='batch', use_dropout=False, init_type='normal', init_gain=0.02, gpu_ids=[]):
	netG = None
	norm_layer = get_norm_layer(norm_type=norm)
	if which_model_netG == 'unet_128':
		netG = AaaGenerator(input_nc, 7, ngf, norm_layer=norm_layer)
	elif which_model_netG == 'unet_256':
		netG = AaaGenerator(input_nc, 8, ngf, norm_layer=norm_layer)
	else:
		raise NotImplementedError('Generator model name [%s] is not recognized' % which_model_netG)
	return init_net(netG, init_type, init_gain, gpu_ids)

def define_D(input_nc, ndf, which_model_netD, n_layers_D=3, norm='batch', init_type='normal', init_gain=0.02, gpu_ids=[], getIntermFeat=False):
    netD = None
    norm_layer = get_norm_layer(norm_type=norm)

    if which_model_netD == 'basic':
        netD = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer, getIntermFeat=getIntermFeat)
    elif which_model_netD == 'n_layers':
        netD = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, getIntermFeat=getIntermFeat)
    elif which_model_netD == 'pixel':
        netD = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer)
    else:
        raise NotImplementedError('Discriminator model name [%s] is not recognized' %
                                  which_model_netD)
    return init_net(netD, init_type, init_gain, gpu_ids)

##############################################################################
# Classes
##############################################################################

# Defines the GAN loss which uses either LSGAN or the regular GAN.
# When LSGAN is used, it is basically same as MSELoss,
# but it abstracts away the need to create the target label tensor
# that has the same size as the input
class GANLoss(nn.Module):
    def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0,
                 tensor=torch.cuda.FloatTensor):
        super(GANLoss, self).__init__()
        self.real_label = target_real_label
        self.fake_label = target_fake_label
        self.real_label_var = None
        self.fake_label_var = None
        self.Tensor = tensor
        if gan_mode == 'lsgan':
            self.loss = nn.MSELoss()
        elif gan_mode == 'vanilla':
            self.loss = nn.BCEWithLogitsLoss()
        elif gan_mode in ['wgangp']:
            self.loss = None
        else:
            raise NotImplementedError('gan mode %s not implemented' % gan_mode)

    def get_target_tensor(self, input, target_is_real):
        target_tensor = None
        if target_is_real:
            create_label = ((self.real_label_var is None) or
                            (self.real_label_var.numel() != input.numel()))
            if create_label:
                real_tensor = self.Tensor(input.size()).fill_(self.real_label)
                self.real_label_var = Variable(real_tensor, requires_grad=False)
            target_tensor = self.real_label_var
        else:
            create_label = ((self.fake_label_var is None) or
                            (self.fake_label_var.numel() != input.numel()))
            if create_label:
                fake_tensor = self.Tensor(input.size()).fill_(self.fake_label)
                self.fake_label_var = Variable(fake_tensor, requires_grad=False)
            target_tensor = self.fake_label_var
        return target_tensor

    def __call__(self, input, target_is_real):
        if isinstance(input[0], list):
            loss = 0
            for input_i in input:
                pred = input_i[-1]
                target_tensor = self.get_target_tensor(pred, target_is_real)
                loss += self.loss(pred, target_tensor)
            return loss
        else:
            target_tensor = self.get_target_tensor(input[-1], target_is_real)
            return self.loss(input[-1], target_tensor)

# Defines the generator that consists of Resnet blocks between a few
# downsampling/upsampling operations.
# Code and idea originally from Justin Johnson's architecture.
# https://github.com/jcjohnson/fast-neural-style/
class ResnetGenerator(nn.Module):
    def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):
        assert(n_blocks >= 0)
        super(ResnetGenerator, self).__init__()
        self.input_nc = input_nc
        self.output_nc = output_nc
        self.ngf = ngf
        if type(norm_layer) == functools.partial:
            use_bias = norm_layer.func == nn.InstanceNorm2d
        else:
            use_bias = norm_layer == nn.InstanceNorm2d
        # pad --> conv --> norm --> relu
        model = [nn.ReflectionPad2d(3),
                 nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0,
                           bias=use_bias),
                 norm_layer(ngf),
                 nn.ReLU(True)]

        n_downsampling = 2
        for i in range(n_downsampling):
            mult = 2**i
            model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,
                                stride=2, padding=1, bias=use_bias),
                      norm_layer(ngf * mult * 2),
                      nn.ReLU(True)]

        mult = 2**n_downsampling
        for i in range(n_blocks):
            model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]

        for i in range(n_downsampling):
            mult = 2**(n_downsampling - i)
            model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
                                         kernel_size=3, stride=2,
                                         padding=1, output_padding=1,
                                         bias=use_bias),
                      norm_layer(int(ngf * mult / 2)),
                      nn.ReLU(True)]
        model += [nn.ReflectionPad2d(3)]
        model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]
        model += [nn.Tanh()]

        self.model = nn.Sequential(*model)

    def forward(self, input):
        return self.model(input)

# Define a resnet block
class ResnetBlock(nn.Module):
    def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):
        super(ResnetBlock, self).__init__()
        self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)

    def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):
        conv_block = []
        p = 0
        if padding_type == 'reflect':
            conv_block += [nn.ReflectionPad2d(1)]
        elif padding_type == 'replicate':
            conv_block += [nn.ReplicationPad2d(1)]
        elif padding_type == 'zero':
            p = 1
        else:
            raise NotImplementedError('padding [%s] is not implemented' % padding_type)

        conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),
                       norm_layer(dim),
                       nn.ReLU(True)]
        if use_dropout:
            conv_block += [nn.Dropout(0.5)]

        p = 0
        if padding_type == 'reflect':
            conv_block += [nn.ReflectionPad2d(1)]
        elif padding_type == 'replicate':
            conv_block += [nn.ReplicationPad2d(1)]
        elif padding_type == 'zero':
            p = 1
        else:
            raise NotImplementedError('padding [%s] is not implemented' % padding_type)
        conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),
                       norm_layer(dim)]

        return nn.Sequential(*conv_block)

    def forward(self, x):
        out = x + self.conv_block(x)
        return out

# Defines the Unet generator.
# |num_downs|: number of downsamplings in UNet. For example,
# if |num_downs| == 7, image of size 128x128 will become of size 1x1
# at the bottleneck
class UnetGenerator(nn.Module):
    def __init__(self, input_nc, output_nc, num_downs, ngf=64,
                 norm_layer=nn.BatchNorm2d, use_dropout=False):
        super(UnetGenerator, self).__init__()

        # construct unet structure
        unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, innermost=True)
        for i in range(num_downs - 5):
            unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, use_dropout=use_dropout)
        unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block)
        unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block)
        unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block)
        unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True)

        self.model = unet_block

    def forward(self, x):
        """Standard forward"""
        return self.model(x)

class MultiGenerator(nn.Module):
    def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):
        assert(n_blocks >= 0)
        super(MultiGenerator, self).__init__()
        self.input_nc = input_nc
        self.output_nc = output_nc
        self.ngf = ngf
        if type(norm_layer) == functools.partial:
            use_bias = norm_layer.func == nn.InstanceNorm2d
        else:
            use_bias = norm_layer == nn.InstanceNorm2d
        # pad --> conv --> norm --> relu
        model = [nn.ReflectionPad2d(3),
                 nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0,
                           bias=use_bias),
                 norm_layer(ngf),
                 nn.ReLU(True)]

        n_downsampling = 2
        for i in range(n_downsampling):
            mult = 2**i
            model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,
                                stride=2, padding=1, bias=use_bias),
                      norm_layer(ngf * mult * 2),
                      nn.ReLU(True)]

        mult = 2**n_downsampling
        for i in range(n_blocks):
            model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]

        for i in range(n_downsampling):
            mult = 2**(n_downsampling - i)
            model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),
                                         kernel_size=3, stride=2,
                                         padding=1, output_padding=1,
                                         bias=use_bias),
                      norm_layer(int(ngf * mult / 2)),
                      nn.ReLU(True)]
        # There the network apart two branches
        self.base = nn.Sequential(*model)
        # Reconstruction branch
        sec_branch = []
        sec_branch += [nn.ReflectionPad2d(3)]
        sec_branch += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]
        sec_branch += [nn.Tanh()]
        self.sec_branch = nn.Sequential(*sec_branch)
        # Segmentation branch
        seg_branch = []
        seg_branch += [nn.ReflectionPad2d(3)]
        seg_branch += [nn.Conv2d(ngf, 1, kernel_size=7, padding=0)]
        seg_branch += [nn.Sigmoid()]
        self.seg_branch = nn.Sequential(*seg_branch)

    def forward(self, input):
        base = self.base(input)
        rec = self.sec_branch(base)
        seg = self.seg_branch(base)
        return rec, seg

class UnetGeneratorS(nn.Module):
    def __init__(self, input_nc, output_nc, num_downs, ngf=64,
                 norm_layer=nn.BatchNorm2d, use_dropout=False):
        super(UnetGenerator, self).__init__()

        # construct unet structure
        unet_block = UnetSkipConnectionBlockS(ngf * 8, ngf * 8, input_nc=None, submodule=None, innermost=True)
        for i in range(num_downs - 5):
            unet_block = UnetSkipConnectionBlockS(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, use_dropout=use_dropout)
        unet_block = UnetSkipConnectionBlockS(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block)
        unet_block = UnetSkipConnectionBlockS(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block)
        unet_block = UnetSkipConnectionBlockS(ngf, ngf * 2, input_nc=None, submodule=unet_block)
        unet_block = UnetSkipConnectionBlockS(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True)

        self.model = unet_block

    def forward(self, x, seg):
        """Standard forward"""
        return self.model(x, seg)

class AaaGenerator(nn.Module):
	def __init__(self, input_nc, num_downs=7, ngf=64, norm_layer=nn.BatchNorm2d):
		super(AaaGenerator, self).__init__()
		self.num_downs = num_downs

		# construct unet encoder parts
		self.u_block_base = EncodeBlock(ngf*8, ngf*8, norm_layer=norm_layer, innermost=True)
		self.u_block_0 = EncodeBlock(ngf * 8, ngf * 8, norm_layer=norm_layer)
		self.u_block_1 = EncodeBlock(ngf * 8, ngf * 8, norm_layer=norm_layer)
		if self.num_downs == 8:
			self.u_block_2 = EncodeBlock(ngf * 8, ngf * 8, norm_layer=norm_layer)
		self.u_block_3 = EncodeBlock(ngf * 4, ngf * 8, norm_layer=norm_layer)
		self.u_block_4 = EncodeBlock(ngf * 2, ngf * 4, norm_layer=norm_layer)
		self.u_block_5 = EncodeBlock(ngf, ngf * 2, norm_layer=norm_layer)
		self.u_block_6 = EncodeBlock(input_nc, ngf, norm_layer=norm_layer, outermost=True)

		# construct two decoder
		# one is for generate rgb images
		self.gen_path0_0 = DecodeBlock(ngf*8, ngf*8, innermost=True, norm_layer=norm_layer)
		self.gen_path0_1 = DecodeBlock(ngf*8, ngf*8, norm_layer=norm_layer)
		self.gen_path0_2 = DecodeBlock(ngf*8, ngf*8, norm_layer=norm_layer)
		if self.num_downs == 8:
			self.gen_path0_3 = DecodeBlock(ngf*8, ngf*8, norm_layer=norm_layer)
		self.gen_path0_4 = DecodeBlock(ngf*8, ngf*4, norm_layer=norm_layer)
		self.gen_path0_5 = DecodeBlock(ngf*4, ngf*2, norm_layer=norm_layer)
		self.gen_path0_6 = DecodeBlock(ngf*2, ngf, norm_layer=norm_layer)
		self.gen_path0_7 = DecodeBlock(ngf, 3, outermost=True, norm_layer=norm_layer)

		# the second is for generate mask
		self.gen_path1_0 = DecodeBlock(ngf*8, ngf*8, innermost=True, norm_layer=norm_layer)
		self.gen_path1_1 = DecodeBlock(ngf*8, ngf*8, norm_layer=norm_layer)
		self.gen_path1_2 = DecodeBlock(ngf*8, ngf*8, norm_layer=norm_layer)
		if self.num_downs == 8:
			self.gen_path1_3 = DecodeBlock(ngf*8, ngf*8, norm_layer=norm_layer)
		self.gen_path1_4 = DecodeBlock(ngf*8, ngf*4, norm_layer=norm_layer)
		self.gen_path1_5 = DecodeBlock(ngf*4, ngf*2, norm_layer=norm_layer)
		self.gen_path1_6 = DecodeBlock(ngf*2, ngf, norm_layer=norm_layer)
		self.gen_path1_7 = DecodeBlock(ngf, 1, outermost=True, is_seg=True, norm_layer=norm_layer)

	def forward(self, x):
		# encoder
		x1 = self.u_block_6(x)
		x2 = self.u_block_5(x1)
		x3 = self.u_block_4(x2)
		x4 = self.u_block_3(x3)
		if self.num_downs == 8:
			x5 = self.u_block_2(x4)
			x6 = self.u_block_1(x5)
		else:
			x6 = self.u_block_1(x4)
		x7 = self.u_block_0(x6)
		base = self.u_block_base(x7)

		# decoder 1
		d_0_0 = self.gen_path0_0(base)
		d_0_1 = self.gen_path0_1(torch.cat([d_0_0, x7], 1))
		d_0_2 = self.gen_path0_2(torch.cat([d_0_1, x6], 1))
		if self.num_downs == 8:
			d_0_3 = self.gen_path0_3(torch.cat([d_0_2, x5], 1))
			d_0_4 = self.gen_path0_4(torch.cat([d_0_3, x4], 1))
		else:
			d_0_4 = self.gen_path0_4(torch.cat([d_0_2, x4], 1))
		d_0_5 = self.gen_path0_5(torch.cat([d_0_4, x3], 1))
		d_0_6 = self.gen_path0_6(torch.cat([d_0_5, x2], 1))
		rgb = self.gen_path0_7(torch.cat([d_0_6, x1], 1))

		# decoder 2
		d_1_0 = self.gen_path1_0(base)
		d_1_1 = self.gen_path1_1(torch.cat([d_1_0, x7], 1))
		d_1_2 = self.gen_path1_2(torch.cat([d_1_1, x6], 1))
		if self.num_downs == 8:
			d_1_3 = self.gen_path1_3(torch.cat([d_1_2, x5], 1))
			d_1_4 = self.gen_path1_4(torch.cat([d_1_3, x4], 1))
		else:
			d_1_4 = self.gen_path1_4(torch.cat([d_1_2, x4], 1))
		d_1_5 = self.gen_path1_5(torch.cat([d_1_4, x3], 1))
		d_1_6 = self.gen_path1_6(torch.cat([d_1_5, x2], 1))
		mask = self.gen_path1_7(torch.cat([d_1_6, x1], 1))

		return rgb, mask

# the EncodeBlock returns a skip connection tensor and a deeper layer interation
# while the innermost return a downconv tensor.
class EncodeBlock(nn.Module):
    def __init__(self, outer_nc, inner_nc, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):
        super(EncodeBlock, self).__init__()
        if type(norm_layer) == functools.partial:
            use_bias = norm_layer.func == nn.InstanceNorm2d
        else:
            use_bias = norm_layer == nn.InstanceNorm2d

        self.downconv = nn.Conv2d(outer_nc, inner_nc, kernel_size=4, stride=2, padding=1, bias=use_bias)
        self.downrelu = nn.LeakyReLU(0.2, True)
        self.downnorm = norm_layer(inner_nc)

        self.innermost = innermost
        self.outermost = outermost

    def forward(self, x):
        if self.innermost:
            x = self.downrelu(x)
            x = self.downconv(x)
            return x
        elif self.outermost:
            x = self.downconv(x)
            return x
        else:
            x = self.downrelu(x)
            x = self.downconv(x)
            x = self.downnorm(x)
            return x

class DecodeBlock(nn.Module):
	def __init__(self, inner_nc, outer_nc, innermost=False, outermost=False, is_seg=False, norm_layer=nn.BatchNorm2d):
		super(DecodeBlock, self).__init__()

		# uprelu = nn.ReLU(True)
		self.uprelu = nn.ReLU()
		self.upnorm = norm_layer(outer_nc)
		self.innermost = innermost
		self.outermost = outermost
		self.is_seg = is_seg
		if outermost:
			# if not is_seg:
			self.upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1)
				# up = [upconv, nn.Tanh()]
			# else:
				# self.upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1)
				# up = [upconv, nn.Sigmoid()]
		elif innermost:
			self.upconv = nn.ConvTranspose2d(inner_nc, outer_nc, kernel_size=4, stride=2, padding=1)
			# up = [uprelu, upconv, upnorm]
		else:
			self.upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc, kernel_size=4, stride=2, padding=1)
			# up = [uprelu, upconv, upnorm]

	def forward(self, x):
		if self.outermost:
			x = self.upconv(x)
			if self.is_seg:
				return nn.Sigmoid()(x)
			else:
				return nn.Tanh()(x)
		elif self.innermost:
			x = self.uprelu(x)
			x = self.upconv(x)
			x = self.upnorm(x)
			return x
		else:
			x = self.uprelu(x)
			x = self.upconv(x)
			x = self.upnorm(x)
			return x

class UnetSkipConnectionBlock(nn.Module):
    """Defines the Unet submodule with skip connection.
        X -------------------identity----------------------
        |-- downsampling -- |submodule| -- upsampling --|
    """

    def __init__(self, outer_nc, inner_nc, input_nc=None,
                 submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):
        """Construct a Unet submodule with skip connections.

        Parameters:
            outer_nc (int) -- the number of filters in the outer conv layer
            inner_nc (int) -- the number of filters in the inner conv layer
            input_nc (int) -- the number of channels in input images/features
            submodule (UnetSkipConnectionBlock) -- previously defined submodules
            outermost (bool)    -- if this module is the outermost module
            innermost (bool)    -- if this module is the innermost module
            norm_layer          -- normalization layer
            user_dropout (bool) -- if use dropout layers.
        """
        super(UnetSkipConnectionBlock, self).__init__()
        self.outermost = outermost
        if type(norm_layer) == functools.partial:
            use_bias = norm_layer.func == nn.InstanceNorm2d
        else:
            use_bias = norm_layer == nn.InstanceNorm2d
        if input_nc is None:
            input_nc = outer_nc

        # spade_config_str = 'spadesyncbatch3x3'  # opt.norm_G.replace('spectral', '')

        downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,
                             stride=2, padding=1, bias=use_bias)
        downrelu = nn.LeakyReLU(0.2, True)
        downnorm = norm_layer(inner_nc)
        # downnorm = SPADE(spade_config_str, inner_nc, 1)   ## opt.semantic_nc = 1
        uprelu = nn.ReLU(True)
        upnorm = norm_layer(outer_nc)
        # upnorm = SPADE(spade_config_str, outer_nc, 1)

        if outermost:
            upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
                                        kernel_size=4, stride=2,
                                        padding=1)
            down = [downconv]
            up = [uprelu, upconv, nn.Tanh()]
            model = down + [submodule] + up
        elif innermost:
            upconv = nn.ConvTranspose2d(inner_nc, outer_nc,
                                        kernel_size=4, stride=2,
                                        padding=1, bias=use_bias)
            down = [downrelu, downconv]
            up = [uprelu, upconv, upnorm]
            model = down + up
        else:
            upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
                                        kernel_size=4, stride=2,
                                        padding=1, bias=use_bias)
            down = [downrelu, downconv, downnorm]
            up = [uprelu, upconv, upnorm]

            if use_dropout:
                model = down + [submodule] + up + [nn.Dropout(0.5)]
            else:
                model = down + [submodule] + up

        self.model = nn.Sequential(*model)

    def forward(self, x):
        if self.outermost:
            return self.model(x)
        else:   # add skip connections
            return torch.cat([x, self.model(x)], 1)

class UnetSkipConnectionBlockS(nn.Module):
    """Defines the Unet submodule with skip connection.
        X -------------------identity----------------------
        |-- downsampling -- |submodule| -- upsampling --|
    """

    def __init__(self, outer_nc, inner_nc, input_nc=None,
                 submodule=None, outermost=False, innermost=False, use_dropout=False):
        """Construct a Unet submodule with skip connections.

        Parameters:
            outer_nc (int) -- the number of filters in the outer conv layer
            inner_nc (int) -- the number of filters in the inner conv layer
            input_nc (int) -- the number of channels in input images/features
            submodule (UnetSkipConnectionBlock) -- previously defined submodules
            outermost (bool)    -- if this module is the outermost module
            innermost (bool)    -- if this module is the innermost module
            norm_layer          -- normalization layer
            user_dropout (bool) -- if use dropout layers.
        """
        super(UnetSkipConnectionBlock, self).__init__()
        self.outermost = outermost
        use_bias = False
        if input_nc is None:
            input_nc = outer_nc

        spade_config_str = 'spadesyncbatch3x3'  # opt.norm_G.replace('spectral', '')

        self.downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,
                             stride=2, padding=1, bias=use_bias)
        self.downrelu = nn.LeakyReLU(0.2, True)
        # downnorm = norm_layer(inner_nc)
        self.downnorm = SPADE(spade_config_str, inner_nc, 1)   ## opt.semantic_nc = 1
        self.uprelu = nn.ReLU(True)
        # upnorm = norm_layer(outer_nc)
        self.upnorm = SPADE(spade_config_str, outer_nc, 1)

        self.outermost = outermost
        self.innermost = innermost
        self.outer_nc = outer_nc
        self.inner_nc = inner_nc
        self.submodule = submodule
        self.use_dropout = use_dropout
        self.tan = nn.Tanh()

        if outermost:
            self.upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
                                        kernel_size=4, stride=2,
                                        padding=1)
        elif innermost:
            self.upconv = nn.ConvTranspose2d(inner_nc, outer_nc,
                                        kernel_size=4, stride=2,
                                        padding=1, bias=use_bias)
        else:
            self.upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,
                                        kernel_size=4, stride=2,
                                        padding=1, bias=use_bias)

    def forward(self, x, seg):
        in_x = x
        if self.outermost:
            x = self.downconv(x)   # down
            x = self.submodule(x, seg)  # submodule
            x = self.uprelu(x)  #  up
            x = self.upconv(x)
            x = self.tan(x)
            return x
        elif self.innermost:
            x = self.downrelu(x)  # down
            x = self.downconv(x)
            x = self.uprelu(x)  # up
            x = self.upconv(x)
            x = self.upnorm(x, seg)
            return torch.cat([in_x, x], 1)
        else:

            x = self.downrelu(x)  # down
            x = self.downconv(x)
            x = self.downnorm(x, seg)
            x = self.submodule(x, seg)  # submodule
            x = self.uprelu(x)   # up
            x = self.upconv(x)
            x = self.upnorm(x, seg)
            if self.use_dropout:
                x = nn.Dropout(0.5)(x)
            return torch.cat([in_x, x], 1)

# Defines the PatchGAN discriminator with the specified arguments.
# class NLayerDiscriminator(nn.Module):
#     def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d):
#         super(NLayerDiscriminator, self).__init__()
#         if type(norm_layer) == functools.partial:
#             use_bias = norm_layer.func == nn.InstanceNorm2d
#         else:
#             use_bias = norm_layer == nn.InstanceNorm2d

#         kw = 4
#         padw = 1
#         sequence = [
#             nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),
#             nn.LeakyReLU(0.2, True)
#         ]

#         nf_mult = 1
#         nf_mult_prev = 1
#         for n in range(1, n_layers):
#             nf_mult_prev = nf_mult
#             nf_mult = min(2**n, 8)
#             sequence += [
#                 nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,
#                           kernel_size=kw, stride=2, padding=padw, bias=use_bias),
#                 norm_layer(ndf * nf_mult),
#                 nn.LeakyReLU(0.2, True)
#             ]

#         nf_mult_prev = nf_mult
#         nf_mult = min(2**n_layers, 8)
#         sequence += [
#             nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,
#                       kernel_size=kw, stride=1, padding=padw, bias=use_bias),
#             norm_layer(ndf * nf_mult),
#             nn.LeakyReLU(0.2, True)
#         ]

#         sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]

#         self.model = nn.Sequential(*sequence)

#     def forward(self, input):
#         return self.model(input)
class NLayerDiscriminator(nn.Module):
    """Defines a PatchGAN discriminator"""

    def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, getIntermFeat=False):
        """Construct a PatchGAN discriminator

        Parameters:
            input_nc (int)  -- the number of channels in input images
            ndf (int)       -- the number of filters in the last conv layer
            n_layers (int)  -- the number of conv layers in the discriminator
            norm_layer      -- normalization layer
        """
        super(NLayerDiscriminator, self).__init__()
        self.getIntermFeat = getIntermFeat
        self.n_layers = n_layers
        if type(norm_layer) == functools.partial:  # no need to use bias as BatchNorm2d has affine parameters
            use_bias = norm_layer.func != nn.BatchNorm2d
        else:
            use_bias = norm_layer != nn.BatchNorm2d

        kw = 4
        padw = 1
        sequence = [[nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw), nn.LeakyReLU(0.2, True)]]
        nf_mult = 1
        nf_mult_prev = 1
        for n in range(1, n_layers):  # gradually increase the number of filters
            nf_mult_prev = nf_mult
            nf_mult = min(2 ** n, 8)
            sequence += [[
                nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=2, padding=padw, bias=use_bias),
                norm_layer(ndf * nf_mult),
                nn.LeakyReLU(0.2, True)
            ]]

        nf_mult_prev = nf_mult
        nf_mult = min(2 ** n_layers, 8)
        sequence += [[
            nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult, kernel_size=kw, stride=1, padding=padw, bias=use_bias),
            norm_layer(ndf * nf_mult),
            nn.LeakyReLU(0.2, True)
        ]]

        sequence += [[nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]]  # output 1 channel prediction map

        if getIntermFeat:
            for n in range(len(sequence)):
                setattr(self, 'model'+str(n), nn.Sequential(*sequence[n]))
        else:
            sequence_stream = []
            for n in range(len(sequence)):
                sequence_stream += sequence[n]
            self.model = nn.Sequential(*sequence_stream)

    def forward(self, input):
        """Standard forward."""
        if self.getIntermFeat:
            res = [input]
            for n in range(self.n_layers+2):
                model = getattr(self, 'model'+str(n))
                res.append(model(res[-1]))
            return res[1:]
        else:
            return self.model(input)

class PixelDiscriminator(nn.Module):
    def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d, use_sigmoid=False):
        super(PixelDiscriminator, self).__init__()
        if type(norm_layer) == functools.partial:
            use_bias = norm_layer.func == nn.InstanceNorm2d
        else:
            use_bias = norm_layer == nn.InstanceNorm2d

        self.net = [
            nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),
            nn.LeakyReLU(0.2, True),
            nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),
            norm_layer(ndf * 2),
            nn.LeakyReLU(0.2, True),
            nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]

        if use_sigmoid:
            self.net.append(nn.Sigmoid())

        self.net = nn.Sequential(*self.net)

    def forward(self, input):
        return self.net(input)


"""
Support for deCONZ sensor.

For more details about this component, please refer to the documentation at
https://home-assistant.io/components/sensor.deconz/
"""
from homeassistant.components.deconz.const import (
    ATTR_DARK, ATTR_ON, CONF_ALLOW_CLIP_SENSOR, DECONZ_REACHABLE,
    DOMAIN as DECONZ_DOMAIN)
from homeassistant.const import (
    ATTR_BATTERY_LEVEL, ATTR_VOLTAGE, DEVICE_CLASS_BATTERY)
from homeassistant.core import callback
from homeassistant.helpers.device_registry import CONNECTION_ZIGBEE
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from homeassistant.helpers.entity import Entity
from homeassistant.util import slugify

DEPENDENCIES = ['deconz']

ATTR_CURRENT = 'current'
ATTR_DAYLIGHT = 'daylight'
ATTR_EVENT_ID = 'event_id'

async def async_setup_platform(hass, config, async_add_entities,
                               discovery_info=None):
    """Old way of setting up deCONZ sensors."""
    pass

async def async_setup_entry(hass, config_entry, async_add_entities):
    """Set up the deCONZ sensors."""
    gateway = hass.data[DECONZ_DOMAIN]

    @callback
    def async_add_sensor(sensors):
        """Add sensors from deCONZ."""
        from pydeconz.sensor import DECONZ_SENSOR, SWITCH as DECONZ_REMOTE
        entities = []
        allow_clip_sensor = config_entry.data.get(CONF_ALLOW_CLIP_SENSOR, True)
        for sensor in sensors:
            if sensor.type in DECONZ_SENSOR and \
               not (not allow_clip_sensor and sensor.type.startswith('CLIP')):
                if sensor.type in DECONZ_REMOTE:
                    if sensor.battery:
                        entities.append(DeconzBattery(sensor, gateway))
                else:
                    entities.append(DeconzSensor(sensor, gateway))
        async_add_entities(entities, True)

    gateway.listeners.append(
        async_dispatcher_connect(hass, 'deconz_new_sensor', async_add_sensor))

    async_add_sensor(gateway.api.sensors.values())

class DeconzSensor(Entity):
    """Representation of a sensor."""

    def __init__(self, sensor, gateway):
        """Set up sensor and add update callback to get data from websocket."""
        self._sensor = sensor
        self.gateway = gateway
        self.unsub_dispatcher = None

    async def async_added_to_hass(self):
        """Subscribe to sensors events."""
        self._sensor.register_async_callback(self.async_update_callback)
        self.gateway.deconz_ids[self.entity_id] = self._sensor.deconz_id
        self.unsub_dispatcher = async_dispatcher_connect(
            self.hass, DECONZ_REACHABLE, self.async_update_callback)

    async def async_will_remove_from_hass(self) -> None:
        """Disconnect sensor object when removed."""
        if self.unsub_dispatcher is not None:
            self.unsub_dispatcher()
        self._sensor.remove_callback(self.async_update_callback)
        self._sensor = None

    @callback
    def async_update_callback(self, reason):
        """Update the sensor's state.

        If reason is that state is updated,
        or reachable has changed or battery has changed.
        """
        if reason['state'] or \
           'reachable' in reason['attr'] or \
           'battery' in reason['attr'] or \
           'on' in reason['attr']:
            self.async_schedule_update_ha_state()

    @property
    def state(self):
        """Return the state of the sensor."""
        return self._sensor.state

    @property
    def name(self):
        """Return the name of the sensor."""
        return self._sensor.name

    @property
    def unique_id(self):
        """Return a unique identifier for this sensor."""
        return self._sensor.uniqueid

    @property
    def device_class(self):
        """Return the class of the sensor."""
        return self._sensor.sensor_class

    @property
    def icon(self):
        """Return the icon to use in the frontend."""
        return self._sensor.sensor_icon

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this sensor."""
        return self._sensor.sensor_unit

    @property
    def available(self):
        """Return true if sensor is available."""
        return self.gateway.available and self._sensor.reachable

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def device_state_attributes(self):
        """Return the state attributes of the sensor."""
        from pydeconz.sensor import LIGHTLEVEL
        attr = {}
        if self._sensor.battery:
            attr[ATTR_BATTERY_LEVEL] = self._sensor.battery
        if self._sensor.on is not None:
            attr[ATTR_ON] = self._sensor.on
        if self._sensor.type in LIGHTLEVEL and self._sensor.dark is not None:
            attr[ATTR_DARK] = self._sensor.dark
        if self.unit_of_measurement == 'Watts':
            attr[ATTR_CURRENT] = self._sensor.current
            attr[ATTR_VOLTAGE] = self._sensor.voltage
        if self._sensor.sensor_class == 'daylight':
            attr[ATTR_DAYLIGHT] = self._sensor.daylight
        return attr

    @property
    def device_info(self):
        """Return a device description for device registry."""
        if (self._sensor.uniqueid is None or
                self._sensor.uniqueid.count(':') != 7):
            return None
        serial = self._sensor.uniqueid.split('-', 1)[0]
        bridgeid = self.gateway.api.config.bridgeid
        return {
            'connections': {(CONNECTION_ZIGBEE, serial)},
            'identifiers': {(DECONZ_DOMAIN, serial)},
            'manufacturer': self._sensor.manufacturer,
            'model': self._sensor.modelid,
            'name': self._sensor.name,
            'sw_version': self._sensor.swversion,
            'via_hub': (DECONZ_DOMAIN, bridgeid),
        }

class DeconzBattery(Entity):
    """Battery class for when a device is only represented as an event."""

    def __init__(self, sensor, gateway):
        """Register dispatcher callback for update of battery state."""
        self._sensor = sensor
        self.gateway = gateway
        self.unsub_dispatcher = None

        self._name = '{} {}'.format(self._sensor.name, 'Battery Level')
        self._unit_of_measurement = "%"

    async def async_added_to_hass(self):
        """Subscribe to sensors events."""
        self._sensor.register_async_callback(self.async_update_callback)
        self.gateway.deconz_ids[self.entity_id] = self._sensor.deconz_id
        self.unsub_dispatcher = async_dispatcher_connect(
            self.hass, DECONZ_REACHABLE, self.async_update_callback)

    async def async_will_remove_from_hass(self) -> None:
        """Disconnect sensor object when removed."""
        if self.unsub_dispatcher is not None:
            self.unsub_dispatcher()
        self._sensor.remove_callback(self.async_update_callback)
        self._sensor = None

    @callback
    def async_update_callback(self, reason):
        """Update the battery's state, if needed."""
        if 'reachable' in reason['attr'] or 'battery' in reason['attr']:
            self.async_schedule_update_ha_state()

    @property
    def state(self):
        """Return the state of the battery."""
        return self._sensor.battery

    @property
    def name(self):
        """Return the name of the battery."""
        return self._name

    @property
    def unique_id(self):
        """Return a unique identifier for the device."""
        return self._sensor.uniqueid

    @property
    def device_class(self):
        """Return the class of the sensor."""
        return DEVICE_CLASS_BATTERY

    @property
    def unit_of_measurement(self):
        """Return the unit of measurement of this entity."""
        return self._unit_of_measurement

    @property
    def available(self):
        """Return true if sensor is available."""
        return self.gateway.available and self._sensor.reachable

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def device_state_attributes(self):
        """Return the state attributes of the battery."""
        attr = {
            ATTR_EVENT_ID: slugify(self._sensor.name),
        }
        return attr

    @property
    def device_info(self):
        """Return a device description for device registry."""
        if (self._sensor.uniqueid is None or
                self._sensor.uniqueid.count(':') != 7):
            return None
        serial = self._sensor.uniqueid.split('-', 1)[0]
        bridgeid = self.gateway.api.config.bridgeid
        return {
            'connections': {(CONNECTION_ZIGBEE, serial)},
            'identifiers': {(DECONZ_DOMAIN, serial)},
            'manufacturer': self._sensor.manufacturer,
            'model': self._sensor.modelid,
            'name': self._sensor.name,
            'sw_version': self._sensor.swversion,
            'via_hub': (DECONZ_DOMAIN, bridgeid),
        }


import requests
import time
from bs4 import BeautifulSoup as BS

#Строки ввода значений
print("Введите данные матча: ")
print("1 Команда: ")
Team1 = input()
print("2 Команда: ")
Team2 = input()
print("Дата: ")
Data = input()
print("Время: ")
Time = input()

#Парсинг (город - страна)
r = requests.get('https://www.euro-football.ru/team')
html = BS(r.content,'html.parser')
time.sleep(0.5)
for el in html.select('.infoblock'):
    title = el.select('.infoblock > a')
    if(title[0].text == Team1):
       a = title[0].get('href')
    if(title[0].text == Team2):
       b = title[0].get('href')

rTeam1 = requests.get('https://www.euro-football.ru' + a)
time.sleep(0.5)
rTeam2 = requests.get('https://www.euro-football.ru' + b)
time.sleep(0.5)
htmlS = BS(rTeam1.content,'html.parser')
time.sleep(0.5)
Town1 = ""
Town2 = ""
Country1 = ""
Country2 = ""

for el in htmlS.select('.team-about__info'):
    title = el.select('p')
    Town1 =title[0].text
    Country1 =title[1].text
time.sleep(0.5)
htmlD = BS(rTeam2.content,'html.parser')
time.sleep(0.5)
for el in htmlD.select('.team-about__info'):
    title = el.select('p')
    Town2 =title[0].text
    Country2 =title[1].text
time.sleep(0.5)
Town1 = Town1[6:]
Town2 = Town2[6:]
Country1 = Country1[7:]
Country2 = Country2[7:]

if Data[3] == 0:
    rData = Data[3:]
else:
    rData = Data[2:]

print(Town1)
print(Country1)
print(Town2)
print(Country2)

time.sleep(0.5)

htmlSPos = BS(rTeam1.content,'html.parser')

for el in htmlSPos.select('.team-schedule__table'):
   title = el.select('td')

i = 0
Teams = [0, 0]
for el in htmlSPos.select('td'):
    try:
        if (i % 4 == 0):
            DataPole =  title[i].text
            DataPole = DataPole[:2]
            print(DataPole)
            TimePole =  title[i].text
            TimePole = TimePole[-5:]
            print(TimePole)
        if (i % 4 == 1):
            Teams[0] = title[i].text
            print(Teams[0])
        if (i % 4 == 3):
            Teams[1] = title[i].text
            print(Teams[1])
    except:
        print('---')
    else:
        if (i % 4 == 3):
            print(Teams, [Team1, Team2])
            print((DataPole == Data[:2]) , (TimePole == Time) , (Team1 in Teams , Team2 in Teams))
            if ((DataPole == Data[:2]) and (TimePole == Time) and (Team1 in Teams and Team2 in Teams)):
                Strect = title[i-1]
import requests
import time
from bs4 import BeautifulSoup as BS

def funs(Country,Town,Data,Time,ChekGOROD):
#Строки ввода значений

    htmlpogoda = requests.get('https://world-weather.ru/archive/')
    Pog = BS(htmlpogoda.content,'html.parser')
    for el in Pog.select('.list-cities'):
        title = el.select('a')

    i = 0
    for el in Pog.select('.country-block'):
        print(title[i].text)
        if (title[i].text == Country):
            a = 'https:' + title[i].get('href')
        i = i + 1
    if(Country == 'Англия'):
        a = 'https://world-weather.ru/archive/united_kingdom/'
    print(a)

    if Data[3] == '0':
        rData = Data[4:]
    else:
        rData = Data[3:]
    print(rData)

    if(rData == '1'):
        tData = 'Январь'
    if(rData == '2'):
        tData = 'Февраль'
    if(rData == '3'):
        tData = 'Март'
    if(rData == '4'):
        tData = 'Апрель'
    if(rData == '5'):
        tData = 'Май'
    if(rData == '6'):
        tData = 'Июнь'
    if(rData == '7'):
        tData = 'Июль'
    if(rData == '8'):
        tData = 'Август'
    if(rData == '9'):
        tData = 'Сентябрь'
    if(rData == '10'):
        tData = 'Октябрь'
    if(rData == '11'):
        tData = 'Ноябрь'
    if(rData == '12'):
        tData = 'Декабрь'

    time.sleep(0.5)
    rTime = Time[:2]
    if(rTime[0] == 0):
        rTime = rTime[1:]

    time.sleep(0.5)
    htmlTown = requests.get(a)
    PogTown = BS(htmlTown.content,'html.parser')
    if(ChekGOROD == 1):
        for el in PogTown.select('.list-cities'):
            title = el.select('a')

        i = 0
        for el in PogTown.select('a'):
            try:
                print(title[i].text)
                if (title[i].text == Town):
                    CtructTawn = 'https:' + title[i].get('href')
            except:
                print('---')
            else:
                i = i + 1

        print(CtructTawn)

        time.sleep(0.5)

        htmlmonths = requests.get(CtructTawn)
        Pogmonths = BS(htmlmonths.content,'html.parser')
        for el in Pogmonths.select('.list-months'):
            title = el.select('a')

        print(title)
        i = 0
        for el in Pogmonths.select('a'):
            try:
                print(title[i].text)
                if (title[i].text == tData):
                    CtructMonths = 'https:' + title[i].get('href')
            except:
                print('---')
            else:
                i = i + 1

        print(CtructMonths)

        print(rTime)
        htmltemperatur = requests.get(CtructMonths)
        Pogtemperatur = BS(htmltemperatur.content,'html.parser')
        if(int(rTime) < 16):
            for el in Pogtemperatur.select('.arch-day'):
                title = el.select('.weather-temperature')
                print(title)
                TEMPERATUR = title[0].text
        else:
            for el in Pogtemperatur.select('.arch-night'):
                title = el.select('.weather-temperature')
                print(title)
                TEMPERATUR = title[0].text
    else:
        for el in PogTown.select('.list-cities'):
            title = el.select('a')

        print(title[0].text)
        CtructTawn = 'https:' + title[0].get('href')

        print(CtructTawn)

        time.sleep(0.5)

        htmlmonths = requests.get(CtructTawn)
        Pogmonths = BS(htmlmonths.content,'html.parser')
        for el in Pogmonths.select('.list-months'):
            title = el.select('a')

        print(title)
        i = 0
        for el in Pogmonths.select('a'):
            try:
                print(title[i].text)
                if (title[i].text == tData):
                    CtructMonths = 'https:' + title[i].get('href')
            except:
                print('---')
            else:
                i = i + 1

        print(CtructMonths)

        print(rTime)
        htmltemperatur = requests.get(CtructMonths)
        Pogtemperatur = BS(htmltemperatur.content,'html.parser')
        if(int(rTime) < 16):
            for el in Pogtemperatur.select('.arch-day'):
                title = el.select('.weather-temperature')
                print(title)
                TEMPERATUR = title[0].text
        else:
            for el in Pogtemperatur.select('.arch-night'):
                title = el.select('.weather-temperature')
                print(title)
                TEMPERATUR = title[0].text

    print(title)
    print(TEMPERATUR)
    return TEMPERATUR
#Строки ввода значений
print("Введите данные матча: ")
print("1 Команда: ")
Team1 = input()
print("2 Команда: ")
Team2 = input()
print("Дата: ")
Data = input()
print("Время: ")
Time = input()
print("Прошёл ли матч: ")
PROV = input()

#Парсинг (город - страна)
r = requests.get('https://www.euro-football.ru/team')
html = BS(r.content,'html.parser')
time.sleep(0.5)
for el in html.select('.infoblock'):
    title = el.select('.infoblock > a')
    if(title[0].text == Team1):
       a = title[0].get('href')
    if(title[0].text == Team2):
       b = title[0].get('href')

rTeam1 = requests.get('https://www.euro-football.ru' + a)
time.sleep(0.5)
rTeam2 = requests.get('https://www.euro-football.ru' + b)
time.sleep(0.5)
htmlS = BS(rTeam1.content,'html.parser')
time.sleep(0.5)
Town1 = ""
Town2 = ""
Country1 = ""
Country2 = ""

for el in htmlS.select('.team-about__info'):
    title = el.select('p')
    Town1 =title[0].text
    Country1 =title[1].text
time.sleep(0.5)
htmlD = BS(rTeam2.content,'html.parser')
time.sleep(0.5)
for el in htmlD.select('.team-about__info'):
    title = el.select('p')
    Town2 =title[0].text
    Country2 =title[1].text
time.sleep(0.5)
Town1 = Town1[6:]
Town2 = Town2[6:]
Country1 = Country1[7:-1]
Country2 = Country2[7:-1]
Town1 =str(Town1)
Town2 = str(Town2)
Country1 = str(Country1)
Country2 = str(Country2)
print(Town1)
print(Country1)
print(Town2)
print(Country2)

time.sleep(0.5)

htmlSPos = BS(rTeam1.content,'html.parser')

for el in htmlSPos.select('.team-schedule__table'):
   title = el.select('td')

i = 0
Teams = [0, 0]
for el in htmlSPos.select('td'):
    try:
        if (i % 4 == 0):
            DataPole =  title[i].text
            DataPole = DataPole[:2]
            print(DataPole)
            TimePole =  title[i].text
            TimePole = TimePole[-5:]
            print(TimePole)
        if (i % 4 == 1):
            Teams[0] = title[i].text
            print(Teams[0])
        if (i % 4 == 3):
            Teams[1] = title[i].text
            print(Teams[1])
    except:
        print('---')
    else:
        if (i % 4 == 3):
            print(Teams, [Team1, Team2])
            print((DataPole == Data[:2]) , (TimePole == Time) , (Team1 in Teams , Team2 in Teams))
            if ((DataPole == Data[:2]) and (TimePole == Time) and (Team1 in Teams and Team2 in Teams)):
                Strect = title[i-1]
                Strect = str(Strect)
                if(PROV == '1'):
                    Strect = Strect[100:-14]
                else:
                    Strect = Strect[72:-14]
                print(Strect)
                time.sleep(0.5)
                StrectPole = requests.get(Strect)
                Pole = BS(StrectPole.content,'html.parser')
                for ell in Pole.select('.match-info__description'):
                    titlel = ell.select('a')
                TownPole = titlel[0].get('href')
                print(TownPole)
                time.sleep(0.5)
                TownStrectPole = requests.get(TownPole)
                TownStrectPolePole = BS(TownStrectPole.content,'html.parser')
                for elll in TownStrectPolePole.select('.stadium-about__info'):
                    InfiTawn = elll.select('th')
                    StranaStadi = elll.select('td')
                print(InfiTawn)
                print(StranaStadi)
                ChekCTRANA = 0
                ChekGOROD = 0
                CTRANAPOLE = ""
                GORODPOLE = ""
                for pole in InfiTawn:
                    if "Страна" in pole.text:
                        j = InfiTawn.index(pole)
                        ChekCTRANA = 1
                        break
                for pole in InfiTawn:
                    if "Город" in pole.text:
                        g = InfiTawn.index(pole)
                        ChekGOROD = 1
                        break
                if(ChekCTRANA == 1):
                    CTRANAPOLE = StranaStadi[j].text;
                if(ChekGOROD == 1):
                    GORODPOLE = StranaStadi[g].text;
                break
        i = i + 1

TEMPERATUR1 = funs(Country1,Town1,Data,Time,ChekGOROD)
TEMPERATUR2 = funs(Country2,Town2,Data,Time,ChekGOROD)
TEMPERATUR3 = funs(CTRANAPOLE,GORODPOLE,Data,Time,ChekGOROD)

print(TEMPERATUR1)
print(TEMPERATUR2)
print(TEMPERATUR3)

if(TEMPERATUR1[0] == '-'):
    TEMPERATUR1_int = int(TEMPERATUR1[1:]) * -1
else:
    TEMPERATUR1_int = int(TEMPERATUR1[1:])

if(TEMPERATUR2[0] == '-'):
    TEMPERATUR2_int = int(TEMPERATUR2[1:]) * -1
else:
    TEMPERATUR2_int = int(TEMPERATUR2[1:])

if(TEMPERATUR3[0] == '-'):
    TEMPERATUR3_int = int(TEMPERATUR3[1:]) * -1
else:
    TEMPERATUR3_int = int(TEMPERATUR3[1:])

print(TEMPERATUR1_int)
print(TEMPERATUR2_int)
print(TEMPERATUR3_int)

field = 0.05
tem_4 = 0.125
tem_3 = 0.625
tem_2 = 0.125
tem_1 = 0.5
tem_0 = 0.43

WinA = 50
LoseA = 50
WinB = 50
LoseB = 50

if(TEMPERATUR1_int > TEMPERATUR3_int):
    Raz1 = TEMPERATUR1_int - TEMPERATUR3_int
if(TEMPERATUR1_int < TEMPERATUR3_int):
    Raz1 = TEMPERATUR3_int - TEMPERATUR1_int
if(TEMPERATUR1_int == TEMPERATUR3_int):
    Raz1 = 0
if(TEMPERATUR2_int > TEMPERATUR3_int):
    Raz2 = TEMPERATUR2_int - TEMPERATUR3_int
if(TEMPERATUR2_int < TEMPERATUR3_int):
    Raz2 = TEMPERATUR3_int - TEMPERATUR2_int
if(TEMPERATUR2_int == TEMPERATUR3_int):
    Raz2 = 0

if(Raz1 > 10):
    TEMPERATUR1_int = tem_4
if((Raz1 > 7)and(Raz1 <= 10)):
    TEMPERATUR1_int = tem_3
if((Raz1 > 3)and(Raz1 <= 7)):
    TEMPERATUR1_int = tem_2
if((Raz1 > 0)and(Raz1 <= 3)):
    TEMPERATUR1_int = tem_1
if(Raz1 == 0):
    TEMPERATUR1_int = tem_0

if(Raz2 > 10):
    TEMPERATUR2_int = tem_4
if((Raz2 > 7)and(Raz2 <= 10)):
    TEMPERATUR2_int = tem_3
if((Raz2 > 3)and(Raz2 <= 7)):
    TEMPERATUR2_int = tem_2
if((Raz2 > 0)and(Raz2 <= 3)):
    TEMPERATUR2_int = tem_1
if(Raz2 == 0):
    TEMPERATUR2_int = tem_0

if (ChekGOROD == 1):
    if(Town1 == GORODPOLE):
        WinA = WinA +(field*tem_0)*100
        print(WinA)
    else:
        LoseA = LoseA + (field * (1 - TEMPERATUR1_int))*100
        print("!!!" + str(TEMPERATUR1_int))
        print(100 - LoseA)
    if(Town2 == GORODPOLE):
        WinB = WinB +(field*tem_0)*100
        print(WinB)
    else:
        LoseB = LoseB + (field * (1 - TEMPERATUR2_int))*100
        print(str(TEMPERATUR2_int)+ "!!!")
        print(100 - LoseB)
else:
    if(Country1 == CTRANAPOLE):
        WinA = WinA +(field*tem_0)*100
        print(WinA)
    else:
        LoseA = LoseA + (field * (1 - TEMPERATUR1_int))*100
        print(100 - LoseA)
    if(Country2 == CTRANAPOLE):
        WinB = WinB +(field*tem_0)*100
        print(WinB)
    else:
        LoseB = LoseB + (field * (1 - TEMPERATUR2_int))*100
        print(100 - LoseB)


import numpy as np
import cv2

import os
import glob

drawing  = False
drawing2 = False

exite_ = False
next_  = False
back_  = False
save_  = False
mask_  = False

font = cv2.FONT_HERSHEY_SIMPLEX
bo = True
alfa = 0

kernel = np.ones((10,10),np.uint8)

tx  = "train\\x\\x"
ty  = "train\\y\\y"

img_dir = "train\\x"
data_path = os.path.join(img_dir,'*g')
files = glob.glob(data_path)

nb = len(files)   #####            ##########           ###########           ############    ###########  ♦  !!!!       !!!! !!!

def draw_circle(event,x,y,flags,param):
    global drawing , next_ ,exite_,back_,save_,mask_,bo

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing = True

    if event == cv2.EVENT_LBUTTONUP:
        drawing = False

    if 520<x<590 and 10<y<40 and drawing == True:
        exite_ = True

    if 520<x<590 and 60<y<90 and drawing == True:
        next_ = True

    if 520<x<590 and 110<y<140 and drawing == True:
        back_ = True

    if 520<x<590 and 160<y<190 and drawing == True:
        save_ = True

    if 520<x<590 and 210<y<240 and drawing == True:
        mask_ = True

    if 512<x<600 and drawing == True :
        bo = True

def draw_circle2(event,x,y,flags,param):
    global drawing2,bo,xb,yb

    if event == cv2.EVENT_LBUTTONDOWN:
        drawing2 = True

    if event == cv2.EVENT_LBUTTONUP:
        drawing2 = False

    if drawing2 == True and 0<x<600:
        print(bo)
        if bo == True:
            xb,yb = x,y
            bo = False
        cv2.line(log_main,(xb,yb),(x,y),(255,0,0),2)
        cv2.line(log_main,(xb+600,yb),(x+600,y),(255,0,0),2)
        xb,yb = x,y

def resize_b(image):
    a = 600
    img_x = np.ones((a,a,3), np.uint8)
    img_x[:,:,0] = cv2.resize(image[:,:,0],(a,a))
    img_x[:,:,1] = cv2.resize(image[:,:,1],(a,a))
    img_x[:,:,2] = cv2.resize(image[:,:,2],(a,a))
    return img_x

def resize_c(image):
    a = 256
    img_x = np.ones((a,a,3), np.uint8)
    img_x[:,:,0] = cv2.resize(image[:,:,0],(a,a))
    img_x[:,:,1] = cv2.resize(image[:,:,1],(a,a))
    img_x[:,:,2] = cv2.resize(image[:,:,2],(a,a))
    return img_x

def x_to_main(img_x,img_main):
    img_main[0:600,0:600,:] = img_x
    return img_main

def y_to_main(img_y,img_main):
    img_main[0:600,600:1200,:] = img_y
    return img_main

def reg_main():
    img_main = np.zeros((256,600,3), np.uint8)#512
    img_main[10:40,520:590,2]=255
    img_main[:,513:515,1]=255
    return img_main

def cta_main(img_main):
    img_main[:,515:600,:]=(0,0,0)
    img_main[10:40,520:590,:]=(0,0,255)
    img_main[:,513:515,1]=255

    img_main[60:90,520:590,:  ]=255
    cv2.putText(img_main,'next',(520,85), font, 1,(255,0,0),1,cv2.LINE_AA)

    img_main[110:140,520:590,:]=255
    cv2.putText(img_main,'back',(520,135), font, 1,(255,0,0),1,cv2.LINE_AA)

    img_main[160:190,520:590,:]=255
    cv2.putText(img_main,'save',(520,185), font, 1,(255,0,0),1,cv2.LINE_AA)

    img_main[210:240,520:598,:]=255

    return img_main

img_x = np.zeros((256,256,3), np.uint8)
img_y = np.zeros((256,256,3), np.uint8)
img_main = reg_main()

log_main  = np.zeros((600,1200,3),dtype=np.uint8)

cv2.namedWindow('image')
cv2.namedWindow('log_main')

cv2.setMouseCallback('image',draw_circle)
cv2.setMouseCallback('log_main',draw_circle2)

ind = 0

while(1):

    if next_ == True and alfa < nb:
        alfa += 1
        sr = tx+str(alfa)+".png"
        image = cv2.imread(sr)
        image = resize_b(image)
        log_main = x_to_main(image,log_main)

        log_main[0:600,600:1200,:] = 0
        next_ = False

        img_main[0:256,0:256,:] = 0
        cv2.putText(img_main,str(alfa),(20,200), cv2.FONT_HERSHEY_SIMPLEX, 4,(0,200,101),2,cv2.LINE_AA)

    if back_ == True and alfa > 1 :
        alfa -= 1
        image = cv2.imread(tx+str(alfa)+".png")
        image = resize_b(image)
        log_main = x_to_main(image,log_main)

        log_main[0:600,600:1200,:] = 0
        back_ = False

        img_main[0:256,0:256,:] = 0
        cv2.putText(img_main,str(alfa),(20,200), cv2.FONT_HERSHEY_SIMPLEX, 4,(0,200,101),2,cv2.LINE_AA)

    if save_ == True :
        #cv2.imwrite(tx+str(ind)+".png",image                    )
        sr = ty+str(alfa)+".png"
        cv2.imwrite(sr,resize_c(log_main[0:600,600:1200,:]))
        ind += 1
        save_ = False
        print(alfa,"saved")

    if mask_ == True :
        im_in = log_main[0:600,600:1200,0]

        th, im_th = cv2.threshold(im_in, 127, 255, cv2.THRESH_BINARY)

# Copy the thresholded image
        im_floodfill = im_th.copy()

# Mask used to flood filling.
# NOTE: the size needs to be 2 pixels bigger on eac6h side than the input image
        h, w = im_th.shape[:2]
        mask = np.zeros((h+2, w+2), np.uint8)

# Floodfill from point (0, 0)
        cv2.floodFill(im_floodfill, mask, (0,0), 255)

# Invert floodfilled image
        im_floodfill_inv = cv2.bitwise_not(im_floodfill)

# Combine the two images to get the foreground
        log_main[0:600,600:1200,0] = im_th | im_floodfill_inv

        mask_ = False

        bo=True

    if exite_ == True :
        break

    cv2.imshow('image',img_main)
    cv2.imshow('log_main',log_main)
    img_main = cta_main(img_main)
    cv2.putText(img_main,str(alfa),(520,235), font, 1,(255,0,0),1,cv2.LINE_AA)

    if cv2.waitKey(1) & 0xFF == ord('s'):
        break

cv2.destroyAllWindows()


# -*- coding: utf-8 -*-
from django.db import models
from django.utils.timezone import now

from locations.models import Location

class Application(models.Model):
    name = models.CharField(max_length=255)
    description = models.CharField(max_length=255)
    created = models.DateTimeField(auto_now_add=True, null=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

class Campaign(models.Model):
    PROGRAM_TYPES = {
        '1': 'May/June',
        '2': 'Nov/Dec',
    }

    name = models.CharField(max_length=255)
    locations = models.ManyToManyField(Location, limit_choices_to={
        u'type__name__in': [u'State', u'LGA']})
    start_date = models.DateField()
    end_date = models.DateField()
    apps = models.ManyToManyField(Application)
    created = models.DateTimeField(auto_now_add=True, null=True)
    updated = models.DateTimeField(auto_now=True)

    def __str__(self):
        return self.name

    def campaign_states(self):
        return self.locations.filter(type__name=u'State')

    def campaign_lgas(self, location):
        try:
            if self.locations.get(pk=location.pk) and location.type.name == u'State':
                return self.locations.filter(parent=location,
                    type__name=u'LGA') or location.children.all()
        except Location.DoesNotExist:
            pass

        return Location.objects.none()

    def get_related_objects(self, model_class, state, locations=None):
        try:
            if not locations:
                lgas = self.campaign_lgas(state)
                if lgas.count() == Location.objects.filter(parent=state).count():
                    return model_class.objects.filter(
                        location__code__startswith=state.code,
                        time__range=(self.start_date, self.end_date))
                else:
                    locations = state.get_descendants(include_self=True)

            return model_class.objects.filter(location__in=locations,
                time__range=(self.start_date, self.end_date))
        except Exception:
            pass

        return model_class.objects.none()

    @classmethod
    def active_campaigns(cls, location=None):
        date = now().date()
        qs = cls.objects.filter(start_date__lte=date, end_date__gte=date)

        if location is not None and isinstance(location, Location):
            return qs.filter(locations__lft__lte=location.lft,
                locations__rght__gte=location.rght)

        return qs


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

"""Releasing dailymotion-sdk-js

Usage:

    fab prod release               release the HEAD
    fab prod release:GIT_REF       release the GIT_REF

"""

from __future__ import unicode_literals

import os, fnmatch
from datetime import datetime
from fabric.colors import green, blue
from fabric.contrib.files import exists
from fabric.api import *
from fabric.contrib.project import rsync_project
from fabric.decorators import roles
from fabric.operations import require
from fabric.utils import puts
from time import time

env.use_ssh_config = False
env.conf = {
    'project': 'dailymotion-sdk-js',
    'git_ref': 'master',
    'target_dir': '/data/web/dailymotion-sdk-js',
    'make_dir': '/data/web'
}

@task
def prod():
    """Work on the production environment
    """
    env.environment = 'prod'
    env.user = 'root'
    env.roledefs.update({
        'app': [
            'prov-04.adm.dc3.dailymotion.com'
        ]
    })

@task
def release(ref=None):
    """Perform a release

    Parameters:
    ref -- git reference
    """
    require('environment', provided_by=[prod])
    puts("Release in progress")
    execute(send_file)
    execute(deploy)
    execute(cdn_cache_clear)
    puts(blue('Ready to rock'))

@roles('app')
def send_file():
    put('all.js', env.conf['target_dir'])

@roles('app')
def cdn_cache_clear():
    print('THIS NEEDS TO BE UPDATED TO THE LATEST CDN SERVICE.')

@roles('app')
def deploy():
    with cd(env.conf['make_dir']):
        run('make sync-js-sdk')


import numpy
import quadprog
import cvxopt
from numpy import *

def quadprog_solve_qp(P, q, G=None, h=None, A=None, b=None):
# minimize x^T*P*x + q^T*x s.t. Gx <= h and Ax = b
    qp_G = .5 * (P + P.T)   # make sure P is symmetric
    qp_a = -q
    if A is not None:
        qp_C = -numpy.vstack([A, G]).T
        qp_b = -numpy.hstack([b, h])
        meq = A.shape[0]
    else:  # no equality constraint
        qp_C = -G.T
        qp_b = -h
        meq = 0
    return quadprog.solve_qp(qp_G, qp_a, qp_C, qp_b, meq)[0]

def cvxopt_solve_qp(P, q, G=None, h=None, A=None, b=None):
    P = .5 * (P + P.T)  # make sure P is symmetric
    args = [cvxopt.matrix(P), cvxopt.matrix(q)]
    if G is not None:
        args.extend([cvxopt.matrix(G), cvxopt.matrix(h)])
        if A is not None:
            args.extend([cvxopt.matrix(A), cvxopt.matrix(b)])
    sol = cvxopt.solvers.qp(*args,options={'show_progress':False})
    if 'optimal' not in sol['status']:
        return None
    return numpy.array(sol['x']).reshape((P.shape[1],))

if __name__ == "__main__":
    P = array([[2.,0.],[0,2.]])
    q = array([-8.,-6.])
    G = array([[-1.,0.],[0.,-1.],[1.,1.]])
    h = array([0.,0.,5.]).reshape((3,))
    print(quadprog_solve_qp(P,q,G,h))
    print(cvxopt_solve_qp(P,q,G,h))


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

from django.core.management.base import BaseCommand, CommandError

from datetime import datetime
import time
import requests
import facebook
import geocoder
from incf.countryutils import transformations
import pycountry
import json
import urlparse

from soc_net_dashboards.local import linkedin_access_token, fb_app_id, fb_app_secret
from dashboard.models import LinkedInCountryFollowes, FBCountryFans, Fb_Post, LinkedIn_Post

LINKEDIN_API = 'https://api.linkedin.com/v1/companies/8016'

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        while True:
            # linkedin company followers
            """
            try:
                geo_codes = [
                    {'code': 'eu.dk.*.5038', 'lng': 12.57, 'lat': 55.66, 'name': 'Copenhagen'},
                    {'code': 'eu.dk.*.5041', 'lng': 10.38, 'lat': 55.38, 'name': 'Odense'},
                    {'code': 'eu.dk.*.5044', 'lng': 9.93, 'lat': 57.03, 'name': 'Ålborg'},
                    {'code': 'eu.dk.*.5045', 'lng': 10.18, 'lat': 56.17, 'name': 'Århus'},
                    {'code': 'eu.dk', 'lng': 8.81, 'lat': 56.05, 'name': 'Denmark'},
                    {'code': 'as.cn', 'lng': 112.19, 'lat': 30.86, 'name': 'China'},
                    {'code': 'na.us', 'lng': -105.71, 'lat': 41.88, 'name': 'United States'},
                    {'code': 'as', 'lng': 103.84, 'lat': 46.86, 'name': 'Asia'},
                    {'code': 'eu', 'lng': 15.471, 'lat': 49.81, 'name': 'Europe'},
                    {'code': 'af', 'lng': 21.75, 'lat': -4.03, 'name': 'Africa'},
                    {'code': 'la', 'lng': -44.92, 'lat': -8.23, 'name': 'South America'},
                    {'code': 'na', 'lng': -101.10, 'lat': 48.91, 'name': 'North America'}
                ]
                for code in geo_codes:
                    payload = {
                                'format': 'json',
                                'oauth2_access_token': linkedin_access_token,
                                'geos': code['code']
                    }

                    followers = requests.get("%s/num-followers" % LINKEDIN_API, params=payload).json()
                    if code['code'] == 'as':
                        followers -= LinkedInCountryFollowes.objects.get(code='as.cn').total
                    elif code['code'] == 'eu':
                        followers -= LinkedInCountryFollowes.objects.get(code='eu.dk').total +\
                            self.denmark_cities_followers()
                    elif code['code'] == 'na':
                        followers -= LinkedInCountryFollowes.objects.get(code='na.us').total
                    elif code['code'] == 'eu.dk':
                        followers -= self.denmark_cities_followers()

                    obj, created = LinkedInCountryFollowes.objects.get_or_create(code=code['code'],
                                        defaults={'total': followers, 'latitude': code['lat'],
                                        'longitude': code['lng'], 'country': code['name']})
                    if not created:
                        obj.total = followers
                        obj.save()

                    time.sleep(1)
            except:
                pass
            # linkedin company status updates
            try:
                payload = {
                            'format': 'json',
                            'oauth2_access_token': linkedin_access_token,
                            'event-type': 'status-update'
                }
                statuses = requests.get("%s/updates" % LINKEDIN_API, params=payload).json()
                for status in statuses['values']:
                    share = status['updateContent']['companyStatusUpdate']['share']
                    obj, created = LinkedIn_Post.objects.get_or_create(post_id=share['id'],
                                        defaults={
                                                    'comments': status['updateComments']['_total'],
                                                    'message': share['comment'],
                                                    'img_url': share['content']['submittedImageUrl'],
                                                    'create_at': datetime.fromtimestamp(share['timestamp'] / 1000)
                                        }
                                )
                    if not created:
                        obj.comments = status['updateComments']['_total']
                        obj.save()
            except:
                pass
            """
            # fb
            fb_access_token = facebook.get_app_access_token(fb_app_id, fb_app_secret)
            graph = facebook.GraphAPI(access_token=fb_access_token)
            profile_posts = graph.get_connections("kundeco", "feed", **{'limit': 100})
            # get page feed
            for post in profile_posts['data']:
                if not post.get('message'): continue

                obj, created = Fb_Post.objects.get_or_create(create_at=post['created_time'],
                    message=post['message'], story=post.get('story'), post_id=post['id']
                )
                if (not created and diff_month(datetime.now(), datetime.strptime(post['created_time'][:-5], '%Y-%m-%dT%H:%M:%S')) > 12) or created:
                    try:
                        post_data = graph.get_object("/%s" % post['id'], **{'fields': 'comments.summary(true),likes.summary(true),shares'})
                        obj.likes = post_data['likes']['summary']['total_count']
                        obj.comments = post_data['comments']['summary']['total_count']
                        obj.shares = post_data['shares']['count'] if post_data.get('shares') else 0
                        obj.save()
                    except:
                        obj.likes = 0
                        obj.shares = 0
                        obj.comments = 0
                        obj.save()

            # get page likes
            url = 'https://maps.googleapis.com/maps/api/geocode/json'
            profile_fans = get_page_fans(graph, '/kundeco/insights/page_fans_country')
            for alpha2, fans in profile_fans['value'].items():
                record = FBCountryFans.objects.filter(code=alpha2)
                if not record.exists():
                    try:
                        country = pycountry.countries.get(alpha2=alpha2).name
                        continent = transformations.cca_to_ctn(alpha2)
                        params = {'sensor': 'false', 'address': country}
                        location = requests.get(url, params=params).json()['results'][0]['geometry']['location']
                        FBCountryFans.objects.create(code=alpha2,
                                            total=fans, latitude=location['lat'], continent=continent,
                                            longitude=location['lng'], country=country)
                    except:
                        pass
                else:
                    record = record.first()
                    record.total = fans
                    record.save()
                time.sleep(1)
            time.sleep(1800)

    def denmark_cities_followers(self):
        return LinkedInCountryFollowes.objects.get(code='eu.dk.*.5038').total +\
                    LinkedInCountryFollowes.objects.get(code='eu.dk.*.5041').total +\
                    LinkedInCountryFollowes.objects.get(code='eu.dk.*.5044').total +\
                    LinkedInCountryFollowes.objects.get(code='eu.dk.*.5045').total

def diff_month(d1, d2):
    return (d1.year - d2.year)*12 + d1.month - d2.month

def get_page_fans(graph, url, **kwargs):
    response = graph.get_object(url, **kwargs)
    if response['data']:
        return response['data'][-1]['values'][-1]
    else:
        params = urlparse.parse_qs(urlparse.urlparse(response['paging']['previous']).query)
        return get_page_fans(graph, url, **{'since': params['since'][0], 'until': params['until'][0]})