from enum import Enum

import tcod

from game.game_states import GameStates
from game.menu_functions import inventory_menu

class RenderOrder(Enum):
    CORPSE = 1
    ITEM = 2
    ACTOR = 3

def get_names_under_mouse(mouse, entities, fov_map):
    x, y = mouse.cx, mouse.cy

    names = [entity.name for entity in entities
             if (entity.x == x and entity.y == y and
                 tcod.map_is_in_fov(fov_map, entity.x, entity.y))]

    names = ', '.join(names)
    return names.capitalize()

def render_bar(panel, x, y, total_width, name, value, max_value, color, bg_color):
    bar_width = int(float(value) / max_value * total_width)

    tcod.console_set_default_background(panel, bg_color)
    tcod.console_rect(panel, x, y, total_width, 1, False, tcod.BKGND_SCREEN)

    tcod.console_set_default_background(panel, color)
    if bar_width > 0:
        tcod.console_rect(panel, x, y, bar_width, 1, False, tcod.BKGND_SCREEN)

    tcod.console_set_default_foreground(panel, tcod.white)
    tcod.console_print_ex(panel, x + total_width // 2, y, tcod.BKGND_NONE, tcod.CENTER,
                          '{0}: {1}/{2}'.format(name, value, max_value))

def render_map(console, map, fov_map, colors):
    for y in range(map.height):
        for x in range(map.width):
            visible = tcod.map_is_in_fov(fov_map, x, y)
            wall = map.tiles[x][y].block_sight

            if visible:
                if wall:
                    texture = 'light_wall'
                else:
                    texture = 'light_ground'
                map.tiles[x][y].explored = True
            elif map.tiles[x][y].explored:
                if wall:
                    texture = 'dark_wall'
                else:
                    texture = 'dark_ground'
            else:
                texture = None

            if texture:
                tcod.console_set_char_background(
                    console, x, y,
                    colors.get(texture),
                    tcod.BKGND_SET)

def render_entity(console, entity, fov_map):
    if tcod.map_is_in_fov(fov_map, entity.x, entity.y):
        tcod.console_set_default_foreground(console, entity.color)
        tcod.console_put_char(console, entity.x, entity.y,
                              entity.char, tcod.BKGND_NONE)

def render_all(console, ui_panel, mouse,
               entities, player,
               map, fov_map, fov_recompute,
               screen_width, screen_height,
               ui_bar_width, ui_panel_height, ui_panel_y,
               message_log, colors, game_state):
    # Draw map if fov changed
    if fov_recompute:
        render_map(console, map, fov_map, colors)

    # Draw entities
    entities_in_render_order = sorted(entities, key=lambda x: x.render_order.value)
    for entity in entities_in_render_order:
        render_entity(console, entity, fov_map)

    # Flip changes
    tcod.console_blit(console, 0, 0,
                      screen_width, screen_height,
                      0, 0, 0)

    # GUI
    tcod.console_set_default_background(ui_panel, tcod.black)
    tcod.console_clear(ui_panel)

    message_y = 1
    for message in message_log.messages:
        tcod.console_set_default_foreground(ui_panel, message.color)
        tcod.console_print_ex(ui_panel, message_log.x, message_y,
                              tcod.BKGND_NONE, tcod.LEFT,
                              message.text)
        message_y += 1

    render_bar(ui_panel, 1, 1, ui_bar_width, 'HP',
               player.creature.health, player.creature.max_health,
               tcod.light_red, tcod.dark_red)

    tcod.console_set_default_foreground(ui_panel, tcod.light_gray)
    tcod.console_print_ex(ui_panel, 1, 0, tcod.BKGND_NONE, tcod.LEFT,
                          get_names_under_mouse(mouse, entities, fov_map))

    tcod.console_blit(ui_panel, 0, 0, screen_width, ui_panel_height, 0, 0, ui_panel_y)

    # Draw inventory
    if game_state in (GameStates.SHOW_INVENTORY,
                      GameStates.DROP_INVENTORY):
        if game_state == GameStates.SHOW_INVENTORY:
            inventory_title = 'Press the key next to an item to use it, or Esc to cancel.\n'
        else:
            inventory_title = 'Press the key next to an item to drop it, or Esc to cancel.\n'
        inventory_menu(console, inventory_title, player.inventory, 50, screen_width, screen_height)

def clear_entity(console, entity):
    tcod.console_put_char(console, entity.x, entity.y,
                          ' ', tcod.BKGND_NONE)

def clear_all(console, entities):
    for entity in entities:
        clear_entity(console, entity)


#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""Outputs current time as an approximation"""

import sys
import time

# Locale
sys.path=["locale", "locale"]+sys.path
import pt as locale

def fuzz(h,m):
    """Outputs given time as an approximation"""
    diff = 60
    for i in list(locale.minutes.keys()):
        tmpdiff=m-i
        if abs(tmpdiff) < abs(diff):
            diff=tmpdiff
            ret=locale.minutes[i].replace("%", locale.hours[h]).replace("!", locale.hours[(h+1)%24])
    if h in locale.hoursplural:
        ret=ret.replace("$", locale.plural)
    else:
        ret=ret.replace("$", "")
    if h in locale.hoursfem:
        ret=ret.replace("3", locale.f)
    else:
        ret=ret.replace("3", locale.m)

    if diff == 0:
        ret=locale.exactly.replace("%", ret)
    elif diff < 0:
        ret=locale.almost.replace("%", ret)
    if partypartyparty and h == 0 and m == 0:
        ret="PARTYPARTYPARTY"
    return ret

# SUPER SECRET EASTER EGG
partypartyparty=True
# OH GOD I CAN'T WAIT TO SEE WHAT IT DOES

if __name__ == "__main__":
    t=time.localtime(time.time())
    print(fuzz(t[3],t[4]))


'''

The Magic 8-Ball is a toy used for fortune-telling or seeking advice, developed in the 1950s and manufactured by Mattel.
The user asks a question to the large plastic ball, then turns it over to reveal a written answer which appears on the surface of the toy.

https://en.wikipedia.org/wiki/Magic_8-Ball
'''
from random import randint
print("Your magic 8 ball is here!")
question=input("Ask me something! What's on your mind\n")

answer=randint(1,21)

answerdict={'1':'It is certain.',
'2':'As I see it, yes.',
'3':'Reply hazy, try again',
'4':'Don\'t count on it.',
'5':' It is decidedly so.',
'6':'Most likely.',
'7':'Ask again later.',
'8':'My reply is no.',
'9':'Without a doubt.',
'10':'Outlook good.',
'11':'Better not tell you now.',
'12':'My sources say no.',
'13':'Yes - definitely.',
'14':'Yes',
'15':'Cannot predict now.',
'16':'Outlook not so good.',
'17':'You may rely on it.',
'18':'Signs point to yes.',
'19':'Concentrate and ask again.',
'20':'Very doubtful',
}

for k , val in answerdict.items():
    if int(k)==answer:
        print(val)


'''
Write a function that receives an array of integers and returns an array consisting of the product of all numbers in the array except the number at that index.

Input: a List of integers
Returns: a List of integers

Notes:
- loop through all the numbers
- multiple each number in the array except for that index

step:
- multiply each number in an array
- after after multiply everything except for current index
'''

def product_of_all_other_numbers(arr):
    prod = 1

    for i in arr:
        prod *= i

    all_nums = [prod//i for i in arr]
    return all_nums

if __name__ == '__main__':
    # Use the main function to test your implementation
    # arr = [1, 2, 3, 4, 5]
    arr = [2, 6, 9, 8, 2, 2, 9, 10, 7, 4, 7, 1, 9, 5, 9, 1, 8, 1, 8, 6, 2, 6, 4, 8,
           9, 5, 4, 9, 10, 3, 9, 1, 9, 2, 6, 8, 5, 5, 4, 7, 7, 5, 8, 1, 6, 5, 1, 7, 7, 8]

    print(
        f"Output of product_of_all_other_numbers: {product_of_all_other_numbers(arr)}")


"""Plot the dynamic functional connctivity for a single subject."""
import os
from copy import copy

import matplotlib.pyplot as plt

import numpy as np
import pandas as pd

from brainpipe.system import Study
from brainpipe.connectivity import (remove_site_contact, dfc_summarize,
                                    anat_based_reorder)
from mne.stats import fdr_correction, bonferroni_correction

from bct.algorithms.clustering import clustering_coef_wd

st = Study('DMN-CORR')

###############################################################################
suj = 'th'
th = 1.5
session = 2
condition = ('gamma50-150', 'lp1-10_', 'cmi')
rm_succ_site = 'hard'  # 'soft' | None
plt_as = 'mpl'  # {'mpl', 'visbrain'}
savefig = False
###############################################################################

# Path :
print('-> Get path')
dfc_file = st.search(suj, *condition, folder='dfc')
xyz_file = st.search(suj, 'bipo', folder='xyz')
chan_file = st.search(suj, 'bipo', folder='channels')
anat_file = st.search(suj, folder='anatomy')
fig_path = st.path_to_folder('figure/corr_gamma')
assert len(dfc_file) == len(xyz_file) == len(chan_file) == len(anat_file) == 1

# Load the file :
print('-> Load files')
xyz = st.load(xyz_file[0], folder='xyz')
channels = st.load(chan_file[0], folder='channels')
arch = st.load(dfc_file[0], folder='dfc')
df = st.load(anat_file[0], folder='anatomy')
dfc = arch['dfc'].mean(-1)  #[..., session]
# pval = arch['pval'][..., session]

dfc_std = dfc_summarize(dfc, axis=2, method='std')
dfc_mean = dfc.mean(-1)
dfc_std = anat_based_reorder(dfc_std, df, 'name_7')[0]
dfc_mean, labels, r_index = anat_based_reorder(dfc_mean, df, 'name_7')
channels = channels[r_index]

mask = remove_site_contact(dfc_std, channels, mode='hard')
mask[np.tril_indices(dfc_std.shape[0])] = True
mask[dfc_mean < th] = True

cluster = clustering_coef_wd(dfc_std)

dfc_std = np.ma.masked_array(dfc_std, mask=mask)
dfc_mean = np.ma.masked_array(dfc_mean, mask=mask)

if plt_as == 'mpl':
    # Colormap build :
    cmap_std = copy(plt.cm.viridis)
    cmap_mean = copy(plt.cm.bwr)
    cmap_std.set_bad('black')
    cmap_mean.set_bad('black')

    plt.subplot(1, 2, 1)
    im = plt.imshow(dfc_std, cmap=cmap_std)
    # im.set_clim(0., 1.)
    plt.colorbar(im)

    plt.subplot(1, 2, 2)
    m = np.abs(dfc_mean).max()
    im = plt.imshow(dfc_mean, cmap=cmap_mean)
    # im.set_clim(-m, m)
    plt.colorbar(im)

    plt.show()
elif plt_as == 'visbrain':
    from visbrain.gui import Brain
    from visbrain.objects import SourceObj, ConnectObj, BrainObj

    b_obj = BrainObj('B3')
    s_obj = SourceObj('s', xyz[r_index, :], data=cluster, radius_min=1,
                      radius_max=30, text=channels, text_size=1., edge_width=0.)
    s_obj.color_sources(data=cluster, cmap='bwr')
    c_obj = ConnectObj('c', xyz[r_index, :], dfc_mean, antialias=True)
    Brain(source_obj=s_obj, connect_obj=c_obj, brain_obj=b_obj).show()


#!/usr/bin/env python3

"""
    Copyright 2018-03-02 Alberto Hata

    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.
"""
# TODO
# Make the code work with cv2 from python2
# Import cv2 just from visualize_cv2

# Force loading python 3 version of cv2
import importlib.util
spec = importlib.util.spec_from_file_location("cv2", "/usr/local/lib/python3.5/dist-packages/cv2/cv2.cpython-35m-x86_64-linux-gnu.so")
cv2 = importlib.util.module_from_spec(spec)
spec.loader.exec_module(cv2)

import rospy
from cv_bridge import CvBridge, CvBridgeError
from sensor_msgs.msg import Image

import numpy as np
from visualize_cv import display_instances, class_names

# Root directory of the project
import os
import sys
ROOT_DIR = os.path.abspath("../")
LIB_PATH = os.path.join(ROOT_DIR, "mrcnn/lib")
sys.path.append(LIB_PATH)

# Import Mask RCNN
from mrcnn import model as modellib
from mrcnn.config import Config

# Path to trained weights file
LOG_DIR = os.path.join(ROOT_DIR, "logs")
#MODEL_PATH = os.path.join(ROOT_DIR, "models/mask_rcnn_coco.h5")
MODEL_PATH = os.path.join(ROOT_DIR, "models/coco_vrepall_1002.h5")

class ShapesConfig(Config):
    """Configuration for training on the toy shapes dataset.
    Derives from the base Config class and overrides values specific
    to the toy shapes dataset.
    """
    # Give the configuration a recognizable name
    NAME = "vrepAll"

    # Train on 1 GPU and 8 images per GPU. We can put multiple images on each
    # GPU because the images are small. Batch size is 8 (GPUs * images/GPU).
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

    # Number of classes (including background)
    NUM_CLASSES = 1 + 8  # background + 3 shapes

    # Use small images for faster training. Set the limits of the small side
    # the large side, and that determines the image shape.
    IMAGE_MIN_DIM = 480
    IMAGE_MAX_DIM = 640

    # Use smaller anchors because our image and objects are small
    RPN_ANCHOR_SCALES = (8 * 4, 16 * 4, 32 * 4, 64 * 4, 128 * 4)  # anchor side in pixels

    # Reduce training ROIs per image because the images are small and have
    # few objects. Aim to allow ROI sampling to pick 33% positive ROIs.
    TRAIN_ROIS_PER_IMAGE = 40

    # Use a small epoch since the data is simple
    STEPS_PER_EPOCH = 100

    # use small validation steps since the epoch is small
    VALIDATION_STEPS = 5

class InferenceConfig(ShapesConfig):
    GPU_COUNT = 1
    IMAGES_PER_GPU = 1

class ros_mask_rcnn:

    def __init__(self):

        # Load model
        config = InferenceConfig()
        config.display()

        self.model = modellib.MaskRCNN(
            mode="inference", model_dir=LOG_DIR, config=config
        )

        self.model.load_weights(MODEL_PATH, by_name=True)

        # Set topics
        self.bridge = CvBridge()
        self.image_sub = rospy.Subscriber("/turtlebot2i/camera/rgb/raw_image", Image, self.callback)
        self.image_pub = rospy.Publisher("/turtlebot2i/mrcnn_out", Image, queue_size=1)

    def callback(self, data):

        try:
            cv_image = self.bridge.imgmsg_to_cv2(data, "rgb8")
            results = self.model.detect([cv_image], verbose=1)
            r = results[0]

            img_out = display_instances(
                cv_image, r['rois'], r['masks'], r['class_ids'], class_names, r['scores']
            )

            self.image_pub.publish(self.bridge.cv2_to_imgmsg(img_out, "bgr8"))

        except CvBridgeError as e:
            print(e)

if __name__ == '__main__':
    rospy.init_node('mask_rcnn_py')

    detector = ros_mask_rcnn()
    rospy.spin()


# This file contain python codes to compute globally and yearly averaged datasets
# for 2D and 3D data fields
# The computations of feedback contributions have been made following software
# that accompanies the CAM5 kernels made by Pendergrass et al (2018).

##############################
### IMPORT Python packages ###
##############################

import numpy as np
import xarray as xr
import intake

##################################
## IMPORT CMIP DATA FROM GOOGLE ##
##################################

# Convert data catalog into a dictionary of xarray datasets using the intake-esm package
def drop_time_bounds(ds):
    if 'time_bounds' in ds.coords:
        ds = ds.drop('time_bounds')
    elif 'time_bnds' in ds.coords:
        ds = ds.drop('time_bnds')

    # Rename the spatial dimensions if necessary (not needed for CESM2)
    if ('longitude' in ds.dims) and ('latitude' in ds.dims):
        ds = ds.rename({'longitude':'lon', 'latitude':'lat'})
    return ds

def import_data(col, model_name, var_name):
    cat = col.search(
        source_id = model_name,
        experiment_id = ['abrupt-4xCO2', 'piControl'],
        table_id = 'Amon',
        variable_id = var_name,
        member_id = 'r1i1p1f1' # The only one for CESM2
        )

    ds_dict = cat.to_dataset_dict(preprocess = drop_time_bounds, zarr_kwargs={'consolidated': True, 'decode_times': False})

    return ds_dict

#################################
##### IMPORT RELEVANT FIELDS ####
#################################

def import_var(col, model_name, var_name):

    # Search for relevant datasets and load them in
    ds_dict = import_data(col, model_name, var_name)

    # Get rid of unnecessary coordinates and split in abrupt and control datasets
    for name, ds in ds_dict.items():

        ds = xr.decode_cf(ds)

        for coord in ds.coords:
            if coord not in ['lat', 'lon', 'plev', 'time']:
                ds = ds.drop(coord)

        if 'abrupt' in name:
            ds_abr = ds
        elif 'Control' in name:
            ds_ctrl = ds

    # Compute the monthly averages for control experiment and track changes in the abrupt experiment compared to those
    ctrl_monthly_av = ds_ctrl[var_name].groupby('time.month').mean(dim='time')
    dVAR = ds_abr[var_name].groupby('time.month') - ctrl_monthly_av

    return dVAR.squeeze()

def import_salb(col, model_name):
    ds_rsds_dict = import_data(col, model_name, 'rsds')
    ds_rsus_dict = import_data(col, model_name, 'rsus')

    for name, ds_rsds in ds_rsds_dict.items():
        ds_rsus = ds_rsus_dict[name]

        ds_rsds = xr.decode_cf(ds_rsds)
        ds_rsus = xr.decode_cf(ds_rsus)

        for coord in ds_rsus.coords:
            if coord not in ['lat', 'lon', 'plev', 'time']:
                ds_rsus = ds_rsus.drop(coord)

        for coord in ds_rsds.coords:
            if coord not in ['lat', 'lon', 'plev', 'time']:
                ds_rsds = ds_rsds.drop(coord)

        if 'abrupt' in name:
            salb_abr = ( ds_rsus['rsus'] / ds_rsds['rsds'] ) * 100
        elif 'Control' in name:
            salb_ctrl = ( ds_rsus['rsus'] / ds_rsds['rsds'] ) * 100

    ctrl_monthly_av = salb_ctrl.groupby('time.month').mean(dim='time')
    dsalb = salb_abr.groupby('time.month') - ctrl_monthly_av
    return dsalb.squeeze()

##################################
###### 2D and 3D averages ########
##################################

def compute_global2D(Y):
    # Computes globally averaged yearly values for dataarray Y

    # Global mean average is computed via the surface integral
    # iint f(lat,lon) cos(lat) dS / iint cos(lat) dS
    # So, first: construct help variable containing cosine effective weight values
    weight = np.cos(np.deg2rad(Y['lat'])) * xr.ones_like(Y['lon'])

    # Then compute averages (converting integrals to sums)
    Y_globalMean = (
        ( Y * weight ).sum(dim=['lat', 'lon']) /
        weight.sum(dim=['lat', 'lon'])
    ).squeeze()

    return Y_globalMean

def compute_global3D(Y, p_thickness):
    # Computes globally averaged yearly values for dataarray Y

    # For 3D variables, the tropopause needs to be masked out
    # p_tropopause = 30000 - 20000 cos(lat)
    p_tropopause = 30000 - 20000 * np.cos(np.deg2rad(Y['lat']))
    Y_masked = ( ( Y['plev'] > p_tropopause ) * Y )

    # Global mean average is computed via the surface integral
    # iint f(lat,lon) cos(lat) dS / iint cos(lat) dS
    # So, first: construct help variable containing cosine effective weight values
    latlon_weight = np.cos(np.deg2rad(Y['lat'])) * xr.ones_like(Y['lon'])
    p_weight = p_thickness
    weight = latlon_weight * p_weight

    # Then compute averages (converting integrals to sums)
    Y_globalMean = (
        ( Y_masked * weight ).sum(dim=['lat', 'lon', 'plev']) /
        weight.sum(dim=['lat', 'lon', 'plev'])
    ).squeeze()

    return Y_globalMean

def compute_global3D_fb(Y, p_thickness, kernel):
    # Computes globally averaged yearly values for dataarray Y

    # Global mean average is computed via the surface integral
    # iint f(lat,lon) cos(lat) dS / iint cos(lat) dS
    # So, first: construct help variable containing cosine effective weight values
    weight = np.cos(np.deg2rad(Y['lat'])) * xr.ones_like(Y['lon'])

    # Then compute averages (converting integrals to sums)
    Y_globalMean = (
        ( (p_thickness * kernel * Y.groupby('time.month')).sum(dim='plev', skipna = True) * weight ).sum(dim=['lat', 'lon']) /
        weight.sum(dim=['lat', 'lon'])
        ).groupby('time.year').mean(dim='time').squeeze()

    return Y_globalMean

def compute_2D_field_from_3D(Y, p_thickness, kernel):
    Y_field = (p_thickness * kernel * Y.groupby('time.month')).sum(dim='plev', skipna = True)
    Y_field_yearly = Y_field.groupby('time.year').mean(dim='time')
    Y_field_yearly = Y_field_yearly.compute()
    return Y_field_yearly

############################################
# COMPUTE 2D/3D FEEDBACKS AND GLOBAL MEANS #
############################################

def compute_feedback2D(kernel, dvar, fb_name, var_name):

    # Compute feedback 2Dfield per year
    try:
        fb_field = xr.open_dataarray("Data/fields/" + fb_name + "_field.nc")
        print("Found dataset " + fb_name + "_field -- skipping recomputation")
    except:
        fb_field = (kernel * dvar.groupby('time.month')).groupby('time.year').mean('time').compute()
        fb_field = fb_field.to_netcdf("Data/fields/" + fb_name + "_field.nc")
        fb_field = xr.open_dataarray("Data/fields/" + fb_name + "_field.nc")
        print("Computed " + fb_name + "_field")

    # Compute feedback global mean per yearly
    try:
        fb = xr.open_dataarray("Data/global/" + fb_name + ".nc")
        print("Found dataset " + fb_name + " -- skipping recomputation")
    except:
        fb = compute_global2D(fb_field)
        fb = fb.compute()
        fb.to_netcdf("Data/global/" + fb_name + ".nc")
        print("Computed " + fb_name)

    # Compute global mean for variable
    try:
        dvar_GM = xr.open_dataarray("Data/global/" + var_name + ".nc")
        print("Found dataset " + var_name + " -- skipping recomputation")
    except:
        dvar_GM = compute_global2D(dvar.groupby('time.year').mean('time'))
        dvar_GM = dvar_GM.compute()
        dvar_GM.to_netcdf("Data/global/" + var_name + ".nc")
        print("Computed " + var_name)

    return fb, dvar_GM

def compute_feedback3D(kernel, pthick, dvar, fb_name, var_name):

    # Make height integration (so a field is obtained)
    try:
        fb_field = xr.open_dataarray("Data/fields/" + fb_name + "_field.nc")
        print("Found dataset " + fb_name + "_field -- skipping recomputation")
    except:
        fb_field = compute_2D_field_from_3D(dvar, pthick['dp'], kernel)
        fb_field.to_netcdf("Data/fields/" + fb_name + "_field.nc")
        fb_field = xr.open_dataarray("Data/fields/" + fb_name + "_field.nc")
        print("Computed " + fb_name + "_field")

    try:
        fb = xr.open_dataarray("Data/global/" + fb_name + ".nc")
        print("Found dataset " + fb_name + " -- skipping recomputation")
    except:
        fb = compute_global2D(fb_field)
        fb = fb.compute()
        fb.to_netcdf("Data/global/" + fb_name + ".nc")
        print("Computed " + fb_name)

    return fb

##################################
### NORMALIZATION OF Q KERNELS ###
##################################

## Calculate the change in moisture per degree warming at constant relative humidity.
def calcsatspechum(ta, plev):
    # We only care about the monthly average
    t = ta.squeeze().groupby('time.month').mean(dim='time')
    p = plev.squeeze() * xr.ones_like(t)
    p = p/100 # needs to be in hPa

    # formulae from Buck (1982)
    es = (1.0007+(3.46e-6*p)) * 6.1121 * np.exp(17.502*(t-273.15) / (240.97+(t-273.15)));
    wsl = .622*es /(p-es) # Saturation mixing ratio wrt liquid water
    es = (1.0003+(4.18e-6*p)) * 6.1115 * np.exp(22.452*(t-273.15) / (272.55+(t-273.15)));
    wsi = .622*es/(p-es) # Saturation mixing ratio wrt ice

    # Below freezing we only care about ice, above only about liquid water.
    ws = wsl * (t >= 273.15) + wsi * (t < 273.15)

    qs = ws / (1 + ws) # Saturation specific humidity

    return qs

def comp_moisture_change(col, model_name, dta):
    # Obtain initial q1
    ds_dict = import_data(col, model_name, 'hus')
    for name, ds in ds_dict.items():
        if 'Control' in name:
            ds = xr.decode_cf(ds)
            for coord in ds.coords:
                if coord not in ['lat', 'lon', 'plev', 'time']:
                    ds = ds.drop(coord)
            q1 = ds['hus'].groupby('time.month').mean(dim='time')
            ds_q_ctrl = ds

    ds_dict_ta = import_data(col, model_name, 'ta')
    for name, ds in ds_dict_ta.items():
        ds = xr.decode_cf(ds)
        for coord in ds.coords:
            if coord not in ['lat', 'lon', 'plev', 'time']:
                ds = ds.drop(coord)
        if 'abrupt' in name:
            ds_ta_abr = ds
        elif 'Control' in name:
            ds_ta_ctrl = ds

    qs1 = ( calcsatspechum(ds_ta_ctrl['ta'].isel(plev=slice(0,17)), ds_q_ctrl['plev']) )
    qs2 = ( calcsatspechum(ds_ta_abr['ta'].isel(plev=slice(0,17)), ds_q_ctrl['plev']) )

    # Compute the change of qs2 and qs1
    dqsdt = (qs2 - qs1) / (dta.squeeze().groupby('time.month').mean(dim='time'))
    # Constant relative humidity
    rh = q1 / qs1

    dqdt = rh * dqsdt

    return dqdt

##############################
### COMBINATION FUNCTION  ####
##############################

def compute_feedback_timeseries(col, model_name):

    fb = {}
    #####
    # 1 # TEMPERATURE FEEDBACK
    #####

    ###
    ### Contribution of skin temperature
    ###

    dts = import_var(col,model_name, 'ts')

    # Read-in the kernel related to ts:
    ts_kernel = xr.open_dataset("kernels/ts.kernel.nc")
    ts_kernel = ts_kernel.drop('time')
    ts_kernel = ts_kernel.assign_coords({'month': ts_kernel.time + 1}).swap_dims({'time':'month'}) # Convert 'time' dim to a 'month' coordinate

    dLW_ts, dts_GM = compute_feedback2D(-ts_kernel['FLNT'], dts, 'dLW_ts', 'dts') # Minus sign since feedback contribution of LW has minus sign
    dLW_CS_ts, dts_GM = compute_feedback2D(-ts_kernel['FLNTC'], dts, 'dLW_CS_ts', 'dts')

    ###
    ### Contribution of atmospheric temperature
    ###

    dta = import_var(col, model_name, 'ta')

    # Read-in the kernel related to ta
    ta_kernel = xr.open_dataset("kernels/t.kernel.plev.nc")
    # Only keep the 'FLNT' variable
    for var in ta_kernel.data_vars:
        if var not in ['FLNT', 'FLNTC']:
            ta_kernel = ta_kernel.drop(var)

    ta_kernel = ta_kernel.drop('time').drop('lev_p') # Only keep the relevant coordinates (time will be coverted one line below)
    ta_kernel = ta_kernel.assign_coords({'month': ta_kernel.time + 1}).swap_dims({'time':'month'}) # Covert 'time' dims to a 'month' coordinate
    ta_kernel = ta_kernel.swap_dims({'ncl1' : 'plev'})

    # Read in some pressure weight computed along the kernels (functions as a weight to accurately average over elevation/pressure level)
    pdiff = xr.open_dataset("kernels/dp_plev.nc")/100
    pdiff = pdiff.drop('time')
    pdiff = pdiff.assign_coords({'month': pdiff.time + 1}).swap_dims({'time':'month'})

    ## Filter out the stratosphere
    # Filtering is done with a crude approximation of the (pressure)height of the tropopause:
    # p_tropopause = 30000 - 20000 cos(lat)
    p_tropopause = 30000 - 20000 * np.cos(np.deg2rad(dta['lat']))
    # Only use the plev values that are relevant (the first 17);
    # then mask out the values above the tropopause
    dta_masked = ( dta['plev'].isel(plev=slice(0,17)) > p_tropopause ) * dta

    dLW_ta = compute_feedback3D(-ta_kernel['FLNT'], pdiff, dta_masked, 'dLW_ta', 'dta')# Minus sign since feedback contribution of LW has minus sign
    dLW_CS_ta = compute_feedback3D(-ta_kernel['FLNTC'], pdiff, dta_masked, 'dLW_CS_ta', 'dta')

    fb['temp'] = (dLW_ts + dLW_ta)
    fb['temp-clearsky'] = (dLW_CS_ts + dLW_CS_ta)

    #####
    # 1A# PLANCK FEEDBACK CONTRIBUTION TO TEMPERATURE FEEDBACK
    #####

    # To compute the planck feedback we project the surface temperature (ts) into the height;
    # This mimics the values for atmospheric temperature (ta) that would happen if there were no lapse-rate
    dts3d = dts * xr.ones_like(dta)

    # then mask out the values above the tropopause
    dts3d_masked = ( dts3d['plev'].isel(plev=slice(0,17)) > p_tropopause ) * dts3d

    dLW_planck_atm = compute_feedback3D(-ta_kernel['FLNT'],pdiff, dts3d_masked, 'dLW_planck_atm', 'dts3D')
    dLW_planck = (dLW_planck_atm + dLW_ts)
    dLW_planck.to_netcdf("Data/global/dLW_planck.nc")

    dLW_CS_planck_atm = compute_feedback3D(-ta_kernel['FLNTC'],pdiff, dts3d_masked, 'dLW_CS_planck_atm', 'dts3D')
    dLW_CS_planck = (dLW_CS_planck_atm + dLW_CS_ts)
    dLW_CS_planck.to_netcdf("Data/global/dLW_CS_planck.nc")

    fb['planck'] = dLW_planck
    fb['planck-clearsky'] = dLW_CS_planck

    #####
    # 1B# LAPSE-RATE FEEDBACK CONTRIBUTION TO TEMPERATURE FEEDBACK
    #####

    dlr = dta - dts3d
    dlr_masked = ( dlr['plev'].isel(plev=slice(0,17)) > p_tropopause ) * dlr

    dLW_lr = compute_feedback3D(-ta_kernel['FLNT'], pdiff, dlr_masked, 'dLW_lr', 'dlr') # Minus sign since feedback contribution of LW has minus sign
    dLW_CS_lr = compute_feedback3D(-ta_kernel['FLNTC'], pdiff, dlr_masked, 'dLW_CS_lr', 'dlr')

    fb['LR'] = dLW_lr
    fb['LR-clearksy'] = dLW_CS_lr

    #####
    # 2 # ALBEDO FEEDBACK
    #####

    dsalb = import_salb(col, model_name)

    # Read-in the kernel related to albedo
    alb_kernel = xr.open_dataset("kernels/alb.kernel.nc")
    alb_kernel = alb_kernel.drop('time')
    alb_kernel = alb_kernel.assign_coords({'month': alb_kernel.time + 1}).swap_dims({'time':'month'}) # Convert 'time' dim to a 'month' coordinate

    dSW_alb, dsalb_GM = compute_feedback2D(alb_kernel['FSNT'], dsalb, 'dSW_alb', 'dsalb')
    dSW_CS_alb, dsalb_GM = compute_feedback2D(alb_kernel['FSNTC'], dsalb, 'dSW_CS_alb', 'dsalb')

    fb['albedo'] = dSW_alb
    fb['albedo-clearsky'] = dSW_CS_alb

    #####
    # 3 # WATER VAPOUR FEEDBACK
    #####

    dq = import_var(col, model_name, 'hus')

    # Load kernels
    q_kernel = xr.open_dataset("kernels/q.kernel.plev.nc")
    for var in q_kernel.data_vars:
        if var not in ['FLNT', 'FSNT', 'FLNTC', 'FSNTC']:
            q_kernel = q_kernel.drop(var)

    q_kernel = q_kernel.drop('time').drop('lev_p') # Only keep the relevant coordinates (time will be coverted one line below)
    q_kernel = q_kernel.assign_coords({'month': q_kernel.time + 1}).swap_dims({'time':'month'}) # Covert 'time' dims to a 'month' coordinate

    # Then compute the change in moisture at constant relative humidity (used for normalizing the kernel)
    # Here we only use the monthly averages, as it is too computationally heavy otherwise;
    # this shouldn't be a problem, as we are only interested in a good estimation for the change in moisture,
    # for which this forms an approximation anyways.
    try:
        q_LW_kernel = xr.open_dataarray("kernels/CESM2/q_LW_kernel.nc")
        q_SW_kernel = xr.open_dataarray("kernels/CESM2/q_SW_kernel.nc")
        q_LW_CS_kernel = xr.open_dataarray("kernels/CESM2/q_LW_CS_kernel.nc")
        q_SW_CS_kernel = xr.open_dataarray("kernels/CESM2/q_SW_CS_kernel.nc")
    except:
        try:
            dqdt = xr.open_dataarray("kernels/CESM2/dqdt.nc")
        except:
            dqdt = comp_moisture_change(col, model_name, dta)
            dqdt = dqdt.compute()
            dqdt.to_netcdf("kernels/CESM2/dqdt.nc")

        q_LW_kernel = q_kernel['FLNT']/dqdt
        q_SW_kernel = q_kernel['FSNT']/dqdt
        q_LW_CS_kernel = q_kernel['FLNTC']/dqdt
        q_SW_CS_kernel = q_kernel['FSNTC']/dqdt

        q_LW_kernel = q_LW_kernel.compute()
        q_SW_kernel = q_SW_kernel.compute()
        q_LW_CS_kernel = q_LW_CS_kernel.compute()
        q_SW_CS_kernel = q_SW_CS_kernel.compute()

        q_LW_kernel.to_netcdf("kernels/CESM2/q_LW_kernel.nc")
        q_SW_kernel.to_netcdf("kernels/CESM2/q_SW_kernel.nc")
        q_LW_CS_kernel.to_netcdf("kernels/CESM2/q_LW_CS_kernel.nc")
        q_SW_CS_kernel.to_netcdf("kernels/CESM2/q_SW_CS_kernel.nc")

    dq_masked = ( dq['plev'].isel(plev=slice(0,17)) > p_tropopause ) * dq
    dLW_q = compute_feedback3D(-q_LW_kernel, pdiff, dq_masked, 'dLW_q', 'dq') # Minus sign since feedback contribution of LW has minus sign
    dSW_q = compute_feedback3D(q_SW_kernel, pdiff, dq_masked, 'dSW_q', 'dq')
    dLW_CS_q = compute_feedback3D(-q_LW_CS_kernel, pdiff, dq_masked, 'dLW_CS_q', 'dq')
    dSW_CS_q = compute_feedback3D(q_SW_CS_kernel, pdiff, dq_masked, 'dSW_CS_q', 'dq')

    fb['WV-LW'] = dLW_q
    fb['WV-SW'] = dSW_q
    fb['WV-LW-clearsky'] = dLW_CS_q
    fb['WV-SW-clearsky'] = dSW_CS_q

    return fb

def compute_GMST_imbalance(col, model_name):

    dtas = import_var(col, model_name, 'tas')
    drsdt = import_var(col, model_name, 'rsdt')
    drsut = import_var(col, model_name, 'rsut')
    drlut = import_var(col, model_name, 'rlut')
    drsut_cs = import_var(col, model_name, 'rsutcs')
    drlut_cs = import_var(col, model_name, 'rlutcs')

    dIMB = drsdt - drsut - drlut
    dIMB_CS = drsdt - drsut_cs - drlut_cs

    ###
    # near-surface atmosphere temperature 'tas'
    ###

    # Compute 2Dfield per year
    try:
        dtas_field = xr.open_dataarray("Data/fields/dtas_field.nc")
        print("Found dataset dtas_field -- skipping recomputation")
    except:
        dtas_field = dtas.groupby('time.year').mean('time').compute()
        dtas_field.to_netcdf("Data/fields/dtas_field.nc")
        dtas_field = xr.open_dataarray("Data/fields/dtas_field.nc")
        print("Computed dtas_field")

    # Compute global mean per yearl
    try:
        dGMST = xr.open_dataarray("Data/global/dGMST.nc")
        print("Found dataset dGMST -- skipping recomputation")
    except:
        dGMST = compute_global2D(dtas_field)
        dGMST = dGMST.compute()
        dGMST.to_netcdf("Data/global/dGMST.nc")
        print("Computed dGMST")

    ###
    # Radiative imbalance (full sky)
    ###

    try:
        dIMB_field = xr.open_dataarray("Data/fields/dIMB_field.nc")
        print("Found dataset dIMB_field -- skipping recomputation")
    except:
        dIMB_field = dIMB.groupby('time.year').mean('time').compute()
        dIMB_field.to_netcdf("Data/fields/dIMB_field.nc")
        dIMB_field = xr.open_dataarray("Data/fields/dIMB_field.nc")
        print("Computed dIMB_field")

    try:
        dIMB = xr.open_dataarray("Data/global/dIMB.nc")
        print("Found dataset dIMB -- skipping recomputation")
    except:
        dIMB = compute_global2D(dIMB_field)
        dIMB = dIMB.compute()
        dIMB.to_netcdf("Data/global/dIMB.nc")
        print("Computed dIMB")

    ###
    # Radiative imbalance (clear sky)
    ###

    try:
        dIMB_CS_field = xr.open_dataarray("Data/fields/dIMB_CS_field.nc")
        print("Found dataset dIMB_CS_field -- skipping recomputation")
    except:
        dIMB_CS_field = dIMB_CS.groupby('time.year').mean('time').compute()
        dIMB_CS_field.to_netcdf("Data/fields/dIMB_CS_field.nc")
        dIMB_CS_field = xr.open_dataarray("Data/fields/dIMB_CS_field.nc")
        print("Computed dIMB_CS_field")

    try:
        dIMB_CS = xr.open_dataarray("Data/global/dIMB_CS.nc")
        print("Found dataset dIMB_CS -- skipping recomputation")
    except:
        dIMB_CS = compute_global2D(dIMB_CS_field)
        dIMB_CS = dIMB_CS.compute()
        dIMB_CS.to_netcdf("Data/global/dIMB_CS.nc")
        print("Computed dIMB_CS")

    return dGMST, dIMB, dIMB_CS

1. Python - CMIP Feedback Computations/CESM2 abrupt4xCO2/python_codes/computations_averages.py


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('catalog', '0009_auto_20150706_0024'),
    ]

    operations = [
        migrations.AlterField(
            model_name='address',
            name='link',
            field=models.URLField(db_index=True, verbose_name='Посилання на сайт забудовника', blank=True, max_length=1000),
            preserve_default=True,
        ),
    ]


from django.conf.urls import patterns, include, url
from django.contrib import admin

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

    url(r'^admin/', include(admin.site.urls)),
    url(r'^$', 'adverts.views.index', name='index'),
    url(r'register/$', 'adverts.views.register'),
    url(r'login/$', 'adverts.views.user_login'),
    url(r'cache/$', 'adverts.views.cache_me'),
    url(r'search/$', 'adverts.views.search'),
)


#!/usr/bin/python
"""
Script to initialise CROP database.

"""

import sys

from crop.constants import SQL_CONNECTION_STRING, SQL_DBNAME
from crop.db import create_database

def confirm(question):
    """
    Ask user to enter Y or N (case-insensitive).
    :return: True if the answer is Y.

    """
    answer = ""

    while answer not in ["y", "n"]:
        answer = input("{0} [Y/N]? ".format(question)).lower()

    return answer == "y"

if __name__ == "__main__":

    if confirm("Create DB?"):
        create_database(SQL_CONNECTION_STRING, SQL_DBNAME)

    print("Finished.")


from django.forms import formset_factory
from django.utils import timezone

from .forms import CreatePowerForm, make_enhancement_form, make_drawback_form, make_parameter_form, \
    EditPowerAdditionalForm
from .models import Enhancement_Instance, Drawback_Instance, Power, DICE_SYSTEM, Enhancement, Drawback, \
    Power_Param, \
    Parameter_Value, Base_Power_System, Power_Full, CREATION_REASON

def get_create_power_context_from_base(base_power):
    system = Base_Power_System.objects.filter(dice_system=DICE_SYSTEM[1][0]).get(base_power=base_power)
    primary_form = CreatePowerForm(base_power, initial={'system': system.system_text})
    enhancement_forms = []
    for enhancement in Enhancement.objects.filter(pk__in=base_power.enhancements.all()):
        enhancement_forms.append(formset_factory(make_enhancement_form(enhancement), extra = 1)())
    drawback_forms = []
    for drawback in Drawback.objects.filter(pk__in=base_power.drawbacks.all()):
        drawback_forms.append(formset_factory(make_drawback_form(drawback), extra = 1)())
    parameter_forms = []
    for parameter in Power_Param.objects.filter(relevant_base_power=base_power).all():
        parameter_forms.append(formset_factory(make_parameter_form(parameter))())
    system = Base_Power_System.objects.filter(dice_system=DICE_SYSTEM[1][0]).get(base_power=base_power.slug)
    context = {
        'base_power': base_power,
        'power_system': system,
        'form': primary_form,
        'parameters': parameter_forms,
        'enhancements': enhancement_forms,
        'drawbacks': drawback_forms,
    }
    return context

def get_create_power_context_from_power(power):
    primary_form = CreatePowerForm(power.base,
                                   initial={'system': power.system,
                                            'description': power.description,
                                            'flavor': power.flavor_text,
                                            'activation_style': power.activation_style,
                                            'power_name': power.name})
    enhancement_forms = get_enhancement_formsets_from_power(power)
    drawback_forms = get_drawback_formsets_from_power(power)
    parameter_forms = []
    for parameter_value in Parameter_Value.objects.filter(relevant_power=power).all():
        init= [{'level_picker': parameter_value.value}]
        parameter_forms.append(formset_factory(make_parameter_form(parameter_value.relevant_power_param), extra = 0)(initial = init))
    system = Base_Power_System.objects.filter(dice_system=DICE_SYSTEM[1][0]).get(base_power=power.base.slug)
    context = {
        'base_power': power.base,
        'power_system': system,
        'form': primary_form,
        'parameters': parameter_forms,
        'enhancements': enhancement_forms,
        'drawbacks': drawback_forms,
    }
    return context

def get_edit_power_context_from_power(og_power, power_full):
    context = get_create_power_context_from_power(og_power)
    context["og_power"] = og_power
    context["edit_form"] = EditPowerAdditionalForm()
    return context

def get_enhancement_formsets_from_power(power):
    enhancement_forms = []
    enhancement_instances = Enhancement_Instance.objects.filter(relevant_power=power).all()
    for base_enhancement in Enhancement.objects.filter(pk__in=power.base.enhancements.all()):
        instances_of_this_enhancement = set(
            x for x in enhancement_instances if (x.relevant_enhancement == base_enhancement))
        init = []
        num_extra = 0
        for enhancement_instance in instances_of_this_enhancement:
            init.append({
                'is_selected': True,
                'detail_text': enhancement_instance.detail,
            })
        if base_enhancement.multiplicity_allowed or not instances_of_this_enhancement:
            num_extra = 1
        new_form = formset_factory(make_enhancement_form(base_enhancement), extra=num_extra, max_num=4)(initial=init)
        enhancement_forms.append(new_form)
    return enhancement_forms

def get_drawback_formsets_from_power(power):
    drawback_forms = []
    drawback_instances = Drawback_Instance.objects.filter(relevant_power=power).all()
    for base_drawback in Drawback.objects.filter(pk__in=power.base.drawbacks.all()):
        instances_of_this_drawback = set(
            x for x in drawback_instances if (x.relevant_drawback == base_drawback))
        init = []
        num_extra = 0
        for drawback_instance in instances_of_this_drawback:
            init.append({
                'is_selected': True,
                'detail_text': drawback_instance.detail,
            })
        if base_drawback.multiplicity_allowed or not instances_of_this_drawback:
            num_extra = 1
        new_form = formset_factory(make_drawback_form(base_drawback), extra=num_extra, max_num=4)(initial=init)
        drawback_forms.append(new_form)
    return drawback_forms

def get_enhancement_instances(post_data, enhancements, new_power):
    instances = []
    for enhancement in enhancements:
        if enhancement.slug + "-e-is_selected" in post_data:
            detail_texts = []
            if enhancement.slug + "-e-detail_text" in post_data:
                detail_texts = post_data.getlist(enhancement.slug + "-e-detail_text")
            for on in post_data.getlist(enhancement.slug + "-e-is_selected"):
                if detail_texts:
                    new_detail_text = detail_texts.pop(0)
                else:
                    new_detail_text = ""
                instances.append(Enhancement_Instance(relevant_enhancement=enhancement,
                                     relevant_power=new_power,
                                     detail=new_detail_text))
    return instances

def get_drawback_instances(post_data, drawbacks, new_power):
    instances = []
    for drawback in drawbacks:
        if drawback.slug + "-d-is_selected" in post_data:
            detail_texts = []
            if drawback.slug + "-d-detail_text" in post_data:
                detail_texts = post_data.getlist(drawback.slug + "-d-detail_text")
            for on in post_data.getlist(drawback.slug + "-d-is_selected"):
                if detail_texts:
                    new_detail_text = detail_texts.pop(0)
                else:
                    new_detail_text = ""
                instances.append(Drawback_Instance(relevant_drawback=drawback,
                                     relevant_power=new_power,
                                     detail=new_detail_text))
    return instances

def create_new_full_power(power_form, base):
    return Power_Full(name=power_form.cleaned_data['power_name'],
                  dice_system=DICE_SYSTEM[1][0],
                  base=base,
                  pub_date=timezone.now())

def get_power_from_form(power_form, base):
    return Power(name=power_form.cleaned_data['power_name'],
                  flavor_text=power_form.cleaned_data['flavor'],
                  description=power_form.cleaned_data['description'],
                  system=power_form.cleaned_data['system'],
                  activation_style=power_form.cleaned_data['activation_style'],
                  base=base,
                  dice_system=DICE_SYSTEM[1][0],
                  pub_date=timezone.now())

def create_power_for_new_edit(base_power, request, power_full):
    power_form = CreatePowerForm(base_power, request.POST)
    additional_form = EditPowerAdditionalForm(request.POST)
    if power_form.is_valid() and additional_form.is_valid():
        return create_power_from_post_and_base(base_power, request, power_full)

def create_new_power_and_parent(base_power, request):
    form = CreatePowerForm(base_power, request.POST)
    if form.is_valid():
        power_full = create_new_full_power(power_form=form, base=base_power)
        if request.user.id:
            power_full.owner = request.user
        power_full.save()
        return create_power_from_post_and_base(base_power, request, power_full)
    else:
        print(form.errors)
        return None

def create_power_from_post_and_base(base_power, request, power_full):
    form = CreatePowerForm(base_power, request.POST)
    if form.is_valid():
        power = get_power_from_form(power_form=form, base=base_power)
        additional_form = EditPowerAdditionalForm(request.POST)
        if additional_form.is_valid():
            power.creation_reason = additional_form.cleaned_data['edit_reason']
            power.creation_reason_expanded_text = additional_form.cleaned_data['edit_explanation']
        else:
            power.creation_reason  = CREATION_REASON[0][0]
        if request.user.id:
            power.created_by = request.user
        power.parent_power = power_full
        power.save()
        enhancement_instances = get_enhancement_instances(post_data=request.POST,
                                                          enhancements=Enhancement.objects.filter(
                                                              pk__in=base_power.enhancements.all()),
                                                          new_power=power)
        for enhancement_instance in enhancement_instances:
            enhancement_instance.save()
        drawback_instances = get_drawback_instances(post_data=request.POST,
                                                    drawbacks=Drawback.objects.filter(
                                                        pk__in=base_power.drawbacks.all()),
                                                    new_power=power)
        for drawback_instance in drawback_instances:
            drawback_instance.save()
        power.save()
        for power_param in Power_Param.objects.filter(relevant_base_power=base_power):
            param_val = Parameter_Value(relevant_power=power,
                                        relevant_power_param=power_param,
                                        value=request.POST[power_param.relevant_parameter.slug])
            param_val.save()
        return power
    else:
        print(form.errors)
        return None


# -*- coding: utf-8 -*-
import template
import ast
import inspect

class DotDict(dict):
  def __setattr__(self, name, value):
    self[name] = value

  def __getattr__(self, name):
    return self.get(name, None)

class ActionParams(object):

  def __init__(self, setting, action_klass, preset):

    method = type.__getattribute__(action_klass, 'do_' + setting.method_name)
    self._argspec = inspect.getargspec(method)
    self._preset = preset
    self._raw_params = setting.params

    self.params = None
    self.assert_list = None
    self.assertex_list = None

  def expand(self, global_env):
    self.params = self._preset.apply(self._raw_params)

    for key, value in self.params.items():
      self._expand_params(self.params, key, value, global_env)

    #
    # assert 設定の取得
    #
    self.assert_list = self.params.get('assert', [])
    if isinstance(self.assert_list, basestring):
      self.assert_list = [self.assert_list]
    self.assertex_list = self.params.get('assertex', [])
    if isinstance(self.assertex_list, basestring):
      self.assertex_list = [self.assertex_list]
    self.params.pop('assert', None)
    self.params.pop('assertex', None)

    #
    # params 設定の取得
    #
    argspec = self._argspec
    # instance method は "self" が付いてるので除く
    args = argspec.args[1:]
    if argspec.defaults:
      no_default_key_count = len(args) - len(argspec.defaults)
      required_keys = args[:no_default_key_count]
      optional_params = dict(zip(args[no_default_key_count:], argspec.defaults))
    else:
      required_keys = args
      optional_params = {}
    allow_any_params = bool(argspec.keywords)
    if "scenario" in args:
      self.params["scenario"] = global_env['scenario']
    if "global_env" in args:
      self.params["global_env"] = global_env

    exists_keys = self.params.keys()
    for required_param in required_keys:
      if required_param not in self.params:
        raise Exception("required: " + required_param)
      exists_keys.remove(required_param)

    for optional_param, value in optional_params.items():
      if optional_param in self.params:
        exists_keys.remove(optional_param)
      else:
        self.params[optional_param] = value

    if not allow_any_params and exists_keys:
      raise Exception("unknown param: " + exists_keys[0])
    self.params = DotDict(self.params)

    return self.params

  def _expand_params(self, parent, key, value, global_env):
    # 文字列の場合はテンプレートとして扱い、
    # 辞書、リストの場合はさらにその中の要素を展開する。
    # ここで指定していない数値等の型はそのまま
    if isinstance(value, basestring):
      new_value = template.expand(value, global_env)
      if isinstance(key, basestring) and key.startswith('+'):
        original_key = key.lstrip('+')
        parent[original_key] = ast.literal_eval(new_value)
        del parent[key]
      else:
        parent[key] = new_value
    elif isinstance(value, dict):
      for k, v in value.items():
        self._expand_params(value, k, v, global_env)
    elif isinstance(value, list):
      for k, v in enumerate(value):
        self._expand_params(value, k, v, global_env)


# Write an algorithm to determine if a number is "happy".
# A happy number is a number defined by the following process: Starting with any positive
# integer, replace the number by the sum of the squares of its digits, and repeat the
# process until the number equals 1 (where it will stay), or it loops endlessly in a cycle
# which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

class Solution:
    def isHappy(self, n: int) -> bool:
        dp = set()
        return self.helper(n, dp)

    def helper(self, n: int, dp) -> bool:
        if n in dp:
            return False
        dp.add(n)

        result = 0
        while n != 0:
            result += (n%10)**2
            n //= 10
        if result == 1:
            return True
        else:
            return self.helper(result, dp)


#!/usr/bin/env python
# -*- coding=utf-8 -*-
# Author: kaname
# QQ: 1394041054
# Update:20180622

""" C4d analyzer """
# RUN:
    # 1. From C4Dloader.py to loading RBAnalzer.py to do it.
    # 2. AnalyzeC4d.py loading C4Dloader.py to do it.

import os
import sys,re
import subprocess
import string
import logging
import time
import shutil
from C4d import C4d
from C4dLoader import C4dLoader
from C4dPluginManager import C4dPlugin, C4dPluginMgr
from CommonUtil import RBCommon as CLASS_COMMON_UTIL

class AnalyzeC4d(C4d):
    def __init__(self, **paramDict):
        C4d.__init__(self, **paramDict)
        self.format_log('AnalyzeC4d.init', 'start')

        self.G_TIPS_TXT_NODE=os.path.join(self.G_WORK_RENDER_TASK_CFG, 'tips.json').replace('\\','/')

        for key, value in list(self.__dict__.items()):
            self.G_DEBUG_LOG.info(key + '=' + str(value))

        self.format_log('done','end')
    '''
    def RB_MAP_DRIVE(self):#2.chongxie
        #self.format_log('[映射盘符]','[start]'.decode('utf-8').encode('gbk'))
        self.G_DEBUG_LOG.info('[c4d.RB_MAP_DRIVE.start.....]')

        if self.G_RENDER_OS != '0':
            #delete all mappings
            CLASS_COMMON_UTIL.del_net_use()
            CLASS_COMMON_UTIL.del_subst()

            #net use
            b_flag = False
            if self.G_CG_NAME == 'C4d':
                map_root = os.path.basename(self.G_INPUT_PROJECT_PATH)
                print(map_root + '@KANADAmmmmmmm')
                map_dict = os.path.join(self.G_INPUT_PROJECT_PATH)
                print(map_root + '@KANADAnnnnnnn')
                map_cmd = 'net use %s: "%s"' % (map_root, map_dict)
                CLASS_COMMON_UTIL.cmd_python3(map_cmd,my_log=self.G_DEBUG_LOG)

            if not b_flag:
                map_cmd_b = 'net use B: "%s"' % (os.path.normpath(self.G_PLUGIN_PATH))
                CLASS_COMMON_UTIL.cmd(map_cmd_b,my_log=self.G_DEBUG_LOG,try_count=3)

        self.G_DEBUG_LOG.info('[c4d.RB_MAP_DRIVE.end.....]')
        self.format_log('done','end')
    '''

    def RB_CONFIG(self):

        self.G_DEBUG_LOG.info('[c4d.analyze.配置插件开始]')
        self.G_DEBUG_LOG.info('[c4d.analyze.plugin.config.start......]')

        self.plugin_config()

        self.G_DEBUG_LOG.info('[c4d.analyze.配置插件完成]')
        self.G_DEBUG_LOG.info('[c4d.analyze.plugin.config.end......]')

    def RB_RENDER(self):
        self.G_DEBUG_LOG.info('[c4d.RBanalyse.start.....]')

        cg_ver = self.G_CG_VERSION
        task_id = self.G_TASK_ID
        cg_file = self.G_INPUT_CG_FILE
        task_json = self.G_TASK_JSON
        asset_json = self.G_ASSET_JSON
        tips_json = self.G_TIPS_TXT_NODE
        auto_commit = self.G_AUTO_COMMIT

        c4d_loader = C4dLoader(cg_ver, task_id, cg_file, task_json, asset_json, tips_json, auto_commit)
        c4d_loader.execute()

        self.G_DEBUG_LOG.info('[c4d.RBanalyse.end.....]')


# -*- coding: utf-8 -*-
import os
import pymol
import shutil
import json

def __init_plugin__(app=None):
    from pymol.plugins import addmenuitemqt
    addmenuitemqt('Enlighten', run_plugin_gui)

class EnlightenForm(pymol.Qt.QtWidgets.QDialog):

    def __init__(self):
        super(EnlightenForm, self).__init__()
        self.data = {
            'ligand_name': 'NaN',
            'ligand_charge': '0',
            'ph': '7.0',
            'sphere_size': '20',
            'output_location': os.getcwd(),
            'ENLIGHTEN': os.environ.get('ENLIGHTEN', None),
            'AMBERHOME': os.environ.get('AMBERHOME', None),
        }

    def closeEvent(self, event):
        if getattr(self, 'advanced_options_form', None):
            self.advanced_options_form.close()

def run_plugin_gui():
    dialog = EnlightenForm()
    ui_file = os.path.join(os.path.dirname(__file__), 'ui_form.ui')
    form = pymol.Qt.utils.loadUi(ui_file, dialog)

    if check_path_data_set(form):
        environ_popup_window(form)

    if check_path_data_set(form):
        return

    form.pymolObjectRadio.toggled.connect(lambda: update_view(form))
    bind_file_dialog(form.pdbFileEdit, form.pdbFileBrowseButton)
    bind_directory_dialog(form.outputEdit, form.outputBrowseButton)

    form.outputEdit.textChanged.connect(lambda: update_form_data(
        form))
    form.ligandChargeEdit.textChanged.connect(lambda: update_form_data(
        form))
    form.ligandNameEdit.textChanged.connect(lambda: update_form_data(
        form))

    form.runPrepButton.clicked.connect(lambda: run_prep(form))
    form.websiteButton.clicked.connect(open_enlighten_website)
    test_function(form)
    form.AdvancedOptionsButton.clicked.connect(
        lambda: advanced_popup_window(form))

    initialize_view(form)

    dialog.show()

def update_form_data(form):
    form.data['output_location'] = form.outputEdit.text()
    form.data['ligand_name'] = form.ligandNameEdit.text()
    form.data['ligand_charge'] = form.ligandChargeEdit.text()

def check_path_data_set(form):
    return not form.data['ENLIGHTEN'] or not form.data['AMBERHOME']

def initialize_view(form):
    form.pymolObjectRadio.setChecked(True)
    objects = pymol.cmd.get_names('objects')
    form.pymolObjectCombo.addItems(objects)
    form.pymolObjectCombo.setCurrentIndex(len(objects) - 1)

    form.outputEdit.setText(form.data['output_location'])
    form.ligandChargeEdit.setValidator(pymol.Qt.QtGui.QIntValidator())
    form.ligandChargeEdit.setText(form.data['ligand_charge'])

def display_home_directories(advanced_form, form):
    advanced_form.enlightenEdit.setText(form.data['ENLIGHTEN'] or
                                        "Set path to Enlighten")
    advanced_form.amberEdit.setText(form.data['AMBERHOME'] or
                                    "Set path to Amber")

def update_view(form):
    PDB_FILE_WIDGETS = ('pdbFileLabel', 'pdbFileEdit', 'pdbFileBrowseButton')
    PYMOL_OBJECT_WIDGETS = ('pymolObjectLabel', 'pymolObjectCombo')
    if form.pdbFileRadio.isChecked():
        show_widgets(form, PDB_FILE_WIDGETS)
        hide_widgets(form, PYMOL_OBJECT_WIDGETS)
    else:
        show_widgets(form, PYMOL_OBJECT_WIDGETS)
        hide_widgets(form, PDB_FILE_WIDGETS)

def run_prep(form):
    import threads

    if validate_main(form):
        return

    if form.pdbFileRadio.isChecked():
        pdb_file_path = form.pdbFileEdit.text()
        pdb_folder_name = os.path.splitext(os.path.basename(pdb_file_path))[0]
        pdb_directory_path = os.path.dirname(pdb_file_path)
        output_location = form.data['output_location']

        # pdb_file_path already validated to be a file in validate_main
        if pdb_directory_path != output_location:
            shutil.copy(pdb_file_path, output_location)

    else:
        pdb_file_path = write_object_to_pdb(form.data['output_location'],
                                       form.pymolObjectCombo.currentText())
        pdb_folder_name = form.pymolObjectCombo.currentText()
    pdb_file = os.path.basename(pdb_file_path)

    pdb_folder = os.path.join(form.data['output_location'], pdb_folder_name)

    if os.path.isdir(pdb_folder):
        if delete_pdb_pop_up(form, pdb_folder_name):
            delete_pdb_folder(pdb_folder)
        else:
            print("exiting prep")
            return

    ligand_name = form.data['ligand_name']
    ligand_charge = form.data['ligand_charge']
    enlighten = form.data['ENLIGHTEN']
    amberhome = form.data['AMBERHOME']
    os.chdir(form.data['output_location'])
    os.environ.update({'AMBERHOME': amberhome})
    params_filename = "params.json"
    dump_parameters(form.data, params_filename)
    prepThread = threads.SubprocessThread("{}/prep.py {} {} {} {}"
                                          .format(enlighten, pdb_file,
                                                  ligand_name, ligand_charge,
                                                  params_filename))

    def prep_done():
        form.runPrepButton.setText("Run PREP")
        form.runPrepButton.setEnabled(True)
        if prepThread.error:
            error_message(form,
                          "The following errors were encountered:\n" +
                          prepThread.error)
        else:
            info_message(form, prepThread.output)
    prepThread.finished.connect(prep_done)

    form.runPrepButton.setText("Running...")
    form.runPrepButton.setEnabled(False)
    prepThread.start()

def test_function(form):
    print(form.data)

def dump_parameters(data, filename):
    with open(filename, "w") as f:
        json.dump(get_parameters_dictionary(data), f, indent=4)

def get_parameters_dictionary(data):
    return {
        'antechamber': {
            'ligand': data['ligand_name'],
            'charge': float(data['ligand_charge']),
        },
        'propka': {
            'ph': float(data['ph']),
        },
        'tleap': {
            'solvent_radius': float(data['sphere_size'])
        }
    }

def delete_pdb_pop_up(form, pdb_folder):
    QMessageBox = pymol.Qt.QtWidgets.QMessageBox
    delete_pdb_verification = QMessageBox.question(
        form,
        'Warning',
        "A folder named {0} already exists. "
        "Continuing will the delete folder, are you "
        "sure you want to continue?".format(pdb_folder),
        QMessageBox.Yes | QMessageBox.No,
        QMessageBox.No
    )
    return delete_pdb_verification == QMessageBox.Yes

def delete_pdb_folder(output_path):
    if os.path.isdir(output_path):
        shutil.rmtree(output_path)
        print('Deleting folder at: ' + output_path)
    else:
        print("Folder no longer exists")

def write_object_to_pdb(output_location, object_name):
    filename = os.path.join(output_location, object_name + '.pdb')
    pymol.cmd.save(filename, '({})'.format(object_name))
    return filename

def open_enlighten_website():
    import webbrowser
    webbrowser.open_new("https://github.com/vanderkamp/enlighten2/")

def validate_main(form):
    return validate_fields(form,
                           [pdb_validator, output_validator, ligand_validator])

def validate_fields(form, validators):
    results = [validator(form) for validator in validators]
    errors = [result for result in results if result is not None]
    if errors:
        error_message(form,
                      "The following errors were encountered:\n"
                      "{}".format("\n".join(errors)))
    return errors

def pdb_validator(form):
    if not form.pdbFileRadio.isChecked():
        return None
    if not os.path.isfile(form.pdbFileEdit.text()):
        return "PDB file not found"
    return None

def enlighten_validator(form):
    enlighten_path = form.enlightenEdit.text()
    if not os.path.isdir(enlighten_path):
        return "Wrong Enlighten path"
    if not os.path.isfile(os.path.join(enlighten_path, 'prep.py')):
        return "prep.py not found in {}".format(enlighten_path)
    return None

def amber_validator(form):
    amber_bin_path = os.path.join(form.amberEdit.text(), 'bin')
    if not os.path.isdir(amber_bin_path):
        return "Wrong AMBER path"
    for filename in ('antechamber', 'pdb4amber', 'reduce'):
        if not os.path.isfile(os.path.join(amber_bin_path, filename)):
            return "{} not found in {}".format(filename, amber_bin_path)
    return None

def output_validator(form):
    output_path = form.outputEdit.text()
    if not os.path.isdir(output_path):
        return "directory {} does not exist".format(output_path)
    return None

def ligand_validator(form):
    if not form.ligandNameEdit.text():
        return "Ligand name not provided"
    return None

def info_message(form, text):
    pymol.Qt.QtWidgets.QMessageBox.information(form, "Enlighten", text)

def error_message(form, text):
    pymol.Qt.QtWidgets.QMessageBox.critical(form, "Enlighten", text)

def show_widgets(form, widgets):
    for widget in widgets:
        getattr(form, widget).show()

def hide_widgets(form, widgets):
    for widget in widgets:
        getattr(form, widget).hide()

def bind_file_dialog(lineEdit, browseButton):
    browseButton.clicked.connect(lambda: assign_filename(lineEdit))

def bind_directory_dialog(lineEdit, browseButton):
    browseButton.clicked.connect(lambda: assign_directory(lineEdit))

def assign_filename(lineEdit):
    result = pymol.Qt.QtWidgets.QFileDialog.getOpenFileName()[0]
    if result:
        lineEdit.setText(result)

def assign_directory(lineEdit):
    result = pymol.Qt.QtWidgets.QFileDialog.getExistingDirectory()
    if result:
        lineEdit.setText(result)

class ExtOptionsDialog(pymol.Qt.QtWidgets.QDialog):

    def __init__(self, main_form):
        super(ExtOptionsDialog, self).__init__()
        self.main_form = main_form

    def closeEvent(self, event):
        self.main_form.AdvancedOptionsButton.setEnabled(True)
        self.main_form.advanced_options_form = None

def advanced_popup_window(form):
    advanced_dialog = ExtOptionsDialog(form)
    adv_op_ui_file = os.path.join(os.path.dirname(__file__), 'ui_advoptions.ui')
    advanced_form = pymol.Qt.utils.loadUi(adv_op_ui_file, advanced_dialog)

    form.AdvancedOptionsButton.setEnabled(False)

    def on_slider_moved(value):
        advanced_form.SphereSizeValue.setText(str(value))

    advanced_form.SphereSizeSlider.sliderMoved.connect(on_slider_moved)

    def on_sphere_size_text_changed():
        advanced_form.SphereSizeSlider.setValue(int(
            advanced_form.SphereSizeValue.text()))

    advanced_form.SphereSizeValue.textChanged.connect(on_sphere_size_text_changed)

    bind_directory_dialog(advanced_form.enlightenEdit, advanced_form.enlightenBrowseButton)
    bind_directory_dialog(advanced_form.amberEdit, advanced_form.amberBrowseButton)

    advanced_form.SphereSizeSlider.setMinimum(10)
    advanced_form.SphereSizeSlider.setMaximum(60)
    #set variables only on okay
    advanced_form.SphereSizeSlider.setValue(int(form.data['sphere_size']))
    advanced_form.SphereSizeValue.setText(str(form.data['sphere_size']))

    advanced_form.phEdit.setText(form.data['ph'])
    ph_validator = pymol.Qt.QtGui.QDoubleValidator(5.0, 14.0, 1, advanced_form.phEdit)
    advanced_form.phEdit.setValidator(ph_validator)

    advanced_form.okButton.clicked.connect(lambda: adv_op_popup_ok_click(
                                                     form, advanced_form))

    display_home_directories(advanced_form, form)
    advanced_dialog.show()
    form.advanced_options_form = advanced_form

def set_advanced_option_variables(form, sphere_value, ph_value):
    form.data['sphere_size'] = str(sphere_value)
    form.data['ph'] = str(ph_value)

def environ_popup_window(form):
    set_environmental_variables = pymol.Qt.QtWidgets.QDialog()
    set_environ_ui_file = os.path.join(os.path.dirname(__file__),
                                   'ui_set_environ.ui')
    env_window = pymol.Qt.utils.loadUi(set_environ_ui_file,
                                                set_environmental_variables)

    bind_directory_dialog(env_window.enlightenEdit,
                          env_window.enlightenBrowseButton)
    bind_directory_dialog(env_window.amberEdit, env_window.amberBrowseButton)

    env_window.setEnvironLabel.setText("Environmental variables not found: "
                                       "Please set the location of your Amber and "
                                       "Enlighten installation directories")

    display_home_directories(env_window, form)

    env_window.okButton.clicked.connect(lambda: environ_popup_ok_click(
        form, env_window))

    set_environmental_variables.exec_()

def environ_popup_ok_click(form, popup):

    if not validate_paths(popup):
        set_installation_paths(form, popup)
        popup.close()

def adv_op_popup_ok_click(form, advanced_form):

    if not validate_paths(advanced_form):
        set_installation_paths(form, advanced_form)
        set_advanced_option_variables(form,
                                      advanced_form.SphereSizeValue.text(),
                                      advanced_form.phEdit.text())
        advanced_form.close()

def set_installation_paths(form, popup):

    form.data["AMBERHOME"] = popup.amberEdit.text()
    form.data["ENLIGHTEN"] = popup.enlightenEdit.text()

def validate_paths(form):
    return validate_fields(form, [amber_validator, enlighten_validator])


import random
import time
import datetime
import sys
import torchvision.transforms.functional as TF
from torch.autograd import Variable
import torch
from visdom import Visdom
import numpy as np
import math
import torch.nn as nn
import os
from models import Vgg16
# from torch.utils.serialization import load_lua
import torchfile
irange = range

def tensor2image(tensor):
    image = 127.5 * (tensor[0].cpu().float().numpy() + 1.0)
    if image.shape[0] == 1:
        image = np.tile(image, (3, 1, 1))
    return image.astype(np.uint8)

def get_path(img_A, img_B, idx, grid_size=3):

    b, c, h, w = img_A.shape
    paths_num = grid_size * grid_size

    # 'A' 在paths_pool中的编号: [0 ，paths_num - 1]
    # 'B' 在paths_pool中的编号: [paths_num, 2 * paths_num - 1]
    domain = 'A' if idx < paths_num else 'B'

    # 计算相对编号
    # eg： 编号7 -> 编号7   编号10 -> 编号1(10-9)
    relative_pos = idx if domain == 'A' else idx - paths_num

    if domain == 'A':
        img = img_A.detach()
    else:
        img = img_B.detach()

    x_size = math.ceil(h / 3)
    x_start = [i * x_size for i in range(grid_size - 1)]
    x_start.append(h - x_size)

    y_size = math.ceil(w / 3)
    y_start = [i * y_size for i in range(grid_size - 1)]
    y_start.append(w - y_size)

    paths = []
    for x in x_start:
        for y in y_start:
            paths.append(img[:, :, x:x + x_size, y:y + y_size])

    return paths[relative_pos], img, domain, relative_pos

def make_grid(tensor, nrow=8, padding=2,
              normalize=False, range=None, scale_each=False, pad_value=0):
    """Make a grid of images.

    Args:
        tensor (Tensor or list): 4D mini-batch Tensor of shape (B x C x H x W)
            or a list of images all of the same size.
        nrow (int, optional): Number of images displayed in each row of the grid.
            The final grid size is ``(B / nrow, nrow)``. Default: ``8``.
        padding (int, optional): amount of padding. Default: ``2``.
        normalize (bool, optional): If True, shift the image to the range (0, 1),
            by the min and max values specified by :attr:`range`. Default: ``False``.
        range (tuple, optional): tuple (min, max) where min and max are numbers,
            then these numbers are used to normalize the image. By default, min and max
            are computed from the tensor.
        scale_each (bool, optional): If ``True``, scale each image in the batch of
            images separately rather than the (min, max) over all images. Default: ``False``.
        pad_value (float, optional): Value for the padded pixels. Default: ``0``.

    Example:
        See this notebook `here <https://gist.github.com/anonymous/bf16430f7750c023141c562f3e9f2a91>`_

    """
    if not (torch.is_tensor(tensor) or
            (isinstance(tensor, list) and all(torch.is_tensor(t) for t in tensor))):
        raise TypeError('tensor or list of tensors expected, got {}'.format(type(tensor)))

    # if list of tensors, convert to a 4D mini-batch Tensor
    if isinstance(tensor, list):
        tensor = torch.stack(tensor, dim=0)

    if tensor.dim() == 2:  # single image H x W
        tensor = tensor.unsqueeze(0)
    if tensor.dim() == 3:  # single image
        if tensor.size(0) == 1:  # if single-channel, convert to 3-channel
            tensor = torch.cat((tensor, tensor, tensor), 0)
        tensor = tensor.unsqueeze(0)

    if tensor.dim() == 4 and tensor.size(1) == 1:  # single-channel images
        tensor = torch.cat((tensor, tensor, tensor), 1)

    if normalize is True:
        tensor = tensor.clone()  # avoid modifying tensor in-place
        if range is not None:
            assert isinstance(range, tuple), \
                "range has to be a tuple (min, max) if specified. min and max are numbers"

        def norm_ip(img, min, max):
            img.clamp_(min=min, max=max)
            img.add_(-min).div_(max - min + 1e-5)

        def norm_range(t, range):
            if range is not None:
                norm_ip(t, range[0], range[1])
            else:
                norm_ip(t, float(t.min()), float(t.max()))

        if scale_each is True:
            for t in tensor:  # loop over mini-batch dimension
                norm_range(t, range)
        else:
            norm_range(tensor, range)

    if tensor.size(0) == 1:
        return tensor.squeeze(0)

    # make the mini-batch of images into a grid
    nmaps = tensor.size(0)
    xmaps = min(nrow, nmaps)
    ymaps = int(math.ceil(float(nmaps) / xmaps))
    height, width = int(tensor.size(2) + padding), int(tensor.size(3) + padding)
    grid = tensor.new_full((3, height * ymaps + padding, width * xmaps + padding), pad_value)
    k = 0
    for y in irange(ymaps):
        for x in irange(xmaps):
            if k >= nmaps:
                break
            grid.narrow(1, y * height + padding, height - padding) \
                .narrow(2, x * width + padding, width - padding) \
                .copy_(tensor[k])
            k = k + 1
    return grid

def save_image(tensor, filename, nrow=8, padding=2,
               normalize=False, range=None, scale_each=False, pad_value=0):
    """Save a given Tensor into an image file.

    Args:
        tensor (Tensor or list): Image to be saved. If given a mini-batch tensor,
            saves the tensor as a grid of images by calling ``make_grid``.
        **kwargs: Other arguments are documented in ``make_grid``.
    """
    from PIL import Image
    grid = make_grid(tensor, nrow=nrow, padding=padding, pad_value=pad_value,
                     normalize=normalize, range=range, scale_each=scale_each)
    # Add 0.5 after unnormalizing to [0, 255] to round to nearest integer
    ndarr = grid.mul_(255).add_(0.5).clamp_(0, 255).permute(1, 2, 0).to('cpu', torch.uint8).numpy()
    im = Image.fromarray(ndarr)
    im.save(filename)

class Logger():
    def __init__(self, n_epochs, batches_epoch):
        self.viz = Visdom()
        self.n_epochs = n_epochs
        self.batches_epoch = batches_epoch
        self.epoch = 1
        self.batch = 1
        self.prev_time = time.time()
        self.mean_period = 0
        self.losses = {}
        self.loss_windows = {}
        self.image_windows = {}

    def log(self, losses=None, images=None):
        self.mean_period += (time.time() - self.prev_time)
        self.prev_time = time.time()

        sys.stdout.write(
            '\rEpoch %03d/%03d [%04d/%04d] -- ' % (self.epoch, self.n_epochs, self.batch, self.batches_epoch))

        for i, loss_name in enumerate(losses.keys()):
            if loss_name not in self.losses:
                self.losses[loss_name] = losses[loss_name].item()
            else:
                self.losses[loss_name] += losses[loss_name].item()

            if (i + 1) == len(losses.keys()):
                sys.stdout.write('%s: %.4f -- ' % (loss_name, self.losses[loss_name] / self.batch))
            else:
                sys.stdout.write('%s: %.4f | ' % (loss_name, self.losses[loss_name] / self.batch))

        batches_done = self.batches_epoch * (self.epoch - 1) + self.batch
        batches_left = self.batches_epoch * (self.n_epochs - self.epoch) + self.batches_epoch - self.batch
        sys.stdout.write('ETA: %s' % (datetime.timedelta(seconds=batches_left * self.mean_period / batches_done)))

        # Draw images
        for image_name, tensor in images.items():
            if image_name not in self.image_windows:
                self.image_windows[image_name] = self.viz.image(tensor2image(tensor.data), opts={'title': image_name})
            else:
                self.viz.image(tensor2image(tensor.data), win=self.image_windows[image_name],
                               opts={'title': image_name})

        # End of epoch
        if (self.batch % self.batches_epoch) == 0:
            # Plot losses
            for loss_name, loss in self.losses.items():
                if loss_name not in self.loss_windows:
                    self.loss_windows[loss_name] = self.viz.line(X=np.array([self.epoch]),
                                                                 Y=np.array([loss / self.batch]),
                                                                 opts={'xlabel': 'epochs', 'ylabel': loss_name,
                                                                       'title': loss_name})
                else:
                    self.viz.line(X=np.array([self.epoch]), Y=np.array([loss / self.batch]),
                                  win=self.loss_windows[loss_name], update='append')
                # Reset losses for next epoch
                self.losses[loss_name] = 0.0

            self.epoch += 1
            self.batch = 1
            sys.stdout.write('\n')
        else:
            self.batch += 1

class ImagePool():
    def __init__(self, max_size=50):
        assert (max_size > 0), 'Empty buffer or trying to create a black hole. Be careful.'
        self.max_size = max_size
        self.data = []

    def query(self, data):
        to_return = []
        for element in data.data:
            element = torch.unsqueeze(element, 0)
            if len(self.data) < self.max_size:
                self.data.append(element)
                to_return.append(element)
            else:
                if random.uniform(0, 1) > 0.5:
                    i = random.randint(0, self.max_size - 1)
                    to_return.append(self.data[i].clone())
                    self.data[i] = element
                else:
                    to_return.append(element)
        return Variable(torch.cat(to_return))

class LambdaLR():
    def __init__(self, n_epochs, offset, decay_start_epoch):
        assert ((n_epochs - decay_start_epoch) > 0), "Decay must start before the training session ends!"
        self.n_epochs = n_epochs
        self.offset = offset
        self.decay_start_epoch = decay_start_epoch

    def step(self, epoch):
        return 1.0 - max(0, epoch + self.offset - self.decay_start_epoch) / (self.n_epochs - self.decay_start_epoch)

def weights_init_normal(m):
    classname = m.__class__.__name__
    if classname.find('Conv') != -1:
        torch.nn.init.normal(m.weight.data, 0.0, 0.02)
    elif classname.find('BatchNorm2d') != -1:
        torch.nn.init.normal(m.weight.data, 1.0, 0.02)
        torch.nn.init.constant(m.bias.data, 0.0)

def Rotation(image):
    images_all = [image]
    images_all.append(TF.rotate(img=image, angle=90))
    images_all.append(TF.rotate(img=image, angle=180))
    images_all.append(TF.rotate(img=image, angle=270))
    label_all = []
    for i in range(4):
        for j in images_all[0]:
            label_all.append(i)
    # label_all = [i for i in range(4)]
    images_all = torch.cat((images_all[0], images_all[1], images_all[2], images_all[3]), 0)
    images_all_label = torch.tensor(label_all).cuda()

    return images_all, images_all_label

def vgg_preprocess(batch):
    tensortype = type(batch.data)
    (r, g, b) = torch.chunk(batch, 3, dim = 1)
    batch = torch.cat((b, g, r), dim = 1) # convert RGB to BGR
    batch = (batch + 1) * 255 * 0.5 # [-1, 1] -> [0, 255]
    mean = tensortype(batch.data.size()).cuda()
    mean[:, 0, :, :] = 103.939
    mean[:, 1, :, :] = 116.779
    mean[:, 2, :, :] = 123.680
    batch = batch.sub(Variable(mean)) # subtract mean
    return batch

def compute_vgg_loss(self, vgg, img, target):
    img_vgg = vgg_preprocess(img)
    target_vgg = vgg_preprocess(target)
    img_fea = vgg(img_vgg)
    target_fea = vgg(target_vgg)
    return torch.mean((self.instancenorm(img_fea) - self.instancenorm(target_fea)) ** 2)

def load_vgg16(model_dir):
    """ Use the model from https://github.com/abhiskk/fast-neural-style/blob/master/neural_style/utils.py """
    if not os.path.exists(model_dir):
        os.mkdir(model_dir)
    if not os.path.exists(os.path.join(model_dir, 'vgg16.weight')):
        if not os.path.exists(os.path.join(model_dir, 'vgg16.t7')):
            os.system('wget https://www.dropbox.com/s/76l3rt4kyi3s8x7/vgg16.t7?dl=1 -O ' + os.path.join(model_dir, 'vgg16.t7'))
        vgglua = torchfile.load(os.path.join(model_dir, 'vgg16.t7'))
        vgg = Vgg16()
        for (src, dst) in zip(vgglua.parameters()[0], vgg.parameters()):
            dst.data[:] = src
        torch.save(vgg.state_dict(), os.path.join(model_dir, 'vgg16.weight'))
    vgg = Vgg16()
    vgg.load_state_dict(torch.load(os.path.join(model_dir, 'vgg16.weight')))
    return vgg

class GANLoss(nn.Module):
    """Define different GAN objectives.

    The GANLoss class abstracts away the need to create the target label tensor
    that has the same size as the input.
    """

    def __init__(self, gan_mode, target_real_label=1.0, target_fake_label=0.0):
        """ Initialize the GANLoss class.

        Parameters:
            gan_mode (str) - - the type of GAN objective. It currently supports vanilla, lsgan, and wgangp.
            target_real_label (bool) - - label for a real image
            target_fake_label (bool) - - label of a fake image

        Note: Do not use sigmoid as the last layer of Discriminator.
        LSGAN needs no sigmoid. vanilla GANs will handle it with BCEWithLogitsLoss.
        """
        super(GANLoss, self).__init__()
        self.register_buffer('real_label', torch.tensor(target_real_label))
        self.register_buffer('fake_label', torch.tensor(target_fake_label))
        self.gan_mode = gan_mode
        if gan_mode == 'lsgan':
            self.loss = nn.MSELoss()
        elif gan_mode == 'vanilla':
            self.loss = nn.BCEWithLogitsLoss()
        elif gan_mode in ['wgangp']:
            self.loss = None
        else:
            raise NotImplementedError('gan mode %s not implemented' % gan_mode)

    def get_target_tensor(self, prediction, target_is_real):
        """Create label tensors with the same size as the input.

        Parameters:
            prediction (tensor) - - tpyically the prediction from a discriminator
            target_is_real (bool) - - if the ground truth label is for real images or fake images

        Returns:
            A label tensor filled with ground truth label, and with the size of the input
        """

        if target_is_real:
            target_tensor = self.real_label
        else:
            target_tensor = self.fake_label
        return target_tensor.expand_as(prediction)

    def __call__(self, prediction, target_is_real):
        """Calculate loss given Discriminator's output and grount truth labels.

        Parameters:
            prediction (tensor) - - tpyically the prediction output from a discriminator
            target_is_real (bool) - - if the ground truth label is for real images or fake images

        Returns:
            the calculated loss.
        """
        if self.gan_mode in ['lsgan', 'vanilla']:
            target_tensor = self.get_target_tensor(prediction, target_is_real)
            loss = self.loss(prediction, target_tensor)
        elif self.gan_mode == 'wgangp':
            if target_is_real:
                loss = -prediction.mean()
            else:
                loss = prediction.mean()
        return loss

def set_requires_grad(nets, requires_grad=False):
    """Set requies_grad=Fasle for all the networks to avoid unnecessary computations
    Parameters:
        nets (network list)   -- a list of networks
        requires_grad (bool)  -- whether the networks require gradients or not
    """
    if not isinstance(nets, list):
        nets = [nets]
    for net in nets:
        if net is not None:
            for param in net.parameters():
                param.requires_grad = requires_grad


# -*- coding: UTF-8 -*-
import logging
from openpyxl import Workbook

_LOGGER = logging.getLogger('armory')

class ArmoryExcel(object):
    '''
    armory excel lib, use this lib to read and write excle
    '''
    @staticmethod
    def wirte_excel(file_path, title, sheet_value):
        '''
        write excel
        parameter: two dimension array
        result: a excel file with the data in two
        '''
        workbook = Workbook()
        sheet = workbook.active
        sheet.title = title
        for row_num, row_value in enumerate(sheet_value):
            for column_num, column_value in enumerate(row_value):
                sheet.cell(row=row_num + 1, column=column_num + 1).value = column_value
        workbook.save(file_path)

if __name__ == '__main__':
    content = [[1, 2, 3], [4, 5, 6]]
    ArmoryExcel.write_excel('./a.xlsx', 'test', content)


import smbus
import time
slaveAddress3 = 0x60
slaveAddress2 = 0x40
slaveAddress1 = 0x50
bus = smbus.SMBus(1)

Forward=1
Backward =2
Turn= 4
TurnLeftEje = 7
Stop = 5
delay = 1

#distance = 480; #Colocar experimentalmente

print("Programa de prueba de encoder")
distance = input("ingrese la distancia en ticks que desea recorrer\n ")
global distance
while(1):
    bus.write_byte(slaveAddress3, distance)
    time.sleep(.1)
    bus.write_byte(slaveAddress2, Forward)
    bus.write_byte(slaveAddress1, Forward)

if bus.read_byte(slaveAddress3)==9:
    bus.write_byte(slaveAddress2, Stop)
    bus.write_byte(slaveAddress1, Stop)
    #distance = input("ingrese la distancia en ticks que desea recorrer\n ")
    #time.sleep(.1)
    #bus.write_byte(slaveAddress3, distance)


from __future__ import annotations
from neo3 import contracts, storage, vm
from neo3.network import payloads
from neo3.core import types, cryptography, IInteroperable, serialization, to_script_hash
from neo3.contracts import interop
from typing import Any, Dict, cast, List, Tuple, Type, Optional, Callable
import enum
from dataclasses import dataclass

class ApplicationEngine(vm.ApplicationEngineCpp):
    _interop_calls: Dict[int, interop.InteropDescriptor] = {}
    _invocation_states: Dict[vm.ExecutionContext, InvocationState] = {}
    #: Amount of free GAS added to the engine.
    GAS_FREE = 0
    #: Maximum length of event names for "System.Runtime.Notify" SYSCALLs.
    MAX_EVENT_SIZE = 32
    #: Maximum messasge length for "System.Runtime.Log" SYSCALLs.
    MAX_NOTIFICATION_SIZE = 1024
    #: Maximum size of the smart contract script.
    MAX_CONTRACT_LENGTH = 1024 * 1024
    #: Multiplier for determining the costs of storing the contract including its manifest.
    STORAGE_PRICE = 100000

    @dataclass
    class InvocationState:
        return_type: type = None  # type: ignore
        callback: Optional[Callable] = None
        check_return_value: bool = False

    def __init__(self,
                 trigger: contracts.TriggerType,
                 container: payloads.IVerifiable,
                 snapshot: storage.Snapshot,
                 gas: int,
                 test_mode: bool = False
                 ):
        # Do not use super() version, see
        # https://pybind11.readthedocs.io/en/master/advanced/classes.html#overriding-virtual-functions-in-python
        vm.ApplicationEngineCpp.__init__(self, test_mode)
        #: A ledger snapshot to use for syscalls such as "System.Blockchain.GetHeight".
        self.snapshot = snapshot
        #: The trigger to run the engine with.
        self.trigger = trigger
        #: A flag to toggle infinite gas
        self.is_test_mode = test_mode

        self.script_container = container
        #: Gas available for consumption by the engine while executing its script.
        self.gas_amount = self.GAS_FREE + gas
        self._invocation_counter: Dict[types.UInt160, int] = {}
        #: Notifications (Notify SYSCALLs) that occured while executing the script.
        self.notifications: List[Tuple[payloads.IVerifiable, types.UInt160, bytes, vm.ArrayStackItem]] = []

    def checkwitness(self, hash_: types.UInt160) -> bool:
        """
        Check if the hash is a valid witness for the engines script_container
        """
        if isinstance(self.script_container, payloads.Transaction):
            tx = self.script_container
            for s in tx.signers:
                if s.account == hash_:
                    signer = s
                    break
            else:
                return False

            if signer.scope == payloads.WitnessScope.GLOBAL:
                return True

            if payloads.WitnessScope.CALLED_BY_ENTRY in signer.scope:
                if self.calling_scripthash == self.entry_scripthash:
                    return True

            if payloads.WitnessScope.CUSTOM_CONTRACTS in signer.scope:
                if self.current_scripthash in signer.allowed_contracts:
                    return True

            if payloads.WitnessScope.CUSTOM_GROUPS in signer.scope:
                contract = self.snapshot.contracts.get(self.calling_scripthash)
                group_keys = set(map(lambda g: g.public_key, contract.manifest.groups))
                if any(group_keys.intersection(signer.allowed_groups)):
                    return True
            return False

        # for other IVerifiable types like Block
        hashes_for_verifying = self.script_container.get_script_hashes_for_verifying(self.snapshot)
        return hash_ in hashes_for_verifying

    def _stackitem_to_native(self, stack_item: vm.StackItem, target_type: Type[object]):
        # checks for type annotations like `List[bytes]` (similar to byte[][] in C#)
        if hasattr(target_type, '__origin__') and target_type.__origin__ == list:  # type: ignore
            element_type = target_type.__args__[0]  # type: ignore
            array = []
            if isinstance(stack_item, vm.ArrayStackItem):
                for e in stack_item:
                    array.append(self._convert(e, element_type))
            else:
                count = stack_item.to_biginteger()
                if count > self.MAX_STACK_SIZE:
                    raise ValueError

                # mypy bug: https://github.com/python/mypy/issues/9755
                for e in range(count):  # type: ignore
                    array.append(self._convert(self.pop(), element_type))
            return array
        else:
            try:
                return self._convert(stack_item, target_type)
            except ValueError:
                if isinstance(stack_item, vm.InteropStackItem):
                    return stack_item.get_object()
                else:
                    raise

    def _convert(self, stack_item: vm.StackItem, class_type: Type[object]) -> object:
        """
        convert VM type to native
        """
        if class_type in [vm.StackItem, vm.PointerStackItem, vm.ArrayStackItem, vm.InteropStackItem]:
            return stack_item
        elif class_type in [int, vm.BigInteger]:
            return stack_item.to_biginteger()
        # mypy bug? https://github.com/python/mypy/issues/9756
        elif class_type in [bytes, bytearray]:  # type: ignore
            return stack_item.to_array()
        elif class_type == bool:
            return stack_item.to_boolean()
        elif class_type == types.UInt160:
            return types.UInt160(data=stack_item.to_array())
        elif class_type == types.UInt256:
            return types.UInt256(data=stack_item.to_array())
        elif class_type == str:
            return stack_item.to_array().decode()
        elif class_type == cryptography.ECPoint:
            return cryptography.ECPoint.deserialize_from_bytes(stack_item.to_array())
        elif issubclass(class_type, enum.Enum):
            stack_item = cast(vm.IntegerStackItem, stack_item)
            # mypy seems to have trouble understanding types that support __int__
            return class_type(int(stack_item))  # type: ignore
        else:
            raise ValueError(f"Unknown class type, don't know how to convert: {class_type}")

    def _native_to_stackitem(self, value, native_type) -> vm.StackItem:
        """
        Convert native type to VM type

        Note: order of checking matters.
        e.g. a Transaction should be treated as IInteropable, while its also ISerializable
        """
        if isinstance(value, vm.StackItem):
            return value
        elif value is None:
            return vm.NullStackItem()
        elif native_type in [int, vm.BigInteger]:
            return vm.IntegerStackItem(value)
        elif issubclass(native_type, IInteroperable):
            value_ = cast(IInteroperable, value)
            return value_.to_stack_item(self.reference_counter)
        elif issubclass(native_type, serialization.ISerializable):
            serializable_value = cast(serialization.ISerializable, value)
            return vm.ByteStringStackItem(serializable_value.to_array())
        # mypy bug? https://github.com/python/mypy/issues/9756
        elif native_type in [bytes, bytearray]:  # type: ignore
            return vm.ByteStringStackItem(value)
        elif native_type == str:
            return vm.ByteStringStackItem(bytes(value, 'utf-8'))
        elif native_type == bool:
            return vm.BooleanStackItem(value)
        elif issubclass(native_type, (enum.IntFlag, enum.IntEnum)):
            return self._native_to_stackitem(value.value, int)
        else:
            return vm.StackItem.from_interface(value)

    def _get_invocation_state(self, context: vm.ExecutionContext) -> InvocationState:
        state = self._invocation_states.get(context, None)
        if state is None:
            state = self.InvocationState()
            self._invocation_states.update({context: state})
        return state

    def on_syscall(self, method_id: int) -> Any:
        """
        Handle interop syscalls.

        Args:
            method_id: unique syscall identifier.

        Raise:
            KeyError: if `method_id` is syscall that is not registered with the engine.
            ValueError: if the requested syscall handler is called with the wrong call flags.
            ValueError: if engine stack parameter to native type conversion fails

        Returns:
            The result of the syscall handler
        """
        descriptor = interop.InteropService.get_descriptor(method_id)
        if descriptor is None:
            raise KeyError(f"Requested interop {method_id} is not valid")

        if descriptor.required_call_flags not in contracts.native.CallFlags(self.current_context.call_flags):
            raise ValueError(f"Cannot call {descriptor.method} with {self.current_context.call_flags}")

        self.add_gas(descriptor.price)

        parameters = []
        for target_type in descriptor.parameters:
            try:
                item = self.pop()
                parameters.append(self._stackitem_to_native(item, target_type))
            except IndexError:
                raise ValueError("Failed to pop parameter from stack")
            except Exception:
                raise ValueError(f"Failed to convert parameter stack item '{item}' to type '{target_type}'")

        if len(parameters) > 0:
            return_value = descriptor.handler(self, *parameters)
        else:
            return_value = descriptor.handler(self)
        if descriptor.has_return_value:
            self.push(self._native_to_stackitem(return_value, type(return_value)))
        return return_value

    def invoke_syscall_by_name(self, method: str) -> Any:
        """
        Helper function to call `on_syscall` using the syscall name.

        Args:
            method: full qualified syscall name. e.g. "System.Runtime.Platform"

        Returns: the result of the syscall handler. e.g. for "System.Runtime.Platform" returns "NEO"
        """
        return self.on_syscall(contracts.syscall_name_to_int(method))

    @property
    def current_scripthash(self) -> types.UInt160:
        """
        Get the script hash of the current executing smart contract

        Note: a smart contract can call other smart contracts.
        """
        return to_script_hash(self.current_context.script._value)

    @property
    def calling_scripthash(self) -> types.UInt160:
        """
        Get the script hash of the smart contract that called the current executing smart contract.

        Note: a smart contract can call other smart contracts.

        Raises:
            ValueError: if the current executing contract has not been called by another contract.
        """
        if len(self.current_context.calling_script) == 0:
            raise ValueError("Cannot retrieve calling script_hash - current context has not yet been called")
        return to_script_hash(self.current_context.calling_script._value)

    @property
    def entry_scripthash(self) -> types.UInt160:
        """
        Get the script hash of the first smart contract loaded into the engine

        Note: a smart contract can call other smart contracts.
        """
        return to_script_hash(self.entry_context.script._value)

    def get_invocation_counter(self) -> int:
        """
        Get the number of times the current contract has been called during this execute() run.

        Note: the counter increases with every "System.Contract.Call" or "System.Contract.CallEx" SYSCALL

        Raises:
            ValueError: if the contract has not been called.
        """
        counter = self._invocation_counter.get(self.current_scripthash, None)
        if counter is None:
            raise ValueError(f"Failed to get invocation counter for the current context: {self.current_scripthash}")
        return counter

    def context_unloaded(self, context: vm.ExecutionContext):
        # Do not use super() version, see
        # https://pybind11.readthedocs.io/en/master/advanced/classes.html#overriding-virtual-functions-in-python
        vm.ExecutionEngine.context_unloaded(self, context)
        if self.uncaught_exception is not None:
            return
        if len(self._invocation_states) == 0:
            return
        try:
            state = self._invocation_states.pop(self.current_context)
        except KeyError:
            return
        if state.check_return_value:
            eval_stack_len = len(context.evaluation_stack)
            if eval_stack_len == 0:
                self.push(vm.NullStackItem())
            elif eval_stack_len > 1:
                raise SystemError("Invalid evaluation stack state")

        if state.callback is None:
            return
        # TODO: implementation Action/DynamicInvoke part of callback logic


"""
Input Specification
The first line of input contains the integer K (1 ≤ K ≤ 100). The second line of input contains
the integer m (1 ≤ m ≤ 10), which is the number of rounds of removal. The next m lines each
contain one integer. The ith of these lines (1 ≤ i ≤ m) contains r i ( 2 ≤ r i ≤ 100) indicating that
every person at a position which is multiple of r i should be removed.

Output Specification
The output is the integers assigned to friends who were not removed. One integer is printed per
line in increasing sorted order.

"""

# Solution 1
K = int(input())
friends = [i+1 for i in range(K)]
rounds = int(input())

for i in range(rounds):
    bad = []
    remove = int(input())
    for friend in range(len(friends)):
        if ((friend+1)%remove==0):
            bad.append(friends[friend])
    for baddie in bad:
        friends.remove(baddie)

for friend in friends:
    print(friend)

# Solution 2
a = list(range(int(input())))

for j in range(int(input())):
    b = int(input())
    c = list()
    for i in range(len(a)):
        if (i+1) % b:
            c.append(a[i])
    a = c

for i in a: print(i+1)


from tkinter import *
#from tkinter import messagebox
from tkinter import scrolledtext

root = Tk()
root.title("Monitoring System")
root.geometry("{0}x{1}+0+0".format(root.winfo_screenwidth(), root.winfo_screenheight()))
root.configure(background="rosy brown")

#design of root window
btnDataSet=Button(root, text='Load Dataset', font=("arial",16,'bold'), width=20)
btnRSW=Button(root, text='Remove Stop Words', font=("arial",16,'bold'), width=20)
btnLem=Button(root, text='Lemmatization', font=("arial",16,'bold'), width=20)
btnSA=Button(root, text='Sentiment Analysis', font=("arial",16,'bold'), width=20)
btnCheck=Button(root, text='Check', font=("arial",16,'bold'), width=20)
display=scrolledtext.ScrolledText(root,width=180,height=40)

btnDataSet.place(x=20, y=20)
btnRSW.place(x=300, y=20)
btnLem.place(x=580,y=20)
btnSA.place(x=860, y=20)
btnCheck.place(x=1140, y=20)
display.place(x=10, y=90)

root.mainloop()