import numpy as np
import spiceypy as spice
from PIL import Image
print(spice.tkvrsn("TOOLKIT"))
import os

dir_path = os.path.dirname(os.path.realpath(__file__))
spice_data_path = dir_path+"/../SPICEdata/"
KERNEL_LIST = [spice_data_path + x for x in os.listdir(spice_data_path)]
spice.furnsh(KERNEL_LIST)

JUPITER_EQUATORIAL_RADIUS = 71492  # km
JUPITER_POLAR_RADIUS = 66854  # km
STRIPE_LENGTH = 1648  # px
STRIPE_HEIGHT = 128  # px
STANDARD_IMAGE_START_TIME_OFFSET = 0.06188  # sec

PHOTOACTIVE_PIXELS = np.ones((STRIPE_LENGTH, STRIPE_HEIGHT), dtype=np.int)
PHOTOACTIVE_PIXELS[:23+1,:] = 0
PHOTOACTIVE_PIXELS[1631-1:,:] = 0

MIN_SURFACE_ANGLE = 15*np.pi/180
MIN_SUN_ANGLE = 5*np.pi/180

STANDARD_DATASET_SAMPLING_MAP_SIZE = (1024, 2048)

BAD_PIXEL_MASK = (np.array(Image.open(dir_path+"/BAD_PIXEL_MASK.png"))==0).astype(np.uint8)

# camera distortion parameters taken from
# https://naif.jpl.nasa.gov/pub/naif/pds/data/jno-j_e_ss-spice-6-v1.0/jnosp_1000/data/ik/juno_junocam_v03.ti
# in lists for each color: 0: blue, 1: green, 2: red
# INS-6150#_DISTORTION_X
cx = [814.21, 814.21, 814.21]
# INS-6150#_DISTORTION_Y
cy = [158.48, 3.48, -151.52]
# INS-6150#_DISTORTION_K1
k1 = [-5.9624209455667325e-08, -5.9624209455667325e-08, -5.9624209455667325e-08]
# INS-6150#_DISTORTION_K2
k2 = [2.7381910042256151e-14, 2.7381910042256151e-14, 2.7381910042256151e-14]
# INS-6150#_FOCAL_LENGTH/INS-6150#_PIXEL_SIZE
fl = [10.95637/0.0074, 10.95637/0.0074, 10.95637/0.0074]

def get_junocam_jupiter_rel_pos_orient(time_str, add_seconds=0):
	"""
	:param time_str: str (time stamp from image specific json data file)
	:param add_seconds: int or float (seconds to add to time specified by time str for conveniency)
	:return: ndarray(3), position
		ndarray(3,3), orientation matrix
	"""
	et = spice.str2et(time_str)+add_seconds
	pos, light_time = spice.spkpos("Juno", [et], 'IAU_JUPITER', 'NONE', 'JUPITER BARYCENTER')
	pos = np.array(pos[0])

	orient = spice.pxform("IAU_JUPITER", "JUNO_JUNOCAM", et)
	orient = np.array(orient)  # orient[0, :] is x-vec, orient[1, :] y-vec, orient[2, :] z-vec

	return pos, orient

def get_sun_jupiter_rel_pos(time_str, add_seconds=0):
	et = spice.str2et(time_str) + add_seconds
	pos, light_time = spice.spkpos("SUN", [et], 'IAU_JUPITER', 'NONE', 'JUPITER BARYCENTER')
	return np.array(pos[0])

def undistort(cam_x, cam_y, color):
	# undistort function from juno_junocam_v03.ti changed for using numpy arrays
	cam_x_old = cam_x.copy()
	cam_y_old = cam_y.copy()
	for i in range(5):  # fixed number of iterations for simplicity
		r2 = (cam_x**2+cam_y**2)
		dr = 1+k1[color]*r2+k2[color]*r2*r2
		cam_x = cam_x_old/dr
		cam_y = cam_y_old/dr
	return cam_x, cam_y

def get_lightray_vectors(pixel_x, pixel_y, color):
	"""
	:param pixel_x: nd-ndarray of x pixel coords
	:param pixel_y: nd-ndarray of y pixel coords
	:param color: int (0-2) specifying color 0:blue, 1:green, 2:red
	:return: (n+1)d-ndarray of float 3d-lightray vectors in camera reference frame (n+1)-dimension are x,y,z components
	"""
	cam_x = pixel_x-cx[color]
	cam_y = pixel_y-cy[color]
	cam_x, cam_y = undistort(cam_x, cam_y, color)
	return np.stack([cam_x, cam_y, np.full_like(cam_x, fl[color])], axis=-1)

def distort(cam, color):
	"""
	:param cam: ndarray(..,2)
	:param color: int, color 0:blue 1:green 2:red
	:return: ndarray(..,2), undistortet values
	"""
	r2 = np.sum(cam**2, axis=-1)
	dr = 1 + k1[color] * r2 + k2[color] * r2**2
	return cam * dr[...,None]

def get_pixel_coord_from_lightray(ray_dirs, color):
	behind_sensor = (ray_dirs[...,2] <= 0)
	ray_dirs[behind_sensor, 2] = 1
	alpha = ray_dirs[...,2] / fl[color]
	cam = ray_dirs[...,:2] / alpha[...,None]
	cam = distort(cam, color)
	cam[...,0] += cx[color]
	cam[...,1] += cy[color]
	return np.where(behind_sensor[...,None], -1, cam)

x, y = np.indices((STRIPE_LENGTH, STRIPE_HEIGHT))
# list of precomputed 3d-lighray vectors in camera reference frame for 3 colors 0:blue, 1:green, 2:red
CAMERA_STRIPE_VECTORS = [get_lightray_vectors(x, y, color).transpose(1, 0, 2) for color in range(3)]

def project_onto_jupiter_surf(pos, direct):
	"""
	:param pos: ndarray(..,3), origin of the rays
	:param direct: ndarray(..,3), direction of rays in whatever order
	:return: ndarray(..,3), position of projected points closest to pos
		ndarray(..), mask of if the ray hit the sphere
	"""
	b, a = JUPITER_POLAR_RADIUS, JUPITER_EQUATORIAL_RADIUS
	# equations where the line intersects the jupiter surface
	q1 = b**2*direct[..., 0]**2+b**2*direct[..., 1]**2+a**2*direct[..., 2]**2
	q2 = 2*pos[..., 0]*direct[..., 0]*b**2+2*pos[..., 1]*direct[..., 1]*b**2+2*pos[..., 2]*direct[..., 2]*a**2
	q3 = pos[..., 0]**2*b**2+pos[..., 1]**2*b**2+pos[..., 2]**2*a**2-float(a**2*b**2)

	p, q = q2/q1, q3/q1

	tmp = (0.5*p)**2-q
	mask = tmp >= 0

	s = -p*0.5-np.sqrt(tmp*mask)

	return (pos+s[..., None]*direct)*mask[..., None], mask

def rotate_around_axis(n, v, alpha):
	n /= np.linalg.norm(n)
	return n*n.dot(v) + np.cos(alpha)*np.cross(np.cross(n, v), n) + np.sin(alpha)*np.cross(n, v)

def project_tangential_plane(center, x_extent, y_extent, x_res, y_res, orientation):
	"""
	:param center: ndarray(3) of float, center of map on jupiter surface
	:param x_extent: float, extent of the x-axis of the map in km
	:param y_extent: float, extent of the y-axis of the map in km
	:param x_res: int, number of pixels on x-axis
	:param y_res: int, number of pixels on y-axis
	:param orientation: float, rotating orientation of map around center in radiants
	:return: ndarray(x_res, y_res, 3) 3d positions for map pixels
	"""
	assert np.sqrt(x_extent**2 + y_extent**2) < JUPITER_POLAR_RADIUS
	a = JUPITER_POLAR_RADIUS / JUPITER_EQUATORIAL_RADIUS

	normal_vector = np.array([center[0]*a, center[1]*a, center[2]/a])
	if center[0] == 0 and center[1] == 0:
		east_tang_vector = np.array([0, 1, 0])
	else:
		east_tang_vector = np.array([-center[1], center[0], 0])
		east_tang_vector /= np.linalg.norm(east_tang_vector)

	north_tang_vector = np.cross(normal_vector, east_tang_vector)
	north_tang_vector /= np.linalg.norm(north_tang_vector)

	north_tang_vector = rotate_around_axis(normal_vector, north_tang_vector, orientation)
	east_tang_vector = rotate_around_axis(normal_vector, east_tang_vector, orientation)

	x_raster, y_raster = np.meshgrid(np.linspace(-x_extent/2, x_extent/2, x_res),
									 np.linspace(-y_extent/2, y_extent/2, y_res))

	raster = center[None, None, :] + x_raster[..., None] * east_tang_vector[None, None, :]\
			 + y_raster[..., None] * north_tang_vector[None, None, :]

	points_on_jup, _ = project_onto_jupiter_surf(raster, -normal_vector[None, None, :])
	return points_on_jup

def convert_surf_pos_to_spherical_coords(surf_pos):
	surf_pos = surf_pos.copy()
	surf_pos[...,2] *= JUPITER_EQUATORIAL_RADIUS / JUPITER_POLAR_RADIUS
	phi = np.arccos(surf_pos[...,2] / np.linalg.norm(surf_pos, axis=-1))
	theta = np.arctan2(surf_pos[...,1], surf_pos[...,0])
	return phi, theta

def print_progress_bar(i, n, text, channel=None, length=36):
	if channel is None:
		percentage = 100 * i / n
		bar_progress = int(length * i / n)
		bar = bar_progress * '█' + (length - bar_progress) * '.'
	else:
		percentage = 100 * (channel * n + i) / (3 * n)
		c_blocks = ['B', 'G', 'R']
		full_bar = c_blocks[0] * (length//3) + c_blocks[1] * (length//3) + c_blocks[2] * (length-2*(length//3))
		bar_progress = int(length * (channel * n + i) / (3 * n))
		bar = full_bar[:bar_progress] + (length - bar_progress) * '.'

	print('\r'+text+' |{}| {:.2f}%'.format(bar, percentage),end='\r')
	if i == n and channel != 0 and channel != 1:
		print()

import cv2
def remove_bad_pixels(raw_image):
	s1, s2 = raw_image.shape
	new_raw_image = np.zeros_like(raw_image)
	for k in range(s1//384):
		new_raw_image[k*384:(k+1)*384] = cv2.inpaint(raw_image[k*384:(k+1)*384], BAD_PIXEL_MASK, 3, cv2.INPAINT_NS)
	return new_raw_image


from collections import deque

def solution(queue1, queue2):
    answer = 0
    queue1, queue2 = deque(queue1), deque(queue2)
    sum1, sum2 = sum(queue1), sum(queue2)
    half_sum = (sum1 + sum2) // 2

    while queue1 and queue2:
        if sum1 > half_sum:
            sum1 -= queue1.popleft()
        elif sum1 < half_sum:
            pop_ = queue2.popleft()
            queue1.append(pop_)
            sum1 += queue1[-1]
        else:
            return answer
        answer += 1
    return -1

프로그래머스/unrated/118667. 두 큐 합 같게 만들기/두 큐 합 같게 만들기.py

두 큐 합 같게 만들기.py


import requests

from rdj_voting.ressources import RDJ_VOTING, get_logger

_logger = get_logger(__name__)

class RdjSong:

    def __init__(self, song_title, artist_name, song_list, song_id):
        self.song_title = song_title
        self.artist_name = artist_name
        self.song_id = song_id
        self.song_list = song_list

    def send_voting(self, verbose=False):
        voting_url = RDJ_VOTING.format(self.song_list, self.song_id)
        result = requests.get(voting_url)
        if verbose:
            _logger.info("{}, {} for : {} - {}".format(result.status_code, result.text, self.song_title, self.artist_name))
        return result.status_code == 200


# ----- standard modules -----
import os
import sys

import numpy as np
import scipy as sp
import pandas as pd         # pandas tabular DataFrame for task/behavioral data
import matplotlib as mpl    # plot
import matplotlib.pyplot as plt
import re                   # regular expression
import time                 # time code execution

# ----- modules of the project PyNeuroSG -----
import signal_align         # in this package: align neural data according to task
import PyNeuroAna as pna    # in this package: analysis
import PyNeuroPlot as pnp   # in this package: plot
import misc_tools           # in this package: misc

# ----- modules for the data location and organization in Sheinberg lab -----
import data_load_DLSH       # package specific for DLSH lab data
from GM32_layout import layout_GM32

""" -----  test using synthesit signal ----- """
x_grid = np.arange(0,16)
target = np.sin(2*np.pi/8*x_grid)
target_noisy = target* (1+np.random.randn(*target.shape)/3)
target_noisy[6] = 0
target_gauss = sp.ndimage.filters.gaussian_filter1d(target_noisy, 1)
reload(pna)
# target_smooth = pna.quad_smooth_d3(target=target_noisy, lambda_der=0.5)
target_smooth, csd_smooth = pna.quad_smooth_der(target=target_noisy, lambda_der=1, degree_der=3, return_CSD=True)

_, h_axes = plt.subplots(3,2)
plt.axes(h_axes[0,0])
plt.title('LFP')
plt.plot(x_grid, target)
plt.plot(x_grid, target_noisy)
plt.axes(h_axes[1,0])
plt.plot(x_grid, target)
plt.plot(x_grid, target_gauss)
plt.axes(h_axes[2,0])
plt.plot(x_grid, target)
plt.plot(x_grid, target_smooth)

# plt.legend(['origianl', 'noisy','gaussian_smooth' , 'smoothed'])

csd = pna.cal_1dCSD(target, tf_edge=True)
csd_noisy = pna.cal_1dCSD(target_noisy, tf_edge=True)
csd_gauss = pna.cal_1dCSD(target_gauss, tf_edge=True)
# csd_gauss_after = sp.ndimage.filters.gaussian_filter1d(csd_noisy, 1)
# csd_smooth = pna.cal_1dCSD(target_smooth, tf_edge=True)

plt.axes(h_axes[0,1])
plt.title('CSD')
plt.plot(x_grid, csd, '-', linewidth=2 )
plt.plot(x_grid, csd_noisy, '-', linewidth=2 )
plt.legend(['origianl', 'native estimator'])
plt.axes(h_axes[1,1])
plt.plot(x_grid, csd, '-', linewidth=2 )
plt.plot(x_grid, csd_gauss, '-', linewidth=2 )
# plt.plot(x_grid, csd_gauss_after, '--', linewidth=2 )
plt.legend(['origianl', 'gaussian smoothed'])
plt.axes(h_axes[2,1])
plt.plot(x_grid, csd, '-', linewidth=2 )
plt.plot(x_grid, csd_smooth, '-', linewidth=2 )
plt.legend(['origianl', 'derevative smoothed'])

dir_tdt_tank = '/shared/homes/sguan/neuro_data/tdt_tank'
dir_dg='/shared/homes/sguan/neuro_data/stim_dg'

def GetERP(tankname='GM32.*U16.*161125'):
    [blk, data_df, name_tdt_blocks] = data_load_DLSH.load_data('d_.*srv_mask.*', tankname, tf_interactive=False,
                                                               dir_tdt_tank=dir_tdt_tank, dir_dg=dir_dg)

    """ Get StimOn time stamps in neo time frame """
    ts_StimOn = data_load_DLSH.get_ts_align(blk, data_df, dg_tos_align='stimon')

    """ some settings for saving figures  """
    filename_common = misc_tools.str_common(name_tdt_blocks)
    dir_temp_fig = './temp_figs'

    """ make sure data field exists """
    data_df = data_load_DLSH.standardize_data_df(data_df, filename_common)
    blk     = data_load_DLSH.standardize_blk(blk)

    t_plot = [-0.100, 0.500]

    data_neuro=signal_align.blk_align_to_evt(blk, ts_StimOn, t_plot,
                                             type_filter='ana.*', name_filter='LFPs.*', chan_filter=range(1,48+1))
    ERP = np.mean(data_neuro['data'], axis=0).transpose()

    return ERP, data_neuro['ts']

ERP, ts = GetERP(tankname='GM32.*U16.*161206')

pnp.ErpPlot(ERP[32:, :], ts)

lfp = ERP[32:, :]

reload(pna); csd = pna.cal_1dCSD(lfp, axis_ch=0); pnp.ErpPlot(pna.SmoothTrace(csd, sk_std=2.0, fs=1.0, axis=0), ts)

""" test quadratic smoothing """
lfp = ERP[32:48, :]
# lfp *= np.expand_dims(np.arange(len(lfp))!=8, axis=1)
reload(pna)
# lfp = lfp/np.std(lfp, axis=1, keepdims=True)
lambda_dev = np.ones(16)
lambda_dev[2] = 0
lfp_sm_gau = pna.lfp_cross_chan_smooth(lfp, method='gaussian', sigma_chan=1.5, sigma_t=0.5)
lfp_sm_der = pna.lfp_cross_chan_smooth(lfp, method='der', lambda_dev=lambda_dev, lambda_der=1, sigma_t=0.5)

csd_nai        = pna.cal_1dCSD(lfp, axis_ch=0, tf_edge=True)
csd_gau_before = pna.cal_1dCSD(lfp_sm_gau, axis_ch=0, tf_edge=True)
csd_gau_after  = pna.lfp_cross_chan_smooth(csd_nai, method='gaussian', sigma_chan=0.5, sigma_t=0)
csd_der        = pna.cal_1dCSD(lfp_sm_der, axis_ch=0, tf_edge=True)

pnp.ErpPlot(lfp, ts); plt.suptitle('original lfp')

pnp.ErpPlot(csd_nai,        ts, title='CSD naive'); plt.suptitle('csd from original lfp')
pnp.ErpPlot(csd_gau_before, ts, title='CSD'); plt.suptitle('CSD, gaussian smoothed on lfp')
pnp.ErpPlot(csd_gau_after,  ts, title='CSD'); plt.suptitle('CSD, gaussian smoothed on csd')
pnp.ErpPlot(csd_der,        ts, title='CSD'); plt.suptitle('CSD, derivative smoothed')


#import math

import unreal_engine_scripts.config as config
import unreal_engine_scripts.service.general_ue as general_ue
import unreal_engine_scripts.src.get_asset as get_asset
import unreal_engine_scripts.src.set_asset as set_asset
import unreal_engine_scripts.service.log as log

import unreal

# To apply changes in modules
import importlib
importlib.reload(config)
importlib.reload(general_ue)
importlib.reload(get_asset)
importlib.reload(set_asset)
importlib.reload(log)

NO_MIPMAP_HEADER = 'Textures without mipmaps: '

## Find all textures not in Power of two mode. If texture is not standart, lod can't be generated
def find_no_mipmap_textures_log(target_paths, is_recursive_search, only_on_disk_assets):
    return get_asset.find_assets_data(package_paths = target_paths,
                                        class_names = [config.CLASS_NAME_TEXTURE], recursive_classes = True,
                                        recursive_paths = is_recursive_search,
                                        include_only_on_disk_assets = only_on_disk_assets,
                                        properties_values = [(config.PROPERTY_MIPMAP_GEN, config.SETTING_NO_MIPMAPS)],
                                        log_path = log.LOG_PATH_NO_MIPMAPS, log_title = 'No Mipmap Textures')

## Find all meshes without lod groups
def find_no_lods_meshes_log(target_paths, is_recursive_search, only_on_disk_assets):
    return get_asset.find_assets_data(package_paths = target_paths,
                                      class_names = [config.CLASS_NAME_STATIC_MESH],
                                      recursive_paths = is_recursive_search,
                                      include_only_on_disk_assets = only_on_disk_assets,
                                      properties_values = [(config.PROPERTY_LOD_GROUP, config.SETTING_NO_LOD_GROUP)],
                                      log_path = log.LOG_PATH_NO_LODS, log_title = 'No Lods Static Meshes')

#================================Mipmaps===========================================================

## Sets textures mipmap generation setting to new_value
# @param texture_paths object_paths of texture assets
def set_textures_mipmap_gen_settings_log(texture_paths, new_value = config.SETTING_DEFAULT_MIPMAPS,
                                         is_recursive_search = True, only_on_disk_assets = False,
                                         search_properties_values = [], is_disjunction = True):
    new_properties_values = [(config.PROPERTY_MIPMAP_GEN, new_value)]
    return set_asset.set_assets_properties_in_object_paths(texture_paths, new_properties_values, is_recursive_search,
                                                           only_on_disk_assets, [config.CLASS_NAME_TEXTURE, config.CLASS_NAME_TEXTURE_TWO_D],
                                                           search_properties_values, is_disjunction,
                                                           log_path = log.LOG_PATH_SET_PROPERTIES,
                                                           log_title = 'set_textures_mipmap_gen_settings_log')

## Sets textures mipmap generation setting to new_value
# @param dirs_paths paths to dirs with texture assets
def set_textures_mipmap_gen_settings_dirs(dirs_paths, new_value = config.SETTING_DEFAULT_MIPMAPS,
                                         is_recursive_search = True, only_on_disk_assets = False,
                                         search_properties_values = [], is_disjunction = True):
    assets_data = get_asset.get_textures_data_by_dirs(dirs_paths, is_recursive_search, only_on_disk_assets)
    object_paths = get_asset.get_assets_data_object_paths(assets_data)
    return set_textures_mipmap_gen_settings_log(object_paths, new_value,
                                                is_recursive_search, only_on_disk_assets,
                                                search_properties_values, is_disjunction)

## Sets textures with no mipmap gen settings to generate mipmaps new_value. Writing logs.
# @param dirs_paths paths to dirs with texture assets
def set_textures_with_no_mipmap_gen_settings_dirs(dirs_paths, new_value = config.SETTING_DEFAULT_MIPMAPS,
                                                 is_recursive_search = True, only_on_disk_assets = False,
                                                 search_properties_values = [], is_disjunction = True):
    assets_data = find_no_mipmap_textures_log(dirs_paths, is_recursive_search, only_on_disk_assets)
    object_paths = get_asset.get_assets_data_object_paths(assets_data)
    return set_textures_mipmap_gen_settings_log(object_paths, new_value,
                                                 is_recursive_search, only_on_disk_assets,
                                                 search_properties_values, is_disjunction)

#================================Lod===========================================================

## Sets textures with no mipmap gen settings to generate mipmaps new_value. Writing logs.
# @param dirs_paths paths to dirs with texture assets
def set_meshes_lod_group_log(mesh_paths, new_value = config.SETTING_DEFAULT_LOD_GROUP,
                            is_recursive_search = True, only_on_disk_assets = False,
                            search_properties_values = [], is_disjunction = True):
    new_properties_values = [(config.PROPERTY_LOD_GROUP, new_value)]
    return set_asset.set_assets_properties_in_object_paths(mesh_paths, new_properties_values, is_recursive_search,
                                                           only_on_disk_assets, [config.CLASS_NAME_STATIC_MESH],
                                                           search_properties_values, is_disjunction,
                                                           log_path = log.LOG_PATH_SET_PROPERTIES,
                                                           log_title = 'set_meshes_lod_group_log')

def set_meshes_lod_group_dirs(dirs_paths, new_value = config.SETTING_DEFAULT_LOD_GROUP,
                            is_recursive_search = True, only_on_disk_assets = False,
                            search_properties_values = [], is_disjunction = True):
    assets_data = get_asset.get_static_mesh_data_by_dirs(dirs_paths, is_recursive_search, only_on_disk_assets)
    object_paths = get_asset.get_assets_data_object_paths(assets_data)
    return set_meshes_lod_group_log(object_paths, new_value,
                                     is_recursive_search, only_on_disk_assets,
                                     search_properties_values, is_disjunction)

## Sets lod group to meshes with no lod group in dirs. Writing logs.
def set_meshes_with_no_lods_group_dirs(dirs_paths, new_value = config.SETTING_DEFAULT_LOD_GROUP,
                                        is_recursive_search = True, only_on_disk_assets = False,
                                        search_properties_values = [], is_disjunction = True):
    assets_data = find_no_lods_meshes_log(dirs_paths, is_recursive_search, only_on_disk_assets)
    object_paths = get_asset.get_assets_data_object_paths(assets_data)
    return set_meshes_lod_group_log(object_paths, new_value,
                                     is_recursive_search, only_on_disk_assets,
                                     search_properties_values, is_disjunction)

def set_mipmaps_n_lod_group_to_no_lods_dirs(dirs_paths,
                                            new_value_mipmaps = config.SETTING_DEFAULT_MIPMAPS,
                                            new_value_lod_group = config.SETTING_DEFAULT_LOD_GROUP,
                                            is_recursive_search = True, only_on_disk_assets = False,
                                            search_properties_values = [], is_disjunction = True):
    assets_data_no_mipmaps = set_textures_with_no_mipmap_gen_settings_dirs(dirs_paths, new_value_mipmaps,
                                                                        is_recursive_search, only_on_disk_assets,
                                                                        search_properties_values, is_disjunction)
    unreal.log('_')
    assets_data_no_lods = set_meshes_with_no_lods_group_dirs(dirs_paths, new_value_lod_group,
                                                            is_recursive_search, only_on_disk_assets,
                                                            search_properties_values, is_disjunction)
    unreal.log('_')
    return assets_data_no_mipmaps, assets_data_no_lods

#========================================================================================

def is_lod_number_ok(number_of_lod):
    if number_of_lod in range(1,9):
        return True
    else:
        return False

def get_lod_count(static_mesh):
    if static_mesh is not None:
        return static_mesh.get_num_lods()
    else:
        unreal.log_error(get_lod_count.__name__ + '(): static_mesh must not be None')
    return 0

def is_input_ok_set_number_of_lod(assets_data, number_of_lod):
    if general_ue.is_not_none_or_empty(assets_data):
        if is_lod_number_ok(number_of_lod):
            return True
        else:
            unreal.log_error(is_input_ok_set_number_of_lod.__name__ + '(): number_of_lod must be in range [1, 8]')
    else:
        unreal.log_error(is_input_ok_set_number_of_lod.__name__ + '(): assets_data must not be None or Empty')
    return False

def get_editor_reduction_setting_for_lod(static_mesh, lod_indx, screen_sizes = None):
    if screen_sizes is None:
        screen_sizes = unreal.EditorStaticMeshLibrary.get_lod_screen_sizes(static_mesh)
    mesh_reduction_settings = unreal.EditorStaticMeshLibrary.get_lod_reduction_settings(static_mesh, lod_indx)
    percent_triangles = mesh_reduction_settings.get_editor_property('percent_triangles')
    editor_reduction_setting = unreal.EditorScriptingMeshReductionSettings(percent_triangles, screen_sizes[lod_indx])
    return editor_reduction_setting

## Set lod count
# @param number_of_lod must be in range [1, 8]
# Error: For 6-8 Lod making wrong mesh sections.This leads to problems with texture maps. Better to use editor functions
def change_number_of_lod(assets_data, new_number_of_lod = 1, auto_compute_lod_screen_size = True):
    if is_input_ok_set_number_of_lod(assets_data, new_number_of_lod):
        static_meshes = get_asset.get_assets_from_assets_data(assets_data)
        for static_mesh in static_meshes:
            lod_count = get_lod_count(static_mesh)
            if is_lod_number_ok(lod_count):
                editor_reduction_settings = []
                screen_sizes = unreal.EditorStaticMeshLibrary.get_lod_screen_sizes(static_mesh)
                # Creates list of reduction settings
                if new_number_of_lod > lod_count:
                    for lod_indx in range(lod_count):
                        editor_reduction_settings.append(get_editor_reduction_setting_for_lod(static_mesh, lod_indx, screen_sizes))
                    last_lod_reduction_settings = get_editor_reduction_setting_for_lod(static_mesh, lod_count - 1, screen_sizes)
                    last_lod_percent_triangles = 0
                    if lod_count != 1:
                        last_lod_percent_triangles = last_lod_reduction_settings.get_editor_property('percent_triangles')
                    else:
                        last_lod_percent_triangles = 0.5
                    screen_size = last_lod_reduction_settings.get_editor_property('screen_size')
                    for lod_indx in range(lod_count, new_number_of_lod):
                        if lod_indx > 1:
                            last_lod_percent_triangles = last_lod_percent_triangles * 0.5
                        new_reduction_setting = unreal.EditorScriptingMeshReductionSettings(last_lod_percent_triangles, screen_size)
                        editor_reduction_settings.append(new_reduction_setting)
                elif new_number_of_lod <= lod_count:
                    for lod_indx in range(new_number_of_lod):
                        editor_reduction_settings.append(get_editor_reduction_setting_for_lod(static_mesh, lod_indx, screen_sizes))

                reduction_options = unreal.EditorScriptingMeshReductionOptions(auto_compute_lod_screen_size = True,
                                                                               reduction_settings = editor_reduction_settings)
                reduction_options.set_editor_property('auto_compute_lod_screen_size', True)
                lods_created = unreal.EditorStaticMeshLibrary.set_lods_with_notification(static_mesh, reduction_options, apply_changes = True)

                '''mesh_reduction_settings = []
                for lod_indx in range(new_number_of_lod):
                    mesh_reduction_settings = unreal.EditorStaticMeshLibrary.get_lod_reduction_settings(static_mesh, lod_indx)
                    unreal.EditorStaticMeshLibrary.set_lod_reduction_settings(static_mesh, lod_indx, mesh_reduction_settings)'''

                unreal.log('Lods_created: ' + str(lods_created))
            else:
                unreal.error_log(change_number_of_lod.__name__ + '(): lod_count is out of bound [1, 8]')

## Changes lod count
# @param number_of_lod must be in range [1, 8]
def change_number_of_lod_in_dirs(dirs_paths, new_number_of_lod = 1,
                                 is_recursive_search = True, only_on_disk_assets = False,
                                 search_properties_values = [], is_disjunction = True, auto_compute_lod_screen_size = True):
    assets_data = get_asset.find_assets_data(package_paths = dirs_paths,
                                             class_names = [config.CLASS_NAME_STATIC_MESH],
                                             recursive_paths = is_recursive_search,
                                             include_only_on_disk_assets = only_on_disk_assets,
                                             properties_values = search_properties_values)
    change_number_of_lod(assets_data, new_number_of_lod, auto_compute_lod_screen_size)


# -*- coding: utf-8 -*-
"""
Created on Sun Feb 10 13:10:03 2019

@author: Jzz
"""

import requests
import sys
from bs4 import BeautifulSoup
import re
import json
import calendar  #为了确定终止时间是在某个月的几号

import io
import time
import urllib

def Login(cookie_str):

    #浏览器登录后得到的cookie，一定要是Response Header里 status为200 OK的那个数据里的cookie
#    cookie_str = cookie
    #把cookie字符串处理成字典，以便接下来使用
    cookies = {}
    for line in cookie_str.split(';'):
#        print(line)
        key, value = line.split('=')
        cookies[key] = value

    #设置请求头
    headers = {'User-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
    #在发送get请求时带上请求头和cookies
    #resp = requests.get(url, headers = headers, cookies = cookies)
    #用get方法，得到的实际是https://www.sui.com/tally/new.do的结果，没有需要的数据

    resp = requests.get(url,headers = headers, cookies = cookies)
    print(resp.text)
    #检查是否登录成功
    if re.compile(r"***").search(resp.text):#自己的人人网的姓名
        print('Login Success')
        requestToken = re.findall("requestToken : '([^']*)',",resp.text) #正则出来是列表
        rtk = re.findall("_rtk : '([^']*)'",resp.text)
#        print(requestToken,rtk)
        return (cookies,1,requestToken[0],rtk[0])
    else:
        print('Login failed')
        return (cookies,0)

def savePic(albumUrl,cookies,requestToken,rtk):
#    try:
    headers = {'User-agent':'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:51.0) Gecko/20100101 Firefox/51.0'}
    #在发送get请求时带上请求头和cookies

    resp = requests.get(albumUrl,headers = headers, cookies = cookies)
    data = resp.text
#        print(data)
#正则提取   # "albumId":"1083919536"
    albumIdlist = re.findall('"albumId":"([^"]*)",',data)
#        imglist = re.findall('"url":"([^<]+)"}',data)
    print(albumIdlist)

 ##############根据得到的图片路径URL将图片下载下来保存本地########
    x= 0
    for albumId in albumIdlist:
        #每一个相册的网址

#        single_album_url = 'http://photo.renren.com/photo/***/album-%s/v7' %albumId  # 该网址最多只能解析前40张图片，其余的滚动鼠标，通过ajax加载出来的
        for page_index in range(1,10):
#            print(albumId,str(page_index),requestToken,rtk)
            single_album_single_page_url = 'http://photo.renren.com/photo/***/album-%s/bypage/ajax/v7?page=%s&pageSize=20&requestToken=%s&_rtk=%s'  %(albumId,str(page_index),requestToken,rtk)
            cont = requests.get(single_album_single_page_url,headers = headers, cookies = cookies)
            #相册内部的源代码
#            print(cont.text)
            imglist = re.findall('"url":"([^"]*)"',cont.text)#找到每张图片的ID
    #        print(imglist)
            if imglist !=[]: #如果为空，则终止

                #处理网址去除\
                for index,item in enumerate(imglist):
                    if '\\' in item:
                        imglist[index] = imglist[index].replace('\\','')
#                print(imglist)
                for single_pic_url in imglist:
                    print(single_pic_url)
                    ##############根据得到的图片路径URL将图片下载下来保存本地########
                    request = urllib.request.Request(url = single_pic_url, headers=headers)
                    response = urllib.request.urlopen(request)
                    img = response.read()
                    with open('F:\image\miao\miao%s.jpg' %x, 'wb') as fp:
                        fp.write(img)
        #            urllib.request.urlretrieve(single_pic_url,r'D:\image\miao\miao%s.jpg' %x)
                        print('miao%s.jpg done' %x)
                        x+=1

#登录后才能访问的网页
url = 'http://www.renren.com/34434***' # 自己的登陆主页
albumUrl = "http://photo.renren.com/photo/***/albumlist/v7?offset=0&limit=40#"# ***为你想下载图片的朋友的人人ID

cookie_str = r'***'#为简便起见，利用cookie登陆，火狐浏览器可以利用HttpFox工具查看
login_result = Login(cookie_str)
cookies = login_result[0]

#
if login_result[1] == 1:
    requestToken = login_result[2]
    rtk = login_result[3]
    savePic(albumUrl,cookies,requestToken,rtk)


import json
import re

def __insert_or_append(dic, key, value):
    if key not in dic:
        dic[key] = [value]
    else:
        dic[key].append(value)

def __logger(in_path, out_path, pattern, processor=None):
    in_file = open(in_path, 'r')
    out_file = open(out_path, 'w')
    p = re.compile(pattern)
    for line in in_file:
        j = json.loads(line)
        if not p.match(j['message']):
            continue
        if processor:
            out_file.write(processor(j))
        else:
            out_file.write(str(j).replace('\'', '"') + '\n')

def __processor(in_path, msg_heading):
    info = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        j = json.loads(line)
        msg, pid = j['message'], int(j['process'])

        record = {}
        for field in msg[len(msg_heading):].split(', '):
            [key, value] = field.split('=')
            try:
                value_stored = int(value)
            except:
                value_stored = value
            info[key] = value_stored

        __insert_or_append(info, pid, record)

    return info

def __csv_gen(in_path, out_path, pid, fields, processor):
    info = processor(in_path)
    out = open(out_path, 'w')
    out.write(','.join(fields) + '\n')
    for item in info[pid]:
        out_line = ','.join([str(item[field]) for field in fields])
        out.write(out_line + '\n')

def clean(in_path, out_path):

    def process(j):
        j['timestamp'] = j['timestamp'].split(' ')[1][:-6]
        for field in ['level', 'tag', 'raw']:
            j.pop(field, None)
        return str(j).replace('\'', '"') + '\n'

    __logger(in_path, out_path, r'^\[HT\]', process)

def gc_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[GC\]')

def sys_gc_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[SysGC\]')

def heap_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[Heap\]')

def mem_filter(in_path, out_path):
    __logger(in_path, out_path, r'^\[HT\] \[((IPut)|(IGet))\]')

def __heap_processor(in_path):
    """
    Message format:
        [HT] [Heap] ts=...,
                    bytes_allocated=..., bytes_tl_bulk_allocated=..., heap_num_bytes_allocated=...,
                    art_obj_allocated=..., art_bytes_allocated=...
    Data format:
        { pid: {ts                      : int,  // unix-style timestamp
                bytes_allocated         : int,
                bytes_tl_bulk_allocated : int,
                heap_num_bytes_allocated: int,
                art_obj_allocated       : int,
                art_bytes_allocated     : int,
        }}
    """
    pid_heap = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        l = json.loads(line)
        msg, pid = l['message'], int(l['process'])
        if msg.find('[HT] [Heap]') == -1:
            continue

        heap_alloc_info = {}
        for field in msg[12:].split(', '):
            [key, value] = field.split('=')
            heap_alloc_info[key] = int(value)

        __insert_or_append(pid_heap, pid, heap_alloc_info)

    return pid_heap

def __gc_processor(in_path):
    """
    Message format:
        [HT] [GC] [End] ts=...,
                        gc_cause=..., gc_name=...,
                        heap_obj_allocated=..., heap_bytes_allocated=...,
                        heap_obj_allocated_ever=..., heap_obj_freed_ever=..., heap_bytes_allocated_ever=..., heap_bytes_freed_ever=...,
                        gc_obj_freed=..., gc_bytes_freed=..., gc_large_obj_freed=..., gc_large_bytes_freed=...
    Data format:
        { pid: [{ ts                       : int,
                  tsh                      : int,
                  gc_cause                 : str,
                  gc_name                  : str,
                  heap_obj_allocated       : int,
                  heap_bytes_allocated     : int,
                  heap_obj_allocated_ever  : int,
                  heap_obj_freed_ever      : int,
                  heap_bytes_allocated_ever: int,
                  heap_bytes_freed_ever    : int,
                  gc_obj_freed             : int,
                  gc_bytes_freed           : int,
                  gc_large_obj_freed       : int,
                  gc_large_bytes_freed     : int,
        }]}
    """
    pid_gc = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        l = json.loads(line)
        msg, pid = l['message'], int(l['process'])
        if msg.find('[HT] [GC] [End]') == -1:
            continue

        gc_info = {}
        for field in msg[16:].split(', '):
            [key, value] = field.split('=')
            try:
                value_stored = int(value)
            except:
                value_stored = value
            gc_info[key] = value_stored

        __insert_or_append(pid_gc, pid, gc_info)

    return pid_gc

def __mem_processor(in_path):
    """
    Message format
    Data format
    """
    pid_tid_mem = {}
    in_file = open(in_path, 'r')
    for line in in_file:
        l = json.loads(line)
        msg, pid, tid = l['message'], int(l['process']), int(l['thread'])
        if msg.find('[HT] [IPut]') == -1 and msg.find('[HT] [IGet]') == -1:
            continue

        mem_info = {}
        for field in msg[12:].split(', '):
            [key, value] = field.split('=')
            try:
                value_stored = int(value)
            except:
                value_stored = value
            mem_info[key] = value_stored

        __insert_or_append(pid_tid_mem, (pid, tid), mem_info)

    return pid_tid_mem

def heap_csv(in_path, out_path, pid, fields=None):
    if fields is None:
        fields = ['tshres', 'bytes_allocated', 'bytes_tl_bulk_allocated', 'heap_num_bytes_allocated']
    __csv_gen(in_path, out_path, pid, fields, __heap_processor)

def gc_csv(in_path, out_path, pid, fields=None):
    if fields is None:
        fields = ['tshres', 'gc_obj_freed', 'gc_bytes_freed', 'heap_obj_freed_ever', 'heap_bytes_freed_ever', 'heap_obj_allocated', 'heap_bytes_allocated']
    __csv_gen(in_path, out_path, pid, fields, __gc_processor)

def mem_csv(in_path, out_path, pid, fields=None):
    if fields is None:
        fields = ['tshres', 'method', 'field', 'iget', 'iput']
    __csv_gen(in_path, out_path, (pid, pid), fields, __mem_processor)


from collections import deque, defaultdict

class Graph():
    def __init__(self):
        self.vertices = 0
        self.graph = defaultdict(list)
        self.topoOrder = deque()
        self.cycleExists = False
        self.backEdge = deque()

    def addEdgesfromFile(self, filename):
        with open(filename) as f:
            for line in f:
                templist = []
                templist = line.split(":")
                temp2 = []
                temp2 = line.split()
                temp2 = temp2[1:]
                if len(temp2) == 0:
                    temp2.append(0)
                for i in range(0, len(temp2)):
                    self.graph[int(templist[0])].append(int(temp2[i]))
            f.close()
            self.vertices = len(self.graph)

    def DFS(self):
        color = ["White"] * (self.vertices + 1)
        for i in range(1 , self.vertices + 1):
            if color[i] == "White":
                self.DFSVisit(i, color)
        if self.cycleExists == False:
            self.topoSort()
        elif self.cycleExists == True:
            print("Cycle exists, Back Edges occur at:")
            while(len(self.backEdge) > 0):
                print(self.backEdge.popleft())
    def DFSVisit(self, u, color):
        color[u] = "Gray"
        for v in self.graph[u]:
            if color[v] == "White":
                self.DFSVisit(v, color)
            if color[v] == "Gray":
                self.backEdge.appendleft((u, v))
                self.cycleExists = True
        color[u] = "Black"
        self.topoOrder.appendleft(u)
    def topoSort(self):
        self.topoOrder.remove(0)
        print("Topological Order")
        while(len(self.topoOrder) > 0):
            print(self.topoOrder.popleft())

if __name__ == "__main__":
    filename = input("Enter the name of the graph file, ex. graphin-c1.txt:  ")
    graph = Graph()
    graph.addEdgesfromFile(filename)
    print("Graph Created, Performing DFS Topo Sort")
    graph.DFS()


#!/usr/bin/python3
# shakewebpy.py - Program to serach shakespeare
# James Skon, 2021

import cgi
import cgitb
cgitb.enable()
fileName="/var/www/html/shakewebpy/shakespeare.txt"

def removePunctuation(s):
  "Remove all punctuation from a string"
  import string
  for c in string.punctuation:
    s= s.replace(c,"")
  return s

def addToIndex(index,word,line):
  if word not in index:
    index[word]=[line] # make new entry
  else:
    index[word].append(line)

class textindex:

  def __init__(self,filename):
    "Create a dictionary of all words, with the key being the word, and the value being the number of times the word is found"
    self.index={}
    inFile = open(filename,"r")
    pos=0
    line=inFile.readline()
    while len(line)>0:
      line=line.strip().lower()
      line=removePunctuation(line.lower())
      words=line.split()
      for word in words:
        addToIndex(self.index,word,pos)
      pos=inFile.tell()  # Next line position
      line=inFile.readline()
    return

  def wordcount(self):
    return len(self.index)

  def lookup(self,word):
    word=word.lower()
    if word in self.index:
      lines=self.index[word]
      return lines
    else:
      return []

def print_header():
    print ("Content-type:text/html\n\n")

def lookupWords(index,filename,searchTerm):
  "Allow user to lookup word matches"
  lines = []
  positions=index.lookup(searchTerm)

  if len(positions)>0:
    textfile=open(filename,"r")
    for pos in positions:
      textfile.seek(pos,0)
      line=textfile.readline()
      lines.append(line+'<br />')
  else:
    lines.append(searchTerm+" not found,")
  return lines

def main():
  print_header()

  sIndex=textindex(fileName)

  form = cgi.FieldStorage()
  if (form.getvalue("word")):
    word=form.getvalue("word").upper()
    lines=lookupWords(sIndex,fileName,word)

    for line in lines:
      print(line)
  else:
    print("Error in submission")

main()


### Module imports ###
import math

import torch
from torch import nn
from torchsummary import summary

### Global Variables ###

### Class declarations ###
class SRResNet(nn.Module):

    def __init__(self, scale_factor, num_residual=5):
        upsample_block_num = int(math.log(scale_factor, 2))

        super(SRResNet, self).__init__()
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=3, padding=1),
            nn.PReLU()
        )
        residual = [ResidualBlock(64) for _ in range(num_residual)]
        self.residual = nn.Sequential(*residual)
        self.conv2 = nn.Sequential(
            nn.Conv2d(64, 64, kernel_size=3, padding=1),
            nn.BatchNorm2d(64)
        )
        upsample = [UpsampleBLock(64, 2) for _ in range(upsample_block_num)]
        upsample.append(nn.Conv2d(64, 3, kernel_size=9, padding=4))
        self.upsample = nn.Sequential(*upsample)

    def forward(self, x):
        conv1 = self.conv1(x)
        residual = self.residual(conv1)
        conv2 = self.conv2(residual)
        upsample = self.upsample(conv1 + conv2)
        return (torch.tanh(upsample) + 1) / 2

class ResidualBlock(nn.Module):

    def __init__(self, channels):
        super(ResidualBlock, self).__init__()
        self.conv1 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.bn1 = nn.BatchNorm2d(channels)
        self.prelu = nn.PReLU()
        self.conv2 = nn.Conv2d(channels, channels, kernel_size=3, padding=1)
        self.bn2 = nn.BatchNorm2d(channels)

    def forward(self, x):
        residual = self.conv1(x)
        residual = self.bn1(residual)
        residual = self.prelu(residual)
        residual = self.conv2(residual)
        residual = self.bn2(residual)
        return x + residual

class UpsampleBLock(nn.Module):

    def __init__(self, in_channels, up_scale):
        super(UpsampleBLock, self).__init__()
        self.conv = nn.Conv2d(in_channels, in_channels * up_scale ** 2, kernel_size=3, padding=1)
        self.pixel_shuffle = nn.PixelShuffle(up_scale)
        self.prelu = nn.PReLU()

    def forward(self, x):
        x = self.conv(x)
        x = self.pixel_shuffle(x)
        x = self.prelu(x)
        return x

### Function declarations ###
if __name__ == '__main__':
    model = SRResNet(4, 5).cuda()
    summary(model, (3, 22, 22))


from collections import deque

n, k = map(int, input().split())
m = len(str(n))

def solve():
    ans = 0
    visited = set()
    visited.add((n, 0))

    que = deque([(n, 0)])
    while que:
        cur, cnt = que.pop()
        # k번 연산을 끝낸 숫자 중에서 가장 큰 수가 정답
        if cnt == k:
            ans = max(ans, cur)
            continue

        nums = [*str(cur)]

        # 모든 숫자 교환해서 que에 담아주기
        for i in range(m-1):
            for j in range(i+1, m):
                if i == 0 and nums[j] == '0': continue
                nums[i], nums[j] = nums[j], nums[i]     # 연산 수행하기 위해 숫자 교환하기
                num = int(''.join(nums))                 # 연산 수행 결과를 숫자로 바꾸기
                if (num, cnt + 1) not in visited:        # 연산 결과가 이미 구해져있던 답이라면 중복 계산하지 않기
                    visited.add((num, cnt + 1))
                    que.append((num, cnt + 1))
                # 다음 교환을 위해 다시 되돌리기
                nums[i], nums[j] = nums[j], nums[i]
    print(ans if ans > 0 else -1)                       # ans 가 초기값 0 그대로라면 답이 없다는 의미이므로 -1을 출력해준다

solve()


import os
from flask import Flask, make_response, jsonify, request
from flask.ext.cors import CORS
import pymongo
from pymongo import MongoClient
from bson.json_util import dumps
from bson.objectid import ObjectId
from os.path import join, dirname
from dotenv import load_dotenv
from flask.ext.socketio import SocketIO, emit, send
import ast
import datetime

dotenv_path = join(dirname(__file__), '.env')
load_dotenv(dotenv_path)

app = Flask(__name__, instance_path='/Users/Linehan/desktop/workspace/capstone/project/instance')
CORS(app, resources={r'/*' : {"origins": "*"}}, allow_headers='Content-Type')
socketio = SocketIO(app)

MONGO_URL = os.environ.get("MONGOLAB_URI")
DB_NAME = os.environ.get("DB_NAME")
if not MONGO_URL:
    MONGO_URL = "mongodb://localhost:27017/capstone"

client = MongoClient(MONGO_URL)
db = client[DB_NAME]
events_collection = db['events']

@app.route('/events')
def get_events():
    return dumps(events_collection.find())

@app.route('/create_event', methods=['POST'])
def create_event():
    form_data = ast.literal_eval((request.data).decode())
    venue_city = form_data["venueCity"]
    venue_name = form_data["venueName"]
    venue_state = form_data["venueState"]
    event_name = form_data["eventName"]
    db.events.insert_one(
        {
        "date": "11/13/2015",
        "venue": {
            "city": venue_city,
            "state": venue_state,
            "name": venue_name
            },
        "name": event_name,
        "posts": []
        }
    )

@app.route('/create_post', methods=["POST"])
def create_post():
    form_data = ast.literal_eval((request.data).decode())
    # print(form_data)
    venue_id = form_data["id"]
    post_body = form_data["body"]
    post_name = form_data["name"]
    post_date = datetime.datetime.utcnow()

    if "image" in form_data:
        post_image = form_data["image"]
        db.events.update(
            { "_id": ObjectId(venue_id)},
            { "$push":
                { "posts": {
                    "body": post_body,
                    "image": post_image,
                    "time": post_date,
                    "name": post_name
                    }
                }
        })
    else:
        db.events.update(
            { "_id": ObjectId(venue_id)},
            { "$push":
                { "posts": {
                    "body": post_body,
                    "time": post_date,
                    "name": post_name
                    }
                }
        })

    print("OKAY")
    return "OK"

# ******
# @socketio.on('message', namespace="/test")
# def test_message(message):
#     print(message)
    # socketio.emit('newPostEvent', {'newPost': {
    #             "event_id": ObjectId(venue_id),
    #              "post": {
    #                     "body": post_body,
    #                     "time": post_date,
    #                     "user_name": post_name
    #                     }
    #                 } }, namespace='/test')

# @socketio.on('connect', namespace="/test")
# def test_connect():
#     print("Connected!!!")
#     emit('sendPost', {'data': 'hello world'})
#     emit('test_event', {'data': 'Connected'})

if __name__ == "__main__":
    app.run(debug=True)
    socketio.run(app)


import numpy as np
import pygame
import random

pygame.init() #where the pygame grid starts

width, height = 820, 820 #following 3 lines control the width and height of the pygame window and the name of the window
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("SPLOOSH KABOOM")

BLUE = (43, 101, 236) #these three colors are used to generate colors within the 20x20 grid
RED = (255, 0, 0)
GREEN = (0, 255, 0)

grid_size = 20 #controls grid size
tile_size = 40
grid_padding = 10

grid = np.zeros((grid_size, grid_size), dtype=int)

ship_sizes = [4, 4, 4, 3, 3, 2] #list of the amount of ships plus their varying sizes (three 4 tile ships, two three tile ships, and one 2 tile ship)

for size in ship_sizes:
    valid = False
    while not valid:
        x = random.randint(0, grid_size - 1)
        y = random.randint(0, grid_size - 1) #chooses a random general area of where a ship can be
        orientation = random.choice(["horizontal", "vertical"]) #randomly decides if the ship will be vertical or horziontal

        if orientation == "horizontal": #aligns ship to be  horziontal
            if y + size <= grid_size and np.count_nonzero(grid[x, y:y + size]) == 0:
                grid[x, y:y + size] = 1
                valid = True
        else: #aligns ship to be vertical
            if x + size <= grid_size and np.count_nonzero(grid[x:x + size, y]) == 0:
                grid[x:x + size, y] = 1
                valid = True

hit_count = 0
ships_sunk = 0
totalclicks = 0  #these three variables track variables that will change throughout the loop
font = pygame.font.Font(None, 36)

running = True #as long as running is true the code will run
print("hey welcome to SPLOOSH KABOOM your goal is to find all 6 ships and sink them ")
while running: #code is in a while true loop until win condition is met
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN and ships_sunk < 6:
            if pygame.mouse.get_pressed()[0]: #code registers player's click and finds the row and col where the player clicked
                pos = pygame.mouse.get_pos()
                col = (pos[0] - grid_padding) // tile_size
                row = (pos[1] - grid_padding) // tile_size
                try:
                    if grid[row][col] == 1: #using the value of row and col where the player click if it equals to 1 that means the player hit a ship
                        hit_count += 1
                        grid[row][col] = -1
                        totalclicks += 1
                        print("KABOOM!")
                    if hit_count == 20: #when hit count is 20 (the total amount of hits when you add all the ship totals together ) playe meets win condition
                            ships_sunk = 6
                            if ships_sunk == 6:
                                running = False
                                print("Congratulations! You sunk all the ships!")
                                print("it took ya" + str(totalclicks)+ " clicks.")
                    elif grid[row][col] == 0: #when the value of row and grid make a 0 it means the player missed
                        grid[row][col] = -2
                        print("sploosh...")
                        totalclicks += 1
                except: #when player clicks out of bounds usually an error happens but using try and execept makes it so it doesn't break this is a temp solution until i find a way to fix it
                    print("ERROR: Out Of Bounds. That wasn't very splash kaboomy of you")
    screen.fill(BLUE) #makes the default grid all blue

    for row in range(grid_size):
        for col in range(grid_size):
            x = col * tile_size + grid_padding
            y = row * tile_size + grid_padding
            pygame.draw.rect(screen, BLUE, (x, y, tile_size, tile_size), 1)

            if grid[row][col] == -1: #when ship is hit marked with green tile
                pygame.draw.rect(screen, GREEN, (x + 1, y + 1, tile_size - 2, tile_size - 2))
            elif grid[row][col] == -2: #when ship is missed marked with red tile
                pygame.draw.rect(screen, RED, (x + 1, y + 1, tile_size - 2, tile_size - 2))

    pygame.display.flip()

pygame.quit()


#Startup
import pygame
import random
import math
import webbrowser

# -- Global Constants
size = (640,480)
player_score = 0
pleasework = False
# -- Colours
BLACK = (0,0,0)
WHITE = (255,255,255)
BLUE = (50,50,255)
YELLOW = (255,255,0)
RED = (255, 0, 0)
# -- Initialise PyGame
pygame.init()
#Load music
pygame.mixer.music.load('The-Avengers-Theme-Song.mp3')
#Play music
pygame.mixer.music.play()
# -- Blank Screen
screen = pygame.display.set_mode(size)
# -- Title of new window/screen
pygame.display.set_caption("Space Invaders Lite")

#Displays game stats
def draw_stats(screen, x, y, stats):
    # Select the font to use, size, bold, italics
    font = pygame.font.SysFont('Calibri', 30, True, False)
    # Render the text. "True" means anti-aliased text.
    # Note: This line creates an image of the letters,
    # but does not put it on the screen yet.
    text = font.render(str(stats), True, YELLOW)
    # Puts the image of the text on the screen at x,y
    screen.blit(text, (x, y))
#Endproc

## -- Define the class Player which is a sprite
class Player(pygame.sprite.Sprite):
    # Define the constructor for Player
    def __init__(self, color, width, height, lives, score, bullet_count):

        # Call the sprite constructor
        super().__init__()
        # Create a sprite and fill it with colour
        self.width = width
        self.height = height
        self.image = pygame.Surface([width,height])
        self.image.fill(color)
        # Set the position of the sprite
        self.rect = self.image.get_rect()
        self.rect.x = 300
        self.rect.y = size[1] - height
        self.speed = 0
        self.lives = lives
        self.score = 0
        self.bullet_count = bullet_count
    #Endwhat?

    # Class update function - runs for each pass through the game loop
    def update(self):
        self.rect.x = self.rect.x + self.speed
        if self.rect.x >= size[0]:
            self.rect.x = 0
        elif self.rect.x <= 0:
            self.rect.x = size[0]
        #Endif
    #Endmethod

    def player_set_speed(self, val):
        self.speed = val
    #Endmethod

    def increase_score(self, val):
        self.score += val
    #Endmethod

    def decrease_bcount(self):
        if self.bullet_count > 0:
            self.bullet_count -= 1
        #Endif
    #Endmethod

#Endclass

class Invader(pygame.sprite.Sprite):
    # Define the constructor for Invader
    def __init__(self, color, width, height, speed, enemy):

        #Why can i not have xpos atribute that holds self.rect.x and change it when i call the class?

        # Call the sprite constructor
        super().__init__()
        self.image = pygame.image.load(enemy)
        # Set the position of the sprite
        self.height = height
        self.width = width
        self.rect = self.image.get_rect()
        self.rect.x = random.randrange(0, 600)
        self.rect.y = random.randrange(-self.height, (-150 - self.height), -1)
        self.speed = speed

    def update(self):
        self.rect.y = self.rect.y + self.speed
        if self.rect.y >= size[1]:
            invader_group.remove(self)
        #Endif
    #Endmethod

    def centralise(self):
        while self.rect.x > 0:
            self.rect.x -= 1
        #Endwhile
    #Endmethod

#Endclass

class Bullet(pygame.sprite.Sprite):
    # Define the constructor for Bullet
    def __init__(self, color, width, height):

        # Call the sprite constructor
        super().__init__()
        self.width = width
        self.height = height
        self.image = pygame.Surface([width,height])
        self.image.fill(color)
        # Set the position of the sprite
        self.rect = self.image.get_rect()
        self.rect.x = my_player.rect.x + (0.5 * my_player.width)
        self.rect.y = my_player.rect.y
        self.speed = 3

    def update(self):
        self.rect.y = self.rect.y - self.speed
        if self.rect.y < 0:
            bullet_group.remove(self)
        #Endif
    #Endmethod

#Endclass

# -- Exit game flag set to false
done = False

# Create a sprite group of the invaders
invader_group = pygame.sprite.Group()
# Create a sprite group of the bullets
bullet_group = pygame.sprite.Group()
# Create a sprite group of all sprites
all_sprites_group = pygame.sprite.Group()

# Create the Objects

number_of_invaders = 10
for count in range (number_of_invaders):
    my_invader = Invader(BLUE, 30, 30, 1, "enemy.jpg") # Invaders are blue with size 30 x 30 px
    invader_group.add(my_invader) # Adds the new invader to the group of invaders
    all_sprites_group.add(my_invader) # Adds it to the group of all Sprites
#Next count

my_invader2 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader3 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader4 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader5 = Invader(BLUE, 30, 30, 0, "enemy.jpg")
my_invader6 = Invader(BLUE, 30, 30, 0, "enemy.jpg")

my_player = Player(YELLOW, 15, 15, 5, 0, 200)
all_sprites_group.add(my_player) # Adds it to the group of all Sprites

# -- Manages how fast screen refreshes
clock = pygame.time.Clock()

### -- Game Loop
while not done and my_player.lives > 0:

    # -- User inputs here
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
        elif event.type == pygame.KEYDOWN: # - A key is down
            if event.key == pygame.K_LEFT: # - If the left key pressed
                my_player.player_set_speed(-4) # - Speed set to -4
            elif event.key == pygame.K_RIGHT: # - If the right key pressed
                my_player.player_set_speed(4) # - Speed set to 4
            elif event.key == pygame.K_UP: # - If up key is pressed, Alex's github opens
               #webbrowser.open_new_tab('https://github.com/alex-silcock/silcockaw-Y12-Computer-Science/commit/e7228fab2c1dd2e32832b558ee0dd0479c6049ba')
                pass
            elif event.key == pygame.K_SPACE: # - If space key is pressed
                if my_player.bullet_count > 0:
                    my_bullet = Bullet(RED, 2, 2) # - Bullet is created
                    bullet_group.add(my_bullet) # - Bullet is added to bullet_group
                    my_player.decrease_bcount() # - Bullet count decreases
                    all_sprites_group.add(my_bullet) # - Adds bullets to all sprites group
                #Endif
        elif event.type == pygame.KEYUP: # - A key released
            if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                my_player.player_set_speed(0) # Speed set to 0
                #Endif
            #Endif
        #Endif
    #Nextevent

    # -- Game logic goes after this comment
    if my_invader.rect.y == size[1] + 150:
        print("round2")
        number_of_invaders = 30
        for count in range (number_of_invaders):
            my_invader2 = Invader(BLUE, 30, 30, 1, "enemy.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader2) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader2) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader2.rect.y == size[1] + 150:
        print("round3")
        number_of_invaders = 10
        for count in range (number_of_invaders):
            my_invader3 = Invader(BLUE, 50, 50, 2, "enemy.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader3) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader3) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader3.rect.y == size[1] + 150 or my_invader3.rect.y == size[1] + 151:
        print("round3")
        number_of_invaders = 10
        for count in range (number_of_invaders):
            my_invader4 = Invader(BLUE, 45, 60, 1, "fiona.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader4) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader4) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader4.rect.y == size[1] + 150:
        print("round4")
        number_of_invaders = 10
        for count in range (number_of_invaders):
            my_invader5 = Invader(BLUE, 56, 75, 2, "Spence.jpg") # Invaders are blue with size 30 x 30 px
            invader_group.add(my_invader5) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader5) # Adds it to the group of all Sprites
        #Next count
    #Endif

    if my_invader5.rect.y == size[1] + 150 or my_invader5.rect.y == size[1] + 151:
        print("round5")
        pleasework = True
        number_of_invaders = 1
        for count in range (number_of_invaders):
            clock.tick(1)
            my_invader6 = Invader(BLUE, 636, 478, 1, "piano.jpeg") # Invaders are blue with size 30 x 30 px
            my_invader6.centralise()
            invader_group.add(my_invader6) # Adds the new invader to the group of invaders
            all_sprites_group.add(my_invader6) # Adds it to the group of all Sprites
        #Next count
    #Endif

    # -- When invader hits the player add 5 to score.
    player_hit_group = pygame.sprite.spritecollide(my_player, invader_group, True)
    for p in player_hit_group: #how does this work!?
        my_player.lives = my_player.lives - 1
    #nextp
    for b in bullet_group:
        invader_hit_group = pygame.sprite.spritecollide(b, invader_group, True)
        #if len(invader_hit_group) >= 2:
        #   invader_destroy_group = pygame.sprite.spritecollide(b, invader_group, True)
        for b in invader_hit_group:
            my_player.increase_score(5)
        #Nextb
    #Nextb

    all_sprites_group.update()

# -- Screen background is BLACK
    screen.fill(BLACK)

# -- Draw here
    all_sprites_group.draw(screen)
    draw_stats(screen, 10, 10, "Lives: %d" % my_player.lives)
    draw_stats(screen, 10, 40, "Score: %d" % my_player.score)
    draw_stats(screen, 10, 70, "Bullets: %d" % my_player.bullet_count)

# -- Flip display to reveal new position of objects
    pygame.display.flip()

# - The clock ticks over
    clock.tick(60)
    if pleasework == True:
        clock.tick(20)
#End While - End of game loop

pygame.quit()

#Shmuck's assemble ... we're shmuck's 1, 2 and 3, i like being me, and i like being free!
#Shmuck's assemble ... this is a little freestyle eee. We're shmuck's 1, 2 and 3, i like being me, and i like being free!


#This definition checks whether if the family instance is flipped or not
# and gives the list of elements that are flipped and a Boolean list for filtering in detail.

import clr
clr.AddReference('System.Core')
clr.AddReference('RhinoInside.Revit')
clr.AddReference('RevitAPI')
clr.AddReference('RevitAPIUI')

from System import Enum

import rhinoscriptsyntax as rs
import Rhino
import RhinoInside
import Grasshopper
from Grasshopper.Kernel import GH_RuntimeMessageLevel as RML
from RhinoInside.Revit import Revit, Convert
from Autodesk.Revit import DB

# access the active document object
doc = Revit.ActiveDBDocument

def show_warning(msg):
    ghenv.Component.AddRuntimeMessage(RML.Warning, msg)

def show_error(msg):
    ghenv.Component.AddRuntimeMessage(RML.Error, msg)

def show_remark(msg):
    ghenv.Component.AddRuntimeMessage(RML.Remark, msg)

Bools = []
IsMirrored = []
NotMirrored = []

Elements = Elements if isinstance(Elements, list) else [Elements]

for element in Elements:
    if element.Mirrored == True:
        Bools.append(True)
        IsMirrored.append(element)
    else:
        Bools.append(False)
        NotMirrored.append(element)


import requests
import pathlib
from dotenv import load_dotenv
from pathlib import Path
from general_functions import parse_arg_main
from general_functions import saving_img

def fetch_spacex_last_launch(file_dir, flight_id):
    url_template = "https://api.spacexdata.com/v5/launches/{}"
    url = url_template.format(flight_id)
    response = requests.get(url)
    response.raise_for_status()
    img_links = response.json()
    for img_number, img_link in enumerate(img_links
                                          ["links"]
                                          ["flickr"]
                                          ["original"]):
        img_name = f"spacex_{img_number}.jpg"
        file_path = Path(file_dir).joinpath(img_name)
        saving_img(img_link, file_path, img_name)

def main():
    load_dotenv()
    args = parse_arg_main()
    flight_id = args.flight
    file_dir = args.directory
    script_path = pathlib.Path.cwd()
    file_path = script_path.joinpath(file_dir)
    file_path.mkdir(exist_ok=True)
    fetch_spacex_last_launch(file_path, flight_id)

if __name__ == "__main__":
    main()


from collections import Counter
from typing import Iterator, List, Tuple

class School:

    def __init__(self, fish: str):

        self._school: List[int] = [
            int(fishy) for fishy
            in fish.split(',')
        ]

    def tick(self):

        ready_to_spawn: int = 0
        has_spawned: int = 6
        baby_fish: int = 8

        new_fish: List[int] = [
            baby_fish for fish
            in self._school
            if fish == ready_to_spawn
        ]

        self._school = [
            has_spawned
            if fish == ready_to_spawn
            else fish - 1
            for fish in self._school
        ]

        self._school.extend(new_fish)

    def simulate(self, ticks: int):

        for _ in range(ticks):
            self.tick()

        return len(self._school)

class FastSchool:

    def __init__(self, fish: str):

        self._school = {i:0 for i in range(9)}
        for fishy in fish.split(','):
            self._school[int(fishy)] += 1

    def tick(self):

        ready_to_spawn: int = 0
        has_spawned: int = 6
        new_fish: int = 8

        will_spawn: int = self._school[ready_to_spawn]
        #shift all the items down one day in the school
        for i in range(8):
            self._school[i] = self._school[i+1]

        self._school[has_spawned] += will_spawn
        self._school[new_fish] = will_spawn

    def simulate(self, ticks: int):

        for _ in range(ticks):
            self.tick()

        return sum(self._school.values())

def part1(fish: List[int]) -> int:

    return School(fish).simulate(ticks=80)

def part2(fish: List[str]) -> int:

    return FastSchool(fish).simulate(ticks=256)

with open('input') as f:
    fish = f.read().strip()

print(part1(fish)) #
print(part2(fish)) #


import re
from datetime import datetime

import pdfminer.high_level

import categories
from mail_api.abstract_mail_api import AbstractAttachment
from message_handler import MessageHandler
from utils import temporary_locale

class MusikHugMessageHandler(MessageHandler):
    def get_type(self):
        return categories.SUPPLIES

    def get_query_params(self):
        return {
            self.SUBJECT: "Ihre Bestellung wurde versandt",
            self.SENDER: "musikhug.ch",
        }

    def extract_txt(self, pdffile: str):
        with temporary_locale("de_CH"):
            text: str = pdfminer.high_level.extract_text(pdffile)
            purchase_date: str = re.search(
                r"\b(\d+\. (?:Januar|Februar|März|April|Mai|Juni|Juli|"
                r"August|September|Oktober|November|Dezember).\d\d\d\d)\b",
                text,
            )[1]
            self.purchase_date = datetime.strptime(purchase_date, "%d. %B %Y")
            self.amount = float(re.findall(r"\b(\d+\.\d+)\b", text)[-1])

    def handle_attachment(self, attachment: AbstractAttachment):
        pdffile: str = self.save(attachment)
        self.filename = attachment.get_filename()
        self.extract_txt(pdffile)


from EmotionModel import EmotionModel
import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import time
import torch.optim as optim
import torch
from dataset import get_data_deap,get_data_seed
from config import get_config

def train(Model, source_loader, target_loader):
    correct = 0
    train_correct=0.
    start_time = time.time()
    for (source_data, source_label),(target_data, target_label) in zip(source_loader,target_loader):
        optimizer.zero_grad()
        data_s, label_s = source_data[0].cuda(), source_label.cuda()
        data_t, label_t = target_data.cuda(), target_label.cuda()
        data=torch.cat([data_s,data_t],0)
        label=torch.cat([label_s,label_t],0)
        Model.fit_one_step(data,label,True)
        loss=Model.pred_loss+0.1*Model.walker_loss+Model.visit_loss+Model.domain_loss+Model.l2_loss
        loss.backward(retain_graph=False)
        optimizer.step()
        e_output = torch.argmax(Model.target_logits, dim=1)
        correct += torch.eq(e_output,Model.target_y.argmax(dim=1)).float().sum().item()
        train_correct+=Model.acc_nums.item()
    test_acc = round(correct / (len(target_loader.dataset)) * 100,3)
    train_acc = round(train_correct/ (len(source_loader.dataset)) * 100, 3)
    use_time = time.time() - start_time
    min = int(use_time // 60)
    sum = int(use_time % 60)
    print(f"Train Epoch: [{epoch}/{config.EPOCH}], Test Acc: {test_acc}, Train Acc: {train_acc} "
          f"Walker loss: {Model.walker_loss.item()}, Pred loss: {Model.pred_loss.item()}, Visit loss: {Model.visit_loss.item()}")
    return test_acc

if __name__ == '__main__':
    torch.cuda.empty_cache()
    total_log = []
    config=get_config()
    if config.DATA.DATASET == "deap":
        total = 32
    elif config.DATA.DATASET == "seed":
        total = 15
    else:
        raise NotImplementedError("not improve this dataset")
    for exp in range(1):
        exp = exp + 1
        subject_ACC = []
        for i in range(total):
            print('*' * 20+f'target subject: {i}'+'*'*20)
            index = np.arange(0, total, 1).tolist()
            del index[i]
            if config.DATA.DATASET == "deap":
                sample_path = config.DATA.DEAP_DATA_PATH
                source_loader, target_loader = get_data_deap(sample_path=sample_path,
                                                             index=index,
                                                             i=i,
                                                             num_classes=config.MODEL.DEAP.NUM_CLASSES,
                                                             batchsize=config.MODEL.DEAP.BATCH_SIZE)
                Model = EmotionModel(config.MODEL.DEAP.OUT*config.MODEL.DEAP.TIME_DIM,config.MODEL.DEAP.NUM_CLASSES).cuda()
                optimizer = optim.Adam(
                    # [{'params': Model.linear1.weight, 'weight_decay': 0.001},
                    #  {'params': Model.linear2.weight, 'weight_decay': 0.001},
                    #  {'params': Model.linear3.weight, 'weight_decay': 0.001},
                    #  {'params': Model.linear1.bias},
                    #  {'params': Model.linear2.bias},
                    #  {'params': Model.linear3.bias},]
                    Model.parameters(), lr=2*0.0001
                )

            elif config.DATA.DATASET == "seed":
                sample_path = config.DATA.SEED_DATA_PATH
                source_loader, target_loader = get_data_seed(sample_path=sample_path,
                                                             index=index,
                                                             i=i,
                                                             num_classes=config.MODEL.SEED.NUM_CLASSES,
                                                             batchsize=config.MODEL.SEED.BATCH_SIZE)
                Model = EmotionModel(config.MODEL.SEED.OUT * config.MODEL.SEED.TIME_DIM, config.MODEL.SEED.NUM_CLASSES).cuda()
                optimizer = optim.Adam(
                    # [{'params': Model.linear1.weight, 'weight_decay': 0.001},
                    #  {'params': Model.linear2.weight, 'weight_decay': 0.001},
                    #  {'params': Model.linear3.weight, 'weight_decay': 0.001},
                    #  {'params': Model.linear1.bias},
                    #  {'params': Model.linear2.bias},
                    #  {'params': Model.linear3.bias},]
                    Model.parameters(), lr=2*0.0001
                )

            else:
                raise NotImplementedError("not improve this dataset")
            total_test_acc=[]
            for epoch in range(1, config.EPOCH + 1):
                p = float(i) / epoch
                l = 2. / (1. + np.exp(-10. * p)) - 1
                lr = 0.0045 / (1. + 15 * p) ** 0.75
                Model.alpha=l
                if config.MODEL.IF_TURN_LR:
                    for param_group in optimizer.param_groups:
                        param_group['lr'] = lr
                test_acc=train(Model, source_loader, target_loader)
                total_test_acc.append(test_acc)
            subject_ACC.append(total_test_acc)
    for i in range(config.EPOCH):
        acc=np.array([subject_ACC[j][i] for j in range(total)]).mean()
        print(f"EPOCH {i} ,ACC {acc}")


import torch.nn as nn
from torch.nn.utils import spectral_norm
from torch.nn.functional import pad
import torch

class DnCNN(nn.Module):
    def __init__(self, dimension, depth=13, n_channels=64, i_nc=1, o_nc=1, kernel_size=3, is_batch_normalize=False, is_residual=True):

        self.is_residual = is_residual

        if dimension == 2:
            conv_fn = nn.Conv2d
            bn_fn = nn.BatchNorm2d

        elif dimension == 3:
            conv_fn = nn.Conv3d
            bn_fn = nn.BatchNorm3d

        else:
            raise ValueError()

        super().__init__()
        padding = kernel_size // 2

        layers = [
            spectral_norm(conv_fn(
                in_channels=i_nc,
                out_channels=n_channels,
                kernel_size=kernel_size,
                padding=padding,
                bias=False)),
            nn.ReLU(inplace=True)
        ]

        for _ in range(depth - 1):
            layers.append(spectral_norm(conv_fn(
                in_channels=n_channels,
                out_channels=n_channels,
                kernel_size=kernel_size,
                padding=padding,
                bias=False if is_batch_normalize else True)))

            if is_batch_normalize:
                layers.append(bn_fn(n_channels))

            layers.append(nn.ReLU(inplace=True))

        layers.append(
            spectral_norm(conv_fn(
                in_channels=n_channels,
                out_channels=o_nc,
                kernel_size=kernel_size,
                padding=padding,
                bias=False)))

        self.net = nn.Sequential(*layers)

    def forward(self, x):

        input_ = x

        x = self.net(x)

        ret = input_ - x if self.is_residual else x

        return ret

activation_fn = {
    'relu': lambda: nn.ReLU(inplace=True),
    'lrelu': lambda: nn.LeakyReLU(inplace=True),
    'prelu': lambda: nn.PReLU()
}

class ConvBnActivation(nn.Module):
    def __init__(self, in_channels, out_channels, dimension=2, times=1, is_bn=False, activation='relu', kernel_size=3, is_spe_norm=False):
        super().__init__()

        if dimension == 3:
            conv_fn = lambda in_c: torch.nn.Conv3d(in_channels=in_c,
                                                   out_channels=out_channels,
                                                   kernel_size=kernel_size,
                                                   padding=kernel_size // 2
                                                   )
            bn_fn = lambda: torch.nn.BatchNorm3d(out_channels)

        elif dimension == 2:
            conv_fn = lambda in_c: torch.nn.Conv2d(in_channels=in_c,
                                                   out_channels=out_channels,
                                                   kernel_size=kernel_size,
                                                   padding=kernel_size // 2
                                                   )
            bn_fn = lambda: torch.nn.BatchNorm2d(out_channels)
        else:
            raise ValueError()

        layers = []
        for i in range(times):
            if i == 0:
                layers.append(spectral_norm(conv_fn(in_channels)) if is_spe_norm else conv_fn(in_channels))
            else:
                layers.append(spectral_norm(conv_fn(out_channels)) if is_spe_norm else conv_fn(out_channels))

            if is_bn:
                layers.append(bn_fn())

            if activation is not None:
                layers.append(activation_fn[activation]())

        self.net = nn.Sequential(*layers)

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

class ConvtranBnActivation(nn.Module):
    def __init__(self, in_channels, out_channels, dimension=2, is_bn=False, activation='relu', kernel_size=3, is_spe_norm=False):
        self.is_bn = is_bn
        super().__init__()
        if dimension == 3:
            conv_fn = lambda: torch.nn.ConvTranspose3d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=kernel_size,
                stride=(1, 2, 2),
                padding=kernel_size // 2,
                output_padding=(0, 1, 1)
            )
            bn_fn = lambda: torch.nn.BatchNorm3d(out_channels)

        elif dimension == 2:
            conv_fn = lambda: torch.nn.ConvTranspose2d(
                in_channels=in_channels,
                out_channels=out_channels,
                kernel_size=kernel_size,
                stride=2,
                padding=kernel_size // 2,
                output_padding=1
            )
            bn_fn = lambda: torch.nn.BatchNorm2d(out_channels)
        else:
            raise ValueError()

        self.net1 = spectral_norm(conv_fn()) if is_spe_norm else conv_fn()
        if self.is_bn:
            self.net2 = bn_fn()
        self.net3 = activation_fn[activation]()

    def forward(self, x):
        ret = self.net1(x)
        if self.is_bn:
            ret = self.net2(ret)

        ret = self.net3(ret)

        return ret

class UNet(nn.Module):
    def __init__(self, dimension, i_nc=1, o_nc=1, f_root=32, conv_times=3, is_bn=False, activation='relu',
                 is_residual=False, up_down_times=3, is_spe_norm=False, padding=(1, 4)):

        self.is_residual = is_residual
        self.up_down_time = up_down_times
        self.dimension = dimension
        self.padding = padding

        super().__init__()

        if dimension == 2:
            self.down_sample = nn.MaxPool2d((2, 2))
        elif dimension == 3:
            self.down_sample = nn.MaxPool3d((1, 2, 2))
        else:
            raise ValueError()

        self.conv_in = ConvBnActivation(
            in_channels=i_nc,
            out_channels=f_root,
            is_bn=is_bn,
            activation=activation,
            dimension=dimension,
            is_spe_norm=is_spe_norm
        )

        self.conv_out = ConvBnActivation(
            in_channels=f_root,
            out_channels=o_nc,
            kernel_size=1,
            dimension=dimension,
            times=1,
            is_bn=False,
            activation=None,
            is_spe_norm=is_spe_norm
        )

        self.bottom = ConvBnActivation(
            in_channels=f_root * (2 ** (up_down_times - 1)),
            out_channels=f_root * (2 ** up_down_times),
            times=conv_times, is_bn=is_bn, activation=activation, dimension=dimension,
            is_spe_norm=is_spe_norm
        )

        self.down_list = nn.ModuleList([
                                           ConvBnActivation(
                                               in_channels=f_root * 1,
                                               out_channels=f_root * 1,
                                               times=conv_times, is_bn=is_bn, activation=activation,
                                               dimension=dimension,
                                               is_spe_norm=is_spe_norm
                                           )
                                       ] + [
                                           ConvBnActivation(
                                               in_channels=f_root * (2 ** i),
                                               out_channels=f_root * (2 ** (i + 1)),
                                               times=conv_times, is_bn=is_bn, activation=activation,
                                               dimension=dimension,
                                               is_spe_norm=is_spe_norm
                                            )
                                           for i in range(up_down_times - 1)
                                       ])

        self.up_conv_list = nn.ModuleList([
            ConvBnActivation(
                in_channels=f_root * (2 ** (up_down_times - i)),
                out_channels=f_root * (2 ** (up_down_times - i - 1)),
                times=conv_times, is_bn=is_bn, activation=activation, dimension=dimension,
                is_spe_norm=is_spe_norm
            )
            for i in range(up_down_times)
        ])

        self.up_conv_tran_list = nn.ModuleList([
            ConvtranBnActivation(
                in_channels=f_root * (2 ** (up_down_times - i)),
                out_channels=f_root * (2 ** (up_down_times - i - 1)),
                is_bn=is_bn, activation=activation, dimension=dimension,
                is_spe_norm=is_spe_norm
            )
            for i in range(up_down_times)
        ])

    def forward(self, x):

        input_ = x

        x = pad(x, [0, self.padding[0], 0, self.padding[1]])

        x = self.conv_in(x)

        skip_layers = []
        for i in range(self.up_down_time):
            x = self.down_list[i](x)

            skip_layers.append(x)
            x = self.down_sample(x)

        x = self.bottom(x)

        for i in range(self.up_down_time):
            x = self.up_conv_tran_list[i](x)
            x = torch.cat([x, skip_layers[self.up_down_time - i - 1]], 1)
            x = self.up_conv_list[i](x)

        x = self.conv_out(x)

        if self.padding[0] > 0:
            x = x[..., :-self.padding[0]]
        if self.padding[1] > 0:
            x = x[..., :-self.padding[1], :]

        # x = x[..., :-self.padding[1], :-self.padding[0]]

        ret = input_ - x if self.is_residual else x

        return ret


import numpy as np
import matplotlib.pyplot as plt
from prettytable import PrettyTable
import math

fig, ax = plt.subplots()

data_table = PrettyTable()
data_table.field_names = ["iterations", "estimation", "error%", "f(estimation)"]

def func(x):
    return ((x / (1 - x)) * ((6 / (2 + x)) ** .5)) - 0.05

def differentiation_func(x):
    return ((6 ** .5) * (x ** 2 + x + 4)) / (2 * ((x - 1) ** 2) * ((x + 2) ** 1.5))

def draw_graph():
    ax.spines['left'].set_position(('data', 0))
    ax.spines['bottom'].set_position(('data', 0))
    plt.grid(b=True, which='major', linestyle='-')
    plt.minorticks_on()
    plt.grid(b=True, which='minor', linestyle='-', alpha=0.3)
    plt.margins(x=0, y=0)

    x_val = np.linspace(-.5, .5, 2000)
    y_val = func(x_val)
    plt.plot(x_val, y_val, 'g--')
    plt.title('f(x)')

def newton_raphson(est, approx_err, max_iter):
    new_est = 0
    for i in range(max_iter):
        new_est = est - func(est) / differentiation_func(est)
        new_err = math.fabs((new_est - est) / new_est) * 100
        if new_err < approx_err:
            plt.show()
            return new_est

        a = [est, new_est]
        b = [func(est), 0]
        plt.plot(a, b, 'b')

        est = new_est

    plt.show()
    return new_est

def show_table(est, max_iter):
    for i in range(max_iter):
        new_est = est - func(est) / differentiation_func(est)
        new_err = math.fabs((new_est - est) / new_est) * 100
        data_table.add_row([i + 1, new_est, new_err, func(new_est)])

        est = new_est

    print(data_table)

if __name__ == "__main__":
    draw_graph()
    print("root of the eqn: ", newton_raphson(.5, .5, 20))
    show_table(.5, 20)

1.Non linear Eqn Solve/code/1805004_Week 4/newton_raphson.py


#    Znajdowanie najkrótszej trasy komiwojażera dla 51 dużych miast w Polsce
#    Napisane na potrzeby wykładu popularnonaukowego w ramach Festiwalu Nauki oraz artykułu dla miesięcznika Delta

#    Copyright (C) Łukasz Kowalik 2019, Uniwersytet Warszawski, Wydział Matematyki, Informatyki i Mechaniki.

#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <https://www.gnu.org/licenses/>.

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import csv
from pulp import *

# inicjalizujemy mapowanie współrzędnych geograficznych
map = Basemap(llcrnrlon=13,llcrnrlat=48.5,urcrnrlon=25,urcrnrlat=55,
             resolution='i', projection='tmerc', lat_0 = 52, lon_0 = 19)

# wczytujemy współrzędne i nazwy 51 miast
with open('data/polska-51-coor.csv',encoding='utf-8') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    cities = []
    coor = []
    pos = []
    for row in readCSV:
        cities.append(row[0])
        x,y = map(float(row[2]),float(row[1]))
        coor.append((x,y))
        pos.append((row[3],row[4]))

# wczytujemy tabelę odległości drogowych
with open('data/polska-51-dist.csv',encoding='utf-8') as csvfile:
    readCSV = csv.reader(csvfile, delimiter=',')
    first = True
    dist = []
    for row in readCSV:
        if first:
            first = False
        else:
            num_row = []
            for s in row[1:]:
                num_row.append(float(s))
            dist.append (num_row)

n = len(cities)

sym = [[(min(i,j),max(i,j)) for j in range (n)] for i in range (n)]

# definiujemy program liniowy
prob = LpProblem("TSP", LpMinimize)

# nasz program ma zmiaenną x_(i,j) dla każdego 0<=i<j<=n, o wartościach w przedziale [0,1]
var = LpVariable.dicts("x", [(i,j) for i in range(n) for j in range(i+1,n)], 0, 1, cat="Continuous")

# funkcja celu
prob += lpSum(dist[i][j]*var[(i,j)] for i in range(n) for j in range(i+1,n))

# warunki, które mówią, że suma wszystkich zmiennych dla połączeń o końcu w jednym mieście wynosi 2
for i in range(n):
    prob += lpSum(var[sym[i][j]] for j in range(n) if j != i) == 2

done = False
cnt = 0

def iter():

    global cnt,sym,cities,coor,prob,fig,plt

    if cnt < 5: cnt += 1
    if cnt == 2:
        #krok 2: dodajemy 7 warunków eliminacji podtras
        for S in [[14,33,41],[2,6,13],[32,34,18],[17,24,42,48],[12,15,36],[4,21,49],[11,44,19]]:
            prob += lpSum (var[sym[S[i]][S[j]]] for i in range(len(S)) for j in range(i+1,len(S))) <= len(S) - 1
    elif cnt == 3:
        #krok 3: dodajemy 2 warunki eliminacji podtras
        for S in [[2,6,13,17,42,24,48],[4,21,0,35,45,37,33,14,41,34,18,32,49]]:
            prob += lpSum (var[sym[S[i]][S[j]]] for i in range(len(S)) for j in range(i+1,len(S))) <= len(S) - 1
    elif cnt == 4:
        #krok 4: dodajemy 1 warunek eliminacji podtras
        for S in [[11,19,44,47]]:
            prob += lpSum (var[sym[S[i]][S[j]]] for i in range(len(S)) for j in range(i+1,len(S))) <= len(S) - 1
    elif cnt == 5:
        #krok 5: dodajemy warunek 2-skojarzeniowy
        for (H,T) in [([19,20,50],[(19,11),(50,10),(20,31)])]:
            prob += lpSum (var[sym[H[i]][H[j]]] for i in range(len(H)) for j in range(i+1,len(H))) + \
                    lpSum (var[sym[i][j]] for (i,j) in T) <= len(H) + len(T) // 2

    #rozwiązywanie programu liniowego
    prob.solve()

    # wczytywanie konturu Polski
    fig.clear()
    map.readshapefile("data/gadm36_POL_0", "Poland", linewidth=1)

    n = len(cities)

    # rysowanie trasy
    for i in range(n):
        for j in range(i+1,n):
            if var[(i,j)].varValue == 1:
                plt.plot([coor[i][0], coor[j][0]],[coor[i][1], coor[j][1]],color='black',lw=1)
            elif var[(i,j)].varValue == 0.5:
                plt.plot([coor[i][0], coor[j][0]],[coor[i][1], coor[j][1]],linestyle='dashed',color='red',lw=1)
            elif var[(i,j)].varValue > 0:
                plt.plot([coor[i][0], coor[j][0]],[coor[i][1], coor[j][1]],color='blue',lw=1)

    for i in range(n):
        if cnt < 5:
            map.plot(coor[i][0],coor[i][1],marker='o',color='black',mfc="white",markersize=11)
            plt.text(coor[i][0],coor[i][1]-3000, str(i),fontsize=8,ha="center",va="center",color='black',stretch='condensed')
        else:
            map.plot(coor[i][0],coor[i][1],marker='o',color='black',markersize=3)
            plt.text(coor[i][0],coor[i][1], cities[i],fontsize=8,ha=pos[i][0],va=pos[i][1],color='black',stretch='condensed')
            fig.canvas.set_window_title('Znaleziono trasę optymalną. Zamnij okno.')

    ax = plt.gca()
    ax.axis('off')
    plt.text(0.2,0.1,str(round(value(prob.objective),3))+" km", color='black',transform=ax.transAxes)

    fig.canvas.draw()
    fig.savefig("tsp"+str(cnt)+".pdf", bbox_inches='tight')

def press(event):
    sys.stdout.flush()
    iter()

fig = plt.figure(frameon = False)
fig.canvas.set_window_title('Naciśnij dowolny klawisz aby wykonać kolejny krok')
fig.canvas.mpl_connect('key_press_event', press)
plt.show()


import discord
import os
from keep_alive import keep_alive

client = discord.Client()

@client.event
async def on_ready():
  print('Im logged in as  {0.user}'.format(client))

@client.event
async def on_message(message):
  if message.author == client.user:
    return

    #add custom cmds here
  if message.content.startswith('!hello'):
    await message.channel.send('https://tenor.com/view/hello-gif-19947459')

keep_alive()
client.run(os.getenv('DISCORD_TOKEN'))


import numpy as np
import cv2

def quantizeHSV(origImg, k):

  hsv_image = cv2.cvtColor(origImg, cv2.COLOR_RGB2HSV)
  hsv_flat = np.float32(hsv_image.reshape((-1, 3)))

  hue  = hsv_flat[:,0].copy()

  #kmeans algo
  criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 500, 0.2)
  _, labels, (meanHues) = cv2.kmeans(hue, k,None ,criteria = criteria , attempts = 10, flags = cv2.KMEANS_RANDOM_CENTERS)
  meanHues = np.uint8(meanHues)
  labels = labels.flatten()
  hsv  = meanHues[labels.flatten()]
  ####################

  hsv_flat[:,0] = hsv.flatten()
  hsv_flat = np.uint8(hsv_flat)
  outputImg = hsv_flat.reshape(origImg.shape)
  outputImg = cv2.cvtColor(outputImg, cv2.COLOR_HSV2RGB)

  return outputImg , meanHues