import discord
import asyncio
import aiohttp

async def run(ctx, character):
    rb_list = ["ottarl","revis","riveria", "finn","ottar"]
    if character.lower() in rb_list:
        if(character.lower() == "ottar"):
            character = "ottarl"
        temp_embed = discord.Embed()
        temp_embed.color = 3066993
        temp_embed.set_author(name="Akuno#8965",url="https://discordapp.com",icon_url="https://cdn.discordapp.com/avatars/141222596610883584/0e51b4be33b83b17a4c98ceb381bda85.png?size=128")
        temp_embed.set_image(url="attachment://rb.png")
        await ctx.send(embed=temp_embed, file=discord.File("./rbguides/" + character.lower()+ ".png",filename="rb.png"))
    else:
        temp_embed = discord.Embed()
        temp_embed.color = 16203840
        temp_embed.title = "No character found"
        temp_embed.description= "There doesn't exist an RB for this character. Please search either: Ottar/Otarrl, Revis, Riveria or Finn"
        await ctx.send(embed=temp_embed)


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

# HYPER PARAMETERS
INPUT_FEATURE_SIZE = 10
EMBEDDING_FEATURE_SIZE = 5
BATCH_SIZE = 128
EPOCH = 100
LR = 0.001
#PATHS
WORKSPACE = 'X:\\HM2\\'
TRAIN_PATH = 'X:\\HM\\0403cmu_f.csv'
TEST_PATH = 'X:\\HM\\0403cmu_f.csv'
REPRESENTATION_PATH = 'X:\\HM2\\0403cmu_r_10000.csv'
INFO_PATH = 'X:\\HM2\\0403cmu_ls_10000.csv'
CLUSTER_PATH = 'X:\\HM2\\0403cmu_c_ac_c.csv'
MODEL_PATH = WORKSPACE +str(EMBEDDING_FEATURE_SIZE) +'_'+str(EPOCH) +'_'+str(LR)+'.pth'


class Stack:
    def __init__(self,max_size):
        self.__max_size=max_size
        self.__elements=[]*self.__max_size
        self.__top=len(self.__elements)-1
        #self.__top=-1 #-1 is the last element in reverse order

    def get_max_size(self):
        return self.__max_size

    def is_full(self):
       if self.__max_size==len(self.__elements):
            return True
       else:
           return False

    def push(self,data):
        for i in range(0,len(data)):
            self.__elements.append(data[i])

    def is_empty(self):
       if []==self.__elements:
           return True

    def pop(self):
        length=len(self.__elements)-1
        for i in range(length,-1, -1):
            self.__elements.pop(i)

        print("Popped List:",self.__elements)
        #Remove pass and write the logic to pop an element. Pop the element only if stack is not empty. Otherwise, display appropriate message

    def display(self):
        print(self.__elements)
        print("top is:",self.__top)
        #Remove pass and write the logic to display the element(s).

    #You can use the below __str__() to print the elements of the DS object while debugging
    def __str__(self):
        msg=[]
        length=len(self.__elements)-1
        index=0
        while(index<=length):
            msg.append((str)(self.__elements[index]))
            index+=1
        msg=" ".join(msg)
        msg="Stack data(Top to Bottom): "+msg
        return msg

stack1=Stack(3)
print(stack1.get_max_size())
print(stack1.is_full())
stack1.push(["A","B","C"])
print(stack1.is_full())
stack1.display()
stack1.pop()
stack1.display()

stack1.push(["A","B","C"])
print(stack1.__str__())


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

"""
Django settings for example project.

For more information on this file, see
https://docs.djangoproject.com/en/1.6/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.6/ref/settings/
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
import sys

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
PROJECT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

sys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "ssssssssssssssssssssssssssssssssssssssssssssssssss"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'south',
    'django_fine_uploader',
    'myapp',
)

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    'django.contrib.auth.context_processors.auth',
    'django.contrib.messages.context_processors.messages',
    'django.core.context_processors.i18n'
)

ROOT_URLCONF = 'config.urls'

WSGI_APPLICATION = 'config.wsgi.application'

# Database
# https://docs.djangoproject.com/en/1.6/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Internationalization
# https://docs.djangoproject.com/en/1.6/topics/i18n/

TIME_ZONE = 'Europe/Rome'
USE_TZ = True
USE_I18N = True
USE_L10N = True

LANGUAGE_CODE = 'it'
LANGUAGES = (
    ('it', 'Italiano'),
    ('en', 'English'),
)
ENABLED_LANGUAGES = [l[0] for l in LANGUAGES]
LANGUAGES_ALL = (
    ('it', 'Italiano'),
    ('en', 'English'),
)
LOCALE_PATHS = (
    os.path.join(PROJECT_DIR, '../django_fine_uploader/locale'),
)
SITE_ID = 1

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.6/howto/static-files/

STATIC_ROOT = os.path.join(PROJECT_DIR, 'static')
STATIC_URL = '/static/'

# CUSTOM CONFIG:
# Media URL
MEDIA_URL = '/media/'
# Media root
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

STATICFILES_DIRS = ()
STATICFILES_FINDERS = (
    'django.contrib.staticfiles.finders.FileSystemFinder',
    'django.contrib.staticfiles.finders.AppDirectoriesFinder',
)

# Uploads Directory
# FU_FILE_STORAGE = 'django.core.files.storage.DefaultStorage'
# FU_UPLOAD_DIR = 'uploads/'
# FU_CHUNKS_DIR = 'chunks/'
# FU_CONCURRENT_UPLOADS = True
# FU_CHUNKS_DONE_PARAM_NAME = 'done'


from __future__ import absolute_import, division, print_function

import torch

from pyro.distributions.categorical import Categorical as _Categorical
from pyro.distributions.torch_wrapper import TorchDistribution
from pyro.distributions.util import copy_docs_from, get_clamped_probs

@copy_docs_from(_Categorical)
class Categorical(TorchDistribution):
    enumerable = True

    def __init__(self, ps=None, logits=None, *args, **kwargs):
        ps = get_clamped_probs(ps, logits, is_multidimensional=True)
        torch_dist = torch.distributions.Categorical(ps)
        x_shape = ps.shape[:-1] + (1,)
        event_dim = 1
        super(Categorical, self).__init__(torch_dist, x_shape, event_dim, *args, **kwargs)

    def sample(self):
        x = self.torch_dist.sample(self._sample_shape)
        return x.view(self._sample_shape + self._x_shape)

    def batch_log_pdf(self, x):
        log_pxs = self.torch_dist.log_prob(x.squeeze(-1)).unsqueeze(-1)
        batch_log_pdf_shape = self.batch_shape(x) + (1,)
        batch_log_pdf = torch.sum(log_pxs, -1).contiguous().view(batch_log_pdf_shape)
        if self.log_pdf_mask is not None:
            batch_log_pdf = batch_log_pdf * self.log_pdf_mask
        return batch_log_pdf

    def enumerate_support(self):
        values = self.torch_dist.enumerate_support()
        sample_shape = (self.torch_dist.probs.shape[-1],)
        return values.view(sample_shape + self._x_shape)


"""update url and doi attributes

Revision ID: f6102dc58c7f
Revises: 776edda4b9fa
Create Date: 2019-08-14 16:57:09.992950

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = 'f6102dc58c7f'
down_revision = '776edda4b9fa'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('api_request',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('doi', sa.String(length=64), nullable=False),
    sa.Column('request_url', sa.String(length=512), nullable=True),
    sa.Column('request_type', sa.String(length=32), nullable=True),
    sa.Column('response_content', sa.Text(), nullable=True),
    sa.Column('response_status', sa.String(length=32), nullable=True),
    sa.ForeignKeyConstraint(['doi'], ['doi.doi'], ),
    sa.PrimaryKeyConstraint('id')
    )
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('api_request')
    # ### end Alembic commands ###


from __future__ import print_function
import os
import matplotlib.pyplot as plt
import numpy as np
import tensorflow as tf

from utils.patch import get_patches
from multi_gpus.nets import build

flags = tf.app.flags

flags.DEFINE_string('ckpt_dir', './ckpt', 'check point direction')
flags.DEFINE_integer('patches', 128, 'batch size')
flags.DEFINE_string('model_name', None, '')
flags.DEFINE_integer('patch_size', 64, '')
flags.DEFINE_string('set', 'valid', '')
flags.DEFINE_string('meta_dir', './meta', '')
flags.DEFINE_string('gpu', '3', '')
flags.DEFINE_integer('blocks', 3, '')
flags.DEFINE_string('out_file', '', '')
flags.DEFINE_string('type', '', '')
flags.DEFINE_integer('num_classes', 10, '')
flags.DEFINE_float('weight_decay', 0.00004, '')
flags.DEFINE_string('extra', '', 'j70, j90, g0_8 etc')
flags.DEFINE_string('format', '', 'jpg or tif')
flags.DEFINE_integer('num_branches', 0, '')
flags.DEFINE_boolean('p_relu', False, '')
flags.DEFINE_string('data_dir', '/data/spcup_test', '')
flags.DEFINE_boolean('ema', False, '')
flags.DEFINE_string('stand', '128', '')
FLAGS = flags.FLAGS

# def get_patches(img, max_patches, patch_size):
#     h = img.shape[0]
#     w = img.shape[1]
#     n = 0
#     if len(img.shape) == 2:
#         img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
#     for start_r in range(0, h - patch_size + 1):
#         for  start_c in range(0, w - patch_size + 1):
#             patch = img[start_r:start_r + patch_size, start_c:start_c + patch_size, :]
#             n = n + 1
#             yield patch

def standardization(x):
    # return x
    # x = np.roll(x, 32, 0)
    # x = np.roll(x, 32, 1)
    if FLAGS.stand == '128':
        if FLAGS.data_dir == '/data/spcup_test':
            return (x - 128.)/128.
        else:
            return (x*255 - 128.)/128.
    else:
        return x
    # mean = np.mean(x)
    # stddev = np.std(x)
    # adjusted_stddev = max(stddev, 1./np.sqrt(FLAGS.patch_size * FLAGS.patch_size * 3))
    # return (x - mean) / adjusted_stddev

def main(_):
    ff = open(FLAGS.out_file, 'w')
    if not ff:
        raise RuntimeError('OUTPUT FILE OPEN ERROR!!!!!!')
    print('fname,camera', file=ff)
    os.environ["CUDA_VISIBLE_DEVICES"] = FLAGS.gpu
    config = tf.ConfigProto()
    config.gpu_options.per_process_gpu_memory_fraction = 0.7
    config.gpu_options.allow_growth = True

    with tf.name_scope('input'):
        x = tf.placeholder(tf.float32, [None, FLAGS.patch_size, FLAGS.patch_size, 3], 'x')

    y = build.net(x, False, FLAGS)

    # update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
    # with tf.control_dependencies(update_ops):
    pred = tf.nn.softmax(y, 1)

    if FLAGS.ema:
        variable_averages = tf.train.ExponentialMovingAverage(0.9999)
        variables_to_restore = variable_averages.variables_to_restore()
        saver = tf.train.Saver(variables_to_restore, name='saver')
    else:
        saver = tf.train.Saver(name="saver")

    # f = open(os.path.join(FLAGS.meta_dir, FLAGS.set) + '.txt', 'r')
    # image_names = []
    # labels = []
    # line = f.readline()
    # while line:
    #     l = line.split(' ')
    #     if len(l) == 2:
    #         image_name = l[0]
    #         label = l[1]
    #     else:
    #         image_name = l[0] + ' ' + l[1]
    #         label = l[2]
    #     # image_name, label = line.split(' ')
    #     label = label[0:-1]
    #     image_names.append(image_name.split('.')[0] + '-' + FLAGS.extra + '.' + FLAGS.format)
    #     labels.append(int(label))
    #     line = f.readline()
    # f.close()
    image_names = os.listdir(FLAGS.data_dir)

    f = open(os.path.join(FLAGS.meta_dir, 'spc_classes.txt'), 'r')
    meta = {}
    line = f.readline()
    while line:
        label, class_name = line.split(' ')
        class_name = class_name[0:-1]
        meta[int(label)] = class_name
        line = f.readline()
    f.close()
    # confusion = np.zeros(shape=(10, 10), dtype=np.uint32)
    # confusion_i = np.zeros(shape=(10, 10), dtype=np.uint32)
    # total = 0.
    # correct = 0.
    # total_p = 0.
    # correct_p = 0.
    with tf.Session(config = config) as sess:
        if tf.gfile.Exists(os.path.join(FLAGS.ckpt_dir, 'checkpoint')):
            saver.restore(sess, tf.train.latest_checkpoint(FLAGS.ckpt_dir) if FLAGS.model_name is None else os.path.join(FLAGS.ckpt_dir, FLAGS.model_name))
        else:
            raise RuntimeError("Check point files don't exist!")

        for i in range(len(image_names)):
            # label = labels[i]
            # class_name = meta[label]
            image_name = image_names[i]
            full_path = os.path.join(FLAGS.data_dir, image_name)
            img = plt.imread(full_path)
            if img.shape[2] == 4:
                img = img[:,:,0:3]
            data = np.ndarray(shape=(FLAGS.patches, FLAGS.patch_size, FLAGS.patch_size, 3), dtype=np.float32)
            for n, patch in enumerate(get_patches(img, FLAGS.patches, FLAGS.patch_size)):
                patch = standardization(patch)
                data[n, :] = patch
            # data = standardization(data)
            prediction = sess.run(pred, feed_dict={x: data})
            prediction = np.argmax(prediction, 1)
            # for n in prediction0:
            #     if n == label:
            #         correct_p = correct_p + 1
            #     confusion[label, n] = confusion[label, n] + 1
            # total_p = total_p + FLAGS.patches
            count = np.bincount(prediction)
            prediction = np.argmax(count)
            # prediction = np.sum(prediction, 0)
            #print(prediction)
            # prediction = np.argmax(prediction)

            print("%s,%s" % (image_name, meta[prediction]), file=ff)
            ff.flush()

    ff.close()

if __name__ == '__main__':
    tf.app.run()


import random

import pyForms.ControlBase

class Control(pyForms.ControlBase.Base):
	def __init__(self, obj):
		super().__init__(obj)

		#render config
		self.tagname = "input"
		self.isSelfClosing = True
		self.attributes['type'] = 'file'

		self.name = str(random.randint(100,999))
		if self.id is not None:
			self.name = self.attributes['id'] + "_" + self.name

		self.attributes['name'] = self.name
		self.uploadHandler = self.getEventHandler("upload")

		self.file = None

	def onRequest(self):
		if self.name in self.pageInstance.request.files:
			self.file = self.pageInstance.request.files[self.name]

	def fireEvents(self):
		if self.name in self.pageInstance.request.files and self.uploadHandler:
			self.uploadHandler()

	def render(self):
		return super().render()


#!/usr/bin/env python

import sys
sys.argv.append( '-b-' )
import ROOT
from ROOT import std
ROOT.gROOT.SetBatch(True)
sys.argv.remove( '-b-' )

ROOT.gStyle.SetOptStat(0)
ROOT.gStyle.SetOptTitle(0)
from uncertainties import unumpy
import numpy as np
import os
import datetime

from math import hypot, sqrt, ceil

import argparse
import htcondor

m_list = ['1500_1000','1500_1200','1600_1100','1700_1200','1800_1300','1900_100','1900_1000','1900_800','2200_100','2200_800']
b_list = ['DiLepTT','DY','QCD','SemiLepTT','SingleT','TTV','VV','WJ','Data']
others_bkg = ['DY','SingleT','TTV','VV','WJ'] # keep the QCD out 'QCD'

CRs = ['SR','CR2','CR3','CR4']

bkg_dires = []

for m in m_list :
    small_list = []
    for b in b_list:
        small_list.append(b+'/'+m)
    bkg_dires.append(small_list)

def hadd1ds(histList):
    '''  A functon to hadd background and set it's style '''
    sumbkg = ROOT.TH1F(histList[0].Clone())
    sumbkg.Reset()
    for bkghist in histList :
        sumbkg.Add(bkghist)
    #sumbkg.Draw('goff')
    sumbkg.SetTitle('Total BKG')
    sumbkg.SetName('sumbkg')
    return sumbkg

if __name__ == '__main__':

    parser = argparse.ArgumentParser(description='Runs a NAF batch system for nanoAOD', formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument('--infile', help='List of datasets to process', metavar='infile')
    parser.add_argument('--outdir', help='output dir', metavar='outdir')
    parser.add_argument('--syst', help='systematics',default="nom", metavar='syst')

    args = parser.parse_args()
    infile = args.infile
    syst = args.syst
    outdir = os.path.join(args.outdir,syst)

    if not os.path.exists(outdir):os.makedirs(outdir)
    if os.path.exists(outdir+'/alphabetagammaTable.tex'):
        os.remove(outdir+'/alphabetagammaTable.tex')
    if os.path.exists(outdir+'/alphabetagammaTable.txt'):
            os.remove(outdir+'/alphabetagammaTable.txt')

    latexalphabetagamma = open(outdir+'/alphabetagammaTable.tex', "a+")
    textalphabetagamma = open(outdir+'/alphabetagammaTable.txt', "a+")
    textalphabetagamma.write("{:<20}{:<12}{:<15}{:<12}{:<15}{:<12}{:<15}".format('mass','alpha','alphaE','beta' ,'betaE', 'gamma','gammaE')+" \n")

    latexalphabetagamma.write("\\documentclass[a4paper,11pt]{article} \n")
    latexalphabetagamma.write("\\usepackage{longtable} \n")
    latexalphabetagamma.write("\\begin{document} \n")
    latexalphabetagamma.write("\\begin{longtable}{|c || c | c | c| c|c|} \n")
    latexalphabetagamma.write("\\hline \n")

    f = ROOT.TFile.Open(infile, "read")
    mass_dir = outdir
    if not os.path.exists(mass_dir):os.makedirs(mass_dir)

    otherSR = ROOT.TH1F('otherSR','otherSR',10000,0.0,1.0)
    otherCR1 = ROOT.TH1F('otherCR1','otherCR1',10000,0.0,1.0)
    otherCR2 = ROOT.TH1F('otherCR2','otherCR2',10000,0.0,1.0)
    otherCR3 = ROOT.TH1F('otherCR3','otherCR3',10000,0.0,1.0)
    otherCR4 = ROOT.TH1F('otherCR4','otherCR4',10000,0.0,1.0)

    txtSR  = open(mass_dir+'/SR.txt', "w+")
    txtCR1 = open(mass_dir+'/CR1.txt', "w+")
    txtCR2 = open(mass_dir+'/CR2.txt', "w+")
    txtCR3 = open(mass_dir+'/CR3.txt', "w+")
    txtCR4 = open(mass_dir+'/CR4.txt', "w+")
    txtalphabetagamma = open(mass_dir+'/alphabetagamma.txt', "w+")

    WJ_1 = 0 ; WJ_2 = 0 ; WJ_3 = 0 ; WJ_4 = 0
    TTl_1 = 0 ; TTl_2 = 0 ; TTll_2 = 0 ; Data_2 = 0
    TTll_1 = 0 ;TTl_3 = 0 ; TTll_3 = 0 ; Data_3 = 0
    TTl_4 = 0 ; TTll_4 = 0 ; Data_4 = 0
    err   = ROOT.Double(0.) ; err_1 = ROOT.Double(0.) ; err_3 = ROOT.Double(0.)  ;err_4 = ROOT.Double(0.)  ;err_5 = ROOT.Double(0.)  ;err_6 = ROOT.Double(0.)
    err_7 = ROOT.Double(0.) ; err_8 = ROOT.Double(0.) ; err_9 = ROOT.Double(0.)  ;err_10 = ROOT.Double(0.) ;err_11 = ROOT.Double(0.) ;err_12 = ROOT.Double(0.)
    err_13 = ROOT.Double(0.) ; err_14 = ROOT.Double(0.) ; err_15 = ROOT.Double(0.)  ;err_16 = ROOT.Double(0.) ;err_17 = ROOT.Double(0.) ;err_18 = ROOT.Double(0.)
    err_2 = ROOT.Double(0.)  ;err_0   = ROOT.Double(0.) ;err_00   = ROOT.Double(0.);err_000   = ROOT.Double(0.)

    bkg_list = b_list

    for bkg in bkg_list :
        tdir = f.Get(bkg)
        hList = tdir.GetListOfKeys()
        for i in range(0,len(hList)):
            hname = (hList)[i].GetName()
            if "Data" in bkg :
                if "Jec" in syst :
                    if not '_'+syst in hname: continue
                elif not '_nom' in hname: continue
            else :
                if not '_'+syst in hname: continue
            hist = tdir.Get(hname)
            if not 'sig' in hname : continue
            for obkg in others_bkg :
                if (obkg in bkg and '_SR' in hname ): otherSR.Add(hist)
                if (obkg in bkg and '_CR1' in hname ): otherCR1.Add(hist)
                if (obkg in bkg and '_CR2' in hname ): otherCR2.Add(hist)
                if (obkg in bkg and '_CR3' in hname ): otherCR3.Add(hist)
                if (obkg in bkg and '_CR4' in hname ): otherCR4.Add(hist)
            if ("QCD" in bkg and '_SR' in hname ) : QCDSR  = hist
            if ("QCD" in bkg and '_CR1' in hname ): QCDCR1 = hist
            if ("QCD" in bkg and '_CR2' in hname ): QCDCR2 = hist
            if ("QCD" in bkg and '_CR3' in hname ): QCDCR3 = hist
            if ("QCD" in bkg and '_CR4' in hname ): QCDCR4 = hist

            #print(hname, hist.Integral())

            if ('_SR' in hname and not 'Data' in bkg):
                txtSR.write("{:<20}{:<20}{:<20}".format(hist.GetTitle(),round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err), 2), round(err, 2))+"\n")
                if 'SemiLepTT' in bkg  : TTl_1  = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_0), 2)
                if 'DiLepTT' in bkg    : TTll_1 = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_00), 2)
            elif '_CR1' in hname :
                txtCR1.write("{:<20}{:<20}{:<20}".format(hist.GetTitle(),round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err), 2), round(err, 2))+"\n")
            elif '_CR2' in hname :
                txtCR2.write("{:<20}{:<20}{:<20}".format(hist.GetTitle(),round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err), 2), round(err, 2))+"\n")
                if 'SemiLepTT' in bkg  : TTl_2  = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_1), 2)
                if 'DiLepTT' in bkg    : TTll_2 = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_2), 2)
                if 'Data' in bkg       :
                    # remving the QCD events from data
                    hist.Add(QCDCR2,-1)
                    Data_2 = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_3), 2)
            elif '_CR3' in hname :
                txtCR3.write("{:<20}{:<20}{:<20}".format(hist.GetTitle(),round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err), 2), round(err, 2))+"\n")
                if 'SemiLepTT' in bkg : TTl_3  = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_4), 2)
                if 'DiLepTT' in bkg   : TTll_3 = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_5), 2)
                if 'Data' in bkg     :
                    # remving the QCD events from data
                    hist.Add(QCDCR3,-1)
                    Data_3 = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_6), 2)
            elif '_CR4' in hname :
                txtCR4.write("{:<20}{:<20}{:<20}".format(hist.GetTitle(),round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err), 2), round(err, 2))+"\n")
                if 'SemiLepTT' in bkg  : TTl_4  = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_7), 2)
                if 'DiLepTT' in bkg    : TTll_4 = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_8), 2)
                if 'Data' in bkg       :
                    # remving the QCD events from data
                    hist.Add(QCDCR4,-1)
                    Data_4 = round(hist.IntegralAndError(0, hist.GetNbinsX()+1, err_9), 2)

    txtSR.write((60 *('='))+'\n')
    txtSR.write("{:<20}{:<20}{:<20}".format(otherSR.GetTitle(),round(otherSR.IntegralAndError(0, otherSR.GetNbinsX()+1, err_10), 2), round(err_10, 2))+"\n")
    WJ_1 = round(otherSR.IntegralAndError(0, otherSR.GetNbinsX()+1, err_000),2)
    txtCR1.write((60 *('='))+'\n')
    txtCR1.write("{:<20}{:<20}{:<20}".format(otherCR1.GetTitle(),round(otherCR1.IntegralAndError(0, otherCR1.GetNbinsX()+1, err_11), 2), round(err_11, 2))+"\n")
    txtCR2.write((60 *('='))+'\n')
    txtCR2.write("{:<20}{:<20}{:<20}".format(otherCR2.GetTitle(),round(otherCR2.IntegralAndError(0, otherCR2.GetNbinsX()+1, err_12), 2), round(err_12, 2))+"\n")
    WJ_2 = round(otherCR2.IntegralAndError(0, otherCR2.GetNbinsX()+1, err_12),2)
    txtCR3.write((60 *('='))+'\n')
    txtCR3.write("{:<20}{:<20}{:<20}".format(otherCR3.GetTitle(),round(otherCR3.IntegralAndError(0, otherCR3.GetNbinsX()+1, err_13), 2), round(err_13, 2))+"\n")
    WJ_3 = round(otherCR3.IntegralAndError(0, otherCR3.GetNbinsX()+1, err_13),2)
    txtCR4.write((60 *('='))+'\n')
    txtCR4.write("{:<20}{:<20}{:<20}".format(otherCR4.GetTitle(),round(otherCR4.IntegralAndError(0, otherCR4.GetNbinsX()+1, err_14), 2), round(err_14, 2))+"\n")
    WJ_4 = round(otherCR4.IntegralAndError(0, otherCR4.GetNbinsX()+1, err_14),2)

    del otherSR,otherCR1,otherCR2,otherCR3,otherCR4

    import scipy

    a = unumpy.umatrix([[TTl_2,TTll_2,WJ_2],[TTl_3,TTll_3,WJ_3],[TTl_4,TTll_4,WJ_4]],[[err_1,err_2,err_12],[err_4,err_5,err_13],[err_7,err_8,err_14]])

    b = unumpy.umatrix([[Data_2],[Data_3],[Data_4]],[[err_3],[err_6],[err_9]])

    #fun = lambda x: np.linalg.norm(np.dot(a,x)-b)
    #Y = minimize(fun, np.zeros(n), method='L-BFGS-B', bounds=[(0.,None) for x in range(n)])
    #Y = Y['x']
    #Y = np.linalg.solve(a,b)
    Y_ = a.I * b
    Y = np.squeeze(np.asarray(unumpy.nominal_values(Y_)))
    Yerr = np.squeeze(np.asarray(unumpy.std_devs(Y_)))

    #print (np.allclose(np.dot(a, Y), b))
    alpha, beta , gamma  = round(Y[0],2) , round(Y[1],2),round( Y[2],2)
    alphaerr, betaerr , gammaerr  = round(Yerr[0],2) , round(Yerr[1],2),round( Yerr[2],2)

    QCDSR_err = ROOT.Double(0.)
    QCDCR2_err = ROOT.Double(0.)
    QCDCR3_err = ROOT.Double(0.)
    QCDCR4_err = ROOT.Double(0.)

    QCDSR_yields = QCDSR.IntegralAndError(0, QCDSR.GetNbinsX()+1, QCDSR_err)
    QCDCR2_yields = QCDCR2.IntegralAndError(0, QCDCR2.GetNbinsX()+1, QCDCR2_err)
    QCDCR3_yields = QCDCR3.IntegralAndError(0, QCDCR3.GetNbinsX()+1, QCDCR3_err)
    QCDCR4_yields = QCDCR4.IntegralAndError(0, QCDCR4.GetNbinsX()+1, QCDCR4_err)

    txtalphabetagamma.write("{:<20}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}".format(' '             ,'SemiLepTT' ,' '                       ,'DiLepTT' ,' '                       ,'others' ,' '                       ,'Data' ,' ','MC QCD',' ')+"\n")
    txtalphabetagamma.write("{:<20}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}".format('SemiLepTTCat'  ,TTl_2       ,'+/-'+str(round(err_1,2)) ,TTll_2    ,'+/-'+str(round(err_2,2)) ,WJ_2     ,'+/-'+str(round(err_12,2)) ,Data_2 ,'+/-'+str(round(err_3,2)),round(QCDCR2_yields,2),'+/-'+str(round(QCDCR2_err,2)))+"\n")
    txtalphabetagamma.write("{:<20}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}".format('DiLepTTCat'    ,TTl_3       ,'+/-'+str(round(err_4,2)) ,TTll_3    ,'+/-'+str(round(err_5,2)),WJ_3     ,'+/-'+str(round(err_13,2)) ,Data_3 ,'+/-'+str(round(err_6,2 )),round(QCDCR3_yields,2),'+/-'+str(round(QCDCR3_err,2)))+"\n")
    txtalphabetagamma.write("{:<20}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}".format('othersCat'     ,TTl_4       ,'+/-'+str(round(err_7,2)) ,TTll_4    ,'+/-'+str(round(err_8,2)) ,WJ_4     ,'+/-'+str(round(err_14,2)) ,Data_4 ,'+/-'+str(round(err_9,2)),round(QCDCR4_yields,2),'+/-'+str(round(QCDCR4_err,2)))+"\n")
    txtalphabetagamma.write("{:<20}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}".format('SigCat'        ,TTl_1       ,'+/-'+str(round(err_0,2)) ,TTll_1    ,'+/-'+str(round(err_00,2)) ,WJ_1     ,'+/-'+str(round(err_000,2)) ,'---' ,'+/-'+'---',round(QCDSR_yields,2),'+/-'+str(round(QCDSR_err,2)))+"\n")

    txtalphabetagamma.write((60 *('='))+'\n')

    txtalphabetagamma.write("{:<20}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}".format(' ','alpha',' ','beta' ,' ', 'gamma',' ')+"\n")
    txtalphabetagamma.write("{:<20}{:<12}{:<10}{:<12}{:<10}{:<12}{:<10}".format(' ',alpha, '+/-'+str(alphaerr),beta ,'+/-'+str(betaerr), gamma,'+/-'+str(gammaerr) )+"\n")

    latexalphabetagamma.write("{:<40}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}".format(' & ','Single-lepton \ttJets' ,' &' ,'Dilepton \ttJets' ,' &'                       ,'\WJets' ,' &'                       ,'Data' ,' &','MC QCD',' ')+" \\\\ \n")
    latexalphabetagamma.write('\\hline\\hline \n')

    latexalphabetagamma.write("{:<40}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}".format('Single-lepton \ttJets cat. & ',TTl_2       ,' $\pm$ '+str(round(err_1,2))+'& ' ,TTll_2    ,' $\pm$ '+str(round(err_2,2))+'& ' ,WJ_2     ,' $\pm$ '+str(round(err_12,2))+'& ' ,Data_2,'$\pm$'+str(round(err_3,2))+'& ',round(QCDCR2_yields,2),'$\pm$'+str(round(QCDCR2_err,2)))+"\\\\ \n")
    latexalphabetagamma.write("{:<40}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}".format('Dilepton \ttJets cat. & '     ,TTl_3       ,' $\pm$ '+str(round(err_4,2))+'& ' ,TTll_3    ,' $\pm$ '+str(round(err_5,2))+'& ',WJ_3     ,' $\pm$ '+str(round(err_13,2)) +'& ',Data_3,'$\pm$'+str(round(err_6,2))+'& ',round(QCDCR3_yields,2),'$\pm$'+str(round(QCDCR3_err,2)))+"\\\\ \n")
    latexalphabetagamma.write("{:<40}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}".format('\WJets cat. &'                ,TTl_4       ,' $\pm$ '+str(round(err_7,2))+'& ' ,TTll_4    ,'  $\pm$ '+str(round(err_8,2)) +'& ',WJ_4     ,' $\pm$ '+str(round(err_14,2)) +'& ',Data_4,'$\pm$'+str(round(err_9,2))+'& ',round(QCDCR4_yields,2),'$\pm$'+str(round(QCDCR4_err,2)))+"\\\\ \n")
    latexalphabetagamma.write("{:<40}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}".format('T1tttt cat. &'                ,TTl_1       ,' $\pm$ '+str(round(err_0,2))+'& ' ,TTll_1    ,'  $\pm$ '+str(round(err_00,2)) +'& ',WJ_1     ,' $\pm$ '+str(round(err_000,2)) +'& ','---','$\pm$ ---'+'& ',round(QCDSR_yields,2),'$\pm$'+str(round(QCDSR_err,2)))+"\\\\ \n")

    latexalphabetagamma.write('\\hline\\hline \n')

    latexalphabetagamma.write("{:<40}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}".format('   & ','$\\alpha$',' & ','$\\beta$' ,' & ', '$\\gamma$','   & &')+"\\\\ \n")
    latexalphabetagamma.write('\\hline\\hline \n')
    latexalphabetagamma.write("{:<40}{:<20}{:<10}{:<20}{:<10}{:<20}{:<10}".format('   & ',alpha, ' $\pm$ '+str(alphaerr)+' & ',beta ,' $\pm$ '+str(betaerr)+' & ', gamma,' $\pm$ '+str(gammaerr)+' &  &  \\\\' )+"\n")
    latexalphabetagamma.write('\\hline\\hline\\hline \n')
    textalphabetagamma.write("{:<20}{:<12}{:<15}{:<12}{:<15}{:<12}{:<15}".format("" ,alpha, str(alphaerr) ,beta ,str(betaerr), gamma,str(gammaerr) )+"\n")

    latexalphabetagamma.write("\\caption{ Normalizaton parameters for backgrounds, calculated from control categories.}")
    latexalphabetagamma.write("\\label{normalize}")
    latexalphabetagamma.write("\\end{longtable}\n")
    latexalphabetagamma.write("\\end{document} \n")


#!/opt/csw/bin/python
# coding=utf-8

from urllib import urlopen
import re
import json

youtubeUrlRe = re.compile('(youtube\.com/watch\?v=|youtube\.com/watch\?.*&v=|youtu.be/)(?P<id>[A-Za-z0-9_-]{11})')

def getResponseType():
    return "MSG"

def get(msg, author, folder):
    matches = re.findall(youtubeUrlRe, msg)
    if (not matches):
        return
    response = []
    for match in matches:
        id = match[1]
        url = 'http://gdata.youtube.com/feeds/api/videos/' + id + '?v=2&alt=jsonc'
        result = urlopen(url).read()
        info = json.loads(result)
        if ('error' in info):
            continue
        title = info['data']['title'].encode("utf-8")
        response.append(title)
    return response


from .jsonrpc import *

class TERPCServerError(FixedErrorMessageMixin, ServerError):
    jsonrpc_error_code = -40001
    message = 'Test Engine Internal error'

    def __init__(self, msg=''):
        super(TERPCServerError, self).__init__()
        if msg:
            self.message = msg

class TERPCRequest(JSONRPCRequest):
    def _to_dict(self):
        jdata = {
            'jsonrpc' : JSONRPCProtocol.JSON_RPC_VERSION,
            'id' : self.unique_id,
            'method' : self.method,
            'args' :  self.args,
            'kwargs' : self.kwargs
        }
        return jdata

class TERPCProtocol(JSONRPCProtocol):

    '''
    if no error, the reply should be: dict(id='some_id', jsonrpc='version', result=PASS/FAIL, returned='some value'}
    if the function call expects a result, meaning Param2 is not emptied, then returned should have the returned value,
    otherwise there should be no returned
    if error, the reply should be: dict(id='some_id', 'jsonrpc'='version', 'error'=dict(code=error_code, message='error message'}
    '''

    def __init__(self, *args, **kwargs):
        super(TERPCProtocol, self).__init__(*args, **kwargs)

    def create_request(self, function, params, unit='', timeout=3000):
        request = TERPCRequest()

        request.unique_id = self._get_unique_id()
        request.method = function
        if params is None:
            request.args = []
        else:
            request.args = params

        request.kwargs = {"timeout":timeout, "unit": unit}

        return request

    def parse_reply(self, data):
        #receive variable value
        try:
            rep = json.loads(data)
        except Exception as e:
            raise InvalidReplyError(e)

        for k in rep.keys():
            if not k in JSONRPCProtocol._ALLOWED_REPLY_KEYS:
                raise InvalidReplyError('Key not allowed: %s' % k)

        if not 'jsonrpc' in rep:
            raise InvalidReplyError('Missing jsonrpc (version) in response.')

        if rep['jsonrpc'] != JSONRPCProtocol.JSON_RPC_VERSION:
            raise InvalidReplyError('Wrong JSONRPC version')

        if not 'id' in rep:
            raise InvalidReplyError('Missing id in response')

        if 'error' in rep:
            response = JSONRPCErrorResponse()
            error = rep['error']
            response.error = error['message']
            response.version=rep['jsonrpc']
            response.unique_id = rep['id']
            response._jsonrpc_error_code = error['code']
        else:
            response = JSONRPCSuccessResponse()
            response.result = rep.get('result', None)
            response.unique_id = rep.get('id')
            response.version = rep.get('jsonrpc')

        response.unique_id = rep['id']
        response.method = rep.get("method", None)
        return response

    def _parse_subrequest(self, req):
        for k in req.keys():
            if not k in JSONRPCProtocol._ALLOWED_REQUEST_KEYS:
                raise JSONRPCInvalidRequestError('key in request not allowed')

        if req.get('jsonrpc', None) != JSONRPCProtocol.JSON_RPC_VERSION:
            raise JSONRPCInvalidRequestError('json rpc version unmatched')

        if 'method' not in req:
            raise JSONRPCInvalidRequestError('missing function in request')

        request = TERPCRequest()
        request.method = str(req['method'])
        request.unique_id = req.get('id')
        request.args = req.get('args', [])
        request.version = req.get('jsonrpc')
        request.kwargs = req.get('kwargs', {})

        return request


import torch
import torch.nn as nn
import torch.optim as optim
import torchvision
import torchvision.transforms as transforms
import pandas as pd
from datetime import datetime
import numpy as np
import cv2
import os
import sys
import time
import argparse
import random
from torch.autograd import Variable
from nloss import normLSFLoss
import torchvision.models as models

#just rename models.resnet50 to models.resnet18 similar...
resnet50 = models.resnet50(pretrained=False)
densenet = models.densenet121(pretrained=False)

mobilenet = models.mobilenet_v2(pretrained=False)

from efficientnet_pytorch import EfficientNet
efficientnet = EfficientNet.from_name('efficientnet-b0')

mean_x, std_x = (0.500548956397424, 0.464450589729188, 0.5005489563974249), (0.2534465549796417, 0.2510691153272786, 0.2534465549796417)
def seed_everything(seed=13):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    os.environ['PYTHONHASHSEED'] = str(seed)
    torch.backends.cudnn.benchmark = False
    torch.backends.cudnn.deterministic = True

args = {
        'num_gpus': 1,
        'ckpt_dir': 'ckpt/lce/1resnet50/',
        'epochs': 50,
        'batch_size': 32,
        'val_batch_size': 100,
        'lr' : 0.1,
        'lr_schedule': 2,
        'momentum': 0.9,
        'nesterov': False,
        'weight_decay': 0.000001,
        }

if not os.path.exists(args['ckpt_dir']):
    os.makedirs(args['ckpt_dir'])

def adjust_learning_rate(optimizer, epoch):
    if args['lr_schedule'] == 0:
        lr = args['lr'] * ((0.2 ** int(epoch >= 20)) * (0.2 ** int(epoch >= 80)) * (0.2 ** int(epoch >= 150) * (0.2 ** int(epoch >= 180))))
    elif args['lr_schedule'] == 1:
        lr = args['lr'] * ((0.1 ** int(epoch >= 150)) * (0.1 ** int(epoch >= 225)))
    elif args['lr_schedule'] == 2:
        lr = args['lr'] * ((0.1 ** int(epoch >= 20)) * (0.1 ** int(epoch >= 40)))
    else:
        raise Exception("Invalid learning rate schedule!")
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr
    return lr

# Training
def train(train_loader, model, criterion, optimizer):
    model.train()
    lossl= []
    for batch_idx, (inputs, targets) in enumerate(train_loader):
        inputs, targets = inputs.cuda(), targets.cuda()
        optimizer.zero_grad()
        outputs = model(inputs)
        loss = criterion(outputs, targets)
        loss.backward()
        optimizer.step()
        lossl.append(loss.item())
    tloss= np.mean(np.array(lossl))
    return tloss

# Evaluating
def eval(test_loader, model, epoch, lr, best_acc):
    model.eval()
    correct,total = 0,0
    lossl=[]
    with torch.no_grad():
        for batch_idx, (inputs, targets) in enumerate(test_loader):
            inputs, targets = inputs.cuda(), targets.cuda()
            outputs = model(inputs)
            _, predicted = torch.max(outputs.data, 1)
            total += targets.size(0)
            correct += (predicted == targets).sum().item()
            loss = criterion(outputs, targets)
            lossl.append(loss.item())
    print('Epoch:',epoch, 'Accuracy: %f %%' % (100 * correct / total), 'Best Accuracy:', best_acc, 'lr:', lr)

    vloss= np.mean(np.array(lossl))
    return (float(100 * correct / total)), vloss

if __name__ == '__main__':

    seed_everything(13)
    print('To train and eval on climate dataset......')
    num_classes = 3
    transform_train = transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.RandomHorizontalFlip(),
        transforms.ToTensor(),
        transforms.Normalize(mean_x, std_x),
    ])
    transform_test = transforms.Compose([
        transforms.Resize((224, 224)),
        transforms.ToTensor(),
        transforms.Normalize(mean_x, std_x),
    ])
    train_set = torchvision.datasets.ImageFolder(root='../new_dataset/train', transform=transform_train)
    train_loader = torch.utils.data.DataLoader(train_set, batch_size=args['batch_size'], shuffle=True,
                                               num_workers=4)

    test_set = torchvision.datasets.ImageFolder(root='../new_dataset/valid',  transform=transform_test)
    test_loader = torch.utils.data.DataLoader(test_set, batch_size=args['val_batch_size'], shuffle=False, num_workers=4)

    print('==> Building model..',args['ckpt_dir'][5:] )

    # For Efficient Net
    # efficientnet._fc = nn.Linear(1280, num_classes, bias=True)
    # model  = efficientnet.cuda()

    #For Resnet Waale koi bhi
    num_ftrs = resnet50.fc.in_features
    resnet50.fc = nn.Linear(num_ftrs, num_classes)
    model = resnet50.cuda()

    #For Mobilenet
    # mobilenet.classifier = nn.Linear(1280, num_classes)
    # model  = mobilenet.cuda()

    # densenet.classifier = nn.Linear(1024, num_classes)
    # model  = densenet.cuda()

    #CE

    criterion =normLSFLoss(gamma=0.0, smoothing=0.1, reduction='mean')
    optimizer = optim.SGD(model.parameters(), lr=args['lr'], momentum=args['momentum'], nesterov=args['nesterov'],weight_decay=args['weight_decay'])
    best_acc = 0
    start_epoch = 0
    tlossl, vlossl = [], []
    for epoch in range(start_epoch, args['epochs']):
        lr = adjust_learning_rate(optimizer, epoch + 1)
        tloss = train(train_loader, model, criterion, optimizer)
        acc, vloss = eval(test_loader, model, epoch, lr, best_acc)
        if acc > best_acc:
            best_acc = acc
            torch.save(model.state_dict(), os.path.join(args['ckpt_dir'], 'best_epoch' + '.pth.tar'))
        tlossl.append(tloss)
        vlossl.append(vloss)
    dict = {'train_loss': tlossl, 'val_loss': vlossl}
    df = pd.DataFrame(dict)
    df.to_csv(args['ckpt_dir'] + "/loss.csv")


#Question A26: WAP to print the system date.
import os
from datetime import date
import time

a=time.localtime()
print(a)
'''
#Question A27: WAP to find the age of a person by the given date of birth.
br=int(input('enter the year'))
today=date.today()
a=today.year-br
print(a)

Question B10: An electricity board charges according to the following rates:

For the first 100 units -   40 paisa per unit.

For the next 200 units -   50 paisa per unit.

beyond 300 units -  60 paisa per unit.

All users are charged meter charges also, which are Rs. 50/-

def charges():
          if unit<0 and unit>=100:
                    rate=unit*.40+50
          elif unit>100 and unit<=200:
                    rate=(unit-100)*0.50+100*0.40
          elif unit> 300:
                    rate=(100)*0.50+100*0.40+(unit-300)*0.60

          print(rate)
          return (rate)

unit=int(input("enter the unit of your electricity="))
charges()

#WAP to input a number (1 to 7) and
#print the weekday name according to the given number

def weekdays():

          days=['monday','tuesday','wednesday','thrudasy','friday','saturday','sunday']
          return days

day_name=int(input('Enter a number between 1 to 7 ='))
days=weekdays()
print(days[day_name-1])

B34: WAP to print all the even numbers between 1 and 50
B35: WAP to print all the odd numbers between 1 and 50

def even():
          for x in range(1,51):
                    if x%2==0:
                              print(x)

even()

def odd():
          for x in range(1,51):
                    if x%2!=0:
                              print(x)

odd()

B36: WAP to print the sum and average of first n natural numbers.

Question B37: WAP to print the sum and average of first n odd numbers.

Question B38: WAP to print the sum and average of first n even numbers.
'''
def sumave_naturalnumber():
          sum_natural=0
          for x in range(1,a+1):
                    sum_natural=x+sum_natural
                    x+=1
          print(sum_natural)
          average=sum_natural/a
          print(average)

def sumave_odd():
          sum_odd=0
          for x in range(1,a+1):
                    if x%2!=0:
                              sum_odd=x+sum_odd
                              x+=1
          print(sum_odd)
          average=sum_odd/a
          print(average)

def sumave_even():
          sum_even=0
          for x in range(1,a+1):
                    if x%2==0:
                              sum_even=x+sum_even
                              x+=1
          print(sum_even)
          average=sum_even/a
          print(average)
a=int(input('enter a number='))
sumave_naturalnumber()
sumave_odd()
sumave_even()
'''
a=int(input('enter a number='))
sum=0
for x in range(1,a+1):
         # sum=x+sum
          #x+=1

         # print(sum)
          if x%2==0:
                    sum=x+sum
                    x+=1
                    print(sum)
'''
#WAP to generate all combinations of 1, 2 and 3.
from itertools import permutations
a=permutations([1,2,3])
for i in a:
          print(i)
'''
(5) x + x2/2! + x3/3! + x4/4! + …….xn/n!

(6)x - x2/2! + x3/3! - x4/4! + …….xn/n
'''
import math
a=float(input("enter the value of ="))
n=float(input("enter the value of n="))
sum1=0
for x in range(a,a*n+1/math.factorial(n)):
          sum1=x+sum1
          x+=1
print(sum1)


#!/usr/bin/env python3

################################################################################
# read states                                                                  #
################################################################################

WING_SIZE = 8 # 17 residues windows PSSM input
IN_SIZE = (WING_SIZE * 2 + 1) * 20

dom_ids = open('index/test.ls').read().split()
while '' in dom_ids: dom_ids.remove('')

#######################################
# read PSSM

pssms={}
pssm_file=open('../cath/index/cath_s35.pssm')
for line in pssm_file:
    dom_id = line.strip()[1:]
    pssm_line = pssm_file.readline().strip()

    if dom_id not in dom_ids: continue

    pssm  = [-2.0] * 20 * WING_SIZE

    for residue_pssm in pssm_line.split():
        for score in residue_pssm.split('|'):
            pssm.append(float(score))

    pssm += [-2.0] * 20 * WING_SIZE
    pssms[dom_id]=pssm

pssm_file.close()

#######################################
# read residue exposure
expos={}
exp_file = open('index/cath_s35.exp')
for line in exp_file:
    dom_id = line.strip()[1:]
    exp_line = exp_file.readline().strip()

    if dom_id not in dom_ids: continue

    expo=[]
    for exp_str in exp_line.split():
        if exp_str == 'NA' :
            expo.append(exp_str)
        else :
            expo.append(float(exp_str))

    expos[dom_id]=expo

exp_file.close()

#######################################
# read secondary structure
ss_states  = {}

MAP_8_TO_4={'X':'X',
            'E':'E','B':'E',
            'H':'H',
            'G':'G',
            'C':'C','S':'C','T':'C','I':'C'}

str_file=open('../cath/index/cath_s35.dssp')
for line in str_file:
    dom_id = line.strip()[1:]
    ss_line = str_file.readline().strip()
    if dom_id not in dom_ids: continue

    ss=[]
    for c in ss_line:
        ss.append(MAP_8_TO_4[c])

    ss_5=[]
    ss_5.append(ss[0])
    for i in range(0,len(ss)-2):
        if ss[i]+ss[i+1]+ss[i+2] == 'CHH': ss_5.append('Hb'); continue
        if ss[i]+ss[i+1]+ss[i+2] == 'EHH': ss_5.append('Hb'); continue

        ss_5.append(ss[i+1])

    ss_5.append(ss[-1])
    ss_states[dom_id]=ss_5

str_file.close()

#######################################
# get states

dom_states={}
dom_targets={}
MAP_5_TO_i={'C':0,'E':1,'Hb':2,'H':3,'G':4}

for dom_id in dom_ids:
    states=[]
    targets=[]
    for i in range(len(ss_states[dom_id])):
        ss  = ss_states[dom_id][i]
        expo= expos[dom_id][i]
        target=[0.0]*10
        if ss == 'X' or expo == 'X':
            states.append('X')
            targets.append(target)
            continue
        state=MAP_5_TO_i[ss]
        if expo < 0.5:
            state +=5
        states.append(state)
        target[state]=1
        targets.append(target)

    dom_states[dom_id]=states
    dom_targets[dom_id]=targets

################################################################################
# test networks                                                                #
################################################################################

import sys
from snn import Snn

# ls res/y10_nets/* > t.ls
net_file_names=open('t.ls').read().split()
nets=[]
for file_name in net_file_names:
    net=Snn()
    net.read_net(file_name)
    nets.append(net)

avg_error=0

avg_out     =[0.0] * 10
state_sums  =[0.0] * 10
avg_real_out=[0.0] * 10

test_res_sum=0

from numpy import *

for dom_id in dom_ids:
    for i in range(len(dom_states[dom_id])):
        if dom_states[dom_id][i]=='X': continue

        test_res_sum +=1
        out=array([0.0]*10)
        for net in nets:
            net.propagate(pssms[dom_id][i*20:i*20+IN_SIZE])
            out += net.act_o

        out /= len(nets)

        avg_error -= dot(dom_targets[dom_id][i],log(out))

        state=dom_states[dom_id][i]
        state_sums[state] += 1

        avg_real_out[state] += out[state]
        for j in range(10):
            avg_out[j] += out[j]

avg_error /= test_res_sum
for i in range(10):
    avg_out[i] /= test_res_sum
    avg_real_out[i] /=state_sums[i]

print('avg_err',avg_error,'\n')
print('avg_out')
for i in range(10):
    print(avg_out[i])

print('\navg_real_out')
for i in range(10):
    print(avg_real_out[i])

################################################################################
# end                                                                          #
################################################################################


# Get access to parent directory
import os, sys
sys.path.append(os.path.dirname(os.getcwd()))

# Imports
import tensorflow as tf

class InceptionEncoder(tf.keras.Model):
    def __init__(self, embedding_dim):
        super(InceptionEncoder, self).__init__()
        # shape after fc == (batch_size, 64, embedding_dim)
        self.fc = tf.keras.layers.Dense(embedding_dim)

    def call(self, x):
        x = self.fc(x)
        x = tf.nn.relu(x)
        return x


#-*- encoding: utf-8 -*-
'''
Created on 2017/7/1 13:49
Copyright (c) 2017/7/1, 海牛学院版权所有.
@author: 青牛
'''
import sys
sys.path.append('/home/hadoop/hainiu_crawler')
from configs import config
from commons.util.log_util import LogUtil
import urllib2
import urllib

class SendSmsUtil:

    def send_sms(self, content, phone=config._ALERT_PHONE):
        """send alter sms for phone with content
        """
        l = LogUtil().get_base_logger()
        try:
            send_url = 'http://send.sms.hainiu.com:8080/s?command=cralwer&phone=%s&' % (phone)
            send_url += urllib.urlencode({'content':content.decode('utf-8').encode('gbk')})
            r = urllib2.urlopen(send_url).read()
            if '0-OK' != r:
                l.error("短信发送失败,短信服务器返回状态为:%s,手机号:%s,内容:%s" % (r, phone, content))
                return False
        except:
            l.exception()
            return False
        return True

if __name__ == '__main__':
    SendSmsUtil().send_sms('你好''110')


import os, inspect, pickle, json, nltk
from nltk.util import bigrams

DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = DIR + '/../'

def extract(sentence, stations_tagger=None, stations_list=None):
    """
    it use 2 strategies:
    1. key-word based search (using predefined list of stations)
    2. free-text search (using UnigramTagger - see categorize_stations() )
    if there were results from key-word strategy:
      return them
    else
      return results from free-text strategy

    :param sentence: string where we want to find stations
    :param stations_tagger: UnigramTagger
    :param stations_list: string[]
    :return: list of tuples:
     [
        ("from", ""),
        ("unknown station", "STATION"),
        ("to", ""),
        ("horsham", "STATION"),
     ],
    """
    stations_list = load_stations_list() if stations_list is None else stations_list
    keywords_result = tag_stations_using_keywords(sentence, stations_list)

    if len(list(filter(lambda token: token[1] == 'STATION', keywords_result))) > 0:
        return keywords_result

    stations_tagger = load_trained_tagger() if stations_tagger is None else stations_tagger
    tagging_result = categorize_stations(sentence, stations_tagger)

    return tagging_result

def load_stations_list():
    file_path = os.path.dirname(
        os.path.abspath(inspect.getfile(inspect.currentframe()))
    ) + '/assets/stations_list.txt'
    with open(file_path) as f:
        stations_list = [line.strip().lower() for line in f if len(line.strip()) > 0]

    return stations_list

def train_tagger():
    """
    Get new, freshly trained instance of UnigramTagger.
    :return:
    """
    train_data_input = json.load(open(ROOT_DIR + '/src/assets/training_sets/stationsExtractionTrainingSet.json'))
    train_data = [[(element["pos"], element["classification"]) for element in sentence] for sentence in
                  train_data_input]
    tagger = nltk.UnigramTagger(train_data)
    pickle.dump(tagger, open(ROOT_DIR + "/src/assets/trained_classifiers/stations_classifier.p", "wb"))

    return tagger

def load_trained_tagger():
    """
    load already trained classifier
    :return:
    """
    return pickle.load(open(ROOT_DIR + "/src/assets/trained_classifiers/stations_classifier.p", "rb"))

def categorize_stations(text, stations_tagger: nltk.UnigramTagger = None):
    """
    Categorize stations in a "smart way" - use it to find stations which are not known.

    :param text: simple string
    :param stations_tagger: nltk.UnigramTagger - use load_trained_tagger() to get trained one
    :return:
    """
    stations_tagger = load_trained_tagger() if stations_tagger is None else stations_tagger

    tagged_sentence = nltk.pos_tag(nltk.word_tokenize(text))
    tagged_pos = stations_tagger.tag([element[1] for element in tagged_sentence])
    tagging_result = list(map(
        lambda tagged_word: (tagged_word[0][0], tagged_word[1][1]),  # extract (<word>, <category>)
        list(zip(tagged_sentence, tagged_pos))  # merge (<word>, <pos>) with (<pos>, <category>)
    ))
    return _tag_stations_full_names(tagging_result)

def _tag_stations_full_names(tagged_sentence):
    """
    I'm too lame in functional programming to do it in functional way :)
    Probably Knuth-Smith-Pratt algorithm could be used here, but first I implemented that,
    and then I discovered KSP algorithm :D

    :param tagged_sentence:
    [
        ('Plan', 'O'), ('me', 'O'), ('a', 'O'), ('journey', 'O'), ('from', 'O'),
        ('Manchester', 'STATION'), ('Airport', 'STATION'), ('to', 'O'), ('London', 'STATION')
    ]
    :return:
    [
        ('Plan', ''), ('a', ''), ('journey', ''), ('from', ''),
        ('Manchester Airport', 'STATION'), ('to', ''), ('London', 'STATION')
    ]
    """
    result = []
    is_first_element = True

    for (word1, class1), (word2, class2) in list(bigrams(tagged_sentence)):
        # special handling for 1st element of sequence
        if is_first_element:
            is_first_element = False
            if class1 != 'STATION':
                result.append((word1.lower(), ''))
            else:
                result.append((word1.lower(), 'STATION'))

        # regular logic for all other elements
        if class2 != 'STATION':
            result.append((word2.lower(), ''))
            continue

        if class1 == 'STATION':
            last_station = result.pop()
            result.append((last_station[0] + ' ' + word2.lower(), 'STATION'))
        else:
            result.append((word2.lower(), 'STATION'))

    return result

def tag_stations_using_keywords(sentence, stations_list):
    """
    :param sentence: string where we want to find stations
    :param stations_list: list of stations, all should be lower case.
    :return: list of tuples:
     [
        ("from", ""),
        ("london euston", "STATION"),
        ("to", ""),
        ("horsham", "STATION"),
     ],
    """

    sentence = sentence.lower()
    implode_marker = '____'
    stations_matched = []
    for station in stations_list:
        if station in sentence:
            station_tokenized = implode_marker.join(station.split(" "))
            sentence = sentence.replace(station, station_tokenized)
            stations_matched.append(station_tokenized)
    return [
        (token.replace(implode_marker, " "), "STATION" if token in stations_matched else "")
        for token in nltk.tokenize.word_tokenize(sentence)
    ]


# -*- coding: utf-8 -*-
# Copyright (c) 2014 Metaswitch Networks
# All Rights Reserved.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
felix.config
~~~~~~~~~~~~

Configuration management for Felix.

On instantiation, this module automatically parses the configuration file and
builds a singleton configuration object. Other modules should just import the
Config object and use the fields within it.
"""
import ConfigParser
import logging
import socket

from calico import common

# Logger
log = logging.getLogger(__name__)

class ConfigException(Exception):
    def __init__(self, message, path):
        super(ConfigException, self).__init__(message)
        self.file_path = path

    def __str__(self):
        return "%s (file path : %s)" % (self.message, self.file_path)

class Config(object):
    def __init__(self, config_path):
        self._KnownSections = set()
        self._KnownObjects  = set()

        self._config_path   = config_path

        self.read_cfg_file(config_path)

        self.EP_RETRY_INT_MS = int(
            self.get_cfg_entry("global",
                               "EndpointRetryTimeMillis",
                               500))
        self.RESYNC_INT_SEC  = int(
            self.get_cfg_entry("global",
                               "ResyncIntervalSecs",
                               1800))

        self.HOSTNAME        = self.get_cfg_entry("global",
                                                  "FelixHostname",
                                                  socket.gethostname())

        self.PLUGIN_ADDR     = self.get_cfg_entry("global",
                                                  "PluginAddress")
        self.ACL_ADDR        = self.get_cfg_entry("global",
                                                  "ACLAddress")
        self.METADATA_IP     = self.get_cfg_entry("global",
                                                  "MetadataAddr",
                                                  "127.0.0.1")
        self.METADATA_PORT   = self.get_cfg_entry("global",
                                                  "MetadataPort",
                                                  "9697")
        self.LOCAL_ADDR      = self.get_cfg_entry("global",
                                                  "LocalAddress",
                                                  "*")
        self.LOGFILE         = self.get_cfg_entry("log",
                                                  "LogFilePath",
                                                  "None")
        self.LOGLEVFILE      = self.get_cfg_entry("log",
                                                  "LogSeverityFile",
                                                  "INFO")
        self.LOGLEVSYS       = self.get_cfg_entry("log",
                                                  "LogSeveritySys",
                                                  "ERROR")
        self.LOGLEVSCR       = self.get_cfg_entry("log",
                                                  "LogSeverityScreen",
                                                  "ERROR")

        self.CONN_TIMEOUT_MS   = int(
            self.get_cfg_entry("connection",
                               "ConnectionTimeoutMillis",
                               40000))
        self.CONN_KEEPALIVE_MS = int(
            self.get_cfg_entry("connection",
                               "ConnectionKeepaliveIntervalMillis",
                               5000))

        self.validate_cfg()

        self.warn_unused_cfg()

        # Finally, convert log level names into python log levels.
        loglevels = {"none":      None,
                     "debug":     logging.DEBUG,
                     "info":      logging.INFO,
                     "warn":      logging.WARNING,
                     "warning":   logging.WARNING,
                     "err":       logging.ERROR,
                     "error":     logging.ERROR,
                     "crit":      logging.CRITICAL,
                     "critical":  logging.CRITICAL}

        self.LOGLEVFILE = loglevels[self.LOGLEVFILE.lower()]
        self.LOGLEVSYS  = loglevels[self.LOGLEVSYS.lower()]
        self.LOGLEVSCR  = loglevels[self.LOGLEVSCR.lower()]

    def read_cfg_file(self, config_file):
        self._parser = ConfigParser.ConfigParser()
        self._parser.read(config_file)

        # Build up the list of sections.
        self._items = {}
        for section in self._parser.sections():
            self._items[section] = dict(self._parser.items(section))

    def get_cfg_entry(self, section, name, default=None):
        name    = name.lower()
        section = section.lower()

        if section not in self._items:
            raise ConfigException("Section %s missing from config file" %
                                  section, self._config_path)

        item = self._items[section]

        if name in item:
            value = item[name]
            del item[name]
        elif default is None:
            raise ConfigException("Variable %s not defined in section %s" %
                                  (name, section), self._config_path)
        else:
            value = default

        return value

    def validate_cfg(self):
        #*********************************************************************#
        #* Firewall that the config is not invalid.                          *#
        #*********************************************************************#
        if self.METADATA_IP.lower() == "none":
            # Metadata is not required.
            self.METADATA_IP = None
            self.METADATA_PORT = None
        else:
            # Metadata must be supplied as IP or address, but we store as IP
            self.METADATA_IP = self.validate_addr("MetadataAddr",
                                                  self.METADATA_IP)

            if not common.validate_port(self.METADATA_PORT):
                raise ConfigException("Invalid MetadataPort value : %s" %
                                      self.METADATA_PORT, self._config_path)

        #*********************************************************************#
        #* Now the plugin and ACL manager addresses. These are allowed to be *#
        #* IP addresses, or DNS resolvable hostnames.                        *#
        #*********************************************************************#
        self.validate_addr("PluginAddress", self.PLUGIN_ADDR)
        self.validate_addr("ACLAddress", self.ACL_ADDR)

        #*********************************************************************#
        #* Bind address must be * or an IPv4 address. We allow hostnames,    *#
        #* but resolve them before use.                                      *#
        #*********************************************************************#
        if self.LOCAL_ADDR != "*":
            self.LOCAL_ADDR = self.validate_addr("LocalAddress",
                                                 self.LOCAL_ADDR)

        #*********************************************************************#
        #* Log file may be "None" (the literal string, either provided or as *#
        #* default). In this case no log file should be written.             *#
        #*********************************************************************#
        if self.LOGFILE.lower() == "none":
            # Metadata is not required.
            self.LOGFILE = None

    def warn_unused_cfg(self):
        #*********************************************************************#
        #* Firewall that no unexpected items in the config file - i.e. ones  *#
        #* we have not used.                                                 *#
        #*********************************************************************#
        for section in self._items.keys():
            for lKey in self._items[section].keys():
                log.warning("Got unexpected item %s=%s in %s" %
                             (lKey, self._items[section][lKey], self._config_path))

    def validate_addr(self, name, addr):
        """
        Validate an address, returning the IP address it resolves to. If the
        address cannot be resolved then an exception is returned.

        Parameters :
        - name of the field, for use in logging
        - address to resolve
        """
        try:
            stripped_addr = addr.strip()
            if not stripped_addr:
                raise ConfigException("Blank %s value" % name,
                                      self._config_path)

            return socket.gethostbyname(addr)
        except socket.gaierror:
            raise ConfigException("Invalid or unresolvable %s value : %s" %
                                  (name, addr),
                                  self._config_path)


# noinspection PyMethodMayBeStatic
class Solution(object):
    def numDecodings(self, s):
        """
        :type s: str
        :rtype: int
        """
        if not s:
            return 0

        # Array to store the subproblem results
        dp = [0 for _ in range(len(s) + 1)]

        dp[0] = 1
        # Ways to decode a string of size 1 is 1. Unless the string is '0'.
        # '0' doesn't have a single digit decode.
        dp[1] = 0 if s[0] == '0' else 1

        for i in range(2, len(dp)):
            # Check if successful single digit decode is possible.
            if s[i - 1] != '0':
                dp[i] += dp[i - 1]

            # Check if successful two digit decode is possible.
            two_digit = int(s[i - 2: i])
            if 10 <= two_digit <= 26:
                dp[i] += dp[i - 2]
        return dp[len(s)]

s = Solution()
ans = s.numDecodings('123413123223123123451')
print('answer:', ans)


# server.py
from SimpleXMLRPCServer import SimpleXMLRPCServer
import os

server = SimpleXMLRPCServer(('localhost', 9000))

def save_data(data):
    handle = open("x123.dat", "wb")
    handle.write(data)
    handle.close()

server.register_function(save_data, 'save_data')
server.serve_forever()


# -*- coding: utf-8 -*-
"""
Created on Sat Aug  1 13:01:34 2020

@author: qtckp
"""

import sys, os, io
sys.path.append(os.path.dirname('../'))

from model.detector import get_answer

if __name__=='__main__':

    # with io.open("train.txt",'r', encoding = 'utf-8') as f:
    #     doclines = f.readlines()

    with io.open("test.txt",'r', encoding = 'utf-8') as f:
        doclines = f.readlines()

    result = [(i, a, b, c, d) for i, (a,b,c,d) in enumerate(map(lambda sample: get_answer(sample), doclines))]

    with io.open("results.txt",'w', encoding = 'utf-8') as f:
        f.writelines('\t'.join(map(str, r)) + '\n' for r in result)


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

import re
import json

from django.db.models import Q
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from ..models import Booking
from .booking_add_view import run_work_id
from .booking_page_view import api_get_bookings, api_filter_bookings
from .utility.functions import check_key_detail
from customer.models import Principal, Shipper

@csrf_exempt
def api_save_edit_bookings(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            req = json.loads( request.body.decode('utf-8') )
            bookings = req['bookings']
            filter_mode = req['filter_mode']

            for booking in bookings:
                if not booking['date']:
                    booking['date'] = None
                if not booking['closing_date']:
                    booking['closing_date'] = None
                if not booking['return_date']:
                    booking['return_date'] = None

                pickup_tr = booking['pickup_tr']
                forward_tr = pickup_tr
                backward_tr = pickup_tr
                return_tr = pickup_tr
                if booking['yard_ndd'] == '1' or booking['yard_ndd'] == '2':
                    forward_tr = booking['forward_tr']
                    backward_tr = forward_tr
                    return_tr = forward_tr
                if booking['nextday'] == '1' or booking['nextday'] == '2':
                    backward_tr = booking['backward_tr']
                    return_tr = backward_tr
                if booking['fac_ndd'] == '1' or booking['fac_ndd'] == '3':
                    return_tr = booking['return_tr']
                elif booking['fac_ndd'] == '2':
                    backward_tr = booking['backward_tr']
                    return_tr = booking['return_tr']

                booking_save = Booking.objects.get(pk=booking['id'])

                if str(booking_save.date) != booking['date']:
                    work_id, work_number = run_work_id(booking['date'])
                    booking_save.work_id = work_id
                    booking_save.work_number = work_number

                booking_save.status = booking['status']
                booking_save.time = booking['time']
                booking_save.date = booking['date']
                if booking['principal']:
                    booking_save.principal = Principal.objects.get(pk=booking['principal']['id'])
                if booking['shipper']:
                    booking_save.shipper = Shipper.objects.get(Q(pk=booking['shipper']['id']))

                booking_save.agent = re.sub(' +', ' ', booking['agent'].strip().upper())
                booking_save.size = re.sub(' +', ' ', booking['size'].strip())
                booking_save.booking_no = re.sub(' +', ' ', booking['booking_no'].strip())
                booking_save.pickup_tr = re.sub(' +', ' ', pickup_tr.strip())
                booking_save.pickup_from = re.sub(' +', ' ', booking['pickup_from'].strip().upper())
                booking_save.yard_ndd = booking['yard_ndd']
                booking_save.forward_tr = re.sub(' +', ' ', forward_tr.strip())
                booking_save.factory = re.sub(' +', ' ', booking['factory'].strip().upper())
                booking_save.backward_tr = re.sub(' +', ' ', backward_tr.strip())
                booking_save.fac_ndd = booking['fac_ndd']
                booking_save.return_tr = re.sub(' +', ' ', return_tr.strip())
                booking_save.return_to = re.sub(' +', ' ', booking['return_to'].strip().upper())
                booking_save.container_no = re.sub(' +', ' ', booking['container_no'].strip())
                booking_save.seal_no = re.sub(' +', ' ', booking['seal_no'].strip())
                booking_save.tare = re.sub(' +', ' ', booking['tare'].strip())
                booking_save.closing_date = booking['closing_date']
                booking_save.closing_time = booking['closing_time']
                booking_save.remark = re.sub(' +', ' ', booking['remark'].strip())
                booking_save.nextday = booking['nextday']

                if not booking_save.detail:
                    booking_save.detail = {}

                booking_save.detail = check_key_detail(booking_save.detail, booking['detail'], 'shipper_text_color', True)

                if booking['nextday'] == '1' or booking['nextday'] == '2':
                    booking_save.return_date = booking['return_date']
                    booking_save.detail = check_key_detail(booking_save.detail, booking['detail'], 'return_time', True)

                else:
                    booking_save.pickup_date = booking['date']
                    booking_save.factory_date = booking['date']
                    booking_save.return_date = booking['date']
                    try:
                        booking_save.detail.pop('return_time')
                    except:
                        pass

                booking_save.vessel = re.sub(' +', ' ', booking['vessel'].strip())
                booking_save.port = re.sub(' +', ' ', booking['port'].strip())
                booking_save.save()

        if filter_mode:
            return api_filter_bookings(request)
        else:
            return api_get_bookings(request)
    return JsonResponse('Error', safe=False)

@csrf_exempt
def api_change_state_booking(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            req = json.loads( request.body.decode('utf-8') )

            booking_id = req['booking_id']
            state = req['state']

            booking = Booking.objects.get(pk=booking_id)
            if booking.status == '3' and state == '3':
                state = '1'
            booking.status = state
            booking.save()

            return JsonResponse(booking.status, safe=False)
    return JsonResponse('Error', safe=False)

@csrf_exempt
def api_change_color_field(request):
    if request.user.is_authenticated:
        if request.method == "POST":
            req = json.loads( request.body.decode('utf-8') )

            booking_id = req['id']
            field = req['field']
            color = {field: req['color']}

            booking = Booking.objects.get(pk=booking_id)
            if not booking.detail:
                booking.detail = {}
            booking.detail = check_key_detail(booking.detail, color, field, True)
            booking.save()

            if field in booking.detail:
                color_key = booking.detail[field]
            else:
                color_key = 0

            return JsonResponse(color_key, safe=False)
    return JsonResponse('Error', safe=False)


import os

from easydict import EasyDict
import numpy as np

import utils
from sklearn.neighbors import BallTree

def jump_to_closest_unviseted(model_kdtree_query, model_n_vertices, walk, enable_super_jump=True):
  for nbr in model_kdtree_query[walk[-1]]:
    if nbr not in walk:
      return nbr

  if not enable_super_jump:
    return None

  # If not fouind, jump to random node
  node = np.random.randint(model_n_vertices)

  return node

def get_seq_random_walk_no_jumps(mesh_extra, f0, seq_len):
  nbrs = mesh_extra['edges']
  n_vertices = mesh_extra['n_vertices']
  seq = np.zeros((seq_len + 1,), dtype=np.int32)
  jumps = np.zeros((seq_len + 1,), dtype=np.bool)
  visited = np.zeros((n_vertices + 1,), dtype=np.bool)
  visited[-1] = True
  visited[f0] = True
  seq[0] = f0
  jumps[0] = [True]
  backward_steps = 1
  for i in range(1, seq_len + 1):
    this_nbrs = nbrs[seq[i - 1]]
    nodes_to_consider = [n for n in this_nbrs if not visited[n]]
    if len(nodes_to_consider):
      to_add = np.random.choice(nodes_to_consider)
      jump = False
    else:
      if i > backward_steps:
        to_add = seq[i - backward_steps - 1]
        backward_steps += 2
      else:
        to_add = np.random.randint(n_vertices)
        jump = True
    assert to_add > -1
    seq[i] = to_add
    jumps[i] = jump
    visited[to_add] = 1

  return seq, jumps

def get_seq_random_walk_random_global_jumps(mesh_extra, f0, seq_len):
  nbrs = mesh_extra['edges']
  n_vertices = mesh_extra['n_vertices']
  seq = np.zeros((seq_len + 1,), dtype=np.int32)
  jumps = np.zeros((seq_len + 1,), dtype=np.bool)
  visited = np.zeros((n_vertices + 1,), dtype=np.bool)
  visited[-1] = True
  visited[f0] = True
  seq[0] = f0
  jumps[0] = [True]
  backward_steps = 1
  jump_prob = 1 / 100
  for i in range(1, seq_len + 1):
    this_nbrs = nbrs[seq[i - 1]]
    nodes_to_consider = [n for n in this_nbrs if not visited[n]]
    jump_now = np.random.binomial(1, jump_prob)
    # jump_now = (i+1) % jump_every_k
    if len(nodes_to_consider) and not jump_now:
      to_add = nodes_to_consider[np.random.randint(len(nodes_to_consider))]
      jump = False
      backward_steps = 1
    else:
      if i > backward_steps and not jump_now:
        to_add = seq[i - backward_steps - 1]
        backward_steps += 2
      else:
        to_add = np.random.randint(n_vertices)
        jump = True
        visited[...] = 0
        visited[-1] = True
        backward_steps = 1
        last_jump = i
    visited[to_add] = 1
    seq[i] = to_add
    jumps[i] = jump

  return seq, jumps

def get_seq_random_walk_euclidean_jumps(mesh_extra, f0, seq_len):
  '''
  Return random walk with jump every K steps, jumping with probability according to distance from current position!
  :param mesh_extra:
  :param f0:
  :param seq_len:
  :return:
  '''
  vertices = mesh_extra['vertices']
  ball_tree = BallTree(vertices)

  nbrs = mesh_extra['edges']
  n_vertices = mesh_extra['n_vertices']
  seq = np.zeros((seq_len + 1,), dtype=np.int32)
  jumps = np.zeros((seq_len + 1,), dtype=np.bool)
  visited = np.zeros((n_vertices + 1,), dtype=np.bool)
  visited[-1] = True
  visited[f0] = True
  seq[0] = f0
  jumps[0] = [True]
  backward_steps = 1
  jump_indices = 50
  last_jump = 0
  for i in range(1, seq_len + 1):
    this_nbrs = nbrs[seq[i - 1]]
    nodes_to_consider = [n for n in this_nbrs if not visited[n]]
    jump_now = (i+1) % jump_indices == 0
    if len(nodes_to_consider) and not jump_now:
      to_add = np.random.choice(nodes_to_consider)
      jump = False
      backward_steps = 1
    else:
      if i > backward_steps - last_jump and not jump_now:
        # TODO: try not to jump if not jump now
        # if i > backward_steps and not jump_now:
        to_add = seq[i - backward_steps - 1]
        backward_steps += 2
        # print(backward_steps)
      else:
        inds = ball_tree.query_radius(vertices[seq[i-1]].reshape(1, -1), r=0.5)[0]  # indices of neighbors with radius 0.5
        to_add = inds[np.random.randint(len(inds))]  # choose randomly from neighbors in radius
        jump = True
        visited[...] = 0
        visited[-1] = True
        backward_steps = 1
        last_jump = i
    visited[to_add] = 1
    seq[i] = to_add
    jumps[i] = jump

  return seq, jumps

  return

def get_seq_random_walk_random_global_jumps_new(mesh_extra, f0, seq_len):
  nbrs = mesh_extra['edges']
  n_vertices = mesh_extra['n_vertices']
  seq = np.zeros((seq_len + 1,), dtype=np.int32)
  jumps = np.zeros((seq_len + 1,), dtype=np.bool)
  visited = np.zeros((n_vertices + 1,), dtype=np.bool)
  visited_perm =  np.zeros((n_vertices + 1,), dtype=np.bool)
  visited_perm[-1] = True
  visited_perm[f0] = True
  visited[-1] = True
  visited[f0] = True
  seq[0] = f0
  jumps[0] = [True]
  backprop_stack = []
  jump_prob = 1 / 100
  for i in range(1, seq_len + 1):
    this_nbrs = nbrs[seq[i - 1]]
    nodes_to_consider = [n for n in this_nbrs if not visited[n]]
    # jump_now = np.random.binomial(1, jump_prob)
    jump_now = (i + 1) % 20 == 0
    if len(nodes_to_consider) and not jump_now:
      to_add = np.random.choice(nodes_to_consider)
      jump = False
      backprop_stack.append(i-1)
      # backward_steps = 1
    else:
      if len(backprop_stack) and not jump_now:
        to_add = seq[backprop_stack.pop()]
      else:
        backprop_stack = []
        visited_perm |= visited
        available_indices = np.where(visited_perm==False)[0]
        if len(available_indices):
          to_add = available_indices[np.random.randint(len(available_indices))]
        else:
          to_add = np.random.randint(n_vertices)
          visited_perm = np.zeros_like(visited)
          visited_perm[-1] = True
        jump = True
        visited[...] = 0
        visited[-1] = True
    visited[to_add] = 1
    seq[i] = to_add
    jumps[i] = jump

  return seq, jumps

def get_seq_random_walk_local_jumps(mesh_extra, f0, seq_len):
  n_vertices = mesh_extra['n_vertices']
  kdtr = mesh_extra['kdtree_query']
  seq = np.zeros((seq_len + 1, ), dtype=np.int32)
  jumps = np.zeros((seq_len + 1,), dtype=np.bool)
  seq[0] = f0
  visited = np.zeros((n_vertices + 1,), dtype=np.bool)
  visited[-1] = True
  visited[f0] = True
  for i in range(1, seq_len + 1):
    b = min(0, i - 20)
    to_consider = [n for n in kdtr[seq[i - 1]] if not visited[n]]
    if len(to_consider):
      seq[i] = np.random.choice(to_consider)
      jumps[i] = False
    else:
      seq[i] = np.random.randint(n_vertices)
      jumps[i] = True
      visited = np.zeros((n_vertices + 1,), dtype=np.bool)
      visited[-1] = True
    visited[seq[i]] = True

  return seq, jumps

def get_seq_random_walk_constant_global_jumps(mesh_extra, f0, seq_len):
  nbrs = mesh_extra['edges']
  n_vertices = mesh_extra['n_vertices']
  seq = np.zeros((seq_len + 1,), dtype=np.int32)
  backprop_inds = []
  jumps = np.zeros((seq_len + 1,), dtype=np.bool)
  visited = np.zeros((n_vertices + 1,), dtype=np.bool)
  visited[-1] = True
  visited[f0] = True
  seq[0] = f0
  jumps[0] = [True]
  jump_every_k = get_seq_random_walk_constant_global_jumps.k
  cur_len = 0
  for i in range(1, seq_len + 1):
    this_nbrs = nbrs[seq[i - 1]]
    nodes_to_consider = [n for n in this_nbrs if not visited[n]]
    jump_now = (i+1) % jump_every_k == 0
    if len(nodes_to_consider) and not jump_now:
      to_add = np.random.choice(nodes_to_consider)
      jump = False
      backprop_inds.append(i-1)
    else:
      if backprop_inds and not jump_now:
        to_add = seq[backprop_inds.pop()]
      else:
        to_add = np.random.randint(n_vertices)
        jump = True
        visited[...] = 0
        visited[-1] = True
        if jump_now:
          cur_len = 0
          backprop_inds = []
    cur_len += 1
    visited[to_add] = 1
    seq[i] = to_add
    jumps[i] = jump

  return seq, jumps

def get_mesh():
  from dataset_prepare import prepare_edges_and_kdtree, load_mesh, remesh
  from dataset import norm_model
  model_fn = os.path.expanduser('~') + '/Databases/ModelNet40/airplane/test/*690*.off'
  import glob
  model_fn = np.random.choice(glob.glob(model_fn))
  mesh = load_mesh(model_fn)
  mesh, _, _ = remesh(mesh, 4000)
  mesh = EasyDict({'vertices': np.asarray(mesh.vertices), 'faces': np.asarray(mesh.triangles), 'n_faces_orig': np.asarray(mesh.triangles).shape[0]})
  prepare_edges_and_kdtree(mesh)
  vertices = mesh['vertices']
  norm_model(vertices)
  mesh['vertices'] = vertices
  mesh['n_vertices'] = mesh['vertices'].shape[0]
  return mesh

def show_walk_on_mesh(mesh, i):
  # walk, jumps = get_seq_random_walk_no_jumps(mesh, f0=0, seq_len=400)
  walk, jumps = get_seq_random_walk_random_global_jumps(mesh, f0=0, seq_len=200)

  # get_seq_random_walk_constant_global_jumps.k = 10
  # walk, jumps = get_seq_random_walk_constant_global_jumps(mesh, f0=0, seq_len=400)
  # walk = [walk[i:i + 10] for i in range(1, len(walk), 10)]
  # walk = walk[:9]  # not enough colors in color map, and enough to visualize

  vertices = mesh['vertices']
  if 0:
    dxdydz = np.diff(vertices[walk], axis=0)
    for i, title in enumerate(['dx', 'dy', 'dz']):
      plt.subplot(3, 1, i + 1)
      plt.plot(dxdydz[:, i])
      plt.ylabel(title)
    plt.suptitle('Walk features on Human Body')
  save_name = '/home/ran/mesh_walker/examples'
  utils.visualize_model(mesh['vertices'], mesh['faces'],
                               line_width=1.2, show_edges=1, edge_color_a='black',
                               show_vertices=False, opacity=0.8,
                               point_size=4, all_colors='cadetblue',
                               walk=walk, edge_colors='magenta',
                               off_screen=True, save_fn=os.path.join(save_name, 'airplane_690_walk_{}.png'.format(i)))
  print('debug')

if __name__ == '__main__':
  utils.config_gpu(False)
  np.random.seed(4)
  for i in range(16):
    mesh = get_mesh()
    show_walk_on_mesh(mesh, i)
  print('debug')


#!/usr/bin/env python3.5
# encoding: utf-8
# Created by leiwei on 2020/8/14 15:20

# in 和 not in 运算符
# 用来判断一个内容在可迭代对象里是否存在

word = 'hello'

x = input('请输入一个字符：')

if x in word:
    print('存在')
else:
    print('不存在')


class Solution:
    # tow-pointer
    def twoSum(self, numbers, target):
        left, right = 0, len(numbers)-1
        while left < right:
            if numbers[left] + numbers[right] < target:
                left += 1
            elif numbers[left] + numbers[right] > target:
                right -= 1
            else:
                return [left+1, right+1]

    """
    # binary search
    def twoSum2(self, numbers, target):
        for i in range(len(numbers)):
            left, right = i+1, len(numbers)-1
            tmp = target - numbers[i]
            while left <= right:
                mid = left + (right-left)//2
                if numbers[mid] < tmp:
                    left = mid+1
                elif numbers[mid] > tmp:
                    right = mid-1
                else:
                    return [i+1, mid+1]

    # hash(dictionary)
    def twoSum1(self, numbers, target):
        myhash = {}
        for i, num in enumerate(numbers):
            if target-num in myhash:
                return [myhash[target-num]+1, i+1]
            else:
                myhash[num] = i
    """


#!/usr/bin/python3
# File name   : setup.py
# Date        : 2020/11/24

import os
import time

curpath = os.path.realpath(__file__)
thisPath = os.path.dirname(curpath)

def replace_num(file,initial,new_num):
    newline=""
    str_num=str(new_num)
    with open(file,"r") as f:
        for line in f.readlines():
            if(line.find(initial) == 0):
                line = (str_num+'\n')
            newline += line
    with open(file,"w") as f:
        f.writelines(newline)

for x in range(1,4):
	if os.system("sudo apt-get update") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install -U pip") == 0:
		break

for x in range(1,4):
	if os.system("sudo apt-get install -y python-dev python-pip libfreetype6-dev libjpeg-dev build-essential") == 0:
		break

for x in range(1,4):
	if os.system("sudo -H pip3 install --upgrade luma.oled") == 0:
		break

for x in range(1,4):
	if os.system("sudo apt-get install -y i2c-tools") == 0:
		break

for x in range(1,4):
	if os.system("sudo apt-get install -y python3-smbus") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install icm20948") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install flask") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install flask_cors") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install websockets") == 0:
		break

try:
	replace_num("/boot/config.txt",'#dtparam=i2c_arm=on','dtparam=i2c_arm=on\nstart_x=1')
except:
	print('try again')

for x in range(1,4):
	if os.system("sudo pip3 install numpy") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install opencv-contrib-python==3.4.3.18") == 0:
		break

for x in range(1,4):
	if os.system("sudo apt-get -y install libqtgui4 libhdf5-dev libhdf5-serial-dev libatlas-base-dev libjasper-dev libqt4-test") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install imutils zmq pybase64 psutil") == 0:
		break

for x in range(1,4):
	if os.system("sudo pip3 install pi-ina219") == 0:
		break

for x in range(1,4):
	if os.system("sudo apt-get install -y util-linux procps hostapd iproute2 iw haveged dnsmasq") == 0:
		break

for x in range(1,4):
	if os.system("cd " + thisPath + " && cd .. && sudo git clone https://github.com/oblique/create_ap") == 0:
		break

try:
	os.system("cd " + thisPath + " && cd .. && cd create_ap && sudo make install")
except:
	pass

replace_num('/etc/rc.local','exit 0','cd '+thisPath+' && sudo python3 webServer.py &\nexit 0')

print('Completed!')


'''
uix.gridlayout tests
========================
'''

import unittest
import pytest
from kivy.tests.common import GraphicUnitTest

from kivy.uix.gridlayout import GridLayout

class GridLayoutTest(unittest.TestCase):

    def test_gridlayout_get_max_widgets_cols_rows_None(self):
        gl = GridLayout()
        expected = None
        value = gl.get_max_widgets()
        self.assertEqual(expected, value)

    def test_gridlayout_get_max_widgets_rows_None(self):
        gl = GridLayout()
        gl.cols = 1
        expected = None
        value = gl.get_max_widgets()
        self.assertEqual(expected, value)

    def test_gridlayout_get_max_widgets_cols_None(self):
        gl = GridLayout()
        gl.rows = 1
        expected = None
        value = gl.get_max_widgets()
        self.assertEqual(expected, value)

    def test_gridlayout_get_max_widgets_with_rows_cols(self):
        gl = GridLayout()
        gl.rows = 5
        gl.cols = 3
        expected = 15
        value = gl.get_max_widgets()
        self.assertEqual(expected, value)

class UixGridLayoutTest(GraphicUnitTest):

    def test_rows_cols_sizes(self):
        # ref github issue #5278 _init_rows_cols_sizes fix
        # this combination could trigger an error
        gl = GridLayout()
        gl.cols = 1
        gl.cols_minimum = {i: 10 for i in range(10)}
        gl.add_widget(GridLayout())
        self.render(gl)

@pytest.mark.parametrize(
    "n_cols, n_rows, orientation, expectation", [
        (2, 3, 'lr-tb', [(0, 0), (1, 0), (0, 1), (1, 1), (0, 2), (1, 2)]),
        (2, 3, 'lr-bt', [(0, 2), (1, 2), (0, 1), (1, 1), (0, 0), (1, 0)]),
        (2, 3, 'rl-tb', [(1, 0), (0, 0), (1, 1), (0, 1), (1, 2), (0, 2)]),
        (2, 3, 'rl-bt', [(1, 2), (0, 2), (1, 1), (0, 1), (1, 0), (0, 0)]),
        (2, 3, 'tb-lr', [(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2)]),
        (2, 3, 'tb-rl', [(1, 0), (1, 1), (1, 2), (0, 0), (0, 1), (0, 2)]),
        (2, 3, 'bt-lr', [(0, 2), (0, 1), (0, 0), (1, 2), (1, 1), (1, 0)]),
        (2, 3, 'bt-rl', [(1, 2), (1, 1), (1, 0), (0, 2), (0, 1), (0, 0)]),
    ]
)
def test_create_idx_iter(
        n_cols, n_rows, orientation, expectation):
    from kivy.uix.gridlayout import GridLayout
    gl = GridLayout(orientation=orientation)
    index_iter = gl._create_idx_iter(n_cols, n_rows)
    assert expectation == list(index_iter)

@pytest.mark.parametrize("orientation", [
    'lr-tb', 'lr-bt', 'rl-tb', 'rl-bt',
    'tb-lr', 'tb-rl', 'bt-lr', 'bt-rl',
])
def test_create_idx_iter2(orientation):
    from kivy.uix.gridlayout import GridLayout
    gl = GridLayout(orientation=orientation)
    index_iter = gl._create_idx_iter(1, 1)
    assert [(0, 0)] == list(index_iter)

@pytest.mark.parametrize(
    "n_cols, n_rows, orientation, n_children, expectation", [
        (3, None, 'lr-tb', 4, [(0, 15), (10, 15), (20, 15), (0, 0)]),
        (3, None, 'lr-bt', 4, [(0, 0), (10, 0), (20, 0), (0, 15)]),
        (3, None, 'rl-tb', 4, [(20, 15), (10, 15), (0, 15), (20, 0)]),
        (3, None, 'rl-bt', 4, [(20, 0), (10, 0), (0, 0), (20, 15)]),
        (None, 3, 'tb-lr', 4, [(0, 20), (0, 10), (0, 0), (15, 20)]),
        (None, 3, 'tb-rl', 4, [(15, 20), (15, 10), (15, 0), (0, 20)]),
        (None, 3, 'bt-lr', 4, [(0, 0), (0, 10), (0, 20), (15, 0)]),
        (None, 3, 'bt-rl', 4, [(15, 0), (15, 10), (15, 20), (0, 0)]),
    ]
)
def test_children_pos(n_cols, n_rows, orientation, n_children, expectation):
    from kivy.uix.widget import Widget
    from kivy.uix.gridlayout import GridLayout
    gl = GridLayout(
        cols=n_cols, rows=n_rows, orientation=orientation,
        pos=(0, 0), size=(30, 30))
    for __ in range(n_children):
        gl.add_widget(Widget())
    gl.do_layout()
    actual_layout = [tuple(c.pos) for c in reversed(gl.children)]
    assert actual_layout == expectation

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


import sys
sys.path.append('.')
from dao.OperatorDAOSqliteImpl import OperatorDAOSqliteImpl
from model.Operator import Operator
import datetime

class TestOperatorDAOSqliteImpl:
    """
    This class was used during development.
    Tests functionalities of OperatorDAOSqliteImpl

    """

    def example1(self):
        """

        :return:
        """
        dao = OperatorDAOSqliteImpl()
        dao.drop_table()
        dao.create_table()
        l = [
            Operator(1, "foo", "bar", datetime.date(1991, 10, 10), "ai", "foobar@gmail.com"),
            Operator(2, "edu", "tilos", datetime.date(1992, 10, 10), "ai", "edutilos@gmail.com"),
            Operator(3, "leo", "messi", datetime.date(1993, 10, 10), "ai", "leomessi@gmail.com")
        ]

        for s in l:
            dao.save(s)

        all = dao.find_all()
        print("<<all operators>>")
        for s in all:
            print(s)

        # update
        dao.update(1, Operator(1, "new_foo", "new_bar", datetime.date(2001, 11, 11), "its", "new_foonewbar@gmail.com"))

        # find one
        one = dao.find_by_id(1)
        print("after update = {0}".format(one))

        # remove one
        dao.remove(1)
        all = dao.find_all()
        print("<<all operators after remove by enrolmentNumber = 1>>")
        for s in all:
            print(s)

tester = TestOperatorDAOSqliteImpl()
tester.example1()


#!/usr/bin/env python
"""The in memory database methods for flow handling."""

from grr.lib import rdfvalue
from grr.lib import utils

class InMemoryDBFlowMixin(object):
  """InMemoryDB mixin for flow handling."""

  @utils.Synchronized
  def WriteMessageHandlerRequests(self, requests):
    """Writes a list of message handler requests to the database."""
    now = rdfvalue.RDFDatetime.Now()
    for r in requests:
      flow_dict = self.message_handler_requests.setdefault(r.handler_name, {})
      cloned_request = r.Copy()
      cloned_request.timestamp = now
      flow_dict[cloned_request.request_id] = cloned_request

  @utils.Synchronized
  def ReadMessageHandlerRequests(self):
    """Reads all message handler requests from the database."""
    res = []
    leases = self.message_handler_leases
    for requests in self.message_handler_requests.values():
      for r in requests.values():
        res.append(r.Copy())
        existing_lease = leases.get(r.handler_name, {}).get(r.request_id, None)
        res[-1].leased_until = existing_lease

    return sorted(res, key=lambda r: -1 * r.timestamp)

  @utils.Synchronized
  def DeleteMessageHandlerRequests(self, requests):
    """Deletes a list of message handler requests from the database."""

    for r in requests:
      flow_dict = self.message_handler_requests.get(r.handler_name, {})
      if r.request_id in flow_dict:
        del flow_dict[r.request_id]
      flow_dict = self.message_handler_leases.get(r.handler_name, {})
      if r.request_id in flow_dict:
        del flow_dict[r.request_id]

  @utils.Synchronized
  def LeaseMessageHandlerRequests(self, lease_time=None, limit=1000):
    """Leases a number of message handler requests up to the indicated limit."""

    leased_requests = []

    now = rdfvalue.RDFDatetime.Now()
    zero = rdfvalue.RDFDatetime.FromSecondsSinceEpoch(0)
    expiration_time = now + lease_time

    leases = self.message_handler_leases
    for requests in self.message_handler_requests.values():
      for r in requests.values():
        existing_lease = leases.get(r.handler_name, {}).get(r.request_id, zero)
        if existing_lease < now:
          leases.setdefault(r.handler_name, {})[r.request_id] = expiration_time
          r.leased_until = expiration_time
          r.leased_by = utils.ProcessIdString()
          leased_requests.append(r)
          if len(leased_requests) >= limit:
            break

    return leased_requests


import os
import json

import logging
logger = logging.getLogger(__name__)
from django.http import HttpResponse

from django.http import Http404
from django.http import HttpResponseServerError
from django.core.exceptions import EmptyResultSet

from django.shortcuts import render, redirect
from django.views.generic import TemplateView, ListView, CreateView
from django.http import JsonResponse
from django.utils import timezone

# from django.contrib.staticfiles import finders
import pandas as pd

 #db
# from database.orm import DBRead

#s3
from aws.s3 import s3Bucket
from aws.ses import SES

from django.contrib.admin.views.decorators import staff_member_required
from django.contrib.auth import logout

import time

from django.conf import settings

from django.views.decorators.csrf import csrf_exempt
from django.conf.urls import url
from database.orm import Orders, Raw_query

dataTime= {
    "time": timezone.localtime(),
}

# views
class Home(TemplateView):
    template_name = 'home.html'

#logout
def logout_view(request):
    logout(request)
    return render(request,'home.html')

# -----------------------------------------for api-------------------------------------
class Demo():

    #/version/
    def version(request):
        print("\n\n*************************************version*************************************")

        dataJson= {
            "version": "1.0"
        }

        return JsonResponse(dataJson)

    #/test/s3/
    def s3(request):
        print("\n\n************************************* s3 test*************************************")

        #bucket='thrivee-dev/audiotranscribe'
        bucket=  'thrivee-dev'

        key= 'audiotranscribe/test.wav'

        fileName= 'media/' + key.split('/')[1]
        print(fileName)
        res= s3Bucket(bucket, key, fileName).loadFile()

        data= {
            "s3": res,
        }

        return JsonResponse(data)

    #/test/db
    def db(request):
        print("\n\n************************************* db test*************************************")

        data= {
            "db test": "data"
        }

        return JsonResponse(data)

    def ses(request):
        print("\n\n************************************* ese test*************************************")

        SES().gmail()

        data= {
            "ses": "ses",
        }

        return JsonResponse(data)

    @csrf_exempt
    def sensorsUpdate(request):
        print("\n\n************************************* sensorsUpdate *************************************")

        data = json.loads(request.body)

        if request.method == 'POST':
            print("POST...")

            sensors_id= data['sensors_id']
            serialNumber= data['serialNumber']
            metadata= data['metadata']

            Sensors().update(sensors_id, serialNumber, metadata)

            data_res= {
                "sensors_id": sensors_id,
                "serialNumber": serialNumber,
                "metadata": metadata,
            }

            return JsonResponse(data_res, safe=False)

    @csrf_exempt
    def heartUpdate(request):
        print("\n\n************************************* heart *************************************")
        data = json.loads(request.body)

        if request.method == 'POST':
            print("POST...")

            serialNumber= data['serialNumber']
            message= data['message']

            Heartbeats().update(serialNumber, message);

            data= {
                "serialNumber": serialNumber,
                "message": message,
            }

            return JsonResponse(data, safe=False)

    @csrf_exempt
    def data(request):
        print("\n\n************************************* data *************************************")

        # orm
        #data= Orders().all()
        #data= Orders().update()
        #data= Orders().create()

        #all_manager_method
        #data= Raw_query().all_manager_method()

        # custom_method
        data= Raw_query().all_custom_method()
        #data= Raw_query().update_custom_method()
        #data= Raw_query().create_custom_method()

        if not data:
            data= [{
                "test": "test",
            }]

        return JsonResponse(data, safe=False)
        # return HttpResponse(data, content_type="application/json")

    #/api/demo
    @csrf_exempt
    def demo(request, key):  #s3 key
        print("\n\n************************************* demo *************************************")
        print(key)

        data= {
            "e": "sonething wrong",
        }

        if request.method == 'POST':
            print("POST...")

        if request.method == 'GET':
            print("GET...")

        data= {
            "demo": "demo",
        }

        return JsonResponse(data)

        # data = json.loads(request.body)
        # print(data)

        # return JsonResponse(data)

        # df= pd.DataFrame(data, index=[0])
        # return HttpResponse( df.to_html() )