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

# Атрибуты дрона / Астероида

# coord - координаты собственного местоположения
# direction - курс корабля
# my_mathership - космобаза приписки
# asteroids - список всех астероидов на поле
# payload - кол-во элериума в трюме
# free_space - свободного места в трюме
# fullness - процент загрузки
# is_empty - трюм пустой
# is_full - трюм полностью забит элериумом

# Методы дрона
# turn_to(obj) - повернуться к объекту/точке
# move_at(obj) - двигаться к объекту/точке
# stop() – остановиться
# load_from(obj) - загрузить элериум от объекта в трюм
# unload_to(obj) - разгрузить элериум из трюма в объект
# distance_to(obj) - рассчет расстояния до объекта/точки
# near(obj) - дрон находится рядом с объектом/точкой
from enum import IntEnum
from math import sin, cos, pi, sqrt
from typing import Optional, List
from astrobox.core import Drone, Asteroid, MotherShip
from astrobox.space_field import SpaceField
from robogame_engine import scene
from robogame_engine.geometry import Vector, Point
from robogame_engine.theme import theme

class Commander:

    _instance = None
    _enemy: Drone = None
    _attack_points: List[Point] = []
    _enemies: List[Drone] = []
    _drones: List[Drone] = []
    _excluded_points: List[Point] = []
    _initial: bool = True
    _scene: SpaceField = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls)

        return cls._instance

    def __init__(self, drone: Drone):
        self._drones.append(drone)
        self._scene = drone.scene

    @property
    def initial(self):
        return self._initial

    @initial.setter
    def initial(self, init):
        self._initial = init

    @property
    def enemy(self) -> Drone:
        return self._enemy

    @enemy.setter
    def enemy(self, enemy: Drone):
        self._enemy = enemy

    @property
    def attack_points(self) -> List[Point]:
        return self._attack_points

    @attack_points.setter
    def attack_points(self, points: List[Point]):
        self._attack_points = points

    @property
    def excluded_points(self) -> list:
        return self._excluded_points

    @property
    def enemies(self):
        return self._enemies

    @enemies.setter
    def enemies(self, enemies: List[Drone]):
        self._enemies = enemies

    @property
    def has_enemy(self):
        if self.enemy:
            return True

        return False

    @staticmethod
    def get_attack_points(center: Point, radius: int, size: int) -> list:
        """
            Возвращает точки атаки вокруг обозначенного центра
        """

        angles = int(360 / radius)
        size = size

        points = list()
        x, y = center.x, center.y

        for i in range(angles):
            x1 = x + size * cos(90 + (2 * pi * i) / angles)
            y1 = y + size * sin(90 + (2 * pi * i) / angles)
            points.append(Point(x1, y1))

        points = [point for point in points if int(point.x) in range(1200) and int(point.y) in range(600)]

        return points

    def get_enemies(self, drone):
        self.enemies = [enemy for enemy in drone.scene.drones
                        if enemy not in drone.teammates and enemy != drone and enemy.is_alive]

        self.enemies.extend([mother_ship for mother_ship in drone.scene.motherships
                             if mother_ship != drone.my_mothership and mother_ship.is_alive])

    def get_closest_enemy(self, drone):
        closest_enemy = self.enemies[0]

        for enemy in self.enemies:
            if drone.distance_to(enemy) < drone.distance_to(closest_enemy):
                closest_enemy = enemy

        return closest_enemy

    def get_attack_point(self, drone):
        """
            Выбирает незанятую точку атаки для дрона
        :param drone:
        :return:
        """

        if self.enemy and not self.enemy.is_alive:
            self._excluded_points = []

        self.get_enemies(drone=drone)

        if not self.enemies:
            drone.mode = DroneMode.DRONE_HARVESTER
            return drone.mothership

        self.enemy = self.get_closest_enemy(drone=drone)

        if self.enemy.state.target_point \
                and drone.distance_to(self.enemy) > drone.distance_to(self.enemy.state.target_point):
            target = self.enemy.state.target_point
        else:
            target = self.enemy.coord

        if self.enemy.state.target_point:
            self.attack_points = self.get_attack_points(target,
                                                        drone.radius,
                                                        drone.gun.shot_distance/2)
        elif type(self.enemy) == MotherShip:
            self.attack_points = self.get_attack_points(self.enemy.coord,
                                                        drone.radius/2,
                                                        drone.gun.shot_distance/2)
        else:
            self.attack_points = self.get_attack_points(Point(600, 300), drone.radius, drone.gun.shot_distance/2)

        for attack_point in self.attack_points:
            for excluded_point in self.excluded_points:
                if attack_point.x == excluded_point.x and attack_point.y == excluded_point.y:
                    break
            else:
                point = attack_point
                self.excluded_points.append(point)
                break
        else:
            point = drone.coord

        return point

class DroneMode(IntEnum):
    DRONE_HARVESTER = 1
    DRONE_INTERCEPTOR = 2

class IshmukhamedovDrone(Drone):

    _mode: DroneMode = DroneMode.DRONE_HARVESTER

    full_travel: int = 0
    empty_travel: int = 0
    underload_travel: int = 0

    _commander: Optional[Commander] = None
    _attack_point: Optional[Point] = None
    _enemy: Optional[Drone] = None

    _target: Optional[Asteroid] = None
    _teammates_targets: list = []
    except_targets: list = []

    @property
    def enemy(self):
        return self._enemy

    @enemy.setter
    def enemy(self, enemy):
        self._enemy = enemy

    @property
    def mode(self) -> DroneMode:
        return self._mode

    @mode.setter
    def mode(self, mode: DroneMode):
        self._mode = mode

    @property
    def target(self):
        """
            Метод-свойство возвращает астероид-цель.
        :return: Asteroid
        """
        return self._target

    @target.setter
    def target(self, target):
        self._target = target

    @property
    def teammates_targets(self) -> List[Asteroid]:
        """
            Возвращает список астероидов к которым летят другие дроиды из команды
        :return:
        """
        self._teammates_targets = []
        for teammate in self.teammates:
            self._teammates_targets.append(teammate.target)

        return self._teammates_targets

    def available_targets(self) -> List[Asteroid]:
        targets = [obj for obj in self.scene.objects
                   if obj.team != self.team and not obj.is_empty and obj not in self.except_targets]

        return targets

    def closest_target(self) -> Optional[Asteroid]:
        """
            Возвращает ближайщий к дрону астероид
        :return: Asteroid
        """
        asteroids = self.available_targets()

        if not asteroids:
            return None

        closest = asteroids[0]

        for asteroid in asteroids:
            if self.distance_to(closest) > self.distance_to(asteroid):
                closest = asteroid

        return closest

    def count_teammates(self, asteroid):
        """
            Считает количество дронов-однокомандников, летящих на один и тот-же астероид
        :param asteroid: Астероид для которого надо провести подсчет
        :return: Количество в виде dict('quantity': int, 'teammates': list, 'free_space': int)
        """
        free_space = 0
        teammates = [teammate for teammate in self.teammates if teammate.target == asteroid]

        for teammate in teammates:
            free_space += teammate.free_space

        return {'quantity': len(teammates), 'teammates': teammates, 'free_space': free_space}

    def get_target(self):
        closest = self.closest_target()

        if not closest:
            return []

        if closest not in self.teammates_targets:
            self.target = closest
        else:
            closest_info = self.count_teammates(closest)
            if closest.payload > closest_info['free_space']:
                self.target = closest
            else:
                if self.target:
                    if self.target in self.except_targets:
                        self.except_targets.remove(self.target)

                self.except_targets.append(closest)
                self.target = self.closest_target()

        return self.target

    @property
    def attack_point(self) -> Point:
        return self._attack_point

    @attack_point.setter
    def attack_point(self, point: Point):
        self._attack_point = point

    def shot(self, enemy):
        vector = Vector.from_points(self.coord, enemy.coord, module=1)
        self.vector = vector
        able_to_shot = True

        if any(self.point_in_circle(self.coord, teammate) for teammate in self.teammates) or \
                any(self.point_in_circle(self.coord, mother_ship.coord) for mother_ship in self.scene.motherships):
            point = self.make_a_step(self.coord, Point(scene.theme.FIELD_WIDTH/2, scene.theme.FIELD_HEIGHT/2))
            self.move_at(point)
            return

        for teammate in self.teammates:
            vector = Vector.from_points(self.coord, teammate.coord, module=1)
            difference = abs(self.vector.direction - vector.direction)
            distance = self.distance_to(teammate)

            if difference < 15 and distance < self.gun.shot_distance:
                able_to_shot = False
                break

        if able_to_shot and self.distance_to(enemy) <= self.gun.shot_distance:
            if enemy.is_moving:
                self.gun.shot(Point(enemy.coord.x+enemy.vector.x**enemy.vector.module,
                                    enemy.coord.y+enemy.vector.y**enemy.vector.module))
            else:
                self.gun.shot(enemy)

    def _calculate_statistics(self, destination):
        if self.is_empty:
            IshmukhamedovDrone.empty_travel += self.distance_to(destination)
        elif self.is_full:
            IshmukhamedovDrone.full_travel += self.distance_to(destination)
        else:
            IshmukhamedovDrone.underload_travel += self.distance_to(destination)

    def get_statistics(self):
        stat = [self.empty_travel, self.full_travel, self.underload_travel]
        return stat

    @property
    def commander(self) -> Commander:
        return self._commander

    @commander.setter
    def commander(self, commander: Commander):
        self._commander = commander

    def teammates_attack_points(self):

        attack_points = []

        for teammate in self.teammates:
            attack_points.append(teammate.attack_point)

        return attack_points

    @staticmethod
    def check_attack_point(point: Point, points: List[Point]):
        """
            Проверяет наличие точки в списке точек
        :param point: Точка для проверки
        :param points: Список точек
        :return: True если точка есть и False если нет
        """
        for attack_point in points:
            if attack_point and attack_point.x == point.x and attack_point.y == point.y:
                return True

        return False

    def on_born(self):
        self.commander = Commander(drone=self)

        distance = theme.MOTHERSHIP_HEALING_DISTANCE

        if self.have_gun:
            self.mode = DroneMode.DRONE_INTERCEPTOR

            attack_points = self.commander.get_attack_points(self.my_mothership.coord, (len(self.teammates)+1)*4,
                                                             distance*1.5)
            for point in attack_points:
                teammates_attack_points = self.teammates_attack_points()
                if not self.check_attack_point(point, teammates_attack_points):
                    self.attack_point = point
                    break
            else:
                self.attack_point = self.commander.get_attack_point(drone=self)

            self.move_at(self.attack_point)
        else:
            self.move_at(self.get_target())

    def make_a_step(self, start: Point, destination: Point, ratio: float = 2/8) -> Point:
        """
            Возвращает точку в направлении от start до destination
        :param start: Начальная точка
        :param destination: Точка назначения
        :param ratio: Отпределяет в каком отношении точка делит отрезок.
        :return: Точку на отрезке start - destination
        """

        x = (start.x+ratio*destination.x)/(1+ratio)
        y = (start.y+ratio*destination.y)/(1+ratio)

        distance = 5*self.radius

        teammates = [teammate for teammate in self.teammates if self.point_in_circle(Point(x, y), teammate.coord)]

        if not teammates:
            return Point(x, y)
        else:
            points = self.commander.get_attack_points(center=Point(x, y), radius=36, size=distance)
            if (points):
                return points[0]
            return Point(x, y)

    def find_closest_enemy(self):

        enemies = [enemy for enemy in self.scene.drones
                   if enemy not in self.teammates and enemy != self and enemy.is_alive]

        if not enemies:
            enemies.extend([mother_ship for mother_ship in self.scene.motherships
                            if mother_ship != self.my_mothership and mother_ship.is_alive])

        if enemies:
            closest_enemy = enemies[0]
        else:
            return

        for enemy in enemies:
            if self.distance_to(enemy) < self.distance_to(closest_enemy):
                closest_enemy = enemy

        return closest_enemy

    def point_in_circle(self, point, center):
        radius = 2*self.radius

        in_circle = sqrt(pow(center.x-point.x, 2)+pow(center.y-point.y, 2))

        if in_circle <= radius:
            return True

        return False

    def get_common_enemy(self):
        closest_enemy = self.find_closest_enemy()
        for teammate in self.teammates:
            if teammate.enemy and teammate.enemy.is_alive:
                if self.distance_to(teammate.enemy) < self.distance_to(closest_enemy):
                    return teammate.enemy

        return closest_enemy

    def action(self):
        if self.health < 75:
            if self.distance_to(self.my_mothership) > theme.MOTHERSHIP_HEALING_DISTANCE:
                point = self.make_a_step(self.coord, self.my_mothership.coord, 5 / 5)
                self.move_at(point)
        else:
            closest_enemy = self.find_closest_enemy()
            if closest_enemy:
                if self.distance_to(closest_enemy) <= self.gun.shot_distance:
                    self.shot(closest_enemy)
                else:
                    point = self.make_a_step(self.coord, closest_enemy.coord)
                    self.move_at(point)
            else:
                self.mode = DroneMode.DRONE_HARVESTER

    def on_stop(self):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.action()
        else:
            self.move_at(self.my_mothership)

    def on_stop_at_target(self, target):
        for asteroid in self.asteroids:
            if asteroid.near(target):
                self.on_stop_at_asteroid(asteroid)
                return
        else:
            for ship in self.scene.motherships:
                if ship.near(target):
                    if ship == self.my_mothership:
                        self.on_stop_at_mothership(ship)
                    else:
                        self.on_stop_at_enemy_mothership(ship)

                    return

        self.on_stop_at_point(target)

    def on_stop_at_enemy_mothership(self, mothership):
        if not mothership.is_alive:
            self.load_from(mothership)

    def on_stop_at_point(self, target):
        if self.mode == DroneMode.DRONE_HARVESTER:
            enemy_drones = [drone for drone in self.scene.drones if drone not in self.teammates and not drone.is_empty]
            for drone in enemy_drones:
                if drone.near(target):
                    self.on_stop_at_enemy_drone(drone)
                    return

    def on_stop_at_asteroid(self, asteroid):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.action()
        else:
            self.load_from(asteroid)

    def on_stop_at_enemy_drone(self, drone):
        self.load_from(drone)

    def on_load_complete(self):
        if self.is_full:
            self.move_at(self.my_mothership)
        else:
            target = self.get_target()
            if target:
                self.move_at(target)
            else:
                self.move_at(self.my_mothership)

        self.target = None

    def on_stop_at_mothership(self, mothership):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.attack_point = self.commander.get_attack_point(drone=self)
            self.move_at(self.attack_point)
        else:
            if self.is_empty:
                target = self.get_target()
                if target:
                    self.move_at(target)
                else:
                    self.move_at(self.my_mothership)
            else:
                if mothership is self.my_mothership:
                    self.unload_to(mothership)
                else:
                    self.load_from(mothership)

    def on_unload_complete(self):
        target = self.get_target()
        if target:
            self.move_at(target)
        else:
            self.stop()

    def on_wake_up(self):
        if self.mode == DroneMode.DRONE_INTERCEPTOR:
            self.action()
        else:
            self.move_at(self.my_mothership)

drone_class = IshmukhamedovDrone


import pandas as pd
import pickle
from tools.get_prediction_data import get_bid_results

import torch
from tools.DLinear import Model as Dlinear
device = torch.device('cuda')

# data preparation
today = pd.Timestamp.now().strftime('%Y-%m-%d')
errors_x = get_bid_results().iloc[:, 1:].values
errors_x = torch.FloatTensor(errors_x).reshape(1, -1, 5).to(device)

# errors prediction
class Config:
    def __init__(self, seq_len=10, pred_len=2, individual=True, enc_in=10):
        self.seq_len = seq_len
        self.pred_len = pred_len
        self.individual = individual
        self.enc_in = enc_in  # channels
        return

configs = Config(seq_len=72, pred_len=48, individual=True, enc_in=5)
dlinear = Dlinear(configs).to(device)
dlinear.load_state_dict(torch.load('checkpoints/errors_to_errors_1.pt'))
print('dlinear model load complete.')

with torch.no_grad():
    errors_prediction = dlinear(errors_x).squeeze(dim=0)
    errors_prediction = errors_prediction.cpu().numpy()

# saving
with open(f'data_prediction/{today}-errors_prediction.pickle', 'wb') as f:
    pickle.dump(errors_prediction, f)
print('errors prediction and saving process complete.')


from django import forms
from django.core.exceptions import ValidationError

class Imagen(forms.Form):
    imagen = forms.ImageField(upload_to='imagenes/')

class SubirImagenForm(forms.ModelForm):
    class Meta:
        model = Imagen
        fields = ['imagen']

    def clean_imagen(self):
        imagen = self.cleaned_data.get('imagen')

        # Validar la extensión del archivo
        extensiones_permitidas = ['jpg', 'jpeg', 'png']
        if not any(imagen.name.lower().endswith(ext) for ext in extensiones_permitidas):
            raise forms.ValidationError('La imagen debe tener una extensión jpg o png.')

        # Validar el tamaño del archivo
        tamaño_maximo = 50 * 1024  # 50 KB
        if imagen.size > tamaño_maximo:
            raise forms.ValidationError('La imagen no puede ser mayor a 50 KB.')

        return imagen


from django.core.exceptions import ValidationError
from datetime import date

def calculate_age(born: date):
    today = date.today()
    return today.year - born.year - ((today.month, today.day) < (born.month, born.day))

def valid_age_validator(born: date):
    min_age = 13
    max_age = 100
    age = calculate_age(born)
    if age < 0:
        raise ValidationError('You cannot use date from future.')
    elif age <= min_age:
        raise ValidationError(f'You have to be older than {min_age}.')
    elif age > max_age:
        raise ValidationError('Please provide a valid age.')


# IPv4地址转换成整数【2022 Q2|100】
while 1:
    try:
        nums = list(map(int, input().split("#")))
        if len(nums) != 4:
            print("invalid IP")
        else:
            dp = ""
            for i in range(4):
                if not ((i == 0 and 1 <= nums[i] <= 128) or (i > 0 and 0 <= nums[i] <= 255)):
                    print("invalid IP")
                    break

                dp += bin(nums[i])[2:].zfill(8)
            else:
                print(int(dp, 2))
    except Exception as e:
        break


import argparse
import sys

import gym
from gym import wrappers, logger

class RandomAgent(object):
    """The world's simplest agent!"""
    def __init__(self, action_space):
        self.action_space = action_space

    def act(self, observation, reward, done):
        return self.action_space.sample()

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=None)
    parser.add_argument('env_id', nargs='?', default='CartPole-v0', help='Select the environment to run')
    args = parser.parse_args()

    # You can set the level to logger.DEBUG or logger.WARN if you
    # want to change the amount of output.
    logger.set_level(logger.INFO)

    env = gym.make(args.env_id)

    # You provide the directory to write to (can be an existing
    # directory, including one with existing data -- all monitor files
    # will be namespaced). You can also dump to a tempdir if you'd
    # like: tempfile.mkdtemp().
    outdir = '/tmp/random-agent-results'
    env = wrappers.Monitor(env, directory=outdir, force=True)
    env.seed(0)
    agent = RandomAgent(env.action_space)

    episode_count = 100
    reward = 0
    done = False

    for i in range(episode_count):
        ob = env.reset()
        while True:
            action = agent.act(ob, reward, done)
            ob, reward, done, _ = env.step(action)
            if done:
                break
            # Note there's no env.render() here. But the environment still can open window and
            # render if asked by env.monitor: it calls env.render('rgb_array') to record video.
            # Video is not recorded every episode, see capped_cubic_video_schedule for details.

    # Close the env and write monitor result info to disk
    env.close()


import os

import numpy as np

"""
has functions of operators to flip and rotate a cube in 12 possible ways
as in reference paper
A Parallel 3D 12-_subiteration Thinning Algorithm Kálmán Palágyi,Graphical Models and Image Processing
Volume 61, Issue 4, July 1999, Pages 199-221 Attila Kuba, 1999
cube is of equal dimensions in x, y and z in this program
first dimension(0) is z, second(1) is y, third(2) is x
np.rot90 is not used to Rotate an array by 90 degrees in the counter-clockwise direction.
The first two dimensions are rotated; therefore, the array must be atleast 2-D. nor
scipy.ndimage.interpolation.rotate is used because axes definitions are different in scipy
Instead a rot_3D_90 is written in this program to work to our needs
"""

def _column(cube_array, nth_column):
    """
    Returns array of ith _column of the cube_array
    Parameters
    ----------
    cube_array : numpy array
        2D or 3D numpy array

    nth_column : integer
        nth column of the cube_array

    Returns
    -------
    array formed from nth column of the cube_array

    """
    return np.array([row[nth_column] for row in cube_array])

def rot_3D_90(cube_array, rot_axis='z', k=0):
    """
    Returns a 3D array after rotating 90 degrees anticlockwise k times around rot_axis
    Parameters
    ----------
    cube_array : numpy array
        3D numpy array

    rot_axis : string
        can be z, y or x specifies which axis should the array be rotated around, by default 'z'

    k : integer
        indicates how many times to rotate, by default '0' (doesn't rotate)

    Returns
    -------
    rot_cube_array : array
        roated cube_array of the cube_array

    """
    assert 1 not in np.unique(cube_array.shape)
    assert cube_array.ndim == 3, "number of dimensions must be 3, it is %i " % cube_array.ndim
    k = k % 4  # modulus of k, since rotating 5 times is same as rotating once (360 degrees rotation)
    if k == 0:  # doesn't rotate
            return cube_array
    if rot_axis == 'z':
        if k == 1:  # rotate 90 degrees around z
            return cube_array[::-1, :, :].swapaxes(0, 1)
        elif k == 2:  # rotate 180 degrees around z
            return cube_array[::-1, :, :]
        elif k == 3:  # rotate 270 degrees around z
            return cube_array.swapaxes(0, 1)[::-1, :, :]
    elif rot_axis == 'x':
        if k == 1:  # rotate 90 degrees around x
            return cube_array[:, :, ::-1].swapaxes(1, 2)
        elif k == 2:  # rotate 180 degrees around x
            return cube_array[:, :, ::-1][:, ::-1, :]
        elif k == 3:  # rotate 270 degrees around x
            return cube_array.swapaxes(1, 2)[:, :, ::-1]
    elif rot_axis == 'y':
        if k == 1:  # rotate 90 degrees around y
            ithSlice = [cube_array[i] for i in range(3)]
            rot_slices = [np.column_stack((_column(ithSlice[2], i), _column(ithSlice[1], i), _column(ithSlice[0], i)))
                          for i in range(3)]
            rot_cube_array = np.array((rot_slices[0], rot_slices[1], rot_slices[2]))
        elif k == 2:  # rotate 180 degrees around y
            rot_cube_array = cube_array[::-1, :, :][:, :, ::-1]
        elif k == 3:  # rotate 270 degrees around y
            ithSlice = [cube_array[i] for i in range(3)]
            rot_slices = [np.column_stack((_column(ithSlice[0], i), _column(ithSlice[1], i), _column(ithSlice[2], i)))
                          for i in range(3)]
            rot_cube_array = np.array((rot_slices[0], rot_slices[1], rot_slices[2]))
        return rot_cube_array

def get_directions_list(cube_array):
    """
    Returns a list of rotated 3D arrays to change pixel to one of 12 directions
    where a border point should be removed according to Palagyi's thinning
    algorithm. the 12 directions are UN, UE, US, UW, NE, NW, ND, ES, ED, SW, SD, and WD
    Refer notes
    Parameters
    ----------
    cube_array : numpy array
        3D numpy array

    Returns
    -------
    list

    Notes
    -----
    UN - Up North, UE - Up East, US - Up South, UW - Up West, NE - North East
    NW - North West, ND - North Down, ES - East South, ED - East Down, SW - South West
    SD - South Down, WD - West Down
    """
    assert cube_array.ndim == 3, "number of dimensions must be 3, it is %i " % cube_array.ndim
    # mask outs border voxels in US
    first_subiteration = cube_array.copy(order='C')
    # mask outs border voxels in NE
    second_subiteration = rot_3D_90(rot_3D_90(cube_array, 'y', 2), 'x', 3).copy(order='C')
    # mask outs border voxels in WD
    third_subiteration = rot_3D_90(rot_3D_90(cube_array, 'x', 1), 'z', 1).copy(order='C')
    # mask outs border voxels in ES
    fourth_subiteration = rot_3D_90(cube_array, 'x', 3).copy(order='C')
    # mask outs border voxels in UW
    fifth_subiteration = rot_3D_90(cube_array, 'y', 3).copy(order='C')
    # mask outs border voxels in ND
    sixth_subiteration = rot_3D_90(rot_3D_90(rot_3D_90(cube_array, 'x', 3), 'z', 1), 'y', 1).copy(order='C')
    # mask outs border voxels in SW
    seventh_subiteration = rot_3D_90(cube_array, 'x', 1).copy(order='C')
    # mask outs border voxels in UN
    eighth_subiteration = rot_3D_90(cube_array, 'y', 2).copy(order='C')
    # mask outs border voxels in ED
    ninth_subiteration = rot_3D_90(rot_3D_90(cube_array, 'x', 3), 'z', 1).copy(order='C')
    # mask outs border voxels in NW
    tenth_subiteration = rot_3D_90(rot_3D_90(cube_array, 'y', 2), 'x', 1).copy(order='C')
    # mask outs border voxels in UE
    eleventh_subiteration = rot_3D_90(cube_array, 'y', 1).copy(order='C')
    # mask outs border voxels in SD
    twelveth_subiteration = rot_3D_90(cube_array, 'x', 2).copy(order='C')

    # List of 12 rotated configuration arrays
    DIRECTIONS_LIST = [first_subiteration, second_subiteration, third_subiteration, fourth_subiteration,
                       fifth_subiteration, sixth_subiteration, seventh_subiteration, eighth_subiteration,
                       ninth_subiteration, tenth_subiteration, eleventh_subiteration, twelveth_subiteration]
    return DIRECTIONS_LIST

# Reference array is a flipped configuration number template we convolve thinning input with
# each of the 26 elements are represented in the 2nd order neighborhood are given a value of
# power(2, index)
# 26 configuration convolution kernel's elements list
REFERENCE_ARRAY = [2 ** i for i in range(0, 26)]
# at the center of 26 neighbors, insert 0
REFERENCE_ARRAY.insert(13, 0)
# Flip it in advance to undo flip that convolution does to the kernel
REFERENCE_ARRAY.reverse()
# Reshape it to a (3, 3, 3) matrix of uint64 to use it for convolution
REFERENCE_ARRAY = np.asarray(REFERENCE_ARRAY).reshape(3, 3, 3).astype(np.uint64)

# List of 12 functions corresponding to transformations in 12 directions
DIRECTIONS_LIST = get_directions_list(REFERENCE_ARRAY)

# Path of pre-generated lookuparray.npy
LOOKUPARRAY_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'lookuparray.npy')


# @Author:Liu Yue (v3u.cn)
# @Software:Vscode
# @Time:2022/12/30

import base64
import hmac
import time
from hashlib import sha1
import json
import httpx
import aiofiles

class Qiniu:

    def __init__(self, access_key, secret_key):
        """初始化"""
        self.__checkKey(access_key, secret_key)
        self.__access_key = access_key
        self.__secret_key = secret_key.encode('utf-8')

    def get_access_key(self):
        return self.__access_key

    def get_secret_key(self):
        return self.__secret_key

    def __token(self, data):
        hashed = hmac.new(self.__secret_key,data.encode('utf-8'), sha1)
        return self.urlsafe_base64_encode(hashed.digest())

    def token(self, data):
        return '{0}:{1}'.format(self.__access_key, self.__token(data))

    def token_with_data(self, data):
        data = self.urlsafe_base64_encode(data)
        return '{0}:{1}:{2}'.format(
            self.__access_key, self.__token(data), data)

    def urlsafe_base64_encode(self,data):

        if isinstance(data, str):
            data = data.encode('utf-8')

        ret = base64.urlsafe_b64encode(data)

        data = ret.decode('utf-8')

        return data

    @staticmethod
    def __checkKey(access_key, secret_key):
        if not (access_key and secret_key):
            raise ValueError('invalid key')

    def upload_token(
            self,
            bucket,
            key=None,
            expires=3600,
            policy=None,
            strict_policy=True):
        """生成上传凭证

        Args:
            bucket:  上传的空间名
            key:     上传的文件名，默认为空
            expires: 上传凭证的过期时间，默认为3600s
            policy:  上传策略，默认为空

        Returns:
            上传凭证
        """
        if bucket is None or bucket == '':
            raise ValueError('invalid bucket name')

        scope = bucket
        if key is not None:
            scope = '{0}:{1}'.format(bucket, key)

        args = dict(
            scope=scope,
            deadline=int(time.time()) + expires,
        )

        return self.__upload_token(args)

    @staticmethod
    def up_token_decode(up_token):
        up_token_list = up_token.split(':')
        ak = up_token_list[0]
        sign = base64.urlsafe_b64decode(up_token_list[1])
        decode_policy = base64.urlsafe_b64decode(up_token_list[2])
        decode_policy = decode_policy.decode('utf-8')
        dict_policy = json.loads(decode_policy)
        return ak, sign, dict_policy

    def __upload_token(self, policy):
        data = json.dumps(policy, separators=(',', ':'))
        return self.token_with_data(data)

    @staticmethod
    def __copy_policy(policy, to, strict_policy):
        for k, v in policy.items():
            if (not strict_policy) or k in _policy_fields:
                to[k] = v

    # 上传文件流
    async def upload_data(self,up_token, key,data,url="http://up-z1.qiniup.com",params=None,mime_type='application/octet-stream',file_name=None,metadata=None):

        data.encode('utf-8')

        fields = {}
        if params:
            for k, v in params.items():
                fields[k] = str(v)

        if key is not None:
            fields['key'] = key
        fields['token'] = up_token

        fname = file_name
        if not fname or not fname.strip():
            fname = 'file_name'

        async with httpx.AsyncClient() as client:

            # 调用异步使用await关键字
            res = await client.post(url,data=fields,files={'file': (fname,data,mime_type)})

            print(res.text)

    # 上传文件实体
    async def upload_file(self,up_token,key,path,url="http://up-z1.qiniup.com",params=None,mime_type='application/octet-stream',file_name=None,metadata=None):

        async with aiofiles.open(path, mode='rb') as f:
            contents = await f.read()

        fields = {}
        if params:
            for k, v in params.items():
                fields[k] = str(v)

        if key is not None:
            fields['key'] = key
        fields['token'] = up_token

        fname = file_name
        if not fname or not fname.strip():
            fname = 'file_name'

        async with httpx.AsyncClient() as client:

            # 调用异步使用await关键字
            res = await client.post(url,data=fields,files={'file': (fname,contents,mime_type)})

            print(res.text)


import random
import re
#This is just doing all of the math for the gui version, please don't run this on it's own, it wont do anything if you do, well acutally it will, but you wouldn't be able to tell
#Basically, it would run the simulation with the deaults, and no output, I have tested it
global opt
opt = ''
def Average(lst):
    return sum(lst) / len(lst)
def main():
    global luck
    global mini
    global maxi
    global mini2
    global maxi2
    global numlist
    global temptnumlist
    global mods
    global lucktype
    global die
    global die2
    global toroll
    global hp
    global ac
    global hitlist
    global d4
    global d6
    global d8
    global d10
    global d12
    global d20
    global d100
    global ortherdie
    global numlist2
    global temptnumlist2
    try:
        die = abs(int(die))
        if die > 100:
            die = 100
    except:
        die = 1
    try:
        die2 = abs(int(die2))
        if die2 > 100:
            die2 = 100
        if die2 < 0:
            die2 = 0
    except:
        die2 = 1
    try:
        if mini != 0:
            mini = abs(int(mini))
        else:
            mini = 1
    except:
        mini = 1
    try:
        if maxi != 0:
            maxi = abs(int(maxi))
        else:
            maxi = 20
    except:
        maxi = 20
    try:
        mods = abs(int(mods))
    except:
        mods = 0
    try:
        d4 = abs(int(d4))
        if d4 > 100:
            d4 = 100
        if d4 < 0:
            d4 = 0
    except:
        d4 = 0
    try:
        d6 = abs(int(d6))
        if d6 > 100:
            d6 = 100
        if d6 < 0:
            d6 = 0
    except:
        d6 = 0
    try:
        d8 = abs(int(d8))
        if d8 > 100:
            d8 = 100
        if d8 < 0:
            d8 = 0
    except:
        d8 = 0
    try:
        d10 = abs(int(d10))
        if d10 > 100:
            d10 = 100
        if d10 < 0:
            d10 = 0
    except:
        d10 = 0
    try:
        d12 = abs(int(d12))
        if d12 > 100:
            d12 = 100
        if d12 < 0:
            d12 = 0
    except:
        d12 = 0
    try:
        d20 = abs(int(d20))
        if d20 > 100:
            d20 = 100
        if d20 < 0:
            d20 = 0
    except:
        d20 = 0
    try:
        d100 = abs(int(d100))
        if d100 > 100:
            d100 = 100
        if d100 < 0:
            d100 = 0
    except:
        d100 = 0
    if int(d4) == 0 and int(d6) == 0 and int(d8) == 0 and int(d10) == 0 and int(d12) == 0 and int(d20) == 0 and  int(d100) == 0:
        BeDone()
    numlist = []
    temptnumlist = []
    temptnumlist2 = []
    hitlist = []
    numlist2 = []
    ortherdie = []
    try:
        hp = int(hp)
    except:
        hp = 1000
    global x
    x = 0
    try:
        ac = int(ac)
    except:
        ac = 10
    ToHit()
def ToHit():
    global luck
    global mini
    global maxi
    global numlist
    global temptnumlist
    global mods
    global lucktype
    global die
    global die2
    global toroll
    global hp
    global ac
    global hitlist
    global d4
    global d6
    global d8
    global d10
    global d12
    global d20
    global d100
    global ortherdie
    global numlist2
    global temptnumlist2
    num = random.randint(mini,maxi)
    if num >= ac:
       hitlist.append(1)
       DoMath()
    else:
        if luck == True and maxi == 20:
          if lucktype == 1:
               if num == 1:
                  num = random.randint(mini,maxi)
                  if num >= ac:
                      hitlist.append(1)
                  else:
                      hitlist.append(0)
          if lucktype == 2:
              if num == 1 or num == 2:
                  num = random.randint(mini,maxi)
                  if num >= ac:
                      hitlist.append(1)
                  else:
                      hitlist.append(0)
        else:
            numlist2.append(num)
            hitlist.append(0)
            temptnumlist2.clear()
            ToHit()
def DoMath():
    global luck
    global mini
    global maxi
    global numlist
    global temptnumlist
    global mods
    global lucktype
    global die
    global die2
    global toroll
    global hp
    global ac
    global hitlist
    global d4
    global d6
    global d8
    global d10
    global d12
    global d20
    global d100
    global ortherdie
    global numlist2
    global temptnumlist2
    if d4 != 0:
        for y in range(d4):
            num = random.randint(1,4)
            ortherdie.append(num)
    if d6 != 0:
        for y in range(d6):
            num = random.randint(1,6)
            ortherdie.append(num)
    if d8 != 0:
        for y in range(d8):
            num = random.randint(1,8)
            ortherdie.append(num)
    if d10 != 0:
        for y in range(d10):
            num = random.randint(1,10)
            ortherdie.append(num)
    if d12 != 0:
        for y in range(d12):
            num = random.randint(1,12)
            ortherdie.append(num)
    if d20 != 0:
        for y in range(d20):
            if luck == True:
                num = random.randint(1,20)
                if lucktype == 1:
                    if num == 1:
                       num = random.randint(1,20)
                       ortherdie.append(num)
                if lucktype == 2:
                    if num == 1 or num == 2:
                       num = random.randint(1,20)
                       ortherdie.append(num)
                else:
                    ortherdie.append(num)
            else:
                num = random.randint(1,20)
                ortherdie.append(num)
    if d100 != 0:
        for y in range(d100):
            num = random.randint(1,100)
            ortherdie.append(num)

    num = sum(ortherdie)
    num += mods
    hp -= num
    numlist.append(num)
    temptnumlist.clear()
    ortherdie.clear()
    if hp > 0:
        try:
            ToHit()
        except:
            BeDone()

    normal = 'Rolls:'
    numbers = f'{numlist}\nAttacked: {len(numlist)}'
    numbers2 = f'{numlist2}\nMissed :{len(numlist2)}'
    numbers3 = len(numlist2) + len(numlist)
    average = Average(numlist)
    averageoutput = f'Your average hit roll is {re.sub(".0", "", str(round(average, 0)))}'
    hit = int(hitlist.count(1))
    avghit = round(((hit / len(hitlist))*100),2)
    avghitoutput = f"You hit {avghit}% of the time."
    global opt
    opt = f"""
{normal}
Damage When Hit (All Die Together): {numbers}
Numbers That Missed: {numbers2}
{averageoutput}
{avghitoutput}
Rolls it took to finish the battle: {numbers3}
    """
def BeDone():
    opt = ''
    pass


import sys
from math import sqrt
from subprocess import PIPE, Popen, STDOUT
from time import localtime

from .builder import getCmake, getMake, getPost
from .configuration import cfg
from .invocation import getInvocation
from .utils import notif, safe_cd

def simple_stats(n, s, s2):
  v = (s2/n - pow(s/n,2))
  if n==1:
    sig=sqrt(v)
    halfA=0
  else:
    sig=sqrt(v/(n-1))
    halfA=1.96*sig
  return (s / n), sig, halfA

def profileAgrum(current):
  dic = {k: current[k] for k in current.keys()}
  dic['stats'] = False
  dic['fixed_seed'] = True
  dic['no-fun'] = True

  command = getInvocation(dic)

  target = "+".join(current['targets'])
  safe_cd(current, "build")
  safe_cd(current, "agrum")
  safe_cd(current, current["mode"])

  notif("[cmake]")
  cm = getCmake(dic, target)
  proc = Popen(cm, shell=True, stdout=PIPE, stderr=STDOUT)
  out = proc.stdout.readlines()
  if current['verbose']:
    for line in out:
      print(line, end="")

  notif("[make]")
  ma = getMake(dic, target)
  proc = Popen(ma, shell=True, stdout=PIPE, stderr=STDOUT)
  out = proc.stdout.readlines()
  if current['verbose']:
    for line in out:
      print(line, end="")

  po, rc = getPost(dic, target)

  notif(f"[{cfg.nbr_tests_for_stats} runs] (please be patient) ...")
  sdt = 0
  sdt2 = 0

  dmin=float('inf')
  dmax=float('-inf')

  notif("")
  notif("-------------|------------------|-------------------|")
  notif("  time   #it |    XP (stdev)    | confid. interval  |")
  notif("-------------|------------------|-------------------|")
  for i in range(cfg.nbr_tests_for_stats):
    dt=0
    while dt==0:
      proc = Popen(po, shell=True, stdout=PIPE, stderr=STDOUT)

      out = proc.stdout.readlines()
      for line in out:
        if b"Profiling" in line:
          t=line.split(b" ")
          v=t[4] if len(t[3])==0 else t[3]
          dt = float(v) / 1000.0
      if dt==0:
        notif(f"[error : duration=0]")
      if dt>dmax:
        dmax=dt
      if dt<dmin:
        dmin=dt

    sdt += dt
    sdt2 += dt * dt
    mean, stdev, halfA = simple_stats(i + 1, sdt, sdt2)
    t=localtime()
    notif(f"{t.tm_hour:02d}:{t.tm_min:02d}:{t.tm_sec:02d} #[{i+1:02d}] | {dt:7.3f}s ({stdev:3.3f}) | [{mean:8.3f} ± {halfA:3.3f}]s |")

  notif("-------------|------------------|-------------------|")
  notif("  time   #it |    XP (stdev)    | confid. interval  |")
  notif("-------------|------------------|-------------------|")
  notif(f"=> Conclusion on {cfg.nbr_tests_for_stats} iteration(s) : {dmin:8.3f} <-- [{mean:8.3f} ± {halfA:3.3f}] --> {dmax:8.3f}")

  safe_cd(current, "..")
  safe_cd(current, "..")

  sys.exit(0)


from flask import Flask, request, jsonify
import scanner
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route('/', methods=['POST'])
def analysis():
    try:
        data = request.json
        code = data.get('code')
        response = jsonify(scanner.analyze(code))
    except Exception as e:
        response = jsonify({'error': 'Could not analyze the code: ' + str(e)})
    return response

if __name__ == '__main__':
    app.run()


from django.conf.urls import url
from django.contrib.auth import views as auth_views
from . import views
app_name='pachangapp'
urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^stats/(?P<usernameID>[\w.@+-]+)/$', views.stats, name='stats'),
    url(r'^stats/$', views.stats, name='stats'),
    url(r'^profile/$', views.profile, name='profile'),
    url(r'^login/$', views.login, name='login'),
    url(r'^logout/$', auth_views.logout, {'next_page': '/pachangapp/'}, name='logout')
]


from kivy.uix.scatter import Scatter
from kivy.uix.button import Button
from kivy.uix.floatlayout import FloatLayout
from kivy.app import App
from kivy.uix.scatterlayout import ScatterLayout
from kivy.graphics.transformation import Matrix
from kivy.uix.codeinput import CodeInput
from kivy.uix.checkbox import CheckBox
from pygments.lexers import CythonLexer
from kivy.uix.widget import Widget
from kivy.animation import Animation
from kivy.uix.switch import Switch
from kivy.properties import BooleanProperty, ObjectProperty, NumericProperty
from kivy.uix.label import Label
from kivy.uix.boxlayout import BoxLayout
from kivy.lang import Builder

class MyCodeInput(CodeInput):

    def __init__(self, size, **kwargs):
        super(MyCodeInput, self).__init__(**kwargs)
        x = size[0]
        y = size[1]
        chunk = x * .30
        self.size_hint = (None,None)
        self.size = (x - chunk,y)
        # self.pos = (10,0)
        self.pos_hint = {'x': .15, 'y': 0}
        self.lexer = CythonLexer()

    def Deactivate(self):
        self.disabled = True

    def Activate(self):
        self.disabled = False

    def update(self, size):
        x = size[0]
        y = size[1]
        print("code")
        print(x)
        chunk = x * .30
        self.size_hint = (None,None)
        self.size = (x - chunk,y)

class MyButton(Button):

    def __init__(self, size, **kwargs):
        super(MyButton, self).__init__(**kwargs)
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)
        # self.pos = (690,0)
        self.pos_hint = {'x': .85, 'y': 0}
        # self.size_hint = (.15,1)
        self.text = "Move"

    def update(self, size):
        x = size[0]
        y = size[1]
        print("button")
        print(x)
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)

class MyCheckBox(CheckBox):

    def __init__(self, size, **kwargs):
        super(MyCheckBox, self).__init__(**kwargs)
        self.pos_hint = {'x': 0, 'y': 0}
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)

    def Deactivate(self):
        self.disabled = True

    def Activate(self):
        self.disabled = False

    def update(self, size):
        self.pos_hint = {'x': 0, 'y': 0}
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y)

class MyRunButton(Button):

    def __init__(self, size, **kwargs):
        super(MyRunButton, self).__init__(**kwargs)
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y/2)
        # self.pos = (690,0)
        self.pos_hint = {'x': .85, 'y': 0}
        # self.size_hint = (.15,1)
        self.text = "Run"

    def update(self, size):
        x = size[0]
        y = size[1]
        chunk = x * .85
        self.size_hint = (None, None)
        self.size = (x - chunk,y/2)

class MyScatterLayout(ScatterLayout):
    move_lock = False
    scale_lock_left = False
    scale_lock_right = False
    scale_lock_top = False
    scale_lock_bottom = False
    col = 1,1,1,1
    disp = 1

    def __init__(self, **kwargs):
        super(MyScatterLayout, self).__init__(**kwargs)
        self.size = (800,400)
        self.pos = (400,400)
        self.size_hint = (None, None)
        self.check = MyCheckBox(self.size, id = "check")
        self.code = MyCodeInput(self.size, id = "code")
        self.move = MyButton(self.size, id = "switch")
        self.run = MyRunButton(self.size, id = "run")
        self.move.bind(on_press=self.flip)
        self.add_widget(self.check)
        self.add_widget(self.code)
        self.add_widget(self.move)
        self.add_widget(self.run)

    def flip(self, button):
        if self.disp:
            self.disp = 0
        else:
            self.disp = 1
        self.flipTheSwitch()

    def flipTheSwitch(self):
        if self.disp:
            self.check.Deactivate()
            self.code.Deactivate()

        else:
            self.check.Activate()
            self.code.Activate()

    def on_touch_up(self, touch):
        self.move_lock = False
        self.scale_lock_left = False
        self.scale_lock_right = False
        self.scale_lock_top = False
        self.scale_lock_bottom = False
        if touch.grab_current is self:
            touch.ungrab(self)
            x = self.pos[0] / 10
            x = round(x, 0)
            x = x * 10
            y = self.pos[1] / 10
            y = round(y, 0)
            y = y * 10
            self.pos = x, y
            return super(MyScatterLayout, self).on_touch_up(touch)

    def transform_with_touch(self, touch):
        changed = False
        x = self.bbox[0][0]
        y = self.bbox[0][1]
        width = self.bbox[1][0]
        height = self.bbox[1][1]
        mid_x = x + width / 2
        mid_y = y + height / 2
        inner_width = width * 0.5
        inner_height = height * 0.5
        left = mid_x - (inner_width / 2)
        right = mid_x + (inner_width / 2)
        top = mid_y + (inner_height / 2)
        bottom = mid_y - (inner_height / 2)

            # just do a simple one finger drag
        if len(self._touches) == self.translation_touches:
            # _last_touch_pos has last pos in correct parent space,
            # just like incoming touch
            dx = (touch.x - self._last_touch_pos[touch][0]) \
                 * self.do_translation_x
            dy = (touch.y - self._last_touch_pos[touch][1]) \
                 * self.do_translation_y
            dx = dx / self.translation_touches
            dy = dy / self.translation_touches
            if (touch.x > left and touch.x < right and touch.y < top and touch.y > bottom or self.move_lock) and not self.scale_lock_left and not self.scale_lock_right and not self.scale_lock_top and not self.scale_lock_bottom:
                self.move_lock = True
                self.apply_transform(Matrix().translate(dx, dy, 0))
                changed = True

        change_x = touch.x - self.prev_x
        change_y = touch.y - self.prev_y
        anchor_sign = 1
        sign = 1
        if abs(change_x) >= 9 and not self.move_lock and not self.scale_lock_top and not self.scale_lock_bottom:
            if change_x < 0:
                sign = -1
            if (touch.x < left or self.scale_lock_left) and not self.scale_lock_right:
                self.scale_lock_left = True
                self.pos = (self.pos[0] + (sign * 10), self.pos[1])
                anchor_sign = -1
            elif (touch.x > right or self.scale_lock_right) and not self.scale_lock_left:
                self.scale_lock_right = True
            self.size[0] = self.size[0] + (sign * anchor_sign * 10)
            self.prev_x = touch.x
            changed = True
        if abs(change_y) >= 9 and not self.move_lock and not self.scale_lock_left and not self.scale_lock_right:
            if change_y < 0:
                sign = -1
            if (touch.y > top or self.scale_lock_top) and not self.scale_lock_bottom:
                self.scale_lock_top = True
            elif (touch.y < bottom or self.scale_lock_bottom) and not self.scale_lock_top:
                self.scale_lock_bottom = True
                self.pos = (self.pos[0], self.pos[1] + (sign * 10))
                anchor_sign = -1
            self.size[1] = self.size[1] + (sign * anchor_sign * 10)
            self.prev_y = touch.y
            changed = True
        if changed:
            self.check.update(self.size)
            self.code.update(self.size)
            self.move.update(self.size)
        return changed

    def on_touch_down(self, touch):
        x, y = touch.x, touch.y
        self.prev_x = touch.x
        self.prev_y = touch.y
        # if the touch isnt on the widget we do nothing
        if not self.do_collide_after_children:
            if not self.collide_point(x, y):
                return False

        # let the child widgets handle the event if they want
        touch.push()
        touch.apply_transform_2d(self.to_local)
        if super(Scatter, self).on_touch_down(touch):
            # ensure children don't have to do it themselves
            if 'multitouch_sim' in touch.profile:
                touch.multitouch_sim = True
            touch.pop()
            self._bring_to_front(touch)
            return True
        touch.pop()

        # if our child didn't do anything, and if we don't have any active
        # interaction control, then don't accept the touch.
        if not self.do_translation_x and \
                not self.do_translation_y and \
                not self.do_rotation and \
                not self.do_scale:
            return False

        if self.do_collide_after_children:
            if not self.collide_point(x, y):
                return False

        if 'multitouch_sim' in touch.profile:
            touch.multitouch_sim = True
        # grab the touch so we get all it later move events for sure
        self._bring_to_front(touch)
        touch.grab(self)
        self._touches.append(touch)
        self._last_touch_pos[touch] = touch.pos
        print(self.size)
        return True

class WheatBlock(FloatLayout):

    def __init__(self, **kwargs):
        super(WheatBlock, self).__init__(**kwargs)
        self.s = MyScatterLayout(do_rotation=False)
        self.add_widget(self.s)


#!/usr/bin/env python
import pika
import sys
import json

timeout=30

def callbackresponse(ch, method, properties, body):
	body = body.decode('utf-8')
	print(json.dumps(json.loads(body),sort_keys=True,indent=4, separators=(',', ': ')))
	connection.close()
	exit()

def callbacktimeout():
	print("Timeout")
	connection.close()
	exit()

connection = pika.BlockingConnection(pika.ConnectionParameters(
        host='10.0.0.103'))
connection.add_timeout(timeout,callbacktimeout)
channel = connection.channel()

# create the topic on the rabbitmq server, if not already done
channel.exchange_declare(exchange='lxc',type='topic',durable=True,auto_delete=True)

#declare the queue on the rabbitmq server, if not already done
result = channel.queue_declare(durable=False, exclusive=False, auto_delete=True)
queue_name = result.method.queue

routing_key = sys.argv[1] if len(sys.argv) > 1 else 'anonymous.info'
message = sys.argv[2]

# send to the routing key from the commandline the message from the commandline
channel.basic_publish(exchange='lxc',
                      routing_key=routing_key,
                      body=message)
print ("[x] Sent %r:%r  -- waiting for reply" % (routing_key, message))

#wait the reply for [timeout] seconds
channel.queue_bind(exchange='lxc',
                       queue=queue_name,
                       routing_key="lxc.master")

channel.basic_consume(callbackresponse,
                      queue=queue_name,
                      no_ack=True)

channel.start_consuming()
connection.close()


from dataclasses import dataclass
from pathlib import Path
from typing import Callable, cast
from uuid import UUID, uuid4

import pytest

# use async-asgi-testclient instead of the starlette one because of
# https://github.com/encode/starlette/issues/472
from async_asgi_testclient import TestClient
from fastapi import Depends, Header
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker

from ..app import app
from ..auth import current_user
from ..config import Env, settings
from ..crud import CRUD
from ..database import Base
from ..db import get_db

assets = Path(__file__).parent / "assets"

settings.env = Env.TESTING

SQLALCHEMY_DATABASE_URL = "sqlite+aiosqlite:///:memory:"

engine = create_async_engine(
    SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False}
)
TestingSessionLocal = cast(
    Callable[[], AsyncSession],
    sessionmaker(
        autocommit=False,
        autoflush=False,
        bind=engine,
        class_=AsyncSession,  # type: ignore
    ),
)

async def override_get_db():
    session: AsyncSession
    async with engine.begin() as session:  # type: ignore
        await session.run_sync(Base.metadata.create_all)
    async with TestingSessionLocal() as session:
        yield session

app.dependency_overrides[get_db] = override_get_db

async def override_current_user(
    authorization: str | None = Header(None),
    crud: CRUD = Depends(),
):
    if authorization:
        uname, userid = authorization.split(":")
        uid = UUID(userid)
        return await crud.get_or_create_user(uid, uname)
    return None

app.dependency_overrides[current_user] = override_current_user

@pytest.fixture
def client(tmpdir: Path):
    settings.textures_fs = f"file://{tmpdir}"
    return TestClient(app)

@pytest.fixture(autouse=True)
def anyio_backend():
    return "asyncio"

@dataclass
class TestUser:
    uuid: UUID
    name: str

    __test__ = False

    @property
    def auth_header(self):
        return {"authorization": f"{self.name}:{self.uuid}"}

@pytest.fixture
def user():
    return TestUser(uuid4(), "TestUser")

@pytest.fixture
def users():
    """Fixture to get a list of random users"""
    return [TestUser(uuid4(), f"TestUser{n}") for n in range(1, 11)]


#!/usr/bin/env python2.7
from __future__ import unicode_literals

import simplejson as json
import sys, os
from time import sleep, time
import subprocess

txt_launch_error = '''No path given.

Example:
    %s /tmp/config.json
    \n''' % sys.argv[0]

def main():
    ## defaults:
    if 'jingle_period' in config and type(config['jingle_period']) == int and config['jingle_period'] > 0:
        jingle_period = config['jingle_period']
    else:
        jingle_period = 30000000

    ## Prepare jingles list ##
    if 'jingles' in config:
        if type(config['jingles']) == list and len(config['jingles']) > 0:
            jingles = config['jingles']
        elif type(config['jingles']) == str and os.path.isfile(config['jingles']):
            # Its a path to a json file, load it
            with open(config['jingles'], 'r') as f:
                jingles = json.load(f)
        else:
            jingles = []
    else:
        jingles = []

    if len(jingles) > 0:
        add_j = True
        if len(jingles) > 1:
            jn = 1
        else:
            jn = 0
    else:
        add_j = False
    ## end of prepare jingles ##

    dirname = os.path.dirname(config_file)
    cachedir = '%s/cache' % dirname
    cachelist_file = '%s/%s.playlist.json' % (cachedir, config['name'])
    with open(cachelist_file, 'r') as f:
        cachelist = json.load(f)

    #files = []
    #for item in cachelist

    ## Generate liquidsoap playlist
    lq_playlist_file = '%s/%s.playlist' % (dirname, config['name'])
    with open(lq_playlist_file, 'w') as f:
        if add_j:
            # Add a jingle in the beginning
            jingle = u'request.push ' + jingles[0] + '\n\n'
            f.write(jingle.encode('utf-8'))
        size_count = 0
        for item in cachelist:
            size_count += item[2]
            filename = '%s/%s' % (cachedir, os.path.basename(item[0]))
            playlist_item = u'request.push annotate:artist="%s",title="%s (by %s)":%s\n\n' % (config['title'], item[1], item[3], filename)
            f.write(playlist_item.encode('utf-8'))
            if add_j and size_count > jingle_period:
                jingle = u'request.push ' + jingles[jn] + '\n\n'
                f.write(jingle.encode('utf-8'))
                size_count = 0
                jn += 1
                if jn >= len(jingles):
                    jn = 0
        if add_j:
            # Add last jingle to the end of playlist
            jingle = u'request.push ' + jingles[len(jingles)-1] + '\n\n'
            f.write(jingle.encode('utf-8'))

    ## add playlist to liquidsoap queue
    subprocess.call(['/usr/local/bin/autodj-play', 'list', lq_playlist_file])

if __name__ == '__main__':
    if len(sys.argv) < 2:
        sys.stderr.write(txt_launch_error)
        sys.exit(0)

    config_file = os.path.abspath(sys.argv[1])
    with open(config_file, 'r') as f:
        config = json.load(f)
    try:
        main()
    except KeyboardInterrupt:
        sys.exit(0)


# for i in range(10,21):
#     f = open(r"C:\Users\RAHUL\Documents\OnePython\0.SelfStudy\{}.py".format(i) ,"w")
#     f.write("")

#################################################
#
#################################################
#  TOPICS TO BE COVERED
# ðŸ‘‰ OOP IN PYTHON
#################################################

# Constructor in Python

# A constructor is a special method used to create and initialize an object of a class. This method is defined in the class.

# The constructor is executed automatically at the time of object creation.
# The primary use of a constructor is to declare and initialize data member/ instance variables of a class. The constructor contains a collection of statements (i.e., instructions) that executes at the time of object creation to initialize the attributes of an object.

# In Python, Object creation is divided into two parts in Object Creation and Object initialization

# Internally, the __new__ is the method that creates the object
# And, using the __init__() method we can implement constructor to initialize the object.

# Syntax of a constructor

# def __init__(self):
#     # body of the constructor

# Example: Create a Constructor in Python

class Student:

    # constructor
    # initialize instance variable
    def __init__(self, name):
        print('Inside Constructor')
        self.name = name
        print('All variables initialized')

    # instance Method
    def show(self):
        print('Hello, my name is', self.name)

# create object using constructor
s1 = Student('Emma')
s1.show()

# In Python, we have the following three types of constructors.

        # Default Constructor
        # Non-parametrized constructor
        # Parameterized constructor
            # Constructor With Default Values

 # Default Constructor
class Employee:

    def display(self):
        print('Inside Display')

emp = Employee()
emp.display()

# Non-parametrized constructor
class Company:

    # no-argument constructor
    def __init__(self):
        self.name = "PYnative"
        self.address = "ABC Street"

    # a method for printing data members
    def show(self):
        print('Name:', self.name, 'Address:', self.address)

# creating object of the class
cmp = Company()

# calling the instance method using the object
cmp.show()

# Parameterized constructor
class Employee:
    # parameterized constructor
    def __init__(self, name, age, salary):
        self.name = name
        self.age = age
        self.salary = salary

    # display object
    def show(self):
        print(self.name, self.age, self.salary)

# creating object of the Employee class
emma = Employee('Emma', 23, 7500)
emma.show()

kelly = Employee('Kelly', 25, 8500)
kelly.show()

# Constructor With Default Values

class Student:
    # constructor with default values age and classroom
    def __init__(self, name, age=12, classroom=7):
        self.name = name
        self.age = age
        self.classroom = classroom

    # display Student
    def show(self):
        print(self.name, self.age, self.classroom)

# creating object of the Student class
emma = Student('Emma')
emma.show()

kelly = Student('Kelly', 13)
kelly.show()

# Self Keyword in Python

class Student:
    # constructor
    def __init__(self, name, age):
        self.name = name
        self.age = age

    # self points to the current object
    def show(self):
        # access instance variable using self
        print(self.name, self.age)

# creating first object
emma = Student('Emma', 12)
emma.show()

# creating Second object
kelly = Student('Kelly', 13)
kelly.show()

# Constructor Overloading

# Python does not support constructor overloading. If we define multiple constructors then, the interpreter will considers only the last constructor and throws an error if the sequence of the arguments doesnâ€™t match as per the last constructor.

class Student:
    # one argument constructor
    def __init__(self, name):
        print("One arguments constructor")
        self.name = name

    # two argument constructor
    def __init__(self, name, age):
        print("Two arguments constructor")
        self.name = name
        self.age = age

# creating first object
emma = Student('Emma')

# creating Second object
kelly = Student('Kelly', 13)

# Constructor Chaining

# Constructor chaining is the process of calling one constructor from another constructor. Constructor chaining is useful when you want to invoke multiple constructors, one after another, by initializing only one instance.

# In Python, constructor chaining is convenient when we are dealing with inheritance. When an instance of a child class is initialized, the constructors of all the parent classes are first invoked and then, in the end, the constructor of the child class is invoked.

# Using the super() method we can invoke the parent class constructor from a child class

class Vehicle:
    # Constructor of Vehicle
    def __init__(self, engine):
        print('Inside Vehicle Constructor')
        self.engine = engine

class Car(Vehicle):
    # Constructor of Car
    def __init__(self, engine, max_speed):
        super().__init__(engine)
        print('Inside Car Constructor')
        self.max_speed = max_speed

class Electric_Car(Car):
    # Constructor of Electric Car
    def __init__(self, engine, max_speed, km_range):
        super().__init__(engine, max_speed)
        print('Inside Electric Car Constructor')
        self.km_range = km_range

# Object of electric car
ev = Electric_Car('1500cc', 240, 750)
print(f'Engine={ev.engine}, Max Speed={ev.max_speed}, Km range={ev.km_range}')

# Counting the Number of objects of a Class

# The constructor executes when we create the object of the class. For every object, the constructor is called only once. So for counting the number of objects of a class, we can add a counter in the constructor, which increments by one after each object creation.

class Employee:
    count = 0
    def __init__(self):
        Employee.count = Employee.count + 1

# creating objects
e1 = Employee()
e2 = Employee()
e2 = Employee()
print("The number of Employee:", Employee.count)

# Constructor Return Value
# In Python, the constructor does not return any value. Therefore, while declaring a constructor, we donâ€™t have anything like return type. Instead, a constructor is implicitly called at the time of object instantiation. Thus, it has the sole purpose of initializing the instance variables.

class Test:

    def __init__(self, i):
        self.id = i
        return True

d = Test(10)

# OP>> TypeError: __init__() should return None, not 'bool'


import numpy as np
import pandas as pd
from scipy.sparse import csr_matrix
from sklearn.neighbors import NearestNeighbors
import pickle
import json

data = pd.read_csv('C:/Users/hp/Documents/need-for-code-7/ml/data/kids.csv')

kidsData = pd.read_csv('C:/Users/hp/Documents/need-for-code-7/ml/data/kids.csv')
menData = pd.read_csv('C:/Users/hp/Documents/need-for-code-7/ml/data/men.csv')
womenData = pd.read_csv('C:/Users/hp/Documents/need-for-code-7/ml/data/women.csv')
shoesData = pd.read_csv('C:/Users/hp/Documents/need-for-code-7/ml/data/shoes.csv')

row_subcategory_drop = ['Brassières de grossesse',
       'Costumes pour bébé', 'Salopettes & Combinaisons',
       'Maillots de bain', 'Coutumes & Co-ords',
       'Costume & Jupe-culotte',
       'Blousons & Vestes', 'Tops', 'Pantalons', 'Chaussures pour fille',
       'Vêtements de nuit',
       'Sous-vêtements de maintien de grossesse', 'Trainers',
       'Bas', 'Chaussures pour bébé',
       'Chapeaux',
       'Trousses', "Vêtements d'extérieur & Manteaux",
       'Robes & Sacs de couchage', 'Chaussures pour enfant',
       'Lingerie de grossesse', 'Accessoires pour cheveux', 'Sacs à dos',
       'Accesssoires des vêtements', 'Écharpes', 'Chaussettes',
       'Sets de coutumes', 'Lunettes de soleil', 'Sacs des couches',
       'Sacs à main', 'Swimwear', 'Vêtements pour fille',
       'Vêtements de nuit & Robes',
       'Colliers & Pendentifs', 'Imperméables', 'Accessoires pour enfant',
       'Accessoires']

drop_cloumns = ['discount', 'currency', 'brand', 'brand_url', 'codCountry', 'variation_0_color', 'variation_1_color', 'variation_0_thumbnail', 'variation_0_image', 'variation_1_thumbnail', 'variation_1_image', 'image_url', 'model', 'url']

df = data.drop(drop_cloumns, axis=1)

for i in range(len(row_subcategory_drop)):
    index_names = df[ df['subcategory'] == row_subcategory_drop[i] ].index
    df.drop(index_names, inplace = True)

likes_features_df = df.pivot_table(index='name', columns='subcategory', values=['likes_count','current_price', 'is_new', 'raw_price']).fillna(0)
likes_features_df_matrix = csr_matrix(likes_features_df.values)

# model_kids_knn = NearestNeighbors(metric='cosine', algorithm='brute')
# model_kids_knn.fit(likes_features_df_matrix)
model_kids_knn = pickle.load(open('C:/Users/hp/Documents/need-for-code-7/ml/models/kids_model.pkl', 'rb'))

# query_index = np.random.choice(likes_features_df.shape[0])
# print(query_index)

def getSimilarKidsProducts(productName):
    query_index = 0
    for i in range(likes_features_df.index.shape[0]):
        if likes_features_df.index[i] == productName:
            query_index = i

    distances, indices = model_kids_knn.kneighbors(likes_features_df.iloc[query_index, :].values.reshape(1,-1), n_neighbors=11)

    ls = []
    for i in range(0, len(distances.flatten())):
        if i == 0:
            print("Recommendations for {0}".format(likes_features_df.index[query_index]))
        else:
            print("{0}: {1}, with distance of {2}".format(i, likes_features_df.index[indices.flatten()[i]], distances.flatten()[i]))
            ls.append(likes_features_df.index[indices.flatten()[i]])

    new_ls = data['name'].isin(ls)
    similarProducts = data[new_ls]

    return json.dumps(ls)

# def getProducts():
#     productsData = "Data Not Available"
#     print("Request Recieved!")
#     # recievedData = request.json
#     categoryRequested = "shoes"

#     if categoryRequested == "kids":
#         # kidsData = kidsData.sort_values(by=['likes_count'], ascending=False)
#         print(kidsData.sort_values(by=['likes_count'], ascending=False)['likes_count'])
#     elif categoryRequested == "men":
#         # menData = menData.sort_values(by=['likes_count'], ascending=False)
#         print(menData.sort_values(by=['likes_count'], ascending=False)['likes_count'])
#     elif categoryRequested == "women":
#         # womenData = womenData.sort_values(by=['likes_count'], ascending=False)
#         print(womenData.sort_values(by=['likes_count'], ascending=False)['likes_count'])
#     elif categoryRequested == "shoes":
#         # shoesData = shoesData.sort_values(by=['likes_count'], ascending=False)
#         print(shoesData.sort_values(by=['likes_count'], ascending=False)['likes_count'])

#     print(productsData)

# getProducts()


import os
import json
from glob import glob
from omegaconf import ListConfig
from hydra.utils import to_absolute_path

import numpy as np
import pandas as pd
import uproot

def tau_vs_other(prob_tau, prob_other):
    return np.where(prob_tau > 0, prob_tau / (prob_tau + prob_other), np.zeros(prob_tau.shape))

def create_df(path_to_preds, pred_samples, tau_type_to_select, selection,
              pred_group_name, pred_column_prefix, target_group_name, target_column_prefix,
              add_columns_from, add_columns, group_or_tree_name,
              **kwargs):
    df = []
    path_to_preds = os.path.abspath(to_absolute_path(path_to_preds))

    # loop over input samples
    for sample_name, sample_cfg in pred_samples.items():

        # make list of files with predictions depending on the specified format
        filename_pattern = sample_cfg['filename_pattern']
        if isinstance(filename_pattern, ListConfig):
            pred_files = [f'{path_to_preds}/{sample_name}/{filename}' for filename in filename_pattern]
        elif isinstance(filename_pattern, str):
            pred_files = glob(f'{path_to_preds}/{sample_name}/{filename_pattern}')
        else:
            raise Exception(f"unknown type of filename_pattern: {type(filename_pattern)}")

        df_sample = []
        for pred_file in pred_files:
            # read predictions and labels
            l_ = []
            for group in [pred_group_name, target_group_name]:
                df_ = pd.read_hdf(pred_file, group)
                df_ = df_.rename(columns={column: f'{group}_{column}' for column in df_.columns})
                l_.append(df_)
            assert l_[0].shape[0] == l_[1].shape[0], "Sizes of prediction and target dataframes don't match."
            df_pred = pd.concat(l_, axis=1)

            if add_columns_from == 'inputs':# read add_columns from the corresponding input file
                json_filemap_name = f'{path_to_preds}/{sample_name}/pred_input_filemap.json'
                with open(json_filemap_name, 'r') as json_file:
                    target_input_map = json.load(json_file)

                with uproot.open(target_input_map[pred_file]) as f:
                    df_add = f[group_or_tree_name].arrays(add_columns, library='pd')

                # concatenate input branches and predictions/labels
                assert df_pred.shape[0] == df_add.shape[0], "Sizes of prediction and input dataframes don't match."
            elif add_columns_from == 'predictions':
                df_add = pd.read_hdf(pred_file, group_or_tree_name)
                df_add = df_add[add_columns]
            else:
                raise RuntimeError(f'add_columns_from should be either predictions or inputs, got {add_columns_from}')

            df_sample_ = pd.concat([df_pred, df_add], axis=1)
            assert not any(df_sample_.isna().any(axis=0)), 'found NaNs!'
            df_sample.append(df_sample_)

        # concat together files for a given sample and apply tau_type matching & selection
        df_sample = pd.concat(df_sample, axis=0)
        df_sample = df_sample.query(f'{target_group_name}_{target_column_prefix}{tau_type_to_select}==1')
        if selection is not None:
            df_sample = df_sample.query(selection)

        # compute weight variable
        df_sample['weight'] = 1.
        if sample_cfg['reweight_to_lumi'] is not None:
            df_sample['weight'] *= sample_cfg['sample_lumi'] / (sample_cfg['reweight_to_lumi'] * df_sample.shape[0])

        df.append(df_sample)

    # concat across samples
    df = pd.concat(df, axis=0)

    # compute vs_type discriminator scores
    vs_types = ['e', 'mu', 'jet']
    for vs_type in vs_types:
        df['score_vs_' + vs_type] = tau_vs_other(df[f'{pred_group_name}_{pred_column_prefix}tau'].values, df[f'{pred_group_name}_{pred_column_prefix}' + vs_type].values)

    print(f'\n-> Selected {df.shape[0]} {tau_type_to_select}s')
    return df


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Date: '2018/09/12 9:34'

from django.conf.urls import url

from .views import UserInfoView, UploadImageView, UpdatePwdView, SendEmailCodeView, UpdateEmailView, MycourseView
from .views import MyFavCourseView, MyFavOrgView, MyFavTeacherView, MyMessageView

urlpatterns = [
    url(r'^info/$', UserInfoView.as_view(), name='user_info'),
    url(r'^upload/image/$', UploadImageView.as_view(), name='upload_image'),
    url(r'^update/pwd/$', UpdatePwdView.as_view(), name='update_pwd'),
    url(r'^sendemail_code/$', SendEmailCodeView.as_view(), name='sendemail_code'),
    url(r'^update_email/$', UpdateEmailView.as_view(), name='update_email'),
    url(r'^courses/$', MycourseView.as_view(), name='my_courses'),
    url(r'^fav_courses/$', MyFavCourseView.as_view(), name='my_fav_courses'),
    url(r'^fav_orgs/$', MyFavOrgView.as_view(), name='my_fav_orgs'),
    url(r'^fav_teachers/$', MyFavTeacherView.as_view(), name='my_fav_teachers'),
    url(r'^my_messages/$', MyMessageView.as_view(), name='my_messages'),
]


from flask import Flask, request, Response, jsonify
import json

app = Flask(__name__)

hashset = {'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday'}

def get_data_from_file():
    file = open('quotes.json')
    data = json.load(file)
    file.close()
    return data

def get_result(day, quotes=None):
    if quotes is None:
        quotes = get_data_from_file()
    if day is not None:
        result = {key: value for key, value in quotes.items()
                  if key == day}
    else:
        return jsonify({
            "error": "Invalid Request - No Day Parameter"
        }), 400
    if result == {}:
        return {}, 204
    return jsonify(result), 200

@app.route("/")
def get_all():
    data = get_data_from_file()
    if data == {}:
        return {}, 204
    return jsonify(data), 200

@app.route("/<day>", methods=['GET'])
def get_by_id(day):
    if day == None:
        return {}, 400
    day = day.lower()
    day = " ".join(day.split())
    if day not in hashset:
        return {}, 400
    return get_result(day)

@app.route("/", methods=['POST'])
def add_quote():
    data = request.get_json()
    if 'day' not in data or 'quote' not in data:
        return {}, 400
    day = data.get('day').lower()
    day = " ".join(day.split())
    if day not in hashset:
        return {}, 400
    quote = data.get('quote')
    quote = " ".join(quote.split())
    quote_data = get_data_from_file()
    if day in quote_data:
        return {}, 400
    quote_data[day] = quote
    with open('quotes.json', 'w') as f:
        json.dump(quote_data, f)
    return jsonify({
        day : quote
    }), 201

@app.route("/<day>", methods=["PUT", "DELETE"])
def update(day):
    statusCode = 400
    if day == None:
        return {}, statusCode
    day = day.lower()
    day = " ".join(day.split())
    if day not in hashset:
            return {}, statusCode
    quote_data = get_data_from_file()
    if request.method == "PUT":
        if day in quote_data:
            statusCode = 200
        else:
            statusCode = 201
        quote = request.get_json().get("quote", "invalid")
        if quote == "invalid":
            return {}, 400
        quote = " ".join(quote.split())
        quote_data[day] = quote
        with open("quotes.json", "w") as f:
            json.dump(quote_data, f)
        return jsonify({
            day : quote
        }), statusCode
    if request.method == "DELETE":
        if day in quote_data:
            statusCode = 200
        else:
            return {}, 404
        del quote_data[day]
        with open("quotes.json", "w") as f:
            json.dump(quote_data, f)
        return {}, statusCode

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=5050)


# https://www.hackerrank.com/challenges/diagonal-difference/problem

# hint - python arrays (non-pandas or numpy) are a list of lists
# hint - the array may not actually be square, they try to trick you into thinking it's always square!

#!/bin/python3

import math
import os
import random
import re
import sys

#
# Complete the 'diagonalDifference' function below.
#
# The function is expected to return an INTEGER.
# The function accepts 2D_INTEGER_ARRAY arr as parameter.
#

def diagonalDifference(arr):
    # Write your code here
    # normalize matrix down to smaller dimension
    def regularize(arr):
        category='NoCat'
        bigdim='unknown'
        # if y and x dim same
        if len(arr) == len(arr[0]):
            # do nothing
            category='nochange'
            bigdim='same'
            arr=arr
        # if y dim larger than x dim
        elif len(arr) > len(arr[0]):
            category='ybigger'
            bigdim=len(arr)
            # slice the bottom y dim off
            # slice off by smaller dimension, len(arr[0])
            arr = arr[0:len(arr[0])]
        # if y dim smaller than x dim
        elif len(arr) < len(arr[0]):
            category='xbigger'
            newarr=[]
            # the larger dimension
            bigdim=len(arr[0])
            # columns first, all columns
            for ydim in range(0,len(arr)):
                # append each row, skipping the last column of each row
                # len(arr is the smaller dimension)
                newarr.append(arr[ydim][0:len(arr)])
                # return the newly crafted array
            arr=newarr

        # return
        return(arr,category,bigdim)

    # newly created arr, snipped off for length
    regarr,category,bigdim = regularize(arr)

    # set up empty lists
    def diagmaker(arr):
        righttoleftarr=[]
        lefttorightarr=[]
        for each in range(0,len(arr)):
            # start at n,0 and go to 0,n
            # get the rightleft point value
            rlpoint = arr[len(arr)-each-1][each]
            # append to the diag
            righttoleftarr.append(rlpoint)
            # start at 0,0 and go to n,0
            # get the leftright current point value
            lrpoint = arr[each][each]
            # append the point to the diag
            lefttorightarr.append(lrpoint)
            # return both diag's
        return(righttoleftarr,lefttorightarr)

    # create the actual diag's
    righttoleftarr,lefttorightarr = diagmaker(regarr)
    # sum of righttoleftarr
    rightsum = sum(righttoleftarr)
    # sum of lefttorightarr
    leftsum = sum(lefttorightarr)
    # absolute diagdiff
    absdiagdiff = abs(leftsum-rightsum)

    # return main function
    # absdiagdiff,leftsum,rightsum,righttoleftarr,lefttorightarr
    return(absdiagdiff)

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    arr = []

    for _ in range(n):
        arr.append(list(map(int, input().rstrip().split())))

    result = diagonalDifference(arr)

    fptr.write(str(result) + '\n')

    fptr.close()


import datetime

nowdatetime = datetime.datetime.now()
print(nowdatetime)

class Calculator:
    def __init__(self, num1, num2):
        self.num1 = num1
        self.num2 = num2

    def add(self):
        return self.num1+self.num2

    def substract(self):
        return self.num1-self.num2

    def multiply(self):
        return self.num1*self.num2

    def divide(self):
        return self.num1/self.num2

def inputsprinter(cal):
    for x in cal:
        print(x.num1, " ", x.num2)

f = open("input.txt", "a+")
f.write("=> {} \n".format(nowdatetime))

input_list = []
x = 0
while x < 2:
    print(" ")
    print("************************** CT CALCULATOR ******************************** ")
    print(" ")
    print("{} inputs \n".format(x))
    num1 = int(input("Enter the First Number : "))
    num2 = int(input("Enter the Second Number : "))

    cal = Calculator(num1, num2)
    f.write("{} {} \n".format(num1, num2))
    input_list.append(cal)
    total = cal.add()

    balance = cal.substract()
    multiply = cal.multiply()
    division = cal.divide()
    f.write(("Total : {},  Balance :  {}, Multipication is : {}, Division is : , {} \n").format(
        total, balance, multiply, division))
    x = x+1

print(" ")
f.write("{} inputs \n".format(x))

print(" ")
print("************************** THE END ******************************** ")

print(" ")
inputsprinter(input_list)
f.write(" \n")
f.close()


import datetime
import time
from decimal import Decimal
from unittest.mock import Mock

from django.test import TestCase
from django.utils.timezone import now

from pytz import utc

from api.actions import TrainingConfigurationActionManager
from api.actions import TrainingTaskActionManager
from api.models import TrainingConfiguration
from api.models import TrainingTask

def alter_tz_format(datetime_str):
    return datetime_str.replace("+00:00", "+0000")

def to_timestamp(date_time_instance):
    return time.mktime(date_time_instance.timetuple())

class ActionManagersTestCase(TestCase):

    def test_schedule_training_task(self):
        training_configuration = self.get_training_configuration()
        actions = TrainingConfigurationActionManager(
            training_configuration
        )

        task = actions.run_training()

        self.assertEqual(task.training_configuration, training_configuration)
        self.assertEqual(task.status, TrainingTask.CREATED)
        self.assertEqual(task.started_on, None)
        self.assertEqual(task.terminated_on, None)
        self.assertEqual(task.test_loss, None)
        self.assertEqual(task.test_accuracy, None)
        self.assertAlmostEqual(
            to_timestamp(task.created_on),
            to_timestamp(datetime.datetime.now()),
            places=8
        )

    def get_training_configuration(self):
        return TrainingConfiguration.objects.create(
            algorithm='algo1.py',
            dockerfile='Dockerfile.dms',
        )
    def get_training_task(self, status=TrainingTask.CREATED):
        started_on = now() if status != TrainingTask.CREATED else None
        return TrainingTask.objects.create(
            training_configuration=self.get_training_configuration(),
            status=status,
            started_on=started_on
        )

    def test_build_action_success(self):
        task = self.get_training_task()
        image = Mock()
        mocked_client = Mock()
        mocked_client.images.build.return_value = (image, [])
        actions = TrainingTaskActionManager(task)

        result = actions.build(
            docker_client=mocked_client
        )

        self.assertEqual(actions.model.status, TrainingTask.BUILDING)
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.images.build.called)
        self.assertEqual(result, image)

    def test_build_action_failure(self):
        task = self.get_training_task()
        mocked_client = Mock()
        mocked_client.images.build.side_effect = Exception("Oops")
        actions = TrainingTaskActionManager(task)

        actions.build(
            docker_client=mocked_client
        )

        self.assertEqual(actions.model.status, TrainingTask.FAILURE)
        self.assertEqual(
            actions.model.failure_message,
            "Failed to start image build: Oops"
        )
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.images.build.called)

    def test_build_action_failure(self):
        task = self.get_training_task()
        mocked_client = Mock()
        mocked_client.images.build.side_effect = Exception("Oops")
        actions = TrainingTaskActionManager(task)

        actions.build(
            docker_client=mocked_client
        )

        self.assertEqual(actions.model.status, TrainingTask.FAILURE)
        self.assertEqual(
            actions.model.failure_message,
            "Failed to start image build: Oops"
        )
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.images.build.called)

    def test_run_action_failure(self):
        task = self.get_training_task(status=TrainingTask.BUILDING)
        image = Mock()
        mocked_client = Mock()
        mocked_client.containers.run.side_effect = Exception("Oops")
        actions = TrainingTaskActionManager(task)

        result = actions.run(
            docker_client=mocked_client, docker_image=image
        )

        self.assertEqual(actions.model.status, TrainingTask.FAILURE)
        self.assertEqual(
            actions.model.failure_message,
            "Failed to run docker container : Oops"
        )
        self.assertNotEqual(actions.model.started_on, None)
        self.assertTrue(mocked_client.containers.run.called)
        self.assertEqual(result, None)

    def test_run_action_success(self):
        task = self.get_training_task(status=TrainingTask.BUILDING)
        container = Mock(id=2345)
        image = Mock()
        mocked_client = Mock()
        mocked_client.containers.run.return_value = container
        actions = TrainingTaskActionManager(task)

        result = actions.run(
            docker_client=mocked_client, docker_image=image
        )

        self.assertEqual(actions.model.status, TrainingTask.TRAINING)
        self.assertEqual(actions.model.failure_message, None)
        self.assertTrue(mocked_client.containers.run.called)
        self.assertEqual(result, container)


"""A setuptools based setup module.

Created based on https://github.com/pypa/sampleproject
and dependencies ensured via pipenv-setup sync tooling.
"""
import sys

# Always prefer setuptools over distutils
from setuptools import setup, find_namespace_packages
from os import path

here = path.abspath(path.dirname(__file__))
sys.path.append(path.join(here, "src"))

from tools.utils.version import git_version  # noqa: E402

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

setup(
    name="tools",  # Required
    version=git_version(),  # Required
    description="Project with CLI tools: setup-opendns, automount-cifs",  # Optional
    long_description=long_description,  # Optional
    long_description_content_type="text/markdown",  # Optional (see note above)
    url="https://github.com/matihost/monorepo",  # Optional
    author="matihost",  # Optional
    classifiers=[  # Optional
        "Development Status :: 3 - Alpha",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Build Tools",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 3.11",
    ],
    keywords="exchange rate nbp",  # Optional
    # When your source code is in a subdirectory under the project root, e.g.
    # `src/`, it is necessary to specify the `package_dir` argument.
    package_dir={"": "src"},  # Optional
    packages=find_namespace_packages(where="src"),  # Required
    # Ensures that non .py files are included in package
    setup_requires=["setuptools_scm"],
    include_package_data=True,
    python_requires=">=3.11, <4",
    install_requires=[
        "jinja2>=3.1.2",
        "markupsafe>=2.1.1; python_version >= '2.7' and python_version >= '3.11'",
    ],
    dependency_links=[],
    entry_points={
        "console_scripts": [
            "automount-cifs=tools.cli.automount_cifs:main",
            "setup-opendns=tools.cli.setup_opendns:main",
        ],
    },
    project_urls={"Source": "https://github.com/matihost/monorepo/", },  # Optional
)


from tkinter import Tk, Scale, Button
import json
from utils import load_config, change_theme

class soundMenu:
    def __init__(self, prev):
        self.prev = prev
    def save_slider_value(self, slider):
        value = slider.get()
        self.config["volume"] = value
        with open("config.json", "w") as json_file:
            json.dump(self.config, json_file)
    def on_closing(self):
        self.config = load_config()
        change_theme(self.prev, self.config["theme"])
        self.root.destroy()
        self.prev.deiconify()
    def sound_m(self):
        self.config = load_config()
        volume = self.config["volume"]
        self.prev.withdraw()
        root = Tk()
        root.title("Menu dzwięku")
        root.geometry("225x100")
        root.resizable(False, False)
        self.root = root
        volume_slider = Scale(root, from_=0, to=100, orient="horizontal", length=205)
        volume_slider.set(volume)
        volume_slider.pack(expand=True)
        button = Button(root, text="Zapisz", command=lambda: self.save_slider_value(volume_slider))
        button.pack(expand=True)
        change_theme(root, self.config["theme"])
        root.protocol("WM_DELETE_WINDOW", self.on_closing)
        root.mainloop()


import tkinter as tk
from tkinter import ttk
from random import randint
import simpleaudio as sa
import os
import simpleaudio as sa

class KidsGame(tk.Tk):

    def __init__(self):
        super().__init__()

        self.num1 = tk.StringVar()
        self.num2 = tk.StringVar()

        self.count = 0

        # Creating window
        self.title('Math game')
        self.resizable(0, 0)
        self.geometry('315x130')
        self['bg'] = 'lightblue'

        # Creating num1 label
        self.labelNum1 = ttk.Label(
            self,
            text=self.get_Num1(),
            font = ('Digital-7', 40))

        self.labelNum1.place(x=15, y=20)

        # Styling labels
        self.styleLabel = ttk.Style(self)
        self.styleLabel.configure(
            'TLabel',
            background = 'lightblue',
            foreground = 'black')

        self.labelPlus = ttk.Label(
            self,
            text='+',
            font=('Digital', 35))

        # Creating num2 label
        self.labelNum2 = ttk.Label(
            self,
            text=self.get_Num2(),
            font = ('Digital-7', 40))

        self.labelNum2.place(x=117, y=20)

        self.labelEquals = ttk.Label(
            self,
            text='=',
            font=('Digital', 35))

        self.entrySum = ttk.Entry(
            self,
            font=('Digital', 40))

        self.entrySum.place(x=235, y=25, width=65, height=50)

        # Creating a button to start timer with
        self.checkAnswer = ttk.Button(
            self,
            text='Check answer',
            command=lambda:self.check_Sum(self.entrySum))

        self.checkAnswer.place(x=175, y=90)

        # Creating button for refreshing numbers
        self.refreshNums = ttk.Button(
            self,
            text='Refresh',
            command=lambda:self.call_Both()) # Calling 2 functions at once

        self.counterLabel = ttk.Label(
            self,
            text=self.count
        )

        self.counterLabel.place(x=5, y=5)

        self.refreshNums.place(x=55, y=90)

        self.get_Places()

    def get_Num1(self):
        self.randomNum1 = randint(1, 50)

        return self.randomNum1

    def get_Num2(self):
        self.randomNum2 = randint(1, 50)

        return self.randomNum2

    def check_Sum(self, entrySum):
        dir_path = os.path.dirname(os.path.realpath(__file__))
        correctSoundFilePath = dir_path + '\\correctSound.wav'
        incorrectSoundFilePath = dir_path + '\\incorrectSound.wav'
        correctSound = sa.WaveObject.from_wave_file(correctSoundFilePath)
        incorrectSound = sa.WaveObject.from_wave_file(incorrectSoundFilePath)

        sum = self.randomNum1 + self.randomNum2

        if entrySum.get() == str(sum):
            print('Correct result')
            self.count += 1
            self.get_Count()
            correctSound.play()
            self.entrySum.delete(0, 'end')
            self.update_Nums()
        else:
            print('Incorrect result')
            incorrectSound.play()
            self.count = 0
            self.entrySum.delete(0, 'end')
            self.get_Count()

    def update_Nums(self):
        self.labelNum1.config(text=self.get_Num1())
        self.labelNum2.config(text=self.get_Num2())

        self.get_Places()

        self.entrySum.delete(0, 'end') # Clearing entry box

    def get_Places(self):
        self.get_current_Nums()

        # Setting conditions for placing '=' sign
        if self.curNum1 > 9 and self.curNum2 < 10:
            self.labelEquals.place(x=188, y=22)
            self.labelNum2.place(x=133, y=20)
        if  self.curNum1 <= 9 and self.curNum2 >= 10:
            self.labelEquals.place(x=192, y=22)
            self.labelNum2.place(x=122, y=20)
        if self.curNum1 > 9 and self.curNum2 >= 10:
            self.labelEquals.place(x=193, y=22)
            self.labelNum2.place(x=118, y=20)
        if self.curNum1 <= 9 and self.curNum2 < 10:
            self.labelEquals.place(x=187, y=22)
            self.labelNum2.place(x=136, y=20)

        # Setting conditions for placing '+' sign
        if self.curNum1 > 9 and self.curNum2 < 10:
            self.labelPlus.place(x=85, y=22)
        if self.curNum1 > 9 and self.curNum2 >= 10:
            self.labelPlus.place(x=84, y=22)
        if self.curNum1 <= 9 and self.curNum2 >= 10:
            self.labelPlus.place(x=72, y=22)
        if self.curNum1 <= 9 and self.curNum2 < 10:
            self.labelPlus.place(x=72, y=22)

    def get_current_Nums(self):
        self.curNum1 = self.randomNum1
        self.curNum2 = self.randomNum2

        return self.curNum1, self.curNum2

    def get_Count(self):
        self.counterLabel.config(text=self.count)

    def minus_One(self):
        if self.count != 0:
            self.count -= 1
        self.update_Nums()
        self.get_Count()

    def call_Both(self):
        self.update_Nums()
        self.minus_One()

if __name__ == "__main__":
    game = KidsGame()
    game.mainloop()