import pandas as pd
from utils import get_task2_data, logger, str2bool, preprocess
from pathlib import Path
import argparse
import string
import spacy
from nltk.stem.wordnet import WordNetLemmatizer
from gensim.models import KeyedVectors
from sklearn.preprocessing import MinMaxScaler
import pickle
import numpy as np
from sklearn.metrics import silhouette_score
from sklearn.cluster import MiniBatchKMeans
from bokeh.plotting import figure, output_file, show
from bokeh.models import HoverTool, value, LabelSet, Legend, ColumnDataSource
import seaborn as sns
from sentence_transformers import SentenceTransformer
from sklearn.decomposition import PCA
from sklearn.metrics.cluster import homogeneity_score

MODEL_FOLDER = Path('models')
LEMMATIZER = WordNetLemmatizer()

def preprocess_clustering(text: str):
    text = preprocess(text)
    tokens = text.split(' ')
    doc = []
    for token in tokens:
        if token in string.punctuation:
            continue
        if token.isnumeric():
            continue
        if len(token) < 2:
            continue

        # lemmatize the words
        token = LEMMATIZER.lemmatize(token)
        doc.append(token)
    return doc

def doc2vec_helper(doc, model, size=300):
    vec = np.zeros(size).reshape((1, size))
    count = 0.
    for word in doc:
        try:
            vec += model[word].reshape((1, size))
            count += 1.
        except KeyError:
            continue
    if count != 0:
        vec /= count
    return vec

def doc2vec(docs, model_name):
    doc2vec_path = MODEL_FOLDER / model_name

    if not doc2vec_path.exists():
        docs = [preprocess_clustering(content) for content in docs]
        pretrained_embeddings_path = Path('data') / 'GoogleNews-vectors-negative300.bin'

        model = KeyedVectors.load_word2vec_format(pretrained_embeddings_path, binary=True)
        X_doc2vecs = np.asarray([doc2vec_helper(doc, model) for doc in docs])
        X_doc2vecs = X_doc2vecs.reshape((X_doc2vecs.shape[0], 300))

        with open(doc2vec_path, 'wb') as file:
            pickle.dump(X_doc2vecs, file)

    with open(doc2vec_path, 'rb') as file:
        X_doc2vecs = pickle.load(file)
    return X_doc2vecs

def get_ner_vectors(text, nlp):
    doc = nlp(text)
    entity_tags = dict.fromkeys(['PERSON', 'NORP', 'FAC', 'ORG', 'GPE', 'LOC', 'PRODUCT', 'EVENT', 'WORK_OF_ART'],
                                0)
    for ent in doc.ents:
        if ent.label_ in entity_tags.keys():
            entity_tags[ent.label_] += 1
    entity_vec = np.array(list(entity_tags.values()))
    entity_vec = entity_vec.reshape(1, len(entity_tags.keys()))
    return entity_vec

def bert_vec(docs, model_name):
    bert_model_path = MODEL_FOLDER / model_name

    if not bert_model_path.exists():
        model = SentenceTransformer('bert-large-nli-stsb-mean-tokens')
        embeddings = model.encode(docs)
        with open(bert_model_path, 'wb') as file:
            pickle.dump(embeddings, file)

    with open(bert_model_path, 'rb') as file:
        X_bert = pickle.load(file)
    return X_bert

def NERvec(docs, model_name):
    ner_model_path = MODEL_FOLDER / model_name

    if not ner_model_path.exists():
        nlp = spacy.load("en_core_web_sm")
        # docs = [preprocess_clustering(content) for content in data['text']]
        X_ner = np.array([get_ner_vectors(doc, nlp) for doc in docs])
        X_ner = X_ner.reshape((X_ner.shape[0], X_ner.shape[2]))
        min_max_scaler = MinMaxScaler()
        X_ner = min_max_scaler.fit_transform(X_ner)
        with open(ner_model_path, 'wb') as file:
            pickle.dump(X_ner, file)

    with open(ner_model_path, 'rb') as file:
        X_ner = pickle.load(file)

    return X_ner

def read_data():
    data = pd.DataFrame(get_task2_data())
    # columns ['id', 'text', 'title', 'lang', 'date', 'cluster', 'cluster_name'
    logger.info('Number of samples {}'.format(len(data)))
    logger.info('Language vs. articles {}'.format(data.groupby('lang')['id'].count()))
    expected_clusters_num = len(data['cluster_name'].unique())
    logger.info('Expected cluster {}'.format(expected_clusters_num))
    num_topics = expected_clusters_num
    return data, num_topics

def visualize(source, pos_x, pos_y, clusters):
    output_file('clustering.html')
    num_clusters = len(set(clusters))
    colors = np.array(sns.color_palette(sns.color_palette("muted", num_clusters)).as_hex())
    logger.info(len(colors))
    source = ColumnDataSource(dict(
        x=pos_x,
        y=pos_y,
        id=source['id'],
        title=source['title'],
        # text=source['text'],
        date=source['date'],
        cluster_name=source['cluster_name'],
        color=colors[clusters],
        label=['Cluster {}'.format(i) for i in clusters]
    ))
    plot = figure(title="Clustering with {} clusters".format(num_clusters),
                  plot_width=900, plot_height=700, tools="pan,wheel_zoom,box_zoom,reset,hover,save")

    plot.scatter(source=source, x='x', y='y', color='color', legend_group='label')

    # hover tools
    hover = plot.select(dict(type=HoverTool))

    hover.tooltips = {"content": "Id: @id, Title: @title, Date: @date, Cluster: @cluster_name"}
    plot.legend.location = "top_left"
    show(plot)

def clustering(params):
    data, num_topics = read_data()
    inputs = params.inputs
    if inputs == 'title':
        sub_data = data['title'].tolist()
    elif inputs == 'text':
        sub_data = data['text'].tolist()

    if params.model == 'doc2vec':
        model_name = 'doc2vec' + inputs + '.pk'
        X = doc2vec(sub_data, model_name)
    elif params.model == 'ner':
        model_name = 'ner' + inputs + '.pk'
        X = NERvec(sub_data, model_name)
    elif params.model == 'doc2vec_ner':
        model_name_ner = 'ner' + inputs + '.pk'
        model_name_doc2vec = 'doc2vec' + inputs + '.pk'
        X = np.concatenate((doc2vec(sub_data, model_name_doc2vec), NERvec(sub_data, model_name_ner)), axis=1)
        logger.info(X.shape)
    elif params.model == 'bert':
        assert 'title' == inputs
        model_name = 'berttitle.pk'
        X = bert_vec(sub_data, model_name)

    k = num_topics
    kmeans = MiniBatchKMeans(n_clusters=k, max_iter=1000, random_state=args.random_seed)
    y_pred = kmeans.fit_predict(X)

    logger.info('Silhoutte score: {}'.format(silhouette_score(X, y_pred, random_state=args.random_seed)))
    y_ground = [int(i) for i in data['cluster'].tolist()]
    logger.info('Homogeneity score: {}'.format(homogeneity_score(y_ground, y_pred)))

    pca = PCA(n_components=2, random_state=args.random_seed)
    reduced_pos = pca.fit_transform(X)
    visualize(data, reduced_pos[:, 0], reduced_pos[:, 1], y_pred)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--random_seed', type=int, required=True)
    parser.add_argument('--model', type=str, choices=['doc2vec', 'ner', 'doc2vec_ner', 'bert'], required=True)
    parser.add_argument('--inputs', type=str, choices=['title', 'text'], required=True)

    args = parser.parse_args()

    clustering(args)


import numpy as np
from enum import Enum

class ServerIDs(Enum):
    """
    Description:
        Class storing server names
    """
    msn = 'MSN'
    asn_1 = 'ASN1'
    asn_2 = 'ASN2'

class Groups(Enum):
    """
    Description:
        Class storing group ids
    """
    Group_1 = 1
    Group_2 = 2
    Group_3 = 3

class Statistics(Enum):
    """
    Description:
        Class storing statistcs ids
    """
    mean = 'average'
    q75 = 'q75'
    max_ = 'max'

class Status(Enum):
    """
    Description:
        Class storing status - First Come First Serve (FCFS) principle
    """
    handled = -1
    served = 0
    arrived = np.inf

class CustomerGroup:
    """
    Description:
        Class storing all customer group specific information
    """
    def __init__(self,ID,popularity,activity_pattern,distances):
        self.ID = ID
        self.popularity = popularity
        self.weights=popularity/np.sum(popularity)
        self.activity_pattern = activity_pattern
        self.distances = distances

    def best_server_options(self):
        """
        Description:
            Finding server options
        Return:
            list (str) - sorted list of server options from best to worst
        """
        return sorted(self.distances, key=self.distances.get)

class Server:
    """
    Description:
        Class representing the servers {MSN, ASN1, ASN2}
    """
    def __init__(self, id_, movies_stored, capacity, movie_sizes):
        self.id = id_
        self.movies_stored = movies_stored
        self.capacity = capacity
        self.movie_sizes = movie_sizes

         # Parameter for checking that the capacity limited of the server is not succeeded
        self.capacity_check = capacity
        self.check_capacity_limit()

    def check_capacity_limit(self):
        """
        Description:
            Check capacity limited is not succeeded
        """
        for movie in self.movies_stored:
            self.capacity_check -= self.movie_sizes[movie]
            if self.capacity_check < 0:
                raise Exception('Server Capacity Exceeded')

class LoadBalancer:
    """
    Description:
        Superclass storing the servers and all associated information (e.g. such as serving time)
    """
    def __init__(self, movies_stored_msn, movies_stored_asn_1, movies_stored_asn_2,\
                 capacities, serve_times, movie_sizes):
        self.msn = Server(ServerIDs.msn.value, movies_stored_msn, capacities[0], movie_sizes)
        self.asn_1 = Server(ServerIDs.asn_1.value, movies_stored_asn_1, capacities[1], movie_sizes)
        self.asn_2 = Server(ServerIDs.asn_2.value, movies_stored_asn_2, capacities[2], movie_sizes)
        self.serve_times = serve_times
        self.movie_sizes = movie_sizes

    def get_serve_time(self, movie: int, group_id: int, server_id: str):
        """
        Description:
            Return service time based on input arguments
        Args:
            int - chosen movie
            int - group_id of customer group \in {1,2,3}
            string - server_id of server \in {'MSN', 'ASN1', 'ASN2'}
        Return:
            Int - serve time
        """
        movie_size = self.movie_sizes[movie]
        if movie_size < 900:
            return self.serve_times[900][server_id][group_id]

        elif movie_size >= 900 and movie_size < 1100:
            return self.serve_times[1100][server_id][group_id]

        elif movie_size >= 1100:
            return self.serve_times[1500][server_id][group_id]
        else:
            raise Exception(f'Movie Size: {movie_size}')

class SingleCustomer:
    """
    Description:
        Class representing single customer
    """
    def __init__(self,id_,time,movie_choice,server_address,waiting_time):
        self.id_ = id_
        self.status = Status.arrived.value
        self.time = time
        self.movie_choice = movie_choice
        self.waiting_time = waiting_time
        self.server_address = server_address
        self.is_waiting = False


import pathlib
import shutil
from scanner import frame_reader, ScreenState, ROI
import numpy as np
import cv2 as cv
from detector import level, type_and_main_stat, artifact_set_name, sub_stats

import sketch

# class allroi:
#   upper = ROI(1214, 230, 1550, 430)
#   lower = ROI(1213, 504, 1830, 1111)
#   level = ROI(1251, 530, 1324, 570)
#   sub_stats_template = ROI(1270, 590, 1800, 504)

class allroi:
  upper = ROI(1434, 265, 1828, 520)
  lower = ROI(1434, 596, 2159, 1310)
  level = ROI(1476, 632, 1561, 674)
  sub_stats_template = ROI(1500, 700, 2141, 596)

class ArtifactFields:
  def __repr__(self):
    return '\n'.join([f"{k:10}: {v}" for k, v in self.__dict__.items()])

def parse_frame(frame: np.array):
  artifact = ArtifactFields()
  sketch.sketch('frame', frame)
  gray = cv.cvtColor(frame, cv.COLOR_BGR2GRAY)

  set_roi = artifact_set_name.find_artifact_set_name_roi(frame, allroi.lower)
  artifact.set_name = artifact_set_name.parse_artifact_set_name(gray, set_roi)

  sub_stats_roi = sub_stats.find_sub_stats_roi(set_roi, allroi.sub_stats_template)
  artifact.sub_stats = sub_stats.parse_sub_stats(gray, sub_stats_roi)

  type_name_value = type_and_main_stat.parse_type_main_stat_name_value
  [
    artifact.type,
    artifact.main_stat_name,
    artifact.main_stat_value
  ] = type_name_value(gray, allroi.upper)

  artifact.level = level.parse_level(gray, allroi.level)

  return artifact

import json
def is_data_same(a, b):
  aa = json.dumps(a, sort_keys=True)
  bb = json.dumps(b, sort_keys=True)
  return aa == bb

def test_parse_all(video_path: str, sketch_path: str):
  if not video_path:
    video_path = frame_reader.get_test_video_path()
  reader = frame_reader.FrameReader(video_path, time=0)

  state = ScreenState([allroi.upper, allroi.lower])

  artifacts = []
  last_info = None
  while True:
    frame = reader.next()
    if frame is None: break

    if not state.is_same(frame):
      try:
        if sketch_path:
          with sketch.SketchRecorder(f"{sketch_path}/{reader.time:.4f}", save_error=True, log_error=True):
            info = parse_frame(frame)
        else:
          info = parse_frame(frame)

        info = info.__dict__
      except Exception as e:
        info = dict(error_message=str(e))

      if is_data_same(info, last_info):
        continue

      result = dict(time=reader.frame_time, info=info)
      artifacts.append(result)
      last_info = info
      print(f'{reader.frame_time:.4f}', info)

  return artifacts

import click

@click.command()
@click.option("--output_path", type=click.Path(exists=False, dir_okay=False), default="output.yaml", help='artifacts output filename')
@click.option("--sketch_path", type=click.Path(exists=False, dir_okay=True), default=None, help='debug sketch path')
@click.argument("video_path", type=click.Path(exists=True, dir_okay=False))
def command(output_path, video_path, sketch_path):
  sketch_path_obj = pathlib.Path(sketch_path)
  if sketch_path_obj.exists():
    shutil.rmtree(sketch_path_obj)

  result = test_parse_all(video_path, sketch_path)

  import yaml
  with open(output_path, 'w') as f:
    yaml.dump(result, f, allow_unicode=True)

if __name__ == "__main__":
  command()


'''
Given a binary array nums, you should delete one element from it.

Return the size of the longest non-empty subarray containing only 1's in the resulting array. Return 0 if there is no such subarray.

Example 1:

Input: nums = [1,1,0,1]
Output: 3
Explanation: After deleting the number in position 2, [1,1,1] contains 3 numbers with value of 1's.
Example 2:

Input: nums = [0,1,1,1,0,1,1,0,1]
Output: 5
Explanation: After deleting the number in position 4, [0,1,1,1,1,1,0,1] longest subarray with value of 1's is [1,1,1,1,1].
Example 3:

Input: nums = [1,1,1]
Output: 2
Explanation: You must delete one element.

Constraints:

1 <= nums.length <= 105
nums[i] is either 0 or 1.
'''
from typing import *
from collections import deque

import unittest
from collections import defaultdict

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        next_zero = [len(nums) for _ in range(len(nums))]
        prev_zero = [0 for _ in range(len(nums))]

        # next
        zero_index = len(nums)
        for i in range(len(nums) - 1, -1, -1):
            next_zero[i] = zero_index
            if nums[i] == 0:
                zero_index = i

        # prev
        zero_index = -1
        for i in range(len(nums)):
            prev_zero[i] = zero_index
            if nums[i] == 0:
                zero_index = i

        res = 0
        for i in range(len(nums)):
            res = max(res, i - prev_zero[i] - 1 + next_zero[i] - i - 1)
        return res

class TestSolution(unittest.TestCase):

    def test_case(self):
        examples = (
            (([1,1,0,1], ), 3),
            (([0,1,1,1,0,1,1,0,1], ), 5),
            (([1,1,1], ), 2),
        )
        for first, second in examples:
            self.assert_function(first, second)

    def assert_function(self, first, second):
        self.assertEqual(Solution().longestSubarray(*first), second,
                         msg="first: {}; second: {}".format(first, second))

unittest.main()

Leetcode/1493. Longest Subarray of 1s After Deleting One Element.py


import pygame
from random import randint
import math

pygame.init()

FPS = 70
screensize = (1200, 800)
screen = pygame.display.set_mode(screensize, pygame.SRCALPHA)

pygame.display.update()
clock = pygame.time.Clock()

WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
YELLOW = (255, 255, 0)
GREEN = (0, 255, 0)
MAGENTA = (255, 0, 255)
CYAN = (0, 255, 255)
BLACK = (0, 0, 0)
COLORS = [RED, BLUE, YELLOW, GREEN, MAGENTA, CYAN]

element_mass = {'massive': [], 'remove ind': -1}

targets_mass = {'massive': [], 'remove ind': -1}

class Player:

    def __init__(self, username='', score=0, shots=0):
        """
        Some information about player (Score, Username, number of shots)
        :param username:
        :param score:
        :param shots:
        """
        self.score = score
        self.username = username
        self.shots = shots

class Ball:
    """
    Class of balls (Shells)
    """
    def __init__(self):
        """
        Generates random parameters of Ball (color, coord, velocity)
        Default parameters: gravitation, health, is_alive
        """
        self.color = COLORS[randint(0, 5)]
        self.radius = randint(30, 50)
        self.coord_x = randint(self.radius, screensize[0] - self.radius)
        self.coord_y = randint(self.radius, screensize[1] - self.radius)
        self.velocity_x = int(randint(-5, 5))
        self.velocity_y = int(randint(-5, 5))
        self.gravitation = 0.2
        self.health = 30
        self.is_alive = True
        self.time_of_live = 300

    def draw_ball(self):
        """
        Draws ball
        """
        pygame.draw.circle(screen, self.color, (self.coord_x, self.coord_y), self.radius)
        self.time_of_live -= 1

    def move_ball(self):
        """
        Moves ball
        """
        self.coord_x += self.velocity_x
        self.coord_y -= self.velocity_y
        self.velocity_y -= self.gravitation

        if self.coord_x > screensize[0] - self.radius or self.coord_x < self.radius:
            self.velocity_x *= -0.95
        if self.coord_y > screensize[1] - 50:
            self.velocity_y *= -0.95
        if abs(self.velocity_y) < 0.001:
            self.velocity_y = 0
        if self.time_of_live == 0:
            self.is_alive = False
        self.draw_ball()
        pygame.draw.circle(screen, BLACK, (self.coord_x, self.coord_y), self.radius, width=2)

class BallTarget(Ball):
    """
    Class of Targets, inheritance from Balls
    """
    def __init__(self, health=30, is_alive=True):
        """
        Generates new Target
        :param health: health points
        :param is_alive: Default (True)
        """
        super().__init__()
        self.health = health
        self.is_alive = is_alive

    def move_target(self):
        """
        Moves targets
        """
        self.coord_x += self.velocity_x
        self.coord_y += self.velocity_y
        if self.coord_x >= screensize[0] - self.radius or self.coord_x <= self.radius:
            self.velocity_x *= -1
            self.velocity_y = randint(-5, 5)
        if self.coord_y >= screensize[1] - self.radius or self.coord_y <= self.radius:
            self.velocity_y *= -1
            self.velocity_x = randint(-5, 5)
        self.draw_ball()

    def hit_enemy(self, obj, player):
        """
        Updates health points of target and adds points of player, if he hits
        :param player: Player
        :param obj: Aim
        """
        if (self.coord_x - obj.coord_x) ** 2 + (self.coord_y - obj.coord_y) ** 2 <= (self.radius + obj.radius) ** 2:
            self.health -= 100
            player.score += 1
            if self.health <= 0:
                self.is_alive = False

class Gun:
    """
    Class of Cannon
    """
    def __init__(self, x=40, y=500, color=BLACK, length=70, angle=0, shooting_mode=False, power=0):
        """
        :param x: coordinate x
        :param y: coordinate y
        :param color: color
        :param length: gun barrel length
        :param angle: angle with the horizon
        :param shooting_mode:
        :param power:
        """
        self.x = x
        self.y = y
        self.color = color
        self.length = length
        self.angle = angle
        self.shooting_mode = shooting_mode
        self.power = power
        self.maxlength = length*1.5

    def fire2_start(self):
        """
        Starts shooting mode
        """
        self.shooting_mode = True

    def fire2_end(self):
        """Выстрел мячом.
        Происходит при отпускании кнопки мыши.
        Начальные значения компонент скорости мяча vx и vy зависят от положения мыши.
        """
        new_ball = Ball()
        new_ball.radius = 15

        x0, y0 = pygame.mouse.get_pos()

        if x0 == self.x:
            pass
        else:
            self.angle = -math.atan((y0 - self.y) / (x0 - self.x))
        new_ball.velocity_x = self.power * math.cos(self.angle) * 0.5
        new_ball.velocity_y = self.power * math.sin(self.angle) * 0.5

        new_ball.coord_x = self.x + self.length * math.cos(self.angle)
        new_ball.coord_y = self.y - self.length * math.sin(self.angle)
        element_mass['massive'].append(new_ball)
        self.power = 0
        self.length = 70
        self.color = BLACK
        self.shooting_mode = False

    def draw_gun(self):
        """
        Draws Gun
        """
        pygame.draw.line(screen, self.color, (self.x, self.y),
                         (self.x + self.length * math.cos(self.angle),
                          self.y - self.length * math.sin(self.angle)), width=7)

    def targeting(self):
        """
        Process of targeting (depends on mouse position)
        """
        x0, y0 = pygame.mouse.get_pos()
        if x0 == self.x:
            pass
        else:
            self.angle = -math.atan((y0 - self.y) / (x0 - self.x))
        if self.shooting_mode:
            self.color = RED
            if self.length >= self.maxlength:
                pass
            else:
                self.length += 1
        else:
            self.color = BLACK

        self.draw_gun()

    def power_up(self):
        """
        Gains power of shot
        """
        if self.shooting_mode:
            if self.power < 100:
                self.power += 0.5
            self.color = RED

        else:
            self.color = BLACK

def generate_targets(number_of_targets):
    """
    Generation of targets, put them in massive
    :param number_of_targets:set number of targets
    """
    for i in range(number_of_targets):
        targets_mass['massive'].append(BallTarget())

finished = False

def game():
    """
    Game session process
    """
    global finished
    generate_targets(2)
    counter = 0
    new_gun = Gun()
    finished_session = False
    see_results = False
    new_player = Player()
    element_mass['massive'].clear()

    while not finished_session:

        clock.tick(FPS)
        if not see_results:
            myfont = pygame.font.SysFont('Times New Roman', 30)
            scoretext = myfont.render((str(new_player.shots)), True, BLACK)
            screen.blit(scoretext, (screensize[0] // 8, 30))
        if see_results:
            myfont2 = pygame.font.SysFont('Times New Roman', 30)
            finish_session_text = myfont2.render(("Вы уничтожили все цели за: " + str(new_player.shots) + " выстрелов"),
                                                 True, BLACK)
            screen.blit(finish_session_text, (screensize[0] // 3.5, screensize[1] // 3))
            counter += 1
            if counter == 150:
                finished_session = True

        for event in pygame.event.get():

            if event.type == pygame.QUIT:
                finished = True
                finished_session = True
            elif event.type == pygame.MOUSEBUTTONDOWN:
                new_gun.fire2_start()
            elif event.type == pygame.MOUSEBUTTONUP:
                new_gun.fire2_end()
                if not see_results:
                    new_player.shots += 1

        new_gun.targeting()
        new_gun.power_up()

        targets_mass['remove ind'] = -1
        element_mass['remove ind'] = -1
        for i in range(len(targets_mass['massive'])):
            targets_mass['massive'][i].move_target()
        for j in range(len(element_mass['massive'])):
            element_mass['massive'][j].move_ball()
        for i in range(len(targets_mass['massive'])):
            for j in range(len(element_mass['massive'])):
                if not element_mass['massive'][j].is_alive:
                    element_mass['remove ind'] = j
                if not targets_mass['massive'][i].is_alive:
                    targets_mass['remove ind'] = i
                targets_mass['massive'][i].hit_enemy(element_mass['massive'][j], new_player)

        if targets_mass['remove ind'] == -1:
            pass
        else:
            targets_mass['massive'].remove(targets_mass['massive'][targets_mass['remove ind']])

        if element_mass['remove ind'] == -1:
            pass
        else:
            element_mass['massive'].remove(element_mass['massive'][element_mass['remove ind']])

        if not targets_mass['massive']:
            see_results = True

        pygame.display.update()
        screen.fill(WHITE)

while not finished:
    game()

pygame.quit()


import re
import os
import json
import subprocess
import multiprocessing
import time
from itertools import islice
import sys

def launch_babachi(key, value):
    n_proc = multiprocessing.current_process().name
    print(multiprocessing.current_process().name)
    bed_list = []
    for exp in value:
        bed_file = path + exp.split('/')[-1].split('.')[0] + '.bed'
        bed_list.append(bed_file)
    babachi_inp = ' '.join(bed_list)
    print(key, babachi_inp, mode, n_proc)
    result = subprocess.run([f"/home/safronov/Projects/UDACHA/scripts/badmaps/get_BAD.sh {key} '{babachi_inp}' {mode} {n_proc}"], shell=True)

if __name__ == '__main__':

    mode = sys.argv[1]
    with open(f'/home/safronov/Projects/UDACHA/meta_info/advanced_badgroups/badmaps_dict_{mode}.json', "r") as read_file:
        badgroups = json.load(read_file)
    path = f'/home/safronov/Projects/UDACHA/raw_data/filtered_vcfs/{mode}/'

    start = time.time()
    args = []

    with multiprocessing.Pool(20) as p:
        p.starmap(launch_babachi, badgroups.items())
        p.close()
        p.join()

    end = time.time()


# Nicholas Wojtowicz

# use winsound to enable .wav files to be played in program

import winsound

#create dictionary for pickups, body, and neck with prices for each key

pickups = {
  "1": 200,
  "2": 200,
  "3": 270,
  "4": 180,
  "5": 180,
  "6": 260,
  "7": 155,
  "8": 200
}

body = {
  "12": 220,
  "13": 250,
  "14": 300
}

neck = {
  "9": 180,
  "10": 200,
  "11": 170
}

# balance starts at 0 and money is added to balance for each part selected

balance = 0

def metalguitar():
    statementm = print('Please type the number associated with the part you want')
    pickupselectm = input('Select pickups; Seymour Duncan Invader(1): $200, EMG 81(2): $200, or Bareknuckle Cobra T(3): $270? ')
    while True:
        if pickupselectm == '1' or '2' or '3':
            mbalance = balance + pickups[pickupselectm]
            print('The cost of the guitar is now: $', mbalance)
            neckm = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
            if neckm == '9' or '10' or '11':
               mmbalance = mbalance + neck[neckm]
               print('The cost of the guitar is now: $', mmbalance)
               bodym = input('Select type of wood for the body; Mahogany(12): $220, Maple (13): $250, or Ash(14): $300? ')
               if bodym == '12' or '13' or '14':
                   mmmbalance = mmbalance + body[bodym]
                   print('The total cost of the guitar is: $', mmmbalance)
                   break
               else:
                   print('invalid answer. Try again.')
                   bodym = input('Select type of wood for the body; Mahogany(12): $220, Maple (13): $250, or Ash(14): $300? ')
                   break
            else:
                print('invalid answer. Try again.')
                neckm = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
                break
        else:
            print('Invalid answer. Try again.')
            pickupselectm = input('Select pickups; Seymour Duncan Invader(1): $200, EMG 81(2): $200, or Bareknuckle Cobra T(3): $270? ')
            break

def rockguitar():
    statementr = print('Please type the number associated with the part you want')
    pickupselectr = input('Select pickups; DiMarzio Area T(4): $180, Bareknuckle Cobra T(3): $270, or Seymour Duncan Invader(1): $200?')
    while True:
        if pickupselectr == '1' or '3' or '4':
            rbalance = balance + pickups[pickupselectr]
            print('The cost of the guitar is now: $', rbalance)
            neckr = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
            if neckr == '9' or '10' or '11':
                rrbalance = rbalance + neck[neckr]
                print('The cost of the guitar is now: $', rrbalance)
                bodyr = input('Select type of wood for the body; Mahogany (12): $220, Maple (13): $250, or Ash(14): $300? ')
                if bodyr == '12' or '13' or '14':
                    rrrbalance = rrbalance + body[bodyr]
                    print('The total cost of the guitar is: $', rrrbalance)
                    break
                else:
                    print('invalid answer. Try again.')
                    bodyr = input('Select type of wood for the body; Mahogany(12): $220, Maple (13): $250, or Ash(14): $300? ')
                    break
            else:
                print('invalid answer. Try again.')
                neckr = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
                break
        else:
            print('invalid answer. Try again.')
            pickupselectr = input('Select pickups; DiMarzio Area T(4): $180, Bareknuckle Cobra T(3): $270, or Seymour Duncan Invader(1): $200?')
            break

def jazzguitar():
    statementj = print('Please type the number associated with the part you want')
    pickupselectj = input('Select Pickups: Seymour Duncan SH-2(5): $180, Seymour Duncan SNS(6): $260, or Benedetto S-6 (7): $155?')
    while True:
        if pickupselectj == '5' or '6' or '7':
            jbalance = balance + pickups[pickupselectj]
            print('The cost of the guitar is now: $', balance)
            neckj = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
            if neckj == '9' or '10' or '11':
                jjbalance = jbalance + neck[neckj]
                print('The cost of the guitar is now: $', jjbalance)
                bodyj = input('Select type of wood for the body; Mahogany (12): $220, Maple (13): $250, or Ash(14): $300? ')
                if bodyj == '12' or '13' or '14':
                    jjjbalance = jjbalance + body[bodyj]
                    print('The total cost of the guitar is: $', jjjbalance)
                    break
                else:
                    print('invalid answer. Try again.')
                    bodyj = input('Select type of wood for the body; Mahogany(12): $220, Maple (13): $250, or Ash(14): $300? ')
                    break
            else:
                print('invalid answer. Try again.')
                neckj = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
                break
        else:
            print('invalid answer. Try again.')
            input('Select Pickups: Seymour Duncan SH-2(5): $180, Seymour Duncan SNS(6): $260, or Benedetto S-6 (7): $155?')
            break

def altguitar():
    statementj = print('Please type the number associated with the part you want')
    pickupselecta = input('Bareknuckle Cobra T(3): $270, DiMarzio Area T (4): $180, or EMG 85 (8): $200?')
    while True:
        if pickupselectj == '3' or '4' or '8':
            abalance = balance + pickups[pickupselecta]
            print('The cost of the guitar is now: $', balance)
            necka = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
            if necka == '9' or '10' or '11':
                aabalance = abalance + neck[necka]
                print('The cost of the guitar is now: $', aabalance)
                bodya = input('Select type of wood for the body; Mahogany (12): $220, Maple (13): $250, or Ash(14): $300? ')
                if bodya == '12' or '13' or '14':
                    aaabalance = aabalance + body[bodya]
                    print('The total cost of the guitar is: $', aaabalance)
                    break
                else:
                    print('invalid answer. Try again.')
                    bodya = input('Select type of wood for the body; Mahogany(12): $220, Maple (13): $250, or Ash(14): $300? ')
                    break
            else:
                print('invalid answer. Try again.')
                necka = input('Select type of wood for neck and fretboard; Alder(9): $180, Maple(10): $200, or Rosewood(11): $170? ')
                break
        else:
            print('invalid answer. Try again.')
            input('Select Pickups: Seymour Duncan SH-2(5): $180, Seymour Duncan SNS(6): $260, or Benedetto S-6 (7): $155?')
            break

# user is prompted to choose a genre

genreselect = input('Select genre of music. Metal, Rock, Jazz, Alternative? ')

while True:
    if genreselect == 'Metal':
        winsound.PlaySound("metalpython1.wav", winsound.SND_ASYNC)
        metalguitar()
    elif genreselect == 'Rock':
        rockguitar()
    elif genreselect == 'Jazz':
        jazzguitar()
    elif genreselect == 'Alternative':
        altguitar()
    else:
         print("Option not available. Try Again")
         genreselect = input('Select genre of music. Metal, Rock, Jazz, Alternative? ')
         continue

# depending on which genre the user selects, the appropriate function
# will be called


from crispy_forms.helper import FormHelper
from crispy_forms.layout import Layout, Field
from django.contrib.auth import get_user_model
from django.contrib.auth.forms import UserCreationForm, UsernameField
from django.core.exceptions import ValidationError

from .models import Post, Category, Tag, Comment, UserProfile
from django import forms

User = get_user_model()

class PostModelForm(forms.ModelForm):
    class Meta:
        model = Post
        fields = (
            'title',
            'post_length',
            'body',
            'categories',
            'tags'
        )

    # Override existing HTML widget using ModelChoiceField
    categories = forms.ModelMultipleChoiceField(
        queryset=Category.objects.all(),
        widget=forms.CheckboxSelectMultiple,
        required=False,
        help_text='You can select more than one.'
    )

    # tags = forms.ModelMultipleChoiceField(
    #     queryset=Tag.objects.all(),
    #     widget=forms.CheckboxSelectMultiple,
    #     required=False
    # )

class CustomUserCreationForm(UserCreationForm):
    class Meta:
        model = User
        fields = ("username", "email")
        field_classes = {'username': UsernameField}

    email = forms.CharField(widget=forms.EmailInput(attrs={'required': 'required'}))

    def clean_email(self):
        email = self.cleaned_data["email"]
        if User.objects.filter(email=email).exists():
            raise ValidationError("An user with this email already exists!")
        return email

# Create a ProfileUpdateForm to update image
class ProfileUpdateForm(forms.ModelForm):
    class Meta:
        model = UserProfile
        fields = ['avatar']

# Create a UserUpdateForm to update username and email
class UserUpdateForm(forms.ModelForm):
    email = forms.EmailField()

    class Meta:
        model = User
        fields = ['email']

class CommentModelForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = (
            'text',
        )

    # helper = FormHelper()
    # helper.form_class = 'form-group'
    # helper.layout = Layout(
    #     Field('text', rows="3", css_class='form-control mb-3', style='background: #fff;')
    # )
    text = forms.CharField(
        widget=forms.Textarea(attrs={'class': "form-control", 'rows': 3, 'cols': 50})
    )


from datetime import timedelta, tzinfo
from typing import Optional

from robusta.core.model.base_params import PrometheusParams
from robusta.core.model.pods import k8s_memory_factors
from robusta.integrations.resource_analysis.prometheus_analyzer import PrometheusAnalyzer

class MemoryAnalyzer(PrometheusAnalyzer):
    def __init__(self, prometheus_params: PrometheusParams, prometheus_tzinfo: Optional[tzinfo] = None):
        super().__init__(prometheus_params, prometheus_tzinfo)

    def get_max_node_memory_usage_in_percentage(self, node_name: str, duration: timedelta) -> Optional[float]:
        """
        Gets the maximal memory usage (in percentage) for the node with the given node name, in the time range between now and now - duration.
        :return: a float between 0 and 1, representing the maximal percentage of memory in use by the given node
        """

        max_memory_usage_in_percentage = self._get_max_value_in_first_series_of_query(
            f'instance:node_memory_utilisation:ratio{{job="node-exporter", job="node-exporter", instance="{node_name}"}}',
            duration,
        )
        return max_memory_usage_in_percentage

    def get_container_max_memory_usage_in_bytes(
        self, node_name: str, pod_name: str, container_name: str, duration: timedelta
    ) -> float:
        """
        Returns the maximal memory usage (in bytes) for the given container, in the time range between now and now - duration.r
        """

        # We use the container_memory_usage_bytes metric, with the following filters:
        # - node={node_name}:
        #   In order to filter on the given node.
        #
        # - pod={pod_name}:
        #   In order to filter on the given pod.
        #
        # - image!="":
        #   In order to ignore the metric of the pod in general, which sums the memory of each of its containers.
        #
        # - container!="POD":
        #   In order to ignore paused containers. For more information, please see:
        #   https://stackoverflow.com/questions/68683403/what-is-the-container-pod-label-in-prometheus-and-why-do-most-examples-exclude
        #
        # - container={container_name}:
        #   In order to filter on the given container name.
        #
        # - id=~"/kubepods/.*":
        #   In order to filter multiple ids that are returned for the same container.
        #   In my minikube, for example, 2 time series are returned for each container, one with id=/docker/* and one with id=/kubepods/*.
        #   However, an id of the form /kubepods/* always exists. Also, the following prefixes are always mutual exclusive:
        #       /kubepods/burstable/*
        #       /kubepods/besteffort/*
        #       /kubepods/guaranteed/*
        #   Therefore, there will always be exactly one id of the form /kubepods/* prefix for each container.
        #   See https://stackoverflow.com/questions/49035724/how-do-i-resolve-kubepods-besteffort-poduuid-to-a-pod-name for more information.

        return self._get_max_value_in_first_series_of_query(
            f'container_memory_usage_bytes{{node="{node_name}", pod="{pod_name}", image!="", '
            f'container!="POD", container="{container_name}", id=~"/kubepods/.*"}}',
            duration,
        )

    def _get_max_value_in_first_series_of_query(self, promql_query: str, duration: timedelta) -> Optional[float]:
        results = self._timed_query(promql_query, duration)

        if len(results) == 0:
            return None

        series = results[0]
        series_values = series["values"]
        max_value_in_series = max([float(val) for (timestamp, val) in series_values])
        return max_value_in_series

    def get_total_mem_requests(self, duration: timedelta = timedelta(minutes=10)):
        """
        Gets the total Memory requests for the cluster
        :return: a float of total memory requested
        """
        query = (
            f"sum(avg_over_time(namespace_memory:kube_pod_container_resource_requests"
            f":sum{{}}[{duration.seconds}s]))"
        )
        return self._get_query_value(self._query(query))

    def get_total_mem_allocatable(self, duration: timedelta = timedelta(minutes=10)):
        """
        Gets the total Memory allocatable for the cluster
        :return: a float of total memory allocatable
        """
        query = f'sum(avg_over_time(kube_node_status_allocatable{{resource="memory"}}[{duration.seconds}s]))'
        return self._get_query_value(self._query(query))

class K8sMemoryTransformer:
    @staticmethod
    def get_number_of_bytes_from_kubernetes_mem_spec(mem_spec: str) -> int:
        if len(mem_spec) > 2 and mem_spec[-2:] in k8s_memory_factors:
            return int(mem_spec[:-2]) * k8s_memory_factors[mem_spec[-2:]]

        if len(mem_spec) > 1 and mem_spec[-1] in k8s_memory_factors:
            return int(mem_spec[:-1]) * k8s_memory_factors[mem_spec[-1]]

        raise Exception("number of bytes could not be extracted from memory spec: " + mem_spec)

# bytes pretty-printing
UNITS_MAPPING = [
    (1 << 50, " PB"),
    (1 << 40, " TB"),
    (1 << 30, " GB"),
    (1 << 20, " MB"),
    (1 << 10, " KB"),
    (1, (" byte", " bytes")),
]

def pretty_size(total_bytes):
    """Get human-readable file sizes.
    simplified version of https://pypi.python.org/pypi/hurry.filesize/
    """
    factor, suffix = (None, None)
    for factor, suffix in UNITS_MAPPING:
        if total_bytes >= factor:
            break
    if not (factor or suffix):
        return total_bytes
    amount = round(total_bytes / factor, 2)

    # Handling mapping for tuples (in case we want to add more options to the UNITS_MAPPING)
    if isinstance(suffix, tuple):
        singular, multiple = suffix
        if amount == 1:
            suffix = singular
        else:
            suffix = multiple
    return str(amount) + suffix


import argparse
import torch
import torch.optim as optim
import gym
import time
import random
import os.path

from utils import draw_net, static_var
from designer import DesignerNetwork, info_action_prob
from dppo import DPPO
import design_env

parser = argparse.ArgumentParser(
    description="Unitary Neural Network Design ||| Lukas Palmer",
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("-W", type=int, default=4, help="number of workers (DPPO)")
parser.add_argument("-D", type=int, default=1, help="tolerance for incomplete workers (DPPO)")
parser.add_argument("-M", type=int, default=3, help="number of optimizer steps per round (DPPO)")
parser.add_argument("-T", type=int, default=512, help="environment steps per round (DPPO)")
parser.add_argument("--timesteps", type=int, default=int(1e6), help="total number of timesteps (DPPO)")
parser.add_argument("--lr", type=float, default=3e-4, help="designer network learning rate")
parser.add_argument("--value-coeff", type=float, default=.5, help="coeffecient for value loss term")
parser.add_argument("--S_phi", type=int, default=100, help="size of RNN hidden states for the designer network")
parser.add_argument("--S_rho", type=int, default=100, help="size of primary unit representations for the designer network")
parser.add_argument("--model-path", type=str, default="./designer_params", help="path on which to load and save designer")
parser.add_argument("--load-model", action="store_true", help="load the model at --model-path")
parser.add_argument("--save-model", action="store_true", help="save the model")
parser.add_argument("--save-interval", type=int, default=10000, help="step interval on which to save a checkpoint")

args = parser.parse_args()

N = design_env.N
I = design_env.I
O = design_env.O

model = DesignerNetwork(N, I, O, S_example=design_env.S_example, S_phi=args.S_phi, S_rho=args.S_rho)
optimizer = optim.Adam(model.parameters(), lr=args.lr)
def clone_model(model):
    clone_N, clone_I, clone_O = model.N, model.I, model.O
    clone_S_example, clone_S_phi, clone_S_rho = model.S_example, model.S_phi, model.S_rho
    clone = DesignerNetwork(
        clone_N,
        clone_I,
        clone_O,
        S_example=clone_S_example,
        S_phi=clone_S_phi,
        S_rho=clone_S_rho)
    clone.load_state_dict(model.state_dict())
    return clone

if args.load_model and os.path.exists(args.model_path):
    model.load_state_dict(torch.load(args.model_path))

@static_var("start_time", time.time())
@static_var("next_save", args.save_interval)
def logger(**kwargs):
    rank = kwargs["rank"]
    if rank == 0:
        rewards = kwargs["rewards"]
        env_losses = kwargs["env_losses"]
        env_model = kwargs["env_model"]
        agent_model = kwargs["agent_model"]
        timesteps_done = kwargs["timesteps_done"]

        print(("=" * 20 + " %i steps " + "=" * 20) % timesteps_done)
        print()

        print("Avg. designer reward: %f, avg. primary loss: %f, primary net: %iN, %iW" % (
            sum(rewards) / float(len(rewards)),
            sum(env_losses) / float(len(env_losses)),
            len(env_model._graph.nodes()),
            len(env_model._graph.edges())))
        print()

        print("Sample action probabilities:")
        sample_action_prob = kwargs["sample_action_prob"]
        info_action_prob(sample_action_prob)
        print()

        print("Average speed of %f steps / second" % (timesteps_done / (time.time() - logger.start_time)))
        print()

        draw_net(env_model, "current.png")

        if args.save_model and timesteps_done >= logger.next_save:
            torch.save(agent_model.state_dict(), args.model_path)
            with open(args.model_path + ".steps", "w+") as file:
                file.write("%i\n" % timesteps_done)
            logger.next_save += args.save_interval

rl = DPPO(
    env_name="unitary-design-v0",
    model=model,
    clone_model=clone_model,
    optimizer=optimizer,
    T=args.T,
    W=args.W,
    D=args.D,
    M=args.M,
    logger=logger,
    value_coeff=args.value_coeff)
rl.run(args.timesteps)

if args.save_model:
    torch.save(model.state_dict(), args.model_path)


import sys
from collections import deque
input = sys.stdin.readline

dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]

def bfs(x, y, z):
    q = deque()
    q.append(([x, y, z]))
    visited = [[[0] * 2 for _ in range(m)] for _ in range(n)]
    visited[0][0][1] = 1

    while q:
        a, b, c = q.popleft()

        if a == n-1 and b == m-1:
            return visited[a][b][c]

        for i in range(4):
            nx = dx[i] + a
            ny = dy[i] + b

            if 0 <= nx < n and 0 <= ny < m:
                if graph[nx][ny] == 1 and c == 1:
                    visited[nx][ny][0] = visited[a][b][1] + 1
                    q.append([nx, ny, 0])

                elif graph[nx][ny] == 0 and visited[nx][ny][c] == 0:
                    visited[nx][ny][c] = visited[a][b][c] + 1
                    q.append([nx, ny, c])

    return -1

n, m = map(int, input().split())
graph = []

for i in range(n):
    graph.append(list(map(int, list(input().strip()))))

print(bfs(0, 0, 1))


#!/usr/bin/env python3
"""
rps version 2
python 3.7
"""

import numli

def rps():
    choices = ['Rock', 'Paper', 'Scissors']
    value = {'1': 10, '2': 1, '3': 5}
    numli.addnum(choices)

    player1 = input('Player 1 enter name. ')
    player2 = input('Player 2 enter name. ')

    turn_1 = input(f'{player1.capitalize()} enter choice. ')
    turn_2 = input(f'{player2.capitalize()} enter choice. ')

    play_1 = value[turn_1]
    play_2 = value[turn_2]

    if play_1 > play_2:
    	print(f"{player1.capitalize()} wins!")

    elif turn_1 == turn_2:
    	print("Tie!")

    else:
    	print(f"{player2.capitalize()} wins!")

if __name__ == "__main__":
    rps()


from django.db import models

# Create your models here.
class BaseGateway(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    success_url = models.URLField()
    cancel_url = models.URLField()
    is_active = models.BooleanField(default=True, unique=True)

    PAYMENT_SUCCESS_URL =  lambda self, host : f"{host}/credits/purcashe?message=success"
    PAYMENT_CANCEL_URL =  lambda self, host : f"{host}/credits/purcashe?message=cancel"

    class Meta:
        abstract = True


import pygame,patgametools.sprite,random,sys,time
import patgametools.sprite as sprite

from pygame.locals import *
class Joueur(sprite.Sprite):

    global ecran,largeurEcran,hauteurEcran

    def __init__(self,x,y,image):
        sprite.Sprite.__init__(self,x,y,image)
        self.dx=5
        self.direction=0 # 0=immobile 1=droite -1=gauche

    def mise_a_jour(self):
        if self.direction==1: #déplacement vers la droite
            #vérifier limites ecran
            if self.x+self.direction*self.dx+self.largeur>largeurEcran:
                self.set_x=largeurEcran-self.largeur
            else:
                self.deplacer(self.direction*self.dx,0)

        elif self.direction==-1:#déplacement gauche
            #vérifier limites ecran
            if self.x-self.direction*self.dx<0:
                self.set_x=0
            else:
                self.deplacer(self.direction*self.dx,0)

class Paroi(sprite.Sprite):

    #variables de classe
    largeurparoi=0
    image=""

    def __init__(self,x,y,image):
        sprite.Sprite.__init__(self,x,y,image)
        self.active=1#si 0 à effacer de la liste des parois
        Paroi.image=image

class Canyon():
    #variables de classe
    parois=[]
    derniereparoigauchex=0
    derniereparoidroitex=0

    global largeurEcran,hauteurEcran

    def __init__(self,imageparoi):
        self.largeurMinimale=100
        self.largeurMaximale=400
        self.coordminx=100
        self.coordmaxx=largeurEcran-100
        self.imageparoi=imageparoi
        self.clock=pygame.time.Clock()
        self.temps_cumule=0
        self.delai_creation=200#toutes les xxx ms

        self.creerpremieresparois()

    def creerpremieresparois(self):
        #créer premières paroi
        paroigauchex=int(largeurEcran/2-self.largeurMaximale/2)
        paroidroitex=int(largeurEcran/2+self.largeurMaximale/2)
        y=0
        #créer paroi gauche
        Canyon.parois.append(Paroi(paroigauchex,y,self.imageparoi))
        Canyon.derniereparoigauchex=paroigauchex
        #créer paroi droite
        Canyon.parois.append(Paroi(paroidroitex,y,self.imageparoi))
        Canyon.derniereparoidroitex=paroidroitex
        #retenir la largeur d'une paroi sur base de la première paroi créée
        Paroi.largeurparoi=Canyon.parois[0].largeur

    def nouvelles_coordonnees(self):

        valid=False
        y=0
        paroigauchex=0
        paroidroitex=0

        while not valid:

            direction=random.randint(-1,1)  #direction paroi 0=inchangé, -1=gauche, 1=droite
            paroigauchex=Canyon.derniereparoigauchex+int(direction*Paroi.largeurparoi)
            #vérifier coordonnées dans limites
            if paroigauchex<self.coordminx:
                paroigauchex=self.coordminx

            direction=random.randint(-1,1)  #direction paroi 0=inchangé, -1=gauche, 1=droite
            paroidroitex=Canyon.derniereparoidroitex+int(direction*Paroi.largeurparoi)
            #vérifier coordonnées dans limites
            if paroidroitex>self.coordmaxx:
                paroidroitex=self.coordmaxx

            #print("x1:{} x2:{}".format(self.paroi_gauche_x,self.paroi_droite_x))
            #vérifier largeur canyon
            if paroidroitex-paroigauchex>=self.largeurMinimale \
               and paroidroitex-paroigauchex<=self.largeurMaximale:
                valid=True

        #retenir dernieres coordonnees des parois
        Canyon.derniereparoigauchex=paroigauchex
        Canyon.derniereparoidroitex=paroidroitex
        #retourner la liste des deux nouvelles coordonnées de parois
        return (paroigauchex,paroidroitex)

    def deplacerparois(self):
        for paroi in Canyon.parois:
            y=paroi.y+paroi.hauteur
            paroi.set_y(y)

            #si sortie écran => marquer paroi inactive (à effacer à la prochaine mise à jour)
            if y>hauteurEcran:
                paroi.active=0

    def creerparois(self):
        y=0

        paroigauchex,paroidroitex=self.nouvelles_coordonnees()

        self.parois.append(Paroi(paroigauchex,y,Paroi.image))
        self.parois.append(Paroi(paroidroitex,y,Paroi.image))

    def effacerparoisinactives(self):
        #print("parois avant effacement : {}".format(len(Canyon.parois)))
        nouvelleliste=[]
        index=0
        for paroi in Canyon.parois:
            if (paroi.active):
                nouvelleliste.append(paroi)
            index+=1

        Canyon.parois.clear()
        Canyon.parois.extend(nouvelleliste)

        del(nouvelleliste)

        #print("parois après effacement : {}\n".format(len(Canyon.parois)))

    def mise_a_jour(self):

        self.temps_cumule+=self.clock.tick()

        if self.temps_cumule>self.delai_creation:
            self.temps_cumule=0
            self.deplacerparois()
            self.effacerparoisinactives()
            self.creerparois()

    def dessiner(self):
        for paroi in Canyon.parois:
            paroi.dessiner(ecran)

class MoteurJeu():
    global joueur, ecran

    def __init__(self):
        self.clock=pygame.time.Clock()
        self.joueur=Joueur(largeurEcran/2,hauteurEcran/2,"squidred.png")
        self.canyon=Canyon("wall.png")

    def boucle_principale(self):
        while True:
            ecran.fill((0,0,0))#effacer écran
            #mise à jour joueur
            self.joueur.mise_a_jour()
            #mise à jour canyon
            self.canyon.mise_a_jour()
            #vérifier collision
            if self.joueur.collisionavecsprites(Canyon.parois):
                print("collision")

            #dessiner canyon
            self.canyon.dessiner()
            #dessiner joueur
            self.joueur.dessiner(ecran)

            #update screen
            pygame.display.update()

            #control fps
            self.tempsPasse=self.clock.tick(60)

            #test touches
            for event in pygame.event.get():

                if event.type==pygame.KEYDOWN:
                    if event.key==pygame.K_LEFT:
                        pass
                        self.joueur.direction=-1
                        #print('déplacement gauche')
                    if event.key==pygame.K_RIGHT:
                        pass
                        self.joueur.direction=1
                        #print('déplacement droite')
                    if event.key==pygame.K_ESCAPE:
                        self.quitter_jeu()

                if event.type==pygame.KEYUP:
                    if event.key==pygame.K_LEFT:
                        pass
                        self.joueur.direction=0
                        #print('pas de déplacement')
                    if event.key==pygame.K_RIGHT:
                        pass
                        self.joueur.direction=0
                        #print('pas de déplacement')

                if event.type==pygame.QUIT:
                    self.quitter_jeu()

    def quitter_jeu(self):
        pygame.quit()
        sys.exit()

#démarrage du module
if __name__=="__main__":

    largeurEcran=800
    hauteurEcran=600

    pygame.init()

    ecran=pygame.display.set_mode((largeurEcran,hauteurEcran))

    pygame.display.set_caption("Sea canyon !")

    monMoteurJeu=MoteurJeu()
    monMoteurJeu.boucle_principale()


__author__ = "jacobvanthoog"

import wpilib

ROTATION_TICKS = 131072 # encoder ticks in a full rotation
COMPLETED_DISTANCE = 0.06
# when both motors are within this fraction of their full ticks
# the movement has completed

class Arm:

    def __init__(self, can):
        self.CAN = can
        self.CAN.reverseSensor(True)
        self.CAN.changeControlMode(wpilib.CANTalon.ControlMode.Position)
        self.CAN.setPID(1.0, 0.0002, 3.0, 0.0)

        # target position of the encoders
        self.CAN.setFeedbackDevice(wpilib.CANTalon.FeedbackDevice.QuadEncoder)
        #getPosition is updated more often than getEncPosition
        #but it is negative, because of reverseSensor()
        #TODO: try to remove negatives
        self.Target = -self.CAN.getPosition()
        self.zero()

        self.Velocity = 4000 # ticks per step

    # should be called once per loop!
    def update(self):
        self.rotateToPosition1(self.CAN, self.Target)

    def setTarget(self, position):
        self.Target = position + self.Zero
        print("Target set: ", position)

    def getTarget(self):
        return self.Target - self.Zero

    def moveTarget(self, amount):
        self.setTarget(self.getTarget() + amount)

    def getPosition(self):
        return -self.CAN.getPosition() - self.Zero

    def movePosition(self, amount):
        self.setTarget(self.getPosition() + amount)

    def zero(self):
        self.Zero = -self.CAN.getPosition()

    def movementCompleted(self, can, target):
        return abs(-self.CAN.getPosition() - target)\
            <= (COMPLETED_DISTANCE * ROTATION_TICKS)

    # DON'T USE THESE

    def rotateToPosition1(self, can, target):
        current = -can.getPosition()
        #if current == target:
            #print("At position")
            #can.set(current)
            #return(0)

        distance = (target - current) # amount motor should rotate

        value = 0
        if abs(distance) < self.Velocity:
            value = target
        else:
            if distance > 0:
                value = current + self.Velocity
            else:
                value = current - self.Velocity

        #print(current, target, distance, value)

        #TODO: try to remove this negative
        can.set(-value)
        return(distance)

    def rotateToPosition2(self, can, target):
        current = -can.getPosition()
        target = target
        if current == target:
            #print("At position")
            can.set(0)
            return(0)

        distance = target - current # amount motor should rotate

        if abs(distance) < (self.Velocity):
            pass
        else:
            if distance > 0:
                distance = self.Velocity
            else:
                distance = -self.Velocity

        #print(distance)

        can.set(-distance/2)
        return(distance)


def divisors(integer):
    div_nums = []
    for i in range(2, integer):
        if integer % i == 0:
            div_nums.append(i)
    if len(div_nums) == 0:
        return '%d is a prime' % (integer)
    else:
        return div_nums

print(divisors(12))
# [2, 3, 4, 6]))


import numpy as np
import matplotlib.pyplot as plt

x, y = np.loadtxt(open("hey.csv"), delimiter=',', usecols=(0, 2), unpack=True,skiprows=1)

plt.scatter(x,y)

k4 = []
k8 = []

for (i,k) in enumerate(x):
    if k == 4:
        k4.append(y[i])
    elif k == 8:
        k8.append(y[i])

print("k4:",np.mean(k4), np.std(k4), np.std(k4)/np.sqrt(len(k4)))
print("k8:",np.mean(k8), np.std(k8), np.std(k8)/np.sqrt(len(k8)))

plt.show()


from flask import abort, jsonify, request
from models.MotherBoard import MotherBoard
from server.routes.__init__ import api
from models.User import User

@api.route('/motherboards', methods=['GET'])
def get_motherboards():
    selection_motherboards = MotherBoard.query.order_by('id').all()

    if len(selection_motherboards) == 0:
        abort(404)

    dictionary_motherboards = {motherboard.id: motherboard.format() for motherboard in selection_motherboards}
    return jsonify({
        'success': True,
        'motherboards': dictionary_motherboards,
        'total_motherboards': len(selection_motherboards)
    })

@api.route('/motherboards/<id>', methods=['GET'])
def get_motherboard(id):
    motherboard = MotherBoard.query.filter(MotherBoard.id==id).one_or_none()

    if motherboard is None:
        abort(404)

    dictionary_motherboard = motherboard.format()
    selection_motherboards = MotherBoard.query.order_by('id').all()
    return jsonify({
        'success': True,
        'motherboard': dictionary_motherboard,
        'total_motherboards': len(selection_motherboards)
    })

@api.route('/motherboards/<id>', methods=['DELETE'])
def delete_motherboard(id):
    error_404 = False
    try:
        motherboard_to_delete = MotherBoard.query.filter(MotherBoard.id==id).one_or_none()

        if motherboard_to_delete is None:
            error_404 = True
            abort(404)

        motherboard_to_delete.delete()

        selection_motherboards = MotherBoard.query.order_by('id').all()
        dictionary_motherboards = {motherboard.id: motherboard.format() for motherboard in selection_motherboards}
        return jsonify({
            'success': True,
            'deleted_id': id,
            'motherboards': dictionary_motherboards,
            'total_motherboards': len(selection_motherboards)
        })
    except Exception as e:
        print(e)
        if error_404:
            abort(404)
        else:
            abort(500)

@api.route('/motherboards/<id>', methods=['PATCH'])
def patch_motherboard(id):
    error_404 = False
    error_422 = False
    error_401 = False
    error_403 = False
    try:
        motherboard_to_patch = MotherBoard.query.filter(MotherBoard.id==id).one_or_none()

        if motherboard_to_patch is None:
            error_404 = True
            abort(404)

        body = request.get_json()
        if 'token' not in body:
            error_422 = True
            abort(422)
        user = User.check_token(body.get('token'))
        if user is None:
            error_401 = True
            abort(401)
        if user.role != 'admin':
            error_403 = True
            abort(403)

        motherboard_to_patch.modify_by = user.id
        if 'description' in body:
            motherboard_to_patch.description = body.get('description')
        if 'price' in body:
            motherboard_to_patch.price = body.get('price')
        if 'name' in body:
            motherboard_to_patch.name = body.get('name')

        updated_id = motherboard_to_patch.update()
        if updated_id is None:
            error_422 = True
            abort(422)

        selection_motherboards = MotherBoard.query.order_by('id').all()
        dictionary_motherboards = {motherboard.id: motherboard.format() for motherboard in selection_motherboards}
        return jsonify({
            'success': True,
            'updated_id': id,
            'motherboards': dictionary_motherboards,
            'total_motherboards': len(selection_motherboards)
        })
    except Exception as e:
        print(e)
        if error_404:
            abort(404)
        elif error_422:
            abort(422)
        elif error_401:
            abort(401)
        elif error_403:
            abort(403)
        else:
            abort(500)

@api.route('/motherboards', methods=['POST'])
def post_motherboard():
    error_422 = False
    error_401 = False
    error_403 = False
    try:
        body = request.get_json()

        price = body.get('price', None)
        name = body.get('name', None)
        description = body.get('description', None)
        token = body.get('token', None)

        if price is None or name is None or description is None or token is None:
            error_422 = True
            abort(422)
        user = User.check_token(token)
        if user is None:
            error_401 = True
            abort(401)
        if user.role != 'admin':
            error_403 = True
            abort(403)
        create_by = user.id

        new_motherboard = MotherBoard(price=price, name=name, description=description, create_by=create_by)
        new_motherboard_id = new_motherboard.insert()
        if new_motherboard_id is None:
            error_422 = True
            abort(422)

        selection_motherboards = MotherBoard.query.order_by('id').all()
        dictionary_motherboards = {motherboard.id: motherboard.format() for motherboard in selection_motherboards}
        return jsonify({
            'success': True,
            'created_id': new_motherboard_id,
            'motherboards': dictionary_motherboards,
            'total_motherboards': len(selection_motherboards)
        })
    except:
        if error_422:
            abort(422)
        elif error_401:
            abort(401)
        elif error_403:
            abort(403)
        else:
            abort(500)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys
import os
import logging
import time
import imp
from flask import Flask

import altcoinvw.util
from manager import webindex
from manager import webnode

__all__ = []

BasePath = os.path.abspath(os.path.join(sys.argv[0], '../'))
Logger = logging.getLogger('')
WebApp = Flask(__name__)

class WebServerEnv:
    def __init__(self):
        self.ModuleReloadTime = {}
        self.Nodes = {}
        self.Logger = Logger

def Start():
    env = WebServerEnv()

    loggerHandler = logging.StreamHandler()
    loggerHandler.setLevel(logging.DEBUG)
    loggerHandler.setFormatter(logging.Formatter('%(pathname)s:%(lineno)d %(asctime)s '
        '%(levelname)-8s: %(message)s'))
    Logger.addHandler(loggerHandler)

    WebAppAddUrlRule('/Index', lambda : webindex.CtrIndex(env))
    WebAppAddUrlRule('/RegisterNode', lambda : webnode.CtrRegisterNode(env))
    WebAppAddUrlRule('/ListNodes', lambda : webnode.CtrListNodes(env))
    WebAppAddUrlRule('/Refresh', lambda: CtrRefresh(env))
    WebApp.run(debug=False, host='0.0.0.0', port=80)

def WebAppAddUrlRule(name, func):
    WebApp.add_url_rule(name, name, view_func=func, methods=['GET', 'POST'])

def WebCheckModuleIfNeedReloadAndPrepareReload(modulename):
    return altcoinvw.util.WebCheckModuleIfNeedReloadAndPrepareReload(BasePath,
            'manager',
            ModuleReloadTime,
            modulename)

def CtrRefresh(env):
    try:
        if WebCheckModuleIfNeedReloadAndPrepareReload('webindex') == True:
            imp.reload(webindex)
        if WebCheckModuleIfNeedReloadAndPrepareReload('webnode') == True:
            imp.reload(webnode)

    except Exception as e:
        Logger.fatal('{}'.format(e))
    return 'success'


from sage.all import *
from nose.plugins.skip import SkipTest

from uniformization.prime_function import build_prime_function

#############################################################################
# The following tests use the nosetest generator syntax. See                #
#                                                                           #
# https://nose.readthedocs.org/en/latest/writing_tests.html#test-generators #
#                                                                           #
# for more information. The "checks" used by these tests are defined below. #
#############################################################################
z = var('z')
gamma = var('gamma')

def test_prime_function():
    # run the "checks" below using the following list of (delta,q) pairs
    half = QQ(1)/2
    delta_q_pairs = [
        # ([0], [half]),
        ([half], [half/4]),
        ([-half, half], [half/2, half/2]),
    ]
    product_threshold = 10

    for delta, q in delta_q_pairs:
        genus = len(delta)
        omega = build_prime_function(delta, q, product_threshold)
        phi_j = [
            delta[j] + q[j]**2*z/(1-z*delta[j].conjugate())
            for j in range(genus)
        ]
        yield check_vanishing_gamma, omega
        yield check_vanishing_phij_gamma, omega, phi_j
        yield check_pole_fixed_points, omega, delta, q, phi_j, genus
        # yield check_equation_5_17, omega
        yield check_symmetric, omega

##########
# checks #
##########
def check_vanishing_gamma(omega):
    # Tests that omega(gamma1,gamma2) vanishes.
    value = omega(z=gamma)
    assert simplify(value) == 0

def check_vanishing_phij_gamma(omega, phi_j):
    # Tests that omega(phi_j(gamma1), phi_j(gamma2)) vanishes.
    value = sum(omega(z=phi_jk(z=gamma)) for phi_jk in phi_j)
    assert simplify(value) == 0

def check_pole_fixed_points(omega, delta, q, phi_j, genus):
    # Tests that omega has poles at the fixed points of phi_j.
    term_1 = lambda k: 1 + abs(delta[k])**2 - q[k]**2
    term_2 = lambda k: sqrt(-4*abs(delta[k])**2 + (1+abs(delta[k])**2-q[k]**2)**2)
    denom = lambda k: 2*delta[k].conjugate()
    pole_pt1 = lambda k: (term_1(k) + term_2(k)) / denom(k)
    pole_pt2 = lambda k: (term_1(k) - term_2(k)) / denom(k)

    # assert that these are, in fact, fixed poitns of phi_j
    pole_sum1 = sum(N(phi_j[k](z=pole_pt1(k)) - pole_pt1(k)) for k in range(genus))
    pole_sum2 = sum(N(phi_j[k](z=pole_pt2(k)) - pole_pt2(k)) for k in range(genus))
    value = pole_sum1 + pole_sum2
    assert abs(simplify(value)) < 1e-15

    # perturb slightly to avoid returning an error (result should be large?).
    # as we get closer to the pole the values should be increasing (towards
    # infinity)
    sum1 = sum(N(omega(z=pole_pt1(k) + 1e-10, gamma=1) +
                 omega(z=pole_pt2(k) + 1e-10, gamma=1))
               for k in range(genus))
    sum2 = sum(N(omega(z=pole_pt1(k) + 1e-13, gamma=1) +
                 omega(z=pole_pt2(k) + 1e-13, gamma=1))
               for k in range(genus))
    sum3 = sum(N(omega(z=pole_pt1(k) + 1e-15, gamma=1) +
                 omega(z=pole_pt2(k) + 1e-15, gamma=1))
               for k in range(genus))
    assert abs(sum3) > abs(sum2) > abs(sum1)

    # repeat at gamma = -1
    sum1 = sum(N(omega(z=pole_pt1(k) + 1e-10, gamma=1) +
                 omega(z=pole_pt2(k) + 1e-10, gamma=-1))
               for k in range(genus))
    sum2 = sum(N(omega(z=pole_pt1(k) + 1e-13, gamma=1) +
                 omega(z=pole_pt2(k) + 1e-13, gamma=-1))
               for k in range(genus))
    sum3 = sum(N(omega(z=pole_pt1(k) + 1e-15, gamma=1) +
                 omega(z=pole_pt2(k) + 1e-15, gamma=-1))
               for k in range(genus))
    assert abs(sum3) > abs(sum2) > abs(sum1)

def check_equation_5_17(omega):
    # we also check to see if (5.17) holds, it doesn't unless we take the
    # infinite product, but should approach it as the product_threshold
    # increases! Again choose a number for gamma.
    fiveone7a = omega(z=1/z.conjugate(), gamma=1/gamma.conjugate())
    fiveone7 = fiveone7a.conjugate() + omega/(z*gamma)
    value = abs(N(fiveone7(z=(3+I*3),gamma=1)))
    assert simplify(value) < 1e-8

    value = abs(N(fiveone7(z=0.7+0.1*I,gamma=1)) )
    assert simplify(value) < 1e-8

def check_symmetric(omega):
    # the SK-prime function should also be symmetric in its arguments. I.e. one
    # should have omega(zeta,gamma) = -omega(gamma,zeta). Test this
    # algebraically
    p = var('p')
    q = var('q')
    value = omega(z=p,gamma=q) + omega(z=q,gamma=p)
    assert simplify(value) == 0


from datetime import datetime

from django.db import models
from django.urls import reverse

from core.materiales.models import Materiales

class CommonInfoClientes(models.Model):
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    cedula = models.CharField(max_length=10, primary_key=True, error_messages={
        'unique': 'El cliente con este número de cédula ya existe',
    })
    telefono_celular = models.CharField(max_length=10)
    address = models.CharField(max_length=100)

    def __str__(self):
        return f"{self.first_name} {self.last_name}"

    class Meta:
        abstract = True
        verbose_name = 'clientes'
        verbose_name_plural = 'clientes'

class ContratoClientes(CommonInfoClientes):
    fecha_contrato = models.DateTimeField(default=datetime.now())
    valor_contrato = models.DecimalField(default=0, max_digits=5, decimal_places=2)
    instalado = models.BooleanField(default=False)

    class Meta:
        db_table = 'contrato-clientes'

    def get_absolute_url(self):
        return reverse('clientes:informacion-cliente-contrato', kwargs={"id": self.cedula})

class Clientes(CommonInfoClientes):
    fecha_de_instalacion = models.DateTimeField(default=datetime.now())
    email = models.EmailField(max_length=100)
    activo = models.BooleanField()

    class Meta(CommonInfoClientes.Meta):
        db_table = 'clientes'
        verbose_name = 'cliente'
        verbose_name_plural = 'clientes'

    def get_absolute_url(self):
        return reverse('clientes:informacion-cliente', kwargs={"id": self.cedula})

class OrdenesTrabajoClientes(models.Model):
    INSTALACION_NUEVA = 'IN'
    CAMBIO_DOMICILIO = 'CD'
    ARREGLO = 'AR'
    ADICIONALES = 'AD'
    REINSTALACIONES = 'RI'
    SUSPENCIONES_VOLUNTARIAS = 'SV'
    CORTES_DE_SERVICIO = 'CS'

    DESCRIPCION_ACTIVIDADES_CHOICES = [
        (INSTALACION_NUEVA, 'Instalacion nueva'),
        (CAMBIO_DOMICILIO, 'Cambio de domicilio'),
        (ARREGLO, 'ARREGLO'),
        (ADICIONALES, 'Adicionales'),
        (REINSTALACIONES, 'Reinstalaciones'),
        (SUSPENCIONES_VOLUNTARIAS, 'Suspencion voluntaria'),
        (CORTES_DE_SERVICIO, 'Cortes de Servicio')

    ]

    numero_orden = models.CharField(max_length=333)
    cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE)
    materiales = models.ForeignKey(Materiales, on_delete=models.CASCADE)
    pago_materiales = models.BooleanField(default=False)
    cantidad = models.PositiveIntegerField(default=0)
    descripcion_actividad = models.CharField(max_length=2, choices=DESCRIPCION_ACTIVIDADES_CHOICES)
    fecha_trabajo = models.DateTimeField(auto_now_add=True)

    class Meta:
        verbose_name = 'orden de trabajo'
        verbose_name_plural = 'ordenes de trabajo'
        db_table = 'ordenes de trabajo clientes'

class PagosMensualidadesClientes(models.Model):
    cliente = models.ForeignKey(Clientes, on_delete=models.CASCADE)
    fecha_pago = models.DateTimeField(default=datetime.now)
    valor = models.DecimalField(max_digits=6, decimal_places=2)

    class Meta:
        verbose_name = 'pago'
        verbose_name_plural = 'pagos'
        db_table = 'pagos_mensualidades_clientes'


import omni.ext
from pxr import Usd, UsdGeom
import omni.ui as ui
import omni.kit.commands

WARNINGS = "Something Wrong with Your Hierarchy!"
MAX_LENGTH = 1000

class XsuperzoneTeachExploded_viewExtension(omni.ext.IExt):
    def __init__(self):
        self._stage = omni.usd.get_context().get_stage()
        self.x_mesh = None
        self.y_mesh = None
        self.z_mesh = None

    def on_startup(self, ext_id):
        print("[xsuperzone.teach.exploded_view] exploded_view startup")

        self._window = ui.Window(
            "Exploded-View",
            width=400,
            height=200,
        )

        axis = ["X", "Y", "Z"]

        with self._window.frame:
            with ui.HStack():
                with ui.VStack(width=100):
                    ui.Button(
                        "Select Prims",
                        tooltip="Please select the Primitives you want to Explode",
                        clicked_fn=self.select_prim
                    )
                    ui.Button(
                        "Reset",
                        tooltip="Clear all the data you Set",
                        clicked_fn=self.reset
                    )

                with ui.VStack(width=50):
                    for i in axis:
                        ui.Label(
                            i,
                            tooltip=f"Please decide the max distance of {i}-axis your primitive will reach"
                        )

                with ui.VStack(width=50):
                    self.drag_x = ui.IntField()
                    self.drag_y = ui.IntField()
                    self.drag_z = ui.IntField()

                with ui.VStack():
                    self.slider_x = ui.IntSlider(min=0, max=MAX_LENGTH)
                    self.slider_y = ui.IntSlider(min=0, max=MAX_LENGTH)
                    self.slider_z = ui.IntSlider(min=0, max=MAX_LENGTH)

                    self.slider_x.model = self.drag_x.model
                    self.slider_y.model = self.drag_y.model
                    self.slider_z.model = self.drag_z.model

                    self.slider_x.model.add_value_changed_fn(
                        lambda m: self.prim_translate('x', m)
                    )
                    self.slider_y.model.add_value_changed_fn(
                        lambda m: self.prim_translate('y', m)
                    )
                    self.slider_z.model.add_value_changed_fn(
                        lambda m: self.prim_translate('z', m)
                    )

    def on_shutdown(self):
        print("[xsuperzone.teach.exploded_view] exploded_view shutdown")

    def reset(self):
        self.drag_x.model.set_value(0)
        self.drag_y.model.set_value(0)
        self.drag_z.model.set_value(0)

        if self.x_mesh:
            for mesh in self.x_mesh:
                xform = mesh.GetParent()
                UsdGeom.XformCommonAPI(xform).SetTranslate((0,0,0))
            self.x_mesh.clear()
            self.y_mesh.clear()
            self.z_mesh.clear()

    def select_prim(self):
        """
        将所要爆炸的 mesh 保存到 self.xyz_mesh:list 中
        """

        self.reset()

        # 获取用户选择的path，这个path是需要便利的根节点，没有任何选择则退出
        geo_selected_path: list = omni.usd.get_context().get_selection().get_selected_prim_paths()

        if not geo_selected_path:
            print("Please select something!!!")
            return None

        # 根据选择的 path 找到 根节点的 prim
        self._selected_root: Usd.Prim = self._stage.GetPrimAtPath(geo_selected_path[0])

        # 接受所有遍历到的mesh
        self.meshes_select = []

        # 添加所有子mesh到列表
        self.get_sturctured(self._selected_root)
        print(self.meshes_select)

        print("-" * 20, "Hierarchy Structured Sucessfully", "-" * 20)

        if not self.meshes_select:
            print(WARNINGS, ", Caused by Nothing is mesh")
            return None

        self.x_mesh, self.y_mesh, self.z_mesh = self.sort_mesh_by_axis(self.meshes_select)

        print("-" * 20, "Select Sucessfully", "-" * 20)

        return None

    def get_sturctured(self, root):
        '''
        构建一个层次结构，永远是：xform-mesh的结构
        '''
        for child in root.GetChildren():
            if UsdGeom.Mesh(child):
                if UsdGeom.Xform(child.GetParent()):
                    if child.GetParent() != self._selected_root:
                        self.meshes_select.append(child)
                    else:
                        xform_name = child.GetName() + '_xform'
                        xform_path = child.GetParent().GetPath().pathString + f'/{xform_name}'
                        UsdGeom.Xform.Define(self._stage, xform_path)

                        omni.kit.commands.execute(
                            'MovePrim',
                            path_from=child.GetPath(),
                            path_to=xform_path + f'/{child.GetName()}',
                            keep_world_transform=False,
                            destructive=False)

                        self.meshes_select.append(child)

            else:
                self.get_sturctured(child)

    def sort_mesh_by_axis(self, meshes: list) -> dict:
        """
        获取 mesh 的位置（通过取第一个顶点实现）
        计算好每个 mesh 距离中心的百分比
        最终根据xyz轴分别排序好{Prim:percent}
        """
        x_mesh = {}
        y_mesh = {}
        z_mesh = {}

        for mesh in meshes:
            # meshes_info[mesh] = mesh.GetAttribute('points').Get()
            points:list = mesh.GetAttribute('points').Get()
            if points:
                x_mesh[mesh] = points[0][0]
                y_mesh[mesh] = points[0][1]
                z_mesh[mesh] = points[0][2]
            else:
                meshes.remove(mesh)

        x_mesh = self.get_dis_percent(x_mesh)
        y_mesh = self.get_dis_percent(y_mesh)
        z_mesh = self.get_dis_percent(z_mesh)

        return x_mesh, y_mesh, z_mesh

    def get_dis_percent(self, mesh_list):
        distance = list(mesh_list.values())
        distance = sorted(distance)
        length = max(distance) - min(distance)
        mid_dis = distance[len(distance) // 2]

        for i in mesh_list:
            dis_percent = (mesh_list[i] - mid_dis) / length
            mesh_list[i] = dis_percent

        return mesh_list

    def prim_translate(self, dim:str, model):
        """
        输入：dict{prim:(维度的距离百分比)}
        输出：None，把每个prim进行独特的位移
        """

        if dim == 'x':
            for mesh in self.x_mesh:
                xform = mesh.GetParent()
                new_trans = self.x_mesh[mesh] * model.get_value_as_float()
                origin_pos = xform.GetAttribute('xformOp:translate').Get()
                if not origin_pos:
                    origin_pos = [0,0,0]

                UsdGeom.XformCommonAPI(xform).SetTranslate((
                    new_trans,
                    origin_pos[1],
                    origin_pos[2]
                    ))
        elif dim == 'y':
            for mesh in self.y_mesh:
                xform = mesh.GetParent()
                new_trans = self.y_mesh[mesh] * model.get_value_as_float()
                origin_pos = xform.GetAttribute('xformOp:translate').Get()
                if not origin_pos:
                    origin_pos = [0,0,0]

                UsdGeom.XformCommonAPI(xform).SetTranslate((
                    origin_pos[0],
                    new_trans,
                    origin_pos[2]
                    ))
        if dim == 'z':
            for mesh in self.z_mesh:
                xform = mesh.GetParent()
                new_trans = self.z_mesh[mesh] * model.get_value_as_float()
                origin_pos = xform.GetAttribute('xformOp:translate').Get()
                if not origin_pos:
                    origin_pos = [0,0,0]

                UsdGeom.XformCommonAPI(xform).SetTranslate((
                    origin_pos[0],
                    origin_pos[1],
                    new_trans
                    ))

        print("-" * 20, "Transform Sucessfully", "-" * 20)


import torch
import numpy as np
import datetime

def get_random_problems(batch_size, problem_size):

    depot_xy = torch.rand(size=(batch_size, 1, 2))
    # shape: (batch, 1, 2)

    # node_xy = torch.rand(size=(batch_size, problem_size, 2))
    # # shape: (batch, problem, 2)
    # 시간
    node_x = torch.randint(1, 24, size=(batch_size, problem_size, 1)) #/ float(41024)
    # 분
    node_y = torch.randint(1, 60, size=(batch_size, problem_size, 1)) #/ float(60)
    # 시간, 분
    node_xy = torch.cat((node_x, node_y), dim = 2)
    # unix time
    node_unixtime = torch.zeros(batch_size, problem_size, 3, dtype = torch.long)
    # 0    1    2    3    4    5
    # time time time time time time

    # 초기 값 날짜는 임의로 설정
    # 현재는 시간과 분만 랜덤으로 발생
    date = '2021-01-01 00:00:00'

    # convert string to datetimeformat
    date = datetime.datetime.strptime(date, "%Y-%m-%d %H:%M:%S")

    if problem_size == 20:
        demand_scaler = 30
    elif problem_size == 50:
        demand_scaler = 40
    elif problem_size == 100:
        demand_scaler = 50
    else:
        raise NotImplementedError

    # 노드별 작업 시간 (단위: 분)
    node_demand = torch.randint(40, 60, size=(batch_size, problem_size)) / float(demand_scaler)

    for i, x in enumerate(node_xy[0]):
        date = date.replace(hour = node_xy[0][i][0], minute = node_xy[0][i][1])

        node_unixtime[0][i][0] = i
        # 작업 시작 시간
        node_unixtime[0][i][1] = date.timestamp()
        # 작업 종료 시간
        node_unixtime[0][i][2] = node_unixtime[0][i][1] + (node_demand[i] * 60)
        print(i, node_xy[0][i][0], node_xy[0][i][1], date.strftime("%Y-%m-%d %H:%M:%S"), node_unixtime[0][i][1], node_unixtime[0][i][2])

    # shape: (batch, problem)

    node_xy_unixtime = torch.cat((node_xy, node_unixtime), dim = 2)
    print(node_xy_unixtime)
    return depot_xy, node_xy, node_demand, node_unixtime

def augment_xy_data_by_8_fold(xy_data):
    # xy_data.shape: (batch, N, 2)

    x = xy_data[:, :, [0]]
    y = xy_data[:, :, [1]]
    # x,y shape: (batch, N, 1)

    dat1 = torch.cat((x, y), dim=2)
    dat2 = torch.cat((1 - x, y), dim=2)
    dat3 = torch.cat((x, 1 - y), dim=2)
    dat4 = torch.cat((1 - x, 1 - y), dim=2)
    dat5 = torch.cat((y, x), dim=2)
    dat6 = torch.cat((1 - y, x), dim=2)
    dat7 = torch.cat((y, 1 - x), dim=2)
    dat8 = torch.cat((1 - y, 1 - x), dim=2)

    aug_xy_data = torch.cat((dat1, dat2, dat3, dat4, dat5, dat6, dat7, dat8), dim=0)
    # shape: (8*batch, N, 2)

    return aug_xy_data


import pandas as pd
import numpy as np
import os, sys
from Insurance.entity import config_entity
from Insurance.entity import artifact_entity
from Insurance.exception import InsuranceException
from Insurance.logger import logging
from sklearn.model_selection import train_test_split

class DataIngestion:
    def __init__(self,data_ingestion_config:config_entity.DataIngestionConfig):
        try:
            self.data_ingestion_config = data_ingestion_config
        except Exception as e:
            raise InsuranceException(e,sys)

    def initiate_data_ingestion(self)->artifact_entity.DataIngestionArtifact:

        try:

            logging.info("Read the data from csv file")
            df = pd.read_csv(r"insurance.csv")

            logging.info(f"dataset columns:[{df.columns}]")
            logging.info(f'Rows and Columns: [{df.shape}]')

            df.replace(to_replace ='na', value = np.NAN, inplace = True)

            logging.info("Create feature store folder if not availabel")

            feature_store_dir = os.path.dirname(self.data_ingestion_config.feature_store_file_path)
            os.makedirs(feature_store_dir, exist_ok = True)

            logging.info("save df to feature store folder")
            df.to_csv(path_or_buf=self.data_ingestion_config.feature_store_file_path, index= False, header=True)

            logging.info('Splitting our data into the train and test set')
            train_df, test_df = train_test_split(df, test_size = self.data_ingestion_config.test_size,
                                                random_state= self.data_ingestion_config.random_state)

            logging.info("Create dataset directory folder if not available")
            dataset_dir = os.path.dirname(self.data_ingestion_config.train_data_file_path)
            os.makedirs(dataset_dir, exist_ok = True)

            logging.info("Save train and test dataset into the dataset folder")
            train_df.to_csv(self.data_ingestion_config.train_data_file_path, index= False, header = True)
            test_df.to_csv(self.data_ingestion_config.test_data_file_path, index= False, header = True)

            #prepare artifact folder

            data_ingestion_artifact = artifact_entity.DataIngestionArtifact(
                feature_store_file_path = self.data_ingestion_config.feature_store_file_path,
                train_data_file_path = self.data_ingestion_config.train_data_file_path,
                test_data_file_path = self.data_ingestion_config.test_data_file_path
            )

            return data_ingestion_artifact

        except Exception as e:
            raise InsuranceException(e,sys)


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Base App:
from setting import FLOW_MANAGER, REST_APP
from ryu.base import app_manager

# WSGI / REST API
import json
from ryu.app.wsgi import WSGIApplication, ControllerBase, Response, route
from ryu.lib import dpid as dpid_lib

# Base Application:
from ryu.controller.controller import Datapath

# WSGI / REST API
import json
from ryu.app.wsgi import WSGIApplication, ControllerBase, Response, route

# External Core
# from simple_swtich_13 import SimpleSwitch13
from delay_monitor import DelayMonitor
from flow_statistic import FlowStatistic
from port_statistic import PortStatistic
from topology_data import TopologyData

# logging

class NetworkStat(app_manager.RyuApp):
    # Version - Context
    _CONTEXTS = {
            'wsgi': WSGIApplication,
            'topology_data': TopologyData,
            'port_statistic': PortStatistic,
            'flow_statistic': FlowStatistic,
            'delay_monitor': DelayMonitor,
        }

    def __init__(self, *_args, **_kwargs):
        super(NetworkStat, self).__init__(*_args, **_kwargs)
        self.name = 'controller_rest'

        # Register the WSGI application
        wsgi: WSGIApplication = _kwargs['wsgi']
        wsgi.register(NetworkStatRest, {REST_APP: self})

        # External Apps - Load order: alway start the TopologyData first since the other apps depend on it:
        self.topology_data: TopologyData = _kwargs['topology_data']
        self.port_statistic: PortStatistic = _kwargs['port_statistic']
        self.flow_statistic: FlowStatistic = _kwargs['flow_statistic']
        self.delay_monitor: DelayMonitor = _kwargs['delay_monitor']

class NetworkStatRest(ControllerBase):

    def __init__(self, req, link, data, **config):
        super(NetworkStatRest, self).__init__(req, link, data, **config)
        self.app: NetworkStat = data[REST_APP]

    @route(REST_APP, '/', methods=['GET'])
    def hello(self, req, **_kwargs):
        body = json.dumps([{'hello': 'world'}])
        return (Response(content_type='application/json', body=body, status=200))

    # @route(REST_APP, '/hello/{test}', methods=['GET'])
    # def hello_test(self, req, **_kwargs):
    #     test = _kwargs['test']
    #     body = json.dumps([{'hello': test}])
    #     print(type(test))
    #     return (Response(content_type='application/json', body=body))

    # @route(REST_APP, '/json_test', methods=['PUT'])
    # def json_test(self, req, **_kwargs):
    #     try:
    #         content = req.json if req.body else {}
    #     except ValueError:
    #         raise Response(status=400)
    #     # return (Response(content_type='application/json', body=json.dumps(content), status=200))
    #     print(type(content))
    #     return (Response(content_type='application', body=json.dumps(content), status=200))

    # network info
    @route(REST_APP, '/topology_data', methods=['GET'])
    def topology_data(self, req, **_kwargs):
        hosts, switches, links = self.app.topology_data.get_topology_data()
        topo = {
            'host': hosts,
            'switch': switches,
            'link': links
        }
        body = json.dumps(topo)
        return Response(content_type='application/json', body=body, status=200)

    @route(REST_APP, '/hosts', methods=['GET'])
    def get_hosts(self, req):
        hosts = self.app.topology_data.get_host()
        body = json.dumps({'hosts': hosts})
        return Response(content_type='application/json', body=body, status=200)

    @route(REST_APP, '/links', methods=['GET'])
    def get_links(self, req):
        links = self.app.topology_data.get_link()
        body = json.dumps({'link': links})
        return Response(content_type='application/json', body=body, status=200)

    @route(REST_APP, '/switches', methods=['GET'])
    def get_switches(self, req):
        switches = self.app.topology_data.get_switch()
        body = json.dumps({'switch': switches})
        return Response(content_type='application/json', body=body, status=200)

    @route(REST_APP, '/link_to_port', methods=['GET'])
    def get_link_to_port(self, req):
        '''
        Get link_to_port data with json format:
        {src_dpid: {dst_dpid: [src_port, dst_port]}, ...}
        '''
        data = self.app.topology_data.link_to_port
        reformated_result = {}
        for key in data.keys():
            if key[0] not in reformated_result.keys():
                reformated_result[key[0]] = {key[1]: list(data[key])}
            reformated_result[key[0]][key[1]] = list(data[key])
        body = json.dumps(reformated_result)
        return Response(content_type='application/json', body=body, status=200)

    # network monitor
    @route(REST_APP, '/port_stat', methods=['GET'])
    def get_port_stat(self, req, **kwargs):
        body = json.dumps(self.app.port_statistic.get_port_stats())
        return Response(content_type='application/json', body=body)

    @route(REST_APP, '/delta_port_stat', methods=['GET'])
    def get_delta_port_stat(self, req, **kwargs):
        body = json.dumps(self.app.port_statistic.get_delta_port_stats())
        return Response(content_type='application/json', body=body)

    @route(REST_APP, '/flow_stat', methods=['GET'])
    def get_flow_stat(self, req, **kwargs):
        body = json.dumps(self.app.flow_statistic.get_flow_stats())
        return Response(content_type='application/json', body=body)

    @route(REST_APP, '/delta_flow_stat', methods=['GET'])
    def get_delta_flow_stat(self, req, **kwargs):
        body = json.dumps(self.app.flow_statistic.get_delta_flow_stats())
        return Response(content_type='application/json', body=body)

    # @route(REST_APP, '/port_desc', methods=['GET'])
    # def get_port_desc(self, req, **kwargs):
    #     body = self.app.port_statistic.port_desc.to_json(orient='records')
    #     return Response(content_type='application/json', body=body, status=200)

    @route(REST_APP, '/link_quality', methods=['GET'])
    def get_link_quality(self, req, **kwargs):
        """_summary_
        Get link quality data: packet loss, bandwidth, delay
        Returns:
            _type_: json string response
        """
        link_quality = self.app.topology_data.get_link_quality()
        body = json.dumps(link_quality)
        return Response(content_type='application/json', body=body, status=200)

    @route(REST_APP, '/topology_graph', methods=['GET'])
    def get_topology_graph(self, req, **kwargs):
        """_summary_
        Get topology graph data
        Returns:
            _type_: json string response
        """
        graph = self.app.topology_data.get_topology_graph()
        body = json.dumps(graph)
        return Response(content_type='application/json', body=body, status=200)

# ryu-manager --observe-link --ofp-tcp-listen-port=6633 --wsapi-port=8080 controller_rest.py


####################################################################################################
# ROOT:
#   dataset: a name of dataset (framework set)
#   path: picture relative path (framework set)
#   width: picture width
#   height: picture width
#   seg_tag: a segmentation tag (framework set)
#   box_tag: a box tag (framework set)
#   objects: a array full with document
#
# Object:
#   name: a unique tag name of this object
#   box: a bounding box [x, y, w, h]
#   segmentation_id: a id described a value in each pixel of segmentation picture
#   pose: person pose name

####################################################################################################

import os
import numpy as np
from PIL import Image
from PIL.ImagePalette import ImagePalette
from tensorlab.utils.yaml_object import YamlObject
from tensorlab.image import DEFAULT_PALETTE_COLOR_256

# set output palette
_DEFAULT_PALETTE = ImagePalette('RGB', np.array(DEFAULT_PALETTE_COLOR_256, dtype=np.uint8).tobytes())
#_DEFAULT_PALETTE.dirty = 1
_DEFAULT_PALETTE.rawmode = 'RGB'

class Document(YamlObject):
    def __init__(self):
        super(YamlObject, self).__init__()
        self.__dict__['__cache__'] = {}

    @property
    def _cache(self): return self.__dict__['__cache__']

    @property
    def segmentation_id(self): return self.__get_attr__('segmentation_id')

    @property
    def segmentation(self): return self.segmentation_getter()

    def segmentation_getter(self):
        return self._cache.get('__segmentation__')

    def segmentation_setter(self, seg_image):
        seg_image = seg_image.astype(np.uint8)
        self._cache['__segmentation__'] = seg_image
        self.__set_attr__('segmentation_id', int(seg_image.max()))

    @staticmethod
    def load(path):
        # load doc
        doc = YamlObject.load(path, __class__)

        # load segmentation
        seg_path = os.path.splitext(path)[0] + '.png'
        if os.path.isfile(seg_path):
            image = Image.open(seg_path)
            seg_image = np.array(image)
            seg_docs = []
            def _do(o):
                if not o.has('segmentation_id'): return
                seg = seg_image.copy()
                indexes = (seg != o.segmentation_id) & (seg != 0)
                seg[indexes] = 0
                o._cache['__segmentation__'] = seg

            doc._search_docs(_do)

        return doc

    def save(self, path):
        # save yml
        super(Document, self).save(path)

        # collect datas
        segs = self.search_all('__segmentation__', in_cache=True)

        # save segmentation
        if len(segs) > 0:
            seg_path = os.path.splitext(path)[0] + '.png'
            im_array = np.stack(segs, axis=2).sum(axis=2)
            image = Image.fromarray(im_array.astype(np.uint8), mode='P')
            image.putpalette(_DEFAULT_PALETTE)
            image.save(seg_path)

    def search(self, key, in_cache=False):
        result = None
        def _do(o):
            nonlocal result
            exist = False
            if in_cache:
                exist = key in o._cache.keys()
                if exist: result = o._cache.get(key)
            else:
                exist = o.has(key)
                if exist: result = o.get(key)
            return exist

        self._search_docs(_do)
        return result

    def search_all(self, key, in_cache=False):
        results = []

        def _do(o):
            if in_cache:
                exist = key in o._cache.keys()
                if exist: results.append(o._cache.get(key))
            else:
                exist = o.has(key)
                if exist: results.append(o.get(key))

        self._search_docs(_do)
        return results

    def _search_docs(self, callback):
        def _finds(o):
            if isinstance(o, Document):
                stop = callback(o)
                if stop: return

            if isinstance(o, dict):
                for k, v in o.items():
                    _finds(v)

            elif isinstance(o, list):
                for v in o:
                    _finds(v)

        _finds(self)

    property(segmentation_getter, segmentation_setter)