import sys
from collections import deque
import unittest

class Solution:
    def minCost(self, knownWizards):
        # 10 wizards
        # find the min cost between 0 and 9
        minCost = [sys.maxsize for _ in range(10)]
        minCost[0] = 0

        queue = deque()
        queue.append(0)
        while queue:
            curr = queue.popleft()

            for knownW in knownWizards[curr]:
                cost = minCost[curr] + self.wizardCost(curr, knownW)
                if cost < minCost[knownW]:
                    minCost[knownW] = cost
                    queue.append(knownW)

        return minCost[9]

    def wizardCost(self, i, j):
        return (i - j) ** 2

class SolutionTest(unittest.TestCase):
    sol = Solution()

    def testMinCost(self):
        test = [[] for _ in range(10)]
        test[0] = [1, 4, 5]
        test[4] = [9]
        self.assertEqual(41, self.sol.minCost(test))

if __name__=='__main__':
    unittest.main()


from core.module import Module
from core.prompt_listener import PromptListener
from message_client import MessageClient
import json

class GmcpModule(Module, PromptListener):

    client_data = {
        "Client": "TinyFugue",
        "Version": "6"
        }

    support_data = [
            "Core 1",
            "Char 1",
            "Room 1",
            "Comm.Channel 1",
            "Char.Afflictions 1",
            "Char.Defences 1",
            "IRE.Composer 1",
            ]

    def __init__(self, *args):
        super(GmcpModule, self).__init__(*args)

        self.prompt_count = 0
        self.gmcp_count = 0
        self.message_client = MessageClient("localhost", 12000)

        self.mud.eval("/def -h'CONNECT aetolia' = /python_call main.cb register_gmcp")
        self.mud.eval("/def -waetolia -hGMCP = /python_call main.cb handle_gmcp \%*")
        self.state["callback_handler"].registerCallback(self.handle_gmcp)
        self.state["callback_handler"].registerCallback(self.register_gmcp)

        self.state["alias_builder"].build({
            "gmcp_dump": self.dump_gmcp
            })

    def parse_prompt(self, line):
        if self.gmcp_count:
            return
        self.prompt_count += 1
        if (self.prompt_count % 3) == 0:
            self.mud.warn("Received %d prompts and no GMCP" % self.prompt_count)
            self.register_gmcp()

    def register_gmcp(self):
        self.mud.info("Registering for GMCP")
        self.mud.gmcp("Core.Hello", self.client_data)
        self.mud.gmcp("Core.Supports.Set", self.support_data)

    def handle_gmcp(self, *payloads):
        payload = " ".join(payloads)
        self.gmcp_count += 1
        lines = payload.split(" ", 1)
        key = lines[0]
        package = lines[1]
        data = json.loads(package)
        self.state["callback_handler"].triggerGmcpCallback(key, data)
        if key == "Comm.Channel.Text":
            self.message_client.send(data["text"])
        else:
            self.state["gmcp"][key] = data

    def dump_gmcp(self):
        self.mud.info("Dumping GMCP to gmcp_dump.json")
        with open("gmcp_dump.json", "w") as f:
            f.write(json.dumps(self.state["gmcp"], indent=4, sort_keys=True, separators=(",",": ")))


import os

from google_cloud_pipeline_components.aiplatform import (
    AutoMLTabularTrainingJobRunOp,
    EndpointCreateOp,
    ModelDeployOp,
    TabularDatasetCreateOp,
)
from kfp.v2 import dsl

PIPELINE_ROOT = os.getenv("PIPELINE_ROOT")
PROJECT = os.getenv("PROJECT")
DATASET_SOURCE = os.getenv("DATASET_SOURCE")
PIPELINE_NAME = os.getenv("PIPELINE_NAME", "covertype")
DISPLAY_NAME = os.getenv("MODEL_DISPLAY_NAME", PIPELINE_NAME)
TARGET_COLUMN = os.getenv("TARGET_COLUMN", "Cover_Type")
SERVING_MACHINE_TYPE = os.getenv("SERVING_MACHINE_TYPE", "n1-standard-16")

@dsl.pipeline(
    name=f"{PIPELINE_NAME}-vertex-automl-pipeline",
    description=f"AutoML Vertex Pipeline for {PIPELINE_NAME}",
    pipeline_root=PIPELINE_ROOT,
)
def create_pipeline():

    dataset_create_task = TabularDatasetCreateOp(
        display_name=DISPLAY_NAME,
        bq_source=DATASET_SOURCE,
        project=PROJECT,
    )

    automl_training_task = AutoMLTabularTrainingJobRunOp(
        project=PROJECT,
        display_name=DISPLAY_NAME,
        optimization_prediction_type="classification",
        dataset=dataset_create_task.outputs["dataset"],
        target_column=TARGET_COLUMN,
    )

    endpoint_create_task = EndpointCreateOp(
        project=PROJECT,
        display_name=DISPLAY_NAME,
    )

    model_deploy_task = ModelDeployOp(  # pylint: disable=unused-variable
        model=automl_training_task.outputs["model"],
        endpoint=endpoint_create_task.outputs["endpoint"],
        deployed_model_display_name=DISPLAY_NAME,
        dedicated_resources_machine_type=SERVING_MACHINE_TYPE,
        dedicated_resources_min_replica_count=1,
        dedicated_resources_max_replica_count=1,
    )


from model import *

from data import *

data_gen_args = dict(rotation_range=0.2,
                    width_shift_range=0.05,
                    height_shift_range=0.05,
                    shear_range=0.05,
                    zoom_range=0.05,
                    horizontal_flip=True,
                    fill_mode='nearest')

myGene = trainGenerator(2, 'myData/Original/Train', 'Frames', 'Masks', data_gen_args, save_to_dir = None)
model = unet()
model_checkpoint = ModelCheckpoint('unetOriginal.hdf5', monitor='loss', verbose=1, save_best_only=True)

model.fit_generator(myGene, steps_per_epoch=300, epochs=5, callbacks=[model_checkpoint])

testGene = testGenerator("MyData/Original/Test/Frames")
results = model.predict_generator(testGene, 30, verbose=1)
r = results*255
saveResult("MyData/Original/Test/label", r.astype('uint8'))


import fileinput
p = None # previous value is None
c = 0  #intilaize count is zero
m = (0, 0) #the maximum value the previous and sender is intilaize zero

for l in fileinput.input():
    # to remove leading and trailing whitespace
    l = l.strip()
    # splitting the data on the basis of tab we have provided in mapper.py
    w, r = l.split(' ') #sender and reciever split the line with comma
    if p == None: #previous is none
        p = w #previous is equal to sender
        c = c+1 # add to the c value
    else:
        if w != p: #if sender not equal to the previous
            if c > m[1]: #if c grater than of the maximun of 1
                m = (p, c) #maximum equals to the previous ,count value
            c = 1 #if count value is 1
            p = w # previous value is sender
        else:
            c = c+1 #add to the count value to one
            p = w # previous value is sender

print(m[0], m[1]) # print maximum value


def nameRank(names,marks,updates):
    for i in range(len(names)):
        marks[i]=marks[i]+updates[i]

    max_student=""
    max_marks=0

    for i in range(len(names)):
        if marks[i]>max_marks:
            max_student=names[i]
            max_marks=marks[i]

    pr=0
    previous_ranks=[]
    for x in range(len(names)):
        pr=x+1
        previous_ranks.append(pr)

    previous_rank=0
    for i in range(len(names)):
        if names[i]==max_student:
            previous_rank=previous_ranks[i]

    current_rank=0
    for i in range(len(marks)):
        if marks[i] == max_marks:
            current_rank+=1

    rankjump=previous_rank-current_rank

    print(f'The student with maximum marks after updation is: {max_student}')
    print('-------')
    print(f'Rank of {max_student} before marks updation is: {previous_rank}')
    print('-------')
    print(f'Rank of {max_student} after marks updation is: {current_rank}')
    print('-------')
    print(f'Jump in rank of {max_student} is: {rankjump}')
    print()

names=['Manish','Kamlesh','Riya','Megha']
marks=[90,86,80,77]
updates=[-7,3,12,8]

nameRank(names,marks,updates)


import angr
import nose

def test_file_unlink():
    # Initialize a blank state with an arbitrary errno location
    state = angr.SimState(arch="AMD64", mode="symbolic")
    state.libc.errno_location = 0xa0000000
    state.libc.errno = 0

    # Create a file 'test'
    fd = state.posix.open(b'test', 1)
    state.posix.close(fd)

    # Ensure 'test' was in fact created
    nose.tools.assert_in(b'/test', state.fs._files)

    # Store the filename in memory
    path_addr = 0xb0000000
    state.memory.store(path_addr, b'test\x00')

    # Unlink 'test': should return 0 and leave ERRNO unchanged
    unlink = angr.SIM_PROCEDURES['posix']['unlink']()
    state.scratch.sim_procedure = unlink
    rval = unlink.execute(state, arguments=[path_addr]).ret_expr
    nose.tools.assert_equal(rval, 0)
    nose.tools.assert_equal(state.solver.eval(state.libc.errno), 0)

    # Check that 'test' was in fact deleted
    nose.tools.assert_equal(state.fs._files, {})

    # Unlink again: should return -1 and set ERRNO to ENOENT
    unlink = angr.SIM_PROCEDURES['posix']['unlink']()
    state.scratch.sim_procedure = unlink
    rval = unlink.execute(state, arguments=[path_addr]).ret_expr
    nose.tools.assert_equal(rval, -1)
    nose.tools.assert_equal(state.solver.eval(state.libc.errno), state.posix.ENOENT)


from PIL import Image
import numpy as np
import math
import glob
import pickle as pk

WIDTH = 19
HEIGHT = 19
file_to_integral = {}
'''Region of an image with (x, y) as top left corner
'''

class Region:

    def __init__(self, x, y, w, h):
        self.x = x
        self.y = y
        self.w = w
        self.h = h

    # Returns sum of pixel within this region based on the given integral image
    def get_sum(self, integral_image):
        return integral_image[self.x + self.w][self.y + self.h] + \
               integral_image[self.x][self.y] \
               - integral_image[self.x + self.w][self.y] - \
               integral_image[self.x][self.y + self.h]

''' A WeakLearner represents a weak classifier
'''

class WeakLearner:

    def __init__(self, feature):
        self.feature = feature              # feature
        self.thresh = 0.0                     # threshold
        self.p = 0.0                          # polarity
        self.alpha = 0.0                      # alpha
        self.e = 0.0                          # error

    # Classifies the data and returns the predicted results
    # If positive, return 1 and 0 otherwise
    #   x - data
    def classify(self, x):
        im = Image.open(x)
        np_im = np.asarray(im)
        integral_image = make_integral(np_im)
        feature_value = self.feature.apply_feature(integral_image)
        predicted_y = 0
        if self.p == 1:
            if feature_value > self.thresh:
                predicted_y = 1
        else:
            if feature_value < self.thresh:
                predicted_y = 1
        return predicted_y

''' A Feature represents a Haar-like feature
    It contains rectangles that adds to the feature value
    and rectangles that are negative and lower the feature value
'''

class Feature:

    def __init__(self, pos_rect, neg_rect):
        self.pos_rect = pos_rect                # list of rectangles that are added to sum
        self.neg_rect = neg_rect                # list of rectangles that are subtracted from sum
        self.feature_values = {}                # map of feature values

    # Applies the feature to the given integral image
    # Returns the feature value
    def apply_feature(self, integral_image):
        feature_sum = 0.0
        for region in self.pos_rect:
            feature_sum += region.get_sum(integral_image)
        for region in self.neg_rect:
            feature_sum -= region.get_sum(integral_image)
        return feature_sum

# Loads file with given name
def load_model(model):
    with open(model, "rb") as f:
        return pk.load(f)

def populate_integral_image():
    for currentFile in glob.glob("./faces/train/face/*.pgm"):
        im = Image.open(currentFile)
        np_im = np.asarray(im)
        integral_image = make_integral(np_im)
        file_to_integral[currentFile] = integral_image
    for currentFile in glob.glob("./faces/train/non-face/*.pgm"):
        im = Image.open(currentFile)
        np_im = np.asarray(im)
        integral_image = make_integral(np_im)
        file_to_integral[currentFile] = integral_image

# Makes the feature matrix where each row is one feature and each column is a feature value
# for a sample data
# Returns a tuple (feature matrix, sample y)
#   features - list of features
#   data - sample data
def make_feature_m(features, data):

    # Create matrix where each row is a feature and each column is the feature value
    feature_values = np.zeros((len(features), len(data)))

    # Array that saves expected values for each sample data
    sample_y = []
    for i in range(len(data)):
        sample_y.append(data[i][1])

    i = 0
    for feature in features:
        j = 0
        for (x, y) in data:
            feature_values[i][j] = feature.apply_feature(file_to_integral[x])
            j += 1
        i += 1
    return feature_values, sample_y

# Normalizes the given list of sample weights
#   sample_w - list of sample weights
def normalize(sample_w):
    tot = sum(sample_w)
    for i in range(len(sample_w)):
        sample_w[i] = sample_w[i] / tot

# Calculates and returns a tuple of (detection rate, false positive rate) on the given
# data set
#   pos_data - data that should return 1
#   neg_data - data that should return 0
#   detector - detector to test data on
def validate(pos_data, neg_data, detector):
    detect_count = 0.0
    for (x, y) in pos_data:
        res = detector.classify(x)
        if res == 1:
            detect_count += 1

    error_count = 0.0
    for (x, y) in neg_data:
        res = detector.classify(x)
        if res == 1:
            error_count += 1

    return detect_count / len(pos_data), error_count / len(neg_data)

# Initializes the sorted feature to feature values mapping for each feature
#   feature - list of features
#   m - matrix where number of rows is number of features and number of columns
#       is number of sample data
def get_feature_values(features, m):
    for i in range(m.shape[0]):
        for j in range(m.shape[1]):
            temp = m[i][j]
            features[i].feature_values[j] = temp
        sorted(features[i].feature_values.items(), key=lambda kv: kv[1])

# Looks for optimal threshold and polarity
# Optimal is the minimum sum of the errors of the sample weights
#   feature - the feature to be optimized
#   sample_w - the sample weights after applying the
#               feature
#   sample_y - list of sample y-values
def make_model(feature, sample_w, sample_y):
    ret = WeakLearner(feature)
    tot_pos = 0.0
    tot_neg = 0.0
    for i in range(len(sample_w)):
        if sample_y[i] == 1:
            tot_pos += sample_w[i]
        else:
            tot_neg += sample_w[i]

    print("Total Positive: " + str(tot_pos))
    print("Total negative: " + str(tot_neg))
    min_error = tot_pos + tot_neg
    min_sample = None
    curr_pos = 0.0
    curr_neg = 0.0
    p = 0
    for i in feature.feature_values:
        if sample_y[i] == 1:
            curr_pos += sample_w[i]
        else:
            curr_neg += sample_w[i]
            err_1 = curr_neg + (tot_pos - curr_pos)
            err_2 = curr_pos + (tot_neg - curr_neg)
            error = min(err_1, err_2)
            if error < min_error:
                min_error = error
                min_sample = i
                if error == err_1:
                    p = 1
                else:
                    p = 0
    ret.thresh = feature.feature_values[min_sample]
    ret.p = p
    print("Min error value: " + str(min_error))
    beta = min_error / (1 - min_error)
    if beta == 0:
        beta = math.pow(1, -10)
    ret.alpha = math.log2(1.0 / beta)
    ret.e = min_error
    return ret

# Adjusts the sample weights
#   feature - the feature that has been applied
#   sample_w - the sample weights
#   data - images
def adjust_weights(model, sample_w, data):
    for i in range(len(sample_w)):
        predicted_y = model.classify(data[i][0])
        sample_res = 1
        if predicted_y == data[i][1]:
            sample_res = 0
        sample_w[i] = sample_w[i] * math.pow((model.e / (1.0 - model.e)), 1.0 - sample_res)

# Initializes and returns a map of sample weight pairs
#   data - tuples of form (x, y) where x is image and y is
#           correct label
def initialize_weights(data):
    tot_pos = 0
    tot_neg = 0
    for (x, y) in data:
        if y == 1:
            tot_pos += 1
        else:
            tot_neg += 1

    w = []
    for (x, y) in data:
        if y == 1:
            w.append(1.0 / (2 * tot_pos))
        else:
            w.append(1.0 / (2 * tot_neg))
    return w

# Makes and returns a list of features
def make_features():
    features = []
    for w in range(1, WIDTH + 1):
        for h in range(1, HEIGHT + 1):
            x = 0
            while x + w < WIDTH:
                y = 0
                while y + h < HEIGHT:
                    rect = Region(x, y, w, h)
                    right_rect = Region(x + w, y, w, h)
                    bottom_rect = Region(x, y + h, w, h)
                    right_edge_rect = Region(x + (2 * w), y, w, h)
                    bottom_right = Region(x + w, y + h, w, h)

                    if x + (2 * w) < WIDTH:
                        # features.append(Feature([rect], [right_rect]))
                        features.append(Feature([right_rect], [rect]))

                    if y + (2 * h) < HEIGHT:
                        features.append(Feature([rect], [bottom_rect]))
                        # features.append(Feature([bottom_rect], [rect]))

                    if x + (3 * w) < WIDTH:
                        features.append(Feature([right_rect], [rect, right_edge_rect]))
                        # features.append(Feature([rect, right_edge_rect], [right_rect]))

                    if x + (2 * w) < WIDTH and y + (2 * h) < HEIGHT:
                        features.append(Feature([rect, bottom_right], [right_rect, bottom_rect]))
                        # features.append(Feature([right_rect, bottom_rect], [rect, bottom_right]))
                    y += 1
                x += 1
    return features

# Makes and return an integral image for the given image
#   im_data - image in the form of a matrix
def make_integral(im_data):
    integral_im = np.zeros(im_data.shape)

    for row in range(im_data.shape[0]):
        for col in range(im_data.shape[1]):
            curr_sum = im_data[row][col]
            if row != 0:
                curr_sum += integral_im[row - 1][col]
            if col != 0:
                curr_sum += integral_im[row][col - 1]
            if row != 0 and col != 0:
                curr_sum -= integral_im[row - 1][col - 1]
            integral_im[row][col] = curr_sum
    return integral_im


## In this script color thresholding takes place, where we want to find how many BLUE balls exist in the picture!

import cv2

# Import and Preview Image with BLUE balls
image = cv2.imread('/Users/konstantinosgyftodimos/Documents/OpenCV_Projects/Images and Figures/threshold_red_ball.png')
print(image)
mean_value = cv2.mean(image)
print(mean_value)

lab_image = cv2.cvtColor(image,cv2.COLOR_BGR2Lab)
lab_value = cv2.mean(lab_image)
print(lab_value)

# Import and Preview Image with ALL balls
image = cv2.imread('/Users/konstantinosgyftodimos/Documents/OpenCV_Projects/Images and Figures/threshold_color_balls.jpg')
cv2.imshow('input image',image)
cv2.waitKey(-1)

# This time we are not removing the color, but we are adding blurr
blurred = cv2.GaussianBlur(image, (15,15), None, )
cv2.imshow('blurred version', blurred)
cv2.waitKey(-1)

# inRange creates a binary image in a range (similar to threshold but in a range)
# Remember we want the blue balls ;)

# blue ball should become white and everything else should become black
binary=cv2.inRange(blurred, (165, 0, 0), (255, 175, 155))
cv2.imshow('output',binary)
cv2.waitKey(-1)

contours, hierarchy = cv2.findContours(binary, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
print('There are:', len(contours), 'Blue Balls in the image')

# Draw Contours, Draw around the Footballs and number them!
cv2.drawContours(image, contours, -1, (0, 255, 0), 2)
cv2.imshow('Draw Contours', image)
cv2.waitKey(-1)


import binascii
import collections
import io
import logging
import os
import struct

from . import usb_exceptions
from openhtf.util import argv

FASTBOOT_DOWNLOAD_CHUNK_SIZE_KB = 1024

ARG_PARSER = argv.module_parser()
ARG_PARSER.add_argument(
    '--fastboot_download_chunk_size_kb',
    default=FASTBOOT_DOWNLOAD_CHUNK_SIZE_KB,
    action=argv.StoreInModule,
    type=int,
    target='%s.FASTBOOT_DOWNLOAD_CHUNK_SIZE_KB' % __name__,
    help='Size of chunks to send when downloading fastboot images')

_LOG = logging.getLogger(__name__)

DEFAULT_MESSAGE_CALLBACK = lambda m: _LOG.info('Got %s from device', m)

class FastbootMessage(
    collections.namedtuple('FastbootMessage', [
        'message',
        'header',
    ])):
  pass

class FastbootProtocol(object):
  """Encapsulates the fastboot protocol."""
  FINAL_HEADERS = {'OKAY', 'DATA'}

  def __init__(self, usb):
    """Constructs a FastbootProtocol instance.

    Arguments:
      usb: UsbHandle instance.
    """
    self.usb = usb

  @property
  def usb_handle(self):
    """This instance's USB handle."""
    return self.usb

  def send_command(self, command, arg=None):
    """Sends a command to the device.

    Args:
      command: The command to send.
      arg: Optional argument to the command.
    """
    if arg is not None:
      command = '%s:%s' % (command, arg)
    self._write(io.StringIO(command), len(command))

  def handle_simple_responses(self,
                              timeout_ms=None,
                              info_cb=DEFAULT_MESSAGE_CALLBACK):
    """Accepts normal responses from the device.

    Args:
      timeout_ms: Timeout in milliseconds to wait for each response.
      info_cb: Optional callback for text sent from the bootloader.

    Returns:
      OKAY packet's message.
    """
    return self._accept_responses('OKAY', info_cb, timeout_ms=timeout_ms)

  # pylint: disable=too-many-arguments
  def handle_data_sending(self,
                          source_file,
                          source_len,
                          info_cb=DEFAULT_MESSAGE_CALLBACK,
                          progress_callback=None,
                          timeout_ms=None):
    """Handles the protocol for sending data to the device.

    Arguments:
      source_file: File-object to read from for the device.
      source_len: Amount of data, in bytes, to send to the device.
      info_cb: Optional callback for text sent from the bootloader.
      progress_callback: Callback that takes the current and the total progress
        of the current file.
      timeout_ms: Timeout in milliseconds to wait for each response.

    Raises:
      FastbootTransferError: When fastboot can't handle this amount of data.
      FastbootStateMismatchError: Fastboot responded with the wrong packet type.
      FastbootRemoteFailureError: Fastboot reported failure.
      FastbootInvalidResponseError: Fastboot responded with an unknown packet
        type.

    Returns:
      OKAY packet's message.
    """
    accepted_size = self._accept_responses(
        'DATA', info_cb, timeout_ms=timeout_ms)

    accepted_size = binascii.unhexlify(accepted_size[:8])
    accepted_size, = struct.unpack('>I', accepted_size)
    if accepted_size != source_len:
      raise usb_exceptions.FastbootTransferError(
          'Device refused to download %s bytes of data (accepts %s bytes)' %
          (source_len, accepted_size))
    self._write(source_file, accepted_size, progress_callback)
    return self._accept_responses('OKAY', info_cb, timeout_ms=timeout_ms)

  # pylint: enable=too-many-arguments

  def _accept_responses(self, expected_header, info_cb, timeout_ms=None):
    """Accepts responses until the expected header or a FAIL.

    Arguments:
      expected_header: OKAY or DATA
      info_cb: Optional callback for text sent from the bootloader.
      timeout_ms: Timeout in milliseconds to wait for each response.

    Raises:
      FastbootStateMismatchError: Fastboot responded with the wrong packet type.
      FastbootRemoteFailureError: Fastboot reported failure.
      FastbootInvalidResponseError: Fastboot responded with an unknown packet
        type.

    Returns:
      OKAY packet's message.
    """
    while True:
      response = self.usb.read(64, timeout_ms=timeout_ms)
      header = response[:4]
      remaining = response[4:]

      if header == 'INFO':
        info_cb(FastbootMessage(remaining, header))
      elif header in self.FINAL_HEADERS:
        if header != expected_header:
          raise usb_exceptions.FastbootStateMismatchError(
              'Expected %s, got %s' % (expected_header, header))
        if header == 'OKAY':
          info_cb(FastbootMessage(remaining, header))
        return remaining
      elif header == 'FAIL':
        info_cb(FastbootMessage(remaining, header))
        raise usb_exceptions.FastbootRemoteFailureError('FAIL: %s' % remaining)
      else:
        raise usb_exceptions.FastbootInvalidResponseError(
            'Got unknown header %s and response %s' % (header, remaining))

  def _handle_progress(self, total, progress_callback):  # pylint: disable=no-self-use
    """Calls the callback with the current progress and total ."""
    current = 0
    while True:
      current += yield
      try:
        progress_callback(current, total)
      except Exception:  # pylint: disable=broad-except
        _LOG.exception('Progress callback raised an exception. %s',
                       progress_callback)
        continue

  def _write(self, data, length, progress_callback=None):
    """Sends the data to the device, tracking progress with the callback."""
    if progress_callback:
      progress = self._handle_progress(length, progress_callback)  # pylint: disable=assignment-from-no-return
      next(progress)
    while length:
      tmp = data.read(FASTBOOT_DOWNLOAD_CHUNK_SIZE_KB * 1024)
      length -= len(tmp)
      self.usb.write(tmp)

      if progress_callback:
        progress.send(len(tmp))

class FastbootCommands(object):
  """Encapsulates the fastboot commands."""
  protocol_handler = FastbootProtocol

  def __init__(self, usb):
    """Constructs a FastbootCommands instance.

    Arguments:
      usb: UsbHandle instance.
    """
    self._usb = usb
    self._protocol = self.protocol_handler(usb)

  @property
  def handle(self):
    """This instance's USB handle."""
    return self._usb

  def close(self):
    """Close the USB handle."""
    self._usb.close()

  def _simple_command(self, command, arg=None, **kwargs):
    """Send a simple command."""
    self._protocol.send_command(command, arg)
    return self._protocol.handle_simple_responses(**kwargs)

  # pylint: disable=too-many-arguments
  def flash_from_file(self,
                      partition,
                      source_file,
                      source_len=0,
                      info_cb=DEFAULT_MESSAGE_CALLBACK,
                      progress_callback=None,
                      timeout_ms=None):
    """Flashes a partition from the file on disk.

    Args:
      partition: Partition name to flash to.
      source_file: Filename to download to the device.
      source_len: Optional length of source_file, uses os.stat if not provided.
      info_cb: See Download.
      progress_callback: See Download.
      timeout_ms: The amount of time to wait on okay after flashing.

    Returns:
      Download and flash responses, normally nothing.
    """
    if source_len == 0:
      # Fall back to stat.
      source_len = os.stat(source_file).st_size
    download_response = self.download(
        source_file,
        source_len=source_len,
        info_cb=info_cb,
        progress_callback=progress_callback)
    flash_response = self.flash(
        partition, info_cb=info_cb, timeout_ms=timeout_ms)
    return download_response + flash_response

  # pylint: enable=too-many-arguments

  def download(self,
               source_file,
               source_len=0,
               info_cb=DEFAULT_MESSAGE_CALLBACK,
               progress_callback=None):
    """Downloads a file to the device.

    Args:
      source_file: A filename or file-like object to download to the device.
      source_len: Optional length of source_file. If source_file is a file-like
        object and source_len is not provided, source_file is read into memory.
      info_cb: Optional callback accepting FastbootMessage for text sent from
        the bootloader.
      progress_callback: Optional callback called with the percent of the
        source_file downloaded. Note, this doesn't include progress of the
        actual flashing.

    Returns:
      Response to a download request, normally nothing.
    """
    if isinstance(source_file, str):
      source_len = os.stat(source_file).st_size
      source_file = open(source_file)

    if source_len == 0:
      # Fall back to storing it all in memory :(
      data = source_file.read()
      source_file = io.StringIO(data)
      source_len = len(data)

    self._protocol.send_command('download', '%08x' % source_len)
    return self._protocol.handle_data_sending(
        source_file, source_len, info_cb, progress_callback=progress_callback)

  def flash(self, partition, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK):
    """Flashes the last downloaded file to the given partition.

    Args:
      partition: Partition to flash.
      timeout_ms: Optional timeout in milliseconds to wait for it to finish.
      info_cb: See Download. Usually no messages.

    Returns:
      Response to a download request, normally nothing.
    """
    return self._simple_command(
        'flash', arg=partition, info_cb=info_cb, timeout_ms=timeout_ms)

  def erase(self, partition, timeout_ms=None):
    """Erases the given partition."""
    self._simple_command('erase', arg=partition, timeout_ms=timeout_ms)

  def get_var(self, var, info_cb=DEFAULT_MESSAGE_CALLBACK):
    """Returns the given variable's definition.

    Args:
      var: A variable the bootloader tracks, such as version.
      info_cb: See Download. Usually no messages.

    Returns:
      Value of var according to the current bootloader.
    """
    return self._simple_command('getvar', arg=var, info_cb=info_cb)

  def oem(self, command, timeout_ms=None, info_cb=DEFAULT_MESSAGE_CALLBACK):
    """Executes an OEM command on the device.

    Args:
      command: The command to execute, such as 'poweroff' or 'bootconfig read'.
      timeout_ms: Optional timeout in milliseconds to wait for a response.
      info_cb: See Download. Messages vary based on command.

    Returns:
      The final response from the device.
    """
    return self._simple_command(
        'oem %s' % command, timeout_ms=timeout_ms, info_cb=info_cb)

  def continue_(self):
    """Continues execution past fastboot into the system."""
    return self._simple_command('continue')

  def reboot(self, target_mode=None, timeout_ms=None):
    """Reboots the device.

    Args:
        target_mode: Normal reboot when unspecified (or None). Can specify other
          target modes, such as 'recovery' or 'bootloader'.
        timeout_ms: Optional timeout in milliseconds to wait for a response.

    Returns:
        Usually the empty string. Depends on the bootloader and the target_mode.
    """
    return self._simple_command(
        'reboot', arg=target_mode, timeout_ms=timeout_ms)

  def reboot_bootloader(self, timeout_ms=None):
    """Reboots into the bootloader, usually equiv to Reboot('bootloader')."""
    return self._simple_command('reboot-bootloader', timeout_ms=timeout_ms)


import csv
# opens the boys file
obj1 = open(r'2000_BoysNames.txt')
fout = open('output.csv','w')
fout.write('lol')
#for x in obj1:
#    print(x)

# csvBoys = open('boys.csv','w')
# writer = csv.writer(csvboys)
# for x in obj1:
#     writer.writerows(list)
print('hello')


from csv import writer, DictWriter
# Version using writer
# with open("cats.csv", "w") as file:
#     csv_writer = writer(file)
#     csv_writer.writerow(["Name", "Age"])
#     csv_writer.writerow(["Blue", 3])
#     csv_writer.writerow(["Kitty", 1])

# Version using DictWriter
with open("cats.csv", "w") as file:
	# overwrite the file if it has any data
	# with open("cats.csv", "a") as file: writes new lines and leaves the old one
	headers = ["Name", "Breed", "Age"]
	csv_writer = DictWriter(file, fieldnames=headers)
	csv_writer.writeheader() 	# only writes the header
	csv_writer.writerow({ 		# only writes the first line
		"Name": "Garfield",
		"Breed": "Orange Tabby",
		"Age": 10
	})

bootcamp/Session31 - CSV/03_318 - DictWriter/writer_318.py


from django import forms
from django.utils.safestring import mark_safe

class SimpleMDE(forms.Textarea):
    class Media:
        js = (
            'https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js',
        )
        css = {
           'all': ('https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css',)
        }

    def __init__(self, attrs={'id':'textarea_id'}):
        self.attrs = attrs
        super(self.__class__, self).__init__(self.attrs)

    def render(self, name, value, attrs=None, renderer=None):
        rendered = super(self.__class__, self).render(name, value, attrs=None, renderer=None)
        return rendered + mark_safe("""<script>
            var simplemde = new SimpleMDE({{ element: document.getElementById('{0}'), 	renderingConfig: {{singleLineBreaks: false}} }});
            </script>""".format(self.attrs.get('id'))
            )


from __future__ import absolute_import, unicode_literals
import objc
from . import fnd as Foundation
from PyObjCTools.TestSupport import *
import os

NSObject = objc.lookUpClass('NSObject')

def S(*args):
    return b''.join(args)

FUNCTIONS=[
    ( 'NSHomeDirectory', S(objc._C_ID)),
    ( 'NSIsFreedObject', S(objc._C_NSBOOL, objc._C_ID) ),
    ( 'NSCountFrames', S(objc._C_UINT) ),
    ( 'NSClassFromString', S(objc._C_CLASS, objc._C_ID) ),
]

class TestBundleFunctions (TestCase):
    def setUp(self):
        self.bundle = Foundation.NSBundle.bundleForClass_(Foundation.NSBundle)

    def testSimple(self):
        for bundle in (None, self.bundle):
            d = {}
            objc.loadBundleFunctions(self.bundle, d, FUNCTIONS)

            self.assertIn('NSIsFreedObject', d)
            self.assertIn('NSCountFrames', d)
            self.assertIn('NSHomeDirectory', d)

            # Don't use this API, it is unsupported and causes warnings.
            #fn = d[u'NSIsFreedObject']
            #obj = NSObject.alloc().init()
            #value = fn(obj)
            #self.assertTrue(not value)

            fn = d['NSHomeDirectory']
            value = fn()
            self.assertEqual(value, os.path.expanduser('~'))

            fn = d['NSClassFromString']
            value = fn('NSObject')
            self.assertIs(value, NSObject)

            # Need to look for a different example, NSCountFrames crashes
            # (that is the actual function, not the dynamic wrapper)
            #fn = d[u'NSCountFrames']
            #import Foundation
            #fn = Foundation.NSCountFrames
            #value = fn()
            #self.assertIsInstance(value, int)

if __name__ == "__main__":
    main()


from cx_Freeze import setup, Executable

import sys
base = 'Win32GUI' if sys.platform=='win32' else None

import os
import os.path
PYTHON_INSTALL_DIR = os.path.dirname(os.path.dirname(os.__file__))
os.environ['TCL_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tcl8.6')
os.environ['TK_LIBRARY'] = os.path.join(PYTHON_INSTALL_DIR, 'tcl', 'tk8.6')

options = {
    'build_exe': {
        'include_files':[
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tk86t.dll'),
            os.path.join(PYTHON_INSTALL_DIR, 'DLLs', 'tcl86t.dll'),
         ],
    },
}

executables = [
    Executable('tkedit.py', base=base)
]

setup(name='tkedit',
      version = '1.0',
      description = 'A tkinter text editor',
      options = options,
      executables = executables)


# Author: Vong Chen

from operator import itemgetter

def groupSchedule(pers1Schedule, pers1DailyAct, pers2Schedule, pers2DailyAct, duration):
    updatedSchedule1 = updateSchedule(pers1Schedule, pers1DailyAct)
    # print(updatedSchedule1)
    updatedSchedule2 = updateSchedule(pers2Schedule, pers2DailyAct)
    # print(updatedSchedule2)
    mergedSchedule = mergedSchedules(updatedSchedule1, updatedSchedule2)
    # print(mergedSchedule)
    sortedSchedules = sortedAllSchedules(mergedSchedule)
    # print(sortedSchedules)
    print("Available Schedule is: ", matchedAvailabilities(sortedSchedules, duration))

def updateSchedule(Schedule, DailyAct):
    updatedSchedule = Schedule[:]  # make a copy of the schedule
    updatedSchedule.insert(0, ['00:00', DailyAct[0]])  # update unavailable schedules and add early morning hours
    updatedSchedule.append([DailyAct[1], '23:59'])  # update unavailable schedules and add after work hours
    i = 0
    while i < len(updatedSchedule):
        if len(updatedSchedule[i][0]) == 4:
            updatedSchedule[i][0] = "0" + updatedSchedule[i][0]
        if len(updatedSchedule[i][1]) == 4:
            updatedSchedule[i][1] = "0" + updatedSchedule[i][1]
        i += 1
    return updatedSchedule
    # return list(map(lambda s: [convertToMinutes(s[0]), convertToMinutes(s[1])], updatedSchedule))

def mergedSchedules(pers1Schedule, pers2Schedule):
    merged = []
    i, j = 0, 0
    while i < len(pers1Schedule):
        merged.append(pers1Schedule[i])
        i += 1
    while j < len(pers2Schedule):
        merged.append(pers2Schedule[j])
        j += 1
    return merged

def sortedAllSchedules(Schedule):
    # Todo: write a function to  arrange all schedules. New meeting starts AFTER the end of current meeting.
    allSchedules = Schedule[:]
    allSchedules.sort(key=itemgetter(0, 1))
    return allSchedules

def matchedAvailabilities(Schedule, duration):
    # Todo: write a function to match all availabilities
    availabilities = []  # create empty list to store all the available times
    tempSchedule = Schedule[:]  # make a copy of Schedule to avoid changing the original Schedule in memory
    tempTime = tempSchedule[0]  # assigning current Time to be the one at index 0
    i = 0
    while i < len(tempSchedule):  # this while loop will go through the Schedule list
        # and will append the available times to empty list of availabilities when the algorithm is true
        if tempTime[1] == tempSchedule[i][0] and \
                (convertToMinutes(tempSchedule[i][0])
                 - convertToMinutes(tempTime[1])) \
                < int(duration):
            tempTime = tempSchedule[i]
        elif tempTime[1] < tempSchedule[i][0] and \
                (convertToMinutes(tempSchedule[i][0])
                 - convertToMinutes(tempTime[1])) \
                >= int(duration):
            availableTime = [tempTime[1], tempSchedule[i][0]]
            availabilities.append(availableTime)
            tempTime = tempSchedule[i]
        elif tempSchedule[i][0] <= tempTime[1] <= tempSchedule[i][1]:
            tempTime = [tempTime[1], tempSchedule[i][1]]

        i += 1
    return availabilities

def convertToMinutes(time):
    hours, minutes = list(map(int, time.split(":")))
    return hours * 60 + minutes

def main():
    sp_chars = ['‘', '’']
    pers1Schedule = input("Enter schedule for person 1:")
    for i in sp_chars:
        pers1Schedule = pers1Schedule.replace(i, "'")  # Replacing the ‘,’ characters into '
    pers1Schedule = eval(pers1Schedule)  # This will convert the string into a list of list
    pers2Schedule = input("Enter schedule for person 2:")
    for i in sp_chars:
        pers2Schedule = pers2Schedule.replace(i, "'")  # Replacing the ‘,’ characters into '
    pers2Schedule = eval(pers2Schedule)  # This will convert the string into a list of list
    pers1DailyAct = input("Enter Daily Availability for pers 1: ")
    for i in sp_chars:
        pers1DailyAct = pers1DailyAct.replace(i, "'")  # Replacing the ‘,’ characters into '
    pers1DailyAct = eval(pers1DailyAct)  # This will convert the string into a list of list
    pers2DailyAct = input("Enter Daily Availability for pers 2: ")
    for i in sp_chars:
        pers2DailyAct = pers2DailyAct.replace(i, "'")  # Replacing the ‘,’ characters into '
    pers2DailyAct = eval(pers2DailyAct)  # This will convert the string into a list of list
    duration = input("Enter duration of the proposed meeting: ")
    groupSchedule(pers1Schedule, pers1DailyAct, pers2Schedule, pers2DailyAct, duration)

if __name__ == "__main__":
    main()


import os
import numpy as np
from sklearn import metrics
import matplotlib.pyplot as plt
from clusterValidation import valuate_kmeans, valuate_GM
from dimensionReduction import applyPCA, applyFastICA, applyGRP, applyLDA

training_data_file_name = "phishing_binary.txt"
label_file_name = "phishing_label.txt"
path = os.path.dirname(os.path.realpath(__file__)) + "\\data\\"
data = np.loadtxt(open(path + training_data_file_name),  dtype = int, delimiter = ',')
labels = np.loadtxt(open(path + label_file_name),  dtype = int, delimiter = ',')

clusters = 4
features = len(data[0])
sample_num = len(data)

ARS = []
VMS = []
ARS2 = []
VMS2 = []

components = []
for i in range(1, 40):
    components.append(i)

    grp_data = applyGRP(data, i)
    grp_time, labels_grp = valuate_kmeans(grp_data, clusters)
    grp_time2, labels_grp2 = valuate_GM(grp_data, clusters)
    ARS.append(metrics.adjusted_rand_score(labels_grp, labels) )
    VMS.append(metrics.v_measure_score(labels_grp, labels) )
    ARS2.append(metrics.adjusted_rand_score(labels_grp2, labels) )
    VMS2.append(metrics.v_measure_score(labels_grp2, labels) )

#print ARS_pca, '\n', ARS_ica, '\n', ARS_grp, '\n', ARS_lda

#plot samples using new components
plt.figure()
plt.plot(components, ARS, c='r', linewidth=1, label='ARS-GRP')
plt.plot(components, ARS2, c='r', linestyle=':', linewidth=3, label='ARS-ori')
plt.plot(components, VMS, c='b', linewidth=1, label='VMS-GRP')
plt.plot(components, VMS2, c='b', linestyle=':', linewidth=3, label='VMS-ori')

plt.title("clustering performance vs components")
plt.xlabel("components")
plt.ylabel("scores")
#plt.ylim((-0.2, 1.2))
plt.legend(loc=(2))
plt.show()


import re
from file_loading import load_file_whole

def get_field_rules(td):
    rules = {}

    td_split = td.split('\n')

    for rule in td_split:
        name = re.match(r'([\w\s]+):', rule).group(1)
        rules[name] = []
        for low, high in re.findall(r'(\d+)-(\d+)', rule):
            rules[name].append([int(low), int(high)])

    return rules

def check_nb_ticket(ticket, rules):
    error = 0
    ticket_valid = True

    for field in ticket:
        for rule in rules.values():
            valid = False
            if rule[0][0] <= int(field) <= rule[0][1] or rule[1][0] <= int(field) <= rule[1][1]:
                valid = True

        if not valid:
            error += int(field)
            ticket_valid = False

    ticket.append(ticket_valid)

    return error

def ticket_translation():
    ticket_file = "input.txt"
    error_rate = 0
    field_lookup = {}

    ticket_data = load_file_whole(ticket_file)
    ticket_data_split = ticket_data.split('\n\n')

    field_rules = get_field_rules(ticket_data_split[0])
    own_ticket = ticket_data_split[1].split('\n')
    nearby_tickets = ticket_data_split[2].split('\n')

    own_ticket.__delitem__(0)
    nearby_tickets.__delitem__(0)

    own_ticket = own_ticket[0].split(',')

    for nb_ticket in range(len(nearby_tickets)):
        nearby_tickets[nb_ticket] = nearby_tickets[nb_ticket].split(',')
        error_rate += check_nb_ticket(nearby_tickets[nb_ticket], field_rules)

    for f_name, f_rule in field_rules.items():
        for field in range(len(nearby_tickets[0])):
            column_check = True
            for ticket in range(len(nearby_tickets)):
                if nearby_tickets[ticket][-1]:
                    check = int(nearby_tickets[ticket][field])
                    if not (f_rule[0][0] <= check <= f_rule[0][1]) and not(f_rule[1][0] <= check <= f_rule[1][1]):
                        column_check = False

            if column_check:
                if f_name in field_lookup.keys():
                    field_lookup[f_name].append(field)
                else:
                    field_lookup[f_name] = [field]

    done = False
    del_values = []
    while not done:
        done = True
        for search_field in field_lookup.values():
            if len(search_field) == 1 and search_field[0] not in del_values:
                del_value = search_field[0]
                del_values.append(del_value)
                done = False
                for del_field in field_lookup.values():
                    if len(del_field) != 1 and del_value in del_field:
                        del_field.remove(del_value)

    answer = 1

    for field, location in field_lookup.items():
        if field.startswith('departure'):
            answer *= int(own_ticket[location[0]])

    print(error_rate)
    print(answer)

if __name__ == '__main__':
    ticket_translation()


from pyspark.sql import SparkSession
import pandas as pd

df = pd.read_csv("permit-inspections.csv", delimiter=";")
print(df.shape)
appName = "PySpark Partition Example"
master = "local[1]"

spark = SparkSession.builder \
    .appName(appName) \
    .master(master) \
    .getOrCreate()

print(spark.version)


from PIL import Image
import torch
from torch.utils.data import Dataset
import torchvision.transforms.functional as TF

class MyDataSet(Dataset):

    def __init__(self, images_path1: list, images_path2: list, images_target: list, transform=None):
        self.images_path1 = images_path1
        self.images_path2 = images_path2
        self.images_target = images_target
        self.transform = transform

    def __len__(self):
        return len(self.images_path1)

    def __getitem__(self, item):
        img1 = Image.open(self.images_path1[item])
        img2 = Image.open(self.images_path2[item])
        target = Image.open(self.images_target[item])

        #img1, img2, target = map(TF.to_tensor, (img1, img2, target))
        if self.transform is not None:
            img1 = self.transform(img1)
            img2 = self.transform(img2)
            target = self.transform(target)

        return img1, img2, target


"""API-related classes for the ODIN server.

This module implements a number of classes used by the ODIN server for routing and handling
API calls.

Tim Nicholls, STFC Application Engineering Group
"""

import importlib
import logging
import json

import tornado.web

from odin.http.routes.route import Route
from odin.util import PY3
from odin.http.handlers.base import ApiError, API_VERSION
if PY3:
    from odin.http.handlers.async_api import AsyncApiHandler as ApiHandler
    from odin.async_util import run_async
else:
    from odin.http.handlers.api import ApiHandler

class ApiVersionHandler(tornado.web.RequestHandler):
    """API version handler to allow client to resolve supported version.

    This request handler implements the GET verb to allow a call to the appropriate URI to return
    the supported API version as JSON.
    """

    def get(self):
        """Handle API version GET requests."""
        accept_types = self.request.headers.get('Accept', 'application/json').split(',')
        if "*/*" not in accept_types and 'application/json' not in accept_types:
            self.set_status(406)
            self.write('Requested content types not supported')
            return

        self.write(json.dumps({'api': API_VERSION}))

class ApiAdapterListHandler(tornado.web.RequestHandler):
    """API adapter list handler to return a list of loaded adapters.

    This request hander implements the GET verb to allow a call to the appropriate URI to return
    a JSON-encoded list of adapters loaded by the server.
    """

    def initialize(self, route):
        """Initialize the API adapter list handler.

        :param route: ApiRoute object calling the handler (allows adapters to be resolved)
        """
        self.route = route

    def get(self, version):
        """Handle API adapter list GET requests.

        This handler returns a JSON-encoded list of adapters loaded into the server.

        :param version: API version
        """
        # Validate the API version explicity - can't use the validate_api_request decorator here
        if version != str(API_VERSION):
            self.set_status(400)
            self.write("API version {} is not supported".format(version))
            return

        # Validate the accept type requested is appropriate
        accept_types = self.request.headers.get('Accept', 'application/json').split(',')
        if '*/*' not in accept_types and 'application/json' not in accept_types:
            self.set_status(406)
            self.write('Request content types not supported')
            return

        self.write({'adapters': [adapter for adapter in self.route.adapters]})

class ApiRoute(Route):
    """ApiRoute - API route object used to map handlers onto adapter for API calls."""

    def __init__(self, enable_cors=False, cors_origin="*"):
        """Initialize the ApiRoute object.

        This constructor initialises the API route object, defining handlers for version, adapter
        list and adapter API calls.

        :param enable_cors: flag to enable CORS request support
        :param cors_origin: CORS allowed origins
        """
        super(ApiRoute, self).__init__()

        # Define a default handler which can return the supported API version
        self.add_handler((r"/api/?", ApiVersionHandler))

        # Define a handler which can return a list of loaded adapters
        self.add_handler((r'/api/(.*?)/adapters/?', ApiAdapterListHandler, dict(route=self)))

        # Build a dict of params to be passed to API handler initialisation calls
        handler_params = dict(route=self, enable_cors=enable_cors, cors_origin=cors_origin)

        # Define the handler for API calls. The expected URI syntax, which is
        # enforced by the validate_api_request decorator, is the following:
        #
        #    /api/<version>/<subsystem>/<action>....
        #
        # The second pattern allows an API adapter to be accessed with or without
        # a trailing slash for maximum compatibility
        self.add_handler((r"/api/(.*?)/(.*?)/(.*)", ApiHandler, handler_params))
        self.add_handler((r"/api/(.*?)/(.*?)/?", ApiHandler, handler_params))

        self.adapters = {}

    def register_adapter(self, adapter_config, fail_ok=True):
        """Register an API adapter with the APIRoute object.

        Based on the adapter_config object passed in as an argument, this method attempts to
        load the specified module and create an instance of the adapter class to be used
        to handle requests to the API route on the appropriate path.

        :param adapter_config: AdapterConfig object for the adapter
        :param fail_ok: Allow the adapter import and registration to fail without raising an error
        """
        # Resolve the adapter module and class name from the dotted module path in the config object
        (module_name, class_name) = adapter_config.module.rsplit('.', 1)

        # Try to import the module, resolve the class in the module and create an instance of it
        try:
            adapter_module = importlib.import_module(module_name)
            adapter_class = getattr(adapter_module, class_name)
            if PY3 and adapter_class.is_async:
                adapter = run_async(adapter_class, **adapter_config.options())
            else:
                adapter = adapter_class(**adapter_config.options())
            self.adapters[adapter_config.name] = adapter

        except (ImportError, AttributeError) as e:
            logging.error(
                "Failed to register API adapter %s for path %s with dispatcher: %s",
                adapter_config.module, adapter_config.name, e)
            if not fail_ok:
                raise ApiError(e)
        else:
            logging.debug(
                "Registered API adapter class %s from module %s for path %s",
                class_name, module_name, adapter_config.name
            )

    def has_adapter(self, subsystem):
        """Determine if ApiRoute object has adapter for subsystem.

        :param subsystem: subsystem to check for adapter
        :return: True of adapter present for subsystem
        """
        return subsystem in self.adapters

    def adapter(self, subsystem):
        """Return adapter for subsystem.

        :param subsystem: subsystem to return adapter for
        :return: adapter for subsystem
        """
        return self.adapters[subsystem]

    def cleanup_adapters(self):
        """Clean up state of registered adapters.

        This calls the cleanup method present in any registered adapters, allowing them to
        clean up their state (e.g. connected hardware) in a controlled fashion at shutdown.
        """
        for adapter_name, adapter in self.adapters.items():
            try:
                cleanup_method = getattr(adapter, 'cleanup')
                if PY3 and adapter.is_async:
                    run_async(cleanup_method)
                else:
                    cleanup_method()
            except AttributeError:
                logging.debug("Adapter %s has no cleanup method", adapter_name)

    def initialize_adapters(self):
        """Initialize all the adapters after they have been registered by the route.

        This calls the initialize method present in any registered adapters, passing
        the dictionary of listed adapters to each, for inter adapter communication.
        """
        for adapter_name, adapter in self.adapters.items():
            try:
                initialize_method = getattr(adapter, 'initialize')
                if PY3 and adapter.is_async:
                    run_async(initialize_method, self.adapters)
                else:
                    initialize_method(self.adapters)
            except AttributeError:
                logging.debug("Adapter %s has no initialize method", adapter_name)


import os

with open("input.txt") as f:
    lines = f.readlines()

elf_total = {}
current_elve = 1

for line in [x.replace("\n", "") for x in lines]:
    if line == "":
        current_elve += 1
    else:
        cal_int = int(line)
        if current_elve in elf_total.keys():
            elf_total[current_elve] += cal_int
        else:
            elf_total[current_elve] = cal_int

print(f"Max calories: {max(elf_total.values())}")

totals = set(elf_total.values())

current_total = 0
num_to_count = 3

for x in range(1, num_to_count+1):
    current_max = max(totals)
    print(f"Current Max: {current_max}")
    current_total += current_max
    totals.remove(current_max)

print(f"Total of top {num_to_count}: {current_total}")


class Solution:
    def numberOfBoomerangs(self, points):
        """
        :type points: List[List[int]]
        :rtype: int
        """
        num = 0

        for i, pointA in enumerate(points):
            d = dict()
            for j, pointB in enumerate(points):
                if i == j:
                    continue

                distance = (pointB[0] - pointA[0]) * (pointB[0] - pointA[0]) + (pointB[1] - pointA[1]) * (pointB[1] - pointA[1])

                if distance in d:
                    d[distance] = d[distance] + 1
                else:
                    d[distance] = 1

            for key in d.keys():
                num += d[key] * (d[key] - 1)

        return num


import discord
from discord import app_commands
from discord.ext import commands

class Test(commands.Cog):
    def __init__(self, bot : commands.Bot) -> None:
        self.bot = bot

    @app_commands.command(name="test")
    async def test(self, interaction : discord.Interaction):
        await interaction.response.send_message("Eagle has landed!", ephemeral=True)

    # @commands.command(name="test")
    # async def test(self,ctx,args):
    #     await ctx.reply(args)

async def setup(bot : commands.Bot):
    await bot.add_cog(Test(bot))


import os
import ast
import pystache
import json
import urllib3

from kubernetes import client as k_client
from kubernetes import config as k_config
from kubernetes.client.rest import ApiException
from base64 import b64encode, b64decode

urllib3.disable_warnings()

class ComputeParty:
    """
    Represents one party in a computation.
    Generates all Kubernetes objects.
    """

    def __init__(
            self, pid, all_pids, compute_id, protocol, app, protocol_config,
            namespace_map, jiff_server_ip, data_source="swift"
    ):

        self.pid = pid
        self.all_pids = all_pids
        self.compute_id = compute_id
        self.app = app
        self.data_source = data_source
        self.config = protocol_config
        self.mpc_backend = self.set_mpc_backend()
        self.endpoint = self.get_endpoint()
        self.data_source = self.resolve_data_source()
        self.namespace_map = namespace_map
        self.namespace = namespace_map[int(pid) - 1]
        self.jiff_server_ip = jiff_server_ip

        self.template_directory = "{}/templates/".format(os.path.dirname(os.path.realpath(__file__)))
        self.name = "conclave-{0}-{1}".format(compute_id, str(pid))
        self.config_map_name = "conclave-{0}-{1}-map".format(compute_id, str(pid))

        self.protocol = protocol
        self.protocol_main = self.gen_protocol_main()
        self.conclave_config = self.gen_conclave_config()
        self.config_map_body = self.define_config_map()
        self.pod_body = self.define_pod()
        self.service_body = self.define_service()
        self.network_policy_body = self.define_network_policy()

    def set_mpc_backend(self):

        if len(self.config["data"]["endpoints"]) == 2:
            self.app.logger.info("Using Obliv-C backend for MPC computation.\n")
            return "obliv-c"
        else:
            self.app.logger.info("Using JIFF backend for MPC computation.\n")
            return "jiff"

    def get_endpoint(self):

        return self.config["data"]["endpoints"][self.pid - 1]

    def resolve_data_source(self):

        if self.endpoint["backend"].lower() == "swift":
            return "swift"
        elif self.endpoint["backend"].lower() == "dataverse":
            return "dataverse"
        else:
            raise Exception("Data backend not recognized: {}\n".format(self.endpoint["backend"]))

    @staticmethod
    def format_protocol(protocol):
        """
        Format protocol code with tabs before injecting into template.
        """

        ret = []

        for line in protocol.split("\n"):
            ret.append("\t" + line)

        return "\n".join(ret)

    def gen_protocol_main(self):
        """
        Generate protocol code.
        """

        if self.config['protocol']['format'] == 'b64':
            protocol_decoded = self.format_protocol(b64decode(self.protocol).decode())
        else:
            protocol_decoded = self.format_protocol(self.protocol)

        params = {
            "PROTOCOL": protocol_decoded,
            "MPC_FRAMEWORK": self.mpc_backend
        }

        data_template = open("{}/protocol_main.tmpl".format(self.template_directory), 'r').read()
        rendered = pystache.render(data_template, params)

        self.app.logger.info("CC protocol: \n{}\n".format(rendered))

        return b64encode(rendered.encode()).decode()

    def gen_conclave_config(self):
        """
        Generate CC Config JSON.

        TODO: configurable PROJ_NAME (will probably need to resolve with a db call to the input data)
        """

        net_list = self.gen_net_config()

        params = \
            {
                "PID": self.pid,
                "ALL_PIDS": self.all_pids,
                "WORKFLOW_NAME": "conclave-{}".format(self.compute_id),
                "NET_CONFIG": net_list,
                "SPARK_AVAIL": 0,
                "SPARK_IP_PORT": "N/A",
                "OC_AVAIL": int(self.mpc_backend == "obliv-c"),
                "OC_IP_PORT":
                    "0.0.0.0:5001" if self.pid == 1 else "conclave-{0}-1-service.{1}.svc.cluster.local:5001"
                    .format(self.compute_id, self.namespace_map[1]),
                "JIFF_AVAIL": int(self.mpc_backend == "jiff"),
                "PARTY_COUNT": len(self.all_pids),
                "SERVER_SERVICE": self.jiff_server_ip,
                "DATA_BACKEND": self.data_source,
                "PROJ_NAME": "ccs-musketeer-demo",
                "SOURCE_CONTAINER_NAME": self.endpoint["containerName"] if self.data_source == "swift" else "",
                "FILENAME": self.endpoint["fileName"],
                "OUTPUT_AUTH_URL": open("/etc/swift-auth/auth_url", "r").read(),
                "OUTPUT_PROJ_DOMAIN": open("/etc/swift-auth/proj_domain", "r").read(),
                "OUTPUT_PROJ_NAME": open("/etc/swift-auth/proj_name", "r").read(),
                "OUTPUT_USER_NAME": open("/etc/swift-auth/username", "r").read(),
                "OUTPUT_PASS": open("/etc/swift-auth/password", "r").read(),
                "DEST_CONTAINER_NAME": self.compute_id,
                "SOURCE_ALIAS": self.endpoint["alias"] if self.data_source == "dataverse" else "",
                "SOURCE_DOI": self.endpoint["doi"] if self.data_source == "dataverse" else ""
            }

        data_template = open("{}/conclave_config.tmpl".format(self.template_directory), 'r').read()

        rendered = pystache.render(data_template, params)

        self.app.logger.info("CC JSON file:\n{}".format(rendered))

        return b64encode(rendered.encode()).decode()

    def gen_net_config(self):
        """
        Generate CC Net Config string that gets inserted into CC Config JSON.
        """

        ret_net = []

        for i in self.all_pids:
            if i == self.pid:
                ret_net.append({"host": "0.0.0.0", "port": 5000})
            else:
                ret_net.append({"host": "conclave-{0}-{1}-service.{2}.svc.cluster.local"
                               .format(self.compute_id, str(i), self.namespace_map[i-1]), "port": 5000})

        return json.dumps(ret_net)

    def define_config_map(self):
        """
        Populate ConfigMap template.
        """

        data_params = \
            {
                "NAME": "conclave-{0}-{1}-map".format(self.compute_id, str(self.pid)),
                "NAMESPACE": self.namespace,
                "PROTOCOL_MAIN": str(self.protocol_main),
                "CC-CONF": self.conclave_config
            }

        data_template = open("{}configmap.tmpl".format(self.template_directory), 'r').read()

        rendered = pystache.render(data_template, data_params)

        return ast.literal_eval(rendered)

    def setup_data_params(self):
        """
        Construct key/path values for input data configmap on pod.
        """

        if self.data_source == "swift":
            return [
                {"key": "osAuthUrl", "path": "auth_url"},
                {"key": "username", "path": "username"},
                {"key": "password", "path": "password"}
            ]

        elif self.data_source == "dataverse":
            return [
                {"key": "host", "path": "dv_host"},
                {"key": "token", "path": "dv_token"}
            ]
        else:
            raise Exception("Data backend not recognized: {}\n".format(self.data_source))

    def define_pod(self):
        """
        Populate Pod template.
        """

        params = \
            {
                "POD_NAME": self.name,
                "CONFIGMAP_NAME": self.config_map_name,
                "NAMESPACE": self.namespace,
                "COMPUTE_ID": self.compute_id,
                "IMAGE": "docker.io/bengetch/conclave:jiff" if self.mpc_backend == "jiff"
                else "docker.io/bengetch/conclave:oc",
                "BACKEND": self.data_source,
                "BACKEND_PARAMS": self.setup_data_params(),
                "FILENAME": self.endpoint["fileName"],
                "UID": self.config["uid"]
            }

        data_template = open("{}/pod.tmpl".format(self.template_directory), 'r').read()

        rendered = pystache.render(data_template, params)

        return ast.literal_eval(rendered)

    def define_service(self):
        """
        Populate Service template for CC Pods and MPC backends.
        """

        params = \
            {
                "SERVICE_NAME": "{}-service".format(self.name),
                "APP_NAME": self.name,
                "COMPUTE_ID": self.compute_id
            }

        data_template = open("{}/service.tmpl".format(self.template_directory), 'r').read()

        rendered = pystache.render(data_template, params)

        return ast.literal_eval(rendered)

    def define_network_policy(self):

        params = \
            {
                "NAME": self.name,
                "POD_NAME": self.name,
                "OTHER_PROJECT": "ccd-two" if self.namespace == "ccd-one" else "ccd-one"
            }

        data_template = open("{}/network_policy.tmpl".format(self.template_directory), 'r').read()

        rendered = pystache.render(data_template, params)

        return ast.literal_eval(rendered)

    def launch(self):
        """
        Launch all Kubernetes objects.
        """

        k_config.load_incluster_config()
        kube_client = k_client.CoreV1Api()
        # kube_client_networking = k_client.NetworkingV1Api()

        try:
            api_response = \
                kube_client.create_namespaced_config_map(self.namespace, self.config_map_body, pretty='true')
            self.app.logger.info(
                "ConfigMap created successfully with response: \n{}\n"
                    .format(api_response))
        except ApiException as e:
            self.app.logger.error(
                "Error creating ConfigMap: \n{}\n"
                    .format(e))

        try:
            api_response = \
                kube_client.create_namespaced_service(self.namespace, body=self.service_body, pretty='true')
            self.app.logger.info(
                "Service created successfully with response: \n{}\n"
                    .format(api_response))
        except ApiException as e:
            self.app.logger.error(
                "Error creating Service: \n{}\n"
                    .format(e))

        try:
            api_response = kube_client.create_namespaced_pod(self.namespace, body=self.pod_body, pretty='true')
            self.app.logger.info(
                "Pod created successfully with response: \n{}\n"
                    .format(api_response))
        except ApiException as e:
            self.app.logger.error(
                "Error creating Pod: \n{}\n"
                    .format(e))

        # try:
        #     api_response = kube_client_networking.create_namespaced_network_policy(
        #         self.namespace, body=self.network_policy_body, pretty='true')
        #     self.app.logger.info(
        #         "NetworkPolicy successfully created with response: \n{}\n"
        #             .format(api_response))
        # except ApiException as e:
        #     self.app.logger.error(
        #         "Error creating NetworkPolicy: \n{}\n"
        #             .format(e))

        return


import sys
import os
import argparse
import configparser
import random
import time
import calendar
import re
import py3buddy
import pydbus
import gi

def processmsg(account, sender, message, conversation, flags):
    # a demo version to show some of the capabilities of
    # the iBuddy

    # first reset the iBuddy
    ibuddy.reset()

    # a list of smileys as sent by Google Hangout
    smileys = [':D', ':-D', '^_^', ':-)', ':)', '☺']

    # a command to execute when a smiley is received
    smilecommand = 'RED:HEART:WINGSHIGH:GO:SHORTSLEEP:YELLOW:NOHEART:WINGSLOW:GO:SHORTSLEEP:HEART:BLUE:WINGSHIGH:GO:SHORTSLEEP:PURPLE:NOHEART:WINGSLOW:GO:SHORTSLEEP:HEART:CYAN:WINGSHIGH:GO:SHORTSLEEP:WHITE:NOHEART:WINGSLOW:GO:SHORTSLEEP:RESET'
    for s in smileys:
        if s in message:
            ibuddy.executecommand(smilecommand)
            break

    ibuddy.reset()

def main(argv):
    parser = argparse.ArgumentParser()

    # options for the commandline
    parser.add_argument("-c", "--config", action="store", dest="cfg",
                        help="path to configuration file", metavar="FILE")
    args = parser.parse_args()

    # first some sanity checks for the configuration file
    if args.cfg is None:
        parser.error("Configuration file missing")

    if not os.path.exists(args.cfg):
        parser.error("Configuration file does not exist")

    # then parse the configuration file
    config = configparser.ConfigParser()

    configfile = open(args.cfg, 'r')

    try:
        config.readfp(configfile)
    except Exception:
        print("Cannot read configuration file", file=sys.stderr)
        sys.exit(1)

    buddy_config = {}
    for section in config.sections():
        if section == 'ibuddy':
            try:
                productid = int(config.get(section, 'productid'))
                buddy_config['productid'] = productid
            except:
                pass

            buddy_config['reset_position'] = False
            try:
                reset_position_val = config.get(section, 'reset_position')
                if reset_position_val == 'yes':
                    buddy_config['reset_position'] = True
            except:
                pass
        if section == 'twitter':
            pass

    # This is very ugly, but the only way (I know) to expose the iBuddy to the
    # method processing the message from Pidgin
    global ibuddy

    # initialize an iBuddy and check if a device was found and is accessible
    ibuddy = py3buddy.iBuddy(buddy_config)
    if ibuddy.dev is None:
        print("No iBuddy found, or iBuddy not accessible", file=sys.stderr)
        sys.exit(1)

    # connect to session DBus
    bus = pydbus.SessionBus()

    # register a callback for messages that are received
    purple = bus.get("im.pidgin.purple.PurpleService",
                     "/im/pidgin/purple/PurpleObject")
    purple.ReceivedImMsg.connect(processmsg)

    gi.repository.GObject.MainLoop().run()

    # finally reset the i-buddy again
    ibuddy.reset()

if __name__ == "__main__":
    main(sys.argv)


'''
Training and testing data structure
```
data/
    train/
        cat1/
            cat1001.jpg
            cat1002.jpg
            ...
        cat2/
            cat2001.jpg
            cat2002.jpg
            ...
    validation/
        cat1/
            cat1001.jpg
            cat1002.jpg
            ...
        cat2/
            cat2001.jpg
            cat2002.jpg
            ...
```
'''
import tensorflow as tf
import keras.backend as K
import keras
from keras import applications
from keras.preprocessing.image import ImageDataGenerator
from keras import optimizers
from keras.models import Sequential, Model, load_model
from keras.layers import Dropout, Flatten, Dense
import time
import build_CNN
import action_generator

img_width, img_height = 224, 224

train_data_dir = 'gs://resnet_bucket/tiny_image_200/train'
validation_data_dir = 'gs://resnet_bucket/tiny_image_200/val'
nb_train_samples = 100000
nb_validation_samples = 10000
epochs = 50
batch_size = 64

# tensorflow.python.lib.io.file_io.FileIO(train_file, mode='r')

def tf_config_allow_growth_gpu():
    config = tf.ConfigProto()
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)
    K.set_session(sess)

def pop_layer(model):
    if not model.outputs:
        raise Exception('Sequential model cannot be popped: model is empty.')

    model.layers.pop()
    if not model.layers:
        model.outputs = []
        model.inbound_nodes = []
        model.outbound_nodes = []
    else:
        model.layers[-1].outbound_nodes = []
        model.outputs = [model.layers[-1].output]
    model.built = False

def init_compile_model(state, laststate):
    # build the ResNet50 network
    initial_model = applications.ResNet50(include_top=True)
    # state = [1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0, 1, 1, 0]
    initial_model = build_CNN.update_model(state, 'imagenet')
    pop_layer(initial_model)
    last = initial_model.layers[-1].output
    preds = Dense(200, activation='softmax', name="fc2")(last)
    model = Model(initial_model.input, preds)
    # model = load_model('current_model.h5')
    model.load_weights('current_model.h5')
    print('Model loaded.')
    model.summary()
    # pop_layer(model)
    # set the first x layers (up to the last conv block)
    # to non-trainable (weights will not be updated)
    trainable_index = action_generator.find_last_changed(state, laststate)
    for layer in model.layers[:25]:
        name = layer.get_config()['name']
        if 'blk' not in name:
            layer.trainable = False
        elif int(name.split('blk')[1]) < trainable_index:
            layer.trainable = False

    # compile the model with a SGD/momentum optimizer
    # and a very slow learning rate.
    model.compile(loss='categorical_crossentropy',
                  optimizer=optimizers.SGD(lr=1e-3, momentum=0.9),
                  metrics=['accuracy'])
    print('Model compiled.')
    return model

def init_generators():
    # prepare data augmentation configuration
    train_datagen = ImageDataGenerator(
        rescale=1. / 255,
        shear_range=0.2,
        zoom_range=0.2,
        horizontal_flip=True)

    test_datagen = ImageDataGenerator(rescale=1. / 255)

    train_generator = train_datagen.flow_from_directory(
        train_data_dir,
        target_size=(img_height, img_width),
        batch_size=batch_size)

    validation_generator = test_datagen.flow_from_directory(
        validation_data_dir,
        target_size=(img_height, img_width),
        batch_size=batch_size)
    print('Data generators created.')
    return train_generator, validation_generator

class PrintRuntime(keras.callbacks.Callback):
    def on_train_begin(self, logs={}):
        self.run_time = []
        self.begin = 0
    def on_batch_begin(self, batch, logs={}):
        self.begin = time.time()
    def on_batch_end(self, batch, logs={}):
        end = time.time()
        runtime = end-self.begin
        self.run_time.append(runtime)
        if len(self.run_time)%100:
            # print("Run-time on last batch:", runtime, "seconds")
            print("Avg Run-time on last batch:", sum(self.run_time)/len(self.run_time), "seconds")

# fine-tune the model

def test():  # tf_config_allow_growth_gpu()
    laststate = [1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0]
    state = [1, 1, 0, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 1, 1, 0]
    print("step1")
    model = init_compile_model(state, laststate)
    print("step2")
    train_generator, validation_generator = init_generators()
    print("step3")
    runtime_callback = PrintRuntime()
    print("step4")
    model.fit_generator(
        train_generator,
        steps_per_epoch=10000 / 64,
        epochs=30,
        validation_data=validation_generator,
        validation_steps=1000 / 64, verbose=2)

    model.save('my_model2.h5')


class Solution:
    def findJudge(self, N: int, trust: List[List[int]]) -> int:
        indeg = [0] * (N + 1)
        outdeg = [0] * (N + 1)
        for p in trust:
            indeg[p[1]] = indeg[p[1]] + 1
            outdeg[p[0]] = outdeg[p[0]] + 1
        town_judge = -1
        num_judges = 0
        for i in range(1, N + 1):
            if indeg[i] == (N - 1) and outdeg[i] == 0:
                town_judge = i
                num_judges += 1
        if num_judges > 1:
            return False
        return town_judge

May LeetCoding Challenge/Day 10 - Find the town judge.py


# runs simulations of the calling process described in the project
# the RNG class is used for generating random numbers
# we only used numpy to compute the quartiles
import math
import numpy as np

class RNG:
    def __init__(self, x_0, a, c, k):
        self.seed = x_0
        self.multiplier = a
        self.increment = c
        self.modulus = k
        self.nums = []

    def generate(self, n=1000):
        """
        Generates n random numbers and returns as a list
        :param n: number of random numbers to generate
        :return: a list of random numbers of length n
        """
        ret = []
        x_i = self.seed
        for i in range(n):
            x_i = (x_i * self.multiplier + self.increment) % self.modulus  # x_i = (x_i-1 * a + c) % K
            ret.append(x_i / self.modulus)  # u_i = x_i / K
        self.nums = ret
        return ret

    def show_51(self):
        """returns u_51, u_52, and u_53. Used for the report"""
        nums = self.generate(55)
        return nums[50], nums[51], nums[52]

def map_rand(u, lam=1 / 12):
    """returns a realization of an exponential random variable with parameter lambda given a random number u"""
    ret = (-1 / lam) * math.log(1 - u)
    # print("F^-1(" + str(u) + "):", ret, end=" --> ")
    return ret

def simulate_call(queue, display_output=False):
    """runs a simulation of the calling process and returns the time in seconds that the process took
    displays debugging prints if display_output is set to true"""
    tries = 1
    t = 0
    while tries <= 4:  # gives up after 4 tries
        u = queue.pop(0)  # get a new random number
        t += 6  # 6 seconds to dial the call
        if u <= .2:
            t += 4  # 3 seconds to detect busy line + 1 second to hang up
            if display_output:
                print("line busy, on try #", tries, "seconds so far:", t)
        elif u <= .5:
            t += 26  # 25s to wait for ringing + 1s to hang up
            if display_output:
                print("no answer on try #", tries, "seconds so far:", t)
        elif u <= 1:
            # print("client answered, u =", u)
            u = queue.pop(0)
            t += map_rand(u, 1 / 12)  # use a new random number to determine the wait time
            if display_output:
                print("client answered after", tries, "tries! Total time:", t)
            return t  # process is complete if phone is answered
        tries += 1
    if display_output:
        print("gave up after 4 tries. Total time:", t)
    return t

def run_mcs(n, display_output=False):
    """runs the Monte-Carlo Simulation (MCS) n times and returns a list of n trial times
    displays debugging prints if display_output is set to true"""
    rng = RNG(1000, 24693, 3517, 2**15)  # make a random number generator with the same parameters as the example
    rand_queue = rng.generate(n*5)  # I'm using a queue so that each random number is used exactly once
    # Each iteration needs at most 5 random numbers, so I had the RNG generate n*5 numbers just to be 100% safe
    times = []  # return value
    for i in range(n):
        if display_output:
            print("---------- simulation", i + 1, "-----------")
        times.append(simulate_call(rand_queue))
    if display_output:
        print("simulation time results:", times)
    return times

def parse_times(times):
    """returns a tuple with the following statistics of the parameter list (respectively)
    (mean, min, first quartile, median, third quartile, max"""
    quartiles = np.percentile(times, [0, 25, 50, 75, 100])
    return np.mean(times), quartiles[0], quartiles[1], quartiles[2], quartiles[3], quartiles[4]


import torch
import torch.nn as nn
import torch.nn.functional as F

class Encoder(nn.Module):

    def __init__(self, in_channels, out_channels, base_channels=64, n_layers=4):
        super().__init__()

        layers = [
            nn.ReflectionPad2d(3),
            nn.Conv2d(in_channels, base_channels, kernel_size=7, padding=0),
            nn.InstanceNorm2d(base_channels),
            nn.ReLU(inplace=True),
        ]

        channels = base_channels

        # downsampling
        for _ in range(n_layers):
            layers += [
                nn.Conv2d(channels, 2 * channels, kernel_size=3, stride=2, padding=1),
                nn.InstanceNorm2d(2 * channels),
                nn.ReLU(inplace=True),
            ]
            channels *= 2

        # upsampling
        for _ in range(n_layers):
            layers += [
                nn.ConvTranspose2d(channels, channels // 2, kernel_size=3, stride=2, padding=1, output_padding=1),
                nn.InstanceNorm2d(channels // 2),
                nn.ReLU(inplace=True),
            ]
            channels //= 2

        layers += [
            nn.ReflectionPad2d(3),
            nn.Conv2d(base_channels, out_channels, kernel_size=7, padding=0),
            nn.Tanh(),
        ]

        self.out_channels = out_channels
        self.layers = nn.Sequential(*layers)

    def instancewise_average_pooling(self, x, inst):

        x_mean = torch.zeros_like(x)
        classes = torch.unique(inst, return_inverse=False, return_counts=False)

        for i in classes:
            for b in range(x.size(0)):
                indexes = torch.nonzero(inst[b:b+1] == 1, as_tuple=False)
                for j in range(self.out_channels):
                    x_ins = x[indexes[:, 0] + b, indexes[:, 1] + j, indexes[:, 2], indexes[:, 3]]
                    mean_feat = torch.mean(x_ins).expand_as(x_ins)
                    x_mean[indexes[:, 0] + b, indexes[:, 1] + j, indexes[:, 2], indexes[:, 3]] = mean_feat

        return x_mean

    def forward(self, x, inst):
        x = self.layers(x)
        x = self.instancewise_average_pooling(x, inst)
        return x


# 2D 히스토그램

import cv2
import matplotlib.pylab as plt

# 컬러 스타일을 1.x 스타일로 사용
plt.style.use("classic")
img = cv2.imread("./img/mountain.jpg")

# 파랑과 초록에 대한 2차원 히스토그램
plt.subplot(131)
hist = cv2.calcHist([img], [0,1], None, [32,32], [0,256,0,256])
p = plt.imshow(hist)
plt.title("Blue and Green")
plt.colorbar(p)

# 초록과 빨강에 대한 2차원 히스토그램
plt.subplot(132)
hist = cv2.calcHist([img], [1,2], None, [32,32], [0,256,0,256])
p = plt.imshow(hist)
plt.title("Green and Red")
plt.colorbar(p)

# 파랑과 빨강에 대한 2차원 히스토그램
plt.subplot(133)
hist = cv2.calcHist([img], [0,2], None, [32,32], [0,256,0,256])
p = plt.imshow(hist)
plt.title("Blue and Red")
plt.colorbar(p)

plt.show()