# coding=utf-8
import numpy
import matplotlib
import tkinter as tk
from tkinter import ttk
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from numpy.lib.function_base import append
from STCore.item.Star import StarItem
import STCore.Tracker
import STCore.utils.Icons as icons
from matplotlib.patches import Circle, Polygon

from STCore.utils.backgroundEstimator import GetBackgroundMean
#region Variables
App = None
leftPanel = None
rightPanel = None
Image = None
canvas = None
ImageViewer = None
BrightLabel = None
ConfIcon = None
MousePress = None
XLoc= YLoc = None
#endregion
lastRadius = 10
lastBounds = 60

def Awake(Data, star : StarItem, OnStarChange, OnStarAdd = None, starIndex = -1, location = (0,0), name = ""):
	global App, Image, canvas, leftPanel, rightPanel, ImageViewer, BrightLabel, XLoc, YLoc, ConfIcon
	if App is not None:
		return
	App = tk.Toplevel()
	App.configure(bg= "gray15")
	App.wm_title(string = "Configurar Estrella")
	App.protocol("WM_DELETE_WINDOW", CloseWindow)
	App.attributes('-topmost', 'true')
	App.resizable(False, False)
	App.grid_columnconfigure(tuple(range(3)), weight=1)
	App.grid_rowconfigure(tuple(range(3)), weight=1)

	bounds = lastBounds
	radius = lastRadius
	threshold = 0.75
	sigma = 2
	if star is not None:
		name = star.name
		location = star.location
		bounds = star.bounds
		radius = star.radius
		threshold = star.threshold
		sigma = star.bsigma

	StarName = tk.StringVar(value = name)
	XLoc = tk.IntVar(value = location[1])
	YLoc= tk.IntVar(value = location[0])
	StarBounds = tk.IntVar(value = bounds)
	StarRadius = tk.IntVar(value = radius)
	StarThreshold = tk.IntVar(value = threshold)
	SigmaFactor = tk.IntVar(value = sigma)

	nameLabel = ttk.Label(App, text = "Nombre de la estrella: ")
	nameEntry = ttk.Entry(App, textvariable = StarName)

	posLabel = ttk.Label(App, text = "Posicion:")
	XLocSpinBox = ttk.Spinbox(App, from_ = 0, to = Data.shape[1], textvariable = XLoc, width = 10)
	YLocSpinBox = ttk.Spinbox(App, from_ = 0, to = Data.shape[0], textvariable = YLoc, width = 10)

	radiusLabel = ttk.Label(App, text = "Tamaño de la estrella:")
	RadiusSpinBox = ttk.Spinbox(App, from_ = 1, to = StarBounds.get(), textvariable = StarRadius, width = 10, increment = 1)

	boundsLabel = ttk.Label(App, text = "Radio de búsqueda:")
	BoundSpinBox = ttk.Spinbox(App, from_ = 0, to = min(Data.shape), textvariable = StarBounds, width = 10, increment = 10)

	nameLabel.grid(row = 0, column = 0, columnspan=2, sticky="w")
	nameEntry.grid (row =0,column = 2)
	posLabel.grid(row = 1, column = 0, sticky="w")
	XLocSpinBox.grid(row = 1, column = 1)
	YLocSpinBox.grid(row = 1, column = 2, padx = 20)
	radiusLabel.grid(row = 2, column = 0, columnspan=2, sticky="w")
	RadiusSpinBox.grid(row = 2, column = 2)
	boundsLabel.grid(row = 3, column = 0, columnspan=2, sticky="w")
	BoundSpinBox.grid(row = 3, column = 2)

	#typeSelection = tk.IntVar(Window, value = Type)
	#typeFrame = tk.LabelFrame(leftPanel,text = "Tipo de Estrella")
	#typeFrame.grid(row = 1, column = 0, columnspan = 1, sticky = tk.W + tk.E)
	#ttk.Radiobutton(typeFrame, text = "Variable", variable = typeSelection, value = 0).grid(row = 0, sticky = tk.W)
	#ttk.Radiobutton(typeFrame, text = "Referencia", variable = typeSelection, value = 1).grid (row = 1, sticky = tk.W)

	#ThreSpinBox = ttk.Scale(trackFrame, from_ = 0, to = 100, variable = StarThreshold, orient=tk.HORIZONTAL)
	#SigSpinBox = ttk.Spinbox(trackFrame, from_ = 0, to = 4, textvariable = SigmaFactor, width=10, increment= 0.5)

	#ttk.Label(trackFrame, text = "Variabilidad:").grid(row = 6, column = 2, sticky = tk.W)
	#ThreSpinBox.grid(row = 6, column = 3, columnspan = 2, sticky = tk.EW)

	#ttk.Label(trackFrame, text = "Rechazar si Sigma es menor a:").grid(row = 7, column = 2, sticky = tk.W)
	#SigSpinBox.grid(row = 7, column = 3, columnspan = 1, sticky = tk.EW)

	DrawCanvas(location, radius, Data)

	back_median = float(GetBackgroundMean(Data))

	area = (2 * radius) ** 2
	snr = (Image.get_array()[radius:3*radius, radius:3*radius].sum() / (area * back_median))

	BrightLabel = ttk.Label(App, text = "Señal a Ruido: %.2f " % snr,font="-weight bold", width = 18, anchor = "w")
	_conf = str(numpy.clip(int(snr/2 + 1), 1, 3))
	ConfIcon = ttk.Label(App, image = icons.Icons["conf"+ _conf])

	ConfIcon.grid(row = 4, column = 2)
	BrightLabel.grid(row = 4, column = 0, columnspan=2)

	cmd = lambda a,b,c : UpdateCanvas(Data,(int(YLoc.get()), int(XLoc.get())), int(StarRadius.get()), back_median)
	XLoc.trace("w",cmd)
	YLoc.trace("w",cmd)
	StarRadius.trace("w",cmd)

	applycmd = lambda: Apply(name=StarName.get(),loc=(YLoc.get(), XLoc.get()), bounds=StarBounds.get(),
						 radius=StarRadius.get() , Type=1,
						 value=GetMax(Data,XLoc.get(), YLoc.get(), StarRadius.get(), back_median)
						 , threshold=StarThreshold.get(),
						 stars=star, OnStarChange= OnStarChange, OnStarAdd = OnStarAdd,starIndex=starIndex, sigma = SigmaFactor.get())

	controlButtons = ttk.Frame(App)
	controlButtons.grid(row =4, column=3)

	CancelButton = ttk.Button(controlButtons, text = "Cancelar", command = CloseWindow, image = icons.Icons["delete"], compound = "left")
	ApplyButton = ttk.Button(controlButtons, text = "Aceptar", command = applycmd, image = icons.Icons["check"], compound = "right", style="Highlight.TButton")

	CancelButton.grid(row = 0, column = 0)
	ApplyButton.grid(row = 0, column = 1, padx=4)

def GetMax(data, xloc, yloc, radius, background):
	stLoc = (yloc, xloc)
	clipLoc = numpy.clip(stLoc, radius, (data.shape[0] - radius, data.shape[1] - radius))
	crop = data[clipLoc[0]-radius : clipLoc[0]+radius,clipLoc[1]-radius : clipLoc[1]+radius]

	area = (2 * radius)**2
	snr = (crop.sum() / (area * background))
	return int(numpy.max(crop) - background), snr

def DrawCanvas(stLoc, radius, data):
	global Image, canvas, rig
	fig = matplotlib.figure.Figure(figsize = (2,2), dpi = 100)
	axis = fig.add_subplot(111)
	axis.set_axis_off()
	fig.subplots_adjust(0,0,1,1)
	fig.set_facecolor("black")

	clipLoc = numpy.clip(stLoc, radius, (data.shape[0] - radius, data.shape[1] - radius))
	crop = data[clipLoc[0]-radius*2 : clipLoc[0]+radius*2,clipLoc[1]-radius*2 : clipLoc[1]+radius*2]

	levels = STCore.DataManager.Levels
	Image = axis.imshow(crop, vmin = levels[1], vmax = levels[0], cmap=STCore.ImageView.ColorMaps[STCore.Settings._VISUAL_COLOR_.get()], norm = STCore.ImageView.Modes[STCore.Settings._VISUAL_MODE_.get()])
	canvas = FigureCanvasTkAgg(fig, master=App)
	canvas.draw()

	Viewport = canvas.get_tk_widget()
	Viewport.configure(bg="black")
	Viewport.config(cursor = "fleur")

	canvas.mpl_connect("button_press_event", OnMousePress)
	canvas.mpl_connect("motion_notify_event", OnMouseDrag)
	canvas.mpl_connect("button_release_event", OnMouseRelase)

	circle = Circle((radius*2 - 0.5, radius*2 - 0.5), radius, facecolor = "none", edgecolor = "lime")

	axis.add_artist(circle)
	Viewport.grid(row = 0, column=3, rowspan=3)

def UpdateCanvas(data, stLoc, radius, bkgMedian):
	global Image, canvas, BrightLabel, ConfIcon
	radius = numpy.clip(radius, 2, min(data.shape))
	clipLoc = numpy.clip(stLoc, radius, (data.shape[0] - radius, data.shape[1] - radius))
	crop = data[clipLoc[0]-radius*2 : clipLoc[0]+radius*2,clipLoc[1]-radius*2 : clipLoc[1]+radius*2]
	Image.set_array(crop)

	area = (2 * radius) ** 2
	snr = (crop[radius:3*radius, radius:3*radius].sum() / (area * bkgMedian))
	BrightLabel.config(text = "Señal a Ruido: %.2f " % snr)

	_conf = str(numpy.clip(int(snr/2 + 1), 1, 3))
	ConfIcon.config(image = icons.Icons["conf"+_conf])
	canvas.draw_idle()

def Apply(name, loc, bounds, radius, Type, value, threshold, stars, OnStarChange, OnStarAdd, starIndex, sigma):

	st = StarItem()
	st.name = name
	st.location = loc
	st.bounds = bounds
	st.radius = radius
	st.value = value[0]
	st.std = value[1]
	st.threshold = 1#(threshold * 0.01)
	st.bsigma = 2#sigma

	if starIndex == -1:
		if OnStarAdd is not None:
			OnStarAdd(st)
		STCore.Tracker.DataChanged = True

	OnStarChange(st, starIndex)
	st.PrintData()
	CloseWindow()

	global XLoc, YLoc, lastRadius, lastBounds
	lastBounds = bounds
	lastRadius = radius
	XLoc = YLoc = None

def CloseWindow():
	global App, BrightLabel, ConfIcon
	App.destroy()
	App = None
	BrightLabel = None
	ConfIcon = None

def OnMousePress(event):
	global MousePress
	MousePress = XLoc.get(), YLoc.get(), event.xdata, event.ydata

def OnMouseDrag(event):
	global XLoc, YLoc
	global MousePress
	if MousePress is None or event.inaxes is None: return
	x0, y0, xpress, ypress = MousePress
	dx = event.xdata - xpress
	dy = event.ydata - ypress
	XLoc.set(int(x0 - dx))
	YLoc.set(int(y0 - dy))

def OnMouseRelase(event):
	global MousePress
	MousePress = None


from tkinter import messagebox
import tkinter as tk

class Alert:

    @staticmethod
    def alert(message, title):
        root = tk.Tk()
        root.withdraw()
        messagebox.showinfo(title=title, message=message)
        root.destroy()
        root.quit()


import sys
import random
import parse

def main():
    while True:
        line = sys.stdin.readline()
        for data in parse.words(line):
            if isinstance(data, str):
                sys.stdout.write(data)
            else:
                if len(data) < 4:
                    sys.stdout.write(''.join(data))
                else:
                    sys.stdout.write(confuse(data))

def confuse(data):
    array = [data[0]]
    array.extend(random.sample(data[1:-1], len(data) - 2))
    array.append(data[-1])
    return ''.join(array)

if __name__ == '__main__':
    main()

Python 2.X/ZERO/Console Based/Confuse/Version 2/confuse_3.py


# -*- coding: utf-8 -*-
"""
Created on Thu Sep  3 16:34:24 2020

@author: Hp
"""

import numpy as np
import pandas as pd
from sklearn.preprocessing import LabelEncoder
import matplotlib.pyplot as plt
import seaborn as sns

train_data  = pd.read_csv("application_train.csv")
test_date   = pd.read_csv("application_test.csv")

train_data['TARGET'].value_counts()
train_data['TARGET'].astype(int).plot.hist();

features_with_na = [features for features in train_data.columns if train_data[features].isnull().sum()>1]
#use models such as XGBoost that can handle missing values
# with no need for imputation. Another option would be to drop columns
#  with a high percentage of missing values, although it is impossible to know ahead of
#  time if these columns will be helpful to our model.
#  Therefore, we will keep all of the columns for now.

for features in features_with_na:
    print(features, np.round(train_data[features].isnull().mean(), 4),  ' % missing values')

train_data.dtypes.value_counts()
train_data.select_dtypes('object').apply(pd.Series.nunique, axis = 0)
train_data = pd.get_dummies(train_data,drop_first=True)
test_date = pd.get_dummies(test_date,drop_first=True)

train_target = train_data['TARGET']
train_data,test_date = train_data.align(test_date,join = 'inner', axis = 1)
train_data['TARGET'] = train_target
a= train_data.describe()

train_data['DAYS_BIRTH'] =  train_data['DAYS_BIRTH']/-365
train_data['DAYS_EMPLOYED'].describe()
#it doesnt look right since the max value is 1000 years!

anom = train_data[train_data['DAYS_EMPLOYED'] == 365243]
non_anom = train_data[train_data['DAYS_EMPLOYED'] != 365243]
print('The non-anomalies default on %0.2f%% of loans' % (100 * non_anom['TARGET'].mean()))
print('The anomalies default on %0.2f%% of loans' % (100 * anom['TARGET'].mean()))
print('There are %d anomalous days of employment' % len(anom))

# Create an anomalous flag column
train_data['DAYS_EMPLOYED_ANOM'] = train_data["DAYS_EMPLOYED"] == 365243

# Replace the anomalous values with nan
train_data['DAYS_EMPLOYED'].replace({365243: np.nan}, inplace = True)

train_data['DAYS_EMPLOYED'].plot.hist(title = 'Days Employment Histogram');
plt.xlabel('Days Employment');

test_date['DAYS_EMPLOYED_ANOM'] = test_date["DAYS_EMPLOYED"] == 365243
test_date["DAYS_EMPLOYED"].replace({365243: np.nan}, inplace = True)

correlations = train_data.corr()['TARGET'].sort_values()

# Display correlations
print('Most Positive Correlations:\n', correlations.tail(15))
print('\nMost Negative Correlations:\n', correlations.head(15))
#As the client gets older, there is a negative linear relationship with the target meaning that as clients get older, they tend to repay their loans on time more often.

plt.style.use('fivethirtyeight')

# Plot the distribution of ages in years
plt.hist(train_data['DAYS_BIRTH'], edgecolor = 'k', bins = 25)
plt.title('Age of Client'); plt.xlabel('Age (years)'); plt.ylabel('Count');

plt.figure(figsize = (10, 8))

# KDE plot of loans that were repaid on time
sns.kdeplot(train_data.loc[train_data['TARGET'] == 0, 'DAYS_BIRTH'] , label = 'target == 0')

# KDE plot of loans which were not repaid on time
sns.kdeplot(train_data.loc[train_data['TARGET'] == 1, 'DAYS_BIRTH'] , label = 'target == 1')

# Labeling of plot
plt.xlabel('Age (years)'); plt.ylabel('Density'); plt.title('Distribution of Ages');

#KDE plot shows that as we get older we tend to pay our loans back

data_age  = train_data[['TARGET','DAYS_BIRTH']]
data_age['YEARS_BINNED'] = pd.cut(data_age['DAYS_BIRTH'], bins = np.linspace(20, 70, num = 11))

age_group = data_age.groupby('YEARS_BINNED').mean()

plt.figure(figsize = (8, 8))

# Graph the age bins and the average of the target as a bar plot
plt.bar(age_group.index.astype(str), 100 * age_group['TARGET'])

# Plot labeling
plt.xticks(rotation = 75); plt.xlabel('Age Group (years)'); plt.ylabel('Failure to Repay (%)')
plt.title('Failure to Repay by Age Group');

ext_data = train_data[['TARGET', 'EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH']]
ext_data_corrs = ext_data.corr()
ext_data_corrs
plt.figure(figsize = (8, 6))

# Heatmap of correlations
sns.heatmap(ext_data_corrs, cmap = plt.cm.RdYlBu_r, vmin = -0.25, annot = True, vmax = 0.6)
plt.title('Correlation Heatmap');

#All three EXT_SOURCE featureshave negative correlations with the target, indicating that as the value of the EXT_SOURCE increases, the client is more likely to repay the loan.

#For Feature Engineering use variants of gradient boosting
#Two methods are currently used for this Feature engineering
#1.Polynomial Features
#2.Domain Knowledge Features

#1.
poly_features = train_data[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH', 'TARGET']]
poly_features_test = test_date[['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH']]

# imputer for handling missing values
from sklearn.impute import SimpleImputer
imputer = SimpleImputer(strategy = 'median')

poly_target = poly_features['TARGET']

poly_features = poly_features.drop(columns = ['TARGET'])

# Need to impute missing values
poly_features = imputer.fit_transform(poly_features)
poly_features_test = imputer.transform(poly_features_test)

from sklearn.preprocessing import PolynomialFeatures

# Create the polynomial object with specified degree
poly_transformer = PolynomialFeatures(degree = 3)
poly_transformer.fit(poly_features)

# Transform the features
poly_features = poly_transformer.transform(poly_features)
poly_features_test = poly_transformer.transform(poly_features_test)
print('Polynomial Features shape: ', poly_features.shape)
poly_transformer.get_feature_names(input_features = ['EXT_SOURCE_1', 'EXT_SOURCE_2', 'EXT_SOURCE_3', 'DAYS_BIRTH'])[:15]

# Create a dataframe of the features
poly_features = pd.DataFrame(poly_features,
                             columns = poly_transformer.get_feature_names(['EXT_SOURCE_1', 'EXT_SOURCE_2',
                                                                           'EXT_SOURCE_3', 'DAYS_BIRTH']))

# Add in the target
poly_features['TARGET'] = poly_target

# Find the correlations with the target
poly_corrs = poly_features.corr()['TARGET'].sort_values()

# Display most negative and most positive
print(poly_corrs.head(10))
print(poly_corrs.tail(5))

poly_features_test = pd.DataFrame(poly_features_test,
                                  columns = poly_transformer.get_feature_names(['EXT_SOURCE_1', 'EXT_SOURCE_2',
                                                                                'EXT_SOURCE_3', 'DAYS_BIRTH']))

# Merge polynomial features into training dataframe
poly_features['SK_ID_CURR'] = train_data['SK_ID_CURR']
app_train_poly = train_data.merge(poly_features, on = 'SK_ID_CURR', how = 'left')

# Merge polnomial features into testing dataframe
poly_features_test['SK_ID_CURR'] = test_date['SK_ID_CURR']
app_test_poly = test_date.merge(poly_features_test, on = 'SK_ID_CURR', how = 'left')

# Align the dataframes
app_train_poly, app_test_poly = app_train_poly.align(app_test_poly, join = 'inner', axis = 1)

# Print out the new shapes
print('Training data with polynomial features shape: ', app_train_poly.shape)
print('Testing data with polynomial features shape:  ', app_test_poly.shape)

app_train_domain = train_data.copy()
app_test_domain = test_date.copy()

app_train_domain['CREDIT_INCOME_PERCENT'] = app_train_domain['AMT_CREDIT'] / app_train_domain['AMT_INCOME_TOTAL']
app_train_domain['ANNUITY_INCOME_PERCENT'] = app_train_domain['AMT_ANNUITY'] / app_train_domain['AMT_INCOME_TOTAL']
app_train_domain['CREDIT_TERM'] = app_train_domain['AMT_ANNUITY'] / app_train_domain['AMT_CREDIT']
app_train_domain['DAYS_EMPLOYED_PERCENT'] = app_train_domain['DAYS_EMPLOYED'] / app_train_domain['DAYS_BIRTH']
app_test_domain['CREDIT_INCOME_PERCENT'] = app_test_domain['AMT_CREDIT'] / app_test_domain['AMT_INCOME_TOTAL']
app_test_domain['ANNUITY_INCOME_PERCENT'] = app_test_domain['AMT_ANNUITY'] / app_test_domain['AMT_INCOME_TOTAL']
app_test_domain['CREDIT_TERM'] = app_test_domain['AMT_ANNUITY'] / app_test_domain['AMT_CREDIT']
app_test_domain['DAYS_EMPLOYED_PERCENT'] = app_test_domain['DAYS_EMPLOYED'] / app_test_domain['DAYS_BIRTH']

# #LOGISTIC REGRESSION

from sklearn.preprocessing import MinMaxScaler

# # Drop the target from the training data
# if 'TARGET' in train_data:
#     train = train_data.drop(columns = ['TARGET'])
# else:
#     train = train_data.copy()

# # Feature names
# features = list(train.columns)

# # Copy of the testing data
# test = test_date.copy()

# # Median imputation of missing values
# imputer = SimpleImputer(strategy = 'median')

# # Scale each feature to 0-1
# scaler = MinMaxScaler(feature_range = (0, 1))

# # Fit on the training data
# imputer.fit(train)

# # Transform both training and testing data
# train = imputer.transform(train)
# test = imputer.transform(test)

# # Repeat with the scaler
# scaler.fit(train)
# train = scaler.transform(train)
# test = scaler.transform(test)

# print('Training data shape: ', train.shape)
# print('Testing data shape: ', test.shape)
train_labels = train_data['TARGET']

# from sklearn.linear_model import LogisticRegression

# # Make the model with the specified regularization parameter
# log_reg = LogisticRegression(C = 0.0001)
# # Train on the training data
# log_reg.fit(train, train_labels)

# log_reg_pred = log_reg.predict_proba(test)[:, 1]
# log_reg_pred

# # Submission dataframe
# submit = test_date[['SK_ID_CURR']]
# submit['TARGET'] = log_reg_pred

# submit.head()
# from sklearn.naive_bayes import GaussianNB

# from sklearn.neighbors import KNeighborsClassifier

poly_features_names = list(app_train_poly.columns)

# Impute the polynomial features
imputer = SimpleImputer(strategy = 'median')

poly_features = imputer.fit_transform(app_train_poly)
poly_features_test = imputer.transform(app_test_poly)

# Scale the polynomial features
scaler = MinMaxScaler(feature_range = (0, 1))

poly_features = scaler.fit_transform(poly_features)
poly_features_test = scaler.transform(poly_features_test)

from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, confusion_matrix
model1= LogisticRegression(solver='lbfgs')
model1.fit(poly_features,train_labels)
pred1= model1.predict(poly_features)
accuracy1= accuracy_score(train_labels,pred1)
print(round(accuracy1*100,2))
confusionmat2= confusion_matrix(train_labels,pred1,labels=[0,1])
print(confusionmat2)

"NAIVE CLASSIFIER"
from sklearn.naive_bayes import GaussianNB

gnb = GaussianNB()
gnb.fit(poly_features,train_labels)
pred4= gnb.predict(poly_features)
accuracy2= accuracy_score(train_labels,pred4)
print(round(accuracy2*100,2))
confusionmat4= confusion_matrix(y_test,pred4,labels=[0,1])
print(confusionmat4)

from sklearn.neighbors import KNeighborsClassifier
knn_model = KNeighborsClassifier()
knn_model.fit(poly_features,train_labels)
pred5= knn_model.predict(poly_features)
accuracy3= accuracy_score(train_labels,pred5)
print(round(accuracy3*100,2))
confusionmat4= confusion_matrix(y_test,pred4,labels=[0,1])
print(confusionmat4)

from sklearn.ensemble import RandomForestClassifier
random_forest = RandomForestClassifier(n_estimators = 100, random_state = 50, verbose = 1, n_jobs = -1)
random_forest.fit(poly_features,train_labels)
pred6= random_forest.predict(poly_features)
accuracy4= accuracy_score(train_labels,pred6)
print(round(accuracy4*100,2))
confusionmat4= confusion_matrix(y_test,pred4,labels=[0,1])
print(confusionmat4)


"""
Medium

Given a binary tree, return the preorder traversal of its nodes' values.
Example:
Input: [1,null,2,3]
   1
    \
     2
    /
   3
Output: [1,2,3]
Follow up: Recursive solution is trivial, could you do it iteratively?
"""

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def visitAlongLeftBranch(self, x, res, s):
        while x:
            res.append(x.val)
            if x.right:
                s.append(x.right)
            x = x.left

    def preorderTraversal(self, root: TreeNode) -> List[int]:
        if not root:
            return []
        res = []
        s = [root]
        while s:
            self.visitAlongLeftBranch(s.pop(), res, s)
        return res

LeetCode2019/144. Binary Tree Preorder Traversal.py


import preprocess
import time
import random
from models import utils
from MulticoreTSNE import MulticoreTSNE as TSNE

preprocessed_data_path = preprocess.preprocessed_path
tsne_outputs_path = '../data/tsne_outputs/'

class MultiCoreTSNE:

    def __init__(self, x_tr, y_tr, w_tr, e_tr, x_te, id_te):

        self.x_train = x_tr
        self.y_train = y_tr
        self.w_train = w_tr
        self.e_train = e_tr
        self.x_test = x_te
        self.id_test = id_te

    def train(self, parameters):

        tsne = TSNE(**parameters)
        tsne_outputs = tsne.fit_transform(self.x_train)

        utils.save_data_to_pkl(tsne_outputs, tsne_outputs_path + 'tsne_outputs.p')

def tsne_train(seed):

    x_train, y_train, w_train, e_train, x_test, id_test = utils.load_preprocessed_data(preprocessed_data_path)

    parameters = {'n_components': 2,
                  'perplexity': 30.0,
                  'early_exaggeration': 12.0,
                  'learning_rate': 200.0,
                  'n_iter': 500,
                  'n_iter_without_progress': 300,
                  'min_grad_norm': 1e-07,
                  'metric': 'euclidean',
                  'init': 'random',
                  'verbose': 1,
                  'random_state': seed,
                  'method': 'barnes_hut',
                  'angle': 0.5,
                  'n_jobs': 8}

    MTSNE = MultiCoreTSNE(x_train, y_train, w_train, e_train, x_test, id_test)

    MTSNE.train(parameters=parameters)

if __name__ == "__main__":

    start_time = time.time()

    utils.check_dir([tsne_outputs_path])

    # Create Global Seed for Training and Cross Validation
    global_seed = random.randint(0, 300)

    print('======================================================')
    print('Start Training...')
    print('======================================================')

    tsne_train(global_seed)

    print('======================================================')
    print('All Task Done!')
    print('Global Seed: {}'.format(global_seed))
    print('Total Time: {}s'.format(time.time() - start_time))
    print('======================================================')


# coding: utf-8

from __future__ import absolute_import
from datetime import date, datetime  # noqa: F401

from typing import List, Dict  # noqa: F401

from swagger_server.models.base_model_ import Model
from swagger_server.models.port import Port  # noqa: F401,E501
from swagger_server import util

class Connection(Model):
    """NOTE: This class is auto generated by the swagger code generator program.

    Do not edit the class manually.
    """
    def __init__(self, id: str=None, name: str=None, ingress_port: Port=None, egress_port: Port=None, quantity: int=None, start_time: datetime=None, end_time: datetime=None, status: str=None, complete: bool=False):  # noqa: E501
        """Connection - a model defined in Swagger

        :param id: The id of this Connection.  # noqa: E501
        :type id: str
        :param name: The name of this Connection.  # noqa: E501
        :type name: str
        :param ingress_port: The ingress_port of this Connection.  # noqa: E501
        :type ingress_port: Port
        :param egress_port: The egress_port of this Connection.  # noqa: E501
        :type egress_port: Port
        :param quantity: The quantity of this Connection.  # noqa: E501
        :type quantity: int
        :param start_time: The start_time of this Connection.  # noqa: E501
        :type start_time: datetime
        :param end_time: The end_time of this Connection.  # noqa: E501
        :type end_time: datetime
        :param status: The status of this Connection.  # noqa: E501
        :type status: str
        :param complete: The complete of this Connection.  # noqa: E501
        :type complete: bool
        """
        self.swagger_types = {
            'id': str,
            'name': str,
            'ingress_port': Port,
            'egress_port': Port,
            'quantity': int,
            'start_time': datetime,
            'end_time': datetime,
            'status': str,
            'complete': bool
        }

        self.attribute_map = {
            'id': 'id',
            'name': 'name',
            'ingress_port': 'ingress_port',
            'egress_port': 'egress_port',
            'quantity': 'quantity',
            'start_time': 'start_time',
            'end_time': 'end_time',
            'status': 'status',
            'complete': 'complete'
        }
        self._id = id
        self._name = name
        self._ingress_port = ingress_port
        self._egress_port = egress_port
        self._quantity = quantity
        self._start_time = start_time
        self._end_time = end_time
        self._status = status
        self._complete = complete

    @classmethod
    def from_dict(cls, dikt) -> 'Connection':
        """Returns the dict as a model

        :param dikt: A dict.
        :type: dict
        :return: The connection of this Connection.  # noqa: E501
        :rtype: Connection
        """
        return util.deserialize_model(dikt, cls)

    @property
    def id(self) -> str:
        """Gets the id of this Connection.

        :return: The id of this Connection.
        :rtype: str
        """
        return self._id

    @id.setter
    def id(self, id: str):
        """Sets the id of this Connection.

        :param id: The id of this Connection.
        :type id: str
        """
        if id is None:
            raise ValueError("Invalid value for `id`, must not be `None`")  # noqa: E501

        self._id = id

    @property
    def name(self) -> str:
        """Gets the name of this Connection.

        :return: The name of this Connection.
        :rtype: str
        """
        return self._name

    @name.setter
    def name(self, name: str):
        """Sets the name of this Connection.

        :param name: The name of this Connection.
        :type name: str
        """
        if name is None:
            raise ValueError("Invalid value for `name`, must not be `None`")  # noqa: E501

        self._name = name

    @property
    def ingress_port(self) -> Port:
        """Gets the ingress_port of this Connection.

        :return: The ingress_port of this Connection.
        :rtype: Port
        """
        return self._ingress_port

    @ingress_port.setter
    def ingress_port(self, ingress_port: Port):
        """Sets the ingress_port of this Connection.

        :param ingress_port: The ingress_port of this Connection.
        :type ingress_port: Port
        """
        if ingress_port is None:
            raise ValueError("Invalid value for `ingress_port`, must not be `None`")  # noqa: E501

        self._ingress_port = ingress_port

    @property
    def egress_port(self) -> Port:
        """Gets the egress_port of this Connection.

        :return: The egress_port of this Connection.
        :rtype: Port
        """
        return self._egress_port

    @egress_port.setter
    def egress_port(self, egress_port: Port):
        """Sets the egress_port of this Connection.

        :param egress_port: The egress_port of this Connection.
        :type egress_port: Port
        """
        if egress_port is None:
            raise ValueError("Invalid value for `egress_port`, must not be `None`")  # noqa: E501

        self._egress_port = egress_port

    @property
    def quantity(self) -> int:
        """Gets the quantity of this Connection.

        :return: The quantity of this Connection.
        :rtype: int
        """
        return self._quantity

    @quantity.setter
    def quantity(self, quantity: int):
        """Sets the quantity of this Connection.

        :param quantity: The quantity of this Connection.
        :type quantity: int
        """

        self._quantity = quantity

    @property
    def start_time(self) -> datetime:
        """Gets the start_time of this Connection.

        :return: The start_time of this Connection.
        :rtype: datetime
        """
        return self._start_time

    @start_time.setter
    def start_time(self, start_time: datetime):
        """Sets the start_time of this Connection.

        :param start_time: The start_time of this Connection.
        :type start_time: datetime
        """

        self._start_time = start_time

    @property
    def end_time(self) -> datetime:
        """Gets the end_time of this Connection.

        :return: The end_time of this Connection.
        :rtype: datetime
        """
        return self._end_time

    @end_time.setter
    def end_time(self, end_time: datetime):
        """Sets the end_time of this Connection.

        :param end_time: The end_time of this Connection.
        :type end_time: datetime
        """

        self._end_time = end_time

    @property
    def status(self) -> str:
        """Gets the status of this Connection.

        Connection Status  # noqa: E501

        :return: The status of this Connection.
        :rtype: str
        """
        return self._status

    @status.setter
    def status(self, status: str):
        """Sets the status of this Connection.

        Connection Status  # noqa: E501

        :param status: The status of this Connection.
        :type status: str
        """
        allowed_values = ["success", "fail", "scheduled", "provisioining"]  # noqa: E501
        if status not in allowed_values:
            raise ValueError(
                "Invalid value for `status` ({0}), must be one of {1}"
                .format(status, allowed_values)
            )

        self._status = status

    @property
    def complete(self) -> bool:
        """Gets the complete of this Connection.

        :return: The complete of this Connection.
        :rtype: bool
        """
        return self._complete

    @complete.setter
    def complete(self, complete: bool):
        """Sets the complete of this Connection.

        :param complete: The complete of this Connection.
        :type complete: bool
        """

        self._complete = complete


"""Placeholder module for backwards-compatibility"""
# flake8: noqa: F401, F403
from typing import Iterable, List
from warnings import warn

from pyinaturalist.constants import JsonResponse, ResponseResult
from pyinaturalist.pagination import paginate_all
from pyinaturalist.v1 import *
from pyinaturalist.v1 import get_observations

msg = 'The module `pyinaturalist.node_api` is deprecated; please use `from pyinaturalist import ...`'
warn(DeprecationWarning(msg))

def get_all_observations(**params) -> List[JsonResponse]:
    """Deprecated; use ``get_observations(page='all')`` instead"""
    msg = "get_all_observations() is deprecated; please use get_observations(page='all') instead"
    warn(DeprecationWarning(msg))
    return paginate_all(get_observations, method='id', **params)['results']

def get_geojson_observations(properties: List[str] = None, **params) -> JsonResponse:
    """Get all observation results combined into a GeoJSON ``FeatureCollection``.
    By default this includes some basic observation properties as GeoJSON ``Feature`` properties.
    The ``properties`` argument can be used to override these defaults.

    Example:
        >>> get_geojson_observations(observation_id=16227955, properties=['photo_url'])

        .. admonition:: Example Response
            :class: toggle

            .. literalinclude:: ../sample_data/get_observations.geojson
                :language: JSON

    Returns:
        A ``FeatureCollection`` containing observation results as ``Feature`` dicts.
    """
    warn(DeprecationWarning('get_geojson_observations() has been moved to pyinaturalist-convert'))
    params['mappable'] = True
    params['page'] = 'all'
    response = get_observations(**params)
    return as_geojson_feature_collection(
        response['results'],
        properties=properties if properties is not None else DEFAULT_OBSERVATION_ATTRS,
    )

# Basic observation attributes to include by default in geojson responses
DEFAULT_OBSERVATION_ATTRS = [
    'id',
    'photo_url',
    'positional_accuracy',
    'quality_grade',
    'taxon_id',
    'taxon_name',
    'taxon_common_name',
    'time_observed_at',
    'uri',
]

def as_geojson_feature_collection(
    results: Iterable[ResponseResult], properties: List[str] = None
) -> JsonResponse:
    """
    Convert results from an API response into a
    `geojson FeatureCollection <https://tools.ietf.org/html/rfc7946#section-3.3>`_ object.
    This is currently only used for observations, but could be used for any other responses with
    geospatial info.

    Args:
        results: List of results from API response
        properties: Whitelist of specific properties to include
    """
    results = [flatten_nested_params(obs) for obs in results]
    return {
        'type': 'FeatureCollection',
        'features': [as_geojson_feature(record, properties) for record in results],
    }

def as_geojson_feature(result: ResponseResult, properties: List[str] = None) -> ResponseResult:
    """
    Convert an individual response item to a geojson Feature object, optionally with specific
    response properties included.

    Args:
        result: A single response item
        properties: Whitelist of specific properties to include
    """
    result['geojson']['coordinates'] = [float(i) for i in result['geojson']['coordinates']]
    return {
        'type': 'Feature',
        'geometry': result['geojson'],
        'properties': {k: result.get(k) for k in properties or []},
    }

def flatten_nested_params(observation: ResponseResult) -> ResponseResult:
    """Extract some nested observation properties to include at the top level;
     this makes it easier to specify these as properties for
     :py:func:`.as_as_geojson_feature_collection`.

    Args:
        observation: A single observation result
    """
    taxon = observation.get('taxon', {})
    photos = observation.get('photos', [{}])
    observation['taxon_id'] = taxon.get('id')
    observation['taxon_name'] = taxon.get('name')
    observation['taxon_rank'] = taxon.get('rank')
    observation['taxon_common_name'] = taxon.get('preferred_common_name')
    observation['photo_url'] = photos[0].get('url')
    return observation


import numpy as np
from PyQt4.QtGui import QMessageBox

def cholesky(A):
    if np.linalg.det(A) > 0:
        n = len(A)
        L = np.zeros((n,n))
        L[0,0] = np.sqrt(A[0,0])
        for j in range(1, n):
            L[j, 0] = A[j, 0]/L[0,0]
        for i in range(1, n):
            temp = 0
            for p in range(i):
                temp += L[i, p]**2
            L[i, i] = np.sqrt(A[i, i] - temp)
            if i != n:
                for j in range(i+1, n):
                    temp = 0
                    for p in range(i):
                        temp += L[i, p]*L[j, p]
                    L[j, i] = (A[j, i] - temp)/L[i, i]
        return L
    else:
        msgbx = QMessageBox()
        msgbx.setWindowTitle('Error')
        msgbx.setText('Matrix det is not positive')
        msgbx.exec_()
        return None

def LDLt_decomp(A):
    n = len(A)
    L = np.zeros((n, n))
    D = np.zeros(n)
    for i in range(len(L)):
        L[i, i] = 1
    for i in range(n):
        D[i] = A[i, i] - np.sum(L[i, 0:i]**2*D[0:i])
        for j in range(i+1, n):
            L[j, i] = (A[j, i] - np.sum(L[j, 0:i]*L[i, 0:i]*D[0:i]))/D[i]
    return L, D

def sqrt_method(A, B):
    L, D = LDLt_decomp(A)
    n = len(A)
    z = np.zeros(n)
    y = np.zeros(n)
    x = np.zeros(n)
    y[0] = B[0]
    for i in range(1, n):
        y[i] = B[i] - np.sum(L[i, 0:i]*y[0:i])
    for i in range(n):
        z[i] = y[i] / D[i]
    x[n-1] = z[n-1]
    for i in range(n-2, -1, -1):
        x[i] = z[i] - np.sum(L[i+1:n, i]*x[i+1:n])
    return x, L, D

if __name__ == '__main__':
    A = np.array([
        [1,1,1],
        [1,2,2],
        [1,2,3]
    ])
    B = np.array([3,2,1])
    x = sqrt_method(A, B)
    print(x)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('music', '0011_album_website'),
    ]

    operations = [
        migrations.AddField(
            model_name='user',
            name='profileImg',
            field=models.ImageField(default='user/profileimg/default.jpg', upload_to='user/profileimg'),
        ),
    ]


'''
#第一个注释
print("hello world!")#第二个注释
'''
if True:
    print("yes")
    print("true")
else:
    print("no")
    print("wrong")

item_one = 1

item_two = 1.23

item_three = 1 +2j

total = item_one + \
        item_two + \
        item_three

print(total)

# str='Runoob'

# print(str)                 # 输出字符串
# print(str[0:-1])           # 输出第一个到倒数第二个的所有字符
# print(str[0])              # 输出字符串第一个字符
# print(str[2:5])            # 输出从第三个开始到第五个的字符
# print(str[2:])             # 输出从第三个开始的后的所有字符
# print(str * 2)             # 输出字符串两次
# print(str + '你好')        # 连接字符串

# print('------------------------------')

# print('hello\nrunoob')      # 使用反斜杠(\)+n转义特殊字符
# print(r'hello\nrunoob')     # 在字符串前面添加一个 r，表示原始字符串，不会发生转义


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

import pytest

from goodplay.docker_support import DockerRunner

@pytest.fixture
def without_docker_env_vars(monkeypatch):
    monkeypatch.delenv('DOCKER_TLS_VERIFY', raising=False)
    monkeypatch.delenv('DOCKER_HOST', raising=False)
    monkeypatch.delenv('DOCKER_CERT_PATH', raising=False)
    monkeypatch.delenv('DOCKER_MACHINE_NAME', raising=False)

def test_client_negotiates_version(without_docker_env_vars, mocker):
    client_mock = mocker.patch('docker.Client', autospec=True)

    docker_runner = DockerRunner(ctx=None)
    docker_runner.client

    client_mock.assert_called_once_with(version='auto')

def test_client_uses_docker_host_env_var(without_docker_env_vars, monkeypatch, mocker):
    monkeypatch.setenv('DOCKER_HOST', 'tcp://192.168.10.2:2376')

    client_mock = mocker.patch('docker.Client', autospec=True)

    docker_runner = DockerRunner(ctx=None)
    docker_runner.client

    _, _, kwargs = client_mock.mock_calls[0]
    assert kwargs['base_url'] == 'tcp://192.168.10.2:2376'

def test_client_does_not_validate_hostname(without_docker_env_vars, mocker):
    mocker.patch('docker.Client', autospec=True)
    kwargs_from_env_mock = mocker.patch('docker.utils.kwargs_from_env', autospec=True)

    docker_runner = DockerRunner(ctx=None)
    docker_runner.client

    kwargs_from_env_mock.assert_called_once_with(assert_hostname=False)

def test_client_is_cached(mocker):
    client_mock = mocker.patch('docker.Client', autospec=True)

    docker_runner = DockerRunner(ctx=None)
    first_result = docker_runner.client

    assert id(docker_runner.client) == id(first_result)
    assert client_mock.call_count == 1


#! /usr/bin/env python
import rospy
from spring_seminar.msg import Pos
from spring_seminar.msg import State

def sample_pos_pub(x,y,z):
    pub = rospy.Publisher('sample_position', Pos, queue_size=10)
    rospy.init_node('sample', anonymous=True)
    r = rospy.Rate(1)
    msg = Pos()
    while not rospy.is_shutdown():
        msg.x_pos = x
        msg.y_pos = y
        msg.z_pos = z

        rospy.loginfo("Position:x:%s,y:%s,z:%s",x,y,z)
        pub.publish(msg)
        r.sleep()

def sample_state_pub(s):
    pub = rospy.Publisher('state', State, queue_size=10)
    rospy.init_node('sample', anonymous=True)
    r = rospy.Rate(1)
    msg = State()
    while not rospy.is_shutdown():
        msg.State = s

        rospy.loginfo("State:%s",s)
        pub.publish(msg)
        r.sleep()

def callback_pos(data):
    # rospy.loginfo(rospy.get_caller_id() + "%s,%s,%s",data.x_pos, data.y_pos,data.z_pos)
    # samthing code?
    sample_pos_pub(data.x_pos +2 ,data.y_pos + 1 ,data.z_pos + 3)

def callback_state(data):
    rospy.loginfo(rospy.get_caller_id() + "%s", data.data)
    sample_state_pub(data.data)

def sample_pos_sub():
    rospy.init_node('sample', anonymous=True)
    rospy.Subscriber("position", Pos, callback_pos)

    rospy.spin()

def sample_state_sub():
    rospy.init_node('sample', anonymous=True)
    rospy.Subscriber("state", State ,callback_state)

    rospy.spin()

if __name__ == "__main__":
    sample_pos_sub()
    # sample_state_sub()


import pytest
from flask import url_for

from app.main.views.feedback import has_live_services
from tests.conftest import (
    mock_get_services,
    mock_get_services_with_no_services,
    mock_get_services_with_one_service,
    normalize_spaces,
)

def no_redirect():
    return lambda _external=True: None

@pytest.mark.parametrize('endpoint', [
    'main.old_feedback',
    'main.support',
])
def test_get_support_index_page(
    client,
    endpoint,
):
    response = client.get(url_for('main.support'), follow_redirects=True)
    assert response.status_code == 200

@pytest.mark.parametrize('get_services_mock, expected_return_value', [
    (mock_get_services, True),
    (mock_get_services_with_no_services, False),
    (mock_get_services_with_one_service, False),
])
def test_has_live_services(
    mocker,
    fake_uuid,
    get_services_mock,
    expected_return_value
):
    get_services_mock(mocker, fake_uuid)
    assert has_live_services(12345) == expected_return_value

@pytest.mark.parametrize('out_of_hours_emergency, email_address_provided, out_of_hours, message', (

    # Out of hours emergencies trump everything else
    (
        True, True, True,
        'We’ll reply in the next 30 minutes.',
    ),
    (
        True, False, False,  # Not a real scenario
        'We’ll reply in the next 30 minutes.',
    ),

    # Anonymous tickets don’t promise a reply
    (
        False, False, False,
        'We’ll read your message in the next 30 minutes.',
    ),
    (
        False, False, True,
        'We’ll read your message when we’re back in the office.',
    ),

    # When we look at your ticket depends on whether we’re in normal
    # business hours
    (
        False, True, False,
        'We’ll read your message in the next 30 minutes and reply within one working day.',
    ),
    (
        False, True, True,
        'We’ll reply within one working day.'
    ),

))
def test_thanks(
    client_request,
    mocker,
    api_user_active,
    mock_get_user,
    out_of_hours_emergency,
    email_address_provided,
    out_of_hours,
    message,
):
    mocker.patch('app.main.views.feedback.in_business_hours', return_value=(not out_of_hours))
    page = client_request.get(
        'main.thanks',
        out_of_hours_emergency=out_of_hours_emergency,
        email_address_provided=email_address_provided,
    )
    assert normalize_spaces(page.find('main').find('p').text) == message


from pfac.atom import atomic_data
from pfac.spm import *
from pfac import const
import os

THIS_DIR = os.path.abspath(os.path.join(__file__, os.pardir))

def make_spectrum(asym, neles, z):
    """ Save the spectral calculation for
    asym: string of element such as 'Li', 'He'...
    """
    dir0 = THIS_DIR + '/../{}/'.format(asym)
    if not os.path.exists(dir0):
        os.mkdir(dir0)

    atomic_data(neles, asym, iprint=1, dir=dir0)

    den = [1.0]  # density
    for nele in neles:
        dir1 = dir0 + '/{0:02d}/'.format(nele)
        if not os.path.exists(dir1):
            os.mkdir(dir1)

        (temp, logt, population) = get_tgrid(z, nele, dt=1)
        print('NION = 1')
        spectrum([nele], temp, den, population,
                 asym, dir0=dir0, dir1=dir1, nion=1)

make_spectrum('He', [1, 2], 2)
make_spectrum('Li', [1, 2, 3], 3)
make_spectrum('Be', [1, 2, 3, 4], 4)


import pickle
import numpy as np

import lenskit.util.test as lktu
from lenskit import sharing as lks
from lenskit.algorithms import Recommender
from lenskit.algorithms.basic import Popular
from lenskit.algorithms.als import BiasedMF
from lenskit.algorithms.item_knn import ItemItem

from pytest import mark

stores = [lks.FileModelStore]
if pickle.HIGHEST_PROTOCOL >= 5:
    # we have Python 3.8
    stores.append(lks.SHMModelStore)

store_param = mark.parametrize('store_cls', stores)

def test_sharing_mode():
    "Ensure sharing mode decorator turns on sharing"
    assert not lks.in_share_context()

    with lks.sharing_mode():
        assert lks.in_share_context()

    assert not lks.in_share_context()

@store_param
def test_store_init(store_cls):
    "Test that a store initializes and shuts down."
    with store_cls():
        pass

@store_param
def test_store_save(store_cls):
    algo = Popular()
    algo.fit(lktu.ml_test.ratings)

    with store_cls() as store:
        k = store.put_model(algo)
        a2 = store.get_model(k)
        assert a2 is not algo
        assert a2.item_pop_ is not algo.item_pop_
        assert all(a2.item_pop_ == algo.item_pop_)
        del a2

@store_param
def test_store_client(store_cls):
    algo = Popular()
    algo.fit(lktu.ml_test.ratings)

    with store_cls() as store:
        k = store.put_model(algo)
        client = store.client()

        a2 = client.get_model(k)
        assert a2 is not algo
        assert a2.item_pop_ is not algo.item_pop_
        assert all(a2.item_pop_ == algo.item_pop_)
        del a2

@store_param
def test_store_client_pickle(store_cls):
    algo = Popular()
    algo.fit(lktu.ml_test.ratings)

    with store_cls() as store:
        k = store.put_model(algo)
        client = store.client()
        client = pickle.loads(pickle.dumps(client))
        k = pickle.loads(pickle.dumps(k))

        a2 = client.get_model(k)
        assert a2 is not algo
        assert a2.item_pop_ is not algo.item_pop_
        assert all(a2.item_pop_ == algo.item_pop_)
        del a2

@lktu.wantjit
@store_param
def test_store_als(store_cls):
    algo = BiasedMF(10)
    algo.fit(lktu.ml_test.ratings)

    with store_cls() as store:
        k = store.put_model(algo)
        client = store.client()

        a2 = client.get_model(k)
        assert a2 is not algo
        assert a2.item_features_ is not algo.item_features_
        assert np.all(a2.item_features_ == algo.item_features_)
        assert a2.user_features_ is not algo.user_features_
        assert np.all(a2.user_features_ == algo.user_features_)
        del a2

@lktu.wantjit
@store_param
def test_store_iknn(store_cls):
    algo = ItemItem(10)
    algo = Recommender.adapt(algo)
    algo.fit(lktu.ml_test.ratings)

    with store_cls() as store:
        k = store.put_model(algo)
        client = store.client()

        a2 = client.get_model(k)
        assert a2 is not algo
        del a2

def test_create_store():
    with lks.get_store() as store:
        assert len(lks._active_stores()) == 1
        assert lks._active_stores()[-1] is store

def test_reuse_store():
    with lks.get_store() as outer:
        with lks.get_store() as inner:
            assert inner is outer
            assert len(lks._active_stores()) == 2
            assert lks._active_stores()[-1] is inner
        assert len(lks._active_stores()) == 1

def test_new_store():
    with lks.get_store() as outer:
        with lks.get_store(False) as inner:
            assert inner is not outer
            assert len(lks._active_stores()) == 2
            assert lks._active_stores()[-1] is inner
            assert lks._active_stores()[0] is outer
        assert len(lks._active_stores()) == 1


# handle local disk files in asyncio applications

import asyncio
import aiofiles

async def m(filename, content):
    print(f"writing {filename}")
    async with aiofiles.open(filename, mode='a') as f:
        await f.write(content)
    print(f"written {filename}")

async def main():
    s = "smita"
    a = loop.create_task(m("3.txt", s*10000))
    b = loop.create_task(m("1.txt", s*10))
    c = loop.create_task(m("2.txt", s*1000))
    await asyncio.wait([a, b, c])
    return a, b, c

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    try:
        a, b, c = loop.run_until_complete(main())
        print(a.result())
        print(b.result())
        print(c.result())
    except Exception as e:
        print(e)
    finally:
        loop.close()

"""
async with aiofiles.open('filename') as f:
    async for line in f:
        # do something
"""


import sys

sys.stdin = open('input.txt', 'r')

class Node:

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

class Queue:

    def __init__(self):
        self.front = None
        self.last = None

    def enqueue(self, value):
        node = Node(value)

        if not self.front:
            self.front = node
            self.last = node
        else:
            self.last.next = node
            self.last = node

        return self

    def dequeue(self):

        if not self.front:
            return None
        else:
            node = self.front
            self.front = node.next

            return node

N, M = map(int, input().split())

numbers = [num for num in range(1, N + 1)]

all_seq = []

for i in range(N):
    q = Queue()
    q.enqueue([numbers[i]])

    while q.front:
        node = q.dequeue()

        if len(node.value) == M:
            all_seq.append(node.value)
        else:
            for num in numbers:
                new_seq = node.value + [num]
                q.enqueue(new_seq)

for seq in all_seq:
    print("{}".format(' '.join(map(str, seq))))


"""Testa adaptadores da aplicação core."""

import unittest

from django import urls
from django.core import urlresolvers
from django.test import SimpleTestCase, override_settings
from rest_framework.test import APITestCase

class DisableSignupAdapterTest(SimpleTestCase):
    """Verifica a suspensão de registro no site."""

    @override_settings(
        ACCOUNT_ADAPTER='core.adapters.DisableSignupAdapter',
        REST_AUTH_REGISTER_SERIALIZERS={
            'REGISTER_SERIALIZER': 'core.serializers.DisableSignupSerializer'
        }
    )
    def test_disable_signup(self):
        """Verifica se o processo de registro no site é suspenso."""
        try:
            url = urlresolvers.reverse('account_signup')
            response_content = self.client.get(url).content.decode('utf-8')
            self.assertIn('Registros de novas contas temporariamente suspenso.', response_content)

        except urls.NoReverseMatch as e:
            raise unittest.SkipTest('URL de registro não está ativada.') from e

class DisableSignupAdapterTestAPI(APITestCase):
    """Verifica a suspensão de registro no site via api."""

    @override_settings(
        ACCOUNT_ADAPTER='core.adapters.DisableSignupAdapter',
        REST_AUTH_REGISTER_SERIALIZERS={
            'REGISTER_SERIALIZER': 'core.serializers.DisableSignupSerializer'
        }
    )
    def test_disable_signup_api(self):
        """Verifica se o processo de registro no site é suspenso via api."""
        try:
            url = urlresolvers.reverse('rest_register')
            data = dict(username='u', email='e@b.com', password1='secret123', password2='secret123')
            response = self.client.post(url, data)
            self.assertEqual(
                response.data['non_field_errors'][0],
                'Registro de novas contas temporariamente suspenso.'
            )

        except urls.NoReverseMatch as e:
            raise unittest.SkipTest('URL de registro não está ativada.') from e


info_list = []

def menu():
    print("---------------------------")
    print("      学生管理系统 V1.0")
    print(" 1:添加学生")
    print(" 2:删除学生")
    print(" 3:修改学生")
    print(" 4:查询学生")
    print(" 5:显示所有学生")
    print(" 6:退出系统")
    print("---------------------------")

def add_info():
    global info_list
    info_dict = {}
    name = input("input ur name:")
    gender = input("input ur gender:")
    num = input("input ur num:")

    info_dict["name"] = name
    info_dict["gender"] = gender
    info_dict["num"] = num

    info_list.append(info_dict)

def del_info():
    global info_list
    i = 0
    num = input("please input num:")
    for temp_list in info_list:
        for value in temp_list.values():
            if value == num:
                del info_list[i]
        i += 1

def change_info():
    del_info()
    add_info()
    print("change ok!")

def select_info():
    global info_list
    i = 0
    num = input("please input num:")
    for temp_list in info_list:
        for value in temp_list.values():
            if value == num:
                print(info_list[i])
                break
        i += 1

def show_info():
    global info_list
    for temp_list in info_list:
        print(temp_list)
    # i = 0
    # while i < len(info_list):
    #     print(info_list[i])
    #     i += 1

def exit_info():
    exit()

def main():
    menu()
    while True:
        s = int(input("please choice number:"))
        if 1 == s:
            add_info()
        elif 2 == s:
            del_info()
        elif 3 == s:
            change_info()
        elif 4 == s:
            select_info()
        elif 5 == s:
            show_info()
        elif 6 == s:
            exit_info()
        else:
            print("error number!")

main()


import numpy as np
import numpy.random as rng

def discrete_sample(p, n_samples=1):
    """
    Samples from a discrete distribution.
    :param p: a distribution with N elements
    :param n_samples: number of samples
    :return: vector of samples
    """

    # check distribution
    #assert isdistribution(p), 'Probabilities must be non-negative and sum to one.'

    # cumulative distribution
    c = np.cumsum(p[:-1])[np.newaxis, :]

    # get the samples
    r = rng.rand(n_samples, 1)
    return np.sum((r > c).astype(int), axis=1)

class MarkovJumpProcess:
    """Implements a generic markov jump process and algorithms for simulating it.
    It is an abstract class, it needs to be inherited by a concrete implementation."""

    def __init__(self, init, params):

        self.state = np.asarray(init)
        self.params = np.asarray(params)
        self.time = 0.0

    def _calc_propensities(self):
        raise NotImplementedError('This is an abstract method and should be implemented in a subclass.')

    def _do_reaction(self, reaction):
        raise NotImplementedError('This is an abstract method and should be implemented in a subclass.')

    def sim_steps(self, num_steps):
        """Simulates the process with the gillespie algorithm for a specified number of steps."""

        times = [self.time]
        states = [self.state.copy()]

        for _ in range(num_steps):

            rates = self.params * self._calc_propensities()
            total_rate = rates.sum()

            if total_rate == 0:
                self.time = float('inf')
                break

            self.time += rng.exponential(scale=1/total_rate)

            reaction = discrete_sample(rates / total_rate)[0]
            self._do_reaction(reaction)

            times.append(self.time)
            states.append(self.state.copy())

        return times, np.array(states)

    def sim_time(self, dt, duration, max_n_steps=float('inf')):
        """Simulates the process with the gillespie algorithm for a specified time duration."""

        num_rec = int(duration / dt) + 1
        states = np.zeros([num_rec, self.state.size])
        cur_time = self.time
        n_steps = 0

        for i in range(num_rec):

            while cur_time > self.time:

                rates = self.params * self._calc_propensities()
                total_rate = rates.sum()

                if total_rate == 0:
                    self.time = float('inf')
                    break

                self.time += rng.exponential(scale=1/total_rate)

                reaction = discrete_sample(rates / total_rate)[0]
                self._do_reaction(reaction)

                n_steps += 1
                if n_steps > max_n_steps:
                    raise SimTooLongException(max_n_steps)

            states[i] = self.state.copy()
            cur_time += dt

        return np.array(states)

class LotkaVolterra(MarkovJumpProcess):
    """Implements the lotka-volterra population model."""

    def _calc_propensities(self):

        x, y = self.state
        xy = x * y
        return np.array([xy, x, y, xy])

    def _do_reaction(self, reaction):

        if reaction == 0:
            self.state[0] += 1
        elif reaction == 1:
            self.state[0] -= 1
        elif reaction == 2:
            self.state[1] += 1
        elif reaction == 3:
            self.state[1] -= 1
        else:
            raise ValueError('Unknown reaction.')

def calc_summary_stats(states):
    """
        Given a sequence of states produced by a simulation, calculates and returns a vector of summary statistics.
        Assumes that the sequence of states is uniformly sampled in time.
        """

    N = states.shape[0]
    x, y = states[:, 0].copy(), states[:, 1].copy()

    # means
    mx = np.mean(x)
    my = np.mean(y)

    # variances
    s2x = np.var(x, ddof=1)
    s2y = np.var(y, ddof=1)

    # standardize
    x = (x - mx) / np.sqrt(s2x)
    y = (y - my) / np.sqrt(s2y)

    # auto correlation coefficient
    acx = []
    acy = []
    for lag in [1, 2]:
        acx.append(np.dot(x[:-lag], x[lag:]) / (N-1))
        acy.append(np.dot(y[:-lag], y[lag:]) / (N-1))

    # cross correlation coefficient
    ccxy = np.dot(x, y) / (N-1)

    return np.array([mx, my, np.log(s2x + 1), np.log(s2y + 1)] + acx + acy + [ccxy])


import matplotlib.pyplot as plt
import numpy as np
import sys
sys.path.append('C:/Github/space/simulation2/RESTAPIs')
import atmofunc
n = 500
v = np.zeros((3,n))
v[0,:] =  np.ones((1,n))*-465.1
v[1,:] = np.linspace(0,150,n)
pos = np.zeros((3,n))
pos[1,:] =  np.ones((1,n))*6371000
vAbs = np.linspace(0,150,n)
alt = 0
CD = np.zeros((n,1))
dragForce = np.zeros((n,1))
for i in range(n):
	CD[i] = atmofunc.dragCoefficient(vAbs[i],alt)
	dragForce[i] = atmofunc.dragForce(v[:,i],pos[:,i],A=21.24)

vabsmeas = np.array([10,50,75,100,150])
CDmeas = np.array([0.34,0.34,0.33,0.33,0.33])
dragForcemeas = np.array([424., 10628, 23860, 41631,95507])
p1 = plt.plot(vAbs,CD)
plt.title('dragCoefficient')
p2 = plt.plot(vabsmeas,CDmeas,'r+')
plt.legend(["braeunigs saturn V","simulated CFD"],loc=7)
plt.xlabel('speed [m/s]')
plt.show()
p3 = plt.plot(vabsmeas,dragForcemeas,'r+')
p4 = plt.plot(vAbs,dragForce)
plt.legend(["simulated CFD", "braeunigs saturn V"],loc=2)
plt.title('dragForce')
plt.ylabel('dragForce [N]')
plt.xlabel('speed [m/s]')
plt.show()


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

from odoo import models, fields, api, exceptions, _
import logging

def cojo_padding_4_right(number):
    return str(number).rjust(4, '0') if type(number) == str else "0000"

def cojo_padding_3_right(number):
    return str(number).rjust(3, '0') if type(number) == str else "000"

def cojo_padding_2_right(number):
    return str(number).rjust(2, '0') if type(number) == str else "00"

_logger_ = logging.getLogger(__name__)

# We add these fields because we can use odoo's Company, Country and State models
class Company(models.Model):
    _inherit = "res.company"

    analytic_code = fields.Char(string="Analytic Code")

    _sql_constraints = [(
        'analytic_code_unique', 'unique(analytic_code)', 'Analytic Code must be unique!'
    )]

class AnalyticAccounts(models.Model):
    _inherit = "account.analytic.account"

    country_id = fields.Many2one(string="Country", related="company_id.country_id")
    state_id = fields.Many2one(string="State", related="company_id.state_id")

    department = fields.Many2one("analytic_accounts.group.department", string="Department")
    sub_department = fields.Many2one("analytic_accounts.group.sub_department", string="Sub Department")
    type = fields.Many2one("analytic_accounts.group.type", string="Type")
    group = fields.Many2one("analytic_accounts.group", string="Group")
    account = fields.Many2one("analytic_accounts.group.account", string="Account")
    sub_account = fields.Many2one("analytic_accounts.group.sub_account", string="Sub Account")
    item = fields.Many2one("analytic_accounts.group.item", string="Item")

    country_rel_id = fields.Integer(string='Country Id', related='country_id.id', readonly=False)
    state_rel_id = fields.Integer(string='State Id', related='state_id.id', readonly=False)
    company_rel_id = fields.Integer(string='Company Id', related='company_id.id', readonly=False)
    department_rel_id = fields.Integer(string='Department Id', related='department.id', readonly=False)
    sub_department_rel_id = fields.Integer(string='Sub Department Id', related='sub_department.id', readonly=False)
    type_rel_id = fields.Integer(string='Type Id', related='type.id', readonly=False)
    group_rel_id = fields.Integer(string='Group Id', related='group.id', readonly=False)
    account_rel_id = fields.Integer(string='Account Id', related='account.id', readonly=False)
    sub_account_rel_id = fields.Integer(string='Sub Account Id', related='sub_account.id', readonly=False)
    item_rel_id = fields.Integer(string='Item Id', related='item.id', readonly=False)

    country_rel_code = fields.Char(string='Country Code', related='country_id.code', readonly=False)
    state_rel_code = fields.Char(string='State Code', related='state_id.code', readonly=False)
    company_rel_code = fields.Char(string='Company Code', related='company_id.analytic_code', readonly=False)
    department_rel_code = fields.Char(string='Department Code', related='department.code', readonly=False)
    sub_department_rel_code = fields.Char(string='Sub Department Code', related='sub_department.code', readonly=False)
    type_rel_code = fields.Char(string='Type Code', related='type.code', readonly=False)
    group_rel_code = fields.Char(string='Group Code', related='group.code', readonly=False)
    account_rel_code = fields.Char(string='Account Code', related='account.code', readonly=False)
    sub_account_rel_code = fields.Char(string='Sub Account Code', related='sub_account.code', readonly=False)
    item_rel_code = fields.Char(string='Item Code', related='item.code', readonly=False)

    department_rel_name = fields.Char(string='Department Name', related='department.name', readonly=False)
    sub_department_rel_name = fields.Char(string='Sub Department Name', related='sub_department.name', readonly=False)

    def test_foo(self):
        return "test"

    # Domains
    @api.onchange("department")
    def _onchange_department(self):
        if not self.department:
            self.sub_department = False

    @api.onchange("type")
    def _onchange_type(self):
        res = {}
        if self.type:
            res['domain'] = {'group': [('type_id', '=', self.type.id)]}
            self.group = self.type.group_none
        return res

    @api.onchange("group")
    def _onchange_group(self):
        res = {}
        if self.group:
            res['domain'] = {'account': [('group_id', '=', self.group.id)]}
            self.account = self.group.account_none
        return res

    @api.onchange("account")
    def _onchange_account(self):
        res = {}
        if self.account:
            res['domain'] = {'sub_account': [('account_id', '=', self.account.id)]}
            self.sub_account = self.account.sub_account_none
        return res

    @api.onchange("sub_account")
    def _onchange_sub_account(self):
        res = {}
        if self.sub_account:
            res['domain'] = {'item': [('sub_account_id', '=', self.sub_account.id)]}
            self.item = self.sub_account.item_none
        return res

    def make_or_change(self, values):
        company_code = cojo_padding_4_right(self.company_id.analytic_code)
        if "company_id" in values:
            if values["company_id"]:
                company = self.env['res.company'].browse(values["company_id"])
                company_code = cojo_padding_4_right(company.analytic_code)
        if not company_code:
            company_code = "0000"

        country_code = cojo_padding_2_right(self.country_id.code)
        if "country_id" in values:
            if values["country_id"]:
                country = self.env['res.country'].browse(values["country_id"])
                country_code = country.code
        if not country_code:
            country_code = "00"

        state_code = cojo_padding_3_right(self.state_id.code)
        if "state_id" in values:
            if values["state_id"]:
                state = self.env['res.country.state'].browse(values["state_id"])
                state_code = state.code
        if not state_code:
            state_code = "000"

        department_code = cojo_padding_4_right(self.department.code)
        if "department" in values:
            if values["department"]:
                department = self.env['analytic_accounts.group.department'].browse(values["department"])
                department_code = cojo_padding_4_right(department.code)
            else:
                values["sub_department"] = False
        if not department_code:
            department_code = "0000"

        sub_department_code = cojo_padding_4_right(self.sub_department.code)
        if "sub_department" in values:
            if values["sub_department"]:
                sub_department = self.env['analytic_accounts.group.sub_department'].browse(values["sub_department"])
                sub_department_code = cojo_padding_4_right(sub_department.code)
        if not sub_department_code:
            sub_department_code = "0000"

        type_code = cojo_padding_4_right(self.type.code)
        if "type" in values:
            if values["type"]:
                type_record = self.env['analytic_accounts.group.type'].browse(values["type"])
                type_code = cojo_padding_4_right(type_record.code)
        if not type_code:
            type_code = "0000"

        group_code = cojo_padding_4_right(self.group.code)
        if "group" in values:
            if values["group"]:
                group = self.env['analytic_accounts.group'].browse(values["group"])
                group_code = cojo_padding_4_right(group.code)
        if not group_code:
            group_code = "0000"

        account_code = cojo_padding_4_right(self.account.code)
        if "account" in values:
            if values["account"]:
                account = self.env['analytic_accounts.group.account'].browse(values["account"])
                account_code = cojo_padding_4_right(account.code)
        if not account_code:
            account_code = "0000"

        sub_account_code = cojo_padding_4_right(self.sub_account.code)
        if "sub_account" in values:
            if values["sub_account"]:
                sub_account = self.env['analytic_accounts.group.sub_account'].browse(values["sub_account"])
                sub_account_code = cojo_padding_4_right(sub_account.code)
        if not sub_account_code:
            sub_account_code = "0000"

        item_code = cojo_padding_4_right(self.item.code)

        if "item" in values:
            if values["item"]:
                item = self.env['analytic_accounts.group.item'].browse(values["item"])
                item_code = cojo_padding_4_right(item.code)
        if not item_code:
            item_code = "0000"

        code = "{}{}{}{}{}{}{}{}{}{}".format(country_code,
                                             state_code,
                                             company_code,
                                             department_code,
                                             sub_department_code,
                                             type_code,
                                             group_code,
                                             account_code,
                                             sub_account_code,
                                             item_code)

        values["code"] = code

    def _import(self, values):
        code = values["code"]
        _logger_.info("Importing analytic account with reference: {}".format(code))

        if len(code) == 37:
            country_code        = code[0:2]
            region_code         = code[2:5]
            company_code        = code[5:9]

            #===================================================================
            # Verifica si la compañia existen en Odoo
            # Tambien comprueba si el country y el region son
            # igualmente validos
            #===================================================================

            CompanyEnv = self.env["res.company"]
            company_id = CompanyEnv.search([("analytic_code", "=", company_code)])
            if not company_id:
                raise exceptions.ValidationError(_("Invalid company code, must be 1234"))
            company_record = CompanyEnv.browse([company_id])

            if company_record.ids[0].country_id:
                if company_record.ids[0].country_id.code != country_code:
                    raise exceptions.ValidationError(_("Invalid country code, must be 12"))
                if company_record.ids[0].state_id:
                    if company_record.ids[0].state_id.code != region_code:
                        raise exceptions.ValidationError(_("Invalid region/state code, must be 123"))
                else:
                    raise exceptions.ValidationError(_("Country needs state specified"))
            else:
                raise exceptions.ValidationError(_("Company needs country specified"))

            department_code     = code[9:13]
            sub_department_code = code[13:17]

            type_code           = code[17:21]
            group_code          = code[21:25]
            account_code        = code[25:29]
            sub_account_code    = code[29:33]
            item_code           = code[33:37]

            #===================================================================
            # Estos son distinto porque sin independientes y ademas opcionales
            #===================================================================
            DeptEnv = self.env["analytic_accounts.group.department"]
            existing_dept = DeptEnv.search([["code", "=", department_code]])
            if len(existing_dept.ids) > 1:
                _logger_.error("Multiple departments!: {}".format( [r.name for r in existing_dept] ))

            if existing_dept:
                values["department"] = existing_dept.id
            else:
                new_dept= DeptEnv.create({
                        "name": "department-{}".format(department_code),
                        "code": department_code
                    })
                values["department"] = new_dept.id

            #===================================================================
            # Type
            #===================================================================
            SubDeptEnv = self.env["analytic_accounts.group.sub_department"]
            existing_sub_department = SubDeptEnv.search([["code", "=", sub_department_code]])
            if len(existing_sub_department.ids) > 1:
                _logger_.error("Multiple sub departments!: {}".format( [r.name for r in existing_sub_department] ))

            if existing_sub_department:
                values["sub_department"] = existing_sub_department.id
            else:
                new_sub_department = SubDeptEnv.create({
                        "name": "sub_department-{}".format(sub_department_code),
                        "code": sub_department_code
                    })
                values["sub_department"] = new_sub_department.id

            #===================================================================
            # Todo esto se hace para hacer un "merge" a los
            # datos type, group, account, sub account y item
            #===================================================================

            #===================================================================
            # Type
            #===================================================================
            TypeEnv = self.env["analytic_accounts.group.type"]
            existing_type = TypeEnv.search([["code", "=", type_code]])
            if len(existing_type.ids) > 1:
                _logger_.error("Multiple type!: {}".format( [r.name for r in existing_type] ))

            if existing_type:
                values["type"] = existing_type.id
            else:
                new_type = TypeEnv.create({
                        "name": "type-{}".format(type_code),
                        "code": type_code
                    })
                values["type"] = new_type.id

            #===================================================================
            # Group
            #===================================================================
            GroupEnv = self.env["analytic_accounts.group"]
            existing_group= GroupEnv.search(["&", ("code", "=", group_code), ("type_id", "=", values["type"])])
            if len(existing_group.ids) > 1:
                _logger_.error("Multiple groups!: {}".format( [r.name for r in existing_group] ))

            if existing_group:
                values["group"] = existing_group.id
            else:
                new_group = GroupEnv.create({
                        "name": "group-{}".format(group_code),
                        "type_id": values["type"],
                        "code": group_code
                    })
                values["group"] = new_group.id

            #===================================================================
            # Account
            #===================================================================
            AccountEnv = self.env["analytic_accounts.group.account"]
            existing_account= AccountEnv.search(["&", ("code", "=", account_code), ("group_id", "=", values["group"])])
            if len(existing_account.ids) > 1:
                _logger_.error("Multiple account!: {}".format( [r.name for r in existing_account] ))

            if existing_account:
                values["account"] = existing_account.id
            else:
                new_account = AccountEnv.create({
                        "name": "account-{}".format(account_code),
                        "group_id": values["group"],
                        "code": account_code
                    })
                values["account"] = new_account.id

            #===================================================================
            # Sub Account
            #===================================================================
            SubAccountEnv = self.env["analytic_accounts.group.sub_account"]
            existing_sub_account= SubAccountEnv.search(["&", ("code", "=", sub_account_code), ("account_id", "=", values["account"])])
            if len(existing_sub_account.ids) > 1:
                _logger_.error("Multiple sub account!: {} in account: {}".format( [r.name for r in existing_sub_account], values["account"]))

            if existing_sub_account:
                values["sub_account"] = existing_sub_account.id
            else:
                new_sub_account = SubAccountEnv.create({
                        "name": "sub_account-{}".format(sub_account_code),
                        "account_id": values["account"],
                        "code": sub_account_code
                    })
                values["sub_account"] = new_sub_account.id

            #===================================================================
            # Item
            #===================================================================
            ItemEnv = self.env["analytic_accounts.group.item"]
            existing_item = ItemEnv.search(["&", ("code", "=", item_code), ("sub_account_id", "=", values["sub_account"])])
            if len(existing_item.ids) > 1:
                _logger_.error("Multiple items!: {}".format( [r.name for r in existing_item] ))

            if existing_item:
                values["item"] = existing_item.id
            else:
                new_item = ItemEnv.create({
                        "name": "account-{}".format(item_code),
                        "sub_account_id": values["sub_account"],
                        "code": item_code
                    })
                values["item"] = new_item.id
        else:
            raise exceptions.ValidationError(_("Cosas de la vida ¯\_()_/¯"))
        pass

    def change_groups(self, values):

        department = values["department"] if "department" in values else self.department_rel_id
        AnalyticGroupEnv = self.env["account.analytic.group"]

        department_group_id = False
        if department:

            Deparments = self.env["analytic_accounts.group.department"]
            department = Deparments.browse(department)

            ExistingDeptGroup = AnalyticGroupEnv.search(("&", ["parent_id", "=", False],["analytic_code", "=", department.code]))

            if not ExistingDeptGroup:
                print("DeptGroupBefore: {}".format(ExistingDeptGroup))

                print("Departament: {}".format(department.name))

                dept_dict_obj = {
                    "name": department.name,
                    "analytic_code": department.code,
                    "description": "Code: {}".format(department.code)
                }

                department_group_id = AnalyticGroupEnv.create(dept_dict_obj).id
            else:
                ExistingDeptGroup.write({
                    "name": department.name,
                    "analytic_code": department.code
                })
                department_group_id = ExistingDeptGroup.id

        # department_group_id = department_group_id if department_group_id else department.id
        values["group_id"] = department_group_id
        SubDeparments = self.env["analytic_accounts.group.sub_department"]

        sub_department = values["sub_department"] if "sub_department" in values else self.sub_department_rel_id

        if sub_department:
            sub_department = SubDeparments.browse(sub_department)
            ExistingSubDeptGroup = AnalyticGroupEnv.search(("&", ["parent_id.analytic_code", "=", department.code], ["analytic_code", "=", sub_department.code ]))

            if not ExistingSubDeptGroup:

                print("Sub departament: {}".format(sub_department.name))
                sub_dept_dict_obj = {
                    "name": sub_department.name,
                    "parent_id": department_group_id,
                    "analytic_code": sub_department.code,
                    "description": "Code: {}".format(sub_department.code)
                }

                sub_dept = AnalyticGroupEnv.create(sub_dept_dict_obj)
                values["group_id"] = sub_dept.id
            else:
                ExistingSubDeptGroup.write({
                    "name": sub_department.name,
                    "analytic_code": sub_department.code
                })
                values["group_id"] = ExistingSubDeptGroup.id

    def reload_dept_code(self, values):
        if "department_rel_code" in values:
            department = None
            if "department" in values:
                department = self.env["analytic_accounts.group.department"].browse([values["department"]])
            elif self.department:
                department = self.department
            else:
                return
            department.code = values["department_rel_code"]

    def reload_sub_dept_code(self, values):
        if "sub_department_rel_code" in values:
            sub_department = None
            if "sub_department" in values:
                sub_department = self.env["analytic_accounts.group.sub_department"].browse([values["sub_department"]])
            elif self.sub_department:
                sub_department = self.sub_department
            else:
                return
            sub_department.code = values["sub_department_rel_code"]

    def reload_type_code(self, values):
        if "type_rel_code" in values:
            type_record = None
            if "type" in values:
                type_record = self.env["analytic_accounts.group.type"].browse([values["type"]])
            elif self.type:
                type_record = self.type
            else:
                return
            type_record.code = values["type_rel_code"]

    def reload_group_code(self, values):
        if "group_rel_code" in values:
            group_record = None
            if "group" in values:
                group_record = self.env["analytic_accounts.group.group"].browse([values["group"]])
            elif self.group:
                group_record = self.group
            else:
                return
            group_record.code = values["group_rel_code"]

    def reload_account_code(self, values):
        if "account_rel_code" in values:
            account_record = None
            if "account" in values:
                account_record = self.env["analytic_accounts.group.account"].browse([values["account"]])
            elif self.account:
                account_record = self.account
            else:
                return
            account_record.code = values["account_rel_code"]

    def reload_sub_account_code(self, values):
        if "sub_account_rel_code" in values:
            sub_account_record = None
            if "sub_account" in values:
                sub_account_record = self.env["analytic_accounts.group.sub_account"].browse([values["sub_account"]])
            elif self.sub_account:
                sub_account_record = self.sub_account
            else:
                return
            sub_account_record.code = values["sub_account_rel_code"]

    def reload_item_code(self, values):
        if "item_rel_code" in values:
            item_record = None
            if "item" in values:
                item_record = self.env["analytic_accounts.group.item"].browse([values["item"]])
            elif self.item:
                item_record = self.item
            else:
                return
            item_record.code = values["item_rel_code"]

    @api.model
    def create(self, values):
        # self.ensure_one()
        if "group_id" in values:
            self.make_or_change(values)
        else:
            self._import(values)

        # Create a group based on department and sub department

        self.change_groups(values)

        return super(AnalyticAccounts, self).create(values)

    def write(self, values):
        self.ensure_one()

        self.reload_dept_code(values)
        self.reload_sub_dept_code(values)

        self.reload_type_code(values)
        self.reload_type_code(values)
        self.reload_account_code(values)
        self.reload_sub_account_code(values)
        self.reload_item_code(values)

        self.make_or_change(values)
        self.change_groups(values)

        return super().write(values)

# Just simply to make these groups
class GroupBase(models.Model):
    _name = "analytic_accounts.group.base"

    name = fields.Char(string="Name", required=True)
    code = fields.Char(string="Code", required=True, size=4)

    @api.model
    def create(self, values):

        if "code" in values:
            values["code"] = values["code"].rjust(4, "0")[-4:]

        return super(GroupBase, self).create(values)

    def write(self, values):
        # print("Creando un grupo generico")
        if "code" in values:
            values["code"] = cojo_padding_4_right(values["code"])

        return super(GroupBase, self).write(values)

class GroupDepartment(GroupBase):
    _name = "analytic_accounts.group.department"

    # group_id = fields.Many2one("account.analytic.group", string="Group")

    # def write(self, values):
    #     if "name" in values:
    #         group_id.write({
    #             "name": values["name"]
    #         })
    #     return super().write(values)

class GroupSubDepartment(GroupBase):
    _name = "analytic_accounts.group.sub_department"

    #group_id = fields.Many2one("account.analytic.group", string="Group")

    #def write(self, values):
    #    if "name" in values:
    #        group_id.write({
    #            "name": values["name"]
    #        })
    #    return super().write(values)

class GroupType(GroupBase):
    _name = "analytic_accounts.group.type"

    # sub_department.id = fields.Many2one("analytic_accounts.group.sub_department", required=True)
    group_ids = fields.One2many("analytic_accounts.group", "type_id", ondelete="cascade")
    group_none = fields.Many2one("analytic_accounts.group")

    @api.model
    def create(self, values):
        res = super().create(values)

        none_group = self.env["analytic_accounts.group"].create({
            "type_id": res.id,
            "code": "0000",
            "name": "None"
        })

        res.group_none = none_group.id

        return res

class Group(GroupBase):
    _name = "analytic_accounts.group"

    type_id = fields.Many2one("analytic_accounts.group.type", required=True, ondelete="cascade")
    account_ids = fields.One2many("analytic_accounts.group.account", "group_id", ondelete="cascade")
    account_none = fields.Many2one("analytic_accounts.group.account")

    @api.model
    def create(self, values):
        if not "type_id" in values:
            values["type_id"] = self._context.get("type_id")
        res = super().create(values)

        #=======================================================================
        # print(res)
        #=======================================================================

        none_account = self.env["analytic_accounts.group.account"].create({
            "group_id": res.id,
            "code": "0000",
            "name": "None"
        })

        res.account_none = none_account.id

        return res

class GroupAccount(GroupBase):
    _name = "analytic_accounts.group.account"

    group_id = fields.Many2one("analytic_accounts.group", required=True, ondelete="cascade")
    sub_account_ids = fields.One2many("analytic_accounts.group.sub_account", "account_id", ondelete="cascade")
    sub_account_none = fields.Many2one("analytic_accounts.group.sub_account")

    @api.model
    def create(self, values):
        if not "group_id" in values:
            values["group_id"] = self._context.get("group_id")
        res = super().create(values)

        none_sub_account = self.env["analytic_accounts.group.sub_account"].create({
            "account_id": res.id,
            "code": "0000",
            "name": "None"
        })

        res.sub_account_none = none_sub_account.id

        return res

class GroupSubAccount(GroupBase):
    _name = "analytic_accounts.group.sub_account"

    account_id = fields.Many2one("analytic_accounts.group.account", required=True, ondelete="cascade")
    item_ids = fields.One2many("analytic_accounts.group.item", "sub_account_id", ondelete="cascade")
    item_none = fields.Many2one("analytic_accounts.group.item")

    @api.model
    def create(self, values):
        if not "account_id" in values:
            values["account_id"] = self._context.get("account_id")
        res = super().create(values)

        none_item = self.env["analytic_accounts.group.item"].create({
            "sub_account_id": res.id,
            "code": "0000",
            "name": "None"
        })

        res.item_none = none_item.id

        return res

class GroupItem(GroupBase):
    _name = "analytic_accounts.group.item"

    sub_account_id = fields.Many2one("analytic_accounts.group.sub_account", ondelete="cascade")

    @api.model
    def create(self, values):
        if not "sub_account_id" in values:
            values["sub_account_id"] = self._context.get("sub_account_id")
        res = super().create(values)
        return res


import xlwings as xw
import time

# wb = xw.Book('test.xlsx')
#
# sht = wb.sheets['sheet2']

if __name__ == '__main__':
    app = xw.App(visible=True, add_book=False)
    # wb = app.books.add()
    # app = xw.apps.active
    wb = app.books.open(r'\\LIUHONG\fg经手资料\工程发展台账（零星散户）.xlsx')
    sht = wb.sheets(1)
    cell = sht.cells(1, 1)
    print(cell.value)
    time.sleep(5)

    app.quit()
    # //LIUHONG/fg经手资料/工程发展台账（零星散户）.xlsx


# part-1
# Create input layer
encoder_input = Input(shape=(None, len(english_vocab)))

# Create LSTM Layer of size 256
encoder_LSTM = LSTM(256, return_state = True)

# Save encoder output, hidden and cell state
encoder_outputs, encoder_h, encoder_c = encoder_LSTM(encoder_input)

# Save encoder states
encoder_states = [encoder_h, encoder_c]

# part-2
# Create decoder input layer
decoder_input = Input(shape=(None, len(french_vocab)))

# Create LSTM layer of size 256
decoder_LSTM = LSTM(256, return_sequences=True, return_state = True)

# Save decoder output
decoder_out, _ , _ = decoder_LSTM(decoder_input, initial_state=encoder_states)

# Create a Dense layer with softmax activation
decoder_dense = Dense(len(french_vocab), activation='softmax')

# Save the decoder output
decoder_out = decoder_dense(decoder_out)

Datacamp/Deep Learning for NLP in Python/Natural Language Generation in Python/chapter-3 ex-6.py


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Nov 27 17:38:32 2018

@author: MarcusF
"""

import tifffile as tf
from matplotlib import pyplot as plt
from BackgroundFinder import BackgroundFinder

with tf.TiffFile('/Users/MarcusF/Desktop/TrapAnalysis/260522_CecB-  PCPG vesicles- after flushing_1_MMStack_Pos31.ome-1.tif') as tif:
    frames = tif.asarray()

bgf = BackgroundFinder()

bgf.get_background(frames)

bgf.get_data_gradient()
bgf.find_correct_gaussian_scale()

bgf.plot_gradient()

print(bgf.peak_max_arg,bgf.width,bgf.peak_begin_frame)
plt.show()

bgf.plot_background_intensity()

plt.show()


class Node:
    def __init__(self,val,isWord=False):
        self.val = val
        self.child = {}
        self.isWord = isWord

class Trie:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = Node("")

    def insert(self, word: str) -> None:
        """
        Inserts a word into the trie.
        """
        # Setting current to the root Node
        current = self.root
        # Iterating character by character and checking it is not present in the child nodes if present then point to the node else create a new node with the          character and point it towards the character.
        for ch in word:
            if ch not in current.child:
                current.child[ch] = Node(ch)
            current = current.child.get(ch)
        current.isWord = True

    def search(self, word: str) -> bool:
        """
        Returns if the word is in the trie.
        """
        current = self.root
        for ch in word:
            if ch in current.child:
                current = current.child.get(ch)
            else:
                return False
        return current.isWord

    def startsWith(self, prefix: str) -> bool:
        """
        Returns if there is any word in the trie that starts with the given prefix.
        """
        current = self.root
        for ch in prefix:
            if ch in current.child:
                current = current.child.get(ch)
            else:
                return False
        return True

# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)


import json
import pickle

def get_nomes(nome):
    try:
        memoria = open("databases/" + nome + "Nomes" + '.json', 'r')
    except FileNotFoundError:
        memoria = open("databases/" + nome + "Nomes" + '.json', 'w')
        memoria.write('["Will","Alfredo"]')
        memoria.close()
        memoria = open("databases/" + nome + "Nomes" + '.json', 'r')

    return memoria

def get_locais():
    try:
        locais = open("databases/dicionarioLocais.pickle", 'rb')
    except FileNotFoundError:

        locais = open("databases/dicionarioLocais.pickle", 'wb')
        pickle.dump(({'notepad': 'notepad', 'youtube': 'www.youtube.com' ,
                      'chrome' : 'chrome', 'steam': 'steam'}), locais)
        locais.close()
        locais = open("databases/dicionarioLocais.pickle", 'rb')

    return locais

def get_locaisF():
    try:
        locais = open("databases/dicionarioLocaisF.pickle", 'rb')
    except FileNotFoundError:

        locais = open("databases/dicionarioLocaisF.pickle", 'wb')
        pickle.dump(({'notepad': 'notepad', 'bloco': 'notepad' ,
                      'chrome': 'chrome', 'bloco de notas': 'notepad'}), locais)
        locais.close()
        locais = open("databases/dicionarioLocaisF.pickle", 'rb')

    return locais

def get_respostas(nome):
    try:
        respostas = open("databases/" + nome + "Respostas" + '.pickle', 'rb')
    except FileNotFoundError:
        respostas = open("databases/" + nome + "Respostas" + '.pickle', 'wb')
        pickle.dump(({'oi': 'Olá, qual o seu nome?', 'tchau': 'Adeus!',
                      'ana, qual é o seu segundo nome?': 'Sou conhecida por ser Amável!'}), respostas)
        respostas.close()
        respostas = open("databases/" + nome + "Respostas" + '.pickle', 'rb')

    return respostas

def get_comandos(nome):
    try:
        comandos = open("databases/" + nome + "Comandos" + '.json', 'r')
    except FileNotFoundError:
        comandos = open("databases/" + nome + "Comandos" + '.json', 'w')
        comandos.write('["abrir","abra","execute","abra","open","executa","executar"]')
        comandos.close()
        comandos = open("databases/" + nome + "Comandos" + '.json', 'r')

    return comandos

def get_comandosF(nome):
    try:
        comandos = open("databases/" + nome + "ComandosF" + '.json', 'r')
    except FileNotFoundError:
        comandos = open("databases/" + nome + "ComandosF" + '.json', 'w')
        comandos.write('["fechar","feche","close","fecha"]')
        comandos.close()
        comandos = open("databases/" + nome + "ComandosF" + '.json', 'r')

    return comandos

def get_email():
    try:
        email = open("databases/emails.pickle", 'rb')
    except FileNotFoundError:
        email = open("databases/emails.pickle", 'wb')
        pickle.dump(({"": ""}), email)
        email.close()
        email = open("databases/emails.pickle", 'rb')

    return email

def set_email(e_mail, senha):
    try:
        email = open("databases/emails.pickle", 'wb')
        pickle.dump(({e_mail: senha}), email)
        email.close()
    except:
        return "não encontrado"