import tkinter
from PIL import ImageTk
from PIL import Image

class Frames:
    xAxis = 0
    yAxis = 0
    MainWindow = 0
    MainObj = 0
    winFrame = object()
    btnClose = object()
    btnView = object()
    image = object()
    method = object()
    callingObj = object()
    labelImg = 0

    def __init__(self, mainObj, MainWin, wWidth, wHeight, function, Object, xAxis=10, yAxis=10):
        self.xAxis = xAxis
        self.yAxis = yAxis
        self.MainWindow = MainWin
        self.MainObj = mainObj
        self.MainWindow.title("Brain Tumor Detection")
        if (self.callingObj != 0):
            self.callingObj = Object

        if (function != 0):
            self.method = function

        global winFrame
        self.winFrame = tkinter.Frame(self.MainWindow, width=wWidth, height=wHeight)
        self.winFrame['borderwidth'] = 5
        self.winFrame['relief'] = 'ridge'
        self.winFrame.place(x=xAxis, y=yAxis)

        self.btnClose = tkinter.Button(self.winFrame, text="Close", width=8,
                                      command=lambda: self.quitProgram(self.MainWindow))
        self.btnClose.place(x=1020, y=600)
        self.btnView = tkinter.Button(self.winFrame, text="View", width=8, command=lambda: self.NextWindow(self.method))
        self.btnView.place(x=900, y=600)

    def setCallObject(self, obj):
        self.callingObj = obj

    def setMethod(self, function):
        self.method = function

    def quitProgram(self, window):
        global MainWindow
        self.MainWindow.destroy()

    def getFrames(self):
        global winFrame
        return self.winFrame

    def unhide(self):
        self.winFrame.place(x=self.xAxis, y=self.yAxis)

    def hide(self):
        self.winFrame.place_forget()

    def NextWindow(self, methodToExecute):
        listWF = list(self.MainObj.listOfWinFrame)

        if (self.method == 0 or self.callingObj == 0):
            print("Calling Method or the Object from which Method is called is 0")
            return

        if (self.method != 1):
            methodToExecute()
        if (self.callingObj == self.MainObj.DT):
            img = self.MainObj.DT.getImage()
        else:
            print("Error: No specified object for getImage() function")

        jpgImg = Image.fromarray(img)
        current = 0

        for i in range(len(listWF)):
            listWF[i].hide()
            if (listWF[i] == self):
                current = i

        if (current == len(listWF) - 1):
            listWF[current].unhide()
            listWF[current].readImage(jpgImg)
            listWF[current].displayImage()
            self.btnView['state'] = 'disable'
        else:
            listWF[current + 1].unhide()
            listWF[current + 1].readImage(jpgImg)
            listWF[current + 1].displayImage()

        print("Step " + str(current) + " Extraction complete!")

    def removeComponent(self):
        self.btnClose.destroy()
        self.btnView.destroy()

    def readImage(self, img):
        self.image = img

    def displayImage(self):
        imgTk = self.image.resize((250, 250), Image.ANTIALIAS)
        imgTk = ImageTk.PhotoImage(image=imgTk)
        self.image = imgTk
        self.labelImg = tkinter.Label(self.winFrame, image=self.image)
        self.labelImg.place(x=700, y=150)


from BybitWebsocket import BybitWebsocket
import logging
from time import sleep

def setup_logger():
    # Prints logger info to terminal
    logger = logging.getLogger()
    logger.setLevel(logging.INFO)  # Change this to DEBUG if you want a lot more info
    ch = logging.StreamHandler()
    # create formatter
    formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
    ch.setFormatter(formatter)
    logger.addHandler(ch)
    return logger

if __name__ == "__main__":
    logger = setup_logger()
    ws = BybitWebsocket(wsURL="wss://stream-testnet.bybit.com/realtime",
                         api_key=None, api_secret=None)

    ws.subscribe_orderBookL2("BTCUSD")
    ws.subscribe_kline("BTCUSD", '1m')
    ws.subscribe_order()
    ws.subscribe_execution()
    ws.subscribe_position()
    ws.subscribe_instrument_info('BTCUSD')
    ws.subscribe_insurance()
    while(1):
        logger.info(ws.get_data("orderBookL2_25.BTCUSD"))
        logger.info(ws.get_data('kline.BTCUSD.1m'))
        logger.info(ws.get_data('order'))
        logger.info(ws.get_data("execution"))
        logger.info(ws.get_data("position"))
        logger.info(ws.get_data("instrument_info.100ms.BTCUSD"))
        logger.info(ws.get_data('insurance.BTC'))
        logger.info(ws.get_data('insurance.EOS'))
        sleep(1)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 17:49:11 2020

@author: nikhildhamne
"""

import pyNN.nest as sim
import numpy as np

n = 10
spiky = n//2

mu = 0.
sig = 1

weight_to_spike = 0.025 #0.01 #0.05
delay_cann2cann = 1.

cell_params = {
    'tau_m'      : 20.0,   # (ms)
    'tau_syn_E'  : 2.0,    # (ms)
    'tau_syn_I'  : 4.0,    # (ms)
    'e_rev_E'    : 0.0,    # (mV)
    'e_rev_I'    : -70.0,  # (mV)
    'tau_refrac' : 2.0,    # (ms)
    'v_rest'     : -60.0,  # (mV)
    'v_reset'    : -70.0,  # (mV)
    'v_thresh'   : -60.0,  # (mV)
    'cm'         : 0.5}
sim.setup()

dist = np.zeros((n, n))
weights = np.zeros((n, n))
hd_cann_connector = list()
pos_rot_connector = list()
neg_rot_connector = list()
hd_conj_connector = list()

for i in range(n):
    for j in range(n):
        dist[i][j] = abs(i - j)%(n)
        if dist[i][j] > n/2:
            dist[i][j] = n - dist[i][j]
        weights[i][j] = round(weight_to_spike * \
                    (1 / (sig * np.sqrt(2 * np.pi)) * \
                    (np.exp(-np.power(dist[i][j] - mu, 2.) \
                    / (2 * np.power(sig, 2.))))), 2)
        hd_cann_connector.append((i, j, weights[i][j]))#, delay_cann2cann))
#print("Weight matrix:\n", weights)

hd_spike_times = [2000., 2005., 2010., 2015.]

spikes_in = 20 #5 #10 #50
pos_spike_times = [None] * spikes_in
for i,j in zip(range(spikes_in), range(4000, 4100, 2)):
    pos_spike_times[i] = j
print(pos_spike_times)
#pos_spike_times = [2000., 2005., 2010., 2015.]
neg_spike_times = []#[4000., 4005., 4010., 4015.]

# Populations

hd_cann_pop = sim.Population(n, sim.IF_cond_alpha(**cell_params),
                         label = "hd_cann_pop")

inhib_pop = sim.Population(n, sim.IF_cond_alpha(**cell_params),
                         label = "inhib_pop")

#pos_rot_conj = sim.Population(n, sim.IF_cond_alpha(**cell_params),
pos_rot_conj = sim.Population(n, sim.IF_cond_alpha(),
                          label = "pos_rot_conj")

#neg_rot_conj = sim.Population(n, sim.IF_cond_alpha(**cell_params),
neg_rot_conj = sim.Population(n, sim.IF_cond_alpha(),
                          label = "neg_rot_conj")

# Spike Sources

hd_spike_src = sim.Population(1, sim.SpikeSourceArray(
    spike_times = hd_spike_times))

pos_spike_src = sim.Population(1, sim.SpikeSourceArray(
    spike_times = pos_spike_times))

neg_spike_src = sim.Population(1, sim.SpikeSourceArray(
    spike_times = neg_spike_times))

# Connections between spike sources and ppopulation

spike_2_hd = sim.Projection(hd_spike_src, hd_cann_pop[3:4], sim.OneToOneConnector(),
                      sim.StaticSynapse(weight = 0.002, delay = 0.1))

pos_spikes = sim.Projection(pos_spike_src, pos_rot_conj, sim.AllToAllConnector(),
                            sim.StaticSynapse(weight = 0.2, delay = 0.1))

neg_spikes = sim.Projection(neg_spike_src, neg_rot_conj, sim.AllToAllConnector(),
                            sim.StaticSynapse(weight = 0.2, delay = 0.1))

# Connections/ Projections between main populations

hd_cann_2_hd_cann = sim.Projection(hd_cann_pop, hd_cann_pop,
                                   sim.FromListConnector(hd_cann_connector, column_names=["weight"]),
                                   sim.StaticSynapse(weight = 0.0001, delay = 75))

hd_cann_2_inh = sim.Projection(hd_cann_pop, inhib_pop, sim.AllToAllConnector(),
                               sim.StaticSynapse(weight = 0.02, delay = 0.1),
                               receptor_type = "excitatory")

inh_2_hd_cann = sim.Projection(inhib_pop, hd_cann_pop, sim.AllToAllConnector(),
                               sim.StaticSynapse(weight = 0.5, delay = 0.1),
                               receptor_type = "inhibitory")

for i in range(n):
    pos_rot_connector.append((i, (i+1)%10, 0.002))
#print(pos_rot_connector)
pos_rot_conj_2_hd_cann = sim.Projection(pos_rot_conj, hd_cann_pop,
                                        sim.FromListConnector(pos_rot_connector, column_names=["weight"]),
                                        receptor_type = "excitatory")

for i in range(n):
    neg_rot_connector.append((i, (i-1)%10, 0.002))

neg_rot_conj_2_hd_cann = sim.Projection(neg_rot_conj, hd_cann_pop,
                                        sim.FromListConnector(neg_rot_connector, column_names=["weight"]),
                                        sim.StaticSynapse(delay = 100),
                                        receptor_type = "excitatory")
for i in range(n):
    hd_conj_connector.append((i, i, weight_to_spike))

hd_cann_2_pos_rot = sim.Projection(hd_cann_pop, pos_rot_conj,
                                   sim.FromListConnector(hd_conj_connector, column_names=["weight"]),
                                   sim.StaticSynapse(delay = 100),
                                   receptor_type = "excitatory")

hd_cann_2_neg_rot = sim.Projection(hd_cann_pop, neg_rot_conj,
                                   sim.FromListConnector(hd_conj_connector, column_names=["weight"]),
                                   receptor_type = "excitatory")

#spike_source.record('spikes')
hd_cann_pop.record(('v','spikes'))
inhib_pop.record(('v','spikes'))
pos_rot_conj.record(('v','spikes'))
neg_rot_conj.record(('v','spikes'))

sim.run(10000.0)

from pyNN.utility.plotting import Figure, Panel
cann_data = hd_cann_pop.get_data().segments[0]
cann_vm = cann_data.filter(name="v")[0]
inh_data = inhib_pop.get_data().segments[0]
inh_vm = inh_data.filter(name="v")[0]

pos_rot_data = pos_rot_conj.get_data().segments[0]
pos_rot_vm = pos_rot_data.filter(name="v")[0]
neg_rot_data = neg_rot_conj.get_data().segments[0]
neg_rot_vm = neg_rot_data.filter(name="v")[0]

Figure(
       #Panel(cann_vm, ylabel = "Cann Membrane potential (mV)", yticks = True),
       Panel(cann_data.spiketrains, ylabel = "HD spikes", yticks = True),
       #Panel(inh_vm, ylabel = "Inh Membrane potential (mV)", yticks = True),
       Panel(inh_data.spiketrains, ylabel = "Inhib. spikes", yticks = True),
       Panel(pos_rot_data.spiketrains, ylabel = "Pos Rot spikes", yticks = True),
       Panel(neg_rot_data.spiketrains, xlabel = "Time (ms)", ylabel = "Neg Rot spikes", yticks = True, xticks = True)
       #Panel(pos_rot_vm, ylabel = "Pos Rot pot (mV)", yticks = True),
       #Panel(neg_rot_vm, xlabel = "Time (ms)", ylabel = "Neg Rot pot (mV)", yticks = True, xticks = True)
)

sim.end()


# uncompyle6 version 3.7.4
# Python bytecode 3.4 (3310)
# Decompiled from: Python 3.6.9 (default, Apr 18 2020, 01:56:04)
# [GCC 8.4.0]
# Embedded file name: build/bdist.linux-x86_64/egg/containerdiff/undocker.py
# Compiled at: 2016-05-22 16:06:03
# Size of source mod 2**32: 4924 bytes
""" Extract a content of docker image."""
import json, os, logging, tarfile, tempfile, shutil, docker, containerdiff
from contextlib import closing
logger = logging.getLogger(__name__)

def find_layers(img, ID):
    """Returns a list of underlying layers for the layer 'ID'. First
    element of the list is a top layer and then the underlying layers -
    it is reversed order in which docker expands layers during
    container creation.

    'img' is a TarFile object of open docker image.

    The 'ID' has to be 'full ID' (64 characters long).
    """
    if len(ID) != 64:
        return []
    with closing(img.extractfile('%s/json' % ID)) as (fd):
        info = json.loads(fd.read().decode('utf8'))
    logger.debug('layer = %s', ID)
    for k in ['os', 'architecture', 'author', 'created']:
        if k in info:
            logger.debug('%s = %s', k, info[k])
            continue

    result = [
     ID]
    if 'parent' in info:
        result.extend(find_layers(img, info['parent']))
    return result

def extract(ID, output, one_layer=False, whiteouts=True):
    """Extract the content of image *ID* to folder *output*.

    If *one_layer* is True only layer *ID* is extracted. If *whiteouts*
    is False there is no logic with files started with '.wh.'.

    File information like owner, modification time and permissions is
    not set. It is stored in the dict structure with 'path to the file'
    key (starting by '/', e.g. '/etc'). This struct is returned by this function.

    Device files are not extracted. Only the additional metadata are
    stored in returned dictionary.
    """
    metadata = {}
    cli = docker.AutoVersionClient(base_url=containerdiff.docker_socket)
    try:
        ID = cli.inspect_image(ID)['Id']
    except docker.errors.NotFound:
        logger.critical("Can't find image %s", ID)
        raise

    logger.info('Saving image %s', ID)
    image = cli.get_image(ID)
    with tempfile.NamedTemporaryFile() as (fd):
        fd.write(image.data)
        with tarfile.open(name=fd.name) as (img):
            logger.info('Extracting image %s', ID)
            if ('manifest.json' and ID.split(':')[(-1)] + '.json') in img.getnames():
                with closing(img.extractfile('manifest.json')) as (fd):
                    manifest = json.loads(fd.read().decode('utf8'))
                ID = manifest[0]['Layers'][(-1)].split('/')[0]
            if not one_layer:
                layers = find_layers(img, ID)
            else:
                layers = [
                 ID]
            if not os.path.isdir(output):
                os.mkdir(output)
            for layer_id in reversed(layers):
                logger.info('Extracting layer %s', layer_id)
                with tarfile.TarFile(fileobj=img.extractfile('%s/layer.tar' % layer_id)) as (layer):
                    for member in layer.getmembers():
                        path = member.path
                        if whiteouts:
                            if path.startswith('.wh.') or '/.wh.' in path:
                                if path.startswith('.wh.'):
                                    newpath = path[4:]
                                else:
                                    newpath = path.replace('/.wh.', '/')
                                logger.debug('Removing path %s', newpath)
                                del metadata['/' + newpath]
                                newpath = os.path.join(output, newpath)
                                if os.path.isdir(newpath):
                                    shutil.rmtree(newpath)
                                else:
                                    os.unlink(newpath)
                                continue
                            metadata['/' + path] = member.get_info()
                            if not member.isdev():
                                layer.extract(member, path=output, set_attrs=False)
                                continue

                    logger.debug('Actual metadata size - %i', len(metadata))

    return metadata


# -*- coding: UTF-8 -*-
from django.db.models.query import QuerySet
from django.contrib.admin.views.main import ChangeList

class HierarchyChangeList(ChangeList):
    """
    extends the django.contrib.admin.views.main.ChangeList class
    for hierarchical structures. The filter method is overwritten
    """
    # overwritten
    def get_queryset(self, request):
        qs = super(HierarchyChangeList, self).get_queryset(request)
        # we have to get all parents of an item (recursively), even if the parent
        # is filtered out. Otherwise the hierarchical structure would be destroyed.
        # All the parents, which would be filtered out, are grayed out in the display.
        self.filtered_out = {}
        if qs.count():
            # all parents list:
            for item in qs:
                parent = item.parent
                while parent:
                    # maybe append parent to "filtered_out_list"
                    if qs.filter(pk=parent.pk).count() == 0:
                        self.filtered_out[parent.pk] = True
                    parent = parent.parent
            qs = qs | QuerySet(self.model).filter(pk__in=list(self.filtered_out))

        # Set ordering again.
        ordering = self.get_ordering(request, qs)
        qs = qs.order_by(*ordering)
        return qs


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

from openerp import models, fields, api, _, tools
from openerp.exceptions import UserError, RedirectWarning, ValidationError
import shutil
import logging
_logger = logging.getLogger(__name__)
class SaleOrder(models.Model):
    _inherit = "sale.order"
    reason_rejection = fields.Many2one('reason.rejection',string="Motivo de Rechazo")
    zona = fields.Char(string="Zona")

    @api.onchange('partner_id')
    def zonapartner(self):
        self.zona = self.partner_id.zona

    @api.multi
    def recompute_coupon_lines2(self):
        #raise UserError(_("hola"))
        hi = self.id
        for order in self:
            order._remove_invalid_reward_lines2()
            order._create_new_no_code_promo_reward_lines2()
            order._update_existing_reward_lines2()

    def _remove_invalid_reward_lines2(self):
        '''Unlink reward order lines that are not applicable anymore'''
        invalid_lines = self.env['sale.order.line']
        for order in self:
            new_applicable_programs = order._get_applicable_no_code_promo_program() + order._get_applicable_programs()
            old_applicable_programs = order.no_code_promo_program_ids + order.applied_coupon_ids.mapped(
                'program_id') + order.code_promo_program_id
            programs_to_remove = old_applicable_programs - new_applicable_programs
            products_to_remove = (programs_to_remove).mapped('discount_line_product_id')
            self.generated_coupon_ids.filtered(
                lambda coupon: coupon.program_id.discount_line_product_id.id in products_to_remove.ids).write(
                {'state': 'expired'})
            order.no_code_promo_program_ids -= programs_to_remove
            order.code_promo_program_id -= programs_to_remove
            order.applied_coupon_ids -= order.applied_coupon_ids.filtered(
                lambda coupon: coupon.program_id in programs_to_remove)
            invalid_lines |= order.order_line.filtered(lambda line: line.product_id.id in products_to_remove.ids)
            order.write({'order_line': [(2, line.id, False) for line in invalid_lines]})

    def _create_new_no_code_promo_reward_lines2(self):
        '''Apply new programs that are applicable'''
        self.ensure_one()
        order = self
        programs = order._get_applicable_no_code_promo_program()
        for program in programs:
            error_status = program._check_promo_code(order, False)
            if not error_status.get('error') and program.promo_applicability == 'on_next_order':
                order._create_reward_coupon(program)
                order.no_code_promo_program_ids |= program
            elif not error_status.get('error') and program.discount_line_product_id.id not in self.order_line.mapped(
                    'product_id').ids:
                self.write({'order_line': [(0, False, order._get_reward_line_values(program))]})
                order.no_code_promo_program_ids |= program

    def _update_existing_reward_lines2(self):
        '''Update values for already applied rewards'''
        self.ensure_one()
        order = self
        applied_programs = order.no_code_promo_program_ids + \
                           order.applied_coupon_ids.mapped('program_id') + \
                           order.code_promo_program_id
        for program in applied_programs:
            values = order._get_reward_line_values(program)
            lines = order.order_line.filtered(lambda line: line.product_id == program.discount_line_product_id)
            # Remove reward line if price or qty equal to 0
            if values['product_uom_qty'] and values['price_unit']:
                order.write({'order_line': [(1, line.id, values) for line in lines]})
            else:
                if program.reward_type != 'free_shipping':
                    order.write({'order_line': [(2, line.id, False) for line in lines]})
                else:
                    values.update(price_unit=0.0)
                    order.write({'order_line': [(1, line.id, values) for line in lines]})


# -*- coding: utf-8 -*-
"""
Created on Tue Jan 21 09:33:58 2020

@author: local_ergo
"""
import numpy as np
import pandas as pd
import os
import time
from math import cos, sin, radians, atan2, degrees
from shapely.geometry import Polygon, Point
from shapely.ops import cascaded_union
from functions_object_placement import door_placement, object_placement, bed_placement
from functions_object_placement import object_placement_againstWall, light_placement, room_surface_initialization, object_name
from functions_collision_detection import rectangle_vertices, door_polygon, polygon_with_clearance, plot_polygon
from functions_collision_detection import collision_detection, door_room_check, door_obj_collision_detection

#############################################################################
#                           CLASSES
#############################################################################
class Environment_Generated():
    ''' This class generates an environment with doors, lights and furniture randomly placed in two rooms, bedroom and bathroom'''
    def __init__(self, mainRoomCodes, bathRoomCodes, furnMainStat, furnBathStat, lightMainStat, lightBathStat,
                 doorMainStat, doorBathStat, numOfRows, numOfColumns, mainDoorPlacement, bedPlacement = 0):
#        print('mainDoorPlacement:' , mainDoorPlacement)
        self.unit_size_m = 0.20 # Grid size in cm (X,Y).
        self.numOfRows = numOfRows # Number of grids in a Y direction.
        self.numOfCols = numOfColumns # Number of grids in a X direction.
        self.sample_zones = {}
        #*********************************************
        # ------ MAIN FURNITURE
        mainFurnitureCodeArray = mainRoomCodes[0]
        if furnMainStat == []:
          mainFurnMu = []
          mainFurnSigma = []
        else:
          mainFurnMu = furnMainStat[0]
          mainFurnSigma = furnMainStat[1]
        # ------ MAIN DDORS
        mainDoorsCodeArray = mainRoomCodes[1]
        if doorMainStat == []:
          mainDoorMu = []
          mainDoorSigma = []
        else:
          mainDoorMu = doorMainStat[0]
          mainDoorSigma = doorMainStat[1]
        # ------ MAIN LIGHTS
        mainLightCodeArray = mainRoomCodes[2]
        if lightMainStat == []:
          mainLightMu = []
          mainLightSigma = []
        else:
          mainLightMu = lightMainStat[0]
          mainLightSigma = lightMainStat[1]
        # ------ MAIN ROON
        room_name = mainRoomCodes[3]
#        mainRoomVertices = [(0,0), (8,0),(8,10),(0,10)] # Perfect square room -> for testing
        mainRoomVertices = [(0,0), (4.27,0), (4.27, 5.79), (1.93, 5.79), (1.93, 4.57), (1.12, 3.78), (0,3.78)]
        mainRoom = self.Room(room_name, mainRoomVertices)
        # ------ BATH FURNITURE
        bathFurnitureCodeArray = bathRoomCodes[0]
        if furnBathStat == []:
          bathFurnMu = []
          bathFurnSigma = []
        else:
          bathFurnMu = furnBathStat[0]
          bathFurnSigma = furnBathStat[1]
        # ------ BATH DOOR
        bathDoorsCodeArray = bathRoomCodes[1]
        if doorBathStat == []:
          bathDoorMu = []
          bathDoorSigma = []
        else:
          bathDoorMu = doorBathStat[0]
          bathDoorSigma = doorBathStat[1]
        # ------ BATH LIGHTS
        bathLightCodeArray = bathRoomCodes[2]
        if lightBathStat == []:
          bathLightMu = []
          bathLightSigma = []
        else:
          bathLightMu = lightBathStat[0]
          bathLightSigma = lightBathStat[1]
        # ------ BATH ROOM
        room_name = bathRoomCodes[3]
#        bathRoomVertices = [(8,1), (13,1),(13,7),(8,7)] # Perfect square bethroom-> for testing
        bathRoomVertices = [(0, 3.78), (1.12,3.78), (1.93, 4.57), (1.93, 5.79), (0, 5.79)]
        bathRoom = self.Room(room_name, bathRoomVertices)

        #---------------------------------------------------------------------
        #                  DEFINING AND PLACING OBJECTS
        #---------------------------------------------------------------------
        mainLightList = light_installation(mainLightCodeArray, mainRoom, mainLightMu, mainLightSigma)
        bathLightList = light_installation(bathLightCodeArray, bathRoom, bathLightMu, bathLightSigma)

        mainDoorList = door_collision(mainDoorsCodeArray, mainRoom, bathRoom, mainDoorMu, mainDoorSigma, mainDoorPlacement)
        bathDoorList = door_collision(bathDoorsCodeArray, bathRoom, mainRoom, bathDoorMu, bathDoorSigma, mainDoorPlacement)

        mainFurnitureList = multiple_object_collision_detection(mainFurnitureCodeArray, mainDoorList+bathDoorList, mainRoom, mainFurnMu, mainFurnSigma, bedPlacement)
        bathFurnitureList = multiple_object_collision_detection(bathFurnitureCodeArray, bathDoorList+mainDoorList, bathRoom, bathFurnMu, bathFurnSigma)

        self.doorListDict = {"main":mainDoorList, "bath":bathDoorList}
        self.doorList  = create_list_of_objects(mainDoorList, bathDoorList)

        self.furnitureListDict = {"main":mainFurnitureList, "bath":bathFurnitureList}
        self.furnitureList  = create_list_of_objects(mainFurnitureList, bathFurnitureList)
#
        self.lightListDict = {"main":mainLightList, "bath":bathLightList}
        self.lightList  = create_list_of_objects(mainLightList, bathLightList)

        self.roomList = []
        self.roomList.append(mainRoom); self.roomList.append(bathRoom)

        self.sample_zones = find_sample_zone(self.doorList, self.furnitureList, self.roomList)

        self.walls = []
        self.floor = np.zeros([self.numOfRows, self.numOfCols]) # Initializing floor_type as a zero matrix with size of number_of_rows * number_of_columns.
        for room in self.roomList:
            self.walls.append(room.wallArray)
            for row in range(self.numOfRows):
                for col in range(self.numOfCols):
                    gridCoordinate = self.grid2meter(col,row)
                    gridPoint = Point(gridCoordinate)
                    if gridPoint.within(room.polygon): # Assigning the floor type based on the room section to each grid in the space
                        self.floor[row, col] = room.surfaceRisk
#        print(self.floor.shape)
    def grid2meter(self, col, row):
        x = row*self.unit_size_m
        y = col*self.unit_size_m
        return (x,y)

    class Room():
        '''
        This class generates rooms as polygons based on the list of vertices
        "vertices" passed to the class and name it "roomName
        '''
        def __init__(self, roomName, vertices):
            library_file_name = os.path.join(os.getcwd(), 'Object_Library.csv') # The object library file address.
            object_library = pd.read_csv(library_file_name,) # Reading the object library file
            del library_file_name
            # Room Dimensions
            xAxis = []
            yAxis = []
            for item in vertices:
                xAxis.append(item[0])
                yAxis.append(item[1])
            xmin = min(xAxis)
            xmax = max(xAxis)
            ymin = min(yAxis)
            ymax = max(yAxis)

            self.x = np.linspace(xmin, xmax, 4*(int(xmax-xmin))+1) # m (the ability of choosing points at each 25cm)
            self.y = np.linspace(ymin, ymax, 4*(int(xmax-xmin))+1) # m (the ability of choosing points at each 25cm)
            self.polygon = Polygon(vertices)
#            print(vertices)
            self.name = roomName
            self.code, self.surfaceType, self.surfaceRisk = room_surface_initialization(object_library)
            self.numWalls, self.walls, self.wallArray = finding_walls(self)
#            plot_polygon(self.polygon)
#            plot_polygon(self.polygon, fignum = 2)

class FurniturePlacement():

    def __init__(self, objects_code, room, mu, sigma, bedPlacement = 0):
        library_file_name = os.path.join(os.getcwd(), 'Object_Library.csv') # The object library file address.
        object_library = pd.read_csv(library_file_name,) # Reading the object library file
        del library_file_name
        orientation = np.linspace(0.0, 179.0, 180)
        # The created object should be inside the room
        self.wallPoint = [] # It takes value if the object is against a wall. Then the mu and std will be 1D for this variable
        self.code = objects_code
        self.room = room.name
        obj_df = object_library.loc[object_library['Object Code'] == self.code[0]]
        againstWall = obj_df.iloc[0]['Against Wall']
        clearance = obj_df.iloc[0]['Clearance']
        inside = False
        while inside == False:
            if againstWall == True:
                if object_name(objects_code, object_library) == 'Bed':
                    if bedPlacement == 'h' or bedPlacement == 'f' :
                        self.conf, self.length, self.width, self.support, self.name, self.wallPoint = bed_placement(objects_code, object_library, orientation, mu, sigma, bedPlacement, room)
                    else:
#                        print('algorithm decides if it is a headwall or footwall room')
                        self.conf, self.length, self.width, self.support, self.name, self.wallPoint = object_placement_againstWall(objects_code, object_library, room, orientation, mu, sigma)
                else:
                    self.conf, self.length, self.width, self.support, self.name, self.wallPoint = object_placement_againstWall(objects_code, object_library, room, orientation, mu, sigma)
#              print('wallPoint:', self.wallPoint)
#              print("Against the wall is detected for object", self.name)
            else:
              self.conf, self.length, self.width, self.support, self.name = object_placement(objects_code, object_library, room, room.x, room.y, orientation, mu, sigma)
            _, _, _, _, self.polygon = rectangle_vertices(self.conf, self.length, self.width)
            if clearance == 1:
              obj = polygon_with_clearance(self, obj_df)
#              print("clearance is detected for object", self.name)
            else:
              _, _, _, _, obj = rectangle_vertices(self.conf, self.length, self.width)
#            plot_polygon(obj)
            inside = room.polygon.contains(obj)

class DoorPlacement():

    def __init__(self, door_code, room, otherRoom, doorMu, doorSigma, mainDoorPlacement):
        library_file_name = os.path.join(os.getcwd(), 'Object_Library.csv') # The object library file address.
        object_library = pd.read_csv(library_file_name,) # Reading the object library file
        del library_file_name
        self.code = door_code
        self.wallPoint = []
        outside = True
        while outside == True:
            self.conf, self.length, self.width, self.support, self.wallPoint = door_placement(door_code, object_library, room, otherRoom, doorMu, doorSigma, mainDoorPlacement)
            self.room = room.name
            _, _, _, _, self.polygon = door_polygon(self.conf, self.length, self.width)
            _, _, _, _, obj = door_polygon(self.conf, self.length, self.width)
#            plot_polygon(obj)
            outside = door_room_check(self, room)

class Lights():
    def __init__(self, light_code, room, lightMu, lightSigma):
        library_file_name = os.path.join(os.getcwd(), 'Object_Library.csv') # The object library file address.
        object_library = pd.read_csv(library_file_name,) # Reading the object library file
        del library_file_name
        self.code = light_code
        self.room = room.name
        inside = False
#        i = 0
        while inside == False:
#            if i>100:
#                print('LGHT: mu is: ', mu, '\n and sigma is: \n', sigma)
#            print('light trial ', i)
            self.pos, self.intensity = light_placement(light_code, object_library, room, lightMu, lightSigma)
#            print(self.pos)
            self.point = Point(self.pos)
            light_source = self.point
#            plot_lights(light_source)
            inside = room.polygon.contains(light_source)

#############################################################################
#                           FUNCTIONS/METHODS
#############################################################################
def finding_walls(room):
    '''
    This function finds the number and coordinates of the input parameter "room" as walls
    it finds each side of the rooms polygon and recognizes them as walls
    '''
    num_walls = len(room.polygon.exterior.coords[:-1])  # counts the side of the rooms polygon -> number of walls
    available_walls = (np.linspace(0, num_walls-1, num_walls)).astype(int) # create a list of walls for sampling
#    print(available_walls)
    wall_list = []
    wall_arrayType = []
    for wall in available_walls:
        # find the position of the center of the door
        if wall == num_walls-1:
    #        print("last wall")
            wall_coords = [(room.polygon.exterior.coords[:-1][wall][0], room.polygon.exterior.coords[:-1][wall][1]),
                           (room.polygon.exterior.coords[:-1][0][0], room.polygon.exterior.coords[:-1][0][1])]
            wall_array = [room.polygon.exterior.coords[:-1][wall][0], room.polygon.exterior.coords[:-1][wall][1],
                           room.polygon.exterior.coords[:-1][0][0], room.polygon.exterior.coords[:-1][0][1]]
        else:
            wall_coords = [(room.polygon.exterior.coords[:-1][wall][0], room.polygon.exterior.coords[:-1][wall][1]),
                           (room.polygon.exterior.coords[:-1][wall+1][0], room.polygon.exterior.coords[:-1][wall+1][1])]
            wall_array = [room.polygon.exterior.coords[:-1][wall][0], room.polygon.exterior.coords[:-1][wall][1],
                          room.polygon.exterior.coords[:-1][wall+1][0], room.polygon.exterior.coords[:-1][wall+1][1]]
        wall_list.append(wall_coords)
        wall_arrayType.append(wall_array)
    return num_walls, wall_list, wall_arrayType

def door_collision(door_code_array, room, otherRoom, doorMu, doorSigma, mainDoorPlacement):
    '''
    This function checks the collision between multiple objects that have been sent
    to this function as a list of objects
    :param objects_code_array: an array of the objects code of interest (the codes
    can be retrived from the corresponding object library csv file)
    :param obj_list: list of objects that are placed in the room
    '''
    #creating a list of objects
    door_list = []
    for door_code in door_code_array:
        door_list.append(DoorPlacement([door_code], room, otherRoom, doorMu, doorSigma, mainDoorPlacement))    # list of the objects in the room
        restart = True
        while restart == True:  # Making sure it checks the collision between all objects even after resampling
            restart = False
            for door in door_list[:-1]:
                collision_bool = door_obj_collision_detection(door, door_list[-1])
    #            print("checking collision between ", obj.code, "and, ", obj_list[-1].code)
                if collision_bool == True:  # If the new object is colliding with any of the existing objects, recreate the latest object and assign new configuration to it
    #                print("Collision detected between objects ", obj.code, " and ", obj_list[-1].code )
                    door_list[-1] = DoorPlacement([door_code], room, otherRoom, doorMu, doorSigma, mainDoorPlacement)
                    restart = True

    return door_list

def multiple_object_collision_detection(objects_code_array, door_list, room, mus, sigmas, bedPlacement = 0):
    '''
    This function checks the collision between multiple objects that have been sent
    to this function as a list of objects
    :param objects_code_array: an array of the objects code of interest (the codes
    can be retrived from the corresponding object library csv file)
    :param obj_list: list of objects that are placed in the room
    '''
#    print('Function Called')
    ''' creating a list of objects'''
    obj_list = []
    i = 0
    for obj_code in objects_code_array: # for each piece of furniture in the list
        if mus == []:
            mu = mus
            sigma = sigmas
        else:
            mu = mus[i]
            sigma = sigmas[i]
#        print('\n and sigma is: \n, ', sigma)
        i +=1
        obj_list.append(FurniturePlacement([obj_code], room, mu, sigma, bedPlacement))    # list of the objects in the room

        restart = True
        timeOut = 5
        timeStart = time.time()
        while restart == True:  # Making sure it checks the collision between all objects even after resampling
            restart = False
            for obj in obj_list[:-1]:
                collision_obj = collision_detection(obj, obj_list[-1])
#                print("checking collision between", obj.name, "and ", obj_list[-1].name)
                if collision_obj == True:  # If the new object is colliding with any of the existing objects, recreate the latest object and assign new configuration to it
#                    print("COLLISION detected between", obj.name, " and", obj_list[-1].name )
                    obj_list[-1] = FurniturePlacement([obj_code], room, mu, sigma, bedPlacement)
                    restart = True
                if time.time() > timeStart + timeOut:
                    print('Time out! Unable to set the room. Recreating room', room.name)
                    return multiple_object_collision_detection(objects_code_array, door_list, room, mus, sigmas)
#            timeStart = time.time()
            for door in door_list:
                collision_door = door_obj_collision_detection(door, obj_list[-1])
#                print("checking collision between door", door.code, "and", obj_list[-1].name)
                if collision_door == True:  # If the new object is colliding with any of the existing objects, recreate the latest object and assign new configuration to it
                    obj_list[-1] = FurniturePlacement([obj_code], room, mu, sigma, bedPlacement)
#                    print("COLLISION detected between door", door.code, " and", obj_list[-1].name)
                    restart = True
                if time.time() > timeStart + timeOut:
                    print('Time out! Unable to place the doors. Recreating room', room.name)
                    return multiple_object_collision_detection(objects_code_array, door_list, room, mus, sigmas)
    return obj_list

def light_installation(light_code_array, room, lightMus, lightSigmas):
    light_list = []
#    print('mu at the begining of the function:', lightMus)
    i = 0
    for light_code in light_code_array:
        if lightMus != []:
            lightMu = lightMus[i]
            lightSigma = lightSigmas[i]
        else:
          lightMu = lightMus
          lightSigma = lightSigmas
        i +=1
#        print('light mu in the for loop:', lightMu)
        light_list.append(Lights([light_code], room, lightMu, lightSigma))
    restart = True
    while restart == True:
        restart = False
        for light in light_list[:-1]:
#            print('light pos: ', light.pos, ' and the type is', type(light.pos))
#            if light.pos.all() == light_list[-1].pos.all():
            if isinstance(light.pos, list):
#              print('light pos is already a list')
              lightPos = light.pos
              lastLightPos = light_list[-1].pos
            else:
#              print('light pos is an array list, converting it to list')
              lightPos = light.pos.tolist()
              lastLightPos = light_list[-1].pos.tolist()

            if lightPos == lastLightPos:
                light_list[-1] = Lights([light_code], room, lightMu, lightSigma)
                restart = True
    return light_list

def create_list_of_objects(main, bath):
    '''
    This function takes in a list of furniture for main room and bathroom
    and save them in a list (instead of a list of lists)
    '''
    list =[]
    for item in main:
        list.append(item)
    for item in bath:
        list.append(item)
    return list

def find_sample_zone(doorList, furnitureList, roomList):
    '''
    This function chooses the side of the object that the activity happens. For example the side on the toilet that can be sit on
    or the side of the bed that the patient can use to sit and get up from (side). The side variable is hard coded for different objects
    Then the algorithm uses a predefined length, l, to define apolygon on the activity side of the object for the fall model to sample from
    that polygon to start the trajectory (furn.samplingZone). Then a sample zone for each object is defined based on its corner sitting.
    The sample zone is the area in front of the object that is being used by the trajectory to sample from for the start and end points of
    the trajectories
    '''

    l = 0.4 # The length of the clearance, or where the activity intention sampling happens
    side = []
    sample_zones = {}

    for door in doorList:
        if door.room == 'main_room':
            sample_zones['Main Door'] = door.polygon
#            print('sample_zones:', sample_zones['Main Door'])

    for furn in furnitureList:
        if furn.name == 'Toilet':
            side = [3]
        if furn.name == 'Bed':
            side = [2,4]
        if furn.name == 'Chair-Visitor' or furn.name == 'Chair-Patient' or furn.name == 'Sofa' or furn.name == 'Couch' or furn.name == 'Sink-Bath':
            side = [2]

        x, y = furn.polygon.exterior.coords.xy # extracting the furniture orginal polygon
        theta = furn.conf[2]
        tempSamplingZone = []
        # creating the points for the sample zone polygon
        if 1 in side:
            p1 = [x[1], y[1]]
            p2 = [x[2], y[2]]
            p3 = (x[2]-l*cos(radians(theta)), y[2]-l*sin(radians(theta)))
            p4 = (x[1]-l*cos(radians(theta)), y[1]-l*sin(radians(theta)))
            tempSamplingZone.append(Polygon([p1, p2, p3, p4]))
        if 2 in side:
            p1 = (x[2], y[2])
            p2 = (x[2]+l*sin(radians(theta)), y[2]-l*cos(radians(theta)))
            p3 = (x[3]+l*sin(radians(theta)), y[3]-l*cos(radians(theta)))
            p4 = (x[3], y[3])
            tempSamplingZone.append(Polygon([p1, p2, p3, p4]))
        if 3 in side:
            p1 = [x[0], y[0]]
            p2 = [x[3], y[3]]
            p3 = (x[3]+l*cos(radians(theta)), y[3]+l*sin(radians(theta)))
            p4 = (x[0]+l*cos(radians(theta)), y[0]+l*sin(radians(theta)))
            tempSamplingZone.append(Polygon([p1, p2, p3, p4]))
        if 4 in side:
            p1 = (x[1], y[1])
            p2 = (x[0], y[0])
            p3 = (x[0]-l*sin(radians(theta)), y[0]+l*cos(radians(theta)))
            p4 = (x[1]-l*sin(radians(theta)), y[1]+l*cos(radians(theta)))
            tempSamplingZone.append(Polygon([p1, p2, p3, p4]))
        '''Check the intersection between the furniture samplinf zone and the corresponding room'''
        pp = cascaded_union(tempSamplingZone) # This makes sense when I have two sides, like bed
        if furn.room == 'main_room':
          furn.samplingZone = pp.intersection(roomList[0].polygon)
        else:
          furn.samplingZone = pp.intersection(roomList[1].polygon)
        sample_zones[furn.name] = furn.samplingZone

    return sample_zones


# -*- coding: utf-8 -*-
"""
Created on Fri Jun 22 20:22:07 2018

Simple body parse

@author: James
"""

import os
import json
import body_clean

def load_body(file_dir):

    file_list = os.listdir(file_dir)

    body_data = {}
    ref_data = {}
    str_data = ''
    email_count = 0
    linedel_count = 0

    for i in range(len(file_list)):

        filename = file_list[i]

        with open(file_dir + filename, 'r', encoding = 'utf-8') as bodyfile:

            text = bodyfile.read()
            bodyfile.close()

        text = str(json.loads(text))

        parse, clean, count = body_clean.BodyClean(text)

        parse = body_clean.bag_of_words(parse)

        body_data[str(filename[:-5])] = parse.lower()
        ref_data[str(filename[:-5])] = clean
        str_data = str_data + parse.lower()

        email_count += 1
        linedel_count = linedel_count + count

    print('\n'+str(email_count)+' emails have been read.\n'
          +str(linedel_count)+' lines have been removed.\n')

    return body_data, ref_data, str_data


#인간 대포
import sys, heapq, math

def time_walk(a,b):
    dist = ((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5
    return dist/5

def time_canon(a,b):
    dist = abs(((a[0]-b[0])**2 + (a[1]-b[1])**2)**0.5 - 50)
    return (dist/5) +2

X1, Y1 = map(float,sys.stdin.readline().split())
X2, Y2 = map(float,sys.stdin.readline().split())

N = int(sys.stdin.readline())
X = []*(N+2)
X.append([X1,Y1])
for _ in range(N):
    X.append(list(map(float,sys.stdin.readline().split())))
X.append([X2,Y2])
A = [[] for _ in range(N+2)]

for i in range(1,N+2):
    A[0].append([time_walk(X[0],X[i]),i])
    A[i].append([time_walk(X[0],X[i]),0])

for i in range(1,N+2):
    for j in range(i+1,N+2):
        A[i].append([min(time_walk(X[i],X[j]),time_canon(X[i],X[j])),j])
        A[j].append([min(time_walk(X[i],X[j]),time_canon(X[i],X[j])),i])

def dij():
    vis = [0 for _ in range(N+2)]
    time = [math.inf for _ in range(N+2)]
    queue = []
    time[0] = 0
    heapq.heappush(queue,[time[0],0])
    while(queue):
        _,cur = heapq.heappop(queue)
        if vis[cur]: continue
        vis[cur] = 1
        for d, to in A[cur]:
            time[to] = min(time[to],time[cur]+d)
            if not vis[to]:
                heapq.heappush(queue,[time[to],to])
    return time[-1]

print(dij())

import sys
a, b = map(int,sys.stdin.readline().split())
print(a-b)


import random

results = {
    1 : 0,
    2 : 0,
    3 : 0,
    4 : 0,
    5 : 0,
    6 : 0
}

antal_kast = 100000
for i in range(antal_kast):
    results[random.randint(1,6)] += 1

for key, item in results.items():
    print(f"{key}: {item}")


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

import streamlit as st
from PIL import Image

import matplotlib.pyplot as plt
import matplotlib
import seaborn as sns
import pandas as pd
import numpy as np
import datetime as dt

matplotlib.use("Agg")

st.sidebar.title('Menu')
pages = ('Início', 'Modelos preditivos', 'Modelos descritivos', 'Sobre')
selected_page = st.sidebar.radio('Paginas', pages)

csv_file = pd.read_csv('../covid19_previsoes_municipios/website/web_data/est_cidade.csv', sep=';', encoding='latin-1')
states = list(csv_file['UF'].drop_duplicates().sort_values())

df_casos = pd.read_parquet('../covid19_previsoes_municipios/data/app/covid_saude_obito_municipio.parquet')
df_casos['data'] = pd.to_datetime(df_casos['data'])

def find_cities(selected_states):
    return list(csv_file[csv_file['UF']==selected_states]['Município'].sort_values())

def filter_state_city():
    choose_state = st.sidebar.checkbox('Filtrar por estado')
    choose_city = None
    selected_state = None
    selected_city = None

    if choose_state:
        selected_state = st.sidebar.selectbox('Estado', states)
        choose_city = st.sidebar.checkbox('Filtrar por cidade')
    if choose_city:
        selected_city = st.sidebar.selectbox('Cidade', find_cities(selected_state))

    return selected_state, selected_city

def filter_date(df):
    choose_date = st.sidebar.checkbox('Filtrar por data')
    min_date = df['data'].min()
    max_date = df['data'].max()
    date_range = (dt.date(min_date.year, min_date.month, min_date.day), dt.date(max_date.year, max_date.month, max_date.day))
    selected_date = None

    if choose_date:
        selected_date = st.sidebar.slider('Data', value=date_range, format="DD/MM/YYYY")

    return selected_date

def filters(df_casos):
    selected_filters = dict()
    selected_data = st.sidebar.selectbox('Dados disponíveis', ('Casos Confirmados', 'Óbitos', 'Vacinação'))
    selected_state, selected_city = filter_state_city()

    selected_filters['state'] =  selected_state
    selected_filters['city']  = selected_city

    if selected_filters['city']:
        df_filtered = df_casos.loc[(df_casos['municipio']==selected_filters['city'])]
    else:
        df_filtered = df_casos.loc[(df_casos['municipio']=='São Paulo')]

    selected_date_range = filter_date(df_filtered)

    selected_filters['database'] = selected_data
    selected_filters['date'] = selected_date_range

    if selected_filters['date']:
        df_filtered = df_filtered.loc[(df_filtered['data'].dt.date>=selected_filters['date'][0]) & (df_filtered['data'].dt.date<=selected_filters['date'][1])]

    return selected_filters, df_filtered

def home():
    st.title('Início')

def predictive_models():
    st.title('Modelos preditivos')

    selected_filters, df_filtered = filters(df_casos)
    if selected_filters:
        st.info(f"{selected_filters}")

def descriptive_models():
    st.title('Modelos descritivos')

    selected_filters, df_filtered = filters(df_casos)
    if selected_filters:
        st.info(f"{selected_filters}")

    st.title('Número de óbitos por dia')
    st.line_chart(df_filtered[['data', 'obitosNovos']].set_index('data'))

def about():
    st.title('Sobre')

    st.markdown("""

    ### O Projeto
    Plataforma Web para disponibilizar publicamente a previsão de casos
    de óbito e vacinação relacionados à Covid-19 em nível municipal.

    ### A Gerência
    | Membro | Função |
    | ------ | ------ |
    | Francisco Louzada Neto | CEO |
    | Loriz Sallum | Diretora |
    | Oilson Gonzatto | Diretor |

    ### Os membros da equipe
    | Aluno | Função |
    | ------ | ------ |
    | Bernardo | Estatístico |
    | Bruno Braziel | Programador |
    | Francisco Pigato | Coordenador |
    | Lucas Nakadaira | Programador |
    | Mariana Spanol | Estatística |

    #### PROBABILIDADE E ESTATÍSTICA
    #### MECAI - 2021
    """)

# In[ ]:
if selected_page == 'Início':
    home()
elif selected_page == 'Modelos preditivos':
    predictive_models()
elif selected_page == 'Modelos descritivos':
    descriptive_models()
elif selected_page == 'Sobre':
    about()


"""This module provides a framework that can be used to create games."""
import time
import math
import random
import pygame

# Colors
WHITE = [225, 225, 225]
BLACK = [0, 0, 0]
YELLOW = [255, 255, 0]
RED = [255, 0, 0]
GREEN = [0, 128, 0, 128]
BLUE = [0, 192, 255, 128]

# Directions
BOTTOM = 0
TOP = 1
LEFT = 2
RIGHT = 3

# State variables
CURRENT_STATE = 0
PREVIOUS_STATE = 0
EPSILON = 1.0e-15

def init(window, name):
    """Initialize pygame and random seed."""
    pygame.init()
    random.seed(time.time())
    pygame.display.set_caption(name)
    return pygame.display.set_mode(window.as_sequence())

# create a random position from the given range of values
def random_position(minimum, maximum):
    """create a random position from the given range of values"""
    return (random.randint(minimum, maximum), random.randint(minimum, maximum))

class SIZE:
    """Size class used to keep track of a width and height."""
    width = 1.0
    height = 1.0
    def __init__(self, width_value, height_value):
        self.width = width_value
        self.height = height_value

    def as_sequence(self):
        """Returns the width and height as a truple."""
        return (self.width, self.height)

class OBJECT:
    """Object class used to track objects, their positions, and their image data."""
    sprite = 0
    location = pygame.math.Vector2(0, 0)
    scale = pygame.math.Vector2(1, 1)
    velocity = pygame.math.Vector2(0, 0)
    rotation = 0
    active = False
    collision = [False] * 4

    def __init__(self, image):
        self.location = pygame.math.Vector2(0, 0)
        self.velocity = pygame.math.Vector2(0, 0)
        self.sprite = image

    def get_transformed_rect(self):
        """returns a transformed version of the object sprite."""
        sprite = pygame.transform.rotate(self.sprite, self.rotation)
        rect = sprite.get_rect()
        rect.center = self.location + self.velocity
        return rect

    def width(self):
        """Gets the width of the object."""
        rect = self.get_transformed_rect()
        return rect.width

    def height(self):
        """Gets the height of the object."""
        rect = self.get_transformed_rect()
        return rect.height

    def move(self, x_value, y_value):
        """Move the object by the given coordinates"""
        self.location += pygame.math.Vector2(x_value, y_value)

    def set_position(self, x_value, y_value):
        """Teleport the object to the given values (x, y)"""
        self.location = pygame.math.Vector2(x_value, y_value)

    def add_rotation(self, degrees):
        """Add to the existing rotation of an object in degrees. Positive is clockwise."""
        self.rotation = self.rotation + degrees
        self.rotation = self.rotation - 360 * int(self.rotation /360)

    def set_rotation(self, degrees):
        """Set the rotation of the object to the given value in degrees. Positive is clockwise."""
        self.rotation = degrees - 360 * int(degrees / 360)

    def add_velocity(self, direction, speed, max_speed):
        """Add velocity to the object with the given direction and speed."""
        direction = pygame.math.Vector2(math.cos(math.radians(direction - 90)),
                                        math.sin(math.radians(direction - 90)))
        if direction.x < EPSILON and direction.x > 0:
            direction.x = 0

        if direction.y < EPSILON and direction.y > 0:
            direction.y = 0

        vel = pygame.math.Vector2(-1 * direction.x * speed, direction.y * speed)

        self.velocity += vel
        distance_sq = self.velocity.length()

        if distance_sq > max_speed:
            self.velocity.normalize_ip()
            self.velocity *= max_speed

    def set_velocity(self, direction, speed):
        """Set the velocity of the object to the given value given an angle and speed."""
        self.velocity.x = -1 * math.cos(math.radians(direction - 90)) * speed
        self.velocity.y = math.sin(math.radians(direction - 90)) * speed

    def collides_with(self, other_obj):
        """Check if this object collides with the given object."""
        # check for early rejection.
        dist = (self.location - other_obj.location).length_squared()
        # if distance between objects is greater then 64^2
        if dist > 4096:
            self.collision[BOTTOM] = self.collision[TOP] = False
            self.collision[LEFT] = self.collision[RIGHT] = False
            return False

        #get transformed rectangles
        rect1 = self.get_transformed_rect()
        rect2 = other_obj.get_transformed_rect()

        if not rect1.colliderect(rect2):
            return False

        self.collision[BOTTOM] = rect2.collidepoint((rect1.center[0] - rect1.width / 4, rect1.center[1] + rect1.height / 2)) or rect2.collidepoint((rect1.center[0] + rect1.width / 4, rect1.center[1] + rect1.height / 2))
        self.collision[TOP] = rect2.collidepoint((rect1.center[0] - rect1.width / 4, rect1.center[1] - rect1.height / 2)) or rect2.collidepoint((rect1.center[0] + rect1.width / 4, rect1.center[1] - rect1.height / 2))
        self.collision[LEFT] = rect2.collidepoint((rect1.center[0] - rect1.width / 2, rect1.center[1] + rect1.height / 4)) or rect2.collidepoint((rect1.center[0] - rect1.width / 2, rect1.center[1] - rect1.height / 4))
        self.collision[RIGHT] = rect2.collidepoint((rect1.center[0] + rect1.width / 2, rect1.center[1] + rect1.height / 4)) or rect2.collidepoint((rect1.center[0] + rect1.width / 2, rect1.center[1] - rect1.height / 4))

        return True

    def snap_to_object_x(self, other_obj, direction):
        """Snaps the object to the left or right of the other object given."""
        if direction == LEFT:
            self.location.x = (other_obj.location.x +
                               other_obj.width() / 2 +
                               self.width() / 2)
        else:
            self.location.x = (other_obj.location.x -
                               (other_obj.width() / 2 +
                                self.width() / 2))

    def snap_to_object_y(self, other_obj, direction):
        """Snaps the object to the left or right of the other object given."""
        if direction == TOP:
            self.location.y = (other_obj.location.y +
                               other_obj.height() / 2 +
                               self.height() / 2)
        else:
            self.location.y = (other_obj.location.y -
                               (other_obj.height() / 2 +
                                self.height() / 2))

    def collides_with_point(self, point):
        """Check if this object collides with the given point."""
        sprite = pygame.transform.rotate(self.sprite, self.rotation)
        rect = sprite.get_rect()
        location = self.location + self.velocity
        rect.center = location
        return rect.collidepoint(point)

    def draw(self, screen):
        """Updates and draws the object to the screen."""
        sprite = pygame.transform.rotate(self.sprite, self.rotation)
        rect = sprite.get_rect()
        self.location += self.velocity
        rect.center = self.location
        screen.blit(sprite, rect)

# Returns an array of all lines in a given file.
def read_file(filename):
    """Read a file line by line and return an array of strings."""
    # Create an empty array.
    array = []
    # Open our file for read.
    file = open(filename, 'r')

    # put all the lines in an array
    for line in file:
        array.append(line.rstrip())

    return array

def screen_wrap(obj, window):
    """Wraps a given framework object around the screen, returns true if object is at edge."""
    flag = False
    # Wrap X direction
    if obj.location.x > window.width:
        obj.location.x = 0
        flag = True
    elif obj.location.x < 0:
        obj.location.x = window.width
        flag = True

    # Wrap Y direction
    if obj.location.y > window.height:
        obj.location.y = 0
        flag = True
    elif obj.location.y < 0:
        obj.location.y = window.height
        flag = True

    return flag

def health_bar(screen, health, max_health, max_size, location):
    """Creates a health bar at the given position."""
    if health > max_health - max_health * 0.25:
        bar_color = GREEN
    elif health > max_health - max_health * 0.5:
        bar_color = YELLOW
    else:
        bar_color = RED

    width = max_size[0] * (health / max_health)
    pygame.draw.rect(screen, bar_color, (location[0], location[1], width, max_size[1]))


# -*- coding: utf-8 -*-
import os
import uuid
from django.conf import settings
from PIL import Image

upload_path = os.path.join(settings.DIRNAME, 'static', 'uploads')

def resize(path, box, fit):
   '''Downsample the image.
   @param img: Image -  an Image-object
   @param box: tuple(x, y) - the bounding box of the result image
   @param fit: boolean - crop the image to fill the box
   '''
   img = Image.open(path)

   #preresize image with factor 2, 4, 8 and fast algorithm
   width_ratio = float(img.size[0]) / float(box[0])
   height_ratio = float(img.size[1]) / float(box[1])

   ratio = min(width_ratio, height_ratio)

   if ratio > 1:
      new_width = int(img.size[0]/ratio)
      new_height = int(img.size[1]/ratio)
      img.thumbnail((new_width, new_height), Image.NEAREST)

   #calculate the cropping box and get the cropped part
   if fit:
      x1 = y1 = 0
      x2, y2 = img.size
      wRatio = 1.0 * x2/box[0]
      hRatio = 1.0 * y2/box[1]

      if hRatio > wRatio:
         y1 = y2/2-box[1]*wRatio/2
         y2 = y1+box[1]
      else:
         x1 = x2/2-box[0]*hRatio/2
         x2 = x1+box[0]

      img = img.crop((int(x1),int(y1),int(x2),int(y2)))

   #Resize the image with best quality algorithm ANTI-ALIAS
   img.thumbnail(box, Image.ANTIALIAS)

   return img

class PhotoStorage:

    @classmethod
    def save_uploaded_file(cls, f, sizes=None):

        # generate file name
        unique_id = str(uuid.uuid4())
        unique_path = unique_id.split('-')

        # use last element as file name
        file_name = unique_path.pop()

        temp, ext = os.path.splitext(f.name)

        file_name = ''.join([file_name, ext])

        # sub path of file, with in the uploads folder
        file_dir = '/'.join(unique_path)

        # absolute dir of file
        full_file_dir = os.path.join(upload_path, file_dir)

        if not os.path.exists(full_file_dir):
            os.makedirs(full_file_dir)

        file_path = '/'.join([full_file_dir, file_name])

        destination = open(file_path, 'wb+')

        for chunk in f.chunks():
            destination.write(chunk)

        destination.close()

        img = Image.open(file_path)
        if img.mode != 'RGB':
          img = img.convert('RGB')

        paths = file_path.split('.')
        new_path = '%s.jpg' % paths[0]
        width,height = img.size
        img.save(new_path, 'JPEG', quality=95)

        if new_path != file_path:
          os.unlink(file_path)
          names = file_name.split('.')
          file_name = '%s.jpg' % names[0]

        # original file
        files = []
        files.append('/'.join([file_dir, file_name]))

        if sizes is not None:
            # resize image
            for size in sizes:
                files.append(cls.resize_image(files[0], size[0], size[1]))

        return files, width, height

    @classmethod
    def resize_image(cls, path, width, height):

        size = width, height

        dir_name = os.path.dirname(path)
        name, ext = os.path.splitext(path)
        path = os.path.join(upload_path, path)

        size = [width, height]
        im = resize(path, size, True)

        width, height = im.size
        relative_path = ''.join([name, str(width), 'x', str(height), ext])
        new_file_name = os.path.join(upload_path, relative_path)
        im.save(new_file_name, 'JPEG', quality=95)

        return relative_path


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
matplotlib是类似matlab的一个可视化的画图包
"""
import matplotlib.pyplot as plt
import numpy as np

# 将-1到1之间平分成50分，返回50个点的坐标
x = np.linspace(-1, 1, 50)

print(x)

y = 2 * x + 1

plt.plot(x, y)

plt.show()

y = x**2

plt.plot(x, y)

plt.show()


# -*- coding: utf-8 -*-
"""
Created on Fri Mar 13 10:26:49 2020

@author: Ola
"""
#wip - work in progress
import math
from math import *
print("""Kalkulator tarasu """)
choose = input("""Jaki typ tarasu wybierasz?
               s - standardowy, c - niestandardowy:\n""")
def tarasStandardowy():
    print("Podaj wymiary trarasu w metrach")
    bok_tarasu_a = float(input())
    bok_tarasu_b = float(input())

    print("Wymiary paneli/płyt w metrach")
    bok_panela_a = float(input())
    bok_panelu_b = float(input())

    powierzchnia_tarasu = bok_tarasu_a*bok_tarasu_b
    powierzchnia_plyty = bok_panela_a * bok_panelu_b

    print("Będzie potrzebnych:",powierzchnia_tarasu/powierzchnia_plyty,"płyt")

def tarasDostosowany():
    print("Podaj wymiary tarasu w metrach: ")
    bok_a = float(input("Bok a: "))
    bok_b = float(input("Bok b: "))
    bok_c = float(input("Bok c: "))
    bok_d = float(input("Bok d: "))
    bok_e = float(input("Bok e: "))
    bok_f = float(input("Bok f: "))
    bok_g = float(input("Bok g: "))
    bok_h = float(input("Bok h: "))

    print("Podaj wymiary płyty/panela w metrach: ")
    plyta_a = float(input("Bok a: "))
    plyta_b =float(input("Bok b: "))
    if bok_a + bok_g == bok_c + bok_e and bok_b+bok_d == bok_h + bok_f:
        powierzchnia_tarasu = pow((bok_a+bok_g),2) * pow((bok_h + bok_f),2)
        powierzchnia_plyty = plyta_a * plyta_b
        print("Będzie potrzebnych:",powierzchnia_tarasu/powierzchnia_plyty,"płyt")

if choose == "s":
    tarasStandardowy()
else:
    tarasDostosowany()


from moviepystabilizer import wrapcv
import shelve
import hashlib
import struct

class VideoStabilizer:
    def __init__(self, sourceClip, cache="/tmp/moviepystabilizer.cache", **kwargs):
        self._cache = cache
        self._digest = self._clipDigest(sourceClip)
        savedMotions = self._cachedSavedMotions(self._digest)
        self._shouldCache = savedMotions == ""
        self._internal = wrapcv.VideoStabilizer(
            source=_ClipWrapper(sourceClip, self._cacheSavedMotions),
            width=sourceClip.w,
            height=sourceClip.h,
            saved_motion=savedMotions,
            **kwargs)

    def reset(self):
        return self._internal.reset()

    def nextFrame(self):
        return self._internal.nextFrame()

    def _cacheSavedMotions(self):
        if self._cache is None:
            return
        if not self._shouldCache:
            return
        saved = self._internal.savedMotion()
        cacheShelve = shelve.open(self._cache)
        try:
            cacheShelve[self._digest] = saved
        finally:
            cacheShelve.close()

    def _cachedSavedMotions(self, digest):
        if self._cache is None:
            return ""
        cacheShelve = shelve.open(self._cache)
        try:
            cached = cacheShelve.get(digest, "")
            return cacheShelve.get(digest, "")
        finally:
            cacheShelve.close()

    def _clipDigest(self, clip):
        digest = hashlib.sha512()
        digest.update(struct.pack("I", clip.w))
        digest.update(struct.pack("I", clip.h))
        digest.update(struct.pack("d", clip.duration))
        digest.update(struct.pack("d", clip.fps))
        digest.update(clip.get_frame(0).tostring())
        digest.update(clip.get_frame(clip.duration).tostring())
        return digest.digest()

class _ClipWrapper:
    def __init__(self, clip, saveMotionCallback):
        self._clip = clip
        self._saveMotionCallback = saveMotionCallback
        self._iterator = None
        self._done = False

    def reset(self):
        self._iterator = None
        self._done = False

    def nextFrame(self):
        if self._iterator is None:
            self._iterator = self._clip.iter_frames(dtype="uint8")
        if self._done:
            return None
        try:
            result = self._iterator.next()
            return result
        except StopIteration:
            self._done = True
            if self._saveMotionCallback is not None:
                self._saveMotionCallback()
                self._saveMotionCallback = None
            return None


import re
import os
import json
from lib.commands.core.git import changed_file_gpaths, untracked_file_gpaths, make_stamp
from lib.commands.core.custom_types import Config
from lib.commands.core.configure import load_config
from lib.commands.core.shell import fpshell

yes_command = ["Y", "YES"]

def c_save_history(commit=True, debug=True):
    gpaths = changed_file_gpaths()
    ut_gpaths = untracked_file_gpaths()
    stamp = make_stamp()
    config: Config = load_config()
    uuid = config["uuid"]
    commit_header = config["commit_header"]

    doc_uuid = fr".docs/{uuid}"

    doc_gpaths = [gpath for gpath in gpaths if re.match(doc_uuid, gpath)]
    ut_gpaths = [ut_gpath for ut_gpath in ut_gpaths if re.match(doc_uuid, ut_gpath)]

    for gpath in doc_gpaths + ut_gpaths:
        print(f"Save change history of {gpath}? [y/N]")
        yes_or_no = input()
        if yes_or_no.upper() in yes_command:
            if re.match(fr"{doc_uuid}/", gpath):
                print("Put a commit message")
                user_message = input()
                history_gpath = re.sub(r".docs", ".histories", gpath)
                root_path = config["root_path"]
                save_path_body, save_path_file_type = os.path.splitext(
                    f"{root_path}/{history_gpath}"
                    )
                if save_path_body and commit:
                    save_path = f"{save_path_body}-{save_path_file_type}.json"
                    if os.path.isfile(save_path):
                        with open(save_path, "r") as f:
                            history_data = json.load(f)
                        with open(save_path, "w") as f:
                            diff_log = stamp.get(gpath)
                            if diff_log:
                                history_data.append(diff_log)
                                json.dump(history_data, f)
                    else:
                        with open(save_path, "w") as f:
                            diff_log = stamp.get(gpath)
                            if diff_log:
                                json.dump([diff_log], f)

                stage_and_commit_command = f"git add {gpath} && git commit -m '{commit_header} {user_message}'"
                if debug:
                    print(stage_and_commit_command)
                if commit:
                    fpshell(stage_and_commit_command)


# UFCG - 2019.2
# André Lucas Medeiros Martins - 119210592
# Tweets por Página

total_tweets = int(input())

paginas = total_tweets//400

porcentagem = ((total_tweets - paginas*400)/total_tweets)*100

print("Serão necessárias {} página(s) para visualizar os tweets.".format(paginas))
print("{:.1f}% dos tweets serão perdidos.".format(porcentagem))


from typing import TypeVar, List

from jmetal.algorithm.singleobjective.evolutionaryalgorithm.elitistEvolutionStrategy import ElitistEvolutionStrategy
from jmetal.core.operator.mutationoperator import MutationOperator
from jmetal.core.problem.problem import Problem

""" Class representing elitist evolution strategy algorithms """
__author__ = "Antonio J. Nebro"

S = TypeVar('S')
R = TypeVar('R')

class NonElitistEvolutionStrategy(ElitistEvolutionStrategy[S, R]):
    def __init__(self, problem: Problem[S], mu: int, lambdA: int,
                 max_evaluations: int, mutation_operator: MutationOperator[S]):
        super(NonElitistEvolutionStrategy, self).__init__(problem, mu, lambdA,
                                                    max_evaluations, mutation_operator)

    def replacement(self, population: List[S], offspring_population: List[S])\
            -> List[S]:
        offspring_population.sort(key=lambda s: s.objectives[0])

        new_population = []
        for i in range(self.mu):
            new_population.append(offspring_population[i])

        return new_population

    def get_name(self):
        return "("+str(self.mu)+ "," + str(self.lambdA)+")ES"


'''

Codeforces A. Stones on the Table

'''
n = int(input())
s = input()
a = 0

for i in range(0, n-1):
    if s[i] == s[i+1]:
        a+=1

print(a)