from imgaug import HeatmapsOnImage

from aichallenger import AicGaussian
from pathlib import Path
import cv2
import numpy as np
from aichallenger.defines import Box, Joint, Person, Crowd
from typing import Tuple, List

from constants.enum_keys import HK
from constants.keypoints import aic_bones

class AicAffinityField(AicGaussian):
    """
    Construct "pafs"
    """
    def __init__(self, data_path: Path, is_train: bool, resize_img_size: tuple, heat_size: tuple, **kwargs):
        super().__init__(data_path, is_train, resize_img_size, heat_size, **kwargs)
        self.__paf_line_width = 2

    def __getitem__(self, index) -> dict:
        res = super().__getitem__(index)
        heat_keypoints = res[HK.HEAT_KEYPOINTS]  # Shape: (PeJX) Person,Joint,X
        visibility = res[HK.VISIBILITIES]  # Shape: (PeJ)
        # aic_bones.shape: (BE) Bone,Endpoint
        bones = np.array(aic_bones) - 1
        coord = np.take(heat_keypoints, bones, axis=1)  # Shape:(Person, Bone, Endpoint, X)
        map_PeBHW = [cv2.line(np.zeros(self.heat_size, dtype=np.uint8), (x1, y1), (x2, y2), 255, self.__paf_line_width)
                       for x1, y1, x2, y2 in coord.reshape(-1, 4).astype(np.int)]
        # To 0~1
        map_PeBHW = np.asarray(map_PeBHW, dtype=np.float32) / 255.
        map_PeBHW = map_PeBHW.reshape(coord.shape[0], coord.shape[1], self.heat_size[1], self.heat_size[0])
        # Masks
        j_vis = np.take(visibility, bones, axis=1)  # Shape:(Person, Bone, Endpoint)
        j_vis_all = np.logical_or(j_vis == 1, j_vis == 2)  # Shape: (PeBE)
        b_vis_all = np.logical_and(j_vis_all[..., 0], j_vis_all[..., 1]).astype(np.float32)  # Shape: (PeB)
        b_vis_all = np.expand_dims(b_vis_all, (2, 3))  # Shape: (PeBHW)
        j_vis_noocc = (j_vis == 1)  # Shape: (PeBE)
        b_vis_noocc = np.logical_and(j_vis_noocc[..., 0], j_vis_noocc[..., 1]).astype(np.float32)  # Shape: (PeBE)
        b_vis_noocc = np.expand_dims(b_vis_noocc, (2, 3))  # Shape: (PeBHW)
        paf_vis_all = map_PeBHW * b_vis_all
        paf_vis_noocc = map_PeBHW * b_vis_noocc
        paf_vis_all = paf_vis_all.max(axis=0, initial=0)  # Shape: (BHW)
        paf_vis_noocc = paf_vis_noocc.max(axis=0, initial=0)
        res[HK.PAF_ALL] = paf_vis_all  # Shape: (BHW)
        res[HK.PAF_NOT_OCC] = paf_vis_noocc

        if 'visual_debug' in self.kwargs and self.kwargs.get('visual_debug'):
            debug_paf_all = paf_vis_all.max(axis=0, initial=0)  # HW
            debug_paf_all = HeatmapsOnImage(debug_paf_all, shape=self.heat_size, min_value=0.0, max_value=1.0)
            res[HK.DEBUG_PAF_ALL] = debug_paf_all.draw_on_image(res[HK.AUG_IMAGE])[0]
            debug_paf_noocc = paf_vis_noocc.max(axis=0, initial=0)
            debug_paf_noocc = HeatmapsOnImage(debug_paf_noocc, shape=self.heat_size, min_value=0.0, max_value=1.0)
            res[HK.DEBUG_PAF_NOOCC] = debug_paf_noocc.draw_on_image(res[HK.AUG_IMAGE])[0]
        return res


import tensorflow as tf
import os
from models.data_setup import data_generators
from models.vgg16 import vgg16_base, vgg16_dropout, vgg16_weights

config = tf.compat.v1.ConfigProto()
config.gpu_options.allow_growth = True
config.log_device_placement = True
sess = tf.compat.v1.Session(config=config)
tf.compat.v1.keras.backend.set_session(sess)

IMG_DIM = os.getenv('IMG_DIM', 150)
epochs = os.getenv('EPOCHS', 100)
batch_size = os.getenv('BATCH_SIZE', 64)
i = 6
classes, train_data_gen, val_data_gen, test_data_gen = data_generators(i, batch_size=batch_size, IMG_DIM=IMG_DIM)

# TRAIN MODELS
vgg16_base(train_data_gen, val_data_gen, test_data_gen, num_classes=classes, IMG_DIM=IMG_DIM, epochs=epochs)
vgg16_weights(train_data_gen, val_data_gen, test_data_gen, num_classes=classes, IMG_DIM=IMG_DIM, epochs=epochs)
vgg16_dropout(train_data_gen, val_data_gen, test_data_gen, num_classes=classes, IMG_DIM=IMG_DIM, epochs=epochs, dropout=0.1)
vgg16_dropout(train_data_gen, val_data_gen, test_data_gen, num_classes=classes, IMG_DIM=IMG_DIM, epochs=epochs, dropout=0.2)


from osv import osv, fields

class stock_picking(osv.osv):
    _inherit = 'stock.picking'

    def _invoice_hook(self, cr, uid, picking, invoice_id):
        invoice_pool = self.pool.get('account.invoice')
        res = super(stock_picking, self)._invoice_hook(cr, uid, picking, invoice_id)
        if picking and invoice_id:
            val = {'picking_id': picking.id}
            if picking.sale_id:
                val['sale_id'] = picking.sale_id.id
            invoice_pool.write(cr, uid, invoice_id, val, context={})
        return res

stock_picking()

# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:


from catcam.curses_image import CursesFrameRenderer
from numpy.testing import assert_array_equal
import numpy as np
from PIL import Image
from catcam.xterm_colors import xterm_256_colors

def test_render_frame():
    # Make tiny image with one black pixel and one white pixel
    white, black = (255, 255, 255), (0, 0, 0)
    image = Image.fromarray(np.array([[white, black]], np.uint8))
    curses_frame_renderer = CursesFrameRenderer((2, 1))
    frame = curses_frame_renderer.render_frame(image)

    character_gradient = curses_frame_renderer.character_transformer.character_gradient
    lightest_character = character_gradient[-1]
    darkest_character = character_gradient[0]
    expected_colors = [[xterm_256_colors.index(white), xterm_256_colors.index(black)]]
    expected_characters = [[lightest_character, darkest_character]]

    assert_array_equal(expected_colors, frame.colors)
    assert_array_equal(expected_characters, frame.characters)


from User97 import User

class Computer:

    def __init__(self, status):
        self.status = status  # состояние вкл\выкл

    def is_on(self):  # проверка на состояние вкл\выкл
        return self.status  # Возвращаем True - включен, False - выключен

    def calculator(self):
        first_number = float(input("Введите первое число: "))
        sign = input("Введите знак опреции (* , **, +, -, /): ")
        second_number = float(input("Введите второе число: "))

        if sign == "*":
            print(first_number * second_number)
        if sign == "**":
            print(first_number ** second_number)
        if sign == "+":
            print(first_number + second_number)
        if sign == "-":
            print(first_number - second_number)
        if sign == "/":
            print(first_number / second_number)

    def transfer(self):
        num = int(input("Введите число для перeвода\n"))
        print(bin(num)[2:])

    def built(self):

        import matplotlib.pyplot as plt

        k = float(input("Введите угловой коэффициент: "))
        b = float(input("Введите значение свободного члена: "))
        diapazon_x1 = int(input("Введите  начало диапазона: "))
        diapazon_x2 = int(input("Введите  конец диапазона: "))
        value_y = []
        value_x = []
        for i in range(diapazon_x1, diapazon_x2):
            y = k * i + b
            value_y.append(y)
            value_x.append(i)
        plt.plot(value_x, value_y, color='aqua')
        plt.show()

    def application_func(self, user):  # предлагает пользователю ввести имя приложения
        print("Выберите приложение из списка:")
        print("> Калькулятор")
        print("> Перевод целого числа из 10-ой системы в 2-ую")
        print("> Построение графика линейной функции (только для Администратора)")
        print("> Выключить компьютер")
        self.app = user.set_application()  # input("Введите первое слово названия приложения:\n")
        if self.app == "Калькулятор":   # действие с двумя числами
            self.calculator()
        elif self.app == "Перевод":
            self.transfer()
        elif self.app == "Построение" and user.profile == "Администратор":  # y = kx + b
            self.built()
        elif self.app == "Построение" and user.profile != "Администратор":
            print("Вам требуются права Администратора")
        elif self.app == "Выключить":
            self.status = False
        else:
            print("Неверно введено приложение!")

a = Computer(True)
b = User()
b.set_profile()

while a.is_on():
    a.application_func(b)


import pytest
import os

from dev_detect.storage import DatabaseStorage

@pytest.fixture(scope='function')
def storage(request, tmpdir):
    database_dir = tmpdir.mkdir('dev-detect')
    db_path = os.path.join(database_dir, 'dev-detect.db')
    storage = DatabaseStorage(db_path)

    if hasattr(request, 'param'):
        for item in request.param:
            print("Storing item {}".format(item))
            storage.store(item)

    yield storage

def pytest_make_parametrize_id(config, val):
    return repr(val)


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

from django.db import migrations, models

class Migration(migrations.Migration):

    dependencies = [
        ('heritage', '0006_auto_20160101_2028'),
    ]

    operations = [
        migrations.AlterField(
            model_name='session',
            name='number',
            field=models.CharField(verbose_name='Session number', max_length=3),
        ),
    ]


# -*- coding: utf-8 -*-
"""
Created on Sat Sep 24 12:09:22 2022
File Name : .py
@author: BAESORI

"""
"""
 QUIZ B :
     1 ~ 100까지 중복을 허용하지 않는 난수 100개를 뽑아서 오름차순으로 정렬하는 코드 Solution 5 가지
"""
import random
r = random.random()
print('r=', r)

# 1 구상 > 난수 100개 > 난수를 리스트에 넣고 중복제거 > 100이 될때까지
def rand(N):
    rd = []
    for i in range(100) :
        r = random.randint(1, 100) # 난수발생
        rd.append(r) #난수 저장
    return rd

# if len(rd) == 100 :
    # break
# print(rd)

# 2 구상 > 난수 100개 > 난수를 리스트에 넣고 셋으로 중복제거 > 100이 될때까지
# 리스트[값]
def rand01(N):
    rd = []
    for i in range(100) :
        rd.append( random.randint( 1, 100 ) ) # 난수발생
        srd = set(rd)
        rd = list(srd)
        if len(rd) == 100 :
            break
    return rd

# 2-1 셋연산을 쓰지 않고 리스트 안에 있는 데이터 중에서 확인
def findNum( array, x ) :
    N = len( array )
    for k in range( N ) :
        if ( array[k] == x ):
            return True
    return False

def rand02( N = 100 ):
    rd = []
    cnt = N
    while ( cnt > 0 ) :
        x = random.randint( 1, 100 ) # floating 시간함수 정규분포로 만들 수 있음
        if ( findNum( rd, x ) ) :
            continue
        else :
            rd.append( x )
            cnt -= 1
    return rd

# 3 최초 구상했던 것
def rand03(N):
    rd = []
    for i in range(100) :
        rd.append( random.randint( 1, 100 ) ) # 난수발생
        srd = set(rd)
        rd= list(srd)
        for i in range(100) :
            rd.append( random.randint( 1, 100 ) )
            srd = set(rd)
            rd= list(srd)
    return srd

# 4 append 없이 랜덤 100까지

# if len(rd) == 100 :
    # break
# print(rd)

# 1 while 문 예시 sum( 1 , 100 )
def sigma01( N = 100 ) :
    S = 0
    k = 1
    while(k < (N + 1) ) :
        S = S + k
        k = k + 1
    return S

def sigma01_test( N = 100 ):
    for k in range( 1, N ) :
        print( sigma01( k ) )

# 2 while 문 예시 sum( 1 , 100 )
def sigma02( N = 100 ) :
    S = 0
    k = 1
    while(k < (N + 1) ) :
        S = S + k
        k = k + 1
    return S

def sigma02_test( N = 100 ):
    SL = [0] * ( N + 1 )
    print( SL )
    k = 1
    # for k in range( 1, N ) :
    while ( k < ( N + 1 ) ) :
        SL = sigma02( k )
        k = k + 1
    print( SL )

# 3 while 문 예시 sum( 1 , 100 )
def sigma03( N = 100 ) :
    S = 0
    k = 1
    while(k < (N + 1) ) :
        S = S + k
        k = k + 1
    return S

def sigma03_test( N = 100 ):
    SL = [0] * ( N + 1 )
    # print( SL )
    k = 1
    # for k in range( 1, N ) :
    while ( k < ( N + 1 ) ) :
        SL[k] = sigma03( k )
        k = k + 1
    print( SL )


import codecs
import fnmatch
import os
import random
import sys
import re
from collections import *
import nltk
import numpy as np
import tensorflow as tf
from six.moves import cPickle as pickle
import logging

import csv
# for long CSV
maxInt = sys.maxsize
decrement = True
while decrement:
	# decrease the maxInt value by factor 10
	# as long as the OverflowError occurs.
	decrement = False
	try:
		csv.field_size_limit(maxInt)
	except OverflowError:
		maxInt = int(maxInt / 10)
		decrement = True

class MyError(Exception):
  def __init__(self, value):
    self.value = value
  def __str__(self):
    return repr(self.value)

class TextDataHandler:
	_force_read_input = False
	_word_to_id = {}
	_id_to_word = {}
	_words = []
	_unknown_terms = set()
	_unknown_terms_freq = 0

	def __init__(self, all_doc_path, save_dir):

		files = Utilities.recursive_glob(all_doc_path, "*")
		Utilities.create_file_dir(save_dir)
		# base_name = os.path.basename(os.path.normpath(all_doc_path))
		# word_to_id
		word_to_id_pickle = os.path.join(save_dir, 'word_to_id.pkl')
		self._word_to_id = self._maybe_pickling(word_to_id_pickle, self._build_dict_from_a_set_of_file, files)

		# id_to_word
		id_to_word_pickle = os.path.join(save_dir, 'id_to_word.pkl')
		self._id_to_word = self._maybe_pickling(id_to_word_pickle, self._build_reverse_dict, self._word_to_id)

	def _maybe_pickling(self, pickle_name, func, *func_param):
		if os.path.exists(pickle_name) and not self._force_read_input:
			# You may override by setting force=True.
			print('%s already present - Skipping pickling.' % pickle_name)
			try:
				with open(pickle_name, 'rb') as f:
					data = pickle.load(f)
			except Exception as e:
				print('Unable to process data from', pickle_name, ':', e)
				raise
		else:
			data = func(*func_param)
			self.pickling(pickle_name, data)
		return data

	def pickling(self, pickle_file_name, data):
		print('Pickling %s' % pickle_file_name)
		try:
			with open(pickle_file_name, 'wb') as f:
				pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
		except Exception as e:
			logging.error('Unable to save data to', pickle_file_name, ':', e)

	@staticmethod
	def clean_str(string):
		"""
		string cleanin
		"""
		string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string)
		string = re.sub(r"\'s", " \'s", string)
		string = re.sub(r"\'ve", " \'ve", string)
		string = re.sub(r"n\'t", " n\'t", string)
		string = re.sub(r"\'re", " \'re", string)
		string = re.sub(r"\'d", " \'d", string)
		string = re.sub(r"\'ll", " \'ll", string)
		string = re.sub(r",", " , ", string)
		string = re.sub(r"!", " ! ", string)
		string = re.sub(r"\(", " \( ", string)
		string = re.sub(r"\)", " \) ", string)
		string = re.sub(r"\?", " \? ", string)
		string = re.sub(r"\s{2,}", " ", string)
		#       string = re.sub(r"[^A-Za-z0-9]", " ", string)
		return string.strip().lower()

	def read_words(self, filename):
		"""
		Tokenization using NLTK
		"""
		with tf.gfile.GFile(filename, "r") as f:
			return nltk.word_tokenize(TextDataHandler.clean_str(f.read()))

	def _build_dict_from_a_set_of_file(self, filenames):
		counter = Counter()
		file_cnt = len(filenames)
		cnt = 0
		for filename in filenames:
			if cnt % 500 == 0:
				print(str(cnt) + " out of " + str(file_cnt) + " has been processed")
			words = self.read_words(filename)
			counter.update(words)
			cnt += 1
		count_pairs = sorted(counter.items(), key=lambda x: (-x[1], x[0]))
		# if vocab_size == -1:
		# 	vocab_size = len(count_pairs)
		# words, _ = list(zip(*count_pairs[:vocab_size]))
		words, _ = list(zip(*count_pairs))
		word_to_id = dict(zip(words, range(1, len(words) + 1)))
		return word_to_id

	def get_vocab_size(self):
		if not self._word_to_id.values:
			raise MyError('first build the dictionary...')
		return len(self._word_to_id) + 1  # unknown

	def truncate_vocab(self, new_vocab_size):
		if new_vocab_size < 0:
			print("New Vocab Size:", self.get_vocab_size())
			return
		self._word_to_id = OrderedDict(sorted(self._word_to_id.items(), key=lambda item: item[1])[:new_vocab_size - 1])
		self._id_to_word = self._build_reverse_dict(self._word_to_id)
		print("New Vocab Size:", self.get_vocab_size())

	def _build_reverse_dict(self, original_dict):
		if not original_dict:
			raise MyError('first build the dictionary...')
		reverse_dict = dict(zip(original_dict.values(), original_dict.keys()))
		return reverse_dict

	def get_id_of_word(self, word):
		#     return self._word_to_id.get(word, 0) # dictionary['UNK'] = 0
		if word in self._word_to_id:
			return self._word_to_id[word]
		else:  # dictionary['UNK'] = 0
			self._unknown_terms.add(word)
			self._unknown_terms_freq += 1
			return 0

	def get_word_of_id(self, i):
		if i == 0:
			word = 'UNK'
		elif i in self._id_to_word:
			word = self._id_to_word[i]
		else:
			print(i)
			raise MyError('unknown_id')
		return word

	def word_list_to_id_list(self, words):
		return [self.get_id_of_word(word) for word in words]

	def id_list_to_word_list(self, ids):
		return [self.get_word_of_id(i) for i in ids]

	def get_vocab_dict(self):
		return self._word_to_id.copy()

	def get_rev_vocab_dict(self):
		return self._id_to_word.copy()

	def get_vocab(self):
		if not self._words:
			self._words = list(self._word_to_id)
		return self._words

	def get_one_hot_vector(self, wordIds_vec):
		vocab_size = self.get_vocab_size()
		vec = (np.arange(vocab_size) == np.array(wordIds_vec)[:, None]).astype(np.float32)
		return np.array(vec)

	def get_ids_from_one_hot_vector(self, one_hot_Vec):
		#to be implimented
		return None

	def get_binary_vector(self, wordIds_vec):
		vec = np.zeros(self.get_vocab_size(), dtype=int)
		inices = list(set(wordIds_vec))
		vec[inices] = 1
		return np.array(vec)

	def get_ids_from_binary_vector(self, binary_vector):
		return np.nonzero(binary_vector)

	def get_freq_vector(self, wordIds_vec):
		vec = np.zeros(self.get_vocab_size(), dtype=int)
		counter = Counter(wordIds_vec)
		vec[list(counter.keys())] = list(counter.values())
		return np.array(vec)

	def get_ids_from_freq_vector(self, freq_vector):
		# return [[freq_vector[i]] * i for i in np.nonzero(freq_vector)]
		return None

class BatchCreator4RNN:
	def __init__(self, tensor, batch_size, seq_length):
		self.tensor = tensor
		self.batch_size = batch_size
		self.seq_length = seq_length
		self.create_batches()
		self.pointer = 0

	# abcd -> x:abc y:bcd
	def create_batches(self):
		self.num_batches = int(self.tensor.size / (self.batch_size *
																							 self.seq_length))
		if self.num_batches == 0:
			assert False, "Not enough data. Make seq_length and batch_size small."

		self.tensor = self.tensor[:self.num_batches * self.batch_size * self.seq_length]
		xdata = self.tensor
		ydata = np.copy(self.tensor)

		ydata[:-1] = xdata[1:]
		ydata[-1] = xdata[0]
		self.x_batches = np.split(xdata.reshape(self.batch_size, -1), self.num_batches, 1)
		self.y_batches = np.split(ydata.reshape(self.batch_size, -1), self.num_batches, 1)

	def next_batch(self):
		x, y = self.x_batches[self.pointer], self.y_batches[self.pointer]
		self.pointer += 1
		return x, y

	def reset_batch_pointer(self):
		self.pointer = 0

class Retrieval_Data_Util(object):
	doc_query_pairs = []

	def __init__(self, runres, qrel):
		with codecs.open(qrel, "r", encoding='utf-8', errors='ignore') as f:
			csv_reader = csv.reader(f, delimiter=' ', quoting=csv.QUOTE_NONE)
			for row in csv_reader:
				if row[3] == '1':
					self.doc_query_pairs.append((row[2], row[0]))
			f.close()
		self._runRes = runres

	def get_rel_qd(self):
		d = [tup[0] for tup in self.doc_query_pairs]
		q = [tup[1] for tup in self.doc_query_pairs]
		return d, q

	def get_pseudo_rel_qd(self, top_k):
		d = []
		q = []
		with codecs.open(self._runRes, "r", encoding='utf-8', errors='ignore') as f:
			csv_reader = csv.reader(f, delimiter=' ', quoting=csv.QUOTE_NONE)
			for row in csv_reader:
				if int(row[3]) <= top_k:
					d.append(row[2])
					q.append(row[0])
			f.close()
		return d, q

	def get_label(self, d, q):
		return (d, q) in self.doc_query_pairs

class Utilities():
	@staticmethod
	def shufflize(data, label):
		assert len(data) == len(label)
		perm = np.random.permutation(len(data))
		return data[perm], data[perm]

	@staticmethod
	def recursive_glob(treeroot, pattern):
		results = []
		for base, dirs, files in os.walk(treeroot):
			goodfiles = fnmatch.filter(files, pattern)
			results.extend(os.path.join(base, f) for f in goodfiles)
		return results

	@staticmethod
	def create_file_dir(filename):
		if not os.path.exists(os.path.dirname(filename)):
			try:
				os.makedirs(os.path.dirname(filename))
			except OSError as exc:  # Guard against race condition
				if exc.errno != errno.EEXIST:
					raise

	@staticmethod
	def sample_distribution(distribution):
		"""Sample one element from a distribution assumed to be an array of normalized
    probabilities.
    """
		r = random.uniform(0, 1)
		s = 0
		for i in range(len(distribution)):
			s += distribution[i]
			if s >= r:
				return i
		return len(distribution) - 1

	@staticmethod
	def random_distribution(vector_size):
		"""Generate a random column of probabilities."""
		b = np.random.uniform(0.0, 1.0, size=[1, vector_size])
		return b / np.sum(b, 1)[:, None]

	@staticmethod
	def accuracy(predictions, labels):
		return (100.0 * np.sum(np.argmax(predictions, 1) == np.argmax(labels, 1))
						/ predictions.shape[0])


import os
from input_output_management import run_test
from data_structures.linked_list import list_to_dllist

def dllist_to_hashmap(node):
    ll_dict = {}
    while node:
        if node.value not in ll_dict:
            ll_dict[node.value] = [node]
        else:
            ll_dict[node.value].append(node)
        node = node.next
    return ll_dict

def sprinkler_dllist_to_str(dllist):
    if not dllist:
        return ''
    output = dllist.value
    dllist = dllist.next
    while dllist:
        if dllist.value not in [',', '.']:
            output += ' '
        output += dllist.value
        dllist = dllist.next

    return output + '\n'

def txt_to_sprinkler_list(s):
    output = []
    words = s.split()
    for word in words:
        if word[-1] in ['.', ',']:
            output += [word[:-1], word[-1]]
        else:
            output += [word]

    return output

def comma_sprinkler(text):
    text_as_list = txt_to_sprinkler_list(text)
    dllist_h, dllist_t = list_to_dllist(text_as_list)
    dllist_hashmap = dllist_to_hashmap(dllist_h)

    prec_candidates = set()
    succ_candidates = set()
    prec_visited = set()
    succ_visited = set()

    # Looking for first candidates
    commas = dllist_hashmap.get(',', [])
    for comma in commas:
        next_val = comma.next.value
        prev_val = comma.prev.value
        if next_val not in succ_visited:
            succ_candidates.add(next_val)
        if prev_val not in prec_visited:
            prec_candidates.add(prev_val)

    if not commas:
        return text

    while prec_candidates or succ_candidates:
        if prec_candidates:
            prec_candidate = prec_candidates.pop()
            # print('dealing with: %s' % prec_candidate)
            prec_visited.add(prec_candidate)

            # Adding commas on the right, creating succ candidates
            for node in dllist_hashmap[prec_candidate]:
                next_val = node.next.value
                if next_val not in [',', '.']:
                    if next_val not in succ_visited:
                        succ_candidates.add(next_val)
                    node.add_right(',')

        elif succ_candidates:
            succ_candidate = succ_candidates.pop()
            # print('dealing with: %s' % succ_candidate)
            succ_visited.add(succ_candidate)

            # Adding commas on the left, creating prec candidates
            for node in dllist_hashmap[succ_candidate]:
                if node.prev:
                    prev_val = node.prev.value
                    if prev_val not in [',', '.']:
                        if prev_val not in prec_visited:
                            prec_candidates.add(prev_val)
                        node.add_left(',')

    return sprinkler_dllist_to_str(dllist_h)

if __name__ == '__main__':
    path = 'icpc2018data/B-comma/'
    sample_name = 'sample-2'
    run_test(path, comma_sprinkler)


import webapp2
import os
import jinja2

import hmac

from handlers.authhandler import Signup, Register, Login, Logout
from handlers.mainpagehandler import Landing, BlogFront,NewPost,LikeHandler,\
                                     UnLikeHandler,CommentHandler,PostPage,\
                                     DeletePost,EditPost,EditComment,DeleteComment

app = webapp2.WSGIApplication([('/', Landing),
                            ('/blog/?', BlogFront),
                            ('/blog/newpost', NewPost),
                            ('/blog/like/([0-9]+)', LikeHandler),
                            ('/blog/unlike/([0-9]+)', UnLikeHandler),
                            ('/blog/([0-9]+)/comment', CommentHandler),
                            ('/login', Login),
                            ('/blog/([0-9]+)', PostPage),
                            ('/blog/deletepost/([0-9]+)', DeletePost),
                            ('/blog/editpost/([0-9]+)', EditPost),
                            ('/blog/([0-9]+)/editcomment/([0-9]+)', EditComment),
                            ('/blog/([0-9]+)/deletecomment/([0-9]+)', DeleteComment),
                            ('/logout', Logout),
                            ('/signup', Register),
                            ],
                            debug=True)


def flatten(d):
    r = {}
    def f(x, s=""):
        for k, v in x.items():
            kk = (s + '/' + k).strip('/')
            if isinstance(v, dict):
                if len(v) == 0: r[kk] = ''
                else: f(v, s + '/' + k)
            else: r[kk] = v

    f(d)
    return r


# 주어진 문자열 word가 주어질 때, 해당 단어를 역순으로 뒤집은 결과를 출력하시오.
string = input()
reverse_string = string[::-1]
print(reverse_string)
# 같은 결과
a = input()
value = ''
for i in a:
    value = i + value
print(value)
# 같은 결과
b = input()
print(''.join(reversed(b)))
# 같은 결과
c = input()
for i in range(len(c)):
    print((c[len(c)-i-1]), end='')


from typing import TYPE_CHECKING, Dict, Iterable, Iterator, Mapping, Sequence, Union

from pip._vendor.resolvelib.providers import AbstractProvider

from .base import Candidate, Constraint, Requirement
from .factory import Factory

if TYPE_CHECKING:
    from pip._vendor.resolvelib.providers import Preference
    from pip._vendor.resolvelib.resolvers import RequirementInformation

    PreferenceInformation = RequirementInformation[Requirement, Candidate]

    _ProviderBase = AbstractProvider[Requirement, Candidate, str]
else:
    _ProviderBase = AbstractProvider

# Notes on the relationship between the provider, the factory, and the
# candidate and requirement classes.
#
# The provider is a direct implementation of the resolvelib class. Its role
# is to deliver the API that resolvelib expects.
#
# Rather than work with completely abstract "requirement" and "candidate"
# concepts as resolvelib does, pip has concrete classes implementing these two
# ideas. The API of Requirement and Candidate objects are defined in the base
# classes, but essentially map fairly directly to the equivalent provider
# methods. In particular, `find_matches` and `is_satisfied_by` are
# requirement methods, and `get_dependencies` is a candidate method.
#
# The factory is the interface to pip's internal mechanisms. It is stateless,
# and is created by the resolver and held as a property of the provider. It is
# responsible for creating Requirement and Candidate objects, and provides
# services to those objects (access to pip's finder and preparer).

class PipProvider(_ProviderBase):
    """Pip's provider implementation for resolvelib.

    :params constraints: A mapping of constraints specified by the user. Keys
        are canonicalized project names.
    :params ignore_dependencies: Whether the user specified ``--no-deps``.
    :params upgrade_strategy: The user-specified upgrade strategy.
    :params user_requested: A set of canonicalized package names that the user
        supplied for pip to install/upgrade.
    """

    def __init__(
        self,
        factory,  # type: Factory
        constraints,  # type: Dict[str, Constraint]
        ignore_dependencies,  # type: bool
        upgrade_strategy,  # type: str
        user_requested,  # type: Dict[str, int]
    ):
        # type: (...) -> None
        self._factory = factory
        self._constraints = constraints
        self._ignore_dependencies = ignore_dependencies
        self._upgrade_strategy = upgrade_strategy
        self._user_requested = user_requested

    def identify(self, requirement_or_candidate):
        # type: (Union[Requirement, Candidate]) -> str
        return requirement_or_candidate.name

    def get_preference(
        self,
        identifier: str,
        resolutions: Mapping[str, Candidate],
        candidates: Mapping[str, Iterator[Candidate]],
        information: Mapping[str, Iterator["PreferenceInformation"]],
    ) -> "Preference":
        """Produce a sort key for given requirement based on preference.

        The lower the return value is, the more preferred this group of
        arguments is.

        Currently pip considers the followings in order:

        * Prefer if any of the known requirements points to an explicit URL.
        * If equal, prefer if any requirements contain ``===`` and ``==``.
        * If equal, prefer if requirements include version constraints, e.g.
          ``>=`` and ``<``.
        * If equal, prefer user-specified (non-transitive) requirements, and
          order user-specified requirements by the order they are specified.
        * If equal, order alphabetically for consistency (helps debuggability).
        """

        def _get_restrictive_rating(requirements):
            # type: (Iterable[Requirement]) -> int
            """Rate how restrictive a set of requirements are.

            ``Requirement.get_candidate_lookup()`` returns a 2-tuple for
            lookup. The first element is ``Optional[Candidate]`` and the
            second ``Optional[InstallRequirement]``.

            * If the requirement is an explicit one, the explicitly-required
              candidate is returned as the first element.
            * If the requirement is based on a PEP 508 specifier, the backing
              ``InstallRequirement`` is returned as the second element.

            We use the first element to check whether there is an explicit
            requirement, and the second for equality operator.
            """
            lookups = (r.get_candidate_lookup() for r in requirements)
            cands, ireqs = zip(*lookups)
            if any(cand is not None for cand in cands):
                return 0
            spec_sets = (ireq.specifier for ireq in ireqs if ireq)
            operators = [
                specifier.operator for spec_set in spec_sets for specifier in spec_set
            ]
            if any(op in ("==", "===") for op in operators):
                return 1
            if operators:
                return 2
            # A "bare" requirement without any version requirements.
            return 3

        rating = _get_restrictive_rating(r for r, _ in information[identifier])
        order = self._user_requested.get(identifier, float("inf"))

        # HACK: Setuptools have a very long and solid backward compatibility
        # track record, and extremely few projects would request a narrow,
        # non-recent version range of it since that would break a lot things.
        # (Most projects specify it only to request for an installer feature,
        # which does not work, but that's another topic.) Intentionally
        # delaying Setuptools helps reduce branches the resolver has to check.
        # This serves as a temporary fix for issues like "apache-airlfow[all]"
        # while we work on "proper" branch pruning techniques.
        delay_this = identifier == "setuptools"

        return (delay_this, rating, order, identifier)

    def find_matches(
        self,
        identifier: str,
        requirements: Mapping[str, Iterator[Requirement]],
        incompatibilities: Mapping[str, Iterator[Candidate]],
    ) -> Iterable[Candidate]:
        def _eligible_for_upgrade(name):
            # type: (str) -> bool
            """Are upgrades allowed for this project?

            This checks the upgrade strategy, and whether the project was one
            that the user specified in the command line, in order to decide
            whether we should upgrade if there's a newer version available.

            (Note that we don't need access to the `--upgrade` flag, because
            an upgrade strategy of "to-satisfy-only" means that `--upgrade`
            was not specified).
            """
            if self._upgrade_strategy == "eager":
                return True
            elif self._upgrade_strategy == "only-if-needed":
                return name in self._user_requested
            return False

        return self._factory.find_candidates(
            identifier=identifier,
            requirements=requirements,
            constraint=self._constraints.get(identifier, Constraint.empty()),
            prefers_installed=(not _eligible_for_upgrade(identifier)),
            incompatibilities=incompatibilities,
        )

    def is_satisfied_by(self, requirement, candidate):
        # type: (Requirement, Candidate) -> bool
        return requirement.is_satisfied_by(candidate)

    def get_dependencies(self, candidate):
        # type: (Candidate) -> Sequence[Requirement]
        with_requires = not self._ignore_dependencies
        return [r for r in candidate.iter_dependencies(with_requires) if r is not None]


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def swapPairs(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        new = ListNode(0)
        new.next = head
        p = new
        while p and p.next and p.next.next:
            f = p.next
            s = p.next.next
            last = p.next.next.next
            f.next = last
            s.next = f
            p.next = s
            p = p.next.next
        return new.next


# -*- coding: utf-8 -*-
"""
Created on Thu Apr 15 16:00:07 2021

@author: petil
"""

import math
from collections import Counter
import pandas as pd
import copy
import time as t
import random as rd

#Variable
pd.set_option('min_rows', 20)
pathApprentissage = 'data.csv';
pathTest = 'preTest.csv';
pathExecutable = 'finalTest.csv';
pathWrite = 'result.txt'
compteurVarConnu = 0;
afficherMatriceConfusion = True;
kMax = 10;
ratioValApprentissage = 0.75;

#Return le dataframe du csv fournit dans le path
def importDataWithDataFrame(path):
    df=pd.read_csv(path)
    if(df.axes[1][0] != '0'):
        df = pd.read_csv(path,header=None)
        df.columns = df.columns.map(str)

    df["prediction"] = "None";
    return df

def choixValApprentissage(data):
    global compteurVarConnu
    newdata = copy.deepcopy(data);
    newdata["prediction"] = "None";
    for i in newdata.index:
        if(rd.random() < ratioValApprentissage):
            newdata.loc[i,"prediction"] = newdata.loc[i,str(len(newdata.columns) - 2)]
            compteurVarConnu = compteurVarConnu + 1
    return newdata;

def calculEuclidien(i,j,data):
    res = 0;
    for k in range(0,(len(data.columns) - 2)):
        res = res + (data[str(k)][i] - data[str(k)][j])**2

    return [math.sqrt(res),data['prediction'][j]];

def knn(data,i):
    distancePointTest = []
    for j in data.loc[data['prediction'] != "None"].index:
            distancePointTest.append(calculEuclidien(i,j,data));

    #on trie
    distancePointTest = sorted(distancePointTest);

    return distancePointTest;

def remplissagePoint(data,k):
    newdata = copy.deepcopy(data);
    #pour tout les points qui n'ont pas de prédiction
    for i in newdata.loc[newdata['prediction'] == "None"].index:
            #On calcul distance euclidienne
            knnTab = knn(data,i);
            #On short au k choisi
            FinalChoixTab = [];
            for j in range(0,k+1):
                FinalChoixTab.append(knnTab[j][1]);
            #On determine la classe
            FinalChoixTab = Counter(FinalChoixTab);
            #on l'ajoute a la tab data
            newdata.loc[i, 'prediction'] = list(FinalChoixTab.most_common(1)[0])[0];
    return newdata;

def MatriceConfusion(data):
    #on affiche le header
    y_actu = pd.Series(data[str(len(data.columns) - 2)], name='Actual')
    y_pred = pd.Series(data['prediction'], name='Predicted')
    df_confusion = pd.crosstab(y_actu, y_pred)
    print(df_confusion)

def Prediction(data):
    global compteurVarConnu;
    nombrelementIncorrect = 0;
    #On fait les calcul
    for i in data.index:
        if not (data.loc[i, 'prediction'] == data.loc[i, str(len(data.columns) - 2)]):
            nombrelementIncorrect = nombrelementIncorrect + 1;
    print('nombrelementIncorrect : ',nombrelementIncorrect , "compteurVarConnu",compteurVarConnu);

    #On affiche
    if(afficherMatriceConfusion):
        MatriceConfusion(data)

    #On renvoie le pourcentage de réussite.
    print("Ratio :" , 100 - ((nombrelementIncorrect * 100)/(len(data) - compteurVarConnu)))
    return 100 - ((nombrelementIncorrect * 100)/(len(data) - compteurVarConnu));

def Bestk(data):
    #On Cherche le meillieur k
    tabBestK = []
    for k in range(1,kMax + 1):
        print("Debut Analyse du k = ",k ," : OK")
        #On rempli notre tableau avec les prévisions de l'algo
        newdata = copy.deepcopy(data)
        newdata = remplissagePoint(newdata,k);

        #prediction & matrice
        print("Debut Calcul ratioPrediction k = ",k ," : OK")
        ratioPrediction = Prediction(copy.deepcopy(newdata));
        tabBestK.append([k,ratioPrediction,newdata])
        print("Fin Analyse du k = ",k ," : OK")

    #on le choisi
    bestkval = tabBestK[0];
    for i in tabBestK[1:]:
        if(bestkval[1] < i[1]):
            bestkval = i;

    return bestkval;

def checklabel():
    allLabels = ['classA','classB','classC','classD','classE']
    #ce fichier s'attend à lire 3000 prédictions, une par ligne
    #réduisez nbLines en période de test.
    nbLines = 3000
    fd =open("result.txt",'r')
    lines = fd.readlines()

    count=0
    for label in lines:
    	if label.strip() in allLabels:
    		count+=1
    	else:
    		if count<nbLines:
    			print("Wrong label line:"+str(count+1))
    			break
    if count<nbLines:
    	print("Labels Check : fail!")
    else:
    	print("Labels Check : Successfull!")

def predictionFinal(bestApprentissage):
    newdata = importDataWithDataFrame(pathExecutable);
    newdata2 = bestApprentissage[2];
    newdata2 = newdata2.append(newdata, ignore_index=True);
    fichier = open(pathWrite, "w")
    for i in newdata.index:
        print(i)
        #On calcul distance euclidienne
        knnTab = knn(newdata2,i);
        #On short au k choisi
        FinalChoixTab = [];
        for j in range(0,bestApprentissage[0] + 1):
                FinalChoixTab.append(knnTab[j][1]);
        #On determine la classe
        FinalChoixTab = Counter(FinalChoixTab);
        print(Counter(FinalChoixTab));
        #on l'ajoute a la tab data
        newdata2.loc[i, 'prediction'] = list(FinalChoixTab.most_common(1)[0])[0];
        fichier.write(list(FinalChoixTab.most_common(1)[0])[0] + "\n")

    fichier.close()

    checklabel()

if __name__ == "__main__":
    #METHODE DATAFRAME
    début=t.process_time()
    print("Lancement de l'IA : OK ... ");
    #on recuperere les data , on remplie les colums d'apprentissage et on trouve le meilleur k
    data = choixValApprentissage(importDataWithDataFrame(pathApprentissage).append(importDataWithDataFrame(pathTest), ignore_index=True))

    bestApprentissage = Bestk(data)
    print("Valeur de k optimal trouvé : OK ... ");

    #on remet les bonne valeur de preTest pour enlever les erreurs
    bestApprentissage[2]['prediction'] = data[str(len(data.columns) - 2)]

    #on prédis les valeurs sans outpout
    predictionFinal(bestApprentissage)

    fin=t.process_time()
    temps=fin-début
    print("temps d'execution du programme : ",temps, "s")

    print("Fin du programme");


#!/usr/local/bin/python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/7 21:48
# @File    : jd_wishing_pool.py
# @Project : jd_scripts
# @Cron    : 45 */12 * * *
# @Desc    : 京东APP首页->京东众筹->众筹许愿池

from utils.jd_common import JdCommon
from config import USER_AGENT

CODE_KEY = 'jd_wishing_pool'

class JdWishingPool(JdCommon):
    """
    众筹许愿池
    """
    appid = '1E1NXxq0'

    code_key = CODE_KEY

    # 请求头
    headers = {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Referer': 'https://h5.m.jd.com/babelDiy/Zeus/4FdmTJQNah9oDJyQN8NggvRi1nEY/index.html',
        'User-Agent': USER_AGENT
    }

if __name__ == '__main__':
    from utils.process import process_start
    process_start(JdWishingPool, '众筹许愿池', code_key=CODE_KEY)


#!/usr/bin/env python
import rospy
from std_msgs.msg import String

def callback(data):
    rospy.loginfo(rospy.get_caller_id() + " [Robotics Indoor SDK] x, y = %s", data.data)

def listener():
    rospy.init_node('listener', anonymous=True)
    rospy.Subscriber("estimote_position", String, callback)
    rospy.spin()

if __name__ == '__main__':
    listener()


import docker
import json
import sqlite3
import multiprocessing as mp
import datetime
import os
import time
import indexes

stop=0

# 1. Data Volume measurement separately for DL and UL, per QCI per UE, by eNB
# 2. Throughput separately for DL and UL, per RAB per UE and per UE for the DL, per UE for the UL, by eNB
# 3. Packet Delay measurement, separately for DL and UL, per QCI per UE
# 4. Packet Loss rate measurement, separately for DL and UL per QCI per UE, by the eNB
# 5. Number of active UEs in RRC_CONNECTED

def get_num_servedUEs(client,id):
    container=client.containers.list(filters={"id":id})
    if len(container)==0:
        print ("no container running with given id")
        return
    logs = container[0].logs().decode("utf-8")
    st = 'Total number of UEs'
    res = logs.rfind(st)
    return logs[res+21]
def kill_meas_collection():
    global stop
    stop=1

def get_num_ActiveUEs(client,id):
    Num_ActiveUEs=[]
    container=client.containers.list(filters={"id":id})
    if len(container)==0:
        print ("no container running with given id")
        return
    run=container[0].exec_run('nr-cli --dump')
    temp1=(run.output.decode("utf-8")).split("\n")
    gnb_id=temp1[0]
    temp1=container[0].exec_run('nr-cli ' + gnb_id + ' -e ue-list')
    temp2=temp1.output.decode("utf-8")
    st = "ue-id:"
    res = [i for i in range(len(temp2)) if temp2.startswith(st, i)]
    Num_ActiveUEs.append(len(res))
    sum=0
    for i in Num_ActiveUEs:
        sum = sum + i
    return(sum)

def get_db():
    conn=sqlite3.connect('db_for_flask.db',isolation_level=None)
    return conn

def make_meas_table():
    conn = get_db()
    cursor=conn.cursor()
    """Clear existing data and create new table for measurements"""
    sql = "DROP TABLE IF EXISTS measurements"
    cursor.execute(sql)
    sql="CREATE TABLE measurements (ue_name TEXT NOT NULL, id TEXT NOT NULL, gnb_name TEXT NOT NULL, time_stamp TEXT NOT NULL, DL_Thp REAL, UL_Thp REAL, Latency REAL, Tx_Bytes REAL, Rx_Bytes REAL)"
    cursor.execute(sql)
    return cursor

def make_packet_table():
    conn = get_db()
    cursor=conn.cursor()
    """Clear existing data and create new table for measurements"""
    sql = "DROP TABLE IF EXISTS packets"
    cursor.execute(sql)
    sql="CREATE TABLE measurements (c_name TEXT NOT NULL, id TEXT NOT NULL, gnb_name TEXT NOT NULL, time_stamp TEXT NOT NULL, DL_Thp REAL, UL_Thp REAL, Latency REAL, Tx_Bytes REAL, Rx_Bytes REAL)"
    cursor.execute(sql)
    return cursor

def if_table_exists(cursor,table_name):
    sql="SELECT name FROM sqlite_master WHERE type='table' AND name='"+table_name+"'; "
    listOfTables = cursor.execute(sql).fetchall()
    if listOfTables == []:
        return False
    else:
        return True

def get_IPaddressOfUE(client,id):
    container=client.containers.list(filters={"id":id})
    if len(container)==0:
        print ("no container running with given id")
        return
    run=container[0].exec_run('ip -j a')
    ipraw=run.output.decode("utf-8")
    ipjson=json.loads(ipraw)
    ip=""
    for dicts in ipjson:
        if dicts['ifname']=='oaitun_ue1':
            for subdicts in dicts['addr_info']:
                if subdicts['label']=='oaitun_ue1':
                    ip=subdicts['local']
    return ip

def get_measurements(client):
    indexes.write_ip_index_table(client)
    global stop
    cursor = make_meas_table()
    while True:
        if stop ==1:
            stop=0
            break
        ts = datetime.datetime.now()
        processes =[ mp.Process(target=write_measurements, args=(client,server,cursor,str(ts))) for server in client.containers.list() if 'ue' in server.name]
        # Run processes
        for p in processes:
            p.start()
            time.sleep(90)

        # Exit the completed processes
        for p in processes:
            p.join()

def write_measurements(client,container,cursor,ts):
    IPaddr = get_IPaddressOfUE(client,container.id)
    print(IPaddr)
    if IPaddr != "":
        ue_listen_iperf = 'iperf -s -i 1 -B '+ IPaddr
        ext_ping_iperf= 'iperf -u -i 1 -fk -b 125M -c '+IPaddr+' -t 10 | awk -Wi -F\'[ -]+\' \'/sec/{print $3"-"$4" "$8}\''
        ue_ping_cmd="ping -I oaitun_ue1 192.168.72.135 -c 10"
        ext_container=client.containers.list(filters={"name":"rfsim5g-oai-ext-dn"})
        #'iperf -u -i 1 -fk -B'+ IPaddr+ '-b 125M -c 192.168.72.135 -t 10 | awk -Wi -F\'[ -]+\' \'/sec/{print $3"-"$4" "$8}\''
        gnb_name = get_gNB(client,container.id)
        print("GNB name",gnb_name)
        gnb_Container = client.containers.list(filters={"name":gnb_name.strip()})

        if len(container.name)==0:
            print ("UE container not found with given name")
            return
        try:
            ue_iperf_run=container.exec_run(['sh', '-c', ue_listen_iperf])
            ext_iperf_run=ext_container[0].exec_run(['sh', '-c', ext_ping_iperf])
            temp1=(ext_iperf_run.output.decode("utf-8"))
            temp2 = [int(s) for s in temp1.split() if s.isdigit() and int(s)>100]
            temp2 =sum(temp2)/len(temp2)
            ue_ping_run=container.exec_run(['sh', '-c', ue_ping_cmd])
            result=ue_ping_run.output.decode("utf-8")
            lat=[int(r.split(' ms')[0]) for r in result.split('time=') if r[0].is_digit()]
            dl_thp = temp2 # bits per second
            ul_thp = 0#temp2['upload']
            latency = sum(lat)/len(lat)#temp2['server']['latency']
            #tx_byte,rx_byte=get_TxRx_Bytes(client,container.name)
            print("Reached here")
        except Exception as e:
            print ("Error in running speedtest "+str(e))
        try:
            cursor.execute("INSERT INTO measurements (ue_name,id,gnb_name,time_stamp,DL_Thp,UL_Thp,latency) VALUES ( ?, ?, ?, ?, ?, ?, ?)", (container.name, container.id, gnb_Container[0].name, ts, dl_thp, ul_thp, latency) )
        except :
            print ("measurements insert not executing")
        time.sleep(90)

def get_gNB(client,id):
    #print("get_gnb")
    container=client.containers.list(filters={"id":id})
    if len(container)==0:
        print ("no container running with given id")
        return
    try:
        if 'oai' in container[0].name:
            run = container[0].exec_run(['sh', '-c', 'echo $RFSIMULATOR'])
            out=(run.output.decode("utf-8")).split("\n")
            print("out[0]", out[0])
            gnb_details=indexes.get_name_and_id_from_ip(out[0])
            print(gnb_details)
            return gnb_details[0][0]
        else:
            run = container[0].exec_run(['sh', '-c', 'echo $GNB_HOSTNAME'])
            out=(run.output.decode("utf-8")).split("\n")
            return out[0]
    except:
        print ("Error in running exec_run")
        return

def read():
    conn=get_db()
    cursor=conn.cursor()
    sql="SELECT * FROM measurements; "
    if if_table_exists(cursor,'measurements'):
        cursor.execute(sql)
        args=cursor.fetchall()
    else:
        args=0
        print("No data exists in database table measurements")
    cursor.close()
    conn.close()
    return args

def get_TxRx_Bytes(client,name):
    container=client.containers.list(filters={"name":name})
    if len(container)==0:
        print ("no container running with given name")
        return
    try:
        run=container[0].exec_run(['sh', '-c', 'ifconfig uesimtun0 | grep RX'])
        temp1=(run.output.decode("utf-8")).split('bytes ')
        m = temp1[1].split(' ')
        rx_bytes=m[0]
        run=container[0].exec_run(['sh', '-c', 'ifconfig uesimtun0 | grep TX'])
        temp2=(run.output.decode("utf-8")).split('bytes ')
        n = temp2[1].split(' ')
        tx_bytes=n[0]
    except:
        rx_bytes=0
        tx_bytes=0
        print ("Error in running exec_run")
    return tx_bytes,rx_bytes

def get_Health(shortid):
    run=os.popen("docker ps -q ")
    r = run.read().replace('\n','')
    flag=0
    if shortid in r:
        flag=1
    return flag
def make_latency_table(cursor):
    sql="CREATE TABLE IF NOT EXISTS latency (sug_action_key INTEGER PRIMARY KEY AUTOINCREMENT,\
         uename TEXT UNIQUE NOT NULL, ueid TEXT NOT NULL, avg_latency TEXT NOT NULL)"
    cursor.execute(sql)
    return
#include packet loss from png command, modify ping command
def get_PingLatency(client,name):
    latency_values=[]
    avg_latency=0
    container=client.containers.list(filters={"name":name})
    #print(container[0].name)
    if len(container)==0:
        print ("no container running with given name")
        return
    try:
        run=container[0].exec_run('ping -I uesimtun0 142.250.183.206 -c 10')
        temp=run.output.decode("utf-8")
        temp1=temp.split('rtt ')
        temp2=temp1[1].split('=')
        temp3=temp2[1].split('/')
        tmp=temp.split('time=')
        for i in range(1,len(tmp)):
            tmp1=tmp[i].split('ms')
            if i != len(tmp):
                latency_values.append(tmp1[0])
        #avg_latency=int(''.join([i for i in temp3[1] if (i.isdigit() or i=='.')]))
        avg_latency=float(temp3[1].strip())
        if avg_latency > 50:
            conn=get_db()
            cursor=conn.cursor()
            make_latency_table(cursor)
            cursor.execute("INSERT INTO latency (uename,ueid,avg_latency) VALUES(?,?,?)",(container[0].name,container[0].id,avg_latency))
    except:
        print ("Error in running Ping command")
    return latency_values,avg_latency

def read_actions():
    output={'action_button':'no',"action_button_text":''}
    conn=get_db()
    cursor=conn.cursor()
    list_of_tables=cursor.execute("""SELECT name FROM sqlite_master WHERE type='table' AND name='latency'; """).fetchall()
    if len(list_of_tables)==0:
        output['action_button']='no'
        output['action_button_text']=''
    else:
        sql="SELECT * FROM latency"
        actions=cursor.execute(sql).fetchall()
        if len(actions)==0:
            output['action_button']='no'
            output['action_button_text']=''
        else:
            uename=actions[0][1]
            avg_latency=actions[0][3]
            output['action_button']='yes'
            output['action_button_text']=uename+' is experiencing '+avg_latency+'ms of latency. Switch the Userplane path'
    conn.close()
    return output
def pop_latency():
    conn=get_db()
    cursor=conn.cursor()
    list_of_tables=cursor.execute("""SELECT name FROM sqlite_master WHERE type='table' AND name='latency'; """).fetchall()
    if len(list_of_tables)==0:
        return
    else:
        sql="SELECT * FROM latency"
        actions=cursor.execute(sql).fetchall()
        if len(actions)==0:
            return
        else:
            action_id=actions[0][0]
            sql="DELETE FROM latency WHERE sug_action_key='"+str(action_id)+"'; "
            cursor.execute(sql)
            return

#############################################################################################################################################

#client=docker.from_env()
#id = "19f0f29cfbc11fd4464d5dde07d8c68882e4ad41b55ed1f228ce383ebc85072a"
#get_num_ActiveUEs(client)
#res=read()
#print(res)
#get_IPaddressOfUE(client,id)
#get_TxRx_Bytes(client,'ue1')
#write(client,str(datetime.datetime.now()))
#read('ue2')
#read('ue1')
#get_Health(client,id)
#p=get_PingLatency(client,'ue1')
#print(p)


from django.urls import path
from . import views
# app_name='projectapp'
urlpatterns =[
    path("home",views.home,name="home"),
    path("movie/<int:movie_id>/",views.detail,name="detail"),
    path("add_movies",views.add_movies,name='add_movies'),
    path("update/<int:id>/",views.updatehtml,name="update"),
    path("delete/<int:id>/",views.delete,name="delete"),
    path("register",views.register_request,name="register"),
    path("login", views.login_request, name="login"),
    path("logout",views.logout_request,name="logout")
]


from rest_framework.response import Response
from rest_framework.pagination import PageNumberPagination

class ReactAdminPagination(PageNumberPagination):
    page_query_param = "page"
    page_size_query_param = "perPage"

    def get_paginated_response(self, data):
        count = self.page.paginator.count
        item_starting_index = self.page.start_index() - 1
        item_ending_index = self.page.end_index() - 1

        content_range = "items {0}-{1}/{2}".format(
            item_starting_index, item_ending_index, count
        )
        return Response(
            data,
            headers={
                "Content-Range": content_range,
                "X-Total-Count": count,
                "Access-Control-Expose-Headers": "X-Total-Count",
            },
        )


import pygame
from client import Client
from protocols import Protocols

class MathGame:
    def __init__(self, client):
        self.client = client
        client.start()

        self.font = None
        self.input_box = pygame.Rect(100, 100, 400, 45)
        self.color_inactive = pygame.Color("lightskyblue3")
        self.color_active = pygame.Color("dodgerblue2")
        self.color = self.color_inactive

        self.text = ""
        self.done = False
        self.logged_in = False

    def handle_event(self, event):
        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.input_box.collidepoint(event.pos):
                self.color = self.color_active
            else:
                self.color = self.color_inactive

        if event.type != pygame.KEYDOWN or self.color == self.color_inactive:
            return

        if event.key == pygame.K_RETURN:
            if not self.logged_in:
                self.client.send(Protocols.Request.NICKNAME, self.text)
                self.client.nickname = self.text
                self.logged_in = True
                self.text = ""
            elif self.client.started:
                self.client.send(Protocols.Request.ANSWER, int(self.text))
                self.client.client_validate_answer(self.text)
                self.text = ""
        elif event.key == pygame.K_BACKSPACE:
            self.text = self.text[:-1]
        else:
            self.text += event.unicode

    def draw(self, screen):
        screen.fill((255, 255, 255))
        if not self.logged_in and not self.client.started:
            self.draw_login(screen)
        elif not self.client.started:
            self.draw_waiting(screen)
        else:
            self.draw_game(screen)

        pygame.display.update()

    def draw_waiting(self, screen):
        text = 'Waiting for player'
        text_surface = self.font.render(text, 1, (0, 0, 0))
        screen.blit(text_surface, (screen.get_width()/2 - text_surface.get_width()/2, screen.get_height()/2 - text_surface.get_height()/2))

    def draw_login(self, screen):
        prompt = 'Enter A Nickname'
        prompt_surface = self.font.render(prompt, 1, (0, 0, 0))
        screen.blit(prompt_surface, (100, 50))
        self.draw_input(screen)

    def draw_input(self, screen):
        pygame.draw.rect(screen, self.color, self.input_box, 2)
        txt_surface = self.font.render(self.text, 1, self.color)
        screen.blit(txt_surface, (self.input_box.x + 5, self.input_box.y + 5))
        self.input_box.w = max(100, txt_surface.get_width()+10)

    def draw_game(self, screen):
        question = self.client.get_current_question()
        question_surface = self.font.render(f"#{self.client.current_question_index + 1}: {question} = ", 1, (0, 0, 0))
        screen.blit(question_surface, (100, 50))
        self.draw_input(screen)
        self.draw_opponent_data(screen)

    def draw_opponent_data(self, screen):
        if not self.client.opponent_data:
            return

        name_surface = self.font.render(f"Opponent: {self.client.opponent_data['name']}", 1, (0, 0, 0))
        screen.blit(name_surface, (550, 50))

        wins_surface = self.font.render(f"Wins: {self.client.opponent_data['wins']}", 1, (0, 0, 0))
        screen.blit(wins_surface, (550, 100))

        loss_surface = self.font.render(f"Losses: {self.client.opponent_data['losses']}", 1, (0, 0, 0))
        screen.blit(loss_surface, (550, 150))

        question_num = self.client.opponent_question_index + 1
        question_surface = self.font.render(f"Question #{question_num}", 1, (0,0,0))
        screen.blit(question_surface, (550, 200))

    def handle_end(self, screen):
        run = True
        while run:
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False

            if self.client.winner:
                text = f"{self.client.winner} has won the game!"
            else:
                text = f"Opponent left the game..."

            text_surface = self.font.render(text, 1, (0, 0, 0))
            screen.blit(text_surface,(screen.get_width()/2 - text_surface.get_width()/2, screen.get_height()/2 - text_surface.get_height()/2))
            pygame.display.update()

    def run(self):
        pygame.init()
        screen = pygame.display.set_mode((800, 600))
        clock = pygame.time.Clock()
        self.font = pygame.font.SysFont("comicsans", 32)

        while not self.client.closed:
            clock.tick(30)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    self.client.close()
                    pygame.quit()
                else:
                    self.handle_event(event)

            self.draw(screen)

        self.handle_end(screen)
        pygame.quit()

if __name__ == "__main__":
    game = MathGame(Client())
    game.run()


"""
Read file into texts and calls.
It's ok if you don't understand how to read files
"""
import csv

with open('texts.csv', 'r') as f:
    reader = csv.reader(f)
    texts = list(reader)

with open('calls.csv', 'r') as f:
    reader = csv.reader(f)
    calls = list(reader)

def combine_phone_time():
    phone_time = {}
    for call in calls:
        if call[0] not in phone_time:
            phone_time[call[0]] = int(call[3])
        else:
            phone_time[call[0]] += int(call[3])
        if call[1] not in phone_time:
            phone_time[call[1]] = int(call[3])
        else:
            phone_time[call[1]] += int(call[3])

    return (max(phone_time, key=phone_time.get),
            max(phone_time.values()))

ans = combine_phone_time()
print(
    '{} spent the longest time, {} seconds, on the phone during September 2016.'
    .format(ans[0], ans[1])
)

"""
TASK 2: Which telephone number spent the longest time on the phone
during the period? Don't forget that time spent answering a call is
also time spent on the phone.
Print a message:
"<telephone number> spent the longest time, <total time> seconds, on the phone during
September 2016.".
"""


import math
from typing import Tuple

from model_space.utils.point import Point

def get_correct_prediction(predictions: Tuple[Point, Point],
                           last_position: Point,
                           speed: float):
    diff0 = abs(math.dist(predictions[0].as_list(), last_position.as_list()) - speed)
    diff1 = abs(math.dist(predictions[1].as_list(), last_position.as_list()) - speed)

    if diff0 < diff1:
        return predictions[0]
    else:
        return predictions[1]


from os import environ
import json

from config import es as default_es

def create_index(es_index='memex', mapping=environ['DDT_HOME']+'/elastic/mapping.json', es=None):
    if es is None:
        es = default_es

    json_page_data=open(mapping).read()

    page_mappings = json.loads(json_page_data)

    doctypes = {}
    for doc_type in page_mappings.keys():
        doctypes[doc_type] = page_mappings[doc_type]

    mappings = {
        "mappings": doctypes
    }

    fields = es_index.lower().split(' ')
    es_index = '_'.join([item for item in fields if item not in ''])

    res = es.indices.create(index=es_index, body=mappings, ignore=400)

    es.indices.refresh(es_index)

    return res

def create_terms_index(es_index='ddt_terms', es=None):
    if es is None:
        es = default_es

    json_terms_data=open(environ['DDT_HOME']+'/elastic/mapping_terms.json').read()

    terms_mappings = json.loads(json_terms_data)

    mappings = {"mappings":
                {
                    "terms":terms_mappings["terms"]
                }
            }

    fields = es_index.lower().split(' ')
    es_index = '_'.join([item for item in fields if item not in ''])

    res = es.indices.create(index=es_index, body=mappings, ignore=400)

    es.indices.refresh(es_index)

    return res

def create_config_index(es_index='config', es=None):
    if es is None:
        es = default_es

    json_config_data=open(environ['DDT_HOME']+'/elastic/config.json').read()

    config_mappings = json.loads(json_config_data)

    mappings = {"mappings":
                {
                    "domains": config_mappings["domains"]
                }
            }

    fields = es_index.lower().split(' ')

    es_index = '_'.join([item for item in fields if item not in ''])

    res = es.indices.create(index=es_index, body=mappings, ignore=400)

    return res


n=int(input('enter a number'))
r=int(input('entr starting point'))
e=int(input('enter ending point'))
for i in range(r,e+1):
    print(n,'*', i ,' = ', n*i)
for i in range(r,e-1,-1):
    print(n,'*', i ,' = ', n*i)
"""this multiline comments
this is vivek ..
"""


"""
   Copyright 2016 Erik Jan de Vries

   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.
"""

from __future__ import division;

import logging;
log = logging.getLogger(__name__);
from collections import deque;

# %matplotlib inline
import matplotlib.pyplot as plt;

import numpy as np;

from tools import ensure_dir;
from qnet import qnet;

class CatchAgent(object):
    """Agent to act in the Catch environment for the OpenAI Gym"""
    def __init__( self, env
                , memory_maxlen = 1000
                , net = None
                , discount = 0.9
                , output_folder = "output"
                ):
        log.info("Creating an agent to play Catch");
        self.env = env;
        self.memory = deque(maxlen=memory_maxlen);
        if net is None:
            self.net = qnet( (None, self.env.grid_size, self.env.grid_size)
                           , self.env.action_space.n);
        else:
            self.net = net;
        self.discount = discount;
        ensure_dir(output_folder);
        self.output_folder = output_folder;
        self.results_filename = "{}/results.csv".format(self.output_folder);

    def save_net(self, filename = "net.pkl"):
        self.net.save("{}/{}".format(self.output_folder, filename))

    def load_net(self, filename = "net.pkl"):
        self.net.load("{}/{}".format(self.output_folder, filename))

    def choose_action(self, observation, policy='random', epsilon=0.1):
        if policy == 'random':
            action = self.env.action_space.sample();
            return action
        elif policy == 'greedy':
            q = self.net.predict(observation[np.newaxis,:,:]);
            action = np.argmax(q[0]);
            return action
        elif policy == 'eps_greedy':
            if np.random.rand() <= epsilon:
                return self.choose_action(observation, policy='random');
            else:
                return self.choose_action(observation, policy='greedy');
        raise ValueError("Policy {} not recognised!".format(policy));

    def store_memory(self, observation_t0, action, reward, observation_t1, done):
        self.memory.append([observation_t0, action, reward, observation_t1, done])

    def get_training_batch(self, batch_size = 50):
        len_memory = len(self.memory)
        inputs = np.zeros((min(len_memory, batch_size),) + self.memory[0][0].shape)
        targets = np.zeros((inputs.shape[0], self.env.action_space.n))
        for i, idx in enumerate(np.random.randint(0, len_memory, size=inputs.shape[0])):
            observation_t0, action, reward, observation_t1, done = self.memory[idx]

            inputs[i:i+1] = observation_t0
            # Get current Q-values from the net
            targets[i] = self.net.predict(observation_t0[np.newaxis,:,:])[0]

            # Correct the target Q-value given the observed reward for the given action
            if done:
                targets[i, action] = reward
            else:
                Q_t1 = np.max(self.net.predict(observation_t1[np.newaxis,:,:])[0])
                targets[i, action] = reward + self.discount * Q_t1
        return inputs, targets

    def train( self
             , n_episodes = 1000
             , batch_size = 50
             , render_on_screen = False
             , save_net_every_n_episodes = None
             , learning_rate = None
             ):
        if learning_rate is not None:
            self.net.set_learning_rate(learning_rate);

        log.info("Starting training ({} episodes)".format(n_episodes));

        log.info("Creating the results file: {}".format(self.results_filename));
        with open(self.results_filename, 'w', 0) as results_file:
            results_file.write("episode,epsilon,loss,wins\n");
        try:
            # Keeping track of the number of wins is not needed,
            # but as an indicator of how well our agent is doing,
            # it may be easier to interpret than the value of the loss function.
            wins = 0
            for i_episode in range(n_episodes):
                # During training we'll use an epsilon greedy policy to select actions
                # with epsilon decreasing exponentially from 1 to 0.1.
                epsilon = 10**(-i_episode/n_episodes)

                # The episode starts with resetting the environment.
                observation_t1 = self.env.reset()
                if render_on_screen:
                    self.env.render(mode='human');

                loss = 0.
                done = False
                while not done:
                    # The starting point for the current action is the outcome
                    # of the previous action:
                    observation_t0 = observation_t1;
                    # Choose an action using the epsilon greedy policy:
                    action = self.choose_action(observation_t0, 'eps_greedy', epsilon);
                    # Observe the outcome of taking this action:
                    observation_t1, reward, done, info = self.env.step(action);
                    if render_on_screen:
                        self.env.render(mode='human');

                    # Count the number of wins
                    if reward == 1:
                        wins += 1;

                    # Store the experience in memory
                    self.store_memory(observation_t0, action, reward, observation_t1, done)

                    # To train the q-net to select better actions in the future:
                    # - select a batch of memories to train on
                    inputs, targets = self.get_training_batch(batch_size);
                    # - train the net
                    loss += self.net.train(inputs, targets);

                if save_net_every_n_episodes is not None:
                    if i_episode % save_net_every_n_episodes == 0:
                        self.save_net("net/net_{}.pkl".format(i_episode));

                with open(self.results_filename, 'a', 0) as results_file:
                    results_file.write("{},{},{},{}\n".format(i_episode + 1, epsilon, loss, wins));
                log.info("Epoch {:03d}/{} | epsilon {:.4f} | Loss {:.4f} | Win count {}".format(i_episode, n_episodes - 1, epsilon, loss, wins))

        except KeyboardInterrupt:
            print("");
            log.warn('Training interrupted by user');

    def plot_results(self, filename = "results.png"):
        log.info("Plotting results: {}/{}".format(self.output_folder, filename));
        results = np.loadtxt(open(self.results_filename, "r"), delimiter=",", skiprows=1)
        plt.plot(results[:, 0], results[:, 2], '-')
        plt.savefig("{}/{}".format(self.output_folder, filename));
        plt.close();

    def play(self, n_episodes = 10, save_images = True, render_on_screen = False):
        log.info("Playing catch with the trained agent ({} episodes)".format(n_episodes));
        if save_images:
            output_folder = "{}/images".format(self.output_folder);
            ensure_dir(output_folder);
            log.info("Images will be saved in the folder: {}".format(output_folder));

        try:
            wins = 0
            for e in range(n_episodes):
                # The episode starts with resetting the environment.
                observation = self.env.reset();
                if render_on_screen:
                    self.env.render(mode='human');

                loss = 0.;
                done = False;

                c = 0;
                if save_images:
                    # save the initial observation as an image
                    if not render_on_screen:
                        self.env.render(mode='matplotlib');
                    plt.savefig("{}/{:02d}_{:02d}.png".format(output_folder, e, c));
                while not done:
                    c += 1;
                    # get next action
                    action = self.choose_action(observation, 'greedy');
                    # apply action, get rewards and new state
                    observation, reward, done, info = self.env.step(action);
                    if render_on_screen:
                        self.env.render(mode='human');

                    # Count the number of wins
                    if reward == 1:
                        wins += 1;

                    if save_images:
                        # save the observation as an image
                        if not render_on_screen:
                            self.env.render(mode='matplotlib');
                        plt.savefig("{}/{:02d}_{:02d}.png".format(output_folder, e, c))

        except KeyboardInterrupt:
            print("");
            log.warn('Playing interrupted by user');

        log.info("Won {} out of {} games ({} %)".format(wins, n_episodes, (100*wins/n_episodes)));


import os
import openpyxl # For Excel manipulation
import boto3
import traceback
from shutil import copyfile
from PIL import Image, ImageOps
from preview_generator.manager import PreviewManager

# {
#   "dest_bucket": "lambda-generate-preview-image-destination",
#   "dest_path": "pig_#{width}_#{height}.png",
#   "error_sns": "arn:aws:sns:us-west-2:020275857710:file-previewer-failed-dev-neil",
#   "format": "png",
#   "ok_sns": "arn:aws:sns:us-west-2:020275857710:file-previewer-succeeded-dev-neil",
#   "src_bucket": "lambda-generate-preview-image-source",
#   "src_path": "source_folder/pig.jpg",
#   "request_id": "23453rjdkwfhdskjfh29er82349rewfds",
#   "dimensions": [
#     {
#       "width": "1000",
#       "height": "500"
#     },
#     {
#       "width": "500",
#       "height": "250"
#     },
#     {
#       "width": "250",
#       "height": "120"
#     }
#   ]
# }

def lambda_handler(event, context):

  ### Inputs
  print("#### Received event is: " + str(event))
  src_bucket = event["src_bucket"]
  src_path = event["src_path"]
  dest_bucket = event["dest_bucket"]
  dest_path = event["dest_path"]
  dimensions = event["dimensions"]
  output_format = event["format"]
  ok_sns = event["ok_sns"]
  error_sns = event["error_sns"]
  request_id = event["request_id"]

  try:
    ### Remove the leading slash from src_path and dest_path
#     if src_path[0] == "/":
#       scr_path = src_path[1:]
#     if dest_path[0] == "/":
#       dest_path = dest_path[1:]

    ### Get the maximum size from the dimensions received
    maximum_width = 0
    maximum_height = 0
    for dimension in dimensions:
      if int(dimension["width"]) > maximum_width:
        maximum_width = int(dimension["width"])
        maximum_height = int(dimension["height"])

    ### Copy the file from S3:
    print("Copy file from source S3")
    if src_bucket != "":
      client = boto3.client('s3')
      source_file = "/tmp/" + src_path.split("/")[-1]
      client.download_file(src_bucket, src_path, source_file)
    else:
      # If the src_bucket == 0 we will not copy from S3, and use local path.
      # This is for local testing
      source_file = src_path
    print("Successfully copied file from source S3")

    ### If file is Excel and it is big, make it smaller.
    if ".xls" in src_path and os.path.getsize(source_file) > 5000000: #5MB
      print("It seems to be a big Excel file. Try to keep only first 100 lines and columns")
      # opening the source excel file
      wb1 = openpyxl.load_workbook(source_file)
      ws1 = wb1.worksheets[0]

      # opening the destination excel file
      truncated_file = source_file + ".truncated." + source_file.split(".")[-1]

      # Create new empty file
      wb = openpyxl.Workbook()
      ws =  wb.active
      ws.title = "Changed Sheet"
      wb.save(filename = truncated_file)

      wb2 = openpyxl.load_workbook(truncated_file)
      ws2 = wb2.active

      # We will write only the first 100 lines and columns
      mr = 100
      mc = 100

      # copying the cell values from source
      # excel file to destination excel file
      for i in range (1, mr + 1):
          for j in range (1, mc + 1):
              # reading cell value from source excel file
              c = ws1.cell(row = i, column = j)

              # writing the read value to destination excel file
              ws2.cell(row = i, column = j).value = c.value

      # saving the destination excel file
      print("Saving truncated file to: " + truncated_file)
      wb2.save(str(truncated_file))
      print("Saved")
      source_file = truncated_file
      print("Successfuly truncated the big Excel file")

    ### Generate preview
    print("Generating preview")
    manager = PreviewManager("/tmp/cache", create_folder= True)
    preview_image = manager.get_jpeg_preview(source_file, width=maximum_width, height=maximum_height)
    print("Successfully generated preview")

    ### Make sure the image has the expected size and format
    print("Resize and change the format")
    # Open the preview image
    img = Image.open(preview_image)

    # Calculate the differences between actual sizes and wanted sizes
    delta_w = maximum_width - img.width
    delta_h = maximum_height - img.height

    # Then actual sizes is odd (not even), the we need to add one more pixel
    precision_pixel_w = maximum_width - img.width - int(delta_w/2) - int(delta_w-(delta_w/2))
    precision_pixel_h = maximum_height - img.height - int(delta_h/2) - int(delta_h-(delta_h/2))

    # Resize the image
    ltrb_border=(int(delta_w/2), int(delta_h/2), int(delta_w-(delta_w/2)) + precision_pixel_w, int(delta_h-(delta_h/2)) + precision_pixel_h)
    img_with_border = ImageOps.expand(img, border=ltrb_border, fill='white')
    output_file = "/tmp/output_preview." + output_format
    img_with_border.convert('RGB').save(output_file)
    print("Successfully resized and formatted for the maximum (" + str(maximum_width) + ":" + str(maximum_height) + ") wanted size")

    ### Copy to S3
    print("Copy the maximum (" + str(maximum_width) + ":" + str(maximum_height) + ") preview to destination bucket")
    if dest_bucket != "":
      client = boto3.client('s3')
      client.upload_file(output_file, dest_bucket, dest_path.replace("#{width}", str(maximum_width)).replace("#{height}", str(maximum_height)))
    else:
      # If the dest_bucket == 0 we will not copy from S3, but will copy on local path
      copyfile(output_file, dest_path.replace("#{width}", str(maximum_width)).replace("#{height}", str(maximum_height)))
    print("Successfully copied the maximum (" + str(maximum_width) + ":" + str(maximum_height) + ") preview to destination bucket")

    ### Transform, and copy all other wanted dimensions to S3 bucket
    for dimension in dimensions:
      # Get dimensions
      current_width = int(dimension["width"])
      current_height = int(dimension["height"])

      # Skip if the dimension is the maximum one
      if current_width == maximum_width and current_height == maximum_height:
        continue

      # Open image
      image = Image.open(output_file)
      new_image = image.resize((current_width, current_height))
      output_file_resized = "/tmp/output_preview_resized." + output_format
      new_image.save(output_file_resized)

      ### Copy to S3
      print("Copy the dimension (" + str(current_width) + ":" + str(current_height) + ") to destination bucket")
      if dest_bucket != "":
        client = boto3.client('s3')
        client.upload_file(output_file_resized, dest_bucket, dest_path.replace("#{width}", str(current_width)).replace("#{height}", str(current_height)))
      else:
        # If the dest_bucket == 0 we will not copy from S3, but will copy on local path
        copyfile(output_file_resized, dest_path.replace("#{width}", str(current_width)).replace("#{height}", str(current_height)))
      print("Successfully copied the dimension (" + str(current_width) + ":" + str(current_height) + ") preview to destination bucket")

    ### Send ok message to ok SNS
    print("Sending OK to SNS")
    if src_bucket != "":
      # If the src_bucket is not empty, then the function is running locally for dev purposes, so no need to send SNS
      # Compose the OK JSON
      okJSON = {
        "success": "true",
        "request_id": request_id,
        "src_bucket": src_bucket,
        "src_path": src_path
      }
      client = boto3.client('sns')
      response = client.publish(
          TopicArn=ok_sns,
          Message=str(okJSON)
      )
    print("Successfully send OK to SNS")
    return "OK"

  except Exception as e:
    print("Error: {}".format(e))
    tracebackError = traceback.format_exc()
    print(tracebackError)
    ### Send error message to error SNS
    print("Sending ERROR to SNS")
    # Compose the ERROR JSON
    errorJSON = {
      "success": "false",
      "request_id": request_id,
      "src_bucket": src_bucket,
      "src_path": src_path
    }
    if src_bucket != "":
      # If the src_bucket is not empty, then the function is running locally for dev purposes, so no need to send SNS
      client = boto3.client('sns')
      response = client.publish(
          TopicArn=error_sns,
          Message=str(errorJSON)
      )
    print("Successfully send ERROR to SNS")
    return "ERROR"


# Veri Tipleri type()

a = 3 # Integer
b = 5.8 # Float
c = "STAR" # String
d = True # Boolean

# Float --> Integer
b = int(b)
print(b)

# Integer --> Float
a = float(a)
print(a)

# String --> Number
c = int(c)
print(c)

c = float(c)
print(c)

# Number --> String
b = str(b)
print(b)

a = str(a)
print(a)


# 127 Word Ladder
#
# To find the shortest route, we can use BFS - to be precise, we can use
# bi-directional BFS since we know the goal in order to avoid the worst case
# (exploring on one end where it is more sparse compared to another).

class Solution:
    def wordLadder(self, begin, end, words):
        words = set(words)
        if not end in words:
            return 1

        length = 1
        front, back = { begin }, { end }
        visited = set()
        g = collections.defaultdict(set)
        for word in words:
            for i in range(len(word)):
                wild = word[:i] + "." + word[i+1:]
                g[wild].add(word)

        while front:
            if front & back:
                return length

            newfront = set()
            for word in front:
                visited.add(word)
                for i in range(len(word)):
                    wild = word[:i] + "." + word[i+1:]
                    nextWords = g[wild]
                    nextWords -= visited
                    newfront |= nextWords

            front = newfront
            length += 1

            if len(front) > len(back):
                front, back = back, front

        return -1


# Installing this requires C++ compilation. If you don't want to install that capability on your computer, you can install it by downloading the wheel from https://www.lfd.uci.edu/~gohlke/pythonlibs/#noise
# Then running pip install <wheel-location>
from lib.general import interpolate_looped, vector_from_angle
from lib.presetObject import PresetObject
from noise import pnoise1
import matplotlib.pyplot as plt
import numpy as np
import scipy.stats as st

# TODO: write some custom functions that work as settings for the wind
# One can be a constant magnitude
# One can be the OpenRocket method
# One can be the method that I made up

class Wind(PresetObject):
    """
    A wind simulator based on perlin noise and visual matching with second by second data from Salt Lake City
    Completely independent of time increment, but does vary over time and altitude
    Adjusts average wind speeds for altitude, and varies direction over time
    Also simulates gusts using a Weibull distribution
    """

    def __init__(self, **kwargs):
        """
        :param float average_wind_speed: At the supplied base altitude, what is the wind speed in m/s
        """

        # https://www.homerenergy.com/products/pro/docs/latest/weibull_k_value.html
        # 3 or 4 will be relatively steady, 1.5 will be gusty
        # This parameter is similar to the standard deviation / amplitude
        self.weibull_shape = 1
        self.interpolation_speed = 0.00005
        self.count = 30
        self.seeds = np.random.random(self.count) * self.count * 100

        # I have no idea what this does, but it is in the code for noise and it is an important parameter
        self.base = 0.9
        self.octaves = 50

        self.base_altitude = 10
        self.average_wind_speed = 5
        self.roughness = 1

        self.overwrite_defaults(**kwargs)

        self.altitude_randomized = 0
        # This value is the number of meters of altitude change that that is equivalent to one second passing
        # idk; this value has virtually no effect on our time scale
        self.time_from_altitude = 1000 / 10
        self.time_last_randomized = 0
        self.time_to_interpolate = self.get_random_interpolation_time()
        self.start_direction = 0
        self.wind_direction = self.start_direction
        self.target_direction = self.get_random_direction()

        # Have to manually calculate normalized perlin noise deviation
        self.std = self.determine_std()

    # region Statistics Stuff

    def get_normal_perlin(self, time):
        total = 0
        for i in range(self.count):
            total += pnoise1(self.seeds[i] + time, self.octaves, self.base)

        return total / self.count

    def get_z_score(self, mean, std, val):
        return (val - mean) / std

    def get_percentile_from_z(self, z):
        # Get the cumulative distribution function for a normal distribution based on a z-value
        return st.norm.cdf(z)

    def lookup_weibull(self, p, average):
        "Given the percentile, return the multiplier based on the weibull shape parameter and the average"
        # use self.weibull_shape
        # Based on https://www.itl.nist.gov/div898/handbook/eda/section3/eda3668.htm, I found the output given a percentile (after flipping x and y around)

        return (-np.log(1 - p)) ** (1 / self.weibull_shape) * average

    def determine_std(self):
        size = 10000

        ys = [[] for _ in range(self.count)]

        for index in range(len(ys)):
            for i in range(size):
                # Actually, I don't think time increment even needs to be included in tis
                ys[index].append(pnoise1(
                    self.seeds[index] + i * self.interpolation_speed, self.octaves))

        average_ys = []
        for i in range(len(ys[0])):
            total = 0
            for j in range(len(ys)):
                total += ys[j][i]

            average_ys.append(total / len(ys))

        return np.std(average_ys)

    # endregion

    def get_average_speed_altitude(
            self, altitude):
        if altitude == 0:
            print("Because this assumes the no slip condition, it does not work at altitude=0. Returning zero for wind speed")
            return 0
        # Roughness is z_0, or roughness length
        # For lake jackson, z_0 = 1
        # Relatively good explanation: https://wind-data.ch/tools/profile.php?lng=en
        # Review this equation more closely, it does not appear to be giving high enough increases
        return self.average_wind_speed * np.log(altitude / self.roughness) / np.log(
            self.base_altitude / self.roughness)

    def get_air_velocity(self, time, altitude=10):
        """
        Gets the air speed in all three dimensions at a point in time
        :param float base_altitude: The altitude AGL in meters where the average wind speed was recorded
        """

        wind_unit_vector = vector_from_angle(
            self.get_air_direction(time, altitude))

        value = self.get_normal_perlin(time * self.interpolation_speed)
        z_score = self.get_z_score(0, self.std, value)

        p = self.get_percentile_from_z(z_score)

        average_speed = self.get_average_speed_altitude(altitude)

        speed = self.lookup_weibull(p, average_speed)

        # TODO: Add some variability to the wind direction, particularly as altitude changes
        # In meters per second
        return wind_unit_vector * speed

    def get_random_interpolation_time(self):
        return np.random.normal(1800, 300)

    def get_random_direction(self):
        return np.random.uniform() * 2 * np.pi

    def calculate_average_direction(self, time, altitude):
        adjusted_time = time + (
            altitude - self.altitude_randomized) / self.time_from_altitude

        if adjusted_time > self.time_last_randomized + self.time_to_interpolate:
            self.target_direction = (
                self.wind_direction + (self.get_random_direction() - np.pi) * 0.5) % (2 * np.pi)
            if self.target_direction > 2 * np.pi:
                self.target_direction -= np.pi

            self.start_direction = self.wind_direction
            self.time_last_randomized = time
            self.altitude_randomized = altitude
            self.time_to_interpolate = self.get_random_interpolation_time()

        # This isn't exactly a linear interpolation since I am setting the start point each time. I think it is more of an ease-out interpolation; we will see how it looks
        self.wind_direction = interpolate_looped(
            adjusted_time, self.time_last_randomized, self.
            time_last_randomized + self.time_to_interpolate, self.
            start_direction, self.target_direction)

    def get_air_direction(self, time, altitude=10):
        # I am including altitude as an input, because as your altitude changes the wind direction will also change

        # The average direction is just a line moving from one randomly generated point on a circle to another randomly generated point on a circle. However, the direction has an additional perlin noise added to it, which makes it match the wobbliness of the real thing (visual inspection seems to say that direction variability is relatively independent of strength)

        # Maybe need some other variables for direction
        value = self.get_normal_perlin(time * self.interpolation_speed)
        z_score = self.get_z_score(0, self.std, value)

        noise_component = z_score * 1

        self.calculate_average_direction(time, altitude)

        return np.array([(self.wind_direction + noise_component) %
                         (2 * np.pi) - np.pi, np.pi / 2])

if __name__ == "__main__":
    w = Wind()

    print(w.get_average_speed_altitude(150))