from markdown.inlinepatterns import ImagePattern, IMAGE_LINK_RE
from markdown.extensions import Extension
import re

"""Extension allows you to specify the width and height of the image in markdown
    ![AgriInnovate Logo]({filename}/images/sms_controller/agri_innovate.jpg =400x600)
    ![AgriInnovate Logo]({filename}/images/sms_controller/agri_innovate.jpg =400x)
"""

class ImageExtensions(Extension):
    def extendMarkdown(self, md, md_globals):
        md.inlinePatterns['image_link'] = ImageWithSize(IMAGE_LINK_RE, md)

class Match(object):
    def __init__(self):
        self.data = dict()

    def set(self, key, value):
        self.data[key] = value

    def group(self, key):
        if key in self.data:
            return self.data[key]
        else:
            return None

REGEX_MATCH = '.*(?:=(\d+)x(\d*)).*'
REGEX_REPL = '=(\d+)x(\d*)'

class ImageWithSize(ImagePattern):
    def handleMatch(self, m):
        regex_repl = re.compile(REGEX_REPL)
        src_string = m.group(9)
        width, height = "", ""

        if regex_repl.search(m.group(9)):
            regex_match = re.compile(REGEX_MATCH)
            width, height = regex_match.match(src_string).groups()
            src_string = regex_repl.sub("", src_string)

        match = Match()
        match.set(2, m.group(2))
        match.set(9, src_string)
        tree = super().handleMatch(match)
        if width:
            tree.set('width', width)
        if height:
            tree.set('height', height)
        return tree


# Given a string with capital letters, punctuation and spaces, determine if the sequence is a palindrome. Return true or false. Don't forget your edge cases!

# Example Input: "bl o lb"
# Example Output: True

# Example Input: "Hey ,sis, yeh"
# Example Output: False

# Example Input: "RacecaR"
# Example Output: True

# Do not store a new copy of the string. Try to do this with O(1) space complexity

word = "Hey ,sis, yeh"

def palindrom(word):
    return  word == word[::-1]

print(palindrom(word))

# Given a string with capital letters, punctuation and spaces, return the longest palindrome sequence.
#Don't forget your edge cases!

# Example Input: "Hey ,sis, yeh"
# Example Output: "ey, sis, ye"

# Example Input: "racecars are great!"
# Example Output: "racecar"

# Example Input: "summer love"
# Example Output: "mm"
word = "racecars are great!"

def word_chacker(word):
    split_word = list(word)
    j = -1
    for i, num in enumerate(split_word):
        if split_word[i] != split_word[j]:
            split_word.remove(split_word[i])
            split_word.remove(split_word[j])
        j -= 1
    return "".join(split_word)

def chek_longest(word):
    splited_s = word.split()
    print(splited_s)
    s = []
    for w in splited_s:
        b = word_chacker(w)
        s.append(b)
        print(b)
    print(s)
    return s

print(chek_longest(word))

def longestPalindrome(s):
    # Create a string to store our resultant palindrome
    palindrome = ''

    # loop through the input string
    for i in range(len(s)):

        # loop backwards through the input string
        for j in range(len(s), i, -1):

            # Break if out of range
            if len(palindrome) >= j-i:
                break

            # Update variable if matches
            elif s[i:j] == s[i:j][::-1]:
                palindrome = s[i:j]
                break

    return palindrome


import os
import subprocess
import tempfile

from fetch import Fetch
from linchpin.exceptions import LinchpinError

class FetchGit(Fetch):
    def __init__(self, ctx, fetch_type, src, dest, cache_dir, root):
        super(FetchGit, self).__init__(ctx, fetch_type, dest, root)
        self.src = src

        self.cache_dir = os.path.join(cache_dir, "git")
        if not os.path.exists(self.cache_dir):
            os.mkdir(self.cache_dir)

    def fetch_files(self):
        # The key cannot contain ':' since linchpin does not support python 3.
        # Configparser uses ':' as a delimiter, which poses problem when using
        # urls in key during parsing. Delimiters can be specified when
        # initializing a configparser object in python 3 so this does not
        # become an issue.
        key = "{0}|{1}".format(self.dest.replace(':', ''),
                               self.src.replace(':', ''))

        fetch_dir = self.cfgs["git"].get(key, None)
        td = self.call_clone(fetch_dir)

        if fetch_dir is None:
            self.write_cfg("git", key, td)

        if self.root is not None:
            for ext in self.root:
                self.tempdirs.append(os.path.join(td, ext.lstrip('/')))
        else:
            self.tempdirs.append(td)

    def call_clone(self, fetch_dir=None):
        if fetch_dir:
            retval = subprocess.call(
                ['git', '-C', fetch_dir, 'pull', '--quiet'])
            tempdir = fetch_dir
        else:
            tempdir = tempfile.mkdtemp(prefix="git_", dir=self.cache_dir)
            retval = subprocess.call(
                ['git', 'clone', '--quiet', self.src, tempdir])

        if retval != 0:
            raise LinchpinError("Unable to clone {0}".format(self.src))
        return tempdir


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

def how_many_squares(line):
    n,m = line.split()
    return ((int(n)-1)*(int(m)-1))

if __name__=='__main__':
    test_or_submit = 'test'
    counter = 0
    current_counter = 0
    current_line=2
    with open(test_or_submit+'Input') as f:
        with open(test_or_submit+'Output', 'w') as r:
            lines = f.readlines()[1:]
            for idx, line in enumerate(lines):
                try:
                    n,m = line.split()
                    current_line = idx + 1
                    counter += 1
                    current_counter = counter
                    print('n {} m {} count {}'.format(n,m, counter))
                except ValueError:
                    if counter != current_counter:
                        print(lines[current_line:current_line+int(n)])
                        r.write('Case #{}: {}\n'.format(counter,''))
                    #print('is tabletop')


#
# @lc app=leetcode.cn id=42 lang=python3
#
# [42] 接雨水
#
# %%
# @lc code=start
class Solution:
    def trapBrutal(self, height):
        if len(height) < 3:
            return 0
        res = 0
        left_max = 0
        right_max = 0
        for i in range(1, len(height) - 1):
            for j in range(0, i):
                if height[j] > left_max:
                    left_max = height[j]
            for j in range(i+1, len(height)):
                if height[j] > right_max:
                    right_max = height[j]
            res += max(min(left_max, right_max) - height[i], 0)
            left_max, right_max = 0, 0
        return res

    def trap(self, height):
        stack = []
        res = 0
        for i in range(len(height)):
            while stack and height[i] > height[stack[-1]]:
                curr = height[stack.pop()]
                if not stack:
                    break
                res += (min(height[stack[-1]] - curr, height[i] - curr)) * (i - stack[-1] - 1)
            stack.append(i)
        return res
# @lc code=end
# %%


try:
  import usocket as socket
except:
  import socket

from machine import Pin, ADC
import network
import ntptime
import time
import urequests
import ujson as json
import dht

analogPin = ADC(0)
lightPin = Pin(0, Pin.OUT)
soilPin = Pin(14, Pin.OUT)
ledPin = Pin(2, Pin.OUT)
tempSensorPin = dht.DHT11(Pin(5))
relayPin = Pin(4, Pin.OUT)
relayPin.off()
ledPin.off()

insertUrl = "https://data.mongodb-api.com/app/data-ojsvg/endpoint/data/v1/action/insertOne"
findOneUrl = "https://data.mongodb-api.com/app/data-ojsvg/endpoint/data/v1/action/findOne"

api=""

ssid = ''
password = ''

headers = {
  'Content-Type': 'application/json',
  'Access-Control-Request-Headers': '*',
  'api-key': api,
}

wlanStation = network.WLAN(network.STA_IF)
wlanStation.active(True)
wlanStation.connect(ssid, password)
accessPoint = network.WLAN(network.AP_IF)
accessPoint.active(False)

while wlanStation.isconnected() == False:
  pass

def begin_settime():
  try:
    ntptime.host = "1.europe.pool.ntp.org"
    ntptime.settime()
  except Exception as e:
    htmlPage = """
        <!DOCTYPE html>

            <title>My MicroPython Web Server</title>

BOOT

"""+str(e)+"""

Restart required

        """

    clientSocket, clientAddress = serverSocket.accept()
    serve(clientSocket,htmlPage)

def serve(clientSocket,htmlPage):
    request = clientSocket.recv(1024)
    response = "HTTP/1.1 200 OK\r\nContent-Type: text/html\r\n\r\n" + htmlPage
    clientSocket.send(response)
    clientSocket.close()

serverSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverSocket.bind(('0.0.0.0', 80))
serverSocket.listen(1)

print()
print('Connection successful')
print(wlanStation.ifconfig())
begin_settime()
ledPin.on()


"""
coda-kids is a partial wrapper package around pygame. It's purpose
is to make game development more accessible to a younger audiences
of students. It provides inline documentation, wrappers for linter
unfriendly features, and provides utility functionality/classes such
as game objects and constants for common colors.

It is currently being designed for and tested with a series of
game programming exercises for an educational book titled
Coda Kids.

The package was designed and implemented with and for the
following toolset:

Python 3.5.2 with lastest Pygame and Pylint
Visual Studio Code 1.11+ with the Python extension installed.
"""
import pygame

import framework.coda_kids.color
import framework.coda_kids.utilities
import framework.coda_kids.dir
import framework.coda_kids.event
import framework.coda_kids.state
import framework.coda_kids.actions

def start(window_size, game_name):
    """
    Initializes the library and returns a pygame screen. Call this first!

        SCREEN = coda.start((w, h), "Title");
    """
    pygame.init()
    framework.coda_kids.utilities.time.sleep(2)
    framework.coda_kids.utilities.random.seed(framework.coda_kids.utilities.time.time())
    pygame.display.set_caption(game_name)
    pygame.mixer.init()
    return pygame.display.set_mode((int(window_size[0]), int(window_size[1])))

def stop():
    """
    Stops pygame and closes the window immediately.

        coda.stop();
    """
    framework.coda_kids.utilities.sys.exit()

class Image:
    def __init__(self, image_file_name):
        if image_file_name is not None:
            self.data = pygame.image.load(image_file_name).convert_alpha()
        else:
            self.data = None

    def update(self, dt):
        return

    def surface(self):
        return self.data

def Sound(sound_file_name):
    """
    Loads and returns a sound file with the given file name.

        SOUND = coda.Image("Example.wav");
    """
    return pygame.mixer.Sound(sound_file_name)

def draw_rect(screen, color, top_left, size):
    """
    Draw's a rectangle with the given values. Doesn't return.

        coda.draw_rect(SCREEN, (r, g, b, a), (0, 0), (10, 10));
    """
    pygame.draw.rect(screen, color, (top_left[0], top_left[1], size[0], size[1]))

def Vector2(X_VALUE, Y_VALUE):
    """
    Creates a 2D coordinate with values x and y. Can also be used as a tuple.

        a = coda.Vector2(1, 1) # a = (1, 1);

        b = coda.vector2(2, 4) # b = (2, 4);

        c = coda.Vector2(a.x, b.y) # c = (a[0], b[1]);
    """
    return pygame.math.Vector2(X_VALUE, Y_VALUE)

def start_draw(screen, fill_color):
    """Begin drawing to the screen."""
    screen.fill(fill_color)

def end_draw():
    """End drawing to screen."""
    pygame.display.flip()

class CountdownTimer:
    """
    Countdown timer class for timer logic.

        timer = CountdownTimer(seconds);

        if (timer.tick(delta_time)):
            do_things();
    """
    def __init__(self, max_time):
        """Initialize the timer with the given values."""
        self.max_time = max_time
        self.current_time = 0

    def tick(self, delta_time):
        """update timer and check if finished."""
        self.current_time += delta_time
        if self.current_time >= self.max_time:
            return True
        return False

class SpriteSheet:
    """
    Sprite sheet class for managing sprite animations.

        sheet = coda.SpriteSheet("image.png", (16, 16));
    """

    def __init__(self, filename, frame_size):
        self.sheet = pygame.image.load(filename).convert_alpha()
        rect = self.sheet.get_rect()
        self.columns = rect.width / frame_size[0]
        self.rows = rect.height / frame_size[1]
        rect.width = frame_size[0]
        rect.height = frame_size[1]
        self.rectangle = rect

    def image_at(self, index):
        """
        Get an image at the given 0 based index.

            obj.sprite = sheet.image_at(0);
        """
        x = framework.coda_kids.utilities.math.floor(index % self.columns) * self.rectangle.width
        y = framework.coda_kids.utilities.math.floor(index / self.columns) * self.rectangle.height
        self.rectangle.centerx = x + self.rectangle.width / 2
        self.rectangle.centery = y + self.rectangle.height / 2
        image = Image(None)
        image.data = pygame.Surface(self.rectangle.size, pygame.SRCALPHA, 32).convert_alpha()
        image.data.blit(self.sheet, (0, 0), self.rectangle)
        return image

    def num_frames(self):
        """
        Return the number of frames of animation for the given sheet.

            size = sheet.num_frames();
        return self.columns * self.rows
        """
        return self.columns * self.rows

class Animator:

    def __init__(self, sheet, duration_seconds):
        self.sheet = sheet
        self.frame_num = 0

        self.frame_time = 0.0

        self.playing = True
        self.playspeed = 1.0
        self.looping = True

        self.reset()
        self.set_duration(duration_seconds)

    def set_duration(self, duration_seconds):
        self.duration = duration_seconds
        self.transition = self.duration / self.num_frames

    def use_anim(self, sheet):
        self.sheet = sheet
        self.reset()

    def reset(self):
        self.frame_num = 0
        self.current = self.sheet.image_at(self.frame_num)
        self.frame_time = 0
        self.num_frames = self.sheet.num_frames()

    def play(self, playspeed=1.0):
        self.playspeed = playspeed
        self.reset()
        self.unpause()

    def pause(self):
        self.playing = False

    def unpause(self):
        self.playing = True

    def update(self, dt):
        dt = dt * self.playspeed

        if self.playing:
            self.frame_time += dt

            if self.frame_time >= self.transition:
                self.frame_time -= self.transition
                self.frame_num += 1

                if self.looping:
                    self.frame_num %= self.num_frames

                self.current = self.sheet.image_at(self.frame_num)

                if self.frame_num >= self.num_frames:
                    self.playing = False

    def surface(self):
        return self.current.surface()

class Object:
    """
    Object class used to organize and track common game object data, such as location and appearance.

        obj = coda.Object(IMAGE);
    """
    location = Vector2(0, 0)
    scale = 1
    velocity = Vector2(0, 0)

    def __init__(self, image):
        self.sprite = image
        self.rotation = 0
        self.active = False
        self.collision = [False] * 5

    def __setattr__(self, name, value):
        if name == "location" or name == "velocity":
            self.__dict__[name] = pygame.math.Vector2(value[0], value[1])
        elif name == "rotation":
            self.__dict__[name] = value - 360 * int(value / 360)
        elif name == "sprite":
            if isinstance(value, Image):
                self.__dict__[name] = value
            elif isinstance(value, Animator):
                self.__dict__[name] = value
        else:
            self.__dict__[name] = value

    def get_transformed_rect(self):
        """
        Returns a transformed version of the object sprite. Generally for internal use only.

            rect = obj.get_transformed_rect();
        """
        sprite = pygame.transform.rotozoom(self.sprite.surface(), self.rotation, self.scale)
        rect = sprite.get_rect()
        rect.center = self.location
        return rect

    def width(self):
        """
        Gets the width of the object in reference to it's image data.

            width = obj.width();
        """
        rect = self.get_transformed_rect()
        return rect.width

    def height(self):
        """
        Gets the height of the object in reference to it's image data.

            height = obj.height();
        """
        rect = self.get_transformed_rect()
        return rect.height

    def add_rotation(self, degrees):
        """
        Add to the existing rotation of an object in degrees. Positive is clockwise.

            obj.add_rotation(90);
        """
        self.rotation = self.rotation + degrees
        self.rotation = self.rotation - 360 * int(self.rotation /360)

    def add_velocity(self, direction, speed, max_speed):
        """
        Add velocity to the object with the given direction and speed.

            obj.add_velocity((0, 1), 1, 10); # increase upwards
        """
        epsilon = 1.0e-15
        direction = Vector2(framework.coda_kids.utilities.math.cos(framework.coda_kids.utilities.math.radians(direction - 90)),
                            framework.coda_kids.utilities.math.sin(framework.coda_kids.utilities.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 = 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, degrees, speed):
        """
        set velocity of the object with the given angle and speed.

            obj.set_velocity(45, 5); # left 5
        """
        self.velocity = Vector2(-1 * framework.coda_kids.utilities.math.cos(framework.coda_kids.utilities.math.radians(degrees - 90)) * speed,
                                framework.coda_kids.utilities.math.sin(framework.coda_kids.utilities.math.radians(degrees - 90)) * speed)

    def collides_with(self, other_obj):
        """
        Check if this object collides with the given object.

            if obj1.collides_with(obj2):
                do_things();
        """
        # 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[coda_kids.dir.DOWN] = self.collision[coda_kids.dir.UP] = False
            self.collision[coda_kids.dir.LEFT] = self.collision[coda_kids.dir.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[coda_kids.dir.DOWN] = 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[coda_kids.dir.UP] = 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[coda_kids.dir.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[coda_kids.dir.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, facing):
        """
        Snaps the object to the left or right of the other object given.

            # Snap obj1 left of obj2
            obj1.snap_to_object_x(obj2, coda.dir.LEFT);
        """
        if facing == framework.coda_kids.dir.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, facing):
        """
        Snaps the object to the left or right of the other object given.

            # Snap obj1 left of obj2
            obj1.snap_to_object(obj2, coda.dir.LEFT);
        """
        if facing == framework.coda_kids.dir.UP:
            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 position.

            # point
            obj.collides_with_point(10, 10);

            # Mouse position
            obj.collides_with_point(coda.event.mouse_position());
        """
        sprite = pygame.transform.rotate(self.sprite.surface(), self.rotation)
        rect = sprite.get_rect()
        location = self.location + self.velocity
        rect.center = location
        return rect.collidepoint(point)

    def update(self, delta_time):
        self.location += self.velocity * delta_time
        self.sprite.update(delta_time)

    def draw(self, screen):
        """
        draws the object to the screen.

            # draw the object
            obj.draw(SCREEN);
        """
        sprite = pygame.transform.rotozoom(self.sprite.surface(), self.rotation, self.scale)
        rect = sprite.get_rect()
        rect.center = self.location
        screen.blit(sprite, rect)

class TextObject:
    """
    Create an object that renders text. Assumes that the default font
    freesansbold exists in the project directory as a true type font.

        #create a text object
        title = TextObject(coda.color.RED, 12, "example");
    """

    def __init__(self, color_value, font_size, text):
        self.location = Vector2(0, 0)
        self.color = color_value
        self.font_size = font_size
        self.text = text
        self.centered = False

    def __setattr__(self, name, value):
        if name == "location":
            self.__dict__[name] = Vector2(value[0], value[1])
        elif name == "font_size":
            self.__dict__[name] = value
            self.font = pygame.font.Font('freesansbold.ttf', int(self.font_size))
        else:
            self.__dict__[name] = value

    def draw(self, screen):
        """
        Draws the object text to the screen.

            text.draw(SCREEN);
        """

        obj = self.font.render(self.text, 1, self.color)
        loc = Vector2(self.location.x, self.location.y)
        if self.centered is True:
            loc.x -= obj.get_rect().width / 2
        screen.blit(obj, loc)

class FiniteState:
    """Simple state. Used by state machine. TO BE REPLACED."""
    def __init__(self, owner, init_function, update_function):
        self.owner = owner
        self.initialize = init_function
        self.update = update_function

class StateMachine:
    """Simple variable finite state machine. TO BE REPLACED."""
    def __init__(self):
        """Initialize the state machine."""
        self.current_state = 0
        self.previous_state = -1
        self.states = []

    def add_state(self, init_function, update_function):
        """append a state to the state machine."""
        self.states.append(FiniteState(self, init_function, update_function))

    def update(self, delta_time):
        """update the the state at index current_state of states."""
        if self.current_state != self.previous_state:
            if self.states[self.current_state].initialize != None:
                self.states[self.current_state].initialize(self.states[self.current_state], delta_time)
            self.previous_state = self.current_state

        self.states[self.current_state].update(self.states[self.current_state], delta_time)

"""
To do notes:

1. Because of rotation set attribute, rotation might be unnecessary.
2. Set and add velocity methods do not follow convention
3. create animation system
4. get rid of finite state machine. please. its so bad.
5. Add animation system for sprite sheets.
"""


import random, pickup, bullet2
from pygame import *

import damage_text
from math_tools import *

dead_body_decay_time = 240 # number of frames before a dead body decays

class Mob:  # Class used for the player and enemies
    def __init__(self, x, y, w, h, vX, vY, vM, vAx, fA, jumps, health=100, shield=100, enemyType=0, animation=0,
                 weapon='braton', avoidance=50, shootRange=200, money=5000):
        self.X, self.Y = x, y
        self.width, self.H = w, h
        self.vX, self.vY = vX, vY
        self.vM, self.vAx = vM, vAx  # max velocity for mob to travel at, acceleration rate to the max
        self.oG, self.oW = False, False  # whether the mob is on the ground/floor, whether the mob is on a wall
        self.facing_left = fA  # (player.fAcing) True for left, False for right
        self.jumps = jumps  # amount of jumps the mob has left
        self.frame = 0  # Current frame the mob is on
        self.hP, self.hW = [Rect(0, 0, 0, 0), 0], [Rect(0, 0, 0, 0),
                                                   0]  # Hit Plat, Hit Wall - last floor platform the mob hit
        self.maxHealth = health  # Won't be changed, only read to find the limit
        self.maxShield = shield  # same as maxHealth
        self.money = money  # Credits, for purchasing weapons

        self.health = health  # current Health
        self.shield = shield  # current shields

        self.shieldTimer = 300  # Time until shield begins regenerating
        self.animation = animation  # current frame set the mob is on
        self.weaponName = weapon  # current weapon the mob is using (Used more with enemies)
        self.shootCooldown = 0  # Fire rate timer
        self.mag = 45  # Current magazine size, changes with weapon
        # Enemy Related things
        self.enemyType = enemyType
        self.attacking = False
        self.dying = 0  # 0 if alive >0 if not alive
        self.avoidance = avoidance  # How close the player can be
        self.shootRange = shootRange  # How far the mob tries to stay
        self.shootCounter = 0  # Enemy fire rate timer
        self.despawn = False
        self.decay = 0
        # Companion Related Things
        self.target = -1

    def move(self):
        self.X += int(self.vX)
        self.Y += int(self.vY)

    def enemyLogic(self, player, pickupList, enemyDeathSounds, pickupSprites, playTile, doorList, bulletList, weaponList, playerRect):
        # Logic
        distX = abs(self.X - player.X)  # distance from player
        distY = abs(self.Y - player.Y)
        enemyRect = Rect(self.X, self.Y, self.width, self.H)  # enemy hitbox
        losX = self.X  # line of sight x for checking whether you can shoot or not
        checkLos = True
        # Checking health
        if self.health <= 0:  # start dying if not enough health
            if self.dying == 0:
                if self.facing_left:
                    self.animation = 6
                else:
                    self.animation = 7

            self.dying += 1
            if self.dying == 1:
                self.frame = 1
                if self.enemyType !=1:
                    random.choice(enemyDeathSounds).play()  # find a lovely death sound
            if self.frame % 25 == 0 and self.decay == 0:  # wait until enemy death animation is done
                if random.randint(0, 2) == 0:  # spawn a drop
                    dropType = random.randint(0, len(pickupSprites) - 1)
                    dropAmounts = [20, 10, 50, 10, 'health', 'credits']  # Rifle, shotgun, laser, health, sniper
                    pickupList.append(pickup.Pickup(self.X + self.width // 2,
                                                    self.Y + self.H - pickupSprites[dropType].get_height(),
                                                    dropType,
                                                    dropAmounts[dropType]))
                if self.facing_left:
                    self.animation = 8
                else:
                    self.animation = 9
                self.decay+=1
            elif self.decay > 0:
                self.despawn = self.decay > dead_body_decay_time
                self.decay+=1
        elif distY > 1000 or distX > 1200:  # if enemy is too far away then despawn it
            self.despawn = True
        else:
            # Jumping over obstacles
            if self.oW and self.oG:  # if there's a wall and the enemy is on the ground
                self.jumps -= 1
                self.vY -= 7

            # Jumping across gaps
            if self.facing_left:
                if (not enemyRect.move(int(self.vM), 1).colliderect(
                        self.hP[
                            0])) and self.oG:  # if the moved enemy won't be still on the platform (hP)
                    self.vY -= 7  # jump
            elif not self.facing_left:
                if (not enemyRect.move(-int(self.vM), 1).colliderect(self.hP[0])) and self.oG:
                    self.vY -= 7

            # Shooting
            if abs(self.X - player.X) in range(self.avoidance,
                                               self.shootRange):  # if player distance is in between the enemy avoidance and the sooting range
                if abs(self.Y - player.Y) < 30 and int(
                        self.vX) == 0:  # if player and enemy are both on the same level
                    while checkLos:  # if the mob can shoot the playeer
                        for j in playTile[2]:
                            if j[0].collidepoint(losX,
                                                 player.Y):  # if there is a tile between the mob and the player
                                checkLos = False
                                break
                        for j in doorList:
                            if j.hitBox.collidepoint(losX, player.Y):
                                checkLos = False
                                break
                        if abs(player.X - losX) > self.shootRange:  # if the player is out of range
                            checkLos = False
                        if playerRect.collidepoint(losX, player.Y):  # if the player is in line of sight
                            self.attacking = True  # begin attacking
                            self.shootCounter += 1
                            if self.facing_left:  # shooting animation
                                self.animation = 4
                            else:
                                self.animation = 5
                            if self.shootCounter % weaponList[self.weaponName].firerate == 0:
                                # different bullet based on different enemy type
                                if self.enemyType == 0:
                                    if self.facing_left:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X, self.Y + 25 + random.randint(-1,1), 0,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 3,
                                                            weaponList[self.weaponName].bulletColour,
                                                            (255, 0, 0), 7, 0, 0, 2))
                                    else:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X + self.width, self.Y + 25 + random.randint(-1, 1), 180,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 3,
                                                            weaponList[self.weaponName].bulletColour, (255, 0, 0), 7,
                                                            0, 0, 2))
                                elif self.enemyType == 1:
                                    if self.facing_left:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X + self.width // 2, self.Y + random.randint(-1, 1), 0,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 3,
                                                            weaponList[self.weaponName].bulletColour, (255, 0, 0), 5,
                                                            0, 0, 4))
                                    else:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X + self.width // 2, self.Y, 180,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 3,
                                                            weaponList[self.weaponName].bulletColour, (255, 0, 0), 5,
                                                            0, 0, 4))
                                elif self.enemyType == 2:
                                    if self.facing_left:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X + self.width // 2, self.Y + 25 + random.randint(-1, 1), 0,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 7,
                                                            weaponList[self.weaponName].bulletColour, (255, 0, 0), 5,
                                                            0, 0, 4))
                                    else:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X + self.width // 2, self.Y + 25 + random.randint(-1, 1), 180,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 7,
                                                            weaponList[self.weaponName].bulletColour, (255, 0, 0), 5,
                                                            0, 0, 4))
                                elif self.enemyType == 3:
                                    if self.facing_left:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X, self.Y + 22 + random.randint(-1,1), 0,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 3,
                                                            weaponList[self.weaponName].bulletColour,
                                                            (255, 0, 0), 7, 0, 0, 2))
                                    else:
                                        bulletList.append(
                                            bullet2.Bullet2(self.X + self.width, self.Y + 22 + random.randint(-1, 1), 180,
                                                            weaponList[self.weaponName].damage // 2, 0, 400, 3,
                                                            weaponList[self.weaponName].bulletColour, (255, 0, 0), 7,
                                                            0, 0, 2))
                                weaponList[self.weaponName].fireSound.play()
                            break
                        if player.X > self.X:  # check 3 pixels along the line of sight
                            losX += 3
                        elif player.X < self.X:
                            losX -= 3
                else:
                    self.attacking = False

            # Moving left and right
            if self.animation != 6:  # Won't work if mob is currently dying
                if player.X > self.X:  # face right if player is on right
                    self.facing_left = True
                    if not self.attacking:  # use standing animation if not attacking
                        self.shootCounter = 0
                        self.animation = idleRight
                elif player.X < self.X:  # Face left is player is on left
                    self.facing_left = False
                    if not self.attacking:
                        self.shootCounter = 0
                        self.animation = idleLeft

                if abs(
                                player.X - self.X) > self.shootRange or not self.oG:  # Move towards player if not on ground or if outside of shooting range
                    if player.X > self.X:  # begin walking to the right
                        self.facing_left = True
                        self.vX += self.vAx
                        self.animation = right
                    elif player.X < self.X:  # begin walking to the left
                        self.facing_left = False
                        self.vX -= self.vAx
                        self.animation = left
                    self.shootCounter = 0
                elif abs(
                                player.X - self.X) < self.avoidance or not self.oG:  # Move away from player if not on ground or inside avoidance area
                    if player.X > self.X:  # Move left
                        self.facing_left = False
                        self.vX -= self.vAx
                        self.animation = left
                    elif player.X < self.X:  # Move right
                        self.facing_left = True
                        self.vX += self.vAx
                        self.animation = right
                    self.shootCounter = 0

    def kubrowLogic(self, player, mobList, damagePopoff):
        # Logic
        distX = abs(self.X - player.X)  # distance from player
        distY = abs(self.Y - player.Y)
        kubrowRect = Rect(self.X, self.Y, self.width, self.H)  # enemy hitbox
        if self.target == -1:
            if random.randint(0, 120) == 0:
                enemyDistances = []
                for i in mobList:
                    if i.health > 0:
                        enemyDistances.append(abs(i.X - self.X))
                if len(enemyDistances)>0:
                    self.target = enemyDistances.index(min(enemyDistances))
                else:
                    self.target = -1
        if distY > 1000 or distX > 1200:  # if enemy is too far away then despawn it
            self.X, self.Y = player.X, player.Y
            self.target = -1
        else:
            # Jumping over obstacles
            if self.oW and self.oG:  # if there's a wall and the enemy is on the ground
                self.jumps -= 1
                self.vY -= 7

            # Jumping across gaps
            if self.facing_left:
                if (not kubrowRect.move(int(self.vM), 1).colliderect(
                        self.hP[
                            0])) and self.oG:  # if the moved enemy won't be still on the platform (hP)
                    self.vY -= 7  # jump
            elif not self.facing_left:
                if (not kubrowRect.move(-int(self.vM), 1).colliderect(self.hP[0])) and self.oG:
                    self.vY -= 7
            if self.target != -1:
                # Shooting

                try:
                    if abs(self.X - mobList[self.target].X) in range(0,
                                                                     10):  # if player distance is in between the enemy avoidance and the sooting range
                        if abs(self.Y - mobList[self.target].Y) < 30 and int(
                                self.vX) == 0:  # if player and enemy are both on the same level
                            self.attacking = True
                            mobList[self.target].damage(25, damagePopoff)
                            self.target = -1
                    else:
                        self.attacking = False
                except IndexError:
                    self.target = -1
        # Moving left and right
        if self.target == -1:
            self.attacking = False
            if self.animation != 6:  # Won't work if mob is currently dying
                if player.X > self.X:  # face right if player is on right
                    self.facing_left = True
                    if not self.attacking:  # use standing animation if not attacking
                        self.animation = idleRight
                elif player.X < self.X:  # Face left is player is on left
                    self.facing_left = False
                    if not self.attacking:
                        self.animation = idleLeft

                if abs(
                                player.X - self.X) > 20 or not self.oG:  # Move towards player if not on ground or if outside of shooting range
                    if player.X > self.X:  # begin walking to the right
                        self.facing_left = True
                        self.vX += self.vAx
                        self.animation = right
                    elif player.X < self.X:  # begin walking to the left
                        self.facing_left = False
                        self.vX -= self.vAx
                        self.animation = left
                elif abs(
                                player.X - self.X) < 1 or not self.oG:  # Move away from player if not on ground or inside avoidance area
                    if player.X > self.X:  # Move left
                        self.facing_left = False
                        self.vX -= self.vAx
                        self.animation = left
                    elif player.X < self.X:  # Move right
                        self.facing_left = True
                        self.vX += self.vAx
                        self.animation = right
        else:
            if abs(
                            mobList[
                                self.target].X - self.X) > 10 or not self.oG:  # Move towards mobList[self.target] if not on ground or if outside of shooting range
                if mobList[self.target].X > self.X:  # begin walking to the right
                    self.facing_left = True
                    self.vX += self.vAx
                    self.animation = right
                elif mobList[self.target].X < self.X:  # begin walking to the left
                    self.facing_left = False
                    self.vX -= self.vAx
                    self.animation = left
            elif abs(
                            mobList[
                                self.target].X - self.X) < 1 or not self.oG:  # Move away from mobList[self.target] if not on ground or inside avoidance area
                if mobList[self.target].X > self.X:  # Move left
                    self.facing_left = False
                    self.vX -= self.vAx
                    self.animation = left
                elif mobList[self.target].X < self.X:  # Move right
                    self.facing_left = True
                    self.vX += self.vAx
                    self.animation = right

    def damage(self, amount, damagePopoff, dtype=0):
        self.health -= amount
        damagePopoff.append(
            damage_text.DamageText(self.X + (self.width // 2) + random.randint(-30, 30), self.Y + random.randint(-10, 0), amount,
                                   dtype))

    def applyFriction(self, friction, airFriction):
        if self.vX > 0:  # if self is moving, apply friction
            if self.oG:
                # Friction on Ground
                self.vX = min(self.vX, self.vM)
                self.vX -= friction
            else:
                # Friction in Air
                self.vX = min(self.vX, self.vM)
                self.vX -= airFriction
        elif self.vX < 0:
            if self.oG:
                # Friction On ground
                self.vX = max(self.vX, -self.vM)
                self.vX += friction
            else:
                # Friction in Air
                self.vX = max(self.vX, -self.vM)
                self.vX += airFriction
        elif self.vX in range(1, -1):
            self.vX = 0

    def hitStuff(self, playTile, gravity):
        mobRect = Rect(self.X, self.Y, self.width, self.H)
        hitRect = [Rect(0, 0, 0, 0)]
        wallRect = [Rect(0, 0, 0, 0)]
        for platTile in playTile[2]:
            if mobRect.move(0, 1).colliderect(Rect(platTile[0])) and (
                            platTile[1] == 0 or platTile[1] == 2):  # if the tile is a platform or an invisible platform
                self.vY = 0
                self.hP = platTile
                if mobRect.bottom < platTile[
                    0].bottom:  # if the mob is clipping into the tile and is closer to the top of it
                    self.Y = platTile[0].top - self.H  # move mob to top of platform
                    self.oG = True
                    self.jumps = 2
                elif mobRect.top > platTile[0].top:  # if mob is closer to bottom
                    self.Y = platTile[0].bottom  # move to bototm
                    self.vY *= -1  # reflect vY
                    self.oG = False
            if mobRect.colliderect(platTile[0]) and platTile[1] == 1:  # if colliding with a wall
                self.oW = True
                self.hW = platTile
                if mobRect.left < platTile[0].left:  # if mob is on the right side of the wall
                    self.X = platTile[0].left - self.width - 1  # move to right
                    self.jumps = 1  # more jumps for jumping off of the wall
                elif mobRect.right > platTile[0].right:
                    self.X = platTile[0].right + 1
                    self.jumps = 1
        if not mobRect.move(0, 1).colliderect(self.hP[0]):  # if player isn't hitting the ground
            self.oG = False
            self.vY += gravity
        if not (mobRect.move(0, 1).colliderect(self.hW[0]) or mobRect.move(0, -1).colliderect(
                self.hW[0])):  # if player isn't hitting a wall
            self.oW = False


import copy
import glob
import hashlib
import json

# from the index file when we created the crops for the labellers to our src coordinate system
import os
import random
import shutil
import sys
import time
from collections import defaultdict
from os import path
from pathlib import Path
import PIL
import PIL.ImageDraw as ImageDraw
import PIL.Image as Image
import svgwrite
from PIL import ImageOps
import numpy as np
from sys import platform
import hashlib
from PIL.Image import Transpose
import concurrent.futures

import process_labels

def render_labels_per_crop( dataset_root, json_file, output_folder, reses=[512], mode='None', render_svg=False):
    '''
    Render out a labelled dataset. RGB labels and greyscale labels.
    '''

    if not mode in process_labels.VALID_CROPS:
        print ("unknown crop mode %s. pick from: %s " % (crop_mode, " ".join(process_labels.VALID_CROPS)))
        return

    out = []
    colors = process_labels.colours_for_mode(process_labels.GREY_NO_DOOR)
    photo_file = process_labels.find_photo_for_json(dataset_root, json_file )

    for res in reses:
        os.makedirs(os.path.join(output_folder, f"{res}px", "rgb"   ), exist_ok=True)
        os.makedirs(os.path.join(output_folder, f"{res}px", "labels"), exist_ok=True)

    if render_svg:
        os.makedirs(os.path.join(output_folder, "svg"), exist_ok=True)

    batch_name = Path(json_file).parent.name

    country = process_labels.country_from_batch(dataset_root, batch_name)

    if  os.stat(json_file).st_size == 0: # while the labelling is in progress, some label files are empty placeholders.
        print ("skipping empty label file")
        return

    with open(json_file, "r") as f:
        data = json.load(f)

    photo = process_labels.open_and_rotate( os.path.join(dataset_root, photo_file), data )

    label_mode = "L" # greyscale

    # crop to each defined region
    for crop_name, crop_data in data.items():

        crop_bounds = crop_data["crop"]
        crop_photo =photo.crop (crop_bounds)

        label_img = Image.new(label_mode, (crop_photo.width, crop_photo.height))
        draw_label_photo = ImageDraw.Draw(label_img, label_mode)
        draw_label_photo.rectangle([(0, 0), (label_img.width, label_img.height)], fill=colors["none"] )
        base_name = os.path.splitext(crop_name)[0]

        if isinstance( crop_data["labels"], dict ): # metadata_window_labels / part 1, render each category separately
            for cat, polies in crop_data["labels"].items():
                for poly in polies:
                    poly = [tuple(x) for x in poly]
                    draw_label_photo.polygon( poly, colors[cat])
        else: # metadata_window_labels_2 / part 2, render in order
            for catl in crop_data["labels"]:
                cat = catl[0]
                for poly in catl[1]:
                    poly = [tuple(x) for x in poly]
                    draw_label_photo.polygon(poly, colors[cat])

        for res in reses:
            # crop down
            crop_photo_r = process_labels.crop(crop_photo, res, mode, resample=Image.Resampling.LANCZOS, background_col="black")
            label_img_r  = process_labels.crop(label_img , res, mode, resample=Image.Resampling.NEAREST, background_col="white")

            print(f"rendering crops from {json_file} @ {res}:{mode}  = {base_name}")

            crop_photo_r.save(os.path.join(output_folder, f"{res}px", "rgb"   , base_name + ".jpg"), quality=90)
            label_img_r .save(os.path.join(output_folder, f"{res}px", "labels", base_name + ".png"))

        if render_svg:

            dwg = svgwrite.Drawing(os.path.join(output_folder, "svg", crop_name + ".svg"), profile='tiny')
            dwg.add(dwg.text(crop_name, insert=(0, 0.2), fill='black'))

            for cat, polies in crop_data["labels"].items():
                for poly in polies:
                    poly = [tuple(x) for x in poly]
                    draw_label_photo.polygon(poly, colors[cat])
                    dwg.add(dwg.polygon(poly, fill=f'rgb({colors[cat][0]},{colors[cat][1]},{colors[cat][2]})'))

            dwg.save()

        out.append((country, base_name))

    return out

if __name__ == "__main__":

    # if platform == "win32":
    dataset_root = "." #sys.argv[1]
        # dataset_root = r"C:\Users\twak\Documents\architecture_net\dataset"
    # else:
    #     dataset_root = r"/home/twak/archinet/data"

    output_folder = f"./metadata_cook/winsyn_cook_no_door_9k_{time.time()}/"

    os.makedirs(output_folder, exist_ok=True)

    json_src = []
    # json_src.extend(glob.glob(r'/home/twak/Downloads/LYD__KAUST_batch_2_24.06.2022/LYD<>KAUST_batch_2_24.06.2022/**.json'))
    json_src.extend(glob.glob(os.path.join(dataset_root, "metadata_window_labels_2", "*", "*.json")))
    json_src.extend(glob.glob(os.path.join(dataset_root, "metadata_window_labels", "*", "*.json")))

    if True: # threaded
        with concurrent.futures.ThreadPoolExecutor(max_workers=32) as _pool:

            futures = [_pool.submit( render_labels_per_crop, dataset_root, f, output_folder, reses=[128,256,512,1024,2048], mode='square_crop') for f in json_src]

            print ("all jobs submitted!")

            for r in concurrent.futures.as_completed(futures):
                for country, base_name in r.result():

                    with open(os.path.join(output_folder, country + ".txt"), "a") as log:
                        log.write(base_name + "\n")
                        log.flush()

                    with open(os.path.join(output_folder, "all.txt"), "a") as log:
                        log.write(base_name + "\n")
                        log.flush()
    else:
        for f in json_src:
            render_labels_per_crop(dataset_root, f, output_folder, reses=[512], mode='square_crop')


from PyQt5 import QtWidgets
import sys

#import UI.mainGUI
import UI.mainGUI

class MainWindow(QtWidgets.QMainWindow, UI.mainGUI.Ui_MainWindow):
    """Documentation for MainWindo

    """
    def __init__(self, parent=None):
        super(MainWindow, self).__init__(parent)
        self.setupUi(self)
        self.menubar.setNativeMenuBar(False)

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    form = MainWindow()
    form.show()

    sys.exit(app.exec_())


__author__ = 'lich'

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'onlogin', views.onlogin, name='onlogin'),
    url(r'onqrcode', views.onQRCodeScaned, name='onQRCodeScaned'),
    url(r'heartbeat', views.heartbeat, name='heartbeat'),
    url(r'^attendee/(?P<aid>[0-9]+)/lecture/(?P<lid>[0-9]+)/review/$', views.ReviewListView.as_view()),
    url(r'^attendee/(?P<aid>[0-9]+)/lecture/$', views.AttendeeLectureListView.as_view()),
    url(r'^attendee/(?P<pk>[0-9]+)/$', views.AttendeeView.as_view()),
    url(r'^lecture/$', views.LectureListView.as_view()),
    url(r'^lecture/(?P<lid>[0-9]+)/review/$', views.LectureReviewListView.as_view()),
    url(r'^review/(?P<pk>[0-9]+)/$', views.ReviewDetailView.as_view()),
    url(r'^announce/$', views.AnnounceListView.as_view()),
    url(r'^ranking/$', views.AttendeeRankingListView.as_view()),
]


# Preguntas

# Suma de los cuadrados
n = 20
mysum = 0
for i in range(n+1):
    mysum = mysum + i**2
print(mysum)

# Productos
n = 19
myproduct = 1
for i in range(1, n+1, 2):
    myproduct = myproduct * i
print(myproduct)

# Tablas de multiplicar
for a in range(11):
    for b in range(11):
        print(a, "x", b, "=", a * b)


from odoo import _, api, fields, models, tools
from odoo.exceptions import UserError
from odoo.osv import expression

class MassMailingContact(models.Model):
    """Model of a contact. This model is different from the partner model
    because it holds only some basic information: name, email. The purpose is to
    be able to deal with large contact list to email without bloating the partner
    base."""
    _name = 'mailing.contact'
    _inherit = ['mail.thread.blacklist']
    _description = 'Mailing Contact'
    _order = 'name ASC, id DESC'
    _mailing_enabled = True

    def default_get(self, fields_list):
        """ When coming from a mailing list we may have a default_list_ids context
        key. We should use it to create subscription_ids default value that
        are displayed to the user as list_ids is not displayed on form view. """
        res = super(MassMailingContact, self).default_get(fields_list)
        if 'subscription_ids' in fields_list and not res.get('subscription_ids'):
            list_ids = self.env.context.get('default_list_ids')
            if 'default_list_ids' not in res and list_ids and isinstance(list_ids, (list, tuple)):
                res['subscription_ids'] = [
                    (0, 0, {'list_id': list_id}) for list_id in list_ids]
        return res

    name = fields.Char()
    company_name = fields.Char(string='Company Name')
    title_id = fields.Many2one('res.partner.title', string='Title')
    email = fields.Char('Email')
    list_ids = fields.Many2many(
        'mailing.list', 'mailing_subscription',
        'contact_id', 'list_id', string='Mailing Lists')
    subscription_ids = fields.One2many(
        'mailing.subscription', 'contact_id', string='Subscription Information')
    country_id = fields.Many2one('res.country', string='Country')
    tag_ids = fields.Many2many('res.partner.category', string='Tags')
    opt_out = fields.Boolean(
        'Opt Out',
        compute='_compute_opt_out', search='_search_opt_out',
        help='Opt out flag for a specific mailing list. '
             'This field should not be used in a view without a unique and active mailing list context.')

    @api.model
    def _search_opt_out(self, operator, value):
        # Assumes operator is '=' or '!=' and value is True or False
        if operator != '=':
            if operator == '!=' and isinstance(value, bool):
                value = not value
            else:
                raise NotImplementedError()

        if 'default_list_ids' in self._context and isinstance(self._context['default_list_ids'], (list, tuple)) and len(self._context['default_list_ids']) == 1:
            [active_list_id] = self._context['default_list_ids']
            contacts = self.env['mailing.subscription'].search([('list_id', '=', active_list_id)])
            return [('id', 'in', [record.contact_id.id for record in contacts if record.opt_out == value])]
        return expression.FALSE_DOMAIN if value else expression.TRUE_DOMAIN

    @api.depends('subscription_ids')
    @api.depends_context('default_list_ids')
    def _compute_opt_out(self):
        if 'default_list_ids' in self._context and isinstance(self._context['default_list_ids'], (list, tuple)) and len(self._context['default_list_ids']) == 1:
            [active_list_id] = self._context['default_list_ids']
            for record in self:
                active_subscription_list = record.subscription_ids.filtered(lambda l: l.list_id.id == active_list_id)
                record.opt_out = active_subscription_list.opt_out
        else:
            for record in self:
                record.opt_out = False

    @api.model_create_multi
    def create(self, vals_list):
        """ Synchronize default_list_ids (currently used notably for computed
        fields) default key with subscription_ids given by user when creating
        contacts.

        Those two values have the same purpose, adding a list to to the contact
        either through a direct write on m2m, either through a write on middle
        model subscription.

        This is a bit hackish but is due to default_list_ids key being
        used to compute oupt_out field. This should be cleaned in master but here
        we simply try to limit issues while keeping current behavior. """
        default_list_ids = self._context.get('default_list_ids')
        default_list_ids = default_list_ids if isinstance(default_list_ids, (list, tuple)) else []

        for vals in vals_list:
            if vals.get('list_ids') and vals.get('subscription_ids'):
                raise UserError(_('You should give either list_ids, either subscription_ids to create new contacts.'))

        if default_list_ids:
            for vals in vals_list:
                if vals.get('list_ids'):
                    continue
                current_list_ids = []
                subscription_ids = vals.get('subscription_ids') or []
                for subscription in subscription_ids:
                    if len(subscription) == 3:
                        current_list_ids.append(subscription[2]['list_id'])
                for list_id in set(default_list_ids) - set(current_list_ids):
                    subscription_ids.append((0, 0, {'list_id': list_id}))
                vals['subscription_ids'] = subscription_ids

        return super(MassMailingContact, self.with_context(default_list_ids=False)).create(vals_list)

    @api.returns('self', lambda value: value.id)
    def copy(self, default=None):
        """ Cleans the default_list_ids while duplicating mailing contact in context of
        a mailing list because we already have subscription lists copied over for newly
        created contact, no need to add the ones from default_list_ids again """
        if self.env.context.get('default_list_ids'):
            self = self.with_context(default_list_ids=False)
        return super().copy(default)

    @api.model
    def name_create(self, name):
        name, email = tools.parse_contact_from_email(name)
        contact = self.create({'name': name, 'email': email})
        return contact.id, contact.display_name

    @api.model
    def add_to_list(self, name, list_id):
        name, email = tools.parse_contact_from_email(name)
        contact = self.create({'name': name, 'email': email, 'list_ids': [(4, list_id)]})
        return contact.id, contact.display_name

    def _message_get_default_recipients(self):
        return {
            r.id: {
                'partner_ids': [],
                'email_to': ','.join(tools.email_normalize_all(r.email)) or r.email,
                'email_cc': False,
            } for r in self
        }

    def action_import(self):
        action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.mailing_contact_import_action")
        context = self.env.context.copy()
        action['context'] = context
        if (not context.get('default_mailing_list_ids') and context.get('from_mailing_list_ids')):
            action['context'].update({
                'default_mailing_list_ids': context.get('from_mailing_list_ids'),
            })

        return action

    def action_add_to_mailing_list(self):
        ctx = dict(self.env.context, default_contact_ids=self.ids)
        action = self.env["ir.actions.actions"]._for_xml_id("mass_mailing.mailing_contact_to_list_action")
        action['view_mode'] = 'form'
        action['target'] = 'new'
        action['context'] = ctx

        return action

    @api.model
    def get_import_templates(self):
        return [{
            'label': _('Import Template for Mailing List Contacts'),
            'template': '/mass_mailing/static/xls/mailing_contact.xls'
        }]


#encoding=utf-8
import os
import time
import pygame
import pandas as pd
list1=[]
b = range(3755)
for i in b:
	a = str(i)
	if len(a) == 1:
		c = '0000'+a
		chinese_dir = '../data/train/'+c
		list1.append(chinese_dir)
		if not os.path.exists(list1[i]):
		    os.mkdir(list1[i])
	elif len(a) == 2:
		c = '000'+a
		chinese_dir = '../data/train/'+c
		list1.append(chinese_dir)
		if not os.path.exists(list1[i]):
		    os.mkdir(list1[i])
	elif len(a) == 3:
		c = '00'+a
		chinese_dir = '../data/train/' +c
		list1.append(chinese_dir)
		if not os.path.exists(list1[i]):
		    os.mkdir(list1[i])
	else:
		c = '0'+a
		chinese_dir = '../data/train/'+c
		list1.append(chinese_dir)
		if not os.path.exists(list1[i]):
		    os.mkdir(list1[i])
pygame.init()
# start,end = (0x4E00, 0x9FA5) # 汉字编码范围
# for codepoint in range(int(start), int(end)):
mydata_txt = pd.read_csv('p/chinese.txt', sep=',', encoding='utf8')

list2 = []
for i in mydata_txt:
	list2.append(i)
print(list2)
for i in range(len(list2)):
    for j in range(40):
    	if j%2==0:
    		font = pygame.font.Font("ziti/SIMLI.TTF", 64)
    	elif j%3==0:
    		font = pygame.font.Font("ziti/msyh.ttc", 64)
    	else:
    		font = pygame.font.Font("ziti/simsun.ttc", 64)
    	rtext = font.render(list2[i], True, (0,0,0), (255, 255, 255))
    	pygame.image.save(rtext, os.path.join(list1[i], str(time.time())+ ".png"))


import logging
from ckanext.datacitation.postgresdb_controller import PostgresDbController
log=logging.getLogger(__name__)

controller = PostgresDbController()

def datacitation_querystore_resolve(context, data_dict):

    pid = data_dict.get('pid')
    skip = data_dict.get('offset', None)
    limit = data_dict.get('limit', None)

    if skip:
        skip = int(skip)
    if limit:
        limit = int(limit)

    records_format = data_dict.get('records_format', 'objects')

    log.debug('querystore_resolve parameters {0}'.format([pid, skip, limit, records_format]))

    result = controller.querystore_resolve(pid, records_format)

    log.debug('querystore_resolve result: {0}'.format(result))

    return result


"""
    Creates a .txt file containg the x,y,z coordinates of electron values that
    have been distributed around a centered aroud the point (0,0,0). The user
    must include the Van Der Waals radius in Angstroms and the element symbol
    as arguments. Text file saves in ElectronClouds directoryself.

    SYSTEM ARGUMENTS:
    1) Desired radius in Angstrom
    2) Desired output file name (do not include .txt)
    3) Path to DIRECTORY containing the other electron clouds
"""
from numpy import pi, cos, sin, arccos, arange
from math import ceil
import os
import sys

#Initializes all values that use systems args
radius = float(sys.argv[1])         #Van Der Waals radius in Angstroms
filename = str(sys.argv[2])+".txt"  #Output file name
cloudPath = str(sys.argv[3])        #Path to DIRECTORY with other cached clouds (output DIR)

num_pts = int(radius ** 2 * 4 * pi * 4) #makes a consistant number of electrons per radius
indices = arange(0, num_pts, dtype=float) + 0.5
os.chdir(cloudPath)
outFile = open(filename, 'w+')
xv = []
yv = []
zv = []

"""
    Generates a unit sphere or electrons that have been evenly distributed
    across the surphace of the spere.
"""
phi = arccos(1 - 2*indices/num_pts)
theta = pi * (1 + 5**0.5) * indices
x, y, z = cos(theta) * sin(phi), sin(theta) * sin(phi), cos(phi);

"""
    Takes the unit sphere and creates a scaled version of it at every
    hundreths of an Angstrom.
"""
for i in range(len(x)):
    xr = ceil(x[i] * 100) / 100.0
    yr = ceil(y[i] * 100) / 100.0
    zr = ceil(z[i] * 100) / 100.0
    for j in range(1, int(radius*10)):
        xf = ceil((1/10 * j * xr)*100) / 100.0
        yf = ceil((1/10 * j * yr)*100) / 100.0
        zf = ceil((1/10 * j * zr)*100) / 100.0
        xv.append(xf)
        yv.append(yf)
        zv.append(zf)

for i in range(len(xv)):
    outFile.write(str(xv[i])+", "+str(yv[i])+", "+str(zv[i]))
    outFile.write("\n")

outFile.close()


# Удаление элементов

"""
С помощью оператора del можно удалять элементы списка по определенному индексу.
"""

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
del numbers[5]    # удаляем элемент имеющий индекс 5

print(numbers)


__author__ = 'Clemens Prescher'

import os
from PyQt4 import QtGui, QtCore
import numpy as np
from Data.HelperModule import get_base_name
from copy import copy
import pyqtgraph as pg

class IntegrationPhaseController(object):
    def __init__(self, working_dir, view, calibration_data,
                 spectrum_data, phase_data):
        self.working_dir = working_dir
        self.view = view
        self.calibration_data = calibration_data
        self.spectrum_data = spectrum_data
        self.phase_data = phase_data
        self.phase_lw_items = []
        self.create_signals()

    def create_signals(self):
        self.connect_click_function(self.view.phase_add_btn, self.add_phase)
        self.connect_click_function(self.view.phase_del_btn, self.del_phase)
        self.connect_click_function(self.view.phase_clear_btn, self.clear_phases)

        self.view.phase_pressure_step_txt.editingFinished.connect(self.update_phase_pressure_step)
        self.view.phase_temperature_step_txt.editingFinished.connect(self.update_phase_pressure_step)

        self.view.phase_pressure_sb.valueChanged.connect(self.phase_pressure_sb_changed)
        self.view.phase_temperature_sb.valueChanged.connect(self.phase_temperature_sb_changed)
        #
        # self.view.phase_lw.currentItemChanged.connect(self.phase_item_changed)
        self.view.phase_tw.currentCellChanged.connect(self.phase_selection_changed)
        self.view.phase_color_btn_clicked.connect(self.phase_color_btn_clicked)
        self.view.phase_show_cb_state_changed.connect(self.phase_show_cb_state_changed)
        self.view.phase_name_changed.connect(self.rename_phase)

        self.view.spectrum_view.view_box.sigRangeChangedManually.connect(self.update_intensities_slot)
        self.view.spectrum_view.spectrum_plot.autoBtn.clicked.connect(self.spectrum_auto_btn_clicked)
        self.spectrum_data.subscribe(self.spectrum_data_changed)

    def connect_click_function(self, emitter, function):
        self.view.connect(emitter, QtCore.SIGNAL('clicked()'), function)

    def add_phase(self, filename=None):
        """
        Loads a new phase from jcpds file.
        :param filename: *.jcpds filename. I not set or None it a FileDialog will open.
        :return:
        """
        if filename is None:
            filenames = QtGui.QFileDialog.getOpenFileNames(
                self.view, "Load Phase(s).", self.working_dir['phase'])
            if len(filenames):
                self.working_dir['phase'] = os.path.dirname(str(filenames[0]))
                progress_dialog = QtGui.QProgressDialog("Loading multiple phases.", "Abort Loading", 0, len(filenames),
                                                        self.view)
                progress_dialog.setWindowModality(QtCore.Qt.WindowModal)
                progress_dialog.show()
                QtGui.QApplication.processEvents()
                for ind, filename in enumerate(filenames):
                    filename = str(filename)
                    progress_dialog.setValue(ind)
                    progress_dialog.setLabelText("Loading: " + os.path.basename(filename))
                    QtGui.QApplication.processEvents()
                    self.phase_data.add_phase(filename)

                    if self.view.phase_apply_to_all_cb.isChecked():
                        pressure = np.float(self.view.phase_pressure_sb.value())
                        temperature = np.float(self.view.phase_temperature_sb.value())
                        self.phase_data.phases[-1].compute_d(pressure=pressure,
                                                             temperature=temperature)
                    else:
                        pressure = 0
                        temperature = 300

                    self.phase_data.get_lines_d(-1)
                    color = self.add_phase_plot()
                    self.view.add_phase(get_base_name(filename), '#%02x%02x%02x' % (color[0], color[1], color[2]))

                    self.view.set_phase_tw_pressure(len(self.phase_data.phases)-1, pressure)
                    self.update_phase_temperature(len(self.phase_data.phases)-1, temperature)

                    if progress_dialog.wasCanceled():
                        break
                progress_dialog.close()
                QtGui.QApplication.processEvents()
                self.update_temperature_control_visibility()
        else:
            self.phase_data.add_phase(filename)

            if self.view.phase_apply_to_all_cb.isChecked():
                pressure = np.float(self.view.phase_pressure_sb.value())
                temperature = np.float(self.view.phase_temperature_sb.value())
                self.phase_data.phases[-1].compute_d(pressure=pressure,
                                                     temperature=temperature)
            else:
                pressure = 0
                temperature = 300

            self.phase_data.get_lines_d(-1)
            color = self.add_phase_plot()
            self.view.add_phase(get_base_name(filename), '#%02x%02x%02x' % (color[0], color[1], color[2]))

            self.view.set_phase_tw_pressure(len(self.phase_data.phases)-1, pressure)
            self.update_phase_temperature(len(self.phase_data.phases)-1, temperature)

            self.working_dir['phase'] = os.path.dirname(str(filename))
            self.update_temperature_control_visibility()

    def add_phase_plot(self):
        """
        Adds a phase to the Spectrum view.
        :return:
        """
        axis_range = self.view.spectrum_view.spectrum_plot.viewRange()
        x_range = axis_range[0]
        y_range = axis_range[1]
        positions, intensities, baseline = \
            self.phase_data.rescale_reflections(
                -1, self.spectrum_data.spectrum,
                x_range, y_range,
                self.calibration_data.geometry.wavelength * 1e10,
                self.get_unit())
        color = self.view.spectrum_view.add_phase(self.phase_data.phases[-1].name,
                                                  positions,
                                                  intensities,
                                                  baseline)
        return color

    def del_phase(self):
        """
        Deletes the currently selected Phase
        """
        cur_ind = self.view.get_selected_phase_row()
        if cur_ind >= 0:
            self.view.del_phase(cur_ind)
            self.phase_data.del_phase(cur_ind)
            self.view.spectrum_view.del_phase(cur_ind)
        self.update_temperature_control_visibility()

    def clear_phases(self):
        """
        Delets all phases from the GUI and phase data
        """
        while self.view.phase_tw.rowCount() > 0:
            self.del_phase()

    def update_phase_pressure_step(self):
        value = np.float(self.view.phase_pressure_step_txt.text())
        self.view.phase_pressure_sb.setSingleStep(value)

    def update_phase_temperature_step(self):
        value = np.float(self.view.phase_temperature_step_txt.text())
        self.view.phase_temperature_sb.setSingleStep(value)

    def phase_pressure_sb_changed(self, val):
        """
        Called when pressure spinbox emits a new value. Calculates the appropriate EOS values and updates line
        positions and intensities.
        """
        if self.view.phase_apply_to_all_cb.isChecked():
            for ind in xrange(len(self.phase_data.phases)):
                self.phase_data.set_pressure(ind, np.float(val))
                self.view.set_phase_tw_pressure(ind, val)
            self.update_intensities()

        else:
            cur_ind = self.view.get_selected_phase_row()
            self.phase_data.set_pressure(cur_ind, np.float(val))
            self.view.set_phase_tw_pressure(cur_ind, val)
            self.update_intensity(cur_ind)

    def phase_temperature_sb_changed(self, val):
        """
        Called when temperature spinbox emits a new value. Calculates the appropriate EOS values and updates line
        positions and intensities.
        """
        if self.view.phase_apply_to_all_cb.isChecked():
            for ind in xrange(len(self.phase_data.phases)):
                self.update_phase_temperature(ind, val)
            self.update_intensities()

        else:
            cur_ind = self.view.get_selected_phase_row()
            self.update_phase_temperature(cur_ind, val)
            self.update_intensity(cur_ind)

    def update_phase_temperature(self, ind, val):
        if self.phase_data.phases[ind].has_thermal_expansion():
            self.phase_data.set_temperature(ind, np.float(val))
            self.view.set_phase_tw_temperature(ind, val)
        else:
            self.phase_data.set_temperature(ind, 300)
            self.view.set_phase_tw_temperature(ind, '-')

    def phase_selection_changed(self, row, col, prev_row, prev_col):
        cur_ind = row
        pressure = self.phase_data.phases[cur_ind].pressure
        temperature = self.phase_data.phases[cur_ind].temperature

        self.view.phase_pressure_sb.blockSignals(True)
        self.view.phase_pressure_sb.setValue(pressure)
        self.view.phase_pressure_sb.blockSignals(False)

        self.view.phase_temperature_sb.blockSignals(True)
        self.view.phase_temperature_sb.setValue(temperature)
        self.view.phase_temperature_sb.blockSignals(False)
        self.update_temperature_control_visibility(row)

    def update_temperature_control_visibility(self, row_ind = None):
        if row_ind is None:
            row_ind = self.view.get_selected_phase_row()
        if self.phase_data.phases[row_ind].has_thermal_expansion():
            self.view.phase_temperature_sb.setEnabled(True)
            self.view.phase_temperature_step_txt.setEnabled(True)
        else:
            self.view.phase_temperature_sb.setDisabled(True)
            self.view.phase_temperature_step_txt.setDisabled(True)

    def phase_color_btn_clicked(self, ind, button):
        previous_color = button.palette().color(1)
        new_color = QtGui.QColorDialog.getColor(previous_color, self.view)
        if new_color.isValid():
            color = str(new_color.name())
        else:
            color = str(previous_color.name())
        self.view.spectrum_view.set_phase_color(ind, color)
        button.setStyleSheet('background-color:' + color)

    def phase_show_cb_state_changed(self, ind, state):
        if state:
            self.view.spectrum_view.show_phase(ind)
        else:
            self.view.spectrum_view.hide_phase(ind)

    def rename_phase(self, ind, name):
        self.view.spectrum_view.rename_phase(ind, name)

    def update_intensities_slot(self, *args):
        """
        Used as a slot when autoRange of the view is. Tries to prevent a call on autorange while updating intensities of
        phases.
        """
        axis_range = self.view.spectrum_view.spectrum_plot.viewRange()
        auto_range = copy(self.view.spectrum_view.spectrum_plot.vb.state['autoRange'])

        self.view.spectrum_view.spectrum_plot.disableAutoRange()
        self.update_intensities(axis_range)

        if auto_range[0] and auto_range[1]:
            self.view.spectrum_view.spectrum_plot.enableAutoRange()

    def update_intensity(self, ind, axis_range=None):
        """
        Updates the intensities of a specific phase with index ind.
        :param ind: Index of the phase
        :param axis_range: list/tuple of visible x_range and y_range -- ((x_min, x_max), (y_min, y_max))
        """
        if axis_range is None:
            axis_range = self.view.spectrum_view.spectrum_plot.viewRange()
        x_range = axis_range[0]
        y_range = axis_range[1]
        positions, intensities, baseline = \
            self.phase_data.rescale_reflections(
                ind, self.spectrum_data.spectrum,
                x_range, y_range,
                self.calibration_data.geometry.wavelength * 1e10,
                self.get_unit())
        self.view.spectrum_view.update_phase_intensities(
            ind, positions, intensities, baseline)

    def update_intensities(self, axis_range=None):
        """
        Updates all intensities of all phases in the spectrum view. Also checks if phase lines are still visible.
        (within range of spectrum and/or overlays
        :param axis_range: list/tuple of x_range and y_range -- ((x_min, x_max), (y_min, y_max)
        """
        self.view.spectrum_view.view_box.blockSignals(True)
        for ind in xrange(len(self.phase_data.phases)):
            self.update_intensity(ind, axis_range)
        self.view.spectrum_view.view_box.blockSignals(False)
        self.view.spectrum_view.update_phase_line_visibilities()

    def get_unit(self):
        """
        returns the unit currently selected in the GUI
                possible values: 'tth', 'q', 'd'
        """
        if self.view.spec_tth_btn.isChecked():
            return 'tth'
        elif self.view.spec_q_btn.isChecked():
            return 'q'
        elif self.view.spec_d_btn.isChecked():
            return 'd'

    def spectrum_auto_btn_clicked(self):
        """
        Runs self.update_intensities_slot after 50 ms.
        This is needed because the graph scaling is to slow, to call update_intensities immediately after the autoscale-btn
        was clicked
        """
        QtCore.QTimer.singleShot(50, self.update_intensities_slot)

    def spectrum_data_changed(self):
        """
        Function is called after the specturm data has changed.
        """
        QtCore.QTimer.singleShot(10, self.update_intensities_slot)
        self.view.spectrum_view.view_box.sigRangeChanged.connect(self.update_intensities_spectrum_slot)

    def update_intensities_spectrum_slot(self, *args):
        """
        function will be executed after a sigRangeChange event after a spectrum changed. It will disconnect the first
        handler afterwards. This is needed because of some timing issues.
        """
        self.update_intensities()
        try:
            self.view.spectrum_view.view_box.sigRangeChanged.disconnect(self.update_intensities_spectrum_slot)
        except TypeError:
            pass


import requests
import json
from datetime import datetime as dt
from sharedutils import stdlog, errlog
import os

def writeline(file, line):
    '''write line to file'''
    with open(file, 'a', encoding='utf-8') as f:
        f.write(line + '\n')
        f.close()

url = "https://api.ransomwhe.re/export"

NowTime=dt.now()

# Fetch the JSON data from the URL
response = requests.get(url)
response.raise_for_status()
result = response.json()

# Load the other JSON file
with open("groups.json") as json_file:
    groups = json.load(json_file)

for group in groups:
    keep = False
    stdlog(group["name"] + ' : analyze crypto')
    cryptofile='docs/crypto/'+ group["name"] +'.md'
    with open(cryptofile, 'w', encoding='utf-8') as f:
        f.close()
    writeline(cryptofile,'# ' + group["name"] + ' : Crypto wallet(s)')
    writeline(cryptofile,'')
    writeline(cryptofile,'| address | blockchain | Balance |')
    writeline(cryptofile, '|---|---|---|')
    # Sort the result list by family
    result["result"].sort(key=lambda x: x.get("family", ""))

    # Iterate through the sorted result list
    for address_info in result["result"]:
        family = address_info.get("family", "").split(" ", 1)[0].lower()
        if family == group["name"]:
            keep = True
            url = address_info['address']
            if address_info['blockchain'] == "bitcoin":
                url='[' + address_info['address'] + '](https://www.blockchain.com/explorer/addresses/btc/' + address_info['address'] + ')'
            writeline(cryptofile, '| ' + url + ' | ' + address_info['blockchain'] + ' | $ ' + str(round(float(address_info['balanceUSD']))) + ' |')
        #else:
        #    print(family)
    writeline(cryptofile, '')
    writeline(cryptofile, 'Last update : _'+ NowTime.strftime('%A %d/%m/%Y %H.%M') + ' (UTC)_')
    writeline(cryptofile, '')
    if keep == False:
        os.remove(cryptofile)


import torchvision
from .task_2_1 import (
    train,
    backbone,
    anchors,
    loss_objective,
    model,
    optimizer,
    schedulers,
    train_cpu_transform,
    val_cpu_transform,
    data_train,
    data_val,
    label_map
)
from tops.config import LazyCall as L
from ssd.data.transforms import ToTensor, Resize, GroundTruthBoxesToAnchors, RandomHorizontalFlip, RandomSampleCrop

train_cpu_transform = L(torchvision.transforms.Compose)(transforms=[
    L(RandomSampleCrop)(),
    L(ToTensor)(),
    L(RandomHorizontalFlip)(),
    L(Resize)(imshape="${train.imshape}"),
    L(GroundTruthBoxesToAnchors)(anchors="${anchors}", iou_threshold=0.5),
])


import sys
sys.path.append("..")
from CTScanImage import CTScanImage
import utils
import dataset_functions as df
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
import re

data_directory = "../../../ct_atrium/training/"

CT_scan_parameters_template = {
		"CT_scan_path_template" : data_directory + "CTScan_name",
		"NRRD_path_template"    : data_directory + "CTScan_name/CTScan_name.nrrd",
		"DICOM_directory"		: data_directory + "CTScan_name/DICOMS",
		"DICOM_path_template"   : data_directory + "CTScan_name/DICOMS/DICOM_name",
		"CT_directory_pattern"  : re.compile("[0-9]{8}")
		}

CT_scan_name 	= "14022803"
x 				= 250
y 				= 200
z 				= 40
patch_size 		= 32

CT_scan 			= CTScanImage(CT_scan_name, CT_scan_parameters_template)

patches = df.generate_example_inputs((x,y,z), CT_scan, patch_size)

# Plot 3 patches next to their respective DICOM slice.
fig = plt.figure()
a   = fig.add_subplot(3,4,1)
plt.imshow(CT_scan.image[:,:,z], cmap = cm.Greys_r)
plt.scatter(y,x)
plt.axis('off')
a   = fig.add_subplot(3,4,2)
plt.imshow(patches[0,:,:], cmap = cm.Greys_r)
plt.axis('off')
a   = fig.add_subplot(3,4,3)
plt.imshow(patches[3,:,:], cmap = cm.Greys_r)
plt.axis('off')
a   = fig.add_subplot(3,4,4)
plt.imshow(CT_scan.labels[:,:,z], cmap = cm.Greys_r)
plt.axis('off')
plt.scatter(y,x)

a   = fig.add_subplot(3,4,5)
plt.imshow(utils.resize_image_2d_array(CT_scan.image[:,y,:], 480/3, 480), cmap = cm.Greys_r)
plt.scatter(z,x)
plt.axis('off')

a   = fig.add_subplot(3,4,6)
plt.imshow(patches[1,:,:], cmap = cm.Greys_r)
plt.axis('off')

a   = fig.add_subplot(3,4,7)
plt.imshow(patches[4,:,:], cmap = cm.Greys_r)
plt.axis('off')

a   = fig.add_subplot(3,4,8)
plt.imshow(utils.resize_image_2d_array(CT_scan.labels[:,y,:], 480/3, 480), cmap = cm.Greys_r)
plt.axis('off')
plt.scatter(z,x)

a   = fig.add_subplot(3,4,9)
plt.imshow(utils.resize_image_2d_array(CT_scan.image[x,:,:], 480/3, 480), cmap = cm.Greys_r)
plt.axis('off')
plt.scatter(z,y)
a   = fig.add_subplot(3,4,10)
plt.imshow(patches[2,:,:], cmap = cm.Greys_r)
plt.axis('off')
a   = fig.add_subplot(3,4,11)
plt.imshow(patches[5,:,:], cmap = cm.Greys_r)
plt.axis('off')
a   = fig.add_subplot(3,4,12)
plt.imshow(utils.resize_image_2d_array(CT_scan.labels[x,:,:], 480/3, 480), cmap = cm.Greys_r)
plt.axis('off')
plt.scatter(z,y)
fig.tight_layout()
plt.show()


import discord
from discord.ext import commands
from service.utils import TemplateColours

class GlobarErrorHandler(commands.Cog):

    def __init__(self, client):
        self.client = client

    @commands.Cog.listener()
    async def on_command_error(self, ctx, error):
        # not @has_role
        if isinstance(error, commands.MissingRole):
            embed = discord.Embed(
                title='Ой-ой, ошибочка !',
                description=(f'**<@{ctx.author.id}>, у тебя отсутствует необходимая роль `{error.missing_role}`!**'),
                color=TemplateColours("service\\templateColours.json").Red
            )
        # not @has_permissions
        elif isinstance(error, commands.MissingPermissions):
            embed = discord.Embed(
                title='Ой-ой, ошибочка !',
                description=(f'**<@{ctx.author.id}>, прости, но у тебе нужно больше прав.\n~Уаа**'),
                color=TemplateColours("service\\templateColours.json").Red
            )
        # not @is_owner
        elif isinstance(error, commands.NotOwner):
            embed = discord.Embed(
                title='Ой-ой, ошибочка !',
                description=(f'**<@{ctx.author.id}>, это команда только для создателей.\n~Ня**'),
                color=TemplateColours("service\\templateColours.json").Red
            )
        # any errors
        elif isinstance(error, commands.CommandError):
            embed = discord.Embed(
                title='Ой-ой, ошибочка !',
                description=(f'**<@{ctx.author.id}>, команда не найдена. Или что-то пошло не так!\n~Ня**'),
                color=TemplateColours("service\\templateColours.json").Red
            )
        return await ctx.send(embed=embed)

def setup(client):
    client.add_cog(GlobarErrorHandler(client))


import datetime
import logging
import os
from enum import Enum

import aiohttp
import discord

from configurations import CONFIG

IMMEDIATE_RECONNECT_TIME = datetime.timedelta(milliseconds=500)

LOGLEVEL = logging.DEBUG

formatter = logging.Formatter('%(asctime)-15s [%(levelname)s] %(message)s')
handler = logging.StreamHandler()
handler.setFormatter(formatter)
handler.setLevel(LOGLEVEL)
log = logging.getLogger(__name__)

log.setLevel(logging.DEBUG)
log.addHandler(handler)

class EmbedLimitsExceed(Exception):
    pass

class InteractionResponseType(Enum):
    PONG = 1
    MESSAGE = 4
    DEFERRED_MESSAGE = 5

class FakeTyping:
    async def __aenter__(self):
        pass

    async def __aexit__(self, type, value, traceback):
        pass

class FakeChannel:
    def __init__(self, channel):
        self.typing = FakeTyping
        self.channel = channel

    def send(self, *args, **kwargs):
        return self.channel.send(*args, **kwargs)

    @property
    def id(self):
        return self.channel.id

    @property
    def type(self):
        return self.channel.type

    @property
    def name(self):
        return self.channel.name

    def __str__(self) -> str:
        return str(self.channel)

class FakeMessage:
    id = 0

    def __init__(self, author, guild, channel, content, interaction_id=None, interaction_token=None):
        self.author = author
        self.guild = guild
        self.channel = FakeChannel(channel)
        self.content = content
        self.interaction_id = interaction_id
        self.interaction_token = interaction_token

class BaseBot(discord.Client):
    WHITE = discord.Color.from_rgb(254, 254, 254)
    BLACK = discord.Color.from_rgb(0, 0, 0)
    RED = discord.Color.from_rgb(255, 0, 0)
    NEEDED_PERMISSIONS = []

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

        self.permissions = self.generate_permissions()
        self.invite_url = ''
        self.my_emojis = {}
        self.bot_disconnect = datetime.datetime.now()
        self.bot_start = datetime.datetime.now()
        self.bot_connect = None
        self.downtimes = datetime.timedelta(seconds=0)
        log.debug(f'__init__ reset uptime to {self.bot_start}.')

    async def on_disconnect(self):
        if self.bot_connect > self.bot_disconnect:
            self.bot_disconnect = datetime.datetime.now()
            log.debug(f'Disconnected at {self.bot_disconnect}.')

    async def on_resumed(self):
        if self.bot_disconnect > self.bot_connect:
            self.bot_connect = datetime.datetime.now()
            added_downtime = self.bot_connect - self.bot_disconnect
            if added_downtime > IMMEDIATE_RECONNECT_TIME:
                self.downtimes += added_downtime
            else:
                added_downtime = datetime.timedelta(seconds=0)
            log.debug(f'Reconnected at {self.bot_connect}, increased downtime by {added_downtime} to {self.downtimes}.')

    async def generate_embed_from_text(self, message_lines, title, subtitle):
        e = discord.Embed(title=title, color=self.WHITE)
        message_text = ''
        field_title = subtitle
        for line in message_lines:
            if len(field_title) + len(message_text) + len(line) + len('``````') > 1024:
                e.add_field(name=field_title, value=f'```{message_text}```', inline=False)
                message_text = f'{line}\n'
                field_title = 'Continuation'
            else:
                message_text += f'{line}\n'
        e.add_field(name=field_title, value=f'```{message_text}```')
        return e

    def generate_permissions(self):
        permissions = discord.Permissions.none()

        for perm_name in self.NEEDED_PERMISSIONS:
            setattr(permissions, perm_name, True)
        log.debug(f'Permissions required: {", ".join([p for p, v in permissions if v])}')
        return permissions

    @staticmethod
    async def is_writable(channel):
        if not channel:
            return False
        me = channel.guild.me
        permissions = channel.permissions_for(me)
        return permissions.send_messages

    @staticmethod
    async def react(message, reaction: discord.Emoji):
        try:
            await message.add_reaction(emoji=reaction)
        except discord.DiscordException as e:
            log.warning(f'[{message.guild}][{message.channel}] Could not post response: {e}.')

    async def answer(self, message, embed: discord.Embed, content='', no_interaction=False):
        try:
            if not embed:
                return await self.answer_or_react(message, embed, content)
            self.embed_check_limits(embed)
            if message.author and message.author.avatar:
                embed.set_author(name=message.author.display_name, icon_url=message.author.avatar.url)
            elif message.author and not message.author.avatar:
                embed.set_author(name=message.author.display_name)
            return await self.answer_or_react(message, embed, content, no_interaction)
        except discord.errors.Forbidden:
            log.warning(f'[{message.guild}][{message.channel}] Could not post response, channel is forbidden for me.')
        except EmbedLimitsExceed as e:
            warning = f'[{message.guild}][{message.channel}] Could not post response, embed limits exceed: {e}.'
            e = discord.Embed(title='Error', description=warning)
            return await message.channel.send(embed=e)

    async def answer_or_react(self, message, embed: discord.Embed, content=None, no_interaction=False):
        if hasattr(message, 'interaction_id') and not no_interaction:
            return await self.send_slash_command_result(message, embed, content)
        elif not embed:
            return await message.channel.send(content=content)
        return await message.channel.send(embed=embed)

    @staticmethod
    async def send_slash_command_result(message, embed, content, response_type=InteractionResponseType.MESSAGE.value):
        endpoint = f'interactions/{message.interaction_id}/{message.interaction_token}/callback'
        url = f'https://discord.com/api/v8/{endpoint}'
        response = {
            'type': response_type,
            'data': {
                'embeds': [embed.to_dict()] if embed else [],
                'content': content,
            },
            'flags': 64 if response_type == InteractionResponseType.DEFERRED_MESSAGE else 0,
        }
        async with aiohttp.ClientSession() as session:
            await session.post(url, headers={"Authorization": f"Bot {os.getenv('DISCORD_TOKEN')}"}, json=response)

    async def on_slash_command(self, function, options, message):
        raise NotImplemented('This function has not been implemented.')

    async def on_interaction(self, interaction):
        channel = interaction.channel
        if isinstance(channel, discord.channel.PartialMessageable):
            channel = 'Private Message'
        guild = interaction.guild
        author = interaction.user
        function = getattr(self, interaction.data['name'])
        options = {o['name']: o['value'] for o in interaction.data.get('options', [])}
        options_text = ' '.join([f'{k}={v}' for k, v in options.items()])
        content = f'/{interaction.data["name"]} {options_text}'
        message = FakeMessage(author, guild, channel, content, interaction.id, interaction.token)
        await self.on_slash_command(function, options, message)

    async def on_raw_reaction_add(self, payload):
        if not payload.member or payload.member.bot:
            return

        if payload.emoji.name != '❌':
            return

        channel = await self.fetch_channel(payload.channel_id)
        me = channel.guild.me
        permissions = channel.permissions_for(me)

        try:
            message = await channel.fetch_message(payload.message_id)
        except discord.errors.NotFound:
            log.debug(f'[{channel.guild}][{channel}][{payload.member}] '
                      f'Tried to react to an emoji for a nonexistent message: {payload}')
            return
        except discord.errors.Forbidden:
            log.debug(f'[{channel.guild}][{channel}][{payload.member}] '
                      f'Was not allowed to access message: {payload}')
            return

        if message.author != me:
            return
        if not message.embeds or payload.member.display_name != message.embeds[0].author.name:
            return
        if not permissions.manage_messages:
            await message.add_reaction('⛔')
            return

        await message.clear_reaction(payload.emoji)
        log.debug(f'[{message.guild}][{message.channel}][{payload.member.display_name}] '
                  f'requested deletion of message {message.id}')
        return await message.delete()

    async def on_guild_join(self, guild):
        log.debug(f'Joined guild {guild} (id {guild.id}) Now in {len(self.guilds)} guilds.')

    async def on_guild_remove(self, guild):
        log.debug(f'Guild {guild.name} (id {guild.id}) kicked me out. Now in {len(self.guilds)} guilds.')

    async def update_base_emojis(self):
        for guild_id in CONFIG.get('base_guilds'):
            await self.fetch_emojis_from_guild(guild_id)

    async def fetch_emojis_from_guild(self, guild_id):
        guild = self.get_guild(guild_id)
        for emoji in guild.emojis:
            self.my_emojis[emoji.name] = str(emoji)

    async def is_owner(self, message):
        app_info = await self.application_info()
        if app_info.team:
            return message.author in app_info.team.members
        return message.author == app_info.owner

    @staticmethod
    def is_guild_admin(message):
        if message.channel.type == discord.ChannelType.private:
            return True
        has_admin_role = any(['admin' in r.name.lower() for r in message.author.roles])
        is_administrator = any([r.permissions.administrator for r in message.author.roles])
        is_owner = message.author.id == message.guild.owner_id
        return is_owner or is_administrator or has_admin_role

    @staticmethod
    def embed_check_limits(embed):
        if len(embed.title) > 256:
            raise EmbedLimitsExceed(f'Embed title too long: {len(embed.title)}')
        if len(embed.description) > 4096:
            raise EmbedLimitsExceed(f'Embed description too long: {len(embed.description)}')
        if embed.fields and len(embed.fields) > 25:
            raise EmbedLimitsExceed(f'Number of embed fields: {len(embed.fields)}')
        for field in embed.fields:
            if len(field.name) > 256:
                raise EmbedLimitsExceed(f'Field name too long: {len(field.name)}')
            if len(field.value) > 1024:
                raise EmbedLimitsExceed(f'Field value too long: {len(field.value)}')
        if getattr(embed, '_footer', None) and len(embed.footer.text) > 2048:
            raise EmbedLimitsExceed(f'Footer too long: {len(embed.footer.text)}')
        if getattr(embed, '__author', None) and len(embed.author.name) > 256:
            raise EmbedLimitsExceed(f'Author name too long: {len(embed.author.name)}')
        if len(embed) > 6000:
            raise EmbedLimitsExceed(f'Total embed too big: {len(embed)}')

    @staticmethod
    def first_writable_channel(guild):
        for channel in guild.text_channels:
            if channel.permissions_for(guild.me).send_messages:
                return channel


def divide(x,y):
    try:
        return x/y
    except ZeroDivisionError:
        print("No se puede dividir entre cero")
    except TypeError:
        print("No se pueden usar caracteres")

resultado = divide(10,'a')
print(resultado)


def replaceMiddle(arr):
    middle = int(math.floor(len(arr) / 2 - 1))
    sum = 0
    doubleMiddle = False
    res = list()

    if(len(arr) % 2 == 0):
        doubleMiddle = True

    for x in range(0, middle):
        res.append(arr[x])

    resumePoint = 0
    if(doubleMiddle):
        sum = arr[middle] + arr[middle+1]
        resumePoint = middle + 2
    else:
        sum = arr[middle]
        resumePoint = middle + 1

    res.append(sum)

    for x in range(resumePoint, len(arr)):
        res.append(arr[x])

    return res

The Core/List Forest Edge/41. Replace Middle/replaceMiddle.py