#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os, sys, argparse
import functools, time

import tensorflow
import tensorflow.compat.v1 as tf
import numpy as np

from models.SSD300 import SSD300
from models.YOLOv2 import YOLOv2
from models.YOLOv3 import YOLOv3
from models.RetinaNet import RetinaNet
from models.CenterNet import CenterNet
from models.FCOS import FCOS

from utils import voc_dataset

#np.random.seed(1337)
#tf.disable_eager_execution()
tf.disable_v2_behavior()

model_map = {
    'SSD300': SSD300,
    'YOLOv2': YOLOv2,
    'YOLOv3': YOLOv3,
    'RetinaNet': RetinaNet,
    'CenterNet': CenterNet,
    'FCOS': FCOS,
}

class Estimator(object):
    def __init__(self, model, dataset_config):
        self.model = model
        self.sess = self._sess_config()
        self.batch_size = self.model.batch_size
        self.num_train = dataset_config['num_train']
        self.num_val = dataset_config['num_val']
        self.saver = tf.train.Saver()
        self.global_step = tf.Variable(0, name="global_step", trainable=False)
        #global variables init
        self.sess.run(tf.global_variables_initializer())

    def compile(self, optimizer, metrics=None, logdir=None):
        with self.model.graph.as_default():

            #build loss & optimizer op
            #with tf.control_dependencies([self.model.loss]):
            update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS)
            self.optimize_op = optimizer.minimize(self.model.loss, global_step=self.global_step)
            self.train_op = tf.group([update_ops, self.optimize_op])

            #build metric op
            #correct_prediction = tf.equal(tf.argmax(self.model.output, 1), tf.argmax(self.labels, 1))
            #self.metrics = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))

            #global variables init
            self.sess.run(tf.global_variables_initializer())
            self.sess.run(self.model.train_initializer)

            #summary writer
            self.epoch_num = 0
            self.summary_writer = None
            if logdir:
                self.summary_writer = tf.summary.FileWriter(logdir, self.model.graph)

    def _sess_config(self):
        config = tf.ConfigProto()
        config.gpu_options.allow_growth = True   #dynamic alloc GPU resource
        config.gpu_options.per_process_gpu_memory_fraction = 0.9  #GPU memory threshold 0.9

        sess = tf.InteractiveSession(config=config, graph=self.model.graph)
        return sess

    def train_one_epoch(self):
        """
        train one epoch
        """
        self.model.is_training = True
        self.sess.run(self.model.train_initializer)
        loss_list = []
        metrics_list = []
        step_time_list = []
        mean_step_time = 0

        steps_per_epoch = self.num_train // self.batch_size
        for i in range(steps_per_epoch):
            start_time = time.process_time()
            loss_value, summary, _ = self.sess.run([self.model.loss, self.model.summary_op, self.train_op], feed_dict={})
            end_time = time.process_time()
            step_time_list.append(end_time-start_time)
            mean_step_time = sum(step_time_list)/len(step_time_list)
            time_log = 'ETA: %.2fs -' % (mean_step_time*(steps_per_epoch-i))

            # 记录loss均值
            loss_list.append(loss_value)
            # 记录准确率
            metrics_log = ''
            metrics_result = None

            #save summary
            if self.summary_writer:
                self.summary_writer.add_summary(summary, self.epoch_num*steps_per_epoch + i)

            print("[%s/%s]: %s loss: %06.4f %s" % (i, steps_per_epoch, time_log, np.mean(loss_list), metrics_log), end='\r')
            sys.stdout.flush()

        return np.mean(loss_list), np.mean(metrics_list) if len(metrics_list)>0 else 0., mean_step_time

    def train(self, epochs=10, validation_data=None, callbacks=None):

        for idx in range(1, epochs + 1):
            print("Epoch %s/%s" % (idx, epochs))
            start_time = time.process_time()
            loss, acc, step_time = self.train_one_epoch()
            end_time = time.process_time()
            self.epoch_num = idx
            time_log = '- %.2fs %.2fs/step' % (end_time-start_time, step_time)
            acc_log = '- acc: %06.4f' % acc if acc else ''
            val_log = ''
            if validation_data:
                val_loss, val_acc = self.evaluate(validation_data[0], validation_data[1], batch_size)
                val_acc_log = '- val_acc: %06.4f' % val_acc if val_acc else ''
                val_log = "- val_loss: %06.4f %s" % (val_loss, val_acc_log)
            print("[%s/%s] %s - loss: %06.4f %s %s" % (self.num_train // self.batch_size, self.num_train // self.batch_size, time_log, loss, acc_log, val_log))

    def test_one_image(self, images):
        self.model.is_training = False
        pred = self.sess.run(self.model.detection_pred, feed_dict={self.model.images: images})
        return pred

    def save(self, path):
        if not tf.gfile.Exists(os.path.dirname(path)):
            tf.gfile.MakeDirs(os.path.dirname(path))
            print(os.path.dirname(path), 'does not exist, create it done')
        self.saver.save(self.sess, path, global_step=self.global_step)
        print('save model in', path, 'successfully')

    def load_model(self, path):
        self.saver.restore(self.sess, path)
        print('load weight', path, 'successfully')

def model_test(clf, classes, image_file):
    import matplotlib.pyplot as plt
    import matplotlib.patches as patches
    from skimage import io, transform
    #from utils.voc_classname_encoder import classname_to_ids

    img = io.imread(image_file)
    img = transform.resize(img, [clf.model.input_size, clf.model.input_size])
    img = np.expand_dims(img, 0)
    result = clf.test_one_image(img)
    #id_to_classname = {k:v for (v,k) in classname_to_ids.items()}
    scores = result[0]
    bbox = result[1]
    class_id = result[2]
    #print(scores, bbox, class_id)
    plt.figure(1)
    plt.imshow(np.squeeze(img))
    axis = plt.gca()
    for i in range(len(scores)):
        rect = patches.Rectangle((bbox[i][1],bbox[i][0]), bbox[i][3]-bbox[i][1],bbox[i][2]-bbox[i][0],linewidth=2,edgecolor='b',facecolor='none')
        axis.add_patch(rect)
        plt.text(bbox[i][1],bbox[i][0], classes[class_id[i]]+str(' ')+str(scores[i]), color='red', fontsize=12)
    plt.show()

def load_config(config_file):
    import json
    f = open(config_file, 'r')
    config = json.load(f)

    return config

def get_optimizer(optimizer_config):
    if optimizer_config['type'] == 'momentum':
        optimizer = tf.train.MomentumOptimizer(learning_rate=optimizer_config['learning_rate'], momentum=optimizer_config['momentum'])
    elif optimizer_config['type'] == 'adam':
        optimizer = tf.train.AdamOptimizer(learning_rate=optimizer_config['learning_rate'])

    return optimizer

def main():
    # Training settings
    parser = argparse.ArgumentParser(description='TF Object Detection training')

    parser.add_argument('--mode', type=str, default='train',
                        help='train or test mode (default: train)')
    #parser.add_argument('--batch_size', type=int, default=8, metavar='N',
                        #help='input batch size for training (default: 8)')
    #parser.add_argument('--epochs', type=int, default=10, metavar='N',
                        #help='number of epochs to train (default: 10)')
    #parser.add_argument('--lr', type=float, default=0.001, metavar='LR',
                        #help='learning rate (default: 0.001)')
    parser.add_argument('--config_path', type=str, default='./configs/YOLOv3.json',
                        help='path to json format train config file (default: ./configs/YOLOv3.json)')
    #parser.add_argument('--data_path', type=str, default='./voc2007',
                        #help='path to directory holding tfrecord train data (default: ./voc2007)')
    parser.add_argument('--checkpoint_path', type=str, default=None,
                        help='path to directory holding a checkpoint for test (default: None)')
    #parser.add_argument('--logdir', type=str, default=None,
                        #help='logdir for tensorboard summary (default: None)')
    parser.add_argument('--test_image', type=str, default='./dog.jpg',
                        help='image file for model evaluation under test mode (default: ./dog.jpg)')

    args = parser.parse_args()

    config = load_config(args.config_path)

    model_type = config['model_type']
    model_config = config['model_config']
    image_augmentor_config = config['image_augmentor_config']
    dataset_config = config['dataset_config']
    train_config = config['train_config']

    model_config['batch_size'] = train_config['batch_size']

    # dataset settings
    data = os.listdir(dataset_config['data_path'])
    data = [os.path.join(dataset_config['data_path'], name) for name in data]

    train_gen = voc_dataset.get_generator(data,
                                        train_config['batch_size'], dataset_config['buffer_size'], image_augmentor_config)

    if args.mode == 'train':
        model = model_map[model_type](model_config, train_gen)
        optimizer = get_optimizer(train_config['optimizer'])

        clf = Estimator(model, dataset_config)
        clf.compile(optimizer=optimizer, logdir=train_config['logdir'])
        if args.checkpoint_path:
            clf.load_model(args.checkpoint_path)
        clf.train(epochs=train_config['epochs'])

        clf.save(os.path.join(train_config['checkpoint_path'], 'model.ckpt'))

    else:
        model_config['mode'] = 'test'
        classes = open(dataset_config['classes_path']).read().strip().split()
        model = model_map[model_type](model_config, train_gen)
        clf = Estimator(model, dataset_config)
        if args.checkpoint_path:
            clf.load_model(args.checkpoint_path)
        model_test(clf, classes, args.test_image)

if __name__ == '__main__':
    main()


from pystickynote.paths import NOTES_PATH
import PySimpleGUIQt as g
import sys
import json

if 'darwin' in sys.platform:
    NTB = False
else:
    NTB = True

def open_note(name, config):
    g.SetOptions(background_color=config.background_color, text_color=config.text_color,
                 input_elements_background_color=config.background_color, input_text_color=config.text_color,
                 button_color=(config.text_color, config.background_color), border_width=config.border_width, font=('Arial', int(config.font_size)))
    with open(NOTES_PATH, 'r+') as notes:
        note_obj = json.load(notes)
        match = False
        content = ''
    for k, v in note_obj.items():
        if name == k:
            match = True
            content = v
    if match == False:
        print('No Note Found With That Name')
        exit(1)
    layout = [
        [g.T(name, font=('Arial', int(config.title_size)), justification='center')],
        [g.Multiline(content, size=(50, 5), key='content')],
        [g.B('Close'), g.B('Delete'), g.B('Save')]
    ]

    window = g.Window('Create', no_titlebar=NTB, keep_on_top=True, grab_anywhere=True, layout=layout, alpha_channel=float(config.alpha))

    while True:
        event, value = window.Read()
        if event == 'Close':
            window.Close()
            break
        elif event == 'Save':
            note_obj[name] = value['content']
            with open(NOTES_PATH, 'r+') as notes:
                notes.seek(0)
                notes.truncate()
                json.dump(note_obj, notes, indent=4)
            window.Close()
            break
        elif event == 'Delete':
            new_layout = [
                [g.T('Are you sure you want to delete {}?'.format(name), justification='center')],
                [g.B('No'), g.B('Yes')]
            ]
            confirm_window = g.Window('', no_titlebar=NTB, keep_on_top=True, grab_anywhere=True, layout=new_layout)
            while True:
                event1, value1 = confirm_window.Read()
                if event1 == 'Yes':
                    note_obj.pop(name, [])
                    with open(NOTES_PATH, 'r+') as notes:
                        notes.seek(0)
                        notes.truncate()
                        json.dump(note_obj, notes, indent=4)
                    confirm_window.Close()
                    break
                else:
                    confirm_window.Close()
                    break
            window.Close()
            break


# import os
import pandas as pd
import cv2
import numpy as np
from pandas.core.tools.datetimes import DatetimeScalar
from tensorflow.keras.layers import Conv2D, SeparableConv2D, MaxPool2D, GlobalAveragePooling2D, Flatten, Dense, Input, BatchNormalization, GlobalMaxPool2D
from tensorflow.keras.models import Model, Sequential
# from tensorflow.keras.utils import to_categorical
from sklearn.preprocessing import OneHotEncoder
from tensorflow.python.keras.backend import conv2d
from sklearn.model_selection import KFold
from sklearn.utils import shuffle
path = "D:\python\pjt_odo\labels-map.csv"
load = pd.read_csv(path,encoding="utf-8")

def Recognition_model():
    input = Input(shape=(64,64,3))
    x = Conv2D(filters=(64), kernel_size=(64,21),strides=1)(input)
    x = BatchNormalization()(x)
    x1 = GlobalMaxPool2D()(x)

    x = Conv2D(filters=(64), kernel_size=(21,64),strides=1)(input)
    x = BatchNormalization()(x)
    x2 = GlobalMaxPool2D()(x)

    x = Conv2D(filters=(64), kernel_size=(21,21),strides=1)(input)
    x = BatchNormalization()(x)
    x3 = GlobalMaxPool2D()(x)

    x = Conv2D(filters=(64), kernel_size=(5,5),strides=1)(input)
    x = BatchNormalization()(x)
    x4 = GlobalMaxPool2D()(x)

    # x5 = Flatten()(x1+x2+x3+x4)

    x = Dense(1512)(x5)
    output = Dense(2350, activation="softmax")(x)

    model = Model(inputs=input, outputs= output)

    model.summary()
    model.compile(optimizer='adam', loss="categorical_crossentropy", metrics=['acc'])
    return model

model = Recognition_model()
load = shuffle(load)

for i in range(0,16):
    step = 42300

    lst_image_path = list(load.iloc[step*i:step*(i+1),0])
    lst_image_lable = list(load.iloc[step*i:step*(i+1),-1])

    x_images = []
    for i, image_path in enumerate(lst_image_path) :
        img = cv2.imread(image_path)
        x_images.append(img)
        print(i)
    x_images = np.array(x_images)
    y_label = np.array(lst_image_lable)

    print(y_label.shape)
    print(x_images.shape)
    print(np.unique(y_label))
    # (37599,)
    # (37599, 64, 64, 3)

    y_label = y_label.reshape(-1,1)
    onthot = OneHotEncoder()
    onthot.fit(y_label)
    y_label = onthot.transform(y_label).toarray()

    print(y_label.shape)

    x_images = x_images/255.
    print(x_images.shape)

    kfold = KFold(n_splits=5, shuffle=True)
    a = 1
    for train_index, test_index in kfold.split(x_images):
        print("TRAIN:", train_index.shape, "TEST:", test_index.shape)
        x_train, x_val = x_images[train_index], x_images[test_index]
        y_train, y_val = y_label[train_index], y_label[test_index]

        model.fit(x=x_train, y=y_train, batch_size=2350, epochs=100, validation_data=(x_val, y_val), shuffle=True)
        if a == 5:
            model.save("model1_{}.h5".format(i))
        a += 1


from Framework.Elements.CrossOver.CrossOverSelector import CrossOverSelector
import numpy as np

class RoulettewheelSelector(CrossOverSelector):

    def __init__(self, logger=None):
        CrossOverSelector.__init__(self, logger=logger)

    def selectPairs(self, population, amount):
        '''
        Expects a population already sorted by fitness.
        Randomly selects individuals from the population relative to their fitness (higher fitness = higher selection chance) for <amount> pairs.
        :return: <amount> pairs (p1, p2) for crossover
        '''
        self._logger.debug("Selecting " + str(amount) + " pairs (roulette wheel)")
        pairs = []
        totalFitness = sum([ind.getUsedFitness() for ind in population])
        for i in range(0, amount):
            r1, r2 = np.random.uniform(0, totalFitness), np.random.uniform(0, totalFitness)
            pairs.append((self._fitnessToIndivdual(population, r1), self._fitnessToIndivdual(population, r2)))
        return pairs


import pandas as pd
import matplotlib.pyplot as plt

MY_FILE = "../../data/globalterrorismdb_0616dist.csv"

def build_df():
    """ Builds the specific DataFrame needed for this project from a csv file"""
    # read the .csv file and save to Pandas DataFrame, isolating only the Country Names & Target Types
    pandas_df = pd.read_csv(MY_FILE, usecols=['country_txt', 'targtype1_txt'])

    # find the data for just the US and Italy
    # (new variables are Pandas Series)
    us_data = pandas_df.query('country_txt == ["United States"]')
    italy_data = pandas_df.query('country_txt == ["Italy"]')

    # count the number of each target type for both countries
    # (new variables are Pandas Series)
    us_counter = us_data.targtype1_txt.value_counts()
    italy_counter = italy_data.targtype1_txt.value_counts()

    # add 'missing' targets in Italy and assign value of 0
    add_dict = {}
    it_ind = italy_counter.index
    for x in us_counter.iteritems():
        ind, count = x
        if ind not in it_ind:
            add_dict[ind] = 0
    italy_counter = italy_counter.append(pd.Series(add_dict))

    # combine Series to new DataFrame
    df = pd.concat([us_counter, italy_counter], axis=1)
    df.columns = ["United States", "Italy"]

    return df

def visualize(df):
    """builds & saves a bar graph"""
    i_u_plot = df.plot(kind="barh", title="Terrorist Attacks by Target Type, US & Italy")
    plt.tight_layout()
    fig = i_u_plot.get_figure()
    fig.savefig("../output/US_Italy_Type_Compare.PNG")
    fig.clf()

def main():
    df = build_df()
    visualize(df)

if __name__ == "__main__":
    main()


# Copyright (c) 2020 Manuel Burki
#
# 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.

import os
import boto3
from botocore.exceptions import ClientError
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from urllib.parse import  parse_qs

def lambda_handler(event, context):

    elements = parse_qs(event['body'])

    # Technical variables for SES email
    SENDER_EMAIL    = os.environ['SENDER_EMAIL']
    RECIPIENT       = os.environ['RECIPIENT']
    EMAIL_SUBJECT   = os.environ['EMAIL_SUBJECT']
    SITE_URL        = os.environ['SITE_URL']
    CHARSET         = "utf-8"
    AWS_REGION      = os.environ['AWS_REGION']

    # Form data / use POST method and Lambda proxy integration
    FORM_NAME       = elements['cf-name'][0]
    FORM_EMAIL      = elements['cf-email'][0]
    FORM_SUBJECT    = elements['cf-subject'][0]
    FORM_MESSAGE    = 'Name: ' + FORM_NAME + '\r\n' + 'Email: ' + FORM_EMAIL + '\r\n' + \
                      'Subject: ' + FORM_SUBJECT + '\r\n' + \
                      'Message: ' + '\n\n' + elements['cf-message'][0]

    client = boto3.client('ses',region_name=AWS_REGION)

    msg = MIMEMultipart('mixed')
    msg['Subject'] = EMAIL_SUBJECT
    msg['From'] = SENDER_EMAIL
    msg['To'] = RECIPIENT

    msg_body = MIMEMultipart('alternative')
    textpart = MIMEText(FORM_MESSAGE.encode(CHARSET), 'plain', CHARSET)
    msg_body.attach(textpart)
    msg.attach(msg_body)

    try:
        response = client.send_raw_email(
            Source=SENDER_EMAIL,
            Destinations=[ RECIPIENT ],
            RawMessage={ 'Data':msg.as_string(), }
        )

    except ClientError as e:
        resp_msg = '{ "alert": "error", "message": "An error has occured." }'
        status_code = 500
    else:
        resp_msg = '{ "alert": "success", "message": "Your message has been sent successfully." }'
        status_code = 200

    return {
        'statusCode': status_code,
        'headers': { 'Access-Control-Allow-Origin': SITE_URL, },
        'body': resp_msg
    }


import discord
import feedparser
from discord.ext import commands

class News(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.command(name='news', help='This command returns the amount  of pc game news user want')
    async def news(self, ctx, *args):
        #the feed is an list file
        feed = feedparser.parse("https://www.gameinformer.com/news.xml")

        # if no user didn't input how many news they want
        # the chicken will print all the pc game news from
        # today
        if not args:
          for entry in feed.entries:
            # We only print the link since discord will automatically
            # display the pic and some content
            article_link = entry.link
            await ctx.send(article_link)

        # if there is an input number
        # print only the amount  user want
        else:
           x = int(args[0])

           for i in range(x):
             await ctx.send(feed.entries[i].link)

def setup(client):
    client.add_cog(News(client))


from pyrpde import rpde
# pip install pyrpde
from scipy.io import wavfile
import sys
sys.path.append('NeuroSpeech-master/src/prosody/')
import prosody
sys.path.append('NeuroSpeech-master/src/phonVowels/')
import phonVowels
sys.path.append('NeuroSpeech-master/src/DDK/')
import DDK

import numpy as np

def getfeature(audio_path):

    # RPDE方法必须输入float32格式
    fs, data_audio = wavfile.read(audio_path)

    # PRDE = rpde(data_audio, tau=30, dim=4, epsilon=0.01, tmax=1500)
    #RPDE = rpde(data_audio, tau=30, dim=4, epsilon=0.01, tmax=1500)
    # try:
    #     RPDE = rpde(audio_path, tau=30, dim=4, epsilon=0.01, tmax=1500)
    # except    Exception:
    #     pass

    path_base = 'NeuroSpeech-master/src/prosody/'
    F0, logE, mF0, sF0, mmF0, mlogE, slogE, mmlogE, Vrate, avgdurv, stddurv, Silrate, avgdurs, stddurs, F0varsemi = prosody.prosody(audio_path, path_base)

    path_base = 'NeuroSpeech-master/src/phonVowels/'
    F0, F0semi, mjitter, mshimmer, apq, ppq, mlogE, mcd, degreeU, varF0  = phonVowels.phonationVowels( audio_path, path_base )

    path_base = 'NeuroSpeech-master/src/DDK/'
    F0, logE, mF0, sF0, mmF0, mlogE, slogE, mmlogE, DDKrate, avgdurddk, stddurddk, Silrate, avgdurs, stddurs, F0varsemi=DDK.DDK(audio_path, path_base)

    if np.isnan(avgdurs):
        avgdurs=0
    if np.isnan(stddurs):
        stddurs=0

    f_prosofy = [F0, logE, mF0, sF0, mmF0, mlogE, slogE, mmlogE, Vrate, avgdurv, stddurv, Silrate, avgdurs, stddurs, F0varsemi]
    f_phon = [F0, F0semi, mjitter, mshimmer, apq, ppq, mlogE, mcd, degreeU, varF0]
    f_ddk = [F0, logE, mF0, sF0, mmF0, mlogE, slogE, mmlogE, DDKrate, avgdurddk, stddurddk, Silrate, avgdurs, stddurs,
             F0varsemi]
    f = []
    # if 'RPDE' in globals():
    #     f.extend(RPDE)
    # f.append(RPDE)
    f.extend(f_prosofy[2:])
    f.extend(f_phon[2:-3])
    f.extend(f_phon[-2:])
    f.extend(f_ddk[-3:-1])

    return f#我不知道罗正潮用了哪些量，python的都在上面


'''
方法二：继承Process类 ，需实现 run 方法

'''

from multiprocessing import Process
import time

class MyProcess(Process):
    def __init__(self,name2):
        super() .__init__() # 需加上父类的 init方法，以免覆盖，造成某些功能无法使用
        self.name2=name2

    def run(self):
        print("<%s> is running" % self.name2)
        time.sleep(2)
        print("<%s> is done" % self.name2)

if __name__ == '__main__':
    p1=MyProcess('AIF333')
    p2=MyProcess('Iverson')
    p1.start()
    p2.start()
    print("===主进程is running ！===")


# -*- coding: utf-8 -*-
"""
Created on Mon Jun 22 14:18:30 2020

@author: marco
"""
cities = ["New York City", "Los Angeles", "Chicago", "Mountain View", "Denver", "Boston"]

is_short = lambda x : len(x) < 10
#def is_short(name):
#    return len(name) < 10

short_cities = list(filter(is_short, cities))
print(short_cities)


import unittest
import os

class MyTestCase(unittest.TestCase):

  def test_equal_output(self):
    expected = open("example.tab.reference.txt" , "rw+")
    output = open("example.tab.txt" , "rw+")

    self.assertEquals(len(expected.readlines()), len(output.readlines()))

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


from __future__ import absolute_import, division, print_function

import tempfile
import os

try:
    from urllib.request import urlopen
except ImportError:
    from urllib2 import urlopen

from .. import data
from .. import get_hashes

def test_check_hashes():
    with tempfile.NamedTemporaryFile() as temp:
        temp.write(b'Some data')
        temp.flush()
        fname = temp.name
        d = {fname: "5b82f8bf4df2bfb0e66ccaa7306fd024"}
        assert data.check_hashes(d)
        d = {fname: "4b82f8bf4df2bfb0e66ccaa7306fd024"}
        assert not data.check_hashes(d)

def test_get_hashes():
    # Download class data to current directory.
    url = 'http://www.jarrodmillman.com/rcsds/_downloads/ds107_sub001_highres.nii'
    file_name = 'ds107_sub001_highres.nii'
    ds107 = urlopen(url)
    output = open(file_name,'wb')
    output.write(ds107.read())
    output.close()
    # Now get all hashes of all files in current directory.
    file_hashes = get_hashes.get_all_hashes('.')
    # The class data should be in the dictionary of hashes, with the
    # correct hash.
    assert(file_hashes['./ds107_sub001_highres.nii'] == 'fd733636ae8abe8f0ffbfadedd23896c')
    # Delete the file.
    os.remove('ds107_sub001_highres.nii')


numRows = 5

if numRows == 0:
    return

pascal = [[1]]
for i in range(numRows - 1):
    prevrow = pascal[-1]
    newrow = [1]

    for h in range(len(prevrow) - 1):
        newrow.append(prevrow[h + 1] + prevrow[h])
    newrow.append(1)
    pascal.append(newrow)

return pascal


class CategoryAnalysis:
    def __init__(self):
        self.firstPartyCollection = set()
        self.thirdPartySharing = set()
        self.userChoice = set()
        self.accessEditDelete = set()
        self.policyChange = set()

    def insert(self, category, index):
        if category == "Edit and Deletion":
            self.accessEditDelete.add(index)
        elif category == "First Party Collection/Use":
            self.firstPartyCollection.add(index)
        elif category == "Policy Change":
            self.policyChange.add(index)
        elif category == "Third Party Sharing/Collection":
            self.thirdPartySharing.add(index)
        elif category == "User Access":
            self.accessEditDelete.add(index)

    def count(self):
        return len(self.firstPartyCollection) + len(self.thirdPartySharing) + len(self.userChoice) \
               + len(self.policyChange)


# 모든 도로의 거리가 1이므로 BFS 접근
from collections import deque
N, M, K, X= map(int, input().split())
graph=[[0]*(N+1) for _ in range(N+1)]
for i in range(M):
    A, B = map(int, input().split())
    graph[A][B]=graph[B][A]=1

def bfs(start, min, count):
    visited=[start]
    queue=deque([start])

    while queue:
        n=queue.popleft()
        count+=1
        for c in range(len(graph[start])):
            if graph[n][c]==1 and (c not in visited):
                visited.append(c)
                queue.append(c)
                if min[c]<count:
                    min[c]=count
    return min
result=bfs(X, [0]*(N+1), 0)
for i in range(1, N+1):
    if result[i]==K:
        print(i)
if K not in result:
    print("-1")
# print(result)

특정거리의도시찾기.py


number = input("How many students do you have: ")
i=1
my_dict = dict()
while i<=number:
    student = raw_input('Enter than Student name: ')
    result = input("Enter the result: ")
    my_dict[result] = student
    i+=1  #to count and continue for number of students
studentresult=[]

for i in my_dict:      #change dictionary results to list for sorting
    studentresult.append(i)
studentresult.sort()

print(("Here is the highest result: "),my_dict.get(studentresult[-1]))   #using results to extract names
print(("Here is the 2nd highest result: "),my_dict.get(studentresult[-2]))


#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright @ 2015 OPS.
#
# Author: tingfang.bao <tingfang.bao@acadine.com>
# DateTime: 16/4/21 09:19
import logging
from aws_egg.api.session import elb_client
from aws_egg.api.vpc_resource import get_sec_group, get_subnet_by_name
from aws_egg.api.ec2_resources import get_instance
from botocore.exceptions import ClientError

LOG = logging.getLogger(__name__)

def get_elb(name):
    try:
        resp = elb_client.describe_load_balancers(LoadBalancerNames=[name])
    except ClientError:
        return None

    elbs = resp["LoadBalancerDescriptions"]

    if len(elbs) > 0:
        return elbs[0]
    else:
        return None

def create_elb(name, instance_port, subnet_names_list, sec_group_name="default", elb_protocol="HTTP", instance_protocol="HTTP", schema="internet-facing"):
    """

    :param instance_protocol:
    :param elb_protocol: TCP|HTTP|HTTPS
    :param name: ELB名称
    :param instance_port:
    :param subnet_names_list: 子网组名称列表
    :param sec_group_name: 安全组名称
    :param schema: internet-facing|internal
    """
    elb = get_elb(name)

    if elb:
        return

    sec_group = get_sec_group(sec_group_name)

    subnet_ids = []
    for subnet_name in subnet_names_list:
        subnet = get_subnet_by_name(subnet_name)
        subnet_ids.append(subnet.id)

    server_cer_arn = ""
    elb_port = 80

    if elb_protocol == "HTTPS":
        from aws_egg.api.session import iam

        cert = iam.ServerCertificate("acadinecrt")
        server_cer_arn = cert.server_certificate_metadata["Arn"]
        elb_port = 443

    elb_client.create_load_balancer(
        LoadBalancerName=name,
        Scheme=schema,
        Listeners=[
            {
                'Protocol': elb_protocol,
                'LoadBalancerPort': elb_port,
                'InstanceProtocol': instance_protocol,
                'InstancePort': instance_port,
                'SSLCertificateId': server_cer_arn
            },
        ],
        Subnets=subnet_ids,
        SecurityGroups=[sec_group.id],

        Tags=[
            {
                'Key': 'Name',
                'Value': name
            },
        ]
    )

"""
1. 上线前要先摘掉机器
2. 发布完成后
3. 上线机器
4. 检查健康状态
"""

def add_instances(elb_name, instance_name_list):
    instance_ids = []
    for instance_name in instance_name_list:
        instance_id = get_instance(instance_name).id

        instance_ids.append({
            "InstanceId": instance_id
        })

    elb_client.register_instances_with_load_balancer(
        LoadBalancerName=elb_name,
        Instances=instance_ids
    )

def remove_instances(elb_name, instance_name_list):
    instance_ids = []
    for instance_name in instance_name_list:
        instance_id = get_instance(instance_name).id
        instance_ids.append({
            "InstanceId": instance_id
        })

    elb_client.deregister_instances_from_load_balancer(
        LoadBalancerName=elb_name,
        Instances=instance_ids
    )

# noinspection PyBroadException
def get_health_state(elb_name, instance_name):
    try:
        instance_id = get_instance(instance_name).id
    except:
        LOG.error("Can not find instance: %s" % instance_name)
        return

    resp = elb_client.describe_instance_health(
        LoadBalancerName=elb_name,
        Instances=[
            {
                'InstanceId': instance_id
            },
        ]
    )

    # InService|OutOfService|Unknown
    return resp["InstanceStates"][0]["State"]

# 重新定义健康检查配置
def config_health_check(elb_name, target):
    """
    target的写法:
        TCP方式: TCP:5000
        HTTP方式: HTTP:80/healthcheck.html
        HTTPS方式: HTTPS:443/healthcheck.html
        SSL方式: SSL:443

    :param elb_name:
    :param target:
    """
    elb_client.configure_health_check(
        LoadBalancerName=elb_name,
        HealthCheck={
            'Target': target,
            'Interval': 6,
            'Timeout': 5,
            'UnhealthyThreshold': 2,
            'HealthyThreshold': 3
        }
    )

if __name__ == '__main__':
    logging.basicConfig()
    # create_elb("test-elb", 8080, ["dev-web-a", "dev-web-b"])
    # create_elb("test-tcp-elb", 8080, ["dev-web-a", "dev-web-b"], elb_protocol="TCP", instance_protocol="TCP")
    # create_elb("test-https-elb", 8080, ["dev-web-a", "dev-web-b"], elb_protocol="HTTPS", instance_protocol="HTTP")

    # print get_health_state("test-elb", "l-web1.dev")
    # config_health_check("test-elb", "HTTP:80/healthcheck.html")
    # elb = get_elb("public-account-service")
    # print elb["DNSName"]


#!/usr/bin/env python3.6
# -*- coding: utf-8 -*-
#
import logging

from telegram.ext import (
    Updater, CommandHandler, InlineQueryHandler, MessageHandler, Filters,
    ConversationHandler, RegexHandler
)

from botcommands import *

if __name__ == '__main__':
    # Enable logging
    logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
                        level=logging.INFO)

    logger = logging.getLogger(__name__)

    with open('bot.token', encoding='utf-8') as f:
        token = f.read().strip()
    updater = Updater(token)

    dp = updater.dispatcher
    dp.add_handler(CommandHandler(
        'start', start
    ))
    dp.add_handler(InlineQueryHandler(
        formatinline
    ))
    dp.add_handler(MessageHandler(
        Filters.text, formatall
    ))

    updater.start_polling()
    updater.idle()


#!/usr/bin/env python3

from flask import Flask, jsonify
from flask_restful import Api, Resource
from datetime import datetime
import json

app = Flask(__name__)
api = Api(app)

class Time(Resource):
    def get( self):
        result = {'version': 'v1'}
        result['time'] = datetime.now().time().__str__()
        return jsonify(result)

api.add_resource(Time, "/time", "/time/")

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0')


'''
numpy libary test
'''
import numpy as np

def redraw(board):
    '''
    redraw game board
    '''
    for row in board:
        print(row)

def main():
    '''
    main()
    '''
    current_board = np.zeros((3, 3))    # Create an 3 x 3 array of all zeros

    # fill some data
    current_board[0][0] = 1
    current_board[1][0] = 1
    current_board[2][0] = 1

    # get first column of data
    col = current_board[:, 0]
    print('col %s' % col)
    # check all numbers are equal
    print('Are all numbers in col set to 1? % r' % np.all(col == 1))

    # get first row of data
    row = current_board[0, :]
    print('row %s' % row)
    print('Are all numbers in row set to 1? % r' % np.all(row == 1))

    redraw(current_board)

    b = np.array([[100, 23, 10, 10], [102, 26, 20, 10]])
    print(b.shape)

    print('avg = %s' % np.average(b, 0))
    print('max = %s' % np.max(b, 0))
    print('min = %s' % np.min(b, 0))

if __name__ == "__main__":
    main()


from __future__ import print_function

import click
from timeit import default_timer as timer

from dwave.cloud.qpu import Client
from dwave.cloud.utils import readline_input
from dwave.cloud.exceptions import (
    SolverAuthenticationError, InvalidAPIResponseError, UnsupportedSolverError)
from dwave.cloud.config import (
    load_config_from_file, get_default_config,
    detect_configfile_path, get_default_configfile_path)

@click.group()
def cli():
    """D-Wave cloud tool."""

@cli.command()
@click.option('--config-file', default=None, help='Config file path',
              type=click.Path(exists=True, dir_okay=False))
@click.option('--profile', default=None,
              help='Connection profile name (config section name)')
def configure(config_file, profile):
    """Create and/or update cloud client configuration file."""

    # determine the config file path
    if config_file:
        print("Using config file:", config_file)
    else:
        # path not given, try to detect; or use default, but allow user to override
        config_file = detect_configfile_path()
        if config_file:
            print("Found existing config file:", config_file)
        else:
            config_file = get_default_configfile_path()
            print("Config file not found, the default location is:", config_file)
        config_file = readline_input("Confirm config file path (editable): ", config_file)

    # try loading existing config, or use defaults
    try:
        config = load_config_from_file(config_file)
    except ValueError:
        config = get_default_config()

    # determine profile
    if profile:
        print("Using profile:", profile)
    else:
        existing = config.sections()
        if existing:
            profiles = 'create new or choose from: {}'.format(', '.join(existing))
            default_profile = ''
        else:
            profiles = 'create new'
            default_profile = 'prod'
        while not profile:
            profile = readline_input("Profile (%s): " % profiles, default_profile)
            if not profile:
                print("Profile name can't be empty.")

    if not config.has_section(profile):
        config.add_section(profile)

    # fill out the profile variables
    variables = 'endpoint token client solver proxy'.split()
    prompts = ['API endpoint URL (editable): ', 'Auth token (editable): ',
               'Client class (qpu or sw): ', 'Solver (can be left blank): ',
               'Proxy URL (can be left blank): ']
    for var, prompt in zip(variables, prompts):
        default_val = config.get(profile, var, fallback=None)
        val = readline_input(prompt, default_val)
        if val != default_val:
            config.set(profile, var, val)

    with open(config_file, 'w') as fp:
        config.write(fp)

    print("Config saved.")
    return 0

@cli.command()
@click.option('--config-file', default=None, help='Config file path',
              type=click.Path(exists=True, dir_okay=False))
@click.option('--profile', default=None, help='Connection profile name')
def ping(config_file, profile):
    """Ping the QPU by submitting a single-qubit problem."""

    try:
        client = Client.from_config(config_file=config_file, profile=profile)
    except Exception as e:
        print("Invalid config: {}".format(e))
        return 1
    if config_file:
        print("Using config file:", config_file)
    if profile:
        print("Using profile:", profile)
    print("Using endpoint:", client.endpoint)

    t0 = timer()
    try:
        solvers = client.get_solvers()
    except SolverAuthenticationError:
        print("Authentication error. Check credentials in your config file.")
        return 1
    except (InvalidAPIResponseError, UnsupportedSolverError):
        print("Invalid or unexpected API response.")
        return 2

    try:
        solver = client.get_solver()
    except (ValueError, KeyError):
        # if not otherwise defined (ValueError), or unavailable (KeyError),
        # just use the first solver
        if solvers:
            _, solver = next(iter(solvers.items()))
        else:
            print("No solvers available.")
            return 1

    t1 = timer()
    print("Using solver: {}".format(solver.id))

    timing = solver.sample_ising({0: 1}, {}).timing
    t2 = timer()

    print("\nWall clock time:")
    print(" * Solver definition fetch web request: {:.3f} ms".format((t1-t0)*1000.0))
    print(" * Problem submit and results fetch: {:.3f} ms".format((t2-t1)*1000.0))
    print(" * Total: {:.3f} ms".format((t2-t0)*1000.0))
    print("\nQPU timing:")
    for component, duration in timing.items():
        print(" * {} = {} us".format(component, duration))
    return 0


from django.shortcuts import render
from django.views import generic
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse

from .models import Book, Author, BookRating, Genre
from .forms import RateBookForm

# Create your views here.

@login_required
def index(request):

   my_reviews = BookRating.objects.filter(user__pk=request.user.pk)
   book_list = Book.objects.all()
   review_ids = [r.book.pk for r in my_reviews]
   id_list = [book.pk for book in book_list]
   book_feed =[book for book in book_list if book.pk not in review_ids]
   book_feed = book_feed[:10]

   return render(
      request,
      'index.html',
      context={'book_list': book_feed},
   )

class BookListView(LoginRequiredMixin, generic.ListView):
   model = Book
   context_object_name = 'book_list'
   template_name='catalog/book_list.html'
   paginate_by = 10

class BookDetailView(LoginRequiredMixin, generic.DetailView):
   model = Book
   context_object_name = 'book'
   template_name='catalog/book_detail.html'

class AuthorListView(LoginRequiredMixin, generic.ListView):
   model = Author
   context_object_name = 'author_list'
   template_name='catalog/author_list.html'
   paginate_by = 10

class AuthorDetailView(LoginRequiredMixin, generic.DetailView):
   model = Author
   context_object_name = 'author'
   template_name='catalog/author_detail.html'

   def get_context_data(self, **kwargs):
       context = super(AuthorDetailView, self).get_context_data(**kwargs)
       context['books'] = Book.objects.filter(author__pk=context['author'].pk)
       return context

class BookRatingsByUserListView(LoginRequiredMixin, generic.ListView):
    """
    Generic class-based view listing books on loan to current user.
    """
    model = BookRating
    context_object_name = 'ratings'
    template_name ='catalog/bookrating_list_user.html'
    paginate_by = 10

    def get_queryset(self):
        return BookRating.objects.filter(user=self.request.user)

@login_required
def rate_book(request, pk):

    book = get_object_or_404(Book, pk = pk)

    rating = None

    try:
        rating = BookRating.objects.get(user=request.user, book=book)
    except BookRating.DoesNotExist:
        pass

    if request.method == 'POST':
        form = RateBookForm(request.POST)

        if form.is_valid():

            book_rating = BookRating()

            if rating:
                book_rating = rating
                book.accumulated_rate -= book_rating.rate
                book.number_of_reviews -= 1

            book_rating.book = book
            book_rating.user = request.user
            book_rating.rate = form.cleaned_data['rate']
            book_rating.comment = form.cleaned_data['comment']
            book_rating.status = form.cleaned_data['status']
            book_rating.save()

            book.accumulated_rate += form.cleaned_data['rate']
            book.number_of_reviews += 1
            book.save()

            return HttpResponseRedirect(reverse('my-readings'))

    else:
        init_data = {'rate': 0, 'comment': '', 'status': 'i'}
        if rating:
            init_data = {'rate': rating.rate, 'comment': rating.comment, 'status': rating.status}

        form = RateBookForm(initial=init_data)

    return render(request, 'catalog/book_rating.html', {'form': form, 'book': book})


# THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY O
# ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
# THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
# PARTICULAR PURPOSE.
#
# Copyright 2020-2029 Zach (Yuzhe) Ni All rights reserved

#
# The purpose of this python program is to automatically create web pages (i.e. index.html, <posts>.html, <archivedate>.html).

import zipfile
import os, time, datetime

#
# Initialize all the variable
#

zipfilelist = {}
blog_description = open("blog.txt", "r")
blog = blog_description.read().split('\n')
allfile = []
bucket = { }
archive_content = ""
thumbnail = "title

"
strblogpost = "

  as2TITLEs2a

as2DATEs2a by Zach Ni
 as2Content2sa
"

#
# filtering metadata
#
for i in range(0,len(blog)-1,2):
    modified = os.path.getmtime(blog[i])
    Timestamped = time.ctime(modified).split(' ')[1]+' '+time.ctime(modified).split(' ')[2]+' '+time.ctime(modified).split(' ')[-1]
    Monthyearstamped = time.ctime(modified).split(' ')[1]+' '+time.ctime(modified).split(' ')[-1]
    a = {
        "filename" : blog[i],
        "title" : blog[i+1],
        "time" : os.stat(blog[i]).st_mtime,
        "Timestamped" : Timestamped,
        "Monthyearstamped" : Monthyearstamped
    }
    allfile.append(a)

#
# Sorting posts based on time in ascending order, allfile[-1] represents the metadata for the latest modified file
#
def sortcomp(e):
    return e["time"]
allfile.sort(key=sortcomp)

#
# Initialize buckets which contain specific month/year and their respective posts
#

for x in allfile:
    bucket[x['Monthyearstamped']] = []

for x in allfile:
    bucket[x['Monthyearstamped']].append(x)

#
# Create Archive Content for different year/month
#
for x in bucket:
    filename = ""
    for i in x.split(' '):
        filename += i
    filename += ".html"
    archive_content += thumbnail.replace("page",filename).replace("title",x)

#
# Read template for blog posts
#

template_file = open("template.html", 'r')
template = template_file.read()

#
# write to specific blog html file
#

for x in allfile:
    title = x['title']
    file = x['filename']
    Timestamped = x['Timestamped']
    Monthyearstamped = x['Monthyearstamped']
    content_file = open(file, 'r')
    content = content_file.read()
    result = template.replace("", content).replace("", title).replace("", Timestamped).replace("", archive_content)
    html_file = open(file.replace(".txt", ".html"), "w")
    zipfilelist[file.replace(".txt", ".html")] = 1
    html_file.write(result)
    html_file.close()

#
# Read Archives html file for creating specific datetime.html files and create them
#

content_file = open("Archives.html", 'r')
content = content_file.read()

for x in bucket:
    date = x
    filename = ""
    for i in date.split(' '):
        filename += i
    filename += ".html"
    post = ""
    for y in bucket[x]:
        title = y['title']
        file = y['filename']
        post += thumbnail.replace("page",file.replace(".txt", ".html")).replace("title",title)
    result = content.replace("",date).replace("",post).replace("",archive_content)
    html_file = open(filename, "w")
    zipfilelist[filename] = 1
    html_file.write(result)
    html_file.close()

#
# Write to index file
#

bp = ""
count = 0
for y in range(len(allfile)-1,-1,-1):
    count = count + 1
    x = allfile[y]
    if count > 3:
        break
    content_file = open(x['filename'], 'r')
    content = content_file.read()
    htmltext = x['filename'].replace(".txt",".html")
    bp += strblogpost.replace("as2TITLEs2a",x['title']).replace("as2DATEs2a",x['Timestamped']).replace('as2Content2sa',content).replace("as2LINK2sa",htmltext )

content_file = open("index32.html", 'r')
content = content_file.read()
result = content.replace("",bp).replace("", archive_content)
html_file = open("index.html", "w")
zipfilelist["index.html"] = 1
html_file.write(result)
html_file.close()

from zipfile import ZipFile

# zip related html pages

with ZipFile('pages.zip', 'w') as myzip:
    for file in zipfilelist:
        myzip.write(file)


import numpy as np
import matplotlib.pyplot as plt
import cmath as cm
j=cm.sqrt(-1)
w=np.linspace(0,2*np.pi,1000)
x=[1.0/3.0,1.0/3.0,1.0/3.0,0.0]
y=[]
y=np.zeros(1000)
l=len(x)
for i in range(0,1000):
	sum=0
	for n in range(0,l-1):
		sum=sum+(x[n]*(np.exp(-j*w[i]*n)))
		y[i]=sum
	y=np.append(y,sum)
print(y)
p=np.abs(y)
plt.subplot(2,1,1)
plt.plot(p)
q=np.angle(y)
plt.subplot(2,1,2)
plt.plot(q)
plt.show()


from numpy import inf

def findMaxCrossingSubList(v,low, high, middle):
    '''
    findMaxCrossingSubList takes a list and 3 integers
    It returns a continuus sublist,whose elements have the biggest sum, but has the v[middle] element in it
    '''
    leftSum=-inf
    totSum=0
    for i in range(middle,low-1,-1):
        totSum=totSum+v[i]
        if totSum>leftSum:
            leftSum=totSum
            leftMax=i
    rightSum=-inf
    totSum=0
    for i in range(middle,high):
        totSum=totSum+v[i]
        if totSum>rightSum:
            rightSum=totSum
            rightMax=i
    return leftMax,rightMax,leftSum+rightSum-v[middle]

def findMaxSubList(v,low=0,high=-1):
    '''
    findMaxCrossingSubList takes a list and 2 integers
    It returns the indices of a continuus sublist,whose elements have the biggest sum and return its sum
    '''
    if high==-1:
        high=len(v)
    if high==low+1:
        return low,high,v[low]
    else:
        middle=(low+high)/2
        lowLeft,highLeft, sumLeft = findMaxSubList(v,low,middle)
        lowRight, highRight, sumRight = findMaxSubList(v,middle,high)
        lowMid, highMid, sumMid = findMaxCrossingSubList(v,low,high,middle)
        if sumLeft>=sumRight and sumLeft>=sumMid:
            return lowLeft,highLeft, sumLeft
        if sumRight>=sumLeft and sumRight>=sumMid:
            return lowRight, highRight, sumRight
        else:
            return lowMid, highMid, sumMid


from django.views.generic import TemplateView
from django.views.generic.base import RedirectView
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.utils.decorators import method_decorator
from django.utils.translation import ugettext_lazy as _
from .forms import AddNetworkForm, RenameSubnetForm, AddHostForm, SplitSubnetForm
from .models import Subnet, Host
import ipaddress

class RootView(TemplateView):
    def get(self, request, *args, **kwargs):
        return redirect('ip_list')

@method_decorator(login_required, name='dispatch')
class IPListView(TemplateView):
    template_name = "subnetbase/iplist.html"

    @staticmethod
    def get_subnet(pk):
        return Subnet.objects.get(pk=pk)

    @staticmethod
    def format_form_errors(errors):
        result = []
        for value in errors.itervalues():
            result.append(value)
        return result

    def get(self, request, *args, **kwargs):
        tree = Subnet.objects.all()
        return render(request, self.template_name, {'subnets_tree': tree, 'form': AddNetworkForm(),
                                                    'rename_form': RenameSubnetForm(), 'add_host_form': AddHostForm(),
                                                    'split_subnet_form': SplitSubnetForm()})

    def post(self, request, *args, **kwargs):
        form = AddNetworkForm(request.POST)
        tree = Subnet.objects.all()
        if form.is_valid():
            subnet = Subnet()
            subnet.subnet = form.cleaned_data['network']
            subnet.prefix = form.cleaned_data['prefix']
            subnet.title = form.cleaned_data['title']
            subnet.calculate()
            subnet.save()
            return redirect('ip_list')
        else:
            for msg in self.format_form_errors(form.errors):
                messages.error(request, msg)
            return render(request, self.template_name, {'subnets_tree': tree, 'form': form})

@method_decorator(login_required, name='dispatch')
class SplitSubnetView(TemplateView):

    def get(self, request, *args, **kwargs):
        messages.error(request, _('Method GET not supported for this URL'))
        return redirect('ip_list')

    def post(self, request, *args, **kwargs):
        form = SplitSubnetForm(request.POST)
        if form.is_valid():
            to_split = IPListView.get_subnet(form.cleaned_data['subnet'])
            if to_split.get_children is not None:
                messages.error(request, _('Subnet %(net)s/%(prefix)s already splited.') %
                               {'net': to_split.net, 'prefix': to_split.prefix})
                return redirect('ip_list')
            subnet = ipaddress.IPv4Network('%s/%s' % (to_split.net, to_split.prefix))
            new_prefix = form.cleaned_data['new_prefix']
            if new_prefix <= to_split.prefix or new_prefix > 32:
                messages.error(request, _('%(new_prefix)s is incorrect prefix for subnet %(subnet)s/%s(old_prefix)s') %
                               {'new_prefix': new_prefix, 'subnet': to_split.net, 'old_prefix': to_split.prefix})
                return redirect('ip_list')
            for splited in list(subnet.subnets(prefixlen_diff=new_prefix-to_split.prefix)):
                new_subnet = Subnet()
                new_subnet.subnet = str(splited.network_address)
                new_subnet.prefix = new_prefix
                new_subnet.calculate()
                new_subnet.parent = to_split
                new_subnet.title = form.cleaned_data['title']
                new_subnet.save()
            return redirect('ip_list')
        else:
            for msg in IPListView.format_form_errors(form.errors):
                messages.error(request, msg)
            return redirect('ip_list')

@method_decorator(login_required, name='dispatch')
class RenameSubnetView(RedirectView):

    def get(self, request, *args, **kwargs):
        messages.error(request, _('Method GET not supported for this URL'))
        return redirect('ip_list')

    def post(self, request, *args, **kwargs):
        form = RenameSubnetForm(request.POST)
        if form.is_valid():
            subnet = IPListView.get_subnet(form.cleaned_data['subnet'])
            subnet.title = form.cleaned_data['new_title']
            subnet.save()
            return redirect('ip_list')
        else:
            for msg in IPListView.format_form_errors(form.errors):
                messages.error(request, msg)
            return redirect('ip_list')

@method_decorator(login_required, name='dispatch')
class DeleteSubnetView(RedirectView):

    def get(self, request, *args, **kwargs):
        if 'subnet' in kwargs.keys():
            subnet = IPListView.get_subnet(kwargs.get('subnet'))
            siblings = subnet.get_siblings()
            for sibling in siblings:
                sibling.delete()
            subnet.delete()
            return redirect('ip_list')
        else:
            messages.error(request, _('No subnet specified'))
            return redirect('ip_list')

@method_decorator(login_required, name='dispatch')
class AddHostView(RedirectView):

    def get(self, request, *args, **kwargs):
        messages.error(request, _('Method GET not supported for this URL'))
        return redirect('ip_list')

    def post(self, request, *args, **kwargs):
        form = AddHostForm(request.POST)
        if form.is_valid():
            subnet = IPListView.get_subnet(form.cleaned_data['subnet'])
            for host in subnet.hosts.all():
                if host.address == form.cleaned_data['address']:
                    messages.error(request, _('Host with that address already exists'))
                    return redirect('ip_list')
            network = ipaddress.IPv4Network('%s/%s' % (subnet.subnet, subnet.prefix))
            try:
                ip = ipaddress.IPv4Address(subnet.subnet) + form.cleaned_data['address']
                if ip not in network:
                    messages.error(request, _('IP Address %(ip)s not part of subnet %(subnet)s') %
                                   {'ip': str(ip), 'subnet': str(network)})
                    return redirect('ip_list')
            except ipaddress.AddressValueError:
                messages.error(request, _('Invalid IP Address'))
                return redirect('ip_list')
            host = Host()
            host.description = form.cleaned_data['description']
            host.address = form.cleaned_data['address']
            if form.cleaned_data['mac']:
                host.mac = form.cleaned_data['mac']
            host.parent = subnet
            host.save()
            return redirect('ip_list')
        else:
            for msg in IPListView.format_form_errors(form.errors):
                messages.error(request, msg)
            return redirect('ip_list')

@method_decorator(login_required, name='dispatch')
class DeleteHostView(RedirectView):

    def get(self, request, *args, **kwargs):
        if 'host' in kwargs.keys():
            host_id = kwargs.get('host')
            host = Host.objects.get(pk=host_id)
            host.delete()
        else:
            messages.error(request, _('No host specified'))
            return redirect('ip_list')


import numpy as np

def precompute_BM(img, kHW, NHW, nHW, tauMatch):
    """
    :search for similar patches
    :param img: input image
    :param kHW: length of side of patch
    :param NHW: how many patches are stacked
    :param nHW: length of side of search area
    :param tauMatch: threshold determine whether two patches are similar
    :return ri_rj_N__ni_nj: The top N most similar patches to the referred patch
    :return threshold_count: according to tauMatch how many patches are similar to the referred one
    """
    img = img.astype(np.float64)
    height, width = img.shape
    Ns = 2 * nHW + 1
    threshold = tauMatch * kHW * kHW
    sum_table = np.ones((Ns, Ns, height, width)) * 2 * threshold  # di, dj, ph, pw
    row_add_mat, column_add_mat = get_add_patch_matrix(height, width, nHW, kHW)
    diff_margin = np.pad(np.ones((height - 2 * nHW, width - 2 * nHW)), nHW, 'constant', constant_values=0.)
    sum_margin = (1 - diff_margin) * 2 * threshold

    for di in range(-nHW, nHW + 1):
        for dj in range(-nHW, nHW + 1):
            t_img = translation_2d_mat(img, right=-dj, down=-di)
            diff_table_2 = (img - t_img) * (img - t_img) * diff_margin

            sum_diff_2 = row_add_mat @ diff_table_2 @ column_add_mat
            sum_table[di + nHW, dj + nHW] = np.maximum(sum_diff_2, sum_margin)  # sum_table (2n+1, 2n+1, height, width)

    sum_table = sum_table.reshape((Ns * Ns, height * width))  # di_dj, ph_pw
    sum_table_T = sum_table.transpose((1, 0))  # ph_pw__di_dj
    argsort = np.argpartition(sum_table_T, range(NHW))[:, :NHW]
    argsort[:, 0] = (Ns * Ns - 1) // 2
    argsort_di = argsort // Ns - nHW
    argsort_dj = argsort % Ns - nHW
    near_pi = argsort_di.reshape((height, width, -1)) + np.arange(height)[:, np.newaxis, np.newaxis]
    near_pj = argsort_dj.reshape((height, width, -1)) + np.arange(width)[np.newaxis, :, np.newaxis]
    ri_rj_N__ni_nj = np.concatenate((near_pi[:, :, :, np.newaxis], near_pj[:, :, :, np.newaxis]), axis=-1)

    sum_filter = np.where(sum_table_T < threshold, 1, 0)
    threshold_count = np.sum(sum_filter, axis=1)
    threshold_count = closest_power_of_2(threshold_count, max_=NHW)
    threshold_count = threshold_count.reshape((height, width))

    return ri_rj_N__ni_nj, threshold_count

def get_add_patch_matrix(h, w, nHW, kHW):
    row_add = np.eye(h - 2 * nHW)
    row_add = np.pad(row_add, nHW, 'constant')
    row_add_mat = row_add.copy()
    for k in range(1, kHW):
        row_add_mat += translation_2d_mat(row_add, right=k, down=0)

    column_add = np.eye(w - 2 * nHW)
    column_add = np.pad(column_add, nHW, 'constant')
    column_add_mat = column_add.copy()
    for k in range(1, kHW):
        column_add_mat += translation_2d_mat(column_add, right=0, down=k)

    return row_add_mat, column_add_mat

def translation_2d_mat(mat, right, down):
    mat = np.roll(mat, right, axis=1)
    mat = np.roll(mat, down, axis=0)
    return mat

def closest_power_of_2(M, max_):
    M = np.where(max_ < M, max_, M)
    while max_ > 1:
        M = np.where((max_ // 2 < M) * (M < max_), max_ // 2, M)
        max_ //= 2
    return M

if __name__ == '__main__':
    import os
    import cv2
    from utils import add_gaussian_noise, symetrize

    # <hyper parameter>
    # ref_i, ref_j = 196, 142
    ref_i, ref_j = 164, 135
    # ref_i, ref_j = 271, 206

    kHW = 8
    NHW = 3
    nHW = 16
    tauMatch = 2500
    # <hyper parameter \>

    im = cv2.imread('test_data/image/Cameraman.png', cv2.IMREAD_GRAYSCALE)
    im = im[100:, :]
    ref_i, ref_j = 64, 135
    im_noisy = add_gaussian_noise(im, 10, seed=1)

    img_noisy_p = symetrize(im_noisy, nHW)
    near_pij, threshold_count = precompute_BM(img_noisy_p, kHW=kHW, NHW=NHW, nHW=nHW, tauMatch=tauMatch)

    im = cv2.cvtColor(img_noisy_p, cv2.COLOR_GRAY2RGB)
    # <draw search area>
    points_list = [(ref_j - nHW, ref_i - nHW), (ref_j + nHW, ref_i - nHW), (ref_j - nHW, ref_i + nHW),
                   (ref_j + nHW, ref_i + nHW)]
    for point in points_list:
        cv2.circle(im, point, 0, (0, 0, 255), 1)
    # <draw search area \>

    # <draw reference patch>
    cv2.rectangle(im, (ref_j, ref_i), (ref_j + kHW, ref_i + kHW), color=(255, 0, 0), thickness=1)
    # <draw reference patch \>

    # <draw similar patches>
    count = threshold_count[ref_i, ref_j]
    for i, Pnear in enumerate(near_pij[ref_i, ref_j]):
        if i == 0:
            continue
        if i > count:
            break
        y, x = Pnear
        cv2.rectangle(im, (x, y), (x + kHW, y + kHW), color=(0, 255, 0), thickness=1)
    # <draw similar patches \>

    # cv2.imshow('im', im)
    # cv2.waitKey()
    cv2.imwrite('BM_real_im_test.png', im)


from tkinter import *
import tkinter as tk
import attendance_window
import database_options_window

class AttendanceApplication:

	def __init__(self):
		main_window = Tk()
		main_window.title('Pi Kappa Phi Brotherhood Database')
		main_window.geometry('700x400+100+100')
		main_window.resizable(width=FALSE, height=FALSE)

		main_frame = Frame(main_window)
		main_frame.grid(column=0, row=0)

		welcome_label = tk.Label(main_frame,
			text = "Welcome to the Pi Kappa Phi Brotherhood Database!",
			font = ("Corbel", "20", "bold"))
		welcome_label.grid(row = 1, column = 1, padx = 32, pady = 32)

		description_label = tk.Label(main_frame,
			text = "Please choose an option above...",
			font = ("Corbel", "16", "italic"))
		description_label.grid(row = 5, column = 1, padx = 32, pady = 32)

		attendance_button = tk.Button(main_frame,
			text = "Take Attendance",
			command = self.attendance_button_clicked,
			font = ("Corbel", "16"))
		attendance_button.grid(row =2, column=1, padx = 20, pady = 20)

		database_options_button = tk.Button(main_frame,
			text = "Database Options",
			command = self.database_options_button_clicked,
			font = ("Corbel", "16"))
		database_options_button.grid(row = 3, column = 1, padx = 20, pady = 20)

		main_window.mainloop()

	def attendance_button_clicked(*args):
		attendance_window.AttendanceWindow()

	def database_options_button_clicked(*args):
		database_options_window.DatabaseOptionsWindow()


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

import os
import datetime
import sys
import commands
import shutil
import random
import copy
import rospy
import numpy as np

from random import randint

import uav
import mapa
import grid
import posicionamento

def main():

    uavs = []
    for i in range(tam_uav):
        u = uav.UAV( 'ardrone_'+str(i), divisao, 'boustrophedon', bs)
        uavs.append(u)

    tam=tam_uav
    rospy.loginfo("[UAVs] Instanciando %d uavs.", tam)

    rospy.init_node('mestrado', anonymous=True)
    #rospy.Rate(10) # 1hz: equivale a 1 atualização por segundo

    # Ajustar posicionamento aleatório para cada uav
    p = posicionamento.Pos(uavs)
    p.inicializarBous()

    #Instante inicial
    now1=rospy.get_time()
    bsIni=rospy.get_time()

    #while (not rospy.is_shutdown() or bs['sair'] == False):
    while (not rospy.is_shutdown()):
        try:
            if bs['sair']==False:
                for u in uavs:
                    if bs['sair']==True:
                        break

                    bs["heat"]+=1
                    u.executarMissao(uavs)

                now2=rospy.get_time() #Instante atual
                #rospy.loginfo("[Tempo] now1: %.2f, now2: %.2f, dif: %.2f", now1, now2, now2-now1)

                if (now1 == 0.00 and now2 >= 670.0) or (now1 != 0 and now2-now1 >= 5.0):
                    now1=rospy.get_time()

                    if len(comando)>0:
                        if comando[0] == 'i':
                            incluir(uavs, p, tam).incluir(uavs)
                            tam+=1
                        elif comando[0] == 'e':
                            u_excluir=excluir(uavs, tam-1)
                            bs['mapa'].areasVisitadas += u_excluir.mapa.areasVisitadas
                            u_excluir.excluir(uavs)
                            tam-=1
                        del comando[0]

                #bs['mapa'].areasVisitadas
                bs_out = open('rascunho_bsAreasVisitadas.out', 'w+')
                np.savetxt(bs_out, bs['mapa'].areasVisitadas, fmt='%03.1f', delimiter=' , ', newline='\n',)
                bs_out.close()

            elif bs['sair']==True:
                break

        except rospy.ROSInterruptException:
            rospy.loginfo("Saindo...")
            rospy.is_shutdown()
        except rospy.service.ServiceException:
            rospy.loginfo("Exceção ServiceException lançada!")
            rospy.is_shutdown()

    base_station(bsIni)
    rospy.loginfo("Encerrando.")

def incluir(uavs, p, tam):
    u = uav.UAV('ardrone_'+str(tam), divisao, 'boustrophedon', bs)

    uavs.append(u)

    return u

def excluir(uavs, tam):
    pos=random.randint(0,tam)
    #pos=random.randint(0,4)

    u=uavs[pos]
    uavs.remove(u)

    return u

def base_station(bsIni):
    bsEnd=rospy.get_time()
    local_visitado = np.argwhere(bs['mapa'].areasVisitadas != 0)

    min    = np.amin(bs['mapa'].areasVisitadas)
    max    = np.amax(bs['mapa'].areasVisitadas)
    mean   = np.mean(bs['mapa'].areasVisitadas)
    median = np.median(bs['mapa'].areasVisitadas)
    avg    = np.average(bs['mapa'].areasVisitadas)
    std    = np.std(bs['mapa'].areasVisitadas)
    perc   = np.percentile(bs['mapa'].areasVisitadas,90)

    ts2 = datetime.datetime.now()
    timestamp=str(ts2.year)+str(ts2.month)+str(ts2.day)+'_'+str(ts2.hour)+str(ts2.minute)+str(ts2.second)

    bs_out = open(timestamp+'_bsAreasVisitadas.out', 'w+')

    dif=ts2-ts1

    tempo_min=divmod(dif.total_seconds(), 60)[0]

    np.savetxt(bs_out, \
               bs['mapa'].areasVisitadas, fmt='%03.1f', delimiter=' , ', newline=']\n[', \
               header='result=np.array([',
               footer=']]) \n \
 --- Cobertura: '+str((float(len(local_visitado)) / 400.0) * 100 )+'% ('+str(len(local_visitado))+'/400.0) \n \
 --- Percurso em: '+str(tempo_min)+' min ('+ts1.strftime("%H:%M")+', '+ts2.strftime("%H:%M")+') \n \
 --- Qtde de uavs: '+str(tam_uav)+', Comando: '+str(cp_comando)+' \n \
 --- Min: '+str(min)+', \n \
 --- Max: '+str(max)+', \n \
 --- Mean: '+str(round(mean,2))+', \n \
 --- Median: '+str(round(median,2))+', \n \
 --- Average: '+str(round(avg,2))+', \n \
 --- Std: '+str(round(std,2))+', \n \
 --- Percentile90: '+str(perc)+' ')

    bs_out.close()

    cmd='mv %s atuacao/' % (timestamp+'_bsAreasVisitadas.out')
    status, output0 = commands.getstatusoutput(cmd)

    cmd='ls -tr heat*.png | tail -n 1'
    status, output1 = commands.getstatusoutput(cmd)

    cmd='mv %s atuacao/%s' % (output1, timestamp+'_'+output1)
    status, output2 = commands.getstatusoutput(cmd)

    #os.system("avconv -start_number 20 -i heat%08d.png -r 10000 -c:v libx264 -crf 20 -pix_fmt yuv420p atuacao/"+timestamp+"_mapa_de_calor2.mp4")

def apagarDiretorios():
    # Apagando arquivo bs
    files = os.listdir("/home/grazieno/ros-mestrado")
    for f in files:
        if f.endswith(".out") or f.endswith(".png"):
            os.remove(f)

    # Apagando diretorios anteriores
    dirs = os.listdir("/home/grazieno/ros-mestrado")
    for d in dirs:
        if d.startswith("ardrone_"):
            shutil.rmtree(d)

if __name__ == "__main__":
    divisao = 'voronoi'
    tam_uav = int(sys.argv[1])

    #comando=[]
    #comando=['i']
    #comando=['e']
    comando=['i', 'e']

    cp_comando=copy.deepcopy(comando)

    ts1 = datetime.datetime.now()

    bs = {
        "mapa": mapa.Mapa(),  #idade,areasVisitadas,alvos,probabilidade
        "grid": grid.Grid(),  #grid com regioes de voronoi
        "sair": False,        #flag para execucao terminar
        "heat": 0             #contador para mapa de calor (heat)
    }

    #bs['mapa'].areasVisitadas[:]=1.0
    #bs['mapa'].areasVisitadas[0][0]=0

    apagarDiretorios()
    main()


'''
http://www.pythonchallenge.com
#1-2 url = http://www.pythonchallenge.com/pc/def/map.html
to build a Caesar cipher system as the roles described as the wiki said:
https://en.wikipedia.org/wiki/Caesar_cipher
letters only no matter lower case or upper case, return none letter directly
tools: ord chr and str.maketrans() and str.translate()
    A to Z, means 65 to 90
    a to z, means 97 to 122
'''
shiftValue = -2
plaintext = \
'''
i hope you didnt translate it by hand. thats what computers are for.
doing it in by hand is inefficient and that's why this text is so long.
using string.maketrans() is recommended. now apply on the url.
'''
ciphertext = \
'''
g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. \
bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle.\
 sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj.
'''
def shiftValueConvert(shiftValue):
    '''
    convert caesar cipher shift value from any possible value to a positive int number between 0-25
    :param shiftValue: int nubmer
    :return: the int number between 0-25
    '''
    if type(shiftValue) == type(1):
        return shiftValue%26
    else:
        raise ValueError('please input int number only!')

def Caesar_cipher(text, shiftValue, encryptOrDecrypt):
    import string
    lc = string.ascii_lowercase
    lu = string.ascii_uppercase
    if encryptOrDecrypt == 'encrypt':
        shiftValue = shiftValueConvert(shiftValue)
    else:
        shiftValue = shiftValueConvert(-shiftValue)

    lcShift = lc[shiftValue:] + lc[:shiftValue]
    luShift = lu[shiftValue:] + lu[:shiftValue]
    convMap = str.maketrans(lc+lu,lcShift+luShift)
    print(convMap)
    return text.translate(convMap)

def Caesar_cipher_encrypt(plaintext, shiftValue):
    return Caesar_cipher(plaintext, shiftValue, 'encrypt')

def Caesar_cipher_decrypt(ciphertext, shiftValue):
    return Caesar_cipher(ciphertext, shiftValue, 'decrypt')

#test
if __name__ == '__main__':
    test1 = Caesar_cipher_encrypt(plaintext, shiftValue)
    test2 = Caesar_cipher_decrypt(ciphertext, shiftValue)
    print('this is test1:\n')
    print(test1)
    print('this is test2:\n')
    print(test2)


'''

裁剪圖片

'''

from PIL import Image   # Importing Image class from PIL module

filename = r'C:/_git/vcs/_1.data/______test_files1/picture1.jpg'

# Opens a image in RGB mode
im = Image.open(filename)

# Size of the image in pixels (size of original image)
# (This is not mandatory)
width, height = im.size

print(width)
print(height)

# Setting the points for cropped image
left = 20
top = 20
right = width - 20 *2
bottom = height - 20 * 2

# Cropped image of above dimension
# (It will not change original image)
im1 = im.crop((left, top, right, bottom))

# Shows the image in image viewer
im.show()
im1.show()


# Programmers Greedy Algorithm
'''
무인도에 갇힌 사람들을 구명보트를 이용하여 구출하려고 합니다.
구명보트는 작아서 한 번에 최대 2명씩 밖에 탈 수 없고, 무게 제한도 있습니다.

예를 들어, 사람들의 몸무게가 [70kg, 50kg, 80kg, 50kg]이고 구명보트의 무게 제한이 100kg이라면
2번째 사람과 4번째 사람은 같이 탈 수 있지만 1번째 사람과 3번째 사람의 무게의 합은 150kg이므로
구명보트의 무게 제한을 초과하여 같이 탈 수 없습니다.

구명보트를 최대한 적게 사용하여 모든 사람을 구출하려고 합니다.

사람들의 몸무게를 담은 배열 people과 구명보트의 무게 제한 limit가 매개변수로 주어질 때,
모든 사람을 구출하기 위해 필요한 구명보트 개수의 최솟값을 return 하도록 solution 함수를 작성해주세요.
'''

# 제한사항
'''
제한사항
무인도에 갇힌 사람은 1명 이상 50,000명 이하입니다.
각 사람의 몸무게는 40kg 이상 240kg 이하입니다.
구명보트의 무게 제한은 40kg 이상 240kg 이하입니다.
구명보트의 무게 제한은 항상 사람들의 몸무게 중 최댓값보다 크게 주어지므로 사람들을 구출할 수 없는 경우는 없습니다.
'''

def solution(people, limit):
    answer = len(people)
    people = sorted(people)
    small = 0
    big = answer-1

    while ( small < big ): #다 구명보트에 넣을 때까지
        if ( people[big] + people[small] <= limit): # 가장 큰 사람과 작은 사람을 함께 태울 수 있는가
            small += 1 # 작은 사람 보트에
            answer -= 1 # 보트 하나 줄이기
        big -= 1 # 큰 사람 보트에
    return answer

print(solution([70, 80, 50],100))


#-*- coding: utf-8 -*-
#from sparta.lib.base import *
from sparta.model import *

import Login
import Files
import SMS

## 쪽지함 접근용 API 클래스
# @date 2009-11-09 정기영

def getNoReadCount():
	""" 읽지않은 쪽지 갯수를 반환한다 """

	CntNonRead = Archive.RunQuery("select count(IDX) from MsgInBox where Receiver = :id and IsRead =0", id=Login.getID() )[0][0]
	return CntNonRead

def getMessage(msgidx, readStamp=True):
	""" 쪽지를 읽어온다 """

	mData = Archive("MsgInBox").getValues(msgidx, "Content,Receiver,Sender,Attachments,IsRead")

	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")

	if mData["Receiver"] != Login.getID() and mData["Sender"] != Login.getID():
		raise SpartaUserError("메세지를 볼수있는 권한이 없습니다")

	if readStamp and (mData["IsRead"] == False):
		# 스탬핑 처리
		Archive("MsgInBox").Edit(msgidx, IsRead=True)

		# 보낸 편지에도 읽기 스템핑
		r_idx = Archive("MsgSent").getValue("MsgSent.RelateIDX == "+str(msgidx), "IDX")
		if r_idx:
			Archive("MsgSent").Edit(r_idx, IsRead=True)

	outText = mData["Content"]

	if mData["Attachments"]:
		outText += u'

첨부	%s

' % ( msgidx, mData["Attachments"])

	return outText

def getMessage2(msgidx, readStamp=True):
	""" 쪽지를 읽어온다 """

	mData = Archive("MsgSent").getValues(msgidx, "Content,Receiver,Sender,Attachments,IsRead")

	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")

	outText = mData["Content"]

	if mData["Attachments"]:
		outText += u'

첨부	%s

' % ( msgidx, mData["Attachments"])

	return outText

def sendSystemMessage(receiver, subject, content):
	""" 시스템에서 변경사항에 대해 쪽지를 발송 """

	TODAY_STR = datetime.datetime.now().strftime("%Y-%m-%d")
	NOW_STR = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

	sendCnt = 0
	msgSave = {"Subject": subject, "Sender": "system", "SenderName": "업데이트" }

	if "<" in receiver:
		# Address Parsing :: "정기영" <im@fxpoet.com>, "김태희" <kim@google.com>  -> ["im@fxpoet.com",	"kim@google.com"]
		addrsList = re.findall("\<([._,a-zA-Z0-9:\#\@]+)\>+", receiver)
	else:
		addrsList = [n.strip() for n in receiver.split(",")]

	for recID in addrsList:

		q = "MsgInBox.Sender == system,MsgInBox.Receiver == %s,MsgInBox.CreateDate > %s" % (recID, TODAY_STR)
		rs = Archive("MsgInBox").getValues(q, "IDX,Subject,Content,IsRead", orderString="MsgInBox.CreateDate DESC")

		if rs and not rs["IsRead"]:
			# 로그 수정
			mIDX = rs["IDX"]
			mContent = rs["Content"] + u"\n %s --------- \n%s\n "  % (NOW_STR, unicode(content,"UTF8"))
			Archive("MsgInBox").Edit( mIDX, Subject=subject, Content=mContent )

		else:
			msgSave["Content"] = u"\n %s --------- \n%s\n "  % (NOW_STR, unicode(content,"UTF8"))
			msgSave["Receiver"] = recID

			# 로그 발송
			if Archive("MsgInBox").New(**msgSave):
				sendCnt += 1

	return sendCnt

def sendMessage( receiver, subject, content, attachments=None, withSMS=None ):
	""" 쪽지함에 쪽지를 발송
	"""
	#[TODO] To,CC,BCC에 대한 처리 필요
	#[TODO] IF not logined !!

	smsList = []
	msgIDXs = []
	msgSave = { "Subject": subject, "Content": content, "Sender": Login.getID(), "SenderName": Login.getName() }

	if "<" in receiver:
		#ex) Address Parsing :: "정기영" <im@fxpoet.com>, "김태희" <kim@google.com>  -> ["im@fxpoet.com",  "kim@google.com"]
		addrsList = re.findall("\<([._,a-zA-Z0-9:\#\@]+)\>+", receiver)
	else:
		addrsList = [n.strip() for n in receiver.split(",")]

	for recID in addrsList:

		userData = Archive("User").getValues( "User.UserID == "+ recID, "Name,HandPhone" )
		if userData:
			msgSave["Receiver"] = recID

			result_IDX = Archive("MsgInBox").New(**msgSave)

			if result_IDX:
				msgIDXs.append( result_IDX )
				if userData["HandPhone"] and not userData["HandPhone"].replace("-","") in smsList:
					smsList.append( str(userData["HandPhone"].replace("-","")) )

				sentMsg = { "RelateIDX": result_IDX, "Subject": subject, "Content": content, "Receiver": recID, "ReceiverName": userData["Name"], "Sender": Login.getID() }
				r = Archive("MsgSent").New( **sentMsg )

	if attachments:
		#[TODO] 임시 코드입니다. 멀티센딩에서 업된 파일에 대한 레퍼런스 카운트가 이상적이나 일단 그냥 복제형태로 갑니다.
		if type(attachments) == unicode:
			attachments = attachments.encode("utf8")

		uploadFile = Files.getRootDir() + attachments
		fileName = os.path.split(attachments)[1]

		if os.path.exists( uploadFile ):
			for ridx in msgIDXs:
				if str(ridx).isdigit():
					targetFile = "/data/message/%s.%s" % ( fileName, ridx )
					shutil.copy2( uploadFile, Files.getSpartaDir() + targetFile )
					msgMod = { "IDX" : ridx, "Attachments" : "%s" % fileName }
					r = Archive( "MsgInBox" ).New( **msgMod )
			os.remove(uploadFile)

	if withSMS and smsList:
		SMS.send( sendMsg=u"스팔타쪽지>"+msgSave["Subject"], recvList=smsList )

	return len(msgIDXs)

def removeMessage(msgidx):

	mData = Archive("MsgInBox").getValues(msgidx, "Receiver,Sender,Attachments")

	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")

	if mData["Receiver"] != Login.getID() and (not CheckAdmin()) and mData["Sender"] != Login.getID():
		raise SpartaAccessError("메세지를 삭제할 수 있는 권한이 없습니다")

	r = Archive("MsgInBox").Remove( msgidx )
	#[TODO] 파일삭제 처리!!!
	return r

def removeSent(sendidx):

	mData = Archive("MsgSent").getValues(sendidx, "Sender,Attachments")

	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")

	if mData["Sender"] != Login.getID() and (not CheckAdmin()):
		raise SpartaAccessError("메세지를 삭제할 수 있는 권한이 없습니다")

	r = Archive("MsgInBox").Remove(sendidx)
	#[TODO] 파일삭제 처리!!!

	return r

def cancelMessage(sentidx):

	mData = Archive("MsgSent").getValues(msgidx, "RelateIDX,Sender,Attachments")

	if mData == None:
		raise SpartaUserError("존재하지 않는 쪽지번호 입니다")

	if mData["Sender"] != Login.getID() and (not CheckAdmin()):
		raise SpartaUserError("메세지를 삭제할 수 있는 권한이 없습니다")

	rData = Archive("MsgInBox").getValue( mData["RelateIDX"], "IDX,IsRead")

	if rData:
		if rData["IsRead"] == False:
			return removeMessage( rData["IDX"] )
		else:
			raise SpartaUserError("발송된 메세지는 이미 읽은 메세지입니다")
	else:
		raise SpartaUserError("발송된 메세지는 이미 삭제되었습니다")

	return int(0)


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

import random
import string
import traceback

# See:
# https://atcoder.jp/contests/abc284/submissions/37841742
class RollingHashWithRange:
    def __init__(self, parent, left, right) -> None:
        self.parent = parent
        self.left = left
        self.right = right

    def __getitem__(self, key):
        if key > self.right - self.left:
            traceback.print_exc()
            raise Exception("index out of range")

        return self.get(self.left, self.left + key)

    # Overall hash value
    def get(self, left, right):
        mod = RollingHash.mod
        return (
            self.parent.hash[right]
            - self.parent.hash[left] * self.parent.power[right - left]
        ) % mod

    def __len__(self):
        return self.right - self.left

    def __eq__(self, other):
        return self.get(self.left, self.right) == other.get(other.left, other.right)

    # Longest Common Prefix
    def __lt__(self, other):
        length = min(len(self), len(other))

        if self[length] == other[length]:
            return len(self) < len(other)

        left, right = 0, length

        while True:
            mid = (left + right) // 2

            if left == right:
                return (
                    self.parent.s[self.left + right - 1]
                    < other.parent.s[other.left + right - 1]
                )

            if self[mid] != other[mid]:
                right = mid
            else:
                left = mid + 1
                right = right

class RollingHash:
    base = 30
    mod = 10**9 + 9

    @classmethod
    def config(cls, base, mod) -> None:
        RollingHash.base = base
        RollingHash.mod = mod

    def __init__(self, s) -> None:
        mod = RollingHash.mod
        base = RollingHash.base
        self.power = power = [1] * (len(s) + 1)
        self.s = s

        size = len(s)
        self.hash = hash = [0] * (size + 1)

        value = 0

        for i in range(size):
            hash[i + 1] = value = (value * base + ord(s[i])) % mod

        value = 1

        for i in range(size):
            power[i + 1] = value = value * base % mod

    def get(self, left, right) -> RollingHashWithRange:
        return RollingHashWithRange(self, left, right)

def get_random_name(n):
    rand_list = [random.choice(string.ascii_letters + string.digits) for i in range(n)]
    return "".join(rand_list)

def test():
    RollingHash.config(100, 10**9 + 7)

    for i in range(100):
        n = 5
        x, y = get_random_name(n), get_random_name(n)
        y = x

        if (x < y) != (RollingHash(x).get(0, n) < RollingHash(y).get(0, n)):
            print(
                "No", x < y, RollingHash(x).get(0, n) < RollingHash(y).get(0, n), x, y
            )

def main():
    import sys

    input = sys.stdin.readline

    n, q = map(int, input().split())
    s = input().rstrip()
    rh = RollingHash(s)

    for _ in range(q):
        ai, bi, ci, di = map(int, input().split())
        ai -= 1
        ci -= 1

        if rh.get(ai, bi) == rh.get(ci, di):
            print("Yes")
        else:
            print("No")

if __name__ == "__main__":
    main()


import math
import numpy as np
import csv

# Calculates distance between v1 and v2
def euclidean(v1,v2):
	d=0.0
	for i in range(len(v1)):
		d+=(float(v1[i])-float(v2[i]))**2
	return math.sqrt(d)

# Gets distance list
def getdistances(data,vec1):

	distancelist=[]
	for i in range(len(data)):
		vec2=data[i]
		distancelist.append(euclidean(vec1,vec2))
	return distancelist

# KNN Algorithm
def knn(data,data_y,y_labels,test,k):
	# Gets the distance list
	dis_list=getdistances(data,test)
	# Sort the distance list
	sorted_dis_list=sorted(dis_list)

	Dz=[]
	for i in range(k):
		Dz.append(dis_list.index(sorted_dis_list[i]))

	vote=[]
	for i in range(len(y_labels)):
		vote.append(0)
		for j in range(len(Dz)):
			# Increment the vote for a class
			if data_y[Dz[j]]==y_labels[i]:
				vote[i]+=1
	return vote

'''
# Preprocessing
# To Generate Dataset in matrix form
f=open("splice.data","r")

reader=csv.reader(f,delimiter=',')
data=[]
data_y=[]
d={'A':1.0,'T':2.0,'G':3.0,'C':4.0,'N':5.0,'D':6.0,'R':7.0,'S':8.0}

for row in reader:
	s=list(row[2].strip())
	data1=[]
	for i in s:
		if i in d:
			data1.append(d[i])
	data1.append(row[0])
	data.append(data1)
	if row[0] not in data_y:
		data_y.append(row[0])

count=0
print data_y
for i in data[1:]:
	vote=knn(data,data_y,i[:-1],1)
	#print data_y[vote.index(max(vote))],i[-1]
	if data_y[vote.index(max(vote))]==i[-1]:
		count+=1

print count,len(data)-1
print float(count)/(len(data)-1)
'''


from networks import *
from Utils.utils import *
from torch.nn.functional import interpolate as Inter
from torch.nn import Conv2d
class Rain_steaks_with_BG(nn.Module):
    '''get rain steaks with background from RGBrain_img
    return img-----512 512 3*3    '''
    def __init__(self):
        super(Rain_steaks_with_BG, self).__init__()
        self.conv_3_0 = conv_blocks_size_3(in_dim=3 , out_dim=4 , Use_pool=True) #256
        weights_init_xavier(self.conv_3_0)
        self.conv_3_1 = conv_blocks_size_3(4,8,Use_pool=True) #128
        weights_init_xavier(self.conv_3_1)
        self.conv_3_2 = conv_blocks_size_3(8,16,True) #64
        weights_init_xavier(self.conv_3_2)

        self.deconv_3_0 = deconv_blocks_size_3(16,8,True) #128
        weights_init_xavier(self.deconv_3_0)
        self.deconv_3_1 = deconv_blocks_size_3(8, 4, True) #256
        weights_init_xavier(self.deconv_3_1)
        self.deconv_3_2 = deconv_blocks_size_3(4,3,True) #512
        weights_init_xavier(self.deconv_3_2)

        self.conv_5_0 = conv_blocks_size_5(in_dim=3, out_dim=4, Use_pool=True)  # 256
        weights_init_xavier(self.conv_5_0)
        self.conv_5_1 = conv_blocks_size_5(4, 8, Use_pool=True)  # 128
        weights_init_xavier(self.conv_5_1)
        self.conv_5_2 = conv_blocks_size_5(8,16,True) #64
        weights_init_xavier(self.conv_5_2)

        self.conv_7_0 = conv_blocks_size_7(in_dim=3, out_dim=4, Use_pool=True)  # 256
        weights_init_xavier(self.conv_7_0)
        self.conv_7_1 = conv_blocks_size_7(4,8, Use_pool=True)  # 128
        weights_init_xavier(self.conv_7_1)
        self.conv_7_2 = conv_blocks_size_7(8,16, True)  # 64
        weights_init_xavier(self.conv_7_2)

    def forward(self,x):
        input_3 = x
        input_3 = self.conv_3_0(input_3)
        input_3 = self.conv_3_1(input_3)
        input_3 = self.conv_3_2(input_3)
        input_3 = self.deconv_3_0(input_3)
        input_3 = self.deconv_3_1(input_3)
        input_3 = self.deconv_3_2(input_3)

        input_5 = x
        input_5 = self.conv_5_0(input_5)
        input_5 = self.conv_5_1(input_5)
        input_5 = self.conv_5_2(input_5)
        input_5 = self.deconv_3_0(input_5)
        input_5 = self.deconv_3_1(input_5)
        input_5 = self.deconv_3_2(input_5)

        input_7 = x
        input_7 = self.conv_7_0(input_7)
        input_7 = self.conv_7_1(input_7)
        input_7 = self.conv_7_2(input_7)
        input_7 = self.deconv_3_0(input_7)
        input_7 = self.deconv_3_1(input_7)
        input_7 = self.deconv_3_2(input_7)

        return torch.cat([input_3,input_5,input_7] ,dim=1)

class Low_BackGround(nn.Module):
    '''get low background from RGB rain_Img
    in order to move rain steaks ,wo decide to insert some residual img
    to make CNN do his jod better  input 512 512 3 retrun 32 32 64'''
    def __init__(self):
        super(Low_BackGround, self).__init__()
        self.encode1 = conv_blocks_size_3(in_dim=4 , out_dim=8 ,Use_pool=True)  #256
        weights_init_xavier(self.encode1)
        self.encode2 = conv_blocks_size_3(in_dim=8 ,out_dim=16,Use_pool=True)   #128
        weights_init_xavier(self.encode2)
        self.encode3 = conv_blocks_size_3(in_dim=16 ,out_dim=32,Use_pool=True)   #64
        weights_init_xavier(self.encode3)
        self.encode4 = conv_blocks_size_3(in_dim=32,out_dim=64,Use_pool=True)   #32
        weights_init_xavier(self.encode4)
        self.encode5 = conv_blocks_size_3(in_dim=64,out_dim=128,Use_pool=True)  #16
        weights_init_xavier(self.encode5)
        self.encode6 = conv_blocks_size_5(in_dim=128,out_dim=256,Use_pool=True)#8
        weights_init_xavier(self.encode5)

        self.decode1 = deconv_blocks_size_3(in_dim=256,out_dim=128,Use_pool=True) #16
        weights_init_xavier(self.decode1)
        self.decode2 =deconv_blocks_size_3(128,64,Use_pool=True) #32
        weights_init_xavier(self.decode2)
        self.decode3 = deconv_blocks_size_3(64,32,Use_pool=True) #64
        weights_init_xavier(self.decode3)
        self.decode4 = deconv_blocks_size_3(32,16,Use_pool=True) #128
        weights_init_xavier(self.decode4)
        self.decode5 = deconv_blocks_size_3(16,8,True) #256
        weights_init_xavier(self.decode5)
        self.decode6 = deconv_blocks_size_3(8,4,True) #512
        weights_init_xavier(self.decode6)

        self.eencode1 = conv_blocks_size_3(4,8,True) #256
        weights_init_xavier(self.eencode1)
        self.eencode2 = conv_blocks_size_3(8,16,True)#128
        weights_init_xavier(self.eencode2)
        self.eencode3 = conv_blocks_size_3(16,32,True)#64
        weights_init_xavier(self.eencode3)
        self.eencode4 = conv_blocks_size_3(32, 64, True)  # 32
        weights_init_xavier(self.eencode4)
        self.eencode5 = conv_blocks_size_3(64, 128, True)  # 16
        weights_init_xavier(self.eencode5)
        self.eencode6 = conv_blocks_size_3(128, 256, True)  # 8
        weights_init_xavier(self.eencode6)

        self.ddcode1 = deconv_blocks_size_3(256,128)
        self.ddcode2 = deconv_blocks_size_3(128,64)
        self.ddcode3 = deconv_blocks_size_3(64, 32)
        self.ddcode4 = deconv_blocks_size_3(32, 16)
        self.ddcode5 = deconv_blocks_size_3(16, 8)
        self.ddcode6 = deconv_blocks_size_3(8, 4)

    def forward(self,x):
        # x  512 512 3
        """insert img to use residual_img as a auxiliary"""
        insert_img = 0.8 * get_residue(x) + 0.2 * rgb2grad(x)  #insert image
        x = torch.cat([x , insert_img], 1) #512
        encode1 = self.encode1(x)      #256
        encode2 = self.encode2(encode1) #128
        encode3 = self.encode3(encode2) #64
        encode4 = self.encode4(encode3) #32
        encode5 = self.encode5(encode4) #16
        encode6 = self.encode6(encode5) #8

        #super_U-net

        decode = torch.add(encode5 , self.decode1(encode6))  #16
        decode = torch.add(encode4 , self.decode2(decode))   #32
        decode = torch.add(encode3 , self.decode3(decode))  #64
        decode = torch.add(encode2 ,self.decode4(decode))  #128
        decode = torch.add(encode1 , self.decode5(decode)) #256
        decode = torch.add(x , self.decode6(decode)) #512

        del encode1
        del encode2
        del encode3
        del encode4
        del encode5
        del encode6

        eencode1 = self.eencode1(decode)
        eencode2 = self.eencode2(eencode1)
        eencode3 = self.eencode3(eencode2)
        eencode4 = self.eencode4(eencode3)
        eencode5 = self.eencode5(eencode4)
        eencode6 = self.eencode6(eencode5)

        ddecode = torch.add(self.ddcode1(eencode6) , eencode5)
        del eencode6,eencode5
        ddecode = torch.add(self.ddcode2(ddecode) , eencode4)
        del eencode4
        ddecode = torch.add(self.ddcode3(ddecode), eencode3)
        del eencode3
        ddecode = torch.add(self.ddcode4(ddecode), eencode2)
        del eencode2
        ddecode = torch.add(self.ddcode5(ddecode), eencode1)
        del eencode1
        ddecode = torch.add(self.ddcode6(ddecode), decode)

        return  ddecode

class Classfication(nn.Module):
    '''classfication to classfy rain dense ,make sure Rain_with_Background success extract
    rain steaks (with some high level background will be fine )
    input 512 512 9'''
    def __init__(self):
        super(Classfication, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(9,16, kernel_size=3, stride=1, padding=1),
            nn.ReLU(True),
            nn.BatchNorm2d(16),
            nn.MaxPool2d(kernel_size=2, stride=2),        #256

            nn.Conv2d(16,32, kernel_size=3, stride=1, padding=1),
            nn.ReLU(True),
            nn.BatchNorm2d(32),
            nn.MaxPool2d(kernel_size=2, stride=2),    #128

            nn.Conv2d(32, 2*32, kernel_size=3, stride=1, padding=1),
            nn.ReLU(True),
            nn.BatchNorm2d(2*32),
            nn.MaxPool2d(kernel_size=2, stride=2),  # 64

            nn.Conv2d(32*2, 4 * 32, kernel_size=3, stride=1, padding=1),
            nn.ReLU(True),
            nn.BatchNorm2d( 4 * 32),
            nn.MaxPool2d(kernel_size=2, stride=2),  # 32

            nn.Conv2d(32 * 4, 8 * 32, kernel_size=3, stride=1, padding=1),
            nn.ReLU(True),
            nn.BatchNorm2d(8 * 32),
            nn.MaxPool2d(kernel_size=2, stride=2),  # 16

            nn.Conv2d(32 * 8, 16 * 32, kernel_size=3, stride=1, padding=1),
            nn.ReLU(True),
            nn.BatchNorm2d(16 * 32),
            nn.MaxPool2d(kernel_size=2, stride=2),  # 8

            nn.Conv2d(32 * 16, 32 * 32, kernel_size=3, stride=1, padding=1),
            nn.ReLU(True),
            nn.BatchNorm2d(32 * 32),
            nn.MaxPool2d(kernel_size=2, stride=2),  # 4

        )

        self.classfier = nn.Sequential(

            nn.Linear( 4*4*32*32, 4096 ),
            nn.ReLU(True),
            nn.Linear(4096 , 1000 ),
            nn.ReLU(True),
            nn.Linear(1000 ,3),
            nn.ReLU(True),
        )
        weights_init_xavier(self.features)
        weights_init_xavier(self.classfier)
        self.relu = nn.ReLU()
    def forward(self,x):
        x = self.relu(x)
        x = self.features(x)
        x = x.view( x.size(0) , -1)
        x = self.classfier(x)
        return  x

class Derain(nn.Module):
    '''refine our model out put ,ny magnifying input and then refine it
    input 64 64 4*32 return 512 512 3 '''
    def __init__(self):
        super(Derain, self).__init__()
        self.low1 = deconv_blocks_size_3(32,16,True)
        weights_init_xavier(self.low1)
        self.low2 = deconv_blocks_size_3(16 ,8 ,True)
        weights_init_xavier(self.low2)
        self.low3 = deconv_blocks_size_3(8,4,True)
        weights_init_xavier(self.low3)

        self.conv1 =conv_block_size_3_without_bn(16,8)
        weights_init_xavier(self.conv1)
        self.conv2 = conv_block_size_3_without_bn(8, 4)
        weights_init_xavier(self.conv2)
        self.conv3 = conv_block_size_3_without_bn(4, 3)
        weights_init_xavier(self.conv3)

        self.relu = Nonlinear_layer(relu= True)
    def forward(self,High, Low , rain_img):
        '''High           512 512 9
        low 512 512 4'''

        rain_img = torch.cat([Low , High , rain_img],dim=1)  #512 512 16
        rain_img = self.conv1(rain_img)
        rain_img = self.conv2(rain_img)
        rain_img = self.conv3(rain_img)

        return rain_img


from configparser import ConfigParser
config = ConfigParser()

class map_fact_production:
    def __init__(self, file_config):
        config.read(file_config, encoding='utf-8-sig')
        self.script = "insert into dbo.Table_Map_FACT_PRODUCTION (Etat_reel,Etat_erp) Values \n"

    def mapping(self):
        section_name = 'Table_Map_FACT_PRODUCTION'
        if (config.options(section_name) == []):
            self.script=" \n";
        else:
            for key, value in config.items(section_name):
                if(value == ""):
                    self.script=" \n";
                    break
                self.script = self.script+"("+key+","+value+"),\n"

        return self.script[:-2]+"\n"


# pylint: disable=invalid-name
"""handleRouteHealthCheck"""
from setup_adaguc import setup_adaguc
from flask_cors import cross_origin
from flask import Blueprint, Response

routeHealthCheck = Blueprint('routeHealthCheck', __name__)

@routeHealthCheck.route("/healthcheck", methods=["GET"])
@cross_origin()
def handleRouteHealthCheck():
    """handleRouteHealthCheck"""
    setup_adaguc(False)
    response = Response(
        response="OK",
        mimetype='text/plain',
        status=200,
    )
    return response


def f(x):
    return {
        "monday"   :  "no",
        "tuesday"  :  "no",
        "wednesday":  "no",
        "thursday" :  "no",
        "friday"   :  "no",
        "saturday" :  "yes",
        "sunday"   :  "yes"

    }.get(x,"not a valid day")
p=raw_input()
k=f(p.lower())
print(k)


from django.urls import path
from . import views

urlpatterns = [
    path('', views.organizations_index, name='OrganizationsIndex'),
    path('new_organization/', views.create_organization, name='NewOrganization'),
    path('new_team/', views.create_team, name='NewTeam'),
    path('search_organizations/', views.search_organizations, name='SearchOrganizations'),
    path('new_organization_invites/<str:organization>/', views.new_organization_invites, name="NewOrganizationInvites"),
    path('user/', views.user, name='user'),
    path('add_user_to_organization/', views.add_user_to_organization, name='AddUserToOrg'),
    path('remove_user_from_organization/', views.remove_user_from_organization, name='RemoveUserFromOrg'),
    path('find_people/', views.find_people, name='FindPeople'),
    path('search_members/', views.search_members, name='SearchMembers'),
    path('people/<str:username>/', views.user_profile, name='UserProfile'),
    path('<str:name>/', views.organization_details, name='OrganizationDetails'),
    path('teams/add_user_to_team/<str:username>', views.add_user_to_team, name='AddUserToTeam'),
    path('add_member/<str:username>', views.add_member, name='AddMember'),
    path('remove_member/<str:username>', views.remove_member, name='RemoveMember'),
]