'''
6 April 2020

Python file that contains the custom algorithm that finds the most optimal source/sink pair

and the most useful voltage measurement electrode pairs.

by Ivo Mihov and Vasil Avramov

in collaboration with Artem Mischenko and Sergey Slizovskiy

from Solid State Physics Group

at the University of Manchester

'''

import numpy as np
import meshing
import cupy as cp
from pyeit.eit.fem import Forward as FEM_normal
from pyeit.eit.fem_forallmeas import Forward
from pyeit.eit.fem_for_given_meas import Forward as FEM
import h5py as h5
import greit_rec_training_set as train

def volt_mat(ne):
	#generates all possible pairs of voltage measurements
	step_arr = cp.arange(ne)
	parser = None
	A = cp.arange(ne)
	M = cp.dot(cp.ones(ne)[:,None], A[None, :]) % ne
	N = (M + step_arr[:, None]) % ne
	pair_mat = cp.stack((N, M), axis=-1)
	pair_mat = pair_mat.reshape(((ne)**2, 2))

	ind = pair_mat[:,0] < pair_mat[:, 1]

	return pair_mat[ind].astype(int)

def get_total_map(rec, voltages, h_mat, npix=64, pert=0.5, p_influence=-10., p_rec=10.):
	v_pert = np.empty(shape=(len(voltages), len(voltages)))
	perturbing_mat = np.ones((len(voltages), len(voltages))) + pert * np.identity(len(voltages))
	v_pert[:] = np.dot(perturbing_mat, np.diag(voltages))
	influence_mat = -np.dot(h_mat, v_pert).reshape(npix, npix, len(voltages)) - rec[:, :, None]
	influence_mat = np.absolute(influence_mat)
	influence_mat = np.sum(influence_mat, axis=2)
	grad_mat =  np.linalg.norm(np.gradient(rec), axis = 0)

	if np.amin(rec) <= -1.:
		rec = - rec / np.amin(rec)

	rec = np.log(rec + 1.0000001)
	#rec[(rec < 1.e-3) * (rec > 0.)] = 1.e-3
	#rec[(rec > -1.e-3) * (rec < 0.)] = -1.e-3
	#p_influence /= 1e3
	return grad_mat * influence_mat ** p_influence * rec ** p_rec, grad_mat, rec

def get_centre_squares(npix=64, a = 2., centre=None):

	if centre is None:
		centre = [0, 0]
	C_sq = np.empty((npix, npix, 2), dtype='f4')
	# initialising the j vector to prepare for tiling
	j = np.arange(npix)
	# tiling j to itself npix times (makes array shape (npix, npix))
	j = np.tile(j, (npix, 1))
	# i and j are transposes of each other
	i = j
	j = j.T
	# assigning values to C_sq
	C_sq[i, j, :] = np.transpose([a / 2 * ((2 * i + 1) / npix - 1) + centre[0], a / 2 * ((2 * j + 1) / npix - 1) + centre[1]])

	return C_sq

def find_all_distances(rec, h_mat, el_coords, n_el, a = 2., npix = 64, cutoff = 0.8):

	c_sq = get_centre_squares(npix = 64, a = 2.)
	#print(el_coords)
	if el_coords.shape[0] > n_el:
		el_coords = np.mean(el_coords.reshape((n_el, int(el_coords.shape[0] / n_el), 2)), axis=1)
	#print(el_coords)
	all_meas_pairs = cp.asnumpy(volt_mat(n_el))
	#print(all_meas_pairs.shape)
	const_X_index = ( (el_coords[all_meas_pairs[:, 0], 0] - el_coords[all_meas_pairs[:, 1], 0]) == 0 )
	const_Y_arr = np.sort(el_coords[all_meas_pairs[const_X_index], 1], axis=1)

	all_slopes = np.empty(all_meas_pairs.shape[0])
	all_const =  np.empty(all_meas_pairs.shape[0])
	all_slopes[~const_X_index] = (el_coords[all_meas_pairs[~const_X_index, 0], 1] - el_coords[all_meas_pairs[~const_X_index, 1], 1]) / (
					el_coords[all_meas_pairs[~const_X_index, 0], 0] - el_coords[all_meas_pairs[~const_X_index, 1], 0])
	all_const[~const_X_index] = el_coords[all_meas_pairs[~const_X_index, 1], 1] - el_coords[all_meas_pairs[~const_X_index, 1], 0] * all_slopes[~const_X_index]

	p_st = np.empty(shape=(all_meas_pairs.shape[0],2))
	p_st[:, 0] = np.amin(el_coords[all_meas_pairs,0], axis = 1)
	p_st[:, 1] = all_slopes * p_st[:, 0] + all_const

	p_st[const_X_index, 0] = el_coords[all_meas_pairs[const_X_index][:, 0], 0]
	p_st[const_X_index, 1] = const_Y_arr[:, 0]

	p_end = np.empty(shape=(all_meas_pairs.shape[0],2))
	p_end[:, 0] = np.amax(el_coords[all_meas_pairs,0], axis = 1)
	p_end[:, 1] = all_slopes * p_end[:, 0] + all_const

	p_end[const_X_index, 0] = el_coords[all_meas_pairs[const_X_index][:, 0], 0]
	p_end[const_X_index, 1] = const_Y_arr[:, 1]

	indices = (np.abs(np.cross((p_end - p_st)[:, None, None, :],
								   np.transpose(np.array([p_st[:, 0][:, None, None] - c_sq[None, :, :, 0],
								   			 p_st[:, 1][:, None, None] - c_sq[None, :, :, 1]]), axes=(1, 2, 3, 0)))
					   / np.linalg.norm(p_end - p_st, axis=1)[:, None, None])
					   < a / (npix * np.sqrt(2)))

	return indices, all_meas_pairs

def findNextPair(fileJac, ne, anomaly=None, el_dist=None, meas=None, a=2., npix=64, pert=0.5, p_influence=-10., p_rec=10.):
	# find indices in the already calculated const. permitivity Jacobian (CPJ)
	if meas is None:
		if el_dist is None:
			el_dist = np.random.randint(1, 20)
		A = cp.arange(ne)
		B = (cp.arange(ne) + el_dist) % ne
		ex_mat = cp.stack((A, B), axis=1)
		#test to see how different excitation matrices will affect the sensitivity in different areas
		#even_ind = (np.arange((len(A))) % 2) == 0
		#ex_mat = ex_mat[even_ind]

		volt_mat, ex_mat, ind_new = voltMeterwStep(ne, ex_mat, step_arr=10)
		measurements = cp.concatenate((ex_mat, volt_mat), axis=1)
	else:
		measurements = meas
	#print(measurements)
	rec, h_mat, voltages, volt_const, tr, num = simulateMeasurements(fileJac, anomaly=anomaly, measurements=measurements)
	#volts = volts.reshape((len(volts), 1))

	v_pert = np.empty(shape=(len(voltages), len(voltages)))
	perturbing_mat = np.ones((len(voltages), len(voltages))) + pert * np.identity(len(voltages))
	v_pert[:] = np.dot(perturbing_mat, np.diag(voltages))
	influence_mat = -np.dot(h_mat, v_pert).reshape(npix, npix, len(voltages)) - rec[:, :, None]
	influence_mat = np.absolute(influence_mat)
	influence_mat = np.sum(influence_mat, axis=2)

	_, el_coords = meshing.fix_electrodes_multiple(centre=None, edgeX=0.1, edgeY=0.1, a=2, b=2, ppl=ne, el_width=0.2, num_per_el=3)
	pixel_indices, voltage_all_possible = find_all_distances(rec, h_mat, el_coords, 20, cutoff = 0.8)
	total_map, grad_mat, rec_log = np.abs(get_total_map(rec, voltages, h_mat, pert=pert, p_influence=p_influence, p_rec=p_rec))
	'''
	plt.figure(3)
	im3 = plt.imshow(grad_mat.astype(float), cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1])
	plt.title("Gradient of reconstruction")
	plt.colorbar(im3)
	plt.figure(4)
	im4 = plt.imshow(rec_log.astype(float), cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1])
	plt.title("Reconstruction logarithmic")
	plt.colorbar(im4)
	plt.figure(5)
	im5 = plt.imshow(influence_mat.astype(float), cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1])
	plt.title("Influence Map")
	plt.colorbar(im5)
	plt.figure(6)
	im6 = plt.imshow(total_map.astype(float), cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1])
	plt.title("Total Map")
	plt.colorbar(im6)'''

	total_maps_along_lines = total_map[None] * pixel_indices
	proximity_to_boundary = np.sum(total_maps_along_lines, axis=(1, 2)) / np.sum(pixel_indices, axis=(1, 2))
	proposed_ex_line = voltage_all_possible[np.argsort(proximity_to_boundary)[::-1]][:10]
	#print(proposed_ex_line)

	#volt_measurements = findNextVoltagePair(proposed_ex_line, fileJac, total_map, npix, 0.85)

	'''
	# optional: weight the sensitivity by its distance from the center to avoid focusing only on edge areas
	xm = np.arange(64)
	xm, ym= np.meshgrid(xm, xm)
	print(xm, ym)
	xm = (xm * a / npix + a / (2 * npix)) - a / 2
	ym = (ym * a / npix + a / (2 * npix)) - a / 2
	weight = xm**2 + ym**2
	print(weight[30:34, 30:34])
	influence_mat *= weight

	# old measurement selection
	zones = np.less(influence_mat, 2 * np.amin(influence_mat))
	#zones = np.greater(influence_mat, np.amax(influence_mat)/1.2)
	zone_index = np.where(zones)

	zone_index = np.concatenate((zone_index[1][:, None], zone_index[0][:, None]), axis=1)
	zone_coords = (zone_index * a / npix + a / (2 * npix)) - a / 2
	avg_coords = np.mean(zone_coords, axis=0)
	closest = np.argsort(np.linalg.norm(zone_coords - avg_coords[None], axis=1))
	closest_coords = zone_coords[closest[:3]]

	# for one coordinate
	closest_coords = np.array(np.where(influence_mat == np.amin(influence_mat)))
	closest_coords = (closest_coords * a / npix + a / (2 * npix)) - a / 2
	chosen_pair = findMinimumTriArea(closest_coords)
	'''
	#plt.show()
	'''
	plt.plot(closest_coords[:, 0], closest_coords[:, 1], 'rx')
	plt.plot(avg_coords[0], avg_coords[1], 'gx')
	plt.show()'''
	return proposed_ex_line, rec, tr, num, total_map

def findNextVoltagePair(new_ex_line, jac_file, total_map, number_of_voltages, counter, npix=64, cutoff=0.97):

	file = h5.File(jac_file, 'r')
	p = file['p'][()]
	t = file['t'][()]
	jac = file['jac'][()]
	meas = file['meas'][()]
	file.close()
	#region of interest index
	roi_index = total_map > cutoff * np.amax(total_map)
	C_sq = get_centre_squares()
	square_to_tri_index = np.empty((npix, npix,  t.shape[0]), dtype=bool)
	C_tri = np.mean(p[t], axis=1)
	distance_all = np.linalg.norm(C_sq[:, :, None] - C_tri[None, None, :], axis=3)
	weight = 1./(1 + np.exp(1.*(distance_all - 0.)))
	weight[~roi_index] = 0.
	weight_on_each_tri = np.sum(weight, (0, 1))
	new_ex_line = np.sort(new_ex_line)
	index_source = new_ex_line[0] == meas[:, 0]
	index_sink = new_ex_line[1] == meas[:, 1]
	index_current = index_source * index_sink
	#assert np.sum(index_current) == (n_el - 2) * (n_el - 3) / 2
	jac_of_interest = jac[index_current]
	jac_weighted = jac_of_interest * weight_on_each_tri[None, :]
	voltage_pair_initial_index = np.argsort(np.sum(jac_weighted, axis=1))[::-1]
	#print(meas[index_current][voltage_pair_initial_index])
	voltage_measurement_predictions = meas[index_current, 2:][voltage_pair_initial_index]
	#print(voltage_measurement_predictions)
	return meas[index_current, 2:][voltage_pair_initial_index][int(counter * number_of_voltages) : int((counter + 1) * number_of_voltages)]

def circleMask(npix, a, pc=[0, 0]):
	C_sq = np.empty((npix, npix, 2), dtype='f4')
	j = np.arange(npix)
	j = np.tile(j, (npix, 1))
	i = j
	j = j.T
	C_sq[i, j, :] = np.transpose([a / 2 * ((2 * i + 1) / npix - 1) + pc[0], a / 2 * ((2 * j + 1) / npix - 1) + pc[1]])
	mask = np.power(C_sq[:, :, 0], 2) + np.power(C_sq[:, :, 1], 2) < np.power(a/2, 2)

	return mask

def findMinimumTriArea(closest_coords):
	el_coords = train.fix_electrodes(edgeX=0.2, edgeY=0.2, a=2, b=2, ppl=20)[1]
	ex_mat_all = train.generateExMat(ne=20)
	coord_mat = el_coords[ex_mat_all]

	#tri_area_all = np.empty(len(ex_mat_all))
	'''
	# for one coordinate
	tri_area = 0.5 * np.absolute(coord_mat[:, 0, 0] * (coord_mat[:, 1, 1] - closest_coords[0]) - coord_mat[:, 0, 1] * (coord_mat[:, 1, 0] - closest_coords[1]) + coord_mat[:, 1, 0]*closest_coords[0] - coord_mat[:, 1, 1] * closest_coords[1] )
	min_area_ind  = np.argsort(tri_area)
	'''
	tri_area_sum = np.sum(0.5 * np.absolute(coord_mat[:, None, 0, 0] * (coord_mat[:, None, 1, 1] - closest_coords[None, :, 1]) - coord_mat[:, None, 0, 1] * (coord_mat[:, None, 1, 0] - closest_coords[None, :, 0]) + coord_mat[:, None, 1, 0]*closest_coords[None, :, 1] - coord_mat[:, None, 1, 1] * closest_coords[None, :, 0] ), axis=1)
	#print(np.array_equal(tri_area_all[:, 1], tri_area))
	min_area_ind = np.argsort(tri_area_sum)

	ex_mat_pred = ex_mat_all[min_area_ind[:10]]
	#print('Next src/sink recommendation (from 1 to n_el starting from upper left corner clockwise):', ex_mat_pred + 1)
	return ex_mat_pred

def voltMeterwStep(ne, ex_mat, step_arr=None, parser=None):
    '''

    Returns all measurements with this step_arr and ex_mat

    takes:

    ex_mat - array shape (n_source/sinks, 2) - excitation matrix with source and sink for each measurement
    step_arr - array shape (n_source/sinks) - step between measuring electrodes for each source/sink pair
    parser - string

    returns:

    pair_mat - array shape (n_measurements, 2) - matrix with all possible meas. electrode combinations
    ind_new - array shape (n_measurements) - helper array

    '''
    if step_arr is None:
        step_arr = 1 + cp.arange((ex_mat.shape[0])) % (ne)
    elif type(step_arr) is int:
    	step_arr = step_arr * cp.ones(ex_mat.shape[0]) % ne

    drv_a = ex_mat[:, 0]
    drv_b = ex_mat[:, 1]
    i0 = drv_a if parser == 'fmmu' else 0
    A = cp.arange(ne)

    #M = cp.dot(cp.ones(ex_mat.shape[0])[:,None], A[None, :]) % self.ne
    #N = (M + step_arr[:, None]) % self.ne

    M = cp.arange(ex_mat.shape[0] * ne) % ne
    N = (M.reshape((ex_mat.shape[0], ne)) + step_arr[:, None]) % ne
    pair_mat = cp.stack((N.ravel(), M), axis=-1)

    #ind_new = cp.arange(pair_mat.shape[0]) % ex_mat.shape[0]
    ind_new = cp.arange(ex_mat.shape[0])
    ind_new = cp.tile(ind_new, (ne, 1)).T.ravel()
    #print('before indtest', ind_new[20:70])
    nz2 = cp.where(pair_mat == drv_a[ind_new, None])
    nz3 = cp.where(pair_mat == drv_b[ind_new, None])
    #print(ind_new)
    ind_ = cp.arange(pair_mat.shape[0])
    ind_fin = cp.sum(ind_[:, None] == nz2[0][None], axis=1)
    ind_fin2 = cp.sum(ind_[:, None] == nz3[0][None], axis=1)

    ind_test = cp.less((ind_fin + ind_fin2), 0.5 * cp.ones(len(ind_fin)))

    pair_mat = pair_mat[ind_test, :]
    ind_new = ind_new[ind_test]
    sort_index = cp.argsort(ind_new)

    #print('after indtest', ind_new[20:70])
    #meas = cp.concatenate((ex_mat[ind_new], pair_mat), axis=1)
    #print(meas[20:70])
    return pair_mat, ex_mat[ind_new], ind_new

def simulateMeasurements(fileJac, anomaly=0, measurements=None, v_meas=None, n_el=20, n_per_el=3, n_pix=64, a=2.):
	# extract const permittivity jacobian and voltage (& other)
	file = h5.File(fileJac, 'r')

	meas = file['meas'][()]
	new_ind = file['new_ind'][()]
	p = file['p'][()]
	t = file['t'][()]
	file.close()
	# initialise const permitivity and el_pos variables
	perm = np.ones(t.shape[0], dtype=np.float32)
	el_pos = np.arange(n_el * n_per_el).astype(np.int16)
	mesh_obj = {'element': t,
				'node':	p,
				'perm':	perm}

	#for testing
	if measurements is None:
		el_dist = np.random.randint(1, 20)
		ex_mat = (cp.concatenate((cp.arange(20)[None], (cp.arange(20) + el_dist)[None])) % 20).T
		#print(ex_mat.shape)
		fem_all = Forward(mesh_obj, el_pos)
		measurements = fem_all.voltMeter(ex_mat)
		#ex_mat = mesurements[1]
		measurements = cp.concatenate((measurements[1], measurements[0]), axis=1)
		#print(measurements.shape)
	# list all possible active/measuring electrode permutations of this measurement
	meas = cp.array(meas)
	# find their indices in the already calculated const. permitivity Jacobian (CPJ)
	measurements = cp.array(measurements)
	measurements_0 = cp.amin(measurements[:, :2], axis=1)
	measurements_1 = cp.amax(measurements[:, :2], axis=1)
	measurements_2 = cp.amin(measurements[:, 2:], axis=1)
	measurements_3 = cp.amax(measurements[:, 2:], axis=1)
	measurements = cp.empty((len(measurements), 4))
	measurements[:, 0] = measurements_0
	measurements[:, 1] = measurements_1
	measurements[:, 2] = measurements_2
	measurements[:, 3] = measurements_3
	index = (cp.sum(cp.equal(measurements[:, None, :], meas[None, :, :]), axis=2) == 4)
	index = cp.where(index)
	ind = cp.unique(index[1])
	i = cp.asnumpy(ind)
	j = index[0]
	mask = np.zeros(len(meas), dtype=int)
	mask[i] = 1
	mask = mask.astype(bool)
	# take a slice of Jacobian, voltage readings and B matrix
	file = h5.File(fileJac, 'r')
	jac = file['jac'][mask, :][()]
	v = file['v'][mask][()]
	b = file['b'][mask, :][()]
	file.close()
	pde_result = train.namedtuple("pde_result", ['jac', 'v', 'b_matrix'])
	f = pde_result(jac=jac,
				   v=v,
				   b_matrix=b)

	# simulate voltage readings if not given
	if v_meas is None:
		if np.isscalar(anomaly):
			print("generating new anomaly")
			anomaly = train.generate_anoms(a, a)
		true = train.generate_examplary_output(a, int(n_pix), anomaly)
		mesh_new = train.set_perm(mesh_obj, anomaly=anomaly, background=1)
		fem = FEM(mesh_obj, el_pos, n_el)
		new_ind = cp.array(new_ind)
		f2, raw = fem.solve_eit(volt_mat=meas[ind, 2:], new_ind=new_ind[ind], ex_mat=meas[ind, :2], parser=None, perm=mesh_new['perm'].astype('f8'))
		v_meas = f2.v
		'''
		#plot
		fig = plt.figure(3)
		x, y = p[:, 0], p[:, 1]
		ax1 = fig.add_subplot(111)
		# draw equi-potential lines
		print(raw.shape)
		raw = cp.asnumpy(raw[5]).ravel()
		vf = np.linspace(min(raw), max(raw), 32)
		ax1.tricontour(x, y, t, raw, vf, cmap=plt.cm.viridis)
		# draw mesh structure
		ax1.tripcolor(x, y, t, np.real(perm),
					  edgecolors='k', shading='flat', alpha=0.5,
					  cmap=plt.cm.Greys)

		ax1.plot(x[el_pos], y[el_pos], 'ro')
		for i, e in enumerate(el_pos):
			ax1.text(x[e], y[e], str(i+1), size=12)
		ax1.set_title('Equipotential Lines of Uniform Permittivity')
		# clean up
		ax1.set_aspect('equal')
		ax1.set_ylim([-1.2, 1.2])
		ax1.set_xlim([-1.2, 1.2])
		fig.set_size_inches(6, 6)
		#plt.show()'''
	elif len(measurements) == len(v_meas):
		measurements = np.array(measurements)
		v_meas = np.array(v_meas[j[:len(ind)]])
	else:
		raise ValueError('Sizes of arrays do not match (have to have voltage reading for each measurement). If you don\'t have readings, leave empty for simulation.')
	print('Number of measurements:', len(v_meas), len(f.v))

	# now we can use the real voltage readings and the GREIT algorithm to reconstruct
	greit = train.greit.GREIT(mesh_obj, el_pos, f=f, ex_mat=(meas[index[1], :2]), step=None)
	greit.setup(p=0.2, lamb=0.01, n=n_pix)
	h_mat = greit.H
	reconstruction = greit.solve(v_meas, f.v).reshape(n_pix, n_pix)

	# optional: see reconstruction
	'''
	plt.figure(1)
	im1 = plt.imshow(reconstruction, cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1])
	plt.title("Reconstruction")
	plt.colorbar(im1)
	plt.figure(2)
	im2 = plt.imshow(true, cmap=plt.cm.viridis, origin='lower', extent=[-1, 1, -1, 1])
	plt.colorbar(im2)
	plt.title("True Image")
	plt.show()
	'''
	return reconstruction, h_mat, v_meas, f.v, true, len(v_meas)


import boto3
import base64
import pathlib
import os
from urllib.parse import urlparse

def get_analytics_page(client, analytics_addr):
  addr = urlparse(analytics_addr)
  return (
    f""
    f"  "
    f"    <link rel=\"icon\" type=\"image/png\" href=\"{addr.scheme}://{addr.netloc}/favicon.png\">"
    f"    <meta http-equiv=\"Content-Type\" content=\"text/html;charset=ISO-8859-1\">"
    f"    <title>Tweddle Group Insights - {client}</title>"
    f"  "
    f"  "
    f"    "
    f"  "
    f""
  )

def unauthorized():
  return {
    'status': '401',
    'statusDescription': 'Unauthorized',
    'body': 'Unauthorized',
    'headers': {
      'www-authenticate': [{'key': 'WWW-Authenticate', 'value':'Basic'}]
    }
  }

def analytics_response(body):
  return {
    'status': '200',
    'statusDescription': 'OK',
    'headers': {
      'cache-control': [{
        'key': 'Cache-Control',
        'value': 'max-age=100'
      }],
      'content-type': [{
        'key': 'Content-Type',
        'value': 'text/html'
      }],
      'content-encoding': [{
        'key': 'Content-Encoding',
        'value': 'UTF-8'
      }],
    },
    'body': body
  }

def parse_lambda_alias_arn(arn):
  parts = arn.split(":")
  name_parts = parts[6].split(".")
  return {
    'region': name_parts[0],
    'name': name_parts[1],
    'account_id': parts[4]
  }

def build_lambda_arn(name, region, account_id):
  return f"arn:aws:lambda:{region}:{account_id}:function:{name}"

def get_headers(raw_headers):
    headers = {}
    for header, values in raw_headers.items():
        headers[header] = []
        for value in values:
            for v in value['value'].split(","):
                headers[header].append(v)
    return headers

def handler(event, context):
  request = event["Records"][0]["cf"]["request"]
  event_type = event["Records"][0]["cf"]["config"]["eventType"]
  if event_type == "viewer-request":
      request['headers']['x-forwarded-host'] = [{ 'key': 'X-Forwarded-Host', 'value': request['headers']['host'][0]['value'] }]
  elif event_type == "origin-request":
      if 's3' in request['origin']:
          headers = get_headers(request['headers'])
          if 'x-forwarded-host' in headers:
              host = headers['x-forwarded-host'][0]
              custom_headers = get_headers(request['origin']['s3']['customHeaders'])
              if 'analytics-auth' in custom_headers:
                  if ('analytics-host' in custom_headers and host in custom_headers['analytics-host']) or 'analytics-host' not in custom_headers:
                    if not 'authorization' in headers or not headers['authorization'][0] in custom_headers['analytics-auth']:
                        return unauthorized()
                    if 'analytics-addr' in custom_headers:
                      args = parse_lambda_alias_arn(context.invoked_function_arn)
                      function_arn = build_lambda_arn(**args)
                      aws_lambda = boto3.client("lambda", region_name=args['region'])
                      response = aws_lambda.list_tags(
                        Resource=function_arn
                      )
                      tags = response['Tags']
                      client = tags['Brand'] if tags.get('Brand') else tags['Client']
                      body = get_analytics_page(client, custom_headers['analytics-addr'][0])
                      return analytics_response(body)
          if not pathlib.Path(request['uri']).suffix:
              request['uri'] = '/index.html'
      elif request['origin'].get('custom'):
        if request['uri'].startswith("/logs"):
          if request['method'] == "POST":
            custom_headers = get_headers(request['origin']['custom']['customHeaders'])
            request['uri'] = custom_headers['ingest-path'][0]
  return request


import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from sklearn.feature_extraction.text import TfidfVectorizer
from collections import OrderedDict

def main():
    sys.path.append(os.path.join(os.path.dirname(__file__), '..'))

    from keras_en_parser_and_analyzer.library.dl_based_parser import ResumeParser
    from keras_en_parser_and_analyzer.library.utility.io_utils import read_pdf_and_docx

    current_dir = os.path.dirname(__file__)
    current_dir = current_dir if current_dir is not '' else '.'
    data_dir_path = current_dir + '/data/resume_samples'  # directory to scan for any pdf and docx files

    def parse_resume(file_path, file_content):
        print('parsing file: ', file_path)

        parser = ResumeParser()
        parser.load_model(current_dir + '/models')
        parser.parse(file_content)

        if parser.unknown is False:
            summary, expertise, experience, knowledge, project = parser.summary()
            # print("Condition Success")
            #
            # print(summary.encode('utf-8'))
            # vocabulary = []
            # for i in experience:
            #     vocabulary.append(i.encode("utf-8"))
            # print(vocabulary)

            experience_vocabulary = []
            for i in experience:
                j = i.encode('ascii', 'ignore').decode("utf-8").split(':')
                print(j)
                if len(j) != 1:
                    for k in j[1:]:
                        l = k.split(',')
                        experience_vocabulary.extend(l)
                else:
                    for k in j:
                        l = k.split(',')
                        experience_vocabulary.extend(l)
                        print(l)
            experience_vocabulary = list(filter(None, experience_vocabulary))
            experience_vocabulary = list(OrderedDict.fromkeys(experience_vocabulary))
            print(experience_vocabulary)
            expertise_vocabulary = []
            for i in expertise:
                expertise_vocabulary.append(i.encode('ascii', 'ignore').decode("utf-8"))
            knowledge_vocabulary = []
            for i in knowledge:
                knowledge_vocabulary.append(i.encode('ascii', 'ignore').decode("utf-8"))
            project_vocabulary = []
            for i in project:
                project_vocabulary.append(i.encode('ascii', 'ignore').decode("utf-8"))
            # print(summary.encode('utf-8'))
            document1 = "".join(experience_vocabulary)
            document2 = "".join(knowledge_vocabulary)
            document3 = "".join(project_vocabulary)
            corpus = dict([('expertise',document1),('knowledge',document2),('project',document3)])
            tfidf = TfidfVectorizer(vocabulary=experience_vocabulary, stop_words='english', ngram_range=(1, 2))
            tfs = tfidf.fit_transform(corpus.values())
            feature_names = tfidf.get_feature_names()
            corpus_index = [n for n in corpus]
            # rows, cols = tfs.nonzero()
            # for row, col in zip(rows, cols):
            #     print((feature_names[col], corpus_index[row]), tfs[row, col])
            import pandas as pd
            df = pd.DataFrame(tfs.T.todense(), index=feature_names, columns=corpus_index)
            print(df)
            # print(experience_vocabulary)
            # print(expertise_vocabulary)
            # print(knowledge_vocabulary)
            # print(project_vocabulary)
        print('++++++++++++++++++++++++++++++++++++++++++')

    collected = read_pdf_and_docx(data_dir_path, command_logging=True, callback=lambda index, file_path, file_content: {
        parse_resume(file_path, file_content)
    })
    print('count: ', len(collected))

if __name__ == '__main__':
    main()


from src.handler import Handler
from src.model.post import Post

class MyPost(Handler):
    def get(self):
        if self.user:
            posts = Post.all().filter('owner_id = ', self.user.key()).order('-created')
            self.render('blog/front_blog.html', posts=posts, owner=True)
        else:
            self.redirect('/login')


#!/usr/bin/env python
from __future__ import division

import copy
import json
import logging
import pprint
import sys
import time
from datetime import datetime

from WMCore.Database.CMSCouch import CouchServer
from WMCore.Database.CMSCouch import Document as CouchDoc
from WMCore.Lexicon import splitCouchServiceURL
from WMCore.Services.McM.McM import McM, McMNoDataError
from WMCore.Services.WMStats.DataStruct.RequestInfoCollection import RequestInfoCollection
from WMCore.Services.WMStats.WMStatsReader import WMStatsReader

maxMCMCalls = 250  # Maximum # of entries to retrieve from McM per run

def gatherWMDataMiningStats(wmstatsUrl, reqmgrUrl, wmMiningUrl,
                            mcmUrl, mcmCert, mcmKey, tmpDir,
                            archived=False, log=logging.info):
    server, database = splitCouchServiceURL(wmMiningUrl)
    analyticsServer = CouchServer(server)
    couchdb = analyticsServer.connectDatabase(database)

    WMStats = WMStatsReader(wmstatsUrl, reqdbURL=reqmgrUrl, reqdbCouchApp="ReqMgr")

    reqMgrServer, reqMgrDB = splitCouchServiceURL(reqmgrUrl)

    reqMgr = CouchServer(reqMgrServer).connectDatabase(reqMgrDB, False)

    if archived:
        funcName = "Archived Requests"
    else:
        funcName = "Active Requests"

    log.info("%s: Getting job information from %s and %s. Please wait." % (
        funcName, wmstatsUrl, reqmgrUrl))

    if archived:
        checkStates = ['normal-archived', 'rejected-archived', 'aborted-archived']
        jobInfoFlag = False
    else:
        checkStates = WMStatsReader.ACTIVE_STATUS
        jobInfoFlag = True
    requests = WMStats.getRequestByStatus(checkStates, jobInfoFlag=jobInfoFlag, legacyFormat=True)

    requestCollection = RequestInfoCollection(requests)
    result = requestCollection.getJSONData()
    requestsDict = requestCollection.getData()
    log.info("%s: Total %s requests retrieved\n" % (funcName, len(result)))

    report = {}
    nMCMCalls = 0
    with McM(cert=mcmCert, key=mcmKey, url=mcmUrl, tmpDir=tmpDir) as mcm:
        for wf in result.keys():

            # Store a copy of the CouchDB document so we can compare later before updating
            if couchdb.documentExists(wf):
                oldCouchDoc = couchdb.document(wf)
                wfExists = True
            else:
                oldCouchDoc = CouchDoc(id=wf)
                wfExists = False

            newCouchDoc = copy.deepcopy(oldCouchDoc)
            ancientCouchDoc = copy.deepcopy(oldCouchDoc)
            report[wf] = oldCouchDoc
            # FIXME: remove report, only have two instances of couchDoc

            if 'filterEfficiency' not in oldCouchDoc or 'runWhiteList' not in oldCouchDoc:
                runWhiteList = []
                filterEfficiency = None
                try:
                    # log.debug("Looking up %s in ReqMgr" % wf)
                    rmDoc = reqMgr.document(wf)
                    runWhiteList = rmDoc.get('RunWhiteList', [])
                    filterEfficiency = rmDoc.get('FilterEfficiency', None)
                except:
                    pass  # ReqMgr no longer has the workflow
                report[wf].update({'filterEfficiency': filterEfficiency, 'runWhiteList': runWhiteList})

            if oldCouchDoc.get('mcmTotalEvents', 'Unknown') == 'Unknown' or \
                oldCouchDoc.get('mcmApprovalTime', 'Unknown') == 'Unknown':

                prepID = oldCouchDoc.get('prepID', None)
                if prepID and nMCMCalls <= maxMCMCalls:
                    log.info("Trying to update McM info for %s, PREPID %s" % (wf, prepID))
                    # Get information from McM. Don't call too many times, can take a long time
                    nMCMCalls += 1
                    try:
                        mcmHistory = mcm.getHistory(prepID=prepID)
                        if 'mcmApprovalTime' not in oldCouchDoc:
                            report[wf].update({'mcmApprovalTime': 'NoMcMData'})
                        found = False
                        for entry in mcmHistory:
                            if entry['action'] == 'set status' and entry['step'] == 'announced':
                                dateString = entry['updater']['submission_date']
                                dt = datetime.strptime(dateString, '%Y-%m-%d-%H-%M')
                                report[wf].update({'mcmApprovalTime': time.mktime(dt.timetuple())})
                                found = True
                        if not found:
                            log.error("History found but no approval time for %s" % wf)
                    except McMNoDataError:
                        log.error("Setting NoMcMData for %s" % wf)
                        report[wf].update({'mcmApprovalTime': 'NoMcMData'})
                    except (RuntimeError, IOError):
                        exc_type, dummy_exc_value, dummy_exc_traceback = sys.exc_info()
                        log.error("%s getting history from McM for PREP ID %s. May be transient and/or SSO problem." %
                                  (exc_type, prepID))
                    except:
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        log.error("%s getting history from McM for PREP ID %s. Unknown error." %
                                  (exc_type, prepID))

                    try:
                        mcmRequest = mcm.getRequest(prepID=prepID)
                        report[wf].update({'mcmTotalEvents': mcmRequest.get('total_events', 'NoMcMData')})
                    except (RuntimeError, IOError):
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        log.error("%s getting request from McM for PREP ID %s. May be transient and/or SSO problem." %
                                  (exc_type, prepID))
                    except:
                        exc_type, exc_value, exc_traceback = sys.exc_info()
                        log.error("%s getting request from McM for PREP ID %s. Unknown error." %
                                  (exc_type, prepID))

            # Basic parameters of the workflow
            priority = requests[wf].get('priority', 0)
            requestType = requests[wf].get('request_type', 'Unknown')
            targetLumis = requests[wf].get('input_lumis', 0)
            targetEvents = requests[wf].get('input_events', 0)
            campaign = requests[wf].get('campaign', 'Unknown')
            prep_id = requests[wf].get('prep_id', None)
            outputdatasets = requests[wf].get('outputdatasets', [])
            statuses = requests[wf].get('request_status', [])

            if not statuses:
                log.error("Could not find any status from workflow: %s" % wf)  # Should not happen but it does.

            # Remove a single  task_ from the start of PREP ID if it exists
            if prep_id and prep_id.startswith('task_'):
                prep_id.replace('task_', '', 1)

            # Can be an empty list, full list, empty string, or non-empty string!
            inputdataset = requests[wf].get('inputdataset', "")
            if isinstance(inputdataset, list):
                if inputdataset:
                    inputdataset = inputdataset[0]
                else:
                    inputdataset = ''

            outputTier = 'Unknown'
            try:
                outputTiers = []
                for ds in outputdatasets:
                    if isinstance(ds, list):
                        outputTiers.append(ds[0].split('/')[-1])
                    else:
                        outputTiers.append(ds.split('/')[-1])
            except:
                log.error(
                    "Could not decode outputdatasets: %s" % outputdatasets)  # Sometimes is a list of lists, not just a list. Bail
            if inputdataset:
                inputTier = inputdataset.split('/')[-1]
                if inputTier in ['GEN']:
                    outputTier = 'LHE'
                elif inputTier in ['RAW', 'RECO']:
                    outputTier = 'AOD'
                elif inputTier in ['GEN-SIM']:
                    outputTier = 'AODSIM'
                elif 'AODSIM' in outputTiers:
                    outputTier = 'AODSIM'

            else:
                if len(outputTiers) == 1 and 'GEN' in outputTiers:
                    if 'STEP0ATCERN' in wf:
                        outputTier = 'STEP0'
                    else:
                        outputTier = 'FullGen'
                elif 'GEN-SIM' in outputTiers and 'AODSIM' in outputTiers and requestType == 'TaskChain':
                    outputTier = 'RelVal'
                elif 'RECO' in outputTiers and requestType == 'TaskChain':
                    outputTier = 'RelVal'
                elif 'GEN-SIM' in outputTiers:
                    outputTier = 'GEN-SIM'
                elif 'AODSIM' in outputTiers:
                    outputTier = 'AODSIM'
                elif 'RECO' in outputTiers:
                    outputTier = 'AOD'
                elif 'AOD' in outputTiers:
                    outputTier = 'AOD'
                else:
                    outputTier = 'GEN-SIM'

            # Calculate completion ratios for events and lumi sections, take minimum for all datasets
            eventPercent = 200
            lumiPercent = 200
            datasetReports = requestsDict[wf].getProgressSummaryByOutputDataset()
            for dataset in datasetReports:
                dsr = datasetReports[dataset].getReport()
                events = dsr.get('events', 0)
                lumis = dsr.get('totalLumis', 0)
                if targetLumis:
                    lumiPercent = min(lumiPercent, lumis / targetLumis * 100)
                if targetEvents:
                    eventPercent = min(eventPercent, events / targetEvents * 100)
            if eventPercent > 100:
                eventPercent = 0
            if lumiPercent > 100:
                lumiPercent = 0

            # Sum up all jobs across agents to see if we've run the first, last
            successJobs = 0
            totalJobs = 0
            for agent in result[wf]:
                jobs = result[wf][agent]
                successJobs += jobs['sucess']
                totalJobs += jobs['created']
            try:
                if totalJobs and not report[wf].get('firstJobTime', None):
                    report[wf].update({'firstJobTime': int(time.time())})
                if totalJobs and successJobs == totalJobs and not report[wf].get('lastJobTime', None):
                    report[wf].update({'lastJobTime': int(time.time())})
            except:
                pass

            # Figure out current status of workflow and transition times
            finalStatus = None
            newTime = None
            approvedTime = None
            assignedTime = None
            acquireTime = None
            completedTime = None
            closeoutTime = None
            announcedTime = None
            archivedTime = None
            requestDate = None

            for status in statuses:
                finalStatus = status['status']
                if status['status'] == 'new':
                    newTime = status['update_time']
                if status['status'] == 'assignment-approved':
                    approvedTime = status['update_time']
                if status['status'] == 'assigned':
                    assignedTime = status['update_time']
                if status['status'] == 'completed':
                    completedTime = status['update_time']
                if status['status'] == 'acquired':
                    acquireTime = status['update_time']
                if status['status'] == 'closed-out':
                    closeoutTime = status['update_time']
                if status['status'] == 'announced':
                    announcedTime = status['update_time']
                if status['status'] == 'normal-archived':
                    archivedTime = status['update_time']

            # Build or modify the report dictionary for the WF
            report.setdefault(wf, {})

            if approvedTime and not report[wf].get('approvedTime', None):
                report[wf].update({'approvedTime': approvedTime})
            if assignedTime and not report[wf].get('assignedTime', None):
                report[wf].update({'assignedTime': assignedTime})
            if acquireTime and not report[wf].get('acquireTime', None):
                report[wf].update({'acquireTime': acquireTime})
            if closeoutTime and not report[wf].get('closeoutTime', None):
                report[wf].update({'closeoutTime': closeoutTime})
            if announcedTime and not report[wf].get('announcedTime', None):
                report[wf].update({'announcedTime': announcedTime})
            if completedTime and not report[wf].get('completedTime', None):
                report[wf].update({'completedTime': completedTime})
            if newTime and not report[wf].get('newTime', None):
                report[wf].update({'newTime': newTime})
            if archivedTime and not report[wf].get('archivedTime', None):
                report[wf].update({'archivedTime': archivedTime})

            try:
                dt = requests[wf]['request_date']
                requestDate = '%4.4d-%2.2d-%2.2d %2.2d:%2.2d:%2.2d' % tuple(dt)
                report[wf].update({'requestDate': requestDate})
            except:
                pass

            report[wf].update({'priority': priority, 'status': finalStatus, 'type': requestType})
            report[wf].update({'totalLumis': targetLumis, 'totalEvents': targetEvents,})
            report[wf].update({'campaign': campaign, 'prepID': prep_id, 'outputTier': outputTier,})
            report[wf].update({'outputDatasets': outputdatasets, 'inputDataset': inputdataset,})

            report[wf].setdefault('lumiPercents', {})
            report[wf].setdefault('eventPercents', {})
            lumiProgress = 0
            eventProgress = 0
            for percentage in [1, 10, 20, 30, 40, 50, 60, 70, 80, 90, 95, 98, 99, 100]:
                percent = str(percentage)
                percentReported = report[wf]['lumiPercents'].get(percent, None)
                if not percentReported and lumiPercent >= percentage:
                    report[wf]['lumiPercents'][percent] = int(time.time())
                if lumiPercent >= percentage:
                    lumiProgress = percentage

                percentReported = report[wf]['eventPercents'].get(percent, None)
                if not percentReported and eventPercent >= percentage:
                    report[wf]['eventPercents'][percent] = int(time.time())
                if eventPercent >= percentage:
                    eventProgress = percentage

            report[wf].update({'eventProgress': eventProgress, 'lumiProgress': lumiProgress,})

            newCouchDoc.update(report[wf])

            # Queue the updated document for addition if it's changed.
            if ancientCouchDoc != newCouchDoc:
                if wfExists:
                    # log.debug("Workflow updated: %s" % wf)
                    pass
                else:
                    # log.debug("Workflow created: %s" % wf)
                    pass

                try:
                    newCouchDoc['updateTime'] = int(time.time())
                    report[wf]['updateTime'] = int(time.time())
                    dummy = json.dumps(newCouchDoc)  # Make sure it encodes before trying to queue
                    couchdb.queue(newCouchDoc)
                except:
                    log.error("Failed to queue document:%s \n" % pprint.pprint(newCouchDoc))

    log.info("%s: Finished getting job. wait for the next Cycle" % funcName)
    # Commit all changes to CouchDB
    couchdb.commit()


import typing

import jk_flexdata
import jk_typing

from .AlertMessage import AlertMessage
from ..DictValue import DictValue
from ..DictTextMessage import DictTextMessage

class _AbstractComparator(object):

	def __init__(self, sourceLocation:str):
		if sourceLocation:
			assert isinstance(sourceLocation, str)
		else:
			sourceLocation = ""

		self.sourceLocation = sourceLocation
	#

	def check(self, dataTree:jk_flexdata.FlexObject, v:DictValue):
		raise NotImplementedError()
	#

#

class _AbstractBinaryComparator(_AbstractComparator):

	def __init__(self, refValue, refSelectorPath:str, sourceLocation:str):
		super().__init__(sourceLocation)

		if refSelectorPath:
			assert isinstance(refSelectorPath, str)
			self.refSelectorPath = jk_flexdata.FlexDataSelector(refSelectorPath)
			self.refValue = None
		else:
			self.refSelectorPath = None
			if isinstance(refValue, DictValue):
				self.refValue = refValue
			else:
				self.refValue = DictValue(refValue, None, sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def check(self, dataTree:jk_flexdata.FlexObject, v:DictValue):
		if self.refSelectorPath is not None:
			spath, refValue = self.refSelectorPath.getOne(dataTree)
			if refValue is None:
				return -1
			else:
				refValue = DictValue(refValue, None, None)
		else:
			refValue = self.refValue

		return self._doCheck(v, refValue)
	#

	def _doCheck(self, v:DictValue, refValue:DictValue):
		raise NotImplementedError()
	#

	def __str__(self):
		if self.refSelectorPath is not None:
			s = repr(str(self.refSelectorPath))
		else:
			s = str(self.refValue)

		name = self.__class__.__name__
		p = name.rindex("_")
		name = name[p + 1:]
		name = name[0].lower() + name[1:]

		return name + " " + s
	#

#

class _Comparator_HasValues(_AbstractComparator):

	def __init__(self, sourceLocation:str):
		super().__init__(sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def check(self, dataTree:jk_flexdata.FlexObject, v:DictValue):
		if v.test_isEmpty():
			return 0
		else:
			return 1
	#

	def __str__(self):
		return "hasValues"
	#

#

class _Comparator_GreaterThan(_AbstractBinaryComparator):

	def __init__(self, refValue, refSelectorPath:str, sourceLocation:str):
		super().__init__(refValue, refSelectorPath, sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def _doCheck(self, v:DictValue, refValue:DictValue):
		if v.test_gt(refValue):
			return 1
		else:
			return 0
	#

#

class _Comparator_GreaterOrEqual(_AbstractBinaryComparator):

	def __init__(self, refValue, refSelectorPath:str, sourceLocation:str):
		super().__init__(refValue, refSelectorPath, sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def _doCheck(self, v:DictValue, refValue:DictValue):
		if v.test_ge(refValue):
			return 1
		else:
			return 0
	#

#

class _Comparator_LowerThan(_AbstractBinaryComparator):

	def __init__(self, refValue, refSelectorPath:str, sourceLocation:str):
		super().__init__(refValue, refSelectorPath, sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def _doCheck(self, v:DictValue, refValue:DictValue):
		if v.test_lt(refValue):
			return 1
		else:
			return 0
	#

#

class _Comparator_LowerOrEqual(_AbstractBinaryComparator):

	def __init__(self, refValue, refSelectorPath:str, sourceLocation:str):
		super().__init__(refValue, refSelectorPath, sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def _doCheck(self, v:DictValue, refValue:DictValue):
		if v.test_le(refValue):
			return 1
		else:
			return 0
	#

#

class _Comparator_Equal(_AbstractBinaryComparator):

	def __init__(self, refValue, refSelectorPath:str, sourceLocation:str):
		super().__init__(refValue, refSelectorPath, sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def _doCheck(self, v:DictValue, refValue:DictValue):
		if v.test_eq(refValue):
			return 1
		else:
			return 0
	#

#

class _Comparator_NotEqual(_AbstractBinaryComparator):

	def __init__(self, refValue, refSelectorPath:str, sourceLocation:str):
		super().__init__(refValue, refSelectorPath, sourceLocation)
	#

	@jk_typing.checkFunctionSignature()
	def _doCheck(self, v:DictValue, refValue:DictValue):
		if v.test_ne(refValue):
			return 1
		else:
			return 0
	#

#

class _RuleAction(object):

	#
	# @param		str message		The message to format later during output. Please note the special syntax that can be used to place variables within the message.
	#
	@jk_typing.checkFunctionSignature()
	def __init__(self, comparator:_AbstractComparator, alertClass:str, message:DictTextMessage):
		self.__comparator = comparator
		self.__alertClass = alertClass
		self.__message = message
	#

	@property
	def alertClass(self) -> str:
		return self.__alertClass
	#

	#
	# Check if the condition for this action is fullfilled.
	#
	# @param	jk_flexdata.FlexObject dataTree		The full data tree to work on. This argument is required as some conditions require access to other parts of the data tree.
	# @param	DictValue v			This is the value encountered. Check /this/ value to check if action is needed.
	#
	def checkValue(self, dataTree:jk_flexdata.FlexObject, v:DictValue) -> bool:
		nCheckResult = self.__comparator.check(dataTree, v)
		if nCheckResult < 0:
			# failed for some reason
			#print("--- " + str(action.comparator) + " >>> " + jk_console.Console.ForeGround.STD_DARKYELLOW + "failed" + jk_console.Console.RESET)
			return False
		elif nCheckResult == 0:
			# no match
			#print("--- " + str(action.comparator) + " >>> " + jk_console.Console.ForeGround.STD_DARKGRAY + "no match" + jk_console.Console.RESET)
			return False
		else:
			# match!
			#print("--- " + str(action.comparator) + " >>> " + jk_console.Console.ForeGround.STD_GREEN + "MATCH!" + jk_console.Console.RESET)
			return True
	#

	def formatMessage(self, dataTree:jk_flexdata.FlexObject, varValueMap:dict):
		return self.__message.format(dataTree, varValueMap)
	#

#

class Rule(object):

	#
	# @param	str selectorPath		The string representation of the path(s) where this rule should be applied to. (required)
	# @param	str valueVisFlavor		If we need to visualize the value selected by the path use /this/ visusalization flavor. (optional)
	# @param	_RuleAction[] actions		If we have a match perform these actions. (required)
	# @param	str sourceLocation		This rule is retrieved from /this/ location. (optional)
	#
	def __init__(self, selectorPath:str, valueVisFlavor:str, actions:list, sourceLocation:str):
		assert isinstance(sourceLocation, str)
		self.__sourceLocation = sourceLocation

		if valueVisFlavor is not None:
			assert isinstance(valueVisFlavor, str)
		self.__valueVisFlavor = valueVisFlavor

		# stores a value selector: jk_flexdata.FlexDataSelector
		assert isinstance(selectorPath, str)
		self.__selector = jk_flexdata.FlexDataSelector(selectorPath)
		self.__selectorPath = selectorPath

		# stores actions: AbstractAction[]
		assert isinstance(actions, (tuple, list))
		for action in actions:
			assert isinstance(action, _RuleAction)
		self.__actions = actions
	#

	@property
	def sourceLocation(self) -> typing.Union[None,str]:
		return self.__sourceLocation
	#

	@staticmethod
	@jk_typing.checkFunctionSignature()
	def __loadComparator(jsonData:dict, sourceLocation:str) -> _AbstractComparator:
		ruleType = jsonData["ruleType"]
		if ruleType == "hasValues":
			return _Comparator_HasValues(sourceLocation)
		elif ruleType == ">":
			return _Comparator_GreaterThan(jsonData.get("refValue"), jsonData.get("refSelector"), sourceLocation)
		elif ruleType == ">=":
			return _Comparator_GreaterOrEqual(jsonData.get("refValue"), jsonData.get("refSelector"), sourceLocation)
		elif ruleType == "<":
			return _Comparator_LowerThan(jsonData.get("refValue"), jsonData.get("refSelector"), sourceLocation)
		elif ruleType == "<=":
			return _Comparator_LowerOrEqual(jsonData.get("refValue"), jsonData.get("refSelector"), sourceLocation)
		elif ruleType == "==":
			return _Comparator_Equal(jsonData.get("refValue"), jsonData.get("refSelector"), sourceLocation)
		elif ruleType == "!=":
			return _Comparator_NotEqual(jsonData.get("refValue"), jsonData.get("refSelector"), sourceLocation)
		else:
			raise Exception("Unknown rule type specified: " + repr(ruleType) + " (" + sourceLocation + ")")
	#

	@staticmethod
	@jk_typing.checkFunctionSignature()
	def loadFromJSON(jsonData:dict, sourceLocation:str):
		selectorPath = jsonData["selector"]
		valueVisFlavor = jsonData.get("valueVisFlavor")

		jChecks = None
		if "check" in jsonData:
			jChecks = [ jsonData["check"] ]
		elif "checks" in jsonData:
			jChecks = jsonData["checks"]
		else:
			raise Exception("No 'check' or 'checks' found! (" + sourceLocation + ")")

		actionOrActions = []
		for jCheck in jChecks:
			assert isinstance(jCheck, dict)
			visFlavors = {}
			for k, v in jCheck.items():
				if k.endswith(".visFlavor"):
					visFlavors[k[:-10]] = v
			action = _RuleAction(
				Rule.__loadComparator(jCheck, sourceLocation),
				jCheck["alert"],
				DictTextMessage(jCheck["msg"], sourceLocation),
				)
			actionOrActions.append(action)

		return Rule(selectorPath, valueVisFlavor, actionOrActions, sourceLocation)
	#

	#
	# Apply this rule. Produce output as needed.
	#
	@jk_typing.checkFunctionSignature()
	def generateAlertMessages(self, systemName:typing.Union[str,None], serviceName:typing.Union[str,None], dataTree:jk_flexdata.FlexObject):
		for spath, _vDict in self.__selector.getAll(dataTree):
			# we have a match for the current rule. now analyse if our conditions match
			# * `spath` contains the location where we found the match
			# * `:_vDict` contains the data; this is a jk_flexdata.FlexObject (if the data tree does not contain any errors)

			# let's create `v` which is a object oriented representation of that value.
			# we use DictValue as this way we have a type and formatting-aware component.
			v = DictValue(_vDict, self.__valueVisFlavor, self.__sourceLocation)

			#print("- Match: " + spath)
			for action in self.__actions:
				if not action.checkValue(dataTree, v):
					# no action required
					continue

				# produce text message

				msgArgs = {
					"value": v,
				}
				msgText = action.formatMessage(dataTree, msgArgs)

				# modify alert state of tree node

				_vDict.a = action.alertClass

				# return alert message

				yield AlertMessage(systemName, serviceName, spath, action.alertClass, msgText)

	#

#


from os.path import join as j
from re import compile as c
from re import findall as l
from glob import glob as u
from operator import itemgetter as g

def parse_submissions(d):
    z = []
    q = j(d, '*', 'data.tcl')
    h = c('Classify ([^\n]*)')
    i = c('Date ([^\n]*)')
    t = c('Team ([^\n]*)')
    p = c('Problem ([^\n]*)')
    for m in u(q):
        with open(m, encoding='utf-8') as f:
            k = f.read()
        v = l(i, k)
        b = l(t, k)
        n = l(p, k)
        y = l(k, k)
        z += [(v[0], b[0], n[0], y[0])]
    z.sort(key=g(0))
    return [(x[1], x[2]) for x in z if 'Accepted' in x[3]]


import cv2

img = cv2.imread("obj1_5.jpg")

sift = cv2.xfeatures2d.SIFT_create(contrastThreshold=0.16, edgeThreshold=9)
kp, des = sift.detectAndCompute(img, None)
img = cv2.drawKeypoints(img, kp, img, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)

cv2.imshow('sift_kp', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.imwrite('sift_kp.png', img)


#python3
import sys

def binary_search(a, x):
    low, high = 0, len(a)
    while low<=high:
        mid=(low+high)//2
        if low>=len(a):
            return -1
        if x==a[mid]:
            return mid
        elif x<a[mid]:
            high=mid-1
        else:
            low=mid+1
    return -1

if __name__ == '__main__':
    input = sys.stdin.read()
    data = list(map(int, input.split()))
    n = data[0]
    m = data[n + 1]
    a = data[1 : n + 1]
    for x in data[n + 2:]:
        print(binary_search(a, x), end = ' ')


import flappy_headless
import numpy as np
import sys
from collections import defaultdict
import pickle

rewardAlive = 1
rewardKill = -10000
alpha = 0.2
gamma = 0.9

# Q[state] = (Nicht springen, springen)
Q = defaultdict(lambda: [0, 0])

def paramsToState(params):
    playerVelY = params['playerVelY']
    playery = round(params["playery"] / 10) * 10

    if int(params["upperPipes"][0]['x']) < 56:
        index = 1
    else:
        index = 0

    upperPipeX = round(int(params["upperPipes"][index]['x']) / 10) * 10
    upperPipeY = round(int(params["upperPipes"][index]['y']) / 10) * 10

    return str(playerVelY) + "_" + str(playery) + "_" + str(upperPipeX) + "_" + str(upperPipeY)

oldState = None
oldAction = None
gameCounter = 0

def onGameover(gameInfo):
    global oldState
    global oldAction
    global gameCounter

    print(str(gameCounter) + ":" + str(gameInfo['score']))

    # Q updaten für die vorherige Aktion
    #  -> Die vorherige Aktion war nicht erfolgreich!
    prevReward = Q[oldState]
    index = None
    if oldAction == False:
        index = 0
    else:
        index = 1

    prevReward[index] = (1 - alpha) * prevReward[index] + \
        alpha * rewardKill
    Q[oldState] = prevReward

    oldState = None
    oldAction = None

    if gameCounter % 10000 == 0:
        with open("Q/" + str(gameCounter) + ".pickle", "wb") as file:
            pickle.dump(dict(Q), file)

    gameCounter+=1

def shouldEmulateKeyPress(params):
    global oldState
    global oldAction

    state = paramsToState(params)
    estReward = Q[state]

    # Q updaten für die vorherige Aktion
    #  -> Die vorherige Aktion war erfolgreich!
    prevReward = Q[oldState]
    index = None
    if oldAction == False:
        index = 0
    else:
        index = 1

    prevReward[index] = (1 - alpha) * prevReward[index] + \
        alpha * (rewardAlive + gamma * max(estReward))
    Q[oldState] = prevReward

    oldState = state
    if estReward[0] >= estReward[1]:
        oldAction = False
        return False
    else:
        oldAction = True
        return True

flappy_headless.main(shouldEmulateKeyPress, onGameover)

Kursmaterialien/550 - Q-Learning fuer Flappy Bird/qlearning7.py


import boto3
import os
from requests_aws4auth import AWS4Auth
#import cottoncandy as cc

# AWS S3 setting
service = 's3'
session = boto3.Session(
  aws_access_key_id=os.environ.get('AWS_ACCESS_KEY_ID', ''),
  aws_secret_access_key=os.environ.get('AWS_SECRET_ACCESS_KEY', '')
)
credentials = session.get_credentials()

region = os.environ.get('AWS_REGION', '')
http_auth = AWS4Auth(credentials.access_key, credentials.secret_key, region, service)

s3 = boto3.resource('s3')

# cci = cc.get_interface(os.environ.get('S3_BUCKET',''),
#                         ACCESS_KEY=os.environ.get('AWS_ACCESS_KEY_ID',''),
#                         SECRET_KEY=os.environ.get('AWS_SECRET_ACCESS_KEY',''),
#                         endpoint_url=os.environ.get('S3_ENDPOINT',''))


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Sep 11 14:39:43 2018

@author: mlpa
"""

import numpy as np
import pandas as pd
#import matlab.engine as matlab
#import scipy.linalg
import os

#eng = matlab.engine.start_matlab()

class Null_LDA:
    def __init__(self, out_file):
        self.out_file = out_file

    def LOAD_DATASETS(self, data_path):
        file = pd.read_csv(filepath_or_buffer=data_path,header=None,skiprows=0)
        print('Load Data, path is ::' , data_path)
        print('file Shape is : ',file.shape)
        file = np.array(file)
        file_row , file_col = file.shape
        self.tr_data = file
        self.label_data = file[:,file_col-1] # last index
        print("DATA Load Done !")

    def LOAD_DATASETS_without_path(self, data):
        file_row, file_col = data.shape
        self.tr_data = data
        self.label_data = data[:,file_col-1]

    def DATA_NORMALIZE(self, data, mean_f, std_f):

        N_Tr, N_F = data.shape
        for index in range(N_Tr):
            for jndex in range(N_F):
                if std_f[jndex] == 0:
                    data[index,jndex] = 0
                else:
                    data[index,jndex] = ((data[index,jndex] - mean_f[jndex]) / std_f[jndex])
            clear = lambda:os.system('clear')
            clear() #function call
            #print(" Normalize : ",index)

        return data

    def CAL_STD(self, data):

        N_P , N_F = data.shape
        sum_dic = {}
        mean_vec = {}
        std_vec = {}

        for jndex in range(N_F):
            sum_dic[jndex] = 0
            for index in range(N_P):
                sum_dic[jndex] += data[index,jndex]
            mean_vec[jndex] = sum_dic[jndex] / N_P

        for jndex in range(N_F):
            sum_dic[jndex] = 0
            for index in range(N_P):
                sum_dic[jndex] = sum_dic[jndex] + (data[index,jndex] - mean_vec[jndex])*(data[index,jndex] - mean_vec[jndex])
            std_vec[jndex] = np.sqrt( ( sum_dic[jndex] ) / (N_P -1) )

        print("Calculation Standard and Variation is Done")
        return mean_vec , std_vec

    def CLASS_SEPARATION(self, data, label_data, class_label, N_class):
        # data , class , class_label, N_class in MATLAB
        print('===================================================================================')
        print('\n ::: Class Separation Initialize :::')
        N_data , N_f = data.shape
        sep_class = np.array([])
        sep_dic = {}

        #
        for index in range(N_class):
            #exec(['sep_class_' + 'str(class_label[index]))' + '= np.zeros(1, N_f)'])
            #print(str(class_1))
            sep_class = np.zeros((1,N_f))
            sep_dic[index] = sep_class

        #
        for index in range(N_data):
            sep_class = sep_dic[label_data[index ]]

            if np.sum(sep_class) == 0 :
                sep_class = data[index,:]
            else:
                sep_class = np.vstack((sep_class, data[index,:]))
            sep_dic[label_data[index]] = sep_class

        print('test 1 class: ' ,sep_dic[0].shape)
        print('test 2 class: ' ,sep_dic[1].shape)

        # pima dataset column name discard, If datasets have not any column name, Don't Use this Code
        for index in range(N_class):
            sep_class = sep_dic[index]
            sep_dic[index] = sep_class[:, :]  # name column discarded

        # because We use Dictionary, don't need sorted. It already Done
        #sorted_data = {}

        #for index in range(N_class):
        #    sorted_data[index] = sep_dic[index]

        # pima dataset column name discard, If datasets have not any column name, Don't Use this Code
        #for index in range(N_class):
        #    sorted_class = sep_dic[index]
        #    sorted_data[index] = sorted_class[:,:] # name column discarded
        sorted_data = sep_dic  # edit this

        class_index = np.zeros((N_class, 2))
        start = 0

        for index in range(N_class):
            N_sam , N_f = sep_dic[index].shape
            last = start + N_sam - 1
            class_index[index,0] = start
            class_index[index,1] = last
            start = last + 1

        print('Class Separation is Done !')

        return sorted_data , class_index
    def CLASS_INFORMATION(self, file):
        # label_data is 'class' variable in MATLAB

        N_data = len(file)
        #print(N_data)

        N_class = 1
        #class_label = np.zeros(file.shape)
        class_label = list()
        class_label.append(int(file[0]))
        #print('N_class is :', N_class)
        #print('class_label (1) is :', int(class_label[0]))

        for index in range(N_data):
            if file[index] not in class_label:
                N_class += 1
                class_label.append(int(file[index]))

        class_label = sorted(class_label)
        #print(class_label)

        N_class_sample = {}

        for key in range(N_class):
            N_class_sample[key] = 0

        for key in N_class_sample:
            for index in range(N_data):
                print(int(key), int(file[index]))
                if int(key) == int(file[index]):
                    N_class_sample[key] += 1

        self.N_class = N_class
        self.class_label = class_label
        self.N_class_sample = N_class_sample
        print('N_cFSDD_Pythonlass :',self.N_class)
        print('class_label :',self.class_label)
        print('N_class_sample :',self.N_class_sample)
        print('Class Information is Done !')
        return N_class,class_label,N_class_sample

    def DATA_SORT_INFORMATION(self, in_data):
        irow, icol = in_data.shape
        only_data = in_data[:, :icol-1]
        N_data, N_F = only_data.shape

        label_data = in_data[:,icol-1] # label_data is 'class' variable in MATLAB
        N_C, class_label, N_class_sample = self.CLASS_INFORMATION(label_data)
        sorted_data, class_index = self.CLASS_SEPARATION(in_data, label_data, class_label, N_C)

        # class_infrom, tem = sort(class_label') MATLAB CODE
        class_label = np.transpose(class_label)
        sorted_class_label = sorted(class_label)
        class_inform = sorted_class_label

        temp_row, true_col = sorted_data[0].shape

        true_data_tr = np.zeros((1,true_col))
        for key in sorted_data:
            #if true_data_tr.shape == sorted_data[key].shape:
            #    continue
            true_data_tr = np.vstack((true_data_tr , sorted_data[key]))

        true_data_tr = true_data_tr[1:]

        return true_data_tr, N_data, N_F, N_C, class_inform, N_class_sample

    def NULL_LDA(self, tr_data):
        #def NULL_LDA(self, tr_data, label_data):
        self.tr_data = tr_data
        #self.label_data = label_data
        print("NULL_LDA Initialize")

        sorted_data, N_Tr, N_F, N_C, class_inform, N_class_sample = self.DATA_SORT_INFORMATION(self.tr_data)
        print(N_F, N_C, class_inform, N_class_sample)

        srow, scol = sorted_data.shape
        data_tr = sorted_data[:,:scol-1]
        class_tr = sorted_data[:,scol-1]

        mean_tr, std_tr = self.CAL_STD(data_tr)
        data_tr = self.DATA_NORMALIZE(data_tr, mean_tr, std_tr)
        print("DATA Normalize Done")

        class_0 = data_tr[:N_class_sample[0], :]
        start_idx = N_class_sample[0]
        for index in range(1,N_C):
            end_idx = start_idx + N_class_sample[index]
            temp_str1 = 'class_' + str(index) + ' = data_tr[start_idx: end_idx]'
            exec(temp_str1)
            print(temp_str1)
            start_idx = start_idx + N_class_sample[index]

        self.one_tr_data_per_class = np.zeros((N_C,scol-1))

        for index in range(N_C):
            temp_str2 = 'trow, tcol = class_' + str(index) + '.shape'
            exec(temp_str2)
            temp_str3 = 'self.one_tr_data_per_class['+ str(index) +', : ] = class_' + str(index) + '[trow-1, :]'
            exec(temp_str3)

        one_tr_data_per_class = self.one_tr_data_per_class

        sum_class = np.zeros((N_C, N_F))
        mean_class = np.zeros((N_C, N_F))

        for index in range(N_C):
            for jndex in range(N_class_sample[index]):
                temp_str4 = 'sum_class[index,:] = sum_class[index, :] + class_' + str(index) + '[jndex,:]'
                exec(temp_str4)
            mean_class[index, :] = sum_class[index, :] / N_class_sample[index]

        t0 = 0

        A = np.zeros([0,N_F])
        #self.data_rest = np.array([])
        for index in range(N_C):
            for jndex in range(N_class_sample[index]):
                temp_str5 = 'self.data_rest = (class_' + str(index) + '[jndex, :] - mean_class[index, :])'
                exec(temp_str5)
                T_data_rest = np.transpose(self.data_rest)
                A = np.vstack((A, T_data_rest))

        T_A = np.transpose(A)
        K = (np.dot(A,T_A)) / N_Tr

        ra_K = np.linalg.matrix_rank(K)

        # matlab = E, D
        # python = w , v
        #q_comp, d = scipy.linalg.eig(K)

        K = np.array(K)

        #td, tq_comp = matlab.eig(K)
        print("First Eigen Decomposition")

        td, tq_comp = np.linalg.eig(K)
        #d = np.diag(d)
        q_comp = tq_comp
        d = np.diag(td)
        #q_comp = np.real_if_close(tq_comp)
        #d = np.real_if_close(np.diag(td))

        #np.save('/home/mlpa/Documents/mlpa/FSDD_Python/Eigen_Similarity/q_comp_py.npy', q_comp)
        #np.save('/home/mlpa/Documents/mlpa/FSDD_Python/Eigen_Similarity/d_py.npy', d)
        #d = np.real_if_close(np.diag(d))

        d_temp = list()
        w = np.zeros((N_Tr, 0))
        #q = np.array(([]))
        for index in range(N_Tr):
            d_temp.append(d[index, index])

        eig_val = sorted(d_temp)
        d_idx = list()
        for i in range(len(eig_val)):
            d_idx.append(i)
        #d_idx = sorted(d_temp)

        w_range = np.zeros((N_F, ra_K))
        for index in range(N_Tr):
            temp =  np.array(q_comp[:, int(d_idx[(N_Tr-1) -index])])
            #temp = np.transpose(temp)
            w = np.column_stack((w, temp))

        q = np.zeros((N_F, N_Tr))
        q = q.astype('complex')

        for index in range(N_Tr):
            temp_q = T_A @ w[:,index]
            q[:,index] = temp_q.astype('complex')
            norm_weight = np.linalg.norm(q[:,index])
            q[:,index] = q[:,index] / norm_weight

        w_range = q[:,:ra_K]

        T_w_range = np.transpose(w_range)
        T_one_tr_data_per_class = np.transpose(one_tr_data_per_class)
        temp10 = T_w_range @ T_one_tr_data_per_class
        #x_range = np.matmul(w_range , temp10)
        x_range = w_range @ temp10
        x_com = T_one_tr_data_per_class - x_range
        T_x_com = np.transpose(x_com)
        mean_x_com = np.transpose(np.mean(T_x_com))

        A_com = np.zeros((N_F,))
        for index in range(N_C):
            temp_sqrt = np.sqrt(N_class_sample[index]) * N_Tr
            temp11 = ( x_com[:, index] - mean_x_com ) * temp_sqrt
            A_com = np.column_stack((A_com, temp11))

        A_com = A_com[:,1:]
        #K_com = (np.transpose(A_com) * A_com) / N_C
        #K_com = np.dot(np.transpose(A_com), A_com) / N_C
        K_com = ( np.transpose(A_com) @ A_com ) / N_C
        ra_K_com = np.linalg.matrix_rank(K_com)

        d_temp_com = list()
        print("Second Eigen Decomposition")
        d_com, q_comp_com  = np.linalg.eig(K_com)
        #d_com = np.diag(d_com)
        #d_com = np.real_if_close(np.diag(d_com))
        d_com = np.diag(d_com)
        #np.save('/home/mlpa/Documents/mlpa/FSDD_Python/Eigen_Similarity/q_comp_com_py.npy', q_comp_com)
        #np.save('/home/mlpa/Documents/mlpa/FSDD_Python/Eigen_Similarity/d_com_py.npy', d_com)

        for index in range(N_C):
            d_temp_com.append(d_com[index, index])

        eig_val_com = sorted(d_temp_com)
        d_idx_com = list()
        for i in range(len(eig_val_com)):
            d_idx_com.append(i)

        #for index in range(len(d_temp_com)):
        #    d_idx_com[index] = index

        w_dis = np.zeros((N_C,N_C))
        for index in range(N_C):
            w_dis[:,index] = q_comp_com[:, d_idx_com[N_C -index - 1]]

        w_dis_com = np.zeros((N_F ,N_C))
        print(N_C)
        for index in range(N_C):
            #w_dis_com[:,index] = np.dot(A_com , w_dis[:,index])
            w_dis_com[:,index] = A_com @ w_dis[:, index]
            norm_weight_com = np.linalg.norm(w_dis_com[:,index])
            w_dis_com[:,index] = w_dis_com[:,index] / norm_weight_com

            #Result = w_dis_com[:,index] / norm_weight_com
            #np.save('/home/mlpa/Documents/mlpa/FSDD_Python/Eigen_Similarity/NLDA_Result_py.npy',Result)
            # Result is ' W_dis_com '

            dummy = 1

        W_dis_com = w_dis_com[:, :ra_K_com]
        Result = W_dis_com
        self.w_dis_com = w_dis_com
        self.std_tr = std_tr
        self.mean_tr = mean_tr

        return Result, std_tr, mean_tr

#data_path = '/home/mlpa/Documents/mlpa/Python_WorkSpace/FSDD_NLDA_Python/pima.csv'
##data_path = '/home/mlpa/Documents/mlpa/CNN/data_result/mono/flatten.csv'
##data_path = /home/mlpa/Documents/Dku_Cau_CROSS/datasets'
#
#NLDA = Null_LDA("PIMA_NLDA_OUTPUT")
#NLDA.LOAD_DATASETS(data_path)
#result = NLDA.NULL_LDA()
#
#
#
#


import pymongo
import json

from flask import request, Flask, Response

MONGODB_HOST = "fonkdb-mongodb.default"
MONGODB_PORT = 27017
MONGODB_NAME = "guestbook_app"
MONGODB_COLLECTION = "entries"

def main():
    try:
        client = pymongo.MongoClient("mongodb://{}".format(MONGODB_HOST), int(MONGODB_PORT))
        collection = client[MONGODB_NAME][MONGODB_COLLECTION]
        entries = []
        for doc in collection.find({}):
            doc["_id"] = str(doc["_id"])
            entries.append(doc)
        result = {"entries": entries}
        return response(json.dumps(result), 200)
    except pymongo.errors.PyMongoError as err:
        return response({"error": "MongoDB error: " + str(err)}, 500)
    except Exception as err:
        return response({"error": str(err)}, 500)

def response(body, status):
    return Response(str(body), status, {"Content-Type": "application/json", "Access-Control-Allow-Origin": "*"})


# Answer: 932718654
# Running Time: 0.03 sec

from Euler import is_pandigital
import time

count_t = time.time()

maxi = 0
for i in range(1, 10000):
    j = 1
    temp = ""
    while j < 10:
        temp += str(i*j)
        if len(temp) > 9:
            break
        elif len(temp) == 9:
            if is_pandigital(temp):
                if int(temp) > maxi:
                    maxi = int(temp)
        j += 1

print("Answer: {:d}".format(maxi))
print("Running Time: {:.02f} sec".format(time.time()-count_t))


from PyQt5 import uic
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem, QTableWidget, QWidget
import sys
import sqlite3

class App(QMainWindow):
    def __init__(self):
        super().__init__()
        uic.loadUi("addEditCoffeeForm.ui", self)
        self.pushButton.clicked.connect(self.add)
        self.con = sqlite3.connect("coffee.sqlite")
        self.cur = self.con.cursor()
        self.initUi()

    def initUi(self):
        result = list(self.cur.execute("select * from coffee").fetchall())
        self.c = ["ID", "Сорт", "Степень обжарки", "Молотый/в зернах", "Описание вкуса", "Цена", "Объем упаковки"]
        self.table.setColumnCount(len(self.c))
        self.table.setHorizontalHeaderLabels(self.c)
        self.table.setRowCount(0)
        for i, row in enumerate(result):
            self.table.setRowCount(self.table.rowCount() + 1)
            for j, elem in enumerate(row):
                    self.table.setItem(i, j, QTableWidgetItem(str(elem)))
        self.table.resizeColumnsToContents()
        self.table.cellChanged.connect(self.run)

    def run(self, row, column):
        st = self.c[column]
        it = self.table.item(row, column).text()
        id = self.table.item(row, 0).text()
        res = self.cur.execute(f"""update coffee set '{st}' = ? where ID = ?""", (it, int(id)))
        self.con.commit()

    def add(self):
        a = Add().__init__()

class Add(QWidget):
    def __init__(self):
        super().__init__()
        uic.loadUi('add.ui', self)
        self.pushButton.clicked.connect(self.add)
        self.con = sqlite3.connect('coffee.sqlite')
        self.cur = self.con.cursor()
        self.show()

    def add(self):
        print(0)
        s = self.lineEdit_s.text()
        o = self.lineEdit_o.text()
        m = self.lineEdit_m.text()
        t = self.lineEdit_t.text()
        p = self.lineEdit_p.text()
        v = self.lineEdit_v.text()
        res = self.cur.execute("""insert into coffee('Сорт', 'Степень обжарки', 'Молотый/в зернах', 'Описание вкуса', 'Цена',
        'Объем упаковки') values(?, ?, ?, ?, ?, ?)""", (s, o, m, t, p, v))
        self.con.commit()
        App.initUi(self)
        self.close()

app = QApplication(sys.argv)
a = App()
a.show()
sys.exit(app.exec_())


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

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('admin', '0015_giftpage_theme'),
    ]

    operations = [
        migrations.AddField(
            model_name='giftpage',
            name='home_url',
            field=models.CharField(verbose_name='货架首页地址', null=True, max_length=128, blank=True),
        ),
    ]


import json
import urllib

from movie_posters.models import Image, Request
from django.core.files import File
from annoying.decorators import render_to, ajax_request
from django.conf import settings

@render_to('index.html')
def index(request):
    return {}

@ajax_request
def poster(request):
    """
    This view searches for poster of the movie with a given name.
    In case API returns an image file, it's being saved at a local storage.
    Whenever the requested image is already at the local storage, it's retreived
    from there.
    :param request:
    :return:
    """
    if request.is_ajax() and request.method == 'POST':
        title = request.POST.get('title')
        if not title:
            return {'status': 'error',
                    'msg': 'Sorry, this field must not be empty'}

        source, title_param = getattr(settings, 'API')
        resp = urllib.urlopen('%s?%s' %
                              (source, urllib.urlencode({title_param: title})))

        content = json.loads(resp.read())
        resp.close()
        if content['Response'] != u'True':
            Request.objects.create(title=title)
            return {'status': 'error', 'msg': content[u'Error']}

        img_url = content[u'Poster']
        stored_images = Image.objects.filter(url=img_url)

        if img_url == 'N/A':
            return {'status': 'error', 'msg': 'Sorry, the poster is not available'}

        if stored_images.exists():
            to_return = stored_images[0]
        else:
            result = urllib.urlretrieve(img_url)
            file = open(result[0])
            to_return = Image.objects.create(image=File(file), url=img_url)
            file.close()

        Request.objects.create(image=to_return, title=title)
        return {'status': 'success', 'img': to_return.image.url}

@render_to('history.html')
def history(request):
    return {'requests': Request.objects.all().order_by('-date')}


#
# @lc app=leetcode id=279 lang=python
#
# [279] Perfect Squares
#

# @lc code=start

import math

class Solution(object):
    def numSquares(self, n):
        """
        :type n: int
        :rtype: int
        """
        squares = []
        for i in range(1,int(math.sqrt(n))+1):
            squares.append(math.pow(i, 2))
        level = 0
        cur = [0]
        while True:
            nxt = []
            for val in cur:
                for square in squares:
                    if val + square == n:
                        return level + 1
                    if val + square < n:
                        nxt.append(val + square)
            cur = list(set(nxt))
            level += 1
# @lc code=end


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

from __future__ import print_function
import time
from dronekit import connect, VehicleMode, LocationGlobalRelative
import cv2
import math
import cv2.aruco as aruco
from dronekit import connect, VehicleMode
from picamera.array import PiRGBArray
from picamera import PiCamera
from pymavlink import mavutil
import math

WIDTH = 640
HEIGHT = 480

TEMPLATE_L = .07					#in meters
TEMPLATE_H = .07				#in meters

CENTER_X_px = 334				#cam center in pixels
CENTER_Y_px = 275

xfov = 62.2 * math.pi/180			# pi camera v2's field of view in radians
yfov = 48.8 * math.pi/180

def get_z_7x7(area):
	return (4201.1 * (area ** -0.496))

def get_z_20x20(area):
	return (12632 * (area ** -0.502))

def send_land_message(x, y, z):
	message = drone.message_factory.landing_target_encode(
		0,	# ms since boot, a time stamp
		0,	# target ID for case of multiple targets
		mavutil.mavlink.MAV_FRAME_BODY_NED,	# MAV_FRAME enum specifying frame, try mavutil.mavlink.MAV_FRAME_BODY_NED
		x,	# X-axis angular offset in radians of target from center of image
		y,	# Y-axis angular offset
		z,	# distance to the target from vehicle in meters
		0,	# size of target in radians along x-axis
		0)	# size along y-axis
	drone.send_mavlink(message)
	drone.flush()

def distance(x1, y1, x2, y2):
	return math.hypot(x2-x1, y2-y1)

def calculate_xyz(corners):
	sumx = 0
	sumy = 0

	for x in corners[0][0]:
		sumx = sumx + x[0]
		sumy = sumy + x[1]

	avgx = sumx/4
	avgy = sumy/4

	x = (avgx - WIDTH/2)*xfov/WIDTH
	y = (avgy - HEIGHT/2)*yfov/HEIGHT

	side1 = distance(corners[0][0][0][0], corners[0][0][0][1], corners[0][0][1][0], corners[0][0][1][1])
	side2 = distance(corners[0][0][0][0], corners[0][0][0][1], corners[0][0][2][0], corners[0][0][2][1])
	area = side1 * side2

	if TEMPLATE_L is .07:
		z = get_z_7x7(area)
	else:
		z = get_z_20x20(area)

	return (x, y, z)

# Connect to the Vehicle
connection_string = "tcp:127.0.0.1:57600"
print('Connecting to vehicle on: %s' % connection_string)
drone = connect(connection_string, wait_ready=True)

def arm_and_takeoff(aTargetAltitude):
    """
    Arms vehicle and fly to aTargetAltitude.
    """

    print("Basic pre-arm checks")
    # Don't try to arm until autopilot is ready
    while not drone.is_armable:
        print(" Waiting for vehicle to initialise...")
        time.sleep(1)

    print("Arming motors")
    # Copter should arm in GUIDED mode
    drone.mode = VehicleMode("GUIDED")
    drone.armed = True

    # Confirm vehicle armed before attempting to take off
    while not drone.armed:
        print(" Waiting for arming...")
        time.sleep(1)

    print("Taking off!")
    drone.simple_takeoff(aTargetAltitude)  # Take off to target altitude

    # Wait until the drone reaches a safe height before processing the goto
    #  (otherwise the command after Vehicle.simple_takeoff will execute
    #   immediately).
    while True:
        print(" Altitude: ", drone.location.global_relative_frame.alt)
        # Break and return from function just below target altitude.
        if drone.location.global_relative_frame.alt >= aTargetAltitude * 0.9:
            print("Reached target altitude")
            break
        time.sleep(1)

arm_and_takeoff(2.5)

print("Open camera")
camera = PiCamera()
camera.resolution = (WIDTH, HEIGHT)
camera.framerate = 30
camera.shutter_speed = 1100
camera.ISO = 100
camera.meter_mode = 'matrix'

print("Begin camera, dictionary, params")

print("Set default/target airspeed")
drone.airspeed = 2.5

print("Set parameters")
drone.parameters['PLND_ENABLED'] = 1
drone.parameters['PLND_TYPE'] = 1

print("Set dictionary")
#TODO load pi camera and aruco library
aruco_dic = aruco.Dictionary_get(aruco.DICT_6X6_250)
#print(drone.battery)

print("Start landing")
count = 1
while(1):
	#A = time.time()
	print("Count: " + str(count))
	rawCapt = PiRGBArray(camera, size = (WIDTH, HEIGHT))
	time.sleep(0.1)
	camera.capture(rawCapt, format = "bgr", use_video_port = True)
	vid = rawCapt.array
	rawCapt.truncate(0)
	time.sleep(0.1)
	corners, ids, rejects = aruco.detectMarkers(vid, aruco_dic)
	time.sleep(0.1)
	#print("CORNERS:")
	#print(corners)

	if len(corners) is not 0:
		count = 0
		print(corners)
		(x, y, z) = calculate_xyz(corners)
		send_land_message(x, y, z)
		print ("Landing message sent")
	#	B = time.time()
	#	print("Time: %0.3f") % (B-A)

	else:
		path = '/home/pi/drone_scripts/fail' + str(count) + '.jpg'
		cv2.imwrite(str(path), vid)
		if count == 10:
			print ("Target not in frame, use default RTL")
			break

	count = count + 1

	#if drone.location.global_relative_frame.alt <= 0.7:
	#	print ("Too close to ground, use default RTL")
	#	break

drone.mode = VehicleMode("RTL")

camera.close()
drone.close()
print ("Done")


"""Base Element Class"""

#  Created by Egor Kostan.
#  GitHub: https://github.com/ikostan
#  LinkedIn: https://www.linkedin.com/in/egor-kostan/

import selenium.webdriver
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.common.exceptions import TimeoutException, \
    NoSuchElementException, \
    NoSuchAttributeException

class BaseElement:
    """
    Base Web Element
    """

    def __init__(self,
                 driver: selenium.webdriver,
                 explicit_wait_time: int,
                 locator=None):
        self.__driver = self.__set_driver(driver)
        self.__explicit_wait_time = explicit_wait_time
        self.__locator = self.__set_locator(locator)
        self.__element = self.__find_element()

    @property
    def explicit_wait_time(self):
        """
        Returns Explicit wait time
        :return:
        """
        return self.__explicit_wait_time

    @property
    def driver(self):
        """
        Returns selenium.webdriver object
        :return:
        """
        return self.__driver

    def attribute(self, attribute: str):
        """
        Returns attribute value
        :return:
        """
        try:
            atr = self.element.get_attribute(attribute)
            # print('\nattribute: {}, object: {}'.format(attribute, atr))  # debug only
            return atr

        except TimeoutException:
            raise NoSuchAttributeException(
                '\nERROR: The element has no attribute "{}".\n'
                'LOCATOR: {}\n'.format(attribute, self.locator))

    @property
    def element(self):
        """
        Returns Element instance
        :return:
        """
        return self.__element

    @property
    def locator(self):
        """
        Returns locator object (tuple)
        :return:
        """
        return self.__locator

    @locator.setter
    def locator(self, locator) -> None:
        """
        Set Base Element locator
        :param locator:
        :return:
        """
        self.__set_locator(locator)
        return None

    def __find_element(self):
        """
        Returns web element or NoSuchElementException in
        case element does not exist on the DOM
        :return:
        """
        try:
            element = WebDriverWait(self.driver, self.explicit_wait_time).until(
                EC.presence_of_element_located(self.locator))
            return element

        except TimeoutException:
            raise NoSuchElementException(
                '\nERROR: can not find element. The element is not present on the DOM.\n'
                'LOCATOR: {}\n'.format(self.locator))

    @staticmethod
    def __set_driver(driver: selenium.webdriver):
        """
        Check if driver of type: selenium.webdriver
        :param driver:
        :return:
        """
        BaseElement.__check_driver_type(driver)
        return driver

    @staticmethod
    def __check_driver_type(driver):

        # print('\nDRIVER TYPE: {}\n'.format(type(driver)))  # Debug only
        # print('\nDRIVER NAME: {}\n'.format(driver.capabilities['browserName']))  # Debug only

        if driver.capabilities['browserName'] == 'chrome':

            if not isinstance(driver, selenium.webdriver.chrome.webdriver.WebDriver):
                raise TypeError('\nERROR: driver must be of type '
                                '"selenium.webdriver.chrome_tests.webdriver.WebDriver"\n')
            return None

        if driver.capabilities['browserName'] == 'firefox':
            if not isinstance(driver, selenium.webdriver.firefox.webdriver.WebDriver):
                raise TypeError('\nERROR: driver must be of type '
                                '"selenium.webdriver.firefox.webdriver.WebDriver"\n')
            return None

        if driver.capabilities['browserName'] == 'MicrosoftEdge':
            if not isinstance(driver, selenium.webdriver.edge.webdriver.WebDriver):
                raise TypeError('\nERROR: driver must be of type '
                                '"selenium.webdriver.edge.webdriver.WebDriver"\n')
            return None

        raise TypeError('\nERROR: unsupported webdriver type: '
                        '{}. Browser: {}\n'.format(type(driver),
                                                   driver.capabilities['browserName']))

    @staticmethod
    def __set_locator(locator: tuple):
        """
        Check if locator of type: tuple
        :param locator:
        :return:
        """
        if not isinstance(locator, tuple):
            raise TypeError('\nERROR: locator must be of type TUPLE\n')
        return locator


#!/usr/bin/env python3
# caesar

from sys import argv
from cs50 import get_string

def prompt_and_exit():
    # Prompt the user for the usage
    print('Usage: python caesar.py k')
    exit(1)

def check_key():
    # Ensure that command line argument is a digit
    if not argv[1].isdigit():
        prompt_and_exit()
    # Convert argv[1] to integer
    key = int(argv[1])
    if key < 0:  # Ensure that command line argument is positive number
        prompt_and_exit()
    return key

def main():
    # Ensure that command line argument is one
    if len(argv) != 2:
        prompt_and_exit()
    key = check_key()
    # Ask user for the input
    text = get_string("plaintext: ")
    print("ciphertext: ", end='')
    for c in text:  # Iterate over every character in the plaintext and encrypt
        if c.isupper():
            print(chr(ord('A') + (ord(c) - ord('A') + key) % 26), end='')
        elif c.islower():
            print(chr(ord('a') + (ord(c) - ord('a') + key) % 26), end='')
        else:
            print(c, end='')
    print()
    return 0

if __name__ == '__main__':
    main()


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

import cv2
import glob

IMAGE_SIZE = 80
COLOR_NUM = 64

def resize():
    image_files = glob.glob('t/*')

    for index, image_path in enumerate(image_files):
        image = cv2.imread(image_path)
        resize_image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
        cv2.imwrite('r/t%06d.jpg' % index, resize_image)

    image_files = glob.glob('e/*')

    for index, image_path in enumerate(image_files):
        image = cv2.imread(image_path)
        resize_image = cv2.resize(image, (IMAGE_SIZE, IMAGE_SIZE))
        cv2.imwrite('r/e%06d.jpg' % index, resize_image)

if __name__ == '__main__':
    resize()


def nextMove(n, r, c, grid):
    bot_pos = r,c
    g = Grid(n, bot_pos, grid)
    g.solve()
    return g.solution[0]

class Node():
    def __init__(self, state, parent, action):
        self.state = state
        self.parent = parent
        self.action = action

class Queue():
    def __init__(self):
        self.q = []

    def put(self, node):
        self.q.append(node)

    def get(self):
        if self.is_empty():
            raise Exception("empty queue")
        return self.q.pop(0)

    def contain_state(self, state):
        return any(node.state==state for node in self.q)

    def is_empty(self):
        return len(self.q)==0

class Grid():
    def __init__(self, n, bot_pos, grid):
        self.height = n
        self.width = n
        str_grd = ''.join(grid)
        self.start = bot_pos
        self.goal = None

        #validate start and goal
        if str_grd.count('m') != 1:
            raise Exception("grid must have exactly one player")
        if str_grd.count('p') != 1:
            raise Exception("grid must have exactly one princess")

        # Get princess and player position
        for i in range(self.height):
            for j in range(self.width):
                if self.start is not None and self.goal is not None:
                    break
                if grid[i][j] == 'm':
                    self.start = i, j
                elif grid[i][j] == 'p':
                    self.goal = i, j

        self.solution = None

    def neighbors(self, state):
        row, col = state
        candidate = [
            ("UP", (row - 1, col)),
            ("DOWN", (row + 1, col)),
            ("LEFT", (row, col - 1)),
            ("RIGHT", (row, col + 1))
        ]
        neighbors = []
        for action,(r,c) in candidate:
            if 0<=r<=self.height and 0<=c<=self.width:
                neighbors.append((action, (r,c)))
        return neighbors

    def solve(self):
        """Find the princess"""
        start = Node(self.start, None, None)
        frontier = Queue()
        frontier.put(start)

        self.explored = set()

        while True:
            # If nothing is left in the frontier, then no path
            if frontier.is_empty():
                raise Exception("no solution")

            node = frontier.get()
            # check if node is the goal state
            if node.state == self.goal:
                actions = []
                #actions.append()
                while node.parent:
                    actions.append(node.action)
                    node = node.parent
                actions.reverse()
                self.solution = actions
                break

            self.explored.add(node.state)

            # add neighbors to the frontier
            for action, state in self.neighbors(node.state):
                if not frontier.contain_state(state) and state not in self.explored:
                    child = Node(state, node, action)
                    frontier.put(child)

n = int(input())
r,c = [int(i) for i in input().strip().split()]
grid = []
for i in range(0, n):
    grid.append(input())
print(nextMove(n, r, c, grid))


#!/usr/local/bin/python3
# send urgent data from client before handshake has completed

import os
import sys
import threading
from addr import *
from scapy.all import *

client=os.getpid() & 0xffff
relay=int(sys.argv[2])
server=int(sys.argv[1])

class Sniff1(threading.Thread):
	filter = None
	captured = None
	packet = None
	def __init__(self):
		# clear packets buffered by scapy bpf
		sniff(iface=LOCAL_IF, timeout=1)
		super(Sniff1, self).__init__()
	def run(self):
		self.captured = sniff(iface=LOCAL_IF, filter=self.filter,
		    count=1, timeout=5)
		if self.captured:
			self.packet = self.captured[0]

ip=IP(src=FAKE_NET_ADDR, dst=REMOTE_ADDR)

print("Send SYN packet, receive SYN+ACK")
syn=TCP(sport=client, dport=relay, seq=0, flags='S', window=(2**16)-1)
synack=sr1(ip/syn, iface=LOCAL_IF, timeout=5)

if synack is None:
	print("ERROR: No matching SYN+ACK packet received")
	exit(1)

print("Expect spliced SYN")
sniffer = Sniff1();
sniffer.filter = "src %s and dst %s and tcp port %u " \
    "and tcp[tcpflags] = tcp-syn" % (ip.dst, ip.src, server)
sniffer.start()
time.sleep(1)

print("Send ACK packet to finish handshake")
ack=TCP(sport=synack.dport, dport=synack.sport,
    seq=1, ack=synack.seq+1,  flags='A')
send(ip/ack, iface=LOCAL_IF)

sniffer.join(timeout=7)
spliced_syn = sniffer.packet

if spliced_syn is None:
	print("ERROR: No spliced SYN packet received")
	exit(1)

print("Send 20 bytes payload and one urgent byte")
data="0123456789Xabcdefghij"
payload=TCP(sport=synack.dport, dport=synack.sport, urgptr=11,
    seq=1, ack=synack.seq+1,  flags='APU')/data
payload_ack=sr1(ip/payload, iface=LOCAL_IF)

if payload_ack is None:
	print("ERROR: No payload ACK packet received")
	exit(1)
if payload_ack.ack != len(data)+1:
	print("ERROR: Expected ack %d, got %d in payload ACK" %
	    (len(data)+1, payload_ack.ack))
	exit(1)

time.sleep(1)

print("Expect spliced urgent payload")
sniffer = Sniff1();
sniffer.filter = "src %s and dst %s and tcp port %u " \
    "and tcp[tcpflags] = tcp-ack|tcp-urg" % (ip.dst, ip.src, server)
sniffer.start()
time.sleep(1)

print("Send spliced SYN+ACK packet to finish handshake")
spliced_synack=TCP(sport=spliced_syn.dport, dport=spliced_syn.sport,
    seq=0, ack=spliced_syn.seq+1, flags='SA')
spliced_ack=sr1(ip/spliced_synack, iface=LOCAL_IF)

if spliced_ack is None:
	print("ERROR: No spliced ACK packet received")
	exit(1)

sniffer.join(timeout=7)
spliced_payload = sniffer.packet

if spliced_payload is None:
	print("ERROR: No spliced urgent payload packet received")
	exit(1)
if spliced_payload.seq != spliced_ack.seq:
	print("ERROR: Expected seq %d, got %d in spliced payload" %
	    (spliced_ack.seq, spliced_payload.seq))
	exit(1)
if spliced_payload.urgptr != 11:
	print("ERROR: Expected urgptr %d, got %d in spliced payload" %
	    (11, spliced_payload.urgptr))
	exit(1)

print("Expect spliced ACK retransmission")
sniffer = Sniff1();
sniffer.filter = "src %s and dst %s and tcp port %u " \
    "and tcp[tcpflags] = tcp-ack" % (ip.dst, ip.src, server)
sniffer.start()
time.sleep(1)

print("Retransmit spliced SYN+ACK packet to trigger ACK")
send(ip/spliced_synack, iface=LOCAL_IF)

sniffer.join(timeout=7)
spliced_ack_retrans = sniffer.packet

if spliced_ack_retrans is None:
	print("ERROR: No spliced ACK retransmit packet received")
	exit(1)
if spliced_ack_retrans.seq != spliced_syn.seq+1+len(data):
	print("ERROR: Expected seq %d, got %d in retransmitted spliced ack" %
	    (spliced_syn.seq+1+len(data), spliced_ack_retrans.seq))
	exit(1)
if spliced_ack_retrans.ack != 1:
	print("ERROR: Expected ack %d, got %d in retransmitted spliced ack" %
	    (1, spliced_ack_retrans.ack))
	exit(1)
if spliced_ack_retrans.len-20-20 != 0:
	print("ERROR: Expected len %d, got %d in retransmitted spliced ack" %
	    (0, spliced_ack_retrans.len-20-20))
	exit(1)

print("Kill connections with RST")
spliced_rst=TCP(sport=spliced_ack.dport, dport=spliced_ack.sport,
    seq=1, ack=spliced_ack.seq, flags='RA')
send(ip/spliced_rst, iface=LOCAL_IF)
rst=TCP(sport=synack.dport, dport=synack.sport,
    seq=payload_ack.ack, ack=synack.seq+1, flags='RA')
send(ip/rst, iface=LOCAL_IF)

exit(0)


from api import app
from api.db_config import con, cur
from flask import request, jsonify
from flask_jwt_extended import get_jwt_identity, jwt_required
from api.v2.validations.models import Validations

validationObject = Validations()

class OrderCreation():

	@jwt_required
	def order_request(self):
		email = get_jwt_identity()
		email_check = validationObject.email_check(email)
		pick_up = request.json['pick_up']
		drop_off = request.json['drop_off']
		recipient_name = request.json['recipient_name']
		weight = request.json['weight']

		if any(user_input == "" for user_input in (pick_up, drop_off, recipient_name,weight)):
			return "fields cannot be empty"

		if weight <= 0:
			return "weight cannot be zero"

		if email_check:
			role_check = validationObject.role_check(email)
			role = "admin"

			if role_check != role:
				result = cur.execute ("SELECT name, email FROM users WHERE email = '{}';".format(email))
				result = cur.fetchall()

				if result:
					output = {"cost" : 200,
						"status" : "Order requested",
						"pick_up": pick_up,
						"drop_off": drop_off,
						"recipient_name" : recipient_name,
						"weight" : weight,
						"current_location": request.json['pick_up']
						}

					for row in result:
						output.update({'name': row[0], 'email': row[1] })

					cur.execute("INSERT INTO orders(sender_name, sender_email, pick_up, drop_off, recipient_name,weight, cost, status, current_location) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)", (output['name'], output['email'], output['pick_up'], output['drop_off'], output['recipient_name'], output['weight'], output['cost'], output['status'], output['current_location']))
					con.commit()
					return "Order created"

			return "Orders cannot be created on admin account"

		return "email not registered"


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

load("@flatbuffers//:build_defs.bzl", "flatc_path")

def flatbuffer_schema_compat_test(name, ref_schema, schema):
    """Generates a test for schema binary compatibility.

    Generates a test that the specified schema file is binary backwards
    compatible with a reference schema (e.g. a previous version of the
    schema).

    Note: currently this build macro requires that the schema be a single
    fully self-contained .fbs file; it does not yet support includes.
    """

    native.genrule(
        name = name + "_gen",
        srcs = [ref_schema, schema],
        outs = [name + "_test.sh"],
        tools = [flatc_path],
        cmd = ("echo $(rootpath {}) --conform $(rootpath {}) $(rootpath {}) > $@"
            .format(flatc_path, ref_schema, schema)),
    )

    native.sh_test(
        name = name,
        srcs = [name + "_test.sh"],
        data = [flatc_path, ref_schema, schema],
    )