import tkinter as tk
import re

class LetterCell:
    """Store an item for a linked list."""
    def __init__(self, letter, next):
        self.letter = letter
        self.next = next

    def insert_after(self, letter):
        """ Insert a new cell after this one."""
        cell = LetterCell(letter, self.next)
        self.next = cell

    @staticmethod
    def from_string(txt):
        """ Return a list that represents a string."""
        # Create the sentinels.
        top_sentinel = LetterCell("<sentinel>", None)

        # Make it into a list.
        first_cell = top_sentinel
        for ch in txt:
            first_cell.insert_after(ch)
            first_cell = first_cell.next

        # Return the top sentinel.
        return top_sentinel

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

    def to_string(self):
        txt = ""
        while self != None:
            txt += self.letter
            self = self.next
        return txt

    def is_palindrome_reverse(self):
        """
        Use a reversed list to return True if the
        cells after this one form a palindrome.
        """
        # Make a reversed list.
        new_top = None
        old_cell = self
        while old_cell != None:
            new_cell = LetterCell(old_cell.letter, new_top)
            new_top = new_cell
            old_cell = old_cell.next

        # Compare the lists.
        cell1 = self
        cell2 = new_top
        while cell1 != None:
            if cell1.letter != cell2.letter:
                return False
            cell1 = cell1.next
            cell2 = cell2.next

        return True

    def is_palindrome_reverse_half(self):
        """
        Use half a reversed list to return True if the
        cells after this one form a palindrome.
        """
        # Lists with 0 or 1 letters are palindromes.
        if (self.next == None) or (self.next.next == None):
            return True

        # Find the list's halfway point.
        second_half = self.find_second_half(False)

        # Make a reversed list.
        last_cell = None
        old_cell = second_half
        while old_cell != None:
            new_cell = LetterCell(old_cell.letter, last_cell)
            last_cell = new_cell
            old_cell = old_cell.next

        # Compare the lists.
        cell1 = last_cell
        cell2 = self
        while cell1 != None:
            if cell1.letter != cell2.letter:
                return False
            cell1 = cell1.next
            cell2 = cell2.next
        return True

    def find_second_half(self, count_middle_cell):
        """
        Return the first cell in the second half of the list.
        If the list has an odd number of cells and
        count_middle_cell is True, return the middle cell.
        If the list has an odd number of cells and
        count_middle_cell is False, return the cell after the middle.
        """
        # Find the list's halfway point.
        slow_cell = self
        fast_cell = slow_cell
        while True:
            # Move slow_cell.
            slow_cell = slow_cell.next

            # Move fast_cell.
            fast_cell = fast_cell.next
            if fast_cell == None:
                # The list has an even number of items and
                # slow_cell is the first cell in the second half.
                return slow_cell

            fast_cell = fast_cell.next
            if fast_cell == None:
                # The list has an odd number of items
                # and slow_cell is the middle item.
                if not count_middle_cell:
                    slow_cell = slow_cell.next
                return slow_cell

    def is_palindrome_recurse(self):
        """
        Recursively see if the
        cells after this one form a palindrome.
        """
        # Find the start of the second half.
        second_half = self.find_second_half(False)

        # Recursively compare the second and first halves.
        first_half = self
        result, first_half = self.compare_halves(first_half, second_half)
        return result

    def compare_halves(self, first_half, second_half):
        """
        Recursively compare the second and first halves.
        Return a True/False result and an updated value for first_half.
        """

        # See if we're at the end of the second half.
        if second_half.next == None:
            # Compare the last cell in the second half
            # to the first cell in the first half.
            our_result = (second_half.letter == first_half.letter)

            # Move first_half to the next item.
            first_half = first_half.next

            # Return so the next level up can continue checking.
            return our_result, first_half

        # We are not at the end of the second half.
        # Recursively check one cell farther in the second half.
        # If the recursive call returns False,
        # this is not a palindrome.
        our_result, first_half = self.compare_halves(first_half, second_half.next)
        if not our_result:
            return False, None

        # Compare the next cells in the two halves.
        if first_half.letter != second_half.letter:
            return False, None

        # If we get this far, it is a palindrome so far.
        # Move first_half to the next item.
        first_half = first_half.next

        # So far so good.
        return True, first_half

class App:
    def kill_callback(self):
        self.window.destroy()

    def __init__(self):
        self.window = tk.Tk()
        self.window.title("list_is_palindrome")
        self.window.protocol("WM_DELETE_WINDOW", self.kill_callback)
        self.window.geometry("300x160")

        frame = tk.Frame(self.window)
        frame.pack(padx=10, pady=10, fill=tk.BOTH)
        frame.columnconfigure(1, weight=1)

        label = tk.Label(frame, text="String:")
        label.grid(row=0, column=0, padx=5, pady=2, sticky=tk.W)
        self.string_entry = tk.Entry(frame)
        self.string_entry.grid(row=0, column=1, padx=5, pady=2, sticky=tk.W+tk.E)
        self.string_entry.insert(0, "Drab as a fool, aloof as a bard")

        check_button = tk.Button(frame, text="Check", width=8, command=self.check)
        check_button.grid(row=1, column=0, columnspan=2, pady=10)

        label = tk.Label(frame, text="Reverse:")
        label.grid(row=2, column=0, padx=5, pady=2, sticky=tk.W)
        self.reverse_entry = tk.Entry(frame)
        self.reverse_entry.grid(row=2, column=1, padx=5, pady=2, sticky=tk.W+tk.E)

        label = tk.Label(frame, text="Reverse Half:")
        label.grid(row=3, column=0, padx=5, pady=2, sticky=tk.W)
        self.reverse_half_entry = tk.Entry(frame)
        self.reverse_half_entry.grid(row=3, column=1, padx=5, pady=2, sticky=tk.W+tk.E)

        label = tk.Label(frame, text="Recursive:")
        label.grid(row=4, column=0, padx=5, pady=2, sticky=tk.W)
        self.recursive_entry = tk.Entry(frame)
        self.recursive_entry.grid(row=4, column=1, padx=5, pady=2, sticky=tk.W+tk.E)

        # Bind some keys.
        self.window.bind('<Return>', (lambda e, button=check_button: check_button.invoke()))

        # Force focus so Alt+F4 closes this window and not the Python shell.
        self.string_entry.focus_force()
        self.window.mainloop()

    def check(self):
        """ See if the string is a palindrome."""
        # Make the string into a list.
        txt = self.string_entry.get().upper()
        regex = re.compile("[^A-Z]")
        txt = regex.sub("", txt)
        top_sentinel = LetterCell.from_string(txt)

        # Check for a palindrome in various ways.
        self.reverse_entry.delete(0, tk.END)
        self.reverse_half_entry.delete(0, tk.END)
        self.recursive_entry.delete(0, tk.END)

        if top_sentinel.next.is_palindrome_reverse():
            self.reverse_entry.insert(0, "Is a palindrome")
        else:
            self.reverse_entry.insert(0, "Not a palindrome")

        if top_sentinel.next.is_palindrome_reverse_half():
            self.reverse_half_entry.insert(0, "Is a palindrome")
        else:
            self.reverse_half_entry.insert(0, "Not a palindrome")

        if top_sentinel.next.is_palindrome_recurse():
            self.recursive_entry.insert(0, "Is a palindrome")
        else:
            self.recursive_entry.insert(0, "Not a palindrome")

if __name__ == '__main__':
    app = App()

# app.root.destroy()


import urllib.request as uuuu

def transform(a,key):
	b = (a+key)%256
	return b

def reform(b,key):
	a = (b-key)%256
	return(a)

print("encrypt or decrypt")
a = input()

if(a=="encrypt"):
	old = (open("sample.txt")).read()
	new = ""
	key=int(input("enter key"))
	for i in old:
		a = ord(i)
		b = chr(transform(a,key))
		new += b

	(open("sample_change.txt", 'w')).write(new)

elif(a=="decrypt"):
	print("normal or brute or freq")
	a = input()
	old = (open("sample_change.txt")).read()
	new = ""
	if(a=="normal"):
		for i in old:
			a = ord(i)
			key = int(input("enter key"))
			b = chr(reform(a,key))
			new += b

		(open("sample_returns.txt", 'w')).write(new)

	elif(a=="brute"):
		key = 0
		while(a!="ok"):
			new = ""
			print("key = "+str(key)+"---------------------------------------------------------------------")
			for i in old:
				a = ord(i)
				b = chr(reform(a,key))
				new += b
			print(new)
			print("is it ok?")
			a = input()
			key+=1
		(open("sample_returns.txt", 'w')).write(new)

	elif(a=="freq"):
		D = {}
		internet = " etaoinsrhdlucmfywgpbvkxqjz0123456789"
		for i in old:
			try:
				D[i] = D[i]+1
			except:
				D[i] = 1
		maxn = 0
		maxc = ""
		for i in D:
			if(D[i]>maxn):
				maxn = D[i]
				maxc = i
		print("max is = "+str(maxc)+"-------------------------------------------------")

		for i in internet:
			a = ord(i)
			b = ord(maxc)
			key = (b-a)%256
			print("key = " +str(key)+"------------------------------------------------------------------")
			new = ""
			for j in old:
				a = ord(j)
				b = chr(reform(a,key))
				new += b
			print(new)
			print("is it ok")
			z = input()
			if(z=="ok"):
				print("key = "+str(key))
				break


import random
import numpy as np
import matplotlib.pyplot as plt

# number of random walkers
W = 200

# total number of steps taken by each walker
N = 50

#probabilities
prob = np.array([1,2])

r = np.zeros(W)    # right step variable for all the walkers, zero assigned initially
l = np.zeros(W)	   # left step variable for all the walkers, zero assigned initially
avg = np.zeros(N)  # average of right distances of all the walkers at every time interval till N steps
var = np.zeros(N)  # varience fo right distances of all the walkers at every time interval till N steps

# defining a function which can be called when ever a step is to be made by all the walkers
def step(r,l,W):
	# for each and every walker found out weather he goes right or left in for loop
	for e in range(W): # e is for loop variable and W is number of walkers
		a = random.choice(prob) # generating a random intezer between 1 and 2
		if a == 1 :             # if 0 is obtained that particular walker numbered e goes right
			r[e]=r[e]+1     # number of right steps taken by that walker is incremented
	#		print('right')
		elif a == 2 :           # if 1 is obtained that particular walker numbered e goes left
			l[e]=l[e]+1     # number of right steps taken by that walker is incremented
	#		print('left')

# taking N number of steps and calculating avg and var after each step
for i in range(N):
	step(r,l,W)          # All the walkers take one random step
	avg[i] = np.mean(r)  # Average/mean of positions of all the walkers after i steps or time
	var[i] = np.var(r)   # Varience of positions of all the walkers after i steps or time

# plotting the mean and varience after corresponding number of steps

plt.figure('Mean')
plt.plot(avg,'g-')
plt.title('Mean vs number of steps')
plt.xlabel('Number of steps')
plt.ylabel('Mean of right steps of all the walkers')

plt.figure('Varience')
plt.plot(var , 'r-')
plt.title('Varience vs number of steps')
plt.xlabel('Number of steps')
plt.ylabel('Varience of right steps of all the walkers')

plt.show()


import numpy as np

import pprint
pp = pprint.PrettyPrinter(indent=4)

a_z1 = np.ones((3,3),dtype='uint16')
a_z2 = a_z1 * 2
a_z3 = a_z1 * 3

a_z1 = np.array([[98,	99,	98],
				[101,	105,	104],
				[99,	104,	103]], dtype=np.float)

a_z2 = np.array([[89,	91,	95],
				[95,	99,	103],
				[97,	102,	104]], dtype=np.float)

a_z3 = np.array([[80,	80,	86],
                [86,	86,	91],
                [90,	91,	94]], dtype=np.float)

a_3D = np.vstack([a_z1, a_z2, a_z3]).reshape(3,3,3)

print("a_3D",a_3D.shape, a_3D.dtype)
pp.pprint(a_3D)

spacing = [7.5,1,1]
a_grad = np.gradient(a_3D,*spacing)

print("a_dz",a_grad[0].shape)
pp.pprint(a_grad[0])


#!/usr/bin/python
#
# Copyright 2018-2022 Polyaxon, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from polyaxon.managers.base import BaseConfigManager
from polyaxon.schemas.cli.cli_config import CliConfig
from polyaxon.utils.tz_utils import now

class CliConfigManager(BaseConfigManager):
    """Manages access cli configuration .cli file."""

    VISIBILITY = BaseConfigManager.VISIBILITY_GLOBAL
    CONFIG_FILE_NAME = ".cli"
    CONFIG = CliConfig

    @classmethod
    def reset(
        cls,
        current_version=None,
        installation=None,
        compatibility=None,
        log_handler=None,
        last_check=None,
    ):
        if not any(
            [current_version, installation, compatibility, log_handler, last_check]
        ):
            return
        cli_config = cls.get_config_or_default()
        if current_version is not None:
            cli_config.current_version = current_version
        if installation is not None:
            cli_config.installation = installation
        if compatibility is not None:
            cli_config.compatibility = compatibility
        if log_handler is not None:
            cli_config.log_handler = log_handler
        if last_check is not None:
            cli_config.last_check = cli_config.get_last_check(last_check)

        CliConfigManager.set_config(config=cli_config)
        return cli_config

    @classmethod
    def should_check(cls, interval: int = None):
        config = cls.get_config_or_default()
        should_check = config.should_check(interval=interval)
        if should_check:
            cls.reset(last_check=now())
        return should_check

    @classmethod
    def get_config_from_env(cls):
        pass


# HW2-Logistic Regression
import sys
import numpy as np
import pandas as pd
import csv
import matplotlib.pyplot as plt

### Parameters ###
RAWDATA_PATH = './dataset/train.csv'
OBSERVE_PATH = './dataset/test.csv'
SUBMISSION_PATH = './dataset/sample_submission.csv'
RAW_FEATURE_PATH = './dataset/X_train' # after one-hot encoding with raw data
RAW_LABEL_PATH = './dataset/Y_train'
OB_FEATURE_PATH = './dataset/X_test'
#RAWDATA_PATH = sys.argv[1]
#OBSERVE_PATH = sys.argv[2]
#SUBMISSION_PATH = sys.argv[3]
MODE_PATH = './model'
HIS_PATH = './history'
PIC_PATH = './picture'
##################

class Data():
    def __init__(self):
        self.data = {}
        self.feature = {}
    # row : number of data as 'n', col : number of feature as 'm'
    def Read(self,name,path):
        with open(path,newline = '',encoding='utf-8') as csvfile:
            rows = np.array(list(csv.reader(csvfile)))
            self.data[name] = rows[1:].astype(float) # setting the data
            self.feature[name] = rows[0].tolist()

# Data Processing - Normalization, One-hot encoding, discreate presentation
def Normalization(x,method='Rescaling',mean_or_max='None',std_or_min='None',trans=False):
    if trans == False:
        if method == 'Rescaling':
            mean_or_max = np.max(x,axis=0).reshape(1,-1)
            std_or_min = np.min(x,axis=0).reshape(1,-1)
        elif method == 'Standardization':
            mean_or_max = np.mean(x, axis = 0).reshape(1,-1)
            std_or_min = np.std(x, axis = 0).reshape(1,-1)
    if method == 'Rescaling':
        x = (x - std_or_min) / (mean_or_max - std_or_min)
    elif method == 'Standardization':
        x = (x-mean_or_max) / std_or_min
    if trans:
        return x
    else:
        return x,mean_or_max,std_or_min

def Split_train_val(x,y,train_rate=0.7):
    perm = np.random.permutation(len(y)) # Shuffle
    x, y = x[perm], y[perm]
    split_pos = np.round(len(y)*train_rate).astype('int32')
    return x[:split_pos], x[split_pos:], y[:split_pos], y[split_pos:]

def Fit(X,y,val=None,validation_split=0.0,bias=True,weights='zeros',
      loss='rmse',opt='vanilla',act='sigmoid',regularization=None,lamda=0.0001,
      learning_rate=0.001,decay='exp',decay_rate=1.0,
      epochs=1,batch_size=None,monitor='loss',patience=None,save_model=True):

    def initial(X,weights,bias):
        dim = X.shape[1]
        if bias:
            dim = dim + 1
            X = np.concatenate((np.ones((X.shape[0],1)),X),axis=1).astype(float)
        if weights == 'zeros':
            w = np.zeros(shape=(dim, 1))
        elif weights == 'random':
            w = np.random.rand(dim, 1)
        return X, w

    # Activation
    def activation(z,act):
        if act == 'sigmoid':
            return np.clip(1 / (1.0 + np.exp(-z)), 1e-6, 1-1e-6)
        else: # linear
            return z

    # Regularization
    def regular_term(mount,select,lamda,w):
        if mount == 'loss_value':
            if select == 'l1':
                reg = lamda * np.sum(w)
            elif select == 'l2':
                reg = lamda * np.sum(w**2)
            elif select == 'non-negative-l1':
                reg = lamda * np.sum(np.abs(w))
            elif select == 'non-negative-l2':
                reg = lamda * np.sum(np.abs(w)**2)
            elif select == None:
                reg = np.sum(np.zeros(w.shape))
        elif mount == 'optimize':
            if select == 'non-negative-l1' or 'l1':
                reg = lamda
            elif select == 'l2':
                reg = 2. *lamda * w
            elif select == 'non-negative-l2':
                reg = 2. *lamda * np.abs(w)
            elif select == None:
                reg = 0.
        return reg

    # Loss function
    def loss_value(X,y,w,loss,act):
        reg = regular_term('loss_value',regularization,lamda,w)
        if loss == 'mse':
            pred = activation(X.dot(w),act)
            square_error = (y-pred)**2
            loss_value = square_error.sum()/len(y) # mse
        elif loss == 'rmse':
            pred = activation(X.dot(w),act)
            square_error = (y-pred)**2
            mse = square_error.sum()/len(y) # mse
            loss_value = np.power(mse,0.5) # rmse
        elif loss == 'cross_entropy':
            pred = activation(X.dot(w),act).reshape(1,-1)
            cross_entropy = -np.dot(np.log(pred),y)-np.dot(np.log(1-pred),(1-y)) # shape=(1,1)
            loss_value = cross_entropy[0] / len(y) # cross_entropy
        return (loss_value + reg)

    # Optmize function
    def update_parameters(grad,w,sigma,m,t,opt,b1=0.9,b2=0.999):
        EPSILON = 1e-08 # To avoid thah sigma divied by nan or zero
        reg = regular_term('optimize',regularization,lamda,w)
        grad += reg
        if opt == 'ada':
            sigma += np.sqrt(grad**2)
            w -= grad * learning_rate / (sigma + EPSILON)
        elif opt == 'RMSProp':
            sigma = np.sqrt(b2 * sigma**2 + (1-b2) * grad**2)
            w -= grad * learning_rate / (sigma + EPSILON)
        elif opt == 'Adam':
            m = (b1 * m + (1-b1) * grad)
            sigma = (b2 * sigma + (1-b2) * grad**2)
            m_t = m / (1 - b1**t)
            sigma_t =  sigma / (1 - b2**t)
            w -= m_t * learning_rate / (np.sqrt(sigma_t) + EPSILON)
        else:
            m = b1 * m + learning_rate * grad # momentum
            w -= m
        return w, sigma, m

    # Decay Learning rate
    def decay_learing_rate(lr,epoch,epochs,decay,decay_rate):
        if decay == 'exp':
            decay_lr = lr * decay_rate**(epochs/epoch)
        elif decay == 'natural_exp':
            decay_lr = lr * np.exp(-decay_rate*epochs/epoch)
        elif decay == 'sqrt':
            decay_lr = lr/np.sqrt(epoch)
        else:
            decay_lr = lr
        return decay_lr

    # Mini-batch
    def get_mini_batch(X,y,batch_size):
        mini_batches = []
        data = np.hstack((X,y))
        for i in range(int(np.floor(len(y)/batch_size))):
            mini_batch = data[i * batch_size:(i + 1)*batch_size, :]
            X_mini = mini_batch[:, :-1]
            Y_mini = mini_batch[:, -1].reshape((-1, 1))
            mini_batches.append((X_mini, Y_mini))
        if data.shape[0] % batch_size != 0:
            mini_batch = data[i * batch_size:data.shape[0]]
            X_mini = mini_batch[:, :-1]
            Y_mini = mini_batch[:, -1].reshape((-1, 1))
            mini_batches.append((X_mini, Y_mini))
        return mini_batches

    # Split Training and Validation Set
    if val:
        X_t,X_v,y_t,y_v = Split_train_val(X,y,(1-validation_split))
    else:
        X_t,X_v,y_t,y_v = X,X,y,y

    # Fitting summary
    print('training sample:',len(X_t),' validation sample:',len(X_v))

    # Initialization
    X_t, w = initial(X_t,weights,bias)
    X_v, _ = initial(X_v,weights,bias)
    ## Set model parameter
    sigma = None
    m = 0
    if opt == 'sgd':
        batch_size = 1
    elif opt == 'ada' or 'RMSProp' or 'Adam':
        sigma = np.zeros(w.shape)
    # Mini-Batch Training
    cost_history, acc_history = [], []
    see_best,see = None,0
    best_w = np.copy(w) # if we use '=', it will assign the same address.
    # Decay learning rate
    if batch_size != None:
        gobal_t = int(np.floor(len(y_t)/batch_size))
    for epoch in range(1,epochs):
        # Parameter
        t = 1 # for Adam , adaptive learning depend on time && for decay learning rate
        # Shuffle
        perm = np.random.permutation(len(y_t))
        X_t, y_t = X_t[perm], y_t[perm]

        if batch_size == None:
            # Update learning
            learning_rate = decay_learing_rate(learning_rate,epoch,epochs,decay,decay_rate)
            # Update gradient
            pred = activation(X_t.dot(w),act)
            grad = -2. * np.dot(X_t.T,y_t-pred)
            # Update weights
            w, sigma, m = update_parameters(grad,w,sigma,m,epoch,opt)
        # Using mini-batch, get batch data
        else:
            mini_batches = get_mini_batch(X_t, y_t, batch_size)
            for mini_batch in mini_batches:
                X_mini, y_mini = mini_batch
                # Update learning
                learning_rate = decay_learing_rate(learning_rate,t,gobal_t,decay,decay_rate)
                # Udate gradient
                pred = activation(X_mini.dot(w),act)
                grad = -2. * np.dot(X_mini.T,y_mini-pred)
                # Update weights
                w, sigma, m = update_parameters(grad,w,sigma,m,t,opt)
                t+=1
        # Cost
        cost = loss_value(X_t,y_t,w,loss,act) # on training set
        cost_v = loss_value(X_v,y_v,w,loss,act) # on validation ser
        cost_history.append((cost,cost_v))
        # Accuracy
        pred = activation(X_t.dot(w),act)
        classify = np.round(pred)
        acc = accuracy(classify, y_t)
        pred = activation(X_v.dot(w),act)
        classify = np.round(pred)
        acc_v = accuracy(classify, y_v)
        acc_history.append((acc,acc_v))
        print('Epoch:'+str(epoch) + '/' + str(epochs),'--loss: %.3f' % cost," val loss: %.3f" % cost_v, end=' ')
        print('--acc: %.3f' % acc,'-val_acc: %.3f' % acc_v)

        # Early Stopping - Avoid Overfitting
        if patience != None:
            see += 1
            if monitor == 'loss':
                moni = cost
            elif monitor == 'acc':
                moni = acc
            if see_best == None:
                see_best = np.round(moni,decimals=3)
            elif (see_best > moni and monitor == 'loss') or (see_best < moni and monitor =='acc'):
                see_best = np.round(moni,decimals=3)
                see = 0
                best_w = np.copy(w)
                continue
            elif (see_best <= moni and monitor == 'loss') or (see_best >= moni and monitor =='acc'):
                print('The current '+monitor+' %.3f'%moni,'is not best than',see_best)
                if see < patience:
                    continue
                else:
                    print('early stopping',see,'/',patience)
                    break
    # Save the best model
    if save_model != False:
        if patience != None:
            np.save(MODE_PATH+'/'+save_model+'_weight.npy',best_w) # save best weight
        else:
            np.save(MODE_PATH+'/'+save_model+'_weight.npy',w)
        np.save(HIS_PATH+'/'+save_model+'_history.npy',np.asarray(cost_history)) # save history
    return w, np.asarray(cost_history), np.asarray(acc_history)

def accuracy(pred, y):
    acc = np.sum(pred == y)/len(pred)
    return acc

def Plot_loss_history(history,save_model):
    plt.clf()
    loss_t, loss_v = history[:,0], history[:,1]
    plt.plot(loss_t,'b')
    plt.plot(loss_v,'r')
    if "loss" in save_model:
        plt.legend(['loss', 'val_loss'], loc="upper left")
        plt.ylabel("loss")
    elif "acc" in save_model:
        plt.legend(['acc', 'val_acc'], loc="upper left")
        plt.ylabel("acc")
    plt.xlabel("epoch")
    plt.title("Training Process")
    if save_model == False:
        plt.savefig(PIC_PATH+'/_history.png')
    else:
        plt.savefig(PIC_PATH+'/'+save_model+'_history.png')
    plt.show()
    plt.close()

def Sample():
    ## Read in raw data
    raw = Data()
    raw.Read('X_raw',RAW_FEATURE_PATH)
    raw.Read('y_raw',RAW_LABEL_PATH)

    col = [range(106)]
    nor,mean,std = Normalization(raw.data['X_raw'][:,col],'Standardization')
    raw.data['X_raw'][:,col] = nor
    X_train, y_train = raw.data['X_raw'], raw.data['y_raw']

    ##  Training
    val=True
    validation_split=0.1155
    bias=True
    weights='zeros'
    loss='cross_entropy'
    opt='Adam'
    act='sigmoid'
    regularization='non-negative-l2'
    lamda= 0.0001
    learning_rate=0.001
    decay=None
    decay_rate=1
    epochs=1024
    batch_size=16
    monitor='acc'
    patience=128
    save_model='sample'

    model, cost_history, acc_history\
        = Fit(X_train,y_train,val,validation_split,bias,weights,
              loss,opt,act,regularization,lamda,learning_rate,
              decay,decay_rate,epochs,batch_size,
              monitor,patience,save_model)

#    ##Load model
#    model = np.load(MODE_PATH+'/'+save_model+'_weight.npy')

    # Plot the history
    Plot_loss_history(cost_history,save_model+'_loss_')
    Plot_loss_history(acc_history,save_model+'_acc_')

    ## Read in Observe set
    ob = Data()
    ob.Read('X_test',OB_FEATURE_PATH)
    ob.data['X_test'][:,col] = Normalization(ob.data['X_test'][:,col],'Standardization',mean,std,trans=True)
    ob_X_p = ob.data['X_test']

    # Add the bias-term to ob_X_p
    if bias:
        ob_X_p = np.concatenate((np.ones(shape = (ob_X_p.shape[0],1)),ob_X_p),axis = 1).astype(float)

    # Predict
    ob_y_z = ob_X_p.dot(model)
    ob_y_p = np.clip(1 / (1.0 + np.exp(-ob_y_z)), 1e-6, 1-1e-6)
    ob_y_c = np.round(ob_y_p)

    ## Write file
    print('Submission')
    with open(SUBMISSION_PATH,"w") as f:
        f.write('id,label\n')
        for i,value in enumerate(ob_y_c):
            f.write('%d,%d\n' %(i+1, value))

def Ensemble(Num):
    ## Read in raw data
    raw = Data()
    raw.Read('X_raw',RAW_FEATURE_PATH)
    raw.Read('y_raw',RAW_LABEL_PATH)

    norm_col = [range(106)]
    nor,mean,std = Normalization(raw.data['X_raw'][:,norm_col],'Standardization')
    raw.data['X_raw'][:,norm_col] = nor
    X_train, y_train = raw.data['X_raw'], raw.data['y_raw']

    ## Ensemble Learning
    for i in range(1,Num+1):
        # Bagging
        sample_idx = np.random.choice(X_train.shape[0],X_train.shape[0])
        X_train , y_train = X_train[sample_idx], y_train[sample_idx]

        # Dropout - drop the weight
#        dropout_rate = 0.2
#        drop_feature = np.random.randint(1,X_train.shape[1],size=int(X_train.shape[1]*dropout_rate))
#        X_train[:,drop_feature] = np.full([X_train.shape[0],len(drop_feature)], np.nan)
#        X_train[:,drop_feature] = np.full([X_train.shape[0],len(drop_feature)], 0)

        print('---Training with',i,'model---')
        ##  Training
        val=True
        validation_split=0.3
        bias=True
        weights='zeros'
        loss='cross_entropy'
        opt='Adam'
        act='sigmoid'
        regularization='non-negative-l2'
        lamda= 0.0007
        learning_rate=0.001
        decay=None
        decay_rate=1
        epochs=128
        batch_size=32
        monitor='acc'
        patience=16
        save_model='sample_'+str(i)

        model, cost_history, acc_history\
            = Fit(X_train,y_train,val,validation_split,bias,weights,
                  loss,opt,act,regularization,lamda,learning_rate,
                  decay,decay_rate,epochs,batch_size,
                  monitor,patience,save_model)

    ## Read in Observe set
    ob = Data()
    ob.Read('X_test',OB_FEATURE_PATH)
    ob.data['X_test'][:,norm_col] = Normalization(ob.data['X_test'][:,norm_col],'Standardization',mean,std,trans=True)
    ob_X_p = ob.data['X_test']

    # Add the bias-term to ob_X_p
    if bias:
        ob_X_p = np.concatenate((np.ones(shape = (ob_X_p.shape[0],1)),ob_X_p),axis = 1).astype(float)

    ## Ensmeble Predict
    result = []
    for i in range(1,Num+1):
        save_model='sample_'+str(i)
        # Load model
        model = np.load(MODE_PATH+'/'+save_model+'_weight.npy')
        # Predict
        ob_y_z = ob_X_p.dot(model)
        ob_y_p = np.clip(1 / (1.0 + np.exp(-ob_y_z)), 1e-6, 1-1e-6)
        ob_y_c = np.round(ob_y_p).reshape(-1,)
        result.append(ob_y_c)

    # Voting
    result = np.asarray(result)
    vot = np.sum(result,axis=0)
    half_people = int(result.shape[0] / 2)
    result = np.asarray([vot > half_people],dtype='int').reshape(-1,1)

    ## Write file
    print('Submission...')
    with open(SUBMISSION_PATH,"w") as f:
        f.write('id,label\n')
        for i,value in enumerate(result):
            f.write('%d,%d\n' %(i+1, value))
    print('Done...!')

if __name__ == '__main__':
    Ensemble(20)


#!/usr/bin/env python

from __future__ import print_function
import sys
import os
from argparse import ArgumentParser, SUPPRESS
import cv2
import time
import logging as log

from openvino.inference_engine import IENetwork, IECore

def main():

    model_xml = "model.xml"
    model_bin = "model.bin"

    ie = IECore()
    net=ie.read_network(model=model_xml, weights=model_bin)

    input_blob = next(iter(net.inputs))

    feed_dict = {}

    out_blob = next(iter(net.outputs))

    exec_net = ie.load_network(network=net, num_requests=2, device_name="CPU")

    n, c, h, w = net.inputs[input_blob].shape

    cap = cv2.VideoCapture("road.mp4")

    cur_request_id = 0
    next_request_id = 1

    with open('labels.txt', 'r') as f:
        labels_map = [x.strip() for x in f]

    ret, frame = cap.read()
    frame_h, frame_w = frame.shape[:2]

    #Open file for writing video .avi format
    out_video = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_w,frame_h))

    #Define numbers to each frame
    frame_num = 0

    while cap.isOpened():

        ret, next_frame = cap.read()

        #Print Frame number
        sys.stdout.write("\nFrame  " + str(frame_num)+'       ')
        frame_num = frame_num + 1

        #Slow down a little..
        time.sleep(0.2)

        if ret:
            frame_h, frame_w = frame.shape[:2]
        if not ret:
            break

        in_frame = cv2.resize(next_frame, (w, h))
        in_frame = in_frame.transpose((2, 0, 1))
        in_frame = in_frame.reshape((n, c, h, w))
        feed_dict[input_blob] = in_frame
        exec_net.start_async(request_id=next_request_id, inputs=feed_dict)

        if exec_net.requests[cur_request_id].wait(-1) == 0:
            res = exec_net.requests[cur_request_id].outputs[out_blob]
            for obj in res[0][0]:
                if obj[2] > 0.5:
                    xmin = int(obj[3] * frame_w)
                    ymin = int(obj[4] * frame_h)
                    xmax = int(obj[5] * frame_w)
                    ymax = int(obj[6] * frame_h)
                    class_id = int(obj[1])

                    #Print Detected classes
                    sys.stdout.write(str(class_id)+'  ')

                    color = (min(class_id * 25, 255), min(class_id * 60, 255), min(class_id * 5, 255))
                    cv2.rectangle(frame, (xmin, ymin), (xmax, ymax), color, 2)
                    det_label = labels_map[class_id] if labels_map else str(class_id)
                    cv2.putText(frame, det_label + ' ' + str(round(obj[2] * 100, 1)) + ' %', (xmin, ymin - 7),
                                cv2.FONT_HERSHEY_COMPLEX, 0.6, color, 1)

        #write next frame to video file.
        out_video.write(frame)

        cur_request_id, next_request_id = next_request_id, cur_request_id
        frame = next_frame
        frame_h, frame_w = frame.shape[:2]

        key = cv2.waitKey(1)
        if key == 27:
            break

    cv2.destroyAllWindows()

if __name__ == '__main__':
    sys.exit(main() or 0)


# Быстрая сортировка Хоара

import time

def quicksort(alist, start, end):
    if end - start > 1:
        p = partition(alist, start, end)
        quicksort(alist, start, p)
        quicksort(alist, p + 1, end)

def partition(alist, start, end):  # разделение
    pivot = alist[start]  # точка опоры
    i = start + 1
    j = end - 1

    while True:
        while (i <= j and alist[i] <= pivot):
            i = i + 1
        while (i <= j and alist[j] >= pivot):
            j = j - 1

        if i <= j:
            alist[i], alist[j] = alist[j], alist[i]
        else:
            alist[start], alist[j] = alist[j], alist[start]
            return j

print('Какое пожелаете количество элементов массива?')
N = int(input())  # указываем файл с каким кол-вом чисел хотим открыть

with open('input' + str(N) + '.txt') as file:  # открываем файл input[N].txt
    string = [row.strip() for row in file]  # и разделяем на строки

arr = string[1].split(' ')  # строку с числами разделяем на массив
arr = [int(arr) for arr in arr]  # присваиваем элементам массива тип integer
#print(arr)  # начальный массив

start_time = time.time()  # время начала сортировки

quicksort(arr, 0, len(arr))

finish_time = time.time()  # время окончания сортировки
#print(arr)  # конечный массив

print('Время сортировки:')
print(finish_time - start_time, "seconds")  # длительность сортировки

f = open('output' + str(N) + '.txt', 'w')  # создаём файл output[N].txt

for i in range(N):
    f.write(str(arr[i]) + ' ')  # вписываем отсортированные числа в файл, разделяя пробелами

f.close()


print("----this shit shows if your input value can be written as n(n+1) or not----")
x = "n"
while x == "n":
    try:
        s = 0
        print("< now you're expected to input a valid number; >")
        p = int(input())
        for i in range(1, p + 1, 1):
            k = i * (i + 1)
            if k == p:
                print("eligible number. it can be written like;")
                print(str(i) + " x " + str((i + 1)))
                s = 1
        if s == 1:
            pass
        else:
            print("the number you've written can't be defined in n.(n+1) format.")
    except:
        print("fill a integer in.")
    print("exit? y/n")
    x = input()

# code apri44 sended but never got fixed.

Folder for apri to post questions or code/apri44 helping with code/afq.py


import sys;

def tp(a,m,n):
    return [[a[i][j] for i in range(0,n)] for j in range(0,m)]

def stylePoints(g,n):
    p = 0;
    for i in range(0,n):
        for j in range(0,n):
            if g[i][j] != ".":
                p += 2 if g[i][j] == "o" else 1;
    return p;

rows = []
cols = []
main = []
anti = []
def isE(g,r,c):
    return g[r][c] == '.'
def isO(g,r,c):
    return g[r][c] == 'o'
def isXO(g,r,c):
    return g[r][c] == 'x' or g[r][c] == 'o'
def isPlusO(g,r,c):
    return g[r][c] == '+' or g[r][c] == 'o'
def populateRowColDiagData(g,n):
    global rows
    global cols
    global main
    global anti
    rows = [0 for i in range(0,n)]
    cols = [0 for i in range(0,n)]
    main = [0 for i in range(0,2*n-1)]
    anti = [0 for i in range(0,2*n-1)]

    for i in range(0,n):
        for j in range(0,n):
            if isXO(g,i,j):
                rows[i] += 1
                cols[j] += 1
            if isPlusO(g,i,j):
                main[j-i+n-1] += 1
                anti[i+j] += 1
    """print "From Populate RS CS MS AS";
    print "rows:", rows
    print "cols:", cols
    print "main:", main
    print "anti:", anti"""
def getRowColNumber(g,i,j):
    dx = -1 if isXO(g,i,j) else 0;
    """ old - delete this old debugs -- TODO
    print "cols:", cols
    print "rows:", rows
    print "main:", main
    print "anti:", anti

    print "Get RCN:", i, "|", j
    print rows[0]
    print rows[1]
    print i, "|", rows[i]
    print j, "|", cols[j]"""
    #print "GetRC:", "(",i, j,  "),(", rows[i], cols[j], ")dx", dx;
    return max(rows[i] + dx, cols[j] + dx);
def getMainAntiNumber(g,n,i,j):
    dx = -1 if isPlusO(g,i,j) else 0;
    #print "GetMA:",  "(",i, j, "),(",main[j-i+n-1], anti[i+j], ")dx",dx;
    return max(main[j-i+n-1] + dx, anti[i+j] + dx);

class Point:
   def __init__(self, x, y):
      self.x = x
      self.y = y
class Model:
    def __init__(self, p, c):
        self.p = p
        self.c = c
def checkPoint(g,x,y,lookingForO):
    rc = getRowColNumber(g,x,y)
    ma = getMainAntiNumber(g,n,x,y)

    if lookingForO:
                    if not isO(g, x, y) and rc == 0 and ma == 0:
                        found = True
                        return {'found': True, 'model': Point(x, y)}
    else:
                    if isE(g, x, y) and rc == 1 and ma == 0:
                        found = True
                        return {'found': True, 'model': Point(x, y)}
    return {'found':False}
def pyramid(g,n,lookingForO):
    for i in range(0,(n+1)/2):
        for j in range(0,n-1-2*i):
            result = checkPoint(g, i, j + i, lookingForO);
            if result['found']:
                return result
            result = checkPoint(g, i + j, n - 1 - i, lookingForO);
            if result['found']:
                return result
            result = checkPoint(g, n - 1 - i, n - 1 - i - j, lookingForO);
            if result['found']:
                return result
            result = checkPoint(g, n - 1 - i - j, i, lookingForO);
            if result['found']:
                return result
    return {'found':False}
def plain(g,n):
    for i in range(0,n):
        for j in range(0,n):
            rc = getRowColNumber(g,i,j)
            ma = getMainAntiNumber(g,n,i,j)
            if isE(g,i,j) and rc == 0 and ma == 1:
                return {'found': True, 'model': Point(i, j)}
    return {'found':False}
def solve(g,n,m):
    if n == 1:
        if g[0][0] == "o":
            return "2 0"
        else:
            return "2 1\r\no 1 1";
    populateRowColDiagData(g,n);

    oModelCandidate = Point(-1,-1)
    plusModelCandidate = Point(-1,-1)
    xModelCandidate = Point(-1,-1)

    models = []

    oModelFound = False
    plusModelFound = False
    xModelFound = False

    rerun = False

    result = pyramid(g, n, False)
    if result['found']:
        p = result['model']
        m = Model(p, "+")
        g[p.x][p.y] = "+"
        models.append(m)
        rerun = True
    else:
        result = plain(g,n)
        if result['found']:
            p = result['model']
            m = Model(p, "x")
            g[p.x][p.y] = "x"
            models.append(m)
            rerun = True
        else:
            result = pyramid(g, n, True)
            if result['found']:
                p = result['model']
                m = Model(p, "o")
                g[p.x][p.y] = "o"
                models.append(m)
                rerun = True

    while rerun:
        populateRowColDiagData(g,n);

        rerun = False
        result = pyramid(g, n, False)
        if result['found']:
            p = result['model']
            m = Model(p, "+")
            g[p.x][p.y] = "+"
            models.append(m)
            rerun = True
        else:
            result = plain(g,n)
            if result['found']:
                p = result['model']
                m = Model(p, "x")
                g[p.x][p.y] = "x"
                models.append(m)
                rerun = True
            else:
                result = pyramid(g, n, True)
                if result['found']:
                    p = result['model']
                    m = Model(p, "o")
                    g[p.x][p.y] = "o"
                    models.append(m)
                    rerun = True

    return str(stylePoints(g, n)) + " " + str(len(models)) + "\r\n" + ("\r\n".join(map(lambda m: m.c + " " + str(m.p.x+1) + " " + str(m.p.y+1), models)));

inputFile =  sys.argv[1] if (len(sys.argv) > 1) else "input.txt";
outputFile = sys.argv[2] if (len(sys.argv) > 2) else (inputFile + "out.txt") if (len(sys.argv) > 1) else "output.txt";
print(inputFile, outputFile)
file = open(outputFile, "w")

with open(inputFile, 'r') as f:
    t = int(f.readline())
    print(t)
    for i in range(1, t + 1):
        file.write("Case #" + str(i) + ": ")
        n,m = map(int, f.readline().split())
        #print( "n,m",n," ",m)
        grid=[["." for i in range(0,n)] for j in range(0,n)];
        #print grid;

        for i in range(0,m):
            x, r, c = f.readline().split(" ")
            r = int(r)
            c = int(c)
            grid[r-1][c-1] = x;

        file.write(str(solve(grid, n, m)) + "\n")
file.close()


from .Graph import WeightedUDGraph

# Driver code
def testmain():
    testcases = []
    n = 9
    weighted_edges = [[0, 1, 4], [0, 7, 8], [1, 2, 8], [1, 7, 11], [2, 5, 4], [2, 3, 7],
             [3, 4, 9], [3, 5, 14], [5, 4, 10], [6, 5, 2], [7, 6, 1], [7, 8, 7],
             [8, 2, 2], [8, 6, 6]]
    testcases.append((n, weighted_edges))

    for cases in testcases:
        n, edges = cases
        g = WeightedUDGraph(n)
        for edge in edges:
            u, v, w = edge
            g.add_weighted_edges(u, v, w)

        print('KruskalMST:')
        for result in g.KruskalMST():
            print(result)

if __name__ == '__main__':
    testmain()


#! /usr/bin/env python3
import json
import os

import docker
from flask import Flask, Response, send_from_directory
from flask_cors import CORS, cross_origin

app = Flask(__name__, static_folder='../web/build/static')
CORS(app, origins="*", allow_headers=[
    'Content-Type', 'Authorization', 'X-Requested-With',
    'Content-Length', 'Accept', 'Origin'
])

@app.after_request
def after_request(response):
    header = response.headers
    header['Access-Control-Allow-Headers'] = 'Content-Type'

    return response

@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def react(path):
    print('Path: {}'.format(path))
    if path != "" and os.path.exists("react_app/build/{}".format(path)):
        print('Accessing path: {}'.format(path))
        return send_from_directory('../web/build', path)
    else:
        print('Accessing default: {}../web/build/index.html'.format(os.path.curdir))
        return send_from_directory('../web/build', 'index.html')

@app.route('/api/images', methods=['GET'])
@cross_origin()
def get_applications():
    client = docker.from_env()

    images = dict()

    for con in get_valid_containers(client):
        try:
            img_name = get_image_name(con.image, only_app=True)
            if img_name not in images:
                images.update({
                    img_name: {
                        'image': {
                            'name': img_name.split('/')[-1],
                            'extra': img_name.split('/')[0:-1]
                        },
                        'status': dict(),
                        'containers': list(),
                    }
                })

            images[img_name]['containers'].append(get_container_version(con))

            # Updates total status counter
            # with each containers status
            statuses = images[img_name]['status']
            statuses.update({con.status: statuses.get(con.status, 0) + 1})
        except Exception as e:
            print('Could not include container: {}, when fetching image: {}'.format(con, img_name))
            print(e)

    result = [images[v] for v in images]

    client.close()
    return ok_response(result)

@app.route('/api/images/<img_name>/containers', methods=['GET'])
@cross_origin()
def get_app_versions(img_name):
    client = docker.from_env()

    try:
        result = [
            extract_container_info(container) for container in get_valid_containers(client)
            if img_name == get_image_name(container.image, only_app=True)
        ]
    except Exception as e:
        print('Could not fetch containers for image {}'.format(img_name))
        print(e)

    client.close()
    return ok_response(result)

@app.route('/api/containers/<con_id>', methods=['GET'])
@cross_origin()
def get_container_info(con_id):
    client = docker.from_env()

    container = next((extract_container_info(c) for c in get_valid_containers(client) if c.id == con_id), None)
    if not container:
        err = 'No container with id {} available'.format(con_id)
        print(err)
        return err_response(err, 400)

    client.close()
    return ok_response(container)

@app.route('/api/containers/<con_id>/restart', methods=['POST'])
@cross_origin()
def restart_container(con_id):
    client = docker.from_env()

    try:
        con = client.containers.get(con_id)
        if restartable_container(con):
            print('Restarting container with ID {}'.format(con_id))
            con.restart()
        else:
            err = 'Container ({}) not restartable'.format(con_id)
            print(err)

            client.close()
            return err_response(err, 400)
    except docker.errors.APIError as e:
        print('Failed restarting container with ID {}: \n{}'.format(con_id, e))
        client.close()
        return err_response(e, 500)

    print('Restart complete')
    client.close()
    return ok_response(dict())

@app.route('/api/containers/<con_id>/delete', methods=['DELETE'])
@cross_origin()
def remove_container(con_id):
    client = docker.from_env()

    try:
        con = client.containers.get(con_id)
        if removable_container(con):
            print('Removing container with ID {}'.format(con_id))
            client.containers.get(con_id).remove(force=True)
        else:
            err = 'Container ({}) not restartable'.format(con_id)
            print(err)

            client.close()
            return err_response(err, 400)
    except docker.errors.APIError as e:
        print('Failed removing container with ID {}: \n{}'.format(con_id, e))
        client.close()
        return err_response(e, 500)

    print('Removal complete')
    client.close()
    return ok_response(dict())

@app.route('/api/containers/<con_id>/logs', methods=['GET'])
def get_container_logs(con_id):
    def generate():
        client = docker.from_env()

        for row in client.containers.get(con_id).logs(stream=True, follow=True):
            yield row.decode("utf-8")
        client.close()

    return Response(generate(), mimetype='text/plain')

def err_response(err, code):
    return Response(
        response=json.dumps({'error': err}),
        mimetype='application/json',
        status=code,
    )

def ok_response(result):
    return Response(
        response=json.dumps(result),
        mimetype='application/json',
        status=200,
    )

def get_valid_containers(client):
    return [
        con for con in client.containers.list(all=True)
        if not hidden_container(con) and not untagged_image(con.image)
    ]

def hidden_container(con):
    return con.labels.get('dockwatch.hidden', 'false').lower() != 'false'

def restartable_container(con):
    return con.labels.get('dockwatch.restartable', 'false').lower() == 'true'

def removable_container(con):
    return con.labels.get('dockwatch.removable', 'false').lower() == 'true'

def untagged_image(image):
    return not image.tags

def get_container_version(con):
    return {
        'id': con.id,
        'name': con.name,
        'image': {
            'id': con.image.id.split(':')[-1],
            'version': get_image_version(con.image),
        }
    }

def get_image_name(img, only_app=False):
    name = img.tags[0].split(':')[0]

    return name.split('/')[-1] if only_app else name

def get_image_version(img):
    return img.tags[0].split(':')[-1]

def extract_container_info(container):
    return {
        'id': container.id,
        'name': container.name,
        'image': {
            'id': container.image.id.split(':')[-1],
            'name': get_image_name(container.image),
            'version': get_image_version(container.image),
        },
        'created': container.attrs.get('Created', None),
        'status': container.status,
        'labels': container.labels,
        'restarted': container.attrs.get('RestartCount', 0),
        'state': container.attrs.get('State', dict()),
    }

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=os.environ.get('DW_PORT', 1609))


import PyDAQmx as mx
import logging
logger = logging.getLogger(__name__)

class NamedTask(mx.Task):
    ''' replaces __init__ with one that accepts a name for the task, otherwise identical to PyDaqmx task
        override PyDAQmx definition, which does not support named tasks
        no special chars in names, space OK
    '''
    def __init__(self, name= ''):
        self.taskHandle = mx.TaskHandle(0)
        mx.DAQmxCreateTask(name, mx.byref(self.taskHandle))

class NI_TaskWrap(object):
    '''
    class to wrap National Instruments tasks using DAQmx drivers
    '''
    def __init__(self, name = '' ):
        '''
        Constructor
        '''
        self._error_list = []
        self._channel = self._task_name = self._mode = ''
        self._chan_count = self._rate = 0
        self.make_task( name )

    def make_task(self, name = '' ):
        ''' creates a [named] task, should not fail if DAQmx present'''
        # clean up name to remove unallowed characters (might be missing some)
        for char in '/,;':
            name = name.replace(char, "_")
        print("make_task", name)
        self._task_name = name
        try:
            self.task = NamedTask(name)
        except mx.DAQError as err:
            self.error( err )
            self.task = None

    def error(self, err ):
            self._error_list.append(err)
            logger.error('Error calling "{}": {}'.format( err.fname, err.mess ))

    def stop(self):
        try:
            self.task.StopTask()
        except mx.DAQError as err:
            self.error(err)

    def start(self):
        try:
            self.task.StartTask()
        except mx.DAQError as err:
            self.error(err)

    def clear(self):
        try:
            self.task.ClearTask()
        except mx.DAQError as err:
            self.error(err)
        finally:
            self.task = None

    def close(self):
        return self.clear()

    def unreserve(self):
        ''' releases resources for other tasks to use without destroying task'''
        try:
            self.task.TaskControl(mx.DAQmx_Val_Task_Unreserve)
        except mx.DAQError as err:
            self.error(err)

    def ready(self):
        ''' validates params, reserves resources, ready to start'''
        try:
            self.task.TaskControl(mx.DAQmx_Val_Task_Commit)
        except mx.DAQError as err:
            self.error(err)

    def is_done(self):
        ''' checks for task done'''
        status = mx.bool32(0)
        try:
            self.task.GetTaskComplete( mx.byref(status));
        except mx.DAQError as err:
            self.error(err)
        if status.value:
            return True
        else:
            return False

    def get_rate(self):
        return self._rate

    def get_chan_count(self):
        return self._chan_count

    def wait(self, timeout = 10.0 ):
        try:
            self.task.WaitUntilTaskDone( timeout)
        except mx.DAQError as err:
            self.error(err)

    def get_devices(self):
        '''
        polls for installed NI devices
        '''
        buffSize = 2048
        buff = mx.create_string_buffer( buffSize )
        try:
            mx.DAQmxGetSysDevNames( buff, buffSize );
        except mx.DAQError as err:
            self.error( err )
        dev_list = buff.value.split(',')
        for i in range(len(dev_list)):
            dev_list[i] = dev_list[i].strip()
        self._device_list = dev_list
        #mx.DAQmxGetDevAIPhysicalChans( AIdev, chanList, buffSize )


#! ~/.miniconda3/envs/pytorch/bin/python
import torch
import torch.nn as nn
from typing import List, Tuple

class conv1d(nn.Sequential):
    def __init__(self,
                 in_channels,
                 out_channels,
                 kernel_size,
                 stride,
                 padding,
                 name,
                 bias=True,
                 activation_fn=nn.ReLU(inplace=True),
                 bn=True,
                 eps=1e-6,
                 momentum=0.99):
        super(conv1d, self).__init__()
        conv1d_layer = nn.Conv1d(in_channels=in_channels,
                                 out_channels=out_channels,
                                 kernel_size=kernel_size,
                                 stride=stride,
                                 padding=padding,
                                 bias=bias)
        nn.init.xavier_normal_(conv1d_layer.weight.data)
        if bias is True:
            nn.init.constant_(conv1d_layer.bias.data, 0)
        self.add_module(name + 'conv1d', conv1d_layer)

        if bn is True:
            bn_layer = nn.BatchNorm1d(num_features=out_channels,
                                      eps=eps,
                                      momentum=momentum)
            self.add_module(name + 'bn1d', bn_layer)
        if activation_fn is not None:
            self.add_module(name + 'activation', activation_fn)

class conv2d(nn.Sequential):
    def __init__(self,
                 in_channels,
                 out_channels,
                 kernel_size,
                 stride,
                 padding,
                 name,
                 bias=True,
                 activation_fn=nn.ReLU(inplace=True),
                 bn=True,
                 eps=1e-6,
                 momentum=0.99):
        super(conv2d, self).__init__()
        conv2d_layer = nn.Conv2d(in_channels=in_channels,
                                 out_channels=out_channels,
                                 kernel_size=kernel_size,
                                 stride=stride,
                                 padding=padding,
                                 bias=bias)
        nn.init.xavier_normal_(conv2d_layer.weight.data)
        if bias is True:
            nn.init.constant_(conv2d_layer.bias.data, 0)
        self.add_module(name + 'conv2d', conv2d_layer)

        if bn is True:
            bn_layer = nn.BatchNorm2d(num_features=out_channels,
                                      eps=eps,
                                      momentum=momentum)
            self.add_module(name + 'bn2d', bn_layer)

        if activation_fn is not None:
            self.add_module(name + 'activation', activation_fn)

class conv2d_transpose(nn.Sequential):
    def __init__(self,
                 in_channels,
                 out_channels,
                 kernel_size,
                 stride,
                 padding,
                 name,
                 bias=True,
                 activation_fn=nn.ReLU(inplace=True),
                 bn=True,
                 eps=1e-6,
                 momentum=0.99):
        super(conv2d_transpose, self).__init__()
        conv2d_transpose_layer = nn.ConvTranspose2d(in_channels=in_channels,
                                                    out_channels=out_channels,
                                                    kernel_size=kernel_size,
                                                    stride=stride,
                                                    padding=padding,
                                                    bias=bias)
        nn.init.xavier_normal_(conv2d_transpose_layer.weight.data)
        if bias is True:
            nn.init.constant_(conv2d_transpose_layer.bias.data, 0)
        self.add_module(name + 'conv2d_transpose', conv2d_transpose_layer)

        if bn is True:
            bn_layer = nn.BatchNorm2d(num_features=out_channels,
                                      eps=eps,
                                      momentum=momentum)
            self.add_module(name + 'bn2d', bn_layer)

        if activation_fn is not None:
            self.add_module(name + 'activation', activation_fn)

class SharedMLP(nn.Sequential):
    def __init__(self,
                 args: List[int],
                 *,
                 bn: bool = False,
                 activation=nn.ReLU(inplace=True),
                 preact: bool = False,
                 first: bool = False,
                 name: str = "",
                 instance_norm: bool = False):
        super().__init__()

        for i in range(len(args) - 1):
            self.add_module(
                name + 'layer{}'.format(i),
                Conv2d(args[i],
                       args[i + 1],
                       bn=(not first or not preact or (i != 0)) and bn,
                       activation=activation if
                       (not first or not preact or (i != 0)) else None,
                       preact=preact,
                       instance_norm=instance_norm))

class _ConvBase(nn.Sequential):
    def __init__(self,
                 in_size,
                 out_size,
                 kernel_size,
                 stride,
                 padding,
                 activation,
                 bn,
                 init,
                 conv=None,
                 batch_norm=None,
                 bias=True,
                 preact=False,
                 name="",
                 instance_norm=False,
                 instance_norm_func=None):
        super().__init__()

        bias = bias and (not bn)
        conv_unit = conv(in_size,
                         out_size,
                         kernel_size=kernel_size,
                         stride=stride,
                         padding=padding,
                         bias=bias)
        init(conv_unit.weight)
        if bias:
            nn.init.constant_(conv_unit.bias, 0)

        if bn:
            if not preact:
                bn_unit = batch_norm(out_size)
            else:
                bn_unit = batch_norm(in_size)
        if instance_norm:
            if not preact:
                in_unit = instance_norm_func(out_size,
                                             affine=False,
                                             track_running_stats=False)
            else:
                in_unit = instance_norm_func(in_size,
                                             affine=False,
                                             track_running_stats=False)

        if preact:
            if bn:
                self.add_module(name + 'bn', bn_unit)

            if activation is not None:
                self.add_module(name + 'activation', activation)

            if not bn and instance_norm:
                self.add_module(name + 'in', in_unit)

        self.add_module(name + 'conv', conv_unit)

        if not preact:
            if bn:
                self.add_module(name + 'bn', bn_unit)

            if activation is not None:
                self.add_module(name + 'activation', activation)

            if not bn and instance_norm:
                self.add_module(name + 'in', in_unit)

class _BNBase(nn.Sequential):
    def __init__(self, in_size, batch_norm=None, name=""):
        super().__init__()
        self.add_module(name + "bn",
                        batch_norm(in_size, eps=1e-6, momentum=0.99))

        nn.init.constant_(self[0].weight, 1.0)
        nn.init.constant_(self[0].bias, 0)

class BatchNorm1d(_BNBase):
    def __init__(self, in_size: int, *, name: str = ""):
        super().__init__(in_size, batch_norm=nn.BatchNorm1d, name=name)

class BatchNorm2d(_BNBase):
    def __init__(self, in_size: int, name: str = ""):
        super().__init__(in_size, batch_norm=nn.BatchNorm2d, name=name)

class Conv1d(_ConvBase):
    def __init__(self,
                 in_size: int,
                 out_size: int,
                 *,
                 kernel_size: int = 1,
                 stride: int = 1,
                 padding: int = 0,
                 activation=nn.LeakyReLU(negative_slope=0.2, inplace=True),
                 bn: bool = False,
                 init=nn.init.kaiming_normal_,
                 bias: bool = True,
                 preact: bool = False,
                 name: str = "",
                 instance_norm=False):
        super().__init__(in_size,
                         out_size,
                         kernel_size,
                         stride,
                         padding,
                         activation,
                         bn,
                         init,
                         conv=nn.Conv1d,
                         batch_norm=BatchNorm1d,
                         bias=bias,
                         preact=preact,
                         name=name,
                         instance_norm=instance_norm,
                         instance_norm_func=nn.InstanceNorm1d)

class Conv2d(_ConvBase):
    def __init__(self,
                 in_size: int,
                 out_size: int,
                 *,
                 kernel_size: Tuple[int, int] = (1, 1),
                 stride: Tuple[int, int] = (1, 1),
                 padding: Tuple[int, int] = (0, 0),
                 activation=nn.LeakyReLU(negative_slope=0.2, inplace=True),
                 bn: bool = False,
                 init=nn.init.kaiming_normal_,
                 bias: bool = True,
                 preact: bool = False,
                 name: str = "",
                 instance_norm=False):
        super().__init__(in_size,
                         out_size,
                         kernel_size,
                         stride,
                         padding,
                         activation,
                         bn,
                         init,
                         conv=nn.Conv2d,
                         batch_norm=BatchNorm2d,
                         bias=bias,
                         preact=preact,
                         name=name,
                         instance_norm=instance_norm,
                         instance_norm_func=nn.InstanceNorm2d)

class Conv2d_Transpose(_ConvBase):
    def __init__(self,
                 in_size: int,
                 out_size: int,
                 *,
                 kernel_size: Tuple[int, int] = (1, 1),
                 stride: Tuple[int, int] = (1, 1),
                 padding: Tuple[int, int] = (0, 0),
                 activation=nn.LeakyReLU(negative_slope=0.2, inplace=True),
                 bn: bool = False,
                 init=nn.init.kaiming_normal_,
                 bias: bool = True,
                 preact: bool = False,
                 name: str = "",
                 instance_norm=False):
        super().__init__(in_size,
                         out_size,
                         kernel_size,
                         stride,
                         padding,
                         activation,
                         bn,
                         init,
                         conv=nn.ConvTranspose2d,
                         batch_norm=BatchNorm2d,
                         bias=bias,
                         preact=preact,
                         name=name,
                         instance_norm=instance_norm,
                         instance_norm_func=nn.InstanceNorm2d)

class FC(nn.Sequential):
    def __init__(self,
                 in_size: int,
                 out_size: int,
                 *,
                 activation=nn.ReLU(inplace=True),
                 bn: bool = False,
                 init=None,
                 preact: bool = False,
                 name: str = ""):
        super().__init__()

        fc = nn.Linear(in_size, out_size, bias=not bn)
        if init is not None:
            init(fc.weight)
        if not bn:
            nn.init.constant(fc.bias, 0)

        if preact:
            if bn:
                self.add_module(name + 'bn', BatchNorm1d(in_size))

            if activation is not None:
                self.add_module(name + 'activation', activation)

        self.add_module(name + 'fc', fc)

        if not preact:
            if bn:
                self.add_module(name + 'bn', BatchNorm1d(out_size))

            if activation is not None:
                self.add_module(name + 'activation', activation)

def set_bn_momentum_default(bn_momentum):
    def fn(m):
        if isinstance(m, (nn.BatchNorm1d, nn.BatchNorm2d, nn.BatchNorm3d)):
            m.momentum = bn_momentum

    return fn

class BNMomentumScheduler(object):
    def __init__(self,
                 model,
                 bn_lambda,
                 last_epoch=-1,
                 setter=set_bn_momentum_default):
        if not isinstance(model, nn.Module):
            raise RuntimeError("Class '{}' is not a PyTorch nn Module".format(
                type(model).__name__))

        self.model = model
        self.setter = setter
        self.lmbd = bn_lambda

        self.step(last_epoch + 1)
        self.last_epoch = last_epoch

    def step(self, epoch=None):
        if epoch is None:
            epoch = self.last_epoch + 1

        self.last_epoch = epoch
        self.model.apply(self.setter(self.lmbd(epoch)))


import graphviz as gv
from copy import copy, deepcopy

JUPYTER_NOTEBOOK = True

class VizuGraphe:

    def __init__(self, type_structure, structure_adjacence,
                                            oriente = False,
                                            moteur = 'neato',
                                            etiquettes_secondaires = None,
                                            couleurs = None,
                                            etiquettes_principales = None,
                                            formes = None,
                                            **kwargs):
        '''
        - type_structure : représentation utilisée pour le graphe:

                 - 'liste'       : liste d'adjacence sous forme d'un dictionnaire dont
                                   les valeurs sont les listes des sommets adjacents

                 - 'liste_pond'   : liste d'adjacence pondérée sous forme d'un dictionnaire
                                    dont les valeurs sont des dictionnaires ayant pour clefs
                                    les sommets adjacents et pour valeurs les poids des arêtes

                 - 'matrice_bool' : matrice d'adjacence dont les éléments sont des bool False
                                    ou True

                 - 'matrice_bin'  : matrice d'adjacence dont les éléments sont des int 0 ou 1

                 - 'matrice_pond' : matrice d'adjacence pondérée dont les éléments sont des int
                                    (ou des float)

        - structure_adjacence : la matrice ou le dictionnaire servant de liste d'adjacence

        - oriente [ = False] : booléen indiquant si le graphe est orienté ou pas ?

        - moteur [ = 'neato']             : moteur de placement des sommets utilisé par graphviz.
                                    Autres choix :'circo', 'dot', 'fdp', 'neato', 'osage',
                                    'patchwork', 'sfdp','twopi'
                                     https://graphviz.org/documentation/

        - etiquettes_secondaires [ = None] : dictionnaire ayant pour clefs des étiquettes
                                             du graphe et pour valeurs les étiquette secondaires
                                             à afficher.

        - couleurs [ = None] : dictionnaire ayant pour clefs des étiquettes du graphe et pour
                                        valeurs les couleurs des sommets au format (H, S, V)
                                        avec H, S, V de type float entre 0 et 1.

        - formes [ = None] : dictionnaire ayant pour clefs des étiquettes du graphe et pour valeurs
                             les formes des sommets ('rect', 'rectangle', 'folder', 'house',
                             'ellipse', 'egg', 'triangle', 'diamond' [...]
                             https://graphviz.org/doc/info/shapes.html

        - etiquettes_principales [ = None] : pour les *matrices d'adjacence* de taille NxN,
                                             dictionnaire ayant  pour clefs les indices des
                                             sommets (entre 0 et N-1) et pour valeurs les
                                             étiquettes principales à afficher si on souhaite
                                             ne pas utiliser les indices des sommets

        - **kwargs : il s'agit des paramètres supplémentaires acceptés par la méthode modifier
        '''

        self.type_structure = type_structure
        self.structure = structure_adjacence
        self.etiquettes_secondaires = deepcopy(etiquettes_secondaires)
        self.couleurs = copy(couleurs)
        self.etiquettes_principales = deepcopy(etiquettes_principales)
        self.formes = copy(formes)
        self.oriente = oriente
        self.moteur = moteur
        self._initialiser_parametres_dessin()
        self._modifier(**kwargs)
        self._creer_objet_graphviz()

    def _initialiser_parametres_dessin(self):

        self.size = '10'                              #taille maximale de l'image générée
        self.label = 'Graphe'                         #titre du graphique

        self.node_style = 'filled'                    #remplissage des noeuds
        self.node_shape = 'circle'                    #forme des noeuds
        self.node_fontsize = '12'                     #taille de la police des noeuds
        self.node_small_fontsize = '11'               #taille de la police secondaire des noeuds
        self.node_color = (0.5, 0.2, 1.0)             #couleur par défaut au format HSV
        self.node_width = '0.35'                      #largeur des noeuds
        self.node_height = '0.35'                     #hauteur des noeuds
        self.node_main = True                         #affichage des etiquettes principales

        self.edge_style = 'solid'                     #flèches en traits pleins
        self.edge_arrowhead = 'open' if self.oriente == True else 'none'  #forme des têtes de flèches
        self.edge_arrowsize = '0.5'                   #taille des têtes de flèches
        self.edge_fontsize = '12'                     #taille de la police pour les arêtes

    def _creer_objet_graphviz(self):
        graph_maker = gv.Digraph if self.oriente else gv.Graph
        self.G = graph_maker('graphe', strict = 'True', engine = self.moteur)
        self._injecter_parametres_dessin_dans_graphviz()
        self._dessiner_graphe()
        if JUPYTER_NOTEBOOK :
            display(self.G)
        else :
            self.G.render(view=True)

    def _injecter_parametres_dessin_dans_graphviz(self):
        self.G.attr(root = '',
                    size = self.size,
                    label = self.label)

        self.G.node_attr.update(style = self.node_style,
                                fontsize = self.node_fontsize,
                                width = self.node_width,
                                height = self.node_height,
                                fixedsize = 'False',
                                margin = '0, 0')

        self.G.edge_attr.update(style = self.edge_style,
                                arrowhead = self.edge_arrowhead,
                                arrowsize = self.edge_arrowsize,
                                fontsize = self.edge_fontsize)

    def _tuple_to_string(couleur):
        return ' '.join([str(round(c, 4)) for c in couleur])

    def _donner_couleur(self, sommet):
        if self.couleurs == None or sommet not in self.couleurs:
            return VizuGraphe._tuple_to_string(self.node_color)
        else:
            return VizuGraphe._tuple_to_string(self.couleurs[sommet])

    def _donner_label(self, sommet):
        if self.node_main:
            if self.etiquettes_principales == None or sommet not in self.etiquettes_principales:
                e = str(sommet)
            else:
                e = str(self.etiquettes_principales[sommet])
        else :
            e = ''

        if self.etiquettes_secondaires == None or sommet not in self.etiquettes_secondaires:
            S = '<' + e + '>'
        else:
            e_2 = str(self.etiquettes_secondaires[sommet])
            small = str(self.node_small_fontsize)
            S = '<' + e + '
' + e_2 + '>'
        return S

    def _donner_forme(self, sommet):
        if self.formes == None or sommet not in self.formes:
            return self.node_shape
        else:
            return self.formes[sommet]

    def _dessiner_graphe(self):
        dico = { 'liste'         : self._dessiner_liste,
                 'liste_pond'    : self._dessiner_liste_pond,
                 'matrice_bool'  : self._dessiner_matrice_bool,
                 'matrice_bin'   : self._dessiner_matrice_bin,
                 'matrice_pond'  : self._dessiner_matrice_pond}

        dico[self.type_structure]()

    def _dessiner_liste(self):
        #sommets  = self._recuperer_dico_sommets_liste()
        sommets = self.structure.keys()
        self._creer_noeuds_graphviz(sommets)
        for sommet, successeurs in self.structure.items():
            for succ in successeurs :
                self.G.edge(str(sommet), str(succ))

    def _dessiner_liste_pond(self):
        #sommets  = self._recuperer_dico_sommets_liste()
        sommets = self.structure.keys()
        self._creer_noeuds_graphviz(sommets)
        for sommet, successeurs in self.structure.items():
            for succ in successeurs :
                p = self.structure[sommet][succ]
                if p != 0:
                    self.G.edge(str(sommet), str(succ), label = str(p))

    def _dessiner_matrice_bool(self):
        #sommets  = self._recuperer_liste_sommets_matrice()
        sommets = list(range(len(self.structure)))
        self._creer_noeuds_graphviz(sommets)
        for lig in range(len(self.structure)):
            for col in range(len(self.structure[0])):
                if self.structure[lig][col]:
                    self.G.edge(str(lig), str(col))

    def _dessiner_matrice_bin(self):
        #sommets  = self._recuperer_liste_sommets_matrice()
        sommets = list(range(len(self.structure)))
        self._creer_noeuds_graphviz(sommets)
        for lig in range(len(self.structure)):
            for col in range(len(self.structure[0])):
                if self.structure[lig][col] == 1:
                    self.G.edge(str(lig), str(col))

    def _dessiner_matrice_pond(self):
        #sommets  = self._recuperer_liste_sommets_matrice()
        sommets = list(range(len(self.structure)))
        self._creer_noeuds_graphviz(sommets)
        for lig in range(len(self.structure)):
            for col in range(len(self.structure[0])):
                p = self.structure[lig][col]
                if p != 0:
                    self.G.edge(str(lig), str(col), label = str(p))

    def _recuperer_liste_sommets_matrice(self):
        if self.etiquettes_principales== None:
            sommets = list(range(len(self.structure)))
        elif type(self.etiquettes_principales) == list:
            sommets = self.etiquettes_principales
        elif type(self.etiquettes_principales) == dict:
            sommets = [self.etiquettes_principales[i] for i in range(len(self.etiquettes_principales))]
        return sommets

    def _recuperer_liste_sommets_liste(self):
        if self.etiquettes_principales== None:
            sommets = list(self.structure.keys())
        elif type(self.etiquettes_principales) == dict:
            sommets = list(self.etiquettes_principales.values())
        return sommets

    def _creer_noeuds_graphviz(self, liste_sommets):
        for sommet in liste_sommets:
            self.G.node( str(sommet), label = self._donner_label(sommet),
                                      color = self._donner_couleur(sommet),
                                      shape = self._donner_forme(sommet))

    def _modifier(self, **kwargs):
        legal_args = ("size", "label", "node_style", "node_shape", "node_fontsize",
                      "node_small_fontsize","node_color", "node_width", "node_height",
                      "edge_style", "edge_arrowhead", "edge_arrowsize", "edge_fontsize",
                      "moteur", "oriente", "reset", "etiquettes_secondaires", "couleurs",
                      "formes", "etiquettes_principales", "node_main")

        if "reset" in kwargs.keys():
            if kwargs["reset"] == True:
                self._initialiser_parametres_dessin()
                self.etiquettes_secondaires = None
                self.etiquettes_principales = None
                self.couleurs = None
                self.formes = None
        for key, val in kwargs.items():
            if key in legal_args:
                if type(val) == int or type(val) == float:
                    setattr(self, key, str(val))
                elif type(val) == dict or type(val) == list:
                    setattr(self, key, deepcopy(val))
                else:
                    setattr(self, key, val)

    def modifier(self, **kwargs):
        '''
        Une fois un graphique créé et représenté, permet de modifier les paramètres de dessin.

        - REINITIALISATION  :

            - reset  [ = False]               : booléen indiquant si on réinitialise
                                                les modifications de paramètres déjà
                                                prises en compte auparavant
                                                (sauf 'moteur' et 'oriente')

        - PARAMETRES DU GRAPHE EN ENTIER :

            - size [ = 10]                    : taille maximale de l'image générée

            - label [ = 'Graphe']             : titre du graphique

            - oriente [ = False]              : est-ce que le graphe est orienté ou pas

            - moteur [ = 'neato']             : moteur de placement des sommets utilisé
                                                par graphviz.  Autres choix :'circo', 'dot',
                                                'fdp', 'neato', 'osage', 'patchwork', 'sfdp','twopi'
                                                https://graphviz.org/documentation/

        - PARAMETRES INDIVIDUELS :

            - etiquettes_secondaires [ = None] : dictionnaire ayant pour clefs des étiquettes
                                                   du graphe et pour valeurs les étiquette
                                                   secondaires à afficher.

            - couleurs [ = None] : dictionnaire ayant pour clefs des étiquettes du graphe et pour
                                     valeurs les couleurs des sommets au format (H, S, V) avec H, S, V
                                     de type float entre 0 et 1.

            - formes [ = None] : dictionnaire ayant pour clefs des étiquettes du graphe et
                                    pour valeurs les formes des sommets ('rect', 'rectangle',
                                    'folder', 'house', 'ellipse', 'egg', 'triangle', 'diamond' [...]
                                    https://graphviz.org/doc/info/shapes.html

            - etiquettes_principales [ = None] : dictionnaire ayant pour clefs les indices
                                                 ou clefs des sommets que l'on ne souhaite
                                                 pas afficher en tant qu'étiquettes principales
                                                 et pour valeurs les  étiquettes principales
                                                 à utiliser à la place

        - PARAMETRES DES NOEUDS PAR DEFAUT :

            - node_shape [ = 'circle']        : forme des noeuds dessinés. Autres formes disponibles
                                                   rect, ellipse, folder, star [...].
                                                   https://graphviz.org/doc/info/shapes.html

            - node_width [ = 0.35]          : largeur des noeuds

            - node_height [ = 0.35]         : hauteur des noeuds

            - node_color [ = (0.5, 0.2, 1)]   : couleur des noeuds au format HSV

            - node_fontsize [ = 12]         : taille de police de l'étiquette principale des noeuds

            - node_small_fontsize [ = 11]   : taille de police de l'étiquette secondaire des noeuds

            - node_style [ = 'filled']        : style de remplissage. Au choix parmi 'solid', 'dashed',
                                                   'dotted', 'bold', 'rounded', 'filled' [...]
                                                   https://graphviz.org/doc/info/attrs.html#k:style

            - node_main [ = True]          : pour afficher ou pas l'étiquette principale

        - PARAMETRES DES ARCS PAR DEFAUT :

            - edge_fontsize [ = 12]         : taille de la police dans le cas d'un graphe pondéré

            - edge_style [ = 'solid']         : style du tracé, au choix parmi 'solid', 'dashed',
                                                   'dotted', 'bold'

            - edge_arrowhead [= 'empty']      : forme de la tête de la flèche. Au choix parmi 'normal',
                                                   'none', 'invempty', 'open' [...]
                                                   https://graphviz.org/doc/info/attrs.html#k:arrowType

            - edge_arrowsize [= 0.5]        : taille de la tête de la flèche
        '''

        self._modifier(**kwargs)
        self._creer_objet_graphviz()

    def enregistrer(self, nom_fichier = 'mon_graphe', format_image = 'png'):
        '''
         Permet d'enregistrer le graphe au format texte 'graphviz' et au format image choisi.
         Il y a donc deux fichiers qui sont générés.

          - nom_fichier [ = 'mon_graphe'] : nom des deux fichiers sauvegardés dont l'un sera
                                                   suffixé avec l'extension correspondant au format
                                                   image choisi

          - format_image [ = 'png']              : format de fichier de l'image générée. Au choix parmi :
                                                   'ps', 'eps', 'svg', 'jpg', 'tiff' [...]
                                                   https://graphviz.org/doc/info/output.html
        '''
        self.G.render(filename = nom_fichier, format = format_image)


import math

#makes sure seams are of equal length for reassembly
def seam_equilize(edges, vts):

    for edge in edges.keys():
        edge_variants = edges[edge]
        variant_to_length = {}
        for variant in edge_variants:
           variant_to_length[str(variant)] = find_length(variant, vts)
        #find max length / scale factor
        maxlen = max(variant_to_length.values())
        #scale by that length
        for variant in edge_variants:
            if variant_to_length[str(variant)] != maxlen:
                newpt = scale(variant, maxlen, vts, variant_to_length[str(variant)])
                vts[int(variant[1])-1] = newpt[1]
                vts[int(variant[0])-1] = newpt[0]

def find_length(variant, vts):
    pt0 = vts[int(variant[0])-1]
    pt1 = vts[int(variant[1])-1]

    #convert to floats

    pt0 = [float(x) for x in pt0]
    pt1 = [float(x) for x in pt1]

    #length = spatial.distance.cdist(pt0,pt1, "euclidean")
    length = euclidean_dist(pt0,pt1)
    return length

def scale(variant, factor, vts, currentlen):
    pt0 = vts[int(variant[0])-1]
    pt1 = vts[int(variant[1])-1]

    #convert to floats

    pt0 = [float(x) for x in pt0]
    pt1 = [float(x) for x in pt1]

    midpt = midpoint(pt0, pt1)

    newpt_x = pt0[0] + (pt1[0]-pt0[0]) / currentlen * factor
    newpt_y = pt0[1] + (pt1[1]-pt0[1]) / currentlen * factor

    newpt1 = [newpt_x,newpt_y]

    new_midpt = midpoint(pt0, newpt1)
    diff_x = new_midpt[0] - midpt[0]
    diff_y = new_midpt[1] - midpt[1]

    newpt1 = [newpt1[0]-diff_x, newpt1[1]-diff_y]

    newpt0 = [pt0[0]-diff_x, pt0[1]-diff_y]

    return [[str(round(x,4)) for x in newpt0], [str(round(x,4)) for x in newpt1]]

def midpoint(pt_a, pt_b):
    return [(pt_a[0]+pt_b[0])/2.0, (pt_a[1]+pt_b[1])/2.0]

def euclidean_dist(pt_a,pt_b):
    diff1 = pt_a[0] - pt_b[0]
    diff2 = pt_a[1] - pt_b[1]
    return math.sqrt(diff1*diff1 + diff2*diff2)


from pymongo import MongoClient
from initial import pool
import tools
db = MongoClient()

db = db['amino_mongo_test']
db = db.games

def changePuntuation(points, userId):
    for usr in pool.pool:
        if usr['userId'] == userId:
            usr['puntos'] = usr['puntos'] + points
            break

def saveGame(game):

    if len(pool.pool) > 1:
        return db.insert({"players":pool.pool,"game": game})

def updateGame(id):
    if len(pool.pool) > 1:
        db.update_one({"_id":id},{'$set':{"players":pool.pool}})

def getGame(sub, chatId):
    global pool
    pooldb= db.find_one()
    pool.pool= pooldb['players']
    sub.send_message(chatId=chatId,message=f"Se ah restaurado la partida de {pooldb['game']}")

def getPoints(sub,chatId):
    nicks = [usr['nickname'] for usr in pool.pool]
    points = [usr['puntos'] for usr in pool.pool]
    sub.send_message(chatId=chatId,message=f"[CB]Tabla de puntaje:\n{tools.forString(nicks,points=points)}")


from statistics import mean
# try:
#     count= int(input("How many Processes?[int]: ",))
#
#     lst=[]
#     for i in range (count):
#         a= int(input("Enter Process "+str(i+1)+" time : "))
#         lst.append(a)
# except ValueError:
#     print("Enter a number please.")
time1 = []
time2 = []

def fcfs(lst):
    # print("_______List of Programs_________")
    # for i in range (len(lst)):
    #     print("Program: ", i, "     Time: ",lst[i])
    print("_______FCFS_______")
    t1 = 0
    for i in range(len(lst)):
        t1 = t1 + lst[i]
        time1.append(t1)
    print(time1)
    toatl = sum(time1[:len(time1) - 1])
    leng = len(time1)
    avg = toatl / leng
    print("Avg time: ", avg)
    print(lst)
    gant1(lst)

def gant1(lst):
    t1 = 0
    print("0P1 ", end=" ")
    for i in range(len(lst)):
        t1 = t1 + lst[i]
        time1.append(t1)
        if i < len(lst)-1:
            print(str(t1) + "P" + str(i + 2), end=" ")
    print(t1)
    print("")

def pairmaker(lst):
    pair=[]
    for i in range (len(lst)):
        (pair.append([i,lst[i]]))
        # print(pair)
    return pair

def scfs(lst):
    print("_______SCFS_______")
    pair= pairmaker(lst)
    gant2(pair)
    lst=sorted(lst)
    t1 = 0
    for i in range(len(lst)):
        t1 = t1 + lst[i]
        time2.append(t1)
    toatl = sum(time2[:len(time2) - 1])
    print(time2[:len(time2) - 1])
    leng = len(time2)
    avg = toatl / leng
    print("Avg time: ", avg)

def gant2(pair):
    a=[]
    b=[]
    sortedpair=(sorted(pair,key = lambda x: x[1]))
    # print(sortedpair)
    for x,y in sortedpair:
        a.append(x+1)#procces names
        b.append(y)
    print('Process: a: ',a)
    print('Time: b: ',b)

    t1 = 0
    print("0P"+str(a[0]), end=" ")
    for i in range(len(b)):
        t1 = t1 + b[i]
        time1.append(t1)
        if i < len(b) - 1:
            print(str(t1) + "P" + str(a[i+1]), end=" ")
    print(t1)
    print("")

x = [21, 3, 6, 2]
#fcfs(x)
scfs(x)
# 1,21 2,3 3,6 4,2
# 4,2  2,3 3,6 1,21


import cv2
import matplotlib.pyplot as plt

num_of_sample=200
vid=cv2.VideoCapture(0) #to open the camera
face_cascade=cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

iter1=0
while(iter1<num_of_sample):
    r,frame=vid.read();
    frame=cv2.resize(frame,(640,480)) #resizing the frame
    im1=cv2.cvtColor(frame,cv2.COLOR_RGB2GRAY) #gray scale conversion of color image
    face=face_cascade.detectMultiScale(im1)
    for x,y,w,h in(face):
        cv2.rectangle(frame,(x,y),(x+w,y+h),[255,0,0],4)
        iter1+=1
        im_f=im1[y:y+h,x:x+w]
        im_f=cv2.resize(im_f,(112,92))
        cv2.putText(frame,'face No. '+str(iter1),(x,y), cv2.FONT_ITALIC, 1,
                    (255,0,255),2,cv2.LINE_AA)
        path = 'C:/Users/sample/%d.png'%(iter1) #path to save the image
        cv2.imwrite(path,im_f)  #to save the image

cv2.imshow('frame',frame)
cv2.waitKey(1)
vid.release()
cv2.destroyAllWindows()


import socket
import tkinter
from tkinter import Frame, Tk, BOTH, Text, Menu, END
import threading
# import tkFont

top = tkinter.Tk()
top.config(bg="#ffffff")
top.geometry("600x600")
top.title("GUI")

s = socket.socket()
rueda = dict()

class Looping(object):
    def __init__(self):
        # helv100 = tkFont.Font(family='Helvetica',size=100, weight='bold')
        self.B_start = tkinter.Button(top, text ="Start", command = self.button_start)
        self.B_start.pack(fill=BOTH, expand=1)
        self.B_stop = tkinter.Button(top, text ="Stop", command = self.button_stop)
        self.B_stop.pack(fill=BOTH, expand=1)
        self.isRunning = True
    def button_start(self):
        l.isRunning = True
        t = threading.Thread(target = l.measuredistance)
        t.start()
    def measuredistance(self):
        global recived
        s = socket.socket()
        s.connect(('127.0.0.1', 6000))
        while self.isRunning == True:
            recived = s.recv(60)#number of bytes recived
            print(recived)
        else:
             print("Not connected to the wheel")
    def button_stop(self):
        l.isRunning = False
        s.close()
        print("Socket connection breaked")

l=Looping()
top.mainloop()


from urllib.request import urlopen
from urllib.parse import urlencode, urlparse, parse_qs, quote
import time
from datetime import date

from django.core.management.base import BaseCommand
from bs4 import BeautifulSoup

from dgeq.models import Contributor
from ...models import OIQQuery, OIQResult

def fetch_soup(url, data=None):
    if data:
        data = urlencode(data).encode('ascii')
    with urlopen(url, data) as fp:
        contents = fp.read()
    return BeautifulSoup(contents)

def parse_contact_ids(resulttable):
    result = []
    for resultrow in resulttable.tbody('tr'):
        detail_link = resultrow.td.a.attrs['href']
        qs = urlparse(detail_link).query
        contactid = parse_qs(qs)['ContactId'][0]
        result.append(contactid)
    return result

def fetch_oiq_info(query):
    firstname = query.person.firstname
    lastname = query.person.lastname
    url = 'http://www.oiq.qc.ca/fr/Pages/BottinDesMembres.aspx'
    soup = fetch_soup(url)
    hidden_inputs = soup('form', {'name':'aspnetForm'})[0]('input', type='hidden')
    post_data = {}
    for input in hidden_inputs:
        post_data[input.attrs['name']] = input.attrs['value']
    post_data['ctl00$PlaceHolderMain$txtLName'] = lastname
    post_data['ctl00$PlaceHolderMain$txtFName'] = firstname
    soup = fetch_soup(url, post_data)
    resulttable = soup('table', id='ctl00_PlaceHolderMain_tblResults')[0]
    if resulttable.tbody is None: # no result
        print("Nothing")
        return
    contactids = parse_contact_ids(resulttable)
    print("Got %d contact ids" % len(contactids))
    for contactid in contactids:
        if OIQResult.objects.filter(contactid=contactid).exists():
            print("We've already fetched contactid %s. Skipping." % contactid)
            continue
        print("Fetching contact %s" % contactid)
        time.sleep(1)
        url = "http://www.oiq.qc.ca/fr/Pages/BottinDesMembresDetails.aspx?ContactId=" + quote(contactid)
        soup = fetch_soup(url)
        def getfield(name):
            try:
                return soup('span', id='ctl00_PlaceHolderMain_' + name)[0].get_text().strip()
            except IndexError: # It's possible that the field is not there
                return ''
        result = OIQResult(query=query)
        result.contactid = contactid
        fullname = getfield('lblContactName')
        print("The name is: %s" % fullname)
        result.lastname, result.firstname = fullname.split(', ', 1)
        result.category = getfield('lblCategory')
        result.employer = getfield('lblEmployer')
        print("Employer is: %s" % result.employer)
        result.address = getfield('lblAddress')
        result.city = getfield('lblCity')
        result.postal_code = getfield('lblPostalCode')
        result.telephone = getfield('lblPhone')
        result.graduation = getfield('lblGraduationDate')
        result.university = getfield('lblSchool')
        result.speciality = getfield('lblSpecialty')
        result.save()

class Command(BaseCommand):
    def handle(self, *args, **options):
        for index, contributor in enumerate(Contributor.contributors_by_total_amount()):
            print("Checking out [%d] %s (%d $)" % (index, contributor, contributor.total_amount))
            if contributor.person.oiqquery_set.count() > 0:
                print("We've already queried that person. Skipping.")
                continue
            query = OIQQuery(date=date.today(), person=contributor.person)
            query.save()
            try:
                fetch_oiq_info(query)
            except Exception:
                query.delete() # It didn't complete correctly, remove it.
            except KeyboardInterrupt:
                query.delete()
                raise
            time.sleep(1)


# 1365. How Many Numbers Are Smaller Than the Current Number

# vwc 178
# 2021/12/21

# Runtime: 48 ms, faster than 96.52% of Python3 online submissions for How Many Numbers Are Smaller Than the Current Number.
# Memory Usage: 14.4 MB, less than 13.03% of Python3 online submissions for How Many Numbers Are Smaller Than the Current Number.

# prefix sum. O(max(num) + n)

class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        counts = [0] * (max(nums) + 1)
        for num in nums:
            counts[num] += 1
        sums = [0]
        for x in counts:
            sums.append(sums[-1] + x)
        ans = []
        for num in nums:
            ans.append(sums[num])
        return ans

1365. How Many Numbers Are Smaller Than the Current Number.py


#!/bin/python3

import math
import os
import random
import re
import sys

if __name__ == '__main__':

        d = []
        d = sys.stdin.read().splitlines()
        d = [list(map(int,i.split())) for i in d]
        maxval = None
        for j in range(4):
         for i in range(4):
           add = d[j][i] + d[j][i+1] + d[j][i+2] + d[j+1][i+1]                   + d[j+2][i] + d[j+2][i+1] + d[j+2][i+2]
           if maxval ==None:
            maxval=add
           elif add>maxval:
            maxval=add
print(maxval)


from django.contrib import admin
from groupup.models import Location, Group
# Register your models here.

class GroupAdmin(admin.ModelAdmin):
    fieldsets = [
        ("Location", {'fields':['location']}),
        ('Title', {'fields':['title']}),
        ('url',{'fields':['url']}),
        ('views',{'fields':['views']}),
        ('likes',{'fields':['likes']}),
    ]
    list_display = ('title','location','url')

class LocationAdmin(admin.ModelAdmin):
    prepopulated_fields = {'slug':('name',)}

admin.site.register(Location, LocationAdmin)
admin.site.register(Group, GroupAdmin)