import plotly.plotly as py
import plotly.graph_objs as go

import igraph

nr_vertices = 25
v_label = map(str, range(nr_vertices))
# 2 stands for children number
G = Graph.Tree(nr_vertices, 2)
lay = G.layout('rt')

position = {k: lay[k] for k in range(nr_vertices)}
Y = [lay[k][1] for k in range(nr_vertices)]
M = max(Y)

# sequence of edges
es = EdgeSeq(G)
# list of edges
E = [e.tuple for e in G.es]

L = len(position)
Xn = [position[k][0] for k in range(L)]
Yn = [2 * M - position[k][1] for k in range(L)]
Xe = []
Ye = []
for edge in E:
    Xe+=[position[edge[0]][0],position[edge[1]][0], None]
    Ye+=[2 * M - position[edge[0]][1], 2 * M - position[edge[1]][1], None]

labels = v_label


def smallest(array1,array2):
    array1.sort()
    array2.sort()
    idxone = 0
    idxTwo = 0
    default = float("inf")
    diff = float("inf")
    smallestPair = []

    while idxone<len(array1) and idxTwo<len(array2):
        firstnum = array1[idxone]
        secondnum = array2[idxTwo]
        if firstnum < secondnum:
            diff = secondnum - firstnum
            idxone += 1
        elif secondnum < firstnum:
            diff = firstnum - secondnum
            idxTwo += 1
        else:
            return [firstnum,secondnum]

        if default > diff:
            default = diff
            smallestPair = [firstnum,secondnum]
    return smallestPair

x = smallest([-1,5,10,20,28,3],[26,134,135,15,17])
print(x)


import torch
torch.set_num_threads(2)
from torch import nn
import numpy as np
import plotly.graph_objects as go
import plotly.express as px
import matplotlib.pyplot as plt
import matplotlib.colors as mcolors
from digit_classifier_NN import (
    MLP,
    MLP_model_fp,
    MLP_model_fp_2,
    train_images,
    test_images,
    train_labels,
    test_labels,
    get_s_from_state_dict,
    get_keys,
    train_NN_process
)

unit = 0.02

node_color = 'lightblue'
node_marker_size = 12

min_edge_weight = 0.6

def get_random_img_and_label(images=test_images, labels=test_labels):
    idx = np.random.randint(0,len(images)-1)
    return images[idx], labels[idx]

def remove_axes(fig):
    fig.update_layout(
        coloraxis_showscale=False,
        xaxis=dict(showgrid=False, zeroline=False, showticklabels=False, showline=False),
        yaxis=dict(showgrid=False, zeroline=False, showticklabels=False, showline=False)
        )
    return fig

def display_img(img):
    if img is None:
        return remove_axes(go.Figure())
    fig =  px.imshow(img, color_continuous_scale='gray')
    remove_axes(fig)
    return fig

def get_digit_img_display(images=test_images):
    img, _label = get_random_img_and_label(images)
    return display_img(img)

def get_square_input_layer(s0, x0):
    if s0 != 784:
        raise Exception(f"Detected invalid s[0] value: {s0}")
    h = 28
    w = 28

    sep = 1*unit
    y0 = 28*sep/2

    locs = np.zeros((h,w,2))
    for i in range(h):
        for j in range(w):
            locs[j,i,0] = x0 - (h-i)*sep
            locs[j,i,1] = y0 - j*sep
    return locs.reshape(784,2)

def get_node_positions(s, input_nodes):
    L = len(s)
    h_sep = [10*unit, 20*unit, 25*unit, 25*unit, 25*unit, 25*unit]
    v_sep = [-1*unit]*L
    node_locs = []
    for layer in range(L):

        if input_nodes and layer==0:
            node_locs.append(get_square_input_layer(s[0], -h_sep[0]))
            continue

        top = (s[layer]-1)*v_sep[layer]
        bottom = -top

        x = layer*h_sep[layer]*np.ones(s[layer])
        y = np.linspace(bottom, top, s[layer])
        node_locs.append(np.stack((x,y)).T)

    return node_locs

def draw_node(fig, pos, radius=1*unit, line_color = 'black', fill_color = 'lightblue'):

    x,y = pos
    # Add a circle
    fig.add_shape(
        go.layout.Shape(
            type="circle",
            xref="x",
            yref="y",
            x0=x-radius,
            y0=y-radius,
            x1=x+radius,
            y1=y+radius,
            line=dict(color=line_color),
            fillcolor = fill_color
        )
    )

    # Update axes properties
    fig.update_xaxes(range=[-1, 3])
    fig.update_yaxes(range=[-1, 3])

def normalise_to_1(A, minimum = None):
    package = torch if type(A) == torch.Tensor else np
    if minimum is None: minimum = package.min(A)
    return (A - minimum) / (package.max(A) - minimum)

def get_random_node_colors(s):
    color = []
    for k in s:
        color.append(np.random.rand(k))
    return color

def node_colors_from_vals(node_values):
    color = []

    for nv in node_values:
        layer_colors = normalise_to_1(nv[0])
        layer_colors = node_cmap(normalise_to_1(nv[0]))
        layer_colors_formatted = [0]*len(layer_colors)
        for j in range(len(layer_colors)):
            layer_colors_formatted[j] = to_dumb_format(layer_colors[j])
        color.append(layer_colors_formatted)
    return color

def draw_nodes(fig, s, node_locs, color=node_color, node_vals=None):
    if node_vals is not None:
        color=node_colors_from_vals(node_vals)
    else:
        color = [[color]*sl for sl in s]

    for k,node_loc_layer in enumerate(node_locs):
        fig.add_trace(go.Scatter(
            x=node_loc_layer[:,0],
            y=node_loc_layer[:,1],
            mode='markers',
            marker=dict(color=color[k], size=node_marker_size,
            line=dict(
            width=1,
            color='black'
        ))
        ))
        # for pos in node_loc_layer:
        #     draw_node(fig,pos)]

def to_dumb_format(rgba):
    rgb = (rgba[:-1]*255).astype(int)
    return f'rgb({rgb[0]},{rgb[1]},{rgb[2]},0.1)'

def node_cmap(z):
    rgba = np.array(plt.get_cmap("YlGn")(z))
    return rgba

def edge_cmap(z):
    if type(z) == torch.Tensor: z = z.item()
    rgba = np.array(plt.get_cmap("YlGn")(z))
    return to_dumb_format(rgba)

def get_edge_weights(state_dict, node_vals, L, input_nodes, img):
    edge_weight = []

    keys = get_keys(L, input_nodes)
    for l, key in enumerate(keys):
        weights = state_dict[key]
        weights = normalise_to_1(weights)
        weights = normalise_to_1(weights, min_edge_weight)

        if node_vals is None:
            edge_weight.append(np.array(weights).T)
            continue
        n,m = weights.shape
        layer_colors = [n*[0] for _ in range(m)]
        for i in range(m):
            for j in range(n):
                layer_colors[i][j] = weights[j][i].item()*node_vals[l][0][i]
        edge_weight.append(layer_colors)
    return edge_weight

def draw_edges(fig, state_dict, node_locs, node_vals, L, input_nodes, img):

    edge_weight = get_edge_weights(state_dict, node_vals, L, input_nodes, img)
    keys = get_keys(L, input_nodes)
    for l, key in enumerate(keys):
        weights = state_dict[key]
        n,m = weights.shape
        for i in range(m):
            for j in range(n):
                weight_lij = edge_weight[l][i][j]
                if weight_lij < 0.01:
                    continue
                fig.add_trace(go.Scatter(
                    x=[node_locs[l][i][0], node_locs[l+1][j][0]],
                    y=[node_locs[l][i][1], node_locs[l+1][j][1]],
                    mode='lines',
                    line = dict(color = edge_cmap(weight_lij), width=0.7)
                    ))

def get_untrained_state_dict(s, input_nodes):
    L = len(s)
    keys = get_keys(L, input_nodes)
    state_dict = {}
    l = 0 if input_nodes else 1
    for key in keys:
        state_dict[key] = torch.ones((s[l+1], s[l]))*0.5
        l += 1
    return state_dict

def plot_NN(model, input_img=None, s=[784, 16, 10], input_nodes=True):

    fig = go.Figure()

    if model is not None:
        state_dict = model.state_dict()
        s = get_s_from_state_dict(state_dict)
    else:
        state_dict = get_untrained_state_dict(s, input_nodes)

    L = len(s)
    if not input_nodes: s = s[1:]
    node_locs = get_node_positions(s, input_nodes = input_nodes)
    node_vals = model.get_node_vals(input_img, input_nodes) if model is not None else None
    if model is not None:
        draw_edges(fig, state_dict, node_locs, node_vals, L, input_nodes, input_img)
    draw_nodes(fig, s, node_locs, node_vals=node_vals)

    fig.update_layout(showlegend=False)
    fig.update_yaxes(scaleanchor="x", scaleratio=1)
    remove_axes(fig)
    return fig

def plot_opt_progress():
    fig = go.Figure()

    return fig

def test_plot_opt_progress():
    model = MLP(s=[784, 16, 10])
    process, queue = train_NN_process(model, n_epochs=1, batch_size=64, lr=0.001)

    data0 = {
        'epoch': 0,
        'batch': 0,
        'loss': 0,
        'accuracy': 0,
        'epoch_completed': 0,
        'n_intervals': 0,
        'train_model_n_clicks': 0,
    },

    while process.is_alive():
        if not queue.empty():
            status = queue.get()
            print(status)
    process.join()

if __name__ == '__main__':
    # model = MLP.load(MLP_model_fp_2)
    model = MLP(s=[784, 16, 16, 16, 10])
    train_NN_process(model, n_epochs=5, batch_size=100, lr=0.001)
    plot_NN(model=model, input_img=get_random_img_and_label()[0], input_nodes=True).show()
    # display_img(None).show()
    # fig = go.Figure()
    # draw_node(fig, (1,1), 1)
    # fig.update_yaxes(scaleanchor="x", scaleratio=1)
    # fig.show()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Oct 24 12:38:48 2022

@author: aswinpaul
"""

import gym
env = gym.make('Taxi-v3')
env.action_space.seed(42)
# Environment grid_env.grid_environment()

import numpy as np
np.random.seed(10)

# agent
import agent_dpefe_strict_c as helper
from agent_dpefe_strict_c import agent as dpefe_agent

# %%

# Generative model
s1_size = 500
s1_actions = ['move south', 'move north', 'move east', 'move west', 'pickup passenger', 'drop off passenger']

o1_size = s1_size

# Hidden states
num_states = [s1_size]
num_factors = len(num_states)

# Controls
num_controls = [len(s1_actions)]

#Observations
num_obs = [o1_size]
num_modalities = len(num_obs)

A = helper.random_A_matrix(num_obs, num_states)*0
A[0] = np.eye(s1_size)
# %%

T = 2
a = dpefe_agent(num_states=num_states, num_obs=num_obs, num_controls=num_controls,
                a = A, planning_horizon = T)

# %%

# Trial
m_trials = 1
n_trials = 100
time_horizon = 15000

t_length = np.zeros((m_trials, n_trials))

for mt in range(m_trials):
    print(mt)

    for trial in range(n_trials):

        print(mt, "trial: ", trial)

        obs, info = env.reset(seed=42)
        obs_list = [obs]

        score = 0
        for t in range(time_horizon):

            action  = a.step(obs_list, t)
            obs, reward, terminated, truncated, info = env.step(action)
            obs_list = [obs]

            #Learning C only for the goal-state
            if(reward == 20):
                a.update_c(obs_list)

            score += reward

            #Checking for succesful episode
            if terminated or truncated:
                break

        t_length[mt,trial] = score
        a.end_of_trial()


#
# @lc app=leetcode.cn id=556 lang=python3
#
# [556] 下一个更大元素 III
#

# @lc code=start
# 和下一个更大元素-i 下一个更大元素-ii 有一点不一样
# 这里要找的是当前元素之后比该元素大的最小元素，而不是第一个比当前元素大的元素
# 所以这里的思路要变一下
class Solution:
    def nextGreaterElement(self, n: int) -> int:
        stack = []
        l = [int(x) for x in str(n)]
        len_l = len(l)
        idx = 0
        for i in range(len_l-1, -1, -1):
            while stack and l[i] < l[stack[-1]]: # 走开，比我高的高个子都走开
                if idx != 0:# 记录下每次被pop的高个子索引，这样就可以记录下来比当前元素大的最小元素
                    if l[stack[-1]] == l[idx]:
                        stack.pop()
                    else:
                        idx = stack.pop()
                else:
                    idx = stack.pop()
            # 只要idx不等于0，说明进行了pop，也就是当前元素后面有比该元素大的元素
            # 此时进行交换即可，结束循环
            if idx != 0:
                l[idx], l[i] = l[i], l[idx]
                break
            stack.append(i)
        if idx == 0:
            return -1
        # 将之后的元素按照从小到大排列
        l[i+1:] = sorted(l[i+1:])
        res = int(''.join([str(item) for item in l]))
        return -1 if res > 2147483647 else res

# @lc code=end

sol = Solution()
print(sol.nextGreaterElement(12443322))


class SemiBoostClassifier():

    def __init__(self, base_model =SVC()):

        self.BaseModel = base_model
        self.weights = None

    def fit(self, X, y,
            n_neighbors=4, n_jobs = 1,
            max_models = 15,
            sample_percent = 0.5,
            sigma_percentile = 90,
            similarity_kernel = 'rbf',
            verbose = False):

        #Localize labeled data
        label_index = np.argwhere((y == 0) | (y == 1)).flatten()
        unlabel_index = np.array([i for i in np.arange(len(y)) if i not in label_index])

        # For Fully Supervised Learning
        if unlabel_index.size == 0:
            index = np.where(y!=-1)
            X,y = X[index],y[index]
            self.BaseModel.fit(X,y)
            return

        # First we need to create the similarity matrix
        if similarity_kernel == 'knn':

            graph = neighbors.kneighbors_graph(X,
                                                n_neighbors=n_neighbors,
                                                mode='distance',
                                                include_self=True,
                                                n_jobs=n_jobs)

            graph = sparse.csr_matrix(graph)

        elif similarity_kernel == 'rbf':
            # First aprox
            graph = np.sqrt(rbf_kernel(X, gamma = 1))
            # set gamma parameter as the 15th percentile
            sigma = np.percentile(np.log(graph), sigma_percentile)
            sigma_2 = (1/sigma**2)*np.ones((graph.shape[0],graph.shape[0]))
            graph = np.power(graph, sigma_2)
            # Matrix to sparse
            graph = sparse.csr_matrix(graph)

        else:
            print('No kernel type ', similarity_kernel)

        # Initialise variables
        self.models = []
        self.weights = []
        H = np.zeros(unlabel_index.shape[0])

        # Loop for adding sequential models
        for t in range(max_models):
            # Calculate p_i and q_i for every sample
            p_1 = np.einsum('ij,j', graph[:,label_index].todense(), (y[label_index]==1))[unlabel_index]*np.exp(-2*H)
            p_2 = np.einsum('ij,j', graph[:,unlabel_index].todense(), np.exp(H))[unlabel_index]*np.exp(-H)
            p = np.add(p_1, p_2)
            p = np.squeeze(np.asarray(p))

            q_1 = np.einsum('ij,j', graph[:,label_index].todense(), (y[label_index]==-1))[unlabel_index]*np.exp(2*H)
            q_2 = np.einsum('ij,j', graph[:,unlabel_index].todense(), np.exp(-H))[unlabel_index]*np.exp(H)
            q = np.add(q_1, q_2)
            q = np.squeeze(np.asarray(q))

            # Compute predicted label z_i
            z = np.sign(p-q)
            z_conf = np.abs(p-q)
            # Sample sample_percent most confident predictions
            # Sampling weights
            sample_weights = z_conf/np.sum(z_conf)
            # If there are non-zero weights
            if np.any(sample_weights != 0):
                pick = np.random.choice(np.arange(z.size),
                                              size = int(sample_percent*unlabel_index.size),
                                              p = sample_weights,
                                              replace = False)
                sample_index = unlabel_index[pick]

            else:
                print('No similar unlabeled observations left.')
                break

            # Create new X_t, y_t
            total_sample = np.concatenate([label_index,sample_index])
            X_t = X[total_sample,]
            np.put(y, sample_index, z[pick])# Include predicted to train new model
            y_t = y[total_sample]

            # Fit BaseModel to samples using predicted labels
            # Fit model to unlabeled observations
            clf = self.BaseModel
            clf.fit(X_t, y_t)
            # Make predictions for unlabeled observations
            h = clf.predict(X[unlabel_index])

            # Refresh indexes
            label_index = total_sample
            unlabel_index = np.array([i for i in np.arange(len(y)) if i not in label_index])

            if verbose:
                print('There are still ', unlabel_index.shape[0], ' unlabeled observations')

            # Compute weight (a) for the BaseModel as in (12)
            e = (np.dot(p,h==-1) + np.dot(q,h==1))/(np.sum(np.add(p,q)))
            a = 0.25*np.log((1-e)/e)
            # Update final model
            # If a<0 the model is not converging
            if a<0:
                if verbose:
                    print('Problematic convergence of the model. a<0')
                break

            # Save model
            self.models.append(clf)
            #save weights
            self.weights.append(a)
            # Update
            H = np.zeros(len(unlabel_index))
            w = np.sum(self.weights)
            for i in range(len(self.models)):
                H = np.add(H, self.weights[i]*self.models[i].predict(X[unlabel_index]))

            # Breaking conditions

            # Maximum number of models reached
            if (t==max_models) & verbose:
                print('Maximum number of models reached')

            # If no samples are left without label, break
            if unlabel_index.size <= 1:
                if verbose:
                    print('All observations have been labeled')
                    print('Number of iterations: ',t + 1)
                break

        if verbose:
            print('\n The model weights are \n')
            print(self.weights)

    def predict(self, X):
        if self.weights is None:
            return self.BaseModel.predict(X)

        estimate = np.zeros(X.shape[0])
        # Predict weighting each model
        w = np.sum(self.weights)
        for i in range(len(self.models)):
            estimate = np.add(estimate, self.weights[i]*self.models[i].predict(X))
        estimate = np.array(list(map(lambda x: 1 if x>0 else 0, estimate)))
        estimate = estimate.astype(int)
        return estimate


def webapi_request(url, method='GET', caller=None, session=None, params=None):
    """Low level function for calling Steam's WebAPI

    .. versionchanged:: 0.8.3

    :param url: request url (e.g. ``https://api.steampowered.com/A/B/v001/``)
    :type url: :class:`str`
    :param method: HTTP method (GET or POST)
    :type method: :class:`str`
    :param caller: caller reference, caller.last_response is set to the last response
    :param params: dict of WebAPI and endpoint specific params
    :type params: :class:`dict`
    :param session: an instance requests session, or one is created per call
    :type session: :class:`requests.Session`
    :return: response based on paramers
    :rtype: :class:`dict`, :class:`lxml.etree.Element`, :class:`str`
    """
    if method not in ('GET', 'POST'):
        raise NotImplemented("HTTP method: %s" % repr(self.method))
    if params is None:
        params = {}

    onetime = {}
    for param in DEFAULT_PARAMS:
        params[param] = onetime[param] = params.get(param, DEFAULT_PARAMS[param])
    for param in ('raw', 'apihost', 'https', 'http_timeout'):
        del params[param]

    if onetime['format'] not in ('json', 'vdf', 'xml'):
        raise ValueError("Expected format to be json,vdf or xml; got %s" % onetime['format'])

    for k, v in list(params.items()): # serialize some types
        if isinstance(v, bool): params[k] = 1 if v else 0
        elif isinstance(v, dict): params[k] = _json.dumps(v)
        elif isinstance(v, list):
            del params[k]
            for i, lvalue in enumerate(v):
                params["%s[%d]" % (k, i)] = lvalue

    kwargs = {'params': params} if method == "GET" else {'data': params} # params to data for POST

    if session is None: session = _make_session()

    f = getattr(session, method.lower())
    resp = f(url, stream=False, timeout=onetime['http_timeout'], **kwargs)

    # we keep a reference of the last response instance on the caller
    if caller is not None: caller.last_response = resp
    # 4XX and 5XX will cause this to raise
    resp.raise_for_status()

    if onetime['raw']:
        return resp.text
    elif onetime['format'] == 'json':
        return resp.json()
    elif onetime['format'] == 'xml':
        from lxml import etree as _etree
        return _etree.fromstring(resp.content)
    elif onetime['format'] == 'vdf':
        import vdf as _vdf
        return _vdf.loads(resp.text)


import pymysql
from config import Config

class Db:
    def __init__(self):
        config = Config()
        self.con = pymysql.connect(config.db["host"], config.db["user"], config.db["pwd"], config.db["db_name"],
                                   cursorclass=pymysql.cursors.DictCursor)

    def close(self):
        self.con.close()

    def write(self, sql):
        # print(sql)
        # exit(1)
        cursor = self.con.cursor()
        lastId = 0
        try:
            cursor.execute(sql)
            lastId = int(cursor.lastrowid)
            self.con.commit()
        except:
            print(sql)

        return lastId

    def query(self, sql):
        cursor = self.con.cursor()
        cursor.execute(sql)
        data = cursor.fetchall()
        return data

    def find(self, sql):
        cursor = self.con.cursor()
        try:
            cursor.execute(sql)
        except:
            print(sql)
        else:
            data = cursor.fetchone()
            return data

    def rowCount(self, sql):
        cursor = self.con.cursor()
        cursor.execute(sql)
        count = cursor.rowcount
        return count


import requests
from bs4 import BeautifulSoup
import shutil
res = requests.get("https://www.gamebase.com.tw/forum/38033/topic/97494527/1#1460716494")
soup = BeautifulSoup(res.text)
#print(soup.select(".img"))
for img in soup.select(".img"):
    # print(img['src'])
    fname = 'C:\\Users\\a7894\\Desktop\\demo\\img\\' + img['src'].split('/')[-1]
    # print(fname)
    res2 = requests.get(img['src'], stream = True)
    f = open(fname, "wb")
    shutil.copyfileobj(res2.raw, f)
    f.close()


import sys
from facerec_from_webcam import Video, FaceSet

operations = (
    'init',
    'show'
)

if __name__ == '__main__':
    args = sys.argv
    action = args[1]
    outer_id = args[2]
    # outer_id = 'downtown1'
    if action == 'init':

        # 获取每个照片的face_token
        face_dict = FaceSet.load_faceset(path='./faceset')

        # 创建faceset
        FaceSet.create_faceset(outer_id=outer_id)

        # face_token存入faceset中
        FaceSet.add_face(outer_id=outer_id, face_tokens=[k for k, v in face_dict.items()])

    elif action == 'show':
        ip = 'rtsp://192.168.124.2:554/1/h264major'
        video = Video(ip_address=0)
        # video.connect()
        video.show2(outer_id=outer_id)
    print('哟哟stop it now')


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

#   ProgressPlayer.py por:
#   Flavio Danesse <fdanesse@gmail.com>
#   Uruguay
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA

import os
import gobject
import gtk

from Globales import COLORES

BASE_PATH = os.path.dirname(__file__)

class ProgressPlayer(gtk.EventBox):

    __gsignals__ = {
    "seek": (gobject.SIGNAL_RUN_LAST,
        gobject.TYPE_NONE, (gobject.TYPE_FLOAT, )),
    "volumen": (gobject.SIGNAL_RUN_LAST,
        gobject.TYPE_NONE, (gobject.TYPE_FLOAT,))}

    def __init__(self):

        gtk.EventBox.__init__(self)

        self.modify_bg(gtk.STATE_NORMAL, COLORES["window"])

        self.barraprogreso = BarraProgreso()
        self.volumen = ControlVolumen()

        hbox = gtk.HBox()
        hbox.pack_start(self.barraprogreso, True, True, 0)
        hbox.pack_start(self.volumen, False, False, 0)

        self.add(hbox)

        self.barraprogreso.connect("user-set-value", self.__user_set_value)
        self.volumen.connect("volumen", self.__set_volumen)

        self.show_all()

    def __user_set_value(self, widget=None, valor=None):
        self.emit("seek", valor)

    def __set_volumen(self, widget, valor):
        self.emit('volumen', valor)

    def set_progress(self, valor):
        self.barraprogreso.set_progress(valor)

class BarraProgreso(gtk.EventBox):
    """
    Barra de progreso para mostrar estado de reproduccion.
    """

    __gsignals__ = {
    "user-set-value": (gobject.SIGNAL_RUN_LAST,
        gobject.TYPE_NONE, (gobject.TYPE_FLOAT, ))}

    def __init__(self):

        gtk.EventBox.__init__(self)

        self.modify_bg(gtk.STATE_NORMAL, COLORES["window"])

        self.escala = ProgressBar(
            gtk.Adjustment(0.0, 0.0, 101.0, 0.1, 1.0, 1.0))

        self.valor = 0

        self.add(self.escala)
        self.show_all()

        self.escala.connect('user-set-value', self.__emit_valor)
        self.set_size_request(-1, 24)

    def __emit_valor(self, widget, valor):
        if self.valor != valor:
            self.valor = valor
            self.emit("user-set-value", self.valor)

    def set_progress(self, valor=0.0):
        if self.escala.presed:
            return

        if self.valor != valor:
            self.valor = valor
            self.escala.ajuste.set_value(valor)
            self.escala.queue_draw()

class ProgressBar(gtk.HScale):
    """
    Escala de SlicerBalance.
    """

    __gsignals__ = {
    "user-set-value": (gobject.SIGNAL_RUN_LAST,
        gobject.TYPE_NONE, (gobject.TYPE_FLOAT, ))}

    def __init__(self, ajuste):

        gtk.HScale.__init__(self)

        self.modify_bg(gtk.STATE_NORMAL, COLORES["window"])

        self.ajuste = ajuste
        self.set_digits(0)
        self.set_draw_value(False)

        self.presed = False
        self.ancho, self.borde = (10, 10)

        icono = os.path.join(BASE_PATH, "Iconos", "controlslicer.svg")
        self.pixbuf = gtk.gdk.pixbuf_new_from_file_at_size(icono, 24, 24)

        self.connect("button-press-event", self.__button_press_event)
        self.connect("button-release-event", self.__button_release_event)
        self.connect("motion-notify-event", self.__motion_notify_event)
        self.connect("expose_event", self.__expose)

        self.show_all()

    def __button_press_event(self, widget, event):
        self.presed = True

    def __button_release_event(self, widget, event):
        self.presed = False

    def __motion_notify_event(self, widget, event):
        """
        Cuando el usuario se desplaza por la barra de progreso.
        Se emite el valor en % (float).
        """

        if event.state == gtk.gdk.MOD2_MASK | gtk.gdk.BUTTON1_MASK:
            rect = self.get_allocation()
            valor = float(event.x * 100 / rect.width)

            if valor >= 0.0 and valor <= 100.0:
                self.ajuste.set_value(valor)
                self.queue_draw()
                self.emit("user-set-value", valor)

    def __expose(self, widget, event):
        """
        Dibuja el estado de la barra de progreso.
        """

        x, y, w, h = self.get_allocation()
        ancho, borde = (self.ancho, self.borde)

        gc = gtk.gdk.Drawable.new_gc(self.window)

        # todo el widget
        gc.set_rgb_fg_color(COLORES["window"])
        self.window.draw_rectangle(gc, True, x, y, w, h)

        # vacio
        gc.set_rgb_fg_color(COLORES["text"])
        ww = w - borde * 2
        xx = x + w / 2 - ww / 2
        hh = ancho
        yy = y + h / 2 - ancho / 2
        self.window.draw_rectangle(gc, True, xx, yy, ww, hh)

        # progreso
        ximage = int(self.ajuste.get_value() * ww / 100)
        gc.set_rgb_fg_color(COLORES["toolbar"])
        self.window.draw_rectangle(gc, True, xx, yy, ximage, hh)

        # borde de progreso
        gc.set_rgb_fg_color(COLORES["text"])
        self.window.draw_rectangle(gc, False, xx, yy, ww, hh)

        # La Imagen
        imgw, imgh = (self.pixbuf.get_width(), self.pixbuf.get_height())
        yimage = yy + hh / 2 - imgh / 2

        self.window.draw_pixbuf(gc, self.pixbuf, 0, 0, ximage, yimage,
            imgw, imgh, gtk.gdk.RGB_DITHER_NORMAL, 0, 0)

        return True

class ControlVolumen(gtk.VolumeButton):

    __gsignals__ = {
    "volumen": (gobject.SIGNAL_RUN_LAST,
        gobject.TYPE_NONE, (gobject.TYPE_FLOAT,))}

    def __init__(self):

        gtk.VolumeButton.__init__(self)

        self.modify_bg(gtk.STATE_NORMAL, COLORES["window"])

        self.connect("value-changed", self.__value_changed)
        self.show_all()

        self.set_value(0.9)

    def __value_changed(self, widget, valor):
        """
        Cuando el usuario desplaza la escala.
        """

        valor = int(valor * 10)
        self.emit('volumen', valor)


"""
Author(s):
    Miguel Alex Cantu (miguel.can2@gmail.com)
Date: 02/21/2020
Description:
    This module will include common utility methods for the actions that will
    be implemented in this `action` subpackage of AUT.
"""

import requests
import logging
import datetime

from azure_utility_tool.graph_endpoints import *
from azure_utility_tool.utils import paginate
from azure_utility_tool.test_cases import TestCases
from azure_utility_tool.file_logger import file_logger
from azure_utility_tool.transformers import expand_onPremisesExtensionAttributes

def get_mfa_enforced_groups_displayname(parsed_args, config, app):
    """
    This method returns a dictionary mapping of the IDs of the
    MFA_ENFORCED_GROUPS defined in the config and their respective
    displayNames
    """
    MFA_ENFORCED_GROUPS_WITH_DISPLAY_NAME = {}
    for group in config["MFA_ENFORCED_GROUPS"].copy():
        group_info = []
        paginate(
                GROUP_GET.format(group),
                group_info,
                'displayName',
                parsed_args,
                config,
                app,
                test_data=TestCases().get_group_test_data(),
                std_output=False)
        MFA_ENFORCED_GROUPS_WITH_DISPLAY_NAME[group] = "".join(group_info)

    return MFA_ENFORCED_GROUPS_WITH_DISPLAY_NAME

def get_users_from_enforced_groups(parsed_args, config, app):
    """
    This method returns a list of dictionary objects representing the users
    in the MFA_ENFORCED_GROUPS.
    """
    users = []
    groups = config['MFA_ENFORCED_GROUPS'].copy()
    while groups:
        members = []
        group = groups.pop()
        paginate(
            GROUP_LIST_TRANSITIVEMEMBERS.format(group),
            members,
            'value',
            parsed_args,
            config,
            app,
            test_data=TestCases().
                get_users_in_enforced_groups_test_data(),
            std_output=False)
        for member in members:
            if 'user' in member["@odata.type"]:
                member['mfaEnforcedGroup'] = group
                users.append(member)
            if 'group' in member["@odata.type"]:
                groups.append(member["id"])
    return users


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2018/5/24 11:56
# @Author  : hardyxia
# @File    : release.py

from django.shortcuts import render, redirect, resolve_url, reverse
from django.contrib import auth
from django.http import HttpResponseRedirect
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password, check_password
from django.views import View
from django.views.decorators.csrf import csrf_exempt
from django.utils.decorators import method_decorator
from utils.release import JenkinsApi
from utils.pagination import page
from utils.cache import OperationCache
import inspect

jenkins = JenkinsApi()
# 创建一个cache对象
cache_obj = OperationCache(inspect.stack()[0][3])

class ReleaseListView(View):
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(ReleaseListView, self).dispatch(request, *args, **kwargs)

    def get(self, request, *args, **kwargs):
        title = ['项目名称', '运行状态', '是否可运行', '项目描述', ]

        cache_data = cache_obj.read_from_cache()
        if cache_data:
            print('from  redis ====================')
            response = cache_data.get('response')
            total = cache_data.get('total')
        else:
            print('from  api ====================')
            details = jenkins.get_job_details()
            response = details.get('job_list')
            total = details.get("job_count")
            data = {"response": response, "total": total}
            cache_obj.write_to_cache(data)
        response = page(request, response)

        return render(request, 'release/release.html', {"response": response,
                                                        'title': title,
                                                        "total": total,
                                                        "page": 10,
                                                        "release_active": "active open",
                                                        "release_list_active": "active"})

class JobBuildView(View):
    @method_decorator(login_required)
    def dispatch(self, request, *args, **kwargs):
        return super(JobBuildView, self).dispatch(request, *args, **kwargs)

    def get(self, request, job_name, *args, **kwargs):
        details = jenkins.get_job_details()
        response = details.get('job_list')
        total = details.get("job_count")
        for job in details.get('job_list'):
            if job["job_name"] == job_name:
                job['job_is_running'] = True
        data = {"response": response, "total": total}
        cache_obj.write_to_cache(data)
        jenkins.build_job(job_name,params=None)
        for job in details.get('job_list'):
            if job["job_name"] == job_name:
                job['job_is_running'] = False
        data = {"response": response, "total": total}
        cache_obj.write_to_cache(data)
        return HttpResponseRedirect(reverse('release_list'))


"""
    2nd approach:
    - 1000 buckets
    - each bucket has 1000 slots

    however, there is a limition of total number of items inserted into the hashtable

     624 ms beats 17.74%
    1apr2019
"""

class MyHashSet(object):

    def __init__(self):
        """
        Initialize your data structure here.
        """
        # 1000 buckets
        # each bucket has 1000 slots
        self.buckets = []
        for i in range(1000):
            self.buckets.append(1000*[False])

    def _getBucket(self, num):
        return num//1000

    def _getSlot(self, num):
        return num % 1000

    def add(self, key):
        """
        :type key: int
        :rtype: None
        """
        b = self._getBucket(key)
        s = self._getSlot(key)
        self.buckets[b][s] = True

    def remove(self, key):
        """
        :type key: int
        :rtype: None
        """
        b = self._getBucket(key)
        s = self._getSlot(key)
        self.buckets[b][s] = False

    def contains(self, key):
        """
        Returns true if this set contains the specified element
        :type key: int
        :rtype: bool
        """
        b = self._getBucket(key)
        s = self._getSlot(key)
        return self.buckets[b][s]

"""
    3rd approach:
    - linked list chaining

    advantage: no limitation of total number of key&value pairs

    although it gets TLE on leetcode, it is a decent and pragmatic approach to deal with hash collision
"""

class ListNode(object):

    def __init__(self, key):
        self.key = key
        self.next = None

class MyHashSet(object):

    def __init__(self):
        self.buckets = 1000*[ListNode(-1)]

    def _getBucket(self, num):
        return self.buckets[num//1000]

    def add(self, key):
        """
        :type key: int
        :rtype: None
        """
        head = self._getBucket(key)
        prev = head
        cur = prev.next
        while cur != None:
            if cur.key == key:
                return
            prev = cur
            cur = cur.next
        prev.next = ListNode(key)

    def remove(self, key):
        """
        :type key: int
        :rtype: None
        """
        head = self._getBucket(key)
        prev = head
        cur = prev.next
        while cur != None:
            if cur.key == key:
                prev.next = cur.next
            prev = cur
            cur = cur.next

    def contains(self, key):
        """
        Returns true if this set contains the specified element
        :type key: int
        :rtype: bool
        """
        head = self._getBucket(key)
        cur = head.next
        while cur != None:
            if cur.key == key:
                return True
            cur = cur.next
        return False

hs = MyHashSet()
hs.add(1)
hs.add(2)
hs.add(3)
print(hs.contains(1))
print(hs.contains(2))
print(hs.contains(3))
hs.add(2)
hs.remove(2)
print(hs.contains(2))


''' symbolic data generators for arithmetic '''
import numpy as np
import pickle
import sys
sys.path.append('/hd1/scsnl/neural_networks/modular_math_cog/utility')
import data_modifiers
from PIL import Image
import os
from os.path import join as pjoin
from torchvision import datasets, transforms, utils
np.set_printoptions(threshold=np.inf)
import torch
from torch import from_numpy
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
from pygame.locals import *
import random
import pygame
from math import pi, cos, sin
from copy import deepcopy
from subprocess import call
import time
import scipy.misc

def dataset_dict_generator(samples = 2000, nums = [0,1,2,3,4,5,6,7,8,9],ops = ['+','-'], min_ans = 0, max_ans = 18, noise = .5):
	output_dict = {}
	for p in range(samples):
		output_dict[p] = {}
		in_range = False
		while not in_range:
			num1 = np.random.choice(nums)
			num2 = np.random.choice(nums)
			op = np.random.choice(ops)
			string = str(num1)+op+str(num2)
			ans = eval(str(num1)+op+str(num2))
			if min_ans <= ans <= max_ans:
				in_range = True
				output_dict[p]['num1'] = num1
		output_dict[p]['num2'] = num2
		output_dict[p]['op'] = op
		output_dict[p]['op_onehot'] = data_modifiers.num_2_onehot(ops.index(op),0,len(ops)-1)
		output_dict[p]['string'] = string
		output_dict[p]['ans'] = ans
		output_dict[p]['num1_onehot'] = data_modifiers.num_2_onehot(num1,min(nums),max(nums))
		output_dict[p]['num2_onehot'] = data_modifiers.num_2_onehot(num2,min(nums),max(nums))
		output_dict[p]['ans_onehot'] = data_modifiers.num_2_onehot(num2,min_ans,max_ans)
		output_dict[p]['num1_gauss'] = data_modifiers.onehot_2_gaussian(output_dict[p]['num1_onehot'],std = noise)
		output_dict[p]['num2_gauss'] = data_modifiers.onehot_2_gaussian(output_dict[p]['num2_onehot'],std = noise)
		output_dict[p]['ans_gauss'] = data_modifiers.onehot_2_gaussian(output_dict[p]['ans_onehot'],std = noise)

	file_name = str(samples)+'_'
	for o in ops:
		file_name += o
	file_name += '_'+str(noise)
	pickle.dump(output_dict,open('../data/datasets/%s.pkl'%file_name,'wb'))

def gen_color(avoid_color = (0,0,0)):
	redo = True
	while redo:
		redo = False
		r = int(np.random.choice(list(range(255))))
		g = int(np.random.choice(list(range(255))))
		b = int(np.random.choice(list(range(255))))
		#print('%s %s %s'%(r,g,b))
		if avoid_color != 'none':
			if abs(r - avoid_color[0]) < 40 and abs(g - avoid_color[1]) < 40 and abs(b - avoid_color[2]) < 40:
				redo = True
	return (r,g,b)

def image_generator(samples_per = 100, nums = [0,1,2,3,4,5,6,7,8,9],ops = ['+','-'],min_ans = 0,max_ans = 18,
max_size = 40,min_size = 15,max_dim = 256,border_buffer = 30, versions = ['color','bow','wob'],
fontpath = '/hd1/scsnl/neural_networks/modular_math_cog/utility/font_list.txt',outputdir = '../data/images'):
	fontfile = open(fontpath,'r')
	fullfontlist = [x.strip() for x in fontfile.readlines()]
	BLACK = (  0,   0,   0)
	WHITE = (255, 255, 255)
	RED = (255,   0,   0)
	GREEN = (  0, 255,   0)
	BLUE = (  0,   0, 255)
	draw_space = int(np.floor(float(max_dim - 4*border_buffer)/3))

	os.environ["SDL_VIDEO_CENTERED"] = "1"
	pygame.init()
	screen = pygame.display.set_mode((max_dim,max_dim))
	pygame.display.set_caption("Simple Operation")
	pygame.font.init()
	clock = pygame.time.Clock()

	output_dict = {}
	p = -1
	for num1 in nums:
		for num2 in nums:
			for op in ops:
				ans = eval(str(num1)+op+str(num2))
				if not 0 <= ans:
					continue
				for sample in range(samples_per):
					string = str(num1)+op+str(num2)
					symbols = {'num1':num1,'num2':num2,'op':op}

					for version in versions:
						colors = {}
						if version == 'color':
							background_color = gen_color(avoid_color = 'none')
							colors['num1'] = gen_color(avoid_color = background_color)
							colors['op'] = gen_color(avoid_color = background_color)
							colors['num2'] = gen_color(avoid_color = background_color)
						elif version == 'bow':
							background_color = WHITE
							colors['num1'] = BLACK
							colors['num2'] = BLACK
							colors['op'] = BLACK
						elif version == 'wob':
							background_color = BLACK
							colors['num1'] = WHITE
							colors['num2'] = WHITE
							colors['op'] = WHITE
						screen.fill(background_color)

						positions = {}
						positions['num1'] = (int(np.random.choice(list(range(border_buffer,border_buffer+draw_space)))),int(np.random.choice(list(range(border_buffer,max_dim-border_buffer)))))
						positions['op'] = (int(np.random.choice(list(range(2*border_buffer+draw_space,2*border_buffer+2*draw_space)))),int(np.random.choice(list(range(border_buffer,max_dim-border_buffer)))))
						positions['num2'] = (int(np.random.choice(list(range(3*border_buffer+2*draw_space,3*border_buffer+3*draw_space)))),int(np.random.choice(list(range(border_buffer,max_dim-border_buffer)))))

						sizes = {}
						fonts  = {}
						for sym in ['num1', 'op', 'num2']:
							sizes[sym] = int(np.random.choice(list(range(min_size,max_size))))
							fonts[sym] = np.random.choice(fullfontlist)
						#drawing
						for sym in ['num1', 'op', 'num2']:
							font = pygame.font.SysFont(fonts[sym], sizes[sym])
							fontsurface = font.render(str(symbols[sym]), False, colors[sym])
							surface_size = fontsurface.get_width(), fontsurface.get_height()
							screen.blit(fontsurface,positions[sym])

						output_file_name = str(num1)+op+str(num2)+'_'+version+'_'+str(sample)+'.png'
						pygame.image.save(screen, pjoin(outputdir,output_file_name))

						p += 1
						output_dict[p] = {}
						output_dict[p]['num2'] = num2
						output_dict[p]['op'] = op
						output_dict[p]['op_onehot'] = data_modifiers.num_2_onehot(ops.index(op),0,len(ops)-1)
						output_dict[p]['string'] = string
						output_dict[p]['ans'] = ans
						output_dict[p]['num1_onehot'] = data_modifiers.num_2_onehot(num1,min(nums),max(nums))
						output_dict[p]['num2_onehot'] = data_modifiers.num_2_onehot(num2,min(nums),max(nums))
						output_dict[p]['ans_onehot'] = data_modifiers.num_2_onehot(num2,min_ans,max_ans)
						output_dict[p]['symbols'] = symbols
						output_dict[p]['colors'] = colors
						output_dict[p]['sizes'] = sizes
						output_dict[p]['positions'] = positions
						output_dict[p]['ans'] = ans
						output_dict[p]['file_name'] = output_file_name
	pickle.dump(output_dict,open(pjoin(outputdir,'image_dict.pkl'),'wb'))

class CountingDotsDataSet(Dataset):
	"""How many dots are in this pic dataset."""

	def __init__(self, root_dir, train=True, blackandwhite=False, cutoff=10, resize = False, size=30, include_negatives = True, onehot=False, transform=transforms.Compose([transforms.Grayscale(num_output_channels=1),transforms.ToTensor(),transforms.Normalize((0.1307,), (0.3081,))])):
		"""
		"""

		self.root_dir = root_dir
		if train:
			self.pic_dir = os.path.join(root_dir,'train')
		else:
			self.pic_dir = os.path.join(root_dir,'test')
		self.pic_names = sorted(os.listdir(self.pic_dir))
		if not include_negatives:
			self.pic_names = [i for i in self.pic_names if not ('neg' in i)]
		self.transform = transform
		self.onehot = onehot
		self.size = size
		self.resize = resize
		self.cutoff = cutoff
	def __len__(self):
		return len(self.pic_names)

	def get_label_from_name(self,img_name,cutoff):
		split_name = img_name.split('_')
		num = int(split_name[0])-1
		if num > int(cutoff-1):
			num = int(cutoff-1)
		if self.onehot:
			return numtoarr(num,1,cutoff)
		else:
			return np.array(num)

	def __getitem__(self, idx):
		img_name = os.path.join(self.pic_dir,self.pic_names[idx])
		#image = image.imread(img_name,as_gray=True)
		#image = rgb2grey(image)
		image = Image.open(img_name)
		if self.resize:
			image = image.resize((self.size,self.size))
		#image = np.array([image])
		#image = image.astype(float)
		label = self.get_label_from_name(self.pic_names[idx],self.cutoff)
		#sample = {'image': image, 'label': label}
		if self.transform:
			image = self.transform(image)
		label = from_numpy(label)
		sample = (image,label)
		return sample

class three_num_abstract(Dataset):
	def __init__(self, dict_path, train=True, train_test_split = .8, input_noise = True, ans_noise = False):
			self.dict_path = dict_path
			self.dict = pickle.load(open(dict_path,'rb'))
			self.train = train
			self.train_test_split = train_test_split
			self.input_noise = input_noise
			self.ans_noise = ans_noise
			self.file_name = dict_path.split('/')[-1]
			file_name_list = self.file_name.split('_')
			self.samples = int(file_name_list[0])
			self.noise_std = float(file_name_list[-1].replace('.pkl',''))
			self.training_samples = int(np.ceil(float(len(self.dict))*self.train_test_split))
			self.testing_samples = int(len(self.dict)-np.ceil(float(len(self.dict))*self.train_test_split))
	def __len__(self):
		if self.train:
			return self.training_samples
		else:
			return self.testing_samples

	def __getitem__(self, idx):
		if self.train:
			p = idx
		else:
			p = int(np.ceil(float(len(self.dict))*self.train_test_split))+idx
		if self.input_noise:
			np_input = np.concatenate((self.dict[p]['num1_gauss'],self.dict[p]['num2_gauss'],self.dict[p]['op_onehot']))
		else:
			np_input = np.concatenate((self.dict[p]['num1_onehot'],self.dict[p]['num2_onehot'],self.dict[p]['op_onehot']))
		input = from_numpy(np_input).type(torch.FloatTensor)
		if self.ans_noise:
			label = from_numpy(self.dict[p]['ans_gauss']).type(torch.FloatTensor)
		else:
			label = from_numpy(self.dict[p]['ans_onehot']).type(torch.FloatTensor)
		return (input,label)

	def get_info(self):
		input_dim = len(np.concatenate((self.dict[0]['num1_gauss'],self.dict[0]['num2_gauss'],self.dict[0]['op_onehot'])))
		label_dim = len(self.dict[0]['ans_gauss'])
		samples = self.samples
		noise_std = self.noise_std
		return {'input_dim':input_dim,'label_dim':label_dim,'noise_std':noise_std,'samples':samples,'training_samples':self.training_samples,'testing_samples':self.testing_samples}

#class three_num_image(Dataset):


import csv, sys

from code.algorithms.bfs import BreadthFirst
from code.algorithms.randomise import Randomise
from code.algorithms.minibfs import MiniBFS
from code.algorithms.hybrid import Hybrid

from code.visualisation.visualisation import Visualize

if __name__ == '__main__':

    # initialize MAX for randomise
    MAX = 0

    # correct input
    if len(sys.argv) < 3:
        print("command: python main.py breadthfirst 6x6_1")
        sys.exit(1)

    # get algorithm and bord
    algorithm_choice = sys.argv[1]
    board_choice = sys.argv[2]

    # MAX for randomise
    if len(sys.argv) == 4:
        MAX = sys.argv[3]

    # different possible algorithms
    algorithms = {
    "randomise" : Randomise,
    "breadthfirst" : BreadthFirst,
    "hybrid" : Hybrid
    }

    # run algorithm
    if algorithm_choice == 'breadthfirst':
        moves_set = algorithms[algorithm_choice](f'data/Rushhour{board_choice}.csv').run()

    else:
        if not MAX:
            MAX = 1000

        moves_set = algorithms[algorithm_choice](f'data/Rushhour{board_choice}.csv', MAX).run()

    # write moves set to outputfile
    with open(f'output/{board_choice}/output{board_choice}_{algorithm_choice}_{len(moves_set)}.csv', 'w', newline='') as outputfile:
        fieldnames = ['car', 'move']
        writer = csv.writer(outputfile)
        writer.writerow(fieldnames)
        writer.writerows(moves_set)

    # visualize output
    Visualize(f'data/Rushhour{board_choice}.csv', f'output/{board_choice}/output{board_choice}_{algorithm_choice}_{len(moves_set)}.csv').run()


import random

class Point:
    total = 0

    def __init__(self, x=0, y=0, id=0):
        self.x = x
        self.y = y
        self.id = id
        Point.total = Point.total + 1

    def display(self):
        print(self.x, self.y)

    def get_id(self):
        print(self.id)

    def __del__(self):
        Point.total -= 1

    @classmethod
    def get_total(cls):
        print(Point.total)

#p1 = Point()
#p1.display()

if __name__ == "__main__":
    liste_point = []
    for n in range(10):
        liste_point.append(Point(random.randint(0, 100), random.randint(0, 100), n))

print("Point 1-------------------")
print("id:")
liste_point[0].get_id()
print("Total:")
liste_point[0].get_total()
print("Point 2-------------------")
print("id:")
liste_point[9].get_id()
print("Total:")
liste_point[9].get_total()

print("Suppression d'un point:")
del liste_point[1]
print("Nouveau total")
Point.get_total()

print("Information du dernier point:")
print("id:")
liste_point[-1].get_id()
print("total")
liste_point[-1].get_total()


# 나무자르기
# 이분탐색

import sys
input = sys.stdin.readline

n, m = map(int, input().split())

trees = list(map(int, input().split()))

trees.sort()

start = 0
end = max(trees)
cut = 0
#print(f'cut: {cut}')
ans = 0
while start <= end:
    cut = (start + end) // 2
    #print(cut)
    total = 0
    for tree in trees:
        if tree > cut:
            total += tree - cut

    if total < m:
        end = cut - 1
    # 자른 결과가 m보다 클 수도 있다
    # 예시: 4 3 / 2 2 2 2
    else:
        ans = cut
        start = cut + 1

print(ans)


from dependency_injector.wiring import Provide, inject
from fastapi import APIRouter, Depends
from pydantic import BaseModel

from app.container import AppContainer
from app.core.jwt import get_current_user
from app.modules.messages.model import Message

from .usecases import (
    CreateThreadMessageUsecase,
    DeleteThreadMessageUsecase,
    GetThreadMessagesUsecase,
)

Container = AppContainer.message
router = APIRouter(prefix="/threads/{thread_id}/messages", tags=["messages"])

@router.get("")
@inject
def get_thread_messages(
    thread_id: int,
    user_id: int = Depends(get_current_user),
    usecase: GetThreadMessagesUsecase = Depends(Provide[Container.get_thread_messages]),
):
    messages = usecase.get_thread_messages_for_user(thread_id, user_id)
    return {"data": messages}

class CreateThreadMessageRequest(BaseModel):
    message: str

@router.post("")
@inject
def create_thread_message(
    thread_id: int,
    req: CreateThreadMessageRequest,
    user_id: int = Depends(get_current_user),
    usecase: CreateThreadMessageUsecase = Depends(
        Provide[Container.create_thread_message]
    ),
):
    msg = usecase.create_message(
        Message(thread_id=thread_id, user_id=user_id, message=req.message)
    )
    return {"data": msg}

@router.delete("/{message_id}")
@inject
def delete_thread_message(
    thread_id: int,
    message_id: int,
    user_id: int = Depends(get_current_user),
    usecase: DeleteThreadMessageUsecase = Depends(
        Provide[Container.delete_thread_message]
    ),
):
    usecase.delete_message_for_user(user_id, message_id)
    return {"data": {"success": True}}


def get_options():
    return {
        'A': {
            'name'     : "Addition",
            'operation': add
        },
        'B': {
            'name': "Subtraction",
            'operation': sub
        },
        'C': {
            'name': "Multiplication",
            'operation': mul
        },
        'D': {
            'name': "Division",
            'operation': div
        },
        'E': {
            'name': "Exit",
            'operation': False
        }
    }

def add(a, b):
    answer = a + b
    print(" " * 20)
    print("#" * 5, "RESULT", "#" * 5)
    print(f"{str(a)} + {str(b)} = {str(answer)}")

def sub(a, b):
    answer = a - b
    print(" " * 20)
    print("#" * 5, "RESULT", "#" * 5)
    print(f"{str(a)} - {str(b)} = {str(answer)}")

def mul(a, b):
    answer = a * b
    print(" " * 20)
    print("#" * 5, "RESULT", "#" * 5)
    print(f"{str(a)} * {str(b)} = {str(answer)}")

def div(a, b):
    answer = a / b
    print(" " * 20)
    print("#" * 5, "RESULT", "#" * 5)
    print(f"{str(a)} / {str(b)} = {str(answer)}")

def exits_user_choice(choice, options):
    return True if (choice in options) else False

def printHeader():
    print(" " * 20)
    print("#" * 5, "BASIC CALCULATOR", "#" * 5)
    print(" " * 20)

def userOptions():
    while True:
        printHeader()
        options = get_options()
        for index, option in options.items():
            print(f"{index}. {option['name']}")

        choice = input("Input your choice: ")
        choice = choice.upper();

        if(exits_user_choice(choice, options)):
            operation = options[choice]['operation']

            if(operation == False):
                print(" " * 20)
                print("*" * 15, "PROGRAM ENDED", "*" * 15,)
                print(" " * 20)
                quit()

            try:
                a = int(input('Input first number: '))
                b = int(input('Input second number: '))
                operation(a, b)
            except Exception as e:
                print(e)
                print(" " * 20)
                print("!" * 5, "Error. Try again.", "!" * 5,)

        else:
            print(" " * 20)
            print("!" * 5, "Incorrect Option. Try again.", "!" * 5,)

def run():
    userOptions()

#* Entry point
if __name__ == '__main__':
    run()


import os
import sys
import warnings
import time
import logging
import matplotlib.pyplot as plt
import numpy as np
import datetime
import traceback
import argparse

from custom_metrics import f2, average_precision, average_recall, hamming_score

sys.path.insert(0, '/home/reflex/refleX/lib/fastai')
from fastai.conv_learner import *

def save_lr_chart(lrs, losses, filename, n_skip=10, n_skip_end=5):
    plt.ylabel("validation loss")
    plt.xlabel("learning rate (log scale)")
    plt.plot(lrs[n_skip:-(n_skip_end+1)], losses[n_skip:-(n_skip_end+1)])
    plt.xscale('log')
    plt.savefig(filename)
    plt.clf()

def get_data (model, PATHS, img_size, custom_transformations, batch_size, val_idxs):
    tfms = tfms_from_model(model, img_size, aug_tfms=custom_transformations, max_zoom=1.1)
    return ImageClassifierData.from_csv(PATHS['DATA_PATH'], PATHS['DATA_FOLDER'], PATHS['CSV_PATH'], tfms=tfms,
                    suffix='.png', val_idxs=val_idxs, bs=batch_size, num_workers=2)

def grid_search(PATHS, CONFIG, experiment_name, PARAMS, output_csv='results.csv'):

    val_idxs = PARAMS['val_idxs']

    # TODO: Czy LR wyznaczamy przed na samym początku czy przed kazdym uczeniem (tj. przed zmiana rozdzielczosci?)

    # Logger
    logger = logging.getLogger(f'{experiment_name}')
    logging.basicConfig(filename=f'{PATHS["EXP_PATH"]}/{experiment_name}/{experiment_name}.log', format='%(asctime)s - %(levelname)s - %(message)s',\
        filemode='w', datefmt='%d-%m-%Y %I:%M:%S %p', level=logging.INFO)

    # Dodatowe parametry
    dropout = PARAMS['dropout']
    earlystoping = PARAMS['earlystopping']
    log_step = PARAMS['log_step']
    custom_aug_tfms = PARAMS['transformations']
    gpu = PARAMS['gpu_id']
    torch.cuda.set_device(gpu)

    # 1. INFO
    logging.info(f" [ ------ EXPERIMENT: {experiment_name.upper()} ------ ] \n")

    # Log
    logging.info(' --- PARAMETERS: --- ')
    logging.info(f"Predefined metrics: [val_loss], {', '.join([metric.__name__ for metric in CONFIG['predefined_metrics']])}")
    logging.info(f"Predefined architecutres: {', '.join([architecture[0] for architecture in CONFIG['architectures'].items()])}")
    logging.info(f"Predefined batch sizes: {', '.join([str(batch_size) for batch_size in CONFIG['batch_sizes']])}")
    logging.info(f"Predefined image sizes: {', '.join([str(img_size) for img_size in CONFIG['image_sizes']])}")
    logging.info(f"Dropout: {dropout}")
    logging.info(f"Earlystopping after: {earlystoping} epochs.")
    logging.info(f"Log every {log_step} epochs.")
    logging.info(f'GPU: {torch.cuda.current_device()} | Available: {torch.cuda.device_count()} \n')

    for model_name, model in CONFIG['architectures'].items():

        logging.info(f"    ----- *** {model_name.upper()} *** ----- \n")

        # Definiujemy obiekt learner'a
        data = get_data(model, PATHS, CONFIG['image_sizes'][0], custom_aug_tfms, CONFIG['batch_sizes'][0], val_idxs)
        learn = ConvLearner.pretrained(model, data, ps=dropout, metrics=CONFIG['predefined_metrics'])

        # Obliczanie LR - wybieranie najmniejszego loss i dzielenie przez 10
        learn.lr_find()
        save_lr_chart(learn.sched.lrs, learn.sched.losses, f'{PATHS["EXP_PATH"]}/{experiment_name}/{model_name}_lr_sched.png')

        lr = sorted(list(zip(learn.sched.lrs, learn.sched.losses)), key=lambda x: x[1])[0][0] / 10
        lrs = [lr/8, lr/4, lr/2, lr]

        # Log
        logging.info(f' Learning rate = {round(lr, 6)}')
        logging.info(f' Learning rates = {[round(lr, 6) for lr in lrs]} \n')

        for batch_size in CONFIG['batch_sizes']:

            for img_size in CONFIG['image_sizes']:

                try:
                    logging.info(f" --- Batch: {batch_size} | Img size: {img_size} --- \n ")

                    # Preparing data
                    best_model_name = f'{PATHS["EXP_PATH"]}/{experiment_name}/models/best_{model_name}_imgsize{img_size}_batch{batch_size}'
                    data = get_data(model, PATHS, img_size, custom_aug_tfms, batch_size, val_idxs)
                    learn.set_data(data)

                    # Freeze
                    logging.info(f" --- Type: FREEZE --- ")
                    learn.freeze()
                    learn.fit(lr, 12, cycle_len=1, cycle_mult=2, best_save_name=f'{best_model_name}_freeze', earlystopping=earlystoping, logger_name=experiment_name, log_step=log_step)

                    # Print results
                    results = open(f'{best_model_name}_freeze_metrics.log', 'r').read()
                    logging.info(f"[ Saved model: best_{model_name}_imgsize{img_size}_batch{batch_size}_freeze.h5 ] ")
                    logging.info(f'[ Results: {results} ]\n')

                    # Unfreeze
                    logging.info(f" --- Type: UNFREEZE --- ")
                    learn.unfreeze()
                    learn.fit(lr, 12, cycle_len=1, cycle_mult=2, best_save_name=f'{best_model_name}_unfreeze', earlystopping=earlystoping, logger_name=experiment_name, log_step=log_step)

                    # Print results
                    results = open(f'{best_model_name}_unfreeze_metrics.log', 'r').read()
                    logging.info(f"[ Saved model: best_{model_name}_imgsize{img_size}_batch{batch_size}_unfreeze.h5 ]")
                    logging.info(f'[ Results: {results} ]\n')

                    if img_size == CONFIG['image_sizes'][-1]:
                        logging.info(" ************************** ")
                        logging.info(f'COPYPASTE: {model_name} | IMS: {CONFIG["image_sizes"][0]} -> {img_size} | BS: {batch_size}')
                        logging.info(f'COPYPASTE: {results} ')
                        logging.info(" ************************** \n")

                except Exception as e:
                    logging.error(f'ERROR: A: {model_name} | IS: {img_size} | BS: {batch_size}')
                    logging.error(traceback.format_exc())

            if batch_size != CONFIG['batch_sizes'][-1]:
                logging.info(' --- INCREMENTING BATCH SIZE --- \n')

        logging.info(f"    ----- *** END: {model_name} *** ----- \n")

    print("[ --- DONE! --- ]")

def ac_polar_max_configuration():

    paths = {
        'DATA_FOLDER' : 'polar512_max'
    }

    params = {
        'transformations': [RandomLighting(0.1, 0.1)],
        'gpu_id': 0
    }

    config = {
        'image_sizes': [64, 128, 256, 512],
        'predefined_metrics': [f2, average_precision, average_recall, hamming_score],
        'batch_sizes': [8, 16, 32, 64], # PARAMETER
        'architectures' : {
            'resnet34' : resnet34 # PARAMETER
        }
    }

    return params, paths, config

def ac_polar_min_configuration():

    paths = {
        'DATA_FOLDER' : 'polar512_min'
    }

    params = {
        'transformations': [RandomLighting(0.1, 0.1)],
        'gpu_id': 1
    }

    config = {
        'image_sizes': [64, 128, 256, 512],
        'predefined_metrics': [f2, average_precision, average_recall, hamming_score],
        'batch_sizes': [8, 16, 32, 64], # PARAMETER
        'architectures' : {
            'resnet34' : resnet34 # PARAMETER
        }
    }

    return params, paths, config

def ac_resnet34_configuration():
    paths = {
        'DATA_FOLDER': 'original512'
    }

    params = {
        'gpu_id': 2,
        'transformations' : [RandomLighting(0.1, 0.1), RandomDihedral()]
    }

    config = {
        'image_sizes': [64, 128, 256, 512],
        'predefined_metrics': [f2, average_precision, average_recall, hamming_score],
        'batch_sizes': [8, 16, 32],
        'architectures' : {
            'resnet34' : resnet34
        }
    }

    return params, paths, config

def ac_resnet18_configuration():
    paths = {
        'DATA_FOLDER': 'original512'
    }

    params = {
        'gpu_id': 3,
        'transformations' : [RandomLighting(0.1, 0.1), RandomDihedral()]
    }

    config = {
        'image_sizes': [64, 128, 256, 512],
        'predefined_metrics': [f2, average_precision, average_recall, hamming_score],
        'batch_sizes': [64, 128, 256],
        'architectures' : {
            'resnet18' : resnet18
        }
    }

    return params, paths, config

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('working_title')
    parser.add_argument('-g', '--gpu_id', default=0, help="GPU ID")
    parser.add_argument('-cc', '--custom_config', default=None, help="Path to custom configuration file.")
    parser.add_argument('-cn', '--config_name', default='test', help="Name of hardcoded configuration")
    args = parser.parse_args()

    CUSTOM_PARAMS, CUSTOM_PATHS, CONFIG = globals()[args.config_name + "_configuration"]()

    #  --- DEFAULT PATHS ---
    PATHS = {
        'CSV_PATH': '/home/reflex/refleX/metadata/6K/csv/fastai_labels_val_train.csv',
        'DATA_PATH': '/home/reflex/refleX/metadata/6K/',
        'DATA_FOLDER': 'original512',
        'EXP_PATH': '/home/reflex/refleX/results/fastai_experiments'
    }

    # --- APPLY CUSTOM PATHS  ---
    for custom_path in CUSTOM_PATHS.keys():
        PATHS[custom_path] = CUSTOM_PATHS[custom_path]

    # --- DEFAULT PARAMS ---
    PARAMS = {
        'val_idxs': range(631),
        'dropout': 0.5,
        'earlystopping': 12,
        'log_step': 5,
        'gpu_id': args.gpu_id,
        'transformations' : [RandomLighting(0.1, 0.1), RandomDihedral()]
    }

    # --- APPLY CUSTOM PARAMETERS ---
    for custom_param in CUSTOM_PARAMS.keys():
        PARAMS[custom_param] = CUSTOM_PARAMS[custom_param]

    # Create dirs
    current_instance_dir = f'{PATHS["EXP_PATH"]}/{args.working_title}'
    models_dir = f'{PATHS["EXP_PATH"]}/{args.working_title}/models/'
    tmp_dir = f'{PATHS["EXP_PATH"]}/{args.working_title}/tmp/'

    os.makedirs(current_instance_dir, exist_ok=True)
    os.makedirs(models_dir, exist_ok=True)
    os.makedirs(tmp_dir, exist_ok=True)

    # Set validation set
    # convert_csv_to_fastai_format.py

    # Run grid search
    grid_search(PATHS, CONFIG, args.working_title, PARAMS)


from behave.__main__ import main as behave_main
from datetime import date
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.application import MIMEApplication
from thamos.config import config
from thamos.lib import thamos_version
import os
import smtplib
import sys
import shutil

__version__ = "0.11.5"

_BEHAVE_REPORT_FILE = "behave-report.html"
_DEPLOYMENT_NAME = os.getenv("THOTH_DEPLOYMENT_NAME", "N/A")
_EMAIL_SMTP_SERVER = os.getenv("THOTH_EMAIL_SMTP_SERVER", "smtp.corp.redhat.com")
_EMAIL_TO = os.getenv("THOTH_EMAIL_TO", "aicoe-thoth-devops@redhat.com")
_EMAIL_FROM = os.getenv("THOTH_EMAIL_FROM", "noreply@redhat.com")
_GENERATE_REPORT = bool(int(os.getenv("GENERATE_REPORT", 0)))
_MAIL_REPORT = bool(int(os.getenv("MAIL_REPORT", 0)))
_TAGS = os.getenv("THOTH_INTEGRATION_TESTS_TAGS")
_BEHAVE_HTML_REPORT = "behave-report.html"
_ARTIFACTS_DIRECTORY = os.getenv("ARTIFACTS", None)

def _print_info() -> None:
    """Print test information."""
    print(
        f"""--------------------------------------------------------------------------------
> Tests are executed against {_DEPLOYMENT_NAME} deployment
> Tests are executed against User API at {os.getenv('THOTH_USER_API_HOST')}
> Tests are executed against Management API at {os.getenv('THOTH_MANAGEMENT_API_HOST')}
> Tests are executed against Amun API at {os.getenv('THOTH_AMUN_API_HOST')}
--------------------------------------------------------------------------------"""
    )

def _create_email_subject() -> str:
    """Create e-mail subject."""
    today = date.today()
    return f"Integration tests update for {_DEPLOYMENT_NAME} ({today.strftime('%Y-%m-%d')} version {__version__})"

def send_email() -> None:
    """Send e-mail with begave test reports."""
    msg = MIMEMultipart()
    with open(_BEHAVE_REPORT_FILE, "r") as fp:
        report = fp.read()

    msg["Subject"] = _create_email_subject()
    msg["From"] = _EMAIL_FROM
    msg["To"] = _EMAIL_TO
    msg.attach(MIMEText(report, "html"))  # Message body.
    msg.attach(MIMEText(f"Thoth version: {config.get_thoth_version()}\n"))
    msg.attach(MIMEText(f"Thamos version: {thamos_version}"))

    attachment = MIMEApplication(report, _subtype="html")
    attachment.add_header("content-disposition", "attachment", filename=_BEHAVE_REPORT_FILE)
    msg.attach(attachment)

    s = smtplib.SMTP(_EMAIL_SMTP_SERVER)
    s.sendmail(msg["From"], [msg["To"]], msg.as_string())
    s.quit()

def main() -> None:
    """Run main entry-point for s2i based integration tests."""
    args = ["--show-timings"]
    if _GENERATE_REPORT:
        args.extend(["-f", "html", "-o", "behave-report.html"])

    if _TAGS:
        args.extend(["--tags", _TAGS])

    # Pass any additional arguments to behave.
    args.extend(sys.argv[1:])

    _print_info()
    print("Tests are executed using", args, file=sys.stderr)

    try:
        exit_code = behave_main(args)
    except OSError:
        pass

    if _GENERATE_REPORT and _MAIL_REPORT:
        send_email()

    if _ARTIFACTS_DIRECTORY is not None:
        shutil.copy(_BEHAVE_HTML_REPORT, _ARTIFACTS_DIRECTORY)

    sys.exit(exit_code)

__name__ == "__main__" and main()


from datetime import datetime

from pyspark.sql import DataFrame, SparkSession
from pyspark.sql.functions import when, substring, lit, col, concat
from pyspark.sql.types import IntegerType

from ...interfaces import TransformerInterface
from ...._pipeline_utils.models import Libraries, SystemType
from ...._pipeline_utils.weather import WEATHER_DATA_MODEL

class RawForecastToWeatherDataModel(TransformerInterface):
    """
    Converts a raw forecast into weather data model.

    Parameters:
        spark (SparkSession): Spark Session instance.
        data (DataFrame): Dataframe to be transformed
    """

    spark: SparkSession
    data: DataFrame

    def __init__(
        self,
        spark: SparkSession,
        data: DataFrame,
    ) -> None:
        self.spark = spark
        self.data = data
        self.target_schema = WEATHER_DATA_MODEL

    @staticmethod
    def system_type():
        """
        Attributes:
            SystemType (Environment): Requires PYSPARK
        """
        return SystemType.PYSPARK

    @staticmethod
    def libraries():
        libraries = Libraries()
        return libraries

    @staticmethod
    def settings() -> dict:
        return {}

    def pre_transform_validation(self):
        return True

    def post_transform_validation(self) -> bool:
        assert str(self.data.schema) == str(self.target_schema)
        return True

    def _convert_into_target_schema(self) -> None:
        """
        Converts a Spark DataFrame structure into new structure based on the Target Schema.

        Returns: Nothing.

        """

        df: DataFrame = self.data
        df = df.select(self.target_schema.names)

        for field in self.target_schema.fields:
            df = df.withColumn(field.name, col(field.name).cast(field.dataType))

        self.data = self.spark.createDataFrame(df.rdd, self.target_schema)

    def transform(self) -> DataFrame:
        """
        Returns:
            DataFrame: A Forecast dataframe converted into Weather Data Model
        """

        self.pre_transform_validation()

        processed_date = datetime.utcnow().strftime("%Y-%m-%d %H:%M:%S")

        df = (
            self.data.withColumn("WeatherDay", substring("FcstValidLocal", 0, 10))
            .withColumn(
                "WeatherHour",
                (substring("FcstValidLocal", 12, 2).cast(IntegerType()) + 1),
            )
            .withColumn("WeatherTimezoneOffset", substring("FcstValidLocal", 20, 5))
            .withColumn("WeatherType", lit("F"))
            .withColumn("ProcessedDate", lit(processed_date))
            .withColumnRenamed("Temp", "Temperature")
            .withColumnRenamed("Dewpt", "DewPoint")
            .withColumnRenamed("Rh", "Humidity")
            .withColumnRenamed("Hi", "HeatIndex")
            .withColumnRenamed("Wc", "WindChill")
            .withColumnRenamed("Wdir", "WindDirection")
            .withColumnRenamed("Wspd", "WindSpeed")
            .withColumnRenamed("Clds", "CloudCover")
            .withColumn("WetBulbTemp", lit(""))
            .withColumn("SolarIrradiance", lit(""))
            .withColumnRenamed("Qpf", "Precipitation")
            .withColumnRenamed("DayInd", "DayOrNight")
            .withColumnRenamed("Dow", "DayOfWeek")
            .withColumnRenamed("Gust", "WindGust")
            .withColumnRenamed("Mslp", "MslPressure")
            .withColumnRenamed("Num", "ForecastDayNum")
            .withColumnRenamed("Pop", "PropOfPrecip")
            .withColumnRenamed("PrecipType", "PrecipType")
            .withColumnRenamed("SnowQpf", "SnowAccumulation")
            .withColumnRenamed("UvIndex", "UvIndex")
            .withColumnRenamed("Vis", "Visibility")
        )

        columns = df.columns
        for column in columns:
            df = df.withColumn(
                column, when(col(column) == "", lit(None)).otherwise(col(column))
            )

        self.data = df
        self._convert_into_target_schema()
        self.post_transform_validation()

        return self.data


from pickle import TRUE
import pygame
import classes
import algo
import threading
import time

RUN_ALGO_TIMES = 10
CUR_RUN = 1
ALGO_RESULTS = list()
TEST_AI_STATE = True

class AlgoResult:
    def __init__(self, endState, endScore, endHigh):
        self.endState = endState
        self.endScore = endScore
        self.endHigh = endHigh

pygame.init()

screen = pygame.display.set_mode([300, 300])

gridObj = classes.gameGrid()
gameObj = classes.game()

gameObj.placeRandomNumb(True)
gameObj.placeRandomNumb(True)

print("\r\n\r\n")

running = True
while running:
    if CUR_RUN == RUN_ALGO_TIMES:
        if not TEST_AI_STATE:
            TEST_AI_STATE = True
            CUR_RUN = 1
        else:
            running = False

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((0, 0, 0)) # Clears screen
    gridObj.update(gameObj.state)

    if len(gameObj.find_valid_moves()) == 0:
        score, highVal = gameObj.endStats()
        print(f"{CUR_RUN}) {classes.blcolors.RED}GAME OVER{classes.blcolors.CLEAR} Score: {score}, highest: {highVal}")

        ALGO_RESULTS.append(AlgoResult(gameObj.state, score, highVal))

        gameObj.clear()
        pygame.event.clear()
        CUR_RUN += 1

    score, highVal = gameObj.endStats()
    print(f"{classes.blcolors.GREEN}RUNING{classes.blcolors.CLEAR} Score: {score}, highest: {highVal}", end="\r")

    moveEval, moves = algo.algo(gameObj, 3, ENABLE_2_4_ADDING=TEST_AI_STATE)
    try:
        gameObj.move(moves[0], place=True)

    except IndexError:
        score, highVal = gameObj.endStats()
        print(
            f"{classes.blcolors.RED}FAILED DUE TO UNKNOWN CAUSE{classes.blcolors.CLEAR}" +
            f": moveEval: {moveEval}, moves: {moves}\r\n{gameObj.state}\r\n" +
            f"{CUR_RUN}) {classes.blcolors.RED}GAME OVER{classes.blcolors.CLEAR} Score: {score}, highest: {highVal}"
        )
        ALGO_RESULTS.append(AlgoResult(gameObj.state, score, highVal))

        gameObj.clear()
        pygame.event.clear()
        CUR_RUN += 1

    # x = threading.Thread(target=algo.asyncAlgo, args=(gameObj, 3, gameObj.move), daemon=True)
    # x.start()

pygame.quit()


def get_document_value(document, key):
    '''
    Returns the display value of a field for a particular MongoDB document.
    '''
    value = getattr(document, key)
    if isinstance(value, ObjectId):
        return value

    if isinstance(document._fields.get(key), URLField):
        return mark_safe("""{1}""".format(value, value))

    if isinstance(value, Document):
        app_label = value.__module__.replace(".models", "")
        document_name = value._class_name
        url = reverse(
            "document_detail",
            kwargs={'app_label': app_label, 'document_name': document_name,
                    'id': value.id})
        return mark_safe("""{1}""".format(url, value))

    return value


#!/usr/bin/env python

"""Create heterogeneous targets using label hierarchy to reduce imbalance"""

import argparse
import json
import logging
import os
from collections import Counter, defaultdict
from statistics import mean, stdev
from typing import Tuple

from utils import set_logger

def imbalance_ratios(target_cases: dict) -> Tuple[float, float, float, float]:
    """Compute imbalance ratios for given targets"""
    max_class = max(map(lambda x: len(x), target_cases.values()))
    imbl = [max_class * 1./len(v) for v in target_cases.values()]
    max_imbl = max(imbl)
    min_imbl = min(imbl)
    stdev_imbl = stdev(imbl)
    mean_imbl = mean(imbl)
    return max_imbl, min_imbl, stdev_imbl, mean_imbl

def split_area(
        target_cases: dict,
        largest_class: str,
        label_cases: dict,
        present_lb1_lb2: dict,
        min_cases: int,
        big_atomic_classes: list) -> Tuple[dict, float]:
    new_areas = {
        k: label_cases[k] for k in present_lb1_lb2[largest_class]
        if len(label_cases[k]) >= min_cases}
    if len(new_areas) == 0:
        big_atomic_classes.append(largest_class)

        n_max_imbl, n_min_imbl, n_stdev_imbl, n_mean_imbl = imbalance_ratios(
                                                                target_cases)
        logging.info(f"{largest_class} is atomic. Mean IMbl: {n_mean_imbl} "
                     f"Stdev IMbl: {n_stdev_imbl}")
        return big_atomic_classes, target_cases, n_mean_imbl

    composite_area = list(set(target_cases[largest_class]) -
                          set([v for val in new_areas.values() for v in val]))
    if len(composite_area) != 0 and len(composite_area) < min_cases:
        least_new = min([len(v) for v in new_areas.values()])
        least_new_class = [
                k for k, v in new_areas.items()
                if len(v) == least_new]
        least_new_class = least_new_class[0]
        composite_area.extend(new_areas[least_new_class])
        del new_areas[least_new_class]

    del target_cases[largest_class]
    target_cases.update(new_areas)
    if len(composite_area) != 0:
        target_cases.update({f"{largest_class}_COMPOSITE": composite_area})
        big_atomic_classes.append(f"{largest_class}_COMPOSITE")
    n_max_imbl, n_min_imbl, n_stdev_imbl, n_mean_imbl = imbalance_ratios(
                                                                target_cases)
    logging.info(f"Split {largest_class}. Mean IMbl: {n_mean_imbl} "
                 f"Stdev IMbl: {n_stdev_imbl}")
    return big_atomic_classes, target_cases, n_mean_imbl

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--case_info_path", "-i", type=str,
                        help="Path to load case information")
    parser.add_argument("--act_area_path", "-a", type=str,
                        help="Path to load act to area mapping")
    parser.add_argument("--section_chapter_path", "-s", type=str,
                        help="Path to load section to chapter mapping")
    parser.add_argument("--min_cases", "-m", type=int, default=50,
                        help="Minimum number of cases to retain a label")
    parser.add_argument("--imbl", "-b", type=float, default=25.0,
                        help="Mean imbalance ratio to achieve")
    parser.add_argument("--output_path", "-o", type=str,
                        help="Path to save generated data")

    args = parser.parse_args()
    set_logger(os.path.join(args.output_path, "get_balanced_targets"))
    logging.info("Passed arguments:")
    for name, value in vars(args).items():
        logging.info(f"{name}: {value}")

    with open(args.case_info_path, 'r') as f:
        case_info = json.load(f)

    with open(args.act_area_path, 'r') as f:
        act_areas = json.load(f)

    with open(args.section_chapter_path, 'r') as f:
        section_chapters = json.load(f)

    # Get reverse mapping
    area_acts = defaultdict(lambda: list())
    chapter_sections = defaultdict(lambda: list())
    # area to acts
    for act, areas in act_areas.items():
        for area in areas:
            area_acts[area].append(act)
    # chapter to acts
    for section, chapters in section_chapters.items():
        for chapter in chapters:
            chapter_sections[chapter].append(section)

    # Get present areas, acts, chapters and sections and their cases
    target_cases = defaultdict(lambda: list())
    present_areas = []
    present_acts = []
    present_chapters = []
    present_sections = []
    present_area_acts = defaultdict(lambda: set())
    present_act_chapters = defaultdict(lambda: set())
    present_chapter_sections = defaultdict(lambda: set())
    area_cases = defaultdict(lambda: list())
    act_cases = defaultdict(lambda: list())
    chapter_cases = defaultdict(lambda: list())
    section_cases = defaultdict(lambda: list())

    for case, info in case_info.items():
        for area in info["areas"]:
            # Start at highest granularity i.e. areas
            target_cases[area].append(case)
            present_areas.append(area)
            area_cases[area].append(case)
        for act in info["acts"]:
            present_acts.append(act)
            act_cases[act].append(case)
            for area in act_areas.get(act, []):
                present_area_acts[area].update([act])
        for chapter in info["chapters"]:
            present_chapters.append(chapter)
            chapter_cases[chapter].append(case)
            act = chapter.split("_")[0]
            present_act_chapters[act].update([chapter])
        for section in info["sections"]:
            present_sections.append(section)
            chapter = section_chapters.get(section, "")
            # HACKY
            # TODO: Fix at the area act chapter section annotation level
            if "Constitution" in section:
                logging.info(f"Fixing for {section}")
                present_chapters.append(chapter)
                present_act_chapters["Constitution"].update([chapter])
                chapter_cases[chapter].append(case)
            present_chapter_sections[chapter].update([section])
            section_cases[section].append(case)

    # Convert to dictionaries with frequencies
    present_areas = dict(Counter(present_areas))
    present_acts = dict(Counter(present_acts))
    present_chapters = dict(Counter(present_chapters))
    present_sections = dict(Counter(present_sections))
    big_atomic_classes = []
    non_atomic_usable_classes = [
            k for k, v in target_cases.items()
            if len(v) >= args.min_cases and
            k not in big_atomic_classes]

    # Define initial imbalance ratio
    max_imbl, min_imbl, stdev_imbl, mean_imbl = imbalance_ratios(target_cases)

    while len(non_atomic_usable_classes) > 0:
        # Get largest class
        largest = max([len(v) for k, v in target_cases.items()
                       if k not in big_atomic_classes])
        largest_class = [
                k for k, v in target_cases.items()
                if len(v) == largest and k not in big_atomic_classes]
        largest_class = largest_class[0]
        # Check what hierarchy largest class belongs to
        # and split accordingly
        if present_areas.get(largest_class, -1) != -1:
            big_atomic_classes, target_cases, mean_imbl = split_area(
                    target_cases, largest_class,
                    act_cases, present_area_acts,
                    args.min_cases, big_atomic_classes)
        elif present_acts.get(largest_class, -1) != -1:
            big_atomic_classes, target_cases, mean_imbl = split_area(
                    target_cases, largest_class,
                    chapter_cases, present_act_chapters,
                    args.min_cases, big_atomic_classes)
        elif present_chapters.get(largest_class, -1) != -1:
            big_atomic_classes, target_cases, mean_imbl = split_area(
                    target_cases, largest_class,
                    section_cases, present_chapter_sections,
                    args.min_cases, big_atomic_classes)
        else:
            logging.info(f"Largest class '{largest_class}' is either "
                         "an unsplittable class or a composite class")
            big_atomic_classes.append(largest_class)

        non_atomic_usable_classes = [
                k for k, v in target_cases.items()
                if len(v) > args.min_cases and
                k not in big_atomic_classes]

    logging.info(f"Dataset balanced to create {len(target_cases)} labels")
    case_targets = defaultdict(lambda: list())
    for label, cases in target_cases.items():
        for case in cases:
            case_targets[case].append(label)

    label_case_num = {
            k: len(v)
            for k, v in sorted(target_cases.items(),
                               key=lambda x: len(x[1]),
                               reverse=True)}

    with open(os.path.join(
              args.output_path, "label_case_info.json"), 'w') as f:
        json.dump(target_cases, f, indent=4)
    with open(os.path.join(
              args.output_path, "label_case_num.json"), 'w') as f:
        json.dump(label_case_num, f, indent=4)
    with open(os.path.join(
              args.output_path, "balanced_case_labels.json"), 'w') as f:
        json.dump(case_targets, f, indent=4)

if __name__ == "__main__":
    main()


#$ 마지막 체크 문자가 조건문 $#
import sys
input = sys.stdin.readline

S = list(input().rstrip())

stack = []

chk = ["P", "P", "A", "P"]

for i, c in enumerate(S):
    stack.append(c)

    while len(stack) > 3 and stack[-4:] == chk:
        for _ in range(4):
            stack.pop()
        stack.append("P")

if stack == ["P"]:
    print("PPAP")
else:
    print("NP")


def additional_problems(n, m, good_complexity, problems):
    index = 0
    count = 0

    while count < n and index < m:
        if problems[index] >= good_complexity[count]:
            count += 1
        index += 1

    return n - count

if __name__ == '__main__':
    line_1 = input().split()
    n = int(line_1[0])
    m = int(line_1[1])
    good_complexities = [int(_) for _ in input().split()]
    problems = [int(_) for _ in input().split()]

    print(additional_problems(n, m, good_complexities, problems))


import pygame
from random import *
from pygame.locals import *
from screen.screen2 import *
from screen.screen_key import *

SURFACE = pygame.display.set_mode([display_width, display_height])
pygame.init()
# 시작 화면 그리기

def start_screen(x, y):
    myImg = pygame.image.load(adress + 'ttpang1_bgr.PNG')
    SURFACE.blit(myImg, (x, y))

# 버튼

def button(x, y, w, h, ic, ac, strt, cstrt, action=None):
    mouse = pygame.mouse.get_pos()
    click = pygame.mouse.get_pressed()

    rect = pygame.Rect(x, y, w, h)
    on_button = rect.collidepoint(mouse)
    if on_button:
        pygame.draw.rect(SURFACE, ac, rect)
        SURFACE.blit(cstrt, cstrt.get_rect(center=rect.center))
    else:
        pygame.draw.rect(SURFACE, ic, (x, y, w, h))
        SURFACE.blit(strt, strt.get_rect(center=rect.center))

# 버튼 클릭 수행
    if on_button:
        if click[0] == 1 and action != None:
            if action == "continue":
                mode_select_screen()  # 다음모드로 넘어가게
            elif action == "quit":
                pygame.quit()

# 버튼이미지로딩
strt = pygame.image.load(adress + "starticon.png").convert_alpha()
cstrt = pygame.image.load(adress + "clickedStartIcon.png").convert_alpha()
qt = pygame.image.load(adress + "quiticon.png").convert_alpha()
cqt = pygame.image.load(adress + "clickedQuitIcon.png").convert_alpha()

def screen1():
    # event handling logic
    pygame.init()
    finished = False
    # 색깔 : 흰색만 사용
    WHITE = (255, 255, 255)
    # pygame 창이름 설정
    pygame.display.set_caption("시간표 테트리스, 시간표팡!")
    while not finished:
        for event in pygame.event.get():
            if event.type == QUIT:
                finished = True
                pygame.quit()
                quit()

        SURFACE.fill((255, 255, 255))  # 배경색 지정
        start_screen(x, y)  # 이미지 그리기
        button(250, 480, 180, 68, WHITE, WHITE, strt, cstrt, "continue")
        button(870, 480, 180, 68, WHITE, WHITE, qt, cqt, "quit")
        pygame.display.update()

if __name__ == '__main__':
    screen1()


#! python3
# -*- coding:utf-8 -*-
'''
  exception2.py
    Basics of exception handling in python.
    Processing flow when exception has occurred.
'''

import sys
import traceback

def test_exception(number):
    try:
        return 100 / number

    except ZeroDivisionError as e:
        print("zero division has occured")
        raise e
    finally:
        print("処理が終了しました")

try:
    test_exception(0)

except ZeroDivisionError as e:
    sys.stderr.write('0で割り算できません')
    print(traceback.format_exc())

# 処理の流れ
# ゼロ除算発生
# メソッド内のexcept句が実行される
# finallyが実行される
# raise eによって呼び出し元に委譲される
# 呼び出し元のexcept句が実行される
# raise eをしていない場合は関数を囲うtry句ではキャッチされない。


import unittest
import time

from mu.integration_tests import int_test
from mu.sims.bms_carrier import BmsCarrier
from mu.sims.sub_sims.mcp23008 import NUM_MCP23008_PINS, MCP23008_KEY

class TestMcp23008(int_test.IntTest):
    def setUp(self):
        super().setUp()
        self.board = self.manager.start(BmsCarrier, proj_name='smoke_mcp23008')

    def test_mcp23008(self):
        time.sleep(0.1)
        for x in range(NUM_MCP23008_PINS):  # test all pins init'd
            self.board.sub_sim('mcp23008').assert_pin_state(MCP23008_KEY, x, 1)
        time.sleep(0.1)
        for x in range(NUM_MCP23008_PINS):  # test all pins toggled
            self.board.sub_sim('mcp23008').assert_pin_state(MCP23008_KEY, x, 0)

if __name__ == '__main__':
    unittest.main()


def _get_execution_state_with_watch(self, topologyName, callback, isWatching):
    """
    Helper function to get execution state with
    a callback. The future watch is placed
    only if isWatching is True.
    """
    path = self.get_execution_state_path(topologyName)
    if isWatching:
      LOG.info("Adding data watch for path: " + path)

    # pylint: disable=unused-variable, unused-argument
    @self.client.DataWatch(path)
    def watch_execution_state(data, stats):
      """ invoke callback to watch execute state """
      if data:
        executionState = ExecutionState()
        executionState.ParseFromString(data)
        callback(executionState)
      else:
        callback(None)

      # Returning False will result in no future watches
      # being triggered. If isWatching is True, then
      # the future watches will be triggered.
      return isWatching