import logging
# To change this template, choose Tools | Templates
# and open the template in the editor.

__author__="cooke"
__date__ ="$29-Sep-2011 13:58:46$"
import time

from ant.core import log
from sofiehdfformat.core.SofieUtils import convertRawDataToHexString

"""
Implements a File like object to read lines from the SparkFunLogFile file.

"""
def open(filename):
        reader = log.LogReader(filename)
        return SparkFunFile(reader);

class SparkFunFile(object):
    def __init__(self, reader):
        self.reader = reader

    def readline(self,size=0):
        """
        Reads one sample from the file.
        """
        event = self.reader.read()
        while (event != None):

            if event[0] == log.EVENT_READ:
                data = event[2]
                #logging.debug('========== [EVENT_READ:{0}] =========='.format(event[1]))
                #if logging.isEnabledFor(logging.debug):
                #    length = 8
                #    while data:
                #        row = data[:length]
                #        data = data[length:]
                #        hex_data = ['%02X' % ord(byte) for byte in row]
                #        logging.debug('0x'+' '.join(hex_data))
                logging.debug('TIMESTAMP:'+\
                    time.ctime(event[1])+\
                    ' : '+convertRawDataToHexString(data))
                return {'packet':data,'timestamp':event[1]};
            event = self.reader.read()
        if event == None:
            return False;

    def close(self):
        self.reader.close();

    def __iter__(self):
        return self

    def next(self):
        data = self.readline()
        if data == False or data == None:
            raise StopIteration
        return data


import KratosMultiphysics

# Import applications
import KratosMultiphysics.DEMApplication as DEM

# Other imports

def Factory(settings, Model):
    if(type(settings) != KratosMultiphysics.Parameters):
        raise Exception("expected input shall be a Parameters object, encapsulating a json string")

    process_settings = settings["Parameters"]

    folder_settings = KratosMultiphysics.Parameters("""{
            "help"                 : "This process applies loads over the rigid walls in a certain submodelpart, for a certain time interval",
            "mesh_id"              : 0,
            "model_part_name"      : "please_specify_model_part_name",
            "force_settings" : {
                "value"            : [10.0, "3*t", "x+y"],
                "table"            : [0, 0, 0]
            },
            "moment_settings" : {
                "value"            : [10.0, "3*t", "x+y"],
                "table"            : [0, 0, 0]
            },
            "interval"             : [0.0, 1e30]
        }""" )

    process_settings.AddMissingParameters(folder_settings)

    if process_settings.Has("model_part_name"):
        computing_model_part = Model[process_settings["model_part_name"].GetString()]
    else: # using default name
        computing_model_part = Model["DEM_FEM_boundary"]

    process_settings.RemoveValue("help")

    return DEM.ApplyForcesAndMomentsToWallsProcess(computing_model_part, process_settings)


print("HELLO WHIRLED")

# Add our dependencies
import csv
import os

# Assign a variable to load a file from the path.
file_to_load = os.path.join("Resources", "election_results.csv")
# Assign a variable to save the file to a path.
file_to_save = os.path.join("analysis", "election_analysis.txt")

# Counter/Tally
total_votes = 0
candidate_options = []
candidate_votes = {}
# Winner/Stats
winning_candidate = ""
winning_count = 0
winning_percentage = 0

# Open the election results and read the file with reader function
with open(file_to_load) as election_data:
    file_reader = csv.reader(election_data)

    # Read the header row
    headers = next(file_reader)

    # Add to the total vote count and candidate list
    for row in file_reader:
        total_votes += 1
        candidate_name = row[2]
        if candidate_name not in candidate_options:
            candidate_options.append(candidate_name)
            candidate_votes[candidate_name] = 0
        candidate_votes[candidate_name] += 1

# Save results to text file.
with open(file_to_save, "w") as txt_file:

    # Print final vote count to terminal
    election_results = (
        f"\nElection Results\n"
        f"-------------------------\n"
        f"Total Votes: {total_votes:,}\n"
        f"-------------------------\n")
    print(election_results, end="")
    # Save final vote count to text file
    txt_file.write(election_results)

    # Determine vote count & percentage of votes for each candidate
    for candidate_name in candidate_votes:
        votes = candidate_votes[candidate_name]
        vote_percentage = float(votes) / float(total_votes) * 100

        # Save & print candidate names, percentages, & totals
        candidate_results = (f"{candidate_name}: {vote_percentage:.1f}% ({votes:,})\n")
        print(candidate_results)
        txt_file.write(candidate_results)

        # Determine winning candidate, percentage, & total
        if (votes > winning_count) and (vote_percentage > winning_percentage):
            # If true, set candidate, votes, & percentage to winning...
            winning_count = votes
            winning_percentage = vote_percentage
            winning_candidate = candidate_name

        # Assign winning results to variable
        winning_candidate_summary = (
            f"-------------------------\n"
            f"Winner: {winning_candidate}\n"
            f"Winning Vote Count: {winning_count:,}\n"
            f"Winning Percentage: {winning_percentage:.1f}%\n"
            f"-------------------------\n")

    print(winning_candidate_summary)

    # Save winning results to text file
    txt_file.write(winning_candidate_summary)


# -*- coding: utf-8 -*-
# Copyright (c) 2016 Aladom SAS & Hosting Dvpt SAS
from datetime import datetime
import os
import re

from django.core.signing import Signer
from django.urls import reverse
from django.db import models
from django.template import Template
from django.template.loader import get_template
from django.utils import timezone
from django.utils.translation import ugettext_lazy as _

from ..conf import (
    TextConfRef, TEMPLATES_UPLOAD_DIR, SUBJECT_PREFIX, MIRROR_SIGNING_SALT,
)
from .manager import BlacklistManager, SubscriptionManager
from .options import (
    AbstractBaseMailHeader, AbstractBaseStaticAttachment,
    AbstractBaseDynamicAttachment,
)

__all__ = [
    'Campaign', 'CampaignMailHeader', 'CampaignStaticAttachment',
    'Mail', 'MailHeader', 'MailStaticAttachment', 'MailDynamicAttachment',
    'SubscriptionType', 'Subscription', 'Blacklist',
]

def templates_upload_to(instance, filename):
    if callable(TEMPLATES_UPLOAD_DIR):
        return TEMPLATES_UPLOAD_DIR(instance, filename)
    else:
        return os.path.join(format(datetime.now(), TEMPLATES_UPLOAD_DIR),
                            filename)

class SubscriptionType(models.Model):

    class Meta:
        verbose_name = _("subscription type")
        verbose_name_plural = _("subscription types")

    name = models.CharField(
        max_length=200, unique=True, verbose_name=_("name"))
    description = models.TextField(verbose_name=_("description"))
    subscribed_by_default = models.BooleanField(
        default=True, verbose_name=_("subscribed by default"),
        help_text=_(
            "Whether potential recipients are subscribed or not to "
            "this type by default"
        ))

    def __str__(self):
        return self.name

    def is_subscribed(self, email):
        match = re.match(r'.*\s<([^<> ]+)>', email)
        if match:
            email = match.group(1)

        try:
            return self.subscriptions.get(email=email).subscribed
        except Subscription.DoesNotExist:
            return self.subscribed_by_default

class Subscription(models.Model):

    class Meta:
        verbose_name = _("subscription")
        verbose_name_plural = _("subscriptions")
        unique_together = [
            ('email', 'subscription_type'),
        ]

    email = models.EmailField(
        db_index=True, verbose_name=_("e-mail"))
    subscription_type = models.ForeignKey(
        SubscriptionType, models.CASCADE,
        related_name='subscriptions', related_query_name='subscriptions',
        verbose_name=_("subscription type"))
    subscribed = models.BooleanField(
        default=True, verbose_name=_("subscribed"))
    date_joined = models.DateTimeField(default=timezone.now)
    last_modified = models.DateTimeField(default=timezone.now)

    objects = SubscriptionManager()

    def save(self, *args, **kwargs):
        self.last_modified = timezone.now()
        super().save(*args, **kwargs)

class Campaign(models.Model):

    class Meta:
        ordering = ['name']
        verbose_name = _("e-mail campaign")
        verbose_name_plural = _("e-mail campaigns")

    key = models.SlugField(
        max_length=50, unique=True, verbose_name=_("key"),
        help_text=_(
            "The key will be used to reference this campaign from your "
            "scripts."
        ))
    name = models.CharField(
        max_length=255, verbose_name=_("name"))
    subject = models.CharField(
        max_length=255, verbose_name=_("e-mail subject"),
        help_text=_("May contain template variables."))
    prefix_subject = models.BooleanField(
        default=True, verbose_name=_("prefix subject"),
        help_text=TextConfRef('SUBJECT_PREFIX', within=_(
            "Wheter to prefix the subject with \"{}\" or not."
        )))
    is_enabled = models.BooleanField(
        default=True, verbose_name=_("enabled"),
        help_text=_(
            "E-mails won't be sent for campaigns that are not enabled. "
            "Even if a script requests for sending. This is a way to turn off "
            "some campaigns temporarily without changing the source code."
        ))
    debug_mode = models.BooleanField(
        default=False, verbose_name=_("debug mode"))
    template_file = models.FileField(
        upload_to=templates_upload_to, blank=True,
        verbose_name=_("template file"),
        help_text=_(
            "Leave blank to use mailing/{key}.html "
            "from within your template directories."
        ))
    subscription_type = models.ForeignKey(
        SubscriptionType, models.SET_NULL, blank=True, null=True,
        verbose_name=_("subscription type"))

    def __str__(self):
        return self.key

    def get_template(self):
        if self.template_file:
            with open(self.template_file.path, 'r') as f:
                template = Template(f.read())
        else:
            template = get_template('mailing/{key}.html'.format(key=self.key))
        return template

    def get_subject(self):
        if self.prefix_subject and SUBJECT_PREFIX:
            return '{} {}'.format(SUBJECT_PREFIX, self.subject)
        else:
            return self.subject

    def is_subscribed(self, email):
        return (not self.subscription_type or
                self.subscription_type.is_subscribed(email))

class CampaignMailHeader(AbstractBaseMailHeader):

    class Meta:
        verbose_name = _("extra header")
        verbose_name_plural = _("extra headers")

    campaign = models.ForeignKey(
        'Campaign', models.CASCADE, related_name='extra_headers')

class CampaignStaticAttachment(AbstractBaseStaticAttachment):

    campaign = models.ForeignKey(
        'Campaign', models.CASCADE, related_name='static_attachments')

class Mail(models.Model):

    class Meta:
        ordering = ['-scheduled_on']
        verbose_name = _("e-mail")
        verbose_name_plural = _("e-mails")

    STATUS_PENDING = 1
    STATUS_SENT = 2
    STATUS_CANCELED = 3
    STATUS_FAILURE = 4
    STATUS_DRAFT = 5
    STATUS_CHOICES = [
        (STATUS_PENDING, _("Pending")),
        (STATUS_SENT, _("Sent")),
        (STATUS_CANCELED, _("Canceled")),
        (STATUS_FAILURE, _("Failure")),
        (STATUS_DRAFT, _("Draft")),
    ]

    campaign = models.ForeignKey(
        'Campaign', models.SET_NULL, blank=True, null=True,
        verbose_name=_("campaign"))
    status = models.PositiveSmallIntegerField(
        choices=STATUS_CHOICES, default=STATUS_DRAFT,
        verbose_name=_("status"))
    scheduled_on = models.DateTimeField(
        default=timezone.now, verbose_name=_("scheduled on"))
    sent_on = models.DateTimeField(
        blank=True, null=True, editable=False, verbose_name=_("sent on"))
    subject = models.CharField(
        max_length=255, verbose_name=_("subject"))
    html_body = models.TextField(
        verbose_name=_("HTML body"))
    text_body = models.TextField(
        blank=True, verbose_name=_("text body"),
        help_text=_("Leave blank to generate from HTML body."))
    failure_reason = models.TextField(
        blank=True, editable=False, verbose_name=_("failure reason"))

    def __str__(self):
        return "[{}] {}".format(self.scheduled_on, self.subject)

    def get_headers(self):
        headers = dict(self.headers.items())
        headers.setdefault("X-Mail-Id", str(self.pk))
        return headers

    def get_attachments(self):
        return list(self.static_attachments.all()) + list(self.dynamic_attachments.all())

    def get_absolute_url(self):
        signer = Signer(salt=MIRROR_SIGNING_SALT)
        signed_pk = signer.sign(str(self.pk))
        return reverse('mailing:mirror', kwargs={'signed_pk': signed_pk})

class MailHeader(AbstractBaseMailHeader):

    class Meta:
        verbose_name = _("header")
        verbose_name_plural = _("headers")

    mail = models.ForeignKey(
        'Mail', models.CASCADE, related_name='headers')

class MailStaticAttachment(AbstractBaseStaticAttachment):

    mail = models.ForeignKey(
        'Mail', models.CASCADE, related_name='static_attachments')

class MailDynamicAttachment(AbstractBaseDynamicAttachment):

    mail = models.ForeignKey(
        'Mail', models.CASCADE, related_name='dynamic_attachments')

class Blacklist(models.Model):

    class Meta:
        verbose_name = _("blacklisted address")
        verbose_name_plural = _("blacklisted addresses")
        ordering = ['-reported_on']

    REASON_OTHER = 1
    REASON_SPAM = 2
    REASON_BLOCKED = 3
    REASON_HARDBOUNCE = 4
    REASON_CHOICES = [
        (REASON_SPAM, _("SPAM")),
        (REASON_BLOCKED, _("Blocked")),
        (REASON_HARDBOUNCE, _("Hard bounce")),
        (REASON_OTHER, _("Other")),
    ]

    email = models.EmailField(
        unique=True, verbose_name=_("e-mail address"))
    reason = models.PositiveSmallIntegerField(
        choices=REASON_CHOICES, default=REASON_OTHER,
        verbose_name=_("reason"))
    verbose_reason = models.CharField(
        max_length=250, blank=True, verbose_name=_("verbose reason"))
    reported_on = models.DateTimeField(
        verbose_name=_("reported on"), auto_now_add=True)

    objects = BlacklistManager()

    def __str__(self):
        return "{} ({})".format(self.email, self.get_reason_display())


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import os
import random
from glob import glob
import csv
import tensorflow as tf
import cv2

class Dataset:
    def __init__(self, datadir, org_height, org_width, org_depth=3, batch_size=32, threads_num=4, type=1, crop=False):
        if type == 1:
            # hollywood
            self.data = glob(os.path.join(datadir, "*.jpg"))
            self.train_csv = "train.csv"
            with open(self.train_csv, "w") as f:
                allnum = len(self.data)
                for i, image in enumerate(self.data):
                    try:
                        print("num: %d %d" % (i, allnum))
                        # img = cv2.imread(image)
                        # height, width, channels = img.shape
                        # if height/width > 1:
                        #     print("wrong image %s" % image)
                        #     continue
                    except Exception as ex:
                        print("broken image %s" % ex)
                        continue
                    f.write(image)
                    f.write("\n")
            print("dataset number: %d" % (len(self.data)))
            self.data_num = len(self.data)
            self.org_height = org_height
            self.org_width = org_width
            self.org_depth = org_depth
            self.threads_num = threads_num
            self.batch_size = batch_size
            self.batch_idxs = len(self.data) / self.batch_size
            self.crop = crop
        elif type == 2:
            # lfw
            self.data = glob(os.path.join(datadir, "*.jpg"))
            self.train_csv = "train.csv"
            with open(self.train_csv, "w") as f:
                for image in self.data:
                    try:
                        img = cv2.imread(image)
                    except Exception as ex:
                        print("broken image %s" % ex)
                        continue
                    f.write(image)
                    f.write("\n")
            print("dataset number: %d" % (len(self.data)))
            self.data_num = len(self.data)
            self.org_height = org_height
            self.org_width = org_width
            self.org_depth = org_depth
            self.threads_num = threads_num
            self.batch_size = batch_size
            self.batch_idxs = len(self.data) / self.batch_size
            self.crop = crop

    def _generate_image_and_label_batch(self, image, min_queue_examples):
        num_preprocess_threads = self.threads_num
        images = tf.train.shuffle_batch(
            [image],
            batch_size=self.batch_size,
            num_threads=num_preprocess_threads,
            capacity=min_queue_examples + 3 * self.batch_size,
            min_after_dequeue=min_queue_examples
        )
        # Display the training images in the visualizer
        # tf.image_summary('images', images, max_images=BATCH_SIZE)
        return images

    def get_inputs(self, input_height, input_width):
        filename_queue = tf.train.string_input_producer([self.train_csv], shuffle=True)
        reader = tf.TextLineReader()
        _, serialized_example = reader.read(filename_queue)
        filename = tf.decode_csv(serialized_example, [["path"]])
        jpeg = tf.read_file(filename[0])
        image = tf.image.decode_jpeg(jpeg, channels=3)

        if self.crop:
            image = tf.image.resize_images(image, [self.org_height, self.org_width])
            # resize to input size
            image = tf.image.crop_to_bounding_box(image, offset_height=20, offset_width=20, target_height=input_height, target_width=input_width)
            image = tf.cast(image, tf.float32)
            image = tf.image.resize_images(image, (input_height, input_width))
        else:
            image = tf.cast(image, tf.float32)
            image = tf.image.resize_images(image, (input_height, input_width))
        image = tf.subtract(tf.div(image, 127.5), 1.0)
        min_fraction_of_examples_in_queue = 0.4
        min_queue_examples = int(10000 * min_fraction_of_examples_in_queue)
        print ('filling queue with %d train images before starting to train. This will take a few minutes.' % min_queue_examples)
        return self._generate_image_and_label_batch(image, min_queue_examples)

def load_csv(path):
    print("load csv: %s" % (path))
    images = []
    with open(path, 'r') as f:
        rows = csv.reader(f)
        for row in rows:
            images.append(row)
    return images


from django.urls import path
from .views import StatusList, StatusEdit, StatusDelete, StatusNovo

urlpatterns = [
    path('', StatusList.as_view(), name='list_status'),
    path('editar/<int:pk>', StatusEdit.as_view(), name='update_status'),
    path('delete/<int:pk>', StatusDelete.as_view(), name='delete_status'),
    path('novo', StatusNovo.as_view(), name='create_status'),

]


#! /usr/bin/env python
class Solution:
  # @param {string} s
  # @return {integer}
  def lengthOfLastWord(self, s):
    L = s.split(' ')
    L.reverse()
    for i in range(0, len(L)):
      if len(L[i]) != 0:
        return len(L[i])
    return 0

# Note that reversed() function return a strange object not a sequence
# range(m, n) doesn't include n, from m to n-1
# Another thing is that s.split() will return more empty strings than
# than expected when there are some continuous empty spaces in s


import pandas as pd
import numpy as np
import tensorflow as tf
import os
from keras.preprocessing.image import ImageDataGenerator, array_to_img, img_to_array, load_img
import random
from skimage.transform import resize

from keras.models import Model, load_model
from keras.layers import Input,Dropout,BatchNormalization,Activation,Add
from keras.layers.core import Lambda
from keras.layers.convolutional import Conv2D, Conv2DTranspose
from keras.layers.pooling import MaxPooling2D
from keras.layers.merge import concatenate
from keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from keras import backend as K
#
def mean_iou(y_true, y_pred):
    prec = []
    for t in np.arange(0.5, 1.0, 0.05):
        y_pred_ = tf.to_int32(y_pred > t)
        score, up_opt = tf.metrics.mean_iou(y_true, y_pred_, 2)
        K.get_session().run(tf.local_variables_initializer())
        with tf.control_dependencies([up_opt]):
            score = tf.identity(score)
        prec.append(score)
    return K.mean(K.stack(prec), axis=0)
#
im_width = 128
im_height = 128
im_chan = 1

path_train = '/home/luxuyan2016/SaltMaskCompetition/train/'
train_ids = next(os.walk(path_train+"images"))[2]

# Get and resize train images and masks
X_train = np.zeros((len(train_ids), im_height, im_width, im_chan), dtype=np.uint8)
Y_train = np.zeros((len(train_ids), im_height, im_width, 1), dtype=np.bool)

for n, id_ in enumerate(train_ids):
    path = path_train
    img = load_img(path + '/images/' + id_)
    x = img_to_array(img)[:,:,1]
    x = resize(x, (128, 128, 1), mode='constant', preserve_range=True)
    X_train[n] = x
    mask = img_to_array(load_img(path + '/masks/' + id_))[:,:,1]
    Y_train[n] = resize(mask, (128, 128, 1), mode='constant', preserve_range=True)

ACTIVATION = "relu"

def convolution_block(x, filters, size, strides=(1,1), padding='same', activation=True):
    x = Conv2D(filters, size, strides=strides, padding=padding)(x)
    x = BatchNormalization()(x)
    if activation == True:
        x = Activation(ACTIVATION)(x)
    return x

def residual_block(blockInput, num_filters=16):
    x = Activation(ACTIVATION)(blockInput)
    x = BatchNormalization()(x)
    x = convolution_block(x, num_filters, (3,3))
    x = convolution_block(x, num_filters, (3,3), activation=False)
    x = Add()([x, blockInput])
    return x

# Build model
def build_model(input_layer, start_neurons, DropoutRatio = 0):
    # 128 -> 64
    conv1 = Conv2D(start_neurons * 1, (3, 3), activation=None, padding="same")(input_layer)
    conv1 = residual_block(conv1, start_neurons * 1)
    conv1 = residual_block(conv1, start_neurons * 1)
    conv1 = Activation(ACTIVATION)(conv1)
    pool1 = MaxPooling2D((2, 2))(conv1)
    pool1 = Dropout(DropoutRatio / 2)(pool1)

    # 64 -> 32
    conv2 = Conv2D(start_neurons * 2, (3, 3), activation=None, padding="same")(pool1)
    conv2 = residual_block(conv2, start_neurons * 2)
    conv2 = residual_block(conv2, start_neurons * 2)
    conv2 = Activation(ACTIVATION)(conv2)
    pool2 = MaxPooling2D((2, 2))(conv2)
    pool2 = Dropout(DropoutRatio)(pool2)

    # 32 -> 16
    conv3 = Conv2D(start_neurons * 4, (3, 3), activation=None, padding="same")(pool2)
    conv3 = residual_block(conv3, start_neurons * 4)
    conv3 = residual_block(conv3, start_neurons * 4)
    conv3 = Activation(ACTIVATION)(conv3)
    pool3 = MaxPooling2D((2, 2))(conv3)
    pool3 = Dropout(DropoutRatio)(pool3)

    # 16 -> 8
    conv4 = Conv2D(start_neurons * 8, (3, 3), activation=None, padding="same")(pool3)
    conv4 = residual_block(conv4, start_neurons * 8)
    conv4 = residual_block(conv4, start_neurons * 8)
    conv4 = Activation(ACTIVATION)(conv4)
    pool4 = MaxPooling2D((2, 2))(conv4)
    pool4 = Dropout(DropoutRatio)(pool4)

    # Middle
    convm = Conv2D(start_neurons * 16, (3, 3), activation=None, padding="same")(pool4)
    convm = residual_block(convm, start_neurons * 16)
    convm = residual_block(convm, start_neurons * 16)
    convm = Activation(ACTIVATION)(convm)

    # 8 -> 16
    deconv4 = Conv2DTranspose(start_neurons * 8, (2, 2), strides=(2, 2), padding="same")(convm)
    uconv4 = concatenate([deconv4, conv4])
    uconv4 = Dropout(DropoutRatio)(uconv4)

    uconv4 = Conv2D(start_neurons * 8, (3, 3), activation=None, padding="same")(uconv4)
    uconv4 = residual_block(uconv4, start_neurons * 8)
    uconv4 = residual_block(uconv4, start_neurons * 8)
    uconv4 = Activation(ACTIVATION)(uconv4)

    # 16 -> 32
    deconv3 = Conv2DTranspose(start_neurons * 4, (2, 2), strides=(2, 2), padding="same")(uconv4)
    # deconv3 = Conv2DTranspose(start_neurons * 4, (3, 3), strides=(2, 2), padding="valid")(uconv4)
    uconv3 = concatenate([deconv3, conv3])
    uconv3 = Dropout(DropoutRatio)(uconv3)

    uconv3 = Conv2D(start_neurons * 4, (3, 3), activation=None, padding="same")(uconv3)
    uconv3 = residual_block(uconv3, start_neurons * 4)
    uconv3 = residual_block(uconv3, start_neurons * 4)
    uconv3 = Activation(ACTIVATION)(uconv3)

    # 32 -> 64
    deconv2 = Conv2DTranspose(start_neurons * 2, (2, 2), strides=(2, 2), padding="same")(uconv3)
    uconv2 = concatenate([deconv2, conv2])

    uconv2 = Dropout(DropoutRatio)(uconv2)
    uconv2 = Conv2D(start_neurons * 2, (3, 3), activation=None, padding="same")(uconv2)
    uconv2 = residual_block(uconv2, start_neurons * 2)
    uconv2 = residual_block(uconv2, start_neurons * 2)
    uconv2 = Activation(ACTIVATION)(uconv2)

    # 64 -> 128
    deconv1 = Conv2DTranspose(start_neurons * 1, (2, 2), strides=(2, 2), padding="same")(uconv2)
    # deconv1 = Conv2DTranspose(start_neurons * 1, (3, 3), strides=(2, 2), padding="valid")(uconv2)
    uconv1 = concatenate([deconv1, conv1])

    uconv1 = Dropout(DropoutRatio)(uconv1)
    uconv1 = Conv2D(start_neurons * 1, (3, 3), activation=None, padding="same")(uconv1)
    uconv1 = residual_block(uconv1, start_neurons * 1)
    uconv1 = residual_block(uconv1, start_neurons * 1)
    uconv1 = Activation(ACTIVATION)(uconv1)

    uconv1 = Dropout(DropoutRatio / 2)(uconv1)
    output_layer = Conv2D(1, (1, 1), padding="same", activation="sigmoid")(uconv1)

    return output_layer
#
# model
input_layer = Input((im_height, im_width, im_chan))
s = Lambda(lambda x: x / 255)(input_layer)
output_layer = build_model(s, 16, 0.5)
#
model = Model(input_layer, output_layer)
model.summary()
model.compile(loss="binary_crossentropy", optimizer="adam", metrics=["acc", mean_iou])
early_stopping = EarlyStopping(monitor='val_acc', mode = 'max', patience=20, verbose=1)
model_checkpoint = ModelCheckpoint("./unet_best1.model", monitor='val_acc',
                                   mode = 'max', save_best_only=True, verbose=1)
reduce_lr = ReduceLROnPlateau(monitor='val_acc', mode = 'max',factor=0.2, patience=5, min_lr=0.00001, verbose=1)
# reduce_lr = ReduceLROnPlateau(factor=0.2, patience=5, min_lr=0.00001, verbose=1)

epochs = 200
batch_size = 32

history = model.fit(X_train, Y_train,
                    validation_split=0.1,
                    epochs=epochs,
                    batch_size=batch_size,
                    callbacks=[early_stopping, model_checkpoint, reduce_lr],
                    verbose=1)


"""Turtle World Demo"""
from swampy.TurtleWorld import *

def position(turtle, start_x, start_y, angle):
	turtle.x = start_x
	turtle.y = start_y
	turtle.heading = angle

def draw_line(turtle, line_length):
	turtle.fd(line_length)

def turn_right(turtle, angle):
	turtle.rt(angle)

def turtle_text(letter):
	position(beth, -150, -100, 60)
	draw_line(beth, 200)
	turn_right(beth, 120)
	draw_line(beth, 200)
	position(beth, )

world = TurtleWorld()
beth = Turtle()
beth.set_pen_color = 'red'
turtle_text('A')
wait_for_user()


load("@io_bazel_rules_go//go/private:common.bzl",
    "go_importpath",
)
load("@io_bazel_rules_go//go/private:mode.bzl",
    "RACE_MODE",
    "NORMAL_MODE",
)
load("@io_bazel_rules_go//go/private:providers.bzl",
    "get_library",
    "GoLibrary",
    "GoEmbed",
)
load("@io_bazel_rules_go//go/private:rules/prefix.bzl",
    "go_prefix_default",
)

def _go_proto_library_impl(ctx):
  go_proto_toolchain = ctx.toolchains[ctx.attr._toolchain]
  importpath = go_importpath(ctx)
  go_srcs = go_proto_toolchain.compile(ctx,
    proto_toolchain = ctx.toolchains["@io_bazel_rules_go//proto:proto"],
    go_proto_toolchain = go_proto_toolchain,
    lib = ctx.attr.proto,
    importpath = importpath,
  )
  go_toolchain = ctx.toolchains["@io_bazel_rules_go//go:toolchain"]
  golib, goembed = go_toolchain.actions.library(ctx,
      go_toolchain = go_toolchain,
      srcs = go_srcs,
      deps = ctx.attr.deps + go_proto_toolchain.deps,
      embed = ctx.attr.embed,
      want_coverage = ctx.coverage_instrumented(),
      importpath = importpath,
  )
  return [
      golib, goembed,
      DefaultInfo(
          files = depset([get_library(golib, NORMAL_MODE)]),
          runfiles = golib.runfiles,
      ),
      OutputGroupInfo(
          race = depset([get_library(golib, RACE_MODE)]),
      ),
  ]

go_proto_library = rule(
    _go_proto_library_impl,
    attrs = {
        "proto": attr.label(mandatory=True, providers=["proto"]),
        "deps": attr.label_list(providers = [GoLibrary]),
        "importpath": attr.string(),
        "embed": attr.label_list(providers = [GoEmbed]),
        "gc_goopts": attr.string_list(),
        "_go_prefix": attr.label(default = go_prefix_default),
        "_go_toolchain_flags": attr.label(default=Label("@io_bazel_rules_go//go/private:go_toolchain_flags")),
        "_toolchain": attr.string(default = "@io_bazel_rules_go//proto:go_proto"),
    },
    toolchains = [
        "@io_bazel_rules_go//go:toolchain",
        "@io_bazel_rules_go//proto:proto",
        "@io_bazel_rules_go//proto:go_proto",
    ],
)
"""
go_proto_library is a rule that takes a proto_library (in the proto
attribute) and produces a go library for it.
"""

go_grpc_library = rule(
    _go_proto_library_impl,
    attrs = {
        "proto": attr.label(mandatory=True, providers=["proto"]),
        "deps": attr.label_list(providers = [GoLibrary]),
        "importpath": attr.string(),
        "embed": attr.label_list(providers = [GoEmbed]),
        "gc_goopts": attr.string_list(),
        "_go_prefix": attr.label(default = go_prefix_default),
        "_toolchain": attr.string(default = "@io_bazel_rules_go//proto:go_grpc"),
        "_go_toolchain_flags": attr.label(default=Label("@io_bazel_rules_go//go/private:go_toolchain_flags")),
    },
    toolchains = [
        "@io_bazel_rules_go//go:toolchain",
        "@io_bazel_rules_go//proto:proto",
        "@io_bazel_rules_go//proto:go_grpc",
    ],
)
"""
go_grpc_library is a rule that takes a proto_library (in the proto
attribute) and produces a go library that includes grpc services for it.
"""

def proto_register_toolchains():
  native.register_toolchains(
    "@io_bazel_rules_go//proto:proto",
    "@io_bazel_rules_go//proto:go_proto",
    "@io_bazel_rules_go//proto:go_grpc",
  )


class GenomicPrefixSumMap:
    def __init__(self, S):
        self.prefixSumMap = self.getPrefixSumMap(S)

    def getPrefixSumMap(self, genomicString):
        result = [[], [], [], []]
        sums = [0, 0, 0, 0]
        for index in range(4):
            result[index].append(sums[index])
        for factor in genomicString:
            if factor == 'A':
                sums[0] += 1
            elif factor == 'C':
                sums[1] += 1
            elif factor == 'G':
                sums[2] += 1
            else:
                sums[3] += 1
            for index in range(4):
                result[index].append(sums[index])
        return result

    def getMinFactorInRange(self, start, end):
        startFactors = [self.prefixSumMap[index][start] for index in range(4)]
        endFactors = [self.prefixSumMap[index][end+1] for index in range(4)]
        print(startFactors, endFactors)
        for i in range(4):
            if startFactors[i] != endFactors[i]:
                return i + 1
        return 4

def solution(S, P, Q):
    queryLen = len(P)
    result = list()
    prefixSumMap = GenomicPrefixSumMap(S)
    for index in range(queryLen):
        start = P[index]
        end = Q[index]
        result.append(prefixSumMap.getMinFactorInRange(start, end))
    return result

if __name__ == "__main__":
    # S = "CAGCCTA"
    S = "GGGGGGG"
    P = [2, 5, 0, 0, 6, 3]
    Q = [4, 5, 6, 0, 6, 3]
    print(solution(S, P, Q))
    S = "G"
    P = [0]
    Q = [0]
    print(solution(S, P, Q))


class Config(object):
    def __init__(self, fileName):
        servers = []
        policy = {}
        # prepare 10 slots for servers; at most 10 servers can be configed
        for i in range(10):
            servers.append(dict())
        exec(open(fileName).read())
        self.servers = servers

        '''
        urls = config.get('Servers', 'urls')
        for url in urls.strip().split(' '):
            temp = url.strip().split('%')
            self.servers.append({'type': temp[0].lower(), 'url': temp[1]})
        '''
        self.policy = policy

    def display(self):
        for server in self.servers:
            if len(server) != 0:
                print('Server: ' + server['url'] + '(' + server['type'] + ')')
        print(
            'Policy: interval %s, probability %.2f, '
            'percentage %.2f, minperkill %d, '
            'maxperkill %d, minperday %d, '
            'maxperday %d' %
            (self.policy['interval'], self.policy['probability'],
                self.policy['percentage'], self.policy['minperkill'],
                self.policy['maxperkill'], self.policy['minperday'],
                self.policy['maxperday']))


import numpy as np
import scipy.signal as signal

z = np.array( [ -0.8, 1 ] )
p = np.array( [ 0.6 + 0.8j, 0.6 - 0.8j, -1 ] )
k = 0.8

b, a = signal.zpk2tf( z, p, k )

print( "Numerator Polynomial Coefficients =", b )
print( "Denominator Polynomial Coefficients =", a )


#  Minimum Path Sum
#  Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
#
#  Note: You can only move either down or right at any point in time.

#  Solution: DP(i,j) = min(DP(i-1,j), DP(i,j-1)) + grid(i,j)

class Solution:
    # @param grid, a list of lists of integers
    # @return an integer
    def minPathSum(self, grid):
        m = len(grid)
        if m== 0:
            return 0
        n = len(grid[0])
        if n == 0:
            return 0

        for col in range(1, n):
            grid[0][col] += grid[0][col-1]
        for row in range(1, m):
            grid[row][0] += grid[row-1][0]

        for row in range(1,m):
            for col in range(1,n):
                grid[row][col] += min(grid[row-1][col], grid[row][col-1])
        return grid[-1][-1]


# Copyright (c) 2014 CodiLime
__author__ = 'Piotr Niedzwiedz <piotr@codilime.com>'

import Image
import argparse
import logging
import os

import ch24.common.helpers

LOG = logging.getLogger()

def _common_img_format(filename):
    COMMON_IMG_FORMATS = ['.jpg', '.jpeg', '.png']
    _, extension = os.path.splitext(filename)
    extension = extension.lower()
    return extension in COMMON_IMG_FORMATS

def image_from_imf(lines):
    """Creates Matrix Image from IMF
    """
    RGBA_OPAQUE = 255
    height, width, color_model = lines[0].split()
    height = eval(height)
    width = eval(width)
    color_model = color_model.lower()
    assert(color_model in ['rgb', 'rgba', 'grayscale'])
    img = Image.new("RGBA", (width, height), "white")
    pixels = img.load()
    for y in xrange(height):
        line_pixels = lines[y+1].split()
        for x in xrange(width):
            if color_model == 'rgb':
                pixel = line_pixels[:3]
                line_pixels = line_pixels[3:]
                pixel.append(RGBA_OPAQUE)
            elif color_model == 'rgba':
                pixel = line_pixels[:4]
                line_pixels = line_pixels[4:]
            else:  # grayscale
                pixel = line_pixels[:1]
                line_pixels = line_pixels[1:]
                pixel = pixel[0], pixel[0], pixel[0], RGBA_OPAQUE
            assert len(pixel) == 4
            pixels[(x, y)] = tuple(map(int, pixel))
    return img

def load_img_from_file(filename):
    if _common_img_format(filename):
        LOG.debug('Loading from file in common image format.')
        image = Image.open(filename)
        image = image.convert('RGBA')
    else:
        LOG.debug('Loading from file in Integer matrix format.')
        fd = open(filename, 'r')
        image = image_from_imf(fd.readlines())
    return image

def img_to_imf(image, color_model):
    width, height = image.size
    lines = []
    lines.append('{} {} {}\n'.format(height, width, color_model))
    pixels = image.load()
    for y in xrange(height):
        line = []
        for x in xrange(width):
            pixel = pixels[(x,y)]
            if isinstance(pixel, tuple):
                line.append(' '.join(map(str, pixel)))
            else:
                line.append(str(pixel))
        lines.append(' '.join(line) + '\n')
    return lines

def save_to_file(filename, image, color_model):
    if color_model == 'grayscale':
        image = image.convert('L')
    elif color_model == 'rgb':
        image = image.convert('RGB')
    else:
        assert color_model == 'rgba'
    if _common_img_format(filename):
        LOG.debug('Saving to file in common image format.')
        image.save(filename)
    else:
        LOG.debug('Loading from file in Integer matrix format.')
        try:
            fd = open(filename, 'w')
            fd.writelines(img_to_imf(image, color_model))
        finally:
            fd.close()

def main():
    parser = argparse.ArgumentParser(description='Image converter.')
    parser.add_argument('input_file', metavar='input_file', type=str, help='path to the input file')
    parser.add_argument('output_file', metavar='output_file', type=str, help='path to the output file')
    parser.add_argument('color_model',
                        metavar='color_model',
                        type=str,
                        help='has to have one of the following values: "grayscale", "rgb" and "rgba".')
    parser.add_argument('-d',
                        '--debug',
                        dest='debug',
                        action='store_const',
                        const=True,
                        default=False,
                        help='print debugging information')
    args = parser.parse_args()

    ch24.common.helpers.set_up_logging(args.debug)

    image = load_img_from_file(args.input_file)
    save_to_file(args.output_file, image, args.color_model.lower())


colors = [
{
"colors": "red",
"values": "#f00"
},
{
"colors": "green",
"values": "#0f0"
},
{
"colors": "blue",
"values": "#00f"
},
{
"colors": "cyan",
"values": "#0ff"
},
{
"colors": "magenta",
"values": "#f0f"
},
{
"colors": "yellow",
"values": "#ff0"
},
{
"colors": "black",
"values": "#000"
}
]

for item in colors:
    #validating each item is dictionary Or not
    if isinstance(item,dict):
        #reading all values from dict
        info = list(item.values())
        print(info[0],info[1])


#
# bsh.py
#
# Copyright © 2004-2013, 2016 Monotype Imaging Inc. All Rights Reserved.
#

"""
Support for reading and generating binary-search headers, as are used in
several places in TrueType.
"""

# System imports
import logging

# Other imports
from fontio3 import utilitiesbackend
from fontio3.fontdata import simplemeta

# -----------------------------------------------------------------------------

#
# Constants
#

ERR_CODES = ('V0654', 'V0655', 'V0656')
ERR_STRINGS = ("searchRange", "entrySelector", "rangeShift")

# -----------------------------------------------------------------------------

#
# Functions
#

def binsearchheader(n, unitsize, **kwArgs):
    """
    Returns a string with 4 16-bit binary values: nUnits, searchRange,
    entrySelector and rangeShift.

    >>> utilities.hexdump(binsearchheader(200, 6))
           0 | 00C8 0300 0007 01B0                      |........        |

    >>> utilities.hexdump(binsearchheader(200, 6, use32Bits=True))
           0 | 0000 00C8 0000 0300  0000 0007 0000 01B0 |................|
    """

    kwArgs['skipUnitSize'] = True
    return BSH(nUnits=n, unitSize=unitsize).binaryString(**kwArgs)

# -----------------------------------------------------------------------------

#
# Classes
#

if 0:
    def __________________(): pass

class BSH(object, metaclass=simplemeta.FontDataMetaclass):
    """
    Objects representing binary-search headers. These are simple objects with
    two attributes, nUnits and unitSize. There are also three read-only
    properties: searchRange, entrySelector, and rangeShift.

    >>> bsh = BSH(nUnits=10, unitSize=6)
    >>> utilities.hexdump(bsh.binaryString())
           0 | 0006 000A 0030 0003  000C                |.....0....      |

    >>> bsh.nUnits = 11
    >>> utilities.hexdump(bsh.binaryString())
           0 | 0006 000B 0030 0003  0012                |.....0....      |

    >>> bsh.nUnits = 0
    >>> utilities.hexdump(bsh.binaryString())
           0 | 0006 0000 0006 0000  0000                |..........      |
    """

    #
    # Class definition variables
    #

    attrSpec = dict(
        unitSize = dict(
            attr_initfunc = (lambda: 2),
            attr_label = "Bytes per unit"),

        nUnits = dict(
            attr_initfunc = (lambda: 1),
            attr_label = "Number of units"),

        _cachedKey = dict(
            attr_ignoreforcomparisons = True),

        _cachedFields = dict(
            attr_ignoreforcomparisons = True))

    attrSorted = ('unitSize', 'nUnits')

    #
    # Methods
    #

    def _getEntrySelector(self):
        """
        >>> bsh = BSH(nUnits=10, unitSize=6)
        >>> print((bsh._getEntrySelector()))
        3
        """
        self._recalc()
        return self._cachedFields[1]

    def _getRangeShift(self):
        """
        >>> bsh = BSH(nUnits=10, unitSize=6)
        >>> print((bsh._getRangeShift()))
        12
        """
        self._recalc()
        return self._cachedFields[2]

    def _getSearchRange(self):
        """
        >>> bsh = BSH(nUnits=0, unitSize=6)
        >>> print((bsh._getSearchRange()))
        6
        """
        self._recalc()
        return self._cachedFields[0]

    entrySelector = property(_getEntrySelector)
    rangeShift = property(_getRangeShift)
    searchRange = property(_getSearchRange)

    def _recalc(self):
        """
        Recalculates (if necessary) the three derived fields of this binary
        search header.
        """

        k = (self.unitSize, self.nUnits)

        if k != self._cachedKey:
            # the following line uses an exceedingly hacky
            # way of computing the base 2 log!
            es = max(0, [k[1] < 2**x for x in range(32)].index(1) - 1)
            sr = (2 ** es) * k[0]
            rs = k[0] * max(0, k[1] - (2 ** es))
            self._cachedFields = (sr, es, rs)
            self._cachedKey = k

    def buildBinary(self, w, **kwArgs):
        """
        Adds the binary data for the BSH object to the specified LinkedWriter.
        The following keyword arguments are optional:

            skipUnitSize    If True, the resulting binary data will only
                            comprise nUnits, searchRange, entrySelector, and
                            rangeShift. If False (the default), unitSize will
                            be included (first).

            use32Bits       Default is False. If True, all operations will use
                            32-bit words instead of 16-bit words.

        >>> d = {'use32Bits': True}
        >>> obj = _testingValues[1]
        >>> utilities.hexdump(obj.binaryString())
               0 | 0006 000A 0030 0003  000C                |.....0....      |

        >>> utilities.hexdump(obj.binaryString(**d))
               0 | 0000 0006 0000 000A  0000 0030 0000 0003 |...........0....|
              10 | 0000 000C                                |....            |
        """

        self._recalc()

        use32Bits = kwArgs.get('use32Bits', False)

        if not kwArgs.get('skipUnitSize', False):
            w.add(("L" if use32Bits else "H"), self.unitSize)

        w.add(("4L" if use32Bits else "4H"), self.nUnits, *self._cachedFields)

    @classmethod
    def fromvalidatedwalker(cls, w, **kwArgs):
        """
        Creates and returns a new BSH object from the specified walker, doing
        source validation. The following optional keyword arguments are
        supported:

            autoSkip        Default is True. If True, 5 words will be read from
                            the walker, even though only the first two words
                            (unitSize and nUnits) will be used. If False, only
                            2 words will be read, so the caller must skip or
                            otherwise process the walker for the remaining
                            three words.

            logger          A logger to which messages will be posted.

            recalcFirst     Default is False. If True, the objects three
                            derived values will be recalculated before the
                            object is returned. If False, only nUnits and
                            unitSize will be set.

            use32Bits       Default is False. If True, all operations will use
                            32-bit words instead of 16-bit words.

        >>> FH = utilities.fromhex
        >>> logger = utilities.makeDoctestLogger("bsh_fvw")
        >>> fvb = BSH.fromvalidatedbytes
        >>> obj = fvb(FH("00 06 00 0A 00 30 00 03 00 0C"), logger=logger)
        bsh_fvw.binsrch header - DEBUG - Walker has 10 remaining bytes.
        >>> fvb(FH("00 06 00 0A 00 00 00 00 00 00"), logger=logger)
        bsh_fvw.binsrch header - DEBUG - Walker has 10 remaining bytes.
        bsh_fvw.binsrch header - ERROR - The searchRange should have a value of 48, but is 0.
        bsh_fvw.binsrch header - ERROR - The entrySelector should have a value of 3, but is 0.
        bsh_fvw.binsrch header - ERROR - The rangeShift should have a value of 12, but is 0.

        >>> s = FH("00 00 00 06 00 00 00 0A 00 00 00 30 00 00 00 03 00 00 00 0C")
        >>> obj = fvb(s, logger=logger, use32Bits=True)
        bsh_fvw.binsrch header - DEBUG - Walker has 20 remaining bytes.
        >>> fvb(s[:-1] + FH("99"), logger=logger, use32Bits=True)
        bsh_fvw.binsrch header - DEBUG - Walker has 20 remaining bytes.
        bsh_fvw.binsrch header - ERROR - The rangeShift should have a value of 12, but is 153.

        >>> s = FH("00 00 00 06 ")
        >>> fvb(s[:-1] + FH("99"), logger=logger, use32Bits=True)
        bsh_fvw.binsrch header - DEBUG - Walker has 4 remaining bytes.
        bsh_fvw.binsrch header - ERROR - Insufficient bytes.

        >>> fvb(s[:-1] + FH("99"), logger=logger, use32Bits=True, autoSkip=False)
        bsh_fvw.binsrch header - DEBUG - Walker has 4 remaining bytes.
        bsh_fvw.binsrch header - ERROR - Insufficient bytes.

        >>> a = FH("00 00 00 06 10 00 00 00 00 01 02 00 ")
        >>> x = fvb(a[:-1] + FH("99"), logger=logger, use32Bits=True, autoSkip=False)
        bsh_fvw.binsrch header - DEBUG - Walker has 12 remaining bytes.
        >>> x.nUnits, x.unitSize
        (268435456, 6)

        >>> b = FH("00 00 00 06 10 00 00 00 00 01 02 00 ")
        >>> x = fvb(b[:-1] + FH("99"), logger=logger, use32Bits=False, autoSkip=False)
        bsh_fvw.binsrch header - DEBUG - Walker has 12 remaining bytes.
        >>> x.nUnits, x.unitSize
        (6, 0)

        >>> c = FH("00 00 00 06 ")
        >>> fvb(c[:-1] + FH("99"), logger=logger, use32Bits=False, autoSkip=True)
        bsh_fvw.binsrch header - DEBUG - Walker has 4 remaining bytes.
        bsh_fvw.binsrch header - ERROR - Insufficient bytes.

        >>> d = FH("00 00 06 ")
        >>> fvb(d[:-1] + FH("99"), logger=logger, use32Bits=False, autoSkip=False)
        bsh_fvw.binsrch header - DEBUG - Walker has 3 remaining bytes.
        bsh_fvw.binsrch header - ERROR - Insufficient bytes.
        """

        logger = kwArgs.pop('logger', logging.getLogger())
        logger = logger.getChild("binsrch header")

        logger.debug((
          'V0001',
          (w.length(),),
          "Walker has %d remaining bytes."))

        use32Bits = kwArgs.get('use32Bits', False)
        autoSkip = kwArgs.get('autoSkip', True)

        if use32Bits:
            if autoSkip:
                if w.length() < 20:
                    logger.error(('V0004', (), "Insufficient bytes."))
                    return None

                t = w.unpack("2L")
                parts = w.unpack("3L")

            else:
                if w.length() < 8:
                    logger.error(('V0004', (), "Insufficient bytes."))
                    return None

                t = w.unpack("2L")
                parts = None

        else:
            if autoSkip:
                if w.length() < 10:
                    logger.error(('V0004', (), "Insufficient bytes."))
                    return None

                t = w.unpack("2H")
                parts = w.unpack("3H")

            else:
                if w.length() < 4:
                    logger.error(('V0004', (), "Insufficient bytes."))
                    return None

                t = w.unpack("2H")
                parts = None

        r = cls(*t)

        if parts is not None:
            r._recalc()
            it = zip(parts, r._cachedFields, ERR_CODES, ERR_STRINGS)

            for part, good, code, s in it:
                if part != good:
                    if all(t):
                        logger.error((
                          code,
                          (s, good, part),
                          "The %s should have a value of %d, but is %d."))

                        r = None

                    else:
                        logger.warning((
                          code,
                          (s, good, part),
                          "The %s should have a value of %d, but is %d. "
                          "However, since nUnits and/or unitSize are zero, "
                          "this is only a warning."))

        return r

    @classmethod
    def fromwalker(cls, w, **kwArgs):
        """
        Creates and returns a new BSH object from the specified walker. The
        following optional keyword arguments are supported:

            autoSkip        Default is True. If True, 5 words will be read from
                            the walker, even though only the first two words
                            (unitSize and nUnits) will be used. If False, only
                            2 words will be read, so the caller must skip or
                            otherwise process the walker for the remaining
                            three words.

            recalcFirst     Default is False. If True, the objects three
                            derived values will be recalculated before the
                            object is returned. If False, only nUnits and
                            unitSize will be set.

            use32Bits       Default is False. If True, all operations will use
                            32-bit words instead of 16-bit words.

        >>> d = {'use32Bits': True}
        >>> obj = _testingValues[1]
        >>> obj == BSH.frombytes(obj.binaryString())
        True
        >>> obj == BSH.frombytes(obj.binaryString(**d), **d)
        True
        """

        use32Bits = kwArgs.get('use32Bits', False)
        r = cls(*w.group(("L" if use32Bits else "H"), 2))

        if kwArgs.get('autoSkip', True):
            w.skip(12 if use32Bits else 6)

        return r

# -----------------------------------------------------------------------------

#
# Test code
#

if 0:
    def __________________(): pass

if __debug__:
    from fontio3 import utilities

    _testingValues = (
        BSH(),
        BSH(nUnits=10, unitSize=6))

def _test():
    import doctest
    doctest.testmod()

if __name__ == "__main__":
    if __debug__:
        _test()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jun  7 12:25:53 2020

@author: israel
"""

class Card():
    def __init__(self, tuple):
        self.value = tuple[0]
        self.suit = tuple[1]
        #self.value = tuple[0:-1]
        #self.suit = tuple[-1]
        #print(f'value: {tuple[0:-1]} suit: {tuple[-1]}')

    @property
    def value(self):
        return self.__value
    @value.setter
    def value(self, value):
        if value == 'T':
            self.__value = 10
        elif value == 'J':
            self.__value = 11
        elif value == 'Q':
            self.__value = 12
        elif value == 'K':
            self.__value = 13
        elif value == 'A':
            self.__value = 14
        else:
            self.__value = int(value)
    @property
    def suit(self):
        return self.__suit
    @suit.setter
    def suit(self, suit):
        self.__suit = suit

    def __str__(self):
        return (str(self.value) + self.suit)

class Hand():
    def __init__(self, cards):
        self.cards = cards
    def __str__(self):
        output = ''
        for c in self.__cards:
            output += str(c)
            output += ' '
        return output

    @property
    def cards(self):
        return self.__cards
    @cards.setter
    def cards(self, cards):
        self.__cards = cards

    # Devuelve array con todos los palos
    def get_suits(self):
        suits = []
        for c in self.cards:
            suits.append(c.suit)
        return suits
    # Devuelve array con todos los valores
    def get_values(self):
        values = []
        for c in self.cards:
            values.append(c.value)
        return values
    # Comprueba si todas las cartas son del mismo palo
    def same_suit(self):
        suits = self.get_suits()
        return suits[0] == suits[1] and suits[1] == suits[2] and \
            suits[2] == suits[3] and suits[3] == suits[4]

    # Ten, Jack, Queen, King, Ace, in same suit
    def is_royal_flush(self):
        suma = 14+13+12+11+10
        s = 0
        for i in self.cards:
            s += i.value
        return (suma == s and self.same_suit())

    # All cards are consecutive values of same suit
    def is_straight_flush(self):
        values = self.get_values()
        values.sort()
        for i in range(0,4):
            if values[i] != values[i+1]-1:
                return 0
        if self.same_suit():
            return values[4]
        return 0

    # Four cards of the same value
    def is_four_of_a_kind(self):
        values = self.get_values()
        values.sort()
        if values[0] == values[1] and values[1] == values[2] and \
            values[2] == values[3]:
            return values[0]
        if values[1] == values[2] and values[2] == values[3] and \
            values[3] == values[4]:
            return values[1]
        return 0

    # Three of a kind and a pair
    def is_full_house(self):
        values = self.get_values()
        values.sort()
        if values.count(values[0]) == 3 and values.count(values[4]) == 2:
            return values[0]
        if values.count(values[0]) == 2 and values.count(values[4]) == 3:
            return values[4]
        return 0

    # All cards of the same suit
    def is_flush(self):
        suits = self.get_suits()
        values = self.get_values()
        values.sort(reverse=True)
        if suits[0] == suits[1] and suits[1] == suits[2] and \
            suits[2] == suits[3] and suits[3] == suits[4]:
                return values
        return 0

    # All cards are consecutive values
    def is_straight(self):
        values = self.get_values()
        values.sort()
        for i in range(0,4):
            if values[i] != values[i+1]-1:
                return 0
        return values[4]

    # Three cards of the same value
    def is_three_of_a_kind(self):
        values = self.get_values()
        for v in values:
            if values.count(v) == 3:
                return v
        return 0

    # Two different pairs
    def is_two_pairs(self):
        values = self.get_values()
        values.sort(reverse=True)
        pairs = []
        for v in values:
            if values.count(v) == 2 and v not in pairs:
                pairs.append(v)
        if len(pairs) == 2:
            return pairs
        else:
            return 0

    # Two cards of the same value
    def is_one_pair(self):
        values = self.get_values()
        for v in values:
            if values.count(v) == 2:
                return v
        return 0

    # Highest value card
    def is_high_card(self):
        values = self.get_values()
        values.sort(reverse=True)
        return values

    # 1: gana jugador 1
    # 2: gana jugador 2
    # 0: ninguno tiene esa mano
    # -1: empate
    def compare_royal_flush(self, h2):
        h2_rf = h2.is_royal_flush()
        if self.is_royal_flush():
            if h2_rf:
                return -1
            return 1
        if h2_rf:
            return 2
        return 0

    def compare_straight_flush(self, h2):
        h1_sf = self.is_straight_flush()
        h2_sf = h2.is_straight_flush()
        if h1_sf == 0 and h2_sf == 0:
            return 0
        if h1_sf > h2_sf:
            return 1
        if h2_sf > h1_sf:
            return 2
        return self.compare_high_card(h2)

    def compare_four_kind(self, h2):
        h1_fk = self.is_four_of_a_kind()
        h2_fk = h2.is_four_of_a_kind()
        if h1_fk == 0 and h2_fk == 0:
            return 0
        if h1_fk > h2_fk:
            return 1
        if h2_fk > h1_fk:
            return 2
        return self.compare_high_card(h2)

    def compare_full_house(self, h2):
        h1_fh = self.is_full_house()
        h2_fh = h2.is_full_house()
        print(f'h1: {h1_fh}  h2: {h2_fh}')
        if h1_fh == 0 and h2_fh == 0:
            return 0
        if h1_fh > h2_fh:
            return 1
        if h1_fh < h2_fh:
            return 2

    def compare_flush(self, h2):
        h1_fl = self.is_flush()
        h2_fl = h2.is_flush()
        if h1_fl == 0 and h2_fl == 0:
            return 0
        if h1_fl == 0 and h2_fl != 0:
            return 2
        if h1_fl != 0 and h2_fl == 0:
            return 1
        for i in range(0,len(h1_fl)):
            if h1_fl[i] > h2_fl[i]:
                return 1
            if h1_fl[i] < h2_fl[i]:
                return 2
        return -1

    def compare_straight(self, h2):
        h1_st = self.is_straight()
        h2_st = h2.is_straight()
        if h1_st == 0 and h2_st == 0:
            return 0
        if h1_st > h2_st:
            return 1
        if h1_st < h2_st:
            return 2
        return -1

    def compare_three_kind(self, h2):
        h1_tk = self.is_three_of_a_kind()
        h2_tk = h2.is_three_of_a_kind()
        if h1_tk == 0 and h2_tk == 0:
            return 0
        if h1_tk > h2_tk:
            return 1
        if h1_tk < h2_tk:
            return 2
        return -1

    def compare_two_pairs(self, h2):
        h1_tp = self.is_two_pairs()
        h2_tp = h2.is_two_pairs()
        if h1_tp == 0 and h2_tp == 0:
            return 0
        if h1_tp == 0:
            return 2
        if h2_tp == 0:
            return 1
        for i in range(0,len(h1_tp)):
            if h1_tp[i] > h2_tp[i]:
                return 1
            if h1_tp[i] < h2_tp[i]:
                return 2
        return self.compare_high_card(h2)

    def compare_one_pair(self, h2):
        h1_op = self.is_one_pair()
        h2_op = h2.is_one_pair()
        if h1_op == 0 and h2_op == 0:
            return 0
        if h1_op > h2_op:
            return 1
        if h1_op < h2_op:
            return 2
        return self.compare_high_card(h2)

    def compare_high_card(self, h2):
        h1_hc = self.is_high_card()
        h2_hc = h2.is_high_card()
        for i in range(0,len(h1_hc)):
            if h1_hc[i] > h2_hc[i]:
                return 1
            if h1_hc[i] < h2_hc[i]:
                return 2
        return -1


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

import numpy as np

from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.python.framework import errors
from tensorflow.python.framework import test_util
from tensorflow.python.ops import array_ops
from tensorflow.python.ops import gen_linalg_ops
from tensorflow.python.ops import gradient_checker_v2
from tensorflow.python.ops import linalg_ops
from tensorflow.python.ops import math_ops
from tensorflow.python.ops import random_ops
from tensorflow.python.ops import sort_ops
from tensorflow.python.platform import test

def _AddTest(test_class, op_name, testcase_name, fn):
  test_name = "_".join(["test", op_name, testcase_name])
  if hasattr(test_class, test_name):
    raise RuntimeError("Test %s defined more than once" % test_name)
  setattr(test_class, test_name, fn)

class EigTest(test.TestCase):

  @test_util.run_deprecated_v1
  def testWrongDimensions(self):
    # The input to self_adjoint_eig should be a tensor of
    # at least rank 2.
    scalar = constant_op.constant(1.)
    with self.assertRaises(ValueError):
      linalg_ops.eig(scalar)
    vector = constant_op.constant([1., 2.])
    with self.assertRaises(ValueError):
      linalg_ops.eig(vector)

  @test_util.run_deprecated_v1
  def testConcurrentExecutesWithoutError(self):
    all_ops = []
    with self.session():
      for compute_v_ in True, False:
        matrix1 = random_ops.random_normal([5, 5], seed=42)
        matrix2 = random_ops.random_normal([5, 5], seed=42)
        if compute_v_:
          e1, v1 = linalg_ops.eig(matrix1)
          e2, v2 = linalg_ops.eig(matrix2)
          all_ops += [e1, v1, e2, v2]
        else:
          e1 = linalg_ops.eigvals(matrix1)
          e2 = linalg_ops.eigvals(matrix2)
          all_ops += [e1, e2]
      val = self.evaluate(all_ops)
      self.assertAllEqual(val[0], val[2])
      # The algorithm is slightly different for compute_v being True and False,
      # so require approximate equality only here.
      self.assertAllClose(val[2], val[4])
      self.assertAllEqual(val[4], val[5])
      self.assertAllEqual(val[1], val[3])

  def testMatrixThatFailsWhenFlushingDenormsToZero(self):
    # Test a 32x32 matrix which is known to fail if denorm floats are flushed to
    # zero.
    matrix = np.genfromtxt(
        test.test_src_dir_path(
            "python/kernel_tests/linalg/testdata/"
            "self_adjoint_eig_fail_if_denorms_flushed.txt")).astype(np.float32)
    self.assertEqual(matrix.shape, (32, 32))
    matrix_tensor = constant_op.constant(matrix)
    with self.session() as _:
      (e, v) = self.evaluate(linalg_ops.self_adjoint_eig(matrix_tensor))
      self.assertEqual(e.size, 32)
      self.assertAllClose(
          np.matmul(v, v.transpose()), np.eye(32, dtype=np.float32), atol=2e-3)
      self.assertAllClose(matrix,
                          np.matmul(np.matmul(v, np.diag(e)), v.transpose()))

  def testMismatchedDtypes(self):
    tensor = constant_op.constant([[0, 1], [2, 3]], dtype=dtypes_lib.float32)
    with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                "Invalid output dtype"):
      self.evaluate(
          gen_linalg_ops.eig(
              input=tensor,
              Tout=dtypes_lib.complex128,  # Expected dtype: complex64.
              compute_v=True))

def SortEigenValues(e):
  perm = np.argsort(e.real + e.imag, -1)
  return np.take(e, perm, -1)

def SortEigenDecomposition(e, v):
  if v.ndim < 2:
    return e, v
  perm = np.argsort(e.real + e.imag, -1)
  return np.take(e, perm, -1), np.take(v, perm, -1)

def EquilibrateEigenVectorPhases(x, y):
  """Equilibrate the phase of the Eigenvectors in the columns of `x` and `y`.

  Eigenvectors are only unique up to an arbitrary phase. This function rotates x
  such that it matches y. Precondition: The columns of x and y differ by a
  multiplicative complex phase factor only.

  Args:
    x: `np.ndarray` with Eigenvectors
    y: `np.ndarray` with Eigenvectors

  Returns:
    `np.ndarray` containing an equilibrated version of x.
  """
  phases = np.sum(np.conj(x) * y, -2, keepdims=True)
  phases /= np.abs(phases)
  return phases * x

def _GetEigTest(dtype_, shape_, compute_v_):

  def CompareEigenVectors(self, x, y, tol):
    x = EquilibrateEigenVectorPhases(x, y)
    self.assertAllClose(x, y, atol=tol)

  def CompareEigenDecompositions(self, x_e, x_v, y_e, y_v, tol):
    num_batches = int(np.prod(x_e.shape[:-1]))
    n = x_e.shape[-1]
    x_e = np.reshape(x_e, [num_batches] + [n])
    x_v = np.reshape(x_v, [num_batches] + [n, n])
    y_e = np.reshape(y_e, [num_batches] + [n])
    y_v = np.reshape(y_v, [num_batches] + [n, n])
    for i in range(num_batches):
      x_ei, x_vi = SortEigenDecomposition(x_e[i, :], x_v[i, :, :])
      y_ei, y_vi = SortEigenDecomposition(y_e[i, :], y_v[i, :, :])
      self.assertAllClose(x_ei, y_ei, atol=tol, rtol=tol)
      CompareEigenVectors(self, x_vi, y_vi, tol)

  def Test(self):
    np.random.seed(1)
    n = shape_[-1]
    batch_shape = shape_[:-2]
    np_dtype = dtype_.as_numpy_dtype

    def RandomInput():
      # Most matrices are diagonalizable
      a = np.random.uniform(
          low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
      if dtype_.is_complex:
        a += 1j * np.random.uniform(
            low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
      a = np.tile(a, batch_shape + (1, 1))
      return a

    if dtype_ in (dtypes_lib.float32, dtypes_lib.complex64):
      atol = 1e-4
    else:
      atol = 1e-12

    a = RandomInput()
    np_e, np_v = np.linalg.eig(a)
    with self.session():
      if compute_v_:
        tf_e, tf_v = linalg_ops.eig(constant_op.constant(a))

        # Check that V*diag(E)*V^(-1) is close to A.
        a_ev = math_ops.matmul(
            math_ops.matmul(tf_v, array_ops.matrix_diag(tf_e)),
            linalg_ops.matrix_inverse(tf_v))
        self.assertAllClose(self.evaluate(a_ev), a, atol=atol)

        # Compare to numpy.linalg.eig.
        CompareEigenDecompositions(self, np_e, np_v, self.evaluate(tf_e),
                                   self.evaluate(tf_v), atol)
      else:
        tf_e = linalg_ops.eigvals(constant_op.constant(a))
        self.assertAllClose(
            SortEigenValues(np_e),
            SortEigenValues(self.evaluate(tf_e)),
            atol=atol)

  return Test

class EigGradTest(test.TestCase):
  pass  # Filled in below

def _GetEigGradTest(dtype_, shape_, compute_v_):

  def Test(self):
    np.random.seed(1)
    n = shape_[-1]
    batch_shape = shape_[:-2]
    np_dtype = dtype_.as_numpy_dtype

    def RandomInput():
      # Most matrices are diagonalizable
      a = np.random.uniform(
          low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
      if dtype_.is_complex:
        a += 1j * np.random.uniform(
            low=-1.0, high=1.0, size=n * n).reshape([n, n]).astype(np_dtype)
      a = np.tile(a, batch_shape + (1, 1))
      return a

    # Optimal stepsize for central difference is O(epsilon^{1/3}).
    epsilon = np.finfo(np_dtype).eps
    delta = 0.1 * epsilon**(1.0 / 3.0)
    # tolerance obtained by looking at actual differences using
    # np.linalg.norm(theoretical-numerical, np.inf) on -mavx build
    # after discarding one random input sample
    _ = RandomInput()
    if dtype_ in (dtypes_lib.float32, dtypes_lib.complex64):
      tol = 1e-2
    else:
      tol = 1e-7
    with self.session():

      def Compute(x):
        e, v = linalg_ops.eig(x)

        # We sort eigenvalues by e.real+e.imag to have consistent
        # order between runs
        b_dims = len(e.shape) - 1
        idx = sort_ops.argsort(math_ops.real(e) + math_ops.imag(e), axis=-1)
        e = array_ops.gather(e, idx, batch_dims=b_dims)
        v = array_ops.gather(v, idx, batch_dims=b_dims)

        # (complex) Eigenvectors are only unique up to an arbitrary phase
        # We normalize the vectors such that the first component has phase 0.
        top_rows = v[..., 0:1, :]
        angle = -math_ops.angle(top_rows)
        phase = math_ops.complex(math_ops.cos(angle), math_ops.sin(angle))
        v *= phase
        return e, v

      if compute_v_:
        funcs = [lambda x: Compute(x)[0], lambda x: Compute(x)[1]]
      else:
        funcs = [linalg_ops.eigvals]

      for f in funcs:
        theoretical, numerical = gradient_checker_v2.compute_gradient(
            f, [RandomInput()], delta=delta)
        self.assertAllClose(theoretical, numerical, atol=tol, rtol=tol)

  return Test

if __name__ == "__main__":
  dtypes_to_test = [
      dtypes_lib.float32, dtypes_lib.float64, dtypes_lib.complex64,
      dtypes_lib.complex128
  ]
  for compute_v in True, False:
    for dtype in dtypes_to_test:
      for size in 1, 2, 5, 10:
        for batch_dims in [(), (3,)] + [(3, 2)] * (max(size, size) < 10):
          shape = batch_dims + (size, size)
          name = "%s_%s_%s" % (dtype.name, "_".join(map(str, shape)), compute_v)
          _AddTest(EigTest, "Eig", name, _GetEigTest(dtype, shape, compute_v))

          if dtype not in [dtypes_lib.float32, dtypes_lib.float64]:
            _AddTest(EigGradTest, "EigGrad", name,
                     _GetEigGradTest(dtype, shape, compute_v))
  test.main()


import pandas as pd
import numpy as np
import glob
import os
import subprocess

ibm = pd.read_csv('../data/ibm.us.txt')
df = ibm
ibm_days = df[(df['Date'] > '1995-01-01') & (df['Date'] < '2018-01-01')]
days = list(ibm_days['Date'])
types = ['Open', 'High', 'Low', 'Close', 'Volume']
stocks = ['aes', 'aep', 'cnp', 'ed', 'd', 'duk', 'eix', 'exc', 'fe',
             'ni', 'pcg', 'peg', 'so']

dropped = []

stocks = np.array(stocks + dropped)

data = np.zeros( (len(stocks), len(days), len(types)) )

for i, file in enumerate(stocks):
    file = pd.read_csv('../data/' + file + '.us.txt')

    for j, d in enumerate(days):
        # for k, t in enumerate(types):
        day_data = file[ file['Date'] == d ]
        if not day_data.empty:
            data[i, j, :] = day_data.values[0, 1:6]

print(data.shape[0])

np.save('../data/dowset_utility.npy', data)


# -*- coding: utf-8 -*-
"""
Created on Thu Mar 30 12:26:41 2017

@author: mqbpwbe2
"""

from multiprocessing.dummy import Pool
from pathlib import Path
from updash_lib.read_spectrum import read_spectrum
import numpy as np
import matplotlib.pyplot as plt
import datetime

fpath = 'Spectra/2017-09-06/spectro_gui_out(1)/USB2+H15972/spectra/spectrum_'

start = 0
stop = 243
global ind
ind = 300
global val
val = np.ndarray(2)

def get_val(i):

    n = '{num:05d}'.format(num=i)
    # Construct full filepath
    fname = fpath + n + '.txt'

    # Check file exists, if true then read
    if Path(fname).is_file():
        global grid
        grid, y, data_date, data_time = read_spectrum(fname)

        return y[ind]

def get_times(i):

    n = '{num:05d}'.format(num=i)
    # Construct full filepath
    fname = fpath + n + '.txt'

    # Check file exists, if true then read
    if Path(fname).is_file():
        global grid
        grid, y, data_date, data_time = read_spectrum(fname)

        time = datetime.datetime.strptime(data_time,'%H:%M:%S')

        return time

pool = Pool()

vals = pool.map(get_val,range(start,stop+1))

# Create figure for the plot
plt.rcParams.update({'font.size': 18})
fig, ax = plt.subplots(1)
ax.plot(range(start,stop+1),vals)
ax.set_xlabel('Spectrum number')
ax.set_ylabel('Value at ' + str(grid[ind]) + ' nm')
plt.show()


#!/usr/bin/env python3

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('FILE', nargs = '?', default = 'input')
    args = parser.parse_args()
    with open(args.FILE, 'r') as f:
        a = int(f.readline().split(' ')[-1])
        b = int(f.readline().split(' ')[-1])
    f_a = 16807
    f_b = 48271

    def gen(i, f):
        while True:
            i = (i*f)%2147483647
            yield i
    gen_a = gen(a, f_a)
    gen_b = gen(b, f_b)

    N = 40000000
    matches = 0
    for _ in range(N):
        a_bin = next(gen_a)
        b_bin = next(gen_b)
        matches += (a_bin%65536 == b_bin%65536)
    print(matches)

    def gen2(i, f, n):
        while True:
            i = (i*f)%2147483647
            if not i%n:
                yield i

    gen_a = gen2(a, f_a, 4)
    gen_b = gen2(b, f_b, 8)

    N = 5000000
    matches = 0
    for _ in range(N):
        a_bin = next(gen_a)
        b_bin = next(gen_b)
        matches += (a_bin%65536 == b_bin%65536)
    print(matches)


from heapq import heappush, heappop
from random import randrange
Q = []
for i in range(10):
	heappush(Q, randrange(100))

def sift_up(heap, startpos, pos):
	newitem = heap[pos]
	while pos > startpos:
		parentpos = (pos - 1) >> 1
		parent = heap[parentpos]
		if parent <= newitem:
			break
		heap[pos] = parent
		pos = parentpos
	heap[pos] = newitem

from heapq import heapify, heappush, heappop
from itertools import count
def huffman(seq, frq):
	num = count()
	trees = list(zip(frq, num, seq))
	heapify(trees)
	while len(trees) > 1:
		fa, _, a = heappop(trees)
		fb, _, b = heappop(trees)
		n = next(num)
		heappush(trees, (fa+fb, n, [a, b]))
	return trees[0][-1]
# num ensures valid ordering # A min-heap based on freq
# Until all are combined
# Get the two smallest trees
# Combine and re-add them


file_location = r"C:\Users\NITHEESH\OneDrive\Desktop\sample_input.txt"
output_locaton = r"C:\Users\NITHEESH\OneDrive\Desktop\output.txt"

file1 = open(file_location, 'r')
Lines = file1.readlines()
M = int(Lines[0].replace("Number of employees: ", "")) - 1
d = dict()
for i in Lines[4:]:
    k = i.split(': ')
    d[int(k[1])] = k[0]
n = len(d)

k = list(d.keys())
k.sort()
final = []
for i in range(n - M):
    final.append(k[i + M] - k[i])

kk = 0
mn = final[0]
for i in range(1, n - M):
    if (mn > final[i]):
        mn = final[i]
        kk = i

ans = "The goodies selected for distribution are:\n\n"

for i in k[kk:kk + M + 1]:
    ans += d[i] + ": " + str(i) + "\n"
ans += "\nAnd the difference between the chosen goodie with highest price and the lowest price is " + str(mn)

print(ans)

# Writing output

file1 = open(output_locaton, 'w')
file1.write(ans)
file1.close()


import sys
import os
import pygame
import neat
from player import Player
import game_objects

# variables for the size of the screen
screen_width = 960
screen_height = 640

# start a pygame module and
pygame.init()
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Man vs Machine")

# set fonts for the different uses in game, then the winning message when you beat the computer
pygame.font.init()
win_font = pygame.font.SysFont(None, 65)
menu_font = pygame.font.SysFont(None, 100)
button_font = pygame.font.SysFont(None, 50)
win_msg = win_font.render('Win!', True, (0, 128, 0))
info_font = pygame.font.SysFont(None, 30)
score_font = pygame.font.SysFont(None, 30)

# global variables to track the player and ai scores
ai_score = 0
player_score = 0

# set path and load images for menu icons
script_dir = os.path.dirname(__file__)
human_img_path = os.path.join(script_dir, 'user.png')
ai_img_path = os.path.join(script_dir, 'bot.png')
human_img = pygame.image.load(human_img_path)
ai_img = pygame.image.load(ai_img_path)

# set some simple colors for use later on with buttons and whatnot
red = (200, 0, 25)
lightred = (255, 0, 50)
green = (0, 128, 0)
lightgreen = (0, 175, 0)
blue = (0, 0, 125)
lightblue = (0,0,200)
white = (255, 255, 255)

'''
def run_human_player():

    game_objects.init(screen)

    player = Player(screen)

    clock = pygame.time.Clock()

    # main loop
    run = True
    win = False
    while run:
        clock.tick(50)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run = False

        keys = pygame.key.get_pressed()

        if keys[pygame.K_SPACE]:
            if not(player.jumping):
                player.jumping = True
                player.on_obstacle = False

        if keys[pygame.K_LEFT]:
            player.moving_left = True
            player.moving_right = False

        elif keys[pygame.K_RIGHT]:
            player.moving_left = False
            player.moving_right = True

        else:
            player.moving_left = False
            player.moving_right = False

        player.move()

        if win:
            win = False # reset win

        if player.on_obstacle and player.obstacle == 5:
            win = True

        screen.fill((0,0,0))

        make_button("Menu", button_font, green, red, lightred, screen_width - 100, 0, 100, 50, "menu")

        for game_object in game_objects.obstacles:
            game_object.draw()

        player.draw()

        if win:
            screen.blit(win_msg, (screen_width // 2, screen_height // 2))
            player_score += 1
        else:
            pygame.display.update()

    pygame.quit()
    sys.exit()
'''

def add_player_movement(player):

    keys = pygame.key.get_pressed()

    if keys[pygame.K_SPACE]:
        if not (player.jumping):
            player.jumping = True
            player.on_obstacle = False

    if keys[pygame.K_LEFT]:
        player.moving_left = True
        player.moving_right = False

    elif keys[pygame.K_RIGHT]:
        player.moving_left = False
        player.moving_right = True

    else:
        player.moving_left = False
        player.moving_right = False

    player.move()

# function to create the counters for score while the game plays
def scoreboard(player_score, ai_score):

    # creates the exit button in the top right corner
    make_button("Menu", button_font, green, red, lightred, screen_width - 100, 0, 100, 50, "menu")

    # place border and background
    pygame.draw.rect(screen, white, (5, 5, 300, 200))
    pygame.draw.rect(screen, (0,0,0), (10, 10, 290, 190))

    # Add title of scoreboard
    text_surf, text_rect = text_objects("Score", win_font, white)
    text_rect.center = (155, 35)
    screen.blit(text_surf, text_rect)

    # add rectangles to house the points
    pygame.draw.rect(screen, (47, 79, 79), (30, 65, 100, 115))
    pygame.draw.rect(screen, (47, 79, 79), (180, 65, 100, 115))

    # add score titles
    # human title first
    text_surf, text_rect = text_objects("Human", score_font, white)
    text_rect.center = (80, 90)
    screen.blit(text_surf, text_rect)
    # ai title second
    text_surf, text_rect = text_objects("AI", score_font, white)
    text_rect.center = (230, 90)
    screen.blit(text_surf, text_rect)

    # add scores in the boxes
    # player score first
    text_surf, text_rect = text_objects(str(player_score), win_font, white)
    text_rect.center = (80, 155)
    screen.blit(text_surf, text_rect)
    # ai score second
    text_surf, text_rect = text_objects(str(ai_score), win_font, white)
    text_rect.center = (230, 155)
    screen.blit(text_surf, text_rect)

# Run A.I. simulation of the game - calculates the fitness function
def eval_genomes(genomes, config):

    # fetch the global variables for the scoreboard
    global ai_score
    global player_score

    # lists to hold the players, the genomes, and the neural net associated with that genome and player
    neural_nets = []
    genome = []
    players = []

    # this tracks the user beating the AI
    win = False

    # initialize neural nets and genomes
    for _, g in genomes:
        g.fitness = 0
        nn = neat.nn.FeedForwardNetwork.create(g, config)
        neural_nets.append(nn)
        players.append(Player(screen))
        genome.append(g)

    # initialize the game
    game_objects.init(screen)

    clock = pygame.time.Clock()

    # call player constructor to create a movable character
    human_player = Player(screen, pygame.Color(255, 100, 50))

    run_simulation = True
    while run_simulation and len(players) > 0:
        clock.tick(50)
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                run_simulation = False
                pygame.quit()
                sys.exit()

        add_player_movement(human_player)

        obstacles = game_objects.obstacles
        winning_path = [0, 1, 2, 3, 4]
        goal = 4
        cur_goal = 0
        for i, p in enumerate(players):
            x, y, obst = p.get_position()
            # where do we need to get to based on where we currently are (except if we are on goal)
            if obst != goal:
                cur_goal = obst + 1
            else: # stay where we are for right now (on top of the goal block)
                cur_goal = goal

            from_goal = obstacles[cur_goal].x - x

            output = neural_nets[players.index(p)].activate((x, y, from_goal))

            # set values to allow the computer to jump
            if output[1] > 0.5:
                if not p.jumping:
                    p.jumping = True
                    p.on_obstacle = False

            # blocks to choose character's movement left and right
            if output[0] > 0.5:
                p.moving_left = False
                p.moving_right = True
            else:
                p.moving_left = True
                p.moving_right = False

            prev_obst = obst
            prev_x = x

            p.move()

            # get new position
            x, y, obst = p.get_position()

            # find if we backtracked from our cur_goal
            if obst < prev_obst:
                genome[players.index(p)].fitness -= 1

            # see if we are any closer to our goal
            if obst > prev_obst:
                genome[players.index(p)].fitness += 2

            if obst != goal:
                new_from_goal = abs(obstacles[(obst + 1)].x - x)
            else:
                new_from_goal = goal

            if new_from_goal < abs(from_goal):
                genome[players.index(p)].fitness += 0.1
            else:
                genome[i].fitness -= 0.1

            # standing or jumping in place?
            '''if prev_x < x + p.speed and prev_x > x - p.speed and obst != goal:
                genome[players.index(p)].fitness -= 5
                p.life_counter -= 2'''

            # did we achieve the goal?
            if obst == goal:
                # if we achieved the goal, we will take this instance out and its fitness will increase
                genome[players.index(p)].fitness += 15
                neural_nets.pop(players.index(p))
                genome.pop(players.index(p))
                players.pop(players.index(p))
                ai_score += 1
            else:
                # decrease exist counter for this player
                p.life_counter -= 1

            if p.life_counter < 0:
                # remove this player and neural net
                genome[players.index(p)].fitness -= 5  # remove some fitness for not making it to the goal
                genome[players.index(p)].fitness += 2 * obst  # add some fitness back proportional to how close it got to the goal
                neural_nets.pop(players.index(p))
                genome.pop(players.index(p))
                players.pop(players.index(p))

        # add the background and the scoreboard
        screen.fill((0, 0, 0))
        scoreboard(player_score, ai_score)

        # add the obstacles across the stage
        for game_object in game_objects.obstacles:
            game_object.draw()

        # add the ai_players from the list
        for p in players:
            p.draw()

        # add the human player to the screen
        human_player.draw()

        # reset the winner, so it doesn't mess up the loop's dependencies
        if win:
            win = False  # reset win

        # case for human landing on the correct goal obstacle
        if human_player.on_obstacle and human_player.obstacle == goal:
            win = True

        # increment user score and end the iteration once you make it to the end
        if win:
            screen.blit(win_msg, (screen_width // 2, screen_height // 2))
            player_score += 1
            players.clear()

        # at the end of the loop make sure everything updates constantly
        pygame.display.update()

# implements the run method according to the neat configuration
def run(config_file):

    config = neat.config.Config(neat.DefaultGenome, neat.DefaultReproduction,
                                neat.DefaultSpeciesSet, neat.DefaultStagnation,
                                config_file)

    # creates the population to run the top-level simulation
    p = neat.Population(config)

    # output statistics to console
    p.add_reporter(neat.StdOutReporter(True))
    stats = neat.StatisticsReporter()
    p.add_reporter(stats)

    # run the simulation
    num_generations = 100

    # eventually change this to be called in main -- the menu will launch the rest
        # commented out, but left for testing and logging purposes
    # game_menu()
    results = p.run(eval_genomes, num_generations)

    # show stats
    print(results)

# output the information screen
def game_info():

    info = True

    # loop ensuring the objects remain created
    while info:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        # paint a black background that matches the game
        screen.fill((0,0,0))

        # Title block at the top of the screen
        text_surf, text_rect = text_objects('Man vs Machine', menu_font, lightblue)
        text_rect.center = (int(screen_width / 2), 50)
        screen.blit(text_surf, text_rect)

        # lines 383 - 432 simply output text explanations to the screen
        text_surf, text_rect = text_objects('Man vs Machine is a small-scale platforming game', info_font, white)
        text_rect.center = (int(screen_width / 3), 125)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('It has been developed to implement and test basic AI', info_font, white)
        text_rect.center = (int(screen_width / 3) + 10, 150)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('How it works:', win_font, lightred)
        text_rect.center = (int(screen_width / 4.7) + 10, 210)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('The AI get a headstart of sorts and run through the program a few preliminary times', info_font, white)
        text_rect.center = (int(screen_width / 2.05) + 10, 250)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('Users then choose a level of difficulty: easy, medium, or hard', info_font, white)
        text_rect.center = (int(screen_width / 2.45) + 10, 275)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('The difficulty level corresponds to a set number of AIs the player will be up against', info_font, white)
        text_rect.center = (int(screen_width / 1.925) + 10, 300)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('Essentially, the more AI trying to win, the tougher it will be for you', info_font, white)
        text_rect.center = (int(screen_width / 2.49) + 10, 325)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('If you reach the finish before the AI, you win!', info_font, white)
        text_rect.center = (int(screen_width / 3.43) + 10, 350)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('If any of the AI beat you there, they win!', info_font, white)
        text_rect.center = (int(screen_width / 3.77) + 10, 375)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('As soon as you finish a level, you\'ll continue on to a new one', info_font, white)
        text_rect.center = (int(screen_width / 2.71) + 10, 400)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('There are more AI than there are of you, so multiple AI could beat you in one round!', info_font, white)
        text_rect.center = (int(screen_width / 2.06) + 10, 425)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('Good luck!', win_font, lightred)
        text_rect.center = (int(screen_width / 2) + 10, 525)
        screen.blit(text_surf, text_rect)

        # make a lil button to get back to the menu
        make_button('Back', score_font, lightblue, green, lightgreen, screen_width - 200, screen_height - 100, 100, 50, "menu")

        pygame.display.update()

# output the starting menu
def game_menu():

    global player_score
    global ai_score

    player_score = 0
    ai_score = 0

    intro = True

    screen.fill((0, 0, 0))

    # add some dope icons in the menu to make it pretty
    screen.blit(human_img, (int(screen_width/3), int(screen_height/5)))
    text_surf, text_rect = text_objects('VS', button_font, white)
    text_rect.center = (int(screen_width / 2), int(screen_height / 3.5))
    screen.blit(text_surf, text_rect)
    screen.blit(ai_img, (int(screen_width*2/3 - 80), int(screen_height/5)))

    while intro:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        # title words
        text_surf, text_rect = text_objects('Welcome to Man vs Machine', menu_font, lightblue)
        text_rect.center = (int(screen_width / 2), int(screen_height / 2))
        screen.blit(text_surf, text_rect)

        # call functions to create buttons to move to other screens or quit
        make_button('Start', button_font, green, red, lightred, 150, screen_height - 200, 200, 100, "sett")
        make_button('Quit', button_font, green, red, lightred, screen_width - 100, screen_height-50, 100, 50, "quit")
        make_button('Info', button_font, green, red, lightred, screen_width - 200 - 150, screen_height - 200, 200, 100, "info")

        pygame.display.update()

# once user starts the game, let them select the difficulty with this menu
def game_settings():

    sett = True

    while sett:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()

        screen.fill((0, 0, 0))

        text_surf, text_rect = text_objects('Man vs Machine', menu_font, lightblue)
        text_rect.center = (int(screen_width / 2), 50)
        screen.blit(text_surf, text_rect)

        text_surf, text_rect = text_objects('Difficulty', win_font, lightred)
        text_rect.center = (int(screen_width / 2) + 10, 125)
        screen.blit(text_surf, text_rect)

        make_button('Easy', button_font, white, green, lightgreen, screen_width/4 - 100, screen_height/2, 200, 100, "easy")
        make_button('Medium', button_font, white, blue, lightblue, screen_width/2 - 100, screen_height/2, 200, 100, "med")
        make_button('Hard', button_font, white, red, lightred, screen_width*3/4 - 100, screen_height/2, 200, 100, "hard")

        pygame.display.update()

# button creator function
def make_button (text, font, textcolor, color_off, color_on, x_pos, y_pos, width, height, action = None):
    mouse = pygame.mouse.get_pos()

    click = pygame.mouse.get_pressed()

    if x_pos + width > mouse[0] > x_pos and y_pos + height > mouse[1] > y_pos:
        pygame.draw.rect(screen, color_on, (int(x_pos), int(y_pos), int(width), int(height)))
        if click[0] == 1 and action is not None:
            if action == 'sett':
                # start game action
                game_settings()
            elif action == 'quit':
                pygame.quit()
                quit()
            elif action == 'menu':
                game_menu()
            elif action == 'info':
                game_info()
            elif action == 'easy':
                run(config_easy)
            elif action == 'med':
                run(config_med)
            elif action == 'hard':
                run(config_hard)
    else:
        pygame.draw.rect(screen, color_off, (int(x_pos), int(y_pos), int(width), int(height)))

    text_surf, text_rect = text_objects(text, font, textcolor)
    text_rect.center = (int(x_pos) + int(width / 2), int(y_pos) + int(height / 2))

    screen.blit(text_surf, text_rect)

# helper function to create text blocks
def text_objects(text, font, color):

    text_surface = font.render(text, True, color)
    return text_surface, text_surface.get_rect()

if __name__ == "__main__":

    # run_human_player()

    # set file paths to respective difficulty levels
    local_dir = os.path.dirname(__file__)
    config_path = os.path.join(local_dir, 'config-neat.txt')
    config_easy = os.path.join(local_dir, 'config-neat-easy.txt')
    config_med = os.path.join(local_dir, 'config-neat-medium.txt')
    config_hard = os.path.join(local_dir, 'config-neat-hard.txt')

    game_menu()