import csv
import numpy as np
import matplotlib.pyplot as plt

def frist_graph():
    """this function open file, read file and return data it."""
    yeardata = []
    north, float_north = [], []
    northeast, float_northeast = [], []
    east, float_east = [], []
    central, float_central = [], []
    south, float_south = [], []

    ifile  = open('DatabaseCSV/พื้นที่ป่าประเทศไทยปี 2516 - 2558.csv', 'r')
    reader = csv.reader(ifile)

    for row in reader:
        yeardata.append(row[0]), north.append(row[1]), northeast.append(row[2]), east.append(row[3]), central.append(row[4]), south.append(row[5])

    for i in north[1:20]:
        i = i.replace(",", "")
        float_north.append(float(i))

    for i in northeast[1:20]:
        i = i.replace(",", "")
        float_northeast.append(float(i))

    for i in east[1:20]:
        i = i.replace(",", "")
        float_east.append(float(i))

    for i in central[1:20]:
        i = i.replace(",", "")
        float_central.append(float(i))

    for i in south[1:20]:
        i = i.replace(",", "")
        float_south.append(float(i))

    return yeardata[1:20], float_north, float_northeast, float_east, float_central, float_south

def second_graph():
    """this function open file, read file and return data it."""
    year = []
    budget, float_budget = [], []
    non_budget, non_float_budget = [], []

    ifile  = open('DatabaseCSV/พื้นที่ป่าที่ได้รับการฟื้นฟูโดยกรมป่าไม้2007-2015.csv', 'r')
    reader = csv.reader(ifile)

    for row in reader:
        year.append(row[0]), budget.append(row[1]), non_budget.append(row[2])

    for i in budget[2:11]:
        float_budget.append(float(i))

    for i in non_budget[2:11]:
        non_float_budget.append(float(i))

    return year[2:11], float_budget, non_float_budget

def third_graph():
    """this function open file, read file and return data it."""
    year = []
    forest, wood = [], []
    int_forest, int_wood = [], []

    ifile  = open('DatabaseCSV/สถิติคดีการกระทำผิดกฎหมายเกี่ยวกับการป่าไม้ปี 2557 - 2558.csv', 'r')
    reader = csv.reader(ifile)

    for row in reader:
        year.append(row[0]), forest.append(row[1]), wood.append(row[2])

    for i in forest[1:12]:
        int_forest.append(int(i))

    for i in wood[1:12]:
        int_wood.append(int(i))

    return year[1:12], int_forest, int_wood

frist_plotgraph = frist_graph() # Call Function
second_plotgraph = second_graph() # Call Function
third_plotgraph = third_graph() # Call Function

def theforest():
    """this function will plot graph and show it."""
    font = {'family': 'serif',
        'color':  'darkred',
        'weight': 'normal',
        'size': 16,
        }

    frist_num_graph = 19
    frist_ind = np.arange(frist_num_graph)  # the x locations for the groups
    width = 0.10       # the width of the bars

    # Frist Graph
    fig, plot = plt.subplots()
    rects1 = plot.bar(frist_ind, frist_plotgraph[1], width, color='b')
    rects2 = plot.bar(frist_ind + width, frist_plotgraph[2], width, color='orangered')
    rects3 = plot.bar(frist_ind + (width * 2), frist_plotgraph[3], width, color='m')
    rects4 = plot.bar(frist_ind + (width * 3), frist_plotgraph[4], width, color='y')
    rects5 = plot.bar(frist_ind + (width * 4), frist_plotgraph[5], width, color='navy')
    plot.set_xlabel('Years', fontdict=font)
    plot.set_ylabel('Forest area (farm)', fontdict=font)
    plot.set_title('Forestry analyzed by region')
    plot.set_xticks(frist_ind + (width * 2.5))
    plot.set_xticklabels(frist_plotgraph[0])
    plot.set_yticklabels(('0.00', '10,000,000.00', '20,000,000.00', '30,000,000.00', '40,000,000.00', '50,000,000.00', '60,000,000.00', '70,000,000.00', '80,000,000.00'))
    plot.legend((rects1[0], rects2[0], rects3[0], rects4[0], rects5[0]), ('North', 'North East', 'East', 'Central', 'South'))

    second_num_graph = 9
    second_ind = np.arange(second_num_graph)  # the x locations for the groups

    # Second Graph
    fig2, plot2 = plt.subplots()
    rects1 = plot2.bar(second_ind, second_plotgraph[1], width, color='b')
    rects2 = plot2.bar(second_ind + width, second_plotgraph[2], width, color='orangered')
    plot2.set_xlabel('Years', fontdict=font)
    plot2.set_ylabel('Forest area (farm)', fontdict=font)
    plot2.set_title('Forest areas that have been reclaimed by the forest department.')
    plot2.set_xticks(second_ind + (width * 1.1))
    plot2.set_xticklabels(second_plotgraph[0])
    plot2.set_yticklabels(('0.00', '10,000.00', '20,000.00', '30,000.00', '40,000.00', '50,000.00', '60,000.00', '70,000.00', '80,000.00', '90,000.00'))
    plot2.legend((rects1[0], rects2[0]), ('Reforestation budget', 'Reforestation non-budgetary funds'))

    third_num_graph = 11
    third_ind = np.arange(third_num_graph)  # the x locations for the groups

    # Third Graph
    fig3, plot3 = plt.subplots()
    rects1 = plot3.bar(third_ind, third_plotgraph[1], width, color='b')
    rects2 = plot3.bar(third_ind + width, third_plotgraph[2], width, color='orangered')
    plot3.set_xlabel('Month/Year', fontdict=font)
    plot3.set_ylabel('Number (case)', fontdict=font)
    plot3.set_title('Statistics about the offense in the forest.')
    plot3.set_xticks(third_ind + (width * 1.1))
    plot3.set_xticklabels(third_plotgraph[0])
    plot3.set_yticklabels(('0', '50', '100', '150', '200', '250', '300', '350', '400', '450', '500'))
    plot3.legend((rects1[0], rects2[0]), ('Forest encroachment', 'Wood Processing'))

    plt.show()

theforest()


"""A setuptools based setup module.
See:
https://packaging.python.org/en/latest/distributing.html
https://github.com/pypa/sampleproject
"""

# Always prefer setuptools over distutils
from setuptools import setup, find_packages
# To use a consistent encoding
from codecs import open
from os import path

here = path.abspath(path.dirname(__file__))

# Get the long description from the README file
with open(path.join(here, 'README.md'), encoding='utf-8') as f:
    long_description = f.read()

setup(
    name='clear-skies-gql',
    version='0.1.2',
    description='clearskies bindings for Apollo GQL',
    long_description=long_description,
    long_description_content_type='text/markdown',
    url='https://github.com/cmancone/clearskies-gql',
    author='Conor Mancone',
    author_email='cmancone@gmail.com',
    license='MIT',

    # See https://pypi.python.org/pypi?%3Aaction=list_classifiers
    classifiers=[
        'Development Status :: 4 - Beta',
        'Intended Audience :: Developers',
        'Topic :: Software Development :: Build Tools',
        'License :: OSI Approved :: MIT License',
        'Programming Language :: Python :: 3',
    ],
    keywords='setuptools development',
    packages=find_packages(where="src"),
    package_dir={"": "src"},
    python_requires=">=3.6",
    install_requires=['clear-skies'],
)


import logging
import logging.handlers
import os
import sys

class CustomFormatter(logging.Formatter):
	"""Logging colored formatter, adapted from https://stackoverflow.com/a/56944256/3638629"""

	grey = '\x1b[38;21m'
	blue = '\x1b[38;5;39m'
	yellow = '\x1b[38;5;226m'
	red = '\x1b[38;5;196m'
	bold_red = '\x1b[31;1m'
	reset = '\x1b[0m'

	def __init__(self, fmt, *args, **kwargs):
		super().__init__()

		self.fmts = {}

		lvls = {
			logging.DEBUG: self.grey,
			logging.INFO: self.blue,
			logging.WARNING: self.yellow,
			logging.ERROR: self.red,
			logging.CRITICAL: self.bold_red,
		}

		use_cols = sys.platform.startswith('linux')

		for lvl, col in lvls.items():
			if use_cols and fmt is not None:
				fmt = fmt.replace('%(asctime)s', self.grey + '%(asctime)s' + self.reset)
				fmt = fmt.replace('%(levelname)s', col + '%(levelname)s' + self.reset)
			self.fmts[lvl] = logging.Formatter(fmt, *args, **kwargs)

		# self.FORMATS = {
		# 	logging.DEBUG: self.grey + self.fmt + self.reset,
		# 	logging.INFO: self.blue + self.fmt + self.reset,
		# 	logging.WARNING: self.yellow + self.fmt + self.reset,
		# 	logging.ERROR: self.red + self.fmt + self.reset,
		# 	logging.CRITICAL: self.bold_red + self.fmt + self.reset
		# }

	def format(self, record):
		# log_fmt = self.FORMATS.get(record.levelno)
		# formatter = logging.Formatter(log_fmt)
		formatter = self.fmts.get(record.levelno)

		return formatter.format(record)

def setup_logs():
	# Logging setup
	if not os.path.exists('logs'):
		os.mkdir('logs')

	# log_file = f'logs/helium_{datetime.now().isoformat()}.log'
	log_file = 'logs/helium.log'

	logger = logging.getLogger('helium_logger')
	logger.setLevel(logging.DEBUG)
	format_args = {
		'fmt': '%(asctime)s-%(levelname)s: %(message)s',
		'datefmt': '%H:%M:%S'
	}

	ch = logging.StreamHandler(sys.stdout)
	ch.setFormatter(CustomFormatter(**format_args))
	logger.addHandler(ch)

	fh = logging.handlers.RotatingFileHandler(log_file, maxBytes=(1048576*5), backupCount=7, encoding='utf-8')
	fh.setFormatter(logging.Formatter(**format_args))
	logger.addHandler(fh)


from Operations import *
import matplotlib.pyplot as plt

steiner_v, terminal_v, edges = read_input()
neighbour_v = {}
neighbour_v = create_condition(edges, neighbour_v)

print('steiner_v_dict : ')
print(steiner_v_dict)

print('terminal_v_dict : ')
print(terminal_v_dict)

print('Neighbour rules')
print(neighbour_v)

# an_individual = steiner_v + terminal_v
population = []

populationSize = 3
numberOfGenerations = 5
# mutation rate should be lower than 0.2
mutationRate = 0.2
tornumentSize = 10
thereshold = 1
generation = []
best_individual = []
neighbour_v_copy = neighbour_v

def plot_optimum_path(generation, terminal_v_dict):
    indiv = generation[0].an_individual
    counter_6 = 0
    flag_5 = 0
    while counter_6 < len(indiv) and flag_5 == 0:
        if indiv[counter_6][1] in terminal_v_dict:
            explored_nodes = bfs_connected_component(generation[0].neighbour_v, indiv[counter_6][1])
            flag = 0
            for item in terminal_v_dict:
                if item not in explored_nodes:
                    flag = 1
            if flag != 1:
                print('hora')
                accepted_path = explored_nodes
                flag_5 = 1
        counter_6 += 1

    # x axis values
    x = []
    # corresponding y axis values
    y = []
    for each_node in accepted_path:
        flag_find_node = 0
        count_7 = 0
        while flag_find_node == 0 and count_7 < len(indiv):
            if indiv[count_7][1] == each_node:
                x.append(indiv[count_7][0][0])
                y.append(indiv[count_7][0][1])
                flag_find_node = 1
            count_7 += 1

    # outputs :
    plt.plot(x, y)
    plt.plot(x, y, color='blue', linewidth=3,
             marker='o', markerfacecolor='red', markersize=12)
    plt.xlabel('x - axis')
    plt.ylabel('y - axis')
    plt.title('Optimum path')
    plt.show()

    return accepted_path

for i in range(populationSize):
    an_individual = Individual(steiner_v, terminal_v, neighbour_v_copy)
    random.shuffle(an_individual.an_individual)
    generation.append(an_individual)

# initialed path
plot_optimum_path(generation, terminal_v_dict)

report = []
# Generate new populations
for numberOfRemainingGeneration in range(numberOfGenerations):
    count = 0
    for individual in generation:
        visited = []  # List to keep track of visited nodes.
        queue = []  # Initialize a queue
        explored = []
        explored_dict = {}
        individual.fitness = fitness(individual)
        count += 1
    generation_sorted = sorted(generation, key=operator.attrgetter('fitness'))
    repeated_fitness = []
    repeated_gens = []
    for item in generation_sorted:
        if item.fitness not in repeated_fitness:
            repeated_fitness.append(item.fitness)
        else:
            repeated_gens.append(item)
    for term in repeated_gens:
        del generation_sorted[generation_sorted.index(term)]
    population_selected = generation_sorted[0:tornumentSize]
    # for item in generation_sorted:
    #     print(item.fitness)

    # for item in population_selected:
    #     print(item.an_individual)

    report.append({'generation': numberOfRemainingGeneration,
                   'mean_fitness': np.mean(np.array([item.fitness for item in generation]))})
    print(report)
    print('********************************************')
    new_generation = generate_crossover(population_selected, neighbour_v, thereshold, mutationRate)
    print('********************************************')
    # for item in population_selected:
    #     print(item.an_individual)
    # print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
    # for item in new_generation:
    #     print(item.an_individual)

    all_gens = new_generation + generation
    all_gens_sorted = sorted(all_gens, key=operator.attrgetter('fitness'))
    repeated_list_fitness = []
    counter_8 = 0
    counter_9 = 0
    while counter_8 < populationSize:
        if all_gens_sorted[counter_9].fitness not in repeated_list_fitness:
            repeated_list_fitness.append(all_gens_sorted[counter_9].fitness)
            generation.append(all_gens_sorted[counter_9])
            counter_8 += 1
        counter_9 += 1
    generation = sorted(generation, key=operator.attrgetter('fitness'))
    print('!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!')

x = []
y = []
for item in report:
    x.append(item['generation'])
    y.append(item['mean_fitness'])

accepted_path = plot_optimum_path(generation, terminal_v_dict)
plt.plot(x, y)
plt.xlabel('number of generations')
plt.ylabel('Mean Fitness')
plt.title('Optimum path')
plt.show()
with open('steiner_out.txt', 'w') as the_file:
    for node in accepted_path:
        the_file.write(str(node) + '\n')
    the_file.write(str(generation[0].fitness) + '\n')


import numpy as np
from torchvision import transforms
import cv2
from objectAttentionModelConvLSTM import *
from attentionMapModel import attentionMap
from PIL import Image
import os
import imageio

DEVICE = "cuda"

# Model definition
num_classes = 61  # Classes in the pre-trained model
mem_size = 512
#model_state_dict = '/content/drive/My Drive/FINAL_LOGS/200+150epochs_RGB_16frames/test_2/model_rgb_state_dict.pth'
#model_state_dict = "/content/drive/My Drive/Lorenzo/ego-rnn-latest/200+150epochs_RGB_16frames/test_2/model_rgb_state_dict.pth"
model_state_dict = "/content/drive/My Drive/Lorenzo/ego-rnn-ss-task/experiments/rgb_16frames_regression_kl/model_rgb_state_dict.pth"
model = attentionModel(num_classes=num_classes, mem_size=mem_size)
model.load_state_dict(torch.load(model_state_dict), strict=False)
model_backbone = model.resNet
attentionMapModel = attentionMap(model_backbone).to(DEVICE)
attentionMapModel.train(False)
for params in attentionMapModel.parameters():
    params.requires_grad = False

normalize = transforms.Normalize(
    mean=[0.485, 0.456, 0.406],
    std=[0.229, 0.224, 0.225]
)

preprocess1 = transforms.Compose([
    transforms.Scale(256),
    transforms.CenterCrop(224),
])

preprocess2 = transforms.Compose([
    transforms.ToTensor(),
    normalize])

fl_name_in = './attention_test/frames/'
fl_name_out = './attention_test/open_mayo_2/'

# load video and get frames #

'''
cam = cv2.VideoCapture("./attention_test/grab_glass.mp4")            # load video

currentframe = 0
while (True):
    ret, frame = cam.read()
    if ret:
        name = fl_name_in + "/" + str(currentframe).zfill(3) + '.jpg'
        cv2.imwrite(name, frame)
        currentframe += 1
    else:
        break
'''

frames = []
for i, img_name in enumerate(sorted(os.listdir(fl_name_in))):
    img_pil = Image.open(os.path.join(fl_name_in, img_name))                    # open image
    img_pil1 = preprocess1(img_pil)                                             # apply preprocessing (scaling and cropping)
    img_size = img_pil1.size
    size_upsample = (img_size[0], img_size[1])
    img_tensor = preprocess2(img_pil1)                                          # convert to tensor
    img_variable = Variable(img_tensor.unsqueeze(0).to(DEVICE))                 # send to gpu
    img = np.asarray(img_pil1)                                                  # keep original image (transformed)
    attentionMap_image = attentionMapModel(img_variable, img, size_upsample)    # compute attention map and stack it on original image
    cv2.imwrite(os.path.join(fl_name_out, img_name), attentionMap_image)        # save image

    frames.append(imageio.imread(os.path.join(fl_name_out, img_name)))          # keep image, read with imageio

    print(f"frame_{i}")

kargs = {'duration': 0.05}                                                      # duration of single frame
imageio.mimsave(fl_name_out + "/frames.gif", frames, **kargs)                   # create gif


"""
연습 문제4. 이진 탐색
 - 이진 탐색을 반복문과 재귀 함수를 활용하여 구현하시오.
 - 찾고자 하는 값(target)이 있다면 해당 값의 인덱스를 없다면 -1을 반환하시오.

중요!
"""

#1. iteration
def binary_search_iteration(nums, target):
    low = 0
    high = len(nums) - 1
    while low <= high:
        mid = low + (high - low) // 2
        if nums[mid] == target:
            return mid
        elif nums[mid] > target:
            high = mid - 1
        else:
            low = mid + 1
    return -1

nums = [6, 2, 3, 4, 5, 30, 1, 85, 10, 15, 40]
nums.sort()
target = 2       # 있는 경우 -> 해당 요소의 인덱스 반환
# target = 90    # 없는 경우 -> -1
print(binary_search_iteration(nums, target))

#2. recursion
def binary_search_recursion(nums, low, high, target):
    if low > high:
        return -1
    else:
        mid = (low + high) // 2
        if target == nums[mid]:
            return mid
        elif target < nums[mid]:
            return binary_search_recursion(nums, low, mid-1, target)
        else:
            return binary_search_recursion(nums, mid+1, high, target)

nums = [6, 2, 3, 4, 5, 30, 1, 85, 10, 15, 40]
nums.sort()
# target = 2       # 있는 경우 -> 해당 요소의 인덱스 반환
target = 90    # 없는 경우 -> -1
print(binary_search_recursion(nums, 0, len(nums)-1, target))


from sense_hat import SenseHat
import time
from math import cos, sin, radians, degrees, sqrt, atan2

"""

  Sense HAT Sensors Display !

  Select Temperature, Pressure, or Humidity  with the Joystick
  to visualize the current sensor values on the LED.

  Note: Requires sense_hat 2.2.0 or later

"""

sense = SenseHat()

green = (0, 255, 0)
red = (255, 0, 0)
blue = (0, 0, 255)
white = (255, 255, 255)

inCal = (-4,2,43.5,71,93.5,114,137,162,186,214,242.5,269,311,356,360)
outCal = (0,0,30,60,90,120,150,180,210,240,270,300,360,360)
calData = ( (0, -4), \
            (0,  2), \
            (30, 43.5), \
            (60, 71), \
            (90, 93.5), \
            (120, 114), \
            (150, 137), \
            (180, 162), \
            (210, 186), \
            (240, 214), \
            (270, 242.5), \
            (300, 269), \
            (330, 311), \
            (360, 356), \
            (360, 360) )

sense.clear()
sense.set_pixel(0,0,green)
sense.set_pixel(7,0,blue)
sense.set_pixel(0,7,white)
sense.set_pixel(7,7,red)
time.sleep(5)

def show_t():
  sense.show_letter("T", back_colour = red)
  time.sleep(.5)

def show_p():
  sense.show_letter("P", back_colour = green)
  time.sleep(.5)

def show_h():
  sense.show_letter("H", back_colour = blue)
  time.sleep(.5)

def update_screen(angle, show_letter = False):

  yorig = 3
  xorig = 3
  ca = cos(radians(angle))
  sa = sin(radians(angle))
  sense.clear()

  for l in range(-10,0):
    x = int(ca*float(l)/2 + xorig)
    y = int(sa*float(l)/2 + yorig)
    if x >= 0 and x <= 7 and y >= 0 and y <= 7:
      sense.set_pixel(x,y,white)
  for l in range(0,10):
    x = int(ca*float(l)/2 + xorig)
    y = int(sa*float(l)/2 + yorig)
    if x >= 0 and x <= 7 and y >= 0 and y <= 7:
      sense.set_pixel(x,y,red)
  sense.set_pixel(xorig,yorig,green)

####
# Intro Animation
####

show_t()
show_p()
show_h()

# update_screen("temp")

index = 0
sensors = ["temp", "pressure", "humidity"]
startTime = time.time()
logFile=open("/home/pi/Projects/VMS/orientation_raw.csv","w+")
####
# Main game loop
####

sense.clear()
while True:
#   selection = False
#   events = sense.stick.get_events()
#   for event in events:
#     # Skip releases
#     if event.action != "released":
#       if event.direction == "left":
#         index -= 1
#         selection = True
#       elif event.direction == "right":
#         index += 1
#         selection = True
#       if selection:
#         current_mode = sensors[index % 3]
#         update_screen(current_mode, show_letter = True)
#
#   if not selection:
#     current_mode = sensors[index % 3]
#     update_screen(current_mode)

  elapsedTime = time.time() - startTime
  gyroRaw = sense.get_gyroscope_raw()
  accelRaw = sense.get_accelerometer_raw()
  magRaw = sense.get_compass_raw()
  orientation = sense.get_orientation_degrees()

#   print("0,{0},{x},{y},{z}".format(elapsedTime,**gyroRaw)) # rad/sec
#   print("1,{0},{x},{y},{z}".format(elapsedTime,**accelRaw)) # Gs
#   print("2,{0},{x},{y},{z}".format(elapsedTime,**magRaw))

#   logFile.write("0,{0},{x},{y},{z}\r\n".format(elapsedTime,**gyroRaw)) # rad/sec
#   logFile.write("1,{0},{x},{y},{z}\r\n".format(elapsedTime,**accelRaw)) # Gs
  logFile.write("2,{0},{x},{y},{z}\r\n".format(elapsedTime,**magRaw)) # microT

  orientation = sense.get_orientation_degrees()
  if(orientation["pitch"] > 180):
      orientation["pitch"] = orientation["pitch"] - 360
  if(orientation["roll"] > 180):
      orientation["roll"] = orientation["roll"] - 360

  print("3,{0},{pitch},{roll},{yaw}".format(elapsedTime,**orientation))
#   yawRaw = orientation["yaw"]
#   for idx in range(len(inCal)):
#       if yawRaw < inCal[idx]:
#           break
#   print(idx)
#   delta = (yawRaw - inCal[idx-1])/(inCal[idx]-inCal[idx-1])
#   print(delta)
#   calYaw = outCal[idx-1] + delta * (outCal[idx] - outCal[idx-1])
#   orientation["yaw"] = calYaw
#   print("ot 3,{0},{1},{2},{3}".format(elapsedTime,orientation["pitch"],orientation["roll"],calYaw))
  logFile.write("3,{0},{pitch},{roll},{yaw}".format(elapsedTime,**orientation))

#
#   xTiltComp = -1*accelRaw["x"]
#   yTiltComp = accelRaw["y"]
#   xyTiltMag = sqrt(xTiltComp**2 + yTiltComp**2)
#   xyTilt = degrees(atan2(xTiltComp/xyTiltMag,yTiltComp/xyTiltMag))
#   print(xyTilt)
#   update_screen(float(-1*orientation["yaw"]))
#   update_screen(float(-1*orientation["pitch"]))
#   update_screen(float(xyTilt)-90.0)
#   time.sleep(0.1)

#   #north = sense.get_compass()
#   north = 0
#   print("{0},{1},{2},{3},{4}".format(elapsedTime,orientation["pitch"],orientation["roll"],orientation["yaw"], north))
#   time.sleep(10)


"""
name: battle_ship.py

purpose: the main class for connecting the game and the protocol

author: bis-hanich-8

changelog:
    created: 30/12/2020
"""

from protocol_manager import ProtocolManager
from game_manager import GameManager
from excpetions import GameEnd

class BattleShip:
    """
    A main class for connecting the game and the protocol
    """

    def __init__(self, protocol_manager: ProtocolManager, game_manager: GameManager):
        """
        Initialize the battle ship classes
        :param protocol_manager: the protocol manager
        :param game_manager: the game manager
        """
        self._protocol_manager = protocol_manager
        self._game_manager = game_manager

    def play_game(self):
        """
        Play the game
        :return: None
        """
        self._protocol_manager.play_game()
        self._game_manager.initialize_board()
        my_turn = self._protocol_manager.ready_to_start()
        game_over = False
        try:
            while True:
                if my_turn:
                    guess = self._game_manager.get_next_guess()
                    self._protocol_manager.send_guess(guess)
                    answer = self._protocol_manager.get_guess_reply()
                    self._game_manager.set_answer(guess, answer)
                else:
                    answer = self._game_manager.attack(self._protocol_manager.get_guess())
                    self._protocol_manager.send_guess_reply(answer)
                if not answer[0]:
                    my_turn = not my_turn
        except GameEnd:
            print("Game over!")


# PROBLEM NOT SOLVED

a = [1, 0, 1, 0, 1, 1]
b = [1, 1, 0, 1, 1]
c = [0, 1, 0]
d = [0, 1, 1, 0]

def solution(data):

    if data[0] == 1 and data[1] == 0:
        x = 'oneZero'

    elif data[0] == 0 and data [1] == 1:
        x = 'zeroOne'

    elif data[0] == 1 and data [1] == 1:
        x = 'oneOne'

    else:
        x = 'zeroZero'

    count = 0

    for index in range(0, len(data) - 1, 2):
        print(index)

        if index >= len(data) - 1:
            break

        elif data[index] != first or data[ index + 1] != second:
            count = 1

    return count

print(solution(a), 1)
print(solution(b), 2)
print(solution(c), 0)
print(solution(d), 2)

# def valley(data): #valley list
#     valley = []

#     for index in range(len(data)):
#         if index == 0: # skip first item on the list
#             index = index + 1
#         elif data[index] < (data[index - 1]) and data[index] < data[index + 1]:
#             #if item is smaller than item location -1 and item location +1
#             valley.append(index)

#     return valley

# def peak_and_valley(data):
#     peak_and_valley = []

#     for index in range(len(data) - 1): #add -1 to avoid end of list error
#         if (data[index] > (data[index - 1]) and data[index] > data[index + 1]) or (data[index] < (data[index - 1]) and data[index] < data[index + 1]):
#             # if item is bigger than item location -1 and item location +1
#             peak_and_valley.append(index)
#     peak_and_valley.pop(0)
#     return peak_and_valley

# print(f'''
# Peak index/es:
# {peak(data)}

# Valley index/es:
# {valley(data)}

# Peak and Valley index/es:
# {peak_and_valley(data)}
# ''')


"""
[BOJ] 2110 공유기 설치
23.03.19 pcs
"""

"""
C개 공유기 - N개 집에 적당히 설치,
가장 인접한 두 공유기 사이 거리를 최대로 하는 프로그램

"""

n, c = map(int, input().split())
house = []
for i in range(n):
    house.append(int(input()))
ans = -1
house.sort()

def binary_search():
    global ans
    # 이분탐색 - 정답을 X라고 가정하고 진행
    # 이 문제에서 정답은 가장 인접한 공유기 사이의 최대 거리를 X라고 가정한다.
    left = 1  # 최소 값
    right = house[n-1] - house[0]  # 최대 값
    while left <= right:
        mid = (left + right) // 2
        curr = house[0]  # 현재위치
        count = 1

        for i in range(1, len(house)):
            if house[i] >= curr + mid:  # 거리가 mid보다 클 때 공유기 설치 가능
                curr = house[i]
                count += 1

        if count >= c:  # 더 많이 설치했다면 (거리증가)
            left = mid+1
            ans = mid
        else:  # 더 적게 설치했다면 (거리감소)
            right = mid-1

binary_search()
print(ans)


import pygame
from pygame.sprite import Sprite

class Ship(Sprite):
	"""Класс для управления кораблем"""

	def __init__(self, ai_game):
		"""Задает начальную позицию"""
		super().__init__()

		self.screen = ai_game.screen
		self.settings = ai_game.settings
		# Rectangle surface
		self.screen_rect = ai_game.screen.get_rect()

		# Загружает изображение корабля и получает прямоугольник
		self.image = pygame.image.load('images/ship.bmp')
		# Положение корабля
		self.rect = self.image.get_rect()
		# Каждый новый корабль появляется у нижнего края экрана midtop etc positions
		self.rect.midbottom = self.screen_rect.midbottom

		# Прямоугольники принимают только целые значения, а скорость взяли дробную, поэтому
		self.x = float(self.rect.x)
		self.y = float(self.rect.y)

		# Флаги для перемещения
		self.moving_right = False
		self.moving_left = False
		self.moving_up = False
		self.moving_down = False

	def update(self):

		if self.moving_right and self.rect.right < self.screen_rect.right:
			self.x += self.settings.ship_speed

		if self.moving_left and self.rect.left > 0:
			self.x -= self.settings.ship_speed

		if self.moving_up and self.rect.top > self.screen_rect.top:
			self.y -= self.settings.ship_speed

		if self.moving_down and self.rect.bottom < self.screen_rect.bottom:
			self.y += self.settings.ship_speed

		self.rect.x = self.x
		self.rect.y = self.y

	def update1(self):
		"""Обновляет позицию корабля с учетом нажатия клавиш"""
		if self.moving_right and self.rect.right < self.screen_rect.right:
			self.x += self.settings.ship_speed

		# Можно поставить и > 0, т.к. (0,0) в левом углу, но мы это опустим
		if self.moving_left and self.rect.left > self.screen_rect.left:
			self.x -= self.settings.ship_speed

		# Будет сохранена только целая часть
		self.rect.x = self.x

	def blitme(self):
		"""Рисует корабль в текущей позиции"""
		self.screen.blit(self.image, self.rect)

	def center_ship(self):
		"""Размещает корабль в центр экрана"""
		self.rect.midbottom = self.screen_rect.midbottom
		self.x = float(self.rect.x)
		self.y = float(self.rect.y)


from __future__ import absolute_import, print_function, division

import random

import yelp_data as yd
from utils.textdata import tokenize_text
from utils.statistics import map_range

from nltk.sentiment.vader import SentimentIntensityAnalyzer

from sklearn.feature_extraction import DictVectorizer
from sklearn.naive_bayes import MultinomialNB
import sklearn.metrics as metrics

def get_ngram_counts(n, text):
    """
    Return a dictionary counts of all ngrams in the list of sentences.
    """
    ngram_dict = {}
    for s in text:
        for i in range(len(s)):
            if i + n > len(s): break
            ngram = tuple(s[i:i+n])
            ngram_dict[ngram] = ngram_dict.get(ngram, 0) + 1
    return ngram_dict

def evaluate(classifier, data_x, data_y, report=False):
    y_true = data_y
    y_pred = classifier.predict(data_x)
    print("Accuracy =", metrics.accuracy_score(y_true, y_pred))
    if report:
        print(metrics.classification_report(y_true, y_pred))

def run():
    random.seed(42)
    sid = SentimentIntensityAnalyzer()

    print("Load data...")
    train_x, train_y = yd.load_yelp_reviews(yd.TRAIN_FILE)
    test_x, test_y = yd.load_yelp_reviews(yd.TEST_FILE)
    all_x = train_x + test_x

    # Extract features as dictionaries (it seems bigram works best)
    print("Extract features...")
    train_feat = [get_ngram_counts(2, tokenize_text(t)) for t in train_x]
    test_feat = [get_ngram_counts(2, tokenize_text(t)) for t in test_x]

    # Vectorize
    vec = DictVectorizer()
    vec.fit(train_feat)
    train_feat = vec.transform(train_feat)
    test_feat = vec.transform(test_feat)

    print("Begin training...")
    classifier = MultinomialNB().fit(train_feat, train_y)

    # Evaluating
    print("Evaluating trainset")
    evaluate(classifier, train_feat, train_y)
    print("Evaluating testset")
    evaluate(classifier, test_feat, test_y)

if __name__ == '__main__':
    run()


import os
from datetime import datetime

import handlers
from boto_retry import get_client_with_retries
from helpers import safe_json

MESSAGE_TYPE_ENDED = "task-ended"
MESSAGE_TYPE_STARTED = "task-started"

ERR_SEND_NOTIFICATION = "Cannot send notification to topic {}, {}"

ENV_RESULT_TOPIC = "SNS_RESULT_TOPIC_ARN"
MAX_SIZE = 262143

class ResultNotifications(object):

    def __init__(self, context, logger):
        self._sns_client = None
        self._context = context
        self._logger = logger

    @property
    def sns_client(self):
        if self._sns_client is None:
            self._sns_client = get_client_with_retries("sns", methods=["publish"], context=self._context)
        return self._sns_client

    @property
    def topic_arn(self):
        return os.getenv(ENV_RESULT_TOPIC, None)

    @classmethod
    def _build_common_attributes(cls, task):
        message = {a: task.get(a, "") for a in [
            handlers.TASK_TR_ID,
            handlers.TASK_TR_NAME,
            handlers.TASK_TR_ACTION,
            handlers.TASK_TR_ACCOUNT,
            handlers.TASK_TR_RESOURCES,
            handlers.TASK_TR_PARAMETERS
        ]}

        message["Time"] = datetime.now().isoformat()
        return message

    def _publish(self, message):
        self.sns_client.publish_with_retries(TopicArn=self.topic_arn, Message=safe_json(message)[0:MAX_SIZE])

    def publish_started(self, task):
        try:
            if task.get(handlers.TASK_TR_NOTIFICATIONS, False):
                message = self._build_common_attributes(task)
                message["Type"] = MESSAGE_TYPE_STARTED
                self._publish(message)
        except Exception as ex:
            self._logger.error(ERR_SEND_NOTIFICATION, self.topic_arn, ex)

    def publish_ended(self, task):
        try:
            if task.get(handlers.TASK_TR_NOTIFICATIONS, False):
                message = self._build_common_attributes(task)
                message["Type"] = MESSAGE_TYPE_ENDED
                message[handlers.TASK_TR_STATUS] = task.get(handlers.TASK_TR_STATUS, "")
                if task[handlers.TASK_TR_STATUS] == handlers.STATUS_COMPLETED:
                    message[handlers.TASK_TR_RESULT] = task.get(handlers.TASK_TR_RESULT)
                else:
                    message[handlers.TASK_TR_ERROR] = task.get(handlers.TASK_TR_ERROR, "")
                self._publish(message)
        except Exception as ex:
            self._logger.error(ERR_SEND_NOTIFICATION, self.topic_arn, ex)


#Graph from a txt file
import Tkinter as tk
import ttk
import matplotlib
matplotlib.use("TkAgg")
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2TkAgg
import matplotlib.animation as animation
from matplotlib.figure import Figure

Large_Font= ("Verdana", 12)

f = Figure(figsize=(5,5), dpi=100)
a = f.add_subplot(111)

def animate(i):
    pullData = open("Test-Data.txt", 'r').read()
    dataList = pullData.split('\n')
    xList = []
    yList = []
    for eachLine in dataList:
        if len (eachLine) > 1:
            x, y = eachLine.split(',')
            xList.append(int(x))
            yList.append(int(y))
    a.clear()
    a.plot(xList, yList)

class TextDapp (tk.Tk):

      def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args,**kwargs)
        tk.Tk.wm_title(self, "Sea of BTC Client")
        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand="true")
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, GraphP):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky='nsew')

        self.show_frame(StartPage)

      def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text='Text Data Graph', font=Large_Font)
        label.pack(pady=10, padx=10)
        label = tk.Label(self, text='This is a Test Python script that Graphs numbers from a .txt File')
        label.pack()
        button0 = ttk.Button(self,text='Graph',command=lambda: controller.show_frame(GraphP))
        button0.pack()
        button1 = ttk.Button(self, text='Exit', command=quit)
        button1.pack()
        label = tk.Label(self, text='Make sure Test-Data.txt is in the same Dir as the script & 1,2,3 ect in Each Line then a (,) &  then your # ')
        label.pack()

class GraphP(tk.Frame):

    def __init__(self,parent , controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Graph Page", font=Large_Font)
        label.pack(pady=10, padx=10)
        button5 = ttk.Button(self, text='Quit', command=quit)
        button5.pack()
        button6 = ttk.Button(self, text='Home', command=lambda: controller.show_frame(StartPage))
        button6.pack()

        canvas = FigureCanvasTkAgg(f, self)
        canvas.show()
        canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand = "true")

        toolbar = NavigationToolbar2TkAgg(canvas, self)
        toolbar.update()
        canvas._tkcanvas.pack(side=tk.TOP, fill=tk.BOTH, expand = "true")

app = TextDapp()
ani = animation.FuncAnimation(f, animate, interval=2000)
app.mainloop()


import pytest
from life_grid import LifeGrid

steps_cases = [("""
........
....*...
...**...
........
""",
"""
........
...**...
...**...
........
"""),
("""
*.......
....*...
...**...
........
""",
"""
........
...**...
...**...
........
"""),
]

class TestGridEvolution:

    @pytest.mark.parametrize("in_grid, out_grid", steps_cases)
    def test_evolution(self, in_grid, out_grid):
        g1 = LifeGrid.from_string( in_grid )
        g2 = LifeGrid.from_string( out_grid )
        assert g2 == g1.step()


"""
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to
target.
"""

class Solution:

    def twoSum(self, nums, target: int):
        mmap = {}
        for i, v in enumerate(nums):
            if v in mmap:
                return [mmap[v], i]
            mmap[target-v] = i


from gi.repository import RwcalYang
from gi.repository.RwTypes import RwStatus
import logging
import rw_peas
import rwlogger
import time
import argparse
import os
import sys
import uuid
from os.path import basename

FLAVOR_NAME = 'm1.medium'
DEFAULT_IMAGE='/net/sharedfiles/home1/common/vm/rift-root-latest.qcow2'

persistent_resources = {
    'vms'      : ['mission_control','launchpad',],
    'networks' : ['public', 'private', 'multisite'],
    'flavors'  : ['m1.tiny', 'm1.small', 'm1.medium', 'm1.large', 'm1.xlarge'],
    'images'   : ['rwimage','rift-root-latest.qcow2','rift-root-latest-trafgen.qcow2', 'rift-root-latest-trafgen-f.qcow2']
}

#
# Important information about openstack installation. This needs to be manually verified
#
openstack_info = {
    'username'           : 'pluto',
    'password'           : 'mypasswd',
    'project_name'       : 'demo',
    'mgmt_network'       : 'private',
    'physical_network'   : 'physnet1',
    'network_type'       : 'VLAN',
    'segmentation_id'    : 42, ### What else?
    'subnets'            : ["11.0.0.0/24", "12.0.0.0/24", "13.0.0.0/24", "14.0.0.0/24"],
    'subnet_index'       : 0,
    }

logging.basicConfig(level=logging.INFO)

USERDATA_FILENAME = os.path.join(os.environ['RIFT_INSTALL'],
                                 'etc/userdata-template')

RIFT_BASE_USERDATA = '''
#cloud-config
runcmd:
 - sleep 5
 - /usr/rift/scripts/cloud/enable_lab
 - /usr/rift/etc/fix_this_vm
'''

try:
    fd = open(USERDATA_FILENAME, 'r')
except Exception as e:
    #logger.error("Received exception during opening of userdata (%s) file. Exception: %s" %(USERDATA_FILENAME, str(e)))
    sys.exit(-1)
else:
    LP_USERDATA_FILE = fd.read()
    # Run the enable lab script when the openstack vm comes up
    LP_USERDATA_FILE += "runcmd:\n"
    LP_USERDATA_FILE += " - /usr/rift/scripts/cloud/enable_lab\n"
    LP_USERDATA_FILE += " - /usr/rift/etc/fix_this_vm\n"

def get_cal_plugin():
    """
    Loads rw.cal plugin via libpeas
    """
    plugin = rw_peas.PeasPlugin('rwcal_openstack', 'RwCal-1.0')
    engine, info, extension = plugin()
    cal = plugin.get_interface("Cloud")
    # Get the RwLogger context
    rwloggerctx = rwlogger.RwLog.Ctx.new("Cal-Log")
    try:
        rc = cal.init(rwloggerctx)
        assert rc == RwStatus.SUCCESS
    except:
        logger.error("ERROR:Cal plugin instantiation failed. Aborting tests")
    else:
        logger.info("Openstack Cal plugin successfully instantiated")
        return cal

def get_cal_account(auth_url):
    """
    Returns cal account
    """
    account                        = RwcalYang.CloudAccount()
    account.account_type           = "openstack"
    account.openstack.key          = openstack_info['username']
    account.openstack.secret       = openstack_info['password']
    account.openstack.auth_url     = auth_url
    account.openstack.tenant       = openstack_info['project_name']
    account.openstack.mgmt_network = openstack_info['mgmt_network']
    return account

logger = logging.getLogger('rift.cal.openstackresources')

class OpenstackResources(object):
    """
    A stupid class to manage bunch of openstack resources
    """
    def __init__(self, controller):
        self._cal      = get_cal_plugin()
        self._acct     = get_cal_account('http://'+controller+':5000/v3/')
        self._id       = 0
        self._image_id = None
        self._flavor_id = None

    def _destroy_vms(self):
        """
        Destroy VMs
        """
        logger.info("Initiating VM cleanup")
        rc, rsp = self._cal.get_vdu_list(self._acct)
        vdu_list = [vm for vm in rsp.vdu_info_list if vm.name not in persistent_resources['vms']]
        logger.info("Deleting VMs : %s" %([x.name for x in vdu_list]))

        for vdu in vdu_list:
            self._cal.delete_vdu(self._acct, vdu.vdu_id)

        logger.info("VM cleanup complete")

    def _destroy_networks(self):
        """
        Destroy Networks
        """
        logger.info("Initiating Network cleanup")
        rc, rsp = self._cal.get_virtual_link_list(self._acct)
        vlink_list = [vlink for vlink in rsp.virtual_link_info_list if vlink.name not in persistent_resources['networks']]

        logger.info("Deleting Networks : %s" %([x.name for x in vlink_list]))
        for vlink in vlink_list:
            self._cal.delete_virtual_link(self._acct, vlink.virtual_link_id)
        logger.info("Network cleanup complete")

    def _destroy_flavors(self):
        """
        Destroy Flavors
        """
        logger.info("Initiating flavor cleanup")
        rc, rsp = self._cal.get_flavor_list(self._acct)
        flavor_list = [flavor for flavor in rsp.flavorinfo_list if flavor.name not in persistent_resources['flavors']]

        logger.info("Deleting flavors : %s" %([x.name for x in flavor_list]))

        for flavor in flavor_list:
            self._cal.delete_flavor(self._acct, flavor.id)

        logger.info("Flavor cleanup complete")

    def _destroy_images(self):
        logger.info("Initiating image cleanup")
        rc, rsp = self._cal.get_image_list(self._acct)
        image_list = [image for image in rsp.imageinfo_list if image.name not in persistent_resources['images']]

        logger.info("Deleting images : %s" %([x.name for x in image_list]))

        for image in image_list:
            self._cal.delete_image(self._acct, image.id)

        logger.info("Image cleanup complete")

    def destroy_resource(self):
        """
        Destroy resources
        """
        logger.info("Cleaning up openstack resources")
        self._destroy_vms()
        self._destroy_networks()
        self._destroy_flavors()
        self._destroy_images()
        logger.info("Cleaning up openstack resources.......[Done]")

    def create_mission_control(self):
        vm_id = self.create_vm('mission_control',
                               userdata = RIFT_BASE_USERDATA)
        return vm_id

    def create_launchpad_vm(self, salt_master=None):
        node_id = str(uuid.uuid4())
        if salt_master is not None:
           userdata = LP_USERDATA_FILE.format(master_ip = salt_master,
                                           lxcname = node_id)
        else:
           userdata = RIFT_BASE_USERDATA

        vm_id = self.create_vm('launchpad',
                              userdata = userdata,
                              node_id = node_id)
#        vm_id = self.create_vm('launchpad2',
#                               userdata = userdata,
#                               node_id = node_id)
        return vm_id

    def create_vm(self, name, userdata, node_id = None):
        """
        Creates a VM. The VM name is derived from username

        """
        vm = RwcalYang.VDUInitParams()
        vm.name = name
        vm.flavor_id = self._flavor_id
        vm.image_id  = self._image_id
        if node_id is not None:
            vm.node_id = node_id
        vm.vdu_init.userdata = userdata
        vm.allocate_public_address = True
        logger.info("Starting a VM with parameter: %s" %(vm))

        rc, vm_id = self._cal.create_vdu(self._acct, vm)
        assert rc == RwStatus.SUCCESS
        logger.info('Created vm: %s with id: %s', name, vm_id)
        return vm_id

    def create_network(self, name):
        logger.info("Creating network with name: %s" %name)
        network                = RwcalYang.NetworkInfoItem()
        network.network_name   = name
        network.subnet         = openstack_info['subnets'][openstack_info['subnet_index']]

        if openstack_info['subnet_index'] == len(openstack_info['subnets']):
            openstack_info['subnet_index'] = 0
        else:
            openstack_info['subnet_index'] += 1

        if openstack_info['physical_network']:
            network.provider_network.physical_network = openstack_info['physical_network']
        if openstack_info['network_type']:
            network.provider_network.overlay_type     = openstack_info['network_type']
        if openstack_info['segmentation_id']:
            network.provider_network.segmentation_id  = openstack_info['segmentation_id']
            openstack_info['segmentation_id'] += 1

        rc, net_id = self._cal.create_network(self._acct, network)
        assert rc == RwStatus.SUCCESS

        logger.info("Successfully created network with id: %s" %net_id)
        return net_id

    def create_image(self, location):
        img = RwcalYang.ImageInfoItem()
        img.name = basename(location)
        img.location = location
        img.disk_format = "qcow2"
        img.container_format = "bare"

        logger.info("Uploading image : %s" %img.name)
        rc, img_id = self._cal.create_image(self._acct, img)
        assert rc == RwStatus.SUCCESS

        rs = None
        rc = None
        image = None
        for i in range(100):
            rc, rs = self._cal.get_image(self._acct, img_id)
            assert rc == RwStatus.SUCCESS
            logger.info("Image (image_id: %s) reached status : %s" %(img_id, rs.state))
            if rs.state == 'active':
                image = rs
                break
            else:
                time.sleep(2) # Sleep for a second

        if image is None:
            logger.error("Failed to upload openstack image: %s", img)
            sys.exit(1)

        self._image_id = img_id
        logger.info("Uploading image.......[Done]")

    def create_flavor(self):
        """
        Create Flavor suitable for rift_ping_pong VNF
        """
        flavor = RwcalYang.FlavorInfoItem()
        flavor.name = FLAVOR_NAME
        flavor.vm_flavor.memory_mb   = 16384 # 16GB
        flavor.vm_flavor.vcpu_count  = 4
        flavor.vm_flavor.storage_gb  = 20 # 20 GB

        logger.info("Creating new flavor. Flavor Info: %s" %str(flavor.vm_flavor))

        rc, flavor_id = self._cal.create_flavor(self._acct, flavor)
        assert rc == RwStatus.SUCCESS
        logger.info("Creating new flavor.......[Done]")
        return flavor_id

    def find_image(self, name):
        logger.info("Searching for uploaded image: %s" %name)
        rc, rsp = self._cal.get_image_list(self._acct)
        image_list = [image for image in rsp.imageinfo_list if image.name ==  name]

        if not image_list:
            logger.error("Image %s not found" %name)
            return None

        self._image_id = image_list[0].id
        logger.info("Searching for uploaded image.......[Done]")
        return self._image_id

    def find_flavor(self, name=FLAVOR_NAME):
        logger.info("Searching for required flavor: %s" %name)
        rc, rsp = self._cal.get_flavor_list(self._acct)
        flavor_list = [flavor for flavor in rsp.flavorinfo_list if flavor.name == name]

        if not flavor_list:
            logger.error("Flavor %s not found" %name)
            self._flavor_id = self.create_flavor()
        else:
            self._flavor_id = flavor_list[0].id

        logger.info("Searching for required flavor.......[Done]")
        return self._flavor_id

def main():
    """
    Main routine
    """
    parser = argparse.ArgumentParser(description='Script to manage openstack resources')

    parser.add_argument('--controller',
                        action = 'store',
                        dest = 'controller',
                        type = str,
                        help='IP Address of openstack controller. This is mandatory parameter')

    parser.add_argument('--cleanup',
                        action = 'store',
                        dest = 'cleanup',
                        nargs = '+',
                        type = str,
                        help = 'Perform resource cleanup for openstack installation. \n Possible options are {all, flavors, vms, networks, images}')

    parser.add_argument('--persist-vms',
                        action = 'store',
                        dest = 'persist_vms',
                        nargs = '+',
                        type = str,
                        help = 'VM instance name to persist')

    parser.add_argument('--salt-master',
                        action = 'store',
                        dest = 'salt_master',
                        type = str,
                        help='IP Address of salt controller. Required, if VMs are being created.')

    parser.add_argument('--upload-image',
                        action = 'store',
                        dest = 'upload_image',
                        help='Openstack image location to upload and use when creating vms.x')

    parser.add_argument('--use-image',
                        action = 'store',
                        dest = 'use_image',
                        help='Image name to be used for VM creation')

    parser.add_argument('--use-flavor',
                        action = 'store',
                        dest = 'use_flavor',
                        help='Flavor name to be used for VM creation')

    parser.add_argument('--mission-control',
                        action = 'store_true',
                        dest = 'mission_control',
                        help='Create Mission Control VM')

    parser.add_argument('--launchpad',
                        action = 'store_true',
                        dest = 'launchpad',
                        help='Create LaunchPad VM')

    parser.add_argument('--use-project',
                        action = 'store',
                        dest = 'use_project',
                        help='Project name to be used for VM creation')

    argument = parser.parse_args()

    if argument.persist_vms is not None:
        for vm_name in argument.persist_vms:
            vm_name_list = vm_name.split(',')
            for single_vm in vm_name_list:
                persistent_resources['vms'].append(single_vm)
        print("persist: {}".format(persistent_resources['vms']))
        #sys.exit(0)

    if argument.controller is None:
        logger.error('Need openstack controller IP address')
        sys.exit(-1)

    if argument.use_project is not None:
        openstack_info['project_name'] = argument.use_project

    ### Start processing
    logger.info("Instantiating cloud-abstraction-layer")
    drv = OpenstackResources(argument.controller)
    logger.info("Instantiating cloud-abstraction-layer.......[Done]")

    if argument.cleanup is not None:
        for r_type in argument.cleanup:
            if r_type == 'all':
                drv.destroy_resource()
                break
            if r_type == 'images':
                drv._destroy_images()
            if r_type == 'flavors':
                drv._destroy_flavors()
            if r_type == 'vms':
                drv._destroy_vms()
            if r_type == 'networks':
                drv._destroy_networks()

    if argument.upload_image is not None:
        drv.create_image(argument.upload_image)
    elif argument.use_image is not None:
        img = drv.find_image(argument.use_image)
        if img == None:
            logger.error("Image: %s not found" %(argument.use_image))
            sys.exit(-4)
    else:
        if argument.mission_control or argument.launchpad:
            img = drv.find_image(basename(DEFAULT_IMAGE))
            if img == None:
                drv.create_image(DEFAULT_IMAGE)

    if argument.use_flavor is not None:
        drv.find_flavor(argument.use_flavor)
    else:
        drv.find_flavor()

    if argument.mission_control == True:
        drv.create_mission_control()

    if argument.launchpad == True:
        drv.create_launchpad_vm(salt_master = argument.salt_master)

if __name__ == '__main__':
    main()


# 作业1 : 分页获取豆瓣的数据（json数据）， 把电影图片存入本地，且图片名取电影名
# url = "https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start="+ str(i * 20)+"&limit=20"
import json
import urllib.request
import os

path = r'/home/misaka/PycharmProjects/PaChong/day02/img'

headers = {
    'User-Agent':'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'
}

x = 0
for i in range(1, 3):
    url = "https://movie.douban.com/j/chart/top_list?type=11&interval_id=100%3A90&action=&start=" + str(i * 20) + "&limit=20"

    req = urllib.request.Request(url,headers=headers)
    response = urllib.request.urlopen(req)
    context = response.read().decode()

    json_list = json.loads(context)
    # print(json_list)

    # print(cover_url)
    for item in json_list:
        cover_url = item['cover_url']
        file_name = item['title']
        x += 1
        urllib.request.urlretrieve(cover_url,'/home/misaka/PycharmProjects/PaChong/day02/img/'+file_name+'.jpg')
        print(x,'下载中')


from turtle import Turtle, Screen
import random

screen = Screen()
screen.setup(width=500, height=400)
user_bet = screen.textinput(title="Make your bet:", prompt="Which turtle will win the race: Enter Color:  ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
is_race_on = False
y_pos = [-125, -75, -25, 25, 75, 125]
turt_list = []

for index in range(0, 6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.color(colors[index])
    new_turtle.penup()
    new_turtle.goto(x=-230, y=y_pos[index])
    turt_list.append(new_turtle)

if user_bet:
    is_race_on = True

while is_race_on:

    for turtle in turt_list:
        if turtle.xcor() > 230:
            is_race_on = False
            winner = turtle.pencolor()
            if winner == user_bet:
               print(f"You Won! The {winner} turtle is the winner!")
            else:
                print(f"You've lost! The winner was {winner} turtle")
        ran_dist = random.randint(0, 10)
        turtle.forward(ran_dist)

screen.exitonclick()


from django.contrib.auth.models import User
from django.db import transaction
from rest_framework import serializers

from anime.models import Anime
from user.serializer import UsuarioListSerializer

class AnimeListSerializer(serializers.ModelSerializer):
    cd_usuario = UsuarioListSerializer()

    class Meta:
        model = Anime
        fields = (
            'id',
            'nm_anime',
            'ds_anime',
            'ie_assistido',
            'ie_favorito',
            'cd_usuario'
        )

class AnimeCreateSerializer(serializers.ModelSerializer):

    class Meta:
        model = Anime
        fields = (
            'nm_anime',
            'ds_anime',
            'ie_assistido',
            'ie_favorito',
            'cd_usuario'
        )

class AnimeUpdadeSerializer(serializers.ModelSerializer):

    class Meta:
        model = Anime
        fields = (
            'nm_anime',
            'ds_anime',
            'ie_assistido',
            'ie_favorito',
        )


Import('env')
Import('ice_libs')
Import('db_libs')
Import('boost_libs')
Import('cpp_')
Import('all_libs')

autogrouping = env.Program('autogroup',
	source = [
		Glob('*.cc'),
		Glob('./method/*.cc'),
		Glob('./util/*.cc'),
		Glob('./method/impl/*.cc')
	],
	LIBS = [
		cpp_['fcgi'],
		cpp_['cwf'],
		cpp_['arch'],
		cpp_['dbpool'],
		cpp_['xceadapter'],
		cpp_['base'],
		boost_libs,
		db_libs,
		ice_libs,
		'log4cplus',
		all_libs,
	]
)


import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.nn import init

def conv3x3(in_channels, out_channels, stride=1,
            padding=1, bias=True, groups=1):
    return nn.Conv2d(
        in_channels,
        out_channels,
        kernel_size=3,
        stride=stride,
        padding=padding,
        bias=bias,
        groups=groups)

def upconv2x2(in_channels, out_channels, mode='transpose'):
    if mode == 'transpose':
        return nn.ConvTranspose2d(
            in_channels,
            out_channels,
            kernel_size=2,
            stride=2)
    else:
        # out_channels is always going to be the same
        # as in_channels
        return nn.Sequential(
            nn.Upsample(mode='bilinear', scale_factor=2),
            conv1x1(in_channels, out_channels))

def conv1x1(in_channels, out_channels, groups=1):
    return nn.Conv2d(
        in_channels,
        out_channels,
        kernel_size=1,
        groups=groups,
        stride=1)

class DownConv(nn.Module):
    """
    A helper Module that performs 2 convolutions and 1 MaxPool.
    A ReLU activation follows each convolution.
    """

    def __init__(self, in_channels, out_channels, pooling=True):
        super(DownConv, self).__init__()

        self.in_channels = in_channels
        self.out_channels = out_channels
        self.pooling = pooling

        self.conv1 = conv3x3(self.in_channels, self.out_channels)
        self.conv2 = conv3x3(self.out_channels, self.out_channels)

        if self.pooling:
            self.pool = nn.MaxPool2d(kernel_size=2, stride=2)

    def forward(self, x):
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        before_pool = x
        if self.pooling:
            x = self.pool(x)
        return x, before_pool

class UpConv(nn.Module):
    """
    A helper Module that performs 2 convolutions and 1 UpConvolution.
    A ReLU activation follows each convolution.
    """

    def __init__(self, in_channels, out_channels,
                 merge_mode='concat', up_mode='transpose'):
        super(UpConv, self).__init__()

        self.in_channels = in_channels
        self.out_channels = out_channels
        self.merge_mode = merge_mode
        self.up_mode = up_mode

        self.upconv = upconv2x2(self.in_channels, self.out_channels,
                                mode=self.up_mode)

        if self.merge_mode == 'concat':
            self.conv1 = conv3x3(
                2*self.out_channels, self.out_channels)
        else:
            # num of input channels to conv2 is same
            self.conv1 = conv3x3(self.out_channels, self.out_channels)
        self.conv2 = conv3x3(self.out_channels, self.out_channels)

    def forward(self, from_down, from_up):
        """ Forward pass
        Arguments:
            from_down: tensor from the encoder pathway
            from_up: upconv'd tensor from the decoder pathway
        """
        from_up = self.upconv(from_up)
        if self.merge_mode == 'concat':
            x = torch.cat((from_up, from_down), 1)
        else:
            x = from_up + from_down
        x = F.relu(self.conv1(x))
        x = F.relu(self.conv2(x))
        return x

class AbstractUNet(nn.Module):
    """ `UNet` class is based on https://arxiv.org/abs/1505.04597
    The U-Net is a convolutional encoder-decoder neural network.
    Contextual spatial information (from the decoding,
    expansive pathway) about an input tensor is merged with
    information representing the localization of details
    (from the encoding, compressive pathway).
    Modifications to the original paper:
    (1) padding is used in 3x3 convolutions to prevent loss
        of border pixels
    (2) merging outputs does not require cropping due to (1)
    (3) residual connections can be used by specifying
        UNet(merge_mode='add')
    (4) if non-parametric upsampling is used in the decoder
        pathway (specified by upmode='upsample'), then an
        additional 1x1 2d convolution occurs after upsampling
        to reduce channel dimensionality by a factor of 2.
        This channel halving happens with the convolution in
        the tranpose convolution (specified by upmode='transpose')
    """
    # * enforces named parameters to avoid accidential misconfigurations
    def __init__(self, config):
        super(AbstractUNet, self).__init__()
        up_mode = config['UP_MODE']
        if up_mode in ('transpose', 'upsample'):
            self.up_mode = up_mode
        else:
            raise ValueError("\"{}\" is not a valid mode for "
                             "upsampling. Only \"transpose\" and "
                             "\"upsample\" are allowed.".format(up_mode))
        merge_mode = config['MERGE_MODE']
        if merge_mode in ('concat', 'add'):
            self.merge_mode = merge_mode
        else:
            raise ValueError("\"{}\" is not a valid mode for"
                             "merging up and down paths. "
                             "Only \"concat\" and "
                             "\"add\" are allowed.".format(up_mode))

        # NOTE: up_mode 'upsample' is incompatible with merge_mode 'add'
        if self.up_mode == 'upsample' and self.merge_mode == 'add':
            raise ValueError("up_mode \"upsample\" is incompatible "
                             "with merge_mode \"add\" at the moment "
                             "because it doesn't make sense to use "
                             "nearest neighbour to reduce "
                             "depth channels (by half).")
        self.mean = config['MEAN']
        self.std = config['STD']
        self.in_channels = config['IN_CHANNELS']
        self.depth = config['DEPTH']
        self.patch_size = config['PRED_PATCH_SIZE']
        self.overlap = config['OVERLAP']
        self.augment_data = config['AUGMENT_DATA']
        self.start_filts = config['START_FILTS']
        self.up_mode = config['UP_MODE']
        self.merge_mode = config['MERGE_MODE']
        self.device = torch.device(config['DEVICE'])

        AbstractUNet._verify_depth_config(self.depth, self.patch_size,
                                          self.overlap)

        self.down_convs = []
        self.up_convs = []

        self.noiseSTD = nn.Parameter(data=torch.log(torch.tensor(0.5)))
        self.noiseSTD.requires_grad = False

        # create the encoder pathway and add to a list
        for i in range(self.depth):
            ins = self.in_channels if i == 0 else outs
            outs = self.start_filts*(2**i)
            pooling = True if i < self.depth-1 else False
            down_conv = DownConv(ins, outs, pooling=pooling)
            self.down_convs.append(down_conv)

        # create the decoder pathway and add to a list
        # - careful! decoding only requires depth-1 blocks
        for i in range(self.depth-1):
            ins = outs
            outs = ins // 2
            up_conv = UpConv(ins, outs, up_mode=up_mode,
                             merge_mode=merge_mode)
            self.up_convs.append(up_conv)

        # add the list of modules to current module
        self.down_convs = nn.ModuleList(self.down_convs)
        self.up_convs = nn.ModuleList(self.up_convs)

        self._build_network_head(outs)

        self.reset_params()

        # Push network to respective device
        self.to(self.device)

        if config.get('FREEZE_WEIGHTS', False):
            for param in self.parameters():
                param.requires_grad = False

    def _build_network_head(self, outs):
        raise NotImplementedError

    @staticmethod
    def _verify_depth_config(depth, patch_size, overlap):
        while depth > 0:
            patch_size = patch_size / 2.0
            depth -= 1
        assert patch_size.is_integer(), 'Patch size must be [depth]-many times'+\
                                        ' divisible by 2.'
        # No idea what to do with overlap...

    @staticmethod
    def weight_init(m):
        if isinstance(m, nn.Conv2d):
            init.xavier_normal_(m.weight)
            init.constant_(m.bias, 0)

    def reset_params(self):
        for _, m in enumerate(self.modules()):
            self.weight_init(m)

    def params_for_key(self, key):
        """This function returns the parameters of this network corresponding to
        the specified key. This is to enable different learning rates throughout
        the network. For example, a network could return its subnetwork's parameters
        for the key "LEARNING_RATE_SUBNETWORK_1". The appropriate learning rate
        gets automatically set by the trainer.

        Can be overwritten by subclasses to return custom parameters for custom
        param keys.

        Arguments:
            key {string} -- the key of the parameters
        """
        if key != "LEARNING_RATE":
            raise ValueError("Unrecognized learning rate.")
        return self.parameters()

    def loss_function(self, result):
        """The loss function of this network.

        Arguments:
            result {dict} -- dictionary containting at least the keys 'output',
                             'gt', 'mask'. Might contain more keys depending
                             one the implementation of the subclass.
        """
        raise NotImplementedError

    def forward(self, x):
        """Runs this network on the given input x.

        Arguments:
            x {torch.Tensor} -- the input image to process, must be of shape
                                [batch_size, C, H, W]

        Returns:
            {torch.Tensor} -- the denoised image
            NOTE -- subclasses might return additional artifacts
        """
        raise NotImplementedError

    def training_predict(self, sample):
        """Performs a forward step during training.

        Arguments:
            train_data {dict} -- Dictionary containting at least the keys 'raw',
                                 'gt' and 'mask'. Subclasses might require
                                 additional keys.

        Returns:
            {dict} -- containing at leas the keys 'output', 'gt' and 'mask
        """
        raise NotImplementedError

    def predict(self, image):
        """Performs prediction on the whole image. Since we have certain memory
        constraints on the GPU it is important to define an appropriate patch
        size. The overlap defines the overlap between patches.

        Arguments:
            image {torch.Tensor} -- 2D image (grayscale or RGB), must be of
                                    shape [batch_size, C, H, W]

        Returns:
            {np.array} -- the denoised image of shape [H, W, C]
            NOTE -- subclasses might return additional artifacts
        """
        data = self._pre_process_predict(image)
        image_height = image.shape[-2]
        image_width = image.shape[-1]
        xmin = 0
        ymin = 0
        xmax = self.patch_size
        ymax = self.patch_size
        ovLeft = 0
        # Image is in [C, H, W] shape
        while (xmin < image_width):
            ovTop = 0
            while (ymin < image_height):
                # We do not receive anything from this method because it
                # modifies the data in-place
                self._process_patch(data, ymin, ymax, xmin, xmax, ovTop, ovLeft)
                ymin = ymin-self.overlap+self.patch_size
                ymax = ymin+self.patch_size
                ovTop = self.overlap//2
            ymin = 0
            ymax = self.patch_size
            xmin = xmin-self.overlap+self.patch_size
            xmax = xmin+self.patch_size
            ovLeft = self.overlap//2
        return self._post_process_predict(data)

    def _pre_process_predict(self, image):
        """Subclasses are supposed to prepare needed variables to perform
        the actual prediction.

        Returns:
            {dict} -- dictionary containing all the necessary variables
        """
        raise NotImplementedError

    def _process_patch(self, data, ymin, ymax, xmin, xmax, ovTop, ovLeft):
        """Performs prediction on the specified patch coordinates given the
        specified data dictionary. This method is for internal use of the
        prediction pipeline only.

        NOTE: Does not return anything because it modifies the data in-place.

        Arguments:
            data {dict} -- a dictionary with the data to work on
            ymin {int} -- y minimum of patch
            ymax {int} -- y maximum of patch
            xmin {int} -- x minimum of patch
            xmax {int} -- x maximum of patch
            ovTop {int} -- overlap top
            ovLef {int} -- overlap left
        """
        raise NotImplementedError

    def predict_patch(self, patch):
        """Performs prediction on the specified patch without any further
        processing.

        Arguments:
            patch {torch.Tensor} -- the patch to process of shape
                                    [batch_size, C, H, W]
        """
        raise NotImplementedError

    def _post_process_predict(self, result):
        """In this method subclasses can assemble the final results of the
        prediction.

        Arguments:
            result {dict} -- containing all the keys that the subclasses need

        Returns:
            {dict}        -- a dictionary containing the final results
        """
        raise NotImplementedError


def solution(prices):
    st = []
    st_idx = [-1]

    length = len(prices)
    answer = [0 for i in range(length)]

    for i in range(length):
        p = prices[i]
        while(len(st)>0):
            cur_p = st_get(st, st_idx)
            if(p<cur_p[0]):
                idx = cur_p[1]
                answer[idx] = i - idx
                continue
            else:
                st_put(cur_p, st, st_idx)
                break
        st_put((p, i), st, st_idx)
    index = length-1
    while(len(st)):
        cur_p = st_get(st, st_idx)
        idx = cur_p[1]
        answer[idx] = index - idx
    return answer

def st_put(val, st, idx):
    st.append(val)
    idx[0]+=1
    return

def st_get(st, idx):
    value = st[idx[0]]
    del st[idx[0]]
    idx[0]-=1
    return value

print(solution([1, 2, 3, 2, 3]))


from flask import Blueprint, current_app, jsonify, request

from bhadrasana.models.laudo import get_empresas, get_ncm, get_empresa, \
    get_empresas_nome

cadastrosapi = Blueprint('cadastrosapi', __name__)

@cadastrosapi.route('/api/empresa/<cnpj>', methods=['GET'])
def empresa_(cnpj):
    db_session = current_app.config['db_session']
    try:
        empresa = get_empresa(db_session, cnpj)
        if empresa is None:
            return jsonify({'msg': 'Empresa %s não encontrada' % cnpj}), 404
    except ValueError as err:
        return jsonify(
            {'msg': str(err)}), 400
    except Exception as err:  # pragma: no cover
        current_app.logger.error(err, exc_info=True)
        return jsonify(
            {'msg': 'Erro inesperado! Detalhes no log da aplicação. ' + str(err)}), 500
    return jsonify(empresa.dump()), 200

@cadastrosapi.route('/api/empresa_e_filiais/<cnpj>', methods=['GET'])
def empresa_filiais(cnpj):
    db_session = current_app.config['db_session']
    try:
        empresas = get_empresas(db_session, cnpj)
        result = [empresa.dump() for empresa in empresas]
    except ValueError as err:
        return jsonify(
            {'msg': str(err)}), 400
    except Exception as err:  # pragma: no cover
        current_app.logger.error(err, exc_info=True)
        return jsonify(
            {'msg': 'Erro inesperado! Detalhes no log da aplicação. ' + str(err)}), 500
    return jsonify(result), 404 if len(result) == 0 else 200

@cadastrosapi.route('/api/empresas', methods=['GET'])
def empresas_():
    db_session = current_app.config['db_session']
    try:
        nome = request.args.get('nome')
        empresas = get_empresas_nome(db_session, nome)
        result = [empresa.dump() for empresa in empresas]
        if len(result) == 0:
            return jsonify(
                {'msg': 'Empresas não encontradas com filtro %s ' % request.args}), 404
    except ValueError as err:
        return jsonify(
            {'msg': str(err)}), 400
    except Exception as err:  # pragma: no cover
        current_app.logger.error(err, exc_info=True)
        return jsonify(
            {'msg': 'Erro inesperado! Detalhes no log da aplicação. ' + str(err)}), 500
    return jsonify(result), 404 if len(result) == 0 else 200

@cadastrosapi.route('/api/ncm/<codigo>', methods=['GET'])
def ncm_(codigo):
    db_session = current_app.config['db_session']
    try:
        ncm = get_ncm(db_session, codigo)
        if ncm is None:
            return jsonify({'msg': 'NCM %s não encontrado' % codigo}), 404
    except ValueError as err:
        return jsonify(
            {'msg': str(err)}), 400
    except Exception as err:  # pragma: no cover
        current_app.logger.error(err, exc_info=True)
        return jsonify(
            {'msg': 'Erro inesperado! Detalhes no log da aplicação. ' + str(err)}), 500
    return jsonify(ncm.dump()), 200


from math import sin

import numpy as np
from mpi4py import MPI

class Task:
    f = staticmethod(lambda x, y: x * y)
    f_left = f1 = staticmethod(lambda y: y ** 2)
    f_right = f2 = staticmethod(lambda y: sin(y))
    f_bottom = f3 = staticmethod(lambda x: x ** 3)
    f_top = f4 = staticmethod(lambda x: x ** 2)

class Point:
    def __init__(self, x, y):
        self.x, self.y = x, y

    def __repr__(self):
        return '({0:.2f}, {1:.2f})'.format(self.x, self.y)

class Index:
    def __init__(self, rows, rows_start, cols, cols_start):
        self.rows, self.rows_start, self.cols, self.cols_start = rows, rows_start, cols, cols_start

class Region:
    def __init__(self, top=0, right=0, bottom=0, left=0):
        self.top, self.right, self.bottom, self.left = top, right, bottom, left

    def __repr__(self):
        return '{' \
               + 't: {0}, r: {1}, b: {2}, l: {3}'.format(self.top, self.right, self.bottom, self.left) \
               + '}'

class ProcSquare:
    def __init__(self, full_region, region, left_top, step_x, step_y):
        self.full_region, self.region, self.left_top, self.step_x, self.step_y = full_region, region, left_top, step_x, step_y
        self.rows = region.bottom - region.top
        self.cols = region.right - region.left
        self.calc_region = Region(
            top=int(region.top == full_region.top),
            left=int(region.left == full_region.left),
            right=self.cols - int(region.right == full_region.right),
            bottom=self.rows - int(region.bottom == full_region.bottom)
        )
        self.diff = 0.0

        if self.rows > 0 and self.cols > 0:
            self.top_border = np.zeros(self.cols, dtype=np.float64)
            self.left_border = np.zeros(self.rows, dtype=np.float64)
            self.bottom_border = np.zeros(self.cols, dtype=np.float64)
            self.right_border = np.zeros(self.rows, dtype=np.float64)

            self.sqr_step_x = self.step_x * self.step_x
            self.sqr_step_y = self.step_y * self.step_y
            self.weight = 1. / (2 * (1. / self.sqr_step_x + 1. / self.sqr_step_y))

            if self.region.top == self.full_region.top:
                for j in range(self.cols):
                    self.set(0, j, Task.f_top(left_top.x + step_x * j))
            else:
                self.neighbor_top_border = np.zeros(self.cols, dtype=np.float64)

            if region.bottom == full_region.bottom:
                for j in range(self.cols):
                    self.set(self.rows - 1, j, Task.f_bottom(left_top.x + step_x * j))
            else:
                self.neighbor_bottom_border = np.zeros(self.cols, dtype=np.float64)

            if region.left == full_region.left:
                for i in range(self.rows):
                    self.set(i, 0, Task.f_left(left_top.y + step_y * i))
            else:
                self.neighbor_left_border = np.zeros(self.rows, dtype=np.float64)

            if region.right == full_region.right:
                for i in range(self.rows):
                    self.set(i, self.cols - 1, Task.f_right(left_top.y + step_y * i))
            else:
                self.neighbor_right_border = np.zeros(self.rows, dtype=np.float64)

        if self.rows > 2 and self.cols > 2:
            self.inner_lines = []
            for i in range(self.rows - 2):
                self.inner_lines.append(np.zeros(self.cols - 2, dtype=np.float64))

    def get(self, i, j):
        if j == -1:
            return self.neighbor_left_border[i]
        elif j == self.cols:
            return self.neighbor_right_border[i]
        elif i == -1:
            return self.neighbor_top_border[j]
        elif i == self.rows:
            return self.neighbor_bottom_border[j]
        elif j == 0:
            return self.left_border[i]
        elif j == self.cols - 1:
            return self.right_border[i]
        elif i == 0:
            return self.top_border[j]
        elif i == self.rows - 1:
            return self.bottom_border[j]
        else:
            return self.inner_lines[i - 1][j - 1]

    def set(self, i, j, val):
        if j == -1:
            self.neighbor_left_border[i] = val
        elif j == self.cols:
            self.neighbor_right_border[i] = val
        elif i == -1:
            self.neighbor_top_border[j] = val
        elif i == self.rows:
            self.neighbor_bottom_border[j] = val
        else:
            if j == 0:
                self.left_border[i] = val

            if j == self.cols - 1:
                self.right_border[i] = val

            if i == 0:
                self.top_border[j] = val

            if i == self.rows - 1:
                self.bottom_border[j] = val

            if (0 < i < self.rows - 1) and (0 < j < self.cols - 1):
                self.inner_lines[i - 1][j - 1] = val

    def exch(self, comm):
        left, right = comm.Shift(1, 1)
        top, bottom = comm.Shift(0, 1)

        if top != MPI.PROC_NULL:
            comm.send(self.top_border, dest=top)

        if bottom != MPI.PROC_NULL:
            self.neighbor_bottom_border = comm.recv(source=bottom)

        if bottom != MPI.PROC_NULL:
            comm.send(self.bottom_border, dest=bottom)

        if top != MPI.PROC_NULL:
            self.neighbor_top_border = comm.recv(source=top)

        if right != MPI.PROC_NULL:
            comm.send(self.right_border, dest=right)

        if left != MPI.PROC_NULL:
            self.neighbor_left_border = comm.recv(source=left)

        if left != MPI.PROC_NULL:
            comm.send(self.left_border, dest=left)

        if right != MPI.PROC_NULL:
            self.neighbor_right_border = comm.recv(source=right)

        comm.barrier()

    def calc(self):
        self.diff = 0.0

        for i in range(self.calc_region.top, self.calc_region.bottom):
            for j in range(self.calc_region.left, self.calc_region.right):
                x = self.left_top.x + j * self.step_x
                y = self.left_top.y + i * self.step_y
                val = self.weight * (
                    (self.get(i + 1, j) + self.get(i - 1, j)) / self.sqr_step_x +
                    (self.get(i, j + 1) + self.get(i, j - 1)) / self.sqr_step_y -
                    Task.f(x, y)
                )
                self.diff = max(self.diff, abs(self.get(i, j) - val))
                self.set(i, j, val=val)

    def data(self):
        temp = np.zeros(self.cols * self.rows, dtype=np.float64)

        for i in range(self.rows):
            for j in range(self.cols):
                temp[i * self.cols + j] = self.get(i, j)

        return temp


from tensorflow.keras.layers import Flatten, Dense
from tensorflow.keras.applications import ResNet50V2 as pre_trained_model
import tensorflow as tf

def build_imagenet_model(freeze):
    imagenet = pre_trained_model(weights='imagenet', include_top=False, input_shape=(224,224,3))
    if freeze:
        imagenet.trainable = False
        # for layer in imagenet.layers:
        #     layer.trainable = False
    x = imagenet.output
    x = Flatten()(x)
    imagenet_model = tf.keras.Model(inputs=imagenet.inputs, outputs=x)
    return imagenet_model


from django.contrib import admin
from jobs.models import Job

class JobAdmin(admin.ModelAdmin):
	ordering = ['created']
	list_display = ['title', 'organisation', 'location', 'experience', 'employment_type', 'salary', 'approved',]
	list_filter = ['approved','source','created']

admin.site.register(Job, JobAdmin)


"""crm1 URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, include
from accounts import views as auth_views
from users import views as user_views
from django.contrib.auth.views import LoginView, LogoutView
from django.conf.urls.static import static
from django.conf import settings

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', auth_views.home, name='dashboards'),
    path('product/', auth_views.product, name='products'),
    path('customer/<int:pk>/', auth_views.customer, name='customers'),
    path('create_order/<int:pk>/', auth_views.createOrder, name='create-order'),
    path('update_order/<int:pk>/', auth_views.updateOrder, name='order-update'),
    path('update_form/<int:pk>/', auth_views.updateCustomer, name='update-customer'),
    path('delete_order/<int:pk>/', auth_views.deleteOrder, name='delete'),
    path('create_customer/', auth_views.createCustomer, name='create-customer'),
    path('users/register/', user_views.register, name='user-registration'),
    path('users/login/', LoginView.as_view(template_name='users/login.html'), name='user-login'),
    path('users/logout/', LogoutView.as_view(template_name='users/logout.html'), name='user-logout'),
    path('user/', auth_views.userPage, name='user-page'),
    path('user_account/', user_views.user_account, name='user-account')
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)


import cv2
import numpy as np

#burada gruplandırm, bölgeye göre eşik değeri ayarlanabiliyor
image= cv2.imread("101/ders15/color.jpg",0) #gri tonlamalı olmalı

ret,thresh = cv2.threshold(image,160,255,cv2.THRESH_BINARY) #simple thresholding

thresh2 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY,23,2) #piksel sınırları
t#karmaşık görsellerde belirli bir bölge için istediğimiz gibi thresh uygulaması yaparız.
thresh3 = cv2.adaptiveThreshold(image,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C,cv2.THRESH_BINARY,23,2)

cv2.imshow("thresh",thresh)
cv2.imshow("thresh2",thresh2)
cv2.imshow("thresh3",thresh3)

cv2.waitKey(0)
cv2.destroyAllWindows()
cv2.waitKey(1)


"""
Скрипт предназначен для получения локального ip-адреса с помощью стандартных средств
операционной системы, в зависимости от того, какая операционная система запущена
в данный момент. Работает на Linux и Windows. Выполняется парсинг вывода стандартных команд.
Данный код требует более детальной проверки на различных дистрибутивах ОС Linux, так как
вывод команды может немного отличатся. Проверен на: Kali, Ubuntu, Mint.
Для Windows, также требуется проверка на версиях ОС младше и старше 10 версии. В данный
момент протестирован на Windows 10 Pro.

Установки дополнительных библиотек для работы не требует.
"""
from platform import system
from subprocess import check_output

def local_ipv4() -> (str, None):
    """
    Выполняется определение ОС. В зависимости от этого выполняется
    команда с помощью subprocess.check_output для получения локального
    ip-адреса. Парситься и возвращается вывод команд. Если в процессе
    выполнения команды поднимается исключение, возвращается None.
    :return: строковый параметр - локальный ip-адрес или None.
    """
    if system() == "Linux":
        try:
            return check_output('ip -h -br a | grep UP', shell=True).decode().split()[2].split("/")[0]
        except Exception:
            return

    elif system() == "Windows":
        try:
            net_set = check_output("wmic nicconfig get IPAddress, IPEnabled /value"). decode("cp866").strip().\
                split("\r\r\n")

            text = ""
            for net in net_set:
                if net.strip() == "":
                    text = f"{text}|"
                else:
                    text = f"{text}~{net.strip()}"
            text = text.strip().split("||")
            for tx in text:
                if tx.split("~")[-1].split("=")[1] != "TRUE":
                    continue
                for item in tx.split("~"):
                    if item.strip() == "":
                        continue
                    if item.strip().split("=")[0] == "IPEnabled":
                        continue
                    if item.strip().split("=")[1] != "":
                        if item.strip().split("=")[0] == "IPAddress":
                            return item.strip().split("=")[1].split(",")[0].replace('"', '').replace("{", "")
        except Exception:
            return


import os

def extract_files(dir):
    return [el for el in dir_content if os.path.isfile(el)]

def get_report_for_files_extensions(files):
    report = {}
    for file in files:
        file_name, extension = file.split(".")
        if file_name not in report:
            report[extension] = []
        report[extension].append(file_name)
    return report

dir_content = os.listdir()

files = extract_files(dir_content)
report = get_report_for_files_extensions(files)

result_string = ""

for extension, file_names in sorted(report.items(), key=lambda x: x[0]):
    result_string += f".{extension}\n"
    result_string += f"- - - {''.join(file_names)}.{extension}\n"

with open("C:\\Users\\User\\Desktop\\result.txt", "w") as file:
    file.write(result_string)


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

from builtins import super

import requests
import sys

from requests.exceptions import HTTPError
from requests.adapters import HTTPAdapter
from requests.packages.urllib3.util.retry import Retry

DEFAULT_TIMEOUT = 295  # seconds
TOTAL_RETRIES = 5
DEBUG_FLAG = False

def exception_handler(exception_type, exception, traceback, debug_hook=sys.excepthook):
    if DEBUG_FLAG:
        debug_hook(exception_type, exception, traceback)
    else:
        print("%s: %s" % (exception_type.__name__, exception))

sys.excepthook = exception_handler

class TimeoutHTTPAdapter(HTTPAdapter):
    def __init__(self, *args, **kwargs):
        self.timeout = DEFAULT_TIMEOUT
        if "timeout" in kwargs:
            self.timeout = kwargs["timeout"]
            del kwargs["timeout"]
        super().__init__(*args, **kwargs)

    def send(self, request, **kwargs):
        timeout = kwargs.get("timeout")
        if timeout is None:
            kwargs["timeout"] = self.timeout
        return super().send(request, **kwargs)

retry_strategy = Retry(total=TOTAL_RETRIES,
                       backoff_factor=2,
                       status_forcelist=[429, 500, 502, 503, 504],
                       method_whitelist=["GET", "POST"])
adapter = TimeoutHTTPAdapter(max_retries=retry_strategy)

def expanded_raise_for_status(res):
    """
    Take a "requests" response object and expand the raise_for_status method to return more helpful errors
    :param res:
    :return: None
    """
    try:
        res.raise_for_status()
    except HTTPError as e:
        try:
            raise HTTPError('{}\nReason: {}'.format(str(e), res.json()['message']))
        except ValueError:
            raise e
    return

def resilient_requests(func, *args, **kwargs):
    with requests.Session() as session:
        session.mount("https://", adapter)
        response = getattr(session, func)(*args, **kwargs)
        expanded_raise_for_status(response)
    return response


from unittest import mock

import pytest

from iolib.utils import build_google_api, to_snakecase, normalize_key

@mock.patch('iolib.utils.Credentials')
@mock.patch('iolib.utils.build')
def test_build_google_api(m_build, m_credentials):
    name = '<name>'
    version = '<version>'
    scopes = '<scopes>'
    service_account_json = '<service_account_json>'
    actual = build_google_api(name, version, scopes, service_account_json)
    expected = m_build.return_value
    assert expected == actual
    credentials = m_credentials.from_service_account_file.return_value
    m_credentials.from_service_account_file.assert_called_once_with(
        service_account_json,
        scopes=scopes)
    m_build.assert_called_once_with(name, version, credentials=credentials)

@mock.patch('iolib.utils.Credentials')
@mock.patch('iolib.utils.build')
@mock.patch('iolib.utils.os')
def test_build_google_api_with_credentials_from_env(m_os, m_build, m_credentials):
    name = '<name>'
    version = '<version>'
    scopes = '<scopes>'
    service_account_json = '<service_account_json>'
    m_os.environ = {'GOOGLE_APPLICATION_CREDENTIALS': service_account_json}
    actual = build_google_api(name, version, scopes)
    expected = m_build.return_value
    assert expected == actual
    credentials = m_credentials.from_service_account_file.return_value
    m_credentials.from_service_account_file.assert_called_once_with(
        service_account_json,
        scopes=scopes)
    m_build.assert_called_once_with(name, version, credentials=credentials)

@pytest.mark.parametrize(('value', 'expected'), (
    ('to_csv', 'to_csv'),
    ('user name', 'user_name'),
    ('Email Address', 'email_address'),
    ('phoneNumber', 'phone_number'),
    ('toHTML', 'to_html'),
    ('365days', '365_days'),
    ('52Weeks', '52_weeks'),
))
def test_to_snakecase(value, expected):
    actual = to_snakecase(value)
    assert expected == actual

@pytest.mark.parametrize(('value', 'expected'), (
    ('name', 'name'),
    ('user_name', 'user'),
))
def test_normalize_key(value, expected):
    with mock.patch('iolib.utils.to_snakecase', side_effect=lambda x: x) as m_to_snakecase:
        actual = normalize_key(value)
    assert expected == actual
    m_to_snakecase.assert_called_once_with(value)


import uuid

from api import occi_ext
from occi import backend

class AppBackend(backend.KindBackend, backend.ActionBackend):
    """
    Handle PaaS based Applications.
    """

    def __init__(self, paas_adapter):
        self.glue = paas_adapter

    def create(self, entity, extras):
        if 'occi.app.name' not in entity.attributes:
            raise AttributeError('occi.app.name is a required attribute')

        app_temp = None
        res_temp = None
        for mixin in entity.mixins:
            if isinstance(mixin, occi_ext.AppTemplate):
                app_temp = mixin
            if isinstance(mixin, occi_ext.ResTemplate):
                res_temp = mixin

        scaling = {'scale': 'False'}
        if 'occi.app.scale' in entity.attributes:
            scaling['scale'] = entity.attributes['occi.app.scale']
            if 'occi.app.scales_from' in entity.attributes:
                scaling['scales_from'] = entity.attributes['occi.app.scales_from']
            if 'occi.app.scales_to' in entity.attributes:
                scaling['scales_to'] = entity.attributes['occi.app.scales_to']

        name = entity.attributes['occi.app.name']
        # OpS2 Specific: no problem if there is no mixin in OpS3 when directly deploying docker containers
        if self.glue.PLATFORM == 'OpenShift2':
            if not app_temp or not res_temp:
                raise AttributeError('Please provide a valid App and '
                                     'Resource Template.')

            tmp = self.glue.create_app(name, app_temp.term, res_temp.term, extras['auth_header'], **scaling)
        elif self.glue.PLATFORM == 'OpenShift3':
            # no need for extra info besides docker image
            docker_image = env_vars = None
            if 'occi.app.image' in entity.attributes:
                docker_image = entity.attributes['occi.app.image']
            if 'occi.app.env' in entity.attributes:
                env_vars = entity.attributes['occi.app.env']
            if not docker_image:
                raise AttributeError('Please provide a valid docker image name.')
            if len(name) > 24:
                raise AttributeError('occi.app.name must not be greater than 24 characters')

            tmp = self.glue.create_app(name, docker_image, extras['auth_header'], env=env_vars)
            scale = tmp['data']['scalable']
            entity.attributes['occi.app.scale'] = scale
        else:
            # raise AttributeError('Invalid GLUE chosen in CC API.')
            # TODO: For testing purposes, better to not raise that and instead have the default OpS behaviour
            if not app_temp or not res_temp:
                raise AttributeError('Please provide a valid App and '
                                     'Resource Template.')

            tmp = self.glue.create_app(name, app_temp.term, res_temp.term, extras['auth_header'], **scaling)
        uid = tmp['data']['id']
        entity.attributes['occi.core.id'] = uid
        entity.identifier = '/app/' + uid

    def retrieve(self, entity, extras):
        uid = entity.attributes['occi.core.id']
        tmp, tmp2 = self.glue.retrieve_app(uid, extras['auth_header'])

        # update attributes
        # next two are generic
        entity.attributes['occi.app.url'] = tmp['data']['app_url']
        entity.attributes['occi.app.name'] = tmp['data']['name']
        if 'git_url' in tmp['data']:  # Indicates OpS2 at the moment
            entity.attributes['occi.app.repo'] = tmp['data']['git_url']
            state = tmp2['data'][0]['gears'][0]['state']
            if state in ['started']:
                entity.attributes['occi.app.state'] = 'active'
                entity.actions = [occi_ext.APP_STOP]
            else:
                entity.attributes['occi.app.state'] = 'inactive'
                entity.actions = [occi_ext.APP_START]
            # update scaling status - only exists in OpS2 as OpS3 only indicates current replicas for each pod
            entity.attributes['occi.app.scale'] = tmp['data']['scalable']
            entity.attributes['occi.app.scales_from'] = tmp2['data'][0]['scales_from']
            entity.attributes['occi.app.scales_to'] = tmp2['data'][0]['scales_to']
        else:  # Indicates OpS3 - Better would be a version indicator somewhere
            if tmp['data']['state']:
                entity.attributes['occi.app.state'] = 'active'
            else:
                entity.attributes['occi.app.state'] = 'inactive'
                # no actions configured at the moment on the service

    def delete(self, entity, extras):
        uid = entity.attributes['occi.core.id']
        self.glue.delete_app(uid, extras['auth_header'])

    def action(self, entity, action, attributes, extras):
        uid = entity.attributes['occi.core.id']
        if action not in entity.actions:
            raise AttributeError('This action is currently not applicable.')
        elif action == occi_ext.APP_START:
            self.glue.start_app(uid, extras['auth_header'])
        elif action == occi_ext.APP_STOP:
            self.glue.stop_app(uid, extras['auth_header'])
        entity.actions = []

class ServiceLink(backend.KindBackend):
    """
    Backend for the service links.
    """

    def __init__(self, paas_adapter):
        self.glue = paas_adapter

    def create(self, entity, extras):
        iden = entity.source.identifier.split('/')[-1:][0]
        name = entity.target.identifier.split('/')[-1:][0]
        self.glue.add_service(iden, name, extras['auth_header'])

    def delete(self, entity, extras):
        iden = entity.source.identifier.split('/')[-1:][0]
        name = entity.target.identifier.split('/')[-1:][0]
        self.glue.delete_service(iden, name, extras['auth_header'])

class SshKeyBackend(backend.KindBackend):
    """
    Backend handling ssh keys.
    """

    def __init__(self, paas_adapter):
        self.glue = paas_adapter

    def create(self, entity, extras):
        if 'occi.key.name' not in entity.attributes:
            name = 'key_' + str(uuid.uuid4())
        else:
            name = entity.attributes['occi.key.name']
        if 'occi.key.content' not in entity.attributes:
            raise AttributeError('Key value is required.')
        content = entity.attributes['occi.key.content']
        entity.attributes['occi.core.id'] = name
        self.glue.add_key(name, content, extras['auth_header'])

    def delete(self, entity, extras):
        uid = entity.attributes['occi.core.id']
        self.glue.delete_key(uid, extras['auth_header'])


import pytest

URL = "https://casinoextreme.eu/games"
RUN_CSS = "a.playgame-demo[onclick^='playGame']"
IFRAME_CSS = "#gameplay > iframe"
GOOD_MSG = "GameViewModel"
BAD_MSG = "UnsupportedDevice"

async def check_for_message(client, message):
    await client.navigate(URL)
    client.soft_click(client.await_css(RUN_CSS))
    client.switch_to_frame(client.await_css(IFRAME_CSS))
    await (await client.promise_console_message_listener(message))

@pytest.mark.only_platforms("android")
@pytest.mark.asyncio
@pytest.mark.with_interventions
async def test_enabled(client):
    await check_for_message(client, GOOD_MSG)

@pytest.mark.only_platforms("android")
@pytest.mark.asyncio
@pytest.mark.without_interventions
async def test_disabled(client):
    await check_for_message(client, BAD_MSG)