code stringlengths 2k 1.04M | repo_path stringlengths 5 517 | parsed_code stringlengths 0 1.04M | quality_prob float64 0.02 0.95 | learning_prob float64 0.02 0.93 |
|---|---|---|---|---|
import re
import sys
import logging
import logging.handlers
from pygments.lexer import RegexLexer, include
from pygments.token import (Punctuation, Text, Comment, Keyword, Name, String,
Generic, Operator, Number, Whitespace, Literal, Error, Token)
from pygments import highlight
from pygments.formatters import get_formatter_by_name
from pygments.style import Style
class LogStyle(Style):
background_color = "#000000"
highlight_color = "#222222"
default_style = "#cccccc"
styles = {
Token: "#cccccc",
Whitespace: "",
Comment: "#000080",
Comment.Preproc: "",
Comment.Special: "bold #2BB537",
Keyword: "#cdcd00",
Keyword.Declaration: "#00cd00",
Keyword.Namespace: "#cd00cd",
Keyword.Pseudo: "bold #00cd00",
Keyword.Type: "#00cd00",
Operator: "#3399cc",
Operator.Word: "#cdcd00",
Name: "",
Name.Class: "#00cdcd",
Name.Builtin: "#cd00cd",
Name.Exception: "bold #666699",
Name.Variable: "#00cdcd",
String: "#cd0000",
Number: "#cd00cd",
Punctuation: "nobold #FFF",
Generic.Heading: "nobold #FFF",
Generic.Subheading: "#800080",
Generic.Deleted: "nobold #cd3",
Generic.Inserted: "#00cd00",
Generic.Error: "bold #FF0000",
Generic.Emph: "bold #FFFFFF",
Generic.Strong: "bold #FFFFFF",
Generic.Prompt: "bold #3030F0",
Generic.Output: "#888",
Generic.Traceback: "bold #04D",
Error: "bg:#FF0000 bold #FFF"
}
class LogLexer(RegexLexer):
name = 'Logging.py Logs'
aliases = ['log']
filenames = ['*.log']
mimetypes = ['text/x-log']
flags = re.VERBOSE
_logger = r'-\s(peri)(\.([a-z._\-0-9]+))*\s-'
_uuid = r"([A-Z]{2}_[0-9]{12}_[0-9]{3}-and-[A-Z]{2}_[0-9]{12}_[0-9]{3}-[0-9]{5,})"
_kimid = r"((?:[_a-zA-Z][_a-zA-Z0-9]*?_?_)?[A-Z]{2}_[0-9]{12}(?:_[0-9]{3})?)"
_path = r'(?:[a-zA-Z0-9_-]{0,}/{1,2}[a-zA-Z0-9_\.-]+)+'
_debug = r'DEBUG'
_info = r'INFO'
_pass = r'PASS'
_warn = r'WARNING'
_error = r'ERROR'
_crit = r'CRITICAL'
_date = r'\d{4}-\d{2}-\d{2}'
_time = r'\d{2}:\d{2}:\d{2},\d{3}'
_ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+'
_json = r'{.*}'
tokens = {
'whitespace': [
(_ws, Text),
(r'\n', Text),
(r'\s+', Text),
(r'\\\n', Text),
(r'\s-\s', Text)
],
'root': [
include('whitespace'),
(_uuid, Comment.Special),
(_kimid, Generic.Prompt),
(_logger, Generic.Emph),
(_date, Generic.Output),
(_time, Generic.Output),
(_path, Generic.Subheading),
(_json, Generic.Deleted),
(_warn, Generic.Strong),
(_info, Generic.Traceback),
(_error, Generic.Error),
(_pass, Keyword.Pseudo),
(_crit, Error),
(r'[0-9]+', Generic.Heading),
('[a-zA-Z_][a-zA-Z0-9_]*', Generic.Heading),
(r'[{}`()\"\[\]@.,:-\\]', Punctuation),
(r'[~!%^&*+=|?:<>/-]', Punctuation),
(r"'", Punctuation)
]
}
lexer = LogLexer()
def pygmentize(text, formatter='256', outfile=sys.stdout, style=LogStyle):
fmtr = get_formatter_by_name(formatter, style=style)
highlight(text, lexer, fmtr, outfile)
class PygmentHandler(logging.StreamHandler):
""" A beanstalk logging handler """
def __init__(self):
super(PygmentHandler,self).__init__()
def emit(self,record):
""" Send the message """
err_message = self.format(record)
pygmentize(err_message) | peri/logger_colors.py | import re
import sys
import logging
import logging.handlers
from pygments.lexer import RegexLexer, include
from pygments.token import (Punctuation, Text, Comment, Keyword, Name, String,
Generic, Operator, Number, Whitespace, Literal, Error, Token)
from pygments import highlight
from pygments.formatters import get_formatter_by_name
from pygments.style import Style
class LogStyle(Style):
background_color = "#000000"
highlight_color = "#222222"
default_style = "#cccccc"
styles = {
Token: "#cccccc",
Whitespace: "",
Comment: "#000080",
Comment.Preproc: "",
Comment.Special: "bold #2BB537",
Keyword: "#cdcd00",
Keyword.Declaration: "#00cd00",
Keyword.Namespace: "#cd00cd",
Keyword.Pseudo: "bold #00cd00",
Keyword.Type: "#00cd00",
Operator: "#3399cc",
Operator.Word: "#cdcd00",
Name: "",
Name.Class: "#00cdcd",
Name.Builtin: "#cd00cd",
Name.Exception: "bold #666699",
Name.Variable: "#00cdcd",
String: "#cd0000",
Number: "#cd00cd",
Punctuation: "nobold #FFF",
Generic.Heading: "nobold #FFF",
Generic.Subheading: "#800080",
Generic.Deleted: "nobold #cd3",
Generic.Inserted: "#00cd00",
Generic.Error: "bold #FF0000",
Generic.Emph: "bold #FFFFFF",
Generic.Strong: "bold #FFFFFF",
Generic.Prompt: "bold #3030F0",
Generic.Output: "#888",
Generic.Traceback: "bold #04D",
Error: "bg:#FF0000 bold #FFF"
}
class LogLexer(RegexLexer):
name = 'Logging.py Logs'
aliases = ['log']
filenames = ['*.log']
mimetypes = ['text/x-log']
flags = re.VERBOSE
_logger = r'-\s(peri)(\.([a-z._\-0-9]+))*\s-'
_uuid = r"([A-Z]{2}_[0-9]{12}_[0-9]{3}-and-[A-Z]{2}_[0-9]{12}_[0-9]{3}-[0-9]{5,})"
_kimid = r"((?:[_a-zA-Z][_a-zA-Z0-9]*?_?_)?[A-Z]{2}_[0-9]{12}(?:_[0-9]{3})?)"
_path = r'(?:[a-zA-Z0-9_-]{0,}/{1,2}[a-zA-Z0-9_\.-]+)+'
_debug = r'DEBUG'
_info = r'INFO'
_pass = r'PASS'
_warn = r'WARNING'
_error = r'ERROR'
_crit = r'CRITICAL'
_date = r'\d{4}-\d{2}-\d{2}'
_time = r'\d{2}:\d{2}:\d{2},\d{3}'
_ws = r'(?:\s|//.*?\n|/[*].*?[*]/)+'
_json = r'{.*}'
tokens = {
'whitespace': [
(_ws, Text),
(r'\n', Text),
(r'\s+', Text),
(r'\\\n', Text),
(r'\s-\s', Text)
],
'root': [
include('whitespace'),
(_uuid, Comment.Special),
(_kimid, Generic.Prompt),
(_logger, Generic.Emph),
(_date, Generic.Output),
(_time, Generic.Output),
(_path, Generic.Subheading),
(_json, Generic.Deleted),
(_warn, Generic.Strong),
(_info, Generic.Traceback),
(_error, Generic.Error),
(_pass, Keyword.Pseudo),
(_crit, Error),
(r'[0-9]+', Generic.Heading),
('[a-zA-Z_][a-zA-Z0-9_]*', Generic.Heading),
(r'[{}`()\"\[\]@.,:-\\]', Punctuation),
(r'[~!%^&*+=|?:<>/-]', Punctuation),
(r"'", Punctuation)
]
}
lexer = LogLexer()
def pygmentize(text, formatter='256', outfile=sys.stdout, style=LogStyle):
fmtr = get_formatter_by_name(formatter, style=style)
highlight(text, lexer, fmtr, outfile)
class PygmentHandler(logging.StreamHandler):
""" A beanstalk logging handler """
def __init__(self):
super(PygmentHandler,self).__init__()
def emit(self,record):
""" Send the message """
err_message = self.format(record)
pygmentize(err_message) | 0.260201 | 0.140307 |
import pyDOE as doe
import numpy as np
import os
from itertools import repeat
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import rcParams
import ParetoFrontND as pf
import StandardTestFunctions as fn
import GPyOpt
plt.style.use('ggplot')
rcParams['font.sans-serif'] = "Segoe UI"
rcParams['font.family'] = "sans-serif"
plot_size = 10.0
def fit_model(d2X, d1Y):
model = GPyOpt.models.GPModel(exact_feval=True, ARD=True)
model.updateModel(d2X, d1Y, [], [])
return model
def expected_improvement(mu, sigma, y_star):
s = (y_star - mu) / sigma
return sigma * (s * stats.norm.cdf(s) + stats.norm.pdf(s))
def normalise_f(f, exploration_param):
avg = np.mean(f)
low = np.min(f)
high = np.max(f)
offset = (1 - exploration_param) * avg + exploration_param * low
return (f - offset) / (high - low + 1e-6)
np.random.seed(1234)
# %% Setup problem
FUNCTION_NAME = "ZDT3"
NUM_INPUT_DIMS = 2
NUM_OBJECTIVES = 2
ZETA = 0.0
#REFERENCE = 1.2
# REFERENCE_START = 1.8
# REFERENCE_END = 1.2
#ABSOLUTE_REFERENCE = [REFERENCE, 10.]
# ABSOLUTE_REFERENCE = [100., 100.]
# d1Reference = np.repeat(1000.0, NUM_OBJECTIVES).tolist()
d1Reference = [1.1, 1000.0]
# Define input domain in GPyOpt format and fitness evaluation function
domain, fitnessfunc, d1x_opt, NUM_INPUT_DIMS, NUM_OBJECTIVES = fn.get_function_definition(
FUNCTION_NAME, NUM_INPUT_DIMS, NUM_OBJECTIVES)
def evaluate_fitness(ind):
assert len(ind) == NUM_INPUT_DIMS
return fitnessfunc(ind)
# d1F1F2 = np.array(list( map(evaluate_fitness, d1x_opt) ))
# d1F1F2_PF, _ = pf.getNonDominatedFront(d1F1F2)
# %% Generate initial experimental design
NUM_SAMPLES = NUM_INPUT_DIMS * 4
d2SolutionInput = doe.lhs(NUM_INPUT_DIMS, samples=NUM_SAMPLES, criterion='center')
d2SolutionOutput = np.array(list( map(evaluate_fitness, d2SolutionInput) ))
# Generate map across input space
d1Test = np.linspace(0.0, 1.0, 50)
d2X, d2Y = np.meshgrid(d1Test, d1Test)
d2TestPoints = np.hstack((d2X.reshape((-1,1)), d2Y.reshape((-1,1))))
d2TestResults = np.array(list( map(evaluate_fitness, d2TestPoints)))
d2Sol1 = d2TestResults[:,0].reshape(d2X.shape)
d2Sol2 = d2TestResults[:,1].reshape(d2X.shape)
fig, ax = plt.subplots(1, 2)
plt.subplot(ax[0])
contours = plt.contour(d2X, d2Y, d2Sol1, [0.25,0.5,0.75], colors='black')
plt.clabel(contours, inline=True, fontsize=7)
plt.imshow(d2Sol1, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0, vmax=1)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = 'black', marker = 'x', label = 'Initial Design')
plt.xlabel('$x_1$', fontsize=10)
plt.ylabel('$x_2$', fontsize=10)
plt.title('$f_1$', fontsize=10)
plt.tick_params(
axis='both',
left=True,
labelleft=True,
bottom=True,
labelbottom=True)
for tick in ax[0].get_xticklabels():
tick.set_fontsize(9)
for tick in ax[0].get_yticklabels():
tick.set_fontsize(9)
plt.subplot(ax[1])
contours = plt.contour(d2X, d2Y, d2Sol2, [1,3,5,7,9], colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(d2Sol2, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0, vmax=10)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = 'black', marker = 'x', label = 'Initial Design')
plt.xlabel('$x_1$', fontsize=10)
plt.title('$f_2$', fontsize=10)
plt.tick_params(
axis='both',
left=False,
labelleft=False,
bottom=True,
labelbottom=True)
for tick in ax[1].get_xticklabels():
tick.set_fontsize(9)
for tick in ax[1].get_yticklabels():
tick.set_fontsize(9)
plt.savefig(os.path.join("img","figure_4_a1.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size * 1.62, plot_size])
plot1 = plt.plot(d2TestResults[:,0], d2TestResults[:,1],
linestyle='', marker = '.', markersize=plot_size, color = 'lightblue',
label = 'Grid in input domain')
plt.plot(d2SolutionOutput[:,0], d2SolutionOutput[:,1],
c = 'black', linestyle='', marker = 'x', markersize=plot_size*1.5,
label = 'Initial Design')
d2TestFront, _ = pf.getNonDominatedFront(d2TestResults)
plt.plot(d2TestFront[:,0], d2TestFront[:,1],
linestyle = '', marker = '.', color = 'g', markersize = plot_size*1.5,
label = 'Pareto Front')
plt.xlabel('$f_1$', fontsize=plot_size*3.0)
plt.ylabel('$f_2$', fontsize=plot_size*3.0)
plt.tick_params(
axis='both',
left=True,
labelleft=True,
bottom=True,
labelbottom=True)
for tick in plot1[0].axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in plot1[0].axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.legend(loc='upper right', labelspacing=0.25, fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_a2.svg"), facecolor=None, edgecolor=None)
# %% xHVI example
des_space = GPyOpt.core.task.space.Design_space(domain)
acq_opt = GPyOpt.optimization.AcquisitionOptimizer(des_space, optimizer='lbfgs')
y_norm = normalise_f(np.array([(d2SolutionOutput[:, 0])]).transpose(), 0.0)
for m in range(1, NUM_OBJECTIVES):
y_norm = np.hstack((y_norm, normalise_f(np.array([(d2SolutionOutput[:, m])]).transpose(), 0.0)))
#Calculate xHVI
reference = np.repeat(1.0, NUM_OBJECTIVES).tolist()
d1HVI = pf.calculateHypervolumeContributions(y_norm, reference)
d1HVIn = pf.calculateNegativeHypervolumeContributions(y_norm)
d1xHVI = (d1HVI - d1HVIn)
d1xHVI_norm = normalise_f(d1xHVI, ZETA)
# Fit a GP model to xHVC
model = GPyOpt.models.GPModel(exact_feval=True, ARD=True)
model.updateModel(d2SolutionInput[:,:], -d1xHVI_norm, [], [])
# Run acquisition function
acq = GPyOpt.acquisitions.AcquisitionEI(model, des_space, jitter = 0.0, optimizer = acq_opt)
next_point, y_next_est = acq.optimize()
# Evaluate fitness and archive
y_next = evaluate_fitness(next_point[0])
# Figure: calculated xHVI
plt.figure(figsize=[plot_size * 1.62, plot_size])
scat1 = plt.scatter(y_norm[:,0], y_norm[:,1], c = d1xHVI[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=min(d1xHVI), vmax=-min(d1xHVI),
linewidths=1, edgecolors='k')
plt.axis('equal')
plt.plot(reference[0], reference[1], marker = 'x', markersize = plot_size*2.0, color = 'k')
plt.text(0.51, 0.92, 'reference point $r$', fontsize=plot_size*2.0)
plt.xlabel('$f_1$ (normalised)', fontsize=plot_size*3.0)
plt.ylabel('$f_2$ (normalised)', fontsize=plot_size*3.0)
cb = plt.colorbar()
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'xHVI', fontsize=plot_size*3.0)
for tick in scat1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in scat1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b1.svg"), facecolor=None, edgecolor=None)
# Figures: surrogate for normalised xHVI
mu, stdev = model.predict(d2TestPoints)
ei_xhvi = np.array(list( map(expected_improvement, mu, stdev, repeat(min(-d1xHVI_norm)))))
d2xhvc_pred = mu.reshape(d2X.shape)
d2xhvc_std_pred = stdev.reshape(d2X.shape)
d2xhvi_ei = ei_xhvi.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2xhvc_pred, np.linspace(-0.5, 0.5, 5), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2xhvc_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=-0.5, vmax=0.5)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c=d1xHVI_norm[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=-0.5, vmax=0.5,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $-xHVI_{norm}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$-xHVI_{norm}$', fontsize=plot_size*3.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b2a.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2xhvc_std_pred, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2xhvc_std_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $-xHVI_{norm}$ surrogate', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$xHVC_{norm}$', fontsize=10)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b2b.svg"), facecolor=None, edgecolor=None)
# Figure: EI(xHVI) acquisition
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2xhvi_ei, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2xhvi_ei, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(next_point[0][0], next_point[0][1], c='k', marker = 'x',
s=plot_size*25.0, linewidth=5)
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Expected Improvement Acquisition with xHVI', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'Expected Improvement', fontsize=plot_size*3.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b3.svg"), facecolor=None, edgecolor=None)
# %% HypI example
#Calculate HypI
d1HypI = pf.calculateHypIs(y_norm, reference)
d1HypI_norm = normalise_f(d1HypI, ZETA)
# Fit a GP model to xHVC
model2 = GPyOpt.models.GPModel(exact_feval=True, ARD=True)
model2.updateModel(d2SolutionInput[:,:], -d1HypI_norm, [], [])
# Run acquisition function
acq2 = GPyOpt.acquisitions.AcquisitionEI(model2, des_space, jitter = 0.0, optimizer = acq_opt)
next_point2, y_next_est2 = acq2.optimize()
# Evaluate fitness and archive
y_next2 = evaluate_fitness(next_point2[0])
# Figure: calculated xHVI
plt.figure(figsize=[plot_size * 1.62, plot_size])
scat2 = plt.scatter(y_norm[:,0], y_norm[:,1], c = d1HypI[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=min(d1HypI), vmax=-min(d1HypI),
linewidths=1, edgecolors='k')
plt.axis('equal')
plt.plot(reference[0], reference[1], marker = 'x', markersize = plot_size*2.0, color = 'k')
plt.text(0.51, 0.92, 'reference point $r$', fontsize=plot_size*2.0)
plt.xlabel('$f_1$ (normalised)', fontsize=plot_size*3.0)
plt.ylabel('$f_2$ (normalised)', fontsize=plot_size*3.0)
cb = plt.colorbar()
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'HypI', fontsize=plot_size*3.0)
for tick in scat2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in scat2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d1.svg"), facecolor=None, edgecolor=None)
# Figures: surrogate for normalised HypI
mu2, stdev2 = model2.predict(d2TestPoints)
ei_hypi = np.array(list( map(expected_improvement, mu2, stdev2, repeat(min(-d1HypI_norm)))))
d2hypi_pred = mu2.reshape(d2X.shape)
d2hypi_std_pred = stdev2.reshape(d2X.shape)
d2hypi_ei = ei_hypi.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2hypi_pred, np.linspace(-0.5, 0.5, 5), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im2 = plt.imshow(d2hypi_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=-0.5, vmax=0.5)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c=d1HypI_norm[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=-0.5, vmax=0.5,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $-HypI_{norm}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im2, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$-HypI_{norm}$', fontsize=plot_size*3.0)
for tick in im2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d2a.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2hypi_std_pred, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im2 = plt.imshow(d2hypi_std_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $-HypI_{norm}$ surrogate', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im2, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$xHVC_{norm}$', fontsize=10)
for tick in im2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d2b.svg"), facecolor=None, edgecolor=None)
# Figure: EI(HypI) acquisition
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2hypi_ei, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im2 = plt.imshow(d2hypi_ei, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn', alpha=0.5, vmin=0.0, vmax=0.25)
plt.scatter(next_point[0][0], next_point[0][1], c='k', marker = 'x',
s=plot_size*25.0, linewidth=5)
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Expected Improvement Acquisition with HypI', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im2, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'Expected Improvement', fontsize=plot_size*3.0)
for tick in im2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d3.svg"), facecolor=None, edgecolor=None)
# %% EHVI example
bounds = []
for q in range(len(domain)):
bounds.append(domain[q]['domain'])
bounds = np.array(bounds)
optimizer = GPyOpt.optimization.optimizer.OptLbfgs(bounds)
# Fit GPs
f_norm = normalise_f(np.array([(d2SolutionOutput[:, 0])]).transpose(), ZETA)
for m in range(1, NUM_OBJECTIVES):
f_norm = np.hstack((f_norm, normalise_f(np.array([(d2SolutionOutput[:, m])]).transpose(), ZETA)))
models = []
for m in range(NUM_OBJECTIVES):
models.append(fit_model(d2SolutionInput, f_norm[:,m].reshape((-1,1))))
d2CurrentFrontNorm, _ = pf.getNonDominatedFront(f_norm)
def ehvi_evaluate(d1X):
mu = []
s = []
for m in range(len(models)):
mu_new, s_new = models[m].predict(d1X)
mu.append(mu_new[0])
s.append(s_new[0])
ehvi = pf.calculateExpectedHypervolumeContributionMC(
np.array(mu),
np.array(s),
d2CurrentFrontNorm,
[1., 1.],
1000)
return -ehvi # Maximise
# Run EHVI acquisition
ehvi_max = 0.0
x_next_ehvi = d2SolutionInput[0]
for n in range(10):
# Multi-restart
x_test = pf.getExcitingNewLocation(d2SolutionOutput, d2SolutionInput, bounds[:,0], bounds[:,1], jitter=0.2)
print("EHVI optimisation, iteration {0}/10]".format(n+1))
x_opt, f_opt = optimizer.optimize(np.array(x_test), f=ehvi_evaluate)
#print("Reached [{0:0.3f}, {1:0.3f}], value {2:0.4f}".format(x_opt[0][0], x_opt[0][1], f_opt[0][0]))
if f_opt[0][0] < ehvi_max:
ehvi_max = f_opt[0][0]
x_next_ehvi = x_opt[0]
#print("New best.")
y_next_ehvi = evaluate_fitness(x_next_ehvi)
# Figure: y_norm
plt.figure(figsize=[plot_size * 1.62, plot_size])
scat1 = plt.scatter(f_norm[:,0], f_norm[:,1], c = 'k', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.axis('equal')
plt.plot(1., 1., marker = 'x', markersize = plot_size*2.0, color = 'k')
plt.text(0.51, 0.92, 'reference point $r$', fontsize=plot_size*2.0)
plt.xlabel('$f_1$ (normalised)', fontsize=plot_size*3.0)
plt.ylabel('$f_2$ (normalised)', fontsize=plot_size*3.0)
for tick in scat1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in scat1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c0.svg"), facecolor=None, edgecolor=None)
# Figures: Surrogate models
# F1
mu_f1, stdev_f1 = models[0].predict(d2TestPoints)
d2f1_pred = mu_f1.reshape(d2X.shape)
d2f1_pred_std = stdev_f1.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f1_pred, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f1_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=min(mu_f1), vmax=max(mu_f1))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = f_norm[:,0], s=plot_size*25.0,
linewidths=1, edgecolors='k',
cmap='RdYlGn_r', vmin=min(mu_f1), vmax=max(mu_f1))
# plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $f_{1_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1a1.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f1_pred_std, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f1_pred_std, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=max(stdev_f1))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
# plt.xlabel('$x_1$', fontsize=plot_size*3.0)
# plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $f_{1_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1a2.svg"), facecolor=None, edgecolor=None)
# F2
mu_f2, stdev_f2 = models[1].predict(d2TestPoints)
d2f2_pred = mu_f2.reshape(d2X.shape)
d2f2_pred_std = stdev_f2.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f2_pred, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f2_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=min(mu_f2), vmax=max(mu_f2))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = f_norm[:,1], s=plot_size*25.0,
linewidths=1, edgecolors='k',
cmap='RdYlGn_r', vmin=min(mu_f2), vmax=max(mu_f2))
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $f_{2_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1b1.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f2_pred_std, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f2_pred_std, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=max(stdev_f2))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
# plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $f_{2_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1b2.svg"), facecolor=None, edgecolor=None)
# EHVI surface
d1EHVI = np.zeros([d2TestPoints.shape[0], 1])
for i in range(d2TestPoints.shape[0]):
d1EHVI[i,0] = pf.calculateExpectedHypervolumeContributionMC(
np.array([mu_f1[i], mu_f2[i]]),
np.array([stdev_f1[i], stdev_f2[i]]),
d2CurrentFrontNorm,
np.array([1., 1.]),
1000)
d2ehvi_pred = d1EHVI.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2ehvi_pred, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2ehvi_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(x_next_ehvi[0], x_next_ehvi[1], color='k', marker = 'x',
linewidth=5, s=plot_size*25.0)
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
cb.set_label(label = '$EHVI$', fontsize=plot_size*3.0)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c2.svg"), facecolor=None, edgecolor=None) | standard-test-functions/figure_4.py | import pyDOE as doe
import numpy as np
import os
from itertools import repeat
from scipy import stats
import matplotlib.pyplot as plt
from matplotlib import rcParams
import ParetoFrontND as pf
import StandardTestFunctions as fn
import GPyOpt
plt.style.use('ggplot')
rcParams['font.sans-serif'] = "Segoe UI"
rcParams['font.family'] = "sans-serif"
plot_size = 10.0
def fit_model(d2X, d1Y):
model = GPyOpt.models.GPModel(exact_feval=True, ARD=True)
model.updateModel(d2X, d1Y, [], [])
return model
def expected_improvement(mu, sigma, y_star):
s = (y_star - mu) / sigma
return sigma * (s * stats.norm.cdf(s) + stats.norm.pdf(s))
def normalise_f(f, exploration_param):
avg = np.mean(f)
low = np.min(f)
high = np.max(f)
offset = (1 - exploration_param) * avg + exploration_param * low
return (f - offset) / (high - low + 1e-6)
np.random.seed(1234)
# %% Setup problem
FUNCTION_NAME = "ZDT3"
NUM_INPUT_DIMS = 2
NUM_OBJECTIVES = 2
ZETA = 0.0
#REFERENCE = 1.2
# REFERENCE_START = 1.8
# REFERENCE_END = 1.2
#ABSOLUTE_REFERENCE = [REFERENCE, 10.]
# ABSOLUTE_REFERENCE = [100., 100.]
# d1Reference = np.repeat(1000.0, NUM_OBJECTIVES).tolist()
d1Reference = [1.1, 1000.0]
# Define input domain in GPyOpt format and fitness evaluation function
domain, fitnessfunc, d1x_opt, NUM_INPUT_DIMS, NUM_OBJECTIVES = fn.get_function_definition(
FUNCTION_NAME, NUM_INPUT_DIMS, NUM_OBJECTIVES)
def evaluate_fitness(ind):
assert len(ind) == NUM_INPUT_DIMS
return fitnessfunc(ind)
# d1F1F2 = np.array(list( map(evaluate_fitness, d1x_opt) ))
# d1F1F2_PF, _ = pf.getNonDominatedFront(d1F1F2)
# %% Generate initial experimental design
NUM_SAMPLES = NUM_INPUT_DIMS * 4
d2SolutionInput = doe.lhs(NUM_INPUT_DIMS, samples=NUM_SAMPLES, criterion='center')
d2SolutionOutput = np.array(list( map(evaluate_fitness, d2SolutionInput) ))
# Generate map across input space
d1Test = np.linspace(0.0, 1.0, 50)
d2X, d2Y = np.meshgrid(d1Test, d1Test)
d2TestPoints = np.hstack((d2X.reshape((-1,1)), d2Y.reshape((-1,1))))
d2TestResults = np.array(list( map(evaluate_fitness, d2TestPoints)))
d2Sol1 = d2TestResults[:,0].reshape(d2X.shape)
d2Sol2 = d2TestResults[:,1].reshape(d2X.shape)
fig, ax = plt.subplots(1, 2)
plt.subplot(ax[0])
contours = plt.contour(d2X, d2Y, d2Sol1, [0.25,0.5,0.75], colors='black')
plt.clabel(contours, inline=True, fontsize=7)
plt.imshow(d2Sol1, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0, vmax=1)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = 'black', marker = 'x', label = 'Initial Design')
plt.xlabel('$x_1$', fontsize=10)
plt.ylabel('$x_2$', fontsize=10)
plt.title('$f_1$', fontsize=10)
plt.tick_params(
axis='both',
left=True,
labelleft=True,
bottom=True,
labelbottom=True)
for tick in ax[0].get_xticklabels():
tick.set_fontsize(9)
for tick in ax[0].get_yticklabels():
tick.set_fontsize(9)
plt.subplot(ax[1])
contours = plt.contour(d2X, d2Y, d2Sol2, [1,3,5,7,9], colors='black')
plt.clabel(contours, inline=True, fontsize=8)
plt.imshow(d2Sol2, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0, vmax=10)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = 'black', marker = 'x', label = 'Initial Design')
plt.xlabel('$x_1$', fontsize=10)
plt.title('$f_2$', fontsize=10)
plt.tick_params(
axis='both',
left=False,
labelleft=False,
bottom=True,
labelbottom=True)
for tick in ax[1].get_xticklabels():
tick.set_fontsize(9)
for tick in ax[1].get_yticklabels():
tick.set_fontsize(9)
plt.savefig(os.path.join("img","figure_4_a1.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size * 1.62, plot_size])
plot1 = plt.plot(d2TestResults[:,0], d2TestResults[:,1],
linestyle='', marker = '.', markersize=plot_size, color = 'lightblue',
label = 'Grid in input domain')
plt.plot(d2SolutionOutput[:,0], d2SolutionOutput[:,1],
c = 'black', linestyle='', marker = 'x', markersize=plot_size*1.5,
label = 'Initial Design')
d2TestFront, _ = pf.getNonDominatedFront(d2TestResults)
plt.plot(d2TestFront[:,0], d2TestFront[:,1],
linestyle = '', marker = '.', color = 'g', markersize = plot_size*1.5,
label = 'Pareto Front')
plt.xlabel('$f_1$', fontsize=plot_size*3.0)
plt.ylabel('$f_2$', fontsize=plot_size*3.0)
plt.tick_params(
axis='both',
left=True,
labelleft=True,
bottom=True,
labelbottom=True)
for tick in plot1[0].axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in plot1[0].axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.legend(loc='upper right', labelspacing=0.25, fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_a2.svg"), facecolor=None, edgecolor=None)
# %% xHVI example
des_space = GPyOpt.core.task.space.Design_space(domain)
acq_opt = GPyOpt.optimization.AcquisitionOptimizer(des_space, optimizer='lbfgs')
y_norm = normalise_f(np.array([(d2SolutionOutput[:, 0])]).transpose(), 0.0)
for m in range(1, NUM_OBJECTIVES):
y_norm = np.hstack((y_norm, normalise_f(np.array([(d2SolutionOutput[:, m])]).transpose(), 0.0)))
#Calculate xHVI
reference = np.repeat(1.0, NUM_OBJECTIVES).tolist()
d1HVI = pf.calculateHypervolumeContributions(y_norm, reference)
d1HVIn = pf.calculateNegativeHypervolumeContributions(y_norm)
d1xHVI = (d1HVI - d1HVIn)
d1xHVI_norm = normalise_f(d1xHVI, ZETA)
# Fit a GP model to xHVC
model = GPyOpt.models.GPModel(exact_feval=True, ARD=True)
model.updateModel(d2SolutionInput[:,:], -d1xHVI_norm, [], [])
# Run acquisition function
acq = GPyOpt.acquisitions.AcquisitionEI(model, des_space, jitter = 0.0, optimizer = acq_opt)
next_point, y_next_est = acq.optimize()
# Evaluate fitness and archive
y_next = evaluate_fitness(next_point[0])
# Figure: calculated xHVI
plt.figure(figsize=[plot_size * 1.62, plot_size])
scat1 = plt.scatter(y_norm[:,0], y_norm[:,1], c = d1xHVI[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=min(d1xHVI), vmax=-min(d1xHVI),
linewidths=1, edgecolors='k')
plt.axis('equal')
plt.plot(reference[0], reference[1], marker = 'x', markersize = plot_size*2.0, color = 'k')
plt.text(0.51, 0.92, 'reference point $r$', fontsize=plot_size*2.0)
plt.xlabel('$f_1$ (normalised)', fontsize=plot_size*3.0)
plt.ylabel('$f_2$ (normalised)', fontsize=plot_size*3.0)
cb = plt.colorbar()
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'xHVI', fontsize=plot_size*3.0)
for tick in scat1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in scat1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b1.svg"), facecolor=None, edgecolor=None)
# Figures: surrogate for normalised xHVI
mu, stdev = model.predict(d2TestPoints)
ei_xhvi = np.array(list( map(expected_improvement, mu, stdev, repeat(min(-d1xHVI_norm)))))
d2xhvc_pred = mu.reshape(d2X.shape)
d2xhvc_std_pred = stdev.reshape(d2X.shape)
d2xhvi_ei = ei_xhvi.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2xhvc_pred, np.linspace(-0.5, 0.5, 5), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2xhvc_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=-0.5, vmax=0.5)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c=d1xHVI_norm[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=-0.5, vmax=0.5,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $-xHVI_{norm}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$-xHVI_{norm}$', fontsize=plot_size*3.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b2a.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2xhvc_std_pred, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2xhvc_std_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $-xHVI_{norm}$ surrogate', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$xHVC_{norm}$', fontsize=10)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b2b.svg"), facecolor=None, edgecolor=None)
# Figure: EI(xHVI) acquisition
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2xhvi_ei, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2xhvi_ei, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(next_point[0][0], next_point[0][1], c='k', marker = 'x',
s=plot_size*25.0, linewidth=5)
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Expected Improvement Acquisition with xHVI', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'Expected Improvement', fontsize=plot_size*3.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_b3.svg"), facecolor=None, edgecolor=None)
# %% HypI example
#Calculate HypI
d1HypI = pf.calculateHypIs(y_norm, reference)
d1HypI_norm = normalise_f(d1HypI, ZETA)
# Fit a GP model to xHVC
model2 = GPyOpt.models.GPModel(exact_feval=True, ARD=True)
model2.updateModel(d2SolutionInput[:,:], -d1HypI_norm, [], [])
# Run acquisition function
acq2 = GPyOpt.acquisitions.AcquisitionEI(model2, des_space, jitter = 0.0, optimizer = acq_opt)
next_point2, y_next_est2 = acq2.optimize()
# Evaluate fitness and archive
y_next2 = evaluate_fitness(next_point2[0])
# Figure: calculated xHVI
plt.figure(figsize=[plot_size * 1.62, plot_size])
scat2 = plt.scatter(y_norm[:,0], y_norm[:,1], c = d1HypI[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=min(d1HypI), vmax=-min(d1HypI),
linewidths=1, edgecolors='k')
plt.axis('equal')
plt.plot(reference[0], reference[1], marker = 'x', markersize = plot_size*2.0, color = 'k')
plt.text(0.51, 0.92, 'reference point $r$', fontsize=plot_size*2.0)
plt.xlabel('$f_1$ (normalised)', fontsize=plot_size*3.0)
plt.ylabel('$f_2$ (normalised)', fontsize=plot_size*3.0)
cb = plt.colorbar()
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'HypI', fontsize=plot_size*3.0)
for tick in scat2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in scat2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d1.svg"), facecolor=None, edgecolor=None)
# Figures: surrogate for normalised HypI
mu2, stdev2 = model2.predict(d2TestPoints)
ei_hypi = np.array(list( map(expected_improvement, mu2, stdev2, repeat(min(-d1HypI_norm)))))
d2hypi_pred = mu2.reshape(d2X.shape)
d2hypi_std_pred = stdev2.reshape(d2X.shape)
d2hypi_ei = ei_hypi.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2hypi_pred, np.linspace(-0.5, 0.5, 5), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im2 = plt.imshow(d2hypi_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=-0.5, vmax=0.5)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c=d1HypI_norm[:,0], s=plot_size*25.0,
cmap='RdYlGn', vmin=-0.5, vmax=0.5,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $-HypI_{norm}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im2, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$-HypI_{norm}$', fontsize=plot_size*3.0)
for tick in im2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d2a.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2hypi_std_pred, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im2 = plt.imshow(d2hypi_std_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $-HypI_{norm}$ surrogate', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im2, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
# cb.set_label(label = '$xHVC_{norm}$', fontsize=10)
for tick in im2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d2b.svg"), facecolor=None, edgecolor=None)
# Figure: EI(HypI) acquisition
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9 ])
contours = plt.contour(d2X, d2Y, d2hypi_ei, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im2 = plt.imshow(d2hypi_ei, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn', alpha=0.5, vmin=0.0, vmax=0.25)
plt.scatter(next_point[0][0], next_point[0][1], c='k', marker = 'x',
s=plot_size*25.0, linewidth=5)
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Expected Improvement Acquisition with HypI', fontsize=plot_size*3.0);
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im2, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
cb.set_label(label = 'Expected Improvement', fontsize=plot_size*3.0)
for tick in im2.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in im2.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_d3.svg"), facecolor=None, edgecolor=None)
# %% EHVI example
bounds = []
for q in range(len(domain)):
bounds.append(domain[q]['domain'])
bounds = np.array(bounds)
optimizer = GPyOpt.optimization.optimizer.OptLbfgs(bounds)
# Fit GPs
f_norm = normalise_f(np.array([(d2SolutionOutput[:, 0])]).transpose(), ZETA)
for m in range(1, NUM_OBJECTIVES):
f_norm = np.hstack((f_norm, normalise_f(np.array([(d2SolutionOutput[:, m])]).transpose(), ZETA)))
models = []
for m in range(NUM_OBJECTIVES):
models.append(fit_model(d2SolutionInput, f_norm[:,m].reshape((-1,1))))
d2CurrentFrontNorm, _ = pf.getNonDominatedFront(f_norm)
def ehvi_evaluate(d1X):
mu = []
s = []
for m in range(len(models)):
mu_new, s_new = models[m].predict(d1X)
mu.append(mu_new[0])
s.append(s_new[0])
ehvi = pf.calculateExpectedHypervolumeContributionMC(
np.array(mu),
np.array(s),
d2CurrentFrontNorm,
[1., 1.],
1000)
return -ehvi # Maximise
# Run EHVI acquisition
ehvi_max = 0.0
x_next_ehvi = d2SolutionInput[0]
for n in range(10):
# Multi-restart
x_test = pf.getExcitingNewLocation(d2SolutionOutput, d2SolutionInput, bounds[:,0], bounds[:,1], jitter=0.2)
print("EHVI optimisation, iteration {0}/10]".format(n+1))
x_opt, f_opt = optimizer.optimize(np.array(x_test), f=ehvi_evaluate)
#print("Reached [{0:0.3f}, {1:0.3f}], value {2:0.4f}".format(x_opt[0][0], x_opt[0][1], f_opt[0][0]))
if f_opt[0][0] < ehvi_max:
ehvi_max = f_opt[0][0]
x_next_ehvi = x_opt[0]
#print("New best.")
y_next_ehvi = evaluate_fitness(x_next_ehvi)
# Figure: y_norm
plt.figure(figsize=[plot_size * 1.62, plot_size])
scat1 = plt.scatter(f_norm[:,0], f_norm[:,1], c = 'k', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.axis('equal')
plt.plot(1., 1., marker = 'x', markersize = plot_size*2.0, color = 'k')
plt.text(0.51, 0.92, 'reference point $r$', fontsize=plot_size*2.0)
plt.xlabel('$f_1$ (normalised)', fontsize=plot_size*3.0)
plt.ylabel('$f_2$ (normalised)', fontsize=plot_size*3.0)
for tick in scat1.axes.get_xticklabels():
tick.set_fontsize(plot_size*2.0)
for tick in scat1.axes.get_yticklabels():
tick.set_fontsize(plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c0.svg"), facecolor=None, edgecolor=None)
# Figures: Surrogate models
# F1
mu_f1, stdev_f1 = models[0].predict(d2TestPoints)
d2f1_pred = mu_f1.reshape(d2X.shape)
d2f1_pred_std = stdev_f1.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f1_pred, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f1_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=min(mu_f1), vmax=max(mu_f1))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = f_norm[:,0], s=plot_size*25.0,
linewidths=1, edgecolors='k',
cmap='RdYlGn_r', vmin=min(mu_f1), vmax=max(mu_f1))
# plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $f_{1_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1a1.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f1_pred_std, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f1_pred_std, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=max(stdev_f1))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
# plt.xlabel('$x_1$', fontsize=plot_size*3.0)
# plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $f_{1_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1a2.svg"), facecolor=None, edgecolor=None)
# F2
mu_f2, stdev_f2 = models[1].predict(d2TestPoints)
d2f2_pred = mu_f2.reshape(d2X.shape)
d2f2_pred_std = stdev_f2.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f2_pred, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f2_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=min(mu_f2), vmax=max(mu_f2))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c = f_norm[:,1], s=plot_size*25.0,
linewidths=1, edgecolors='k',
cmap='RdYlGn_r', vmin=min(mu_f2), vmax=max(mu_f2))
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Mean function from $f_{2_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1b1.svg"), facecolor=None, edgecolor=None)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2f2_pred_std, 5, colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2f2_pred_std, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn_r', alpha=0.5, vmin=0.0, vmax=max(stdev_f2))
plt.scatter(d2SolutionInput[:,0], d2SolutionInput[:,1], c ='g', s=plot_size*25.0,
linewidths=1, edgecolors='k')
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
# plt.ylabel('$x_2$', fontsize=plot_size*3.0)
plt.title('Standard deviation from $f_{2_{norm}}$ surrogate', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c1b2.svg"), facecolor=None, edgecolor=None)
# EHVI surface
d1EHVI = np.zeros([d2TestPoints.shape[0], 1])
for i in range(d2TestPoints.shape[0]):
d1EHVI[i,0] = pf.calculateExpectedHypervolumeContributionMC(
np.array([mu_f1[i], mu_f2[i]]),
np.array([stdev_f1[i], stdev_f2[i]]),
d2CurrentFrontNorm,
np.array([1., 1.]),
1000)
d2ehvi_pred = d1EHVI.reshape(d2X.shape)
plt.figure(figsize=[plot_size, plot_size])
ax = plt.axes([0, 0.05, 0.9, 0.9])
contours = plt.contour(d2X, d2Y, d2ehvi_pred, np.linspace(0.05, 0.2, 4), colors='black')
plt.clabel(contours, inline=True, fontsize=plot_size*1.5)
im1 = plt.imshow(d2ehvi_pred, extent=[0, 1.0, 0, 1.0], origin='lower',
cmap='RdYlGn', alpha=0.5, vmin=0.0, vmax=0.2)
plt.scatter(x_next_ehvi[0], x_next_ehvi[1], color='k', marker = 'x',
linewidth=5, s=plot_size*25.0)
plt.xlabel('$x_1$', fontsize=plot_size*3.0)
plt.ylabel('$x_2$', fontsize=plot_size*3.0)
cax = plt.axes([0.95, 0.05, 0.05, 0.9])
cb = plt.colorbar(mappable=im1, cax=cax)
cb.set_label(label = '$EHVI$', fontsize=plot_size*3.0)
for t in cb.ax.get_yticklabels():
t.set_fontsize(plot_size*2.0)
for tick in im1.axes.get_xticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
for tick in im1.axes.get_yticklabels():
tick.set_fontsize(fontsize=plot_size*2.0)
plt.savefig(os.path.join("img","figure_4_c2.svg"), facecolor=None, edgecolor=None) | 0.455683 | 0.606178 |
from powrl3.util.fileio import *
import numpy as np
from collections import deque
import random
import pickle
import os
class EligibilityTraces(object):
def __init__(self, actions, n_dim):
self.actions = actions
n = len(actions)
self.n_dim = n_dim
self.traces = np.zeros((n, n_dim))
def reset(self):
self.traces = np.zeros_like(self.traces)
def get(self, a):
return self.traces[self.actions[a]]
def update(self, X, a, gamma=0.99, lambda_=0.3):
self.traces *= gamma*lambda_
i = self.actions[a]
self.traces[i] += X
def save(self, filename):
"""
Save the model in a TAR file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/el_tr.tgz'
>>> test_model = EligibilityTraces.load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
# 1) Save the JSON with actions (to know which vector corresponds with each action)
base_path = os.path.dirname(filename)
config_path = os.path.join(base_path, 'config.json')
traces_path = os.path.join(base_path, 'traces.pkl')
actions = [{"action": a, "index": i} for (a, i) in self.actions.items()]
json_res = {"n_dimensions": self.n_dim, "actions": actions}
success_save_config = save_dict_as_json(json_res, filename=config_path, pretty_print=True)
# 2) Save the serialized array of traces
success_save_traces = serialize_python_object(self.traces, traces_path)
if all([success_save_config, success_save_traces]):
files = [config_path, traces_path]
success = compress_tar_files(files=files, filename=filename)
else:
success = False
try:
# remove temporary files which are already compressed
os.remove(config_path)
os.remove(traces_path)
except:
pass
return success
def load(self, filename):
success = False
success_decompress = decompress_tar_files(filename)
if success_decompress is True:
base_path = os.path.dirname(filename)
config_path = os.path.join(base_path, 'config.json')
traces_path = os.path.join(base_path, 'traces.pkl')
# 1) Load the JSON config file
json_res = load_json_as_dict(config_path)
# TODO: validate json loaded
self.n_dim = json_res["n_dimensions"]
self.actions = dict([(r["action"], r["index"])
for r in json_res["actions"]])
# 2) Load the array of traces
try:
with open(traces_path, 'rb') as f:
self.traces = pickle.load(f)
success = True
except:
self.traces = np.zeros((len(self.actions), self.n_dim))
success = False
try:
# remove temporary files which are already decompressed
os.remove(config_path)
os.remove(traces_path)
except:
pass
return self
class ReplacingEligibilityTraces(EligibilityTraces):
def __init__(self, actions, n_dim):
EligibilityTraces.__init__(self, actions=actions, n_dim=n_dim)
def update(self, X, a, gamma=0.99, lambda_=0.3):
self.traces *= gamma*lambda_
i = self.actions[a]
self.traces[i] = X
# - https://towardsdatascience.com/reinforcement-learning-w-keras-openai-actor-critic-models-f084612cfd69
# - https://pymotw.com/2/collections/deque.html
class ExperienceReplay2(object):
def __init__(self, max_items=5000):
self.buffer = deque(maxlen=max_items)
self.max_items = max_items
def add_state(self, state, value):
# Overwrite existing value if the state is already stored
self.buffer.append((state, value))
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
return random.sample(self.buffer, n_items)
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = deque([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplay(object):
def __init__(self, max_items=5000):
self.buffer = {}
self.max_items = max_items
def add_state(self, state, value):
# Overwrite existing value if the state is already stored
self.buffer[state] = value
if len(self.buffer) > self.max_items:
# Forget the min value
pop_item = min(self.buffer.items(), key=lambda i: i[1])
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
return random.sample(self.buffer.items(), n_items)
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplayAC(object):
def __init__(self, max_items=5000):
self.buffer = {}
self.max_items = max_items
def add(self, s, a, r, s_prime, t):
# Overwrite existing value if the state is already stored
self.buffer[tuple(s)] = (a, r, s_prime, t)
if len(self.buffer) > self.max_items:
# Forget the item with the least reward
#pop_item = min(self.buffer.items(), key=lambda i: i[1][1])
pop_item = min(self.buffer.items(), key=lambda i: abs(i[1][1]))
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
sample = [(s, a, r, s_prime, t) for (s, (a, r, s_prime, t)) in random.sample(self.buffer.items(), n_items)]
return sample
def get_sample2(self, max_items=50):
n_items = min(len(self.buffer), max_items)
population = self.buffer.items()
sample_index = np.random.multinomial(n=n_items, pvals=[])
sample = [(s, a, r, s_prime, t) for (s, (a, r, s_prime, t)) in random.sample(population, n_items)]
return sample
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplayACA(object):
def __init__(self, max_items=5000):
self.buffer = {}
self.max_items = max_items
def add(self, s, a, r, s_prime, t):
# Overwrite existing value if the state is already stored
self.buffer[(tuple(s), a)] = (r, s_prime, t)
if len(self.buffer) > self.max_items:
# Forget the item with the least reward
#pop_item = min(self.buffer.items(), key=lambda i: i[1][0])
pop_item = min(self.buffer.items(), key=lambda i: abs(i[1][0]))
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
sample = [(s, a, r, s_prime, t) for ((s, a), (r, s_prime, t)) in random.sample(self.buffer.items(), n_items)]
return sample
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplayEligibility(ExperienceReplay):
def __init__(self, max_items=5000):
ExperienceReplay.__init__(self, max_items=max_items)
def add_state_e(self, state, value, e):
# Overwrite existing value if the state is already stored
self.buffer[state] = (value, e)
if len(self.buffer) > self.max_items:
# Forget the min value
pop_item = min(self.buffer.items(), key=lambda i: i[1][0])
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def save(self, filename):
buf = [{"key": k, "value": v, "eligibility": list(e)}
for (k, (v, e)) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(tuple(b["key"]), (b["value"], np.asarray(b["eligibility"])))
for b in json_res["buffer"]])
return self | powrl3/agent/a2c/util.py | from powrl3.util.fileio import *
import numpy as np
from collections import deque
import random
import pickle
import os
class EligibilityTraces(object):
def __init__(self, actions, n_dim):
self.actions = actions
n = len(actions)
self.n_dim = n_dim
self.traces = np.zeros((n, n_dim))
def reset(self):
self.traces = np.zeros_like(self.traces)
def get(self, a):
return self.traces[self.actions[a]]
def update(self, X, a, gamma=0.99, lambda_=0.3):
self.traces *= gamma*lambda_
i = self.actions[a]
self.traces[i] += X
def save(self, filename):
"""
Save the model in a TAR file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/el_tr.tgz'
>>> test_model = EligibilityTraces.load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
# 1) Save the JSON with actions (to know which vector corresponds with each action)
base_path = os.path.dirname(filename)
config_path = os.path.join(base_path, 'config.json')
traces_path = os.path.join(base_path, 'traces.pkl')
actions = [{"action": a, "index": i} for (a, i) in self.actions.items()]
json_res = {"n_dimensions": self.n_dim, "actions": actions}
success_save_config = save_dict_as_json(json_res, filename=config_path, pretty_print=True)
# 2) Save the serialized array of traces
success_save_traces = serialize_python_object(self.traces, traces_path)
if all([success_save_config, success_save_traces]):
files = [config_path, traces_path]
success = compress_tar_files(files=files, filename=filename)
else:
success = False
try:
# remove temporary files which are already compressed
os.remove(config_path)
os.remove(traces_path)
except:
pass
return success
def load(self, filename):
success = False
success_decompress = decompress_tar_files(filename)
if success_decompress is True:
base_path = os.path.dirname(filename)
config_path = os.path.join(base_path, 'config.json')
traces_path = os.path.join(base_path, 'traces.pkl')
# 1) Load the JSON config file
json_res = load_json_as_dict(config_path)
# TODO: validate json loaded
self.n_dim = json_res["n_dimensions"]
self.actions = dict([(r["action"], r["index"])
for r in json_res["actions"]])
# 2) Load the array of traces
try:
with open(traces_path, 'rb') as f:
self.traces = pickle.load(f)
success = True
except:
self.traces = np.zeros((len(self.actions), self.n_dim))
success = False
try:
# remove temporary files which are already decompressed
os.remove(config_path)
os.remove(traces_path)
except:
pass
return self
class ReplacingEligibilityTraces(EligibilityTraces):
def __init__(self, actions, n_dim):
EligibilityTraces.__init__(self, actions=actions, n_dim=n_dim)
def update(self, X, a, gamma=0.99, lambda_=0.3):
self.traces *= gamma*lambda_
i = self.actions[a]
self.traces[i] = X
# - https://towardsdatascience.com/reinforcement-learning-w-keras-openai-actor-critic-models-f084612cfd69
# - https://pymotw.com/2/collections/deque.html
class ExperienceReplay2(object):
def __init__(self, max_items=5000):
self.buffer = deque(maxlen=max_items)
self.max_items = max_items
def add_state(self, state, value):
# Overwrite existing value if the state is already stored
self.buffer.append((state, value))
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
return random.sample(self.buffer, n_items)
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = deque([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplay(object):
def __init__(self, max_items=5000):
self.buffer = {}
self.max_items = max_items
def add_state(self, state, value):
# Overwrite existing value if the state is already stored
self.buffer[state] = value
if len(self.buffer) > self.max_items:
# Forget the min value
pop_item = min(self.buffer.items(), key=lambda i: i[1])
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
return random.sample(self.buffer.items(), n_items)
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplayAC(object):
def __init__(self, max_items=5000):
self.buffer = {}
self.max_items = max_items
def add(self, s, a, r, s_prime, t):
# Overwrite existing value if the state is already stored
self.buffer[tuple(s)] = (a, r, s_prime, t)
if len(self.buffer) > self.max_items:
# Forget the item with the least reward
#pop_item = min(self.buffer.items(), key=lambda i: i[1][1])
pop_item = min(self.buffer.items(), key=lambda i: abs(i[1][1]))
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
sample = [(s, a, r, s_prime, t) for (s, (a, r, s_prime, t)) in random.sample(self.buffer.items(), n_items)]
return sample
def get_sample2(self, max_items=50):
n_items = min(len(self.buffer), max_items)
population = self.buffer.items()
sample_index = np.random.multinomial(n=n_items, pvals=[])
sample = [(s, a, r, s_prime, t) for (s, (a, r, s_prime, t)) in random.sample(population, n_items)]
return sample
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplayACA(object):
def __init__(self, max_items=5000):
self.buffer = {}
self.max_items = max_items
def add(self, s, a, r, s_prime, t):
# Overwrite existing value if the state is already stored
self.buffer[(tuple(s), a)] = (r, s_prime, t)
if len(self.buffer) > self.max_items:
# Forget the item with the least reward
#pop_item = min(self.buffer.items(), key=lambda i: i[1][0])
pop_item = min(self.buffer.items(), key=lambda i: abs(i[1][0]))
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def get_sample(self, max_items=50):
n_items = min(len(self.buffer), max_items)
sample = [(s, a, r, s_prime, t) for ((s, a), (r, s_prime, t)) in random.sample(self.buffer.items(), n_items)]
return sample
def save(self, filename):
"""
Save the model in a serialized file
:param filename: string, path to file where store the model
>>> # Load
>>> model_path = '/tmp/model/test_er.json'
>>> test_model = ExperienceReplay().load(filename=model_path)
>>> # Save
>>> test_model.save(filename=model_path)
"""
buf = [{"state": k, "value": v} for (k, v) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(b["state"], b["value"])
for b in json_res["buffer"]])
return self
def __len__(self):
return len(self.buffer)
class ExperienceReplayEligibility(ExperienceReplay):
def __init__(self, max_items=5000):
ExperienceReplay.__init__(self, max_items=max_items)
def add_state_e(self, state, value, e):
# Overwrite existing value if the state is already stored
self.buffer[state] = (value, e)
if len(self.buffer) > self.max_items:
# Forget the min value
pop_item = min(self.buffer.items(), key=lambda i: i[1][0])
# Forget a random value
#pop_item = random.choice(self.buffer.items())
self.buffer.pop(pop_item[0])
def save(self, filename):
buf = [{"key": k, "value": v, "eligibility": list(e)}
for (k, (v, e)) in self.buffer.items()]
json_res = {"max_items": self.max_items, "buffer": buf}
success = save_dict_as_json(json_res, filename=filename, pretty_print=True)
return success
def load(self, filename):
json_res = load_json_as_dict(filename)
# TODO: validate json loaded
self.max_items = json_res["max_items"]
self.buffer = dict([(tuple(b["key"]), (b["value"], np.asarray(b["eligibility"])))
for b in json_res["buffer"]])
return self | 0.474388 | 0.206134 |
from copy import deepcopy
from scan.test.fetch.kube_fetch.test_data.kube_access import BASE_RESPONSE
VSERVICES_FOLDER_DOC = {
"_id": "5aaf8369c6ad1791934c9a15",
"environment": "kube-aci",
"id": "b5fee42e-1b31-11e8-9d88-00505699cf9e-vservices",
"type": "vservices_folder",
"parent_type": "namespace",
"name": "Vservices",
"id_path": "/kube-aci/kube-aci-namespaces/b5fee42e-1b31-11e8-9d88-00505699cf9e/b5fee42e-1b31-11e8-9d88-00505699cf9e-vservices",
"name_path": "/kube-aci/Namespaces/default/Vservices",
"object_name": "Vservices",
"parent_id": "b5fee42e-1b31-11e8-9d88-00505699cf9e"
}
NAMESPACE_DOC = {
"_id": "5aaf8369c6ad1791934c9a03",
"environment": "kube-aci",
"id": "b5fee42e-1b31-11e8-9d88-00505699cf9e",
"type": "namespace",
"parent_type": "namespaces_folder",
"uid": "b5fee42e-1b31-11e8-9d88-00505699cf9e",
"name": "default",
"id_path": "/kube-aci/kube-aci-namespaces/b5fee42e-1b31-11e8-9d88-00505699cf9e",
"object_name": "default",
"self_link": "/api/v1/namespaces/default",
"name_path": "/kube-aci/Namespaces/default",
"parent_id": "kube-aci-namespaces"
}
VSERVICE_PODS = [
[
{'id': 'pod1', 'name': 'pod1'},
{'id': 'pod2', 'name': 'pod2'}
],
[]
]
EMPTY_RESPONSE = deepcopy(BASE_RESPONSE)
EMPTY_RESPONSE['kind'] = "ServiceList"
EMPTY_RESPONSE['metadata']['selfLink'] = "/api/v1/namespaces/{}/services".format(NAMESPACE_DOC['name'])
VSERVICES_RESPONSE = deepcopy(EMPTY_RESPONSE)
VSERVICES_RESPONSE['items'] = [
{
"metadata": {
"name": "cisco-portal-service",
"namespace": "default",
"selfLink": "/api/v1/namespaces/default/services/cisco-portal-service",
"uid": "16600875-1b34-11e8-9d88-00505699cf9e",
},
"spec": {
"ports": [
{
"protocol": "TCP",
"port": 8008,
"targetPort": 22,
"nodePort": 30679
}
],
"selector": {
"app": "cisco-web"
},
"clusterIP": "10.98.44.236",
"type": "NodePort",
"sessionAffinity": "None",
"externalTrafficPolicy": "Cluster"
}
},
{
"metadata": {
"name": "kubernetes",
"namespace": "default",
"selfLink": "/api/v1/namespaces/default/services/kubernetes",
"uid": "b861f17e-1b31-11e8-9d88-00505699cf9e",
"labels": {
"component": "apiserver",
"provider": "kubernetes"
}
},
"spec": {
"ports": [
{
"name": "https",
"protocol": "TCP",
"port": 443,
"targetPort": 6443
}
],
"clusterIP": "10.96.0.1",
"type": "ClusterIP",
"sessionAffinity": "ClientIP",
"sessionAffinityConfig": {
"clientIP": {
"timeoutSeconds": 10800
}
}
}
}
]
EXPECTED_VSERVICES = [
{
'id': vs['metadata']['uid'],
'type': 'vservice',
'name': vs['metadata']['name'],
'namespace': vs['metadata']['namespace'],
'pods': VSERVICE_PODS[i],
} for i, vs in enumerate(VSERVICES_RESPONSE['items'])
] | scan/test/fetch/kube_fetch/test_data/kube_fetch_vservices.py | from copy import deepcopy
from scan.test.fetch.kube_fetch.test_data.kube_access import BASE_RESPONSE
VSERVICES_FOLDER_DOC = {
"_id": "5aaf8369c6ad1791934c9a15",
"environment": "kube-aci",
"id": "b5fee42e-1b31-11e8-9d88-00505699cf9e-vservices",
"type": "vservices_folder",
"parent_type": "namespace",
"name": "Vservices",
"id_path": "/kube-aci/kube-aci-namespaces/b5fee42e-1b31-11e8-9d88-00505699cf9e/b5fee42e-1b31-11e8-9d88-00505699cf9e-vservices",
"name_path": "/kube-aci/Namespaces/default/Vservices",
"object_name": "Vservices",
"parent_id": "b5fee42e-1b31-11e8-9d88-00505699cf9e"
}
NAMESPACE_DOC = {
"_id": "5aaf8369c6ad1791934c9a03",
"environment": "kube-aci",
"id": "b5fee42e-1b31-11e8-9d88-00505699cf9e",
"type": "namespace",
"parent_type": "namespaces_folder",
"uid": "b5fee42e-1b31-11e8-9d88-00505699cf9e",
"name": "default",
"id_path": "/kube-aci/kube-aci-namespaces/b5fee42e-1b31-11e8-9d88-00505699cf9e",
"object_name": "default",
"self_link": "/api/v1/namespaces/default",
"name_path": "/kube-aci/Namespaces/default",
"parent_id": "kube-aci-namespaces"
}
VSERVICE_PODS = [
[
{'id': 'pod1', 'name': 'pod1'},
{'id': 'pod2', 'name': 'pod2'}
],
[]
]
EMPTY_RESPONSE = deepcopy(BASE_RESPONSE)
EMPTY_RESPONSE['kind'] = "ServiceList"
EMPTY_RESPONSE['metadata']['selfLink'] = "/api/v1/namespaces/{}/services".format(NAMESPACE_DOC['name'])
VSERVICES_RESPONSE = deepcopy(EMPTY_RESPONSE)
VSERVICES_RESPONSE['items'] = [
{
"metadata": {
"name": "cisco-portal-service",
"namespace": "default",
"selfLink": "/api/v1/namespaces/default/services/cisco-portal-service",
"uid": "16600875-1b34-11e8-9d88-00505699cf9e",
},
"spec": {
"ports": [
{
"protocol": "TCP",
"port": 8008,
"targetPort": 22,
"nodePort": 30679
}
],
"selector": {
"app": "cisco-web"
},
"clusterIP": "10.98.44.236",
"type": "NodePort",
"sessionAffinity": "None",
"externalTrafficPolicy": "Cluster"
}
},
{
"metadata": {
"name": "kubernetes",
"namespace": "default",
"selfLink": "/api/v1/namespaces/default/services/kubernetes",
"uid": "b861f17e-1b31-11e8-9d88-00505699cf9e",
"labels": {
"component": "apiserver",
"provider": "kubernetes"
}
},
"spec": {
"ports": [
{
"name": "https",
"protocol": "TCP",
"port": 443,
"targetPort": 6443
}
],
"clusterIP": "10.96.0.1",
"type": "ClusterIP",
"sessionAffinity": "ClientIP",
"sessionAffinityConfig": {
"clientIP": {
"timeoutSeconds": 10800
}
}
}
}
]
EXPECTED_VSERVICES = [
{
'id': vs['metadata']['uid'],
'type': 'vservice',
'name': vs['metadata']['name'],
'namespace': vs['metadata']['namespace'],
'pods': VSERVICE_PODS[i],
} for i, vs in enumerate(VSERVICES_RESPONSE['items'])
] | 0.385028 | 0.289409 |
import numpy as np
import torch
import os, time, sys
from os.path import join as pjoin
from PIL import Image
import argparse
from torch.utils.data import DataLoader
from torchvision.transforms import ToPILImage
import models
from utils import convert_state_dict, Logger
from dataset.dataset import VOC12
def main(args):
# ========= Setup device and seed ============
np.random.seed(42)
torch.manual_seed(42)
if args.cuda:
torch.cuda.manual_seed_all(42)
device = 'cuda' if args.cuda else 'cpu'
logger = Logger(pjoin(args.save_dir, args.model, 'test.log'))
logger.write(f'\nTesting configs: {args}')
# ================= Load processed data ===================
val_dataset = VOC12(args.data_dir, img_size=args.img_size, split='test')
val_loader = DataLoader(val_dataset, num_workers=8, batch_size=1)
n_classes = val_dataset.n_classes
# ================= Init model ====================
model = models.get_model(name=args.model, n_classes=n_classes)
model = model.to(device)
state = convert_state_dict(torch.load(args.model_path)["model_state"])
model.load_state_dict(state)
model.eval()
# ====================== Only one image ==========================
if args.eval:
with torch.no_grad():
img = Image.open(args.img_path)
origin = img.size
if args.img_size:
img = img.resize((val_dataset.img_size[0], val_dataset.img_size[1]))
img = val_dataset.input_transform(img).unsqueeze(0).to(device)
out = model(img)
pred = np.squeeze(out.data.max(1)[1].cpu().numpy(), axis=0)
decoded = val_dataset.decode_segmap(pred)
img_out = ToPILImage()(decoded).resize(origin)
img_out.save(pjoin(args.save_dir, args.model, f'eval_{args.img_size}.png'))
return
# ====================== Testing Many images ==============================
with torch.no_grad():
for idx, (name, img) in enumerate(val_loader):
img = img.to(device)
out = model(img)
pred = out.data.max(1)[1].squeeze_(1).squeeze_(0).cpu().numpy()
decoded = val_dataset.decode_segmap(pred)
ToPILImage()(decoded).save(pjoin(args.save_dir, args.model, f'{name[0]}_{args.img_size}.png'))
if __name__ == '__main__':
parser = argparse.ArgumentParser('Image Segmentation')
parser.add_argument('--cuda', action='store_true')
parser.add_argument('--model', type=str, default='fcn8')
parser.add_argument('--data-dir', type=str, default='/home/jinHM/sunjiahui/MachineLearning/dataset/VOCdevkit')
parser.add_argument('--eval', action='store_true')
parser.add_argument('--model-path', type=str, default='./saved')
parser.add_argument('--img-path', type=str, default='./visual/2007_000129.jpg')
parser.add_argument('--save-dir', type=str, default='./saved')
parser.add_argument('--img-size', type=int, default=256)
args = parser.parse_args()
main(args) | test.py | import numpy as np
import torch
import os, time, sys
from os.path import join as pjoin
from PIL import Image
import argparse
from torch.utils.data import DataLoader
from torchvision.transforms import ToPILImage
import models
from utils import convert_state_dict, Logger
from dataset.dataset import VOC12
def main(args):
# ========= Setup device and seed ============
np.random.seed(42)
torch.manual_seed(42)
if args.cuda:
torch.cuda.manual_seed_all(42)
device = 'cuda' if args.cuda else 'cpu'
logger = Logger(pjoin(args.save_dir, args.model, 'test.log'))
logger.write(f'\nTesting configs: {args}')
# ================= Load processed data ===================
val_dataset = VOC12(args.data_dir, img_size=args.img_size, split='test')
val_loader = DataLoader(val_dataset, num_workers=8, batch_size=1)
n_classes = val_dataset.n_classes
# ================= Init model ====================
model = models.get_model(name=args.model, n_classes=n_classes)
model = model.to(device)
state = convert_state_dict(torch.load(args.model_path)["model_state"])
model.load_state_dict(state)
model.eval()
# ====================== Only one image ==========================
if args.eval:
with torch.no_grad():
img = Image.open(args.img_path)
origin = img.size
if args.img_size:
img = img.resize((val_dataset.img_size[0], val_dataset.img_size[1]))
img = val_dataset.input_transform(img).unsqueeze(0).to(device)
out = model(img)
pred = np.squeeze(out.data.max(1)[1].cpu().numpy(), axis=0)
decoded = val_dataset.decode_segmap(pred)
img_out = ToPILImage()(decoded).resize(origin)
img_out.save(pjoin(args.save_dir, args.model, f'eval_{args.img_size}.png'))
return
# ====================== Testing Many images ==============================
with torch.no_grad():
for idx, (name, img) in enumerate(val_loader):
img = img.to(device)
out = model(img)
pred = out.data.max(1)[1].squeeze_(1).squeeze_(0).cpu().numpy()
decoded = val_dataset.decode_segmap(pred)
ToPILImage()(decoded).save(pjoin(args.save_dir, args.model, f'{name[0]}_{args.img_size}.png'))
if __name__ == '__main__':
parser = argparse.ArgumentParser('Image Segmentation')
parser.add_argument('--cuda', action='store_true')
parser.add_argument('--model', type=str, default='fcn8')
parser.add_argument('--data-dir', type=str, default='/home/jinHM/sunjiahui/MachineLearning/dataset/VOCdevkit')
parser.add_argument('--eval', action='store_true')
parser.add_argument('--model-path', type=str, default='./saved')
parser.add_argument('--img-path', type=str, default='./visual/2007_000129.jpg')
parser.add_argument('--save-dir', type=str, default='./saved')
parser.add_argument('--img-size', type=int, default=256)
args = parser.parse_args()
main(args) | 0.412648 | 0.235152 |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ne_base import NosDeviceAction
from pyswitch.device import Device
import sys
import pyswitch.utilities
class DeletePortChannel(NosDeviceAction):
"""
Implements the logic to delete port-channel configuration from all the member ports
on VDX and SLX devices .
This action achieves the below functionality
1.Delete a port channel
2.Verify whether the port-channel is really deleted
"""
def run(self, mgmt_ip, username, password, port_channel_id):
"""Run helper methods to implement the desired state.
"""
try:
self.setup_connection(host=mgmt_ip, user=username, passwd=password)
except Exception as e:
self.logger.error(e.message)
sys.exit(-1)
changes = {}
with Device(conn=self.conn, auth_snmp=self.auth_snmp) as device:
self.logger.info('successfully connected to %s to delete l2 port channel',
self.host)
valid_po, reason = pyswitch.utilities.validate_port_channel_id(device.platform_type,
port_channel_id)
if not valid_po:
self.logger.error(reason)
sys.exit(-1)
changes['port_channel_configs'] = self._delete_l2_port_channel(device,
portchannel_num=port_channel_id)
self.logger.info('closing connection to %s after'
' deleting l2 port channel -- all done!', self.host)
return changes
def _delete_l2_port_channel(self, device, portchannel_num):
""" Deleting the port channel configuration from all the member ports"""
is_po_present = True
try:
poChannel = device.interface.port_channels
for po in poChannel:
poNo = po['aggregator_id']
if poNo == str(portchannel_num):
self.logger.info('Deleting port channel %s', portchannel_num)
device.interface.remove_port_channel(port_int=str(portchannel_num))
is_po_present = False
except Exception as e:
error_message = str(e.message)
self.logger.error(error_message)
self.logger.error('Failed to get/delete port-channel %s', portchannel_num)
sys.exit(-1)
if not is_po_present:
return True
else:
self.logger.info('port-channel %s does not exist in the switch', portchannel_num)
return False | actions/delete_l2_port_channel.py |
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from ne_base import NosDeviceAction
from pyswitch.device import Device
import sys
import pyswitch.utilities
class DeletePortChannel(NosDeviceAction):
"""
Implements the logic to delete port-channel configuration from all the member ports
on VDX and SLX devices .
This action achieves the below functionality
1.Delete a port channel
2.Verify whether the port-channel is really deleted
"""
def run(self, mgmt_ip, username, password, port_channel_id):
"""Run helper methods to implement the desired state.
"""
try:
self.setup_connection(host=mgmt_ip, user=username, passwd=password)
except Exception as e:
self.logger.error(e.message)
sys.exit(-1)
changes = {}
with Device(conn=self.conn, auth_snmp=self.auth_snmp) as device:
self.logger.info('successfully connected to %s to delete l2 port channel',
self.host)
valid_po, reason = pyswitch.utilities.validate_port_channel_id(device.platform_type,
port_channel_id)
if not valid_po:
self.logger.error(reason)
sys.exit(-1)
changes['port_channel_configs'] = self._delete_l2_port_channel(device,
portchannel_num=port_channel_id)
self.logger.info('closing connection to %s after'
' deleting l2 port channel -- all done!', self.host)
return changes
def _delete_l2_port_channel(self, device, portchannel_num):
""" Deleting the port channel configuration from all the member ports"""
is_po_present = True
try:
poChannel = device.interface.port_channels
for po in poChannel:
poNo = po['aggregator_id']
if poNo == str(portchannel_num):
self.logger.info('Deleting port channel %s', portchannel_num)
device.interface.remove_port_channel(port_int=str(portchannel_num))
is_po_present = False
except Exception as e:
error_message = str(e.message)
self.logger.error(error_message)
self.logger.error('Failed to get/delete port-channel %s', portchannel_num)
sys.exit(-1)
if not is_po_present:
return True
else:
self.logger.info('port-channel %s does not exist in the switch', portchannel_num)
return False | 0.739046 | 0.21099 |
import json
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView, ListView, UpdateView
from djofx import models
from djofx.forms import CategoriseTransactionForm, CategoryForm
from djofx.utils import qs_to_monthly_report
from djofx.views.base import PageTitleMixin, UserRequiredMixin
class CategoryTransactionsView(PageTitleMixin, UserRequiredMixin, ListView):
model = models.Transaction
paginate_by = 50
def get_template_names(self):
if not self.request.is_ajax():
return ['djofx/category.html', ]
else:
return ['djofx/_transaction_list.html', ]
def get_context_data(self, **kwargs):
ctx = super(CategoryTransactionsView, self).get_context_data(**kwargs)
category = self.get_category()
ctx['category'] = category
ctx['categorise_form'] = CategoriseTransactionForm()
qs = models.Transaction.objects.filter(
transaction_category=category
)
report = qs_to_monthly_report(qs, category.category_type)
ctx['month_breakdown'] = json.dumps(report)
return ctx
def get_category(self):
return models.TransactionCategory.objects.get(
owner=self.request.user,
pk=self.kwargs['pk']
)
def get_queryset(self):
qs = super(CategoryTransactionsView, self).get_queryset()
qs = qs.filter(
transaction_category=self.get_category()
)
return qs
def get_page_title(self):
object = self.get_category()
return 'Category (%s)' % object.name
class CategoryListView(PageTitleMixin, UserRequiredMixin, ListView):
model = models.TransactionCategory
paginate_by = 50
template_name = 'djofx/categories.html'
page_title = 'Transaction Categories'
def get_queryset(self):
qs = super(CategoryListView, self).get_queryset()
return qs.filter(owner=self.request.user)
class AddCategoryView(PageTitleMixin, UserRequiredMixin, FormView):
form_class = CategoryForm
template_name = "djofx/add_category.html"
page_title = "Add category"
success_url = reverse_lazy('djofx_home')
def form_valid(self, form):
category = form.save(commit=False)
category.owner = self.request.user
category.save()
messages.success(
self.request,
'Payment category saved.'
)
return super(AddCategoryView, self).form_valid(form)
class UpdateCategoryView(PageTitleMixin, UserRequiredMixin, UpdateView):
model = models.TransactionCategory
form_class = CategoryForm
template_name = "djofx/edit_category.html"
page_title = "Edit category"
success_url = reverse_lazy('djofx_categories')
def form_valid(self, form):
messages.success(
self.request,
'Payment category saved.'
)
return super(UpdateCategoryView, self).form_valid(form) | djofx/views/category.py | import json
from django.contrib import messages
from django.core.urlresolvers import reverse_lazy
from django.views.generic import FormView, ListView, UpdateView
from djofx import models
from djofx.forms import CategoriseTransactionForm, CategoryForm
from djofx.utils import qs_to_monthly_report
from djofx.views.base import PageTitleMixin, UserRequiredMixin
class CategoryTransactionsView(PageTitleMixin, UserRequiredMixin, ListView):
model = models.Transaction
paginate_by = 50
def get_template_names(self):
if not self.request.is_ajax():
return ['djofx/category.html', ]
else:
return ['djofx/_transaction_list.html', ]
def get_context_data(self, **kwargs):
ctx = super(CategoryTransactionsView, self).get_context_data(**kwargs)
category = self.get_category()
ctx['category'] = category
ctx['categorise_form'] = CategoriseTransactionForm()
qs = models.Transaction.objects.filter(
transaction_category=category
)
report = qs_to_monthly_report(qs, category.category_type)
ctx['month_breakdown'] = json.dumps(report)
return ctx
def get_category(self):
return models.TransactionCategory.objects.get(
owner=self.request.user,
pk=self.kwargs['pk']
)
def get_queryset(self):
qs = super(CategoryTransactionsView, self).get_queryset()
qs = qs.filter(
transaction_category=self.get_category()
)
return qs
def get_page_title(self):
object = self.get_category()
return 'Category (%s)' % object.name
class CategoryListView(PageTitleMixin, UserRequiredMixin, ListView):
model = models.TransactionCategory
paginate_by = 50
template_name = 'djofx/categories.html'
page_title = 'Transaction Categories'
def get_queryset(self):
qs = super(CategoryListView, self).get_queryset()
return qs.filter(owner=self.request.user)
class AddCategoryView(PageTitleMixin, UserRequiredMixin, FormView):
form_class = CategoryForm
template_name = "djofx/add_category.html"
page_title = "Add category"
success_url = reverse_lazy('djofx_home')
def form_valid(self, form):
category = form.save(commit=False)
category.owner = self.request.user
category.save()
messages.success(
self.request,
'Payment category saved.'
)
return super(AddCategoryView, self).form_valid(form)
class UpdateCategoryView(PageTitleMixin, UserRequiredMixin, UpdateView):
model = models.TransactionCategory
form_class = CategoryForm
template_name = "djofx/edit_category.html"
page_title = "Edit category"
success_url = reverse_lazy('djofx_categories')
def form_valid(self, form):
messages.success(
self.request,
'Payment category saved.'
)
return super(UpdateCategoryView, self).form_valid(form) | 0.478041 | 0.129155 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import interpolate
import time
start_time = time.time()
data_matrix = np.array(pd.read_csv('SUSY.csv'))
X = data_matrix[:,1:]
Y = data_matrix[:,0]
Y[Y==0.0] = -1.0
nrows, ncols = X.shape[0], X.shape[1]
training_percent = 70
print "\n\n Creating training set ...\n"
X_train = X[:int(training_percent*nrows/100),:]
Y_train = Y[:int(training_percent*nrows/100)]
print "\n Training set created ...\n"
nrows_train, ncols_train = X_train.shape[0], X_train.shape[1]
print "\n\n Creating test set ...\n"
X_test = X[int(training_percent*nrows/100):,:]
Y_test = Y[int(training_percent*nrows/100):]
print "\n Test set created ...\n"
nrows_test, ncols_test = X_test.shape[0], X_test.shape[1]
w = np.zeros(ncols_train)
regularizer = 0.00001
Y_pred = np.dot(X_train, w)
error = float(np.logical_xor((Y_pred > 0).astype(int), (Y_train.astype(int) > 0).astype(int)).sum())/float(nrows_train)
count = 1
total_iterations = 1000
error_list = [error]
count_list = [count]
for t in range(total_iterations):
i = np.random.randint(0, nrows_train, 1)[0]
decision = np.dot(X_train[i,:], w)*Y_train[i]
if decision >= 1:
w_new = np.add(w, 0)
elif decision < 1:
w_new = np.add(w, np.divide(np.multiply(X_train[i],Y_train[i]), np.sqrt(count)))
w_new = np.multiply(w_new, min(1, 1/(np.linalg.norm(w_new)*np.sqrt(regularizer))))
w = w_new
count = count + 1
Y_pred = np.dot(X_test, w)
error = float(np.logical_xor((Y_pred > 0).astype(int), (Y_test.astype(int) > 0).astype(int)).sum())/float(nrows_test)
error_list.append(error)
count_list.append(count)
plt.title('Variation of accuracy in prediction with increasing iterations \n')
plt.xlabel('Iteration number')
plt.ylabel('Test error')
plt.plot(count_list, error_list, color = '#7fffd4')
tck1 = interpolate.splrep(count_list, error_list, k = 3, s = 900)
error_list_int = interpolate.splev(count_list, tck1, der = 0)
plt.plot(count_list, error_list_int, color = 'magenta', label = 'Stochastic Gradient Descent')
plt.legend()
plt.show()
end_time = time.time() - start_time
print "\n\nPercentage accuracy = " + str(100 - error_list[-1] * 100) + "%\n"
print "\nTime taken = " + str(end_time) + " seconds\n" | main.py | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from scipy import interpolate
import time
start_time = time.time()
data_matrix = np.array(pd.read_csv('SUSY.csv'))
X = data_matrix[:,1:]
Y = data_matrix[:,0]
Y[Y==0.0] = -1.0
nrows, ncols = X.shape[0], X.shape[1]
training_percent = 70
print "\n\n Creating training set ...\n"
X_train = X[:int(training_percent*nrows/100),:]
Y_train = Y[:int(training_percent*nrows/100)]
print "\n Training set created ...\n"
nrows_train, ncols_train = X_train.shape[0], X_train.shape[1]
print "\n\n Creating test set ...\n"
X_test = X[int(training_percent*nrows/100):,:]
Y_test = Y[int(training_percent*nrows/100):]
print "\n Test set created ...\n"
nrows_test, ncols_test = X_test.shape[0], X_test.shape[1]
w = np.zeros(ncols_train)
regularizer = 0.00001
Y_pred = np.dot(X_train, w)
error = float(np.logical_xor((Y_pred > 0).astype(int), (Y_train.astype(int) > 0).astype(int)).sum())/float(nrows_train)
count = 1
total_iterations = 1000
error_list = [error]
count_list = [count]
for t in range(total_iterations):
i = np.random.randint(0, nrows_train, 1)[0]
decision = np.dot(X_train[i,:], w)*Y_train[i]
if decision >= 1:
w_new = np.add(w, 0)
elif decision < 1:
w_new = np.add(w, np.divide(np.multiply(X_train[i],Y_train[i]), np.sqrt(count)))
w_new = np.multiply(w_new, min(1, 1/(np.linalg.norm(w_new)*np.sqrt(regularizer))))
w = w_new
count = count + 1
Y_pred = np.dot(X_test, w)
error = float(np.logical_xor((Y_pred > 0).astype(int), (Y_test.astype(int) > 0).astype(int)).sum())/float(nrows_test)
error_list.append(error)
count_list.append(count)
plt.title('Variation of accuracy in prediction with increasing iterations \n')
plt.xlabel('Iteration number')
plt.ylabel('Test error')
plt.plot(count_list, error_list, color = '#7fffd4')
tck1 = interpolate.splrep(count_list, error_list, k = 3, s = 900)
error_list_int = interpolate.splev(count_list, tck1, der = 0)
plt.plot(count_list, error_list_int, color = 'magenta', label = 'Stochastic Gradient Descent')
plt.legend()
plt.show()
end_time = time.time() - start_time
print "\n\nPercentage accuracy = " + str(100 - error_list[-1] * 100) + "%\n"
print "\nTime taken = " + str(end_time) + " seconds\n" | 0.303938 | 0.416797 |
from typing import Iterable, Tuple, Optional
import torch
import numpy as np
from tqdm import tqdm
import sys
sys.path.append('..')
from ltss.utils import read_records_csv, reshape_vector, flatten_vector
from ltss.vectorise import vectorise_record
class DataHandler(object):
"""
Contains logic for loading data from the provided NHS CSV, filtering out non-major cases, and vectorising the
resulting records for training (depending heavily on the parsing and vectorising logic in the `ltss` module).
Additionally contains logic for consistently sampling the training and test splits.
"""
def __init__(self, filename: str, max_samples=None, filter_minor=True, max_los_clip=30,
shuffle=False, fixed_seed=None, train_proportion=0.8, reshape=False, use_tqdm=True,
device: torch.device = torch.device('cpu')):
self.device = device
self.train_proportion = train_proportion
self.max_samples = max_samples
self.shuffle = shuffle
self.fixed_seed = fixed_seed
self.filter_minor = filter_minor
self.max_los_clip = max_los_clip
self.reshape = reshape
# Build a random instance for this handler - if methods are called in the same order, this behaviour will give
# consistent sampling throughout the lifetime of the handler
if self.fixed_seed is not None:
np.random.seed(self.fixed_seed)
# Stream the records from CSV, vectorise, and store in a stack
data, los = zip(*self.__stream_records(filename, use_tqdm, filter_minor, max_los_clip, max_samples, reshape))
# Stack data and los for storage
self.data = np.vstack(data)
self.los = np.vstack(los)
# Drop the extra dimension from the LoS array
self.los = self.los.reshape(-1)
# Carve data into train/test sets
training_indices, test_indices = self.__train_test_splits()
self.train_data = self.data[training_indices]
self.train_los = self.los[training_indices]
self.test_data = self.data[test_indices]
self.test_los = self.los[test_indices]
@staticmethod
def __stream_records(filename: str, use_tqdm: bool, filter_minor: bool, max_los_clip: Optional[int],
max_samples: Optional[int], reshape: bool) -> Iterable[Tuple[np.array, int]]:
"""
Stream records off disk, vectorise them, and optionally filter out "minor" records from the data
:param filename: The filename of raw CSV data to parse
:param use_tqdm: If true, display TQDM progress info (useful when there is a lot of data to load and vectorise)
:param filter_minor: If true, discard entries for the IS_MAJOR is not true
:param max_los_clip: If non-none, clip the maximum LoS to this value
:param max_samples: If non-none, limit the number of records emitted
:param reshape: Whether to flatten and reshape the vector, or only flatten it (impacts output data shape)
:return: Generator of tuples of 8x8 feature vectors, and their ground-truth length of stay
"""
stream = read_records_csv(filename)
if use_tqdm:
stream = tqdm(stream, desc='Loading data', unit=' records')
emitted_samples = 0
for record in stream:
vector = vectorise_record(record)
los = vector['LENGTH_OF_STAY']
# Discard obviously bad data (negative LoS is impossible)
if los < 0:
continue
# Filter out "minor" records
if filter_minor and vector['IS_MAJOR'] != 1:
continue
# Clip LoS to a maximum value
if max_los_clip is not None:
los = min(los, max_los_clip)
if reshape:
yield reshape_vector(vector), los
else:
yield flatten_vector(vector), los
# Update stats
emitted_samples += 1
if use_tqdm:
stream.set_postfix_str(f'generated {emitted_samples} good records', refresh=False)
# If we've emitted enough samples, finish fast
if max_samples is not None and emitted_samples >= max_samples:
return
def __train_test_splits(self):
"""
Make reproducible train/test splits of the data. Optionally, shuffle (reproducibly, controlled by
`self.shuffle` and `self.fixed_seed`) the data for train/test.
:return:
"""
# By default, our indices are just 0-n
split_indices = list(range(len(self.data)))
# If shuffling, use our shared Random instance to shuffle our indices before slicing
if self.shuffle:
np.random.shuffle(split_indices)
# Regardless of shuffle, take the first self.train_proportion for training, and the last
# 1 - self.train_proportion records as test
train_n = int(self.train_proportion * len(self.data))
training_indices = split_indices[:train_n]
test_indices = split_indices[train_n:]
return training_indices, test_indices
def __sample(self, data, los, n: Optional[int], random: bool):
"""
Sample the given data/los distribution, selecting the given N and optionally randomising the sample.
:param data: Dataset of vectors to sample
:param los: Dataset of lengths of stay to sample
:param n: The number of samples to generate
:param random: When true, randomise samples
:return: Torch tensors for the sampled data and los distributions, moved to the relevant Torch device.
"""
if n is None:
n = len(data)
else:
n = min(len(data), n)
# Uniform random sampling from our data array
indices = list(range(len(data)))
if random:
np.random.shuffle(indices)
indices = indices[:n]
data = torch.Tensor(data[indices])
los = torch.Tensor(los[indices])
if self.device != 'cpu' and 'cuda' in self.device.type:
data = data.cuda()
los = los.cuda()
return data, los
def get_training_n(self, n: Optional[int] = None, random: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Sample n records from the training data, optionally at random
:param n: Number of samples to retrieve. Must be <= len(self.train_data)
:param random: When true, randomise the retrieved samples
:return: Tuple of training data and associated lengths of stay
"""
return self.__sample(self.train_data, self.train_los, n, random)
def get_validation(self, n: Optional[int] = None, random: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Sample n records from the test data, optionally at random
:param n: Number of samples to retrieve. Must be <= len(self.test_data)
:param random: When true, randomise the retrieved samples
:return: Tuple of test data and associated lengths of stay
"""
return self.__sample(self.test_data, self.test_los, n, random)
def __str__(self):
config = dict(
device=self.device,
train_proportion=self.train_proportion,
max_samples=self.max_samples,
shuffle=self.shuffle,
fixed_seed=self.fixed_seed,
filter_minor=self.filter_minor,
max_los_clip=self.max_los_clip,
reshape=self.reshape,
)
return f'DataHandler: {len(self.data)} records, with {len(self.train_data)} training and ' \
f'{len(self.test_data)} test records with configuration: ' \
f'{{{", ".join([f"{k}={v}" for k, v in sorted(config.items())])}}}' | training/loader.py | from typing import Iterable, Tuple, Optional
import torch
import numpy as np
from tqdm import tqdm
import sys
sys.path.append('..')
from ltss.utils import read_records_csv, reshape_vector, flatten_vector
from ltss.vectorise import vectorise_record
class DataHandler(object):
"""
Contains logic for loading data from the provided NHS CSV, filtering out non-major cases, and vectorising the
resulting records for training (depending heavily on the parsing and vectorising logic in the `ltss` module).
Additionally contains logic for consistently sampling the training and test splits.
"""
def __init__(self, filename: str, max_samples=None, filter_minor=True, max_los_clip=30,
shuffle=False, fixed_seed=None, train_proportion=0.8, reshape=False, use_tqdm=True,
device: torch.device = torch.device('cpu')):
self.device = device
self.train_proportion = train_proportion
self.max_samples = max_samples
self.shuffle = shuffle
self.fixed_seed = fixed_seed
self.filter_minor = filter_minor
self.max_los_clip = max_los_clip
self.reshape = reshape
# Build a random instance for this handler - if methods are called in the same order, this behaviour will give
# consistent sampling throughout the lifetime of the handler
if self.fixed_seed is not None:
np.random.seed(self.fixed_seed)
# Stream the records from CSV, vectorise, and store in a stack
data, los = zip(*self.__stream_records(filename, use_tqdm, filter_minor, max_los_clip, max_samples, reshape))
# Stack data and los for storage
self.data = np.vstack(data)
self.los = np.vstack(los)
# Drop the extra dimension from the LoS array
self.los = self.los.reshape(-1)
# Carve data into train/test sets
training_indices, test_indices = self.__train_test_splits()
self.train_data = self.data[training_indices]
self.train_los = self.los[training_indices]
self.test_data = self.data[test_indices]
self.test_los = self.los[test_indices]
@staticmethod
def __stream_records(filename: str, use_tqdm: bool, filter_minor: bool, max_los_clip: Optional[int],
max_samples: Optional[int], reshape: bool) -> Iterable[Tuple[np.array, int]]:
"""
Stream records off disk, vectorise them, and optionally filter out "minor" records from the data
:param filename: The filename of raw CSV data to parse
:param use_tqdm: If true, display TQDM progress info (useful when there is a lot of data to load and vectorise)
:param filter_minor: If true, discard entries for the IS_MAJOR is not true
:param max_los_clip: If non-none, clip the maximum LoS to this value
:param max_samples: If non-none, limit the number of records emitted
:param reshape: Whether to flatten and reshape the vector, or only flatten it (impacts output data shape)
:return: Generator of tuples of 8x8 feature vectors, and their ground-truth length of stay
"""
stream = read_records_csv(filename)
if use_tqdm:
stream = tqdm(stream, desc='Loading data', unit=' records')
emitted_samples = 0
for record in stream:
vector = vectorise_record(record)
los = vector['LENGTH_OF_STAY']
# Discard obviously bad data (negative LoS is impossible)
if los < 0:
continue
# Filter out "minor" records
if filter_minor and vector['IS_MAJOR'] != 1:
continue
# Clip LoS to a maximum value
if max_los_clip is not None:
los = min(los, max_los_clip)
if reshape:
yield reshape_vector(vector), los
else:
yield flatten_vector(vector), los
# Update stats
emitted_samples += 1
if use_tqdm:
stream.set_postfix_str(f'generated {emitted_samples} good records', refresh=False)
# If we've emitted enough samples, finish fast
if max_samples is not None and emitted_samples >= max_samples:
return
def __train_test_splits(self):
"""
Make reproducible train/test splits of the data. Optionally, shuffle (reproducibly, controlled by
`self.shuffle` and `self.fixed_seed`) the data for train/test.
:return:
"""
# By default, our indices are just 0-n
split_indices = list(range(len(self.data)))
# If shuffling, use our shared Random instance to shuffle our indices before slicing
if self.shuffle:
np.random.shuffle(split_indices)
# Regardless of shuffle, take the first self.train_proportion for training, and the last
# 1 - self.train_proportion records as test
train_n = int(self.train_proportion * len(self.data))
training_indices = split_indices[:train_n]
test_indices = split_indices[train_n:]
return training_indices, test_indices
def __sample(self, data, los, n: Optional[int], random: bool):
"""
Sample the given data/los distribution, selecting the given N and optionally randomising the sample.
:param data: Dataset of vectors to sample
:param los: Dataset of lengths of stay to sample
:param n: The number of samples to generate
:param random: When true, randomise samples
:return: Torch tensors for the sampled data and los distributions, moved to the relevant Torch device.
"""
if n is None:
n = len(data)
else:
n = min(len(data), n)
# Uniform random sampling from our data array
indices = list(range(len(data)))
if random:
np.random.shuffle(indices)
indices = indices[:n]
data = torch.Tensor(data[indices])
los = torch.Tensor(los[indices])
if self.device != 'cpu' and 'cuda' in self.device.type:
data = data.cuda()
los = los.cuda()
return data, los
def get_training_n(self, n: Optional[int] = None, random: bool = True) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Sample n records from the training data, optionally at random
:param n: Number of samples to retrieve. Must be <= len(self.train_data)
:param random: When true, randomise the retrieved samples
:return: Tuple of training data and associated lengths of stay
"""
return self.__sample(self.train_data, self.train_los, n, random)
def get_validation(self, n: Optional[int] = None, random: bool = False) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Sample n records from the test data, optionally at random
:param n: Number of samples to retrieve. Must be <= len(self.test_data)
:param random: When true, randomise the retrieved samples
:return: Tuple of test data and associated lengths of stay
"""
return self.__sample(self.test_data, self.test_los, n, random)
def __str__(self):
config = dict(
device=self.device,
train_proportion=self.train_proportion,
max_samples=self.max_samples,
shuffle=self.shuffle,
fixed_seed=self.fixed_seed,
filter_minor=self.filter_minor,
max_los_clip=self.max_los_clip,
reshape=self.reshape,
)
return f'DataHandler: {len(self.data)} records, with {len(self.train_data)} training and ' \
f'{len(self.test_data)} test records with configuration: ' \
f'{{{", ".join([f"{k}={v}" for k, v in sorted(config.items())])}}}' | 0.864282 | 0.606498 |
from posixpath import expanduser
from typing import Dict
from lpulive.lpulive_urls import (GET_CAHAT_MEMBERS_URL, GET_CONVRSATION_URL, GET_MESSAGES_THREADS_URL,
GET_MESSAGES_URL, GET_WORKSPACE_DETAIL_URL,
LOGIN_URL, LOGIN_VIA_TOKEN_URL, SEARCH_URL,
SWITCH_WORKSPACE_URL)
import requests
import os
import pickle
import json
# -------- Main User class ------
class User:
def __init__(self, registration_no, password) -> None:
self.__REGNO = str(registration_no)
self.__PASSWORD = str(password)
self.__DATA_PATH = f"data_{self.__REGNO}.pkl"
self.__LOGIN_SUCCESS = False
self.__DATA_FILE = {}
self.__HEADERS = {
"user-agent": "Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0",
"app_version": "1.0.0",
"device_type": "WEB"}
self.__DEVICE_DETAILS = json.dumps(
{"browser-agent": str(self.__HEADERS['user-agent'])})
self.__check_stored_data(self.__DATA_PATH)
self.__WORKSPACE_ID = self.__DATA_FILE["workspace_id"] if self.__LOGIN_SUCCESS else None
self.__USER_SESSION = self.__DATA_FILE["user_session"] if self.__LOGIN_SUCCESS else None
self.__EN_USER_ID = self.__DATA_FILE["en_user_id"] if self.__LOGIN_SUCCESS else None
self.__ACCESS_TOKEN = self.__DATA_FILE["access_token"] if self.__LOGIN_SUCCESS else None
self.__LPU_ACCESS_TOKEN = self.__DATA_FILE["lpu_access_token"] if self.__LOGIN_SUCCESS else None
def __set_pickle_container(self, data_obj, data_path):
with open(data_path, "wb") as pkl:
pickle.dump(data_obj, pkl, pickle.HIGHEST_PROTOCOL)
def __get_pickle_container(self, data_path):
with open(data_path, "rb") as pkl:
return pickle.load(pkl)
def __check_stored_data(self, file_path) -> None:
if not os.path.isfile(file_path):
self.__login()
if self.__LOGIN_SUCCESS:
self.__DATA_FILE = self.__get_pickle_container(file_path)
else:
self.__DATA_FILE = self.__get_pickle_container(file_path)
self.__LOGIN_SUCCESS = True
if self.__REGNO != self.__DATA_FILE["regno"] or self.__DATA_FILE["password"] != self.__PASSWORD:
self.__login()
if self.__LOGIN_SUCCESS:
self.__DATA_FILE = self.__get_pickle_container(file_path)
else:
self.__DATA_FILE = {}
self.__set_pickle_container({}, file_path)
# login function
def __login(self) -> None:
self.__USER_SESSION = requests.session()
json_data = {
"password": <PASSWORD>.__PASSWORD,
"username": self.__REGNO,
"domain": "lpu.in",
"time_zone": 330
}
login_response = self.__USER_SESSION.post(
url=LOGIN_URL, json=json_data, headers=self.__HEADERS)
if login_response.status_code == 200:
return_data = {}
login_response_data = login_response.json()
self.__WORKSPACE_ID = login_response_data["data"]["workspaces_info"][0]["workspace_id"]
self.__ACCESS_TOKEN = login_response_data["data"]["user_info"]["access_token"]
self.__LPU_ACCESS_TOKEN = login_response_data["data"]["user_info"]["lpu_access_token"]
self.__EN_USER_ID = login_response_data["data"]["workspaces_info"][0]["en_user_id"]
return_data = {
"workspace_id": self.__WORKSPACE_ID,
"access_token": self.__ACCESS_TOKEN,
"lpu_access_token": self.__LPU_ACCESS_TOKEN,
"en_user_id": self.__EN_USER_ID,
"user_session": self.__USER_SESSION,
"password": self.__PASSWORD,
"regno": self.__REGNO
}
self.__LOGIN_SUCCESS = True
self.__set_pickle_container(return_data, self.__DATA_PATH)
self.__switch_workspace()
else:
self.__LOGIN_SUCCESS = False
def __switch_workspace(self):
sw_data = {
"workspace_id": self.__WORKSPACE_ID,
"access_token": self.__ACCESS_TOKEN,
"device_details": json.dumps({"browser-agent": str(self.__HEADERS['user-agent'])}),
"device_id": "random_text"
}
sw_response = self.__USER_SESSION.post(
url=SWITCH_WORKSPACE_URL, json=sw_data, headers=self.__HEADERS)
if sw_response.status_code == 200:
self.__login_via_token()
def __login_via_token(self):
lvt_data = {
"token": self.__ACCESS_TOKEN,
"domain": "lpu.in",
"lpu_access_token": self.__LPU_ACCESS_TOKEN,
"time_zone": 330
}
lvt_headers = {"access_token": self.__ACCESS_TOKEN}
lvt_headers.update(self.__HEADERS)
self.__USER_SESSION.post(
url=LOGIN_VIA_TOKEN_URL, json=lvt_data, headers=lvt_headers)
def __get_workpace_details(self):
gwsd_data = f"workspace=spaces&domain=lpu.in&device_id=random_text&device_details={self.__DEVICE_DETAILS}"
self.__USER_SESSION.get(
url=f"{GET_WORKSPACE_DETAIL_URL}?{gwsd_data}", headers=self.__HEADERS)
def __get_conversation_filter(self, data) -> list:
return_data = []
for single in data:
temp = {}
temp["id"] = single["channel_id"]
temp["chat_name"] = single["label"]
temp["date_time"] = single["date_time"]
temp["unread"] = single["unread_count"]
return_data.append(temp)
return return_data
def __get_conversations_func(self) -> dict:
if self.__LOGIN_SUCCESS:
gc_data = f"en_user_id={self.__EN_USER_ID}&page_start=1&device_id=random_text&device_details={self.__DEVICE_DETAILS}"
gc_responce = self.__USER_SESSION.get(
url=f"{GET_CONVRSATION_URL}?{gc_data}", headers=self.__HEADERS)
if gc_responce.status_code == 200:
temp_data = gc_responce.json()["data"]
total_chat = temp_data["count"]
filter_chat_list = self.__get_conversation_filter(
temp_data["conversation_list"])
final_data = {
"chats": filter_chat_list,
"total_chat": total_chat,
}
return final_data
else:
error_data = {
"message": "fail to fetch data"
}
return error_data
else:
return self.login_fail_message(type="dict")
def __get_message_threads_func(self, chat_id, msg_id) -> list:
if self.__LOGIN_SUCCESS:
return_data = []
gmt_data = f"muid={msg_id}&en_user_id={self.__EN_USER_ID}&channel_id={chat_id}"
gmt_responce = self.__USER_SESSION.get(
url=f"{GET_MESSAGES_THREADS_URL}?{gmt_data}", headers=self.__HEADERS)
if gmt_responce.status_code == 200:
temp_data = gmt_responce.json()["data"]["thread_message"]
for single in temp_data:
temp = {
"from_user": single["full_name"].split(":")[0].strip(),
"regno": single["username"],
"message": single["message"],
"date": single["date_time"]
}
return_data.append(temp)
return return_data
else:
return ["Fail to load thread, please check m_id"]
else:
return self.login_fail_message(type="list")
def __get_messages_filter(self, data, chat_id, msg_thread=False) -> list:
return_data = []
for ind, single in enumerate(data[::-1]):
temp = {
"id": ind+1,
"m_id": single["muid"],
"message": single["message"],
"date": single["date_time"],
"from_user": single["full_name"].split(":")[0].strip(),
"regno": single["username"],
"attachment": False
}
if "url" in single:
temp["attachment"] = {
"file_name": single["file_name"],
"url": single["url"],
"file_size": single["file_size"],
"type": single["document_type"]
}
if msg_thread:
if single["thread_message_count"] > 0:
temp["thread"] = self.__get_message_threads_func(
chat_id, single["muid"])
else:
temp["thread"] = "No thread"
else:
temp["thread"] = single["thread_message_count"]
return_data.append(temp)
return return_data
def __get_messages_func(self, chat_id, msg_thread=False) -> dict:
if self.__LOGIN_SUCCESS:
gm_data = f"channel_id={chat_id}&en_user_id={self.__EN_USER_ID}&page_start=1&store_promise=true&device_id=random_text&device_details={self.__DEVICE_DETAILS}"
gm_responce = self.__USER_SESSION.get(
url=f"{GET_MESSAGES_URL}?{gm_data}", headers=self.__HEADERS)
if gm_responce.status_code == 200:
temp_data = gm_responce.json()["data"]
filtered_messages = self.__get_messages_filter(
temp_data["messages"], chat_id, msg_thread)
chat_name = temp_data["label"]
user_name = temp_data["full_name"]
total_messages = len(temp_data["messages"])
final_data = {
"chat_id": chat_id,
"messages": filtered_messages,
"chat_name": chat_name,
"total_messages": total_messages,
"user_name": user_name,
}
with open("lpulive/test/data.json", "w") as f:
json.dump(final_data, f)
return final_data
else:
error_data = {
"message": "fail to load messages, Please check chat_id"
}
return error_data
else:
return self.login_fail_message(type="dict")
def __get_chat_members_filter(self, data):
return_data = []
for single in data:
temp = {
"name": single["full_name"].split(":")[0].strip(),
"regno": single["email"],
"profile_img": single["user_image"],
"phone": single["contact_number"]
}
return_data.append(temp)
return return_data
def __get_chat_members_func(self, chat_id) -> dict:
if self.__LOGIN_SUCCESS:
def gcm_data_func(page):
gcm_data2 = {"channel_id": chat_id,
"en_user_id": self.__EN_USER_ID,
"get_data_type": "MEMBERS",
"user_page_start": page}
res = self.__USER_SESSION.get(
url=GET_CAHAT_MEMBERS_URL, json=gcm_data2, headers=self.__HEADERS)
if res.status_code == 200:
return res.json()["data"]["chat_members"]
else:
return None
return_data = []
for page in range(0, 5000, 51):
x = gcm_data_func(page=page)
if x == None:
return {"message": "Fail to fetch members, Please check chat_id"}
elif len(x) < 1:
break
else:
return_data += x
final_data = {
"chat_id": chat_id,
"members": self.__get_chat_members_filter(return_data),
"total_members": len(return_data)
}
return final_data
else:
return self.login_fail_message(type="dict")
def __search_user_filter(self, data):
return_data = []
for ind, single in enumerate(data):
temp = {
"id": ind+1,
"name": single["full_name"].split(":")[0].strip(),
"regno": single["email"],
"department": single["department"],
"profile_img": single["user_image"]
}
return_data.append(temp)
return return_data
def __search_user_func(self, user) -> dict:
if self.__LOGIN_SUCCESS:
if len(user) < 3:
return {"message": "Search Query must be atleast 2 character long"}
su_data = {
"en_user_id": self.__EN_USER_ID,
"search_text": user,
"user_role": "USER",
"search_deactivated_member": "true"
}
su_response = self.__USER_SESSION.get(
url=SEARCH_URL, json=su_data, headers=self.__HEADERS)
if su_response.status_code == 200:
data = su_response.json()["data"]["users"]
users = self.__search_user_filter(data)
return_data = {
"search_query": user,
"users": users,
"total_found": len(users)
}
return return_data
else:
return {"message": "fail to fetch, please try again later"}
else:
return self.login_fail_message(type="dict")
def login_fail_message(self, type="str"):
if type == "dict":
return {"message": "fail to login, check user details"}
elif type == "list":
return ["fail to login, check user details"]
else:
return "fail to login, check user details"
"""# ------------------------ USER AVAILABLE METHODS ------------------------------ #"""
# ----------GET CONVERSATION METHOD --------------
'''
- To get all the active chat
- function takes no argument
- function return a dictionary object
> chats : list of all the chat active on users profile
-> id : id of particular chat
-> chat_name : name of the chat
-> date_time : last acitve message on that chat
-> unread : total unread messages on that chat
> total_chat : total group/private chat active on users profiles
'''
def get_conversations(self) -> dict:
return self.__get_conversations_func()
# ---------GET MESSAGES METHOD ------------
'''
- To get all the messages of selected chat
- functions takes to argument chat_id, msg_thread
> chat_id : to select a particular chat to get all messages [ required argument ]
> msg_thread : to turn on thread, this will also include the threads of messages ( if appicable ) [ default value is False ]
- function return a dictionary object
> chat_id : id of the chat
> messages : list of all the messages in that chat
-> id : id number ( smaller the id newer the message )
-> m_id : message id
-> message : text message
-> from_user : message sender name
-> regno : message sender registration number
-> attachment : any attachment in that message ( if applicable )
-> thread_message : get all the thread of a particular message ( if msg_thread is True )
> chat_name : name of the chat
> total_messages : total messages in that chat
> user_name : name of current user
'''
def get_messages(self, chat_id, msg_thread=False) -> dict:
return self.__get_messages_func(chat_id=chat_id, msg_thread=msg_thread)
# -------------- GET MESSAGE THREAD METHOD --------------
'''
- To get the thread of particular message
- function takes to parameter chat_id, msg_id
> chat_id : chat_id of the chat
> msg_id : message id for which thread is to be extracted
- Function returns a dictionary object of thread message of that message
> chat_id : chat_id of the chat
> msg_id : message id of the chat
> messages : messages of all the thread
> total_thread : count of total messages in thread
'''
def get_message_threads(self, chat_id, msg_id) -> dict:
messages = self.__get_message_threads_func(
chat_id=chat_id, msg_id=msg_id)
temp_data = {
"chat_id": chat_id,
"msg_id": msg_id,
"messages": messages,
"total_thread": len(messages)
}
return temp_data
# ------------ LOGOUT METHOD ---------------
'''
- Logout the user from local session
- Clears up all the local cache
- function takes no argument
- function return a string object
'''
def logout(self) -> str:
try:
os.remove(self.__DATA_PATH)
return "Successfully logged out and cleared local cache"
except Exception:
return "Fail to logout and clear cache"
# ------------GET CHAT MEMBERS METHOD -----------
'''
- To get all the members list in a particular channel
- function takes one argument chat_id
> chat_id : chat_id of the chat
- function returns a dictionary object
> chat_id : chat_id of the chat
> members : list of members
-> name : name of the member
-> regno : registration number
-> profile_img : profile image of the member
-> phone : phone number ( if available )
> total_members : count fof total members
'''
def get_chat_members(self, chat_id) -> dict:
return self.__get_chat_members_func(chat_id=chat_id)
# ------------ SEARCH USER METHOD ----------
'''
- To search user
- function takes one argument query
> query : search query
- function returns a dictionary object
> search_query : search query
> users : list of users found
-> id : id
-> name : name of the user
-> regno : registration number of the user
-> department : department/batch of the user
-> profile_img : profile image of the user
> total_found : total user matched the query
'''
def search_users(self, query):
return self.__search_user_func(user=query) | lpulive/lpulive_main.py | from posixpath import expanduser
from typing import Dict
from lpulive.lpulive_urls import (GET_CAHAT_MEMBERS_URL, GET_CONVRSATION_URL, GET_MESSAGES_THREADS_URL,
GET_MESSAGES_URL, GET_WORKSPACE_DETAIL_URL,
LOGIN_URL, LOGIN_VIA_TOKEN_URL, SEARCH_URL,
SWITCH_WORKSPACE_URL)
import requests
import os
import pickle
import json
# -------- Main User class ------
class User:
def __init__(self, registration_no, password) -> None:
self.__REGNO = str(registration_no)
self.__PASSWORD = str(password)
self.__DATA_PATH = f"data_{self.__REGNO}.pkl"
self.__LOGIN_SUCCESS = False
self.__DATA_FILE = {}
self.__HEADERS = {
"user-agent": "Mozilla/5.0 (Windows NT x.y; Win64; x64; rv:10.0) Gecko/20100101 Firefox/10.0",
"app_version": "1.0.0",
"device_type": "WEB"}
self.__DEVICE_DETAILS = json.dumps(
{"browser-agent": str(self.__HEADERS['user-agent'])})
self.__check_stored_data(self.__DATA_PATH)
self.__WORKSPACE_ID = self.__DATA_FILE["workspace_id"] if self.__LOGIN_SUCCESS else None
self.__USER_SESSION = self.__DATA_FILE["user_session"] if self.__LOGIN_SUCCESS else None
self.__EN_USER_ID = self.__DATA_FILE["en_user_id"] if self.__LOGIN_SUCCESS else None
self.__ACCESS_TOKEN = self.__DATA_FILE["access_token"] if self.__LOGIN_SUCCESS else None
self.__LPU_ACCESS_TOKEN = self.__DATA_FILE["lpu_access_token"] if self.__LOGIN_SUCCESS else None
def __set_pickle_container(self, data_obj, data_path):
with open(data_path, "wb") as pkl:
pickle.dump(data_obj, pkl, pickle.HIGHEST_PROTOCOL)
def __get_pickle_container(self, data_path):
with open(data_path, "rb") as pkl:
return pickle.load(pkl)
def __check_stored_data(self, file_path) -> None:
if not os.path.isfile(file_path):
self.__login()
if self.__LOGIN_SUCCESS:
self.__DATA_FILE = self.__get_pickle_container(file_path)
else:
self.__DATA_FILE = self.__get_pickle_container(file_path)
self.__LOGIN_SUCCESS = True
if self.__REGNO != self.__DATA_FILE["regno"] or self.__DATA_FILE["password"] != self.__PASSWORD:
self.__login()
if self.__LOGIN_SUCCESS:
self.__DATA_FILE = self.__get_pickle_container(file_path)
else:
self.__DATA_FILE = {}
self.__set_pickle_container({}, file_path)
# login function
def __login(self) -> None:
self.__USER_SESSION = requests.session()
json_data = {
"password": <PASSWORD>.__PASSWORD,
"username": self.__REGNO,
"domain": "lpu.in",
"time_zone": 330
}
login_response = self.__USER_SESSION.post(
url=LOGIN_URL, json=json_data, headers=self.__HEADERS)
if login_response.status_code == 200:
return_data = {}
login_response_data = login_response.json()
self.__WORKSPACE_ID = login_response_data["data"]["workspaces_info"][0]["workspace_id"]
self.__ACCESS_TOKEN = login_response_data["data"]["user_info"]["access_token"]
self.__LPU_ACCESS_TOKEN = login_response_data["data"]["user_info"]["lpu_access_token"]
self.__EN_USER_ID = login_response_data["data"]["workspaces_info"][0]["en_user_id"]
return_data = {
"workspace_id": self.__WORKSPACE_ID,
"access_token": self.__ACCESS_TOKEN,
"lpu_access_token": self.__LPU_ACCESS_TOKEN,
"en_user_id": self.__EN_USER_ID,
"user_session": self.__USER_SESSION,
"password": self.__PASSWORD,
"regno": self.__REGNO
}
self.__LOGIN_SUCCESS = True
self.__set_pickle_container(return_data, self.__DATA_PATH)
self.__switch_workspace()
else:
self.__LOGIN_SUCCESS = False
def __switch_workspace(self):
sw_data = {
"workspace_id": self.__WORKSPACE_ID,
"access_token": self.__ACCESS_TOKEN,
"device_details": json.dumps({"browser-agent": str(self.__HEADERS['user-agent'])}),
"device_id": "random_text"
}
sw_response = self.__USER_SESSION.post(
url=SWITCH_WORKSPACE_URL, json=sw_data, headers=self.__HEADERS)
if sw_response.status_code == 200:
self.__login_via_token()
def __login_via_token(self):
lvt_data = {
"token": self.__ACCESS_TOKEN,
"domain": "lpu.in",
"lpu_access_token": self.__LPU_ACCESS_TOKEN,
"time_zone": 330
}
lvt_headers = {"access_token": self.__ACCESS_TOKEN}
lvt_headers.update(self.__HEADERS)
self.__USER_SESSION.post(
url=LOGIN_VIA_TOKEN_URL, json=lvt_data, headers=lvt_headers)
def __get_workpace_details(self):
gwsd_data = f"workspace=spaces&domain=lpu.in&device_id=random_text&device_details={self.__DEVICE_DETAILS}"
self.__USER_SESSION.get(
url=f"{GET_WORKSPACE_DETAIL_URL}?{gwsd_data}", headers=self.__HEADERS)
def __get_conversation_filter(self, data) -> list:
return_data = []
for single in data:
temp = {}
temp["id"] = single["channel_id"]
temp["chat_name"] = single["label"]
temp["date_time"] = single["date_time"]
temp["unread"] = single["unread_count"]
return_data.append(temp)
return return_data
def __get_conversations_func(self) -> dict:
if self.__LOGIN_SUCCESS:
gc_data = f"en_user_id={self.__EN_USER_ID}&page_start=1&device_id=random_text&device_details={self.__DEVICE_DETAILS}"
gc_responce = self.__USER_SESSION.get(
url=f"{GET_CONVRSATION_URL}?{gc_data}", headers=self.__HEADERS)
if gc_responce.status_code == 200:
temp_data = gc_responce.json()["data"]
total_chat = temp_data["count"]
filter_chat_list = self.__get_conversation_filter(
temp_data["conversation_list"])
final_data = {
"chats": filter_chat_list,
"total_chat": total_chat,
}
return final_data
else:
error_data = {
"message": "fail to fetch data"
}
return error_data
else:
return self.login_fail_message(type="dict")
def __get_message_threads_func(self, chat_id, msg_id) -> list:
if self.__LOGIN_SUCCESS:
return_data = []
gmt_data = f"muid={msg_id}&en_user_id={self.__EN_USER_ID}&channel_id={chat_id}"
gmt_responce = self.__USER_SESSION.get(
url=f"{GET_MESSAGES_THREADS_URL}?{gmt_data}", headers=self.__HEADERS)
if gmt_responce.status_code == 200:
temp_data = gmt_responce.json()["data"]["thread_message"]
for single in temp_data:
temp = {
"from_user": single["full_name"].split(":")[0].strip(),
"regno": single["username"],
"message": single["message"],
"date": single["date_time"]
}
return_data.append(temp)
return return_data
else:
return ["Fail to load thread, please check m_id"]
else:
return self.login_fail_message(type="list")
def __get_messages_filter(self, data, chat_id, msg_thread=False) -> list:
return_data = []
for ind, single in enumerate(data[::-1]):
temp = {
"id": ind+1,
"m_id": single["muid"],
"message": single["message"],
"date": single["date_time"],
"from_user": single["full_name"].split(":")[0].strip(),
"regno": single["username"],
"attachment": False
}
if "url" in single:
temp["attachment"] = {
"file_name": single["file_name"],
"url": single["url"],
"file_size": single["file_size"],
"type": single["document_type"]
}
if msg_thread:
if single["thread_message_count"] > 0:
temp["thread"] = self.__get_message_threads_func(
chat_id, single["muid"])
else:
temp["thread"] = "No thread"
else:
temp["thread"] = single["thread_message_count"]
return_data.append(temp)
return return_data
def __get_messages_func(self, chat_id, msg_thread=False) -> dict:
if self.__LOGIN_SUCCESS:
gm_data = f"channel_id={chat_id}&en_user_id={self.__EN_USER_ID}&page_start=1&store_promise=true&device_id=random_text&device_details={self.__DEVICE_DETAILS}"
gm_responce = self.__USER_SESSION.get(
url=f"{GET_MESSAGES_URL}?{gm_data}", headers=self.__HEADERS)
if gm_responce.status_code == 200:
temp_data = gm_responce.json()["data"]
filtered_messages = self.__get_messages_filter(
temp_data["messages"], chat_id, msg_thread)
chat_name = temp_data["label"]
user_name = temp_data["full_name"]
total_messages = len(temp_data["messages"])
final_data = {
"chat_id": chat_id,
"messages": filtered_messages,
"chat_name": chat_name,
"total_messages": total_messages,
"user_name": user_name,
}
with open("lpulive/test/data.json", "w") as f:
json.dump(final_data, f)
return final_data
else:
error_data = {
"message": "fail to load messages, Please check chat_id"
}
return error_data
else:
return self.login_fail_message(type="dict")
def __get_chat_members_filter(self, data):
return_data = []
for single in data:
temp = {
"name": single["full_name"].split(":")[0].strip(),
"regno": single["email"],
"profile_img": single["user_image"],
"phone": single["contact_number"]
}
return_data.append(temp)
return return_data
def __get_chat_members_func(self, chat_id) -> dict:
if self.__LOGIN_SUCCESS:
def gcm_data_func(page):
gcm_data2 = {"channel_id": chat_id,
"en_user_id": self.__EN_USER_ID,
"get_data_type": "MEMBERS",
"user_page_start": page}
res = self.__USER_SESSION.get(
url=GET_CAHAT_MEMBERS_URL, json=gcm_data2, headers=self.__HEADERS)
if res.status_code == 200:
return res.json()["data"]["chat_members"]
else:
return None
return_data = []
for page in range(0, 5000, 51):
x = gcm_data_func(page=page)
if x == None:
return {"message": "Fail to fetch members, Please check chat_id"}
elif len(x) < 1:
break
else:
return_data += x
final_data = {
"chat_id": chat_id,
"members": self.__get_chat_members_filter(return_data),
"total_members": len(return_data)
}
return final_data
else:
return self.login_fail_message(type="dict")
def __search_user_filter(self, data):
return_data = []
for ind, single in enumerate(data):
temp = {
"id": ind+1,
"name": single["full_name"].split(":")[0].strip(),
"regno": single["email"],
"department": single["department"],
"profile_img": single["user_image"]
}
return_data.append(temp)
return return_data
def __search_user_func(self, user) -> dict:
if self.__LOGIN_SUCCESS:
if len(user) < 3:
return {"message": "Search Query must be atleast 2 character long"}
su_data = {
"en_user_id": self.__EN_USER_ID,
"search_text": user,
"user_role": "USER",
"search_deactivated_member": "true"
}
su_response = self.__USER_SESSION.get(
url=SEARCH_URL, json=su_data, headers=self.__HEADERS)
if su_response.status_code == 200:
data = su_response.json()["data"]["users"]
users = self.__search_user_filter(data)
return_data = {
"search_query": user,
"users": users,
"total_found": len(users)
}
return return_data
else:
return {"message": "fail to fetch, please try again later"}
else:
return self.login_fail_message(type="dict")
def login_fail_message(self, type="str"):
if type == "dict":
return {"message": "fail to login, check user details"}
elif type == "list":
return ["fail to login, check user details"]
else:
return "fail to login, check user details"
"""# ------------------------ USER AVAILABLE METHODS ------------------------------ #"""
# ----------GET CONVERSATION METHOD --------------
'''
- To get all the active chat
- function takes no argument
- function return a dictionary object
> chats : list of all the chat active on users profile
-> id : id of particular chat
-> chat_name : name of the chat
-> date_time : last acitve message on that chat
-> unread : total unread messages on that chat
> total_chat : total group/private chat active on users profiles
'''
def get_conversations(self) -> dict:
return self.__get_conversations_func()
# ---------GET MESSAGES METHOD ------------
'''
- To get all the messages of selected chat
- functions takes to argument chat_id, msg_thread
> chat_id : to select a particular chat to get all messages [ required argument ]
> msg_thread : to turn on thread, this will also include the threads of messages ( if appicable ) [ default value is False ]
- function return a dictionary object
> chat_id : id of the chat
> messages : list of all the messages in that chat
-> id : id number ( smaller the id newer the message )
-> m_id : message id
-> message : text message
-> from_user : message sender name
-> regno : message sender registration number
-> attachment : any attachment in that message ( if applicable )
-> thread_message : get all the thread of a particular message ( if msg_thread is True )
> chat_name : name of the chat
> total_messages : total messages in that chat
> user_name : name of current user
'''
def get_messages(self, chat_id, msg_thread=False) -> dict:
return self.__get_messages_func(chat_id=chat_id, msg_thread=msg_thread)
# -------------- GET MESSAGE THREAD METHOD --------------
'''
- To get the thread of particular message
- function takes to parameter chat_id, msg_id
> chat_id : chat_id of the chat
> msg_id : message id for which thread is to be extracted
- Function returns a dictionary object of thread message of that message
> chat_id : chat_id of the chat
> msg_id : message id of the chat
> messages : messages of all the thread
> total_thread : count of total messages in thread
'''
def get_message_threads(self, chat_id, msg_id) -> dict:
messages = self.__get_message_threads_func(
chat_id=chat_id, msg_id=msg_id)
temp_data = {
"chat_id": chat_id,
"msg_id": msg_id,
"messages": messages,
"total_thread": len(messages)
}
return temp_data
# ------------ LOGOUT METHOD ---------------
'''
- Logout the user from local session
- Clears up all the local cache
- function takes no argument
- function return a string object
'''
def logout(self) -> str:
try:
os.remove(self.__DATA_PATH)
return "Successfully logged out and cleared local cache"
except Exception:
return "Fail to logout and clear cache"
# ------------GET CHAT MEMBERS METHOD -----------
'''
- To get all the members list in a particular channel
- function takes one argument chat_id
> chat_id : chat_id of the chat
- function returns a dictionary object
> chat_id : chat_id of the chat
> members : list of members
-> name : name of the member
-> regno : registration number
-> profile_img : profile image of the member
-> phone : phone number ( if available )
> total_members : count fof total members
'''
def get_chat_members(self, chat_id) -> dict:
return self.__get_chat_members_func(chat_id=chat_id)
# ------------ SEARCH USER METHOD ----------
'''
- To search user
- function takes one argument query
> query : search query
- function returns a dictionary object
> search_query : search query
> users : list of users found
-> id : id
-> name : name of the user
-> regno : registration number of the user
-> department : department/batch of the user
-> profile_img : profile image of the user
> total_found : total user matched the query
'''
def search_users(self, query):
return self.__search_user_func(user=query) | 0.437583 | 0.052328 |
import os, sys, datetime, re, cPickle, gzip, time, csv, glob
from cartography.geometry import Geometry, Point, LinearRing, Polygon
from cartography.proj.srs import SpatialReference
from jpltime import adoytoaymd
GRANULE_RE = re.compile(r'^(M(?:Y|O)D).*?\.(A\d{7}\.\d{4})')
CSV_LINE = "%s,%f,%f,%f,%f,%s,%s"
dataDirs = ['TERRA', 'AQUA']
datasetName = 'MODIS'
minutesPerGranule = 5
daysPerCycle = 16
#get data files
metaFiles = []
for dataDir in dataDirs:
metaDir = os.path.join('ladsweb.nascom.nasa.gov', 'geoMeta',
dataDir)
metaFiles.extend(glob.glob(os.path.join(metaDir, '????',
'M?D03_????-??-??.txt')))
metaFiles.sort()
#initialize variables to do orbit table generation
count = 0
currentTime = None
timeIncr = datetime.timedelta(minutes=minutesPerGranule)
granulesPerDay = 86400/(minutesPerGranule*60)
granulesPerCycle = granulesPerDay*daysPerCycle
table = []
doneFlag = False
currentPickleYear = None
print "id,latMin,latMax,lonMin,lonMax,startDate,endDate"
for metaFile in metaFiles:
r = csv.reader(open(metaFile, "rb"))
for i, row in enumerate(r):
if row[0].startswith('#'): continue
(GranuleID, StartDateTime, ArchiveSet, OrbitNumber, DayNightFlag, EastBoundingCoord,
NorthBoundingCoord, SouthBoundingCoord, WestBoundingCoord, GRingLongitude1,
GRingLongitude2, GRingLongitude3, GRingLongitude4, GRingLatitude1, GRingLatitude2,
GRingLatitude3, GRingLatitude4) = row
granuleIdMatch = GRANULE_RE.search(GranuleID)
if not granuleIdMatch: raise RuntimeError("Failed to match %s" % GranuleID)
granuleId = "%s*.%s" % granuleIdMatch.groups()
date0 = datetime.datetime(*time.strptime(StartDateTime, '%Y-%m-%d %H:%M')[:-3])
date1 = date0 + datetime.timedelta(minutes=minutesPerGranule)
EastBoundingCoord = float(EastBoundingCoord)
NorthBoundingCoord = float(NorthBoundingCoord)
SouthBoundingCoord = float(SouthBoundingCoord)
WestBoundingCoord = float(WestBoundingCoord)
GRingLongitude1 = float(GRingLongitude1)
GRingLongitude2 = float(GRingLongitude2)
GRingLongitude3 = float(GRingLongitude3)
GRingLongitude4 = float(GRingLongitude4)
GRingLatitude1 = float(GRingLatitude1)
GRingLatitude2 = float(GRingLatitude2)
GRingLatitude3 = float(GRingLatitude3)
GRingLatitude4 = float(GRingLatitude4)
#get bounds
srs = SpatialReference(epsg=4326)
shell = LinearRing([Point(GRingLongitude1, GRingLatitude1),
Point(GRingLongitude2, GRingLatitude2),
Point(GRingLongitude3, GRingLatitude3),
Point(GRingLongitude4, GRingLatitude4),
Point(GRingLongitude1, GRingLatitude1)], srs=srs)
poly = Polygon(shell, srs=srs)
minx, miny, maxx, maxy = poly.envelope().totuple()
if abs(minx-maxx) >= 180.: p = (maxx, miny, minx, maxy)
else: p = (minx, miny, maxx, maxy)
print CSV_LINE % (granuleId, p[1], p[3], p[0], p[2],
date0.isoformat()+'Z', date1.isoformat()+'Z') | scripts/dumpCSV_MODIS.py | import os, sys, datetime, re, cPickle, gzip, time, csv, glob
from cartography.geometry import Geometry, Point, LinearRing, Polygon
from cartography.proj.srs import SpatialReference
from jpltime import adoytoaymd
GRANULE_RE = re.compile(r'^(M(?:Y|O)D).*?\.(A\d{7}\.\d{4})')
CSV_LINE = "%s,%f,%f,%f,%f,%s,%s"
dataDirs = ['TERRA', 'AQUA']
datasetName = 'MODIS'
minutesPerGranule = 5
daysPerCycle = 16
#get data files
metaFiles = []
for dataDir in dataDirs:
metaDir = os.path.join('ladsweb.nascom.nasa.gov', 'geoMeta',
dataDir)
metaFiles.extend(glob.glob(os.path.join(metaDir, '????',
'M?D03_????-??-??.txt')))
metaFiles.sort()
#initialize variables to do orbit table generation
count = 0
currentTime = None
timeIncr = datetime.timedelta(minutes=minutesPerGranule)
granulesPerDay = 86400/(minutesPerGranule*60)
granulesPerCycle = granulesPerDay*daysPerCycle
table = []
doneFlag = False
currentPickleYear = None
print "id,latMin,latMax,lonMin,lonMax,startDate,endDate"
for metaFile in metaFiles:
r = csv.reader(open(metaFile, "rb"))
for i, row in enumerate(r):
if row[0].startswith('#'): continue
(GranuleID, StartDateTime, ArchiveSet, OrbitNumber, DayNightFlag, EastBoundingCoord,
NorthBoundingCoord, SouthBoundingCoord, WestBoundingCoord, GRingLongitude1,
GRingLongitude2, GRingLongitude3, GRingLongitude4, GRingLatitude1, GRingLatitude2,
GRingLatitude3, GRingLatitude4) = row
granuleIdMatch = GRANULE_RE.search(GranuleID)
if not granuleIdMatch: raise RuntimeError("Failed to match %s" % GranuleID)
granuleId = "%s*.%s" % granuleIdMatch.groups()
date0 = datetime.datetime(*time.strptime(StartDateTime, '%Y-%m-%d %H:%M')[:-3])
date1 = date0 + datetime.timedelta(minutes=minutesPerGranule)
EastBoundingCoord = float(EastBoundingCoord)
NorthBoundingCoord = float(NorthBoundingCoord)
SouthBoundingCoord = float(SouthBoundingCoord)
WestBoundingCoord = float(WestBoundingCoord)
GRingLongitude1 = float(GRingLongitude1)
GRingLongitude2 = float(GRingLongitude2)
GRingLongitude3 = float(GRingLongitude3)
GRingLongitude4 = float(GRingLongitude4)
GRingLatitude1 = float(GRingLatitude1)
GRingLatitude2 = float(GRingLatitude2)
GRingLatitude3 = float(GRingLatitude3)
GRingLatitude4 = float(GRingLatitude4)
#get bounds
srs = SpatialReference(epsg=4326)
shell = LinearRing([Point(GRingLongitude1, GRingLatitude1),
Point(GRingLongitude2, GRingLatitude2),
Point(GRingLongitude3, GRingLatitude3),
Point(GRingLongitude4, GRingLatitude4),
Point(GRingLongitude1, GRingLatitude1)], srs=srs)
poly = Polygon(shell, srs=srs)
minx, miny, maxx, maxy = poly.envelope().totuple()
if abs(minx-maxx) >= 180.: p = (maxx, miny, minx, maxy)
else: p = (minx, miny, maxx, maxy)
print CSV_LINE % (granuleId, p[1], p[3], p[0], p[2],
date0.isoformat()+'Z', date1.isoformat()+'Z') | 0.306527 | 0.232354 |
import pyyjj
import json
from contextlib import contextmanager
from sqlalchemy import inspect, types, TypeDecorator
import kungfu.wingchun.constants as wc_constants
def make_url(location, filename):
db_file = location.locator.layout_file(location, pyyjj.layout.SQLITE, filename)
return 'sqlite:///{}'.format(db_file)
def object_as_dict(obj):
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs}
@contextmanager
def session_scope(session_factory):
"""Provide a transactional scope around a series of operations."""
session = session_factory()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
class Json(TypeDecorator):
@property
def python_type(self):
return object
impl = types.String
def process_bind_param(self, value, dialect):
return json.dumps(value)
def process_literal_param(self, value, dialect):
return value
def process_result_value(self, value, dialect):
try:
return json.loads(value)
except (ValueError, TypeError):
return None
class EnumTypeDecorator(TypeDecorator):
impl = types.Integer
def __init__(self, enum_type):
TypeDecorator.__init__(self)
self.enum_type = enum_type
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
def process_bind_param(self, value, dialect):
return int(value)
def process_literal_param(self, value, dialect):
return value
def process_result_value(self, value, dialect):
try:
return self.enum_type(value)
except (ValueError, TypeError):
return None
class VolumeCondition(EnumTypeDecorator):
def __init__(self):
super(VolumeCondition, self).__init__(wc_constants.VolumeCondition)
class TimeCondition(EnumTypeDecorator):
def __init__(self):
super(TimeCondition, self).__init__(wc_constants.TimeCondition)
class OrderStatus(EnumTypeDecorator):
def __init__(self):
super(OrderStatus, self).__init__(wc_constants.OrderStatus)
class InstrumentType(EnumTypeDecorator):
def __init__(self):
super(InstrumentType, self).__init__(wc_constants.InstrumentType)
class Side(EnumTypeDecorator):
def __init__(self):
super(Side, self).__init__(wc_constants.Side)
class Offset(EnumTypeDecorator):
def __init__(self):
super(Offset, self).__init__(wc_constants.Offset)
class HedgeFlag(EnumTypeDecorator):
def __init__(self):
super(HedgeFlag, self).__init__(wc_constants.HedgeFlag)
class Direction(EnumTypeDecorator):
def __init__(self):
super(Direction, self).__init__(wc_constants.Direction)
class PriceType(EnumTypeDecorator):
def __init__(self):
super(PriceType, self).__init__(wc_constants.PriceType)
class LedgerCategory(EnumTypeDecorator):
def __init__(self):
super(LedgerCategory, self).__init__(wc_constants.LedgerCategory)
class UINT64(TypeDecorator):
impl = types.String
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
def process_bind_param(self, value, dialect):
return str(value)
def process_literal_param(self, value, dialect):
return value
def process_result_value(self, value, dialect):
try:
return int(value)
except (ValueError, TypeError):
return None | core/python/kungfu/data/sqlite/__init__.py | import pyyjj
import json
from contextlib import contextmanager
from sqlalchemy import inspect, types, TypeDecorator
import kungfu.wingchun.constants as wc_constants
def make_url(location, filename):
db_file = location.locator.layout_file(location, pyyjj.layout.SQLITE, filename)
return 'sqlite:///{}'.format(db_file)
def object_as_dict(obj):
return {c.key: getattr(obj, c.key)
for c in inspect(obj).mapper.column_attrs}
@contextmanager
def session_scope(session_factory):
"""Provide a transactional scope around a series of operations."""
session = session_factory()
try:
yield session
session.commit()
except:
session.rollback()
raise
finally:
session.close()
class Json(TypeDecorator):
@property
def python_type(self):
return object
impl = types.String
def process_bind_param(self, value, dialect):
return json.dumps(value)
def process_literal_param(self, value, dialect):
return value
def process_result_value(self, value, dialect):
try:
return json.loads(value)
except (ValueError, TypeError):
return None
class EnumTypeDecorator(TypeDecorator):
impl = types.Integer
def __init__(self, enum_type):
TypeDecorator.__init__(self)
self.enum_type = enum_type
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
def process_bind_param(self, value, dialect):
return int(value)
def process_literal_param(self, value, dialect):
return value
def process_result_value(self, value, dialect):
try:
return self.enum_type(value)
except (ValueError, TypeError):
return None
class VolumeCondition(EnumTypeDecorator):
def __init__(self):
super(VolumeCondition, self).__init__(wc_constants.VolumeCondition)
class TimeCondition(EnumTypeDecorator):
def __init__(self):
super(TimeCondition, self).__init__(wc_constants.TimeCondition)
class OrderStatus(EnumTypeDecorator):
def __init__(self):
super(OrderStatus, self).__init__(wc_constants.OrderStatus)
class InstrumentType(EnumTypeDecorator):
def __init__(self):
super(InstrumentType, self).__init__(wc_constants.InstrumentType)
class Side(EnumTypeDecorator):
def __init__(self):
super(Side, self).__init__(wc_constants.Side)
class Offset(EnumTypeDecorator):
def __init__(self):
super(Offset, self).__init__(wc_constants.Offset)
class HedgeFlag(EnumTypeDecorator):
def __init__(self):
super(HedgeFlag, self).__init__(wc_constants.HedgeFlag)
class Direction(EnumTypeDecorator):
def __init__(self):
super(Direction, self).__init__(wc_constants.Direction)
class PriceType(EnumTypeDecorator):
def __init__(self):
super(PriceType, self).__init__(wc_constants.PriceType)
class LedgerCategory(EnumTypeDecorator):
def __init__(self):
super(LedgerCategory, self).__init__(wc_constants.LedgerCategory)
class UINT64(TypeDecorator):
impl = types.String
def coerce_compared_value(self, op, value):
return self.impl.coerce_compared_value(op, value)
def process_bind_param(self, value, dialect):
return str(value)
def process_literal_param(self, value, dialect):
return value
def process_result_value(self, value, dialect):
try:
return int(value)
except (ValueError, TypeError):
return None | 0.706393 | 0.239283 |
from tkinter import *
from tkinter import ttk, messagebox
from sqlite3 import Error, connect
import os
def agenda():
"""
#### Estabelece a conexão com o banco de dados Agenda.db
"""
dirdb = os.path.dirname(__file__)
nomedb = dirdb + '/Agenda.db'
con = connect(nomedb)
return con
def limpatv(par):
"""
#### Função para limpar a tela da TreeView antes de mostrar os dados
:param par: informa o nome da TreeView
"""
treev = par
treev.delete(*treev.get_children())
"""
* OU:
for i in treev.get_children():
treev.delete(i)
"""
def tvw(master):
"""
Gera a Treeview que exibe os registros da tabela tb_contatos
do banco de dados Agenda.db
:param master: objeto pai da Treeview
"""
tela = master
global treev
# _Treeview:
# *- ****** Definindo as colunas ******
colunas = ('id', 'nome', 'telefone', 'e-mail',
'endereco', 'cidade', 'estado', 'observacao')
treev = ttk.Treeview(tela, columns=colunas,
show='headings', padding=(1, 1))
# *- ****** Definindo os cabeçalhos das colunas ******
treev.heading('id', text='ID')
treev.heading('nome', text='Nome')
treev.heading('telefone', text='Telefone')
treev.heading('e-mail', text='Email')
treev.heading('endereco', text='Endereço')
treev.heading('cidade', text='Cidade')
treev.heading('estado', text='UF')
treev.heading('observacao', text='Nota')
# *- Adicionando uma scrollbar:
scrollbarv = ttk.Scrollbar(tela, orient=[VERTICAL], command=treev.yview)
scrollbarh = ttk.Scrollbar(
tela, orient=[HORIZONTAL], command=treev.xview)
treev.configure(yscroll=scrollbarv.set)
treev.configure(xscroll=scrollbarh.set)
# *- ***** Definindo o tamanho das colunas *****
treev.column('id', width=35, minwidth=10, stretch=True, anchor=CENTER)
treev.column('nome', width=170, minwidth=0, stretch=True)
treev.column('telefone', width=115, minwidth=0, stretch=True)
treev.column('e-mail', width=150, minwidth=0, stretch=True)
treev.column('endereco', width=200, minwidth=0, stretch=True)
treev.column('cidade', width=100, minwidth=0, stretch=True)
treev.column('estado', width=35, minwidth=0, stretch=True, anchor=CENTER)
treev.column('observacao', width=235, minwidth=0, stretch=True)
# *- ****** Posicionando o elemento Treeview: ******
treev.grid(column=0, row=2, padx=True, pady=True)
scrollbarv.grid(row=2, column=1, sticky='ns')
scrollbarh.grid(row=3, column=0, sticky='ew')
# *- ****** Exibe os dados da tabela tb_contatos na Treeview: ******
exibir(treev)
# <Control-Button-1> <<TreeviewSelect>>
treev.bind('<<TreeviewSelect>>', item_selected)
return
def lfr2(master):
"""
#### Gera os elementos que serão posicionados no tela da tela principal
:param master: objeto pai da LabelFrame
"""
global txtnome, txtfone, txtmail, txtend, txtcid, txtuf, txtobs, lf2
global btninser, btnedita, btnexclui
lf2 = master
# teste = StringVar(tela, 'isto é um teste')
# _ Elementos label e texto (Entry):
# _ Elemento label:
lblnome = Label(lf2, text='Nome: ', width=8, anchor='w') # _ , bg='#0ff'
lblfone = Label(lf2, text='Telefone: ', width=8, anchor='w')
lblmail = Label(lf2, text='E-mail: ', width=8, anchor='w')
lblend = Label(lf2, text='Endereço: ', width=8, anchor='w')
lblcid = Label(lf2, text='Cidade: ', width=8, anchor='w')
lbluf = Label(lf2, text='UF: ', width=8, anchor='w')
lblobs = Label(lf2, text='Nota: ', width=4, anchor='w')
# _ Elemento texto (Entry):
txtnome = Entry(lf2, width=25, font=(
'Ebrima', 12), bd=1, justify='left') # coluna 1 , textvariable=teste
txtfone = Entry(lf2, width=15, font=(
'Ebrima', 12), bd=1, justify='left')
txtmail = Entry(lf2, width=25, font=(
'Ebrima', 12), bd=1, justify='left')
txtend = Entry(lf2, width=30, font=(
'Ebrima', 12), bd=1, justify='left') # coluna 3
txtcid = Entry(lf2, width=25, font=(
'Ebrima', 12), bd=1, justify='left')
txtuf = Entry(lf2, width=2, font=('Ebrima', 12), bd=1, justify='left')
txtobs = Text(lf2, width=29, height=4, font=(
'Ebrima', 12), bd=1) # coluna 5
reglist = [txtnome, txtfone, txtmail, txtend, txtcid, txtuf, txtobs]
# _ Elemento botão do LabelFrame:
btninser = Button(lf2, text='Inserir', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: inserir(reglist))
btnedita = Button(lf2, text='Editar', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: dml('editar'), state='disabled')
btnexclui = Button(lf2, text='Excluir', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: dml('excluir'), state='disabled')
btnreset = Button(lf2, text='Atualizar', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=atualiza)
# _ Posicionando os elementos dentro do LabelFrame:
lblnome.grid(column=0, row=1)
txtnome.grid(column=1, row=1, padx=5, pady=2, sticky='w')
lblfone.grid(column=0, row=2)
txtfone.grid(column=1, row=2, padx=5, pady=2, sticky='w')
lblmail.grid(column=0, row=3)
txtmail.grid(column=1, row=3, padx=5, pady=2, sticky='w')
lblend.grid(column=2, row=1)
txtend.grid(column=3, row=1, padx=5, pady=2, sticky='w')
lblcid.grid(column=2, row=2)
txtcid.grid(column=3, row=2, padx=5, pady=2, sticky='w')
lbluf.grid(column=2, row=3)
txtuf.grid(column=3, row=3, padx=5, pady=2, sticky='w')
lblobs.grid(column=4, row=1)
txtobs.grid(column=5, row=1, padx=5, pady=2, sticky='wn', rowspan=3)
btninser.grid(column=1, row=4, pady=5)
btnedita.grid(column=3, row=4, padx=2.5)
btnexclui.grid(column=5, row=4, padx=5)
btnreset.grid(column=3, row=5, padx=5, pady=10)
return
def lfr3(master):
"""
#### Gera os elementos que serão posicionados no tela da tela principal
:param master: objeto pai da LabelFrame
"""
lf3 = master
# * Elementos label e texto (Entry) do LabelFrame frame3:
# * Elemento label
lblnome1 = Label(lf3, text='Nome: ', width=5, anchor='w')
# -* Elemento texto (Entry) do LabelFrame frame3:
txtnome1 = Entry(lf3, width=30, font=('Ebrima, 12'), justify='left')
# -* Elemento botão do LabelFrame frame3:
btnpesq = Button(lf3, text='Pesquisar', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: pesquisa(treev, txtnome1))
btntudo = Button(lf3, text='Mostrar Tudo', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: exibir(treev)) # _ flat, groove, raised, ridge, solid, or sunken
btnsair = Button(lf3, text='Sair', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=sair)
# -* Posicionando os elementos dentro do frame3:
lblnome1.grid(column=0, row=0, padx=5)
txtnome1.grid(column=1, row=0, padx=5, sticky='w')
btnpesq.grid(column=2, row=0, padx=10, pady=10)
btntudo.grid(column=3, row=0, padx=5, pady=10)
btnsair.grid(column=6, row=0, padx=10, pady=10)
return
def inserir(val: list):
"""
#### Função para inserir um novo registro na tabela do banco de dados
:param val: lista contendo os registro a serem inseridos na tabela tb_contatos do banco de dados Agenda.db
"""
txtnome = val[0]
txtfone = val[1]
txtmail = val[2]
txtend = val[3]
txtcid = val[4]
txtuf = val[5]
txtobs = val[6]
vcon = agenda() # * Abre o banco de dados
po = vcon.cursor() # * Definindo o cursor para receber a conexão
try:
if txtnome.get() == '' or txtfone.get() == '' or txtmail.get() == '':
# ** O formulário está em branco
messagebox.showerror(
'ATENÇÃO ERRO', 'Não foram informados os valores!')
else:
# > 3- Ler os dados inseridos do formulário
reg = f"""INSERT INTO tb_contatos
(t_nome, t_fone, t_email, t_endereco, t_cidade, t_uf, t_obs)
VALUES("{txtnome.get()}", "{txtfone.get()}", "{txtmail.get()}",
"{txtend.get()}", "{txtcid.get()}", "{txtuf.get().upper()}",
"{txtobs.get(1.0, END)}")
"""
# > 4- Inserir os dados do formulário na tabela do banco de dados e fazer o commit (atualizar o banco de dados)
po.execute(reg)
vcon.commit()
messagebox.showinfo('AVISO', 'Registro inserido com sucesso!')
except Error as err:
messagebox.showerror('ATENÇÃO ERRO', err)
finally:
# > 5- Limpando os dados do formulário e fechando o banco de
limpatxt()
txtnome.focus()
vcon.close() # _ fecha a conexão
return
def sair():
"""
#### Encerra o aplicativo
"""
os.system('clear')
exit()
return
def pesquisa(inf, txt):
"""
#### Executa uma pesquisa no banco de dados por um nome e mostra na TreeView
:param inf: informa o nome da Treeview
:param txt: informa o nome para a pesquisa
"""
tv = inf
txtnome1 = txt
# > Conectando o banco de dados:
vcon = agenda()
po = vcon.cursor()
vnome = txtnome1.get()
try:
# _ Conulta por nome:
if vnome == '':
messagebox.showerror(
'ATENÇÃO ERRO', 'Informe um nome para pesquisar')
else:
vsql = 'SELECT * FROM tb_contatos WHERE t_nome LIKE "%'+vnome+'%"'
po.execute(vsql)
vreg = po.fetchall()
# - Limpar os dados da TreeView:
limpatv(inf)
for i in vreg:
reg = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]]
tv.insert('', 'end', values=reg)
except Error as err:
messagebox.showerror('ATENÇÃO ERRO', err)
finally:
# > Limpando a caixa de texto e fechando o banco de dados:
txtnome1.delete(0, END)
vcon.close() # _ fecha a conexão
return
def exibir(inf):
"""
#### Abre um banco de dados Agenda.db, seleciona os registros da tabela tb_contatos e os exibe na tela da TreeView
:param inf: informa o nome da Treeview
"""
vcon = agenda() # - Abrindo o banco de dados
# - Limpando a tela da TreeView antes de mostrar os dados:
limpatv(inf)
try:
# *- ****** Inserindo os dados na Treeview: ******
# * Os dados da Treeview serão os registro da tabela tb_contatos do banco de dados Agenda.db
# *- Abrindo o banco de dados:
vcon = agenda()
c = vcon.cursor() # _ criar um cursor para receber a conexão
# * execução da consulta (query) pelo cursor:
c.execute('select * from tb_contatos')
res = c.fetchall() # _ criar uma lista contendo todos os registros da tabela tb_contatos
vcon.close() # _ fechar a conexão
except Error as err:
messagebox.showerror('ATENÇÃO ERRO', err)
finally:
# - Inserindo (exibir) os registros na Treeview:
for i in res:
treev.insert('', 'end', values=[i[0], i[1],
i[2], i[3], i[4], i[5], i[6], i[7]])
return
def dml(tipo: str): # query = consulta
"""
#### Abre um banco de dados e realiza alterações nos seus registros.
:param tipo: informa o tipo de consulta, se excluir ou atualizar
"""
vID = record[0]
try:
res = messagebox.askquestion('CONFIRMAR', 'Deseja continuar?')
vcon = agenda() # abrir a conexão
if tipo == 'excluir': #_ Excluir o registro
if res == 'yes':
consulta = f'DELETE FROM tb_contatos WHERE n_id = {vID}'
c = vcon.cursor() # criar um cursor para receber a conexão
c.execute(consulta) # execução da consulta (query) pelo cursor
elif tipo == 'editar': #_ Editar o registro
nome = txtnome.get()
fone = txtfone.get()
mail = txtmail.get()
end = txtend.get()
cid = txtcid.get()
uf = txtuf.get()
obs = txtobs.get(1.0, END)
if res == 'yes':
consulta = f'UPDATE tb_contatos SET t_nome = "{nome}", t_fone = "{fone}", t_email= "{mail}", t_endereco= "{end}", t_cidade= "{cid}", t_uf = "{uf}", t_obs = "{obs}" WHERE n_id = {vID}'
c = vcon.cursor() # criar um cursor para receber a conexão
c.execute(consulta) # execução da consulta (query) pelo cursor
except Error as err:
print(f'ATENÇÃO ERRO: {err}')
finally:
vcon.commit() # confirmação dos dados que foram manipulados
vcon.close() # fechar a conexão
atualiza()
btninser.config(state='normal')
btnedita.config(state='disabled')
btnexclui.config(state='disabled')
txtnome.focus()
return
def atualiza():
limpatxt()
exibir(treev)
return
def item_selected(evento):
global vID, record
for selected_item in treev.selection():
btninser.config(state='disabled')
btnedita.config(state='normal')
btnexclui.config(state='normal')
item = treev.item(selected_item) # dictionary
record = item['values'] # list
limpatxt()
vID = record[0]
txtnome.insert(0, record[1])
txtfone.insert(0, record[2])
txtmail.insert(0, record[3])
txtend.insert(0, record[4])
txtcid.insert(0, record[5])
txtuf.insert(0, record[6])
txtobs.insert(END, record[7])
return
def limpatxt():
"""
#### Limpa os elementos Entry e Text do frame2
"""
txtnome.delete(0, END)
txtfone.delete(0, END)
txtmail.delete(0, END)
txtend.delete(0, END)
txtcid.delete(0, END)
txtuf.delete(0, END)
txtobs.delete(1.0, END)
return
def main():
pass
print("""
# > EXCLUIR/ EDITAR
# **Para Excluir e Editar verificar se poderemos usar a função dml(),
# **com algumas adaptações para isso.
# **Após excluir ou editar NÃO esquecer de limpar os campos da frame2.
# - Passo 1: Selecionar qual registro deverá ser excluído/editado!
# - Selecionando um registro:
# O registro que for selecionado na Treeview será vinculando(bind) e inserido nos elementos Entry e text do frame2 -> FEITO
# nos campos do contato da frame2, quando os botões Excluir e Editar forem habilitados o botão Inserir será desabilitado. -> FEITO
# Os botões de Excluir e Editar deverão passar para a frame2 -> FEITO
# Passo 2: Confirmar a exclusão/edição -> FEITO
# Passo 3: Excluir/editar o registro -> FEITO
# Passo 4: Limpar os elementos Entry e Text da frame2 -> FEITO
# Passo 5: Desabilitar os botões Excluir e Editar e habilitar o botão Inserir -> FEITO
# Passo 6: Atualizar a Treeview (treev) para mostrar as alterações realizadas -> FEITO
""")
return
if __name__ == '__main__':
main() | projetos/Agenda/libagenda.py |
from tkinter import *
from tkinter import ttk, messagebox
from sqlite3 import Error, connect
import os
def agenda():
"""
#### Estabelece a conexão com o banco de dados Agenda.db
"""
dirdb = os.path.dirname(__file__)
nomedb = dirdb + '/Agenda.db'
con = connect(nomedb)
return con
def limpatv(par):
"""
#### Função para limpar a tela da TreeView antes de mostrar os dados
:param par: informa o nome da TreeView
"""
treev = par
treev.delete(*treev.get_children())
"""
* OU:
for i in treev.get_children():
treev.delete(i)
"""
def tvw(master):
"""
Gera a Treeview que exibe os registros da tabela tb_contatos
do banco de dados Agenda.db
:param master: objeto pai da Treeview
"""
tela = master
global treev
# _Treeview:
# *- ****** Definindo as colunas ******
colunas = ('id', 'nome', 'telefone', 'e-mail',
'endereco', 'cidade', 'estado', 'observacao')
treev = ttk.Treeview(tela, columns=colunas,
show='headings', padding=(1, 1))
# *- ****** Definindo os cabeçalhos das colunas ******
treev.heading('id', text='ID')
treev.heading('nome', text='Nome')
treev.heading('telefone', text='Telefone')
treev.heading('e-mail', text='Email')
treev.heading('endereco', text='Endereço')
treev.heading('cidade', text='Cidade')
treev.heading('estado', text='UF')
treev.heading('observacao', text='Nota')
# *- Adicionando uma scrollbar:
scrollbarv = ttk.Scrollbar(tela, orient=[VERTICAL], command=treev.yview)
scrollbarh = ttk.Scrollbar(
tela, orient=[HORIZONTAL], command=treev.xview)
treev.configure(yscroll=scrollbarv.set)
treev.configure(xscroll=scrollbarh.set)
# *- ***** Definindo o tamanho das colunas *****
treev.column('id', width=35, minwidth=10, stretch=True, anchor=CENTER)
treev.column('nome', width=170, minwidth=0, stretch=True)
treev.column('telefone', width=115, minwidth=0, stretch=True)
treev.column('e-mail', width=150, minwidth=0, stretch=True)
treev.column('endereco', width=200, minwidth=0, stretch=True)
treev.column('cidade', width=100, minwidth=0, stretch=True)
treev.column('estado', width=35, minwidth=0, stretch=True, anchor=CENTER)
treev.column('observacao', width=235, minwidth=0, stretch=True)
# *- ****** Posicionando o elemento Treeview: ******
treev.grid(column=0, row=2, padx=True, pady=True)
scrollbarv.grid(row=2, column=1, sticky='ns')
scrollbarh.grid(row=3, column=0, sticky='ew')
# *- ****** Exibe os dados da tabela tb_contatos na Treeview: ******
exibir(treev)
# <Control-Button-1> <<TreeviewSelect>>
treev.bind('<<TreeviewSelect>>', item_selected)
return
def lfr2(master):
"""
#### Gera os elementos que serão posicionados no tela da tela principal
:param master: objeto pai da LabelFrame
"""
global txtnome, txtfone, txtmail, txtend, txtcid, txtuf, txtobs, lf2
global btninser, btnedita, btnexclui
lf2 = master
# teste = StringVar(tela, 'isto é um teste')
# _ Elementos label e texto (Entry):
# _ Elemento label:
lblnome = Label(lf2, text='Nome: ', width=8, anchor='w') # _ , bg='#0ff'
lblfone = Label(lf2, text='Telefone: ', width=8, anchor='w')
lblmail = Label(lf2, text='E-mail: ', width=8, anchor='w')
lblend = Label(lf2, text='Endereço: ', width=8, anchor='w')
lblcid = Label(lf2, text='Cidade: ', width=8, anchor='w')
lbluf = Label(lf2, text='UF: ', width=8, anchor='w')
lblobs = Label(lf2, text='Nota: ', width=4, anchor='w')
# _ Elemento texto (Entry):
txtnome = Entry(lf2, width=25, font=(
'Ebrima', 12), bd=1, justify='left') # coluna 1 , textvariable=teste
txtfone = Entry(lf2, width=15, font=(
'Ebrima', 12), bd=1, justify='left')
txtmail = Entry(lf2, width=25, font=(
'Ebrima', 12), bd=1, justify='left')
txtend = Entry(lf2, width=30, font=(
'Ebrima', 12), bd=1, justify='left') # coluna 3
txtcid = Entry(lf2, width=25, font=(
'Ebrima', 12), bd=1, justify='left')
txtuf = Entry(lf2, width=2, font=('Ebrima', 12), bd=1, justify='left')
txtobs = Text(lf2, width=29, height=4, font=(
'Ebrima', 12), bd=1) # coluna 5
reglist = [txtnome, txtfone, txtmail, txtend, txtcid, txtuf, txtobs]
# _ Elemento botão do LabelFrame:
btninser = Button(lf2, text='Inserir', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: inserir(reglist))
btnedita = Button(lf2, text='Editar', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: dml('editar'), state='disabled')
btnexclui = Button(lf2, text='Excluir', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: dml('excluir'), state='disabled')
btnreset = Button(lf2, text='Atualizar', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=atualiza)
# _ Posicionando os elementos dentro do LabelFrame:
lblnome.grid(column=0, row=1)
txtnome.grid(column=1, row=1, padx=5, pady=2, sticky='w')
lblfone.grid(column=0, row=2)
txtfone.grid(column=1, row=2, padx=5, pady=2, sticky='w')
lblmail.grid(column=0, row=3)
txtmail.grid(column=1, row=3, padx=5, pady=2, sticky='w')
lblend.grid(column=2, row=1)
txtend.grid(column=3, row=1, padx=5, pady=2, sticky='w')
lblcid.grid(column=2, row=2)
txtcid.grid(column=3, row=2, padx=5, pady=2, sticky='w')
lbluf.grid(column=2, row=3)
txtuf.grid(column=3, row=3, padx=5, pady=2, sticky='w')
lblobs.grid(column=4, row=1)
txtobs.grid(column=5, row=1, padx=5, pady=2, sticky='wn', rowspan=3)
btninser.grid(column=1, row=4, pady=5)
btnedita.grid(column=3, row=4, padx=2.5)
btnexclui.grid(column=5, row=4, padx=5)
btnreset.grid(column=3, row=5, padx=5, pady=10)
return
def lfr3(master):
"""
#### Gera os elementos que serão posicionados no tela da tela principal
:param master: objeto pai da LabelFrame
"""
lf3 = master
# * Elementos label e texto (Entry) do LabelFrame frame3:
# * Elemento label
lblnome1 = Label(lf3, text='Nome: ', width=5, anchor='w')
# -* Elemento texto (Entry) do LabelFrame frame3:
txtnome1 = Entry(lf3, width=30, font=('Ebrima, 12'), justify='left')
# -* Elemento botão do LabelFrame frame3:
btnpesq = Button(lf3, text='Pesquisar', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: pesquisa(treev, txtnome1))
btntudo = Button(lf3, text='Mostrar Tudo', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=lambda: exibir(treev)) # _ flat, groove, raised, ridge, solid, or sunken
btnsair = Button(lf3, text='Sair', width=10, bg='#b8b1e0',
font=('', '10', 'bold'), cursor='hand1', border=3, relief='raised', command=sair)
# -* Posicionando os elementos dentro do frame3:
lblnome1.grid(column=0, row=0, padx=5)
txtnome1.grid(column=1, row=0, padx=5, sticky='w')
btnpesq.grid(column=2, row=0, padx=10, pady=10)
btntudo.grid(column=3, row=0, padx=5, pady=10)
btnsair.grid(column=6, row=0, padx=10, pady=10)
return
def inserir(val: list):
"""
#### Função para inserir um novo registro na tabela do banco de dados
:param val: lista contendo os registro a serem inseridos na tabela tb_contatos do banco de dados Agenda.db
"""
txtnome = val[0]
txtfone = val[1]
txtmail = val[2]
txtend = val[3]
txtcid = val[4]
txtuf = val[5]
txtobs = val[6]
vcon = agenda() # * Abre o banco de dados
po = vcon.cursor() # * Definindo o cursor para receber a conexão
try:
if txtnome.get() == '' or txtfone.get() == '' or txtmail.get() == '':
# ** O formulário está em branco
messagebox.showerror(
'ATENÇÃO ERRO', 'Não foram informados os valores!')
else:
# > 3- Ler os dados inseridos do formulário
reg = f"""INSERT INTO tb_contatos
(t_nome, t_fone, t_email, t_endereco, t_cidade, t_uf, t_obs)
VALUES("{txtnome.get()}", "{txtfone.get()}", "{txtmail.get()}",
"{txtend.get()}", "{txtcid.get()}", "{txtuf.get().upper()}",
"{txtobs.get(1.0, END)}")
"""
# > 4- Inserir os dados do formulário na tabela do banco de dados e fazer o commit (atualizar o banco de dados)
po.execute(reg)
vcon.commit()
messagebox.showinfo('AVISO', 'Registro inserido com sucesso!')
except Error as err:
messagebox.showerror('ATENÇÃO ERRO', err)
finally:
# > 5- Limpando os dados do formulário e fechando o banco de
limpatxt()
txtnome.focus()
vcon.close() # _ fecha a conexão
return
def sair():
"""
#### Encerra o aplicativo
"""
os.system('clear')
exit()
return
def pesquisa(inf, txt):
"""
#### Executa uma pesquisa no banco de dados por um nome e mostra na TreeView
:param inf: informa o nome da Treeview
:param txt: informa o nome para a pesquisa
"""
tv = inf
txtnome1 = txt
# > Conectando o banco de dados:
vcon = agenda()
po = vcon.cursor()
vnome = txtnome1.get()
try:
# _ Conulta por nome:
if vnome == '':
messagebox.showerror(
'ATENÇÃO ERRO', 'Informe um nome para pesquisar')
else:
vsql = 'SELECT * FROM tb_contatos WHERE t_nome LIKE "%'+vnome+'%"'
po.execute(vsql)
vreg = po.fetchall()
# - Limpar os dados da TreeView:
limpatv(inf)
for i in vreg:
reg = [i[0], i[1], i[2], i[3], i[4], i[5], i[6], i[7]]
tv.insert('', 'end', values=reg)
except Error as err:
messagebox.showerror('ATENÇÃO ERRO', err)
finally:
# > Limpando a caixa de texto e fechando o banco de dados:
txtnome1.delete(0, END)
vcon.close() # _ fecha a conexão
return
def exibir(inf):
"""
#### Abre um banco de dados Agenda.db, seleciona os registros da tabela tb_contatos e os exibe na tela da TreeView
:param inf: informa o nome da Treeview
"""
vcon = agenda() # - Abrindo o banco de dados
# - Limpando a tela da TreeView antes de mostrar os dados:
limpatv(inf)
try:
# *- ****** Inserindo os dados na Treeview: ******
# * Os dados da Treeview serão os registro da tabela tb_contatos do banco de dados Agenda.db
# *- Abrindo o banco de dados:
vcon = agenda()
c = vcon.cursor() # _ criar um cursor para receber a conexão
# * execução da consulta (query) pelo cursor:
c.execute('select * from tb_contatos')
res = c.fetchall() # _ criar uma lista contendo todos os registros da tabela tb_contatos
vcon.close() # _ fechar a conexão
except Error as err:
messagebox.showerror('ATENÇÃO ERRO', err)
finally:
# - Inserindo (exibir) os registros na Treeview:
for i in res:
treev.insert('', 'end', values=[i[0], i[1],
i[2], i[3], i[4], i[5], i[6], i[7]])
return
def dml(tipo: str): # query = consulta
"""
#### Abre um banco de dados e realiza alterações nos seus registros.
:param tipo: informa o tipo de consulta, se excluir ou atualizar
"""
vID = record[0]
try:
res = messagebox.askquestion('CONFIRMAR', 'Deseja continuar?')
vcon = agenda() # abrir a conexão
if tipo == 'excluir': #_ Excluir o registro
if res == 'yes':
consulta = f'DELETE FROM tb_contatos WHERE n_id = {vID}'
c = vcon.cursor() # criar um cursor para receber a conexão
c.execute(consulta) # execução da consulta (query) pelo cursor
elif tipo == 'editar': #_ Editar o registro
nome = txtnome.get()
fone = txtfone.get()
mail = txtmail.get()
end = txtend.get()
cid = txtcid.get()
uf = txtuf.get()
obs = txtobs.get(1.0, END)
if res == 'yes':
consulta = f'UPDATE tb_contatos SET t_nome = "{nome}", t_fone = "{fone}", t_email= "{mail}", t_endereco= "{end}", t_cidade= "{cid}", t_uf = "{uf}", t_obs = "{obs}" WHERE n_id = {vID}'
c = vcon.cursor() # criar um cursor para receber a conexão
c.execute(consulta) # execução da consulta (query) pelo cursor
except Error as err:
print(f'ATENÇÃO ERRO: {err}')
finally:
vcon.commit() # confirmação dos dados que foram manipulados
vcon.close() # fechar a conexão
atualiza()
btninser.config(state='normal')
btnedita.config(state='disabled')
btnexclui.config(state='disabled')
txtnome.focus()
return
def atualiza():
limpatxt()
exibir(treev)
return
def item_selected(evento):
global vID, record
for selected_item in treev.selection():
btninser.config(state='disabled')
btnedita.config(state='normal')
btnexclui.config(state='normal')
item = treev.item(selected_item) # dictionary
record = item['values'] # list
limpatxt()
vID = record[0]
txtnome.insert(0, record[1])
txtfone.insert(0, record[2])
txtmail.insert(0, record[3])
txtend.insert(0, record[4])
txtcid.insert(0, record[5])
txtuf.insert(0, record[6])
txtobs.insert(END, record[7])
return
def limpatxt():
"""
#### Limpa os elementos Entry e Text do frame2
"""
txtnome.delete(0, END)
txtfone.delete(0, END)
txtmail.delete(0, END)
txtend.delete(0, END)
txtcid.delete(0, END)
txtuf.delete(0, END)
txtobs.delete(1.0, END)
return
def main():
pass
print("""
# > EXCLUIR/ EDITAR
# **Para Excluir e Editar verificar se poderemos usar a função dml(),
# **com algumas adaptações para isso.
# **Após excluir ou editar NÃO esquecer de limpar os campos da frame2.
# - Passo 1: Selecionar qual registro deverá ser excluído/editado!
# - Selecionando um registro:
# O registro que for selecionado na Treeview será vinculando(bind) e inserido nos elementos Entry e text do frame2 -> FEITO
# nos campos do contato da frame2, quando os botões Excluir e Editar forem habilitados o botão Inserir será desabilitado. -> FEITO
# Os botões de Excluir e Editar deverão passar para a frame2 -> FEITO
# Passo 2: Confirmar a exclusão/edição -> FEITO
# Passo 3: Excluir/editar o registro -> FEITO
# Passo 4: Limpar os elementos Entry e Text da frame2 -> FEITO
# Passo 5: Desabilitar os botões Excluir e Editar e habilitar o botão Inserir -> FEITO
# Passo 6: Atualizar a Treeview (treev) para mostrar as alterações realizadas -> FEITO
""")
return
if __name__ == '__main__':
main() | 0.485844 | 0.192444 |
# reference about how f2py and cython modules coexists:
# https://stackoverflow.com/questions/7932028/setup-py-for-packages-that-depend-on-both-cython-and-f2py
from setuptools import setup
import numpy as np
try:
from Cython.Build import cythonize
dynprog_ext_modules = cythonize(['graphflow/pagerank/cpagerank.pyx'])
except ImportError:
from setuptools import Extension
dynprog_ext_modules = [Extension('graphflow.pagerank.cpagerank',
sources=['graphflow/pagerank/cpagerank.c'])]
def readme():
with open('README.md') as f:
return f.read()
def install_requirements():
return [package_string.strip() for package_string in open('requirements.txt', 'r')]
setup(name='graphflow',
version="0.4.3",
description="Algorithms for Graph Flow Analysis",
long_description="Numerical routines for analyzing data represented by graphs",
classifiers=[
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Scientific/Engineering :: Mathematics",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Cython",
"Programming Language :: C",
"License :: OSI Approved :: MIT License",
],
keywords="Algorithms for Graph Flow Analysis",
url="https://github.com/stephenhky/GraphFlow",
author="<NAME>",
author_email="<EMAIL>",
license='MIT',
packages=['graphflow',
'graphflow.pagerank',
'graphflow.simvoltage',
'graphflow.hits'],
package_data={'graphflow': ['pagerank/*.f90', 'pagerank/*.pyf',
'pagerank/*.c', 'pagerank/*.pyx'],
'test': ['*.csv']},
setup_requires=['numpy', 'Cython'],
install_requires=install_requirements(),
tests_require=[
'pandas',
],
include_dirs=[np.get_include()],
ext_modules=dynprog_ext_modules,
include_package_data=True,
test_suite="test",
zip_safe=False) | setup.py |
# reference about how f2py and cython modules coexists:
# https://stackoverflow.com/questions/7932028/setup-py-for-packages-that-depend-on-both-cython-and-f2py
from setuptools import setup
import numpy as np
try:
from Cython.Build import cythonize
dynprog_ext_modules = cythonize(['graphflow/pagerank/cpagerank.pyx'])
except ImportError:
from setuptools import Extension
dynprog_ext_modules = [Extension('graphflow.pagerank.cpagerank',
sources=['graphflow/pagerank/cpagerank.c'])]
def readme():
with open('README.md') as f:
return f.read()
def install_requirements():
return [package_string.strip() for package_string in open('requirements.txt', 'r')]
setup(name='graphflow',
version="0.4.3",
description="Algorithms for Graph Flow Analysis",
long_description="Numerical routines for analyzing data represented by graphs",
classifiers=[
"Topic :: Scientific/Engineering :: Artificial Intelligence",
"Topic :: Scientific/Engineering :: Mathematics",
"Topic :: Software Development :: Libraries :: Python Modules",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Cython",
"Programming Language :: C",
"License :: OSI Approved :: MIT License",
],
keywords="Algorithms for Graph Flow Analysis",
url="https://github.com/stephenhky/GraphFlow",
author="<NAME>",
author_email="<EMAIL>",
license='MIT',
packages=['graphflow',
'graphflow.pagerank',
'graphflow.simvoltage',
'graphflow.hits'],
package_data={'graphflow': ['pagerank/*.f90', 'pagerank/*.pyf',
'pagerank/*.c', 'pagerank/*.pyx'],
'test': ['*.csv']},
setup_requires=['numpy', 'Cython'],
install_requires=install_requirements(),
tests_require=[
'pandas',
],
include_dirs=[np.get_include()],
ext_modules=dynprog_ext_modules,
include_package_data=True,
test_suite="test",
zip_safe=False) | 0.732018 | 0.37734 |
from selenium import webdriver
import threading
import queue
import time
import requests
import json
import pymongo
song_hash_queue = queue.Queue()
ROOT_URL = 'http://www.kugou.com/yy/special/index/1-3-0.html'
PLAY_URL = 'http://www.kugou.com/yy/index.php?r=play/getdata&hash=' #1FF3CB3D374E44AAC3AC98BE047748E3
SHOW_BROWSER = True
SAVE_TO_DB = False
class Fetch_Song_Hash_From_Rank(threading.Thread):
rank_list = []
browser = None
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self._search_rank()
self._search_hash()
def _search_hash(self):
for rank in self.rank_list:
print('搜索:' + rank['name'] + '的hash')
self.browser.get(rank['url'])
song_links = self.browser.find_elements_by_css_selector('#songs li a')
for link in song_links:
song = {
"name": link.get_attribute('title'),
"hash": str.split(link.get_attribute('data'), '|')[0]
}
song_hash_queue.put(song)
print('搜索hash结束')
def _search_rank(self):
global song_hash_queue
global ROOT_URL
if SHOW_BROWSER:
self.browser = webdriver.Chrome()
else:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
self.browser = webdriver.Chrome(chrome_options=chrome_options)
self.browser.get(ROOT_URL)
ranks = self.browser.find_elements_by_css_selector('.detail strong a')
print('搜索所有排行榜')
for rank in ranks:
temp = {
"name": rank.get_attribute('title'),
"url": rank.get_attribute('href')
}
self.rank_list.append(temp)
print('搜索排行榜结束')
class Fetch_Song_Data_From_Hash(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self._connect_db()
self._search_song_from_hash()
def _connect_db(self):
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.kugou
self.collection = db.songs
def _search_song_from_hash(self):
global song_hash_queue
global PLAY_URL
global SAVE_TO_DB
song = song_hash_queue.get()
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'
}
if song:
print('正在搜索: <' + song['name'] + '>的信息')
response = requests.get(PLAY_URL + song['hash'], headers=headers)
song_obj = response.json()['data']
with open('../output/kugou/songs.txt', 'a', encoding='utf-8') as song_file:
json.dump(song_obj, song_file, ensure_ascii=False)
song_file.write('\n')
if SAVE_TO_DB:
self.collection.insert_one(song_obj)
print('搜索成功,正在保存')
self._search_song_from_hash()
if __name__ == '__main__':
t1 = Fetch_Song_Hash_From_Rank()
t1.start()
t2 = Fetch_Song_Data_From_Hash()
t2.start()
t1.join()
t2.join() | python_demo_v1/spider/spider_kugou_song.py | from selenium import webdriver
import threading
import queue
import time
import requests
import json
import pymongo
song_hash_queue = queue.Queue()
ROOT_URL = 'http://www.kugou.com/yy/special/index/1-3-0.html'
PLAY_URL = 'http://www.kugou.com/yy/index.php?r=play/getdata&hash=' #1FF3CB3D374E44AAC3AC98BE047748E3
SHOW_BROWSER = True
SAVE_TO_DB = False
class Fetch_Song_Hash_From_Rank(threading.Thread):
rank_list = []
browser = None
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self._search_rank()
self._search_hash()
def _search_hash(self):
for rank in self.rank_list:
print('搜索:' + rank['name'] + '的hash')
self.browser.get(rank['url'])
song_links = self.browser.find_elements_by_css_selector('#songs li a')
for link in song_links:
song = {
"name": link.get_attribute('title'),
"hash": str.split(link.get_attribute('data'), '|')[0]
}
song_hash_queue.put(song)
print('搜索hash结束')
def _search_rank(self):
global song_hash_queue
global ROOT_URL
if SHOW_BROWSER:
self.browser = webdriver.Chrome()
else:
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument('--headless')
self.browser = webdriver.Chrome(chrome_options=chrome_options)
self.browser.get(ROOT_URL)
ranks = self.browser.find_elements_by_css_selector('.detail strong a')
print('搜索所有排行榜')
for rank in ranks:
temp = {
"name": rank.get_attribute('title'),
"url": rank.get_attribute('href')
}
self.rank_list.append(temp)
print('搜索排行榜结束')
class Fetch_Song_Data_From_Hash(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
self._connect_db()
self._search_song_from_hash()
def _connect_db(self):
client = pymongo.MongoClient(host='localhost', port=27017)
db = client.kugou
self.collection = db.songs
def _search_song_from_hash(self):
global song_hash_queue
global PLAY_URL
global SAVE_TO_DB
song = song_hash_queue.get()
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.108 Safari/537.36'
}
if song:
print('正在搜索: <' + song['name'] + '>的信息')
response = requests.get(PLAY_URL + song['hash'], headers=headers)
song_obj = response.json()['data']
with open('../output/kugou/songs.txt', 'a', encoding='utf-8') as song_file:
json.dump(song_obj, song_file, ensure_ascii=False)
song_file.write('\n')
if SAVE_TO_DB:
self.collection.insert_one(song_obj)
print('搜索成功,正在保存')
self._search_song_from_hash()
if __name__ == '__main__':
t1 = Fetch_Song_Hash_From_Rank()
t1.start()
t2 = Fetch_Song_Data_From_Hash()
t2.start()
t1.join()
t2.join() | 0.253676 | 0.047206 |
def transcript(input_lang, output_lang, word, engine):
if input_lang=="en" and output_lang=="ru":
print("In future.")
if input_lang=="ru" and output_lang=="en":
new_word_letters=[]
word_chars=list(word)
if engine=="2":
for letter in word_chars:
if letter=='а':
new_word_letters.append('a')
if letter=='б':
new_word_letters.append('b')
if letter=='в':
new_word_letters.append('v')
if letter=='г':
new_word_letters.append('g')
if letter=='д':
new_word_letters.append('d')
if letter=='е':
new_word_letters.append('e')
if letter=='ё':
new_word_letters.append('jo')
if letter=='ж':
new_word_letters.append('zh')
if letter=='з':
new_word_letters.append('z')
if letter=='и':
new_word_letters.append('i')
if letter=='й':
new_word_letters.append('i')
if letter=='к':
new_word_letters.append('k')
if letter=='л':
new_word_letters.append('l')
if letter=='м':
new_word_letters.append('m')
if letter=='н':
new_word_letters.append('n')
if letter=='о':
new_word_letters.append('o')
if letter=='п':
new_word_letters.append('p')
if letter=='р':
new_word_letters.append('r')
if letter=='с':
new_word_letters.append('s')
if letter=='т':
new_word_letters.append('t')
if letter=='у':
new_word_letters.append('u')
if letter=='ф':
new_word_letters.append('f')
if letter=='х':
new_word_letters.append('x')
if letter=='ц':
new_word_letters.append('c')
if letter=='ч':
new_word_letters.append('ch')
if letter=='ш':
new_word_letters.append('sh')
if letter=='щ':
new_word_letters.append('sh')
if letter=='ъ':
new_word_letters.append('"')
if letter=='ы':
new_word_letters.append('i')
if letter=='ь':
new_word_letters.append("'")
if letter=='э':
new_word_letters.append('e')
if letter=='ю':
new_word_letters.append('ju')
if letter=='я':
new_word_letters.append('ja')
if letter==' ':
new_word_letters.append(' ')
new_word = ''.join(new_word_letters)
return(new_word)
if engine=="1":
ru_to_en={
'а':'a',
'б':'b',
'в':'v',
'г':'g',
'д':'d',
'е':'e',
'ё':'jo',
'ж':'zh',
'з':'z',
'и':'i',
'й':'i',
'к':'k',
'л':'l',
'м':'m',
'н':'n',
'о':'o',
'п':'p',
'р':'r',
'с':'s',
'т':'t',
'у':'u',
'ф':'f',
'х':'x',
'ц':'c',
'ч':'ch',
'ш':'sh',
'щ':'sh',
'ъ':'"',
'ы':'i',
'ь':"'",
'э':'e',
'ю':'ju',
'я':'ja',
' ':' '
}
def encrypt(word):
cipher = ''
for letter in word:
if letter != ' ':
cipher += ru_to_en[letter]
else:
cipher += ' '
return cipher
print(encrypt(word)) | res/transcriptor.py | def transcript(input_lang, output_lang, word, engine):
if input_lang=="en" and output_lang=="ru":
print("In future.")
if input_lang=="ru" and output_lang=="en":
new_word_letters=[]
word_chars=list(word)
if engine=="2":
for letter in word_chars:
if letter=='а':
new_word_letters.append('a')
if letter=='б':
new_word_letters.append('b')
if letter=='в':
new_word_letters.append('v')
if letter=='г':
new_word_letters.append('g')
if letter=='д':
new_word_letters.append('d')
if letter=='е':
new_word_letters.append('e')
if letter=='ё':
new_word_letters.append('jo')
if letter=='ж':
new_word_letters.append('zh')
if letter=='з':
new_word_letters.append('z')
if letter=='и':
new_word_letters.append('i')
if letter=='й':
new_word_letters.append('i')
if letter=='к':
new_word_letters.append('k')
if letter=='л':
new_word_letters.append('l')
if letter=='м':
new_word_letters.append('m')
if letter=='н':
new_word_letters.append('n')
if letter=='о':
new_word_letters.append('o')
if letter=='п':
new_word_letters.append('p')
if letter=='р':
new_word_letters.append('r')
if letter=='с':
new_word_letters.append('s')
if letter=='т':
new_word_letters.append('t')
if letter=='у':
new_word_letters.append('u')
if letter=='ф':
new_word_letters.append('f')
if letter=='х':
new_word_letters.append('x')
if letter=='ц':
new_word_letters.append('c')
if letter=='ч':
new_word_letters.append('ch')
if letter=='ш':
new_word_letters.append('sh')
if letter=='щ':
new_word_letters.append('sh')
if letter=='ъ':
new_word_letters.append('"')
if letter=='ы':
new_word_letters.append('i')
if letter=='ь':
new_word_letters.append("'")
if letter=='э':
new_word_letters.append('e')
if letter=='ю':
new_word_letters.append('ju')
if letter=='я':
new_word_letters.append('ja')
if letter==' ':
new_word_letters.append(' ')
new_word = ''.join(new_word_letters)
return(new_word)
if engine=="1":
ru_to_en={
'а':'a',
'б':'b',
'в':'v',
'г':'g',
'д':'d',
'е':'e',
'ё':'jo',
'ж':'zh',
'з':'z',
'и':'i',
'й':'i',
'к':'k',
'л':'l',
'м':'m',
'н':'n',
'о':'o',
'п':'p',
'р':'r',
'с':'s',
'т':'t',
'у':'u',
'ф':'f',
'х':'x',
'ц':'c',
'ч':'ch',
'ш':'sh',
'щ':'sh',
'ъ':'"',
'ы':'i',
'ь':"'",
'э':'e',
'ю':'ju',
'я':'ja',
' ':' '
}
def encrypt(word):
cipher = ''
for letter in word:
if letter != ' ':
cipher += ru_to_en[letter]
else:
cipher += ' '
return cipher
print(encrypt(word)) | 0.050647 | 0.169166 |
from shapely.geometry import Polygon
from shapely.geometry import Point, LineString
from shapely.geometry import MultiLineString
from shapely.ops import linemerge, split, nearest_points
from scipy.stats import multivariate_normal
import numpy as np
import geopandas as gpd
import pandas as pd
import json
from observations import TimelessGPSObservations
import fiona
import random
class GPSSimulator:
def __init__(self, state_space):
self.state_space = state_space
self.street_network = state_space.street_network
self.crs = state_space.street_network.edges_df.crs
def define_flow(self):
self.flow_dictionary = {}
for node in self.street_network.graph.nodes:
connected_nodes = self.street_network.graph[node]
rnum = np.random.uniform(0, 1, size=(len(connected_nodes),))
self.flow_dictionary[str(node)] = {
str(node): float(num) for node, num in zip(connected_nodes, rnum)
}
def load_flow(self, flow_path):
with open(flow_path, mode="rb") as f:
self.flow_dictionary = json.load(f)
def simulate_node_sequence(self, route_length):
starting_position = list(
random.choice(list(self.street_network.graph.edges.keys()))
)
random.shuffle(starting_position)
node_sequence = []
previous_node = starting_position[0]
current_node = starting_position[1]
length = 0
node_sequence.append(current_node)
while length < route_length:
connected_nodes = self.street_network.graph[current_node]
candidates = list(filter(lambda x: x != previous_node, connected_nodes))
if candidates == []:
candidates = [previous_node]
candidate_weights = [
self.flow_dictionary[str(current_node)][str(candidate)]
for candidate in candidates
]
ps = np.array(candidate_weights) / sum(candidate_weights)
next_node = np.random.choice(np.array(candidates), p=np.array(ps))
length += self.street_network.graph[current_node][next_node]["length"]
previous_node = current_node
current_node = next_node
node_sequence.append(current_node)
self.node_sequence = node_sequence
def simulate_gps_tracks(self, mps, frequency, sigma):
dpm = mps/frequency
measurement_edges = []
measurement_positions = []
measurement_edge_indices = []
initial_node = self.node_sequence[0]
initial_node_coords = list(self.street_network.point_lookup[initial_node].coords)[0]
measurement_edges.append(tuple(sorted([initial_node, self.node_sequence[1]])))
measurement_positions.append(Point([initial_node_coords[0], initial_node_coords[1]]))
counter = 0
remaining_space = 0
for previous_node, current_node in zip(self.node_sequence[:-1], self.node_sequence[1:]):
previous_node_coords = list(self.street_network.point_lookup[previous_node].coords)[0]
current_node_coords = list(self.street_network.point_lookup[current_node].coords)[0]
line = LineString([previous_node_coords, current_node_coords])
length = line.length
#Can move this far
available_space = length
#Need to be able to move this far
required_space = dpm - remaining_space
#Distance covered so far on segment
distance_covered = 0
while available_space >= required_space:
p = line.interpolate(distance_covered + required_space)
distance_covered += required_space
p_coords = list(p.coords)[0]
measurement_edges.append(tuple(sorted([previous_node, current_node])))
measurement_positions.append(Point([p_coords[0], p_coords[1]]))
measurement_edge_indices.append(counter)
available_space -= required_space
required_space = dpm
remaining_space = 0
remaining_space += available_space
counter += 1
self.positions = measurement_positions
self.measurement_edges = list(map(lambda x: tuple(sorted(x)), measurement_edges))
self.measurement_edge_indices = measurement_edge_indices
noise = [multivariate_normal.rvs(mean=np.array([0, 0]), cov=(sigma**2) * np.eye(2)) for _ in range(len(measurement_positions))]
observations = list(
map(lambda x: Point(x[0].x + x[1][0], x[0].y + x[1][1]), zip(measurement_positions, noise))
)
self.track = gpd.GeoSeries(observations, crs=self.crs)
def flow_to_transition_matrix(self, mps, polling_frequency):
f = polling_frequency
v = mps
states = self.state_space.states
state_ids = np.arange(len(states))
graph = self.street_network.graph
flow = self.flow_dictionary
state_to_id_dict = {state : state_id for state_id, state in zip(state_ids, states)}
distance_per_measurement = v/f
M = len(states)
P = np.zeros((M, M))
for segment_set, connection_set in states:
segment = tuple(segment_set)
connection = tuple(connection_set)
#Find the node present in both connection and segment
shared_node = set(segment).intersection(set(connection))
segment_length = graph[segment[0]][segment[1]]["length"]
#The node we move on from
departure_node = segment_set.difference(shared_node)
assert len(departure_node) == 1
#Convert to string, since flow is read from JSON and keys are strings.
departure_key = str(list(departure_node)[0])
#Nodes connected to the departure node
connected_keys = set(flow[departure_key].keys())
#The state we're moving on from
i = state_to_id_dict[(segment_set, connection_set)]
ws = []
if len(connected_keys) == 1:
#We've reached a dead end
deadend_key = departure_key
#We need to travel back and forth on dead end segment
num_self_transitions = (2*segment_length)/distance_per_measurement
#We must now depart from the shared node
new_departure_key = str(list(shared_node)[0])
#The connected keys are those nodes leading away from the shared node
new_connected_keys = set(flow[new_departure_key].keys())
#Extracting the weights from flow dictionary
for key in new_connected_keys.difference(set([deadend_key])):
ws.append(flow[new_departure_key][key])
ws.append(num_self_transitions*sum(ws))
#Scaling to sum to one
ps = np.array(ws)/np.sum(ws)
#Finding the states we can move on to
for n, key in enumerate(new_connected_keys.difference(set([deadend_key]))):
j = state_to_id_dict[(frozenset([int(new_departure_key), int(key)]), (segment_set))]
#Setting the probabilities
P[i, j] = ps[n]
P[i, i] = ps[-1]
else:
#Expected number of transitions to same state
num_self_transitions = segment_length/distance_per_measurement
#Extracting the weights from flow dictionary
for key in connected_keys.difference(set(map(str, shared_node))):
ws.append(flow[departure_key][key])
ws.append(num_self_transitions*sum(ws))
#Scaling to sum to one
ps = np.array(ws)/sum(ws)
#Finding the states we can move on to
for n, key in enumerate(connected_keys.difference(set(map(str, shared_node)))):
j = state_to_id_dict[(frozenset([int(departure_key), int(key)]), (segment_set))]
#Setting the probabilities
P[i, j] = ps[n]
P[i, i] = ps[-1]
return P
def get_gps_observation(self):
x = self.track.map(lambda x: x.x)
y = self.track.map(lambda x: x.y)
df = pd.DataFrame({"x": x, "y": y})
return TimelessGPSObservations(df, "x", "y", self.crs, self.crs)
@property
def edge_sequence(self):
return [
tuple(sorted([i, j]))
for i, j in zip(self.node_sequence[:-1], self.node_sequence[1:])
]
@property
def gdf(self):
return self.street_network.edges_df[
self.street_network.edges_df.node_set.isin(self.edge_sequence)
] | tmmpy/track_simulation.py | from shapely.geometry import Polygon
from shapely.geometry import Point, LineString
from shapely.geometry import MultiLineString
from shapely.ops import linemerge, split, nearest_points
from scipy.stats import multivariate_normal
import numpy as np
import geopandas as gpd
import pandas as pd
import json
from observations import TimelessGPSObservations
import fiona
import random
class GPSSimulator:
def __init__(self, state_space):
self.state_space = state_space
self.street_network = state_space.street_network
self.crs = state_space.street_network.edges_df.crs
def define_flow(self):
self.flow_dictionary = {}
for node in self.street_network.graph.nodes:
connected_nodes = self.street_network.graph[node]
rnum = np.random.uniform(0, 1, size=(len(connected_nodes),))
self.flow_dictionary[str(node)] = {
str(node): float(num) for node, num in zip(connected_nodes, rnum)
}
def load_flow(self, flow_path):
with open(flow_path, mode="rb") as f:
self.flow_dictionary = json.load(f)
def simulate_node_sequence(self, route_length):
starting_position = list(
random.choice(list(self.street_network.graph.edges.keys()))
)
random.shuffle(starting_position)
node_sequence = []
previous_node = starting_position[0]
current_node = starting_position[1]
length = 0
node_sequence.append(current_node)
while length < route_length:
connected_nodes = self.street_network.graph[current_node]
candidates = list(filter(lambda x: x != previous_node, connected_nodes))
if candidates == []:
candidates = [previous_node]
candidate_weights = [
self.flow_dictionary[str(current_node)][str(candidate)]
for candidate in candidates
]
ps = np.array(candidate_weights) / sum(candidate_weights)
next_node = np.random.choice(np.array(candidates), p=np.array(ps))
length += self.street_network.graph[current_node][next_node]["length"]
previous_node = current_node
current_node = next_node
node_sequence.append(current_node)
self.node_sequence = node_sequence
def simulate_gps_tracks(self, mps, frequency, sigma):
dpm = mps/frequency
measurement_edges = []
measurement_positions = []
measurement_edge_indices = []
initial_node = self.node_sequence[0]
initial_node_coords = list(self.street_network.point_lookup[initial_node].coords)[0]
measurement_edges.append(tuple(sorted([initial_node, self.node_sequence[1]])))
measurement_positions.append(Point([initial_node_coords[0], initial_node_coords[1]]))
counter = 0
remaining_space = 0
for previous_node, current_node in zip(self.node_sequence[:-1], self.node_sequence[1:]):
previous_node_coords = list(self.street_network.point_lookup[previous_node].coords)[0]
current_node_coords = list(self.street_network.point_lookup[current_node].coords)[0]
line = LineString([previous_node_coords, current_node_coords])
length = line.length
#Can move this far
available_space = length
#Need to be able to move this far
required_space = dpm - remaining_space
#Distance covered so far on segment
distance_covered = 0
while available_space >= required_space:
p = line.interpolate(distance_covered + required_space)
distance_covered += required_space
p_coords = list(p.coords)[0]
measurement_edges.append(tuple(sorted([previous_node, current_node])))
measurement_positions.append(Point([p_coords[0], p_coords[1]]))
measurement_edge_indices.append(counter)
available_space -= required_space
required_space = dpm
remaining_space = 0
remaining_space += available_space
counter += 1
self.positions = measurement_positions
self.measurement_edges = list(map(lambda x: tuple(sorted(x)), measurement_edges))
self.measurement_edge_indices = measurement_edge_indices
noise = [multivariate_normal.rvs(mean=np.array([0, 0]), cov=(sigma**2) * np.eye(2)) for _ in range(len(measurement_positions))]
observations = list(
map(lambda x: Point(x[0].x + x[1][0], x[0].y + x[1][1]), zip(measurement_positions, noise))
)
self.track = gpd.GeoSeries(observations, crs=self.crs)
def flow_to_transition_matrix(self, mps, polling_frequency):
f = polling_frequency
v = mps
states = self.state_space.states
state_ids = np.arange(len(states))
graph = self.street_network.graph
flow = self.flow_dictionary
state_to_id_dict = {state : state_id for state_id, state in zip(state_ids, states)}
distance_per_measurement = v/f
M = len(states)
P = np.zeros((M, M))
for segment_set, connection_set in states:
segment = tuple(segment_set)
connection = tuple(connection_set)
#Find the node present in both connection and segment
shared_node = set(segment).intersection(set(connection))
segment_length = graph[segment[0]][segment[1]]["length"]
#The node we move on from
departure_node = segment_set.difference(shared_node)
assert len(departure_node) == 1
#Convert to string, since flow is read from JSON and keys are strings.
departure_key = str(list(departure_node)[0])
#Nodes connected to the departure node
connected_keys = set(flow[departure_key].keys())
#The state we're moving on from
i = state_to_id_dict[(segment_set, connection_set)]
ws = []
if len(connected_keys) == 1:
#We've reached a dead end
deadend_key = departure_key
#We need to travel back and forth on dead end segment
num_self_transitions = (2*segment_length)/distance_per_measurement
#We must now depart from the shared node
new_departure_key = str(list(shared_node)[0])
#The connected keys are those nodes leading away from the shared node
new_connected_keys = set(flow[new_departure_key].keys())
#Extracting the weights from flow dictionary
for key in new_connected_keys.difference(set([deadend_key])):
ws.append(flow[new_departure_key][key])
ws.append(num_self_transitions*sum(ws))
#Scaling to sum to one
ps = np.array(ws)/np.sum(ws)
#Finding the states we can move on to
for n, key in enumerate(new_connected_keys.difference(set([deadend_key]))):
j = state_to_id_dict[(frozenset([int(new_departure_key), int(key)]), (segment_set))]
#Setting the probabilities
P[i, j] = ps[n]
P[i, i] = ps[-1]
else:
#Expected number of transitions to same state
num_self_transitions = segment_length/distance_per_measurement
#Extracting the weights from flow dictionary
for key in connected_keys.difference(set(map(str, shared_node))):
ws.append(flow[departure_key][key])
ws.append(num_self_transitions*sum(ws))
#Scaling to sum to one
ps = np.array(ws)/sum(ws)
#Finding the states we can move on to
for n, key in enumerate(connected_keys.difference(set(map(str, shared_node)))):
j = state_to_id_dict[(frozenset([int(departure_key), int(key)]), (segment_set))]
#Setting the probabilities
P[i, j] = ps[n]
P[i, i] = ps[-1]
return P
def get_gps_observation(self):
x = self.track.map(lambda x: x.x)
y = self.track.map(lambda x: x.y)
df = pd.DataFrame({"x": x, "y": y})
return TimelessGPSObservations(df, "x", "y", self.crs, self.crs)
@property
def edge_sequence(self):
return [
tuple(sorted([i, j]))
for i, j in zip(self.node_sequence[:-1], self.node_sequence[1:])
]
@property
def gdf(self):
return self.street_network.edges_df[
self.street_network.edges_df.node_set.isin(self.edge_sequence)
] | 0.667039 | 0.539832 |
from itertools import chain
from typing import List
# Scikit-optimize has a wide range of useful sampling functions, see below link
# https://scikit-optimize.github.io/stable/auto_examples/sampler/initial-sampling-method.html
import skopt
import pygosolnp
# The Sampling class is an abstract class that can be inherited and customized as you please
class GridSampling(pygosolnp.sampling.Sampling):
def __init__(self,
parameter_lower_bounds: List[float],
parameter_upper_bounds: List[float],
seed):
self.__space = skopt.space.Space(dimensions=zip(parameter_lower_bounds, parameter_upper_bounds))
self.__seed = seed
def generate_all_samples(self, number_of_samples: int, sample_size: int) -> List[float]:
# Overwrite this function to define the behavior when generating starting guesses for all samples
# By default it calls `generate_sample` number_of_samples times, however we customize it here
grid = skopt.sampler.Grid()
grid_values = grid.generate(dimensions=self.__space.dimensions,
n_samples=number_of_samples,
random_state=self.__seed)
return list(chain.from_iterable(grid_values))
def generate_sample(self, sample_size: int) -> List[float]:
# This function is abstract in the base class
# Not needed since we are generating a grid for all samples, so overwrite it with pass
pass
# The Permutation Function has unique solution f(x) = 0 when x_i = i
def permutation_function(data):
n = 4
b = 0.5
result1 = 0
for index1 in range(1, n + 1):
result2 = 0
for index2 in range(1, n + 1):
result2 += ((pow(index2, index1) + b) * (pow(data[index2 - 1] / index2, index1) - 1))
result1 += pow(result2, 2)
return result1
parameter_lower_bounds = [-4.0] * 4
parameter_upper_bounds = [4.0] * 4
if __name__ == '__main__':
# Instantiate sampling object
sampling = GridSampling(
parameter_lower_bounds=parameter_lower_bounds,
parameter_upper_bounds=parameter_upper_bounds,
seed=92)
# Note that the seed variable to pygosolnp.solve is ignored due to the custom sampling
results = pygosolnp.solve(
obj_func=permutation_function,
par_lower_limit=parameter_lower_bounds,
par_upper_limit=parameter_upper_bounds,
number_of_restarts=6,
number_of_simulations=2000,
pysolnp_max_major_iter=25,
pysolnp_tolerance=1E-9,
start_guess_sampling=sampling)
print(results.best_solution)
# Best solution: [0.6222222222222218, 2.2222222222222223, 3.822222222222222, 3.2888888888888888]
# Objective function value: 9.91928145483169
# Not perfect, but much better than truncated normal! | python_examples/example_grid_sampling.py |
from itertools import chain
from typing import List
# Scikit-optimize has a wide range of useful sampling functions, see below link
# https://scikit-optimize.github.io/stable/auto_examples/sampler/initial-sampling-method.html
import skopt
import pygosolnp
# The Sampling class is an abstract class that can be inherited and customized as you please
class GridSampling(pygosolnp.sampling.Sampling):
def __init__(self,
parameter_lower_bounds: List[float],
parameter_upper_bounds: List[float],
seed):
self.__space = skopt.space.Space(dimensions=zip(parameter_lower_bounds, parameter_upper_bounds))
self.__seed = seed
def generate_all_samples(self, number_of_samples: int, sample_size: int) -> List[float]:
# Overwrite this function to define the behavior when generating starting guesses for all samples
# By default it calls `generate_sample` number_of_samples times, however we customize it here
grid = skopt.sampler.Grid()
grid_values = grid.generate(dimensions=self.__space.dimensions,
n_samples=number_of_samples,
random_state=self.__seed)
return list(chain.from_iterable(grid_values))
def generate_sample(self, sample_size: int) -> List[float]:
# This function is abstract in the base class
# Not needed since we are generating a grid for all samples, so overwrite it with pass
pass
# The Permutation Function has unique solution f(x) = 0 when x_i = i
def permutation_function(data):
n = 4
b = 0.5
result1 = 0
for index1 in range(1, n + 1):
result2 = 0
for index2 in range(1, n + 1):
result2 += ((pow(index2, index1) + b) * (pow(data[index2 - 1] / index2, index1) - 1))
result1 += pow(result2, 2)
return result1
parameter_lower_bounds = [-4.0] * 4
parameter_upper_bounds = [4.0] * 4
if __name__ == '__main__':
# Instantiate sampling object
sampling = GridSampling(
parameter_lower_bounds=parameter_lower_bounds,
parameter_upper_bounds=parameter_upper_bounds,
seed=92)
# Note that the seed variable to pygosolnp.solve is ignored due to the custom sampling
results = pygosolnp.solve(
obj_func=permutation_function,
par_lower_limit=parameter_lower_bounds,
par_upper_limit=parameter_upper_bounds,
number_of_restarts=6,
number_of_simulations=2000,
pysolnp_max_major_iter=25,
pysolnp_tolerance=1E-9,
start_guess_sampling=sampling)
print(results.best_solution)
# Best solution: [0.6222222222222218, 2.2222222222222223, 3.822222222222222, 3.2888888888888888]
# Objective function value: 9.91928145483169
# Not perfect, but much better than truncated normal! | 0.91376 | 0.665574 |
import unittest
from flask import json
from tests.base_test import BaseTest
from app import db
from app.model.chain_step import ChainStep
from app.model.questionnaires.chain_session_step import ChainSessionStep
class TestChainStep(BaseTest, unittest.TestCase):
def test_chain_step_basics(self):
self.construct_chain_step()
chain_step = db.session.query(ChainStep).first()
self.assertIsNotNone(chain_step)
rv = self.app.get('/api/chain_step/%i' % chain_step.id,
follow_redirects=True,
content_type="application/json", headers=self.logged_in_headers())
self.assert_success(rv)
response = json.loads(rv.get_data(as_text=True))
self.assertEqual(response["id"], chain_step.id)
def test_modify_chain_step_basics(self):
self.construct_chain_step()
chain_step = db.session.query(ChainStep).first()
self.assertIsNotNone(chain_step)
rv = self.app.get('/api/chain_step/%i' % chain_step.id, content_type="application/json", headers=self.logged_in_headers())
response = json.loads(rv.get_data(as_text=True))
response['instruction'] = 'Take out the trash'
rv = self.app.put('/api/chain_step/%i' % chain_step.id, data=self.jsonify(response), content_type="application/json",
follow_redirects=True, headers=self.logged_in_headers())
self.assert_success(rv)
db.session.commit()
rv = self.app.get('/api/chain_step/%i' % chain_step.id, content_type="application/json", headers=self.logged_in_headers())
self.assert_success(rv)
response = json.loads(rv.get_data(as_text=True))
self.assertEqual(response['instruction'], 'Take out the trash')
def test_delete_chain_step(self):
chain_step = self.construct_chain_step()
chain_step_id = chain_step.id
rv = self.app.get('api/chain_step/%i' % chain_step_id, content_type="application/json")
self.assert_success(rv)
rv = self.app.delete('api/chain_step/%i' % chain_step_id, content_type="application/json", headers=self.logged_in_headers())
self.assert_success(rv)
rv = self.app.get('api/chain_step/%i' % chain_step_id, content_type="application/json")
self.assertEqual(404, rv.status_code)
def test_disallow_deleting_chain_step_if_being_used(self):
chain_step = self.construct_chain_step()
chain_step_id = chain_step.id
db.session.add(ChainSessionStep(chain_step_id=chain_step_id))
db.session.commit()
rv = self.app.get('api/chain_step/%i' % chain_step_id, content_type="application/json")
self.assert_success(rv)
rv = self.app.delete('api/chain_step/%i' % chain_step_id, content_type="application/json", headers=self.logged_in_headers())
self.assertEqual(rv.status_code, 400)
self.assertEqual(rv.json['code'], 'can_not_delete')
def test_multiple_chain_steps(self):
chain_steps = self.construct_chain_steps()
self.assertEqual(4, len(chain_steps))
rv = self.app.get('/api/chain_step', follow_redirects=True, content_type="application/json",
headers=self.logged_in_headers())
self.assert_success(rv)
response = json.loads(rv.get_data(as_text=True))
self.assertEqual(len(chain_steps), len(response))
def test_export_chain_data(self):
chain_steps = self.construct_chain_steps()
for chain_step in chain_steps:
chain_step_id = chain_step.id
db.session.add(ChainSessionStep(chain_step_id=chain_step_id))
db.session.commit() | backend/tests/test_chain_steps.py | import unittest
from flask import json
from tests.base_test import BaseTest
from app import db
from app.model.chain_step import ChainStep
from app.model.questionnaires.chain_session_step import ChainSessionStep
class TestChainStep(BaseTest, unittest.TestCase):
def test_chain_step_basics(self):
self.construct_chain_step()
chain_step = db.session.query(ChainStep).first()
self.assertIsNotNone(chain_step)
rv = self.app.get('/api/chain_step/%i' % chain_step.id,
follow_redirects=True,
content_type="application/json", headers=self.logged_in_headers())
self.assert_success(rv)
response = json.loads(rv.get_data(as_text=True))
self.assertEqual(response["id"], chain_step.id)
def test_modify_chain_step_basics(self):
self.construct_chain_step()
chain_step = db.session.query(ChainStep).first()
self.assertIsNotNone(chain_step)
rv = self.app.get('/api/chain_step/%i' % chain_step.id, content_type="application/json", headers=self.logged_in_headers())
response = json.loads(rv.get_data(as_text=True))
response['instruction'] = 'Take out the trash'
rv = self.app.put('/api/chain_step/%i' % chain_step.id, data=self.jsonify(response), content_type="application/json",
follow_redirects=True, headers=self.logged_in_headers())
self.assert_success(rv)
db.session.commit()
rv = self.app.get('/api/chain_step/%i' % chain_step.id, content_type="application/json", headers=self.logged_in_headers())
self.assert_success(rv)
response = json.loads(rv.get_data(as_text=True))
self.assertEqual(response['instruction'], 'Take out the trash')
def test_delete_chain_step(self):
chain_step = self.construct_chain_step()
chain_step_id = chain_step.id
rv = self.app.get('api/chain_step/%i' % chain_step_id, content_type="application/json")
self.assert_success(rv)
rv = self.app.delete('api/chain_step/%i' % chain_step_id, content_type="application/json", headers=self.logged_in_headers())
self.assert_success(rv)
rv = self.app.get('api/chain_step/%i' % chain_step_id, content_type="application/json")
self.assertEqual(404, rv.status_code)
def test_disallow_deleting_chain_step_if_being_used(self):
chain_step = self.construct_chain_step()
chain_step_id = chain_step.id
db.session.add(ChainSessionStep(chain_step_id=chain_step_id))
db.session.commit()
rv = self.app.get('api/chain_step/%i' % chain_step_id, content_type="application/json")
self.assert_success(rv)
rv = self.app.delete('api/chain_step/%i' % chain_step_id, content_type="application/json", headers=self.logged_in_headers())
self.assertEqual(rv.status_code, 400)
self.assertEqual(rv.json['code'], 'can_not_delete')
def test_multiple_chain_steps(self):
chain_steps = self.construct_chain_steps()
self.assertEqual(4, len(chain_steps))
rv = self.app.get('/api/chain_step', follow_redirects=True, content_type="application/json",
headers=self.logged_in_headers())
self.assert_success(rv)
response = json.loads(rv.get_data(as_text=True))
self.assertEqual(len(chain_steps), len(response))
def test_export_chain_data(self):
chain_steps = self.construct_chain_steps()
for chain_step in chain_steps:
chain_step_id = chain_step.id
db.session.add(ChainSessionStep(chain_step_id=chain_step_id))
db.session.commit() | 0.459561 | 0.450843 |
from multiprocessing import Event, Lock, Process
import datetime
import json
from vesper.django.app.models import Job
from vesper.util.bunch import Bunch
from vesper.util.repeating_timer import RepeatingTimer
import vesper.command.job_runner as job_runner
import vesper.util.archive_lock as archive_lock
import vesper.util.time_utils as time_utils
class JobManager:
"""
Manager of Vesper jobs.
A Vesper job executes one Vesper command. Each job runs in its own
process, which may or may not start additional processes. The
`start_job` method of this class starts a job for a specified command,
and the `stop_job` method requests that a running job stop. A job is
not required to honor a stop request, but most jobs should, especially
longer-running ones.
"""
def __init__(self):
self._job_infos = {}
"""
Mapping from job IDs to `Bunch` objects containing job information.
An item is added to this dictionary when each job is started.
A job's item is removed from the dictionary after the job terminates.
The removal is performed by the `_delete_terminated_jobs` method,
which runs off a repeating timer.
"""
self._lock = Lock()
"""
Lock used to synchronize access to the `_job_infos` dictionary
from multiple threads. (The lock can synchronize access from
multiple threads and/or processes, but we access the dictionary
only from threads of the main Vesper process.)
"""
self._timer = RepeatingTimer(10, self._delete_terminated_jobs)
"""Repeating timer that deletes terminated jobs from `_job_infos`."""
self._timer.start()
def start_job(self, command_spec, user):
info = Bunch()
info.command_spec = command_spec
info.job_id = _create_job(command_spec, user)
info.archive_lock = archive_lock.get_lock()
info.stop_event = Event()
with self._lock:
self._job_infos[info.job_id] = info
info.process = Process(target=job_runner.run_job, args=(info,))
info.process.start()
return info.job_id
def stop_job(self, job_id):
with self._lock:
try:
job_info = self._job_infos[job_id]
except KeyError:
return
else:
job_info.stop_event.set()
def _delete_terminated_jobs(self):
terminated_job_ids = set()
with self._lock:
for info in self._job_infos.values():
if not info.process.is_alive():
terminated_job_ids.add(info.job_id)
for job_id in terminated_job_ids:
del self._job_infos[job_id]
def _create_job(command_spec, user):
with archive_lock.atomic():
job = Job.objects.create(
command=json.dumps(command_spec, default=_json_date_serializer),
creation_time=time_utils.get_utc_now(),
creating_user=user,
status='Unstarted')
return job.id
def _json_date_serializer(obj):
"""Date serializer for `json.dumps`."""
if isinstance(obj, datetime.date):
return str(obj)
else:
raise TypeError('{} is not JSON serializable'.format(repr(obj))) | vesper/command/job_manager.py | from multiprocessing import Event, Lock, Process
import datetime
import json
from vesper.django.app.models import Job
from vesper.util.bunch import Bunch
from vesper.util.repeating_timer import RepeatingTimer
import vesper.command.job_runner as job_runner
import vesper.util.archive_lock as archive_lock
import vesper.util.time_utils as time_utils
class JobManager:
"""
Manager of Vesper jobs.
A Vesper job executes one Vesper command. Each job runs in its own
process, which may or may not start additional processes. The
`start_job` method of this class starts a job for a specified command,
and the `stop_job` method requests that a running job stop. A job is
not required to honor a stop request, but most jobs should, especially
longer-running ones.
"""
def __init__(self):
self._job_infos = {}
"""
Mapping from job IDs to `Bunch` objects containing job information.
An item is added to this dictionary when each job is started.
A job's item is removed from the dictionary after the job terminates.
The removal is performed by the `_delete_terminated_jobs` method,
which runs off a repeating timer.
"""
self._lock = Lock()
"""
Lock used to synchronize access to the `_job_infos` dictionary
from multiple threads. (The lock can synchronize access from
multiple threads and/or processes, but we access the dictionary
only from threads of the main Vesper process.)
"""
self._timer = RepeatingTimer(10, self._delete_terminated_jobs)
"""Repeating timer that deletes terminated jobs from `_job_infos`."""
self._timer.start()
def start_job(self, command_spec, user):
info = Bunch()
info.command_spec = command_spec
info.job_id = _create_job(command_spec, user)
info.archive_lock = archive_lock.get_lock()
info.stop_event = Event()
with self._lock:
self._job_infos[info.job_id] = info
info.process = Process(target=job_runner.run_job, args=(info,))
info.process.start()
return info.job_id
def stop_job(self, job_id):
with self._lock:
try:
job_info = self._job_infos[job_id]
except KeyError:
return
else:
job_info.stop_event.set()
def _delete_terminated_jobs(self):
terminated_job_ids = set()
with self._lock:
for info in self._job_infos.values():
if not info.process.is_alive():
terminated_job_ids.add(info.job_id)
for job_id in terminated_job_ids:
del self._job_infos[job_id]
def _create_job(command_spec, user):
with archive_lock.atomic():
job = Job.objects.create(
command=json.dumps(command_spec, default=_json_date_serializer),
creation_time=time_utils.get_utc_now(),
creating_user=user,
status='Unstarted')
return job.id
def _json_date_serializer(obj):
"""Date serializer for `json.dumps`."""
if isinstance(obj, datetime.date):
return str(obj)
else:
raise TypeError('{} is not JSON serializable'.format(repr(obj))) | 0.600188 | 0.162579 |
from math import exp, cos, sin, sqrt
from pathlib import Path
# AHA imports
import magma as m
# msdsl imports
from ..common import *
from msdsl import MixedSignalModel, VerilogGenerator, AnalogSignal, Deriv
NAME = Path(__file__).stem.split('_')[1]
BUILD_DIR = Path(__file__).resolve().parent / 'build'
def pytest_generate_tests(metafunc):
pytest_sim_params(metafunc)
pytest_real_type_params(metafunc)
def gen_model(cap=0.16e-6, ind=0.16e-6, res=0.1, dt=0.01e-6,
real_type=RealType.FixedPoint):
# declare model
m = MixedSignalModel('model', dt=dt, real_type=real_type)
m.add_analog_input('v_in')
m.add_analog_output('v_out')
m.add_digital_input('clk')
m.add_digital_input('rst')
# declare system of equations
m.add_analog_state('i_ind', 10) # TODO: can this be tightened down a bit?
v_l = AnalogSignal('v_l')
v_r = AnalogSignal('v_r')
eqns = [
Deriv(m.i_ind) == v_l / ind,
Deriv(m.v_out) == m.i_ind / cap,
v_r == m.i_ind * res,
m.v_in == m.v_out + v_l + v_r
]
m.add_eqn_sys(eqns, clk=m.clk, rst=m.rst)
BUILD_DIR.mkdir(parents=True, exist_ok=True)
model_file = BUILD_DIR / 'model.sv'
m.compile_to_file(VerilogGenerator(), filename=model_file)
return model_file
def test_rlc(simulator, real_type, cap=0.16e-6, ind=0.16e-6, res=0.1, dt=0.01e-6):
model_file = gen_model(cap=cap, ind=ind, res=res, dt=dt,
real_type=real_type)
# declare circuit
class dut(m.Circuit):
name=f'test_{NAME}'
io=m.IO(
v_in=fault.RealIn,
v_out=fault.RealOut,
clk=m.ClockIn,
rst=m.BitIn
)
# create the tester
tester = MsdslTester(dut, dut.clk)
# initialize
v_in = 1.0
tester.poke(dut.clk, 0)
tester.poke(dut.rst, 1)
tester.poke(dut.v_in, v_in)
tester.eval()
# reset
tester.step(2)
# model for circuit behavior
# see slide 15 here: http://tuttle.merc.iastate.edu/ee201/topics/capacitors_inductors/RLC_transients.pdf
vf = v_in
vi = 0.0
o = -res/(2*ind)
wd = sqrt(1/(ind*cap)-((res/(2*ind))**2))
def model(t):
return vf - (vf-vi)*(exp(o*t)*(cos(wd*t)-(o/wd)*sin(wd*t)))
# print the first few outputs
tester.poke(dut.rst, 0)
for k in range(20):
tester.expect(dut.v_out, model(k*dt), abs_tol=0.025)
tester.print("v_out: %0f\n", dut.v_out)
tester.step(2)
# run the simulation
tester.compile_and_run(
directory=BUILD_DIR,
simulator=simulator,
ext_srcs=[model_file, get_file(f'{NAME}/test_{NAME}.sv')],
real_type=real_type
) | tests/rlc/test_rlc.py | from math import exp, cos, sin, sqrt
from pathlib import Path
# AHA imports
import magma as m
# msdsl imports
from ..common import *
from msdsl import MixedSignalModel, VerilogGenerator, AnalogSignal, Deriv
NAME = Path(__file__).stem.split('_')[1]
BUILD_DIR = Path(__file__).resolve().parent / 'build'
def pytest_generate_tests(metafunc):
pytest_sim_params(metafunc)
pytest_real_type_params(metafunc)
def gen_model(cap=0.16e-6, ind=0.16e-6, res=0.1, dt=0.01e-6,
real_type=RealType.FixedPoint):
# declare model
m = MixedSignalModel('model', dt=dt, real_type=real_type)
m.add_analog_input('v_in')
m.add_analog_output('v_out')
m.add_digital_input('clk')
m.add_digital_input('rst')
# declare system of equations
m.add_analog_state('i_ind', 10) # TODO: can this be tightened down a bit?
v_l = AnalogSignal('v_l')
v_r = AnalogSignal('v_r')
eqns = [
Deriv(m.i_ind) == v_l / ind,
Deriv(m.v_out) == m.i_ind / cap,
v_r == m.i_ind * res,
m.v_in == m.v_out + v_l + v_r
]
m.add_eqn_sys(eqns, clk=m.clk, rst=m.rst)
BUILD_DIR.mkdir(parents=True, exist_ok=True)
model_file = BUILD_DIR / 'model.sv'
m.compile_to_file(VerilogGenerator(), filename=model_file)
return model_file
def test_rlc(simulator, real_type, cap=0.16e-6, ind=0.16e-6, res=0.1, dt=0.01e-6):
model_file = gen_model(cap=cap, ind=ind, res=res, dt=dt,
real_type=real_type)
# declare circuit
class dut(m.Circuit):
name=f'test_{NAME}'
io=m.IO(
v_in=fault.RealIn,
v_out=fault.RealOut,
clk=m.ClockIn,
rst=m.BitIn
)
# create the tester
tester = MsdslTester(dut, dut.clk)
# initialize
v_in = 1.0
tester.poke(dut.clk, 0)
tester.poke(dut.rst, 1)
tester.poke(dut.v_in, v_in)
tester.eval()
# reset
tester.step(2)
# model for circuit behavior
# see slide 15 here: http://tuttle.merc.iastate.edu/ee201/topics/capacitors_inductors/RLC_transients.pdf
vf = v_in
vi = 0.0
o = -res/(2*ind)
wd = sqrt(1/(ind*cap)-((res/(2*ind))**2))
def model(t):
return vf - (vf-vi)*(exp(o*t)*(cos(wd*t)-(o/wd)*sin(wd*t)))
# print the first few outputs
tester.poke(dut.rst, 0)
for k in range(20):
tester.expect(dut.v_out, model(k*dt), abs_tol=0.025)
tester.print("v_out: %0f\n", dut.v_out)
tester.step(2)
# run the simulation
tester.compile_and_run(
directory=BUILD_DIR,
simulator=simulator,
ext_srcs=[model_file, get_file(f'{NAME}/test_{NAME}.sv')],
real_type=real_type
) | 0.365004 | 0.258577 |
import torch
import numpy as np
import pandas as pd
import os
from DBN import DBN
from load_dataset import MNIST
import cv2
from PIL import Image
from matplotlib import pyplot as plt
def image_beautifier(names, final_name):
image_names = sorted(names)
images = [Image.open(x) for x in names]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.save(final_name)
img = cv2.imread(final_name)
img = cv2.resize(img, (img.shape[1]//2, img.shape[0]//2))
cv2.imwrite(final_name, img)
def gen_displayable_images():
suffix = '_image.jpg'
for n in range(10):
prefix = './images_DBN/digitwise/'+str(n)+'_'
names = ['original', 'hidden', 'reconstructed']
names = [prefix+name+suffix for name in names]
image_beautifier(names, './images_DBN/'+str(n)+'.jpg')
if __name__ == '__main__':
mnist = MNIST()
train_x, train_y, test_x, test_y = mnist.load_dataset()
layers = [512, 128, 64, 10]
dbn = DBN(train_x.shape[1], layers)
dbn.layer_parameters = torch.load('mnist_trained_dbn.pt')
for n in range(10):
x = test_x[np.where(test_y==n)[0][0]]
x = x.unsqueeze(0)
gen_image, hidden_image = dbn.reconstructor(x)
gen_image = gen_image.numpy()
hidden_image = hidden_image.numpy()
image = x.numpy()
image = mnist.inv_transform_normalizer(image)[0]
hidden_image = (hidden_image*255)[0]
gen_image = mnist.inv_transform_normalizer(gen_image)[0]
image = np.reshape(image, (28, 28))
hidden_image = np.reshape(hidden_image, (5, 2))
gen_image = np.reshape(gen_image, (28, 28))
image = image.astype(np.int)
hidden_image = hidden_image.astype(np.int)
gen_image = gen_image.astype(np.int)
print(image.shape, hidden_image.shape, gen_image.shape)
prefix = './images_DBN/digitwise/'+str(n)+'_'
suffix = '_image.jpg'
plt.cla()
plt.imshow(image, cmap="gray")
plt.title('original image')
plt.savefig(prefix+'original'+suffix)
plt.cla()
plt.imshow(hidden_image, cmap="gray")
plt.title('hidden image')
plt.savefig(prefix+'hidden'+suffix)
plt.cla()
plt.imshow(gen_image, cmap="gray")
plt.title('reconstructed image')
plt.savefig(prefix+'reconstructed'+suffix)
gen_displayable_images() | test_MNIST_DBN_example.py | import torch
import numpy as np
import pandas as pd
import os
from DBN import DBN
from load_dataset import MNIST
import cv2
from PIL import Image
from matplotlib import pyplot as plt
def image_beautifier(names, final_name):
image_names = sorted(names)
images = [Image.open(x) for x in names]
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.save(final_name)
img = cv2.imread(final_name)
img = cv2.resize(img, (img.shape[1]//2, img.shape[0]//2))
cv2.imwrite(final_name, img)
def gen_displayable_images():
suffix = '_image.jpg'
for n in range(10):
prefix = './images_DBN/digitwise/'+str(n)+'_'
names = ['original', 'hidden', 'reconstructed']
names = [prefix+name+suffix for name in names]
image_beautifier(names, './images_DBN/'+str(n)+'.jpg')
if __name__ == '__main__':
mnist = MNIST()
train_x, train_y, test_x, test_y = mnist.load_dataset()
layers = [512, 128, 64, 10]
dbn = DBN(train_x.shape[1], layers)
dbn.layer_parameters = torch.load('mnist_trained_dbn.pt')
for n in range(10):
x = test_x[np.where(test_y==n)[0][0]]
x = x.unsqueeze(0)
gen_image, hidden_image = dbn.reconstructor(x)
gen_image = gen_image.numpy()
hidden_image = hidden_image.numpy()
image = x.numpy()
image = mnist.inv_transform_normalizer(image)[0]
hidden_image = (hidden_image*255)[0]
gen_image = mnist.inv_transform_normalizer(gen_image)[0]
image = np.reshape(image, (28, 28))
hidden_image = np.reshape(hidden_image, (5, 2))
gen_image = np.reshape(gen_image, (28, 28))
image = image.astype(np.int)
hidden_image = hidden_image.astype(np.int)
gen_image = gen_image.astype(np.int)
print(image.shape, hidden_image.shape, gen_image.shape)
prefix = './images_DBN/digitwise/'+str(n)+'_'
suffix = '_image.jpg'
plt.cla()
plt.imshow(image, cmap="gray")
plt.title('original image')
plt.savefig(prefix+'original'+suffix)
plt.cla()
plt.imshow(hidden_image, cmap="gray")
plt.title('hidden image')
plt.savefig(prefix+'hidden'+suffix)
plt.cla()
plt.imshow(gen_image, cmap="gray")
plt.title('reconstructed image')
plt.savefig(prefix+'reconstructed'+suffix)
gen_displayable_images() | 0.298594 | 0.350088 |
from pathlib import Path
from io import StringIO
import numpy as np
import pandas as pd
import requests
def import_and_clean_cases(save_path: Path) -> pd.DataFrame:
'''
Import and clean case data from covidtracking.com.
'''
# Parameters for filtering raw df
kept_columns = ['date','state','positive','death']
excluded_areas = set(['PR','MP','AS','GU','VI'])
# Import and save result
res = requests.get("https://covidtracking.com/api/v1/states/daily.json")
df = pd.read_json(res.text)
df.to_csv(save_path/"covidtracking_cases.csv", index=False)
# Exclude specific territories and features
df = df[~df['state'].isin(excluded_areas)][kept_columns]
# Format date properly
df.loc[:,'date'] = pd.to_datetime(df.loc[:,'date'], format='%Y%m%d')
# Calculate state change in positives/deaths
df = df.sort_values(['state','date'])
df['delta_positive'] = df.groupby(['state'])['positive'].transform(lambda x: x.diff())
df['delta_death'] = df.groupby(['state'])['death'].transform(lambda x: x.diff())
return df
def get_adaptive_estimates(path: Path) -> pd.DataFrame:
# Parameters for filtering raw df
kept_columns = ['date','state','RR_pred','RR_CI_lower','RR_CI_upper','T_pred',
'T_CI_lower','T_CI_upper','new_cases_ts','anamoly']
# Import and subset columns
df = pd.read_csv(path/"adaptive_estimates.csv")
df = df[kept_columns]
# Format date properly and return
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
return df
def get_new_rt_live_estimates(path: Path) -> pd.DataFrame:
# Parameters for filtering raw df
kept_columns = ['date','region','mean','lower_80','upper_80',
'infections','test_adjusted_positive']
# Import and save as csv
res = requests.get("https://d14wlfuexuxgcm.cloudfront.net/covid/rt.csv")
df = pd.read_csv(StringIO(res.text))
df.to_csv(path/"rtlive_new_estimates.csv", index=False)
# Filter to just necessary features
df = df[kept_columns]
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df.rename(columns={'region':'state','mean':'RR_pred_rtlivenew',
'lower_80':'RR_lower_rtlivenew', 'upper_80':'RR_upper_rtlivenew',
'test_adjusted_positive':'adj_positive_rtlivenew',
'infections':'infections_rtlivenew'}, inplace=True)
return df
def get_old_rt_live_estimates(path: Path) -> pd.DataFrame:
# Parameters for filtering raw df
kept_columns = ['date','state','mean','lower_95','upper_95']
# Import and save as csv
df = pd.read_csv(path/"rtlive_old_estimates.csv")
# Filter to just necessary features
df = df[kept_columns]
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df.rename(columns={'region':'state','mean':'RR_pred_rtliveold',
'lower_95':'RR_lower_rtliveold',
'upper_95':'RR_upper_rtliveold'}, inplace=True)
return df
def get_cori_estimates(path: Path) -> pd.DataFrame:
# Import and save as csv
df = pd.read_csv(path/"cori_estimates.csv")
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
return df
def get_luis_estimates(path: Path) -> pd.DataFrame:
# Import and save as csv
df = pd.read_csv(path/"luis_code_estimates.csv")
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
return df | us_states_validation/etl.py | from pathlib import Path
from io import StringIO
import numpy as np
import pandas as pd
import requests
def import_and_clean_cases(save_path: Path) -> pd.DataFrame:
'''
Import and clean case data from covidtracking.com.
'''
# Parameters for filtering raw df
kept_columns = ['date','state','positive','death']
excluded_areas = set(['PR','MP','AS','GU','VI'])
# Import and save result
res = requests.get("https://covidtracking.com/api/v1/states/daily.json")
df = pd.read_json(res.text)
df.to_csv(save_path/"covidtracking_cases.csv", index=False)
# Exclude specific territories and features
df = df[~df['state'].isin(excluded_areas)][kept_columns]
# Format date properly
df.loc[:,'date'] = pd.to_datetime(df.loc[:,'date'], format='%Y%m%d')
# Calculate state change in positives/deaths
df = df.sort_values(['state','date'])
df['delta_positive'] = df.groupby(['state'])['positive'].transform(lambda x: x.diff())
df['delta_death'] = df.groupby(['state'])['death'].transform(lambda x: x.diff())
return df
def get_adaptive_estimates(path: Path) -> pd.DataFrame:
# Parameters for filtering raw df
kept_columns = ['date','state','RR_pred','RR_CI_lower','RR_CI_upper','T_pred',
'T_CI_lower','T_CI_upper','new_cases_ts','anamoly']
# Import and subset columns
df = pd.read_csv(path/"adaptive_estimates.csv")
df = df[kept_columns]
# Format date properly and return
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
return df
def get_new_rt_live_estimates(path: Path) -> pd.DataFrame:
# Parameters for filtering raw df
kept_columns = ['date','region','mean','lower_80','upper_80',
'infections','test_adjusted_positive']
# Import and save as csv
res = requests.get("https://d14wlfuexuxgcm.cloudfront.net/covid/rt.csv")
df = pd.read_csv(StringIO(res.text))
df.to_csv(path/"rtlive_new_estimates.csv", index=False)
# Filter to just necessary features
df = df[kept_columns]
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df.rename(columns={'region':'state','mean':'RR_pred_rtlivenew',
'lower_80':'RR_lower_rtlivenew', 'upper_80':'RR_upper_rtlivenew',
'test_adjusted_positive':'adj_positive_rtlivenew',
'infections':'infections_rtlivenew'}, inplace=True)
return df
def get_old_rt_live_estimates(path: Path) -> pd.DataFrame:
# Parameters for filtering raw df
kept_columns = ['date','state','mean','lower_95','upper_95']
# Import and save as csv
df = pd.read_csv(path/"rtlive_old_estimates.csv")
# Filter to just necessary features
df = df[kept_columns]
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
df.rename(columns={'region':'state','mean':'RR_pred_rtliveold',
'lower_95':'RR_lower_rtliveold',
'upper_95':'RR_upper_rtliveold'}, inplace=True)
return df
def get_cori_estimates(path: Path) -> pd.DataFrame:
# Import and save as csv
df = pd.read_csv(path/"cori_estimates.csv")
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
return df
def get_luis_estimates(path: Path) -> pd.DataFrame:
# Import and save as csv
df = pd.read_csv(path/"luis_code_estimates.csv")
# Format date properly and rename columns
df.loc[:,'date'] = pd.to_datetime(df['date'], format='%Y-%m-%d')
return df | 0.541166 | 0.405213 |
import csv
import os
import shutil
import tempfile
from unittest import TestCase
from src.extractor import extract_dot_text, extract_dot_text_to_file, \
extract_function_to_file, get_opcode
PREFIX = "BCCFLT_"
class TestExtractor(TestCase):
tmpdir: str = None
file: str = "./resources/tempfile"
expected = [243, 15, 30, 250, 65, 87, 73, 137, 247, 65, 86, 76, 141, 53,
127, 15, 0, 0, 65, 85, 69, 49, 237, 65, 84, 85, 137, 253, 83,
72, 141, 29, 0, 16, 0, 0, 72, 129, 236, 104, 1, 0, 0, 100, 72,
139, 4, 37, 40, 0, 0, 0, 72, 137, 132, 36, 88, 1, 0, 0, 49,
192, 72, 141, 5, 81, 15, 0, 0, 76, 141, 100, 36, 80, 199, 68,
36, 44, 128, 1, 0, 0, 72, 137, 68, 36, 80, 72, 141, 5, 63, 15,
0, 0, 72, 137, 68, 36, 112, 72, 141, 5, 58, 15, 0, 0, 72, 137,
132, 36, 144, 0, 0, 0, 72, 141, 5, 53, 15, 0, 0, 72, 137, 132,
36, 176, 0, 0, 0, 72, 141, 5, 43, 15, 0, 0, 72, 137, 132, 36,
208, 0, 0, 0, 72, 141, 5, 33, 15, 0, 0, 72, 137, 132, 36, 240,
0, 0, 0, 72, 141, 5, 23, 15, 0, 0, 199, 68, 36, 88, 1, 0, 0, 0,
72, 199, 68, 36, 96, 0, 0, 0, 0, 199, 68, 36, 104, 112, 0, 0,
0, 199, 68, 36, 120, 1, 0, 0, 0, 72, 199, 132, 36, 128, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 136, 0, 0, 0, 115, 0, 0, 0, 199,
132, 36, 152, 0, 0, 0, 1, 0, 0, 0, 72, 199, 132, 36, 160, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 168, 0, 0, 0, 100, 0, 0, 0, 199,
132, 36, 184, 0, 0, 0, 1, 0, 0, 0, 72, 199, 132, 36, 192, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 200, 0, 0, 0, 109, 0, 0, 0, 199,
132, 36, 216, 0, 0, 0, 1, 0, 0, 0, 72, 199, 132, 36, 224, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 232, 0, 0, 0, 110, 0, 0, 0, 199,
132, 36, 248, 0, 0, 0, 0, 0, 0, 0, 72, 199, 132, 36, 0, 1, 0,
0, 0, 0, 0, 0, 72, 137, 132, 36, 16, 1, 0, 0, 72, 139, 6, 199,
132, 36, 8, 1, 0, 0, 104, 0, 0, 0, 199, 132, 36, 24, 1, 0, 0,
0, 0, 0, 0, 72, 199, 132, 36, 32, 1, 0, 0, 0, 0, 0, 0, 199,
132, 36, 40, 1, 0, 0, 118, 0, 0, 0, 72, 199, 132, 36, 48, 1, 0,
0, 0, 0, 0, 0, 199, 132, 36, 56, 1, 0, 0, 0, 0, 0, 0, 72, 199,
132, 36, 64, 1, 0, 0, 0, 0, 0, 0, 199, 132, 36, 72, 1, 0, 0, 0,
0, 0, 0, 72, 137, 5, 8, 44, 0, 0, 72, 199, 68, 36, 8, 0, 0, 0,
0, 72, 199, 68, 36, 16, 0, 0, 0, 0, 69, 49, 192, 76, 137, 225,
72, 141, 21, 244, 13, 0, 0, 76, 137, 254, 137, 239, 232, 95,
253, 255, 255, 131, 248, 255, 15, 132, 202, 0, 0, 0, 133, 192,
116, 220, 131, 232, 100, 131, 248, 18, 15, 135, 176, 0, 0, 0,
72, 99, 4, 131, 72, 1, 216, 62, 255, 224, 72, 141, 61, 177, 13,
0, 0, 232, 16, 253, 255, 255, 49, 255, 232, 169, 253, 255, 255,
72, 139, 5, 114, 43, 0, 0, 72, 137, 68, 36, 8, 235, 165, 76,
139, 53, 100, 43, 0, 0, 235, 156, 72, 139, 61, 91, 43, 0, 0,
232, 166, 253, 255, 255, 73, 137, 197, 72, 133, 192, 117, 136,
72, 141, 61, 108, 13, 0, 0, 232, 210, 3, 0, 0, 72, 139, 61, 59,
43, 0, 0, 72, 141, 116, 36, 44, 232, 225, 3, 0, 0, 133, 192,
15, 132, 99, 255, 255, 255, 72, 139, 61, 66, 43, 0, 0, 72, 139,
13, 27, 43, 0, 0, 72, 141, 21, 220, 12, 0, 0, 49, 192, 190, 1,
0, 0, 0, 232, 72, 253, 255, 255, 191, 1, 0, 0, 0, 232, 62, 3,
0, 0, 49, 255, 232, 55, 3, 0, 0, 72, 139, 5, 240, 42, 0, 0, 72,
137, 68, 36, 16, 233, 32, 255, 255, 255, 191, 1, 0, 0, 0, 232,
28, 3, 0, 0, 77, 133, 237, 116, 54, 139, 84, 36, 44, 76, 137,
239, 190, 194, 0, 0, 0, 49, 192, 232, 212, 252, 255, 255, 137,
199, 133, 192, 15, 136, 90, 1, 0, 0, 232, 117, 252, 255, 255,
133, 192, 15, 132, 54, 1, 0, 0, 72, 141, 61, 20, 13, 0, 0, 232,
49, 3, 0, 0, 72, 141, 61, 229, 12, 0, 0, 49, 219, 72, 141, 108,
36, 48, 232, 222, 251, 255, 255, 76, 141, 37, 193, 12, 0, 0,
72, 137, 68, 36, 48, 72, 139, 68, 36, 16, 72, 137, 68, 36, 56,
72, 141, 5, 195, 12, 0, 0, 72, 137, 68, 36, 64, 72, 137, 68,
36, 72, 76, 139, 76, 221, 0, 77, 133, 201, 15, 132, 13, 1, 0,
0, 72, 131, 206, 255, 49, 192, 76, 137, 207, 72, 137, 241, 242,
174, 72, 247, 209, 72, 141, 81, 255, 77, 133, 246, 15, 132, 6,
1, 0, 0, 72, 137, 241, 76, 137, 247, 242, 174, 72, 137, 200,
72, 247, 208, 72, 131, 232, 1, 72, 139, 124, 36, 8, 76, 137,
76, 36, 16, 76, 141, 124, 2, 8, 72, 133, 255, 15, 132, 227, 0,
0, 0, 49, 192, 72, 131, 201, 255, 242, 174, 72, 137, 200, 72,
247, 208, 77, 141, 124, 7, 255, 76, 137, 255, 232, 214, 251,
255, 255, 76, 139, 76, 36, 16, 72, 133, 192, 73, 137, 197, 15,
132, 41, 1, 0, 0, 77, 133, 246, 15, 132, 242, 0, 0, 0, 255,
116, 36, 8, 65, 86, 72, 131, 201, 255, 76, 137, 254, 76, 137,
239, 186, 1, 0, 0, 0, 76, 141, 5, 52, 12, 0, 0, 49, 192, 232,
25, 251, 255, 255, 89, 94, 49, 192, 72, 139, 124, 36, 8, 72,
131, 201, 255, 242, 174, 72, 137, 200, 72, 247, 208, 141, 112,
255, 76, 137, 239, 232, 217, 250, 255, 255, 137, 68, 36, 28,
133, 192, 15, 137, 180, 0, 0, 0, 232, 8, 251, 255, 255, 131,
56, 17, 116, 47, 72, 141, 61, 218, 11, 0, 0, 232, 7, 2, 0, 0,
76, 137, 239, 232, 255, 250, 255, 255, 76, 137, 239, 232, 215,
250, 255, 255, 49, 255, 232, 144, 251, 255, 255, 72, 141, 61,
159, 11, 0, 0, 232, 228, 1, 0, 0, 76, 137, 239, 232, 188, 250,
255, 255, 72, 131, 195, 1, 72, 131, 251, 4, 15, 133, 215, 254,
255, 255, 139, 124, 36, 28, 233, 123, 254, 255, 255, 49, 192,
233, 5, 255, 255, 255, 76, 137, 255, 232, 6, 251, 255, 255, 76,
139, 76, 36, 16, 72, 133, 192, 73, 137, 197, 116, 93, 77, 133,
246, 116, 53, 65, 84, 65, 86, 186, 1, 0, 0, 0, 76, 137, 254,
72, 131, 201, 255, 76, 137, 239, 76, 141, 5, 110, 11, 0, 0, 49,
192, 232, 83, 250, 255, 255, 88, 49, 246, 90, 233, 73, 255,
255, 255, 255, 116, 36, 8, 65, 84, 233, 9, 255, 255, 255, 65,
84, 65, 84, 235, 201, 139, 116, 36, 44, 139, 124, 36, 28, 232,
204, 250, 255, 255, 133, 192, 121, 138, 72, 141, 61, 40, 11, 0,
0, 232, 76, 1, 0, 0, 72, 141, 61, 12, 11, 0, 0, 232, 64, 1, 0,
0, 243, 15, 30, 250, 49, 237, 73, 137, 209, 94, 72, 137, 226,
72, 131, 228, 240, 80, 84, 76, 141, 5, 38, 2, 0, 0, 72, 141,
13, 175, 1, 0, 0, 72, 141, 61, 232, 250, 255, 255, 255, 21, 66,
40, 0, 0, 244, 144, 72, 141, 61, 105, 40, 0, 0, 72, 141, 5, 98,
40, 0, 0, 72, 57, 248, 116, 21, 72, 139, 5, 30, 40, 0, 0, 72,
133, 192, 116, 9, 255, 224, 15, 31, 128, 0, 0, 0, 0, 195, 15,
31, 128, 0, 0, 0, 0, 72, 141, 61, 57, 40, 0, 0, 72, 141, 53,
50, 40, 0, 0, 72, 41, 254, 72, 137, 240, 72, 193, 238, 63, 72,
193, 248, 3, 72, 1, 198, 72, 209, 254, 116, 20, 72, 139, 5,
245, 39, 0, 0, 72, 133, 192, 116, 8, 255, 224, 102, 15, 31, 68,
0, 0, 195, 15, 31, 128, 0, 0, 0, 0, 243, 15, 30, 250, 128, 61,
45, 40, 0, 0, 0, 117, 43, 85, 72, 131, 61, 210, 39, 0, 0, 0,
72, 137, 229, 116, 12, 72, 139, 61, 214, 39, 0, 0, 232, 25,
249, 255, 255, 232, 100, 255, 255, 255, 198, 5, 5, 40, 0, 0, 1,
93, 195, 15, 31, 0, 195, 15, 31, 128, 0, 0, 0, 0, 243, 15, 30,
250, 233, 119, 255, 255, 255, 15, 31, 128, 0, 0, 0, 0, 243, 15,
30, 250, 85, 72, 139, 21, 228, 39, 0, 0, 137, 253, 133, 255,
116, 36, 72, 139, 61, 199, 39, 0, 0, 72, 137, 209, 190, 1, 0,
0, 0, 49, 192, 72, 141, 21, 126, 7, 0, 0, 232, 209, 249, 255,
255, 137, 239, 232, 186, 249, 255, 255, 72, 141, 53, 147, 7, 0,
0, 191, 1, 0, 0, 0, 49, 192, 232, 103, 249, 255, 255, 235, 228,
15, 31, 68, 0, 0, 243, 15, 30, 250, 80, 88, 72, 131, 236, 8,
232, 129, 249, 255, 255, 191, 1, 0, 0, 0, 232, 135, 249, 255,
255, 15, 31, 128, 0, 0, 0, 0, 243, 15, 30, 250, 83, 186, 8, 0,
0, 0, 72, 137, 243, 72, 131, 236, 16, 100, 72, 139, 4, 37, 40,
0, 0, 0, 72, 137, 68, 36, 8, 49, 192, 72, 137, 230, 232, 247,
248, 255, 255, 72, 139, 20, 36, 65, 184, 1, 0, 0, 0, 128, 58,
0, 117, 13, 72, 61, 255, 15, 0, 0, 119, 5, 137, 3, 69, 49, 192,
72, 139, 68, 36, 8, 100, 72, 51, 4, 37, 40, 0, 0, 0, 117, 9,
72, 131, 196, 16, 68, 137, 192, 91, 195, 232, 141, 248, 255,
255, 102, 46, 15, 31, 132, 0, 0, 0, 0, 0, 15, 31, 0, 243, 15,
30, 250, 65, 87, 76, 141, 61, 227, 35, 0, 0, 65, 86, 73, 137,
214, 65, 85, 73, 137, 245, 65, 84, 65, 137, 252, 85, 72, 141,
45, 212, 35, 0, 0, 83, 76, 41, 253, 72, 131, 236, 8, 232, 143,
246, 255, 255, 72, 193, 253, 3, 116, 31, 49, 219, 15, 31, 128,
0, 0, 0, 0, 76, 137, 242, 76, 137, 238, 68, 137, 231, 65, 255,
20, 223, 72, 131, 195, 1, 72, 57, 221, 117, 234, 72, 131, 196,
8, 91, 93, 65, 92, 65, 93, 65, 94, 65, 95, 195, 102, 102, 46,
15, 31, 132, 0, 0, 0, 0, 0, 243, 15, 30, 250, 195]
@classmethod
def setUpClass(self):
systmpdir = tempfile.gettempdir()
self.tmpdir = tempfile.mkdtemp(prefix=PREFIX, dir=systmpdir)
@classmethod
def tearDownClass(self):
shutil.rmtree(self.tmpdir)
# write empty file and asserts no exception is thrown
def test_extract(self):
self.assertTrue(os.path.exists(self.file))
data = extract_dot_text(self.file)
self.assertEqual(data, self.expected)
def test_extract_file(self):
self.assertTrue(os.path.exists(self.file))
extracted = os.path.join(self.tmpdir, "extracted.bin")
extract_dot_text_to_file(self.file, extracted)
with open(extracted, "rb") as fp:
extracted_data = list(fp.read())
self.assertEqual(extracted_data, self.expected)
def test_get_opcode_x8664(self):
inputs = ["f30f1efa", "e953ffff", "0f97C1", "490faf", "f2ff", "f20fc7"]
expected = [bytearray(b"\x0f\x1e"),
bytearray(b"\xe9"),
bytearray(b"\x0f\x97"),
bytearray(b"\x0f\xaf"),
bytearray(b"\xf2"),
bytearray(b"\x0f\xc7")]
for i in range(0, len(inputs)):
opcode = get_opcode(bytearray.fromhex(inputs[i]))
self.assertEqual(opcode, expected[i])
def test_extract_function_to_file(self):
self.assertTrue(os.path.exists(self.file))
extracted = os.path.join(self.tmpdir, "extracted.csv")
extract_function_to_file(self.file, extracted)
# can't check the content, so just hope for the best and check method
# completition
with open(extracted, "r") as fp:
read = csv.reader(fp, delimiter=",")
self.assertEqual(sum(1 for _ in read), 10) | tests/extractor_tests.py | import csv
import os
import shutil
import tempfile
from unittest import TestCase
from src.extractor import extract_dot_text, extract_dot_text_to_file, \
extract_function_to_file, get_opcode
PREFIX = "BCCFLT_"
class TestExtractor(TestCase):
tmpdir: str = None
file: str = "./resources/tempfile"
expected = [243, 15, 30, 250, 65, 87, 73, 137, 247, 65, 86, 76, 141, 53,
127, 15, 0, 0, 65, 85, 69, 49, 237, 65, 84, 85, 137, 253, 83,
72, 141, 29, 0, 16, 0, 0, 72, 129, 236, 104, 1, 0, 0, 100, 72,
139, 4, 37, 40, 0, 0, 0, 72, 137, 132, 36, 88, 1, 0, 0, 49,
192, 72, 141, 5, 81, 15, 0, 0, 76, 141, 100, 36, 80, 199, 68,
36, 44, 128, 1, 0, 0, 72, 137, 68, 36, 80, 72, 141, 5, 63, 15,
0, 0, 72, 137, 68, 36, 112, 72, 141, 5, 58, 15, 0, 0, 72, 137,
132, 36, 144, 0, 0, 0, 72, 141, 5, 53, 15, 0, 0, 72, 137, 132,
36, 176, 0, 0, 0, 72, 141, 5, 43, 15, 0, 0, 72, 137, 132, 36,
208, 0, 0, 0, 72, 141, 5, 33, 15, 0, 0, 72, 137, 132, 36, 240,
0, 0, 0, 72, 141, 5, 23, 15, 0, 0, 199, 68, 36, 88, 1, 0, 0, 0,
72, 199, 68, 36, 96, 0, 0, 0, 0, 199, 68, 36, 104, 112, 0, 0,
0, 199, 68, 36, 120, 1, 0, 0, 0, 72, 199, 132, 36, 128, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 136, 0, 0, 0, 115, 0, 0, 0, 199,
132, 36, 152, 0, 0, 0, 1, 0, 0, 0, 72, 199, 132, 36, 160, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 168, 0, 0, 0, 100, 0, 0, 0, 199,
132, 36, 184, 0, 0, 0, 1, 0, 0, 0, 72, 199, 132, 36, 192, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 200, 0, 0, 0, 109, 0, 0, 0, 199,
132, 36, 216, 0, 0, 0, 1, 0, 0, 0, 72, 199, 132, 36, 224, 0, 0,
0, 0, 0, 0, 0, 199, 132, 36, 232, 0, 0, 0, 110, 0, 0, 0, 199,
132, 36, 248, 0, 0, 0, 0, 0, 0, 0, 72, 199, 132, 36, 0, 1, 0,
0, 0, 0, 0, 0, 72, 137, 132, 36, 16, 1, 0, 0, 72, 139, 6, 199,
132, 36, 8, 1, 0, 0, 104, 0, 0, 0, 199, 132, 36, 24, 1, 0, 0,
0, 0, 0, 0, 72, 199, 132, 36, 32, 1, 0, 0, 0, 0, 0, 0, 199,
132, 36, 40, 1, 0, 0, 118, 0, 0, 0, 72, 199, 132, 36, 48, 1, 0,
0, 0, 0, 0, 0, 199, 132, 36, 56, 1, 0, 0, 0, 0, 0, 0, 72, 199,
132, 36, 64, 1, 0, 0, 0, 0, 0, 0, 199, 132, 36, 72, 1, 0, 0, 0,
0, 0, 0, 72, 137, 5, 8, 44, 0, 0, 72, 199, 68, 36, 8, 0, 0, 0,
0, 72, 199, 68, 36, 16, 0, 0, 0, 0, 69, 49, 192, 76, 137, 225,
72, 141, 21, 244, 13, 0, 0, 76, 137, 254, 137, 239, 232, 95,
253, 255, 255, 131, 248, 255, 15, 132, 202, 0, 0, 0, 133, 192,
116, 220, 131, 232, 100, 131, 248, 18, 15, 135, 176, 0, 0, 0,
72, 99, 4, 131, 72, 1, 216, 62, 255, 224, 72, 141, 61, 177, 13,
0, 0, 232, 16, 253, 255, 255, 49, 255, 232, 169, 253, 255, 255,
72, 139, 5, 114, 43, 0, 0, 72, 137, 68, 36, 8, 235, 165, 76,
139, 53, 100, 43, 0, 0, 235, 156, 72, 139, 61, 91, 43, 0, 0,
232, 166, 253, 255, 255, 73, 137, 197, 72, 133, 192, 117, 136,
72, 141, 61, 108, 13, 0, 0, 232, 210, 3, 0, 0, 72, 139, 61, 59,
43, 0, 0, 72, 141, 116, 36, 44, 232, 225, 3, 0, 0, 133, 192,
15, 132, 99, 255, 255, 255, 72, 139, 61, 66, 43, 0, 0, 72, 139,
13, 27, 43, 0, 0, 72, 141, 21, 220, 12, 0, 0, 49, 192, 190, 1,
0, 0, 0, 232, 72, 253, 255, 255, 191, 1, 0, 0, 0, 232, 62, 3,
0, 0, 49, 255, 232, 55, 3, 0, 0, 72, 139, 5, 240, 42, 0, 0, 72,
137, 68, 36, 16, 233, 32, 255, 255, 255, 191, 1, 0, 0, 0, 232,
28, 3, 0, 0, 77, 133, 237, 116, 54, 139, 84, 36, 44, 76, 137,
239, 190, 194, 0, 0, 0, 49, 192, 232, 212, 252, 255, 255, 137,
199, 133, 192, 15, 136, 90, 1, 0, 0, 232, 117, 252, 255, 255,
133, 192, 15, 132, 54, 1, 0, 0, 72, 141, 61, 20, 13, 0, 0, 232,
49, 3, 0, 0, 72, 141, 61, 229, 12, 0, 0, 49, 219, 72, 141, 108,
36, 48, 232, 222, 251, 255, 255, 76, 141, 37, 193, 12, 0, 0,
72, 137, 68, 36, 48, 72, 139, 68, 36, 16, 72, 137, 68, 36, 56,
72, 141, 5, 195, 12, 0, 0, 72, 137, 68, 36, 64, 72, 137, 68,
36, 72, 76, 139, 76, 221, 0, 77, 133, 201, 15, 132, 13, 1, 0,
0, 72, 131, 206, 255, 49, 192, 76, 137, 207, 72, 137, 241, 242,
174, 72, 247, 209, 72, 141, 81, 255, 77, 133, 246, 15, 132, 6,
1, 0, 0, 72, 137, 241, 76, 137, 247, 242, 174, 72, 137, 200,
72, 247, 208, 72, 131, 232, 1, 72, 139, 124, 36, 8, 76, 137,
76, 36, 16, 76, 141, 124, 2, 8, 72, 133, 255, 15, 132, 227, 0,
0, 0, 49, 192, 72, 131, 201, 255, 242, 174, 72, 137, 200, 72,
247, 208, 77, 141, 124, 7, 255, 76, 137, 255, 232, 214, 251,
255, 255, 76, 139, 76, 36, 16, 72, 133, 192, 73, 137, 197, 15,
132, 41, 1, 0, 0, 77, 133, 246, 15, 132, 242, 0, 0, 0, 255,
116, 36, 8, 65, 86, 72, 131, 201, 255, 76, 137, 254, 76, 137,
239, 186, 1, 0, 0, 0, 76, 141, 5, 52, 12, 0, 0, 49, 192, 232,
25, 251, 255, 255, 89, 94, 49, 192, 72, 139, 124, 36, 8, 72,
131, 201, 255, 242, 174, 72, 137, 200, 72, 247, 208, 141, 112,
255, 76, 137, 239, 232, 217, 250, 255, 255, 137, 68, 36, 28,
133, 192, 15, 137, 180, 0, 0, 0, 232, 8, 251, 255, 255, 131,
56, 17, 116, 47, 72, 141, 61, 218, 11, 0, 0, 232, 7, 2, 0, 0,
76, 137, 239, 232, 255, 250, 255, 255, 76, 137, 239, 232, 215,
250, 255, 255, 49, 255, 232, 144, 251, 255, 255, 72, 141, 61,
159, 11, 0, 0, 232, 228, 1, 0, 0, 76, 137, 239, 232, 188, 250,
255, 255, 72, 131, 195, 1, 72, 131, 251, 4, 15, 133, 215, 254,
255, 255, 139, 124, 36, 28, 233, 123, 254, 255, 255, 49, 192,
233, 5, 255, 255, 255, 76, 137, 255, 232, 6, 251, 255, 255, 76,
139, 76, 36, 16, 72, 133, 192, 73, 137, 197, 116, 93, 77, 133,
246, 116, 53, 65, 84, 65, 86, 186, 1, 0, 0, 0, 76, 137, 254,
72, 131, 201, 255, 76, 137, 239, 76, 141, 5, 110, 11, 0, 0, 49,
192, 232, 83, 250, 255, 255, 88, 49, 246, 90, 233, 73, 255,
255, 255, 255, 116, 36, 8, 65, 84, 233, 9, 255, 255, 255, 65,
84, 65, 84, 235, 201, 139, 116, 36, 44, 139, 124, 36, 28, 232,
204, 250, 255, 255, 133, 192, 121, 138, 72, 141, 61, 40, 11, 0,
0, 232, 76, 1, 0, 0, 72, 141, 61, 12, 11, 0, 0, 232, 64, 1, 0,
0, 243, 15, 30, 250, 49, 237, 73, 137, 209, 94, 72, 137, 226,
72, 131, 228, 240, 80, 84, 76, 141, 5, 38, 2, 0, 0, 72, 141,
13, 175, 1, 0, 0, 72, 141, 61, 232, 250, 255, 255, 255, 21, 66,
40, 0, 0, 244, 144, 72, 141, 61, 105, 40, 0, 0, 72, 141, 5, 98,
40, 0, 0, 72, 57, 248, 116, 21, 72, 139, 5, 30, 40, 0, 0, 72,
133, 192, 116, 9, 255, 224, 15, 31, 128, 0, 0, 0, 0, 195, 15,
31, 128, 0, 0, 0, 0, 72, 141, 61, 57, 40, 0, 0, 72, 141, 53,
50, 40, 0, 0, 72, 41, 254, 72, 137, 240, 72, 193, 238, 63, 72,
193, 248, 3, 72, 1, 198, 72, 209, 254, 116, 20, 72, 139, 5,
245, 39, 0, 0, 72, 133, 192, 116, 8, 255, 224, 102, 15, 31, 68,
0, 0, 195, 15, 31, 128, 0, 0, 0, 0, 243, 15, 30, 250, 128, 61,
45, 40, 0, 0, 0, 117, 43, 85, 72, 131, 61, 210, 39, 0, 0, 0,
72, 137, 229, 116, 12, 72, 139, 61, 214, 39, 0, 0, 232, 25,
249, 255, 255, 232, 100, 255, 255, 255, 198, 5, 5, 40, 0, 0, 1,
93, 195, 15, 31, 0, 195, 15, 31, 128, 0, 0, 0, 0, 243, 15, 30,
250, 233, 119, 255, 255, 255, 15, 31, 128, 0, 0, 0, 0, 243, 15,
30, 250, 85, 72, 139, 21, 228, 39, 0, 0, 137, 253, 133, 255,
116, 36, 72, 139, 61, 199, 39, 0, 0, 72, 137, 209, 190, 1, 0,
0, 0, 49, 192, 72, 141, 21, 126, 7, 0, 0, 232, 209, 249, 255,
255, 137, 239, 232, 186, 249, 255, 255, 72, 141, 53, 147, 7, 0,
0, 191, 1, 0, 0, 0, 49, 192, 232, 103, 249, 255, 255, 235, 228,
15, 31, 68, 0, 0, 243, 15, 30, 250, 80, 88, 72, 131, 236, 8,
232, 129, 249, 255, 255, 191, 1, 0, 0, 0, 232, 135, 249, 255,
255, 15, 31, 128, 0, 0, 0, 0, 243, 15, 30, 250, 83, 186, 8, 0,
0, 0, 72, 137, 243, 72, 131, 236, 16, 100, 72, 139, 4, 37, 40,
0, 0, 0, 72, 137, 68, 36, 8, 49, 192, 72, 137, 230, 232, 247,
248, 255, 255, 72, 139, 20, 36, 65, 184, 1, 0, 0, 0, 128, 58,
0, 117, 13, 72, 61, 255, 15, 0, 0, 119, 5, 137, 3, 69, 49, 192,
72, 139, 68, 36, 8, 100, 72, 51, 4, 37, 40, 0, 0, 0, 117, 9,
72, 131, 196, 16, 68, 137, 192, 91, 195, 232, 141, 248, 255,
255, 102, 46, 15, 31, 132, 0, 0, 0, 0, 0, 15, 31, 0, 243, 15,
30, 250, 65, 87, 76, 141, 61, 227, 35, 0, 0, 65, 86, 73, 137,
214, 65, 85, 73, 137, 245, 65, 84, 65, 137, 252, 85, 72, 141,
45, 212, 35, 0, 0, 83, 76, 41, 253, 72, 131, 236, 8, 232, 143,
246, 255, 255, 72, 193, 253, 3, 116, 31, 49, 219, 15, 31, 128,
0, 0, 0, 0, 76, 137, 242, 76, 137, 238, 68, 137, 231, 65, 255,
20, 223, 72, 131, 195, 1, 72, 57, 221, 117, 234, 72, 131, 196,
8, 91, 93, 65, 92, 65, 93, 65, 94, 65, 95, 195, 102, 102, 46,
15, 31, 132, 0, 0, 0, 0, 0, 243, 15, 30, 250, 195]
@classmethod
def setUpClass(self):
systmpdir = tempfile.gettempdir()
self.tmpdir = tempfile.mkdtemp(prefix=PREFIX, dir=systmpdir)
@classmethod
def tearDownClass(self):
shutil.rmtree(self.tmpdir)
# write empty file and asserts no exception is thrown
def test_extract(self):
self.assertTrue(os.path.exists(self.file))
data = extract_dot_text(self.file)
self.assertEqual(data, self.expected)
def test_extract_file(self):
self.assertTrue(os.path.exists(self.file))
extracted = os.path.join(self.tmpdir, "extracted.bin")
extract_dot_text_to_file(self.file, extracted)
with open(extracted, "rb") as fp:
extracted_data = list(fp.read())
self.assertEqual(extracted_data, self.expected)
def test_get_opcode_x8664(self):
inputs = ["f30f1efa", "e953ffff", "0f97C1", "490faf", "f2ff", "f20fc7"]
expected = [bytearray(b"\x0f\x1e"),
bytearray(b"\xe9"),
bytearray(b"\x0f\x97"),
bytearray(b"\x0f\xaf"),
bytearray(b"\xf2"),
bytearray(b"\x0f\xc7")]
for i in range(0, len(inputs)):
opcode = get_opcode(bytearray.fromhex(inputs[i]))
self.assertEqual(opcode, expected[i])
def test_extract_function_to_file(self):
self.assertTrue(os.path.exists(self.file))
extracted = os.path.join(self.tmpdir, "extracted.csv")
extract_function_to_file(self.file, extracted)
# can't check the content, so just hope for the best and check method
# completition
with open(extracted, "r") as fp:
read = csv.reader(fp, delimiter=",")
self.assertEqual(sum(1 for _ in read), 10) | 0.141845 | 0.115636 |
import argparse
import numpy as np
import scipy.io as sio
from niio import loaded
import os
from fragmenter import RegionExtractor as re
from congrads import conmap
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--subject',
help='Input subject name.',
required=True, type=str)
parser.add_argument('-f', '--features',
help='Feature data file.',
required=True, type=str)
parser.add_argument('-l', '--label',
help='Label file.', required=True,
type=str)
parser.add_argument('-sr', '--sroi',
help='Source rois.', required=True,
type=str)
parser.add_argument('-tr', '--troi',
help='Target rois.', required=False,
type=str, default=None)
parser.add_argument('-hemi', '--hemisphere',
help='Hemisphere to process.',
required=False, default='L',
choices=['L', 'R'], type=str)
parser.add_argument('-d', '--dir',
help='Output directory.',
required=True, type=str)
parser.add_argument('-bo', '--base_out',
help='Base output name, without extension.',
required=True, type=str)
parser.add_argument('-pf', '--full',
help='Process full.', default=True,
required=False, type=bool, choices=[True, False])
parser.add_argument('-pi', '--iters',
help='Process iterations.', default=True,
required=False, type=bool, choices=[True, False])
args = parser.parse_args()
print(args)
def eta2(data, sinds, tinds):
"""
Sub-method for generating eta2 and correlation matrices.
Parameters:
- - - - -
data: float, array
input data array
sinds, tinds: list
source and target indices
"""
data = (data-data.mean(1)[:, None]) / (data.std(1)[:, None])
A = data[sinds, :]
A[np.isnan(A)] = 0
A[np.isinf(A)] = 0
A = A.T
# get target region data matrix
B = data[tinds, :]
B[np.isnan(B)] = 0
B[np.isinf(B)] = 0
zeros = (np.abs(B).sum(1) == 0)
B = B[~zeros, :]
B = B.T
print('Computing voxel-wise connectivity fingerprints...')
[evecs, Bhat, evals] = conmap.pca(B)
R = conmap.corr(A, Bhat)
print('Computing similarity matrix.')
E2 = conmap.eta2(R)
return [E2, R]
if not os.path.exists(args.dir):
print('Output directory does not exist -- creating now.')
os.mkdir(args.dir)
# Load region of interest
if not os.path.isfile(args.label):
raise FileExistsError('Label file does not exist.')
else:
label = loaded.load(args.label)
R = re.Extractor(args.label)
index_map = R.map_regions()
# get source and target indices
sinds = index_map[args.sroi]
if args.troi:
tinds = index_map[args.troi]
else:
tinds = list(set(np.arange(label.shape[0])).difference(set(sinds)))
# Load feature matrix
if not os.path.isfile(args.features):
raise FileExistsError('Features file does not exist.')
else:
print('Loading feature data.')
F = loaded.load(args.features)
n, p = F.shape
# n_samples should be greater than n_features
if n < p:
F = F.T
F[np.isnan(F)] = 0
F[np.isinf(F)] = 0
if args.full:
print('Processing full.')
fext_eta = '%s%s.%s.Eta2.%s.Full.mat' % (
args.dir, args.subject, args.hemisphere, args.base_out)
fext_cor = '%s%s.%s.Corr.%s.Full.mat' % (
args.dir, args.subject, args.hemisphere, args.base_out)
if not os.path.exists(fext_eta) and not os.path.exists(fext_cor):
[E, R] = eta2(F, sinds, tinds)
r = {'r2': R}
e = {'eta2': E}
sio.savemat(file_name=fext_cor, mdict=r)
sio.savemat(file_name=fext_eta, mdict=e)
if args.iters:
print('Processing iterations.')
ranges = [(0, 1200), (1200, 2400), (2400, 3600), (3600, 4800)]
for itx, inds in enumerate(ranges):
r_data = F[:, inds[0]:inds[1]]
[E, R] = eta2(r_data, sinds, tinds)
e = {'eta2': E}
fext_eta = '%s%s.%s.Eta2.%s.Iter.%i.mat' % (
args.dir, args.subject, args.hemisphere, args.base_out, itx)
sio.savemat(file_name=fext_eta, mdict=e) | bin/eta2_regions.py | import argparse
import numpy as np
import scipy.io as sio
from niio import loaded
import os
from fragmenter import RegionExtractor as re
from congrads import conmap
parser = argparse.ArgumentParser()
parser.add_argument('-s', '--subject',
help='Input subject name.',
required=True, type=str)
parser.add_argument('-f', '--features',
help='Feature data file.',
required=True, type=str)
parser.add_argument('-l', '--label',
help='Label file.', required=True,
type=str)
parser.add_argument('-sr', '--sroi',
help='Source rois.', required=True,
type=str)
parser.add_argument('-tr', '--troi',
help='Target rois.', required=False,
type=str, default=None)
parser.add_argument('-hemi', '--hemisphere',
help='Hemisphere to process.',
required=False, default='L',
choices=['L', 'R'], type=str)
parser.add_argument('-d', '--dir',
help='Output directory.',
required=True, type=str)
parser.add_argument('-bo', '--base_out',
help='Base output name, without extension.',
required=True, type=str)
parser.add_argument('-pf', '--full',
help='Process full.', default=True,
required=False, type=bool, choices=[True, False])
parser.add_argument('-pi', '--iters',
help='Process iterations.', default=True,
required=False, type=bool, choices=[True, False])
args = parser.parse_args()
print(args)
def eta2(data, sinds, tinds):
"""
Sub-method for generating eta2 and correlation matrices.
Parameters:
- - - - -
data: float, array
input data array
sinds, tinds: list
source and target indices
"""
data = (data-data.mean(1)[:, None]) / (data.std(1)[:, None])
A = data[sinds, :]
A[np.isnan(A)] = 0
A[np.isinf(A)] = 0
A = A.T
# get target region data matrix
B = data[tinds, :]
B[np.isnan(B)] = 0
B[np.isinf(B)] = 0
zeros = (np.abs(B).sum(1) == 0)
B = B[~zeros, :]
B = B.T
print('Computing voxel-wise connectivity fingerprints...')
[evecs, Bhat, evals] = conmap.pca(B)
R = conmap.corr(A, Bhat)
print('Computing similarity matrix.')
E2 = conmap.eta2(R)
return [E2, R]
if not os.path.exists(args.dir):
print('Output directory does not exist -- creating now.')
os.mkdir(args.dir)
# Load region of interest
if not os.path.isfile(args.label):
raise FileExistsError('Label file does not exist.')
else:
label = loaded.load(args.label)
R = re.Extractor(args.label)
index_map = R.map_regions()
# get source and target indices
sinds = index_map[args.sroi]
if args.troi:
tinds = index_map[args.troi]
else:
tinds = list(set(np.arange(label.shape[0])).difference(set(sinds)))
# Load feature matrix
if not os.path.isfile(args.features):
raise FileExistsError('Features file does not exist.')
else:
print('Loading feature data.')
F = loaded.load(args.features)
n, p = F.shape
# n_samples should be greater than n_features
if n < p:
F = F.T
F[np.isnan(F)] = 0
F[np.isinf(F)] = 0
if args.full:
print('Processing full.')
fext_eta = '%s%s.%s.Eta2.%s.Full.mat' % (
args.dir, args.subject, args.hemisphere, args.base_out)
fext_cor = '%s%s.%s.Corr.%s.Full.mat' % (
args.dir, args.subject, args.hemisphere, args.base_out)
if not os.path.exists(fext_eta) and not os.path.exists(fext_cor):
[E, R] = eta2(F, sinds, tinds)
r = {'r2': R}
e = {'eta2': E}
sio.savemat(file_name=fext_cor, mdict=r)
sio.savemat(file_name=fext_eta, mdict=e)
if args.iters:
print('Processing iterations.')
ranges = [(0, 1200), (1200, 2400), (2400, 3600), (3600, 4800)]
for itx, inds in enumerate(ranges):
r_data = F[:, inds[0]:inds[1]]
[E, R] = eta2(r_data, sinds, tinds)
e = {'eta2': E}
fext_eta = '%s%s.%s.Eta2.%s.Iter.%i.mat' % (
args.dir, args.subject, args.hemisphere, args.base_out, itx)
sio.savemat(file_name=fext_eta, mdict=e) | 0.499512 | 0.179207 |
import flask
import os
import sendgrid
import orton_restitution
app = flask.Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
@app.route('/')
def index():
"""Index page."""
return flask.render_template('index.html')
@app.route('/send-email', methods=['POST'])
def send_email():
email = flask.request.form['email']
if '@' not in email or email.endswith('@georgeschool.org'):
if '@' not in email:
user = email
email += '@georgeschool.org'
elif email.endswith('@georgeschool.org'):
user = email[:-len('@georgeschool.org')]
should_send = True
ort_res = orton_restitution.OrtonRestitution(
google_drive_username,
google_drive_password,
google_drive_spreadsheet_key
)
try:
student = ort_res.get_student(user)
except ValueError:
should_send = False
if should_send:
sg = sendgrid.SendGridClient(sendgrid_username, sendgrid_password, raise_errors=True)
message = sendgrid.Mail()
message.add_to('{} <{}>'.format(student.name, email))
message.set_subject('Your Orton Restitution History')
msg = 'As requested, your Orton restitution history is here.\n\n'
for rest in student.restitutions:
msg += str(rest) + '\n'
if not student.restitutions:
msg += 'You have no restitutions.\n'
msg += '\nIf you have any questions or concerns, please contact the Orton staff.'
message.set_text(msg)
message.set_from('Orton <<EMAIL>>')
_, msg = sg.send(message)
flask.flash('Email sent to {}.'.format(email))
return flask.redirect('/')
flask.flash('Improper email.')
return flask.redirect('/')
sendgrid_username = os.getenv('SENDGRID_USERNAME')
sendgrid_password = os.getenv('SENDGRID_PASSWORD')
google_drive_username = os.getenv("GOOGLE_DRIVE_USERNAME")
google_drive_password = os.getenv("GOOGLE_DRIVE_PASSWORD")
google_drive_spreadsheet_key = os.getenv("GOOGLE_DRIVE_SPREADSHEET_KEY")
ADMINS = ['<EMAIL>']
if not app.debug:
import logging
from logging.handlers import SMTPHandler
mail_handler = SMTPHandler(
'smtp.sendgrid.net',
'<EMAIL>',
ADMINS, 'OrtRes Failed',
credentials=(sendgrid_username, sendgrid_password)
)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
if __name__ == '__main__':
app.debug = True
app.run() | web.py |
import flask
import os
import sendgrid
import orton_restitution
app = flask.Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY')
@app.route('/')
def index():
"""Index page."""
return flask.render_template('index.html')
@app.route('/send-email', methods=['POST'])
def send_email():
email = flask.request.form['email']
if '@' not in email or email.endswith('@georgeschool.org'):
if '@' not in email:
user = email
email += '@georgeschool.org'
elif email.endswith('@georgeschool.org'):
user = email[:-len('@georgeschool.org')]
should_send = True
ort_res = orton_restitution.OrtonRestitution(
google_drive_username,
google_drive_password,
google_drive_spreadsheet_key
)
try:
student = ort_res.get_student(user)
except ValueError:
should_send = False
if should_send:
sg = sendgrid.SendGridClient(sendgrid_username, sendgrid_password, raise_errors=True)
message = sendgrid.Mail()
message.add_to('{} <{}>'.format(student.name, email))
message.set_subject('Your Orton Restitution History')
msg = 'As requested, your Orton restitution history is here.\n\n'
for rest in student.restitutions:
msg += str(rest) + '\n'
if not student.restitutions:
msg += 'You have no restitutions.\n'
msg += '\nIf you have any questions or concerns, please contact the Orton staff.'
message.set_text(msg)
message.set_from('Orton <<EMAIL>>')
_, msg = sg.send(message)
flask.flash('Email sent to {}.'.format(email))
return flask.redirect('/')
flask.flash('Improper email.')
return flask.redirect('/')
sendgrid_username = os.getenv('SENDGRID_USERNAME')
sendgrid_password = os.getenv('SENDGRID_PASSWORD')
google_drive_username = os.getenv("GOOGLE_DRIVE_USERNAME")
google_drive_password = os.getenv("GOOGLE_DRIVE_PASSWORD")
google_drive_spreadsheet_key = os.getenv("GOOGLE_DRIVE_SPREADSHEET_KEY")
ADMINS = ['<EMAIL>']
if not app.debug:
import logging
from logging.handlers import SMTPHandler
mail_handler = SMTPHandler(
'smtp.sendgrid.net',
'<EMAIL>',
ADMINS, 'OrtRes Failed',
credentials=(sendgrid_username, sendgrid_password)
)
mail_handler.setLevel(logging.ERROR)
app.logger.addHandler(mail_handler)
if __name__ == '__main__':
app.debug = True
app.run() | 0.21917 | 0.049474 |
from pycont import Contract, Template, TemplateError
import unittest
import trafaret as t
class TestValidator(unittest.TestCase):
def test_template(self):
with self.assertRaises(ValueError):
template = Template('error')
trafaret = t.String()
template = Template(trafaret)
self.assertEqual(template.template, [trafaret])
template.check('test')
with self.assertRaises(ValueError):
template.check(42)
template.template = t.Int()
template.check(42)
del template.template
with self.assertRaises(ValueError):
template.check('test')
def test_default(self):
trafaret = t.String()
template = Template(trafaret, 'null')
self.assertEqual(template.default, 'null')
template.default = 'new'
self.assertEqual(template.default, 'new')
with self.assertRaises(ValueError):
template.default = 42
del template.template
with self.assertRaises(ValueError):
template.default = 42
del template.default
self.assertIsNone(template.default)
def test_simple_validator(self):
# Create contract
trafaret = t.Trafaret()
template = Template(trafaret)
contract = Contract(template)
self.assertEqual(contract.template, template)
new_template = Template(trafaret)
contract.template = new_template
self.assertEqual(contract.template, new_template)
# Int
int_t = Template(t.Int())
contract = Contract(int_t)
# String
string_t = Template(t.String())
contract = Contract(string_t)
# Dict
dict_t = Template(t.Dict({
'id': t.Int,
'email': t.Email
}))
contract.template = dict_t
# List
list_t = Template(t.List(t.Int))
contract.template = list_t
def test_list_validator(self):
list_t = [
Template(t.Int()),
Template(t.List(t.Int)),
Template(t.Dict({'id': t.Int, 'val': t.String})),
]
contract = Contract(list_t)
list_t = [
Template(t.Int()),
'error',
Template(t.Dict({'id': t.Int, 'val': t.String})),
]
with self.assertRaises(ValueError):
contract.template = list_t
with self.assertRaises(ValueError):
contract = Contract(list_t)
def test_dict_validator(self):
dict_t = {
'id': Template(t.Int(gt=0)),
'val': Template(t.String()),
}
contract = Contract(dict_t)
dict_t = {
'id': Template(t.Int(gt=0)),
'val': 'error',
}
with self.assertRaises(ValueError):
contract.template = dict_t
with self.assertRaises(ValueError):
contract = Contract(dict_t)
dict_t = {
12: Template(t.Int(gt=0)),
'val': 'error',
}
with self.assertRaises(TypeError):
contract = Contract(dict_t)
def test_binary_templates(self):
tempalte_1 = Template(t.Int())
tempalte_2 = Template(t.String())
contract = Contract(tempalte_1 | tempalte_2)
result = contract(42)
self.assertEqual(result, 42)
result = contract('test')
self.assertEqual(result, 'test')
with self.assertRaises(ValueError):
result = contract([123])
tempalte_1 = Template(t.Int(), default=42)
tempalte_2 = Template(t.String(), default='Test')
with self.assertRaises(TemplateError):
tempalte = tempalte_1 | tempalte_2
tempalte_1 = Template(t.Int(), default=42)
tempalte_2 = Template(t.String())
tempalte = tempalte_1 | tempalte_2 # noqa
tempalte_1 = Template(t.Int())
tempalte_2 = Template(t.String(), default='Test')
tempalte = tempalte_1 | tempalte_2 # noqa | tests/test_validator.py | from pycont import Contract, Template, TemplateError
import unittest
import trafaret as t
class TestValidator(unittest.TestCase):
def test_template(self):
with self.assertRaises(ValueError):
template = Template('error')
trafaret = t.String()
template = Template(trafaret)
self.assertEqual(template.template, [trafaret])
template.check('test')
with self.assertRaises(ValueError):
template.check(42)
template.template = t.Int()
template.check(42)
del template.template
with self.assertRaises(ValueError):
template.check('test')
def test_default(self):
trafaret = t.String()
template = Template(trafaret, 'null')
self.assertEqual(template.default, 'null')
template.default = 'new'
self.assertEqual(template.default, 'new')
with self.assertRaises(ValueError):
template.default = 42
del template.template
with self.assertRaises(ValueError):
template.default = 42
del template.default
self.assertIsNone(template.default)
def test_simple_validator(self):
# Create contract
trafaret = t.Trafaret()
template = Template(trafaret)
contract = Contract(template)
self.assertEqual(contract.template, template)
new_template = Template(trafaret)
contract.template = new_template
self.assertEqual(contract.template, new_template)
# Int
int_t = Template(t.Int())
contract = Contract(int_t)
# String
string_t = Template(t.String())
contract = Contract(string_t)
# Dict
dict_t = Template(t.Dict({
'id': t.Int,
'email': t.Email
}))
contract.template = dict_t
# List
list_t = Template(t.List(t.Int))
contract.template = list_t
def test_list_validator(self):
list_t = [
Template(t.Int()),
Template(t.List(t.Int)),
Template(t.Dict({'id': t.Int, 'val': t.String})),
]
contract = Contract(list_t)
list_t = [
Template(t.Int()),
'error',
Template(t.Dict({'id': t.Int, 'val': t.String})),
]
with self.assertRaises(ValueError):
contract.template = list_t
with self.assertRaises(ValueError):
contract = Contract(list_t)
def test_dict_validator(self):
dict_t = {
'id': Template(t.Int(gt=0)),
'val': Template(t.String()),
}
contract = Contract(dict_t)
dict_t = {
'id': Template(t.Int(gt=0)),
'val': 'error',
}
with self.assertRaises(ValueError):
contract.template = dict_t
with self.assertRaises(ValueError):
contract = Contract(dict_t)
dict_t = {
12: Template(t.Int(gt=0)),
'val': 'error',
}
with self.assertRaises(TypeError):
contract = Contract(dict_t)
def test_binary_templates(self):
tempalte_1 = Template(t.Int())
tempalte_2 = Template(t.String())
contract = Contract(tempalte_1 | tempalte_2)
result = contract(42)
self.assertEqual(result, 42)
result = contract('test')
self.assertEqual(result, 'test')
with self.assertRaises(ValueError):
result = contract([123])
tempalte_1 = Template(t.Int(), default=42)
tempalte_2 = Template(t.String(), default='Test')
with self.assertRaises(TemplateError):
tempalte = tempalte_1 | tempalte_2
tempalte_1 = Template(t.Int(), default=42)
tempalte_2 = Template(t.String())
tempalte = tempalte_1 | tempalte_2 # noqa
tempalte_1 = Template(t.Int())
tempalte_2 = Template(t.String(), default='Test')
tempalte = tempalte_1 | tempalte_2 # noqa | 0.483648 | 0.598723 |
import json
import shlex
from abc import abstractmethod
from contextlib import contextmanager
from copy import deepcopy
from os import getenv, getcwd, chdir, environ
from os.path import join, basename, normpath, abspath
from typing import Optional, List, Generator, Dict, Tuple, Union
import click
from jsonschema.validators import Draft7Validator
__all__ = [
# Contexts
'GametaContext', 'gameta_context',
]
SHELL = getenv('SHELL', '/bin/sh')
class File(object):
"""
Generic file interface for Gameta file formats
Attributes:
context (GametaContext): Reference to Gameta Context
file_name (str): Name of the reference file
"""
def __init__(self, context: 'GametaContext', file_name: str):
self.context = context
self.file_name = file_name
@property
def file(self) -> str:
"""
Returns the absolute path to the reference file
Returns:
str: Absolute path to the file
"""
return join(self.context.project_dir, self.file_name)
@abstractmethod
def load(self) -> None:
"""
Abstractmethod to load data and validate data from the file and populate the GametaContext
Returns:
None
"""
@abstractmethod
def export(self) -> None:
"""
Abstractmethod to export data from the GametaContext to the file
Returns:
None
"""
class GitIgnore(File):
"""
Interface for the .gitignore file
Attributes:
context (GametaContext): Reference to Gameta Context
file_name (str): Reference to the .gitignore file
"""
def __init__(self, context: 'GametaContext', file_name: str = '.gitignore'):
super(GitIgnore, self).__init__(context, file_name)
def load(self) -> None:
"""
Loads data from the .gitignore file and populates the GametaContext
Returns:
None
"""
try:
with open(self.file, 'r') as f:
self.context.gitignore_data = f.readlines()
except FileNotFoundError:
return
except Exception as e:
self.context.gitignore_data = []
click.echo(f"Could not load {self.file_name} file due to: {e.__class__.__name__}.{str(e)}")
def export(self) -> None:
"""
Exports data from the GametaContext to the .gitignore file
Returns:
None
"""
try:
with open(self.file, 'w') as f:
f.writelines(self.context.gitignore_data)
except Exception as e:
click.echo(f"Could not export data to {self.file_name} file: {e.__class__.__name__}.{str(e)}")
class Meta(File):
"""
Interface for the .meta file
Attributes:
context (GametaContext): Reference to Gameta Context
file_name (str): Reference to the .meta file
"""
def __init__(self, context: 'GametaContext', file_name: str = '.meta'):
super(Meta, self).__init__(context, file_name)
def load(self) -> None:
"""
Loads data from the .meta file, validates it and populates the GametaContext
Returns:
None
"""
# Attempt to load .meta file
try:
with open(self.file_name, 'r') as f:
self.context.gameta_data = json.load(f)
except FileNotFoundError:
return
except Exception as e:
click.echo(f"Could not load {self.file_name} file due to: {e.__class__.__name__}.{str(e)}")
# Validate repositories
try:
for repo in self.context.gameta_data['projects'].values():
self.context.validators['repositories'].validate(repo)
self.context.repositories = self.context.gameta_data['projects']
self.context.is_metarepo = True
self.context.generate_tags()
except Exception as e:
self.context.repositories = {}
self.context.tags = {}
click.echo(f"Malformed repository element, error: {e.__class__.__name__}.{str(e)}")
# Validate commands
try:
for command in self.context.gameta_data.get('commands', {}).values():
self.context.validators['commands'].validate(command)
self.context.commands = self.context.gameta_data.get('commands', {})
except Exception as e:
self.context.commands = {}
click.echo(f"Malformed commands element, error: {e.__class__.__name__}.{str(e)}")
# Validate constants
try:
self.context.validators['constants'].validate(self.context.gameta_data.get('constants', {}))
self.context.constants = self.context.gameta_data.get('constants', {})
except Exception as e:
self.context.constants = {}
click.echo(f"Malformed constants element, error: {e.__class__.__name__}.{str(e)}")
def export(self) -> None:
"""
Exports data from the GametaContext to the .meta file
Returns:
None
"""
try:
self.context.gameta_data['projects'] = self.context.repositories
if self.context.commands:
self.context.gameta_data['commands'] = self.context.commands
if self.context.constants:
self.context.gameta_data['constants'] = self.context.constants
with open(self.file, 'w') as f:
json.dump(self.context.gameta_data, f, indent=2)
except Exception as e:
click.echo(f"Could not export data to {self.file_name} file: {e.__class__.__name__}.{str(e)}")
class GametaContext(object):
"""
GametaContext for the current Gameta session
Attributes:
__schema__ (Dict): JSON Schema for Gameta .meta file
validators (Dict[str, jsonschema.Draft7Validator]): JSON Schema validators for each object component
reserved_params (Dict[str, List[str]): Reserved parameters for each object group
project_dir (Optional[str]): Project directory
is_metarepo (bool): Project is a metarepo
gameta_data (Dict): Gameta data extracted and exported
repositories (Dict[str, Dict]): Data of all the repositories contained in the metarepo
tags (Dict[str, List[str]]): Repository data organised according to tags
constants (Dict[str, Union[str, int, bool, float]]): Gameta constants data extracted
commands (Dict): Gameta commands data extracted
gitignore_data (List[str]): Gitignore data extracted from the .gitignore file
env_vars (Dict): Extracted environment variables with keys prefixed with $
files (Dict[str, File]): File formats supported
"""
__schema__: Dict = {
'$schema': "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"repositories": {
"$ref": "#/definitions/repositories"
},
"commands": {
"$ref": "#/definitions/commands"
},
"constants": {
"$ref": "#/definitions/constants"
},
"required": [
"repositories"
]
},
'definitions': {
"repositories": {
"type": "object",
"properties": {
"url": {
"type": ["string", "null"],
"format": "uri"
},
"path": {
"type": "string"
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
},
"__metarepo__": {
"type": "boolean"
}
},
"required": [
"url", "path", "__metarepo__"
]
},
"commands": {
"type": "object",
"properties": {
"commands": {
"type": "array",
"items": {
"type": "string"
},
},
"description": {
"type": "string"
},
"raise_errors": {
"type": "boolean"
},
"shell": {
"type": "boolean"
},
"python": {
"type": "boolean"
},
"verbose": {
"type": "boolean"
},
"repositories": {
"type": "array",
"items": {
"type": "string"
},
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
}
},
"minProperties": 6,
"maxProperties": 8,
"additionalProperties": False,
},
"constants": {
"type": "object",
"propertyNames": {
"pattern": "^[$A-Z0-9_-]"
}
}
}
}
validators = {
'meta': Draft7Validator(__schema__),
'repositories': Draft7Validator(__schema__['definitions']['repositories']),
'commands': Draft7Validator(__schema__['definitions']['commands']),
'constants': Draft7Validator(__schema__['definitions']['constants'])
}
reserved_params: Dict[str, List[str]] = {
'repositories': list(__schema__['definitions']['repositories']['properties'].keys()),
'commands': list(__schema__['definitions']['commands']['properties'].keys())
}
def __init__(self):
self.project_dir: Optional[str] = None
self.gitignore_data: List[str] = []
self.is_metarepo: bool = False
self.gameta_data: Dict = {}
self.constants: Dict[str, Union[str, int, bool, float]] = {}
self.commands: Dict = {}
self.repositories: Dict[str, Dict] = {}
self.tags: Dict[str, List[str]] = {}
self.env_vars: Dict = {
'$' + k.upper(): v
for k, v in environ.items()
}
self.files: Dict[str, File] = {
'meta': Meta(self),
'gitignore': GitIgnore(self)
}
@property
def project_name(self) -> str:
"""
Returns the name of the project
Returns:
str: Name of the project
"""
return basename(self.project_dir)
@property
def meta(self) -> str:
"""
Returns the path to the .meta file of the project, i.e. where it should be if the Project has not been
initialised
Returns:
str: Path to the project's .meta file
"""
return self.files['meta'].file
@property
def gitignore(self) -> str:
"""
Returns the path to the .gitignore file of the project, i.e. where it should be if the Project has not been
initialised
Returns:
str: Path to the project's .gitignore file
"""
return self.files['gitignore'].file
def add_gitignore(self, path: str) -> None:
"""
Adds the path to the gitignore_data
Args:
path (str): Path to be added
Returns:
None
"""
self.gitignore_data.append(path + '/\n')
def remove_gitignore(self, path: str) -> None:
"""
Removes the path from the gitignore_data
Args:
path (str): Path to be removed
Returns:
None
"""
try:
self.gitignore_data.remove(path + '/\n')
except ValueError:
return
def is_primary_metarepo(self, repo: str) -> bool:
"""
Returns a boolean if the repository is a primary meta-repository
Args:
repo (str): Repository to check
Returns:
bool: Flag to indicate if repository is a primary meta-repository
"""
return abspath(self.repositories[repo]["path"]) == self.project_dir
def load(self) -> None:
"""
Loads data from all supported file formats
Returns:
None
"""
for file, interface in self.files.items():
interface.load()
def export(self) -> None:
"""
Exports data to all supported file formats
Returns:
None
"""
for file, interface in self.files.items():
interface.export()
def generate_tags(self) -> None:
"""
Updates the tag indexes of the repositories
Returns:
None
"""
for repo, details in self.repositories.items():
for tag in details.get('tags', []):
if tag in self.tags:
self.tags[tag].append(repo)
else:
self.tags[tag] = [repo]
def apply(
self,
commands: List[str],
repos: List[str] = (),
shell: bool = False,
python: bool = False,
) -> Generator[Tuple[str, str], None, None]:
"""
Yields a list of commands to all repositories or a selected set of them, substitutes relevant parameters stored
in .meta file
Args:
commands (List[str]): Commands to be applied
repos (List[str]): Selected set of repositories
shell (bool): Flag to indicate if a separate shell should be used
python (bool): Flag to indicate if commands are to be tokenised as Python commands
Returns:
None
"""
repositories: List[Tuple[str, Dict[str, str]]] = \
[(repo, details) for repo, details in self.repositories.items() if repo in repos] or \
list(self.repositories.items())
for repo, details in repositories:
# Generate complete set of parameters for substitution
with self.cd(details['path']):
repo_commands: List[str] = [
c.format(**self.generate_parameters(repo, details, python)) for c in deepcopy(commands)
]
if python:
command: List[str] = self.python(repo_commands)
elif shell:
command: List[str] = self.shell(repo_commands)
else:
command: List[str] = self.tokenise(' && '.join(repo_commands))
yield repo, command
def generate_parameters(self, repo: str, repo_details: Dict, python: bool = False) -> Dict:
"""
Generates the set of parameters for each repository to be substituted into command strings.
Args:
repo (str): Repository name of parameters to be generated
repo_details (Dict): Repository details from .meta file
python (bool): Flag to indicate if Python variables should be generated, defaults to False
Returns:
Dict: Generated set of parameters
"""
combined_details: Dict = {
k: v.format(**self.env_vars) if isinstance(v, str) else v
for k, v in deepcopy(repo_details).items()
}
if python:
repositories: Dict = deepcopy(self.repositories)
repositories[repo] = deepcopy(combined_details)
combined_details.update(
{
'__repos__':
json.dumps(repositories)
.replace("true", "True")
.replace("false", "False")
.replace("null", "None")
}
)
combined_details.update(self.constants)
combined_details.update(self.env_vars)
return combined_details
@staticmethod
def tokenise(command: str) -> List[str]:
"""
Tokenises the commands into a form that is readily acceptable by subprocess
Args:
command (str): Constructed commands to be tokenised
Returns:
List[str]: Tokenised commands
"""
return shlex.split(command)
@contextmanager
def cd(self, sub_directory: str) -> Generator[str, None, None]:
"""
Changes directory to a subdirectory within the project
Args:
sub_directory (str): Relative subdirectory within the project
Returns:
Generator[str, None, None]: Path to current directory
"""
cwd = getcwd()
path = normpath(join(self.project_dir, sub_directory.lstrip('/')))
chdir(path)
yield path
chdir(cwd)
def shell(self, commands: List[str]) -> List[str]:
"""
Prepares commands to be executed in a separate shell as subprocess does not natively handle piping
Args:
commands (List[str]): User-defined commands
Returns:
List[str]: Shell command string to be executed by subprocess
"""
return self.tokenise(
f'{SHELL} -c "' +
' && '.join(commands) +
'"'
)
def python(self, commands: List[str]) -> List[str]:
"""
Prepares commands to be executed by Python interpreter via shell
Args:
commands List[str]: Python scripts
Returns:
List[str]: Python prepared commands to be executed by subprocess
"""
return self.shell(
["python3 -c \'{}\'".format(command.replace('"', '\\\"')) for command in commands]
)
gameta_context = click.make_pass_decorator(GametaContext, ensure=True) | gameta/context.py | import json
import shlex
from abc import abstractmethod
from contextlib import contextmanager
from copy import deepcopy
from os import getenv, getcwd, chdir, environ
from os.path import join, basename, normpath, abspath
from typing import Optional, List, Generator, Dict, Tuple, Union
import click
from jsonschema.validators import Draft7Validator
__all__ = [
# Contexts
'GametaContext', 'gameta_context',
]
SHELL = getenv('SHELL', '/bin/sh')
class File(object):
"""
Generic file interface for Gameta file formats
Attributes:
context (GametaContext): Reference to Gameta Context
file_name (str): Name of the reference file
"""
def __init__(self, context: 'GametaContext', file_name: str):
self.context = context
self.file_name = file_name
@property
def file(self) -> str:
"""
Returns the absolute path to the reference file
Returns:
str: Absolute path to the file
"""
return join(self.context.project_dir, self.file_name)
@abstractmethod
def load(self) -> None:
"""
Abstractmethod to load data and validate data from the file and populate the GametaContext
Returns:
None
"""
@abstractmethod
def export(self) -> None:
"""
Abstractmethod to export data from the GametaContext to the file
Returns:
None
"""
class GitIgnore(File):
"""
Interface for the .gitignore file
Attributes:
context (GametaContext): Reference to Gameta Context
file_name (str): Reference to the .gitignore file
"""
def __init__(self, context: 'GametaContext', file_name: str = '.gitignore'):
super(GitIgnore, self).__init__(context, file_name)
def load(self) -> None:
"""
Loads data from the .gitignore file and populates the GametaContext
Returns:
None
"""
try:
with open(self.file, 'r') as f:
self.context.gitignore_data = f.readlines()
except FileNotFoundError:
return
except Exception as e:
self.context.gitignore_data = []
click.echo(f"Could not load {self.file_name} file due to: {e.__class__.__name__}.{str(e)}")
def export(self) -> None:
"""
Exports data from the GametaContext to the .gitignore file
Returns:
None
"""
try:
with open(self.file, 'w') as f:
f.writelines(self.context.gitignore_data)
except Exception as e:
click.echo(f"Could not export data to {self.file_name} file: {e.__class__.__name__}.{str(e)}")
class Meta(File):
"""
Interface for the .meta file
Attributes:
context (GametaContext): Reference to Gameta Context
file_name (str): Reference to the .meta file
"""
def __init__(self, context: 'GametaContext', file_name: str = '.meta'):
super(Meta, self).__init__(context, file_name)
def load(self) -> None:
"""
Loads data from the .meta file, validates it and populates the GametaContext
Returns:
None
"""
# Attempt to load .meta file
try:
with open(self.file_name, 'r') as f:
self.context.gameta_data = json.load(f)
except FileNotFoundError:
return
except Exception as e:
click.echo(f"Could not load {self.file_name} file due to: {e.__class__.__name__}.{str(e)}")
# Validate repositories
try:
for repo in self.context.gameta_data['projects'].values():
self.context.validators['repositories'].validate(repo)
self.context.repositories = self.context.gameta_data['projects']
self.context.is_metarepo = True
self.context.generate_tags()
except Exception as e:
self.context.repositories = {}
self.context.tags = {}
click.echo(f"Malformed repository element, error: {e.__class__.__name__}.{str(e)}")
# Validate commands
try:
for command in self.context.gameta_data.get('commands', {}).values():
self.context.validators['commands'].validate(command)
self.context.commands = self.context.gameta_data.get('commands', {})
except Exception as e:
self.context.commands = {}
click.echo(f"Malformed commands element, error: {e.__class__.__name__}.{str(e)}")
# Validate constants
try:
self.context.validators['constants'].validate(self.context.gameta_data.get('constants', {}))
self.context.constants = self.context.gameta_data.get('constants', {})
except Exception as e:
self.context.constants = {}
click.echo(f"Malformed constants element, error: {e.__class__.__name__}.{str(e)}")
def export(self) -> None:
"""
Exports data from the GametaContext to the .meta file
Returns:
None
"""
try:
self.context.gameta_data['projects'] = self.context.repositories
if self.context.commands:
self.context.gameta_data['commands'] = self.context.commands
if self.context.constants:
self.context.gameta_data['constants'] = self.context.constants
with open(self.file, 'w') as f:
json.dump(self.context.gameta_data, f, indent=2)
except Exception as e:
click.echo(f"Could not export data to {self.file_name} file: {e.__class__.__name__}.{str(e)}")
class GametaContext(object):
"""
GametaContext for the current Gameta session
Attributes:
__schema__ (Dict): JSON Schema for Gameta .meta file
validators (Dict[str, jsonschema.Draft7Validator]): JSON Schema validators for each object component
reserved_params (Dict[str, List[str]): Reserved parameters for each object group
project_dir (Optional[str]): Project directory
is_metarepo (bool): Project is a metarepo
gameta_data (Dict): Gameta data extracted and exported
repositories (Dict[str, Dict]): Data of all the repositories contained in the metarepo
tags (Dict[str, List[str]]): Repository data organised according to tags
constants (Dict[str, Union[str, int, bool, float]]): Gameta constants data extracted
commands (Dict): Gameta commands data extracted
gitignore_data (List[str]): Gitignore data extracted from the .gitignore file
env_vars (Dict): Extracted environment variables with keys prefixed with $
files (Dict[str, File]): File formats supported
"""
__schema__: Dict = {
'$schema': "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"repositories": {
"$ref": "#/definitions/repositories"
},
"commands": {
"$ref": "#/definitions/commands"
},
"constants": {
"$ref": "#/definitions/constants"
},
"required": [
"repositories"
]
},
'definitions': {
"repositories": {
"type": "object",
"properties": {
"url": {
"type": ["string", "null"],
"format": "uri"
},
"path": {
"type": "string"
},
"tags": {
"type": "array",
"items": {
"type": "string"
}
},
"__metarepo__": {
"type": "boolean"
}
},
"required": [
"url", "path", "__metarepo__"
]
},
"commands": {
"type": "object",
"properties": {
"commands": {
"type": "array",
"items": {
"type": "string"
},
},
"description": {
"type": "string"
},
"raise_errors": {
"type": "boolean"
},
"shell": {
"type": "boolean"
},
"python": {
"type": "boolean"
},
"verbose": {
"type": "boolean"
},
"repositories": {
"type": "array",
"items": {
"type": "string"
},
},
"tags": {
"type": "array",
"items": {
"type": "string"
},
}
},
"minProperties": 6,
"maxProperties": 8,
"additionalProperties": False,
},
"constants": {
"type": "object",
"propertyNames": {
"pattern": "^[$A-Z0-9_-]"
}
}
}
}
validators = {
'meta': Draft7Validator(__schema__),
'repositories': Draft7Validator(__schema__['definitions']['repositories']),
'commands': Draft7Validator(__schema__['definitions']['commands']),
'constants': Draft7Validator(__schema__['definitions']['constants'])
}
reserved_params: Dict[str, List[str]] = {
'repositories': list(__schema__['definitions']['repositories']['properties'].keys()),
'commands': list(__schema__['definitions']['commands']['properties'].keys())
}
def __init__(self):
self.project_dir: Optional[str] = None
self.gitignore_data: List[str] = []
self.is_metarepo: bool = False
self.gameta_data: Dict = {}
self.constants: Dict[str, Union[str, int, bool, float]] = {}
self.commands: Dict = {}
self.repositories: Dict[str, Dict] = {}
self.tags: Dict[str, List[str]] = {}
self.env_vars: Dict = {
'$' + k.upper(): v
for k, v in environ.items()
}
self.files: Dict[str, File] = {
'meta': Meta(self),
'gitignore': GitIgnore(self)
}
@property
def project_name(self) -> str:
"""
Returns the name of the project
Returns:
str: Name of the project
"""
return basename(self.project_dir)
@property
def meta(self) -> str:
"""
Returns the path to the .meta file of the project, i.e. where it should be if the Project has not been
initialised
Returns:
str: Path to the project's .meta file
"""
return self.files['meta'].file
@property
def gitignore(self) -> str:
"""
Returns the path to the .gitignore file of the project, i.e. where it should be if the Project has not been
initialised
Returns:
str: Path to the project's .gitignore file
"""
return self.files['gitignore'].file
def add_gitignore(self, path: str) -> None:
"""
Adds the path to the gitignore_data
Args:
path (str): Path to be added
Returns:
None
"""
self.gitignore_data.append(path + '/\n')
def remove_gitignore(self, path: str) -> None:
"""
Removes the path from the gitignore_data
Args:
path (str): Path to be removed
Returns:
None
"""
try:
self.gitignore_data.remove(path + '/\n')
except ValueError:
return
def is_primary_metarepo(self, repo: str) -> bool:
"""
Returns a boolean if the repository is a primary meta-repository
Args:
repo (str): Repository to check
Returns:
bool: Flag to indicate if repository is a primary meta-repository
"""
return abspath(self.repositories[repo]["path"]) == self.project_dir
def load(self) -> None:
"""
Loads data from all supported file formats
Returns:
None
"""
for file, interface in self.files.items():
interface.load()
def export(self) -> None:
"""
Exports data to all supported file formats
Returns:
None
"""
for file, interface in self.files.items():
interface.export()
def generate_tags(self) -> None:
"""
Updates the tag indexes of the repositories
Returns:
None
"""
for repo, details in self.repositories.items():
for tag in details.get('tags', []):
if tag in self.tags:
self.tags[tag].append(repo)
else:
self.tags[tag] = [repo]
def apply(
self,
commands: List[str],
repos: List[str] = (),
shell: bool = False,
python: bool = False,
) -> Generator[Tuple[str, str], None, None]:
"""
Yields a list of commands to all repositories or a selected set of them, substitutes relevant parameters stored
in .meta file
Args:
commands (List[str]): Commands to be applied
repos (List[str]): Selected set of repositories
shell (bool): Flag to indicate if a separate shell should be used
python (bool): Flag to indicate if commands are to be tokenised as Python commands
Returns:
None
"""
repositories: List[Tuple[str, Dict[str, str]]] = \
[(repo, details) for repo, details in self.repositories.items() if repo in repos] or \
list(self.repositories.items())
for repo, details in repositories:
# Generate complete set of parameters for substitution
with self.cd(details['path']):
repo_commands: List[str] = [
c.format(**self.generate_parameters(repo, details, python)) for c in deepcopy(commands)
]
if python:
command: List[str] = self.python(repo_commands)
elif shell:
command: List[str] = self.shell(repo_commands)
else:
command: List[str] = self.tokenise(' && '.join(repo_commands))
yield repo, command
def generate_parameters(self, repo: str, repo_details: Dict, python: bool = False) -> Dict:
"""
Generates the set of parameters for each repository to be substituted into command strings.
Args:
repo (str): Repository name of parameters to be generated
repo_details (Dict): Repository details from .meta file
python (bool): Flag to indicate if Python variables should be generated, defaults to False
Returns:
Dict: Generated set of parameters
"""
combined_details: Dict = {
k: v.format(**self.env_vars) if isinstance(v, str) else v
for k, v in deepcopy(repo_details).items()
}
if python:
repositories: Dict = deepcopy(self.repositories)
repositories[repo] = deepcopy(combined_details)
combined_details.update(
{
'__repos__':
json.dumps(repositories)
.replace("true", "True")
.replace("false", "False")
.replace("null", "None")
}
)
combined_details.update(self.constants)
combined_details.update(self.env_vars)
return combined_details
@staticmethod
def tokenise(command: str) -> List[str]:
"""
Tokenises the commands into a form that is readily acceptable by subprocess
Args:
command (str): Constructed commands to be tokenised
Returns:
List[str]: Tokenised commands
"""
return shlex.split(command)
@contextmanager
def cd(self, sub_directory: str) -> Generator[str, None, None]:
"""
Changes directory to a subdirectory within the project
Args:
sub_directory (str): Relative subdirectory within the project
Returns:
Generator[str, None, None]: Path to current directory
"""
cwd = getcwd()
path = normpath(join(self.project_dir, sub_directory.lstrip('/')))
chdir(path)
yield path
chdir(cwd)
def shell(self, commands: List[str]) -> List[str]:
"""
Prepares commands to be executed in a separate shell as subprocess does not natively handle piping
Args:
commands (List[str]): User-defined commands
Returns:
List[str]: Shell command string to be executed by subprocess
"""
return self.tokenise(
f'{SHELL} -c "' +
' && '.join(commands) +
'"'
)
def python(self, commands: List[str]) -> List[str]:
"""
Prepares commands to be executed by Python interpreter via shell
Args:
commands List[str]: Python scripts
Returns:
List[str]: Python prepared commands to be executed by subprocess
"""
return self.shell(
["python3 -c \'{}\'".format(command.replace('"', '\\\"')) for command in commands]
)
gameta_context = click.make_pass_decorator(GametaContext, ensure=True) | 0.750553 | 0.207917 |
from __future__ import annotations
from datetime import date, datetime, time
from decimal import Decimal
from typing import Any
from watchmen_data_kernel.common import ask_all_date_formats, ask_full_datetime_formats, ask_time_formats, \
DataKernelException
from watchmen_model.admin import Factor, FactorType
from watchmen_utilities import is_date, is_decimal, is_time
def cast_value_for_factor(value: Any, factor: Factor) -> Any:
if value is None:
return None
factor_type = factor.type
if factor_type in [
FactorType.SEQUENCE, FactorType.NUMBER, FactorType.UNSIGNED, FactorType.FLOOR, FactorType.RESIDENTIAL_AREA,
FactorType.AGE, FactorType.BIZ_SCALE
]:
parsed, decimal_value = is_decimal(value)
if parsed:
return decimal_value
else:
raise DataKernelException(
f'Value[{value}] is incompatible with factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.TEXT:
if isinstance(value, str):
return value
elif isinstance(value, (int, float, Decimal, bool, date, time)):
return str(value)
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type in [
FactorType.ADDRESS, FactorType.ROAD, FactorType.COMMUNITY, FactorType.EMAIL, FactorType.PHONE,
FactorType.MOBILE, FactorType.FAX, FactorType.OCCUPATION, FactorType.ID_NO
]:
if isinstance(value, str):
return value
elif isinstance(value, (int, float, Decimal)):
return str(value)
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
# noinspection PyPep8
elif factor_type in [
FactorType.CONTINENT, FactorType.REGION, FactorType.COUNTRY, FactorType.PROVINCE, FactorType.CITY,
FactorType.DISTRICT, FactorType.RESIDENCE_TYPE, FactorType.GENDER, FactorType.RELIGION, FactorType.NATIONALITY,
FactorType.BIZ_TRADE, FactorType.ENUM
]:
if isinstance(value, str):
return value
elif isinstance(value, (int, Decimal)):
return str(value)
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.FULL_DATETIME:
# noinspection DuplicatedCode
if isinstance(value, datetime):
return value
if isinstance(value, date):
return datetime(year=value.year, month=value.month, day=value.day)
if isinstance(value, time):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
parsed, date_value = is_date(str(value), ask_full_datetime_formats())
if parsed:
return date_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.DATETIME:
# noinspection DuplicatedCode
if isinstance(value, datetime):
return value
if isinstance(value, date):
return datetime(year=value.year, month=value.month, day=value.day)
if isinstance(value, time):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
parsed, date_value = is_date(str(value), ask_all_date_formats())
if parsed:
return date_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type in [
FactorType.DATE, FactorType.DATE_OF_BIRTH
]:
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
if isinstance(value, time):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
parsed, date_value = is_date(value, ask_all_date_formats())
if parsed:
if isinstance(date_value, datetime):
return date_value.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
else:
return date_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.TIME:
if isinstance(value, datetime):
return value.time()
if isinstance(value, date):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
if isinstance(value, time):
return value
parsed, time_value = is_time(value, ask_time_formats())
if parsed:
return time_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type in [
FactorType.YEAR, FactorType.HALF_YEAR, FactorType.QUARTER,
FactorType.MONTH, FactorType.HALF_MONTH, FactorType.TEN_DAYS,
FactorType.WEEK_OF_YEAR, FactorType.WEEK_OF_MONTH, FactorType.HALF_WEEK,
FactorType.DAY_OF_MONTH, FactorType.DAY_OF_WEEK, FactorType.DAY_KIND,
FactorType.HOUR, FactorType.HOUR_KIND,
FactorType.MINUTE, FactorType.SECOND, FactorType.MILLISECOND,
FactorType.AM_PM
]:
# TODO strictly validation is needed or not?
parsed, decimal_value = is_decimal(value)
if parsed:
return decimal_value
else:
raise DataKernelException(
f'Value[{value}] is incompatible with factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.BOOLEAN:
if isinstance(value, bool):
return value
elif isinstance(value, (int, float, Decimal)):
return value != 0
elif isinstance(value, str):
v = value.strip().lower()
if v == 't' or v == 'y' or v == 'yes' or v == 'true':
return True
elif v == 'f' or v == 'n' or v == 'no' or v == 'false':
return False
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
else:
raise DataKernelException(f'Factor type[{factor_type}] is not supported.') | packages/watchmen-data-kernel/src/watchmen_data_kernel/topic_schema/utils.py | from __future__ import annotations
from datetime import date, datetime, time
from decimal import Decimal
from typing import Any
from watchmen_data_kernel.common import ask_all_date_formats, ask_full_datetime_formats, ask_time_formats, \
DataKernelException
from watchmen_model.admin import Factor, FactorType
from watchmen_utilities import is_date, is_decimal, is_time
def cast_value_for_factor(value: Any, factor: Factor) -> Any:
if value is None:
return None
factor_type = factor.type
if factor_type in [
FactorType.SEQUENCE, FactorType.NUMBER, FactorType.UNSIGNED, FactorType.FLOOR, FactorType.RESIDENTIAL_AREA,
FactorType.AGE, FactorType.BIZ_SCALE
]:
parsed, decimal_value = is_decimal(value)
if parsed:
return decimal_value
else:
raise DataKernelException(
f'Value[{value}] is incompatible with factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.TEXT:
if isinstance(value, str):
return value
elif isinstance(value, (int, float, Decimal, bool, date, time)):
return str(value)
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type in [
FactorType.ADDRESS, FactorType.ROAD, FactorType.COMMUNITY, FactorType.EMAIL, FactorType.PHONE,
FactorType.MOBILE, FactorType.FAX, FactorType.OCCUPATION, FactorType.ID_NO
]:
if isinstance(value, str):
return value
elif isinstance(value, (int, float, Decimal)):
return str(value)
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
# noinspection PyPep8
elif factor_type in [
FactorType.CONTINENT, FactorType.REGION, FactorType.COUNTRY, FactorType.PROVINCE, FactorType.CITY,
FactorType.DISTRICT, FactorType.RESIDENCE_TYPE, FactorType.GENDER, FactorType.RELIGION, FactorType.NATIONALITY,
FactorType.BIZ_TRADE, FactorType.ENUM
]:
if isinstance(value, str):
return value
elif isinstance(value, (int, Decimal)):
return str(value)
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.FULL_DATETIME:
# noinspection DuplicatedCode
if isinstance(value, datetime):
return value
if isinstance(value, date):
return datetime(year=value.year, month=value.month, day=value.day)
if isinstance(value, time):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
parsed, date_value = is_date(str(value), ask_full_datetime_formats())
if parsed:
return date_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.DATETIME:
# noinspection DuplicatedCode
if isinstance(value, datetime):
return value
if isinstance(value, date):
return datetime(year=value.year, month=value.month, day=value.day)
if isinstance(value, time):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
parsed, date_value = is_date(str(value), ask_all_date_formats())
if parsed:
return date_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type in [
FactorType.DATE, FactorType.DATE_OF_BIRTH
]:
if isinstance(value, datetime):
return value.date()
if isinstance(value, date):
return value
if isinstance(value, time):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
parsed, date_value = is_date(value, ask_all_date_formats())
if parsed:
if isinstance(date_value, datetime):
return date_value.replace(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
else:
return date_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.TIME:
if isinstance(value, datetime):
return value.time()
if isinstance(value, date):
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
if isinstance(value, time):
return value
parsed, time_value = is_time(value, ask_time_formats())
if parsed:
return time_value
else:
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
elif factor_type in [
FactorType.YEAR, FactorType.HALF_YEAR, FactorType.QUARTER,
FactorType.MONTH, FactorType.HALF_MONTH, FactorType.TEN_DAYS,
FactorType.WEEK_OF_YEAR, FactorType.WEEK_OF_MONTH, FactorType.HALF_WEEK,
FactorType.DAY_OF_MONTH, FactorType.DAY_OF_WEEK, FactorType.DAY_KIND,
FactorType.HOUR, FactorType.HOUR_KIND,
FactorType.MINUTE, FactorType.SECOND, FactorType.MILLISECOND,
FactorType.AM_PM
]:
# TODO strictly validation is needed or not?
parsed, decimal_value = is_decimal(value)
if parsed:
return decimal_value
else:
raise DataKernelException(
f'Value[{value}] is incompatible with factor[name={factor.name}, type={factor_type}].')
elif factor_type == FactorType.BOOLEAN:
if isinstance(value, bool):
return value
elif isinstance(value, (int, float, Decimal)):
return value != 0
elif isinstance(value, str):
v = value.strip().lower()
if v == 't' or v == 'y' or v == 'yes' or v == 'true':
return True
elif v == 'f' or v == 'n' or v == 'no' or v == 'false':
return False
raise DataKernelException(
f'Value[{value}, type={type(value)}] is incompatible with '
f'factor[name={factor.name}, type={factor_type}].')
else:
raise DataKernelException(f'Factor type[{factor_type}] is not supported.') | 0.528777 | 0.283386 |
from selfea.utils.data_structure_utils import return_indices, get_max_value_key, get_min_value_key
from selfea.utils.dask_clients import ClientFuture
from selfea.core._feature_evaluator import FeatureEvaluator
from selfea.default_models.default_xgboost_regressor import DefaultXGBoostRegressor
from collections import defaultdict
import numpy as np
import copy
import HMF
from sklearn.model_selection import KFold
class Selfea():
def __init__(self, debug_mode=False):
self.score_tracking_dict = dict()
self.debug_mode = debug_mode
def setup_evaluation(self, task_manager):
self.task_manager = task_manager
f = HMF.open_file(self.task_manager.root_dirpath, mode='w+')
numeric_data = self.task_manager.data.select_dtypes(include=[np.number])
self.task_manager.data = None
# numeric_data = self.task_manager.data[self.task_manager.features + [self.task_manager.target, self.task_manager.orderby]]
f.from_pandas(numeric_data, orderby=self.task_manager.orderby)
f.register_array('data_array', numeric_data.columns)
f.set_node_attr('/column_names', key='column_names', value=numeric_data.columns)
f.close()
def run_evaluation(self):
cv = KFold(n_splits=5)
# cv, model_algo, root_dirpath, target
self.feature_evaluator = FeatureEvaluator(cv, self.task_manager.model_algo, self.task_manager.root_dirpath,
self.task_manager.target)
if not self.debug_mode:
self.dask_client = ClientFuture(local_client_n_workers=self.task_manager.local_client_n_workers,
local_client_threads_per_worker=self.task_manager.local_client_threads_per_worker)
self.dask_client.get_dashboard_link()
else:
self.dask_client = None
score_tracking_dict, current_features = self._run_feature_selection()
return score_tracking_dict, current_features
def _feature_evaluation_futures(self, feature_evaluator, dask_client, feature_stack, current_features):
if self.debug_mode:
feature_futures_dict = defaultdict(list)
for new_feature in feature_stack:
for i in range(0, 5):
feature_futures_dict[new_feature].append(feature_evaluator.evaluate_feature(current_features, new_feature, i))
return feature_futures_dict
feature_futures_dict = defaultdict(list)
for new_feature in feature_stack:
for i in range(1, 5):
feature_futures_dict[new_feature].append(dask_client.submit(feature_evaluator.evaluate_feature,
current_features,
new_feature,
i))
return feature_futures_dict
def _run_feature_selection(self):
score_tracking_dict = dict()
current_features = []
feature_stack = copy.copy(self.task_manager.features)
max_num_features = self.task_manager.max_num_features
counter = 0
best_score = np.inf
while(len(feature_stack)>0 and
max_num_features>len(current_features)):
feature_score_dict = dict()
feature_futures_dict = self._feature_evaluation_futures(self.feature_evaluator,
self.dask_client, feature_stack, current_features)
for k, v in feature_futures_dict.items():
if self.debug_mode:
score = score = [future.result() for future in v]
else:
score = np.mean([future.result() for future in v])
#
# score = [future.result() for future in v]
feature_score_dict[k] = score
best_feature = get_min_value_key(feature_score_dict)
worst_feature = get_max_value_key(feature_score_dict)
new_score = feature_score_dict[best_feature]
feature_stack.remove(best_feature)
current_features.append(best_feature)
score_tracking_dict[counter] = feature_score_dict
counter += 1
if self.debug_mode:
pass
else:
if best_score > new_score:
best_score = new_score
else:
print('stopping criterion met!')
break
return score_tracking_dict, current_features | selfea/selfea.py | from selfea.utils.data_structure_utils import return_indices, get_max_value_key, get_min_value_key
from selfea.utils.dask_clients import ClientFuture
from selfea.core._feature_evaluator import FeatureEvaluator
from selfea.default_models.default_xgboost_regressor import DefaultXGBoostRegressor
from collections import defaultdict
import numpy as np
import copy
import HMF
from sklearn.model_selection import KFold
class Selfea():
def __init__(self, debug_mode=False):
self.score_tracking_dict = dict()
self.debug_mode = debug_mode
def setup_evaluation(self, task_manager):
self.task_manager = task_manager
f = HMF.open_file(self.task_manager.root_dirpath, mode='w+')
numeric_data = self.task_manager.data.select_dtypes(include=[np.number])
self.task_manager.data = None
# numeric_data = self.task_manager.data[self.task_manager.features + [self.task_manager.target, self.task_manager.orderby]]
f.from_pandas(numeric_data, orderby=self.task_manager.orderby)
f.register_array('data_array', numeric_data.columns)
f.set_node_attr('/column_names', key='column_names', value=numeric_data.columns)
f.close()
def run_evaluation(self):
cv = KFold(n_splits=5)
# cv, model_algo, root_dirpath, target
self.feature_evaluator = FeatureEvaluator(cv, self.task_manager.model_algo, self.task_manager.root_dirpath,
self.task_manager.target)
if not self.debug_mode:
self.dask_client = ClientFuture(local_client_n_workers=self.task_manager.local_client_n_workers,
local_client_threads_per_worker=self.task_manager.local_client_threads_per_worker)
self.dask_client.get_dashboard_link()
else:
self.dask_client = None
score_tracking_dict, current_features = self._run_feature_selection()
return score_tracking_dict, current_features
def _feature_evaluation_futures(self, feature_evaluator, dask_client, feature_stack, current_features):
if self.debug_mode:
feature_futures_dict = defaultdict(list)
for new_feature in feature_stack:
for i in range(0, 5):
feature_futures_dict[new_feature].append(feature_evaluator.evaluate_feature(current_features, new_feature, i))
return feature_futures_dict
feature_futures_dict = defaultdict(list)
for new_feature in feature_stack:
for i in range(1, 5):
feature_futures_dict[new_feature].append(dask_client.submit(feature_evaluator.evaluate_feature,
current_features,
new_feature,
i))
return feature_futures_dict
def _run_feature_selection(self):
score_tracking_dict = dict()
current_features = []
feature_stack = copy.copy(self.task_manager.features)
max_num_features = self.task_manager.max_num_features
counter = 0
best_score = np.inf
while(len(feature_stack)>0 and
max_num_features>len(current_features)):
feature_score_dict = dict()
feature_futures_dict = self._feature_evaluation_futures(self.feature_evaluator,
self.dask_client, feature_stack, current_features)
for k, v in feature_futures_dict.items():
if self.debug_mode:
score = score = [future.result() for future in v]
else:
score = np.mean([future.result() for future in v])
#
# score = [future.result() for future in v]
feature_score_dict[k] = score
best_feature = get_min_value_key(feature_score_dict)
worst_feature = get_max_value_key(feature_score_dict)
new_score = feature_score_dict[best_feature]
feature_stack.remove(best_feature)
current_features.append(best_feature)
score_tracking_dict[counter] = feature_score_dict
counter += 1
if self.debug_mode:
pass
else:
if best_score > new_score:
best_score = new_score
else:
print('stopping criterion met!')
break
return score_tracking_dict, current_features | 0.200245 | 0.187226 |
import json
import multiprocessing
import time
import requests
import snappi
from flask import Flask, Response, request
from otg_gnmi.common.utils import init_logging, get_current_time
from tests.utils.common import get_mockserver_status
from tests.utils.settings import MockConfig
app = Flask(__name__)
CONFIG = MockConfig()
logfile = 'flask'+'-'+str(get_current_time())+'.log'
flask_logger = init_logging(
'test',
'mockserver',
logfile
)
@app.route('/status', methods=['GET'])
def get_status():
return Response(
status=200,
response=json.dumps({'status': 'up'}),
headers={'Content-Type': 'application/json'})
@app.route('/config', methods=['POST'])
def set_config():
global CONFIG
config = snappi.api().config()
config.deserialize(request.data.decode('utf-8'))
test = config.options.port_options.location_preemption
if test is not None and isinstance(test, bool) is False:
return Response(status=590,
response=json.dumps({'detail': 'invalid data type'}),
headers={'Content-Type': 'application/json'})
else:
status = get_mockserver_status()
if status == "200":
CONFIG = config
return Response(status=200,
response=json.dumps({'warnings': []}),
headers={'Content-Type': 'application/json'})
elif status == "200-warning":
CONFIG = config
return Response(status=200,
response=json.dumps(
{'warnings': ['mock 200 set_config warning']}),
headers={'Content-Type': 'application/json'})
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 set_config error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 set_config error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['set_config is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.route('/config', methods=['GET'])
def get_config():
global CONFIG
status = get_mockserver_status()
if status in ["200", "200-warning"]:
return Response(CONFIG.serialize() if CONFIG is not None else '{}',
mimetype='application/json',
status=200)
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 get_config error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 get_config error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['get_config is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.route('/results/metrics', methods=['POST'])
def get_metrics():
status = get_mockserver_status()
global CONFIG
if status in ["200", "200-warning"]:
api = snappi.api()
metrics_request = api.metrics_request()
metrics_request.deserialize(request.data.decode('utf-8'))
metrics_response = api.metrics_response()
if metrics_request.choice == 'port':
for metric in CONFIG.port_metrics:
metrics_response.port_metrics.metric(
name=metric['name'],
frames_tx=10000,
frames_rx=10000
)
elif metrics_request.choice == 'flow':
for metric in CONFIG.flow_metrics:
metrics_response.flow_metrics.metric(
name=metric['name'],
port_tx="P1",
port_rx="P2",
frames_tx=10000,
frames_rx=10000
)
elif metrics_request.choice == 'bgpv4':
for metric in CONFIG.bgpv4_metrics:
metrics_response.bgpv4_metrics.metric(
name=metric['name'],
session_state=metric["session_state"],
session_flap_count=0,
routes_advertised=1000,
routes_received=500
)
elif metrics_request.choice == 'bgpv6':
for metric in CONFIG.bgpv6_metrics:
metrics_response.bgpv6_metrics.metric(
name=metric['name'],
session_state=metric["session_state"],
session_flap_count=0,
routes_advertised=1000,
routes_received=500
)
elif metrics_request.choice == 'isis':
for metric in CONFIG.isis_metrics:
metrics_response.isis_metrics.metric(
name=metric['name'],
l1_sessions_up=metric["l1_sessions_up"],
)
return Response(metrics_response.serialize(),
mimetype='application/json',
status=200)
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 get_metrics error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 get_metrics error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['get_metrics is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.route('/results/states', methods=['POST'])
def get_states():
status = get_mockserver_status()
global CONFIG
if status in ["200", "200-warning"]:
api = snappi.api()
states_request = api.states_request()
states_request.deserialize(request.data.decode('utf-8'))
flask_logger.info('get_status Request : [%s]', states_request)
states_response = api.states_response()
if states_request.choice == 'ipv4_neighbors':
states_response.choice = 'ipv4_neighbors'
for state in CONFIG.ipv4_neighbors:
states_response.ipv4_neighbors.state(
ethernet_name=state['ethernet_name'],
ipv4_address=state['ipv4_address'],
link_layer_address="aa:bb:cc:dd:ee:ff"
)
elif states_request.choice == 'ipv6_neighbors':
states_response.choice = 'ipv6_neighbors'
for state in CONFIG.ipv6_neighbors:
states_response.ipv6_neighbors.state(
ethernet_name=state['ethernet_name'],
ipv6_address=state['ipv6_address'],
link_layer_address="aa:bb:cc:dd:ee:ff"
)
flask_logger.info('get_status Responese : [%s]', states_response)
return Response(states_response.serialize(),
mimetype='application/json',
status=200)
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 get_states error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 get_states error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['get_states is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.after_request
def after_request(resp):
print(request.method, request.url, ' -> ', resp.status)
return resp
def web_server():
app.run(port=11020, debug=True, use_reloader=False)
class SnappiServer(object):
def __init__(self):
self._CONFIG = None
def start(self):
self._web_server_thread = multiprocessing.Process(
target=web_server, args=())
self._web_server_thread.start()
self._wait_until_ready()
return self
def stop(self):
self._web_server_thread.terminate()
def _wait_until_ready(self):
while True:
try:
r = requests.get(url='http://127.0.0.1:11020/status')
res = r.json()
if res['status'] != 'up':
raise Exception('waiting for SnappiServer to be up')
break
except Exception as e:
print(e)
pass
time.sleep(.1) | tests/snappiserver.py | import json
import multiprocessing
import time
import requests
import snappi
from flask import Flask, Response, request
from otg_gnmi.common.utils import init_logging, get_current_time
from tests.utils.common import get_mockserver_status
from tests.utils.settings import MockConfig
app = Flask(__name__)
CONFIG = MockConfig()
logfile = 'flask'+'-'+str(get_current_time())+'.log'
flask_logger = init_logging(
'test',
'mockserver',
logfile
)
@app.route('/status', methods=['GET'])
def get_status():
return Response(
status=200,
response=json.dumps({'status': 'up'}),
headers={'Content-Type': 'application/json'})
@app.route('/config', methods=['POST'])
def set_config():
global CONFIG
config = snappi.api().config()
config.deserialize(request.data.decode('utf-8'))
test = config.options.port_options.location_preemption
if test is not None and isinstance(test, bool) is False:
return Response(status=590,
response=json.dumps({'detail': 'invalid data type'}),
headers={'Content-Type': 'application/json'})
else:
status = get_mockserver_status()
if status == "200":
CONFIG = config
return Response(status=200,
response=json.dumps({'warnings': []}),
headers={'Content-Type': 'application/json'})
elif status == "200-warning":
CONFIG = config
return Response(status=200,
response=json.dumps(
{'warnings': ['mock 200 set_config warning']}),
headers={'Content-Type': 'application/json'})
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 set_config error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 set_config error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['set_config is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.route('/config', methods=['GET'])
def get_config():
global CONFIG
status = get_mockserver_status()
if status in ["200", "200-warning"]:
return Response(CONFIG.serialize() if CONFIG is not None else '{}',
mimetype='application/json',
status=200)
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 get_config error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 get_config error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['get_config is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.route('/results/metrics', methods=['POST'])
def get_metrics():
status = get_mockserver_status()
global CONFIG
if status in ["200", "200-warning"]:
api = snappi.api()
metrics_request = api.metrics_request()
metrics_request.deserialize(request.data.decode('utf-8'))
metrics_response = api.metrics_response()
if metrics_request.choice == 'port':
for metric in CONFIG.port_metrics:
metrics_response.port_metrics.metric(
name=metric['name'],
frames_tx=10000,
frames_rx=10000
)
elif metrics_request.choice == 'flow':
for metric in CONFIG.flow_metrics:
metrics_response.flow_metrics.metric(
name=metric['name'],
port_tx="P1",
port_rx="P2",
frames_tx=10000,
frames_rx=10000
)
elif metrics_request.choice == 'bgpv4':
for metric in CONFIG.bgpv4_metrics:
metrics_response.bgpv4_metrics.metric(
name=metric['name'],
session_state=metric["session_state"],
session_flap_count=0,
routes_advertised=1000,
routes_received=500
)
elif metrics_request.choice == 'bgpv6':
for metric in CONFIG.bgpv6_metrics:
metrics_response.bgpv6_metrics.metric(
name=metric['name'],
session_state=metric["session_state"],
session_flap_count=0,
routes_advertised=1000,
routes_received=500
)
elif metrics_request.choice == 'isis':
for metric in CONFIG.isis_metrics:
metrics_response.isis_metrics.metric(
name=metric['name'],
l1_sessions_up=metric["l1_sessions_up"],
)
return Response(metrics_response.serialize(),
mimetype='application/json',
status=200)
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 get_metrics error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 get_metrics error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['get_metrics is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.route('/results/states', methods=['POST'])
def get_states():
status = get_mockserver_status()
global CONFIG
if status in ["200", "200-warning"]:
api = snappi.api()
states_request = api.states_request()
states_request.deserialize(request.data.decode('utf-8'))
flask_logger.info('get_status Request : [%s]', states_request)
states_response = api.states_response()
if states_request.choice == 'ipv4_neighbors':
states_response.choice = 'ipv4_neighbors'
for state in CONFIG.ipv4_neighbors:
states_response.ipv4_neighbors.state(
ethernet_name=state['ethernet_name'],
ipv4_address=state['ipv4_address'],
link_layer_address="aa:bb:cc:dd:ee:ff"
)
elif states_request.choice == 'ipv6_neighbors':
states_response.choice = 'ipv6_neighbors'
for state in CONFIG.ipv6_neighbors:
states_response.ipv6_neighbors.state(
ethernet_name=state['ethernet_name'],
ipv6_address=state['ipv6_address'],
link_layer_address="aa:bb:cc:dd:ee:ff"
)
flask_logger.info('get_status Responese : [%s]', states_response)
return Response(states_response.serialize(),
mimetype='application/json',
status=200)
elif status == "400":
return Response(status=400,
response=json.dumps(
{'errors': ['mock 400 get_states error']}),
headers={'Content-Type': 'application/json'})
elif status == "500":
return Response(status=500,
response=json.dumps(
{'errors': ['mock 500 get_states error']}),
headers={'Content-Type': 'application/json'})
else:
return Response(status=501,
response=json.dumps(
{'errors': ['get_states is not implemented']}),
headers={'Content-Type': 'application/json'})
@app.after_request
def after_request(resp):
print(request.method, request.url, ' -> ', resp.status)
return resp
def web_server():
app.run(port=11020, debug=True, use_reloader=False)
class SnappiServer(object):
def __init__(self):
self._CONFIG = None
def start(self):
self._web_server_thread = multiprocessing.Process(
target=web_server, args=())
self._web_server_thread.start()
self._wait_until_ready()
return self
def stop(self):
self._web_server_thread.terminate()
def _wait_until_ready(self):
while True:
try:
r = requests.get(url='http://127.0.0.1:11020/status')
res = r.json()
if res['status'] != 'up':
raise Exception('waiting for SnappiServer to be up')
break
except Exception as e:
print(e)
pass
time.sleep(.1) | 0.408631 | 0.068226 |
import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import logging
import json
from threading import Thread
from queue import Queue
# Handle WebSocket clients
clients = []
class WebSocketHandler(tornado.websocket.WebSocketHandler):
""" Handle default WebSocket connections """
# Logging settings
logger = logging.getLogger("WebSocketHandler")
logger.setLevel(logging.INFO)
def open(self):
""" New connection has been established """
clients.append(self)
self.logger.info("New connection")
def on_message(self, message):
""" Data income event callback """
self.write_message(u"%s" % message)
def on_close(self):
""" Connection was closed """
clients.remove(self)
self.logger.info("Connection removed")
class IndexPageHandler(tornado.web.RequestHandler):
""" Default index page handler. Not implemented yet. """
def get(self):
pass
class Application(tornado.web.Application):
""" Tornado application """
def __init__(self):
# Add here several handlers
handlers = [
(r'/', IndexPageHandler),
(r'/websocket', WebSocketHandler)
]
# Application settings
settings = {
'template_path': 'templates'
}
# Call parents constructor
tornado.web.Application.__init__(self, handlers, **settings)
class WebSocketServer():
""" Create tornado HTTP server serving our application
.. note::
Uses tornado as backend.
"""
def __init__(self, host, port, in_queue=Queue()):
""" Constructor for the WebSocketServer class
Args:
host(str): Hostname
port(int): Port number to listen on
in_queue(Queue): Thread-safe working queue
"""
# Settings
self.application = Application()
self.server = tornado.httpserver.HTTPServer(self.application)
self.host = host
self.port = port
self.in_queue = in_queue
# Listen to ..
self.server.listen(self.port, self.host)
# Logging settings
logging.basicConfig(level=logging.DEBUG)
self.logger = logging.getLogger("WebSocketServer")
self.logger.setLevel(logging.INFO)
def start_server(self):
""" Starts the HTTP server
"""
self.logger.info("Starting WebSocket server on port %d" % self.port)
http_server = Thread(target=tornado.ioloop.IOLoop.instance().start)
http_server.start()
def start_collector(self):
""" Starts collecting packages
"""
self.logger.info("Start collector server")
collector_server = Thread(target=self.collect_data)
collector_server.start()
def collector_process_data(self, data):
""" Process incoming data and send it to all available clients
Args:
data: Received data
"""
for c in clients:
c.on_message(json.dumps(data))
def collect_data(self):
""" Wait for data in individual thread
"""
self.logger.info("Waiting for incoming data ...")
while True:
item = self.in_queue.get()
self.logger.info("Received data!")
self.collector_process_data(item)
def start(self):
""" Starts the server
.. note::
The server will listen for incoming JSON packets and pass them
to all clients connected to the WebSocket.
"""
# Start HTTP server
self.start_server()
# Start data collector
self.start_collector() | lib/WebSocketServer.py | import tornado.web
import tornado.websocket
import tornado.httpserver
import tornado.ioloop
import logging
import json
from threading import Thread
from queue import Queue
# Handle WebSocket clients
clients = []
class WebSocketHandler(tornado.websocket.WebSocketHandler):
""" Handle default WebSocket connections """
# Logging settings
logger = logging.getLogger("WebSocketHandler")
logger.setLevel(logging.INFO)
def open(self):
""" New connection has been established """
clients.append(self)
self.logger.info("New connection")
def on_message(self, message):
""" Data income event callback """
self.write_message(u"%s" % message)
def on_close(self):
""" Connection was closed """
clients.remove(self)
self.logger.info("Connection removed")
class IndexPageHandler(tornado.web.RequestHandler):
""" Default index page handler. Not implemented yet. """
def get(self):
pass
class Application(tornado.web.Application):
""" Tornado application """
def __init__(self):
# Add here several handlers
handlers = [
(r'/', IndexPageHandler),
(r'/websocket', WebSocketHandler)
]
# Application settings
settings = {
'template_path': 'templates'
}
# Call parents constructor
tornado.web.Application.__init__(self, handlers, **settings)
class WebSocketServer():
""" Create tornado HTTP server serving our application
.. note::
Uses tornado as backend.
"""
def __init__(self, host, port, in_queue=Queue()):
""" Constructor for the WebSocketServer class
Args:
host(str): Hostname
port(int): Port number to listen on
in_queue(Queue): Thread-safe working queue
"""
# Settings
self.application = Application()
self.server = tornado.httpserver.HTTPServer(self.application)
self.host = host
self.port = port
self.in_queue = in_queue
# Listen to ..
self.server.listen(self.port, self.host)
# Logging settings
logging.basicConfig(level=logging.DEBUG)
self.logger = logging.getLogger("WebSocketServer")
self.logger.setLevel(logging.INFO)
def start_server(self):
""" Starts the HTTP server
"""
self.logger.info("Starting WebSocket server on port %d" % self.port)
http_server = Thread(target=tornado.ioloop.IOLoop.instance().start)
http_server.start()
def start_collector(self):
""" Starts collecting packages
"""
self.logger.info("Start collector server")
collector_server = Thread(target=self.collect_data)
collector_server.start()
def collector_process_data(self, data):
""" Process incoming data and send it to all available clients
Args:
data: Received data
"""
for c in clients:
c.on_message(json.dumps(data))
def collect_data(self):
""" Wait for data in individual thread
"""
self.logger.info("Waiting for incoming data ...")
while True:
item = self.in_queue.get()
self.logger.info("Received data!")
self.collector_process_data(item)
def start(self):
""" Starts the server
.. note::
The server will listen for incoming JSON packets and pass them
to all clients connected to the WebSocket.
"""
# Start HTTP server
self.start_server()
# Start data collector
self.start_collector() | 0.53437 | 0.074164 |
"""Handling of build perf test reports"""
from collections import OrderedDict, Mapping, namedtuple
from datetime import datetime, timezone
from numbers import Number
from statistics import mean, stdev, variance
AggregateTestData = namedtuple('AggregateTestData', ['metadata', 'results'])
def isofmt_to_timestamp(string):
"""Convert timestamp string in ISO 8601 format into unix timestamp"""
if '.' in string:
dt = datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%f')
else:
dt = datetime.strptime(string, '%Y-%m-%dT%H:%M:%S')
return dt.replace(tzinfo=timezone.utc).timestamp()
def metadata_xml_to_json(elem):
"""Convert metadata xml into JSON format"""
assert elem.tag == 'metadata', "Invalid metadata file format"
def _xml_to_json(elem):
"""Convert xml element to JSON object"""
out = OrderedDict()
for child in elem.getchildren():
key = child.attrib.get('name', child.tag)
if len(child):
out[key] = _xml_to_json(child)
else:
out[key] = child.text
return out
return _xml_to_json(elem)
def results_xml_to_json(elem):
"""Convert results xml into JSON format"""
rusage_fields = ('ru_utime', 'ru_stime', 'ru_maxrss', 'ru_minflt',
'ru_majflt', 'ru_inblock', 'ru_oublock', 'ru_nvcsw',
'ru_nivcsw')
iostat_fields = ('rchar', 'wchar', 'syscr', 'syscw', 'read_bytes',
'write_bytes', 'cancelled_write_bytes')
def _read_measurement(elem):
"""Convert measurement to JSON"""
data = OrderedDict()
data['type'] = elem.tag
data['name'] = elem.attrib['name']
data['legend'] = elem.attrib['legend']
values = OrderedDict()
# SYSRES measurement
if elem.tag == 'sysres':
for subel in elem:
if subel.tag == 'time':
values['start_time'] = isofmt_to_timestamp(subel.attrib['timestamp'])
values['elapsed_time'] = float(subel.text)
elif subel.tag == 'rusage':
rusage = OrderedDict()
for field in rusage_fields:
if 'time' in field:
rusage[field] = float(subel.attrib[field])
else:
rusage[field] = int(subel.attrib[field])
values['rusage'] = rusage
elif subel.tag == 'iostat':
values['iostat'] = OrderedDict([(f, int(subel.attrib[f]))
for f in iostat_fields])
elif subel.tag == 'buildstats_file':
values['buildstats_file'] = subel.text
else:
raise TypeError("Unknown sysres value element '{}'".format(subel.tag))
# DISKUSAGE measurement
elif elem.tag == 'diskusage':
values['size'] = int(elem.find('size').text)
else:
raise Exception("Unknown measurement tag '{}'".format(elem.tag))
data['values'] = values
return data
def _read_testcase(elem):
"""Convert testcase into JSON"""
assert elem.tag == 'testcase', "Expecting 'testcase' element instead of {}".format(elem.tag)
data = OrderedDict()
data['name'] = elem.attrib['name']
data['description'] = elem.attrib['description']
data['status'] = 'SUCCESS'
data['start_time'] = isofmt_to_timestamp(elem.attrib['timestamp'])
data['elapsed_time'] = float(elem.attrib['time'])
measurements = OrderedDict()
for subel in elem.getchildren():
if subel.tag == 'error' or subel.tag == 'failure':
data['status'] = subel.tag.upper()
data['message'] = subel.attrib['message']
data['err_type'] = subel.attrib['type']
data['err_output'] = subel.text
elif subel.tag == 'skipped':
data['status'] = 'SKIPPED'
data['message'] = subel.text
else:
measurements[subel.attrib['name']] = _read_measurement(subel)
data['measurements'] = measurements
return data
def _read_testsuite(elem):
"""Convert suite to JSON"""
assert elem.tag == 'testsuite', \
"Expecting 'testsuite' element instead of {}".format(elem.tag)
data = OrderedDict()
if 'hostname' in elem.attrib:
data['tester_host'] = elem.attrib['hostname']
data['start_time'] = isofmt_to_timestamp(elem.attrib['timestamp'])
data['elapsed_time'] = float(elem.attrib['time'])
tests = OrderedDict()
for case in elem.getchildren():
tests[case.attrib['name']] = _read_testcase(case)
data['tests'] = tests
return data
# Main function
assert elem.tag == 'testsuites', "Invalid test report format"
assert len(elem) == 1, "Too many testsuites"
return _read_testsuite(elem.getchildren()[0])
def aggregate_metadata(metadata):
"""Aggregate metadata into one, basically a sanity check"""
mutable_keys = ('pretty_name', 'version_id')
def aggregate_obj(aggregate, obj, assert_str=True):
"""Aggregate objects together"""
assert type(aggregate) is type(obj), \
"Type mismatch: {} != {}".format(type(aggregate), type(obj))
if isinstance(obj, Mapping):
assert set(aggregate.keys()) == set(obj.keys())
for key, val in obj.items():
aggregate_obj(aggregate[key], val, key not in mutable_keys)
elif isinstance(obj, list):
assert len(aggregate) == len(obj)
for i, val in enumerate(obj):
aggregate_obj(aggregate[i], val)
elif not isinstance(obj, str) or (isinstance(obj, str) and assert_str):
assert aggregate == obj, "Data mismatch {} != {}".format(aggregate, obj)
if not metadata:
return {}
# Do the aggregation
aggregate = metadata[0].copy()
for testrun in metadata[1:]:
aggregate_obj(aggregate, testrun)
aggregate['testrun_count'] = len(metadata)
return aggregate
def aggregate_data(data):
"""Aggregate multiple test results JSON structures into one"""
mutable_keys = ('status', 'message', 'err_type', 'err_output')
class SampleList(list):
"""Container for numerical samples"""
pass
def new_aggregate_obj(obj):
"""Create new object for aggregate"""
if isinstance(obj, Number):
new_obj = SampleList()
new_obj.append(obj)
elif isinstance(obj, str):
new_obj = obj
else:
# Lists and and dicts are kept as is
new_obj = obj.__class__()
aggregate_obj(new_obj, obj)
return new_obj
def aggregate_obj(aggregate, obj, assert_str=True):
"""Recursive "aggregation" of JSON objects"""
if isinstance(obj, Number):
assert isinstance(aggregate, SampleList)
aggregate.append(obj)
return
assert type(aggregate) == type(obj), \
"Type mismatch: {} != {}".format(type(aggregate), type(obj))
if isinstance(obj, Mapping):
for key, val in obj.items():
if not key in aggregate:
aggregate[key] = new_aggregate_obj(val)
else:
aggregate_obj(aggregate[key], val, key not in mutable_keys)
elif isinstance(obj, list):
for i, val in enumerate(obj):
if i >= len(aggregate):
aggregate[key] = new_aggregate_obj(val)
else:
aggregate_obj(aggregate[i], val)
elif isinstance(obj, str):
# Sanity check for data
if assert_str:
assert aggregate == obj, "Data mismatch {} != {}".format(aggregate, obj)
else:
raise Exception("BUG: unable to aggregate '{}' ({})".format(type(obj), str(obj)))
if not data:
return {}
# Do the aggregation
aggregate = data[0].__class__()
for testrun in data:
aggregate_obj(aggregate, testrun)
return aggregate
class MeasurementVal(float):
"""Base class representing measurement values"""
gv_data_type = 'number'
def gv_value(self):
"""Value formatting for visualization"""
if self != self:
return "null"
else:
return self
class TimeVal(MeasurementVal):
"""Class representing time values"""
quantity = 'time'
gv_title = 'elapsed time'
gv_data_type = 'timeofday'
def hms(self):
"""Split time into hours, minutes and seconeds"""
hhh = int(abs(self) / 3600)
mmm = int((abs(self) % 3600) / 60)
sss = abs(self) % 60
return hhh, mmm, sss
def __str__(self):
if self != self:
return "nan"
hh, mm, ss = self.hms()
sign = '-' if self < 0 else ''
if hh > 0:
return '{}{:d}:{:02d}:{:02.0f}'.format(sign, hh, mm, ss)
elif mm > 0:
return '{}{:d}:{:04.1f}'.format(sign, mm, ss)
elif ss > 1:
return '{}{:.1f} s'.format(sign, ss)
else:
return '{}{:.2f} s'.format(sign, ss)
def gv_value(self):
"""Value formatting for visualization"""
if self != self:
return "null"
hh, mm, ss = self.hms()
return [hh, mm, int(ss), int(ss*1000) % 1000]
class SizeVal(MeasurementVal):
"""Class representing time values"""
quantity = 'size'
gv_title = 'size in MiB'
gv_data_type = 'number'
def __str__(self):
if self != self:
return "nan"
if abs(self) < 1024:
return '{:.1f} kiB'.format(self)
elif abs(self) < 1048576:
return '{:.2f} MiB'.format(self / 1024)
else:
return '{:.2f} GiB'.format(self / 1048576)
def gv_value(self):
"""Value formatting for visualization"""
if self != self:
return "null"
return self / 1024
def measurement_stats(meas, prefix=''):
"""Get statistics of a measurement"""
if not meas:
return {prefix + 'sample_cnt': 0,
prefix + 'mean': MeasurementVal('nan'),
prefix + 'stdev': MeasurementVal('nan'),
prefix + 'variance': MeasurementVal('nan'),
prefix + 'min': MeasurementVal('nan'),
prefix + 'max': MeasurementVal('nan'),
prefix + 'minus': MeasurementVal('nan'),
prefix + 'plus': MeasurementVal('nan')}
stats = {'name': meas['name']}
if meas['type'] == 'sysres':
val_cls = TimeVal
values = meas['values']['elapsed_time']
elif meas['type'] == 'diskusage':
val_cls = SizeVal
values = meas['values']['size']
else:
raise Exception("Unknown measurement type '{}'".format(meas['type']))
stats['val_cls'] = val_cls
stats['quantity'] = val_cls.quantity
stats[prefix + 'sample_cnt'] = len(values)
mean_val = val_cls(mean(values))
min_val = val_cls(min(values))
max_val = val_cls(max(values))
stats[prefix + 'mean'] = mean_val
if len(values) > 1:
stats[prefix + 'stdev'] = val_cls(stdev(values))
stats[prefix + 'variance'] = val_cls(variance(values))
else:
stats[prefix + 'stdev'] = float('nan')
stats[prefix + 'variance'] = float('nan')
stats[prefix + 'min'] = min_val
stats[prefix + 'max'] = max_val
stats[prefix + 'minus'] = val_cls(mean_val - min_val)
stats[prefix + 'plus'] = val_cls(max_val - mean_val)
return stats | poky/scripts/lib/build_perf/report.py | """Handling of build perf test reports"""
from collections import OrderedDict, Mapping, namedtuple
from datetime import datetime, timezone
from numbers import Number
from statistics import mean, stdev, variance
AggregateTestData = namedtuple('AggregateTestData', ['metadata', 'results'])
def isofmt_to_timestamp(string):
"""Convert timestamp string in ISO 8601 format into unix timestamp"""
if '.' in string:
dt = datetime.strptime(string, '%Y-%m-%dT%H:%M:%S.%f')
else:
dt = datetime.strptime(string, '%Y-%m-%dT%H:%M:%S')
return dt.replace(tzinfo=timezone.utc).timestamp()
def metadata_xml_to_json(elem):
"""Convert metadata xml into JSON format"""
assert elem.tag == 'metadata', "Invalid metadata file format"
def _xml_to_json(elem):
"""Convert xml element to JSON object"""
out = OrderedDict()
for child in elem.getchildren():
key = child.attrib.get('name', child.tag)
if len(child):
out[key] = _xml_to_json(child)
else:
out[key] = child.text
return out
return _xml_to_json(elem)
def results_xml_to_json(elem):
"""Convert results xml into JSON format"""
rusage_fields = ('ru_utime', 'ru_stime', 'ru_maxrss', 'ru_minflt',
'ru_majflt', 'ru_inblock', 'ru_oublock', 'ru_nvcsw',
'ru_nivcsw')
iostat_fields = ('rchar', 'wchar', 'syscr', 'syscw', 'read_bytes',
'write_bytes', 'cancelled_write_bytes')
def _read_measurement(elem):
"""Convert measurement to JSON"""
data = OrderedDict()
data['type'] = elem.tag
data['name'] = elem.attrib['name']
data['legend'] = elem.attrib['legend']
values = OrderedDict()
# SYSRES measurement
if elem.tag == 'sysres':
for subel in elem:
if subel.tag == 'time':
values['start_time'] = isofmt_to_timestamp(subel.attrib['timestamp'])
values['elapsed_time'] = float(subel.text)
elif subel.tag == 'rusage':
rusage = OrderedDict()
for field in rusage_fields:
if 'time' in field:
rusage[field] = float(subel.attrib[field])
else:
rusage[field] = int(subel.attrib[field])
values['rusage'] = rusage
elif subel.tag == 'iostat':
values['iostat'] = OrderedDict([(f, int(subel.attrib[f]))
for f in iostat_fields])
elif subel.tag == 'buildstats_file':
values['buildstats_file'] = subel.text
else:
raise TypeError("Unknown sysres value element '{}'".format(subel.tag))
# DISKUSAGE measurement
elif elem.tag == 'diskusage':
values['size'] = int(elem.find('size').text)
else:
raise Exception("Unknown measurement tag '{}'".format(elem.tag))
data['values'] = values
return data
def _read_testcase(elem):
"""Convert testcase into JSON"""
assert elem.tag == 'testcase', "Expecting 'testcase' element instead of {}".format(elem.tag)
data = OrderedDict()
data['name'] = elem.attrib['name']
data['description'] = elem.attrib['description']
data['status'] = 'SUCCESS'
data['start_time'] = isofmt_to_timestamp(elem.attrib['timestamp'])
data['elapsed_time'] = float(elem.attrib['time'])
measurements = OrderedDict()
for subel in elem.getchildren():
if subel.tag == 'error' or subel.tag == 'failure':
data['status'] = subel.tag.upper()
data['message'] = subel.attrib['message']
data['err_type'] = subel.attrib['type']
data['err_output'] = subel.text
elif subel.tag == 'skipped':
data['status'] = 'SKIPPED'
data['message'] = subel.text
else:
measurements[subel.attrib['name']] = _read_measurement(subel)
data['measurements'] = measurements
return data
def _read_testsuite(elem):
"""Convert suite to JSON"""
assert elem.tag == 'testsuite', \
"Expecting 'testsuite' element instead of {}".format(elem.tag)
data = OrderedDict()
if 'hostname' in elem.attrib:
data['tester_host'] = elem.attrib['hostname']
data['start_time'] = isofmt_to_timestamp(elem.attrib['timestamp'])
data['elapsed_time'] = float(elem.attrib['time'])
tests = OrderedDict()
for case in elem.getchildren():
tests[case.attrib['name']] = _read_testcase(case)
data['tests'] = tests
return data
# Main function
assert elem.tag == 'testsuites', "Invalid test report format"
assert len(elem) == 1, "Too many testsuites"
return _read_testsuite(elem.getchildren()[0])
def aggregate_metadata(metadata):
"""Aggregate metadata into one, basically a sanity check"""
mutable_keys = ('pretty_name', 'version_id')
def aggregate_obj(aggregate, obj, assert_str=True):
"""Aggregate objects together"""
assert type(aggregate) is type(obj), \
"Type mismatch: {} != {}".format(type(aggregate), type(obj))
if isinstance(obj, Mapping):
assert set(aggregate.keys()) == set(obj.keys())
for key, val in obj.items():
aggregate_obj(aggregate[key], val, key not in mutable_keys)
elif isinstance(obj, list):
assert len(aggregate) == len(obj)
for i, val in enumerate(obj):
aggregate_obj(aggregate[i], val)
elif not isinstance(obj, str) or (isinstance(obj, str) and assert_str):
assert aggregate == obj, "Data mismatch {} != {}".format(aggregate, obj)
if not metadata:
return {}
# Do the aggregation
aggregate = metadata[0].copy()
for testrun in metadata[1:]:
aggregate_obj(aggregate, testrun)
aggregate['testrun_count'] = len(metadata)
return aggregate
def aggregate_data(data):
"""Aggregate multiple test results JSON structures into one"""
mutable_keys = ('status', 'message', 'err_type', 'err_output')
class SampleList(list):
"""Container for numerical samples"""
pass
def new_aggregate_obj(obj):
"""Create new object for aggregate"""
if isinstance(obj, Number):
new_obj = SampleList()
new_obj.append(obj)
elif isinstance(obj, str):
new_obj = obj
else:
# Lists and and dicts are kept as is
new_obj = obj.__class__()
aggregate_obj(new_obj, obj)
return new_obj
def aggregate_obj(aggregate, obj, assert_str=True):
"""Recursive "aggregation" of JSON objects"""
if isinstance(obj, Number):
assert isinstance(aggregate, SampleList)
aggregate.append(obj)
return
assert type(aggregate) == type(obj), \
"Type mismatch: {} != {}".format(type(aggregate), type(obj))
if isinstance(obj, Mapping):
for key, val in obj.items():
if not key in aggregate:
aggregate[key] = new_aggregate_obj(val)
else:
aggregate_obj(aggregate[key], val, key not in mutable_keys)
elif isinstance(obj, list):
for i, val in enumerate(obj):
if i >= len(aggregate):
aggregate[key] = new_aggregate_obj(val)
else:
aggregate_obj(aggregate[i], val)
elif isinstance(obj, str):
# Sanity check for data
if assert_str:
assert aggregate == obj, "Data mismatch {} != {}".format(aggregate, obj)
else:
raise Exception("BUG: unable to aggregate '{}' ({})".format(type(obj), str(obj)))
if not data:
return {}
# Do the aggregation
aggregate = data[0].__class__()
for testrun in data:
aggregate_obj(aggregate, testrun)
return aggregate
class MeasurementVal(float):
"""Base class representing measurement values"""
gv_data_type = 'number'
def gv_value(self):
"""Value formatting for visualization"""
if self != self:
return "null"
else:
return self
class TimeVal(MeasurementVal):
"""Class representing time values"""
quantity = 'time'
gv_title = 'elapsed time'
gv_data_type = 'timeofday'
def hms(self):
"""Split time into hours, minutes and seconeds"""
hhh = int(abs(self) / 3600)
mmm = int((abs(self) % 3600) / 60)
sss = abs(self) % 60
return hhh, mmm, sss
def __str__(self):
if self != self:
return "nan"
hh, mm, ss = self.hms()
sign = '-' if self < 0 else ''
if hh > 0:
return '{}{:d}:{:02d}:{:02.0f}'.format(sign, hh, mm, ss)
elif mm > 0:
return '{}{:d}:{:04.1f}'.format(sign, mm, ss)
elif ss > 1:
return '{}{:.1f} s'.format(sign, ss)
else:
return '{}{:.2f} s'.format(sign, ss)
def gv_value(self):
"""Value formatting for visualization"""
if self != self:
return "null"
hh, mm, ss = self.hms()
return [hh, mm, int(ss), int(ss*1000) % 1000]
class SizeVal(MeasurementVal):
"""Class representing time values"""
quantity = 'size'
gv_title = 'size in MiB'
gv_data_type = 'number'
def __str__(self):
if self != self:
return "nan"
if abs(self) < 1024:
return '{:.1f} kiB'.format(self)
elif abs(self) < 1048576:
return '{:.2f} MiB'.format(self / 1024)
else:
return '{:.2f} GiB'.format(self / 1048576)
def gv_value(self):
"""Value formatting for visualization"""
if self != self:
return "null"
return self / 1024
def measurement_stats(meas, prefix=''):
"""Get statistics of a measurement"""
if not meas:
return {prefix + 'sample_cnt': 0,
prefix + 'mean': MeasurementVal('nan'),
prefix + 'stdev': MeasurementVal('nan'),
prefix + 'variance': MeasurementVal('nan'),
prefix + 'min': MeasurementVal('nan'),
prefix + 'max': MeasurementVal('nan'),
prefix + 'minus': MeasurementVal('nan'),
prefix + 'plus': MeasurementVal('nan')}
stats = {'name': meas['name']}
if meas['type'] == 'sysres':
val_cls = TimeVal
values = meas['values']['elapsed_time']
elif meas['type'] == 'diskusage':
val_cls = SizeVal
values = meas['values']['size']
else:
raise Exception("Unknown measurement type '{}'".format(meas['type']))
stats['val_cls'] = val_cls
stats['quantity'] = val_cls.quantity
stats[prefix + 'sample_cnt'] = len(values)
mean_val = val_cls(mean(values))
min_val = val_cls(min(values))
max_val = val_cls(max(values))
stats[prefix + 'mean'] = mean_val
if len(values) > 1:
stats[prefix + 'stdev'] = val_cls(stdev(values))
stats[prefix + 'variance'] = val_cls(variance(values))
else:
stats[prefix + 'stdev'] = float('nan')
stats[prefix + 'variance'] = float('nan')
stats[prefix + 'min'] = min_val
stats[prefix + 'max'] = max_val
stats[prefix + 'minus'] = val_cls(mean_val - min_val)
stats[prefix + 'plus'] = val_cls(max_val - mean_val)
return stats | 0.701509 | 0.418697 |
import numpy as np
import warnings
from scipy import sparse
from sklearn.utils import (check_array, check_consistent_length)
from sklearn.cluster import DBSCAN as DBSCAN_original
import daal4py
from daal4py.sklearn._utils import (make2d, getFPType)
def _daal_dbscan(X, eps=0.5, min_samples=5, sample_weight=None):
if not eps > 0.0:
raise ValueError("eps must be positive.")
X = check_array(X, dtype=[np.float64, np.float32])
if sample_weight is not None:
sample_weight = np.asarray(sample_weight)
check_consistent_length(X, sample_weight)
ww = make2d(sample_weight)
else:
ww = None
XX = make2d(X)
fpt = getFPType(XX)
alg = daal4py.dbscan(
method='defaultDense',
epsilon=float(eps),
minObservations=int(min_samples),
resultsToCompute="computeCoreIndices")
daal_res = alg.compute(XX, ww)
n_clusters = daal_res.nClusters[0, 0]
assignments = daal_res.assignments.ravel()
if daal_res.coreIndices is not None:
core_ind = daal_res.coreIndices.ravel()
else:
core_ind = np.array([], dtype=np.intc)
return (core_ind, assignments)
class DBSCAN(DBSCAN_original):
"""Perform DBSCAN clustering from vector array or distance matrix.
DBSCAN - Density-Based Spatial Clustering of Applications with Noise.
Finds core samples of high density and expands clusters from them.
Good for data which contains clusters of similar density.
Read more in the :ref:`User Guide <dbscan>`.
Parameters
----------
eps : float, optional
The maximum distance between two samples for one to be considered
as in the neighborhood of the other. This is not a maximum bound
on the distances of points within a cluster. This is the most
important DBSCAN parameter to choose appropriately for your data set
and distance function.
min_samples : int, optional
The number of samples (or total weight) in a neighborhood for a point
to be considered as a core point. This includes the point itself.
metric : string, or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string or callable, it must be one of
the options allowed by :func:`sklearn.metrics.pairwise_distances` for
its metric parameter.
If metric is "precomputed", X is assumed to be a distance matrix and
must be square. X may be a :term:`Glossary <sparse graph>`, in which
case only "nonzero" elements may be considered neighbors for DBSCAN.
.. versionadded:: 0.17
metric *precomputed* to accept precomputed sparse matrix.
metric_params : dict, optional
Additional keyword arguments for the metric function.
.. versionadded:: 0.19
algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute', 'daal'}, optional
The algorithm to be used by the NearestNeighbors module
to compute pointwise distances and find nearest neighbors.
See NearestNeighbors module documentation for details.
If algorithm is set to 'daal', Intel(R) DAAL will be used.
leaf_size : int, optional (default = 30)
Leaf size passed to BallTree or cKDTree. This can affect the speed
of the construction and query, as well as the memory required
to store the tree. The optimal value depends
on the nature of the problem.
p : float, optional
The power of the Minkowski metric to be used to calculate distance
between points.
n_jobs : int or None, optional (default=None)
The number of parallel jobs to run.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
Attributes
----------
core_sample_indices_ : array, shape = [n_core_samples]
Indices of core samples.
components_ : array, shape = [n_core_samples, n_features]
Copy of each core sample found by training.
labels_ : array, shape = [n_samples]
Cluster labels for each point in the dataset given to fit().
Noisy samples are given the label -1.
Examples
--------
>>> from sklearn.cluster import DBSCAN
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 2], [2, 3],
... [8, 7], [8, 8], [25, 80]])
>>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
>>> clustering.labels_
array([ 0, 0, 0, 1, 1, -1])
>>> clustering
DBSCAN(eps=3, min_samples=2)
See also
--------
OPTICS
A similar clustering at multiple values of eps. Our implementation
is optimized for memory usage.
Notes
-----
For an example, see :ref:`examples/cluster/plot_dbscan.py
<sphx_glr_auto_examples_cluster_plot_dbscan.py>`.
This implementation bulk-computes all neighborhood queries, which increases
the memory complexity to O(n.d) where d is the average number of neighbors,
while original DBSCAN had memory complexity O(n). It may attract a higher
memory complexity when querying these nearest neighborhoods, depending
on the ``algorithm``.
One way to avoid the query complexity is to pre-compute sparse
neighborhoods in chunks using
:func:`NearestNeighbors.radius_neighbors_graph
<sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
``mode='distance'``, then using ``metric='precomputed'`` here.
Another way to reduce memory and computation time is to remove
(near-)duplicate points and use ``sample_weight`` instead.
:class:`cluster.OPTICS` provides a similar clustering with lower memory
usage.
References
----------
<NAME>., <NAME>, <NAME>, and <NAME>, "A Density-Based
Algorithm for Discovering Clusters in Large Spatial Databases with Noise".
In: Proceedings of the 2nd International Conference on Knowledge Discovery
and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996
<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2017).
DBSCAN revisited, revisited: why and how you should (still) use DBSCAN.
ACM Transactions on Database Systems (TODS), 42(3), 19.
"""
def __init__(self, eps=0.5, min_samples=5, metric='euclidean',
metric_params=None, algorithm='auto', leaf_size=30, p=None,
n_jobs=None):
self.eps = eps
self.min_samples = min_samples
self.metric = metric
self.metric_params = metric_params
self.algorithm = algorithm
self.leaf_size = leaf_size
self.p = p
self.n_jobs = n_jobs
def fit(self, X, y=None, sample_weight=None):
"""Perform DBSCAN clustering from features, or distance matrix.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features), or \
(n_samples, n_samples)
Training instances to cluster, or distances between instances if
``metric='precomputed'``. If a sparse matrix is provided, it will
be converted into a sparse ``csr_matrix``.
sample_weight : array, shape (n_samples,), optional
Weight of each sample, such that a sample with a weight of at least
``min_samples`` is by itself a core sample; a sample with a
negative weight may inhibit its eps-neighbor from being core.
Note that weights are absolute, and default to 1.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
self
"""
X = check_array(X, accept_sparse='csr')
if not self.eps > 0.0:
raise ValueError("eps must be positive.")
if sample_weight is not None:
sample_weight = np.asarray(sample_weight)
check_consistent_length(X, sample_weight)
_daal_ready = ((self.algorithm in ['auto', 'brute']) and
(self.metric == 'euclidean' or
(self.metric == 'minkowski' and self.p == 2)) and
isinstance(X, np.ndarray) and (X.dtype.kind in ['d', 'f']))
if _daal_ready:
core_ind, assignments = _daal_dbscan(
X, self.eps,
self.min_samples,
sample_weight=sample_weight)
self.core_sample_indices_ = core_ind
self.labels_ = assignments
self.components_ = np.take(X, core_ind, axis=0)
return self
else:
return super().fit(X, y, sample_weight=sample_weight) | daal4py/sklearn/cluster/_dbscan_0_21.py |
import numpy as np
import warnings
from scipy import sparse
from sklearn.utils import (check_array, check_consistent_length)
from sklearn.cluster import DBSCAN as DBSCAN_original
import daal4py
from daal4py.sklearn._utils import (make2d, getFPType)
def _daal_dbscan(X, eps=0.5, min_samples=5, sample_weight=None):
if not eps > 0.0:
raise ValueError("eps must be positive.")
X = check_array(X, dtype=[np.float64, np.float32])
if sample_weight is not None:
sample_weight = np.asarray(sample_weight)
check_consistent_length(X, sample_weight)
ww = make2d(sample_weight)
else:
ww = None
XX = make2d(X)
fpt = getFPType(XX)
alg = daal4py.dbscan(
method='defaultDense',
epsilon=float(eps),
minObservations=int(min_samples),
resultsToCompute="computeCoreIndices")
daal_res = alg.compute(XX, ww)
n_clusters = daal_res.nClusters[0, 0]
assignments = daal_res.assignments.ravel()
if daal_res.coreIndices is not None:
core_ind = daal_res.coreIndices.ravel()
else:
core_ind = np.array([], dtype=np.intc)
return (core_ind, assignments)
class DBSCAN(DBSCAN_original):
"""Perform DBSCAN clustering from vector array or distance matrix.
DBSCAN - Density-Based Spatial Clustering of Applications with Noise.
Finds core samples of high density and expands clusters from them.
Good for data which contains clusters of similar density.
Read more in the :ref:`User Guide <dbscan>`.
Parameters
----------
eps : float, optional
The maximum distance between two samples for one to be considered
as in the neighborhood of the other. This is not a maximum bound
on the distances of points within a cluster. This is the most
important DBSCAN parameter to choose appropriately for your data set
and distance function.
min_samples : int, optional
The number of samples (or total weight) in a neighborhood for a point
to be considered as a core point. This includes the point itself.
metric : string, or callable
The metric to use when calculating distance between instances in a
feature array. If metric is a string or callable, it must be one of
the options allowed by :func:`sklearn.metrics.pairwise_distances` for
its metric parameter.
If metric is "precomputed", X is assumed to be a distance matrix and
must be square. X may be a :term:`Glossary <sparse graph>`, in which
case only "nonzero" elements may be considered neighbors for DBSCAN.
.. versionadded:: 0.17
metric *precomputed* to accept precomputed sparse matrix.
metric_params : dict, optional
Additional keyword arguments for the metric function.
.. versionadded:: 0.19
algorithm : {'auto', 'ball_tree', 'kd_tree', 'brute', 'daal'}, optional
The algorithm to be used by the NearestNeighbors module
to compute pointwise distances and find nearest neighbors.
See NearestNeighbors module documentation for details.
If algorithm is set to 'daal', Intel(R) DAAL will be used.
leaf_size : int, optional (default = 30)
Leaf size passed to BallTree or cKDTree. This can affect the speed
of the construction and query, as well as the memory required
to store the tree. The optimal value depends
on the nature of the problem.
p : float, optional
The power of the Minkowski metric to be used to calculate distance
between points.
n_jobs : int or None, optional (default=None)
The number of parallel jobs to run.
``None`` means 1 unless in a :obj:`joblib.parallel_backend` context.
``-1`` means using all processors. See :term:`Glossary <n_jobs>`
for more details.
Attributes
----------
core_sample_indices_ : array, shape = [n_core_samples]
Indices of core samples.
components_ : array, shape = [n_core_samples, n_features]
Copy of each core sample found by training.
labels_ : array, shape = [n_samples]
Cluster labels for each point in the dataset given to fit().
Noisy samples are given the label -1.
Examples
--------
>>> from sklearn.cluster import DBSCAN
>>> import numpy as np
>>> X = np.array([[1, 2], [2, 2], [2, 3],
... [8, 7], [8, 8], [25, 80]])
>>> clustering = DBSCAN(eps=3, min_samples=2).fit(X)
>>> clustering.labels_
array([ 0, 0, 0, 1, 1, -1])
>>> clustering
DBSCAN(eps=3, min_samples=2)
See also
--------
OPTICS
A similar clustering at multiple values of eps. Our implementation
is optimized for memory usage.
Notes
-----
For an example, see :ref:`examples/cluster/plot_dbscan.py
<sphx_glr_auto_examples_cluster_plot_dbscan.py>`.
This implementation bulk-computes all neighborhood queries, which increases
the memory complexity to O(n.d) where d is the average number of neighbors,
while original DBSCAN had memory complexity O(n). It may attract a higher
memory complexity when querying these nearest neighborhoods, depending
on the ``algorithm``.
One way to avoid the query complexity is to pre-compute sparse
neighborhoods in chunks using
:func:`NearestNeighbors.radius_neighbors_graph
<sklearn.neighbors.NearestNeighbors.radius_neighbors_graph>` with
``mode='distance'``, then using ``metric='precomputed'`` here.
Another way to reduce memory and computation time is to remove
(near-)duplicate points and use ``sample_weight`` instead.
:class:`cluster.OPTICS` provides a similar clustering with lower memory
usage.
References
----------
<NAME>., <NAME>, <NAME>, and <NAME>, "A Density-Based
Algorithm for Discovering Clusters in Large Spatial Databases with Noise".
In: Proceedings of the 2nd International Conference on Knowledge Discovery
and Data Mining, Portland, OR, AAAI Press, pp. 226-231. 1996
<NAME>., <NAME>., <NAME>., <NAME>., & <NAME>. (2017).
DBSCAN revisited, revisited: why and how you should (still) use DBSCAN.
ACM Transactions on Database Systems (TODS), 42(3), 19.
"""
def __init__(self, eps=0.5, min_samples=5, metric='euclidean',
metric_params=None, algorithm='auto', leaf_size=30, p=None,
n_jobs=None):
self.eps = eps
self.min_samples = min_samples
self.metric = metric
self.metric_params = metric_params
self.algorithm = algorithm
self.leaf_size = leaf_size
self.p = p
self.n_jobs = n_jobs
def fit(self, X, y=None, sample_weight=None):
"""Perform DBSCAN clustering from features, or distance matrix.
Parameters
----------
X : array-like or sparse matrix, shape (n_samples, n_features), or \
(n_samples, n_samples)
Training instances to cluster, or distances between instances if
``metric='precomputed'``. If a sparse matrix is provided, it will
be converted into a sparse ``csr_matrix``.
sample_weight : array, shape (n_samples,), optional
Weight of each sample, such that a sample with a weight of at least
``min_samples`` is by itself a core sample; a sample with a
negative weight may inhibit its eps-neighbor from being core.
Note that weights are absolute, and default to 1.
y : Ignored
Not used, present here for API consistency by convention.
Returns
-------
self
"""
X = check_array(X, accept_sparse='csr')
if not self.eps > 0.0:
raise ValueError("eps must be positive.")
if sample_weight is not None:
sample_weight = np.asarray(sample_weight)
check_consistent_length(X, sample_weight)
_daal_ready = ((self.algorithm in ['auto', 'brute']) and
(self.metric == 'euclidean' or
(self.metric == 'minkowski' and self.p == 2)) and
isinstance(X, np.ndarray) and (X.dtype.kind in ['d', 'f']))
if _daal_ready:
core_ind, assignments = _daal_dbscan(
X, self.eps,
self.min_samples,
sample_weight=sample_weight)
self.core_sample_indices_ = core_ind
self.labels_ = assignments
self.components_ = np.take(X, core_ind, axis=0)
return self
else:
return super().fit(X, y, sample_weight=sample_weight) | 0.84489 | 0.59514 |
from __future__ import annotations
import typing
import enum
from pantra.components.context import Context
from pantra.models.types import *
from pantra.common import ADict, WebUnits
if typing.TYPE_CHECKING:
from typing import *
from pantra.models.runtime import AttrInfo
from pantra.components.context import AnyNode
class EntityType(enum.Enum):
CATALOG = enum.auto()
DOCUMENT = enum.auto()
OTHER = enum.auto()
class ValuesDict(ADict):
def __getattr__(self, item):
if item[0] == '_':
return super().__getattr__(item)
return self[item]['value']
def __setattr__(self, key, value):
if key[0] == '_':
super().__setattr__(key, value)
else:
self[key]['value'] = value
TEMPLATE_MAP = {
str: 'TextField',
int: 'NumberField',
float: 'NumberField',
Decimal: 'NumberField',
bool: 'CheckField',
date: 'DateField',
time: 'TimeField',
datetime: 'DateTimeField',
timedelta: None, # TODO
bytes: None,
LongStr: 'TextAreaField',
Json: 'TextAreaField',
UUID: None, # TODO
}
def make_widget(parent: AnyNode, attr: AttrInfo, value: Any = None, **kwargs) -> Optional[Context]:
locals = ADict(
caption=parent.session.gettext(attr.title),
readonly=attr.readonly,
required=not attr.blank,
width='' if not attr.width else WebUnits(attr.width, 'em'),
in_body=hasattr(attr, 'body'),
) | kwargs
if value is not None:
locals['value'] = value
if attr.type == int:
locals['step'] = 1
if attr.name == 'name':
locals['focus'] = True
if isinstance(attr.type, EntityMeta):
template = 'EntityField'
locals['entity'] = attr.type
else:
attr_type = attr.type
if attr_type is LongStr and kwargs.get('flat'):
attr_type = str
template = TEMPLATE_MAP[attr_type]
if not template:
return None
c = Context(template, parent, locals=locals)
c.render.build()
return c | components/Widgets/__init__.py | from __future__ import annotations
import typing
import enum
from pantra.components.context import Context
from pantra.models.types import *
from pantra.common import ADict, WebUnits
if typing.TYPE_CHECKING:
from typing import *
from pantra.models.runtime import AttrInfo
from pantra.components.context import AnyNode
class EntityType(enum.Enum):
CATALOG = enum.auto()
DOCUMENT = enum.auto()
OTHER = enum.auto()
class ValuesDict(ADict):
def __getattr__(self, item):
if item[0] == '_':
return super().__getattr__(item)
return self[item]['value']
def __setattr__(self, key, value):
if key[0] == '_':
super().__setattr__(key, value)
else:
self[key]['value'] = value
TEMPLATE_MAP = {
str: 'TextField',
int: 'NumberField',
float: 'NumberField',
Decimal: 'NumberField',
bool: 'CheckField',
date: 'DateField',
time: 'TimeField',
datetime: 'DateTimeField',
timedelta: None, # TODO
bytes: None,
LongStr: 'TextAreaField',
Json: 'TextAreaField',
UUID: None, # TODO
}
def make_widget(parent: AnyNode, attr: AttrInfo, value: Any = None, **kwargs) -> Optional[Context]:
locals = ADict(
caption=parent.session.gettext(attr.title),
readonly=attr.readonly,
required=not attr.blank,
width='' if not attr.width else WebUnits(attr.width, 'em'),
in_body=hasattr(attr, 'body'),
) | kwargs
if value is not None:
locals['value'] = value
if attr.type == int:
locals['step'] = 1
if attr.name == 'name':
locals['focus'] = True
if isinstance(attr.type, EntityMeta):
template = 'EntityField'
locals['entity'] = attr.type
else:
attr_type = attr.type
if attr_type is LongStr and kwargs.get('flat'):
attr_type = str
template = TEMPLATE_MAP[attr_type]
if not template:
return None
c = Context(template, parent, locals=locals)
c.render.build()
return c | 0.438905 | 0.122235 |
# Standard library imports
import pkg_resources
# Third party imports
import pytest
from qtpy.QtCore import QObject, Signal, Slot
# Local imports
from spyder.plugins.completion.api import (
SpyderCompletionProvider, CompletionRequestTypes)
class DummyCompletionReceiver(QObject):
"""Dummy class that can handle LSP responses."""
sig_response = Signal(str, dict)
@Slot(str, dict)
def handle_response(self, method, params):
self.sig_response.emit(method, params)
class FakeProvider(SpyderCompletionProvider):
COMPLETION_PROVIDER_NAME = 'fake'
CONF_DEFAULTS = [
('key1', 'value1'),
('key2', 'value2'),
('key3', 'value3'),
('key4', 4)
]
CONF_VERSION = "0.1.0"
@pytest.fixture
def completion_receiver(completion_plugin_all_started):
completion_plugin, _ = completion_plugin_all_started
receiver = DummyCompletionReceiver(None)
return completion_plugin, receiver
def test_configuration_merge(completion_plugin):
first_defaults = dict(FakeProvider.CONF_DEFAULTS)
first_version = FakeProvider.CONF_VERSION
# Check that a new completion provider configuration is registered without
# changes
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, {}
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == first_defaults
assert conf_defaults == first_defaults
# Add a new value to the initial default configuration without changing the
# version
second_config = first_defaults.copy()
second_config['extra_value'] = ['value']
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in second_config.items()]
prev_config = {
FakeProvider.COMPLETION_PROVIDER_NAME: {
'version': first_version,
'values': first_defaults,
'defaults': first_defaults
}
}
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == second_config
assert conf_defaults == second_config
# Assert that default values cannot be changed without a bump in the minor
# version
config = first_defaults.copy()
config['key4'] = 5
third_config = first_defaults.copy()
third_config['key4'] = -1
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in third_config.items()]
prev_config = {
FakeProvider.COMPLETION_PROVIDER_NAME: {
'version': first_version,
'values': config,
'defaults': first_defaults
}
}
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == config
assert conf_defaults == first_defaults
# Assert that default values can be replaced with new ones when the
# minor version number is bumped.
config['key1'] = 'othervalue'
expected_config = config.copy()
expected_config['key4'] = -1
FakeProvider.CONF_VERSION = "0.1.1"
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "0.1.1"
assert conf_values == expected_config
assert conf_defaults == third_config
# Ensure that default values cannot be removed if the major version is not
# bumped
fourth_config = third_config.copy()
fourth_config.pop('key2')
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in fourth_config.items()]
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "0.1.1"
assert conf_values == expected_config
assert conf_defaults == third_config
# Remove an option when the major version is bumped.
FakeProvider.CONF_VERSION = "1.0.0"
expected_config.pop('key2')
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "1.0.0"
assert conf_values == expected_config
assert conf_defaults == fourth_config
def test_provider_detection(completion_plugin_all):
print(completion_plugin_all.providers)
assert len(completion_plugin_all.providers) == 3
@pytest.mark.order(1)
def test_plugin_completion_gather(qtbot_module, completion_receiver):
completion, receiver = completion_receiver
# Parameters to perform a textDocument/didOpen request
params = {
'file': 'test.py',
'language': 'python',
'version': 1,
'text': "# This is some text with some classe\nimport os\n\ncla",
'response_instance': receiver,
'offset': 1,
'selection_start': 0,
'selection_end': 0,
'codeeditor': receiver,
'requires_response': False
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_DID_OPEN, params)
# Parameters to perform a textDocument/completion request
params = {
'file': 'test.py',
'line': 2,
'column': 3,
'offset': 50,
'selection_start': 0,
'selection_end': 0,
'current_word': 'cla',
'codeeditor': receiver,
'response_instance': receiver,
'requires_response': True
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_COMPLETION, params)
_, response = blocker.args
response = response['params']
provider_set = {x['provider'] for x in response}
# Assert the response contains information from all the providers
provider_set == {'LSP', 'Fallback', 'Snippets'}
@pytest.mark.order(1)
def test_plugin_first_response_request(qtbot_module, completion_receiver):
completion, receiver = completion_receiver
# Parameters to perform a textDocument/didOpen request
params = {
'file': 'test2.py',
'language': 'python',
'version': 2,
'text': "# This is some text with some classe\nimport os\n\n",
'response_instance': receiver,
'offset': 1,
'diff': '',
'selection_start': 0,
'selection_end': 0,
'codeeditor': receiver,
'requires_response': False
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_DID_OPEN, params)
params = {
'file': 'test2.py',
'line': 1,
'column': 8,
'offset': 43,
'diff': '',
'response_instance': receiver,
'codeeditor': receiver,
'requires_response': True
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_HOVER, params)
_, response = blocker.args
assert len(response['params']) > 0 | spyder/plugins/completion/tests/test_plugin.py | # Standard library imports
import pkg_resources
# Third party imports
import pytest
from qtpy.QtCore import QObject, Signal, Slot
# Local imports
from spyder.plugins.completion.api import (
SpyderCompletionProvider, CompletionRequestTypes)
class DummyCompletionReceiver(QObject):
"""Dummy class that can handle LSP responses."""
sig_response = Signal(str, dict)
@Slot(str, dict)
def handle_response(self, method, params):
self.sig_response.emit(method, params)
class FakeProvider(SpyderCompletionProvider):
COMPLETION_PROVIDER_NAME = 'fake'
CONF_DEFAULTS = [
('key1', 'value1'),
('key2', 'value2'),
('key3', 'value3'),
('key4', 4)
]
CONF_VERSION = "0.1.0"
@pytest.fixture
def completion_receiver(completion_plugin_all_started):
completion_plugin, _ = completion_plugin_all_started
receiver = DummyCompletionReceiver(None)
return completion_plugin, receiver
def test_configuration_merge(completion_plugin):
first_defaults = dict(FakeProvider.CONF_DEFAULTS)
first_version = FakeProvider.CONF_VERSION
# Check that a new completion provider configuration is registered without
# changes
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, {}
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == first_defaults
assert conf_defaults == first_defaults
# Add a new value to the initial default configuration without changing the
# version
second_config = first_defaults.copy()
second_config['extra_value'] = ['value']
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in second_config.items()]
prev_config = {
FakeProvider.COMPLETION_PROVIDER_NAME: {
'version': first_version,
'values': first_defaults,
'defaults': first_defaults
}
}
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == second_config
assert conf_defaults == second_config
# Assert that default values cannot be changed without a bump in the minor
# version
config = first_defaults.copy()
config['key4'] = 5
third_config = first_defaults.copy()
third_config['key4'] = -1
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in third_config.items()]
prev_config = {
FakeProvider.COMPLETION_PROVIDER_NAME: {
'version': first_version,
'values': config,
'defaults': first_defaults
}
}
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == first_version
assert conf_values == config
assert conf_defaults == first_defaults
# Assert that default values can be replaced with new ones when the
# minor version number is bumped.
config['key1'] = 'othervalue'
expected_config = config.copy()
expected_config['key4'] = -1
FakeProvider.CONF_VERSION = "0.1.1"
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "0.1.1"
assert conf_values == expected_config
assert conf_defaults == third_config
# Ensure that default values cannot be removed if the major version is not
# bumped
fourth_config = third_config.copy()
fourth_config.pop('key2')
FakeProvider.CONF_DEFAULTS = [(k, v) for k, v in fourth_config.items()]
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "0.1.1"
assert conf_values == expected_config
assert conf_defaults == third_config
# Remove an option when the major version is bumped.
FakeProvider.CONF_VERSION = "1.0.0"
expected_config.pop('key2')
result = completion_plugin._merge_default_configurations(
FakeProvider, FakeProvider.COMPLETION_PROVIDER_NAME, prev_config
)
(conf_version, conf_values, conf_defaults) = result
assert conf_version == "1.0.0"
assert conf_values == expected_config
assert conf_defaults == fourth_config
def test_provider_detection(completion_plugin_all):
print(completion_plugin_all.providers)
assert len(completion_plugin_all.providers) == 3
@pytest.mark.order(1)
def test_plugin_completion_gather(qtbot_module, completion_receiver):
completion, receiver = completion_receiver
# Parameters to perform a textDocument/didOpen request
params = {
'file': 'test.py',
'language': 'python',
'version': 1,
'text': "# This is some text with some classe\nimport os\n\ncla",
'response_instance': receiver,
'offset': 1,
'selection_start': 0,
'selection_end': 0,
'codeeditor': receiver,
'requires_response': False
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_DID_OPEN, params)
# Parameters to perform a textDocument/completion request
params = {
'file': 'test.py',
'line': 2,
'column': 3,
'offset': 50,
'selection_start': 0,
'selection_end': 0,
'current_word': 'cla',
'codeeditor': receiver,
'response_instance': receiver,
'requires_response': True
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_COMPLETION, params)
_, response = blocker.args
response = response['params']
provider_set = {x['provider'] for x in response}
# Assert the response contains information from all the providers
provider_set == {'LSP', 'Fallback', 'Snippets'}
@pytest.mark.order(1)
def test_plugin_first_response_request(qtbot_module, completion_receiver):
completion, receiver = completion_receiver
# Parameters to perform a textDocument/didOpen request
params = {
'file': 'test2.py',
'language': 'python',
'version': 2,
'text': "# This is some text with some classe\nimport os\n\n",
'response_instance': receiver,
'offset': 1,
'diff': '',
'selection_start': 0,
'selection_end': 0,
'codeeditor': receiver,
'requires_response': False
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_DID_OPEN, params)
params = {
'file': 'test2.py',
'line': 1,
'column': 8,
'offset': 43,
'diff': '',
'response_instance': receiver,
'codeeditor': receiver,
'requires_response': True
}
with qtbot_module.waitSignal(receiver.sig_response, timeout=30000) as blocker:
completion.send_request(
'python', CompletionRequestTypes.DOCUMENT_HOVER, params)
_, response = blocker.args
assert len(response['params']) > 0 | 0.637595 | 0.390883 |
"""This program helps organize and version your dot files with Git."""
import homekeeper.config
import homekeeper.util
import logging
import os
import shutil
__version__ = '3.2.0'
class Homekeeper(object):
"""Organizes and versions your dot files."""
def __init__(self, pathname=None):
self.pathname = homekeeper.config.Config.PATHNAME
if pathname is not None:
self.pathname = pathname
self.config = homekeeper.config.Config(self.pathname)
def init(self):
"""Writes a configuration file with cwd as the dotfiles directory.
Configuration file is written as JSON, and will be removed if it exists
already. If configuration already exists, the new dotfiles directory
path will be merged into existing configuration.
"""
self.config.directory = os.path.realpath(os.getcwd())
logging.info('setting dotfiles directory to %s', self.config.directory)
self.config.save()
def track(self, pathname):
"""Moves a file or directory into your dotfiles directory so it can be
symlinked later.
Args:
pathname: The pathname of the directory or file you want to track.
"""
if not os.path.exists(pathname):
logging.info("pathname not found; won't track %s", pathname)
return
basename = os.path.basename(pathname)
target = os.path.join(self.config.directory, basename)
if os.path.exists(target):
logging.info('this path is already tracked at %s', target)
return
shutil.move(pathname, target)
logging.info('moved %s to %s', pathname, target)
os.symlink(target, pathname)
logging.info('symlinked %s -> %s', pathname, target)
def restore(self):
"""Restores all symlinks (inverse of link)."""
home = os.getenv('HOME')
if self.config.override:
homekeeper.util.restore(self.config.base,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.restore(self.config.directory,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.cleanup_symlinks(home)
def link(self):
"""Symlinks all files and directories from your dotfiles directory into
your home directory.
"""
home = os.getenv('HOME')
if self.config.override:
homekeeper.util.create_symlinks(self.config.base,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.create_symlinks(self.config.directory,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.cleanup_symlinks(home) | homekeeper/__init__.py | """This program helps organize and version your dot files with Git."""
import homekeeper.config
import homekeeper.util
import logging
import os
import shutil
__version__ = '3.2.0'
class Homekeeper(object):
"""Organizes and versions your dot files."""
def __init__(self, pathname=None):
self.pathname = homekeeper.config.Config.PATHNAME
if pathname is not None:
self.pathname = pathname
self.config = homekeeper.config.Config(self.pathname)
def init(self):
"""Writes a configuration file with cwd as the dotfiles directory.
Configuration file is written as JSON, and will be removed if it exists
already. If configuration already exists, the new dotfiles directory
path will be merged into existing configuration.
"""
self.config.directory = os.path.realpath(os.getcwd())
logging.info('setting dotfiles directory to %s', self.config.directory)
self.config.save()
def track(self, pathname):
"""Moves a file or directory into your dotfiles directory so it can be
symlinked later.
Args:
pathname: The pathname of the directory or file you want to track.
"""
if not os.path.exists(pathname):
logging.info("pathname not found; won't track %s", pathname)
return
basename = os.path.basename(pathname)
target = os.path.join(self.config.directory, basename)
if os.path.exists(target):
logging.info('this path is already tracked at %s', target)
return
shutil.move(pathname, target)
logging.info('moved %s to %s', pathname, target)
os.symlink(target, pathname)
logging.info('symlinked %s -> %s', pathname, target)
def restore(self):
"""Restores all symlinks (inverse of link)."""
home = os.getenv('HOME')
if self.config.override:
homekeeper.util.restore(self.config.base,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.restore(self.config.directory,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.cleanup_symlinks(home)
def link(self):
"""Symlinks all files and directories from your dotfiles directory into
your home directory.
"""
home = os.getenv('HOME')
if self.config.override:
homekeeper.util.create_symlinks(self.config.base,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.create_symlinks(self.config.directory,
home,
excludes=self.config.excludes,
cherrypicks=self.config.cherrypicks)
homekeeper.util.cleanup_symlinks(home) | 0.715523 | 0.184676 |
from __future__ import absolute_import
import os
import shutil
import hashlib
import stat
import re
from git.repo import Repo
from gitdb.exc import BadName, BadObject
from lockfile import LockFile
from st2common import log as logging
from st2common.content import utils
from st2common.constants.pack import MANIFEST_FILE_NAME
from st2common.constants.pack import PACK_RESERVED_CHARACTERS
from st2common.constants.pack import PACK_VERSION_SEPARATOR
from st2common.constants.pack import PACK_VERSION_REGEX
from st2common.services.packs import get_pack_from_index
from st2common.util.pack import get_pack_metadata
from st2common.util.pack import get_pack_ref_from_metadata
from st2common.util.green import shell
from st2common.util.versioning import complex_semver_match
from st2common.util.versioning import get_stackstorm_version
__all__ = [
'download_pack',
'get_repo_url',
'eval_repo_url',
'apply_pack_owner_group',
'apply_pack_permissions',
'get_and_set_proxy_config'
]
LOG = logging.getLogger(__name__)
CONFIG_FILE = 'config.yaml'
CURRENT_STACKSTROM_VERSION = get_stackstorm_version()
def download_pack(pack, abs_repo_base='/opt/stackstorm/packs', verify_ssl=True, force=False,
proxy_config=None, force_owner_group=True, force_permissions=True, logger=LOG):
"""
Download the pack and move it to /opt/stackstorm/packs.
:param abs_repo_base: Path where the pack should be installed to.
:type abs_repo_base: ``str``
:param pack: Pack name.
:rtype pack: ``str``
:param force_owner_group: Set owner group of the pack directory to the value defined in the
config.
:type force_owner_group: ``bool``
:param force_permissions: True to force 770 permission on all the pack content.
:type force_permissions: ``bool``
:param force: Force the installation and ignore / delete the lock file if it already exists.
:type force: ``bool``
:return: (pack_url, pack_ref, result)
:rtype: tuple
"""
proxy_config = proxy_config or {}
try:
pack_url, pack_version = get_repo_url(pack, proxy_config=proxy_config)
except Exception as e:
# Pack not found or similar
result = [None, pack, (False, str(e))]
return result
result = [pack_url, None, None]
temp_dir_name = hashlib.md5(pack_url).hexdigest()
lock_file = LockFile('/tmp/%s' % (temp_dir_name))
lock_file_path = lock_file.lock_file
if force:
logger.debug('Force mode is enabled, deleting lock file...')
try:
os.unlink(lock_file_path)
except OSError:
# Lock file doesn't exist or similar
pass
with lock_file:
try:
user_home = os.path.expanduser('~')
abs_local_path = os.path.join(user_home, temp_dir_name)
# 1. Clone / download the repo
clone_repo(temp_dir=abs_local_path, repo_url=pack_url, verify_ssl=verify_ssl,
ref=pack_version)
pack_ref = get_pack_ref(pack_dir=abs_local_path)
result[1] = pack_ref
# 2. Verify that the pack version if compatible with current StackStorm version
if not force:
verify_pack_version(pack_dir=abs_local_path)
# 3. Move pack to the final location
move_result = move_pack(abs_repo_base=abs_repo_base, pack_name=pack_ref,
abs_local_path=abs_local_path,
force_owner_group=force_owner_group,
force_permissions=force_permissions,
logger=logger)
result[2] = move_result
finally:
cleanup_repo(abs_local_path=abs_local_path)
return tuple(result)
def clone_repo(temp_dir, repo_url, verify_ssl=True, ref='master'):
# Switch to non-interactive mode
os.environ['GIT_TERMINAL_PROMPT'] = '0'
os.environ['GIT_ASKPASS'] = '/bin/echo'
# Disable SSL cert checking if explictly asked
if not verify_ssl:
os.environ['GIT_SSL_NO_VERIFY'] = 'true'
# Clone the repo from git; we don't use shallow copying
# because we want the user to work with the repo in the
# future.
repo = Repo.clone_from(repo_url, temp_dir)
active_branch = repo.active_branch
use_branch = False
# Special case when a default repo branch is not "master"
# No ref provided so we just use a default active branch
if (not ref or ref == active_branch.name) and repo.active_branch.object == repo.head.commit:
gitref = repo.active_branch.object
else:
# Try to match the reference to a branch name (i.e. "master")
gitref = get_gitref(repo, 'origin/%s' % ref)
if gitref:
use_branch = True
# Try to match the reference to a commit hash, a tag, or "master"
if not gitref:
gitref = get_gitref(repo, ref)
# Try to match the reference to a "vX.Y.Z" tag
if not gitref and re.match(PACK_VERSION_REGEX, ref):
gitref = get_gitref(repo, 'v%s' % ref)
# Giving up ¯\_(ツ)_/¯
if not gitref:
format_values = [ref, repo_url]
msg = '"%s" is not a valid version, hash, tag or branch in %s.'
valid_versions = get_valid_versions_for_repo(repo=repo)
if len(valid_versions) >= 1:
valid_versions_string = ', '.join(valid_versions)
msg += ' Available versions are: %s.'
format_values.append(valid_versions_string)
raise ValueError(msg % tuple(format_values))
# We're trying to figure out which branch the ref is actually on,
# since there's no direct way to check for this in git-python.
branches = repo.git.branch('-a', '--contains', gitref.hexsha) # pylint: disable=no-member
branches = branches.replace('*', '').split()
if active_branch.name not in branches or use_branch:
branch = 'origin/%s' % ref if use_branch else branches[0]
short_branch = ref if use_branch else branches[0].split('/')[-1]
repo.git.checkout('-b', short_branch, branch)
branch = repo.head.reference
else:
branch = repo.active_branch.name
repo.git.checkout(gitref.hexsha) # pylint: disable=no-member
repo.git.branch('-f', branch, gitref.hexsha) # pylint: disable=no-member
repo.git.checkout(branch)
return temp_dir
def move_pack(abs_repo_base, pack_name, abs_local_path, force_owner_group=True,
force_permissions=True, logger=LOG):
"""
Move pack directory into the final location.
"""
desired, message = is_desired_pack(abs_local_path, pack_name)
if desired:
to = abs_repo_base
dest_pack_path = os.path.join(abs_repo_base, pack_name)
if os.path.exists(dest_pack_path):
logger.debug('Removing existing pack %s in %s to replace.', pack_name,
dest_pack_path)
# Ensure to preserve any existing configuration
old_config_file = os.path.join(dest_pack_path, CONFIG_FILE)
new_config_file = os.path.join(abs_local_path, CONFIG_FILE)
if os.path.isfile(old_config_file):
shutil.move(old_config_file, new_config_file)
shutil.rmtree(dest_pack_path)
logger.debug('Moving pack from %s to %s.', abs_local_path, to)
shutil.move(abs_local_path, dest_pack_path)
# post move fix all permissions
if force_owner_group:
# 1. switch owner group to configured group
apply_pack_owner_group(pack_path=dest_pack_path)
if force_permissions:
# 2. Setup the right permissions and group ownership
apply_pack_permissions(pack_path=dest_pack_path)
message = 'Success.'
elif message:
message = 'Failure : %s' % message
return (desired, message)
def apply_pack_owner_group(pack_path):
"""
Switch owner group of the pack / virtualenv directory to the configured
group.
NOTE: This requires sudo access.
"""
pack_group = utils.get_pack_group()
if pack_group:
LOG.debug('Changing owner group of "%s" directory to %s' % (pack_path, pack_group))
exit_code, _, stderr, _ = shell.run_command(['sudo', 'chgrp', '-R', pack_group, pack_path])
if exit_code != 0:
# Non fatal, but we still log it
LOG.debug('Failed to change owner group on directory "%s" to "%s": %s' %
(pack_path, pack_group, stderr))
return True
def apply_pack_permissions(pack_path):
"""
Recursively apply permission 770 to pack and its contents.
"""
# These mask is same as mode = 775
mode = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH
os.chmod(pack_path, mode)
# Yuck! Since os.chmod does not support chmod -R walk manually.
for root, dirs, files in os.walk(pack_path):
for d in dirs:
os.chmod(os.path.join(root, d), mode)
for f in files:
os.chmod(os.path.join(root, f), mode)
def cleanup_repo(abs_local_path):
# basic lock checking etc?
if os.path.isdir(abs_local_path):
shutil.rmtree(abs_local_path)
# Utility functions
def get_repo_url(pack, proxy_config=None):
"""
Retrieve pack repo url.
:rtype: ``str``
:return: (repo_url, version)
:rtype: tuple
"""
pack_and_version = pack.split(PACK_VERSION_SEPARATOR)
name_or_url = pack_and_version[0]
version = pack_and_version[1] if len(pack_and_version) > 1 else None
if len(name_or_url.split('/')) == 1:
pack = get_pack_from_index(name_or_url, proxy_config=proxy_config)
if not pack:
raise Exception('No record of the "%s" pack in the index.' % (name_or_url))
return (pack['repo_url'], version)
else:
return (eval_repo_url(name_or_url), version)
def eval_repo_url(repo_url):
"""
Allow passing short GitHub style URLs.
"""
if not repo_url:
raise Exception('No valid repo_url provided or could be inferred.')
if repo_url.startswith("file://"):
return repo_url
else:
if len(repo_url.split('/')) == 2 and 'git@' not in repo_url:
url = 'https://github.com/{}'.format(repo_url)
else:
url = repo_url
return url
def is_desired_pack(abs_pack_path, pack_name):
# path has to exist.
if not os.path.exists(abs_pack_path):
return (False, 'Pack "%s" not found or it\'s missing a "pack.yaml" file.' %
(pack_name))
# should not include reserved characters
for character in PACK_RESERVED_CHARACTERS:
if character in pack_name:
return (False, 'Pack name "%s" contains reserved character "%s"' %
(pack_name, character))
# must contain a manifest file. Empty file is ok for now.
if not os.path.isfile(os.path.join(abs_pack_path, MANIFEST_FILE_NAME)):
return (False, 'Pack is missing a manifest file (%s).' % (MANIFEST_FILE_NAME))
return (True, '')
def verify_pack_version(pack_dir):
"""
Verify that the pack works with the currently running StackStorm version.
"""
pack_metadata = get_pack_metadata(pack_dir=pack_dir)
pack_name = pack_metadata.get('name', None)
required_stackstorm_version = pack_metadata.get('stackstorm_version', None)
# If stackstorm_version attribute is speficied, verify that the pack works with currently
# running version of StackStorm
if required_stackstorm_version:
if not complex_semver_match(CURRENT_STACKSTROM_VERSION, required_stackstorm_version):
msg = ('Pack "%s" requires StackStorm "%s", but current version is "%s". ' %
(pack_name, required_stackstorm_version, CURRENT_STACKSTROM_VERSION),
'You can override this restriction by providing the "force" flag, but ',
'the pack is not guaranteed to work.')
raise ValueError(msg)
return True
def get_gitref(repo, ref):
"""
Retrieve git repo reference if available.
"""
try:
return repo.commit(ref)
except (BadName, BadObject):
return False
def get_valid_versions_for_repo(repo):
"""
Retrieve valid versions (tags) for a particular repo (pack).
It does so by introspecting available tags.
:rtype: ``list`` of ``str``
"""
valid_versions = []
for tag in repo.tags:
if tag.name.startswith('v') and re.match(PACK_VERSION_REGEX, tag.name[1:]):
# Note: We strip leading "v" from the version number
valid_versions.append(tag.name[1:])
return valid_versions
def get_pack_ref(pack_dir):
"""
Read pack reference from the metadata file and sanitize it.
"""
metadata = get_pack_metadata(pack_dir=pack_dir)
pack_ref = get_pack_ref_from_metadata(metadata=metadata,
pack_directory_name=None)
return pack_ref
def get_and_set_proxy_config():
https_proxy = os.environ.get('https_proxy', None)
http_proxy = os.environ.get('http_proxy', None)
proxy_ca_bundle_path = os.environ.get('proxy_ca_bundle_path', None)
no_proxy = os.environ.get('no_proxy', None)
proxy_config = {}
if http_proxy or https_proxy:
LOG.debug('Using proxy %s', http_proxy if http_proxy else https_proxy)
proxy_config = {
'https_proxy': https_proxy,
'http_proxy': http_proxy,
'proxy_ca_bundle_path': proxy_ca_bundle_path,
'no_proxy': no_proxy
}
if https_proxy and not os.environ.get('https_proxy', None):
os.environ['https_proxy'] = https_proxy
if http_proxy and not os.environ.get('http_proxy', None):
os.environ['http_proxy'] = http_proxy
if no_proxy and not os.environ.get('no_proxy', None):
os.environ['no_proxy'] = no_proxy
if proxy_ca_bundle_path and not os.environ.get('proxy_ca_bundle_path', None):
os.environ['no_proxy'] = no_proxy
return proxy_config | st2common/st2common/util/pack_management.py | from __future__ import absolute_import
import os
import shutil
import hashlib
import stat
import re
from git.repo import Repo
from gitdb.exc import BadName, BadObject
from lockfile import LockFile
from st2common import log as logging
from st2common.content import utils
from st2common.constants.pack import MANIFEST_FILE_NAME
from st2common.constants.pack import PACK_RESERVED_CHARACTERS
from st2common.constants.pack import PACK_VERSION_SEPARATOR
from st2common.constants.pack import PACK_VERSION_REGEX
from st2common.services.packs import get_pack_from_index
from st2common.util.pack import get_pack_metadata
from st2common.util.pack import get_pack_ref_from_metadata
from st2common.util.green import shell
from st2common.util.versioning import complex_semver_match
from st2common.util.versioning import get_stackstorm_version
__all__ = [
'download_pack',
'get_repo_url',
'eval_repo_url',
'apply_pack_owner_group',
'apply_pack_permissions',
'get_and_set_proxy_config'
]
LOG = logging.getLogger(__name__)
CONFIG_FILE = 'config.yaml'
CURRENT_STACKSTROM_VERSION = get_stackstorm_version()
def download_pack(pack, abs_repo_base='/opt/stackstorm/packs', verify_ssl=True, force=False,
proxy_config=None, force_owner_group=True, force_permissions=True, logger=LOG):
"""
Download the pack and move it to /opt/stackstorm/packs.
:param abs_repo_base: Path where the pack should be installed to.
:type abs_repo_base: ``str``
:param pack: Pack name.
:rtype pack: ``str``
:param force_owner_group: Set owner group of the pack directory to the value defined in the
config.
:type force_owner_group: ``bool``
:param force_permissions: True to force 770 permission on all the pack content.
:type force_permissions: ``bool``
:param force: Force the installation and ignore / delete the lock file if it already exists.
:type force: ``bool``
:return: (pack_url, pack_ref, result)
:rtype: tuple
"""
proxy_config = proxy_config or {}
try:
pack_url, pack_version = get_repo_url(pack, proxy_config=proxy_config)
except Exception as e:
# Pack not found or similar
result = [None, pack, (False, str(e))]
return result
result = [pack_url, None, None]
temp_dir_name = hashlib.md5(pack_url).hexdigest()
lock_file = LockFile('/tmp/%s' % (temp_dir_name))
lock_file_path = lock_file.lock_file
if force:
logger.debug('Force mode is enabled, deleting lock file...')
try:
os.unlink(lock_file_path)
except OSError:
# Lock file doesn't exist or similar
pass
with lock_file:
try:
user_home = os.path.expanduser('~')
abs_local_path = os.path.join(user_home, temp_dir_name)
# 1. Clone / download the repo
clone_repo(temp_dir=abs_local_path, repo_url=pack_url, verify_ssl=verify_ssl,
ref=pack_version)
pack_ref = get_pack_ref(pack_dir=abs_local_path)
result[1] = pack_ref
# 2. Verify that the pack version if compatible with current StackStorm version
if not force:
verify_pack_version(pack_dir=abs_local_path)
# 3. Move pack to the final location
move_result = move_pack(abs_repo_base=abs_repo_base, pack_name=pack_ref,
abs_local_path=abs_local_path,
force_owner_group=force_owner_group,
force_permissions=force_permissions,
logger=logger)
result[2] = move_result
finally:
cleanup_repo(abs_local_path=abs_local_path)
return tuple(result)
def clone_repo(temp_dir, repo_url, verify_ssl=True, ref='master'):
# Switch to non-interactive mode
os.environ['GIT_TERMINAL_PROMPT'] = '0'
os.environ['GIT_ASKPASS'] = '/bin/echo'
# Disable SSL cert checking if explictly asked
if not verify_ssl:
os.environ['GIT_SSL_NO_VERIFY'] = 'true'
# Clone the repo from git; we don't use shallow copying
# because we want the user to work with the repo in the
# future.
repo = Repo.clone_from(repo_url, temp_dir)
active_branch = repo.active_branch
use_branch = False
# Special case when a default repo branch is not "master"
# No ref provided so we just use a default active branch
if (not ref or ref == active_branch.name) and repo.active_branch.object == repo.head.commit:
gitref = repo.active_branch.object
else:
# Try to match the reference to a branch name (i.e. "master")
gitref = get_gitref(repo, 'origin/%s' % ref)
if gitref:
use_branch = True
# Try to match the reference to a commit hash, a tag, or "master"
if not gitref:
gitref = get_gitref(repo, ref)
# Try to match the reference to a "vX.Y.Z" tag
if not gitref and re.match(PACK_VERSION_REGEX, ref):
gitref = get_gitref(repo, 'v%s' % ref)
# Giving up ¯\_(ツ)_/¯
if not gitref:
format_values = [ref, repo_url]
msg = '"%s" is not a valid version, hash, tag or branch in %s.'
valid_versions = get_valid_versions_for_repo(repo=repo)
if len(valid_versions) >= 1:
valid_versions_string = ', '.join(valid_versions)
msg += ' Available versions are: %s.'
format_values.append(valid_versions_string)
raise ValueError(msg % tuple(format_values))
# We're trying to figure out which branch the ref is actually on,
# since there's no direct way to check for this in git-python.
branches = repo.git.branch('-a', '--contains', gitref.hexsha) # pylint: disable=no-member
branches = branches.replace('*', '').split()
if active_branch.name not in branches or use_branch:
branch = 'origin/%s' % ref if use_branch else branches[0]
short_branch = ref if use_branch else branches[0].split('/')[-1]
repo.git.checkout('-b', short_branch, branch)
branch = repo.head.reference
else:
branch = repo.active_branch.name
repo.git.checkout(gitref.hexsha) # pylint: disable=no-member
repo.git.branch('-f', branch, gitref.hexsha) # pylint: disable=no-member
repo.git.checkout(branch)
return temp_dir
def move_pack(abs_repo_base, pack_name, abs_local_path, force_owner_group=True,
force_permissions=True, logger=LOG):
"""
Move pack directory into the final location.
"""
desired, message = is_desired_pack(abs_local_path, pack_name)
if desired:
to = abs_repo_base
dest_pack_path = os.path.join(abs_repo_base, pack_name)
if os.path.exists(dest_pack_path):
logger.debug('Removing existing pack %s in %s to replace.', pack_name,
dest_pack_path)
# Ensure to preserve any existing configuration
old_config_file = os.path.join(dest_pack_path, CONFIG_FILE)
new_config_file = os.path.join(abs_local_path, CONFIG_FILE)
if os.path.isfile(old_config_file):
shutil.move(old_config_file, new_config_file)
shutil.rmtree(dest_pack_path)
logger.debug('Moving pack from %s to %s.', abs_local_path, to)
shutil.move(abs_local_path, dest_pack_path)
# post move fix all permissions
if force_owner_group:
# 1. switch owner group to configured group
apply_pack_owner_group(pack_path=dest_pack_path)
if force_permissions:
# 2. Setup the right permissions and group ownership
apply_pack_permissions(pack_path=dest_pack_path)
message = 'Success.'
elif message:
message = 'Failure : %s' % message
return (desired, message)
def apply_pack_owner_group(pack_path):
"""
Switch owner group of the pack / virtualenv directory to the configured
group.
NOTE: This requires sudo access.
"""
pack_group = utils.get_pack_group()
if pack_group:
LOG.debug('Changing owner group of "%s" directory to %s' % (pack_path, pack_group))
exit_code, _, stderr, _ = shell.run_command(['sudo', 'chgrp', '-R', pack_group, pack_path])
if exit_code != 0:
# Non fatal, but we still log it
LOG.debug('Failed to change owner group on directory "%s" to "%s": %s' %
(pack_path, pack_group, stderr))
return True
def apply_pack_permissions(pack_path):
"""
Recursively apply permission 770 to pack and its contents.
"""
# These mask is same as mode = 775
mode = stat.S_IRWXU | stat.S_IRWXG | stat.S_IROTH | stat.S_IXOTH
os.chmod(pack_path, mode)
# Yuck! Since os.chmod does not support chmod -R walk manually.
for root, dirs, files in os.walk(pack_path):
for d in dirs:
os.chmod(os.path.join(root, d), mode)
for f in files:
os.chmod(os.path.join(root, f), mode)
def cleanup_repo(abs_local_path):
# basic lock checking etc?
if os.path.isdir(abs_local_path):
shutil.rmtree(abs_local_path)
# Utility functions
def get_repo_url(pack, proxy_config=None):
"""
Retrieve pack repo url.
:rtype: ``str``
:return: (repo_url, version)
:rtype: tuple
"""
pack_and_version = pack.split(PACK_VERSION_SEPARATOR)
name_or_url = pack_and_version[0]
version = pack_and_version[1] if len(pack_and_version) > 1 else None
if len(name_or_url.split('/')) == 1:
pack = get_pack_from_index(name_or_url, proxy_config=proxy_config)
if not pack:
raise Exception('No record of the "%s" pack in the index.' % (name_or_url))
return (pack['repo_url'], version)
else:
return (eval_repo_url(name_or_url), version)
def eval_repo_url(repo_url):
"""
Allow passing short GitHub style URLs.
"""
if not repo_url:
raise Exception('No valid repo_url provided or could be inferred.')
if repo_url.startswith("file://"):
return repo_url
else:
if len(repo_url.split('/')) == 2 and 'git@' not in repo_url:
url = 'https://github.com/{}'.format(repo_url)
else:
url = repo_url
return url
def is_desired_pack(abs_pack_path, pack_name):
# path has to exist.
if not os.path.exists(abs_pack_path):
return (False, 'Pack "%s" not found or it\'s missing a "pack.yaml" file.' %
(pack_name))
# should not include reserved characters
for character in PACK_RESERVED_CHARACTERS:
if character in pack_name:
return (False, 'Pack name "%s" contains reserved character "%s"' %
(pack_name, character))
# must contain a manifest file. Empty file is ok for now.
if not os.path.isfile(os.path.join(abs_pack_path, MANIFEST_FILE_NAME)):
return (False, 'Pack is missing a manifest file (%s).' % (MANIFEST_FILE_NAME))
return (True, '')
def verify_pack_version(pack_dir):
"""
Verify that the pack works with the currently running StackStorm version.
"""
pack_metadata = get_pack_metadata(pack_dir=pack_dir)
pack_name = pack_metadata.get('name', None)
required_stackstorm_version = pack_metadata.get('stackstorm_version', None)
# If stackstorm_version attribute is speficied, verify that the pack works with currently
# running version of StackStorm
if required_stackstorm_version:
if not complex_semver_match(CURRENT_STACKSTROM_VERSION, required_stackstorm_version):
msg = ('Pack "%s" requires StackStorm "%s", but current version is "%s". ' %
(pack_name, required_stackstorm_version, CURRENT_STACKSTROM_VERSION),
'You can override this restriction by providing the "force" flag, but ',
'the pack is not guaranteed to work.')
raise ValueError(msg)
return True
def get_gitref(repo, ref):
"""
Retrieve git repo reference if available.
"""
try:
return repo.commit(ref)
except (BadName, BadObject):
return False
def get_valid_versions_for_repo(repo):
"""
Retrieve valid versions (tags) for a particular repo (pack).
It does so by introspecting available tags.
:rtype: ``list`` of ``str``
"""
valid_versions = []
for tag in repo.tags:
if tag.name.startswith('v') and re.match(PACK_VERSION_REGEX, tag.name[1:]):
# Note: We strip leading "v" from the version number
valid_versions.append(tag.name[1:])
return valid_versions
def get_pack_ref(pack_dir):
"""
Read pack reference from the metadata file and sanitize it.
"""
metadata = get_pack_metadata(pack_dir=pack_dir)
pack_ref = get_pack_ref_from_metadata(metadata=metadata,
pack_directory_name=None)
return pack_ref
def get_and_set_proxy_config():
https_proxy = os.environ.get('https_proxy', None)
http_proxy = os.environ.get('http_proxy', None)
proxy_ca_bundle_path = os.environ.get('proxy_ca_bundle_path', None)
no_proxy = os.environ.get('no_proxy', None)
proxy_config = {}
if http_proxy or https_proxy:
LOG.debug('Using proxy %s', http_proxy if http_proxy else https_proxy)
proxy_config = {
'https_proxy': https_proxy,
'http_proxy': http_proxy,
'proxy_ca_bundle_path': proxy_ca_bundle_path,
'no_proxy': no_proxy
}
if https_proxy and not os.environ.get('https_proxy', None):
os.environ['https_proxy'] = https_proxy
if http_proxy and not os.environ.get('http_proxy', None):
os.environ['http_proxy'] = http_proxy
if no_proxy and not os.environ.get('no_proxy', None):
os.environ['no_proxy'] = no_proxy
if proxy_ca_bundle_path and not os.environ.get('proxy_ca_bundle_path', None):
os.environ['no_proxy'] = no_proxy
return proxy_config | 0.518302 | 0.091301 |
"""Helper functions for the Keras implementations of models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import multiprocessing
import os
import time
from absl import logging
import tensorflow as tf
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python import tf2
from tensorflow.python.eager import profiler
class BatchTimestamp(object):
"""A structure to store batch time stamp."""
def __init__(self, batch_index, timestamp):
self.batch_index = batch_index
self.timestamp = timestamp
def __repr__(self):
return "'BatchTimestamp<batch_index: {}, timestamp: {}>'".format(
self.batch_index, self.timestamp)
class TimeHistory(tf.keras.callbacks.Callback):
"""Callback for Keras models."""
def __init__(self, batch_size, log_steps, logdir=None):
"""Callback for logging performance.
Args:
batch_size: Total batch size.
log_steps: Interval of steps between logging of batch level stats.
logdir: Optional directory to write TensorBoard summaries.
"""
# TODO(wcromar): remove this parameter and rely on `logs` parameter of
# on_train_batch_end()
self.batch_size = batch_size
super(TimeHistory, self).__init__()
self.log_steps = log_steps
self.last_log_step = 0
self.steps_before_epoch = 0
self.steps_in_epoch = 0
self.start_time = None
if logdir:
self.summary_writer = tf.summary.create_file_writer(logdir)
else:
self.summary_writer = None
# Logs start of step 1 then end of each step based on log_steps interval.
self.timestamp_log = []
# Records the time each epoch takes to run from start to finish of epoch.
self.epoch_runtime_log = []
@property
def global_steps(self):
"""The current 1-indexed global step."""
return self.steps_before_epoch + self.steps_in_epoch
@property
def average_steps_per_second(self):
"""The average training steps per second across all epochs."""
return self.global_steps / sum(self.epoch_runtime_log)
@property
def average_examples_per_second(self):
"""The average number of training examples per second across all epochs."""
return self.average_steps_per_second * self.batch_size
def on_train_end(self, logs=None):
self.train_finish_time = time.time()
if self.summary_writer:
self.summary_writer.flush()
def on_epoch_begin(self, epoch, logs=None):
self.epoch_start = time.time()
def on_batch_begin(self, batch, logs=None):
if not self.start_time:
self.start_time = time.time()
# Record the timestamp of the first global step
if not self.timestamp_log:
self.timestamp_log.append(BatchTimestamp(self.global_steps,
self.start_time))
def on_batch_end(self, batch, logs=None):
"""Records elapse time of the batch and calculates examples per second."""
self.steps_in_epoch = batch + 1
steps_since_last_log = self.global_steps - self.last_log_step
if steps_since_last_log >= self.log_steps:
now = time.time()
elapsed_time = now - self.start_time
steps_per_second = steps_since_last_log / elapsed_time
examples_per_second = steps_per_second * self.batch_size
self.timestamp_log.append(BatchTimestamp(self.global_steps, now))
logging.info(
"TimeHistory: %.2f examples/second between steps %d and %d",
examples_per_second, self.last_log_step, self.global_steps)
if self.summary_writer:
with self.summary_writer.as_default():
tf.summary.scalar('global_step/sec', steps_per_second,
self.global_steps)
tf.summary.scalar('examples/sec', examples_per_second,
self.global_steps)
self.last_log_step = self.global_steps
self.start_time = None
def on_epoch_end(self, epoch, logs=None):
epoch_run_time = time.time() - self.epoch_start
self.epoch_runtime_log.append(epoch_run_time)
self.steps_before_epoch += self.steps_in_epoch
self.steps_in_epoch = 0
def get_profiler_callback(model_dir, profile_steps, enable_tensorboard,
steps_per_epoch):
"""Validate profile_steps flag value and return profiler callback."""
profile_steps_error_message = (
'profile_steps must be a comma separated pair of positive integers, '
'specifying the first and last steps to be profiled.'
)
try:
profile_steps = [int(i) for i in profile_steps.split(',')]
except ValueError:
raise ValueError(profile_steps_error_message)
if len(profile_steps) != 2:
raise ValueError(profile_steps_error_message)
start_step, stop_step = profile_steps
if start_step < 0 or start_step > stop_step:
raise ValueError(profile_steps_error_message)
if enable_tensorboard:
logging.warning(
'Both TensorBoard and profiler callbacks are used. Note that the '
'TensorBoard callback profiles the 2nd step (unless otherwise '
'specified). Please make sure the steps profiled by the two callbacks '
'do not overlap.')
return ProfilerCallback(model_dir, start_step, stop_step, steps_per_epoch)
class ProfilerCallback(tf.keras.callbacks.Callback):
"""Save profiles in specified step range to log directory."""
def __init__(self, log_dir, start_step, stop_step, steps_per_epoch):
super(ProfilerCallback, self).__init__()
self.log_dir = log_dir
self.start_step = start_step
self.stop_step = stop_step
self.start_epoch = start_step // steps_per_epoch
self.stop_epoch = stop_step // steps_per_epoch
self.start_step_in_epoch = start_step % steps_per_epoch
self.stop_step_in_epoch = stop_step % steps_per_epoch
self.should_start = False
self.should_stop = False
def on_epoch_begin(self, epoch, logs=None):
if epoch == self.start_epoch:
self.should_start = True
if epoch == self.stop_epoch:
self.should_stop = True
def on_batch_begin(self, batch, logs=None):
if batch == self.start_step_in_epoch and self.should_start:
self.should_start = False
profiler.start()
logging.info('Profiler started at Step %s', self.start_step)
def on_batch_end(self, batch, logs=None):
if batch == self.stop_step_in_epoch and self.should_stop:
self.should_stop = False
results = profiler.stop()
profiler.save(self.log_dir, results)
logging.info(
'Profiler saved profiles for steps between %s and %s to %s',
self.start_step, self.stop_step, self.log_dir)
def set_session_config(enable_eager=False,
enable_xla=False):
"""Sets the session config."""
if is_v2_0():
set_config_v2(enable_xla=enable_xla)
else:
config = get_config_proto_v1(enable_xla=enable_xla)
if enable_eager:
tf.compat.v1.enable_eager_execution(config=config)
else:
sess = tf.Session(config=config)
tf.keras.backend.set_session(sess)
def get_config_proto_v1(enable_xla=False):
"""Return config proto according to flag settings, or None to use default."""
config = None
if enable_xla:
config = tf.compat.v1.ConfigProto()
config.graph_options.optimizer_options.global_jit_level = (
tf.OptimizerOptions.ON_2)
return config
def set_config_v2(enable_xla=False):
"""Config eager context according to flag values using TF 2.0 API."""
if enable_xla:
tf.config.optimizer.set_jit(True)
def is_v2_0():
"""Returns true if using tf 2.0."""
return tf2.enabled()
def set_gpu_thread_mode_and_count(gpu_thread_mode, num_gpus,
per_gpu_thread_count):
"""Set GPU thread mode and count, and recommend dataset threads count."""
cpu_count = multiprocessing.cpu_count()
logging.info('Logical CPU cores: %s', cpu_count)
# Allocate private thread pool for each GPU to schedule and launch kernels
per_gpu_thread_count = per_gpu_thread_count or 2
os.environ['TF_GPU_THREAD_MODE'] = gpu_thread_mode
os.environ['TF_GPU_THREAD_COUNT'] = str(per_gpu_thread_count)
logging.info('TF_GPU_THREAD_COUNT: %s',
os.environ['TF_GPU_THREAD_COUNT'])
logging.info('TF_GPU_THREAD_MODE: %s',
os.environ['TF_GPU_THREAD_MODE'])
# Limit data preprocessing threadpool to CPU cores minus number of total GPU
# private threads and memory copy threads.
total_gpu_thread_count = per_gpu_thread_count * num_gpus
num_runtime_threads = num_gpus
datasets_num_private_threads = min(
cpu_count - total_gpu_thread_count - num_runtime_threads,
num_gpus * 8)
logging.info('Recommended datasets_num_private_threads: %s',
datasets_num_private_threads)
return datasets_num_private_threads | image_classification/tensorflow2/tf2_common/utils/misc/keras_utils.py | """Helper functions for the Keras implementations of models."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import multiprocessing
import os
import time
from absl import logging
import tensorflow as tf
from tensorflow.core.protobuf import rewriter_config_pb2
from tensorflow.python import tf2
from tensorflow.python.eager import profiler
class BatchTimestamp(object):
"""A structure to store batch time stamp."""
def __init__(self, batch_index, timestamp):
self.batch_index = batch_index
self.timestamp = timestamp
def __repr__(self):
return "'BatchTimestamp<batch_index: {}, timestamp: {}>'".format(
self.batch_index, self.timestamp)
class TimeHistory(tf.keras.callbacks.Callback):
"""Callback for Keras models."""
def __init__(self, batch_size, log_steps, logdir=None):
"""Callback for logging performance.
Args:
batch_size: Total batch size.
log_steps: Interval of steps between logging of batch level stats.
logdir: Optional directory to write TensorBoard summaries.
"""
# TODO(wcromar): remove this parameter and rely on `logs` parameter of
# on_train_batch_end()
self.batch_size = batch_size
super(TimeHistory, self).__init__()
self.log_steps = log_steps
self.last_log_step = 0
self.steps_before_epoch = 0
self.steps_in_epoch = 0
self.start_time = None
if logdir:
self.summary_writer = tf.summary.create_file_writer(logdir)
else:
self.summary_writer = None
# Logs start of step 1 then end of each step based on log_steps interval.
self.timestamp_log = []
# Records the time each epoch takes to run from start to finish of epoch.
self.epoch_runtime_log = []
@property
def global_steps(self):
"""The current 1-indexed global step."""
return self.steps_before_epoch + self.steps_in_epoch
@property
def average_steps_per_second(self):
"""The average training steps per second across all epochs."""
return self.global_steps / sum(self.epoch_runtime_log)
@property
def average_examples_per_second(self):
"""The average number of training examples per second across all epochs."""
return self.average_steps_per_second * self.batch_size
def on_train_end(self, logs=None):
self.train_finish_time = time.time()
if self.summary_writer:
self.summary_writer.flush()
def on_epoch_begin(self, epoch, logs=None):
self.epoch_start = time.time()
def on_batch_begin(self, batch, logs=None):
if not self.start_time:
self.start_time = time.time()
# Record the timestamp of the first global step
if not self.timestamp_log:
self.timestamp_log.append(BatchTimestamp(self.global_steps,
self.start_time))
def on_batch_end(self, batch, logs=None):
"""Records elapse time of the batch and calculates examples per second."""
self.steps_in_epoch = batch + 1
steps_since_last_log = self.global_steps - self.last_log_step
if steps_since_last_log >= self.log_steps:
now = time.time()
elapsed_time = now - self.start_time
steps_per_second = steps_since_last_log / elapsed_time
examples_per_second = steps_per_second * self.batch_size
self.timestamp_log.append(BatchTimestamp(self.global_steps, now))
logging.info(
"TimeHistory: %.2f examples/second between steps %d and %d",
examples_per_second, self.last_log_step, self.global_steps)
if self.summary_writer:
with self.summary_writer.as_default():
tf.summary.scalar('global_step/sec', steps_per_second,
self.global_steps)
tf.summary.scalar('examples/sec', examples_per_second,
self.global_steps)
self.last_log_step = self.global_steps
self.start_time = None
def on_epoch_end(self, epoch, logs=None):
epoch_run_time = time.time() - self.epoch_start
self.epoch_runtime_log.append(epoch_run_time)
self.steps_before_epoch += self.steps_in_epoch
self.steps_in_epoch = 0
def get_profiler_callback(model_dir, profile_steps, enable_tensorboard,
steps_per_epoch):
"""Validate profile_steps flag value and return profiler callback."""
profile_steps_error_message = (
'profile_steps must be a comma separated pair of positive integers, '
'specifying the first and last steps to be profiled.'
)
try:
profile_steps = [int(i) for i in profile_steps.split(',')]
except ValueError:
raise ValueError(profile_steps_error_message)
if len(profile_steps) != 2:
raise ValueError(profile_steps_error_message)
start_step, stop_step = profile_steps
if start_step < 0 or start_step > stop_step:
raise ValueError(profile_steps_error_message)
if enable_tensorboard:
logging.warning(
'Both TensorBoard and profiler callbacks are used. Note that the '
'TensorBoard callback profiles the 2nd step (unless otherwise '
'specified). Please make sure the steps profiled by the two callbacks '
'do not overlap.')
return ProfilerCallback(model_dir, start_step, stop_step, steps_per_epoch)
class ProfilerCallback(tf.keras.callbacks.Callback):
"""Save profiles in specified step range to log directory."""
def __init__(self, log_dir, start_step, stop_step, steps_per_epoch):
super(ProfilerCallback, self).__init__()
self.log_dir = log_dir
self.start_step = start_step
self.stop_step = stop_step
self.start_epoch = start_step // steps_per_epoch
self.stop_epoch = stop_step // steps_per_epoch
self.start_step_in_epoch = start_step % steps_per_epoch
self.stop_step_in_epoch = stop_step % steps_per_epoch
self.should_start = False
self.should_stop = False
def on_epoch_begin(self, epoch, logs=None):
if epoch == self.start_epoch:
self.should_start = True
if epoch == self.stop_epoch:
self.should_stop = True
def on_batch_begin(self, batch, logs=None):
if batch == self.start_step_in_epoch and self.should_start:
self.should_start = False
profiler.start()
logging.info('Profiler started at Step %s', self.start_step)
def on_batch_end(self, batch, logs=None):
if batch == self.stop_step_in_epoch and self.should_stop:
self.should_stop = False
results = profiler.stop()
profiler.save(self.log_dir, results)
logging.info(
'Profiler saved profiles for steps between %s and %s to %s',
self.start_step, self.stop_step, self.log_dir)
def set_session_config(enable_eager=False,
enable_xla=False):
"""Sets the session config."""
if is_v2_0():
set_config_v2(enable_xla=enable_xla)
else:
config = get_config_proto_v1(enable_xla=enable_xla)
if enable_eager:
tf.compat.v1.enable_eager_execution(config=config)
else:
sess = tf.Session(config=config)
tf.keras.backend.set_session(sess)
def get_config_proto_v1(enable_xla=False):
"""Return config proto according to flag settings, or None to use default."""
config = None
if enable_xla:
config = tf.compat.v1.ConfigProto()
config.graph_options.optimizer_options.global_jit_level = (
tf.OptimizerOptions.ON_2)
return config
def set_config_v2(enable_xla=False):
"""Config eager context according to flag values using TF 2.0 API."""
if enable_xla:
tf.config.optimizer.set_jit(True)
def is_v2_0():
"""Returns true if using tf 2.0."""
return tf2.enabled()
def set_gpu_thread_mode_and_count(gpu_thread_mode, num_gpus,
per_gpu_thread_count):
"""Set GPU thread mode and count, and recommend dataset threads count."""
cpu_count = multiprocessing.cpu_count()
logging.info('Logical CPU cores: %s', cpu_count)
# Allocate private thread pool for each GPU to schedule and launch kernels
per_gpu_thread_count = per_gpu_thread_count or 2
os.environ['TF_GPU_THREAD_MODE'] = gpu_thread_mode
os.environ['TF_GPU_THREAD_COUNT'] = str(per_gpu_thread_count)
logging.info('TF_GPU_THREAD_COUNT: %s',
os.environ['TF_GPU_THREAD_COUNT'])
logging.info('TF_GPU_THREAD_MODE: %s',
os.environ['TF_GPU_THREAD_MODE'])
# Limit data preprocessing threadpool to CPU cores minus number of total GPU
# private threads and memory copy threads.
total_gpu_thread_count = per_gpu_thread_count * num_gpus
num_runtime_threads = num_gpus
datasets_num_private_threads = min(
cpu_count - total_gpu_thread_count - num_runtime_threads,
num_gpus * 8)
logging.info('Recommended datasets_num_private_threads: %s',
datasets_num_private_threads)
return datasets_num_private_threads | 0.862901 | 0.422266 |
from pprint import pprint
from marshmallow import fields, Schema, ValidationError, validate, validates, validates_schema
class PersonSchema(Schema):
first_name = fields.String(required=True, error_messages={"required": "Please enter first name"})
last_name = fields.String(allow_none=None)
email = fields.Email(required=True, error_messages={"required": "Please enter email."})
income = fields.Float(allow_none=None)
def handle_validation_error():
json_string = '{"first_name" : "HMTMCSE", "age" : 7}'
try:
person = PersonSchema().loads(json_string)
pprint(person)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
print("\nValid datas :")
# Get the valid data
print(error.valid_data)
def validate_list_of_data():
input_dict = [
{"first_name": "HMTMCSE", "email": "<EMAIL>"},
{"last_name": "Education", "email": "<EMAIL>"},
{"last_name": "Education", "email": "<EMAIL>"},
]
try:
persons = PersonSchema().load(input_dict, many=True)
pprint(persons)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
print("\nValid datas :")
# Get the valid data
print(error.valid_data)
def validate_without_deserialization():
data = {"last_name": "Education", "email": "<EMAIL>"}
try:
errors = PersonSchema().validate(data)
pprint(errors)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
class ApplySchemaValidator(Schema):
permission = fields.String(validate=validate.OneOf(["read", "write", "admin"]))
age = fields.Integer(allow_none=None, validate=validate.Range(min=16, max=25))
def check_schema_validator_validation():
try:
data = {
"permission": "red",
"age": 28
}
response = ApplySchemaValidator().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
print("\nValid datas :")
# Get the valid data
print(error.valid_data)
def is_even(data):
if data % 2 != 0:
raise ValidationError("Not an even value.")
class CustomValidator(Schema):
data = fields.Float(validate=validate.And(validate.Range(min=4), is_even))
def check_custom_validator_validation():
try:
data = {
"data": 3
}
response = CustomValidator().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
class ValidateByMethod(Schema):
data = fields.Float()
@validates("data")
def validate_quantity(self, value):
if value < 0:
raise ValidationError("Quantity must be greater than 0.")
if value > 30:
raise ValidationError("Quantity must not be greater than 30.")
def check_validate_by_method():
try:
data = {
"data": 31
}
response = ValidateByMethod().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
class SchemaValidation(Schema):
password = fields.String()
confirm_password = fields.String()
@validates_schema
def validate_schema(self, data, **kwargs):
if data["password"] != data["confirm_password"]:
raise ValidationError("Password not matched!", "confirm_password")
def check_schema_validation():
try:
data = {
"password": "<PASSWORD>",
"confirm_password": "<PASSWORD>"
}
response = SchemaValidation().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
fields.Field.default_error_messages["required"] = "Empty value not allowed!"
class CustomErrorMessage(Schema):
password = fields.String(required=True)
def check_custom_error_message():
try:
data = {}
response = CustomErrorMessage().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
if __name__ == '__main__':
check_custom_validator_validation() | schema_validation.py | from pprint import pprint
from marshmallow import fields, Schema, ValidationError, validate, validates, validates_schema
class PersonSchema(Schema):
first_name = fields.String(required=True, error_messages={"required": "Please enter first name"})
last_name = fields.String(allow_none=None)
email = fields.Email(required=True, error_messages={"required": "Please enter email."})
income = fields.Float(allow_none=None)
def handle_validation_error():
json_string = '{"first_name" : "HMTMCSE", "age" : 7}'
try:
person = PersonSchema().loads(json_string)
pprint(person)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
print("\nValid datas :")
# Get the valid data
print(error.valid_data)
def validate_list_of_data():
input_dict = [
{"first_name": "HMTMCSE", "email": "<EMAIL>"},
{"last_name": "Education", "email": "<EMAIL>"},
{"last_name": "Education", "email": "<EMAIL>"},
]
try:
persons = PersonSchema().load(input_dict, many=True)
pprint(persons)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
print("\nValid datas :")
# Get the valid data
print(error.valid_data)
def validate_without_deserialization():
data = {"last_name": "Education", "email": "<EMAIL>"}
try:
errors = PersonSchema().validate(data)
pprint(errors)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
class ApplySchemaValidator(Schema):
permission = fields.String(validate=validate.OneOf(["read", "write", "admin"]))
age = fields.Integer(allow_none=None, validate=validate.Range(min=16, max=25))
def check_schema_validator_validation():
try:
data = {
"permission": "red",
"age": 28
}
response = ApplySchemaValidator().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
print("\nValid datas :")
# Get the valid data
print(error.valid_data)
def is_even(data):
if data % 2 != 0:
raise ValidationError("Not an even value.")
class CustomValidator(Schema):
data = fields.Float(validate=validate.And(validate.Range(min=4), is_even))
def check_custom_validator_validation():
try:
data = {
"data": 3
}
response = CustomValidator().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
class ValidateByMethod(Schema):
data = fields.Float()
@validates("data")
def validate_quantity(self, value):
if value < 0:
raise ValidationError("Quantity must be greater than 0.")
if value > 30:
raise ValidationError("Quantity must not be greater than 30.")
def check_validate_by_method():
try:
data = {
"data": 31
}
response = ValidateByMethod().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
class SchemaValidation(Schema):
password = fields.String()
confirm_password = fields.String()
@validates_schema
def validate_schema(self, data, **kwargs):
if data["password"] != data["confirm_password"]:
raise ValidationError("Password not matched!", "confirm_password")
def check_schema_validation():
try:
data = {
"password": "<PASSWORD>",
"confirm_password": "<PASSWORD>"
}
response = SchemaValidation().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
fields.Field.default_error_messages["required"] = "Empty value not allowed!"
class CustomErrorMessage(Schema):
password = fields.String(required=True)
def check_custom_error_message():
try:
data = {}
response = CustomErrorMessage().load(data)
pprint(response)
except ValidationError as error:
# Print Error Messages
print("Print Errors: ")
print(error.messages)
if __name__ == '__main__':
check_custom_validator_validation() | 0.373304 | 0.231951 |
import random
class Converter(object):
def dec2bin(self, decimal):
if type(decimal).__name__ == 'str':
print "Error type : Not a integer"
return 0
digit = 1
binary = 0
decimal = int(decimal)
while decimal != 0:
binary = binary + (decimal%2) * digit
decimal = decimal/2
digit = digit * 10
return str(binary)
def bin2dec(self, binary):
if type(binary).__name__ == 'int':
print "Error type : Not a string"
return 0
digit = 1
decimal = 0
binary = int(binary)
while binary != 0:
decimal = decimal + (binary%10) * digit
binary = binary/10
digit = digit * 2
return decimal
def count_bit(self, value):
if type(value).__name__ == 'int':
binary = self.dec2bin(value)
num_bits = len(binary)
else:
num_bits = len(value)
return num_bits
class Sender(Converter):
def __init__(self, dataword, divisor):
self.divisor = self.bin2dec(divisor)
self.dataword = self.bin2dec(dataword)
self.remainder = 0
self.codeword = 0
self.arg_dataword = 0
def __getArgdataword(self):
self.arg_dataword = self.dataword << self.count_bit(self.divisor)-1
return self.arg_dataword
def __generator(self):
arg_bit = self.count_bit(self.dec2bin(self.arg_dataword))
div_bit = self.count_bit(self.dec2bin(self.divisor))
padded_bit = arg_bit - div_bit
divisor_shift = self.divisor << padded_bit
result = self.arg_dataword
while(True):
result = result ^ divisor_shift
#print self.dec2bin(result)
padded_bit = self.count_bit(self.dec2bin(result)) - div_bit
if padded_bit < 0:
break
divisor_shift = self.divisor << padded_bit
self.remainder = result
return self.remainder
def __getCodeword(self):
self.codeword = self.arg_dataword | self.remainder
return self.codeword
def send(self):
self.arg_dataword = self.__getArgdataword()
self.remainder = self.__generator()
self.codeword = self.__getCodeword()
def converter():
self.arg_dataword2 = self.dec2bin(self.arg_dataword)
self.remainder2 = self.dec2bin(self.remainder)
self.codeword2 = self.dec2bin(self.codeword)
converter()
class Receiver(Converter):
def __init__(self, codeword, divisor):
self.codeword = codeword
self.divisor = self.bin2dec(divisor)
self.syndrome = 0
self.rx_dataword = 0
self.discard = False
def __getDataword(self):
self.rx_dataword = self.codeword >> self.count_bit(self.divisor)-1
return self.rx_dataword
def __checker(self):
code_bit = self.count_bit(self.dec2bin(self.codeword))
div_bit = self.count_bit(self.dec2bin(self.divisor))
padded_bit = code_bit - div_bit
divisor_shift = self.divisor << padded_bit
result = self.codeword
while(True):
result = result ^ divisor_shift
#print self.dec2bin(result)
padded_bit = self.count_bit(self.dec2bin(result)) - div_bit
if padded_bit < 0:
break
divisor_shift = self.divisor << padded_bit
self.syndrome = result
return self.syndrome
def __decision(self):
self.rx_dataword = self.__getDataword()
if self.syndrome == 0:
return False, self.rx_dataword
else:
return True, self.rx_dataword
def receive(self):
self.syndrome = self.__checker()
self.discard, self.rx_dataword = self.__decision()
def converter():
self.syndrome2 = self.dec2bin(self.syndrome)
self.rx_dataword2 = self.dec2bin(self.rx_dataword)
converter()
class Channel(Converter):
def __init__(self, codeword, rate=0.3):
self.codeword = codeword
self.rate = rate
self.rand = random.randint(1,101)
self.noise = random.randint(1, self.codeword)
self.ch_codeword = 0
self.__passed()
def __passed(self):
if self.rand > self.rate*100:
self.ch_codeword = self.codeword
elif self.rand > self.rate*100*0.5 and self.rand <= self.rate*100:
self.ch_codeword = self.codeword | self.noise
else:
self.ch_codeword = self.codeword ^ self.noise
self.ch_codeword2 = self.dec2bin(self.ch_codeword) | crc/PyCRC-master/pycrc/crclib.py | import random
class Converter(object):
def dec2bin(self, decimal):
if type(decimal).__name__ == 'str':
print "Error type : Not a integer"
return 0
digit = 1
binary = 0
decimal = int(decimal)
while decimal != 0:
binary = binary + (decimal%2) * digit
decimal = decimal/2
digit = digit * 10
return str(binary)
def bin2dec(self, binary):
if type(binary).__name__ == 'int':
print "Error type : Not a string"
return 0
digit = 1
decimal = 0
binary = int(binary)
while binary != 0:
decimal = decimal + (binary%10) * digit
binary = binary/10
digit = digit * 2
return decimal
def count_bit(self, value):
if type(value).__name__ == 'int':
binary = self.dec2bin(value)
num_bits = len(binary)
else:
num_bits = len(value)
return num_bits
class Sender(Converter):
def __init__(self, dataword, divisor):
self.divisor = self.bin2dec(divisor)
self.dataword = self.bin2dec(dataword)
self.remainder = 0
self.codeword = 0
self.arg_dataword = 0
def __getArgdataword(self):
self.arg_dataword = self.dataword << self.count_bit(self.divisor)-1
return self.arg_dataword
def __generator(self):
arg_bit = self.count_bit(self.dec2bin(self.arg_dataword))
div_bit = self.count_bit(self.dec2bin(self.divisor))
padded_bit = arg_bit - div_bit
divisor_shift = self.divisor << padded_bit
result = self.arg_dataword
while(True):
result = result ^ divisor_shift
#print self.dec2bin(result)
padded_bit = self.count_bit(self.dec2bin(result)) - div_bit
if padded_bit < 0:
break
divisor_shift = self.divisor << padded_bit
self.remainder = result
return self.remainder
def __getCodeword(self):
self.codeword = self.arg_dataword | self.remainder
return self.codeword
def send(self):
self.arg_dataword = self.__getArgdataword()
self.remainder = self.__generator()
self.codeword = self.__getCodeword()
def converter():
self.arg_dataword2 = self.dec2bin(self.arg_dataword)
self.remainder2 = self.dec2bin(self.remainder)
self.codeword2 = self.dec2bin(self.codeword)
converter()
class Receiver(Converter):
def __init__(self, codeword, divisor):
self.codeword = codeword
self.divisor = self.bin2dec(divisor)
self.syndrome = 0
self.rx_dataword = 0
self.discard = False
def __getDataword(self):
self.rx_dataword = self.codeword >> self.count_bit(self.divisor)-1
return self.rx_dataword
def __checker(self):
code_bit = self.count_bit(self.dec2bin(self.codeword))
div_bit = self.count_bit(self.dec2bin(self.divisor))
padded_bit = code_bit - div_bit
divisor_shift = self.divisor << padded_bit
result = self.codeword
while(True):
result = result ^ divisor_shift
#print self.dec2bin(result)
padded_bit = self.count_bit(self.dec2bin(result)) - div_bit
if padded_bit < 0:
break
divisor_shift = self.divisor << padded_bit
self.syndrome = result
return self.syndrome
def __decision(self):
self.rx_dataword = self.__getDataword()
if self.syndrome == 0:
return False, self.rx_dataword
else:
return True, self.rx_dataword
def receive(self):
self.syndrome = self.__checker()
self.discard, self.rx_dataword = self.__decision()
def converter():
self.syndrome2 = self.dec2bin(self.syndrome)
self.rx_dataword2 = self.dec2bin(self.rx_dataword)
converter()
class Channel(Converter):
def __init__(self, codeword, rate=0.3):
self.codeword = codeword
self.rate = rate
self.rand = random.randint(1,101)
self.noise = random.randint(1, self.codeword)
self.ch_codeword = 0
self.__passed()
def __passed(self):
if self.rand > self.rate*100:
self.ch_codeword = self.codeword
elif self.rand > self.rate*100*0.5 and self.rand <= self.rate*100:
self.ch_codeword = self.codeword | self.noise
else:
self.ch_codeword = self.codeword ^ self.noise
self.ch_codeword2 = self.dec2bin(self.ch_codeword) | 0.500488 | 0.191914 |
import datetime
import random
import re
import ssl
import typing
import aiohttp
from vkquick.json_parsers import json_parser_policy
def random_id(side: int = 2 ** 31 - 1) -> int:
"""
Случайное число в диапазоне +-`side`.
Используется для API метода `messages.send`
"""
return random.randint(-side, +side)
def peer(chat_id: int = 0) -> int:
"""
Добавляет к `chat_id` значение, чтобы оно стало `peer_id`.
Краткая и более приятная запись сложения любого числа с 2 000 000 000
(да, на один символ)
peer_id=vq.peer(123)
"""
return 2_000_000_000 + chat_id
async def download_file(
url: str,
*,
session: typing.Optional[aiohttp.ClientSession] = None,
**kwargs,
) -> bytes:
"""
Скачивание файлов по их прямой ссылке
"""
used_session = session or aiohttp.ClientSession(
connector=aiohttp.TCPConnector(ssl=ssl.SSLContext()),
skip_auto_headers={"User-Agent"},
raise_for_status=True,
json_serialize=json_parser_policy.dumps,
)
async with used_session.get(url, **kwargs) as response:
downloaded_file = await response.read()
if session is None:
await used_session.close()
return downloaded_file
_registration_date_regex = re.compile('ya:created dc:date="(?P<date>.*?)"')
async def get_user_registration_date(
id_: int, *, session: typing.Optional[aiohttp.ClientSession] = None
) -> datetime.datetime:
request_session = session or aiohttp.ClientSession(
connector=aiohttp.TCPConnector(ssl=False),
skip_auto_headers={"User-Agent"},
raise_for_status=True,
json_serialize=json_parser_policy.dumps,
)
async with request_session:
async with request_session.get(
"https://vk.com/foaf.php", params={"id": id_}
) as response:
user_info = await response.text()
registration_date = _registration_date_regex.search(user_info)
if registration_date is None:
raise ValueError(f"No such user with id `{id_}`")
registration_date = registration_date.group("date")
registration_date = datetime.datetime.fromisoformat(
registration_date
)
return registration_date
def get_origin_typing(type):
# If generic
if typing.get_args(type):
return typing.get_origin(type)
return type | vkquick/chatbot/utils.py | import datetime
import random
import re
import ssl
import typing
import aiohttp
from vkquick.json_parsers import json_parser_policy
def random_id(side: int = 2 ** 31 - 1) -> int:
"""
Случайное число в диапазоне +-`side`.
Используется для API метода `messages.send`
"""
return random.randint(-side, +side)
def peer(chat_id: int = 0) -> int:
"""
Добавляет к `chat_id` значение, чтобы оно стало `peer_id`.
Краткая и более приятная запись сложения любого числа с 2 000 000 000
(да, на один символ)
peer_id=vq.peer(123)
"""
return 2_000_000_000 + chat_id
async def download_file(
url: str,
*,
session: typing.Optional[aiohttp.ClientSession] = None,
**kwargs,
) -> bytes:
"""
Скачивание файлов по их прямой ссылке
"""
used_session = session or aiohttp.ClientSession(
connector=aiohttp.TCPConnector(ssl=ssl.SSLContext()),
skip_auto_headers={"User-Agent"},
raise_for_status=True,
json_serialize=json_parser_policy.dumps,
)
async with used_session.get(url, **kwargs) as response:
downloaded_file = await response.read()
if session is None:
await used_session.close()
return downloaded_file
_registration_date_regex = re.compile('ya:created dc:date="(?P<date>.*?)"')
async def get_user_registration_date(
id_: int, *, session: typing.Optional[aiohttp.ClientSession] = None
) -> datetime.datetime:
request_session = session or aiohttp.ClientSession(
connector=aiohttp.TCPConnector(ssl=False),
skip_auto_headers={"User-Agent"},
raise_for_status=True,
json_serialize=json_parser_policy.dumps,
)
async with request_session:
async with request_session.get(
"https://vk.com/foaf.php", params={"id": id_}
) as response:
user_info = await response.text()
registration_date = _registration_date_regex.search(user_info)
if registration_date is None:
raise ValueError(f"No such user with id `{id_}`")
registration_date = registration_date.group("date")
registration_date = datetime.datetime.fromisoformat(
registration_date
)
return registration_date
def get_origin_typing(type):
# If generic
if typing.get_args(type):
return typing.get_origin(type)
return type | 0.521715 | 0.218294 |
__AUTHOR__ = "hugsy"
__VERSION__ = 0.1
import os
import gdb
def fastbin_index(sz):
return (sz >> 4) - 2 if current_arch.ptrsize == 8 else (sz >> 3) - 2
def nfastbins():
return fastbin_index( (80 * current_arch.ptrsize // 4)) - 1
def get_tcache_count():
if get_libc_version() < (2, 27):
return 0
count_addr = HeapBaseFunction.heap_base() + 2*current_arch.ptrsize
count = p8(count_addr) if get_libc_version() < (2, 30) else p16(count_addr)
return count
@lru_cache(128)
def collect_known_values() -> dict:
arena = get_glibc_arena()
result = {} # format is { 0xaddress : "name" ,}
# tcache
if get_libc_version() >= (2, 27):
tcache_addr = GlibcHeapTcachebinsCommand.find_tcache()
for i in range(GlibcHeapTcachebinsCommand.TCACHE_MAX_BINS):
chunk, _ = GlibcHeapTcachebinsCommand.tcachebin(tcache_addr, i)
j = 0
while True:
if chunk is None:
break
result[chunk.data_address] = "tcachebins[{}/{}] (size={:#x})".format(i, j, (i+1)*0x10+0x10)
next_chunk_address = chunk.get_fwd_ptr(True)
if not next_chunk_address: break
next_chunk = GlibcChunk(next_chunk_address)
j += 1
chunk = next_chunk
# fastbins
for i in range(nfastbins()):
chunk = arena.fastbin(i)
j = 0
while True:
if chunk is None:
break
result[chunk.data_address] = "fastbins[{}/{}]".format(i, j)
next_chunk_address = chunk.get_fwd_ptr(True)
if not next_chunk_address: break
next_chunk = GlibcChunk(next_chunk_address)
j += 1
chunk = next_chunk
# other bins
for name in ["unorderedbins", "smallbins", "largebins"]:
fw, bk = arena.bin(i)
if bk==0x00 and fw==0x00: continue
head = GlibcChunk(bk, from_base=True).fwd
if head == fw: continue
chunk = GlibcChunk(head, from_base=True)
j = 0
while True:
if chunk is None: break
result[chunk.data_address] = "{}[{}/{}]".format(name, i, j)
next_chunk_address = chunk.get_fwd_ptr(True)
if not next_chunk_address: break
next_chunk = GlibcChunk(next_chunk_address, from_base=True)
j += 1
chunk = next_chunk
return result
@lru_cache(128)
def collect_known_ranges()->list:
result = []
for entry in get_process_maps():
if not entry.path:
continue
path = os.path.basename(entry.path)
result.append( (range(entry.page_start, entry.page_end), path) )
return result
@register_external_command
class VisualizeHeapChunksCommand(GenericCommand):
"""Visual helper for glibc heap chunks"""
_cmdline_ = "visualize-libc-heap-chunks"
_syntax_ = "{:s}".format(_cmdline_)
_aliases_ = ["heap-view",]
_example_ = "{:s}".format(_cmdline_)
def __init__(self):
super(VisualizeHeapChunksCommand, self).__init__(complete=gdb.COMPLETE_SYMBOL)
return
@only_if_gdb_running
def do_invoke(self, argv):
ptrsize = current_arch.ptrsize
heap_base_address = HeapBaseFunction.heap_base()
arena = get_glibc_arena()
if not arena.top:
err("The heap has not been initialized")
return
top = align_address(int(arena.top))
base = align_address(heap_base_address)
colors = [ "cyan", "red", "yellow", "blue", "green" ]
cur = GlibcChunk(base, from_base=True)
idx = 0
known_ranges = collect_known_ranges()
known_values = collect_known_values()
while True:
base = cur.base_address
aggregate_nuls = 0
if base == top:
gef_print("{} {} {}".format(format_address(addr), format_address(read_int_from_memory(addr)) , Color.colorify(LEFT_ARROW + "Top Chunk", "red bold")))
gef_print("{} {} {}".format(format_address(addr+ptrsize), format_address(read_int_from_memory(addr+ptrsize)) , Color.colorify(LEFT_ARROW + "Top Chunk Size", "red bold")))
break
if cur.size == 0:
warn("incorrect size, heap is corrupted")
break
for off in range(0, cur.size, cur.ptrsize):
addr = base + off
value = read_int_from_memory(addr)
if value == 0:
if off != 0 and off != cur.size - cur.ptrsize:
aggregate_nuls += 1
if aggregate_nuls > 1:
continue
if aggregate_nuls > 2:
gef_print(" ↓")
gef_print(" [...]")
gef_print(" ↓")
aggregate_nuls = 0
text = "".join([chr(b) if 0x20 <= b < 0x7F else "." for b in read_memory(addr, cur.ptrsize)])
line = "{} {}".format(format_address(addr), Color.colorify(format_address(value), colors[idx % len(colors)]))
line+= " {}".format(text)
derefs = dereference_from(addr)
if len(derefs) > 2:
line+= " [{}{}]".format(LEFT_ARROW, derefs[-1])
if off == 0:
line+= " Chunk[{}]".format(idx)
if off == cur.ptrsize:
line+= " {}{}{}{}".format(value&~7, "|NON_MAIN_ARENA" if value&4 else "", "|IS_MMAPED" if value&2 else "", "|PREV_INUSE" if value&1 else "")
# look in mapping
for x in known_ranges:
if value in x[0]:
line+= " (in {})".format(Color.redify(x[1]))
# look in known values
if value in known_values:
line += "{}{}".format(RIGHT_ARROW, Color.cyanify(known_values[value]))
gef_print(line)
next_chunk = cur.get_next_chunk()
if next_chunk is None:
break
next_chunk_addr = Address(value=next_chunk.data_address)
if not next_chunk_addr.valid:
warn("next chunk probably corrupted")
break
cur = next_chunk
idx += 1
return | scripts/visualize_heap.py | __AUTHOR__ = "hugsy"
__VERSION__ = 0.1
import os
import gdb
def fastbin_index(sz):
return (sz >> 4) - 2 if current_arch.ptrsize == 8 else (sz >> 3) - 2
def nfastbins():
return fastbin_index( (80 * current_arch.ptrsize // 4)) - 1
def get_tcache_count():
if get_libc_version() < (2, 27):
return 0
count_addr = HeapBaseFunction.heap_base() + 2*current_arch.ptrsize
count = p8(count_addr) if get_libc_version() < (2, 30) else p16(count_addr)
return count
@lru_cache(128)
def collect_known_values() -> dict:
arena = get_glibc_arena()
result = {} # format is { 0xaddress : "name" ,}
# tcache
if get_libc_version() >= (2, 27):
tcache_addr = GlibcHeapTcachebinsCommand.find_tcache()
for i in range(GlibcHeapTcachebinsCommand.TCACHE_MAX_BINS):
chunk, _ = GlibcHeapTcachebinsCommand.tcachebin(tcache_addr, i)
j = 0
while True:
if chunk is None:
break
result[chunk.data_address] = "tcachebins[{}/{}] (size={:#x})".format(i, j, (i+1)*0x10+0x10)
next_chunk_address = chunk.get_fwd_ptr(True)
if not next_chunk_address: break
next_chunk = GlibcChunk(next_chunk_address)
j += 1
chunk = next_chunk
# fastbins
for i in range(nfastbins()):
chunk = arena.fastbin(i)
j = 0
while True:
if chunk is None:
break
result[chunk.data_address] = "fastbins[{}/{}]".format(i, j)
next_chunk_address = chunk.get_fwd_ptr(True)
if not next_chunk_address: break
next_chunk = GlibcChunk(next_chunk_address)
j += 1
chunk = next_chunk
# other bins
for name in ["unorderedbins", "smallbins", "largebins"]:
fw, bk = arena.bin(i)
if bk==0x00 and fw==0x00: continue
head = GlibcChunk(bk, from_base=True).fwd
if head == fw: continue
chunk = GlibcChunk(head, from_base=True)
j = 0
while True:
if chunk is None: break
result[chunk.data_address] = "{}[{}/{}]".format(name, i, j)
next_chunk_address = chunk.get_fwd_ptr(True)
if not next_chunk_address: break
next_chunk = GlibcChunk(next_chunk_address, from_base=True)
j += 1
chunk = next_chunk
return result
@lru_cache(128)
def collect_known_ranges()->list:
result = []
for entry in get_process_maps():
if not entry.path:
continue
path = os.path.basename(entry.path)
result.append( (range(entry.page_start, entry.page_end), path) )
return result
@register_external_command
class VisualizeHeapChunksCommand(GenericCommand):
"""Visual helper for glibc heap chunks"""
_cmdline_ = "visualize-libc-heap-chunks"
_syntax_ = "{:s}".format(_cmdline_)
_aliases_ = ["heap-view",]
_example_ = "{:s}".format(_cmdline_)
def __init__(self):
super(VisualizeHeapChunksCommand, self).__init__(complete=gdb.COMPLETE_SYMBOL)
return
@only_if_gdb_running
def do_invoke(self, argv):
ptrsize = current_arch.ptrsize
heap_base_address = HeapBaseFunction.heap_base()
arena = get_glibc_arena()
if not arena.top:
err("The heap has not been initialized")
return
top = align_address(int(arena.top))
base = align_address(heap_base_address)
colors = [ "cyan", "red", "yellow", "blue", "green" ]
cur = GlibcChunk(base, from_base=True)
idx = 0
known_ranges = collect_known_ranges()
known_values = collect_known_values()
while True:
base = cur.base_address
aggregate_nuls = 0
if base == top:
gef_print("{} {} {}".format(format_address(addr), format_address(read_int_from_memory(addr)) , Color.colorify(LEFT_ARROW + "Top Chunk", "red bold")))
gef_print("{} {} {}".format(format_address(addr+ptrsize), format_address(read_int_from_memory(addr+ptrsize)) , Color.colorify(LEFT_ARROW + "Top Chunk Size", "red bold")))
break
if cur.size == 0:
warn("incorrect size, heap is corrupted")
break
for off in range(0, cur.size, cur.ptrsize):
addr = base + off
value = read_int_from_memory(addr)
if value == 0:
if off != 0 and off != cur.size - cur.ptrsize:
aggregate_nuls += 1
if aggregate_nuls > 1:
continue
if aggregate_nuls > 2:
gef_print(" ↓")
gef_print(" [...]")
gef_print(" ↓")
aggregate_nuls = 0
text = "".join([chr(b) if 0x20 <= b < 0x7F else "." for b in read_memory(addr, cur.ptrsize)])
line = "{} {}".format(format_address(addr), Color.colorify(format_address(value), colors[idx % len(colors)]))
line+= " {}".format(text)
derefs = dereference_from(addr)
if len(derefs) > 2:
line+= " [{}{}]".format(LEFT_ARROW, derefs[-1])
if off == 0:
line+= " Chunk[{}]".format(idx)
if off == cur.ptrsize:
line+= " {}{}{}{}".format(value&~7, "|NON_MAIN_ARENA" if value&4 else "", "|IS_MMAPED" if value&2 else "", "|PREV_INUSE" if value&1 else "")
# look in mapping
for x in known_ranges:
if value in x[0]:
line+= " (in {})".format(Color.redify(x[1]))
# look in known values
if value in known_values:
line += "{}{}".format(RIGHT_ARROW, Color.cyanify(known_values[value]))
gef_print(line)
next_chunk = cur.get_next_chunk()
if next_chunk is None:
break
next_chunk_addr = Address(value=next_chunk.data_address)
if not next_chunk_addr.valid:
warn("next chunk probably corrupted")
break
cur = next_chunk
idx += 1
return | 0.270769 | 0.173954 |
from unittest import TestCase
from unittest.mock import Mock, call, patch
import os
import sys
sys.path.append(os.path.abspath('./src'))
from pkgs.ui.models.ctrlrModel import CtrlrModel # noqa: E402
class TestCtrlrModel(TestCase):
"""
CtrlrModel test cases.
"""
def setUp(self):
"""
Test cases setup.
"""
self.ctrlr = 'pkgs.ui.models.ctrlrModel.ctrlrModel.Controller'
self.QStdItem = 'pkgs.ui.models.ctrlrModel.ctrlrModel.QStandardItem'
self.QStdItemModel = 'pkgs.ui.models.ctrlrModel.ctrlrModel.QStandardItemModel' # noqa: E501
self.testLogger = Mock()
self.testCtrlrList = {'test controller 1': 0, 'test controller 2': 1,
'test controller 3': 2, 'test controller 4': 3}
self.mockedCtrlrs = self._setUpMockedCtrlrs(self.testCtrlrList)
self.mockedStdItemModel = Mock()
with patch(self.ctrlr) as mockedCtrlr, \
patch.object(mockedCtrlr, 'initFramework'), \
patch.object(CtrlrModel, 'updateCtrlrList'):
self.ctrlrMdl = CtrlrModel(self.testLogger)
self.ctrlrMdl._controllers['active'] = self.mockedCtrlrs[0]
self.ctrlrMdl._controllers['list'] = self.mockedCtrlrs
self.ctrlrMdl.model = self.mockedStdItemModel
def _setUpMockedCtrlrs(self, ctrlrList: dict):
"""
Setup the mocked controllers.
Params:
ctrlrList: The controller list to mock.
"""
mockedCtrlrs = []
for testCtrlr in ctrlrList:
mockedCtrlr = Mock()
mockedCtrlr.getName.return_value = testCtrlr
mockedCtrlr.getIdx.return_value = ctrlrList[testCtrlr]
mockedCtrlrs.append(mockedCtrlr)
return mockedCtrlrs
def test_constructorInitCtrlrs(self):
"""
The constructor must initialize the controller framework,
create the combobox model and update the controller list.
"""
with patch(f"{self.ctrlr}.initFramework") as mockedinitFmk, \
patch(self.QStdItemModel) as mockedQStdItemMdl, \
patch.object(CtrlrModel, 'updateCtrlrList') \
as mockedInitCtrlrs:
CtrlrModel(self.testLogger)
mockedinitFmk.assert_called_once()
mockedQStdItemMdl.assert_called_once_with(0, 1)
mockedInitCtrlrs.assert_called_once()
def test_listCurrentCtrlrs(self):
"""
The _listCurrentCtrlrs method must return the list of
current controller names.
"""
testResult = self.ctrlrMdl._listCurrentCtrlrs()
self.assertEqual(testResult, tuple(self.testCtrlrList.keys()))
def test_filterAddedCtrlrs(self):
"""
The _filterAddedCtrlrs method must return the list of
newly added controllers.
"""
addedCtrlrs = {'new controller 1': 6, 'new controller 2': 7}
newList = {**self.testCtrlrList, **addedCtrlrs}
testResult = self.ctrlrMdl._filterAddedCtrlrs(newList)
self.assertEqual(testResult, tuple(addedCtrlrs.keys()))
def test_filterRemovedCtrlrs(self):
"""
The _filterRemovedCtrlrs method must return the list
of controllers that have been removed.
"""
removedCtrlrs = ('test controller 2', 'test controller 4')
newList = self.testCtrlrList.copy()
for ctrlr in removedCtrlrs:
del newList[ctrlr]
testResult = self.ctrlrMdl._filterRemovedCtrlrs(newList)
self.assertEqual(testResult, removedCtrlrs)
def test_addControllers(self):
"""
The _addControllers method must add the new controllers.
"""
addedCtrlrs = {'new controller 1': 6, 'new controller 2': 7}
newList = {**self.testCtrlrList, **addedCtrlrs}
mockedNewCtrlrs = self._setUpMockedCtrlrs(addedCtrlrs)
with patch(self.ctrlr) as mockedCtrlr:
mockedCtrlr.side_effect = mockedNewCtrlrs
self.ctrlrMdl._addControllers(newList, tuple(addedCtrlrs))
for mockedCtrlr in mockedNewCtrlrs:
self.assertTrue(mockedCtrlr in
self.ctrlrMdl._controllers['list'])
def test_removeControllers(self):
"""
The _removeControllers method must reset the active controller
if it has been removed and remove the old controllers.
"""
first = 0
last = len(self.testCtrlrList) - 1
ctrlrNames = list(self.testCtrlrList.keys())
oldCtrlrs = (ctrlrNames[first], ctrlrNames[last])
expectedCtrlrList = self.ctrlrMdl._controllers['list'].copy()
expectedCtrlrList.remove(self.ctrlrMdl._controllers['list'][first])
expectedCtrlrList.remove(self.ctrlrMdl._controllers['list'][last])
self.ctrlrMdl._removeControllers(oldCtrlrs)
self.assertEqual(self.ctrlrMdl._controllers['active'], None)
self.assertEqual(self.ctrlrMdl._controllers['list'], expectedCtrlrList)
def test_updateModelClear(self):
"""
The _updateModel method must clear the model.
"""
with patch(self.QStdItem):
self.ctrlrMdl._updateModel()
self.mockedStdItemModel.clear.assert_called_once()
def test_updateModelItem(self):
"""
The _updateModel method must create and add items
for each controllers.
"""
mockedItems = []
itemCalls = []
addItemCalls = []
for ctrlr in self.testCtrlrList:
mockedItems.append(ctrlr)
itemCalls.append(call(ctrlr))
addItemCalls.append(call(ctrlr))
with patch(self.QStdItem) as mockedStdItem:
mockedStdItem.side_effect = mockedItems
self.ctrlrMdl._updateModel()
mockedStdItem.assert_has_calls(itemCalls)
self.ctrlrMdl.model.appendRow.assert_has_calls(addItemCalls)
def test_updateCtrlrListListConnected(self):
"""
The updateCtrlrList method must list the currently
connected controllers.
"""
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") \
as mockedListCtrlrs:
mockedListCtrlrs.return_value = {}
self.ctrlrMdl.updateCtrlrList()
mockedListCtrlrs.assert_called_once()
def test_updateCtrlrListFilterAdd(self):
"""
The updateCtrlrList method must filter the
newly added controllers.
"""
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlList, \
patch.object(self.ctrlrMdl, '_filterAddedCtrlrs') \
as mockedFilterAdded:
mockedCtrlList.return_value = self.testCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedFilterAdded. \
assert_called_once_with(tuple(self.testCtrlrList))
def test_updateCtrlrListAddNew(self):
"""
The updateCtrlrList method must add the new controllers.
"""
newCtrlrs = {"new controller 1": 5, "new controller 2": 6}
newCtrlrList = {**self.testCtrlrList, **newCtrlrs}
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlList, \
patch.object(self.ctrlrMdl, '_addControllers') \
as mockedAddCtrlrs:
mockedCtrlList.return_value = newCtrlrList
print(self.ctrlrMdl._controllers['list'])
self.ctrlrMdl.updateCtrlrList()
mockedAddCtrlrs.assert_called_once_with(newCtrlrList,
tuple(newCtrlrs))
def test_updateCtrlrListFilterRemove(self):
"""
The updateCtrlrList method must filter the
removed controllers.
"""
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlrList, \
patch.object(self.ctrlrMdl, '_filterRemovedCtrlrs') \
as mockedFilterRemove:
mockedCtrlrList.return_value = self.testCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedFilterRemove. \
assert_called_once_with(tuple(self.testCtrlrList))
def test_updateCtrlrListRemoveOld(self):
"""
The updateCtrlrList method must remove the old controllers.
"""
ctrlrs2Remove = ['test controller 2', 'test controller 4']
newCtrlrList = self.testCtrlrList.copy()
for ctrlr2Remove in ctrlrs2Remove:
del newCtrlrList[ctrlr2Remove]
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlrList, \
patch.object(self.ctrlrMdl, '_removeControllers') \
as mockedRemoveCtrlr:
mockedCtrlrList.return_value = newCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedRemoveCtrlr.assert_called_once_with(tuple(ctrlrs2Remove))
def test_updateCtrlrListUpdateModel(self):
"""
The updateCtrlrList method must update the selection combobox.
"""
with patch.object(self.ctrlrMdl, '_updateModel') \
as mockedUpdateModel, \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlrList:
mockedCtrlrList.return_value = self.testCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedUpdateModel.assert_called_once() | tests/unit/pkgs/ui/models/ctrlrModel/test_CtrlrModel.py | from unittest import TestCase
from unittest.mock import Mock, call, patch
import os
import sys
sys.path.append(os.path.abspath('./src'))
from pkgs.ui.models.ctrlrModel import CtrlrModel # noqa: E402
class TestCtrlrModel(TestCase):
"""
CtrlrModel test cases.
"""
def setUp(self):
"""
Test cases setup.
"""
self.ctrlr = 'pkgs.ui.models.ctrlrModel.ctrlrModel.Controller'
self.QStdItem = 'pkgs.ui.models.ctrlrModel.ctrlrModel.QStandardItem'
self.QStdItemModel = 'pkgs.ui.models.ctrlrModel.ctrlrModel.QStandardItemModel' # noqa: E501
self.testLogger = Mock()
self.testCtrlrList = {'test controller 1': 0, 'test controller 2': 1,
'test controller 3': 2, 'test controller 4': 3}
self.mockedCtrlrs = self._setUpMockedCtrlrs(self.testCtrlrList)
self.mockedStdItemModel = Mock()
with patch(self.ctrlr) as mockedCtrlr, \
patch.object(mockedCtrlr, 'initFramework'), \
patch.object(CtrlrModel, 'updateCtrlrList'):
self.ctrlrMdl = CtrlrModel(self.testLogger)
self.ctrlrMdl._controllers['active'] = self.mockedCtrlrs[0]
self.ctrlrMdl._controllers['list'] = self.mockedCtrlrs
self.ctrlrMdl.model = self.mockedStdItemModel
def _setUpMockedCtrlrs(self, ctrlrList: dict):
"""
Setup the mocked controllers.
Params:
ctrlrList: The controller list to mock.
"""
mockedCtrlrs = []
for testCtrlr in ctrlrList:
mockedCtrlr = Mock()
mockedCtrlr.getName.return_value = testCtrlr
mockedCtrlr.getIdx.return_value = ctrlrList[testCtrlr]
mockedCtrlrs.append(mockedCtrlr)
return mockedCtrlrs
def test_constructorInitCtrlrs(self):
"""
The constructor must initialize the controller framework,
create the combobox model and update the controller list.
"""
with patch(f"{self.ctrlr}.initFramework") as mockedinitFmk, \
patch(self.QStdItemModel) as mockedQStdItemMdl, \
patch.object(CtrlrModel, 'updateCtrlrList') \
as mockedInitCtrlrs:
CtrlrModel(self.testLogger)
mockedinitFmk.assert_called_once()
mockedQStdItemMdl.assert_called_once_with(0, 1)
mockedInitCtrlrs.assert_called_once()
def test_listCurrentCtrlrs(self):
"""
The _listCurrentCtrlrs method must return the list of
current controller names.
"""
testResult = self.ctrlrMdl._listCurrentCtrlrs()
self.assertEqual(testResult, tuple(self.testCtrlrList.keys()))
def test_filterAddedCtrlrs(self):
"""
The _filterAddedCtrlrs method must return the list of
newly added controllers.
"""
addedCtrlrs = {'new controller 1': 6, 'new controller 2': 7}
newList = {**self.testCtrlrList, **addedCtrlrs}
testResult = self.ctrlrMdl._filterAddedCtrlrs(newList)
self.assertEqual(testResult, tuple(addedCtrlrs.keys()))
def test_filterRemovedCtrlrs(self):
"""
The _filterRemovedCtrlrs method must return the list
of controllers that have been removed.
"""
removedCtrlrs = ('test controller 2', 'test controller 4')
newList = self.testCtrlrList.copy()
for ctrlr in removedCtrlrs:
del newList[ctrlr]
testResult = self.ctrlrMdl._filterRemovedCtrlrs(newList)
self.assertEqual(testResult, removedCtrlrs)
def test_addControllers(self):
"""
The _addControllers method must add the new controllers.
"""
addedCtrlrs = {'new controller 1': 6, 'new controller 2': 7}
newList = {**self.testCtrlrList, **addedCtrlrs}
mockedNewCtrlrs = self._setUpMockedCtrlrs(addedCtrlrs)
with patch(self.ctrlr) as mockedCtrlr:
mockedCtrlr.side_effect = mockedNewCtrlrs
self.ctrlrMdl._addControllers(newList, tuple(addedCtrlrs))
for mockedCtrlr in mockedNewCtrlrs:
self.assertTrue(mockedCtrlr in
self.ctrlrMdl._controllers['list'])
def test_removeControllers(self):
"""
The _removeControllers method must reset the active controller
if it has been removed and remove the old controllers.
"""
first = 0
last = len(self.testCtrlrList) - 1
ctrlrNames = list(self.testCtrlrList.keys())
oldCtrlrs = (ctrlrNames[first], ctrlrNames[last])
expectedCtrlrList = self.ctrlrMdl._controllers['list'].copy()
expectedCtrlrList.remove(self.ctrlrMdl._controllers['list'][first])
expectedCtrlrList.remove(self.ctrlrMdl._controllers['list'][last])
self.ctrlrMdl._removeControllers(oldCtrlrs)
self.assertEqual(self.ctrlrMdl._controllers['active'], None)
self.assertEqual(self.ctrlrMdl._controllers['list'], expectedCtrlrList)
def test_updateModelClear(self):
"""
The _updateModel method must clear the model.
"""
with patch(self.QStdItem):
self.ctrlrMdl._updateModel()
self.mockedStdItemModel.clear.assert_called_once()
def test_updateModelItem(self):
"""
The _updateModel method must create and add items
for each controllers.
"""
mockedItems = []
itemCalls = []
addItemCalls = []
for ctrlr in self.testCtrlrList:
mockedItems.append(ctrlr)
itemCalls.append(call(ctrlr))
addItemCalls.append(call(ctrlr))
with patch(self.QStdItem) as mockedStdItem:
mockedStdItem.side_effect = mockedItems
self.ctrlrMdl._updateModel()
mockedStdItem.assert_has_calls(itemCalls)
self.ctrlrMdl.model.appendRow.assert_has_calls(addItemCalls)
def test_updateCtrlrListListConnected(self):
"""
The updateCtrlrList method must list the currently
connected controllers.
"""
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") \
as mockedListCtrlrs:
mockedListCtrlrs.return_value = {}
self.ctrlrMdl.updateCtrlrList()
mockedListCtrlrs.assert_called_once()
def test_updateCtrlrListFilterAdd(self):
"""
The updateCtrlrList method must filter the
newly added controllers.
"""
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlList, \
patch.object(self.ctrlrMdl, '_filterAddedCtrlrs') \
as mockedFilterAdded:
mockedCtrlList.return_value = self.testCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedFilterAdded. \
assert_called_once_with(tuple(self.testCtrlrList))
def test_updateCtrlrListAddNew(self):
"""
The updateCtrlrList method must add the new controllers.
"""
newCtrlrs = {"new controller 1": 5, "new controller 2": 6}
newCtrlrList = {**self.testCtrlrList, **newCtrlrs}
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlList, \
patch.object(self.ctrlrMdl, '_addControllers') \
as mockedAddCtrlrs:
mockedCtrlList.return_value = newCtrlrList
print(self.ctrlrMdl._controllers['list'])
self.ctrlrMdl.updateCtrlrList()
mockedAddCtrlrs.assert_called_once_with(newCtrlrList,
tuple(newCtrlrs))
def test_updateCtrlrListFilterRemove(self):
"""
The updateCtrlrList method must filter the
removed controllers.
"""
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlrList, \
patch.object(self.ctrlrMdl, '_filterRemovedCtrlrs') \
as mockedFilterRemove:
mockedCtrlrList.return_value = self.testCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedFilterRemove. \
assert_called_once_with(tuple(self.testCtrlrList))
def test_updateCtrlrListRemoveOld(self):
"""
The updateCtrlrList method must remove the old controllers.
"""
ctrlrs2Remove = ['test controller 2', 'test controller 4']
newCtrlrList = self.testCtrlrList.copy()
for ctrlr2Remove in ctrlrs2Remove:
del newCtrlrList[ctrlr2Remove]
with patch.object(self.ctrlrMdl, '_updateModel'), \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlrList, \
patch.object(self.ctrlrMdl, '_removeControllers') \
as mockedRemoveCtrlr:
mockedCtrlrList.return_value = newCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedRemoveCtrlr.assert_called_once_with(tuple(ctrlrs2Remove))
def test_updateCtrlrListUpdateModel(self):
"""
The updateCtrlrList method must update the selection combobox.
"""
with patch.object(self.ctrlrMdl, '_updateModel') \
as mockedUpdateModel, \
patch(f"{self.ctrlr}.listControllers") as mockedCtrlrList:
mockedCtrlrList.return_value = self.testCtrlrList
self.ctrlrMdl.updateCtrlrList()
mockedUpdateModel.assert_called_once() | 0.490968 | 0.326191 |
import unittest
import time
from app import create_app,db
from app.models import User,AnonymousUser,Role,Permission
class UserModelTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
Role.insert_roles()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_password_setter(self):
u = User(password='<PASSWORD>')
self.assertTrue(u.password_hash is not None)
def test_no_password_getter(self):
u = User(password='<PASSWORD>')
with self.assertRaises(AttributeError):
u.password
def test_password_verification(self):
u = User(password='<PASSWORD>')
self.assertTrue(u.verify_password('<PASSWORD>'))
self.assertFalse(u.verify_password('<PASSWORD>'))
def test_password_salts_are_random(self):
u = User(password='<PASSWORD>')
u2 = User(password='<PASSWORD>')
self.assertTrue(u.password_hash != u2.password_hash)
def test_user_role(self):
u = User(email='<EMAIL>', password='<PASSWORD>')
self.assertTrue(u.can(Permission.FOLLOW))
self.assertTrue(u.can(Permission.COMMENT))
self.assertTrue(u.can(Permission.WRITE))
self.assertFalse(u.can(Permission.MODERATE))
self.assertFalse(u.can(Permission.ADMINISTER))
def test_moderator_role(self):
r = Role.query.filter_by(name='Moderator').first()
u = User(email='<EMAIL>', password='<PASSWORD>', role=r)
self.assertTrue(u.can(Permission.FOLLOW))
self.assertTrue(u.can(Permission.COMMENT))
self.assertTrue(u.can(Permission.WRITE))
self.assertTrue(u.can(Permission.MODERATE))
self.assertFalse(u.can(Permission.ADMINISTER))
def test_administrator_role(self):
r = Role.query.filter_by(name='Administrator').first()
u = User(email='<EMAIL>', password='<PASSWORD>', role=r)
self.assertTrue(u.can(Permission.FOLLOW))
self.assertTrue(u.can(Permission.COMMENT))
self.assertTrue(u.can(Permission.WRITE))
self.assertTrue(u.can(Permission.MODERATE))
self.assertTrue(u.can(Permission.ADMINISTER))
def test_anonymous_user(self):
u = AnonymousUser()
self.assertFalse(u.can(Permission.FOLLOW))
self.assertFalse(u.can(Permission.COMMENT))
self.assertFalse(u.can(Permission.WRITE))
self.assertFalse(u.can(Permission.MODERATE))
self.assertFalse(u.can(Permission.ADMINISTER)) | tests/test_user_model.py | import unittest
import time
from app import create_app,db
from app.models import User,AnonymousUser,Role,Permission
class UserModelTestCase(unittest.TestCase):
def setUp(self):
self.app = create_app('testing')
self.app_context = self.app.app_context()
self.app_context.push()
db.create_all()
Role.insert_roles()
def tearDown(self):
db.session.remove()
db.drop_all()
self.app_context.pop()
def test_password_setter(self):
u = User(password='<PASSWORD>')
self.assertTrue(u.password_hash is not None)
def test_no_password_getter(self):
u = User(password='<PASSWORD>')
with self.assertRaises(AttributeError):
u.password
def test_password_verification(self):
u = User(password='<PASSWORD>')
self.assertTrue(u.verify_password('<PASSWORD>'))
self.assertFalse(u.verify_password('<PASSWORD>'))
def test_password_salts_are_random(self):
u = User(password='<PASSWORD>')
u2 = User(password='<PASSWORD>')
self.assertTrue(u.password_hash != u2.password_hash)
def test_user_role(self):
u = User(email='<EMAIL>', password='<PASSWORD>')
self.assertTrue(u.can(Permission.FOLLOW))
self.assertTrue(u.can(Permission.COMMENT))
self.assertTrue(u.can(Permission.WRITE))
self.assertFalse(u.can(Permission.MODERATE))
self.assertFalse(u.can(Permission.ADMINISTER))
def test_moderator_role(self):
r = Role.query.filter_by(name='Moderator').first()
u = User(email='<EMAIL>', password='<PASSWORD>', role=r)
self.assertTrue(u.can(Permission.FOLLOW))
self.assertTrue(u.can(Permission.COMMENT))
self.assertTrue(u.can(Permission.WRITE))
self.assertTrue(u.can(Permission.MODERATE))
self.assertFalse(u.can(Permission.ADMINISTER))
def test_administrator_role(self):
r = Role.query.filter_by(name='Administrator').first()
u = User(email='<EMAIL>', password='<PASSWORD>', role=r)
self.assertTrue(u.can(Permission.FOLLOW))
self.assertTrue(u.can(Permission.COMMENT))
self.assertTrue(u.can(Permission.WRITE))
self.assertTrue(u.can(Permission.MODERATE))
self.assertTrue(u.can(Permission.ADMINISTER))
def test_anonymous_user(self):
u = AnonymousUser()
self.assertFalse(u.can(Permission.FOLLOW))
self.assertFalse(u.can(Permission.COMMENT))
self.assertFalse(u.can(Permission.WRITE))
self.assertFalse(u.can(Permission.MODERATE))
self.assertFalse(u.can(Permission.ADMINISTER)) | 0.325199 | 0.270112 |
import json
from . import db
import pandas as pd
from datetime import datetime
from geoalchemy2 import functions
from geoalchemy2.types import Geometry
from flask import current_app, request, url_for
from .errors import AlreadyExistsError
class BaseExtension(db.MapperExtension):
"""Base extension for all entities."""
def before_insert(self, mapper, connection, instance):
instance.created_on = datetime.now()
def before_update(self, mapper, connection, instance):
instance.updated_on = datetime.now()
class BaseEntity(object):
__mapper_args__ = {"extension": BaseExtension()}
created_on = db.Column(db.DateTime)
updated_on = db.Column(db.DateTime)
class Facility(db.Model, BaseEntity):
__tablename__ = "facility"
facility_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
type = db.Column(db.Text)
address = db.Column(db.Text)
city = db.Column(db.Text)
state = db.Column(db.CHAR(2))
zipcode = db.Column(db.String)
longitude = db.Column(db.Float, nullable=True)
latitude = db.Column(db.Float, nullable=True)
geometry = db.Column(Geometry(geometry_type="POINT", srid=4326))
storage_tank = db.relationship("StorageTank", back_populates="facility")
waste_unit = db.relationship("WasteUnit", back_populates="facility")
def __repr__(self):
return f"Facility('{self.facility_id}','{self.name}', '{self.address}', '{self.city}','{self.state}', '{self.zipcode}')"
@classmethod
def add_facility(cls, name, address, city, state, zipcode, longitude, latitude):
"""Add a new facility in the database."""
geometry = "POINT({} {})".format(longitude, latitude)
facility = Facility(
name=name,
address=address,
city=city,
state=state,
zipcode=zipcode,
longitude=longitude,
latitude=latitude,
geometry=geometry,
)
db.session.add(facility)
db.session.commit()
@classmethod
def update_geometries(cls):
"""Using each facility's longitude and latitude, add geometry data to db."""
facilities = Facility.query.all()
for facility in facilities:
point = "POINT({} {})".format(facility.longitude, facility.latitude)
facility.geometry = point
db.session.commit()
def to_json(self):
json_facility = {
"url": url_for("api.get_facility", facility_id=self.facility_id),
"name": self.name,
"address": self.address,
"city": self.city,
"state": self.state,
"zipcode": self.zipcode,
"longitude": self.longitude,
"latitude": self.latitude,
}
return json_facility
@staticmethod
def from_json(json_facility):
name = json_facility.get("name")
address = json_facility.get("address")
city = json_facility.get("city")
state = json_facility.get("state")
zipcode = json_facility.get("zipcode")
longitude = json_facility.get("longitude")
latitude = json_facility.get("latitude")
if name is None or name == "":
raise ValidationError("Facility must have a name")
return Facility(
name=name,
address=address,
city=city,
state=state,
zipcode=zipcode,
longitude=longitude,
latitude=latitude,
created_on=datetime.utcnow()
# geometry = "POINT({} {})".format(longitude, latitude)
)
class WasteUnit(db.Model, BaseEntity):
__tablename__ = "waste_unit"
__table_args__ = (db.UniqueConstraint("name", "facility_id"),)
unit_id = db.Column(db.Integer, primary_key=True)
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
name = db.Column(db.String(64), nullable=False)
constructed_date = db.Column(db.Date)
geometry = db.Column(Geometry(geometry_type="POLYGON", srid=4326))
unit_type = db.Column(db.String(12), nullable=False)
facility = db.relationship("Facility", back_populates="waste_unit")
__mapper_args__ = {
"polymorphic_identity": "waste_unit",
"polymorphic_on": unit_type,
}
def __repr__(self):
return f"WasteUnit('{self.name}')"
def to_json(self):
json_waste_unit = {
"url": url_for("api.get_waste_unit", unit_id=self.unit_id),
"name": self.name,
"constructed_date": self.constructed_date,
"unit_type": self.unit_type,
}
return json_waste_unit
class Landfill(WasteUnit, BaseEntity):
__tablename__ = "landfill"
permit_id = db.Column(db.String(24))
__mapper_args__ = {"polymorphic_identity": "landfill"}
def __repr__(self):
return f"Landfill('{self.name}')"
def to_json(self):
json_landfill = {
"url": url_for("api.get_landfill", unit_id=self.unit_id),
"name": self.name,
}
return json_landfill
class Impoundment(WasteUnit, BaseEntity):
__tablename__ = "impoundment"
dam_id = db.Column(db.String(24))
hazard_class = db.Column(db.Text)
__mapper_args__ = {"polymorphic_identity": "impoundment"}
def __repr__(self):
return f"Impoundment('{self.dam_id}', '{self.name}', '{self.hazard_class}')"
def to_json(self):
json_impoundment = {
"url": url_for("api.get_impoundment", unit_id=self.unit_id),
"name": self.name,
}
return json_impoundment
class StorageTank(db.Model, BaseEntity):
"""Base class for UndergroundStorageTank and AbovegroundStorageTank classes using Joined Table Inheritance. When StorageTank is queried only columns in this class are returned."""
__tablename__ = "storage_tank"
__table_args__ = (db.UniqueConstraint("tank_registration_id", "facility_id"),)
tank_id = db.Column(db.Integer, primary_key=True)
tank_registration_id = db.Column(db.String(12))
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
date_installed = db.Column(db.Date)
date_removed = db.Column(db.Date)
capacity = db.Column(db.Integer)
stored_substance = db.Column(db.String(64))
status = db.Column(db.String(10))
longitude = db.Column(db.Float)
latitude = db.Column(db.Float)
geometry = db.Column(Geometry(geometry_type="POINT", srid=4326))
tank_type = db.Column(db.String(3), nullable=False)
facility = db.relationship("Facility", back_populates="storage_tank")
__mapper_args__ = {
"polymorphic_identity": "storage_tank",
"polymorphic_on": tank_type,
}
def __repr__(self):
return f"StorageTank('{self.tank_id}', '{self.tank_type}', '{self.stored_substance}', '{self.status}')"
def to_json(self):
json_storage_tank = {
"url": url_for("api.get_storage_tank", tank_id=self.tank_id),
"facility": self.facility.name,
"tank_registration_id": self.tank_registration_id,
"capacity": self.capacity,
"stored_substance": self.stored_substance,
"status": self.status,
"tank_type": self.tank_type,
"longitude": self.longitude,
"latitude": self.latitude,
}
return json_storage_tank
@staticmethod
def from_json(json_storage_tank):
facility_id = json_storage_tank.get("facility_id")
tank_registration_id = json_storage_tank.get("tank_registration_id")
capacity = json_storage_tank.get("capacity")
stored_substance = json_storage_tank.get("stored_substance")
status = json_storage_tank.get("status")
tank_type = json_storage_tank.get("tank_type")
longitude = json_storage_tank.get("longitude")
latitude = json_storage_tank.get("latitude")
if facility_id is None or facility_id == "":
raise ValidationError("Tank must be associated with a Facility")
return StorageTank(
facility_id=facility_id,
tank_registration_id=tank_registration_id,
capacity=capacity,
stored_substance=stored_substance,
status=status,
tank_type=tank_type,
longitude=longitude,
latitude=latitude,
created_on=datetime.utcnow()
# geometry = "POINT({} {})".format(longitude, latitude)
)
class UndergroundStorageTank(StorageTank, BaseEntity):
"""Subclass to StorageTank with Joined Table Inheritance. When UndergroundStorageTank is queried all columns from StorageTank are inherited."""
__tablename__ = "ust"
__mapper_args__ = {"polymorphic_identity": "ust"}
tank_double_wall = db.Column(db.Boolean)
inner_tank_material = db.Column(db.Text)
outer_tank_material = db.Column(db.Text)
tank_leak_detection = db.Column(db.Text)
tank_corrosion_protection = db.Column(db.Text)
tank_monitoring_system = db.Column(db.Text)
piping_double_wall = db.Column(db.Boolean)
piping_type = db.Column(db.Text) # Pressurized or suction
inner_pipe_material = db.Column(db.Text)
outer_pipe_material = db.Column(db.Text)
piping_corrosion_protection = db.Column(db.Text)
spill_protection = db.Column(db.Text)
overflow_protection = db.Column(db.Text)
def __repr__(self):
return f"UndergroundStorageTank('{self.tank_id}', '{self.tank_type}', '{self.stored_substance}', '{self.status}')"
def to_json(self):
json_ust = {
"url": url_for("api.get_ust", tank_id=self.tank_id),
"capacity": self.capacity,
"stored_substance": self.stored_substance,
}
return json_ust
class AbovegroundStorageTank(StorageTank, BaseEntity):
"""Subclass to StorageTank with Joined Table Inheritance. When AbovegroundStorageTank is queried all columns from StorageTank are inherited."""
__tablename__ = "ast"
__mapper_args__ = {"polymorphic_identity": "ast"}
def __repr__(self):
return f"AbovegroundStorageTank('{self.tank_id}', '{self.tank_type}', '{self.stored_substance}', '{self.status}')"
def to_json(self):
json_ast = {
"url": url_for("api.get_ast", tank_id=self.tank_id),
"capacity": self.capacity,
"stored_substance": self.stored_substance,
}
return json_ast
class MediumCode(db.Model, BaseEntity):
__tablename__ = "medium_code"
medium_cd = db.Column(db.String(3), primary_key=True)
medium_name = db.Column(db.String(64))
medium_description = db.Column(db.Text)
legacy_cd = db.Column(db.CHAR(1))
def __init__(self, **kwargs):
super(MediumCode, self).__init__(**kwargs)
def _insert_medium_codes():
"""Inserts USGS Medium Codes. If the codes have already been entered, an error is thrown."""
if MediumCode.query.first():
raise AlreadyExistsError("Medium Codes have already been entered.")
else:
url = "https://help.waterdata.usgs.gov/medium_cd"
df = pd.read_html(url, header=0, converters={0: str})[0]
df.rename(
index=str,
columns={
"Medium Code": "medium_cd",
"Medium Name": "medium_name",
"Medium Description": "medium_description",
"Medium Legacy Code": "legacy_cd",
},
inplace=True,
)
df.to_sql("medium_code", con=db.engine, if_exists="append", index=False)
class SampleParameter(db.Model, BaseEntity):
__tablename__ = "sample_parameter"
__table_args__ = (
db.CheckConstraint(
"param_cd ~ similar_escape('[[:digit:]]{5}'::text, NULL::text)"
),
)
param_cd = db.Column(db.CHAR(5), primary_key=True)
group_name = db.Column(db.Text)
description = db.Column(db.Text)
epa_equivalence = db.Column(db.Text)
statistical_basis = db.Column(db.Text)
time_basis = db.Column(db.Text)
weight_basis = db.Column(db.Text)
particle_size_basis = db.Column(db.Text)
sample_fraction = db.Column(db.Text)
temperature_basis = db.Column(db.Text)
casrn = db.Column(db.Text)
srsname = db.Column(db.Text)
parameter_unit = db.Column(db.Text)
def __init__(self, **kwargs):
super(SampleParameter, self).__init__(**kwargs)
def _insert_param_codes():
"""Inserts USGS Parameter Codes. If the codes have already been entered, an error is thrown."""
if SampleParameter.query.first():
raise AlreadyExistsError("Parameter Codes have already been entered.")
else:
url = "https://help.waterdata.usgs.gov/parameter_cd?group_cd=%"
df = pd.read_html(url, header=0, converters={0: str})[0]
df.rename(
index=str,
columns={
"Parameter Code": "param_cd",
"Group Name": "group_name",
"Parameter Name/Description": "description",
"Epa equivalence": "epa_equivalence",
"Result Statistical Basis": "statistical_basis",
"Result Time Basis": "time_basis",
"Result Weight Basis": "weight_basis",
"Result Particle Size Basis": "particle_size_basis",
"Result Sample Fraction": "sample_fraction",
"Result Temperature Basis": "temperature_basis",
"CASRN": "casrn",
"SRSName": "srsname",
"Parameter Unit": "parameter_unit",
},
inplace=True,
)
df.to_sql(
"sample_parameter", con=db.engine, if_exists="append", index=False
)
class SampleId(db.Model, BaseEntity):
__tablename__ = "sample_id"
__table_args__ = (db.UniqueConstraint("sample_id", "facility_id"),)
sample_id = db.Column(db.Integer, primary_key=True)
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
sample_name = db.Column(db.Text)
description = db.Column(db.Text)
longitude = db.Column(db.Float, nullable=True)
latitude = db.Column(db.Float, nullable=True)
geometry = db.Column(Geometry(geometry_type="POINT", srid=4326))
sample_type = db.Column(db.String(24))
facility = db.relationship("Facility")
__mapper_args__ = {
"polymorphic_identity": "sample_id",
"polymorphic_on": sample_type,
}
def __repr__(self):
return f"SampleId('{self.sample_id}', '{self.facility.name}', '{self.sample_type}')"
def to_json(self):
json_sample_location = {
"url": url_for("api.get_sample_id", sample_id_id=self.sample_id),
"facility": self.facility.name,
"sample_id": self.sample_id,
"sample_type": self.sample_type,
}
return json_sample_id
@staticmethod
def from_json(json_sample_location):
facility = json_sample_location.get("facility.name")
sample_id = json_sample_location.get("sample_id")
sample_type = json_sample_location.get("sample_type")
if location_id is None or location_id == "":
raise ValidationError("Sample does not have an ID")
return SampleId(sample_id=sample_id, sample_type=sample_type)
class Boring(db.Model, BaseEntity):
__tablename__ = "boring"
boring_id = db.Column(db.Text, primary_key=True)
start_date = db.Column(db.Date)
end_date = db.Column(db.Date)
class Well(SampleId, BaseEntity):
__tablename__ = "well"
__mapper_args__ = {"polymorphic_identity": "monitoring_well"}
well_id = db.Column(db.Text)
boring_id = db.Column(db.Text, db.ForeignKey("boring.boring_id"))
well_type = db.Column(db.String(10))
installation_date = db.Column(db.Date)
abandoned_date = db.Column(db.Date)
top_riser = db.Column(db.Float)
top_bent_seal = db.Column(db.Float)
top_gravel_pack = db.Column(db.Float)
top_screen = db.Column(db.Float)
bottom_screen = db.Column(db.Float)
bottom_well = db.Column(db.Float)
bottom_gravel_pack = db.Column(db.Float)
bottom_boring = db.Column(db.Float)
grout_seal_desc = db.Column(db.Text)
bent_seal_desc = db.Column(db.Text)
screen_type = db.Column(db.Text)
gravel_pack_desc = db.Column(db.Text)
riser_pipe_desc = db.Column(db.Text)
spacer_depths = db.Column(db.Text)
notes = db.Column(db.Text)
boring = db.relationship("Boring")
def __repr__(self):
return f"MonitoringWell('{self.well_id}')"
def to_json(self):
json_monitoring_well = {
"url": url_for("api.get_monitoring_well", well_id=self.well_id),
"top_screen": self.top_screen,
"bottom_screen": self.bottom_screen,
}
return json_monitoring_well
class SampleResult(db.Model, BaseEntity):
__tablename__ = "sample_result"
__table_args__ = (
db.UniqueConstraint(
"lab_id", "sample_id", "sample_date", "param_cd", "analysis_result"
),
db.CheckConstraint(
"param_cd ~ similar_escape('[[:digit:]]{5}'::text, NULL::text)"
),
)
result_id = db.Column(db.Integer, primary_key=True)
lab_id = db.Column(db.Text)
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
sample_id = db.Column(db.Integer, db.ForeignKey("sample_id.sample_id"))
param_cd = db.Column(db.CHAR(5), db.ForeignKey("sample_parameter.param_cd"))
medium_cd = db.Column(db.String(3), db.ForeignKey("medium_code.medium_cd"))
sample_date = db.Column(db.Date, nullable=False)
sample_time = db.Column(db.Time, nullable=True)
prep_method = db.Column(db.Text)
analysis_method = db.Column(db.Text, nullable=True)
analysis_flag = db.Column(db.CHAR(1), nullable=True)
analysis_result = db.Column(db.Float, nullable=True)
analysis_unit = db.Column(db.Text, nullable=False)
detection_limit = db.Column(db.Float)
reporting_limit = db.Column(db.Float)
analysis_qualifier = db.Column(db.CHAR(1))
disclaimer = db.Column(db.Text)
analysis_date = db.Column(db.DateTime)
order_comment = db.Column(db.Text)
analysis_comment = db.Column(db.Text)
sample = db.relationship("SampleId")
medium_code = db.relationship("MediumCode")
sample_parameter = db.relationship("SampleParameter")
facility = db.relationship("Facility")
def __repr__(self):
return f"SampleResult('{self.result_id}')"
def to_json(self):
json_sample_result = {
"url": url_for("api.get_sample_result", result_id=self.result_id),
"lab_id": self.lab_id,
}
return json_sample_result | app/models.py | import json
from . import db
import pandas as pd
from datetime import datetime
from geoalchemy2 import functions
from geoalchemy2.types import Geometry
from flask import current_app, request, url_for
from .errors import AlreadyExistsError
class BaseExtension(db.MapperExtension):
"""Base extension for all entities."""
def before_insert(self, mapper, connection, instance):
instance.created_on = datetime.now()
def before_update(self, mapper, connection, instance):
instance.updated_on = datetime.now()
class BaseEntity(object):
__mapper_args__ = {"extension": BaseExtension()}
created_on = db.Column(db.DateTime)
updated_on = db.Column(db.DateTime)
class Facility(db.Model, BaseEntity):
__tablename__ = "facility"
facility_id = db.Column(db.Integer, primary_key=True)
name = db.Column(db.Text, nullable=False, unique=True)
type = db.Column(db.Text)
address = db.Column(db.Text)
city = db.Column(db.Text)
state = db.Column(db.CHAR(2))
zipcode = db.Column(db.String)
longitude = db.Column(db.Float, nullable=True)
latitude = db.Column(db.Float, nullable=True)
geometry = db.Column(Geometry(geometry_type="POINT", srid=4326))
storage_tank = db.relationship("StorageTank", back_populates="facility")
waste_unit = db.relationship("WasteUnit", back_populates="facility")
def __repr__(self):
return f"Facility('{self.facility_id}','{self.name}', '{self.address}', '{self.city}','{self.state}', '{self.zipcode}')"
@classmethod
def add_facility(cls, name, address, city, state, zipcode, longitude, latitude):
"""Add a new facility in the database."""
geometry = "POINT({} {})".format(longitude, latitude)
facility = Facility(
name=name,
address=address,
city=city,
state=state,
zipcode=zipcode,
longitude=longitude,
latitude=latitude,
geometry=geometry,
)
db.session.add(facility)
db.session.commit()
@classmethod
def update_geometries(cls):
"""Using each facility's longitude and latitude, add geometry data to db."""
facilities = Facility.query.all()
for facility in facilities:
point = "POINT({} {})".format(facility.longitude, facility.latitude)
facility.geometry = point
db.session.commit()
def to_json(self):
json_facility = {
"url": url_for("api.get_facility", facility_id=self.facility_id),
"name": self.name,
"address": self.address,
"city": self.city,
"state": self.state,
"zipcode": self.zipcode,
"longitude": self.longitude,
"latitude": self.latitude,
}
return json_facility
@staticmethod
def from_json(json_facility):
name = json_facility.get("name")
address = json_facility.get("address")
city = json_facility.get("city")
state = json_facility.get("state")
zipcode = json_facility.get("zipcode")
longitude = json_facility.get("longitude")
latitude = json_facility.get("latitude")
if name is None or name == "":
raise ValidationError("Facility must have a name")
return Facility(
name=name,
address=address,
city=city,
state=state,
zipcode=zipcode,
longitude=longitude,
latitude=latitude,
created_on=datetime.utcnow()
# geometry = "POINT({} {})".format(longitude, latitude)
)
class WasteUnit(db.Model, BaseEntity):
__tablename__ = "waste_unit"
__table_args__ = (db.UniqueConstraint("name", "facility_id"),)
unit_id = db.Column(db.Integer, primary_key=True)
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
name = db.Column(db.String(64), nullable=False)
constructed_date = db.Column(db.Date)
geometry = db.Column(Geometry(geometry_type="POLYGON", srid=4326))
unit_type = db.Column(db.String(12), nullable=False)
facility = db.relationship("Facility", back_populates="waste_unit")
__mapper_args__ = {
"polymorphic_identity": "waste_unit",
"polymorphic_on": unit_type,
}
def __repr__(self):
return f"WasteUnit('{self.name}')"
def to_json(self):
json_waste_unit = {
"url": url_for("api.get_waste_unit", unit_id=self.unit_id),
"name": self.name,
"constructed_date": self.constructed_date,
"unit_type": self.unit_type,
}
return json_waste_unit
class Landfill(WasteUnit, BaseEntity):
__tablename__ = "landfill"
permit_id = db.Column(db.String(24))
__mapper_args__ = {"polymorphic_identity": "landfill"}
def __repr__(self):
return f"Landfill('{self.name}')"
def to_json(self):
json_landfill = {
"url": url_for("api.get_landfill", unit_id=self.unit_id),
"name": self.name,
}
return json_landfill
class Impoundment(WasteUnit, BaseEntity):
__tablename__ = "impoundment"
dam_id = db.Column(db.String(24))
hazard_class = db.Column(db.Text)
__mapper_args__ = {"polymorphic_identity": "impoundment"}
def __repr__(self):
return f"Impoundment('{self.dam_id}', '{self.name}', '{self.hazard_class}')"
def to_json(self):
json_impoundment = {
"url": url_for("api.get_impoundment", unit_id=self.unit_id),
"name": self.name,
}
return json_impoundment
class StorageTank(db.Model, BaseEntity):
"""Base class for UndergroundStorageTank and AbovegroundStorageTank classes using Joined Table Inheritance. When StorageTank is queried only columns in this class are returned."""
__tablename__ = "storage_tank"
__table_args__ = (db.UniqueConstraint("tank_registration_id", "facility_id"),)
tank_id = db.Column(db.Integer, primary_key=True)
tank_registration_id = db.Column(db.String(12))
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
date_installed = db.Column(db.Date)
date_removed = db.Column(db.Date)
capacity = db.Column(db.Integer)
stored_substance = db.Column(db.String(64))
status = db.Column(db.String(10))
longitude = db.Column(db.Float)
latitude = db.Column(db.Float)
geometry = db.Column(Geometry(geometry_type="POINT", srid=4326))
tank_type = db.Column(db.String(3), nullable=False)
facility = db.relationship("Facility", back_populates="storage_tank")
__mapper_args__ = {
"polymorphic_identity": "storage_tank",
"polymorphic_on": tank_type,
}
def __repr__(self):
return f"StorageTank('{self.tank_id}', '{self.tank_type}', '{self.stored_substance}', '{self.status}')"
def to_json(self):
json_storage_tank = {
"url": url_for("api.get_storage_tank", tank_id=self.tank_id),
"facility": self.facility.name,
"tank_registration_id": self.tank_registration_id,
"capacity": self.capacity,
"stored_substance": self.stored_substance,
"status": self.status,
"tank_type": self.tank_type,
"longitude": self.longitude,
"latitude": self.latitude,
}
return json_storage_tank
@staticmethod
def from_json(json_storage_tank):
facility_id = json_storage_tank.get("facility_id")
tank_registration_id = json_storage_tank.get("tank_registration_id")
capacity = json_storage_tank.get("capacity")
stored_substance = json_storage_tank.get("stored_substance")
status = json_storage_tank.get("status")
tank_type = json_storage_tank.get("tank_type")
longitude = json_storage_tank.get("longitude")
latitude = json_storage_tank.get("latitude")
if facility_id is None or facility_id == "":
raise ValidationError("Tank must be associated with a Facility")
return StorageTank(
facility_id=facility_id,
tank_registration_id=tank_registration_id,
capacity=capacity,
stored_substance=stored_substance,
status=status,
tank_type=tank_type,
longitude=longitude,
latitude=latitude,
created_on=datetime.utcnow()
# geometry = "POINT({} {})".format(longitude, latitude)
)
class UndergroundStorageTank(StorageTank, BaseEntity):
"""Subclass to StorageTank with Joined Table Inheritance. When UndergroundStorageTank is queried all columns from StorageTank are inherited."""
__tablename__ = "ust"
__mapper_args__ = {"polymorphic_identity": "ust"}
tank_double_wall = db.Column(db.Boolean)
inner_tank_material = db.Column(db.Text)
outer_tank_material = db.Column(db.Text)
tank_leak_detection = db.Column(db.Text)
tank_corrosion_protection = db.Column(db.Text)
tank_monitoring_system = db.Column(db.Text)
piping_double_wall = db.Column(db.Boolean)
piping_type = db.Column(db.Text) # Pressurized or suction
inner_pipe_material = db.Column(db.Text)
outer_pipe_material = db.Column(db.Text)
piping_corrosion_protection = db.Column(db.Text)
spill_protection = db.Column(db.Text)
overflow_protection = db.Column(db.Text)
def __repr__(self):
return f"UndergroundStorageTank('{self.tank_id}', '{self.tank_type}', '{self.stored_substance}', '{self.status}')"
def to_json(self):
json_ust = {
"url": url_for("api.get_ust", tank_id=self.tank_id),
"capacity": self.capacity,
"stored_substance": self.stored_substance,
}
return json_ust
class AbovegroundStorageTank(StorageTank, BaseEntity):
"""Subclass to StorageTank with Joined Table Inheritance. When AbovegroundStorageTank is queried all columns from StorageTank are inherited."""
__tablename__ = "ast"
__mapper_args__ = {"polymorphic_identity": "ast"}
def __repr__(self):
return f"AbovegroundStorageTank('{self.tank_id}', '{self.tank_type}', '{self.stored_substance}', '{self.status}')"
def to_json(self):
json_ast = {
"url": url_for("api.get_ast", tank_id=self.tank_id),
"capacity": self.capacity,
"stored_substance": self.stored_substance,
}
return json_ast
class MediumCode(db.Model, BaseEntity):
__tablename__ = "medium_code"
medium_cd = db.Column(db.String(3), primary_key=True)
medium_name = db.Column(db.String(64))
medium_description = db.Column(db.Text)
legacy_cd = db.Column(db.CHAR(1))
def __init__(self, **kwargs):
super(MediumCode, self).__init__(**kwargs)
def _insert_medium_codes():
"""Inserts USGS Medium Codes. If the codes have already been entered, an error is thrown."""
if MediumCode.query.first():
raise AlreadyExistsError("Medium Codes have already been entered.")
else:
url = "https://help.waterdata.usgs.gov/medium_cd"
df = pd.read_html(url, header=0, converters={0: str})[0]
df.rename(
index=str,
columns={
"Medium Code": "medium_cd",
"Medium Name": "medium_name",
"Medium Description": "medium_description",
"Medium Legacy Code": "legacy_cd",
},
inplace=True,
)
df.to_sql("medium_code", con=db.engine, if_exists="append", index=False)
class SampleParameter(db.Model, BaseEntity):
__tablename__ = "sample_parameter"
__table_args__ = (
db.CheckConstraint(
"param_cd ~ similar_escape('[[:digit:]]{5}'::text, NULL::text)"
),
)
param_cd = db.Column(db.CHAR(5), primary_key=True)
group_name = db.Column(db.Text)
description = db.Column(db.Text)
epa_equivalence = db.Column(db.Text)
statistical_basis = db.Column(db.Text)
time_basis = db.Column(db.Text)
weight_basis = db.Column(db.Text)
particle_size_basis = db.Column(db.Text)
sample_fraction = db.Column(db.Text)
temperature_basis = db.Column(db.Text)
casrn = db.Column(db.Text)
srsname = db.Column(db.Text)
parameter_unit = db.Column(db.Text)
def __init__(self, **kwargs):
super(SampleParameter, self).__init__(**kwargs)
def _insert_param_codes():
"""Inserts USGS Parameter Codes. If the codes have already been entered, an error is thrown."""
if SampleParameter.query.first():
raise AlreadyExistsError("Parameter Codes have already been entered.")
else:
url = "https://help.waterdata.usgs.gov/parameter_cd?group_cd=%"
df = pd.read_html(url, header=0, converters={0: str})[0]
df.rename(
index=str,
columns={
"Parameter Code": "param_cd",
"Group Name": "group_name",
"Parameter Name/Description": "description",
"Epa equivalence": "epa_equivalence",
"Result Statistical Basis": "statistical_basis",
"Result Time Basis": "time_basis",
"Result Weight Basis": "weight_basis",
"Result Particle Size Basis": "particle_size_basis",
"Result Sample Fraction": "sample_fraction",
"Result Temperature Basis": "temperature_basis",
"CASRN": "casrn",
"SRSName": "srsname",
"Parameter Unit": "parameter_unit",
},
inplace=True,
)
df.to_sql(
"sample_parameter", con=db.engine, if_exists="append", index=False
)
class SampleId(db.Model, BaseEntity):
__tablename__ = "sample_id"
__table_args__ = (db.UniqueConstraint("sample_id", "facility_id"),)
sample_id = db.Column(db.Integer, primary_key=True)
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
sample_name = db.Column(db.Text)
description = db.Column(db.Text)
longitude = db.Column(db.Float, nullable=True)
latitude = db.Column(db.Float, nullable=True)
geometry = db.Column(Geometry(geometry_type="POINT", srid=4326))
sample_type = db.Column(db.String(24))
facility = db.relationship("Facility")
__mapper_args__ = {
"polymorphic_identity": "sample_id",
"polymorphic_on": sample_type,
}
def __repr__(self):
return f"SampleId('{self.sample_id}', '{self.facility.name}', '{self.sample_type}')"
def to_json(self):
json_sample_location = {
"url": url_for("api.get_sample_id", sample_id_id=self.sample_id),
"facility": self.facility.name,
"sample_id": self.sample_id,
"sample_type": self.sample_type,
}
return json_sample_id
@staticmethod
def from_json(json_sample_location):
facility = json_sample_location.get("facility.name")
sample_id = json_sample_location.get("sample_id")
sample_type = json_sample_location.get("sample_type")
if location_id is None or location_id == "":
raise ValidationError("Sample does not have an ID")
return SampleId(sample_id=sample_id, sample_type=sample_type)
class Boring(db.Model, BaseEntity):
__tablename__ = "boring"
boring_id = db.Column(db.Text, primary_key=True)
start_date = db.Column(db.Date)
end_date = db.Column(db.Date)
class Well(SampleId, BaseEntity):
__tablename__ = "well"
__mapper_args__ = {"polymorphic_identity": "monitoring_well"}
well_id = db.Column(db.Text)
boring_id = db.Column(db.Text, db.ForeignKey("boring.boring_id"))
well_type = db.Column(db.String(10))
installation_date = db.Column(db.Date)
abandoned_date = db.Column(db.Date)
top_riser = db.Column(db.Float)
top_bent_seal = db.Column(db.Float)
top_gravel_pack = db.Column(db.Float)
top_screen = db.Column(db.Float)
bottom_screen = db.Column(db.Float)
bottom_well = db.Column(db.Float)
bottom_gravel_pack = db.Column(db.Float)
bottom_boring = db.Column(db.Float)
grout_seal_desc = db.Column(db.Text)
bent_seal_desc = db.Column(db.Text)
screen_type = db.Column(db.Text)
gravel_pack_desc = db.Column(db.Text)
riser_pipe_desc = db.Column(db.Text)
spacer_depths = db.Column(db.Text)
notes = db.Column(db.Text)
boring = db.relationship("Boring")
def __repr__(self):
return f"MonitoringWell('{self.well_id}')"
def to_json(self):
json_monitoring_well = {
"url": url_for("api.get_monitoring_well", well_id=self.well_id),
"top_screen": self.top_screen,
"bottom_screen": self.bottom_screen,
}
return json_monitoring_well
class SampleResult(db.Model, BaseEntity):
__tablename__ = "sample_result"
__table_args__ = (
db.UniqueConstraint(
"lab_id", "sample_id", "sample_date", "param_cd", "analysis_result"
),
db.CheckConstraint(
"param_cd ~ similar_escape('[[:digit:]]{5}'::text, NULL::text)"
),
)
result_id = db.Column(db.Integer, primary_key=True)
lab_id = db.Column(db.Text)
facility_id = db.Column(db.Integer, db.ForeignKey("facility.facility_id"))
sample_id = db.Column(db.Integer, db.ForeignKey("sample_id.sample_id"))
param_cd = db.Column(db.CHAR(5), db.ForeignKey("sample_parameter.param_cd"))
medium_cd = db.Column(db.String(3), db.ForeignKey("medium_code.medium_cd"))
sample_date = db.Column(db.Date, nullable=False)
sample_time = db.Column(db.Time, nullable=True)
prep_method = db.Column(db.Text)
analysis_method = db.Column(db.Text, nullable=True)
analysis_flag = db.Column(db.CHAR(1), nullable=True)
analysis_result = db.Column(db.Float, nullable=True)
analysis_unit = db.Column(db.Text, nullable=False)
detection_limit = db.Column(db.Float)
reporting_limit = db.Column(db.Float)
analysis_qualifier = db.Column(db.CHAR(1))
disclaimer = db.Column(db.Text)
analysis_date = db.Column(db.DateTime)
order_comment = db.Column(db.Text)
analysis_comment = db.Column(db.Text)
sample = db.relationship("SampleId")
medium_code = db.relationship("MediumCode")
sample_parameter = db.relationship("SampleParameter")
facility = db.relationship("Facility")
def __repr__(self):
return f"SampleResult('{self.result_id}')"
def to_json(self):
json_sample_result = {
"url": url_for("api.get_sample_result", result_id=self.result_id),
"lab_id": self.lab_id,
}
return json_sample_result | 0.763836 | 0.138899 |
import numpy as np
from ..helpers import numerical_test
__all__ = (
'central_moment',
'mean',
'median',
'mode',
'standard_deviation',
'standard_moment',
)
def mean(dist):
"""
Computes the mean of the distribution.
Parameters
----------
dist : Distribution
The distribution to take the mean of.
Returns
-------
means : ndarray
The mean of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
numerical_test(dist)
outcomes, pmf = zip(*dist.zipped(mode='patoms'))
outcomes = np.asarray(outcomes)
pmf = np.asarray(pmf)
return np.average(outcomes, axis=0, weights=pmf)
def central_moment(dist, n):
"""
Computes the `n`th central moment of a distribution.
Parameters
----------
dist : Distribution
The distribution to take the moment of.
n : int
Which moment to take.
Returns
-------
moments : ndarray
The `n`th central moment of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
mu = mean(dist)
outcomes, pmf = zip(*dist.zipped(mode='patoms'))
outcomes = np.asarray(outcomes)
pmf = np.asarray(pmf)
terms = np.asarray([(np.asarray(o) - mu)**n for o in outcomes])
terms[np.isnan(terms)] = 0
return np.average(terms, axis=0, weights=pmf)
def standard_moment(dist, n):
"""
Computes the `n`th standard moment of a distribution.
Parameters
----------
dist : Distribution
The distribution to take the moment of.
n : int
Which moment to take.
Returns
-------
moments : ndarray
The `n`th standard moment of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
return central_moment(dist, n) / standard_deviation(dist)**n
def standard_deviation(dist):
"""
Compute the standard deviation of a distribution.
Parameters
----------
dist : Distribution
The distribution to take the standard deviation of.
Returns
-------
std : ndarray
The standard deviation of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
return np.sqrt(central_moment(dist, 2))
def median(dist):
"""
Compute the median of a distribution.
Parameters
----------
dist : Distribution
The distribution to compute the median of.
Returns
-------
medians : ndarray
The median of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
numerical_test(dist)
g = np.asarray(dist.outcomes[(dist.pmf.cumsum() > 0.5).argmax()])
ge = np.asarray(dist.outcomes[(dist.pmf.cumsum() >= 0.5).argmax()])
return (g + ge) / 2
def mode(dist):
"""
Compute the modes of a distribution.
Parameters
----------
dist : Distribution
The distribution to compute the modes of.
Returns
-------
modes : [ndarray]
A list of arrays, one for each index of the outcomes. Each array
contains the modes of that index.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
numerical_test(dist)
try:
dists = [dist.marginal([i]) for i in range(dist.outcome_length())]
except AttributeError:
dists = [dist]
modes = [np.asarray(d.outcomes)[d.pmf == d.pmf.max()] for d in dists]
modes = [m.flatten() for m in modes]
return modes | dit/algorithms/stats.py | import numpy as np
from ..helpers import numerical_test
__all__ = (
'central_moment',
'mean',
'median',
'mode',
'standard_deviation',
'standard_moment',
)
def mean(dist):
"""
Computes the mean of the distribution.
Parameters
----------
dist : Distribution
The distribution to take the mean of.
Returns
-------
means : ndarray
The mean of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
numerical_test(dist)
outcomes, pmf = zip(*dist.zipped(mode='patoms'))
outcomes = np.asarray(outcomes)
pmf = np.asarray(pmf)
return np.average(outcomes, axis=0, weights=pmf)
def central_moment(dist, n):
"""
Computes the `n`th central moment of a distribution.
Parameters
----------
dist : Distribution
The distribution to take the moment of.
n : int
Which moment to take.
Returns
-------
moments : ndarray
The `n`th central moment of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
mu = mean(dist)
outcomes, pmf = zip(*dist.zipped(mode='patoms'))
outcomes = np.asarray(outcomes)
pmf = np.asarray(pmf)
terms = np.asarray([(np.asarray(o) - mu)**n for o in outcomes])
terms[np.isnan(terms)] = 0
return np.average(terms, axis=0, weights=pmf)
def standard_moment(dist, n):
"""
Computes the `n`th standard moment of a distribution.
Parameters
----------
dist : Distribution
The distribution to take the moment of.
n : int
Which moment to take.
Returns
-------
moments : ndarray
The `n`th standard moment of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
return central_moment(dist, n) / standard_deviation(dist)**n
def standard_deviation(dist):
"""
Compute the standard deviation of a distribution.
Parameters
----------
dist : Distribution
The distribution to take the standard deviation of.
Returns
-------
std : ndarray
The standard deviation of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
return np.sqrt(central_moment(dist, 2))
def median(dist):
"""
Compute the median of a distribution.
Parameters
----------
dist : Distribution
The distribution to compute the median of.
Returns
-------
medians : ndarray
The median of each index of the outcomes.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
numerical_test(dist)
g = np.asarray(dist.outcomes[(dist.pmf.cumsum() > 0.5).argmax()])
ge = np.asarray(dist.outcomes[(dist.pmf.cumsum() >= 0.5).argmax()])
return (g + ge) / 2
def mode(dist):
"""
Compute the modes of a distribution.
Parameters
----------
dist : Distribution
The distribution to compute the modes of.
Returns
-------
modes : [ndarray]
A list of arrays, one for each index of the outcomes. Each array
contains the modes of that index.
Raises
------
TypeError
If the outcomes of the `dist` are not numerical.
"""
numerical_test(dist)
try:
dists = [dist.marginal([i]) for i in range(dist.outcome_length())]
except AttributeError:
dists = [dist]
modes = [np.asarray(d.outcomes)[d.pmf == d.pmf.max()] for d in dists]
modes = [m.flatten() for m in modes]
return modes | 0.934887 | 0.871037 |
import pprint
import re # noqa: F401
import six
class Quote(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
required_map (dict): The key is attribute name
and the value is whether it is 'required' or 'optional'.
"""
openapi_types = {
'quote_id': 'QuoteId',
'metric_value': 'MetricValue',
'lineage': 'str',
'cut_label': 'str',
'uploaded_by': 'str',
'as_at': 'datetime',
'scale_factor': 'float'
}
attribute_map = {
'quote_id': 'quoteId',
'metric_value': 'metricValue',
'lineage': 'lineage',
'cut_label': 'cutLabel',
'uploaded_by': 'uploadedBy',
'as_at': 'asAt',
'scale_factor': 'scaleFactor'
}
required_map = {
'quote_id': 'required',
'metric_value': 'optional',
'lineage': 'optional',
'cut_label': 'optional',
'uploaded_by': 'required',
'as_at': 'required',
'scale_factor': 'optional'
}
def __init__(self, quote_id=None, metric_value=None, lineage=None, cut_label=None, uploaded_by=None, as_at=None, scale_factor=None): # noqa: E501
"""
Quote - a model defined in OpenAPI
:param quote_id: (required)
:type quote_id: lusid.QuoteId
:param metric_value:
:type metric_value: lusid.MetricValue
:param lineage: Description of the quote's lineage e.g. 'FundAccountant_GreenQuality'.
:type lineage: str
:param cut_label: The cut label that this quote was updated or inserted with.
:type cut_label: str
:param uploaded_by: The unique id of the user that updated or inserted the quote. (required)
:type uploaded_by: str
:param as_at: The asAt datetime at which the quote was committed to LUSID. (required)
:type as_at: datetime
:param scale_factor: An optional scale factor for non-standard scaling of quotes against the instrument. If not supplied, the default ScaleFactor is 1.
:type scale_factor: float
""" # noqa: E501
self._quote_id = None
self._metric_value = None
self._lineage = None
self._cut_label = None
self._uploaded_by = None
self._as_at = None
self._scale_factor = None
self.discriminator = None
self.quote_id = quote_id
if metric_value is not None:
self.metric_value = metric_value
self.lineage = lineage
self.cut_label = cut_label
self.uploaded_by = uploaded_by
self.as_at = as_at
self.scale_factor = scale_factor
@property
def quote_id(self):
"""Gets the quote_id of this Quote. # noqa: E501
:return: The quote_id of this Quote. # noqa: E501
:rtype: QuoteId
"""
return self._quote_id
@quote_id.setter
def quote_id(self, quote_id):
"""Sets the quote_id of this Quote.
:param quote_id: The quote_id of this Quote. # noqa: E501
:type: QuoteId
"""
if quote_id is None:
raise ValueError("Invalid value for `quote_id`, must not be `None`") # noqa: E501
self._quote_id = quote_id
@property
def metric_value(self):
"""Gets the metric_value of this Quote. # noqa: E501
:return: The metric_value of this Quote. # noqa: E501
:rtype: MetricValue
"""
return self._metric_value
@metric_value.setter
def metric_value(self, metric_value):
"""Sets the metric_value of this Quote.
:param metric_value: The metric_value of this Quote. # noqa: E501
:type: MetricValue
"""
self._metric_value = metric_value
@property
def lineage(self):
"""Gets the lineage of this Quote. # noqa: E501
Description of the quote's lineage e.g. 'FundAccountant_GreenQuality'. # noqa: E501
:return: The lineage of this Quote. # noqa: E501
:rtype: str
"""
return self._lineage
@lineage.setter
def lineage(self, lineage):
"""Sets the lineage of this Quote.
Description of the quote's lineage e.g. 'FundAccountant_GreenQuality'. # noqa: E501
:param lineage: The lineage of this Quote. # noqa: E501
:type: str
"""
self._lineage = lineage
@property
def cut_label(self):
"""Gets the cut_label of this Quote. # noqa: E501
The cut label that this quote was updated or inserted with. # noqa: E501
:return: The cut_label of this Quote. # noqa: E501
:rtype: str
"""
return self._cut_label
@cut_label.setter
def cut_label(self, cut_label):
"""Sets the cut_label of this Quote.
The cut label that this quote was updated or inserted with. # noqa: E501
:param cut_label: The cut_label of this Quote. # noqa: E501
:type: str
"""
self._cut_label = cut_label
@property
def uploaded_by(self):
"""Gets the uploaded_by of this Quote. # noqa: E501
The unique id of the user that updated or inserted the quote. # noqa: E501
:return: The uploaded_by of this Quote. # noqa: E501
:rtype: str
"""
return self._uploaded_by
@uploaded_by.setter
def uploaded_by(self, uploaded_by):
"""Sets the uploaded_by of this Quote.
The unique id of the user that updated or inserted the quote. # noqa: E501
:param uploaded_by: The uploaded_by of this Quote. # noqa: E501
:type: str
"""
if uploaded_by is None:
raise ValueError("Invalid value for `uploaded_by`, must not be `None`") # noqa: E501
self._uploaded_by = uploaded_by
@property
def as_at(self):
"""Gets the as_at of this Quote. # noqa: E501
The asAt datetime at which the quote was committed to LUSID. # noqa: E501
:return: The as_at of this Quote. # noqa: E501
:rtype: datetime
"""
return self._as_at
@as_at.setter
def as_at(self, as_at):
"""Sets the as_at of this Quote.
The asAt datetime at which the quote was committed to LUSID. # noqa: E501
:param as_at: The as_at of this Quote. # noqa: E501
:type: datetime
"""
if as_at is None:
raise ValueError("Invalid value for `as_at`, must not be `None`") # noqa: E501
self._as_at = as_at
@property
def scale_factor(self):
"""Gets the scale_factor of this Quote. # noqa: E501
An optional scale factor for non-standard scaling of quotes against the instrument. If not supplied, the default ScaleFactor is 1. # noqa: E501
:return: The scale_factor of this Quote. # noqa: E501
:rtype: float
"""
return self._scale_factor
@scale_factor.setter
def scale_factor(self, scale_factor):
"""Sets the scale_factor of this Quote.
An optional scale factor for non-standard scaling of quotes against the instrument. If not supplied, the default ScaleFactor is 1. # noqa: E501
:param scale_factor: The scale_factor of this Quote. # noqa: E501
:type: float
"""
self._scale_factor = scale_factor
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Quote):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | sdk/lusid/models/quote.py | import pprint
import re # noqa: F401
import six
class Quote(object):
"""NOTE: This class is auto generated by OpenAPI Generator.
Ref: https://openapi-generator.tech
Do not edit the class manually.
"""
"""
Attributes:
openapi_types (dict): The key is attribute name
and the value is attribute type.
attribute_map (dict): The key is attribute name
and the value is json key in definition.
required_map (dict): The key is attribute name
and the value is whether it is 'required' or 'optional'.
"""
openapi_types = {
'quote_id': 'QuoteId',
'metric_value': 'MetricValue',
'lineage': 'str',
'cut_label': 'str',
'uploaded_by': 'str',
'as_at': 'datetime',
'scale_factor': 'float'
}
attribute_map = {
'quote_id': 'quoteId',
'metric_value': 'metricValue',
'lineage': 'lineage',
'cut_label': 'cutLabel',
'uploaded_by': 'uploadedBy',
'as_at': 'asAt',
'scale_factor': 'scaleFactor'
}
required_map = {
'quote_id': 'required',
'metric_value': 'optional',
'lineage': 'optional',
'cut_label': 'optional',
'uploaded_by': 'required',
'as_at': 'required',
'scale_factor': 'optional'
}
def __init__(self, quote_id=None, metric_value=None, lineage=None, cut_label=None, uploaded_by=None, as_at=None, scale_factor=None): # noqa: E501
"""
Quote - a model defined in OpenAPI
:param quote_id: (required)
:type quote_id: lusid.QuoteId
:param metric_value:
:type metric_value: lusid.MetricValue
:param lineage: Description of the quote's lineage e.g. 'FundAccountant_GreenQuality'.
:type lineage: str
:param cut_label: The cut label that this quote was updated or inserted with.
:type cut_label: str
:param uploaded_by: The unique id of the user that updated or inserted the quote. (required)
:type uploaded_by: str
:param as_at: The asAt datetime at which the quote was committed to LUSID. (required)
:type as_at: datetime
:param scale_factor: An optional scale factor for non-standard scaling of quotes against the instrument. If not supplied, the default ScaleFactor is 1.
:type scale_factor: float
""" # noqa: E501
self._quote_id = None
self._metric_value = None
self._lineage = None
self._cut_label = None
self._uploaded_by = None
self._as_at = None
self._scale_factor = None
self.discriminator = None
self.quote_id = quote_id
if metric_value is not None:
self.metric_value = metric_value
self.lineage = lineage
self.cut_label = cut_label
self.uploaded_by = uploaded_by
self.as_at = as_at
self.scale_factor = scale_factor
@property
def quote_id(self):
"""Gets the quote_id of this Quote. # noqa: E501
:return: The quote_id of this Quote. # noqa: E501
:rtype: QuoteId
"""
return self._quote_id
@quote_id.setter
def quote_id(self, quote_id):
"""Sets the quote_id of this Quote.
:param quote_id: The quote_id of this Quote. # noqa: E501
:type: QuoteId
"""
if quote_id is None:
raise ValueError("Invalid value for `quote_id`, must not be `None`") # noqa: E501
self._quote_id = quote_id
@property
def metric_value(self):
"""Gets the metric_value of this Quote. # noqa: E501
:return: The metric_value of this Quote. # noqa: E501
:rtype: MetricValue
"""
return self._metric_value
@metric_value.setter
def metric_value(self, metric_value):
"""Sets the metric_value of this Quote.
:param metric_value: The metric_value of this Quote. # noqa: E501
:type: MetricValue
"""
self._metric_value = metric_value
@property
def lineage(self):
"""Gets the lineage of this Quote. # noqa: E501
Description of the quote's lineage e.g. 'FundAccountant_GreenQuality'. # noqa: E501
:return: The lineage of this Quote. # noqa: E501
:rtype: str
"""
return self._lineage
@lineage.setter
def lineage(self, lineage):
"""Sets the lineage of this Quote.
Description of the quote's lineage e.g. 'FundAccountant_GreenQuality'. # noqa: E501
:param lineage: The lineage of this Quote. # noqa: E501
:type: str
"""
self._lineage = lineage
@property
def cut_label(self):
"""Gets the cut_label of this Quote. # noqa: E501
The cut label that this quote was updated or inserted with. # noqa: E501
:return: The cut_label of this Quote. # noqa: E501
:rtype: str
"""
return self._cut_label
@cut_label.setter
def cut_label(self, cut_label):
"""Sets the cut_label of this Quote.
The cut label that this quote was updated or inserted with. # noqa: E501
:param cut_label: The cut_label of this Quote. # noqa: E501
:type: str
"""
self._cut_label = cut_label
@property
def uploaded_by(self):
"""Gets the uploaded_by of this Quote. # noqa: E501
The unique id of the user that updated or inserted the quote. # noqa: E501
:return: The uploaded_by of this Quote. # noqa: E501
:rtype: str
"""
return self._uploaded_by
@uploaded_by.setter
def uploaded_by(self, uploaded_by):
"""Sets the uploaded_by of this Quote.
The unique id of the user that updated or inserted the quote. # noqa: E501
:param uploaded_by: The uploaded_by of this Quote. # noqa: E501
:type: str
"""
if uploaded_by is None:
raise ValueError("Invalid value for `uploaded_by`, must not be `None`") # noqa: E501
self._uploaded_by = uploaded_by
@property
def as_at(self):
"""Gets the as_at of this Quote. # noqa: E501
The asAt datetime at which the quote was committed to LUSID. # noqa: E501
:return: The as_at of this Quote. # noqa: E501
:rtype: datetime
"""
return self._as_at
@as_at.setter
def as_at(self, as_at):
"""Sets the as_at of this Quote.
The asAt datetime at which the quote was committed to LUSID. # noqa: E501
:param as_at: The as_at of this Quote. # noqa: E501
:type: datetime
"""
if as_at is None:
raise ValueError("Invalid value for `as_at`, must not be `None`") # noqa: E501
self._as_at = as_at
@property
def scale_factor(self):
"""Gets the scale_factor of this Quote. # noqa: E501
An optional scale factor for non-standard scaling of quotes against the instrument. If not supplied, the default ScaleFactor is 1. # noqa: E501
:return: The scale_factor of this Quote. # noqa: E501
:rtype: float
"""
return self._scale_factor
@scale_factor.setter
def scale_factor(self, scale_factor):
"""Sets the scale_factor of this Quote.
An optional scale factor for non-standard scaling of quotes against the instrument. If not supplied, the default ScaleFactor is 1. # noqa: E501
:param scale_factor: The scale_factor of this Quote. # noqa: E501
:type: float
"""
self._scale_factor = scale_factor
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.openapi_types):
value = getattr(self, attr)
if isinstance(value, list):
result[attr] = list(map(
lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
value
))
elif hasattr(value, "to_dict"):
result[attr] = value.to_dict()
elif isinstance(value, dict):
result[attr] = dict(map(
lambda item: (item[0], item[1].to_dict())
if hasattr(item[1], "to_dict") else item,
value.items()
))
else:
result[attr] = value
return result
def to_str(self):
"""Returns the string representation of the model"""
return pprint.pformat(self.to_dict())
def __repr__(self):
"""For `print` and `pprint`"""
return self.to_str()
def __eq__(self, other):
"""Returns true if both objects are equal"""
if not isinstance(other, Quote):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other | 0.835618 | 0.128388 |
import os
import re
import codecs
from setuptools import setup
from setuptools import find_packages
PROJECT = os.path.abspath(os.path.dirname(__file__))
REQUIRE_PATH = "requirements.txt"
EXCLUDES = (
"tests", "bin", "docs", "fixtures", "register", "notebooks", "examples",
)
long_description = open('README.rst').read()
def read(*parts):
"""
Assume UTF-8 encoding and return the contents of the file located at the
absolute path from the REPOSITORY joined with *parts.
"""
with codecs.open(os.path.join(PROJECT, *parts), 'rb', 'utf-8') as f:
return f.read()
def get_requires(path=REQUIRE_PATH):
"""
Yields a generator of requirements as defined by the REQUIRE_PATH which
should point to a requirements.txt output by `pip freeze`.
"""
for line in read(path).splitlines():
line = line.strip()
if line and not line.startswith('#'):
yield line
setup(name="py-opensecrets",
version="0.3.0",
description="Libraries for interacting with the Opensecrets API",
author="<NAME> <<EMAIL>>",
author_email = "<EMAIL>",
license="BSD",
url="http://github.com/ndanielsen/py-opensecrets/",
long_description="Py-opensecrets is a library and set of utilities for interacting with the Opensecrets API",
packages=find_packages(where=PROJECT, exclude=EXCLUDES),
platforms=["any"],
classifiers=["Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6"
],
install_requires=list(get_requires()),
) | setup.py | import os
import re
import codecs
from setuptools import setup
from setuptools import find_packages
PROJECT = os.path.abspath(os.path.dirname(__file__))
REQUIRE_PATH = "requirements.txt"
EXCLUDES = (
"tests", "bin", "docs", "fixtures", "register", "notebooks", "examples",
)
long_description = open('README.rst').read()
def read(*parts):
"""
Assume UTF-8 encoding and return the contents of the file located at the
absolute path from the REPOSITORY joined with *parts.
"""
with codecs.open(os.path.join(PROJECT, *parts), 'rb', 'utf-8') as f:
return f.read()
def get_requires(path=REQUIRE_PATH):
"""
Yields a generator of requirements as defined by the REQUIRE_PATH which
should point to a requirements.txt output by `pip freeze`.
"""
for line in read(path).splitlines():
line = line.strip()
if line and not line.startswith('#'):
yield line
setup(name="py-opensecrets",
version="0.3.0",
description="Libraries for interacting with the Opensecrets API",
author="<NAME> <<EMAIL>>",
author_email = "<EMAIL>",
license="BSD",
url="http://github.com/ndanielsen/py-opensecrets/",
long_description="Py-opensecrets is a library and set of utilities for interacting with the Opensecrets API",
packages=find_packages(where=PROJECT, exclude=EXCLUDES),
platforms=["any"],
classifiers=["Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: BSD License",
"Natural Language :: English",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Topic :: Software Development :: Libraries :: Python Modules",
'Programming Language :: Python',
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6"
],
install_requires=list(get_requires()),
) | 0.423935 | 0.167866 |
import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
from pyasn1.type import univ
from pyasn1_modules import pem, rfc2985, rfc5280, rfc5652, rfc7292
class PKCS9AttrsTestCase(unittest.TestCase):
pem_text = """\
<KEY>
"""
def setUp(self):
self.asn1Spec = rfc2985.AttributeSet()
def testDerCodec(self):
substrate = pem.readBase64fromText(self.pem_text)
asn1Object, rest = der_decoder(substrate, asn1Spec=self.asn1Spec)
self.assertFalse(rest)
self.assertTrue(asn1Object.prettyPrint())
self.assertEqual(der_encoder(asn1Object), substrate)
openTypesMap = {
rfc2985.pkcs_9_at_smimeCapabilities: rfc2985.SMIMECapabilities(),
}
openTypesMap.update(rfc5280.certificateAttributesMap)
openTypesMap.update(rfc5652.cmsAttributesMap)
for attr in asn1Object:
self.assertIn(attr["type"], openTypesMap)
av, rest = der_decoder(
attr["values"][0], asn1Spec=openTypesMap[attr["type"]]
)
self.assertFalse(rest)
self.assertTrue(av.prettyPrint())
self.assertEqual(attr["values"][0], der_encoder(av))
if attr["type"] == rfc2985.pkcs_9_at_userPKCS12:
self.assertEqual(univ.Integer(3), av["version"])
self.assertEqual(rfc5652.id_data, av["authSafe"]["contentType"])
outdata, rest = der_decoder(
av["authSafe"]["content"], asn1Spec=univ.OctetString()
)
self.assertFalse(rest)
authsafe, rest = der_decoder(
outdata, asn1Spec=rfc7292.AuthenticatedSafe()
)
self.assertFalse(rest)
for ci in authsafe:
self.assertEqual(rfc5652.id_data, ci["contentType"])
indata, rest = der_decoder(
ci["content"], asn1Spec=univ.OctetString()
)
self.assertFalse(rest)
sc, rest = der_decoder(indata, asn1Spec=rfc7292.SafeContents())
self.assertFalse(rest)
for sb in sc:
if sb["bagId"] in rfc7292.pkcs12BagTypeMap:
bv, rest = der_decoder(
sb["bagValue"],
asn1Spec=rfc7292.pkcs12BagTypeMap[sb["bagId"]],
)
self.assertFalse(rest)
for bagattr in sb["bagAttributes"]:
if bagattr["attrType"] in openTypesMap:
inav, rest = der_decoder(
bagattr["attrValues"][0],
asn1Spec=openTypesMap[bagattr["attrType"]],
)
self.assertFalse(rest)
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_friendlyName
):
self.assertEqual(
"3f71af65-1687-444a-9f46-c8be194c3e8e", inav
)
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_localKeyId
):
self.assertEqual(
univ.OctetString(hexValue="01000000"), inav
)
if attr["type"] == rfc2985.pkcs_9_at_pkcs7PDU:
ci, rest = der_decoder(
attr["values"][0], asn1Spec=rfc5652.ContentInfo()
)
self.assertFalse(rest)
self.assertEqual(rfc5652.id_signedData, ci["contentType"])
sd, rest = der_decoder(ci["content"], asn1Spec=rfc5652.SignedData())
self.assertFalse(rest)
self.assertEqual(1, sd["version"])
for si in sd["signerInfos"]:
self.assertEqual(1, si["version"])
for siattr in si["signedAttrs"]:
if siattr["attrType"] in openTypesMap:
siav, rest = der_decoder(
siattr["attrValues"][0],
asn1Spec=openTypesMap[siattr["attrType"]],
)
self.assertFalse(rest)
if siattr["attrType"] == rfc2985.pkcs_9_at_contentType:
self.assertEqual(rfc5652.id_data, siav)
if siattr["attrType"] == rfc2985.pkcs_9_at_messageDigest:
self.assertEqual("b6e422a4", siav.prettyPrint()[2:10])
if siattr["attrType"] == rfc2985.pkcs_9_at_signingTime:
self.assertEqual("190529182319Z", siav["utcTime"])
for choices in sd["certificates"]:
for rdn in choices[0]["tbsCertificate"]["subject"]["rdnSequence"]:
if rdn[0]["type"] in openTypesMap:
nv, rest = der_decoder(
rdn[0]["value"], asn1Spec=openTypesMap[rdn[0]["type"]]
)
self.assertFalse(rest)
if rdn[0]["type"] == rfc2985.pkcs_9_at_emailAddress:
self.assertEqual("<EMAIL>", nv)
def testOpenTypes(self):
openTypesMap = {
rfc2985.pkcs_9_at_smimeCapabilities: rfc2985.SMIMECapabilities(),
}
openTypesMap.update(rfc5280.certificateAttributesMap)
openTypesMap.update(rfc5652.cmsAttributesMap)
substrate = pem.readBase64fromText(self.pem_text)
asn1Object, rest = der_decoder(
substrate,
asn1Spec=self.asn1Spec,
openTypes=openTypesMap,
decodeOpenTypes=True,
)
self.assertFalse(rest)
self.assertTrue(asn1Object.prettyPrint())
self.assertEqual(substrate, der_encoder(asn1Object))
for attr in asn1Object:
self.assertTrue(attr["type"], openTypesMap)
if attr["type"] == rfc2985.pkcs_9_at_userPKCS12:
self.assertEqual(univ.Integer(3), attr["values"][0]["version"])
self.assertEqual(
rfc5652.id_data, attr["values"][0]["authSafe"]["contentType"]
)
authsafe, rest = der_decoder(
attr["values"][0]["authSafe"]["content"],
asn1Spec=rfc7292.AuthenticatedSafe(),
)
self.assertFalse(rest)
for ci in authsafe:
self.assertEqual(rfc5652.id_data, ci["contentType"])
indata, rest = der_decoder(
ci["content"], asn1Spec=univ.OctetString()
)
self.assertFalse(rest)
sc, rest = der_decoder(
indata, asn1Spec=rfc7292.SafeContents(), decodeOpenTypes=True
)
self.assertFalse(rest)
for sb in sc:
if sb["bagId"] in rfc7292.pkcs12BagTypeMap:
for bagattr in sb["bagAttributes"]:
if bagattr["attrType"] in openTypesMap:
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_friendlyName
):
self.assertEqual(
"3f71af65-1687-444a-9f46-c8be194c3e8e",
bagattr["attrValues"][0],
)
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_localKeyId
):
self.assertEqual(
univ.OctetString(hexValue="01000000"),
bagattr["attrValues"][0],
)
if attr["type"] == rfc2985.pkcs_9_at_pkcs7PDU:
self.assertEqual(
rfc5652.id_signedData, attr["values"][0]["contentType"]
)
self.assertEqual(1, attr["values"][0]["content"]["version"])
for si in attr["values"][0]["content"]["signerInfos"]:
self.assertEqual(1, si["version"])
for siattr in si["signedAttrs"]:
if siattr["attrType"] in openTypesMap:
if siattr["attrType"] == rfc2985.pkcs_9_at_contentType:
self.assertEqual(
rfc5652.id_data, siattr["attrValues"][0]
)
if siattr["attrType"] == rfc2985.pkcs_9_at_messageDigest:
self.assertEqual(
"b6e422a4",
siattr["attrValues"][0].prettyPrint()[2:10],
)
if siattr["attrType"] == rfc2985.pkcs_9_at_signingTime:
self.assertEqual(
"190529182319Z", siattr["attrValues"][0]["utcTime"]
)
for choices in attr["values"][0]["content"]["certificates"]:
for rdn in choices[0]["tbsCertificate"]["subject"]["rdnSequence"]:
if rdn[0]["type"] in openTypesMap:
if rdn[0]["type"] == rfc2985.pkcs_9_at_emailAddress:
self.assertEqual("<EMAIL>", rdn[0]["value"])
suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(suite) | tests/test_rfc2985.py | import sys
import unittest
from pyasn1.codec.der.decoder import decode as der_decoder
from pyasn1.codec.der.encoder import encode as der_encoder
from pyasn1.type import univ
from pyasn1_modules import pem, rfc2985, rfc5280, rfc5652, rfc7292
class PKCS9AttrsTestCase(unittest.TestCase):
pem_text = """\
<KEY>
"""
def setUp(self):
self.asn1Spec = rfc2985.AttributeSet()
def testDerCodec(self):
substrate = pem.readBase64fromText(self.pem_text)
asn1Object, rest = der_decoder(substrate, asn1Spec=self.asn1Spec)
self.assertFalse(rest)
self.assertTrue(asn1Object.prettyPrint())
self.assertEqual(der_encoder(asn1Object), substrate)
openTypesMap = {
rfc2985.pkcs_9_at_smimeCapabilities: rfc2985.SMIMECapabilities(),
}
openTypesMap.update(rfc5280.certificateAttributesMap)
openTypesMap.update(rfc5652.cmsAttributesMap)
for attr in asn1Object:
self.assertIn(attr["type"], openTypesMap)
av, rest = der_decoder(
attr["values"][0], asn1Spec=openTypesMap[attr["type"]]
)
self.assertFalse(rest)
self.assertTrue(av.prettyPrint())
self.assertEqual(attr["values"][0], der_encoder(av))
if attr["type"] == rfc2985.pkcs_9_at_userPKCS12:
self.assertEqual(univ.Integer(3), av["version"])
self.assertEqual(rfc5652.id_data, av["authSafe"]["contentType"])
outdata, rest = der_decoder(
av["authSafe"]["content"], asn1Spec=univ.OctetString()
)
self.assertFalse(rest)
authsafe, rest = der_decoder(
outdata, asn1Spec=rfc7292.AuthenticatedSafe()
)
self.assertFalse(rest)
for ci in authsafe:
self.assertEqual(rfc5652.id_data, ci["contentType"])
indata, rest = der_decoder(
ci["content"], asn1Spec=univ.OctetString()
)
self.assertFalse(rest)
sc, rest = der_decoder(indata, asn1Spec=rfc7292.SafeContents())
self.assertFalse(rest)
for sb in sc:
if sb["bagId"] in rfc7292.pkcs12BagTypeMap:
bv, rest = der_decoder(
sb["bagValue"],
asn1Spec=rfc7292.pkcs12BagTypeMap[sb["bagId"]],
)
self.assertFalse(rest)
for bagattr in sb["bagAttributes"]:
if bagattr["attrType"] in openTypesMap:
inav, rest = der_decoder(
bagattr["attrValues"][0],
asn1Spec=openTypesMap[bagattr["attrType"]],
)
self.assertFalse(rest)
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_friendlyName
):
self.assertEqual(
"3f71af65-1687-444a-9f46-c8be194c3e8e", inav
)
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_localKeyId
):
self.assertEqual(
univ.OctetString(hexValue="01000000"), inav
)
if attr["type"] == rfc2985.pkcs_9_at_pkcs7PDU:
ci, rest = der_decoder(
attr["values"][0], asn1Spec=rfc5652.ContentInfo()
)
self.assertFalse(rest)
self.assertEqual(rfc5652.id_signedData, ci["contentType"])
sd, rest = der_decoder(ci["content"], asn1Spec=rfc5652.SignedData())
self.assertFalse(rest)
self.assertEqual(1, sd["version"])
for si in sd["signerInfos"]:
self.assertEqual(1, si["version"])
for siattr in si["signedAttrs"]:
if siattr["attrType"] in openTypesMap:
siav, rest = der_decoder(
siattr["attrValues"][0],
asn1Spec=openTypesMap[siattr["attrType"]],
)
self.assertFalse(rest)
if siattr["attrType"] == rfc2985.pkcs_9_at_contentType:
self.assertEqual(rfc5652.id_data, siav)
if siattr["attrType"] == rfc2985.pkcs_9_at_messageDigest:
self.assertEqual("b6e422a4", siav.prettyPrint()[2:10])
if siattr["attrType"] == rfc2985.pkcs_9_at_signingTime:
self.assertEqual("190529182319Z", siav["utcTime"])
for choices in sd["certificates"]:
for rdn in choices[0]["tbsCertificate"]["subject"]["rdnSequence"]:
if rdn[0]["type"] in openTypesMap:
nv, rest = der_decoder(
rdn[0]["value"], asn1Spec=openTypesMap[rdn[0]["type"]]
)
self.assertFalse(rest)
if rdn[0]["type"] == rfc2985.pkcs_9_at_emailAddress:
self.assertEqual("<EMAIL>", nv)
def testOpenTypes(self):
openTypesMap = {
rfc2985.pkcs_9_at_smimeCapabilities: rfc2985.SMIMECapabilities(),
}
openTypesMap.update(rfc5280.certificateAttributesMap)
openTypesMap.update(rfc5652.cmsAttributesMap)
substrate = pem.readBase64fromText(self.pem_text)
asn1Object, rest = der_decoder(
substrate,
asn1Spec=self.asn1Spec,
openTypes=openTypesMap,
decodeOpenTypes=True,
)
self.assertFalse(rest)
self.assertTrue(asn1Object.prettyPrint())
self.assertEqual(substrate, der_encoder(asn1Object))
for attr in asn1Object:
self.assertTrue(attr["type"], openTypesMap)
if attr["type"] == rfc2985.pkcs_9_at_userPKCS12:
self.assertEqual(univ.Integer(3), attr["values"][0]["version"])
self.assertEqual(
rfc5652.id_data, attr["values"][0]["authSafe"]["contentType"]
)
authsafe, rest = der_decoder(
attr["values"][0]["authSafe"]["content"],
asn1Spec=rfc7292.AuthenticatedSafe(),
)
self.assertFalse(rest)
for ci in authsafe:
self.assertEqual(rfc5652.id_data, ci["contentType"])
indata, rest = der_decoder(
ci["content"], asn1Spec=univ.OctetString()
)
self.assertFalse(rest)
sc, rest = der_decoder(
indata, asn1Spec=rfc7292.SafeContents(), decodeOpenTypes=True
)
self.assertFalse(rest)
for sb in sc:
if sb["bagId"] in rfc7292.pkcs12BagTypeMap:
for bagattr in sb["bagAttributes"]:
if bagattr["attrType"] in openTypesMap:
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_friendlyName
):
self.assertEqual(
"3f71af65-1687-444a-9f46-c8be194c3e8e",
bagattr["attrValues"][0],
)
if (
bagattr["attrType"]
== rfc2985.pkcs_9_at_localKeyId
):
self.assertEqual(
univ.OctetString(hexValue="01000000"),
bagattr["attrValues"][0],
)
if attr["type"] == rfc2985.pkcs_9_at_pkcs7PDU:
self.assertEqual(
rfc5652.id_signedData, attr["values"][0]["contentType"]
)
self.assertEqual(1, attr["values"][0]["content"]["version"])
for si in attr["values"][0]["content"]["signerInfos"]:
self.assertEqual(1, si["version"])
for siattr in si["signedAttrs"]:
if siattr["attrType"] in openTypesMap:
if siattr["attrType"] == rfc2985.pkcs_9_at_contentType:
self.assertEqual(
rfc5652.id_data, siattr["attrValues"][0]
)
if siattr["attrType"] == rfc2985.pkcs_9_at_messageDigest:
self.assertEqual(
"b6e422a4",
siattr["attrValues"][0].prettyPrint()[2:10],
)
if siattr["attrType"] == rfc2985.pkcs_9_at_signingTime:
self.assertEqual(
"190529182319Z", siattr["attrValues"][0]["utcTime"]
)
for choices in attr["values"][0]["content"]["certificates"]:
for rdn in choices[0]["tbsCertificate"]["subject"]["rdnSequence"]:
if rdn[0]["type"] in openTypesMap:
if rdn[0]["type"] == rfc2985.pkcs_9_at_emailAddress:
self.assertEqual("<EMAIL>", rdn[0]["value"])
suite = unittest.TestLoader().loadTestsFromModule(sys.modules[__name__])
if __name__ == "__main__":
unittest.TextTestRunner(verbosity=2).run(suite) | 0.412767 | 0.47098 |
import sys
from com.l2jserver import Config
from com.l2jserver.gameserver.model.quest import State
from com.l2jserver.gameserver.model.quest import QuestState
from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest
qn = "426_FishingShot"
SWEET_FLUID = 7586
MOBS1 = {
20005:45,20013:100,20016:100,20017:115,20030:105,20132:70,20038:135,20044:125,20046:100,
20047:100,20050:140,20058:140,20063:160,20066:170,20070:180,20074:195,20077:205,20078:205,
20079:205,20080:220,20081:370,20083:245,20084:255,20085:265,20087:565,20088:605,20089:250,
20100:85,20103:110,20105:110,20115:190,20120:20,20131:45,20135:360,20157:235,20162:195,
20176:280,20211:170,20225:160,20227:180,20230:260,20232:245,20234:290,20241:700,20267:215,
20268:295,20269:255,20270:365,20271:295,20286:700,20308:110,20312:45,20317:20,20324:85,
20333:100,20341:100,20346:85,20349:850,20356:165,20357:140,20363:70,20368:85,20371:100,
20386:85,20389:90,20403:110,20404:95,20433:100,20436:140,20448:45,20456:20,20463:85,20470:45,
20471:85,20475:20,20478:110,20487:90,20511:100,20525:20,20528:100,20536:15,20537:15,20538:15,
20539:15,20544:15,20550:300,20551:300,20552:650,20553:335,20554:390,20555:350,20557:390,
20559:420,20560:440,20562:485,20573:545,20575:645,20630:350,20632:475,20634:960,20636:495,
20638:540,20641:680,20643:660,20644:645,20659:440,20661:575,20663:525,20665:680,20667:730,
20766:210,20781:270,20783:140,20784:155,20786:170,20788:325,20790:390,20792:620,20794:635,
20796:640,20798:850,20800:740,20802:900,20804:775,20806:805,20833:455,20834:680,20836:785,
20837:835,20839:430,20841:460,20845:605,20847:570,20849:585,20936:290,20937:315,20939:385,
20940:500,20941:460,20943:345,20944:335,21100:125,21101:155,21103:215,21105:310,21107:600,
21117:120,21023:170,21024:175,21025:185,21026:200,21034:195,21125:12,21263:650,21520:880,
21526:970,21536:985,21602:555,21603:750,21605:620,21606:875,21611:590,21612:835,21617:615,
21618:875,21635:775,21638:165,21639:185,21641:195,21644:170
}
MOBS2 = {
20579:420,20639:280,20646:145,20648:120,20650:460,20651:260,20652:335,20657:630,20658:570,
20808:50,20809:865,20832:700,20979:980,20991:665,20994:590,21261:170,21263:795,21508:100,
21510:280,21511:995,21512:995,21514:185,21516:495,21517:495,21518:255,21636:950
}
MOBS3 = {
20655:110,20656:150,20772:105,20810:50,20812:490,20814:775,20816:875,20819:280,20955:670,
20978:555,21058:355,21060:45,21075:110,21078:610,21081:955,21264:920
}
MOBS4 = {
20815:205,20822:100,20824:665,20825:620,20983:205,21314:145,21316:235,21318:280,21320:355,
21322:430,21376:280,21378:375,21380:375,21387:640,21393:935,21395:855,21652:375,21655:640,
21657:935
}
MOBS5 = {
20828:935,21061:530,21069:825,21382:125,21384:400,21390:750,21654:400,21656:750
}
MOBSspecial = {
20829:[115,6],20859:[890,8],21066:[5,5],21068:[565,11],21071:[400,12]
}
KAMAELmobs = { #Chances are custom for now, any retail reports are welcome.
22231:160,22233:160,22234:160,22235:160,22237:160,22238:160,22241:160,22244:160,22247:160,
22250:160,22252:160
}
class Quest (JQuest) :
def __init__(self,id,name,descr):
JQuest.__init__(self,id,name,descr)
self.questItemIds = [SWEET_FLUID]
def onEvent (self,event,st) :
htmltext = event
if event == "02.htm" :
st.set("cond","1")
st.setState(State.STARTED)
st.playSound("ItemSound.quest_accept")
elif event == "07.htm" :
st.exitQuest(1)
st.playSound("ItemSound.quest_finish")
return htmltext
def onTalk (self,npc,player):
htmltext = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
npcId = npc.getNpcId()
cond=st.getInt("cond")
if cond==0 :
htmltext = "01.htm"
elif st.getQuestItemsCount(SWEET_FLUID) :
htmltext = "04.htm"
else :
htmltext = "03.htm"
return htmltext
def onKill(self,npc,player,isPet) :
partyMember = self.getRandomPartyMemberState(player, State.STARTED)
if not partyMember : return
st = partyMember.getQuestState(qn)
npcId = npc.getNpcId()
drop = 0
chance = 0
if npcId in MOBS1.keys() :
chance = MOBS1[npcId]
if npcId in KAMAELmobs.keys() :
chance = KAMAELmobs[npcId]
elif npcId in MOBS2.keys() :
chance = MOBS2[npcId]
drop = 1
elif npcId in MOBS3.keys() :
chance = MOBS3[npcId]
drop = 2
elif npcId in MOBS4.keys() :
chance = MOBS4[npcId]
drop = 3
elif npcId in MOBS5.keys() :
chance = MOBS5[npcId]
drop = 4
elif npcId in MOBSspecial.keys() :
chance,drop = MOBSspecial[npcId]
if st.getRandom(1000) <= chance :
drop += 1
if drop != 0 :
st.giveItems(SWEET_FLUID,drop*int(Config.RATE_QUEST_DROP))
st.playSound("ItemSound.quest_itemget")
return
QUEST = Quest(426,qn,"Quest for Fishing Shot")
for npc in range(31562,31580)+[31616,31696,31697,32348,31989,32007,32348] :
QUEST.addStartNpc(npc)
QUEST.addTalkId(npc)
for mob in MOBS1.keys():
QUEST.addKillId(mob)
for mob in KAMAELmobs.keys():
QUEST.addKillId(mob)
for mob in MOBS2.keys():
QUEST.addKillId(mob)
for mob in MOBS3.keys():
QUEST.addKillId(mob)
for mob in MOBS4.keys():
QUEST.addKillId(mob)
for mob in MOBS5.keys():
QUEST.addKillId(mob)
for mob in MOBSspecial.keys():
QUEST.addKillId(mob) | L2J_DataPack/data/scripts/quests/426_FishingShot/__init__.py | import sys
from com.l2jserver import Config
from com.l2jserver.gameserver.model.quest import State
from com.l2jserver.gameserver.model.quest import QuestState
from com.l2jserver.gameserver.model.quest.jython import QuestJython as JQuest
qn = "426_FishingShot"
SWEET_FLUID = 7586
MOBS1 = {
20005:45,20013:100,20016:100,20017:115,20030:105,20132:70,20038:135,20044:125,20046:100,
20047:100,20050:140,20058:140,20063:160,20066:170,20070:180,20074:195,20077:205,20078:205,
20079:205,20080:220,20081:370,20083:245,20084:255,20085:265,20087:565,20088:605,20089:250,
20100:85,20103:110,20105:110,20115:190,20120:20,20131:45,20135:360,20157:235,20162:195,
20176:280,20211:170,20225:160,20227:180,20230:260,20232:245,20234:290,20241:700,20267:215,
20268:295,20269:255,20270:365,20271:295,20286:700,20308:110,20312:45,20317:20,20324:85,
20333:100,20341:100,20346:85,20349:850,20356:165,20357:140,20363:70,20368:85,20371:100,
20386:85,20389:90,20403:110,20404:95,20433:100,20436:140,20448:45,20456:20,20463:85,20470:45,
20471:85,20475:20,20478:110,20487:90,20511:100,20525:20,20528:100,20536:15,20537:15,20538:15,
20539:15,20544:15,20550:300,20551:300,20552:650,20553:335,20554:390,20555:350,20557:390,
20559:420,20560:440,20562:485,20573:545,20575:645,20630:350,20632:475,20634:960,20636:495,
20638:540,20641:680,20643:660,20644:645,20659:440,20661:575,20663:525,20665:680,20667:730,
20766:210,20781:270,20783:140,20784:155,20786:170,20788:325,20790:390,20792:620,20794:635,
20796:640,20798:850,20800:740,20802:900,20804:775,20806:805,20833:455,20834:680,20836:785,
20837:835,20839:430,20841:460,20845:605,20847:570,20849:585,20936:290,20937:315,20939:385,
20940:500,20941:460,20943:345,20944:335,21100:125,21101:155,21103:215,21105:310,21107:600,
21117:120,21023:170,21024:175,21025:185,21026:200,21034:195,21125:12,21263:650,21520:880,
21526:970,21536:985,21602:555,21603:750,21605:620,21606:875,21611:590,21612:835,21617:615,
21618:875,21635:775,21638:165,21639:185,21641:195,21644:170
}
MOBS2 = {
20579:420,20639:280,20646:145,20648:120,20650:460,20651:260,20652:335,20657:630,20658:570,
20808:50,20809:865,20832:700,20979:980,20991:665,20994:590,21261:170,21263:795,21508:100,
21510:280,21511:995,21512:995,21514:185,21516:495,21517:495,21518:255,21636:950
}
MOBS3 = {
20655:110,20656:150,20772:105,20810:50,20812:490,20814:775,20816:875,20819:280,20955:670,
20978:555,21058:355,21060:45,21075:110,21078:610,21081:955,21264:920
}
MOBS4 = {
20815:205,20822:100,20824:665,20825:620,20983:205,21314:145,21316:235,21318:280,21320:355,
21322:430,21376:280,21378:375,21380:375,21387:640,21393:935,21395:855,21652:375,21655:640,
21657:935
}
MOBS5 = {
20828:935,21061:530,21069:825,21382:125,21384:400,21390:750,21654:400,21656:750
}
MOBSspecial = {
20829:[115,6],20859:[890,8],21066:[5,5],21068:[565,11],21071:[400,12]
}
KAMAELmobs = { #Chances are custom for now, any retail reports are welcome.
22231:160,22233:160,22234:160,22235:160,22237:160,22238:160,22241:160,22244:160,22247:160,
22250:160,22252:160
}
class Quest (JQuest) :
def __init__(self,id,name,descr):
JQuest.__init__(self,id,name,descr)
self.questItemIds = [SWEET_FLUID]
def onEvent (self,event,st) :
htmltext = event
if event == "02.htm" :
st.set("cond","1")
st.setState(State.STARTED)
st.playSound("ItemSound.quest_accept")
elif event == "07.htm" :
st.exitQuest(1)
st.playSound("ItemSound.quest_finish")
return htmltext
def onTalk (self,npc,player):
htmltext = "<html><body>You are either not on a quest that involves this NPC, or you don't meet this NPC's minimum quest requirements.</body></html>"
st = player.getQuestState(qn)
if not st : return htmltext
npcId = npc.getNpcId()
cond=st.getInt("cond")
if cond==0 :
htmltext = "01.htm"
elif st.getQuestItemsCount(SWEET_FLUID) :
htmltext = "04.htm"
else :
htmltext = "03.htm"
return htmltext
def onKill(self,npc,player,isPet) :
partyMember = self.getRandomPartyMemberState(player, State.STARTED)
if not partyMember : return
st = partyMember.getQuestState(qn)
npcId = npc.getNpcId()
drop = 0
chance = 0
if npcId in MOBS1.keys() :
chance = MOBS1[npcId]
if npcId in KAMAELmobs.keys() :
chance = KAMAELmobs[npcId]
elif npcId in MOBS2.keys() :
chance = MOBS2[npcId]
drop = 1
elif npcId in MOBS3.keys() :
chance = MOBS3[npcId]
drop = 2
elif npcId in MOBS4.keys() :
chance = MOBS4[npcId]
drop = 3
elif npcId in MOBS5.keys() :
chance = MOBS5[npcId]
drop = 4
elif npcId in MOBSspecial.keys() :
chance,drop = MOBSspecial[npcId]
if st.getRandom(1000) <= chance :
drop += 1
if drop != 0 :
st.giveItems(SWEET_FLUID,drop*int(Config.RATE_QUEST_DROP))
st.playSound("ItemSound.quest_itemget")
return
QUEST = Quest(426,qn,"Quest for Fishing Shot")
for npc in range(31562,31580)+[31616,31696,31697,32348,31989,32007,32348] :
QUEST.addStartNpc(npc)
QUEST.addTalkId(npc)
for mob in MOBS1.keys():
QUEST.addKillId(mob)
for mob in KAMAELmobs.keys():
QUEST.addKillId(mob)
for mob in MOBS2.keys():
QUEST.addKillId(mob)
for mob in MOBS3.keys():
QUEST.addKillId(mob)
for mob in MOBS4.keys():
QUEST.addKillId(mob)
for mob in MOBS5.keys():
QUEST.addKillId(mob)
for mob in MOBSspecial.keys():
QUEST.addKillId(mob) | 0.204501 | 0.24907 |
#input modules
import datetime
#imports
from flask_restful import Resource
from flask import request, make_response, jsonify
#local import
from app.api.v2.utilis.validations import CheckData
from app.api.v2.models.questions import QuestionsModel
from app.api.v2.models.meetup import MeetUp
#error messages
empty_question_title = "Question title empty. Please input data"
empty_question_body = "Question body empty. Please input data"
class PostQuestion(Resource):
"""post question class"""
def post(self, m_id):
try:
data = request.get_json()
question_body = data['question_body']
question_title = data['question_title']
meetup_id = m_id
user_id = 1
votes = 0
question = {
"question_body":question_body,
"question_title":question_title,
"meetup_id": meetup_id,
"user_id":user_id,
"votes":votes
}
if len(question_title)== 0:
return make_response(jsonify({"message": empty_question_title}),400)
if len(question_body)== 0:
return make_response(jsonify({"message": empty_question_body }),400)
question_data = QuestionsModel(**question)
saved = question_data.post_question_db()
question_id = saved
resp = {
"message": "Question successfully posted",
"username": question_body,
"question_id": "{}".format(question_id)
}
if saved == True:
return make_response(jsonify({"Message":"Question already exist"}),409)
return resp, 201
except KeyError:
return make_response(jsonify({"status":400, "message": "Missing either Question body or Question title input"}),400)
class GetQuestionsMeetup(Resource):
def get(self, m_id):
questions = QuestionsModel()
meetup_id = questions.check_meetup_id(m_id)
single_meetup_questions= questions.get_questions(m_id)
resp = {
"status":200,
"message":"all meetups",
"data":[{
"meetups": single_meetup_questions
}]
}
if not meetup_id:
return make_response(jsonify({"Message":"Meetup id not found"}),404)
return resp
class GetSingleQuestion(Resource):
"""get single question class"""
def get(self, m_id, q_id ):
single_question = QuestionsModel()
one_meetup_questions= single_question.get_specificquestion(m_id, q_id)
resp = {
"status":200,
"message":"all meetups",
"data":[{
"meetups": str(one_meetup_questions)
}]
}
return resp,200
class UpvoteQuestion(Resource):
"""upvote question class"""
@staticmethod
def patch(m_id, q_id):
upvoted = QuestionsModel().upvote_question(m_id, q_id)
question_id, question_createdon, question_title, question_body, question_votes= upvoted
resp = {
"id":question_id,
"createdon": question_createdon,
"question_meetup_id":question_body,
"question_title":question_title,
"question_body":question_body,
"votes":question_votes
}
print(resp)
class DownVoteQuestion(Resource):
"""downvote question class"""
def __init__(self):
pass | app/api/v2/views/questionsviews.py | #input modules
import datetime
#imports
from flask_restful import Resource
from flask import request, make_response, jsonify
#local import
from app.api.v2.utilis.validations import CheckData
from app.api.v2.models.questions import QuestionsModel
from app.api.v2.models.meetup import MeetUp
#error messages
empty_question_title = "Question title empty. Please input data"
empty_question_body = "Question body empty. Please input data"
class PostQuestion(Resource):
"""post question class"""
def post(self, m_id):
try:
data = request.get_json()
question_body = data['question_body']
question_title = data['question_title']
meetup_id = m_id
user_id = 1
votes = 0
question = {
"question_body":question_body,
"question_title":question_title,
"meetup_id": meetup_id,
"user_id":user_id,
"votes":votes
}
if len(question_title)== 0:
return make_response(jsonify({"message": empty_question_title}),400)
if len(question_body)== 0:
return make_response(jsonify({"message": empty_question_body }),400)
question_data = QuestionsModel(**question)
saved = question_data.post_question_db()
question_id = saved
resp = {
"message": "Question successfully posted",
"username": question_body,
"question_id": "{}".format(question_id)
}
if saved == True:
return make_response(jsonify({"Message":"Question already exist"}),409)
return resp, 201
except KeyError:
return make_response(jsonify({"status":400, "message": "Missing either Question body or Question title input"}),400)
class GetQuestionsMeetup(Resource):
def get(self, m_id):
questions = QuestionsModel()
meetup_id = questions.check_meetup_id(m_id)
single_meetup_questions= questions.get_questions(m_id)
resp = {
"status":200,
"message":"all meetups",
"data":[{
"meetups": single_meetup_questions
}]
}
if not meetup_id:
return make_response(jsonify({"Message":"Meetup id not found"}),404)
return resp
class GetSingleQuestion(Resource):
"""get single question class"""
def get(self, m_id, q_id ):
single_question = QuestionsModel()
one_meetup_questions= single_question.get_specificquestion(m_id, q_id)
resp = {
"status":200,
"message":"all meetups",
"data":[{
"meetups": str(one_meetup_questions)
}]
}
return resp,200
class UpvoteQuestion(Resource):
"""upvote question class"""
@staticmethod
def patch(m_id, q_id):
upvoted = QuestionsModel().upvote_question(m_id, q_id)
question_id, question_createdon, question_title, question_body, question_votes= upvoted
resp = {
"id":question_id,
"createdon": question_createdon,
"question_meetup_id":question_body,
"question_title":question_title,
"question_body":question_body,
"votes":question_votes
}
print(resp)
class DownVoteQuestion(Resource):
"""downvote question class"""
def __init__(self):
pass | 0.218003 | 0.167185 |
from abc import ABC, abstractmethod
from typing import Dict, Generic, Iterable, Optional, TypeVar, Union
VT = Union[
str, int, float, bool, "Config", Dict[str, Union[str, int, float, bool]]
]
FT = TypeVar("FT", bound="VT")
RawConfig = Dict[str, VT]
class Field(ABC, Generic[FT]):
def __init__(
self,
*,
default: Optional[FT] = None,
key: Optional[str] = None,
env: Optional[str] = None,
path: Optional[str] = None,
consul_path: Optional[str] = None,
vault_path: Optional[str] = None,
readonly: bool = False,
) -> None:
self.env = env
self.key = key
self.path = path
self.consul_path = consul_path
self.vault_path = vault_path
self.readonly = readonly
self.value: Optional[FT] = default
def get_value(self) -> Optional[FT]:
return self.value
@abstractmethod
def normalize(self, value: VT) -> FT:
pass # pragma: no cover
def validate(self, value: FT) -> bool:
return True
def load_from_dict(self, raw: RawConfig) -> Optional[FT]:
normalized = None
if self.key and self.key in raw:
normalized = self.normalize(raw[self.key])
self.validate(normalized)
return normalized
class ValueProvider(ABC):
@abstractmethod
def load(self, field: Field) -> Optional[str]:
pass # pragma: no cover
class BaseConfig(type):
def __new__(cls, name, bases, attrs):
fields: Dict[str, Field] = {}
for base_cls in bases:
for field_name, field in base_cls.__fields__.items():
if field_name not in attrs:
attrs[field_name] = field
for field_name, field in iter(attrs.items()):
if isinstance(field, Field):
if not field.key:
field.key = field_name
if not field.env:
field.env = field_name.upper()
fields[field_name] = field
for field_name in iter(fields.keys()):
del attrs[field_name]
attrs["__fields__"] = fields
return super(BaseConfig, cls).__new__(cls, name, bases, attrs)
class Config(metaclass=BaseConfig):
__dict__: Dict[str, Optional[VT]]
__fields__: Dict[str, Field]
def __init__(self, defaults: Optional[RawConfig] = None) -> None:
for field_name, field in iter(self.__fields__.items()):
self.__dict__[field_name] = field.get_value()
if defaults:
self.load_from_dict(defaults)
def __getattr__(self, item: str) -> Optional[VT]:
return self.__dict__[item]
def __setattr__(self, name: str, value: Optional[VT]) -> None:
if name in self.__fields__:
field = self.__fields__.get(name)
if field:
normalized = field.normalize(value) # type: ignore
field.validate(normalized)
self.__dict__[name] = normalized
def load(self, providers: Iterable[ValueProvider]) -> None:
for field_name, field in iter(self.__fields__.items()):
for provider in providers:
value = provider.load(field)
setattr(self, field_name, value)
def load_from_dict(self, raw: RawConfig) -> None:
for field_name, field in iter(self.__fields__.items()):
value = field.load_from_dict(raw)
if value:
setattr(self, field_name, value) | src/config/abc.py | from abc import ABC, abstractmethod
from typing import Dict, Generic, Iterable, Optional, TypeVar, Union
VT = Union[
str, int, float, bool, "Config", Dict[str, Union[str, int, float, bool]]
]
FT = TypeVar("FT", bound="VT")
RawConfig = Dict[str, VT]
class Field(ABC, Generic[FT]):
def __init__(
self,
*,
default: Optional[FT] = None,
key: Optional[str] = None,
env: Optional[str] = None,
path: Optional[str] = None,
consul_path: Optional[str] = None,
vault_path: Optional[str] = None,
readonly: bool = False,
) -> None:
self.env = env
self.key = key
self.path = path
self.consul_path = consul_path
self.vault_path = vault_path
self.readonly = readonly
self.value: Optional[FT] = default
def get_value(self) -> Optional[FT]:
return self.value
@abstractmethod
def normalize(self, value: VT) -> FT:
pass # pragma: no cover
def validate(self, value: FT) -> bool:
return True
def load_from_dict(self, raw: RawConfig) -> Optional[FT]:
normalized = None
if self.key and self.key in raw:
normalized = self.normalize(raw[self.key])
self.validate(normalized)
return normalized
class ValueProvider(ABC):
@abstractmethod
def load(self, field: Field) -> Optional[str]:
pass # pragma: no cover
class BaseConfig(type):
def __new__(cls, name, bases, attrs):
fields: Dict[str, Field] = {}
for base_cls in bases:
for field_name, field in base_cls.__fields__.items():
if field_name not in attrs:
attrs[field_name] = field
for field_name, field in iter(attrs.items()):
if isinstance(field, Field):
if not field.key:
field.key = field_name
if not field.env:
field.env = field_name.upper()
fields[field_name] = field
for field_name in iter(fields.keys()):
del attrs[field_name]
attrs["__fields__"] = fields
return super(BaseConfig, cls).__new__(cls, name, bases, attrs)
class Config(metaclass=BaseConfig):
__dict__: Dict[str, Optional[VT]]
__fields__: Dict[str, Field]
def __init__(self, defaults: Optional[RawConfig] = None) -> None:
for field_name, field in iter(self.__fields__.items()):
self.__dict__[field_name] = field.get_value()
if defaults:
self.load_from_dict(defaults)
def __getattr__(self, item: str) -> Optional[VT]:
return self.__dict__[item]
def __setattr__(self, name: str, value: Optional[VT]) -> None:
if name in self.__fields__:
field = self.__fields__.get(name)
if field:
normalized = field.normalize(value) # type: ignore
field.validate(normalized)
self.__dict__[name] = normalized
def load(self, providers: Iterable[ValueProvider]) -> None:
for field_name, field in iter(self.__fields__.items()):
for provider in providers:
value = provider.load(field)
setattr(self, field_name, value)
def load_from_dict(self, raw: RawConfig) -> None:
for field_name, field in iter(self.__fields__.items()):
value = field.load_from_dict(raw)
if value:
setattr(self, field_name, value) | 0.92058 | 0.226249 |
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class AmiFromInstance(pulumi.CustomResource):
architecture: pulumi.Output[str]
"""
Machine architecture for created instances. Defaults to "x86_64".
"""
description: pulumi.Output[str]
"""
A longer, human-readable description for the AMI.
"""
ebs_block_devices: pulumi.Output[list]
"""
Nested block describing an EBS block device that should be
attached to created instances. The structure of this block is described below.
"""
ena_support: pulumi.Output[bool]
"""
Specifies whether enhanced networking with ENA is enabled. Defaults to `false`.
"""
ephemeral_block_devices: pulumi.Output[list]
"""
Nested block describing an ephemeral block device that
should be attached to created instances. The structure of this block is described below.
"""
image_location: pulumi.Output[str]
"""
Path to an S3 object containing an image manifest, e.g. created
by the `ec2-upload-bundle` command in the EC2 command line tools.
"""
kernel_id: pulumi.Output[str]
"""
The id of the kernel image (AKI) that will be used as the paravirtual
kernel in created instances.
"""
manage_ebs_snapshots: pulumi.Output[bool]
name: pulumi.Output[str]
"""
A region-unique name for the AMI.
"""
ramdisk_id: pulumi.Output[str]
"""
The id of an initrd image (ARI) that will be used when booting the
created instances.
"""
root_device_name: pulumi.Output[str]
"""
The name of the root device (for example, `/dev/sda1`, or `/dev/xvda`).
"""
root_snapshot_id: pulumi.Output[str]
snapshot_without_reboot: pulumi.Output[bool]
"""
Boolean that overrides the behavior of stopping
the instance before snapshotting. This is risky since it may cause a snapshot of an
inconsistent filesystem state, but can be used to avoid downtime if the user otherwise
guarantees that no filesystem writes will be underway at the time of snapshot.
"""
source_instance_id: pulumi.Output[str]
"""
The id of the instance to use as the basis of the AMI.
"""
sriov_net_support: pulumi.Output[str]
"""
When set to "simple" (the default), enables enhanced networking
for created instances. No other value is supported at this time.
"""
tags: pulumi.Output[dict]
"""
A mapping of tags to assign to the resource.
"""
virtualization_type: pulumi.Output[str]
"""
Keyword to choose what virtualization mode created instances
will use. Can be either "paravirtual" (the default) or "hvm". The choice of virtualization type
changes the set of further arguments that are required, as described below.
"""
def __init__(__self__, resource_name, opts=None, description=None, ebs_block_devices=None, ephemeral_block_devices=None, name=None, snapshot_without_reboot=None, source_instance_id=None, tags=None, __name__=None, __opts__=None):
"""
The "AMI from instance" resource allows the creation of an Amazon Machine
Image (AMI) modelled after an existing EBS-backed EC2 instance.
The created AMI will refer to implicitly-created snapshots of the instance's
EBS volumes and mimick its assigned block device configuration at the time
the resource is created.
This resource is best applied to an instance that is stopped when this instance
is created, so that the contents of the created image are predictable. When
applied to an instance that is running, *the instance will be stopped before taking
the snapshots and then started back up again*, resulting in a period of
downtime.
Note that the source instance is inspected only at the initial creation of this
resource. Ongoing updates to the referenced instance will not be propagated into
the generated AMI. Users may taint or otherwise recreate the resource in order
to produce a fresh snapshot.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] description: A longer, human-readable description for the AMI.
:param pulumi.Input[list] ebs_block_devices: Nested block describing an EBS block device that should be
attached to created instances. The structure of this block is described below.
:param pulumi.Input[list] ephemeral_block_devices: Nested block describing an ephemeral block device that
should be attached to created instances. The structure of this block is described below.
:param pulumi.Input[str] name: A region-unique name for the AMI.
:param pulumi.Input[bool] snapshot_without_reboot: Boolean that overrides the behavior of stopping
the instance before snapshotting. This is risky since it may cause a snapshot of an
inconsistent filesystem state, but can be used to avoid downtime if the user otherwise
guarantees that no filesystem writes will be underway at the time of snapshot.
:param pulumi.Input[str] source_instance_id: The id of the instance to use as the basis of the AMI.
:param pulumi.Input[dict] tags: A mapping of tags to assign to the resource.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if not resource_name:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(resource_name, str):
raise TypeError('Expected resource name to be a string')
if opts and not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
__props__['description'] = description
__props__['ebs_block_devices'] = ebs_block_devices
__props__['ephemeral_block_devices'] = ephemeral_block_devices
__props__['name'] = name
__props__['snapshot_without_reboot'] = snapshot_without_reboot
if source_instance_id is None:
raise TypeError("Missing required property 'source_instance_id'")
__props__['source_instance_id'] = source_instance_id
__props__['tags'] = tags
__props__['architecture'] = None
__props__['ena_support'] = None
__props__['image_location'] = None
__props__['kernel_id'] = None
__props__['manage_ebs_snapshots'] = None
__props__['ramdisk_id'] = None
__props__['root_device_name'] = None
__props__['root_snapshot_id'] = None
__props__['sriov_net_support'] = None
__props__['virtualization_type'] = None
super(AmiFromInstance, __self__).__init__(
'aws:ec2/amiFromInstance:AmiFromInstance',
resource_name,
__props__,
opts)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop | sdk/python/pulumi_aws/ec2/ami_from_instance.py |
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class AmiFromInstance(pulumi.CustomResource):
architecture: pulumi.Output[str]
"""
Machine architecture for created instances. Defaults to "x86_64".
"""
description: pulumi.Output[str]
"""
A longer, human-readable description for the AMI.
"""
ebs_block_devices: pulumi.Output[list]
"""
Nested block describing an EBS block device that should be
attached to created instances. The structure of this block is described below.
"""
ena_support: pulumi.Output[bool]
"""
Specifies whether enhanced networking with ENA is enabled. Defaults to `false`.
"""
ephemeral_block_devices: pulumi.Output[list]
"""
Nested block describing an ephemeral block device that
should be attached to created instances. The structure of this block is described below.
"""
image_location: pulumi.Output[str]
"""
Path to an S3 object containing an image manifest, e.g. created
by the `ec2-upload-bundle` command in the EC2 command line tools.
"""
kernel_id: pulumi.Output[str]
"""
The id of the kernel image (AKI) that will be used as the paravirtual
kernel in created instances.
"""
manage_ebs_snapshots: pulumi.Output[bool]
name: pulumi.Output[str]
"""
A region-unique name for the AMI.
"""
ramdisk_id: pulumi.Output[str]
"""
The id of an initrd image (ARI) that will be used when booting the
created instances.
"""
root_device_name: pulumi.Output[str]
"""
The name of the root device (for example, `/dev/sda1`, or `/dev/xvda`).
"""
root_snapshot_id: pulumi.Output[str]
snapshot_without_reboot: pulumi.Output[bool]
"""
Boolean that overrides the behavior of stopping
the instance before snapshotting. This is risky since it may cause a snapshot of an
inconsistent filesystem state, but can be used to avoid downtime if the user otherwise
guarantees that no filesystem writes will be underway at the time of snapshot.
"""
source_instance_id: pulumi.Output[str]
"""
The id of the instance to use as the basis of the AMI.
"""
sriov_net_support: pulumi.Output[str]
"""
When set to "simple" (the default), enables enhanced networking
for created instances. No other value is supported at this time.
"""
tags: pulumi.Output[dict]
"""
A mapping of tags to assign to the resource.
"""
virtualization_type: pulumi.Output[str]
"""
Keyword to choose what virtualization mode created instances
will use. Can be either "paravirtual" (the default) or "hvm". The choice of virtualization type
changes the set of further arguments that are required, as described below.
"""
def __init__(__self__, resource_name, opts=None, description=None, ebs_block_devices=None, ephemeral_block_devices=None, name=None, snapshot_without_reboot=None, source_instance_id=None, tags=None, __name__=None, __opts__=None):
"""
The "AMI from instance" resource allows the creation of an Amazon Machine
Image (AMI) modelled after an existing EBS-backed EC2 instance.
The created AMI will refer to implicitly-created snapshots of the instance's
EBS volumes and mimick its assigned block device configuration at the time
the resource is created.
This resource is best applied to an instance that is stopped when this instance
is created, so that the contents of the created image are predictable. When
applied to an instance that is running, *the instance will be stopped before taking
the snapshots and then started back up again*, resulting in a period of
downtime.
Note that the source instance is inspected only at the initial creation of this
resource. Ongoing updates to the referenced instance will not be propagated into
the generated AMI. Users may taint or otherwise recreate the resource in order
to produce a fresh snapshot.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] description: A longer, human-readable description for the AMI.
:param pulumi.Input[list] ebs_block_devices: Nested block describing an EBS block device that should be
attached to created instances. The structure of this block is described below.
:param pulumi.Input[list] ephemeral_block_devices: Nested block describing an ephemeral block device that
should be attached to created instances. The structure of this block is described below.
:param pulumi.Input[str] name: A region-unique name for the AMI.
:param pulumi.Input[bool] snapshot_without_reboot: Boolean that overrides the behavior of stopping
the instance before snapshotting. This is risky since it may cause a snapshot of an
inconsistent filesystem state, but can be used to avoid downtime if the user otherwise
guarantees that no filesystem writes will be underway at the time of snapshot.
:param pulumi.Input[str] source_instance_id: The id of the instance to use as the basis of the AMI.
:param pulumi.Input[dict] tags: A mapping of tags to assign to the resource.
"""
if __name__ is not None:
warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
resource_name = __name__
if __opts__ is not None:
warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
opts = __opts__
if not resource_name:
raise TypeError('Missing resource name argument (for URN creation)')
if not isinstance(resource_name, str):
raise TypeError('Expected resource name to be a string')
if opts and not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
__props__ = dict()
__props__['description'] = description
__props__['ebs_block_devices'] = ebs_block_devices
__props__['ephemeral_block_devices'] = ephemeral_block_devices
__props__['name'] = name
__props__['snapshot_without_reboot'] = snapshot_without_reboot
if source_instance_id is None:
raise TypeError("Missing required property 'source_instance_id'")
__props__['source_instance_id'] = source_instance_id
__props__['tags'] = tags
__props__['architecture'] = None
__props__['ena_support'] = None
__props__['image_location'] = None
__props__['kernel_id'] = None
__props__['manage_ebs_snapshots'] = None
__props__['ramdisk_id'] = None
__props__['root_device_name'] = None
__props__['root_snapshot_id'] = None
__props__['sriov_net_support'] = None
__props__['virtualization_type'] = None
super(AmiFromInstance, __self__).__init__(
'aws:ec2/amiFromInstance:AmiFromInstance',
resource_name,
__props__,
opts)
def translate_output_property(self, prop):
return tables._CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop
def translate_input_property(self, prop):
return tables._SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop | 0.672547 | 0.173183 |
from __future__ import print_function
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.datasets import fetch_20newsgroups
from sklearn.datasets.twenty_newsgroups import strip_newsgroup_footer
from sklearn.datasets.twenty_newsgroups import strip_newsgroup_quoting
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.svm import LinearSVC
class TextStats(BaseEstimator, TransformerMixin):
"""Extract features from each document for DictVectorizer"""
def fit(self, x, y=None):
return self
def transform(self, posts):
return [{'length': len(text),
'num_sentences': text.count('.')}
for text in posts]
class SubjectBodyExtractor(BaseEstimator, TransformerMixin):
"""Extract the subject & body from a usenet post in a single pass.
Takes a sequence of strings and produces a dict of sequences. Keys are
`subject` and `body`.
"""
def fit(self, x, y=None):
return self
def transform(self, posts):
# construct object dtype array with two columns
# first column = 'subject' and second column = 'body'
features = np.empty(shape=(len(posts), 2), dtype=object)
for i, text in enumerate(posts):
headers, _, bod = text.partition('\n\n')
bod = strip_newsgroup_footer(bod)
bod = strip_newsgroup_quoting(bod)
features[i, 1] = bod
prefix = 'Subject:'
sub = ''
for line in headers.split('\n'):
if line.startswith(prefix):
sub = line[len(prefix):]
break
features[i, 0] = sub
return features
pipeline = Pipeline([
# Extract the subject & body
('subjectbody', SubjectBodyExtractor()),
# Use ColumnTransformer to combine the features from subject and body
('union', ColumnTransformer(
[
# Pulling features from the post's subject line (first column)
('subject', TfidfVectorizer(min_df=50), 0),
# Pipeline for standard bag-of-words model for body (second column)
('body_bow', Pipeline([
('tfidf', TfidfVectorizer()),
('best', TruncatedSVD(n_components=50)),
]), 1),
# Pipeline for pulling ad hoc features from post's body
('body_stats', Pipeline([
('stats', TextStats()), # returns a list of dicts
('vect', DictVectorizer()), # list of dicts -> feature matrix
]), 1),
],
# weight components in ColumnTransformer
transformer_weights={
'subject': 0.8,
'body_bow': 0.5,
'body_stats': 1.0,
}
)),
# Use a SVC classifier on the combined features
('svc', LinearSVC()),
])
# limit the list of categories to make running this example faster.
categories = ['alt.atheism', 'talk.religion.misc']
train = fetch_20newsgroups(random_state=1,
subset='train',
categories=categories,
)
test = fetch_20newsgroups(random_state=1,
subset='test',
categories=categories,
)
pipeline.fit(train.data, train.target)
y = pipeline.predict(test.data)
print(classification_report(y, test.target)) | examples/compose/plot_column_transformer.py | from __future__ import print_function
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.datasets import fetch_20newsgroups
from sklearn.datasets.twenty_newsgroups import strip_newsgroup_footer
from sklearn.datasets.twenty_newsgroups import strip_newsgroup_quoting
from sklearn.decomposition import TruncatedSVD
from sklearn.feature_extraction import DictVectorizer
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.compose import ColumnTransformer
from sklearn.svm import LinearSVC
class TextStats(BaseEstimator, TransformerMixin):
"""Extract features from each document for DictVectorizer"""
def fit(self, x, y=None):
return self
def transform(self, posts):
return [{'length': len(text),
'num_sentences': text.count('.')}
for text in posts]
class SubjectBodyExtractor(BaseEstimator, TransformerMixin):
"""Extract the subject & body from a usenet post in a single pass.
Takes a sequence of strings and produces a dict of sequences. Keys are
`subject` and `body`.
"""
def fit(self, x, y=None):
return self
def transform(self, posts):
# construct object dtype array with two columns
# first column = 'subject' and second column = 'body'
features = np.empty(shape=(len(posts), 2), dtype=object)
for i, text in enumerate(posts):
headers, _, bod = text.partition('\n\n')
bod = strip_newsgroup_footer(bod)
bod = strip_newsgroup_quoting(bod)
features[i, 1] = bod
prefix = 'Subject:'
sub = ''
for line in headers.split('\n'):
if line.startswith(prefix):
sub = line[len(prefix):]
break
features[i, 0] = sub
return features
pipeline = Pipeline([
# Extract the subject & body
('subjectbody', SubjectBodyExtractor()),
# Use ColumnTransformer to combine the features from subject and body
('union', ColumnTransformer(
[
# Pulling features from the post's subject line (first column)
('subject', TfidfVectorizer(min_df=50), 0),
# Pipeline for standard bag-of-words model for body (second column)
('body_bow', Pipeline([
('tfidf', TfidfVectorizer()),
('best', TruncatedSVD(n_components=50)),
]), 1),
# Pipeline for pulling ad hoc features from post's body
('body_stats', Pipeline([
('stats', TextStats()), # returns a list of dicts
('vect', DictVectorizer()), # list of dicts -> feature matrix
]), 1),
],
# weight components in ColumnTransformer
transformer_weights={
'subject': 0.8,
'body_bow': 0.5,
'body_stats': 1.0,
}
)),
# Use a SVC classifier on the combined features
('svc', LinearSVC()),
])
# limit the list of categories to make running this example faster.
categories = ['alt.atheism', 'talk.religion.misc']
train = fetch_20newsgroups(random_state=1,
subset='train',
categories=categories,
)
test = fetch_20newsgroups(random_state=1,
subset='test',
categories=categories,
)
pipeline.fit(train.data, train.target)
y = pipeline.predict(test.data)
print(classification_report(y, test.target)) | 0.851614 | 0.499451 |
import os
import os.path
import copy
import hashlib
import errno
import numpy as np
from numpy.testing import assert_array_almost_equal
def check_integrity(fpath, md5):
if not os.path.isfile(fpath):
return False
md5o = hashlib.md5()
with open(fpath, 'rb') as f:
# read in 1MB chunks
for chunk in iter(lambda: f.read(1024 * 1024), b''):
md5o.update(chunk)
md5c = md5o.hexdigest()
if md5c != md5:
return False
return True
def download_url(url, root, filename, md5):
from six.moves import urllib
root = os.path.expanduser(root)
fpath = os.path.join(root, filename)
try:
os.makedirs(root)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
# downloads file
if os.path.isfile(fpath) and check_integrity(fpath, md5):
print('Using downloaded and verified file: ' + fpath)
else:
try:
print('Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
except:
if url[:5] == 'https':
url = url.replace('https:', 'http:')
print('Failed download. Trying https -> http instead.'
' Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
def list_dir(root, prefix=False):
"""List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
"""
root = os.path.expanduser(root)
directories = list(
filter(
lambda p: os.path.isdir(os.path.join(root, p)),
os.listdir(root)
)
)
if prefix is True:
directories = [os.path.join(root, d) for d in directories]
return directories
def list_files(root, suffix, prefix=False):
"""List all files ending with a suffix at a given root
Args:
root (str): Path to directory whose folders need to be listed
suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
It uses the Python "str.endswith" method and is passed directly
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the files found
"""
root = os.path.expanduser(root)
files = list(
filter(
lambda p: os.path.isfile(os.path.join(root, p)) and p.endswith(suffix),
os.listdir(root)
)
)
if prefix is True:
files = [os.path.join(root, d) for d in files]
return files
# basic function
def multiclass_noisify(y, P, random_state=0):
""" Flip classes according to transition probability matrix T.
It expects a number between 0 and the number of classes - 1.
"""
print (np.max(y), P.shape[0])
assert P.shape[0] == P.shape[1]
assert np.max(y) < P.shape[0]
# row stochastic matrix
assert_array_almost_equal(P.sum(axis=1), np.ones(P.shape[1]))
assert (P >= 0.0).all()
m = y.shape[0]
print (m)
new_y = y.copy()
flipper = np.random.RandomState(random_state)
for idx in np.arange(m):
i = y[idx]
# draw a vector with only an 1
flipped = flipper.multinomial(1, P[i, :][0], 1)[0]
new_y[idx] = np.where(flipped == 1)[0]
return new_y
# noisify_pairflip call the function "multiclass_noisify"
def noisify_pairflip(y_train, noise, random_state=None, nb_classes=10):
"""mistakes:
flip in the pair
"""
P = np.eye(nb_classes)
n = noise
if n > 0.0:
# 0 -> 1
P[0, 0], P[0, 1] = 1. - n, n
for i in range(1, nb_classes-1):
P[i, i], P[i, i + 1] = 1. - n, n
P[nb_classes-1, nb_classes-1], P[nb_classes-1, 0] = 1. - n, n
y_train_noisy = multiclass_noisify(y_train, P=P,
random_state=random_state)
actual_noise = (y_train_noisy != y_train).mean()
assert actual_noise > 0.0
print('Actual noise %.2f' % actual_noise)
y_train = y_train_noisy
print (P)
return y_train, actual_noise
def noisify_multiclass_symmetric(y_train, noise, random_state=None, nb_classes=10):
"""mistakes:
flip in the symmetric way
"""
P = np.ones((nb_classes, nb_classes))
n = noise
P = (n / (nb_classes - 1)) * P
if n > 0.0:
# 0 -> 1
P[0, 0] = 1. - n
for i in range(1, nb_classes-1):
P[i, i] = 1. - n
P[nb_classes-1, nb_classes-1] = 1. - n
y_train_noisy = multiclass_noisify(y_train, P=P,
random_state=random_state)
actual_noise = (y_train_noisy != y_train).mean()
assert actual_noise > 0.0
print('Actual noise %.2f' % actual_noise)
y_train = y_train_noisy
print (P)
return y_train, actual_noise
def noisify(dataset='mnist', nb_classes=10, train_labels=None, noise_type=None, noise_rate=0, random_state=0):
if noise_type == 'pairflip':
train_noisy_labels, actual_noise_rate = noisify_pairflip(train_labels, noise_rate, random_state=0, nb_classes=nb_classes)
if noise_type == 'symmetric':
train_noisy_labels, actual_noise_rate = noisify_multiclass_symmetric(train_labels, noise_rate, random_state=0, nb_classes=nb_classes)
return train_noisy_labels, actual_noise_rate | code/data/data_util.py | import os
import os.path
import copy
import hashlib
import errno
import numpy as np
from numpy.testing import assert_array_almost_equal
def check_integrity(fpath, md5):
if not os.path.isfile(fpath):
return False
md5o = hashlib.md5()
with open(fpath, 'rb') as f:
# read in 1MB chunks
for chunk in iter(lambda: f.read(1024 * 1024), b''):
md5o.update(chunk)
md5c = md5o.hexdigest()
if md5c != md5:
return False
return True
def download_url(url, root, filename, md5):
from six.moves import urllib
root = os.path.expanduser(root)
fpath = os.path.join(root, filename)
try:
os.makedirs(root)
except OSError as e:
if e.errno == errno.EEXIST:
pass
else:
raise
# downloads file
if os.path.isfile(fpath) and check_integrity(fpath, md5):
print('Using downloaded and verified file: ' + fpath)
else:
try:
print('Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
except:
if url[:5] == 'https':
url = url.replace('https:', 'http:')
print('Failed download. Trying https -> http instead.'
' Downloading ' + url + ' to ' + fpath)
urllib.request.urlretrieve(url, fpath)
def list_dir(root, prefix=False):
"""List all directories at a given root
Args:
root (str): Path to directory whose folders need to be listed
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the directories found
"""
root = os.path.expanduser(root)
directories = list(
filter(
lambda p: os.path.isdir(os.path.join(root, p)),
os.listdir(root)
)
)
if prefix is True:
directories = [os.path.join(root, d) for d in directories]
return directories
def list_files(root, suffix, prefix=False):
"""List all files ending with a suffix at a given root
Args:
root (str): Path to directory whose folders need to be listed
suffix (str or tuple): Suffix of the files to match, e.g. '.png' or ('.jpg', '.png').
It uses the Python "str.endswith" method and is passed directly
prefix (bool, optional): If true, prepends the path to each result, otherwise
only returns the name of the files found
"""
root = os.path.expanduser(root)
files = list(
filter(
lambda p: os.path.isfile(os.path.join(root, p)) and p.endswith(suffix),
os.listdir(root)
)
)
if prefix is True:
files = [os.path.join(root, d) for d in files]
return files
# basic function
def multiclass_noisify(y, P, random_state=0):
""" Flip classes according to transition probability matrix T.
It expects a number between 0 and the number of classes - 1.
"""
print (np.max(y), P.shape[0])
assert P.shape[0] == P.shape[1]
assert np.max(y) < P.shape[0]
# row stochastic matrix
assert_array_almost_equal(P.sum(axis=1), np.ones(P.shape[1]))
assert (P >= 0.0).all()
m = y.shape[0]
print (m)
new_y = y.copy()
flipper = np.random.RandomState(random_state)
for idx in np.arange(m):
i = y[idx]
# draw a vector with only an 1
flipped = flipper.multinomial(1, P[i, :][0], 1)[0]
new_y[idx] = np.where(flipped == 1)[0]
return new_y
# noisify_pairflip call the function "multiclass_noisify"
def noisify_pairflip(y_train, noise, random_state=None, nb_classes=10):
"""mistakes:
flip in the pair
"""
P = np.eye(nb_classes)
n = noise
if n > 0.0:
# 0 -> 1
P[0, 0], P[0, 1] = 1. - n, n
for i in range(1, nb_classes-1):
P[i, i], P[i, i + 1] = 1. - n, n
P[nb_classes-1, nb_classes-1], P[nb_classes-1, 0] = 1. - n, n
y_train_noisy = multiclass_noisify(y_train, P=P,
random_state=random_state)
actual_noise = (y_train_noisy != y_train).mean()
assert actual_noise > 0.0
print('Actual noise %.2f' % actual_noise)
y_train = y_train_noisy
print (P)
return y_train, actual_noise
def noisify_multiclass_symmetric(y_train, noise, random_state=None, nb_classes=10):
"""mistakes:
flip in the symmetric way
"""
P = np.ones((nb_classes, nb_classes))
n = noise
P = (n / (nb_classes - 1)) * P
if n > 0.0:
# 0 -> 1
P[0, 0] = 1. - n
for i in range(1, nb_classes-1):
P[i, i] = 1. - n
P[nb_classes-1, nb_classes-1] = 1. - n
y_train_noisy = multiclass_noisify(y_train, P=P,
random_state=random_state)
actual_noise = (y_train_noisy != y_train).mean()
assert actual_noise > 0.0
print('Actual noise %.2f' % actual_noise)
y_train = y_train_noisy
print (P)
return y_train, actual_noise
def noisify(dataset='mnist', nb_classes=10, train_labels=None, noise_type=None, noise_rate=0, random_state=0):
if noise_type == 'pairflip':
train_noisy_labels, actual_noise_rate = noisify_pairflip(train_labels, noise_rate, random_state=0, nb_classes=nb_classes)
if noise_type == 'symmetric':
train_noisy_labels, actual_noise_rate = noisify_multiclass_symmetric(train_labels, noise_rate, random_state=0, nb_classes=nb_classes)
return train_noisy_labels, actual_noise_rate | 0.515864 | 0.472197 |
from functools import partial
from typing import Callable, Dict
from .. import core
from .. import linear_util as lu
from ..core import Trace, Tracer, new_master
from ..abstract_arrays import ShapedArray, raise_to_shaped
from ..util import safe_map, safe_zip, unzip2, unzip3
map = safe_map
zip = safe_zip
def identity(x): return x
### papply
def papply(fun, name, in_vals, axis_size):
# this function is for testing purposes, so we drop the out_axis
fun, _ = papply_transform(fun, name, axis_size)
return fun.call_wrapped(*in_vals)
@lu.transformation_with_aux
def papply_transform(name, axis_size, *args):
with new_master(PapplyTrace) as master:
trace = PapplyTrace(master, core.cur_sublevel())
in_tracers = map(partial(PapplyTracer, trace, name, axis_size, axis=0), args)
outs = yield in_tracers, {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_axes = unzip2((t.val, t.axis) for t in out_tracers)
del master, out_tracers
yield out_vals, out_axes
@lu.transformation_with_aux
def papply_subtrace(master, name, axis_size, axes, *vals):
trace = PapplyTrace(master, core.cur_sublevel())
outs = yield map(partial(PapplyTracer, trace, name, axis_size), vals, axes), {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_axes = unzip2((t.val, t.axis) for t in out_tracers)
yield out_vals, out_axes
# TODO(mattjj); use a special sentinel type rather than None
NotSharded = type(None)
not_sharded = None
class PapplyTracer(Tracer):
def __init__(self, trace, name, axis_size, val, axis):
self._trace = trace
self.name = name
self.axis_size = axis_size
self.val = val
self.axis = axis
@property
def aval(self):
aval = raise_to_shaped(core.get_aval(self.val))
if self.axis is not_sharded:
return aval
else:
if aval is core.abstract_unit:
return aval
elif type(aval) is ShapedArray:
assert 0 <= self.axis < aval.ndim + 1
new_shape = list(aval.shape)
new_shape.insert(self.axis, self.axis_size)
return ShapedArray(tuple(new_shape), aval.dtype)
else:
raise TypeError(aval)
def full_lower(self):
if self.axis is not_sharded:
return core.full_lower(self.val)
else:
return self
class PapplyTrace(Trace):
def pure(self, val):
return PapplyTracer(self, None, None, val, not_sharded)
def lift(self, val):
return PapplyTracer(self, None, None, val, not_sharded)
def sublift(self, val):
return PapplyTracer(self, val.name, val.axis_size, val.val, val.axis)
def process_primitive(self, primitive, tracers, params):
names, vals, axes = unzip3((t.name, t.val, t.axis) for t in tracers)
if all(axis is not_sharded for axis in axes):
return primitive.bind(*vals, **params)
else:
name, = {n for n in names if n is not None}
size, = {t.axis_size for t in tracers if t.axis_size is not None}
rule = papply_primitive_rules[primitive]
val_out, axis_out = rule(name, size, vals, axes, **params)
return PapplyTracer(self, name, size, val_out, axis_out)
def process_call(self, call_primitive, f: lu.WrappedFun, tracers, params):
names, vals, axes = unzip3((t.name, t.val, t.axis) for t in tracers)
if all(axis is not_sharded for axis in axes):
return call_primitive.bind(f, *vals, **params)
else:
name, = {n for n in names if n is not None}
size, = {t.axis_size for t in tracers if t.axis_size is not None}
f_papply, axes_out = papply_subtrace(f, self.master, name, size, axes)
vals_out = call_primitive.bind(f_papply, *vals, **params)
return [PapplyTracer(self, name, size, x, a)
for x, a in zip(vals_out, axes_out())]
def post_process_call(self, call_primitive, out_tracer):
t = out_tracer
name, val, axis, size = t.name, t.val, t.axis, t.axis_size
master = self.master
def todo(x):
trace = PapplyTrace(master, core.cur_sublevel())
return PapplyTracer(trace, name, size, x, axis)
return val, todo
papply_primitive_rules: Dict[core.Primitive, Callable] = {} | jax/interpreters/parallel.py |
from functools import partial
from typing import Callable, Dict
from .. import core
from .. import linear_util as lu
from ..core import Trace, Tracer, new_master
from ..abstract_arrays import ShapedArray, raise_to_shaped
from ..util import safe_map, safe_zip, unzip2, unzip3
map = safe_map
zip = safe_zip
def identity(x): return x
### papply
def papply(fun, name, in_vals, axis_size):
# this function is for testing purposes, so we drop the out_axis
fun, _ = papply_transform(fun, name, axis_size)
return fun.call_wrapped(*in_vals)
@lu.transformation_with_aux
def papply_transform(name, axis_size, *args):
with new_master(PapplyTrace) as master:
trace = PapplyTrace(master, core.cur_sublevel())
in_tracers = map(partial(PapplyTracer, trace, name, axis_size, axis=0), args)
outs = yield in_tracers, {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_axes = unzip2((t.val, t.axis) for t in out_tracers)
del master, out_tracers
yield out_vals, out_axes
@lu.transformation_with_aux
def papply_subtrace(master, name, axis_size, axes, *vals):
trace = PapplyTrace(master, core.cur_sublevel())
outs = yield map(partial(PapplyTracer, trace, name, axis_size), vals, axes), {}
out_tracers = map(trace.full_raise, outs)
out_vals, out_axes = unzip2((t.val, t.axis) for t in out_tracers)
yield out_vals, out_axes
# TODO(mattjj); use a special sentinel type rather than None
NotSharded = type(None)
not_sharded = None
class PapplyTracer(Tracer):
def __init__(self, trace, name, axis_size, val, axis):
self._trace = trace
self.name = name
self.axis_size = axis_size
self.val = val
self.axis = axis
@property
def aval(self):
aval = raise_to_shaped(core.get_aval(self.val))
if self.axis is not_sharded:
return aval
else:
if aval is core.abstract_unit:
return aval
elif type(aval) is ShapedArray:
assert 0 <= self.axis < aval.ndim + 1
new_shape = list(aval.shape)
new_shape.insert(self.axis, self.axis_size)
return ShapedArray(tuple(new_shape), aval.dtype)
else:
raise TypeError(aval)
def full_lower(self):
if self.axis is not_sharded:
return core.full_lower(self.val)
else:
return self
class PapplyTrace(Trace):
def pure(self, val):
return PapplyTracer(self, None, None, val, not_sharded)
def lift(self, val):
return PapplyTracer(self, None, None, val, not_sharded)
def sublift(self, val):
return PapplyTracer(self, val.name, val.axis_size, val.val, val.axis)
def process_primitive(self, primitive, tracers, params):
names, vals, axes = unzip3((t.name, t.val, t.axis) for t in tracers)
if all(axis is not_sharded for axis in axes):
return primitive.bind(*vals, **params)
else:
name, = {n for n in names if n is not None}
size, = {t.axis_size for t in tracers if t.axis_size is not None}
rule = papply_primitive_rules[primitive]
val_out, axis_out = rule(name, size, vals, axes, **params)
return PapplyTracer(self, name, size, val_out, axis_out)
def process_call(self, call_primitive, f: lu.WrappedFun, tracers, params):
names, vals, axes = unzip3((t.name, t.val, t.axis) for t in tracers)
if all(axis is not_sharded for axis in axes):
return call_primitive.bind(f, *vals, **params)
else:
name, = {n for n in names if n is not None}
size, = {t.axis_size for t in tracers if t.axis_size is not None}
f_papply, axes_out = papply_subtrace(f, self.master, name, size, axes)
vals_out = call_primitive.bind(f_papply, *vals, **params)
return [PapplyTracer(self, name, size, x, a)
for x, a in zip(vals_out, axes_out())]
def post_process_call(self, call_primitive, out_tracer):
t = out_tracer
name, val, axis, size = t.name, t.val, t.axis, t.axis_size
master = self.master
def todo(x):
trace = PapplyTrace(master, core.cur_sublevel())
return PapplyTracer(trace, name, size, x, axis)
return val, todo
papply_primitive_rules: Dict[core.Primitive, Callable] = {} | 0.565899 | 0.307943 |
from mqtt import MqttMessage, MqttConfigMessage
from workers.base import BaseWorker
import logger
REQUIREMENTS = ["python-smartgadget"]
ATTR_CONFIG = [
# (attribute_name, device_class, unit_of_measurement)
("temperature", "temperature", "°C"),
("humidity", "humidity", "%"),
("battery_level", "battery", "%"),
]
_LOGGER = logger.get(__name__)
class SmartgadgetWorker(BaseWorker):
def _setup(self):
from sensirionbt import SmartGadget
_LOGGER.info("Adding %d %s devices", len(self.devices), repr(self))
for name, mac in self.devices.items():
_LOGGER.debug("Adding %s device '%s' (%s)", repr(self), name, mac)
self.devices[name] = SmartGadget(mac)
def config(self):
ret = []
for name, device in self.devices.items():
ret.extend(self.config_device(name, device.mac))
return ret
def config_device(self, name, mac):
ret = []
device = {
"identifiers": self.format_discovery_id(mac, name),
"manufacturer": "Sensirion AG",
"model": "SmartGadget",
"name": self.format_discovery_name(name),
}
for attr, device_class, unit in ATTR_CONFIG:
payload = {
"unique_id": self.format_discovery_id(mac, name, device_class),
"name": self.format_discovery_name(name, device_class),
"state_topic": self.format_prefixed_topic(name, device_class),
"device": device,
"device_class": device_class,
"unit_of_measurement": unit,
}
ret.append(
MqttConfigMessage(
MqttConfigMessage.SENSOR,
self.format_discovery_topic(mac, name, device_class),
payload=payload,
)
)
return ret
def status_update(self):
from bluepy import btle
_LOGGER.info("Updating %d %s devices", len(self.devices), repr(self))
for name, device in self.devices.items():
_LOGGER.debug("Updating %s device '%s' (%s)", repr(self), name, device.mac)
try:
yield self.update_device_state(name, device)
except btle.BTLEException as e:
logger.log_exception(
_LOGGER,
"Error during update of %s device '%s' (%s): %s",
repr(self),
name,
device.mac,
type(e).__name__,
suppress=True,
)
def update_device_state(self, name, device):
values = device.get_values()
ret = []
for attr, device_class, _ in ATTR_CONFIG:
ret.append(
MqttMessage(
topic=self.format_topic(name, device_class), payload=values[attr]
)
)
return ret | workers/smartgadget.py | from mqtt import MqttMessage, MqttConfigMessage
from workers.base import BaseWorker
import logger
REQUIREMENTS = ["python-smartgadget"]
ATTR_CONFIG = [
# (attribute_name, device_class, unit_of_measurement)
("temperature", "temperature", "°C"),
("humidity", "humidity", "%"),
("battery_level", "battery", "%"),
]
_LOGGER = logger.get(__name__)
class SmartgadgetWorker(BaseWorker):
def _setup(self):
from sensirionbt import SmartGadget
_LOGGER.info("Adding %d %s devices", len(self.devices), repr(self))
for name, mac in self.devices.items():
_LOGGER.debug("Adding %s device '%s' (%s)", repr(self), name, mac)
self.devices[name] = SmartGadget(mac)
def config(self):
ret = []
for name, device in self.devices.items():
ret.extend(self.config_device(name, device.mac))
return ret
def config_device(self, name, mac):
ret = []
device = {
"identifiers": self.format_discovery_id(mac, name),
"manufacturer": "Sensirion AG",
"model": "SmartGadget",
"name": self.format_discovery_name(name),
}
for attr, device_class, unit in ATTR_CONFIG:
payload = {
"unique_id": self.format_discovery_id(mac, name, device_class),
"name": self.format_discovery_name(name, device_class),
"state_topic": self.format_prefixed_topic(name, device_class),
"device": device,
"device_class": device_class,
"unit_of_measurement": unit,
}
ret.append(
MqttConfigMessage(
MqttConfigMessage.SENSOR,
self.format_discovery_topic(mac, name, device_class),
payload=payload,
)
)
return ret
def status_update(self):
from bluepy import btle
_LOGGER.info("Updating %d %s devices", len(self.devices), repr(self))
for name, device in self.devices.items():
_LOGGER.debug("Updating %s device '%s' (%s)", repr(self), name, device.mac)
try:
yield self.update_device_state(name, device)
except btle.BTLEException as e:
logger.log_exception(
_LOGGER,
"Error during update of %s device '%s' (%s): %s",
repr(self),
name,
device.mac,
type(e).__name__,
suppress=True,
)
def update_device_state(self, name, device):
values = device.get_values()
ret = []
for attr, device_class, _ in ATTR_CONFIG:
ret.append(
MqttMessage(
topic=self.format_topic(name, device_class), payload=values[attr]
)
)
return ret | 0.379263 | 0.1425 |
import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
"""
Graph Transformer
"""
from layers.graph_transformer_layer import GraphTransformerLayer
from layers.mlp_readout_layer import MLPReadout
class GraphTransformerNet(nn.Module):
def __init__(self, net_params):
super().__init__()
in_dim_node = net_params['in_dim'] # node_dim (feat is an integer)
hidden_dim = net_params['hidden_dim']
out_dim = net_params['out_dim']
n_classes = net_params['n_classes']
num_heads = net_params['n_heads']
in_feat_dropout = net_params['in_feat_dropout']
dropout = net_params['dropout']
n_layers = net_params['L']
self.readout = net_params['readout']
self.layer_norm = net_params['layer_norm']
self.batch_norm = net_params['batch_norm']
self.residual = net_params['residual']
self.dropout = dropout
self.n_classes = n_classes
self.device = net_params['device']
self.lap_pos_enc = net_params['lap_pos_enc']
self.wl_pos_enc = net_params['wl_pos_enc']
max_wl_role_index = 100
if self.lap_pos_enc:
pos_enc_dim = net_params['pos_enc_dim']
self.embedding_lap_pos_enc = nn.Linear(pos_enc_dim, hidden_dim)
if self.wl_pos_enc:
self.embedding_wl_pos_enc = nn.Embedding(max_wl_role_index, hidden_dim)
self.embedding_h = nn.Embedding(in_dim_node, hidden_dim) # node feat is an integer
self.in_feat_dropout = nn.Dropout(in_feat_dropout)
self.layers = nn.ModuleList([GraphTransformerLayer(hidden_dim, hidden_dim, num_heads,
dropout, self.layer_norm, self.batch_norm, self.residual) for _ in range(n_layers-1)])
self.layers.append(GraphTransformerLayer(hidden_dim, out_dim, num_heads, dropout, self.layer_norm, self.batch_norm, self.residual))
self.MLP_layer = MLPReadout(out_dim, n_classes)
def forward(self, g, h, e, h_lap_pos_enc=None, h_wl_pos_enc=None):
# input embedding
h = self.embedding_h(h)
if self.lap_pos_enc:
h_lap_pos_enc = self.embedding_lap_pos_enc(h_lap_pos_enc.float())
h = h + h_lap_pos_enc
if self.wl_pos_enc:
h_wl_pos_enc = self.embedding_wl_pos_enc(h_wl_pos_enc)
h = h + h_wl_pos_enc
h = self.in_feat_dropout(h)
# GraphTransformer Layers
for conv in self.layers:
h = conv(g, h)
# output
h_out = self.MLP_layer(h)
return h_out
def loss(self, pred, label):
# calculating label weights for weighted loss computation
V = label.size(0)
label_count = torch.bincount(label)
label_count = label_count[label_count.nonzero()].squeeze()
cluster_sizes = torch.zeros(self.n_classes).long().to(self.device)
cluster_sizes[torch.unique(label)] = label_count
weight = (V - cluster_sizes).float() / V
weight *= (cluster_sizes>0).float()
# weighted cross-entropy for unbalanced classes
criterion = nn.CrossEntropyLoss(weight=weight)
loss = criterion(pred, label)
return loss | nets/SBMs_node_classification/graph_transformer_net.py | import torch
import torch.nn as nn
import torch.nn.functional as F
import dgl
"""
Graph Transformer
"""
from layers.graph_transformer_layer import GraphTransformerLayer
from layers.mlp_readout_layer import MLPReadout
class GraphTransformerNet(nn.Module):
def __init__(self, net_params):
super().__init__()
in_dim_node = net_params['in_dim'] # node_dim (feat is an integer)
hidden_dim = net_params['hidden_dim']
out_dim = net_params['out_dim']
n_classes = net_params['n_classes']
num_heads = net_params['n_heads']
in_feat_dropout = net_params['in_feat_dropout']
dropout = net_params['dropout']
n_layers = net_params['L']
self.readout = net_params['readout']
self.layer_norm = net_params['layer_norm']
self.batch_norm = net_params['batch_norm']
self.residual = net_params['residual']
self.dropout = dropout
self.n_classes = n_classes
self.device = net_params['device']
self.lap_pos_enc = net_params['lap_pos_enc']
self.wl_pos_enc = net_params['wl_pos_enc']
max_wl_role_index = 100
if self.lap_pos_enc:
pos_enc_dim = net_params['pos_enc_dim']
self.embedding_lap_pos_enc = nn.Linear(pos_enc_dim, hidden_dim)
if self.wl_pos_enc:
self.embedding_wl_pos_enc = nn.Embedding(max_wl_role_index, hidden_dim)
self.embedding_h = nn.Embedding(in_dim_node, hidden_dim) # node feat is an integer
self.in_feat_dropout = nn.Dropout(in_feat_dropout)
self.layers = nn.ModuleList([GraphTransformerLayer(hidden_dim, hidden_dim, num_heads,
dropout, self.layer_norm, self.batch_norm, self.residual) for _ in range(n_layers-1)])
self.layers.append(GraphTransformerLayer(hidden_dim, out_dim, num_heads, dropout, self.layer_norm, self.batch_norm, self.residual))
self.MLP_layer = MLPReadout(out_dim, n_classes)
def forward(self, g, h, e, h_lap_pos_enc=None, h_wl_pos_enc=None):
# input embedding
h = self.embedding_h(h)
if self.lap_pos_enc:
h_lap_pos_enc = self.embedding_lap_pos_enc(h_lap_pos_enc.float())
h = h + h_lap_pos_enc
if self.wl_pos_enc:
h_wl_pos_enc = self.embedding_wl_pos_enc(h_wl_pos_enc)
h = h + h_wl_pos_enc
h = self.in_feat_dropout(h)
# GraphTransformer Layers
for conv in self.layers:
h = conv(g, h)
# output
h_out = self.MLP_layer(h)
return h_out
def loss(self, pred, label):
# calculating label weights for weighted loss computation
V = label.size(0)
label_count = torch.bincount(label)
label_count = label_count[label_count.nonzero()].squeeze()
cluster_sizes = torch.zeros(self.n_classes).long().to(self.device)
cluster_sizes[torch.unique(label)] = label_count
weight = (V - cluster_sizes).float() / V
weight *= (cluster_sizes>0).float()
# weighted cross-entropy for unbalanced classes
criterion = nn.CrossEntropyLoss(weight=weight)
loss = criterion(pred, label)
return loss | 0.908364 | 0.297741 |
import torch, pdb, os, json
from shared import _cat_
import numpy as np
from model import OptionInfer, Scorer
from collections import defaultdict
def get_model(path, cuda=True):
opt = OptionInfer(cuda)
if path.endswith('.yaml') or path.endswith('.yml'):
from model import JointScorer
model = JointScorer(opt)
model.load(path)
if path.endswith('pth'):
from model import Scorer
model = Scorer(opt)
model.load(path)
if cuda:
model.cuda()
return model
def predict(model, cxt, hyps, max_cxt_turn=None):
# split into smaller batch to avoid OOM
n = len(hyps)
i0 = 0
scores = []
while i0 < n:
i1 = min(i0 + 32, n)
_scores = model.predict(cxt, hyps[i0: i1], max_cxt_turn=max_cxt_turn)
scores.append(_scores)
i0 = i1
if isinstance(_scores, dict):
d_scores = dict()
for k in _scores:
d_scores[k] = np.concatenate([_scores[k] for _scores in scores])
return d_scores
else:
return np.concatenate(scores)
def eval_fake(fld, model, fake, max_n=-1, max_cxt_turn=None):
"""
for a given context, we rank k real and m fake responses
if x real responses appeared in topk ranked responses, define acc = x/k, where k = # of real.
this can be seen as a generalized version of hits@k
for a perfect ranking, x == k thus acc == 1.
"""
assert(os.path.isdir(fld))
def read_data(path, max_n=-1):
cxts = dict()
rsps = dict()
for i, line in enumerate(open(path, encoding='utf-8')):
ss = line.strip('\n').split('\t')
ss0 = ss[0].split(_cat_)
if len(ss0) == 2:
cxt, cxt_id = ss0
cxt_id = cxt_id.strip()
else:
cxt = ss0[0]
cxt_id = cxt.strip().replace(' ','')
cxts[cxt_id] = cxt.strip()
rsps[cxt_id] = [s.split(_cat_)[0] for s in ss[1:]]
if i == max_n:
break
return cxts, rsps
print('evaluating %s'%fld)
acc = []
cxts, reals = read_data(fld + '/ref.tsv', max_n=max_n)
_, fakes = read_data(fld + '/%s.tsv'%fake)
n = 0
for cxt_id in reals:
if cxt_id not in fakes:
print('[WARNING] could not find fake examples for [%s]'%cxt_id)
#pdb.set_trace()
continue
scores = predict(model, cxts[cxt_id], reals[cxt_id] + fakes[cxt_id], max_cxt_turn=max_cxt_turn)
ix_score = sorted([(scores[i], i) for i in range(len(scores))], reverse=True)
k = len(reals[cxt_id])
_acc = np.mean([i < k for _, i in ix_score[:k]])
acc.append(_acc)
n += 1
if n % 10 == 0:
print('evaluated %i, avg acc %.3f'%(n, np.mean(acc)))
if n == max_n:
break
print('final acc is %.3f based on %i samples'%(np.mean(acc), n))
def eval_feedback(path, model, max_n=-1, max_cxt_turn=None, min_rank_gap=0., min_score_gap=0, max_hr_gap=1):
"""
for a given context, we compare two responses,
predict which one got better feedback (greater updown, depth, or width)
return this pairwise accuracy
"""
assert(path.endswith('.tsv'))
assert(min_rank_gap is not None)
assert(min_score_gap is not None)
print('evaluating %s'%path)
acc = []
n = 0
for line in open(path, encoding='utf-8'):
cc = line.strip('\n').split('\t')
if len(cc) != 11:
continue
cxt, pos, neg, _, _, _, hr_gap, pos_score, neg_score, pos_rank, neg_rank = cc
if float(hr_gap) > max_hr_gap:
continue
if float(pos_rank) - float(neg_rank) < min_rank_gap:
continue
if int(pos_score) - int(neg_score) < min_score_gap:
continue
scores = predict(model, cxt, [pos, neg], max_cxt_turn=max_cxt_turn)
score_pos = scores[0]
score_neg = scores[1]
acc.append(float(score_pos > score_neg))
n += 1
if n % 10 == 0:
print('evaluated %i, avg acc %.3f'%(n, np.mean(acc)))
if n == max_n:
break
print('final acc is %.3f based on %i samples'%(np.mean(acc), n))
def rank_hyps(path, model, max_n=-1, max_cxt_turn=None):
"""
rank the responses for each given cxt with model
path is the input file, where in each line, 0-th column is the context, and the rest are responses
output a jsonl file, and can be read with function `read_ranked_jsonl`
"""
print('ranking %s'%path)
lines = []
n = 0
sum_avg_score = 0
sum_top_score = 0
for i, line in enumerate(open(path, encoding='utf-8')):
cc = line.strip('\n').split('\t')
if len(cc) < 2:
print('[WARNING] line %i only has %i columns, ignored'%(i, len(cc)))
continue
cxt = cc[0]
hyps = cc[1:]
scores = predict(model, cxt, hyps, max_cxt_turn=max_cxt_turn)
d = {'line_id':i, 'cxt': cxt}
scored = []
if isinstance(scores, dict):
sum_avg_score += np.mean(scores['final'])
sum_top_score += np.max(scores['final'])
for j, hyp in enumerate(hyps):
tup = (
float(scores['final'][j]),
dict([(k, float(scores[k][j])) for k in scores]),
hyp,
)
scored.append(tup)
else:
sum_avg_score += np.mean(scores)
sum_top_score += np.max(scores)
for j, hyp in enumerate(hyps):
scored.append((float(scores[j]), hyp))
d['hyps'] = list(sorted(scored, reverse=True))
lines.append(json.dumps(d))
n += 1
if n % 10 == 0:
print('processed %i line, avg_hyp_score %.3f, top_hyp_score %.3f'%(
n,
sum_avg_score/n,
sum_top_score/n,
))
if n == max_n:
break
print('totally processed %i line, avg_hyp_score %.3f, top_hyp_score %.3f'%(
n,
sum_avg_score/n,
sum_top_score/n,
))
path_out = path+'.ranked.jsonl'
with open(path_out, 'w') as f:
f.write('\n'.join(lines))
print('results saved to '+path_out)
def read_ranked_jsonl(path):
""" read the jsonl file ouput by function rank_hyps"""
data = [json.loads(line) for line in open(path, encoding="utf-8")]
n_hyp = [len(d['hyps']) for d in data]
best = defaultdict(list)
avg = defaultdict(list)
for d in data:
scores = defaultdict(list)
for tup in d['hyps']:
scores['_score'].append(tup[0])
if isinstance(tup[1], dict):
for k in tup[1]:
scores[k].append(tup[1][k])
for k in scores:
best[k].append(max(scores[k]))
avg[k].append(np.mean(scores[k]))
print()
width = 20
print('\t|'.join([' '*width, 'best', 'avg']))
print('-'*40)
for k in best:
print('%s\t|%.3f\t|%.3f'%(
' '*(width - len(k)) + k,
np.mean(best[k]),
np.mean(avg[k]),
))
print('-'*40)
print('n_cxt: %i'%len(data))
print('avg n_hyp per cxt: %.2f'%np.mean(n_hyp))
return data
def play(model, max_cxt_turn=None):
from shared import EOS_token
model.eval()
print('enter empty to stop')
print('use `%s` to delimite turns for a multi-turn context'%EOS_token)
while True:
print()
cxt = input('Context: ')
if not cxt:
break
hyp = input('Response: ')
if not hyp:
break
score = model.predict(cxt, [hyp], max_cxt_turn=max_cxt_turn)
if isinstance(score, dict):
ss = ['%s = %.3f'%(k, score[k][0]) for k in score]
print(', '.join(ss))
else:
print('score = %.3f'%score[0])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('task', type=str)
parser.add_argument('--data', type=str)
parser.add_argument('--max_cxt_turn', type=int, default=2)
parser.add_argument('--path_pth', '-p', type=str)
parser.add_argument('--cpu', action='store_true')
parser.add_argument('--max_n', type=int, default=5000)
parser.add_argument('--min_score_gap', type=int)
parser.add_argument('--min_rank_gap', type=float)
args = parser.parse_args()
cuda = False if args.cpu else torch.cuda.is_available()
if args.task != 'stats':
model = get_model(args.path_pth, cuda)
if args.task in ['eval_human_vs_rand', 'eval_human_vs_machine']:
fake = args.task.split('_')[-1]
eval_fake(args.data, model, fake, max_n=args.max_n, max_cxt_turn=args.max_cxt_turn)
elif args.task == 'eval_human_feedback':
eval_feedback(args.data, model, max_cxt_turn=args.max_cxt_turn,
min_rank_gap=args.min_rank_gap, max_n=args.max_n, min_score_gap=args.min_score_gap)
elif args.task == 'test':
rank_hyps(args.data, model, max_n=args.max_n, max_cxt_turn=args.max_cxt_turn)
elif args.task == 'play':
play(model, max_cxt_turn=args.max_cxt_turn)
elif args.task == 'stats':
read_ranked_jsonl(args.data)
else:
raise ValueError | src/score.py | import torch, pdb, os, json
from shared import _cat_
import numpy as np
from model import OptionInfer, Scorer
from collections import defaultdict
def get_model(path, cuda=True):
opt = OptionInfer(cuda)
if path.endswith('.yaml') or path.endswith('.yml'):
from model import JointScorer
model = JointScorer(opt)
model.load(path)
if path.endswith('pth'):
from model import Scorer
model = Scorer(opt)
model.load(path)
if cuda:
model.cuda()
return model
def predict(model, cxt, hyps, max_cxt_turn=None):
# split into smaller batch to avoid OOM
n = len(hyps)
i0 = 0
scores = []
while i0 < n:
i1 = min(i0 + 32, n)
_scores = model.predict(cxt, hyps[i0: i1], max_cxt_turn=max_cxt_turn)
scores.append(_scores)
i0 = i1
if isinstance(_scores, dict):
d_scores = dict()
for k in _scores:
d_scores[k] = np.concatenate([_scores[k] for _scores in scores])
return d_scores
else:
return np.concatenate(scores)
def eval_fake(fld, model, fake, max_n=-1, max_cxt_turn=None):
"""
for a given context, we rank k real and m fake responses
if x real responses appeared in topk ranked responses, define acc = x/k, where k = # of real.
this can be seen as a generalized version of hits@k
for a perfect ranking, x == k thus acc == 1.
"""
assert(os.path.isdir(fld))
def read_data(path, max_n=-1):
cxts = dict()
rsps = dict()
for i, line in enumerate(open(path, encoding='utf-8')):
ss = line.strip('\n').split('\t')
ss0 = ss[0].split(_cat_)
if len(ss0) == 2:
cxt, cxt_id = ss0
cxt_id = cxt_id.strip()
else:
cxt = ss0[0]
cxt_id = cxt.strip().replace(' ','')
cxts[cxt_id] = cxt.strip()
rsps[cxt_id] = [s.split(_cat_)[0] for s in ss[1:]]
if i == max_n:
break
return cxts, rsps
print('evaluating %s'%fld)
acc = []
cxts, reals = read_data(fld + '/ref.tsv', max_n=max_n)
_, fakes = read_data(fld + '/%s.tsv'%fake)
n = 0
for cxt_id in reals:
if cxt_id not in fakes:
print('[WARNING] could not find fake examples for [%s]'%cxt_id)
#pdb.set_trace()
continue
scores = predict(model, cxts[cxt_id], reals[cxt_id] + fakes[cxt_id], max_cxt_turn=max_cxt_turn)
ix_score = sorted([(scores[i], i) for i in range(len(scores))], reverse=True)
k = len(reals[cxt_id])
_acc = np.mean([i < k for _, i in ix_score[:k]])
acc.append(_acc)
n += 1
if n % 10 == 0:
print('evaluated %i, avg acc %.3f'%(n, np.mean(acc)))
if n == max_n:
break
print('final acc is %.3f based on %i samples'%(np.mean(acc), n))
def eval_feedback(path, model, max_n=-1, max_cxt_turn=None, min_rank_gap=0., min_score_gap=0, max_hr_gap=1):
"""
for a given context, we compare two responses,
predict which one got better feedback (greater updown, depth, or width)
return this pairwise accuracy
"""
assert(path.endswith('.tsv'))
assert(min_rank_gap is not None)
assert(min_score_gap is not None)
print('evaluating %s'%path)
acc = []
n = 0
for line in open(path, encoding='utf-8'):
cc = line.strip('\n').split('\t')
if len(cc) != 11:
continue
cxt, pos, neg, _, _, _, hr_gap, pos_score, neg_score, pos_rank, neg_rank = cc
if float(hr_gap) > max_hr_gap:
continue
if float(pos_rank) - float(neg_rank) < min_rank_gap:
continue
if int(pos_score) - int(neg_score) < min_score_gap:
continue
scores = predict(model, cxt, [pos, neg], max_cxt_turn=max_cxt_turn)
score_pos = scores[0]
score_neg = scores[1]
acc.append(float(score_pos > score_neg))
n += 1
if n % 10 == 0:
print('evaluated %i, avg acc %.3f'%(n, np.mean(acc)))
if n == max_n:
break
print('final acc is %.3f based on %i samples'%(np.mean(acc), n))
def rank_hyps(path, model, max_n=-1, max_cxt_turn=None):
"""
rank the responses for each given cxt with model
path is the input file, where in each line, 0-th column is the context, and the rest are responses
output a jsonl file, and can be read with function `read_ranked_jsonl`
"""
print('ranking %s'%path)
lines = []
n = 0
sum_avg_score = 0
sum_top_score = 0
for i, line in enumerate(open(path, encoding='utf-8')):
cc = line.strip('\n').split('\t')
if len(cc) < 2:
print('[WARNING] line %i only has %i columns, ignored'%(i, len(cc)))
continue
cxt = cc[0]
hyps = cc[1:]
scores = predict(model, cxt, hyps, max_cxt_turn=max_cxt_turn)
d = {'line_id':i, 'cxt': cxt}
scored = []
if isinstance(scores, dict):
sum_avg_score += np.mean(scores['final'])
sum_top_score += np.max(scores['final'])
for j, hyp in enumerate(hyps):
tup = (
float(scores['final'][j]),
dict([(k, float(scores[k][j])) for k in scores]),
hyp,
)
scored.append(tup)
else:
sum_avg_score += np.mean(scores)
sum_top_score += np.max(scores)
for j, hyp in enumerate(hyps):
scored.append((float(scores[j]), hyp))
d['hyps'] = list(sorted(scored, reverse=True))
lines.append(json.dumps(d))
n += 1
if n % 10 == 0:
print('processed %i line, avg_hyp_score %.3f, top_hyp_score %.3f'%(
n,
sum_avg_score/n,
sum_top_score/n,
))
if n == max_n:
break
print('totally processed %i line, avg_hyp_score %.3f, top_hyp_score %.3f'%(
n,
sum_avg_score/n,
sum_top_score/n,
))
path_out = path+'.ranked.jsonl'
with open(path_out, 'w') as f:
f.write('\n'.join(lines))
print('results saved to '+path_out)
def read_ranked_jsonl(path):
""" read the jsonl file ouput by function rank_hyps"""
data = [json.loads(line) for line in open(path, encoding="utf-8")]
n_hyp = [len(d['hyps']) for d in data]
best = defaultdict(list)
avg = defaultdict(list)
for d in data:
scores = defaultdict(list)
for tup in d['hyps']:
scores['_score'].append(tup[0])
if isinstance(tup[1], dict):
for k in tup[1]:
scores[k].append(tup[1][k])
for k in scores:
best[k].append(max(scores[k]))
avg[k].append(np.mean(scores[k]))
print()
width = 20
print('\t|'.join([' '*width, 'best', 'avg']))
print('-'*40)
for k in best:
print('%s\t|%.3f\t|%.3f'%(
' '*(width - len(k)) + k,
np.mean(best[k]),
np.mean(avg[k]),
))
print('-'*40)
print('n_cxt: %i'%len(data))
print('avg n_hyp per cxt: %.2f'%np.mean(n_hyp))
return data
def play(model, max_cxt_turn=None):
from shared import EOS_token
model.eval()
print('enter empty to stop')
print('use `%s` to delimite turns for a multi-turn context'%EOS_token)
while True:
print()
cxt = input('Context: ')
if not cxt:
break
hyp = input('Response: ')
if not hyp:
break
score = model.predict(cxt, [hyp], max_cxt_turn=max_cxt_turn)
if isinstance(score, dict):
ss = ['%s = %.3f'%(k, score[k][0]) for k in score]
print(', '.join(ss))
else:
print('score = %.3f'%score[0])
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('task', type=str)
parser.add_argument('--data', type=str)
parser.add_argument('--max_cxt_turn', type=int, default=2)
parser.add_argument('--path_pth', '-p', type=str)
parser.add_argument('--cpu', action='store_true')
parser.add_argument('--max_n', type=int, default=5000)
parser.add_argument('--min_score_gap', type=int)
parser.add_argument('--min_rank_gap', type=float)
args = parser.parse_args()
cuda = False if args.cpu else torch.cuda.is_available()
if args.task != 'stats':
model = get_model(args.path_pth, cuda)
if args.task in ['eval_human_vs_rand', 'eval_human_vs_machine']:
fake = args.task.split('_')[-1]
eval_fake(args.data, model, fake, max_n=args.max_n, max_cxt_turn=args.max_cxt_turn)
elif args.task == 'eval_human_feedback':
eval_feedback(args.data, model, max_cxt_turn=args.max_cxt_turn,
min_rank_gap=args.min_rank_gap, max_n=args.max_n, min_score_gap=args.min_score_gap)
elif args.task == 'test':
rank_hyps(args.data, model, max_n=args.max_n, max_cxt_turn=args.max_cxt_turn)
elif args.task == 'play':
play(model, max_cxt_turn=args.max_cxt_turn)
elif args.task == 'stats':
read_ranked_jsonl(args.data)
else:
raise ValueError | 0.446736 | 0.242015 |
# ============= enthought library imports =======================
from reportlab.lib.pagesizes import A4, letter, landscape, A2, A0
from reportlab.lib.units import inch, cm
from traits.api import Str, Bool, Enum, Button, Float, Color
from traitsui.api import View, Item, UItem, HGroup, Group, VGroup, spring, Spring
from pychron.core.helpers.traitsui_shortcuts import okcancel_view
from pychron.core.pdf.pdf_graphics_context import UNITS_MAP
from pychron.core.persistence_options import BasePersistenceOptions
from pychron.core.pychron_traits import BorderVGroup
from pychron.envisage.icon_button_editor import icon_button_editor
from pychron.persistence_loggable import dumpable
from pychron.pychron_constants import SIG_FIGS
PAGE_MAP = {'A4': A4, 'letter': letter, 'A2': A2, 'A0': A0}
UNITS_MAP = {'inch': inch, 'cm': cm}
COLUMN_MAP = {'1': 1, '2': 0.5, '3': 0.33, '2/3': 0.66}
mgrp = BorderVGroup(HGroup(Spring(springy=False, width=100),
Item('top_margin', label='Top'),
spring, ),
HGroup(Item('left_margin', label='Left'),
Item('right_margin', label='Right')),
HGroup(Spring(springy=False, width=100), Item('bottom_margin', label='Bottom'),
spring),
label='Margins')
cgrp = VGroup()
sgrp = BorderVGroup(Item('page_type'),
Item('fit_to_page'),
HGroup(Item('use_column_width', enabled_when='not fit_to_page'),
Item('columns', enabled_when='use_column_width')),
HGroup(Item('fixed_width', label='W', enabled_when='not use_column_width and not fit_to_page or '
'page_type=="custom"'),
Item('fixed_height', label='H', enabled_when='not fit_to_page or page_type=="custom"'),
Item('units', enabled_when='not fit_to_page or page_type=="custom"')),
label='Size')
PDFLayoutGroup = VGroup(Item('orientation'),
mgrp,
sgrp,
cgrp,
label='Layout')
PDFLayoutView = okcancel_view(PDFLayoutGroup,
title='PDF Save Options')
class BasePDFOptions(BasePersistenceOptions):
orientation = dumpable(Enum('landscape', 'portrait'))
left_margin = dumpable(Float(1.5))
right_margin = dumpable(Float(1))
top_margin = dumpable(Float(1))
bottom_margin = dumpable(Float(1))
show_page_numbers = dumpable(Bool(False))
_persistence_name = 'base_pdf_options'
page_number_format = None
fixed_width = dumpable(Float)
fixed_height = dumpable(Float)
page_type = dumpable(Enum('letter', 'A4', 'A2', 'A0', 'custom'))
units = dumpable(Enum('inch', 'cm'))
use_column_width = dumpable(Bool(True))
columns = dumpable(Enum('1', '2', '3', '2/3'))
fit_to_page = dumpable(Bool)
@property
def bounds(self):
units = UNITS_MAP[self.units]
if self.page_type == 'custom':
page = [self.fixed_width * units, self.fixed_height * units]
else:
page = PAGE_MAP[self.page_type]
if self.fit_to_page:
if self.orientation == 'landscape':
b = [page[1], page[0]]
else:
b = [page[0], page[1]]
b[0] -= (self.left_margin + self.right_margin) * units
b[1] -= (self.top_margin + self.bottom_margin) * units
elif self.use_column_width:
if self.orientation == 'landscape':
page = landscape(page)
width_margins = self.bottom_margin + self.top_margin
else:
width_margins = self.left_margin + self.right_margin
fw = page[0]
w = fw - width_margins * units
# print 'cw', w, fw, width_margins, width_margins * units, COLUMN_MAP[self.columns]
nw = w * COLUMN_MAP[self.columns]
b = [nw, nw]
else:
b = [self.fixed_width * units, self.fixed_height * units]
return b
@property
def page_size(self):
if self.page_type == 'custom':
units = UNITS_MAP[self.units]
ps = self.fixed_width * units, self.fixed_height * units
else:
orientation = 'landscape_' if self.orientation == 'landscape' else ''
ps = '{}{}'.format(orientation, self.page_type)
return ps
@property
def dest_box(self):
units = UNITS_MAP[self.units]
w, h = self.bounds
w /= units
h /= units
return self.left_margin, self.bottom_margin, w, h
def _get_layout_group(self):
return PDFLayoutGroup
class PDFTableOptions(BasePDFOptions):
title = Str
auto_title = Bool
use_alternating_background = Bool
alternating_background = Color
default_row_height = Float(0.22)
default_header_height = Float(0.22)
options_button = Button
age_nsigma = Enum(1, 2, 3)
kca_nsigma = Enum(1, 2, 3)
link_sigmas = Bool(True)
age_units = Enum('Ma', 'ka', 'Ga', 'a')
kca_sig_figs = Enum(*SIG_FIGS)
age_sig_figs = Enum(*SIG_FIGS)
_persistence_name = 'table_pdf_options'
def _load_yaml_hook(self, d):
self.age_nsigma = d.get('age_nsigma', 2)
self.kca_nsigma = d.get('kca_nsigma', 2)
self.link_sigmas = d.get('link_sigmas', True)
self.age_sig_figs = d.get('age_sig_figs', 3)
self.kca_sig_figs = d.get('kca_sig_figs', 3)
self.age_units = d.get('age_units', 'Ma')
def _get_dump_attrs(self):
return ('auto_title',
'age_nsigma',
'kca_nsigma',
'link_sigmas',
'age_sig_figs',
'kca_sig_figs',
'age_units')
def get_dump_dict(self):
d = super(PDFTableOptions, self).get_dump_dict()
d.update(dict(title=str(self.title)))
return d
def _options_button_fired(self):
if self.edit_traits(view='advanced_view', kind='livemodal'):
self.dump_yaml()
def _age_nsigma_changed(self):
if self.link_sigmas:
self.kca_nsigma = self.age_nsigma
def _kca_nsigma_changed(self):
if self.link_sigmas:
self.age_nsigma = self.kca_nsigma
def _link_sigmas_changed(self):
if self.link_sigmas:
self.kca_nsigma = self.age_nsigma
def traits_view(self):
v = View(HGroup(Item('auto_title'),
UItem('title', enabled_when='not auto_title'),
icon_button_editor('options_button', 'cog')))
return v
def advanced_view(self):
table_grp = Group(Item('use_alternating_background'),
Item('alternating_background'),
label='Table')
layout_grp = self._get_layout_grp()
data_grp = Group(Item('link_sigmas', label='Link'),
Item('age_nsigma', label='Age NSigma'),
Item('kca_nsigma', label='K/CA NSigma'),
Item('age_units'),
VGroup(
HGroup(Item('age_sig_figs', label='Age')),
HGroup(Item('kca_sig_figs', label='K/Ca')),
label='Sig Figs'),
label='Data')
v = okcancel_view(layout_grp,
table_grp,
data_grp,
title='PDF Options',
buttons=['OK', 'Cancel', 'Revert'])
return v
# ============= EOF ============================================= | pychron/core/pdf/options.py |
# ============= enthought library imports =======================
from reportlab.lib.pagesizes import A4, letter, landscape, A2, A0
from reportlab.lib.units import inch, cm
from traits.api import Str, Bool, Enum, Button, Float, Color
from traitsui.api import View, Item, UItem, HGroup, Group, VGroup, spring, Spring
from pychron.core.helpers.traitsui_shortcuts import okcancel_view
from pychron.core.pdf.pdf_graphics_context import UNITS_MAP
from pychron.core.persistence_options import BasePersistenceOptions
from pychron.core.pychron_traits import BorderVGroup
from pychron.envisage.icon_button_editor import icon_button_editor
from pychron.persistence_loggable import dumpable
from pychron.pychron_constants import SIG_FIGS
PAGE_MAP = {'A4': A4, 'letter': letter, 'A2': A2, 'A0': A0}
UNITS_MAP = {'inch': inch, 'cm': cm}
COLUMN_MAP = {'1': 1, '2': 0.5, '3': 0.33, '2/3': 0.66}
mgrp = BorderVGroup(HGroup(Spring(springy=False, width=100),
Item('top_margin', label='Top'),
spring, ),
HGroup(Item('left_margin', label='Left'),
Item('right_margin', label='Right')),
HGroup(Spring(springy=False, width=100), Item('bottom_margin', label='Bottom'),
spring),
label='Margins')
cgrp = VGroup()
sgrp = BorderVGroup(Item('page_type'),
Item('fit_to_page'),
HGroup(Item('use_column_width', enabled_when='not fit_to_page'),
Item('columns', enabled_when='use_column_width')),
HGroup(Item('fixed_width', label='W', enabled_when='not use_column_width and not fit_to_page or '
'page_type=="custom"'),
Item('fixed_height', label='H', enabled_when='not fit_to_page or page_type=="custom"'),
Item('units', enabled_when='not fit_to_page or page_type=="custom"')),
label='Size')
PDFLayoutGroup = VGroup(Item('orientation'),
mgrp,
sgrp,
cgrp,
label='Layout')
PDFLayoutView = okcancel_view(PDFLayoutGroup,
title='PDF Save Options')
class BasePDFOptions(BasePersistenceOptions):
orientation = dumpable(Enum('landscape', 'portrait'))
left_margin = dumpable(Float(1.5))
right_margin = dumpable(Float(1))
top_margin = dumpable(Float(1))
bottom_margin = dumpable(Float(1))
show_page_numbers = dumpable(Bool(False))
_persistence_name = 'base_pdf_options'
page_number_format = None
fixed_width = dumpable(Float)
fixed_height = dumpable(Float)
page_type = dumpable(Enum('letter', 'A4', 'A2', 'A0', 'custom'))
units = dumpable(Enum('inch', 'cm'))
use_column_width = dumpable(Bool(True))
columns = dumpable(Enum('1', '2', '3', '2/3'))
fit_to_page = dumpable(Bool)
@property
def bounds(self):
units = UNITS_MAP[self.units]
if self.page_type == 'custom':
page = [self.fixed_width * units, self.fixed_height * units]
else:
page = PAGE_MAP[self.page_type]
if self.fit_to_page:
if self.orientation == 'landscape':
b = [page[1], page[0]]
else:
b = [page[0], page[1]]
b[0] -= (self.left_margin + self.right_margin) * units
b[1] -= (self.top_margin + self.bottom_margin) * units
elif self.use_column_width:
if self.orientation == 'landscape':
page = landscape(page)
width_margins = self.bottom_margin + self.top_margin
else:
width_margins = self.left_margin + self.right_margin
fw = page[0]
w = fw - width_margins * units
# print 'cw', w, fw, width_margins, width_margins * units, COLUMN_MAP[self.columns]
nw = w * COLUMN_MAP[self.columns]
b = [nw, nw]
else:
b = [self.fixed_width * units, self.fixed_height * units]
return b
@property
def page_size(self):
if self.page_type == 'custom':
units = UNITS_MAP[self.units]
ps = self.fixed_width * units, self.fixed_height * units
else:
orientation = 'landscape_' if self.orientation == 'landscape' else ''
ps = '{}{}'.format(orientation, self.page_type)
return ps
@property
def dest_box(self):
units = UNITS_MAP[self.units]
w, h = self.bounds
w /= units
h /= units
return self.left_margin, self.bottom_margin, w, h
def _get_layout_group(self):
return PDFLayoutGroup
class PDFTableOptions(BasePDFOptions):
title = Str
auto_title = Bool
use_alternating_background = Bool
alternating_background = Color
default_row_height = Float(0.22)
default_header_height = Float(0.22)
options_button = Button
age_nsigma = Enum(1, 2, 3)
kca_nsigma = Enum(1, 2, 3)
link_sigmas = Bool(True)
age_units = Enum('Ma', 'ka', 'Ga', 'a')
kca_sig_figs = Enum(*SIG_FIGS)
age_sig_figs = Enum(*SIG_FIGS)
_persistence_name = 'table_pdf_options'
def _load_yaml_hook(self, d):
self.age_nsigma = d.get('age_nsigma', 2)
self.kca_nsigma = d.get('kca_nsigma', 2)
self.link_sigmas = d.get('link_sigmas', True)
self.age_sig_figs = d.get('age_sig_figs', 3)
self.kca_sig_figs = d.get('kca_sig_figs', 3)
self.age_units = d.get('age_units', 'Ma')
def _get_dump_attrs(self):
return ('auto_title',
'age_nsigma',
'kca_nsigma',
'link_sigmas',
'age_sig_figs',
'kca_sig_figs',
'age_units')
def get_dump_dict(self):
d = super(PDFTableOptions, self).get_dump_dict()
d.update(dict(title=str(self.title)))
return d
def _options_button_fired(self):
if self.edit_traits(view='advanced_view', kind='livemodal'):
self.dump_yaml()
def _age_nsigma_changed(self):
if self.link_sigmas:
self.kca_nsigma = self.age_nsigma
def _kca_nsigma_changed(self):
if self.link_sigmas:
self.age_nsigma = self.kca_nsigma
def _link_sigmas_changed(self):
if self.link_sigmas:
self.kca_nsigma = self.age_nsigma
def traits_view(self):
v = View(HGroup(Item('auto_title'),
UItem('title', enabled_when='not auto_title'),
icon_button_editor('options_button', 'cog')))
return v
def advanced_view(self):
table_grp = Group(Item('use_alternating_background'),
Item('alternating_background'),
label='Table')
layout_grp = self._get_layout_grp()
data_grp = Group(Item('link_sigmas', label='Link'),
Item('age_nsigma', label='Age NSigma'),
Item('kca_nsigma', label='K/CA NSigma'),
Item('age_units'),
VGroup(
HGroup(Item('age_sig_figs', label='Age')),
HGroup(Item('kca_sig_figs', label='K/Ca')),
label='Sig Figs'),
label='Data')
v = okcancel_view(layout_grp,
table_grp,
data_grp,
title='PDF Options',
buttons=['OK', 'Cancel', 'Revert'])
return v
# ============= EOF ============================================= | 0.520009 | 0.134406 |
import os
import shlex
import shutil
from abc import ABCMeta, abstractmethod
from glob import glob
from . import util
_modulefile_template = """#%%Module1.0
set MODULENAME [ file tail [ file dirname $ModulesCurrentModulefile ] ]
set MODULEVERSION [ file tail $ModulesCurrentModulefile ]
set MODULEBASE %s
set basedir $MODULEBASE/$MODULENAME/$MODULEVERSION
conflict $MODULENAME
if { [ file exists $MODULEBASE/$MODULENAME/.modulefile ] } {
source $MODULEBASE/$MODULENAME/.modulefile
}
if { [ file exists $MODULEBASE/$MODULENAME/$MODULEVERSION/.modulefile ] } {
source $MODULEBASE/$MODULENAME/$MODULEVERSION/.modulefile
}
proc ModulesHelp { } {
global dotversion
global MODULENAME
global MODULEVERSION
global DESCRIPTION
global HELPTEXT
global MAINTAINER
puts stderr "\\t$MODULENAME $MODULEVERSION - $DESCRIPTION\\n\\tMaintainer: $MAINTAINER\\n"
puts stderr "\\n$HELPTEXT"
}
module-whatis $DESCRIPTION
"""
class ModuleTree:
def __init__(self, root_dir):
self.root_dir = os.path.abspath(root_dir)
@property
def name(self):
modulefile = self.master_module_file()
if modulefile is not None:
return os.path.basename(modulefile).split("_")[0]
else:
return None
def module_dir(self):
return os.path.join(self.root_dir, "module")
def modulefile_dir(self):
return os.path.join(self.root_dir, "modulefile")
def master_module_file(self):
"""Return the master module file if it exists, None otherwise."""
files = glob(os.path.join(self.module_dir(), "*modulefile"))
if len(files):
return files[0]
else:
return None
def _master_module_file_name(self, name):
"""Construct the name of the master module file"""
return os.path.join(self.module_dir(), f"{name}_modulefile")
def exists(self):
"""Return true if the root directory exists"""
return os.path.lexists(self.root_dir)
def valid(self):
"""
Check if the module root tree is set up. Exit if it appears
corrupted.
"""
return (
self.exists()
and util.writeable_dir(self.root_dir)
and util.writeable_dir(self.modulefile_dir())
and util.writeable_dir(self.module_dir())
and self.master_module_file() is not None
)
def module_names(self):
return [
m for m in os.listdir(self.root_dir) if m != "module" and m != "modulefile"
]
def modules(self, all_versions=False):
if not self.valid():
raise RuntimeError(
"Cannot get available modules from a "
"module tree that has not been setup"
)
for m in self.module_names():
loader = self.load_module(m, parse_error_handler=util.ignore_error)
if all_versions:
for v in loader.available_versions():
version_loader = self.load_module(
m, v, parse_error_handler=util.ignore_error
)
yield version_loader.module
else:
yield loader.module
def can_setup(self, name):
"""Return True if the root directory of this tree can be setup"""
return (
self.exists()
and os.path.exists(self.root_dir)
and os.access(self.root_dir, os.W_OK)
and not len(os.listdir(self.root_dir))
)
def setup(self, name):
"""Set up the module root tree."""
if not self.can_setup(name):
raise ValueError(
"Module tree must be set up in an empty, " "writeable directory"
)
os.makedirs(str(self.modulefile_dir()))
os.makedirs(str(self.module_dir()))
f = open(self._master_module_file_name(name), "w")
f.write(_modulefile_template % self.root_dir)
f.close()
def init_module(self, module, overwrite=False):
"""
Create a module, throwing an exception if any files are in
the way of the module
:return: a ModuleBuilder used to build the module.
"""
builder = ModuleBuilder(self, module)
if not builder.clean():
if overwrite:
builder.clear()
else:
raise ValueError(
f"Some files exist in the module tree " f"where {module} should be."
)
builder.build()
return builder
def shared_module(self, module, version, error_handler=util.raise_value_error):
"""
Get the module object for a shared module, if it exists.
:param module: a module name
:param version: a module version
:error_handler: a callback handler of an error if the module parsing fails
:return: a Module object if a shared module exists for this module, otherwise None.
"""
loader = ModuleLoader(self, module, version)
if loader.shared_exists():
loader.load(force_shared=True, error_handler=error_handler)
return loader.module
else:
return None
def module_clean(self, module):
"""
Return True if nothing is in place where a module would be initialized.
"""
builder = ModuleBuilder(self, module)
return builder.clean()
def module_exists(self, name, version=None):
"""
Check for the existence of a valid module
:param name: the name of the module
:param version: a version number
:return: True if the module is found.
"""
loader = ModuleLoader(self, name, version)
return loader.valid()
def load_module(
self, name, version=None, parse_error_handler=util.raise_value_error
):
"""
Locate and parse the module from the filesystem identified by the
given name and version.
:param name: the name of the module
:param version: the version of the module. if none is provided, the
latest is loaded
:param parse_error_handler: a function which handles parse error
messages. If none is provided, an exception is raised.
:return: a ModuleLoder used to load the module.
"""
loader = ModuleLoader(self, name, version)
if not loader.valid():
raise ValueError(
f"Module {name}-{version} does not appear to "
f"be a valid module in the tree {self.root_dir}"
)
loader.load(error_handler=parse_error_handler)
return loader
class ModuleLocation(metaclass=ABCMeta):
"""Resolves module file locations relative to a module tree"""
@abstractmethod
def __init__(self, module_tree):
self.module_tree = module_tree
self.module = None
@abstractmethod
def category_name(self):
raise NotImplementedError
@abstractmethod
def shared(self):
raise NotImplementedError
@abstractmethod
def name(self):
raise NotImplementedError
@abstractmethod
def version(self):
raise NotImplementedError
def available_versions(self):
return [v for v in os.listdir(self.module_base()) if util.valid_version(v)]
def moduledotfile_path(self):
base = self.module_base()
if self.shared():
return os.path.join(base, ".modulefile")
else:
return os.path.join(base, self.version(), ".modulefile")
def shared_moduledotfile_path(self):
return os.path.join(self.module_base(), ".modulefile")
def module_base(self):
"""
:return: The path to the base of the module without the version
"""
return os.path.join(self.module_tree.root_dir, self.name())
def module_path(self):
return os.path.join(self.module_base(), self.version())
def modulefile_base(self):
return os.path.join(
self.module_tree.modulefile_dir(), self.category_name(), self.name()
)
def modulefile_path(self):
return os.path.join(self.modulefile_base(), self.version())
def clean(self):
"""Return false if files exist where the module resolves to. Note this
does not imply validity or readability"""
return not os.path.exists(self.module_path()) and not os.path.exists(
self.modulefile_path()
)
def valid(self):
return (
util.writeable_dir(self.module_base())
and self.version() is not None
and util.writeable_dir(self.module_path())
and os.path.exists(self.moduledotfile_path())
and os.readlink(self.modulefile_path())
== self.module_tree.master_module_file()
)
def path_exists(self, path):
"""Return true if the path that the path object implies already exists."""
return os.path.lexists(path.resolve(self.module_path()))
def add_path(self, source, path_obj, link=True):
"""Copy or link the contents of the source path to the path implied
in the destination path object."""
dest = path_obj.resolve(self.module_path())
cp = os.symlink if link else shutil.copytree
cp(os.path.abspath(source), dest)
self.module.paths.append(path_obj)
def remove_path(self, path_obj):
loc = path_obj.resolve(self.module_path())
rm = os.unlink if os.path.islink(loc) else shutil.rmtree
rm(path_obj.resolve(self.module_path()))
self.module.remove_path(path_obj)
def save_module_file(self):
if self.module is None:
raise RuntimeError("Cannot save unloaded module")
with open(self.moduledotfile_path(), "w") as f:
f.write(self.module.dump())
def clear(self):
if os.path.exists(self.modulefile_path()):
os.unlink(self.modulefile_path())
shutil.rmtree(self.module_path(), ignore_errors=True)
if len(self.available_versions()) == 0:
shutil.rmtree(self.module_base())
shutil.rmtree(self.modulefile_base())
class ModuleBuilder(ModuleLocation):
"""A module builder class."""
def __init__(self, module_tree, module):
super(ModuleBuilder, self).__init__(module_tree)
self.module = module
def category_name(self):
return self.module.category or self.module_tree.name
def shared(self):
return self.module.shared
def name(self):
return self.module.name
def version(self):
return self.module.version
def build(self):
os.makedirs(os.path.dirname(self.modulefile_path()), exist_ok=True)
os.symlink(self.module_tree.master_module_file(), self.modulefile_path())
os.makedirs(self.module_path())
self.save_module_file()
class ModuleLoader(ModuleLocation):
"""A module loader class."""
def __init__(self, module_tree, name, version=None):
"""
Loads a module. If no version is specified, the latest version is used.
:param module_tree: a ModuleTree object
:param name: The name of the module
:param version: The version of the module
"""
super(ModuleLoader, self).__init__(module_tree)
self._name = name
self._version = version
def category_name(self):
files = glob(os.path.join(self.module_tree.modulefile_dir(), "*", self.name()))
return os.path.basename(os.path.dirname(files[0]))
def shared(self):
return not os.path.exists(
os.path.join(
self.module_tree.root_dir, self.name(), self.version(), ".modulefile"
)
)
def shared_exists(self):
return os.path.exists(self.shared_moduledotfile_path())
def name(self):
return self._name
def version(self):
if self._version is None:
available_versions = self.available_versions()
if len(available_versions) == 0:
raise ValueError(f"No versions found for module {self.name()}")
return max(available_versions, key=util.version_key)
else:
return self._version
def load(self, force_shared=False, error_handler=util.raise_value_error):
self.module = Module.from_file(
self.moduledotfile_path(),
self.module_tree,
self.name(),
self.version(),
force_shared or self.shared(),
self.category_name(),
error_handler,
)
class Path:
"""A module path object"""
def __init__(self, path, operation="prepend-path", name="PATH"):
(self.operation, self.name) = operation, name
if "$basedir" in path:
self.path = path
else:
self.path = os.path.join("$basedir", os.path.basename(path.rstrip("/")))
def __repr__(self):
return f"{self.operation} {self.name} {self.path}"
def resolve(self, basedir):
"""replace the $basedir variable to the given path"""
return self.path.replace("$basedir", basedir)
class Module:
def __init__(
self,
root,
name,
version,
maintainer="no_maintainer",
helptext="",
description="",
extra_vars=None,
category=None,
shared=True,
extra_commands=None,
):
"""
Initialize a module.
:param root: the ModuleTree object under which this module exists
:param name: the name of the module (corresponding to the tool name)
:param version: the version of the module
:param maintainer: name and email address of the maintainer
:param helptext: the helptext for the module
:param description: longer form description of the module
:param extra_vars: a dict of extra variables to add
:param category: a category for the module
:param shared: whether the module file is shared among multiple versions
or, if false, is specific to this version
:param extra_commands: list of extra lines to add to the module file
"""
if extra_commands is None:
extra_commands = []
if extra_vars is None:
extra_vars = {}
self.root = root
self.name = name
self.version = version
self.maintainer = maintainer
self.helptext = helptext
self.description = description
self.category = category
self.shared = shared
self.extra_vars = extra_vars
self.extra_commands = extra_commands
self.paths = []
@classmethod
def from_file(
cls,
filename,
root,
name,
version,
shared,
category=None,
error_handler=util.raise_value_error,
):
"""parse a module file
:param filename: the path to the module dotfile
:param name: the package name for the module
:param version: the version of the module:
:param shared: whether the moduledotfile is located at the shared
:param category: the category of the module
:param error_handler: a which handles any parse errors during parsing.
If there is a parse error and a handler is provided, the line is
not interpreted and error handler is called. The default handler
raises a value error with the given error message.
:return: a new module parsed from the given file
"""
module = cls(root, name, version, shared=shared, category=category)
for line in open(filename):
try:
fields = shlex.split(line.strip())
except ValueError as e:
error_handler(f"parse error in {filename}: {e}")
continue
if len(fields) == 0:
continue
if fields[0] == "set":
if len(fields) < 3:
error_handler(f"Unparsable line in {filename}:\n{line}")
if fields[1] == "MAINTAINER":
module.maintainer = fields[2]
elif fields[1] == "HELPTEXT":
module.helptext = fields[2]
elif fields[1] == "DESCRIPTION":
module.description = fields[2]
else:
module.extra_vars.update({fields[1]: fields[2]})
elif fields[0] == "prepend-path" or fields[0] == "append-path":
module.paths.append(
Path(path=fields[2], operation=fields[0], name=fields[1])
)
else:
module.extra_commands.append(line.strip())
return module
def remove_path(self, path_obj):
"""
Remove the path from the module if the path_obj.path itself matches any of the paths in the module.
:param path_obj: a path object to compare to
:return:
"""
self.paths = [p for p in self.paths if p.path != path_obj.path]
def __repr__(self):
return f"{self.name}-{self.version}"
def dump(self):
"""Dump the module file as a string"""
text = (
f"""set MAINTAINER "{self.maintainer}"
set HELPTEXT "{self.helptext}"
set DESCRIPTION "{self.description}"\n"""
+ "\n".join([f'set {k} "{v}"' for k, v in self.extra_vars.items()])
+ "\n"
+ "\n".join(str(p) for p in self.paths)
+ "\n"
+ "\n".join(self.extra_commands)
)
return text | moduledev/module.py | import os
import shlex
import shutil
from abc import ABCMeta, abstractmethod
from glob import glob
from . import util
_modulefile_template = """#%%Module1.0
set MODULENAME [ file tail [ file dirname $ModulesCurrentModulefile ] ]
set MODULEVERSION [ file tail $ModulesCurrentModulefile ]
set MODULEBASE %s
set basedir $MODULEBASE/$MODULENAME/$MODULEVERSION
conflict $MODULENAME
if { [ file exists $MODULEBASE/$MODULENAME/.modulefile ] } {
source $MODULEBASE/$MODULENAME/.modulefile
}
if { [ file exists $MODULEBASE/$MODULENAME/$MODULEVERSION/.modulefile ] } {
source $MODULEBASE/$MODULENAME/$MODULEVERSION/.modulefile
}
proc ModulesHelp { } {
global dotversion
global MODULENAME
global MODULEVERSION
global DESCRIPTION
global HELPTEXT
global MAINTAINER
puts stderr "\\t$MODULENAME $MODULEVERSION - $DESCRIPTION\\n\\tMaintainer: $MAINTAINER\\n"
puts stderr "\\n$HELPTEXT"
}
module-whatis $DESCRIPTION
"""
class ModuleTree:
def __init__(self, root_dir):
self.root_dir = os.path.abspath(root_dir)
@property
def name(self):
modulefile = self.master_module_file()
if modulefile is not None:
return os.path.basename(modulefile).split("_")[0]
else:
return None
def module_dir(self):
return os.path.join(self.root_dir, "module")
def modulefile_dir(self):
return os.path.join(self.root_dir, "modulefile")
def master_module_file(self):
"""Return the master module file if it exists, None otherwise."""
files = glob(os.path.join(self.module_dir(), "*modulefile"))
if len(files):
return files[0]
else:
return None
def _master_module_file_name(self, name):
"""Construct the name of the master module file"""
return os.path.join(self.module_dir(), f"{name}_modulefile")
def exists(self):
"""Return true if the root directory exists"""
return os.path.lexists(self.root_dir)
def valid(self):
"""
Check if the module root tree is set up. Exit if it appears
corrupted.
"""
return (
self.exists()
and util.writeable_dir(self.root_dir)
and util.writeable_dir(self.modulefile_dir())
and util.writeable_dir(self.module_dir())
and self.master_module_file() is not None
)
def module_names(self):
return [
m for m in os.listdir(self.root_dir) if m != "module" and m != "modulefile"
]
def modules(self, all_versions=False):
if not self.valid():
raise RuntimeError(
"Cannot get available modules from a "
"module tree that has not been setup"
)
for m in self.module_names():
loader = self.load_module(m, parse_error_handler=util.ignore_error)
if all_versions:
for v in loader.available_versions():
version_loader = self.load_module(
m, v, parse_error_handler=util.ignore_error
)
yield version_loader.module
else:
yield loader.module
def can_setup(self, name):
"""Return True if the root directory of this tree can be setup"""
return (
self.exists()
and os.path.exists(self.root_dir)
and os.access(self.root_dir, os.W_OK)
and not len(os.listdir(self.root_dir))
)
def setup(self, name):
"""Set up the module root tree."""
if not self.can_setup(name):
raise ValueError(
"Module tree must be set up in an empty, " "writeable directory"
)
os.makedirs(str(self.modulefile_dir()))
os.makedirs(str(self.module_dir()))
f = open(self._master_module_file_name(name), "w")
f.write(_modulefile_template % self.root_dir)
f.close()
def init_module(self, module, overwrite=False):
"""
Create a module, throwing an exception if any files are in
the way of the module
:return: a ModuleBuilder used to build the module.
"""
builder = ModuleBuilder(self, module)
if not builder.clean():
if overwrite:
builder.clear()
else:
raise ValueError(
f"Some files exist in the module tree " f"where {module} should be."
)
builder.build()
return builder
def shared_module(self, module, version, error_handler=util.raise_value_error):
"""
Get the module object for a shared module, if it exists.
:param module: a module name
:param version: a module version
:error_handler: a callback handler of an error if the module parsing fails
:return: a Module object if a shared module exists for this module, otherwise None.
"""
loader = ModuleLoader(self, module, version)
if loader.shared_exists():
loader.load(force_shared=True, error_handler=error_handler)
return loader.module
else:
return None
def module_clean(self, module):
"""
Return True if nothing is in place where a module would be initialized.
"""
builder = ModuleBuilder(self, module)
return builder.clean()
def module_exists(self, name, version=None):
"""
Check for the existence of a valid module
:param name: the name of the module
:param version: a version number
:return: True if the module is found.
"""
loader = ModuleLoader(self, name, version)
return loader.valid()
def load_module(
self, name, version=None, parse_error_handler=util.raise_value_error
):
"""
Locate and parse the module from the filesystem identified by the
given name and version.
:param name: the name of the module
:param version: the version of the module. if none is provided, the
latest is loaded
:param parse_error_handler: a function which handles parse error
messages. If none is provided, an exception is raised.
:return: a ModuleLoder used to load the module.
"""
loader = ModuleLoader(self, name, version)
if not loader.valid():
raise ValueError(
f"Module {name}-{version} does not appear to "
f"be a valid module in the tree {self.root_dir}"
)
loader.load(error_handler=parse_error_handler)
return loader
class ModuleLocation(metaclass=ABCMeta):
"""Resolves module file locations relative to a module tree"""
@abstractmethod
def __init__(self, module_tree):
self.module_tree = module_tree
self.module = None
@abstractmethod
def category_name(self):
raise NotImplementedError
@abstractmethod
def shared(self):
raise NotImplementedError
@abstractmethod
def name(self):
raise NotImplementedError
@abstractmethod
def version(self):
raise NotImplementedError
def available_versions(self):
return [v for v in os.listdir(self.module_base()) if util.valid_version(v)]
def moduledotfile_path(self):
base = self.module_base()
if self.shared():
return os.path.join(base, ".modulefile")
else:
return os.path.join(base, self.version(), ".modulefile")
def shared_moduledotfile_path(self):
return os.path.join(self.module_base(), ".modulefile")
def module_base(self):
"""
:return: The path to the base of the module without the version
"""
return os.path.join(self.module_tree.root_dir, self.name())
def module_path(self):
return os.path.join(self.module_base(), self.version())
def modulefile_base(self):
return os.path.join(
self.module_tree.modulefile_dir(), self.category_name(), self.name()
)
def modulefile_path(self):
return os.path.join(self.modulefile_base(), self.version())
def clean(self):
"""Return false if files exist where the module resolves to. Note this
does not imply validity or readability"""
return not os.path.exists(self.module_path()) and not os.path.exists(
self.modulefile_path()
)
def valid(self):
return (
util.writeable_dir(self.module_base())
and self.version() is not None
and util.writeable_dir(self.module_path())
and os.path.exists(self.moduledotfile_path())
and os.readlink(self.modulefile_path())
== self.module_tree.master_module_file()
)
def path_exists(self, path):
"""Return true if the path that the path object implies already exists."""
return os.path.lexists(path.resolve(self.module_path()))
def add_path(self, source, path_obj, link=True):
"""Copy or link the contents of the source path to the path implied
in the destination path object."""
dest = path_obj.resolve(self.module_path())
cp = os.symlink if link else shutil.copytree
cp(os.path.abspath(source), dest)
self.module.paths.append(path_obj)
def remove_path(self, path_obj):
loc = path_obj.resolve(self.module_path())
rm = os.unlink if os.path.islink(loc) else shutil.rmtree
rm(path_obj.resolve(self.module_path()))
self.module.remove_path(path_obj)
def save_module_file(self):
if self.module is None:
raise RuntimeError("Cannot save unloaded module")
with open(self.moduledotfile_path(), "w") as f:
f.write(self.module.dump())
def clear(self):
if os.path.exists(self.modulefile_path()):
os.unlink(self.modulefile_path())
shutil.rmtree(self.module_path(), ignore_errors=True)
if len(self.available_versions()) == 0:
shutil.rmtree(self.module_base())
shutil.rmtree(self.modulefile_base())
class ModuleBuilder(ModuleLocation):
"""A module builder class."""
def __init__(self, module_tree, module):
super(ModuleBuilder, self).__init__(module_tree)
self.module = module
def category_name(self):
return self.module.category or self.module_tree.name
def shared(self):
return self.module.shared
def name(self):
return self.module.name
def version(self):
return self.module.version
def build(self):
os.makedirs(os.path.dirname(self.modulefile_path()), exist_ok=True)
os.symlink(self.module_tree.master_module_file(), self.modulefile_path())
os.makedirs(self.module_path())
self.save_module_file()
class ModuleLoader(ModuleLocation):
"""A module loader class."""
def __init__(self, module_tree, name, version=None):
"""
Loads a module. If no version is specified, the latest version is used.
:param module_tree: a ModuleTree object
:param name: The name of the module
:param version: The version of the module
"""
super(ModuleLoader, self).__init__(module_tree)
self._name = name
self._version = version
def category_name(self):
files = glob(os.path.join(self.module_tree.modulefile_dir(), "*", self.name()))
return os.path.basename(os.path.dirname(files[0]))
def shared(self):
return not os.path.exists(
os.path.join(
self.module_tree.root_dir, self.name(), self.version(), ".modulefile"
)
)
def shared_exists(self):
return os.path.exists(self.shared_moduledotfile_path())
def name(self):
return self._name
def version(self):
if self._version is None:
available_versions = self.available_versions()
if len(available_versions) == 0:
raise ValueError(f"No versions found for module {self.name()}")
return max(available_versions, key=util.version_key)
else:
return self._version
def load(self, force_shared=False, error_handler=util.raise_value_error):
self.module = Module.from_file(
self.moduledotfile_path(),
self.module_tree,
self.name(),
self.version(),
force_shared or self.shared(),
self.category_name(),
error_handler,
)
class Path:
"""A module path object"""
def __init__(self, path, operation="prepend-path", name="PATH"):
(self.operation, self.name) = operation, name
if "$basedir" in path:
self.path = path
else:
self.path = os.path.join("$basedir", os.path.basename(path.rstrip("/")))
def __repr__(self):
return f"{self.operation} {self.name} {self.path}"
def resolve(self, basedir):
"""replace the $basedir variable to the given path"""
return self.path.replace("$basedir", basedir)
class Module:
def __init__(
self,
root,
name,
version,
maintainer="no_maintainer",
helptext="",
description="",
extra_vars=None,
category=None,
shared=True,
extra_commands=None,
):
"""
Initialize a module.
:param root: the ModuleTree object under which this module exists
:param name: the name of the module (corresponding to the tool name)
:param version: the version of the module
:param maintainer: name and email address of the maintainer
:param helptext: the helptext for the module
:param description: longer form description of the module
:param extra_vars: a dict of extra variables to add
:param category: a category for the module
:param shared: whether the module file is shared among multiple versions
or, if false, is specific to this version
:param extra_commands: list of extra lines to add to the module file
"""
if extra_commands is None:
extra_commands = []
if extra_vars is None:
extra_vars = {}
self.root = root
self.name = name
self.version = version
self.maintainer = maintainer
self.helptext = helptext
self.description = description
self.category = category
self.shared = shared
self.extra_vars = extra_vars
self.extra_commands = extra_commands
self.paths = []
@classmethod
def from_file(
cls,
filename,
root,
name,
version,
shared,
category=None,
error_handler=util.raise_value_error,
):
"""parse a module file
:param filename: the path to the module dotfile
:param name: the package name for the module
:param version: the version of the module:
:param shared: whether the moduledotfile is located at the shared
:param category: the category of the module
:param error_handler: a which handles any parse errors during parsing.
If there is a parse error and a handler is provided, the line is
not interpreted and error handler is called. The default handler
raises a value error with the given error message.
:return: a new module parsed from the given file
"""
module = cls(root, name, version, shared=shared, category=category)
for line in open(filename):
try:
fields = shlex.split(line.strip())
except ValueError as e:
error_handler(f"parse error in {filename}: {e}")
continue
if len(fields) == 0:
continue
if fields[0] == "set":
if len(fields) < 3:
error_handler(f"Unparsable line in {filename}:\n{line}")
if fields[1] == "MAINTAINER":
module.maintainer = fields[2]
elif fields[1] == "HELPTEXT":
module.helptext = fields[2]
elif fields[1] == "DESCRIPTION":
module.description = fields[2]
else:
module.extra_vars.update({fields[1]: fields[2]})
elif fields[0] == "prepend-path" or fields[0] == "append-path":
module.paths.append(
Path(path=fields[2], operation=fields[0], name=fields[1])
)
else:
module.extra_commands.append(line.strip())
return module
def remove_path(self, path_obj):
"""
Remove the path from the module if the path_obj.path itself matches any of the paths in the module.
:param path_obj: a path object to compare to
:return:
"""
self.paths = [p for p in self.paths if p.path != path_obj.path]
def __repr__(self):
return f"{self.name}-{self.version}"
def dump(self):
"""Dump the module file as a string"""
text = (
f"""set MAINTAINER "{self.maintainer}"
set HELPTEXT "{self.helptext}"
set DESCRIPTION "{self.description}"\n"""
+ "\n".join([f'set {k} "{v}"' for k, v in self.extra_vars.items()])
+ "\n"
+ "\n".join(str(p) for p in self.paths)
+ "\n"
+ "\n".join(self.extra_commands)
)
return text | 0.622115 | 0.107063 |
import itertools
import gzip
import json
import shutil
from pathlib import Path
from typing import Iterable, Generator, List, Callable, TypeVar, Optional, Union, Any
def gzip_unpack(input_file: str, output_file: str):
with gzip.open(input_file, "rb") as packed:
with open(output_file, "wb") as unpacked:
shutil.copyfileobj(packed, unpacked)
def groupby(collection, key):
"""
:param list collection: collection to group
:param function, lambda key: lambda describe how to group
:rtype: dict
"""
# groupby wants sorted collection
sort = sorted(collection, key=key)
groups = itertools.groupby(sort, key)
return {key: list(value) for key, value in groups}
def split(collection, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(collection), n):
yield collection[i:i + n]
def flatten(collection: Iterable[Iterable]) -> Generator:
"""Flatten list of lists in one plane list"""
return (item for sublist in collection for item in sublist)
def dict_get_or_default(d: dict, index, default, convert=None):
if index in d:
value = d[index]
return convert(value) if convert is not None else value
else:
return default
def list_get_or_default(collection: List, index: int, default, convert=None):
if len(collection) > index:
value = collection[index]
return convert(value) if convert is not None else value
else:
return default
def list_get_or_throw(collection: List, index: int, message: str):
if len(collection) > index:
return collection[index]
else:
raise IndexError(message)
T = TypeVar('T')
def first(predicate: Callable[[T], bool], iterable: Iterable[T]) -> T:
return next(filter(predicate, iterable))
def find(predicate: Callable[[T], bool], iterable: Iterable) -> Optional[T]:
return next(filter(predicate, iterable), None)
def slice2range(s: slice, length=2 ** 32) -> range:
return range(*s.indices(length))
def read_json(path: Union[Path, str]):
with open(str(Path(path).absolute()), "rt") as file:
return json.loads(file.read())
def write_json(path: Union[Path, str], obj: Any):
with open(str(Path(path).absolute()), "wt") as file:
file.write(json.dumps(obj)) | utils/functions.py | import itertools
import gzip
import json
import shutil
from pathlib import Path
from typing import Iterable, Generator, List, Callable, TypeVar, Optional, Union, Any
def gzip_unpack(input_file: str, output_file: str):
with gzip.open(input_file, "rb") as packed:
with open(output_file, "wb") as unpacked:
shutil.copyfileobj(packed, unpacked)
def groupby(collection, key):
"""
:param list collection: collection to group
:param function, lambda key: lambda describe how to group
:rtype: dict
"""
# groupby wants sorted collection
sort = sorted(collection, key=key)
groups = itertools.groupby(sort, key)
return {key: list(value) for key, value in groups}
def split(collection, n):
"""Yield successive n-sized chunks from lst."""
for i in range(0, len(collection), n):
yield collection[i:i + n]
def flatten(collection: Iterable[Iterable]) -> Generator:
"""Flatten list of lists in one plane list"""
return (item for sublist in collection for item in sublist)
def dict_get_or_default(d: dict, index, default, convert=None):
if index in d:
value = d[index]
return convert(value) if convert is not None else value
else:
return default
def list_get_or_default(collection: List, index: int, default, convert=None):
if len(collection) > index:
value = collection[index]
return convert(value) if convert is not None else value
else:
return default
def list_get_or_throw(collection: List, index: int, message: str):
if len(collection) > index:
return collection[index]
else:
raise IndexError(message)
T = TypeVar('T')
def first(predicate: Callable[[T], bool], iterable: Iterable[T]) -> T:
return next(filter(predicate, iterable))
def find(predicate: Callable[[T], bool], iterable: Iterable) -> Optional[T]:
return next(filter(predicate, iterable), None)
def slice2range(s: slice, length=2 ** 32) -> range:
return range(*s.indices(length))
def read_json(path: Union[Path, str]):
with open(str(Path(path).absolute()), "rt") as file:
return json.loads(file.read())
def write_json(path: Union[Path, str], obj: Any):
with open(str(Path(path).absolute()), "wt") as file:
file.write(json.dumps(obj)) | 0.783409 | 0.303113 |
from __future__ import print_function
import re, atexit
@atexit.register
def graceful_exit():
from platform import system
if system() == 'Windows':
raw_input('Press enter to close the window...')
# add tab completion to raw_input, for those platforms that support it
try:
import readline
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
except ImportError:
pass
def graceful_read(filename):
try:
return open(filename, 'r').read()
except IOError as e:
print( "ERROR:", e.strerror )
exit()
def graceful_read_csv(filename):
from csv import DictReader
data = []
try:
f = open(filename, 'rb')
except IOError as e:
print( "ERROR:", e.strerror )
exit()
csvreader = DictReader(f)
while True:
try: row = csvreader.next()
except: break
data.append(row)
return data
def graceful_read_csv_list(csv):
data = graceful_read_csv(csv)
result = {}
for row in data:
# todo: check that 'list' exists here!
result[row['list']] = row
return result
def main(data, list_number, template_string):
from os.path import splitext
global substitution
substitution = data[str(list_number)]
def replacement(matchobj):
global substitution
return substitution[matchobj.group(1)]
output = re.sub(r'\$\{(\w+)\}', replacement, template_string)
name_part, extension = splitext(template)
filename = name_part + '.simulation' + extension
output_file = open(filename, 'w')
output_file.write("<h1>This is a simulation! Do not upload this file to Turk!</h1><hr/>")
output_file.write(output)
print( 'Successfully wrote simulation to', filename )
if __name__ == '__main__':
from sys import argv
template_string = ''
if len(argv) > 1:
template = argv[1]
template_string = graceful_read(template)
while re.search(r'\$\{(\w+)\}', template_string) is None:
if template_string != '':
print( "WARNING: This doesn't look like a template file!" )
template = raw_input("Please enter the template file name: ")
template_string = graceful_read(template)
csv = argv[2] if len(argv) > 2 else raw_input("Please enter the turk CSV file name: ")
data = graceful_read_csv_list(csv)
list_number = int(argv[3] if len(argv) > 3 else raw_input("Please enter the list number (0..{0}) you want to simulate: ".format(len(data) - 1)))
main(data, list_number, template_string) | simulator.py | from __future__ import print_function
import re, atexit
@atexit.register
def graceful_exit():
from platform import system
if system() == 'Windows':
raw_input('Press enter to close the window...')
# add tab completion to raw_input, for those platforms that support it
try:
import readline
if 'libedit' in readline.__doc__:
readline.parse_and_bind("bind ^I rl_complete")
else:
readline.parse_and_bind("tab: complete")
except ImportError:
pass
def graceful_read(filename):
try:
return open(filename, 'r').read()
except IOError as e:
print( "ERROR:", e.strerror )
exit()
def graceful_read_csv(filename):
from csv import DictReader
data = []
try:
f = open(filename, 'rb')
except IOError as e:
print( "ERROR:", e.strerror )
exit()
csvreader = DictReader(f)
while True:
try: row = csvreader.next()
except: break
data.append(row)
return data
def graceful_read_csv_list(csv):
data = graceful_read_csv(csv)
result = {}
for row in data:
# todo: check that 'list' exists here!
result[row['list']] = row
return result
def main(data, list_number, template_string):
from os.path import splitext
global substitution
substitution = data[str(list_number)]
def replacement(matchobj):
global substitution
return substitution[matchobj.group(1)]
output = re.sub(r'\$\{(\w+)\}', replacement, template_string)
name_part, extension = splitext(template)
filename = name_part + '.simulation' + extension
output_file = open(filename, 'w')
output_file.write("<h1>This is a simulation! Do not upload this file to Turk!</h1><hr/>")
output_file.write(output)
print( 'Successfully wrote simulation to', filename )
if __name__ == '__main__':
from sys import argv
template_string = ''
if len(argv) > 1:
template = argv[1]
template_string = graceful_read(template)
while re.search(r'\$\{(\w+)\}', template_string) is None:
if template_string != '':
print( "WARNING: This doesn't look like a template file!" )
template = raw_input("Please enter the template file name: ")
template_string = graceful_read(template)
csv = argv[2] if len(argv) > 2 else raw_input("Please enter the turk CSV file name: ")
data = graceful_read_csv_list(csv)
list_number = int(argv[3] if len(argv) > 3 else raw_input("Please enter the list number (0..{0}) you want to simulate: ".format(len(data) - 1)))
main(data, list_number, template_string) | 0.116512 | 0.066904 |
import os
import re
from django import forms
from django.conf import settings
from django.forms import ModelForm
from django.forms.models import modelformset_factory
from django.template import Context, Template, TemplateSyntaxError
import commonware.log
import happyforms
from piston.models import Consumer
from product_details import product_details
from tower import ugettext_lazy as _lazy
from quieter_formset.formset import BaseModelFormSet
from olympia import amo
from olympia.addons.models import Addon
from olympia.amo.urlresolvers import reverse
from olympia.applications.models import AppVersion
from olympia.bandwagon.models import (
Collection, FeaturedCollection, MonthlyPick)
from olympia.compat.forms import CompatForm as BaseCompatForm
from olympia.files.models import File
from olympia.zadmin.models import SiteEvent, ValidationJob
LOGGER_NAME = 'z.zadmin'
log = commonware.log.getLogger(LOGGER_NAME)
class DevMailerForm(happyforms.Form):
_choices = [('eula',
'Developers who have set up EULAs for active add-ons'),
('sdk', 'Developers of active SDK add-ons'),
('all_extensions', 'All extension developers')]
recipients = forms.ChoiceField(choices=_choices, required=True)
subject = forms.CharField(widget=forms.TextInput(attrs=dict(size='100')),
required=True)
preview_only = forms.BooleanField(initial=True, required=False,
label=u'Log emails instead of sending')
message = forms.CharField(widget=forms.Textarea, required=True)
class BulkValidationForm(happyforms.ModelForm):
application = forms.ChoiceField(
label=_lazy(u'Application'),
choices=amo.APPS_CHOICES)
curr_max_version = forms.ChoiceField(
label=_lazy(u'Current Max. Version'),
choices=[('', _lazy(u'Select an application first'))])
target_version = forms.ChoiceField(
label=_lazy(u'Target Version'),
choices=[('', _lazy(u'Select an application first'))])
finish_email = forms.CharField(
required=False,
label=_lazy(u'Email when finished'))
class Meta:
model = ValidationJob
fields = ('application', 'curr_max_version', 'target_version',
'finish_email')
def __init__(self, *args, **kw):
kw.setdefault('initial', {})
kw['initial']['finish_email'] = settings.FLIGTAR
super(BulkValidationForm, self).__init__(*args, **kw)
w = self.fields['application'].widget
# Get the URL after the urlconf has loaded.
w.attrs['data-url'] = reverse('zadmin.application_versions_json')
def version_choices_for_app_id(self, app_id):
versions = AppVersion.objects.filter(application=app_id)
return [(v.id, v.version) for v in versions]
def clean_application(self):
app_id = int(self.cleaned_data['application'])
self.cleaned_data['application'] = app_id
choices = self.version_choices_for_app_id(app_id)
self.fields['target_version'].choices = choices
self.fields['curr_max_version'].choices = choices
return self.cleaned_data['application']
def _clean_appversion(self, field):
return AppVersion.objects.get(pk=int(field))
def clean_curr_max_version(self):
return self._clean_appversion(self.cleaned_data['curr_max_version'])
def clean_target_version(self):
return self._clean_appversion(self.cleaned_data['target_version'])
path = os.path.join(settings.ROOT, 'src/olympia/zadmin/templates/zadmin')
texts = {
'validation': open('%s/%s' % (path, 'validation-email.txt')).read(),
}
varname = re.compile(r'{{\s*([a-zA-Z0-9_]+)\s*}}')
class NotifyForm(happyforms.Form):
subject = forms.CharField(widget=forms.TextInput, required=True)
preview_only = forms.BooleanField(
initial=True, required=False,
label=_lazy(u'Log emails instead of sending'))
text = forms.CharField(widget=forms.Textarea, required=True)
variables = ['{{PASSING_ADDONS}}', '{{FAILING_ADDONS}}', '{{APPLICATION}}',
'{{VERSION}}']
variable_names = [varname.match(v).group(1) for v in variables]
def __init__(self, *args, **kw):
kw.setdefault('initial', {})
if 'text' in kw:
kw['initial']['text'] = texts[kw.pop('text')]
kw['initial']['subject'] = ('Add-on compatibility with '
'{{APPLICATION}} {{VERSION}}')
super(NotifyForm, self).__init__(*args, **kw)
def check_template(self, data):
try:
Template(data).render(Context({}))
except TemplateSyntaxError, err:
raise forms.ValidationError(err)
return data
def clean_text(self):
return self.check_template(self.cleaned_data['text'])
def clean_subject(self):
return self.check_template(self.cleaned_data['subject'])
class FeaturedCollectionForm(happyforms.ModelForm):
LOCALES = (('', u'(Default Locale)'),) + tuple(
(i, product_details.languages[i]['native'])
for i in settings.AMO_LANGUAGES)
application = forms.ChoiceField(amo.APPS_CHOICES)
collection = forms.CharField(widget=forms.HiddenInput)
locale = forms.ChoiceField(choices=LOCALES, required=False)
class Meta:
model = FeaturedCollection
fields = ('application', 'locale')
def clean_collection(self):
application = self.cleaned_data.get('application', None)
collection = self.cleaned_data.get('collection', None)
if not Collection.objects.filter(id=collection,
application=application).exists():
raise forms.ValidationError(
u'Invalid collection for this application.')
return collection
def save(self, commit=False):
collection = self.cleaned_data['collection']
f = super(FeaturedCollectionForm, self).save(commit=commit)
f.collection = Collection.objects.get(id=collection)
f.save()
return f
class BaseFeaturedCollectionFormSet(BaseModelFormSet):
def __init__(self, *args, **kw):
super(BaseFeaturedCollectionFormSet, self).__init__(*args, **kw)
for form in self.initial_forms:
try:
form.initial['collection'] = (
FeaturedCollection.objects
.get(id=form.instance.id).collection.id)
except (FeaturedCollection.DoesNotExist, Collection.DoesNotExist):
form.initial['collection'] = None
FeaturedCollectionFormSet = modelformset_factory(
FeaturedCollection,
form=FeaturedCollectionForm, formset=BaseFeaturedCollectionFormSet,
can_delete=True, extra=0)
class OAuthConsumerForm(happyforms.ModelForm):
class Meta:
model = Consumer
fields = ['name', 'description', 'status']
class MonthlyPickForm(happyforms.ModelForm):
image = forms.CharField(required=False)
blurb = forms.CharField(max_length=200,
widget=forms.Textarea(attrs={'cols': 20,
'rows': 2}))
class Meta:
model = MonthlyPick
widgets = {
'addon': forms.TextInput(),
}
fields = ('addon', 'image', 'blurb', 'locale')
MonthlyPickFormSet = modelformset_factory(MonthlyPick, form=MonthlyPickForm,
can_delete=True, extra=0)
class AddonStatusForm(ModelForm):
class Meta:
model = Addon
fields = ('status', 'highest_status')
class FileStatusForm(ModelForm):
class Meta:
model = File
fields = ('status',)
FileFormSet = modelformset_factory(File, form=FileStatusForm,
formset=BaseModelFormSet, extra=0)
class SiteEventForm(ModelForm):
class Meta:
model = SiteEvent
fields = ('start', 'end', 'event_type', 'description',
'more_info_url')
class YesImSure(happyforms.Form):
yes = forms.BooleanField(required=True, label="Yes, I'm sure")
class CompatForm(BaseCompatForm):
_minimum_choices = [(x, x) for x in xrange(100, -10, -10)]
minimum = forms.TypedChoiceField(choices=_minimum_choices, coerce=int,
required=False)
_ratio_choices = [('%.1f' % (x / 10.0), '%.0f%%' % (x * 10))
for x in xrange(9, -1, -1)]
ratio = forms.ChoiceField(choices=_ratio_choices, required=False)
class GenerateErrorForm(happyforms.Form):
error = forms.ChoiceField(choices=(
['zerodivisionerror', 'Zero Division Error (will email)'],
['iorequesterror', 'IORequest Error (no email)'],
['heka_statsd', 'Heka statsd message'],
['heka_json', 'Heka JSON message'],
['heka_cef', 'Heka CEF message'],
['heka_sentry', 'Heka Sentry message'],
['amo_cef', 'AMO CEF message']))
def explode(self):
error = self.cleaned_data.get('error')
if error == 'zerodivisionerror':
1 / 0
elif error == 'iorequesterror':
class IOError(Exception):
pass
raise IOError('request data read error')
elif error == 'heka_cef':
environ = {'REMOTE_ADDR': '127.0.0.1', 'HTTP_HOST': '127.0.0.1',
'PATH_INFO': '/', 'REQUEST_METHOD': 'GET',
'HTTP_USER_AGENT': 'MySuperBrowser'}
config = {'cef.version': '0',
'cef.vendor': 'Mozilla',
'cef.device_version': '3',
'cef.product': 'zamboni',
'cef': True}
settings.HEKA.cef(
'xx\nx|xx\rx', 5, environ, config,
username='me', ext1='ok=ok', ext2='ok\\ok',
logger_info='settings.HEKA')
elif error == 'heka_statsd':
settings.HEKA.incr(name=LOGGER_NAME)
elif error == 'heka_json':
settings.HEKA.heka(
type="heka_json",
fields={'foo': 'bar', 'secret': 42,
'logger_type': 'settings.HEKA'})
elif error == 'heka_sentry':
# These are local variables only used
# by Sentry's frame hacking magic.
# They won't be referenced which may trigger flake8
# errors.
heka_conf = settings.HEKA_CONF # NOQA
active_heka_conf = settings.HEKA._config # NOQA
try:
1 / 0
except:
settings.HEKA.raven('heka_sentry error triggered')
elif error == 'amo_cef':
from olympia.amo.utils import log_cef
env = {'REMOTE_ADDR': '127.0.0.1', 'HTTP_HOST': '127.0.0.1',
'PATH_INFO': '/', 'REQUEST_METHOD': 'GET',
'HTTP_USER_AGENT': 'MySuperBrowser'}
log_cef(settings.STATSD_PREFIX, 6, env)
class PriceTiersForm(happyforms.Form):
prices = forms.FileField() | src/olympia/zadmin/forms.py | import os
import re
from django import forms
from django.conf import settings
from django.forms import ModelForm
from django.forms.models import modelformset_factory
from django.template import Context, Template, TemplateSyntaxError
import commonware.log
import happyforms
from piston.models import Consumer
from product_details import product_details
from tower import ugettext_lazy as _lazy
from quieter_formset.formset import BaseModelFormSet
from olympia import amo
from olympia.addons.models import Addon
from olympia.amo.urlresolvers import reverse
from olympia.applications.models import AppVersion
from olympia.bandwagon.models import (
Collection, FeaturedCollection, MonthlyPick)
from olympia.compat.forms import CompatForm as BaseCompatForm
from olympia.files.models import File
from olympia.zadmin.models import SiteEvent, ValidationJob
LOGGER_NAME = 'z.zadmin'
log = commonware.log.getLogger(LOGGER_NAME)
class DevMailerForm(happyforms.Form):
_choices = [('eula',
'Developers who have set up EULAs for active add-ons'),
('sdk', 'Developers of active SDK add-ons'),
('all_extensions', 'All extension developers')]
recipients = forms.ChoiceField(choices=_choices, required=True)
subject = forms.CharField(widget=forms.TextInput(attrs=dict(size='100')),
required=True)
preview_only = forms.BooleanField(initial=True, required=False,
label=u'Log emails instead of sending')
message = forms.CharField(widget=forms.Textarea, required=True)
class BulkValidationForm(happyforms.ModelForm):
application = forms.ChoiceField(
label=_lazy(u'Application'),
choices=amo.APPS_CHOICES)
curr_max_version = forms.ChoiceField(
label=_lazy(u'Current Max. Version'),
choices=[('', _lazy(u'Select an application first'))])
target_version = forms.ChoiceField(
label=_lazy(u'Target Version'),
choices=[('', _lazy(u'Select an application first'))])
finish_email = forms.CharField(
required=False,
label=_lazy(u'Email when finished'))
class Meta:
model = ValidationJob
fields = ('application', 'curr_max_version', 'target_version',
'finish_email')
def __init__(self, *args, **kw):
kw.setdefault('initial', {})
kw['initial']['finish_email'] = settings.FLIGTAR
super(BulkValidationForm, self).__init__(*args, **kw)
w = self.fields['application'].widget
# Get the URL after the urlconf has loaded.
w.attrs['data-url'] = reverse('zadmin.application_versions_json')
def version_choices_for_app_id(self, app_id):
versions = AppVersion.objects.filter(application=app_id)
return [(v.id, v.version) for v in versions]
def clean_application(self):
app_id = int(self.cleaned_data['application'])
self.cleaned_data['application'] = app_id
choices = self.version_choices_for_app_id(app_id)
self.fields['target_version'].choices = choices
self.fields['curr_max_version'].choices = choices
return self.cleaned_data['application']
def _clean_appversion(self, field):
return AppVersion.objects.get(pk=int(field))
def clean_curr_max_version(self):
return self._clean_appversion(self.cleaned_data['curr_max_version'])
def clean_target_version(self):
return self._clean_appversion(self.cleaned_data['target_version'])
path = os.path.join(settings.ROOT, 'src/olympia/zadmin/templates/zadmin')
texts = {
'validation': open('%s/%s' % (path, 'validation-email.txt')).read(),
}
varname = re.compile(r'{{\s*([a-zA-Z0-9_]+)\s*}}')
class NotifyForm(happyforms.Form):
subject = forms.CharField(widget=forms.TextInput, required=True)
preview_only = forms.BooleanField(
initial=True, required=False,
label=_lazy(u'Log emails instead of sending'))
text = forms.CharField(widget=forms.Textarea, required=True)
variables = ['{{PASSING_ADDONS}}', '{{FAILING_ADDONS}}', '{{APPLICATION}}',
'{{VERSION}}']
variable_names = [varname.match(v).group(1) for v in variables]
def __init__(self, *args, **kw):
kw.setdefault('initial', {})
if 'text' in kw:
kw['initial']['text'] = texts[kw.pop('text')]
kw['initial']['subject'] = ('Add-on compatibility with '
'{{APPLICATION}} {{VERSION}}')
super(NotifyForm, self).__init__(*args, **kw)
def check_template(self, data):
try:
Template(data).render(Context({}))
except TemplateSyntaxError, err:
raise forms.ValidationError(err)
return data
def clean_text(self):
return self.check_template(self.cleaned_data['text'])
def clean_subject(self):
return self.check_template(self.cleaned_data['subject'])
class FeaturedCollectionForm(happyforms.ModelForm):
LOCALES = (('', u'(Default Locale)'),) + tuple(
(i, product_details.languages[i]['native'])
for i in settings.AMO_LANGUAGES)
application = forms.ChoiceField(amo.APPS_CHOICES)
collection = forms.CharField(widget=forms.HiddenInput)
locale = forms.ChoiceField(choices=LOCALES, required=False)
class Meta:
model = FeaturedCollection
fields = ('application', 'locale')
def clean_collection(self):
application = self.cleaned_data.get('application', None)
collection = self.cleaned_data.get('collection', None)
if not Collection.objects.filter(id=collection,
application=application).exists():
raise forms.ValidationError(
u'Invalid collection for this application.')
return collection
def save(self, commit=False):
collection = self.cleaned_data['collection']
f = super(FeaturedCollectionForm, self).save(commit=commit)
f.collection = Collection.objects.get(id=collection)
f.save()
return f
class BaseFeaturedCollectionFormSet(BaseModelFormSet):
def __init__(self, *args, **kw):
super(BaseFeaturedCollectionFormSet, self).__init__(*args, **kw)
for form in self.initial_forms:
try:
form.initial['collection'] = (
FeaturedCollection.objects
.get(id=form.instance.id).collection.id)
except (FeaturedCollection.DoesNotExist, Collection.DoesNotExist):
form.initial['collection'] = None
FeaturedCollectionFormSet = modelformset_factory(
FeaturedCollection,
form=FeaturedCollectionForm, formset=BaseFeaturedCollectionFormSet,
can_delete=True, extra=0)
class OAuthConsumerForm(happyforms.ModelForm):
class Meta:
model = Consumer
fields = ['name', 'description', 'status']
class MonthlyPickForm(happyforms.ModelForm):
image = forms.CharField(required=False)
blurb = forms.CharField(max_length=200,
widget=forms.Textarea(attrs={'cols': 20,
'rows': 2}))
class Meta:
model = MonthlyPick
widgets = {
'addon': forms.TextInput(),
}
fields = ('addon', 'image', 'blurb', 'locale')
MonthlyPickFormSet = modelformset_factory(MonthlyPick, form=MonthlyPickForm,
can_delete=True, extra=0)
class AddonStatusForm(ModelForm):
class Meta:
model = Addon
fields = ('status', 'highest_status')
class FileStatusForm(ModelForm):
class Meta:
model = File
fields = ('status',)
FileFormSet = modelformset_factory(File, form=FileStatusForm,
formset=BaseModelFormSet, extra=0)
class SiteEventForm(ModelForm):
class Meta:
model = SiteEvent
fields = ('start', 'end', 'event_type', 'description',
'more_info_url')
class YesImSure(happyforms.Form):
yes = forms.BooleanField(required=True, label="Yes, I'm sure")
class CompatForm(BaseCompatForm):
_minimum_choices = [(x, x) for x in xrange(100, -10, -10)]
minimum = forms.TypedChoiceField(choices=_minimum_choices, coerce=int,
required=False)
_ratio_choices = [('%.1f' % (x / 10.0), '%.0f%%' % (x * 10))
for x in xrange(9, -1, -1)]
ratio = forms.ChoiceField(choices=_ratio_choices, required=False)
class GenerateErrorForm(happyforms.Form):
error = forms.ChoiceField(choices=(
['zerodivisionerror', 'Zero Division Error (will email)'],
['iorequesterror', 'IORequest Error (no email)'],
['heka_statsd', 'Heka statsd message'],
['heka_json', 'Heka JSON message'],
['heka_cef', 'Heka CEF message'],
['heka_sentry', 'Heka Sentry message'],
['amo_cef', 'AMO CEF message']))
def explode(self):
error = self.cleaned_data.get('error')
if error == 'zerodivisionerror':
1 / 0
elif error == 'iorequesterror':
class IOError(Exception):
pass
raise IOError('request data read error')
elif error == 'heka_cef':
environ = {'REMOTE_ADDR': '127.0.0.1', 'HTTP_HOST': '127.0.0.1',
'PATH_INFO': '/', 'REQUEST_METHOD': 'GET',
'HTTP_USER_AGENT': 'MySuperBrowser'}
config = {'cef.version': '0',
'cef.vendor': 'Mozilla',
'cef.device_version': '3',
'cef.product': 'zamboni',
'cef': True}
settings.HEKA.cef(
'xx\nx|xx\rx', 5, environ, config,
username='me', ext1='ok=ok', ext2='ok\\ok',
logger_info='settings.HEKA')
elif error == 'heka_statsd':
settings.HEKA.incr(name=LOGGER_NAME)
elif error == 'heka_json':
settings.HEKA.heka(
type="heka_json",
fields={'foo': 'bar', 'secret': 42,
'logger_type': 'settings.HEKA'})
elif error == 'heka_sentry':
# These are local variables only used
# by Sentry's frame hacking magic.
# They won't be referenced which may trigger flake8
# errors.
heka_conf = settings.HEKA_CONF # NOQA
active_heka_conf = settings.HEKA._config # NOQA
try:
1 / 0
except:
settings.HEKA.raven('heka_sentry error triggered')
elif error == 'amo_cef':
from olympia.amo.utils import log_cef
env = {'REMOTE_ADDR': '127.0.0.1', 'HTTP_HOST': '127.0.0.1',
'PATH_INFO': '/', 'REQUEST_METHOD': 'GET',
'HTTP_USER_AGENT': 'MySuperBrowser'}
log_cef(settings.STATSD_PREFIX, 6, env)
class PriceTiersForm(happyforms.Form):
prices = forms.FileField() | 0.427397 | 0.088583 |
import itertools
COLOR_WILD = 0
COLOR_RED = 1
COLOR_YELLOW = 2
COLOR_GREEN = 3
COLOR_BLUE = 4
CARD_0 = 0
CARD_1 = 1
CARD_2 = 2
CARD_3 = 3
CARD_4 = 4
CARD_5 = 5
CARD_6 = 6
CARD_7 = 7
CARD_8 = 8
CARD_9 = 9
CARD_SKIP = 10
CARD_REVERSE = 11
CARD_DRAWTWO = 12
CARD_WILD = 13
CARD_DRAWFOUR = 14
CARD_DRAWEIGHT = 15
CARD_SHUFFLEHANDS = 16
CARD_SPECIALS = [CARD_SKIP, CARD_REVERSE, CARD_DRAWTWO, CARD_DRAWFOUR, CARD_DRAWEIGHT]
CARD_WILDS = [CARD_WILD, CARD_DRAWFOUR, CARD_DRAWEIGHT, CARD_SHUFFLEHANDS]
COLOR_STRINGS = {COLOR_RED: "red",
COLOR_YELLOW: "yellow",
COLOR_GREEN: "green",
COLOR_BLUE: "blue"}
CARD_NONWILD_STRINGS = {CARD_0: "0",
CARD_1: "1",
CARD_2: "2",
CARD_3: "3",
CARD_4: "4",
CARD_5: "5",
CARD_6: "6",
CARD_7: "7",
CARD_8: "8",
CARD_9: "9",
CARD_SKIP: "skip",
CARD_REVERSE: "reverse",
CARD_DRAWTWO: "+2",
CARD_WILD: "wild",
CARD_DRAWFOUR: "wild +4",
CARD_DRAWEIGHT: "wild +8",
CARD_SHUFFLEHANDS: "shuffle hands"}
# CARDS = [tuple(x) for x in itertools.product(COLOR_STRINGS.keys(), range(13))]
# CARDS *= 2
# CARDS.remove((COLOR_RED, CARD_0))
# CARDS.remove((COLOR_YELLOW, CARD_0))
# CARDS.remove((COLOR_GREEN, CARD_0))
# CARDS.remove((COLOR_BLUE, CARD_0))
# CARDS += [
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWEIGHT)
# ]
CARDS = [(COLOR_RED, CARD_0),
(COLOR_RED, CARD_1),
(COLOR_RED, CARD_1),
(COLOR_RED, CARD_2),
(COLOR_RED, CARD_2),
(COLOR_RED, CARD_3),
(COLOR_RED, CARD_3),
(COLOR_RED, CARD_4),
(COLOR_RED, CARD_4),
(COLOR_RED, CARD_5),
(COLOR_RED, CARD_5),
(COLOR_RED, CARD_6),
(COLOR_RED, CARD_6),
(COLOR_RED, CARD_7),
(COLOR_RED, CARD_7),
(COLOR_RED, CARD_8),
(COLOR_RED, CARD_8),
(COLOR_RED, CARD_9),
(COLOR_RED, CARD_9),
(COLOR_RED, CARD_SKIP),
(COLOR_RED, CARD_SKIP),
(COLOR_RED, CARD_REVERSE),
(COLOR_RED, CARD_REVERSE),
(COLOR_RED, CARD_DRAWTWO),
(COLOR_RED, CARD_DRAWTWO),
(COLOR_YELLOW, CARD_0),
(COLOR_YELLOW, CARD_1),
(COLOR_YELLOW, CARD_1),
(COLOR_YELLOW, CARD_2),
(COLOR_YELLOW, CARD_2),
(COLOR_YELLOW, CARD_3),
(COLOR_YELLOW, CARD_3),
(COLOR_YELLOW, CARD_4),
(COLOR_YELLOW, CARD_4),
(COLOR_YELLOW, CARD_5),
(COLOR_YELLOW, CARD_5),
(COLOR_YELLOW, CARD_6),
(COLOR_YELLOW, CARD_6),
(COLOR_YELLOW, CARD_7),
(COLOR_YELLOW, CARD_7),
(COLOR_YELLOW, CARD_8),
(COLOR_YELLOW, CARD_8),
(COLOR_YELLOW, CARD_9),
(COLOR_YELLOW, CARD_9),
(COLOR_YELLOW, CARD_SKIP),
(COLOR_YELLOW, CARD_SKIP),
(COLOR_YELLOW, CARD_REVERSE),
(COLOR_YELLOW, CARD_REVERSE),
(COLOR_YELLOW, CARD_DRAWTWO),
(COLOR_YELLOW, CARD_DRAWTWO),
(COLOR_GREEN, CARD_0),
(COLOR_GREEN, CARD_1),
(COLOR_GREEN, CARD_1),
(COLOR_GREEN, CARD_2),
(COLOR_GREEN, CARD_2),
(COLOR_GREEN, CARD_3),
(COLOR_GREEN, CARD_3),
(COLOR_GREEN, CARD_4),
(COLOR_GREEN, CARD_4),
(COLOR_GREEN, CARD_5),
(COLOR_GREEN, CARD_5),
(COLOR_GREEN, CARD_6),
(COLOR_GREEN, CARD_6),
(COLOR_GREEN, CARD_7),
(COLOR_GREEN, CARD_7),
(COLOR_GREEN, CARD_8),
(COLOR_GREEN, CARD_8),
(COLOR_GREEN, CARD_9),
(COLOR_GREEN, CARD_9),
(COLOR_GREEN, CARD_SKIP),
(COLOR_GREEN, CARD_SKIP),
(COLOR_GREEN, CARD_REVERSE),
(COLOR_GREEN, CARD_REVERSE),
(COLOR_GREEN, CARD_DRAWTWO),
(COLOR_GREEN, CARD_DRAWTWO),
(COLOR_BLUE, CARD_0),
(COLOR_BLUE, CARD_1),
(COLOR_BLUE, CARD_1),
(COLOR_BLUE, CARD_2),
(COLOR_BLUE, CARD_2),
(COLOR_BLUE, CARD_3),
(COLOR_BLUE, CARD_3),
(COLOR_BLUE, CARD_4),
(COLOR_BLUE, CARD_4),
(COLOR_BLUE, CARD_5),
(COLOR_BLUE, CARD_5),
(COLOR_BLUE, CARD_6),
(COLOR_BLUE, CARD_6),
(COLOR_BLUE, CARD_7),
(COLOR_BLUE, CARD_7),
(COLOR_BLUE, CARD_8),
(COLOR_BLUE, CARD_8),
(COLOR_BLUE, CARD_9),
(COLOR_BLUE, CARD_9),
(COLOR_BLUE, CARD_SKIP),
(COLOR_BLUE, CARD_SKIP),
(COLOR_BLUE, CARD_REVERSE),
(COLOR_BLUE, CARD_REVERSE),
(COLOR_BLUE, CARD_DRAWTWO),
(COLOR_BLUE, CARD_DRAWTWO),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWEIGHT)]
CARD_EMOJIS = {(COLOR_RED, CARD_0): "<:red0:642807175865040925>",
(COLOR_RED, CARD_1): "<:red1:642807175378632745>",
(COLOR_RED, CARD_2): "<:red2:642807176070561852>",
(COLOR_RED, CARD_3): "<:red3:642807175911047179>",
(COLOR_RED, CARD_4): "<:red4:642807175533559811>",
(COLOR_RED, CARD_5): "<:red5:642807175906852874>",
(COLOR_RED, CARD_6): "<:red6:642807176045395979>",
(COLOR_RED, CARD_7): "<:red7:642807175734886413>",
(COLOR_RED, CARD_8): "<:red8:642807176041070592>",
(COLOR_RED, CARD_9): "<:red9:642807176158773258>",
(COLOR_RED, CARD_SKIP): "<:redskip:642806932528169002>",
(COLOR_RED, CARD_REVERSE): "<:redreverse:642806932285030401>",
(COLOR_RED, CARD_DRAWTWO): "<:reddraw2:642806932591083530>",
(COLOR_RED, CARD_WILD): "<:redwild:643174385234083842>",
(COLOR_RED, CARD_DRAWFOUR): "<:redwilddraw4:643482873940148264>",
(COLOR_RED, CARD_DRAWEIGHT): "<:redwilddraw8:654772088258822175>",
(COLOR_RED, CARD_SHUFFLEHANDS): "<:redshufflehands:643995233645887499>",
(COLOR_YELLOW, CARD_0): "<:yellow0:642807176062304256>",
(COLOR_YELLOW, CARD_1): "<:yellow1:642807175584153600>",
(COLOR_YELLOW, CARD_2): "<:yellow2:642807175932018709>",
(COLOR_YELLOW, CARD_3): "<:yellow3:642807176188133386>",
(COLOR_YELLOW, CARD_4): "<:yellow4:642807175902658575>",
(COLOR_YELLOW, CARD_5): "<:yellow5:642807176410431568>",
(COLOR_YELLOW, CARD_6): "<:yellow6:642807176540323840>",
(COLOR_YELLOW, CARD_7): "<:yellow7:642807176120893451>",
(COLOR_YELLOW, CARD_8): "<:yellow8:642807176330608641>",
(COLOR_YELLOW, CARD_9): "<:yellow9:642807176485928971>",
(COLOR_YELLOW, CARD_SKIP): "<:yellowskip:642806933367291913>",
(COLOR_YELLOW, CARD_REVERSE): "<:yellowreverse:642806933136605184>",
(COLOR_YELLOW, CARD_DRAWTWO): "<:yellowdraw2:642806933358903326>",
(COLOR_YELLOW, CARD_WILD): "<:yellowwild:643174385607376946>",
(COLOR_YELLOW, CARD_DRAWFOUR): "<:yellowwilddraw4:643482874041073712>",
(COLOR_YELLOW, CARD_DRAWEIGHT): "<:yellowwilddraw8:654772088439177217>",
(COLOR_YELLOW, CARD_SHUFFLEHANDS): "<:yellowshufflehands:643992482883043348>",
(COLOR_GREEN, CARD_0): "<:green0:642807173658837043>",
(COLOR_GREEN, CARD_1): "<:green1:642807173881135151>",
(COLOR_GREEN, CARD_2): "<:green2:642807173927272492>",
(COLOR_GREEN, CARD_3): "<:green3:642807174476726312>",
(COLOR_GREEN, CARD_4): "<:green4:642807174409748510>",
(COLOR_GREEN, CARD_5): "<:green5:642807174514343946>",
(COLOR_GREEN, CARD_6): "<:green6:642807174610944029>",
(COLOR_GREEN, CARD_7): "<:green7:642807174422200340>",
(COLOR_GREEN, CARD_8): "<:green8:642807174602686464>",
(COLOR_GREEN, CARD_9): "<:green9:642807176171094035>",
(COLOR_GREEN, CARD_SKIP): "<:greenskip:642806932486225920>",
(COLOR_GREEN, CARD_REVERSE): "<:greenreverse:642806932310065182>",
(COLOR_GREEN, CARD_DRAWTWO): "<:greendraw2:642806932016594955>",
(COLOR_GREEN, CARD_WILD): "<:greenwild:643174385414438924>",
(COLOR_GREEN, CARD_DRAWFOUR): "<:greenwilddraw4:643482874007257112>",
(COLOR_GREEN, CARD_DRAWEIGHT): "<:greenwilddraw8:654772088078598155>",
(COLOR_GREEN, CARD_SHUFFLEHANDS): "<:greenshufflehands:643992482442510337>",
(COLOR_BLUE, CARD_0): "<:blue0:642807172765450280>",
(COLOR_BLUE, CARD_1): "<:blue1:642807172513660977>",
(COLOR_BLUE, CARD_2): "<:blue2:642807174317342754>",
(COLOR_BLUE, CARD_3): "<:blue3:642807172920770561>",
(COLOR_BLUE, CARD_4): "<:blue4:642807172815650858>",
(COLOR_BLUE, CARD_5): "<:blue5:642807173176492032>",
(COLOR_BLUE, CARD_6): "<:blue6:642807173503647745>",
(COLOR_BLUE, CARD_7): "<:blue7:642807173570887681>",
(COLOR_BLUE, CARD_8): "<:blue8:642807173599985664>",
(COLOR_BLUE, CARD_9): "<:blue9:642807173574819860>",
(COLOR_BLUE, CARD_SKIP): "<:blueskip:642806932045955073>",
(COLOR_BLUE, CARD_REVERSE): "<:bluereverse:642806931647627266>",
(COLOR_BLUE, CARD_DRAWTWO): "<:bluedraw2:642806931332792339>",
(COLOR_BLUE, CARD_WILD): "<:bluewild:643174385213112349>",
(COLOR_BLUE, CARD_DRAWFOUR): "<:bluewilddraw4:643482873717850128>",
(COLOR_BLUE, CARD_DRAWEIGHT): "<:bluewilddraw8:654772088288313394>",
(COLOR_BLUE, CARD_SHUFFLEHANDS): "<:blueshufflehands:643992482610282518>",
(COLOR_WILD, CARD_WILD): "<:wild:642806933383806976>",
(COLOR_WILD, CARD_DRAWFOUR): "<:wilddraw4:642806933065039903>",
(COLOR_WILD, CARD_DRAWEIGHT): "<:wilddraw8:654772088451891220>",
(COLOR_WILD, CARD_SHUFFLEHANDS): "<:shufflehands:642803897961938987>"}
CARD_STRINGS = {(color, card): COLOR_STRINGS[color] + " " + CARD_NONWILD_STRINGS[card]
for (color, card) in itertools.product(COLOR_STRINGS.keys(), CARD_NONWILD_STRINGS.keys())}
CARD_STRINGS.update({(COLOR_WILD, CARD_WILD): "wild",
(COLOR_WILD, CARD_DRAWFOUR): "wild +4",
(COLOR_WILD, CARD_DRAWEIGHT): "wild +8",
(COLOR_WILD, CARD_SHUFFLEHANDS): "shuffle hands"})
CARD_STRINGS_REVERSED = {v: k for k, v in CARD_STRINGS.items()} | modules/games/uno_vars.py | import itertools
COLOR_WILD = 0
COLOR_RED = 1
COLOR_YELLOW = 2
COLOR_GREEN = 3
COLOR_BLUE = 4
CARD_0 = 0
CARD_1 = 1
CARD_2 = 2
CARD_3 = 3
CARD_4 = 4
CARD_5 = 5
CARD_6 = 6
CARD_7 = 7
CARD_8 = 8
CARD_9 = 9
CARD_SKIP = 10
CARD_REVERSE = 11
CARD_DRAWTWO = 12
CARD_WILD = 13
CARD_DRAWFOUR = 14
CARD_DRAWEIGHT = 15
CARD_SHUFFLEHANDS = 16
CARD_SPECIALS = [CARD_SKIP, CARD_REVERSE, CARD_DRAWTWO, CARD_DRAWFOUR, CARD_DRAWEIGHT]
CARD_WILDS = [CARD_WILD, CARD_DRAWFOUR, CARD_DRAWEIGHT, CARD_SHUFFLEHANDS]
COLOR_STRINGS = {COLOR_RED: "red",
COLOR_YELLOW: "yellow",
COLOR_GREEN: "green",
COLOR_BLUE: "blue"}
CARD_NONWILD_STRINGS = {CARD_0: "0",
CARD_1: "1",
CARD_2: "2",
CARD_3: "3",
CARD_4: "4",
CARD_5: "5",
CARD_6: "6",
CARD_7: "7",
CARD_8: "8",
CARD_9: "9",
CARD_SKIP: "skip",
CARD_REVERSE: "reverse",
CARD_DRAWTWO: "+2",
CARD_WILD: "wild",
CARD_DRAWFOUR: "wild +4",
CARD_DRAWEIGHT: "wild +8",
CARD_SHUFFLEHANDS: "shuffle hands"}
# CARDS = [tuple(x) for x in itertools.product(COLOR_STRINGS.keys(), range(13))]
# CARDS *= 2
# CARDS.remove((COLOR_RED, CARD_0))
# CARDS.remove((COLOR_YELLOW, CARD_0))
# CARDS.remove((COLOR_GREEN, CARD_0))
# CARDS.remove((COLOR_BLUE, CARD_0))
# CARDS += [
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_WILD),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWFOUR),
# (COLOR_WILD, CARD_DRAWEIGHT)
# ]
CARDS = [(COLOR_RED, CARD_0),
(COLOR_RED, CARD_1),
(COLOR_RED, CARD_1),
(COLOR_RED, CARD_2),
(COLOR_RED, CARD_2),
(COLOR_RED, CARD_3),
(COLOR_RED, CARD_3),
(COLOR_RED, CARD_4),
(COLOR_RED, CARD_4),
(COLOR_RED, CARD_5),
(COLOR_RED, CARD_5),
(COLOR_RED, CARD_6),
(COLOR_RED, CARD_6),
(COLOR_RED, CARD_7),
(COLOR_RED, CARD_7),
(COLOR_RED, CARD_8),
(COLOR_RED, CARD_8),
(COLOR_RED, CARD_9),
(COLOR_RED, CARD_9),
(COLOR_RED, CARD_SKIP),
(COLOR_RED, CARD_SKIP),
(COLOR_RED, CARD_REVERSE),
(COLOR_RED, CARD_REVERSE),
(COLOR_RED, CARD_DRAWTWO),
(COLOR_RED, CARD_DRAWTWO),
(COLOR_YELLOW, CARD_0),
(COLOR_YELLOW, CARD_1),
(COLOR_YELLOW, CARD_1),
(COLOR_YELLOW, CARD_2),
(COLOR_YELLOW, CARD_2),
(COLOR_YELLOW, CARD_3),
(COLOR_YELLOW, CARD_3),
(COLOR_YELLOW, CARD_4),
(COLOR_YELLOW, CARD_4),
(COLOR_YELLOW, CARD_5),
(COLOR_YELLOW, CARD_5),
(COLOR_YELLOW, CARD_6),
(COLOR_YELLOW, CARD_6),
(COLOR_YELLOW, CARD_7),
(COLOR_YELLOW, CARD_7),
(COLOR_YELLOW, CARD_8),
(COLOR_YELLOW, CARD_8),
(COLOR_YELLOW, CARD_9),
(COLOR_YELLOW, CARD_9),
(COLOR_YELLOW, CARD_SKIP),
(COLOR_YELLOW, CARD_SKIP),
(COLOR_YELLOW, CARD_REVERSE),
(COLOR_YELLOW, CARD_REVERSE),
(COLOR_YELLOW, CARD_DRAWTWO),
(COLOR_YELLOW, CARD_DRAWTWO),
(COLOR_GREEN, CARD_0),
(COLOR_GREEN, CARD_1),
(COLOR_GREEN, CARD_1),
(COLOR_GREEN, CARD_2),
(COLOR_GREEN, CARD_2),
(COLOR_GREEN, CARD_3),
(COLOR_GREEN, CARD_3),
(COLOR_GREEN, CARD_4),
(COLOR_GREEN, CARD_4),
(COLOR_GREEN, CARD_5),
(COLOR_GREEN, CARD_5),
(COLOR_GREEN, CARD_6),
(COLOR_GREEN, CARD_6),
(COLOR_GREEN, CARD_7),
(COLOR_GREEN, CARD_7),
(COLOR_GREEN, CARD_8),
(COLOR_GREEN, CARD_8),
(COLOR_GREEN, CARD_9),
(COLOR_GREEN, CARD_9),
(COLOR_GREEN, CARD_SKIP),
(COLOR_GREEN, CARD_SKIP),
(COLOR_GREEN, CARD_REVERSE),
(COLOR_GREEN, CARD_REVERSE),
(COLOR_GREEN, CARD_DRAWTWO),
(COLOR_GREEN, CARD_DRAWTWO),
(COLOR_BLUE, CARD_0),
(COLOR_BLUE, CARD_1),
(COLOR_BLUE, CARD_1),
(COLOR_BLUE, CARD_2),
(COLOR_BLUE, CARD_2),
(COLOR_BLUE, CARD_3),
(COLOR_BLUE, CARD_3),
(COLOR_BLUE, CARD_4),
(COLOR_BLUE, CARD_4),
(COLOR_BLUE, CARD_5),
(COLOR_BLUE, CARD_5),
(COLOR_BLUE, CARD_6),
(COLOR_BLUE, CARD_6),
(COLOR_BLUE, CARD_7),
(COLOR_BLUE, CARD_7),
(COLOR_BLUE, CARD_8),
(COLOR_BLUE, CARD_8),
(COLOR_BLUE, CARD_9),
(COLOR_BLUE, CARD_9),
(COLOR_BLUE, CARD_SKIP),
(COLOR_BLUE, CARD_SKIP),
(COLOR_BLUE, CARD_REVERSE),
(COLOR_BLUE, CARD_REVERSE),
(COLOR_BLUE, CARD_DRAWTWO),
(COLOR_BLUE, CARD_DRAWTWO),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_WILD),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWFOUR),
(COLOR_WILD, CARD_DRAWEIGHT)]
CARD_EMOJIS = {(COLOR_RED, CARD_0): "<:red0:642807175865040925>",
(COLOR_RED, CARD_1): "<:red1:642807175378632745>",
(COLOR_RED, CARD_2): "<:red2:642807176070561852>",
(COLOR_RED, CARD_3): "<:red3:642807175911047179>",
(COLOR_RED, CARD_4): "<:red4:642807175533559811>",
(COLOR_RED, CARD_5): "<:red5:642807175906852874>",
(COLOR_RED, CARD_6): "<:red6:642807176045395979>",
(COLOR_RED, CARD_7): "<:red7:642807175734886413>",
(COLOR_RED, CARD_8): "<:red8:642807176041070592>",
(COLOR_RED, CARD_9): "<:red9:642807176158773258>",
(COLOR_RED, CARD_SKIP): "<:redskip:642806932528169002>",
(COLOR_RED, CARD_REVERSE): "<:redreverse:642806932285030401>",
(COLOR_RED, CARD_DRAWTWO): "<:reddraw2:642806932591083530>",
(COLOR_RED, CARD_WILD): "<:redwild:643174385234083842>",
(COLOR_RED, CARD_DRAWFOUR): "<:redwilddraw4:643482873940148264>",
(COLOR_RED, CARD_DRAWEIGHT): "<:redwilddraw8:654772088258822175>",
(COLOR_RED, CARD_SHUFFLEHANDS): "<:redshufflehands:643995233645887499>",
(COLOR_YELLOW, CARD_0): "<:yellow0:642807176062304256>",
(COLOR_YELLOW, CARD_1): "<:yellow1:642807175584153600>",
(COLOR_YELLOW, CARD_2): "<:yellow2:642807175932018709>",
(COLOR_YELLOW, CARD_3): "<:yellow3:642807176188133386>",
(COLOR_YELLOW, CARD_4): "<:yellow4:642807175902658575>",
(COLOR_YELLOW, CARD_5): "<:yellow5:642807176410431568>",
(COLOR_YELLOW, CARD_6): "<:yellow6:642807176540323840>",
(COLOR_YELLOW, CARD_7): "<:yellow7:642807176120893451>",
(COLOR_YELLOW, CARD_8): "<:yellow8:642807176330608641>",
(COLOR_YELLOW, CARD_9): "<:yellow9:642807176485928971>",
(COLOR_YELLOW, CARD_SKIP): "<:yellowskip:642806933367291913>",
(COLOR_YELLOW, CARD_REVERSE): "<:yellowreverse:642806933136605184>",
(COLOR_YELLOW, CARD_DRAWTWO): "<:yellowdraw2:642806933358903326>",
(COLOR_YELLOW, CARD_WILD): "<:yellowwild:643174385607376946>",
(COLOR_YELLOW, CARD_DRAWFOUR): "<:yellowwilddraw4:643482874041073712>",
(COLOR_YELLOW, CARD_DRAWEIGHT): "<:yellowwilddraw8:654772088439177217>",
(COLOR_YELLOW, CARD_SHUFFLEHANDS): "<:yellowshufflehands:643992482883043348>",
(COLOR_GREEN, CARD_0): "<:green0:642807173658837043>",
(COLOR_GREEN, CARD_1): "<:green1:642807173881135151>",
(COLOR_GREEN, CARD_2): "<:green2:642807173927272492>",
(COLOR_GREEN, CARD_3): "<:green3:642807174476726312>",
(COLOR_GREEN, CARD_4): "<:green4:642807174409748510>",
(COLOR_GREEN, CARD_5): "<:green5:642807174514343946>",
(COLOR_GREEN, CARD_6): "<:green6:642807174610944029>",
(COLOR_GREEN, CARD_7): "<:green7:642807174422200340>",
(COLOR_GREEN, CARD_8): "<:green8:642807174602686464>",
(COLOR_GREEN, CARD_9): "<:green9:642807176171094035>",
(COLOR_GREEN, CARD_SKIP): "<:greenskip:642806932486225920>",
(COLOR_GREEN, CARD_REVERSE): "<:greenreverse:642806932310065182>",
(COLOR_GREEN, CARD_DRAWTWO): "<:greendraw2:642806932016594955>",
(COLOR_GREEN, CARD_WILD): "<:greenwild:643174385414438924>",
(COLOR_GREEN, CARD_DRAWFOUR): "<:greenwilddraw4:643482874007257112>",
(COLOR_GREEN, CARD_DRAWEIGHT): "<:greenwilddraw8:654772088078598155>",
(COLOR_GREEN, CARD_SHUFFLEHANDS): "<:greenshufflehands:643992482442510337>",
(COLOR_BLUE, CARD_0): "<:blue0:642807172765450280>",
(COLOR_BLUE, CARD_1): "<:blue1:642807172513660977>",
(COLOR_BLUE, CARD_2): "<:blue2:642807174317342754>",
(COLOR_BLUE, CARD_3): "<:blue3:642807172920770561>",
(COLOR_BLUE, CARD_4): "<:blue4:642807172815650858>",
(COLOR_BLUE, CARD_5): "<:blue5:642807173176492032>",
(COLOR_BLUE, CARD_6): "<:blue6:642807173503647745>",
(COLOR_BLUE, CARD_7): "<:blue7:642807173570887681>",
(COLOR_BLUE, CARD_8): "<:blue8:642807173599985664>",
(COLOR_BLUE, CARD_9): "<:blue9:642807173574819860>",
(COLOR_BLUE, CARD_SKIP): "<:blueskip:642806932045955073>",
(COLOR_BLUE, CARD_REVERSE): "<:bluereverse:642806931647627266>",
(COLOR_BLUE, CARD_DRAWTWO): "<:bluedraw2:642806931332792339>",
(COLOR_BLUE, CARD_WILD): "<:bluewild:643174385213112349>",
(COLOR_BLUE, CARD_DRAWFOUR): "<:bluewilddraw4:643482873717850128>",
(COLOR_BLUE, CARD_DRAWEIGHT): "<:bluewilddraw8:654772088288313394>",
(COLOR_BLUE, CARD_SHUFFLEHANDS): "<:blueshufflehands:643992482610282518>",
(COLOR_WILD, CARD_WILD): "<:wild:642806933383806976>",
(COLOR_WILD, CARD_DRAWFOUR): "<:wilddraw4:642806933065039903>",
(COLOR_WILD, CARD_DRAWEIGHT): "<:wilddraw8:654772088451891220>",
(COLOR_WILD, CARD_SHUFFLEHANDS): "<:shufflehands:642803897961938987>"}
CARD_STRINGS = {(color, card): COLOR_STRINGS[color] + " " + CARD_NONWILD_STRINGS[card]
for (color, card) in itertools.product(COLOR_STRINGS.keys(), CARD_NONWILD_STRINGS.keys())}
CARD_STRINGS.update({(COLOR_WILD, CARD_WILD): "wild",
(COLOR_WILD, CARD_DRAWFOUR): "wild +4",
(COLOR_WILD, CARD_DRAWEIGHT): "wild +8",
(COLOR_WILD, CARD_SHUFFLEHANDS): "shuffle hands"})
CARD_STRINGS_REVERSED = {v: k for k, v in CARD_STRINGS.items()} | 0.221267 | 0.0745 |
from moontracker.models import Alert
from tests.utils import test_client
def test_valid_post():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(Alert.phone_number == '5558675309',
Alert.symbol == 'BTC', Alert.price == 100.0,
Alert.condition).all()
assert len(results) == 1
def test_percent_above():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'coinbase',
'cond_option': '2',
'percent': '100',
'percent_duration': '86400'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(
Alert.phone_number == '5558675309',
Alert.symbol == 'BTC',
Alert.percent == 100.0,
Alert.condition == 2,
Alert.percent_duration).all()
assert len(results) == 1
def test_percent_below():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '3',
'percent': '100',
'percent_duration': '86400'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(
Alert.phone_number == '5558675309',
Alert.symbol == 'BTC',
Alert.percent == 100.0,
Alert.condition == 3,
Alert.percent_duration).all()
assert len(results) == 1
def test_valid_post_below():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '0',
'price': '100'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(Alert.phone_number == '5558675309',
Alert.symbol == 'BTC', Alert.price == 100.0,
Alert.condition == 0).all()
assert len(results) == 1
def test_short_phonenumber():
response = test_client.post(
'/',
data={
'phone_number': '3',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert 'Please enter a valid phone number' in str(response.data)
results = Alert.query.filter().all()
assert len(results) == 0
def test_nonint_phonenumber():
response = test_client.post(
'/',
data={
'phone_number': 'aaaaa',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert 'Please enter a valid phone number' in str(response.data)
results = Alert.query.filter().all()
assert len(results) == 0
def test_nonint_price():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gdax',
'cond_option': '1',
'price': 'aaaaa'
})
assert response.status_code == 200
assert 'Not a valid float value' in str(response.data)
results = Alert.query.filter().all()
assert len(results) == 0
def test_product_page():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'coinbase',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert 'Alert is set!' in str(response.data)
results = Alert.query.filter(Alert.phone_number == '5558675309',
Alert.symbol == 'BTC',
Alert.price == 100.0,
Alert.condition == 1,
Alert.market == 'coinbase').all()
assert len(results) == 1
def test_bad_market_page():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'nasdaq',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert "Invalid value, must be one of:" in str(response.data)
def test_no_asset_choice():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'market': 'nasdaq',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert "Not a valid choice" in str(response.data) | tests/views/test_home.py | from moontracker.models import Alert
from tests.utils import test_client
def test_valid_post():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(Alert.phone_number == '5558675309',
Alert.symbol == 'BTC', Alert.price == 100.0,
Alert.condition).all()
assert len(results) == 1
def test_percent_above():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'coinbase',
'cond_option': '2',
'percent': '100',
'percent_duration': '86400'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(
Alert.phone_number == '5558675309',
Alert.symbol == 'BTC',
Alert.percent == 100.0,
Alert.condition == 2,
Alert.percent_duration).all()
assert len(results) == 1
def test_percent_below():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '3',
'percent': '100',
'percent_duration': '86400'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(
Alert.phone_number == '5558675309',
Alert.symbol == 'BTC',
Alert.percent == 100.0,
Alert.condition == 3,
Alert.percent_duration).all()
assert len(results) == 1
def test_valid_post_below():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '0',
'price': '100'
})
assert response.status_code == 200
assert "Please do the recaptcha" not in str(response.data)
results = Alert.query.filter(Alert.phone_number == '5558675309',
Alert.symbol == 'BTC', Alert.price == 100.0,
Alert.condition == 0).all()
assert len(results) == 1
def test_short_phonenumber():
response = test_client.post(
'/',
data={
'phone_number': '3',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert 'Please enter a valid phone number' in str(response.data)
results = Alert.query.filter().all()
assert len(results) == 0
def test_nonint_phonenumber():
response = test_client.post(
'/',
data={
'phone_number': 'aaaaa',
'asset': 'BTC',
'market': 'gemini',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert 'Please enter a valid phone number' in str(response.data)
results = Alert.query.filter().all()
assert len(results) == 0
def test_nonint_price():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'gdax',
'cond_option': '1',
'price': 'aaaaa'
})
assert response.status_code == 200
assert 'Not a valid float value' in str(response.data)
results = Alert.query.filter().all()
assert len(results) == 0
def test_product_page():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'coinbase',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert 'Alert is set!' in str(response.data)
results = Alert.query.filter(Alert.phone_number == '5558675309',
Alert.symbol == 'BTC',
Alert.price == 100.0,
Alert.condition == 1,
Alert.market == 'coinbase').all()
assert len(results) == 1
def test_bad_market_page():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'asset': 'BTC',
'market': 'nasdaq',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert "Invalid value, must be one of:" in str(response.data)
def test_no_asset_choice():
response = test_client.post(
'/',
data={
'phone_number': '5558675309',
'market': 'nasdaq',
'cond_option': '1',
'price': '100'
})
assert response.status_code == 200
assert "Not a valid choice" in str(response.data) | 0.66061 | 0.393909 |
from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Union
from httpx import AsyncClient
from supertokens_python.recipe.thirdparty.provider import Provider
from supertokens_python.recipe.thirdparty.types import (
AccessTokenAPI, AuthorisationRedirectAPI, UserInfo, UserInfoEmail)
if TYPE_CHECKING:
from supertokens_python.framework.request import BaseRequest
class Facebook(Provider):
def __init__(self, client_id: str, client_secret: str,
scope: Union[None, List[str]] = None, is_default: bool = False):
super().__init__('facebook', client_id, is_default)
default_scopes = ['email']
if scope is None:
scope = default_scopes
self.client_secret = client_secret
self.scopes = list(set(scope))
self.access_token_api_url = 'https://graph.facebook.com/v9.0/oauth/access_token'
self.authorisation_redirect_url = 'https://www.facebook.com/v9.0/dialog/oauth'
async def get_profile_info(self, auth_code_response: Dict[str, Any], user_context: Dict[str, Any]) -> UserInfo:
access_token: str = auth_code_response['access_token']
params = {
'access_token': access_token,
'fields': 'id,email',
'format': 'json'
}
async with AsyncClient() as client:
response = await client.get(url='https://graph.facebook.com/me', params=params)
user_info = response.json()
user_id = user_info['id']
if 'email' not in user_info or user_info['email'] is None:
return UserInfo(user_id)
return UserInfo(user_id, UserInfoEmail(user_info['email'], True))
def get_authorisation_redirect_api_info(self, user_context: Dict[str, Any]) -> AuthorisationRedirectAPI:
params: Dict[str, Union[Callable[[BaseRequest], str], str]] = {
'scope': ' '.join(self.scopes),
'response_type': 'code',
'client_id': self.client_id
}
return AuthorisationRedirectAPI(
self.authorisation_redirect_url, params)
def get_access_token_api_info(
self, redirect_uri: str, auth_code_from_request: str, user_context: Dict[str, Any]) -> AccessTokenAPI:
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': auth_code_from_request,
'redirect_uri': redirect_uri
}
return AccessTokenAPI(self.access_token_api_url, params)
def get_redirect_uri(self, user_context: Dict[str, Any]) -> Union[None, str]:
return None | supertokens_python/recipe/thirdparty/providers/facebook.py | from __future__ import annotations
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Union
from httpx import AsyncClient
from supertokens_python.recipe.thirdparty.provider import Provider
from supertokens_python.recipe.thirdparty.types import (
AccessTokenAPI, AuthorisationRedirectAPI, UserInfo, UserInfoEmail)
if TYPE_CHECKING:
from supertokens_python.framework.request import BaseRequest
class Facebook(Provider):
def __init__(self, client_id: str, client_secret: str,
scope: Union[None, List[str]] = None, is_default: bool = False):
super().__init__('facebook', client_id, is_default)
default_scopes = ['email']
if scope is None:
scope = default_scopes
self.client_secret = client_secret
self.scopes = list(set(scope))
self.access_token_api_url = 'https://graph.facebook.com/v9.0/oauth/access_token'
self.authorisation_redirect_url = 'https://www.facebook.com/v9.0/dialog/oauth'
async def get_profile_info(self, auth_code_response: Dict[str, Any], user_context: Dict[str, Any]) -> UserInfo:
access_token: str = auth_code_response['access_token']
params = {
'access_token': access_token,
'fields': 'id,email',
'format': 'json'
}
async with AsyncClient() as client:
response = await client.get(url='https://graph.facebook.com/me', params=params)
user_info = response.json()
user_id = user_info['id']
if 'email' not in user_info or user_info['email'] is None:
return UserInfo(user_id)
return UserInfo(user_id, UserInfoEmail(user_info['email'], True))
def get_authorisation_redirect_api_info(self, user_context: Dict[str, Any]) -> AuthorisationRedirectAPI:
params: Dict[str, Union[Callable[[BaseRequest], str], str]] = {
'scope': ' '.join(self.scopes),
'response_type': 'code',
'client_id': self.client_id
}
return AuthorisationRedirectAPI(
self.authorisation_redirect_url, params)
def get_access_token_api_info(
self, redirect_uri: str, auth_code_from_request: str, user_context: Dict[str, Any]) -> AccessTokenAPI:
params = {
'client_id': self.client_id,
'client_secret': self.client_secret,
'code': auth_code_from_request,
'redirect_uri': redirect_uri
}
return AccessTokenAPI(self.access_token_api_url, params)
def get_redirect_uri(self, user_context: Dict[str, Any]) -> Union[None, str]:
return None | 0.789761 | 0.071851 |
import numpy as np
import pandas as pd
import visualisation
from population import Country
def run(n_infected,
total_time,
super_spreader_proportion=0.05,
infection_distance=0.5,
infection_probability=0.1,
return_gif_frames=False,
figsize=(8, 8)):
df = pd.DataFrame(columns=['n_total', 'n_not_infected', 'n_infected', 'n_recovered', 'n_dead'])
if return_gif_frames:
frames = []
# Initiate country and infections
country = Country(super_spreader_proportion)
i = 0
while i < n_infected:
infection_initiated = False
while not infection_initiated:
city = np.random.choice(country.cities)
patient_zero = np.random.choice(city.residents)
if not patient_zero.infected:
patient_zero.infect(0)
infection_initiated = True
i += 1
df = log(df, country.population, country.n_not_infected, country.n_infected, country.n_recovered, country.n_dead)
# Run simulation
for time in range(total_time):
country.update(time, infection_distance, infection_probability)
df = log(
df,
country.population,
country.n_not_infected,
country.n_infected,
country.n_recovered,
country.n_dead
)
if return_gif_frames:
if total_time < 100:
frames.append(visualisation.plot(country, time, figsize))
elif int(time % (total_time / 100)) == 0:
frames.append(visualisation.plot(country, time, figsize))
if return_gif_frames:
return country, df, frames
else:
return country, df
def log(df, population, n_not_infected, n_infected, n_recovered, n_dead):
df = pd.concat([
df,
pd.DataFrame(
[[population, n_not_infected, n_infected, n_recovered, n_dead]],
columns=['n_total', 'n_not_infected', 'n_infected', 'n_recovered', 'n_dead']
)
])
df.reset_index(drop=True, inplace=True)
return df | simulation.py | import numpy as np
import pandas as pd
import visualisation
from population import Country
def run(n_infected,
total_time,
super_spreader_proportion=0.05,
infection_distance=0.5,
infection_probability=0.1,
return_gif_frames=False,
figsize=(8, 8)):
df = pd.DataFrame(columns=['n_total', 'n_not_infected', 'n_infected', 'n_recovered', 'n_dead'])
if return_gif_frames:
frames = []
# Initiate country and infections
country = Country(super_spreader_proportion)
i = 0
while i < n_infected:
infection_initiated = False
while not infection_initiated:
city = np.random.choice(country.cities)
patient_zero = np.random.choice(city.residents)
if not patient_zero.infected:
patient_zero.infect(0)
infection_initiated = True
i += 1
df = log(df, country.population, country.n_not_infected, country.n_infected, country.n_recovered, country.n_dead)
# Run simulation
for time in range(total_time):
country.update(time, infection_distance, infection_probability)
df = log(
df,
country.population,
country.n_not_infected,
country.n_infected,
country.n_recovered,
country.n_dead
)
if return_gif_frames:
if total_time < 100:
frames.append(visualisation.plot(country, time, figsize))
elif int(time % (total_time / 100)) == 0:
frames.append(visualisation.plot(country, time, figsize))
if return_gif_frames:
return country, df, frames
else:
return country, df
def log(df, population, n_not_infected, n_infected, n_recovered, n_dead):
df = pd.concat([
df,
pd.DataFrame(
[[population, n_not_infected, n_infected, n_recovered, n_dead]],
columns=['n_total', 'n_not_infected', 'n_infected', 'n_recovered', 'n_dead']
)
])
df.reset_index(drop=True, inplace=True)
return df | 0.402392 | 0.302939 |
from __future__ import print_function as _print_function
import sys as _sys
from tensorflow.python.framework.ops import name_scope
from tensorflow.python.keras.backend import abs
from tensorflow.python.keras.backend import all
from tensorflow.python.keras.backend import any
from tensorflow.python.keras.backend import arange
from tensorflow.python.keras.backend import argmax
from tensorflow.python.keras.backend import argmin
from tensorflow.python.keras.backend import backend
from tensorflow.python.keras.backend import batch_dot
from tensorflow.python.keras.backend import batch_flatten
from tensorflow.python.keras.backend import batch_get_value
from tensorflow.python.keras.backend import batch_normalization
from tensorflow.python.keras.backend import batch_set_value
from tensorflow.python.keras.backend import bias_add
from tensorflow.python.keras.backend import binary_crossentropy
from tensorflow.python.keras.backend import cast
from tensorflow.python.keras.backend import cast_to_floatx
from tensorflow.python.keras.backend import categorical_crossentropy
from tensorflow.python.keras.backend import clear_session
from tensorflow.python.keras.backend import clip
from tensorflow.python.keras.backend import concatenate
from tensorflow.python.keras.backend import constant
from tensorflow.python.keras.backend import conv1d
from tensorflow.python.keras.backend import conv2d
from tensorflow.python.keras.backend import conv2d_transpose
from tensorflow.python.keras.backend import conv3d
from tensorflow.python.keras.backend import cos
from tensorflow.python.keras.backend import count_params
from tensorflow.python.keras.backend import ctc_batch_cost
from tensorflow.python.keras.backend import ctc_decode
from tensorflow.python.keras.backend import ctc_label_dense_to_sparse
from tensorflow.python.keras.backend import cumprod
from tensorflow.python.keras.backend import cumsum
from tensorflow.python.keras.backend import dot
from tensorflow.python.keras.backend import dropout
from tensorflow.python.keras.backend import dtype
from tensorflow.python.keras.backend import elu
from tensorflow.python.keras.backend import equal
from tensorflow.python.keras.backend import eval
from tensorflow.python.keras.backend import exp
from tensorflow.python.keras.backend import expand_dims
from tensorflow.python.keras.backend import eye
from tensorflow.python.keras.backend import flatten
from tensorflow.python.keras.backend import foldl
from tensorflow.python.keras.backend import foldr
from tensorflow.python.keras.backend import function
from tensorflow.python.keras.backend import gather
from tensorflow.python.keras.backend import get_session
from tensorflow.python.keras.backend import get_uid
from tensorflow.python.keras.backend import get_value
from tensorflow.python.keras.backend import gradients
from tensorflow.python.keras.backend import greater
from tensorflow.python.keras.backend import greater_equal
from tensorflow.python.keras.backend import hard_sigmoid
from tensorflow.python.keras.backend import in_test_phase
from tensorflow.python.keras.backend import in_top_k
from tensorflow.python.keras.backend import in_train_phase
from tensorflow.python.keras.backend import int_shape
from tensorflow.python.keras.backend import is_sparse
from tensorflow.python.keras.backend import l2_normalize
from tensorflow.python.keras.backend import learning_phase
from tensorflow.python.keras.backend import learning_phase_scope
from tensorflow.python.keras.backend import less
from tensorflow.python.keras.backend import less_equal
from tensorflow.python.keras.backend import local_conv1d
from tensorflow.python.keras.backend import local_conv2d
from tensorflow.python.keras.backend import log
from tensorflow.python.keras.backend import manual_variable_initialization
from tensorflow.python.keras.backend import map_fn
from tensorflow.python.keras.backend import max
from tensorflow.python.keras.backend import maximum
from tensorflow.python.keras.backend import mean
from tensorflow.python.keras.backend import min
from tensorflow.python.keras.backend import minimum
from tensorflow.python.keras.backend import moving_average_update
from tensorflow.python.keras.backend import ndim
from tensorflow.python.keras.backend import normalize_batch_in_training
from tensorflow.python.keras.backend import not_equal
from tensorflow.python.keras.backend import one_hot
from tensorflow.python.keras.backend import ones
from tensorflow.python.keras.backend import ones_like
from tensorflow.python.keras.backend import permute_dimensions
from tensorflow.python.keras.backend import placeholder
from tensorflow.python.keras.backend import pool2d
from tensorflow.python.keras.backend import pool3d
from tensorflow.python.keras.backend import pow
from tensorflow.python.keras.backend import print_tensor
from tensorflow.python.keras.backend import prod
from tensorflow.python.keras.backend import random_binomial
from tensorflow.python.keras.backend import random_normal
from tensorflow.python.keras.backend import random_normal_variable
from tensorflow.python.keras.backend import random_uniform
from tensorflow.python.keras.backend import random_uniform_variable
from tensorflow.python.keras.backend import relu
from tensorflow.python.keras.backend import repeat
from tensorflow.python.keras.backend import repeat_elements
from tensorflow.python.keras.backend import reset_uids
from tensorflow.python.keras.backend import reshape
from tensorflow.python.keras.backend import resize_images
from tensorflow.python.keras.backend import resize_volumes
from tensorflow.python.keras.backend import reverse
from tensorflow.python.keras.backend import rnn
from tensorflow.python.keras.backend import round
from tensorflow.python.keras.backend import separable_conv2d
from tensorflow.python.keras.backend import set_learning_phase
from tensorflow.python.keras.backend import set_session
from tensorflow.python.keras.backend import set_value
from tensorflow.python.keras.backend import shape
from tensorflow.python.keras.backend import sigmoid
from tensorflow.python.keras.backend import sign
from tensorflow.python.keras.backend import sin
from tensorflow.python.keras.backend import softmax
from tensorflow.python.keras.backend import softplus
from tensorflow.python.keras.backend import softsign
from tensorflow.python.keras.backend import sparse_categorical_crossentropy
from tensorflow.python.keras.backend import spatial_2d_padding
from tensorflow.python.keras.backend import spatial_3d_padding
from tensorflow.python.keras.backend import sqrt
from tensorflow.python.keras.backend import square
from tensorflow.python.keras.backend import squeeze
from tensorflow.python.keras.backend import stack
from tensorflow.python.keras.backend import std
from tensorflow.python.keras.backend import stop_gradient
from tensorflow.python.keras.backend import sum
from tensorflow.python.keras.backend import switch
from tensorflow.python.keras.backend import tanh
from tensorflow.python.keras.backend import temporal_padding
from tensorflow.python.keras.backend import tile
from tensorflow.python.keras.backend import to_dense
from tensorflow.python.keras.backend import transpose
from tensorflow.python.keras.backend import truncated_normal
from tensorflow.python.keras.backend import update
from tensorflow.python.keras.backend import update_add
from tensorflow.python.keras.backend import update_sub
from tensorflow.python.keras.backend import var
from tensorflow.python.keras.backend import variable
from tensorflow.python.keras.backend import zeros
from tensorflow.python.keras.backend import zeros_like
from tensorflow.python.keras.backend_config import epsilon
from tensorflow.python.keras.backend_config import floatx
from tensorflow.python.keras.backend_config import image_data_format
from tensorflow.python.keras.backend_config import set_epsilon
from tensorflow.python.keras.backend_config import set_floatx
from tensorflow.python.keras.backend_config import set_image_data_format
del _print_function
from tensorflow.python.util import module_wrapper as _module_wrapper
if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):
_sys.modules[__name__] = _module_wrapper.TFModuleWrapper(
_sys.modules[__name__], "keras.backend", public_apis=None, deprecation=True,
has_lite=False) | cart_venv/Lib/site-packages/tensorflow_core/python/keras/api/keras/backend/__init__.py | from __future__ import print_function as _print_function
import sys as _sys
from tensorflow.python.framework.ops import name_scope
from tensorflow.python.keras.backend import abs
from tensorflow.python.keras.backend import all
from tensorflow.python.keras.backend import any
from tensorflow.python.keras.backend import arange
from tensorflow.python.keras.backend import argmax
from tensorflow.python.keras.backend import argmin
from tensorflow.python.keras.backend import backend
from tensorflow.python.keras.backend import batch_dot
from tensorflow.python.keras.backend import batch_flatten
from tensorflow.python.keras.backend import batch_get_value
from tensorflow.python.keras.backend import batch_normalization
from tensorflow.python.keras.backend import batch_set_value
from tensorflow.python.keras.backend import bias_add
from tensorflow.python.keras.backend import binary_crossentropy
from tensorflow.python.keras.backend import cast
from tensorflow.python.keras.backend import cast_to_floatx
from tensorflow.python.keras.backend import categorical_crossentropy
from tensorflow.python.keras.backend import clear_session
from tensorflow.python.keras.backend import clip
from tensorflow.python.keras.backend import concatenate
from tensorflow.python.keras.backend import constant
from tensorflow.python.keras.backend import conv1d
from tensorflow.python.keras.backend import conv2d
from tensorflow.python.keras.backend import conv2d_transpose
from tensorflow.python.keras.backend import conv3d
from tensorflow.python.keras.backend import cos
from tensorflow.python.keras.backend import count_params
from tensorflow.python.keras.backend import ctc_batch_cost
from tensorflow.python.keras.backend import ctc_decode
from tensorflow.python.keras.backend import ctc_label_dense_to_sparse
from tensorflow.python.keras.backend import cumprod
from tensorflow.python.keras.backend import cumsum
from tensorflow.python.keras.backend import dot
from tensorflow.python.keras.backend import dropout
from tensorflow.python.keras.backend import dtype
from tensorflow.python.keras.backend import elu
from tensorflow.python.keras.backend import equal
from tensorflow.python.keras.backend import eval
from tensorflow.python.keras.backend import exp
from tensorflow.python.keras.backend import expand_dims
from tensorflow.python.keras.backend import eye
from tensorflow.python.keras.backend import flatten
from tensorflow.python.keras.backend import foldl
from tensorflow.python.keras.backend import foldr
from tensorflow.python.keras.backend import function
from tensorflow.python.keras.backend import gather
from tensorflow.python.keras.backend import get_session
from tensorflow.python.keras.backend import get_uid
from tensorflow.python.keras.backend import get_value
from tensorflow.python.keras.backend import gradients
from tensorflow.python.keras.backend import greater
from tensorflow.python.keras.backend import greater_equal
from tensorflow.python.keras.backend import hard_sigmoid
from tensorflow.python.keras.backend import in_test_phase
from tensorflow.python.keras.backend import in_top_k
from tensorflow.python.keras.backend import in_train_phase
from tensorflow.python.keras.backend import int_shape
from tensorflow.python.keras.backend import is_sparse
from tensorflow.python.keras.backend import l2_normalize
from tensorflow.python.keras.backend import learning_phase
from tensorflow.python.keras.backend import learning_phase_scope
from tensorflow.python.keras.backend import less
from tensorflow.python.keras.backend import less_equal
from tensorflow.python.keras.backend import local_conv1d
from tensorflow.python.keras.backend import local_conv2d
from tensorflow.python.keras.backend import log
from tensorflow.python.keras.backend import manual_variable_initialization
from tensorflow.python.keras.backend import map_fn
from tensorflow.python.keras.backend import max
from tensorflow.python.keras.backend import maximum
from tensorflow.python.keras.backend import mean
from tensorflow.python.keras.backend import min
from tensorflow.python.keras.backend import minimum
from tensorflow.python.keras.backend import moving_average_update
from tensorflow.python.keras.backend import ndim
from tensorflow.python.keras.backend import normalize_batch_in_training
from tensorflow.python.keras.backend import not_equal
from tensorflow.python.keras.backend import one_hot
from tensorflow.python.keras.backend import ones
from tensorflow.python.keras.backend import ones_like
from tensorflow.python.keras.backend import permute_dimensions
from tensorflow.python.keras.backend import placeholder
from tensorflow.python.keras.backend import pool2d
from tensorflow.python.keras.backend import pool3d
from tensorflow.python.keras.backend import pow
from tensorflow.python.keras.backend import print_tensor
from tensorflow.python.keras.backend import prod
from tensorflow.python.keras.backend import random_binomial
from tensorflow.python.keras.backend import random_normal
from tensorflow.python.keras.backend import random_normal_variable
from tensorflow.python.keras.backend import random_uniform
from tensorflow.python.keras.backend import random_uniform_variable
from tensorflow.python.keras.backend import relu
from tensorflow.python.keras.backend import repeat
from tensorflow.python.keras.backend import repeat_elements
from tensorflow.python.keras.backend import reset_uids
from tensorflow.python.keras.backend import reshape
from tensorflow.python.keras.backend import resize_images
from tensorflow.python.keras.backend import resize_volumes
from tensorflow.python.keras.backend import reverse
from tensorflow.python.keras.backend import rnn
from tensorflow.python.keras.backend import round
from tensorflow.python.keras.backend import separable_conv2d
from tensorflow.python.keras.backend import set_learning_phase
from tensorflow.python.keras.backend import set_session
from tensorflow.python.keras.backend import set_value
from tensorflow.python.keras.backend import shape
from tensorflow.python.keras.backend import sigmoid
from tensorflow.python.keras.backend import sign
from tensorflow.python.keras.backend import sin
from tensorflow.python.keras.backend import softmax
from tensorflow.python.keras.backend import softplus
from tensorflow.python.keras.backend import softsign
from tensorflow.python.keras.backend import sparse_categorical_crossentropy
from tensorflow.python.keras.backend import spatial_2d_padding
from tensorflow.python.keras.backend import spatial_3d_padding
from tensorflow.python.keras.backend import sqrt
from tensorflow.python.keras.backend import square
from tensorflow.python.keras.backend import squeeze
from tensorflow.python.keras.backend import stack
from tensorflow.python.keras.backend import std
from tensorflow.python.keras.backend import stop_gradient
from tensorflow.python.keras.backend import sum
from tensorflow.python.keras.backend import switch
from tensorflow.python.keras.backend import tanh
from tensorflow.python.keras.backend import temporal_padding
from tensorflow.python.keras.backend import tile
from tensorflow.python.keras.backend import to_dense
from tensorflow.python.keras.backend import transpose
from tensorflow.python.keras.backend import truncated_normal
from tensorflow.python.keras.backend import update
from tensorflow.python.keras.backend import update_add
from tensorflow.python.keras.backend import update_sub
from tensorflow.python.keras.backend import var
from tensorflow.python.keras.backend import variable
from tensorflow.python.keras.backend import zeros
from tensorflow.python.keras.backend import zeros_like
from tensorflow.python.keras.backend_config import epsilon
from tensorflow.python.keras.backend_config import floatx
from tensorflow.python.keras.backend_config import image_data_format
from tensorflow.python.keras.backend_config import set_epsilon
from tensorflow.python.keras.backend_config import set_floatx
from tensorflow.python.keras.backend_config import set_image_data_format
del _print_function
from tensorflow.python.util import module_wrapper as _module_wrapper
if not isinstance(_sys.modules[__name__], _module_wrapper.TFModuleWrapper):
_sys.modules[__name__] = _module_wrapper.TFModuleWrapper(
_sys.modules[__name__], "keras.backend", public_apis=None, deprecation=True,
has_lite=False) | 0.707708 | 0.128826 |
from __future__ import absolute_import, print_function
from sentry import eventstore, nodestore
from sentry.models import Event, EventAttachment, UserReport
from ..base import BaseDeletionTask, BaseRelation, ModelDeletionTask, ModelRelation
class EventDataDeletionTask(BaseDeletionTask):
"""
Deletes nodestore data, EventAttachment and UserReports for group
"""
DEFAULT_CHUNK_SIZE = 10000
def __init__(self, manager, group_id, project_id, **kwargs):
self.group_id = group_id
self.project_id = project_id
self.last_event = None
super(EventDataDeletionTask, self).__init__(manager, **kwargs)
def chunk(self):
conditions = []
if self.last_event is not None:
conditions.extend(
[
["timestamp", "<=", self.last_event.timestamp],
[
["timestamp", "<", self.last_event.timestamp],
["event_id", "<", self.last_event.event_id],
],
]
)
events = eventstore.get_events(
filter=eventstore.Filter(
conditions=conditions, project_ids=[self.project_id], group_ids=[self.group_id]
),
limit=self.DEFAULT_CHUNK_SIZE,
referrer="deletions.group",
orderby=["-timestamp", "-event_id"],
)
if not events:
return False
self.last_event = events[-1]
# Remove from nodestore
node_ids = [Event.generate_node_id(self.project_id, event.event_id) for event in events]
nodestore.delete_multi(node_ids)
# Remove EventAttachment and UserReport
EventAttachment.objects.filter(event_id=event.event_id, project_id=self.project_id).delete()
UserReport.objects.filter(event_id=event.event_id, project_id=self.project_id).delete()
return True
class GroupDeletionTask(ModelDeletionTask):
def get_child_relations(self, instance):
from sentry import models
from sentry.incidents.models import IncidentGroup
relations = []
model_list = (
# prioritize GroupHash
models.GroupHash,
models.GroupAssignee,
models.GroupCommitResolution,
models.GroupLink,
models.GroupBookmark,
models.GroupMeta,
models.GroupEnvironment,
models.GroupRelease,
models.GroupRedirect,
models.GroupResolution,
models.GroupRuleStatus,
models.GroupSeen,
models.GroupShare,
models.GroupSnooze,
models.GroupEmailThread,
models.GroupSubscription,
models.UserReport,
IncidentGroup,
# Event is last as its the most time consuming
models.Event,
)
relations.extend([ModelRelation(m, {"group_id": instance.id}) for m in model_list])
relations.extend(
[
BaseRelation(
{"group_id": instance.id, "project_id": instance.project_id},
EventDataDeletionTask,
)
]
)
return relations
def delete_instance(self, instance):
from sentry.similarity import features
if not self.skip_models or features not in self.skip_models:
features.delete(instance)
return super(GroupDeletionTask, self).delete_instance(instance)
def mark_deletion_in_progress(self, instance_list):
from sentry.models import Group, GroupStatus
Group.objects.filter(id__in=[i.id for i in instance_list]).exclude(
status=GroupStatus.DELETION_IN_PROGRESS
).update(status=GroupStatus.DELETION_IN_PROGRESS) | src/sentry/deletions/defaults/group.py | from __future__ import absolute_import, print_function
from sentry import eventstore, nodestore
from sentry.models import Event, EventAttachment, UserReport
from ..base import BaseDeletionTask, BaseRelation, ModelDeletionTask, ModelRelation
class EventDataDeletionTask(BaseDeletionTask):
"""
Deletes nodestore data, EventAttachment and UserReports for group
"""
DEFAULT_CHUNK_SIZE = 10000
def __init__(self, manager, group_id, project_id, **kwargs):
self.group_id = group_id
self.project_id = project_id
self.last_event = None
super(EventDataDeletionTask, self).__init__(manager, **kwargs)
def chunk(self):
conditions = []
if self.last_event is not None:
conditions.extend(
[
["timestamp", "<=", self.last_event.timestamp],
[
["timestamp", "<", self.last_event.timestamp],
["event_id", "<", self.last_event.event_id],
],
]
)
events = eventstore.get_events(
filter=eventstore.Filter(
conditions=conditions, project_ids=[self.project_id], group_ids=[self.group_id]
),
limit=self.DEFAULT_CHUNK_SIZE,
referrer="deletions.group",
orderby=["-timestamp", "-event_id"],
)
if not events:
return False
self.last_event = events[-1]
# Remove from nodestore
node_ids = [Event.generate_node_id(self.project_id, event.event_id) for event in events]
nodestore.delete_multi(node_ids)
# Remove EventAttachment and UserReport
EventAttachment.objects.filter(event_id=event.event_id, project_id=self.project_id).delete()
UserReport.objects.filter(event_id=event.event_id, project_id=self.project_id).delete()
return True
class GroupDeletionTask(ModelDeletionTask):
def get_child_relations(self, instance):
from sentry import models
from sentry.incidents.models import IncidentGroup
relations = []
model_list = (
# prioritize GroupHash
models.GroupHash,
models.GroupAssignee,
models.GroupCommitResolution,
models.GroupLink,
models.GroupBookmark,
models.GroupMeta,
models.GroupEnvironment,
models.GroupRelease,
models.GroupRedirect,
models.GroupResolution,
models.GroupRuleStatus,
models.GroupSeen,
models.GroupShare,
models.GroupSnooze,
models.GroupEmailThread,
models.GroupSubscription,
models.UserReport,
IncidentGroup,
# Event is last as its the most time consuming
models.Event,
)
relations.extend([ModelRelation(m, {"group_id": instance.id}) for m in model_list])
relations.extend(
[
BaseRelation(
{"group_id": instance.id, "project_id": instance.project_id},
EventDataDeletionTask,
)
]
)
return relations
def delete_instance(self, instance):
from sentry.similarity import features
if not self.skip_models or features not in self.skip_models:
features.delete(instance)
return super(GroupDeletionTask, self).delete_instance(instance)
def mark_deletion_in_progress(self, instance_list):
from sentry.models import Group, GroupStatus
Group.objects.filter(id__in=[i.id for i in instance_list]).exclude(
status=GroupStatus.DELETION_IN_PROGRESS
).update(status=GroupStatus.DELETION_IN_PROGRESS) | 0.638046 | 0.141163 |
from abc import ABC, abstractmethod
from collections import OrderedDict
from typing import Any, Dict, Generator, List
from the_census._api.models import GeographyItem
from the_census._geographies.models import GeoDomain
from the_census._variables.models import Group, GroupVariable, VariableCode
class ICensusApiFetchService(ABC):
"""
Interface for our API client, which will
perform all fetches for the Census API
"""
@abstractmethod
def healthcheck(self) -> None:
"""
makes sure that the API client is
configured properly
"""
...
@abstractmethod
def geography_codes(
self, for_domain: GeoDomain, in_domains: List[GeoDomain] = []
) -> List[List[str]]:
"""
Gets all geography codes for a given location domain:
Args:
for_domain (GeoDomain): the domain you want to search. This must
be a child of any provided `in_domains`, as specified in the API's
geography hierarchy.
in_domains (List[GeoDomain], optional): geography domains
that may help specify the query (e.g., if you want to
search all congressional districts in a particular state).
Defaults to [].
Returns:
List[List[str]]: API response
"""
...
@abstractmethod
def group_data(self) -> Dict[str, Group]:
"""
Retrieves data on available concept groups for a given dataset/survey
Returns:
Dict[str, Group]: Mapping of group ID to concept
"""
...
@abstractmethod
def supported_geographies(self) -> OrderedDict[str, GeographyItem]:
"""
Retrieves all queryable geographies for a given dataset/survey
Returns:
OrderedDict[str, GeographyItem]: mapping between a geography
and possible queries that can be made on it
"""
...
@abstractmethod
def variables_for_group(self, group: str) -> List[GroupVariable]:
"""
Gets all queryable variables for a survey group concept.
Args:
group (str): The group's code
Returns:
List[GroupVariable]
"""
...
@abstractmethod
def all_variables(self) -> List[GroupVariable]:
"""
Gets all variables. This may be costly
Returns:
List[GroupVariable]: all of the variables.
"""
...
@abstractmethod
def stats(
self,
variables_codes: List[VariableCode],
for_domain: GeoDomain,
in_domains: List[GeoDomain] = [],
) -> Generator[List[List[str]], None, None]:
"""
Gets stats based on `variableCodes` for the geographies in question.
Returns a generator, since we may need to make repeat API
calls due to limits on the number of variables (50) that the API
will accept to query at a time.
Args:
variables_codes (List[VariableCode])
for_domain (GeoDomain)
in_domains (List[GeoDomain], optional). Defaults to [].
Yields:
Generator[List[List[str]], None, None]
"""
...
class ICensusApiSerializationService(ABC):
"""
Serialization layer between the raw API results & models
"""
@abstractmethod
def parse_group_variables(self, group_variables: Any) -> List[GroupVariable]:
"""
Parses an API response for variable retrieval
Args:
group_variables (Any): JSON response
Returns:
List[GroupVariable]:
"""
...
@abstractmethod
def parse_supported_geographies(
self, supported_geos_response: Any
) -> OrderedDict[str, GeographyItem]:
"""
parse a supported geographies response from the census API:
Args:
supported_geos_response (Any)
Returns:
OrderedDict[str, GeographyItem]: mapping the geography title to its name and code
"""
...
@abstractmethod
def parse_groups(
self, groups_res: Dict[str, List[Dict[str, str]]]
) -> Dict[str, Group]:
"""
Parses a /groups.json response from the census API
Args:
groups_res (Dict[str, List[Dict[str, str]]])
Returns:
Dict[str, Group]
"""
... | the_census/_api/interface.py | from abc import ABC, abstractmethod
from collections import OrderedDict
from typing import Any, Dict, Generator, List
from the_census._api.models import GeographyItem
from the_census._geographies.models import GeoDomain
from the_census._variables.models import Group, GroupVariable, VariableCode
class ICensusApiFetchService(ABC):
"""
Interface for our API client, which will
perform all fetches for the Census API
"""
@abstractmethod
def healthcheck(self) -> None:
"""
makes sure that the API client is
configured properly
"""
...
@abstractmethod
def geography_codes(
self, for_domain: GeoDomain, in_domains: List[GeoDomain] = []
) -> List[List[str]]:
"""
Gets all geography codes for a given location domain:
Args:
for_domain (GeoDomain): the domain you want to search. This must
be a child of any provided `in_domains`, as specified in the API's
geography hierarchy.
in_domains (List[GeoDomain], optional): geography domains
that may help specify the query (e.g., if you want to
search all congressional districts in a particular state).
Defaults to [].
Returns:
List[List[str]]: API response
"""
...
@abstractmethod
def group_data(self) -> Dict[str, Group]:
"""
Retrieves data on available concept groups for a given dataset/survey
Returns:
Dict[str, Group]: Mapping of group ID to concept
"""
...
@abstractmethod
def supported_geographies(self) -> OrderedDict[str, GeographyItem]:
"""
Retrieves all queryable geographies for a given dataset/survey
Returns:
OrderedDict[str, GeographyItem]: mapping between a geography
and possible queries that can be made on it
"""
...
@abstractmethod
def variables_for_group(self, group: str) -> List[GroupVariable]:
"""
Gets all queryable variables for a survey group concept.
Args:
group (str): The group's code
Returns:
List[GroupVariable]
"""
...
@abstractmethod
def all_variables(self) -> List[GroupVariable]:
"""
Gets all variables. This may be costly
Returns:
List[GroupVariable]: all of the variables.
"""
...
@abstractmethod
def stats(
self,
variables_codes: List[VariableCode],
for_domain: GeoDomain,
in_domains: List[GeoDomain] = [],
) -> Generator[List[List[str]], None, None]:
"""
Gets stats based on `variableCodes` for the geographies in question.
Returns a generator, since we may need to make repeat API
calls due to limits on the number of variables (50) that the API
will accept to query at a time.
Args:
variables_codes (List[VariableCode])
for_domain (GeoDomain)
in_domains (List[GeoDomain], optional). Defaults to [].
Yields:
Generator[List[List[str]], None, None]
"""
...
class ICensusApiSerializationService(ABC):
"""
Serialization layer between the raw API results & models
"""
@abstractmethod
def parse_group_variables(self, group_variables: Any) -> List[GroupVariable]:
"""
Parses an API response for variable retrieval
Args:
group_variables (Any): JSON response
Returns:
List[GroupVariable]:
"""
...
@abstractmethod
def parse_supported_geographies(
self, supported_geos_response: Any
) -> OrderedDict[str, GeographyItem]:
"""
parse a supported geographies response from the census API:
Args:
supported_geos_response (Any)
Returns:
OrderedDict[str, GeographyItem]: mapping the geography title to its name and code
"""
...
@abstractmethod
def parse_groups(
self, groups_res: Dict[str, List[Dict[str, str]]]
) -> Dict[str, Group]:
"""
Parses a /groups.json response from the census API
Args:
groups_res (Dict[str, List[Dict[str, str]]])
Returns:
Dict[str, Group]
"""
... | 0.923726 | 0.573678 |
# pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=E1101,E1102
# We dynamically generate the Button class
# pylint: disable=R0903
# We implement stubs
import enum
import Xlib.display
import Xlib.ext
import Xlib.ext.xtest
import Xlib.X
import Xlib.protocol
from pynput._util.xorg import (
display_manager,
ListenerMixin)
from . import _base
# pylint: disable=C0103
Button = enum.Enum(
'Button',
module=__name__,
names=[
('unknown', None),
('left', 1),
('middle', 2),
('right', 3),
('scroll_up', 4),
('scroll_down', 5),
('scroll_left', 6),
('scroll_right', 7)] + [
('button%d' % i, i)
for i in range(8, 31)])
# pylint: enable=C0103
class Controller(_base.Controller):
def __init__(self):
self._display = Xlib.display.Display()
def __del__(self):
if hasattr(self, '_display'):
self._display.close()
def _position_get(self):
with display_manager(self._display) as dm:
qp = dm.screen().root.query_pointer()
return (qp.root_x, qp.root_y)
def _position_set(self, pos):
px, py = self._check_bounds(*pos)
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.MotionNotify, x=px, y=py)
def _scroll(self, dx, dy):
dx, dy = self._check_bounds(dx, dy)
if dy:
self.click(
button=Button.scroll_up if dy > 0 else Button.scroll_down,
count=abs(dy))
if dx:
self.click(
button=Button.scroll_right if dx > 0 else Button.scroll_left,
count=abs(dx))
def _press(self, button):
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.ButtonPress, button.value)
def _release(self, button):
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.ButtonRelease, button.value)
def _check_bounds(self, *args):
"""Checks the arguments and makes sure they are within the bounds of a
short integer.
:param args: The values to verify.
"""
if not all(
(-0x7fff - 1) <= number <= 0x7fff
for number in args):
raise ValueError(args)
else:
return tuple(int(p) for p in args)
class Listener(ListenerMixin, _base.Listener):
#: A mapping from button values to scroll directions
_SCROLL_BUTTONS = {
Button.scroll_up.value: (0, 1),
Button.scroll_down.value: (0, -1),
Button.scroll_right.value: (1, 0),
Button.scroll_left.value: (-1, 0)}
_EVENTS = (
Xlib.X.ButtonPressMask,
Xlib.X.ButtonReleaseMask)
def _handle(self, dummy_display, event):
px = event.root_x
py = event.root_y
if event.type == Xlib.X.ButtonPress:
# Scroll events are sent as button presses with the scroll
# button codes
scroll = self._SCROLL_BUTTONS.get(event.detail, None)
if scroll:
self.on_scroll(px, py, *scroll)
else:
self.on_click(px, py, self._button(event.detail), True)
elif event.type == Xlib.X.ButtonRelease:
# Send an event only if this was not a scroll event
if event.detail not in self._SCROLL_BUTTONS:
self.on_click(px, py, self._button(event.detail), False)
else:
self.on_move(px, py)
def _suppress_start(self, display):
display.screen().root.grab_pointer(
True, self._event_mask, Xlib.X.GrabModeAsync, Xlib.X.GrabModeAsync,
0, 0, Xlib.X.CurrentTime)
def _suppress_stop(self, display):
display.ungrab_pointer(Xlib.X.CurrentTime)
# pylint: disable=R0201
def _button(self, detail):
"""Creates a mouse button from an event detail.
If the button is unknown, :attr:`Button.unknown` is returned.
:param detail: The event detail.
:return: a button
"""
try:
return Button(detail)
except ValueError:
return Button.unknown
# pylint: enable=R0201 | pype/vendor/pynput/mouse/_xorg.py | # pylint: disable=C0111
# The documentation is extracted from the base classes
# pylint: disable=E1101,E1102
# We dynamically generate the Button class
# pylint: disable=R0903
# We implement stubs
import enum
import Xlib.display
import Xlib.ext
import Xlib.ext.xtest
import Xlib.X
import Xlib.protocol
from pynput._util.xorg import (
display_manager,
ListenerMixin)
from . import _base
# pylint: disable=C0103
Button = enum.Enum(
'Button',
module=__name__,
names=[
('unknown', None),
('left', 1),
('middle', 2),
('right', 3),
('scroll_up', 4),
('scroll_down', 5),
('scroll_left', 6),
('scroll_right', 7)] + [
('button%d' % i, i)
for i in range(8, 31)])
# pylint: enable=C0103
class Controller(_base.Controller):
def __init__(self):
self._display = Xlib.display.Display()
def __del__(self):
if hasattr(self, '_display'):
self._display.close()
def _position_get(self):
with display_manager(self._display) as dm:
qp = dm.screen().root.query_pointer()
return (qp.root_x, qp.root_y)
def _position_set(self, pos):
px, py = self._check_bounds(*pos)
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.MotionNotify, x=px, y=py)
def _scroll(self, dx, dy):
dx, dy = self._check_bounds(dx, dy)
if dy:
self.click(
button=Button.scroll_up if dy > 0 else Button.scroll_down,
count=abs(dy))
if dx:
self.click(
button=Button.scroll_right if dx > 0 else Button.scroll_left,
count=abs(dx))
def _press(self, button):
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.ButtonPress, button.value)
def _release(self, button):
with display_manager(self._display) as dm:
Xlib.ext.xtest.fake_input(dm, Xlib.X.ButtonRelease, button.value)
def _check_bounds(self, *args):
"""Checks the arguments and makes sure they are within the bounds of a
short integer.
:param args: The values to verify.
"""
if not all(
(-0x7fff - 1) <= number <= 0x7fff
for number in args):
raise ValueError(args)
else:
return tuple(int(p) for p in args)
class Listener(ListenerMixin, _base.Listener):
#: A mapping from button values to scroll directions
_SCROLL_BUTTONS = {
Button.scroll_up.value: (0, 1),
Button.scroll_down.value: (0, -1),
Button.scroll_right.value: (1, 0),
Button.scroll_left.value: (-1, 0)}
_EVENTS = (
Xlib.X.ButtonPressMask,
Xlib.X.ButtonReleaseMask)
def _handle(self, dummy_display, event):
px = event.root_x
py = event.root_y
if event.type == Xlib.X.ButtonPress:
# Scroll events are sent as button presses with the scroll
# button codes
scroll = self._SCROLL_BUTTONS.get(event.detail, None)
if scroll:
self.on_scroll(px, py, *scroll)
else:
self.on_click(px, py, self._button(event.detail), True)
elif event.type == Xlib.X.ButtonRelease:
# Send an event only if this was not a scroll event
if event.detail not in self._SCROLL_BUTTONS:
self.on_click(px, py, self._button(event.detail), False)
else:
self.on_move(px, py)
def _suppress_start(self, display):
display.screen().root.grab_pointer(
True, self._event_mask, Xlib.X.GrabModeAsync, Xlib.X.GrabModeAsync,
0, 0, Xlib.X.CurrentTime)
def _suppress_stop(self, display):
display.ungrab_pointer(Xlib.X.CurrentTime)
# pylint: disable=R0201
def _button(self, detail):
"""Creates a mouse button from an event detail.
If the button is unknown, :attr:`Button.unknown` is returned.
:param detail: The event detail.
:return: a button
"""
try:
return Button(detail)
except ValueError:
return Button.unknown
# pylint: enable=R0201 | 0.637031 | 0.115486 |
from sawtooth_processor_test.message_factory import MessageFactory
class XoMessageFactory:
def __init__(self, signer=None):
self._factory = MessageFactory(
family_name="xo",
family_version="1.0",
namespace=MessageFactory.sha512("xo".encode("utf-8"))[0:6],
signer=signer
)
def _game_to_address(self, game):
return self._factory.namespace + \
self._factory.sha512(game.encode())[0:64]
def create_tp_register(self):
return self._factory.create_tp_register()
def create_tp_response(self, status):
return self._factory.create_tp_response(status)
def _create_txn(self, txn_function, game, action, space=None):
payload = ",".join([
str(game), str(action), str(space)
]).encode()
addresses = [self._game_to_address(game)]
return txn_function(payload, addresses, addresses, [])
def create_tp_process_request(self, action, game, space=None):
txn_function = self._factory.create_tp_process_request
return self._create_txn(txn_function, game, action, space)
def create_transaction(self, game, action, space=None):
txn_function = self._factory.create_transaction
return self._create_txn(txn_function, game, action, space)
def create_get_request(self, game):
addresses = [self._game_to_address(game)]
return self._factory.create_get_request(addresses)
def create_get_response(
self, game, board="---------", state="P1-NEXT", player1="", player2=""
):
address = self._game_to_address(game)
data = None
if board is not None:
data = ",".join([game, board, state, player1, player2]).encode()
else:
data = None
return self._factory.create_get_response({address: data})
def create_set_request(
self, game, board="---------", state="P1-NEXT", player1="", player2=""
):
address = self._game_to_address(game)
data = None
if state is not None:
data = ",".join([game, board, state, player1, player2]).encode()
else:
data = None
return self._factory.create_set_request({address: data})
def create_set_response(self, game):
addresses = [self._game_to_address(game)]
return self._factory.create_set_response(addresses)
def get_public_key(self):
return self._factory.get_public_key() | sdk/examples/xo_python/sawtooth_xo/xo_message_factory.py |
from sawtooth_processor_test.message_factory import MessageFactory
class XoMessageFactory:
def __init__(self, signer=None):
self._factory = MessageFactory(
family_name="xo",
family_version="1.0",
namespace=MessageFactory.sha512("xo".encode("utf-8"))[0:6],
signer=signer
)
def _game_to_address(self, game):
return self._factory.namespace + \
self._factory.sha512(game.encode())[0:64]
def create_tp_register(self):
return self._factory.create_tp_register()
def create_tp_response(self, status):
return self._factory.create_tp_response(status)
def _create_txn(self, txn_function, game, action, space=None):
payload = ",".join([
str(game), str(action), str(space)
]).encode()
addresses = [self._game_to_address(game)]
return txn_function(payload, addresses, addresses, [])
def create_tp_process_request(self, action, game, space=None):
txn_function = self._factory.create_tp_process_request
return self._create_txn(txn_function, game, action, space)
def create_transaction(self, game, action, space=None):
txn_function = self._factory.create_transaction
return self._create_txn(txn_function, game, action, space)
def create_get_request(self, game):
addresses = [self._game_to_address(game)]
return self._factory.create_get_request(addresses)
def create_get_response(
self, game, board="---------", state="P1-NEXT", player1="", player2=""
):
address = self._game_to_address(game)
data = None
if board is not None:
data = ",".join([game, board, state, player1, player2]).encode()
else:
data = None
return self._factory.create_get_response({address: data})
def create_set_request(
self, game, board="---------", state="P1-NEXT", player1="", player2=""
):
address = self._game_to_address(game)
data = None
if state is not None:
data = ",".join([game, board, state, player1, player2]).encode()
else:
data = None
return self._factory.create_set_request({address: data})
def create_set_response(self, game):
addresses = [self._game_to_address(game)]
return self._factory.create_set_response(addresses)
def get_public_key(self):
return self._factory.get_public_key() | 0.754915 | 0.29682 |
from urllib.request import urlopen, Request
from urllib.parse import urlencode, quote_plus
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
import threading, random
browsers = ['Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.1) Gecko/20090718 Firefox/3.5.1',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30729)',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x64; Trident/4.0)',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; .NET CLR 2.0.50727; InfoPath.2)',
'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)',
'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)',
'Opera/9.80 (Windows NT 5.2; U; ru) Presto/2.5.22 Version/10.51']
referrer = ['http://www.google.com/?q=',
'http://www.usatoday.com/search/results?q=',
'http://engadget.search.aol.com/search?q=',
'https://www.bing.com/search?q=']
class Search(threading.Thread):
#NOTE, this is not using the API therefore the max results you can get it 10 - change this!
def __init__(self, q):
self.q = q
self.url = "https://www.bing.com"
# here is where we open url and make it into a bs4 object
self.query = quote_plus(self.q)
self.fullUrl = "https://www.bing.com/search?q=%s" % (self.query)
req = Request(self.fullUrl)
req.add_header('User-Agent', random.choice(browsers))
req.add_header('Accept-Language', 'en-US,en;q=0.5')
req.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
req.add_header('Cache-Control', 'no-cache')
req.add_header('Referer', random.choice(referrer))
resp = urlopen(req)
html = resp.read()
self.html = BeautifulSoup(html)
def __search__(self, resultType='search', *args, **kwargs):
results = []
displayResults = kwargs.get('displayResults')
numResults = kwargs.get('numResults')
html = self.html
if(resultType == 'search'):
for res in html.find_all('li', attrs={'class': 'b_algo'}):
res = res.find('div', attrs={'class': 'b_caption'})
res = res.find('p')
text = res.get_text()
results.append(smart_str(text))
elif(resultType == 'resultCount'):
sbCount = html.find('span', attrs={'class': 'sb_count'})
sbCount = sbCount.get_text()[:-8]
results.append(smart_str(sbCount))
elif(resultType == 'getUrls'):
for url in html.find_all('li', attrs={'class': 'b_algo'}):
url = url.find('div', attrs={'class': 'b_attribution'})
url = url.find('cite')
cleanUrl = url.get_text()
results.append(smart_str(cleanUrl))
elif(resultType == 'autocorrect'):
try:
ac = html.find('div', attrs={'id': 'sp_requery'})
ac = ac.find('a')
cleanAc = ac.get_text()
results.append(smart_str(cleanAc))
except Exception: results.append(False)
elif(resultType == 'headline'):
for headline in html.find_all('li', attrs={'class': 'b_algo'}):
headline = headline.find('h2').find('a')
cleanHeadline = headline.get_text()
results.append(smart_str(cleanHeadline))
#trim list
if(resultType == 'search' or resultType == 'getUrls' or resultType == 'headline'): del results[numResults:]
if(displayResults==True): print(results)
elif(displayResults==False): return(results)
def resultCount(self, displayResults=True):
self.__search__(resultType='resultCount', displayResults=displayResults)
def autocorrect(self, displayResults=True):
self.__search__(resultType='autocorrect', displayResults=displayResults)
def headline(self, numResults=10, displayResults=True):
self.__search__(resultType='headline', numResults=numResults, displayResults=displayResults)
def search(self, numResults=10, displayResults=True):
self.__search__(resultType='search', numResults=numResults, displayResults=displayResults)
def getUrls(self, numResults=10, displayResults=True):
self.__search__(resultType='getUrls', numResults=numResults, displayResults=displayResults)
def debug(self):
print('q= "%s"' % (str(self.q)))
print('full_url= "%s"' % (str(self.fullUrl)))
def usage():
print('USAGE:')
print('from BingQuaker.core import Search')
print("app = Search('QUERY') - numResults and displayResults are optional")
print('app.resultCount(displayResults=True) - Prints how many results the query returns')
print('app.autocorrect(displayResults=False) - If the word is spelt wrong, returns the correct suggestion')
print('app.headline(displayResults=False, numResults=3) - Returns the top 3 headlines')
print('app.search(displayResults=False, numResults=6) - Returns the top 6 main information (unless you set displayResults to False)')
print('app.getUrls(displayResults=True, numResults=2) - Prints the top 2 urls from the page')
print('app.debug() - Displays information about things (meant for debugging)')
print('SEE TESTS.PY FOR MORE!')
print('SEE TESTS.PY FOR MORE!')
print('SEE TESTS.PY FOR MORE!')
if __name__ == "__main__":
usage() | BingQuaker/core.py | from urllib.request import urlopen, Request
from urllib.parse import urlencode, quote_plus
from bs4 import BeautifulSoup
from django.utils.encoding import smart_str
import threading, random
browsers = ['Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.3) Gecko/20090913 Firefox/3.5.3',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3 (.NET CLR 3.5.30729)',
'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.1) Gecko/20090718 Firefox/3.5.1',
'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US) AppleWebKit/532.1 (KHTML, like Gecko) Chrome/4.0.219.6 Safari/532.1',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; WOW64; Trident/4.0; SLCC2; .NET CLR 2.0.50727; InfoPath.2)',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30729)',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Win64; x64; Trident/4.0)',
'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; SV1; .NET CLR 2.0.50727; InfoPath.2)',
'Mozilla/5.0 (Windows; U; MSIE 7.0; Windows NT 6.0; en-US)',
'Mozilla/4.0 (compatible; MSIE 6.1; Windows XP)',
'Opera/9.80 (Windows NT 5.2; U; ru) Presto/2.5.22 Version/10.51']
referrer = ['http://www.google.com/?q=',
'http://www.usatoday.com/search/results?q=',
'http://engadget.search.aol.com/search?q=',
'https://www.bing.com/search?q=']
class Search(threading.Thread):
#NOTE, this is not using the API therefore the max results you can get it 10 - change this!
def __init__(self, q):
self.q = q
self.url = "https://www.bing.com"
# here is where we open url and make it into a bs4 object
self.query = quote_plus(self.q)
self.fullUrl = "https://www.bing.com/search?q=%s" % (self.query)
req = Request(self.fullUrl)
req.add_header('User-Agent', random.choice(browsers))
req.add_header('Accept-Language', 'en-US,en;q=0.5')
req.add_header('Accept-Charset', 'ISO-8859-1,utf-8;q=0.7,*;q=0.7')
req.add_header('Cache-Control', 'no-cache')
req.add_header('Referer', random.choice(referrer))
resp = urlopen(req)
html = resp.read()
self.html = BeautifulSoup(html)
def __search__(self, resultType='search', *args, **kwargs):
results = []
displayResults = kwargs.get('displayResults')
numResults = kwargs.get('numResults')
html = self.html
if(resultType == 'search'):
for res in html.find_all('li', attrs={'class': 'b_algo'}):
res = res.find('div', attrs={'class': 'b_caption'})
res = res.find('p')
text = res.get_text()
results.append(smart_str(text))
elif(resultType == 'resultCount'):
sbCount = html.find('span', attrs={'class': 'sb_count'})
sbCount = sbCount.get_text()[:-8]
results.append(smart_str(sbCount))
elif(resultType == 'getUrls'):
for url in html.find_all('li', attrs={'class': 'b_algo'}):
url = url.find('div', attrs={'class': 'b_attribution'})
url = url.find('cite')
cleanUrl = url.get_text()
results.append(smart_str(cleanUrl))
elif(resultType == 'autocorrect'):
try:
ac = html.find('div', attrs={'id': 'sp_requery'})
ac = ac.find('a')
cleanAc = ac.get_text()
results.append(smart_str(cleanAc))
except Exception: results.append(False)
elif(resultType == 'headline'):
for headline in html.find_all('li', attrs={'class': 'b_algo'}):
headline = headline.find('h2').find('a')
cleanHeadline = headline.get_text()
results.append(smart_str(cleanHeadline))
#trim list
if(resultType == 'search' or resultType == 'getUrls' or resultType == 'headline'): del results[numResults:]
if(displayResults==True): print(results)
elif(displayResults==False): return(results)
def resultCount(self, displayResults=True):
self.__search__(resultType='resultCount', displayResults=displayResults)
def autocorrect(self, displayResults=True):
self.__search__(resultType='autocorrect', displayResults=displayResults)
def headline(self, numResults=10, displayResults=True):
self.__search__(resultType='headline', numResults=numResults, displayResults=displayResults)
def search(self, numResults=10, displayResults=True):
self.__search__(resultType='search', numResults=numResults, displayResults=displayResults)
def getUrls(self, numResults=10, displayResults=True):
self.__search__(resultType='getUrls', numResults=numResults, displayResults=displayResults)
def debug(self):
print('q= "%s"' % (str(self.q)))
print('full_url= "%s"' % (str(self.fullUrl)))
def usage():
print('USAGE:')
print('from BingQuaker.core import Search')
print("app = Search('QUERY') - numResults and displayResults are optional")
print('app.resultCount(displayResults=True) - Prints how many results the query returns')
print('app.autocorrect(displayResults=False) - If the word is spelt wrong, returns the correct suggestion')
print('app.headline(displayResults=False, numResults=3) - Returns the top 3 headlines')
print('app.search(displayResults=False, numResults=6) - Returns the top 6 main information (unless you set displayResults to False)')
print('app.getUrls(displayResults=True, numResults=2) - Prints the top 2 urls from the page')
print('app.debug() - Displays information about things (meant for debugging)')
print('SEE TESTS.PY FOR MORE!')
print('SEE TESTS.PY FOR MORE!')
print('SEE TESTS.PY FOR MORE!')
if __name__ == "__main__":
usage() | 0.372619 | 0.104843 |
from bootstrapvz.base import Task
from bootstrapvz.common import phases
from bootstrapvz.common.tasks import workspace
from bootstrapvz.common.tools import rel_path
import os
import shutil
import json
assets = rel_path(__file__, 'assets')
class CheckBoxPath(Task):
description = 'Checking if the vagrant box file already exists'
phase = phases.validation
@classmethod
def run(cls, info):
box_basename = info.manifest.name.format(**info.manifest_vars)
box_name = box_basename + '.box'
box_path = os.path.join(info.manifest.bootstrapper['workspace'], box_name)
if os.path.exists(box_path):
from bootstrapvz.common.exceptions import TaskError
msg = 'The vagrant box `{name}\' already exists at `{path}\''.format(name=box_name, path=box_path)
raise TaskError(msg)
info._vagrant['box_name'] = box_name
info._vagrant['box_path'] = box_path
class CreateVagrantBoxDir(Task):
description = 'Creating directory for the vagrant box'
phase = phases.preparation
predecessors = [workspace.CreateWorkspace]
@classmethod
def run(cls, info):
info._vagrant['folder'] = os.path.join(info.workspace, 'vagrant')
os.mkdir(info._vagrant['folder'])
class AddPackages(Task):
description = 'Add packages that vagrant depends on'
phase = phases.preparation
@classmethod
def run(cls, info):
info.packages.add('openssh-server')
info.packages.add('sudo')
info.packages.add('nfs-client')
class CreateVagrantUser(Task):
description = 'Creating the vagrant user'
phase = phases.system_modification
@classmethod
def run(cls, info):
from bootstrapvz.common.tools import log_check_call
log_check_call(['chroot', info.root,
'useradd',
'--create-home', '--shell', '/bin/bash',
'vagrant'])
class PasswordlessSudo(Task):
description = 'Allowing the vagrant user to use sudo without a password'
phase = phases.system_modification
@classmethod
def run(cls, info):
sudo_vagrant_path = os.path.join(info.root, 'etc/sudoers.d/vagrant')
with open(sudo_vagrant_path, 'w') as sudo_vagrant:
sudo_vagrant.write('vagrant ALL=(ALL) NOPASSWD:ALL')
import stat
ug_read_only = (stat.S_IRUSR | stat.S_IRGRP)
os.chmod(sudo_vagrant_path, ug_read_only)
class AddInsecurePublicKey(Task):
description = 'Adding vagrant insecure public key'
phase = phases.system_modification
predecessors = [CreateVagrantUser]
@classmethod
def run(cls, info):
ssh_dir = os.path.join(info.root, 'home/vagrant/.ssh')
os.mkdir(ssh_dir)
authorized_keys_source_path = os.path.join(assets, 'authorized_keys')
with open(authorized_keys_source_path, 'r') as authorized_keys_source:
insecure_public_key = authorized_keys_source.read()
authorized_keys_path = os.path.join(ssh_dir, 'authorized_keys')
with open(authorized_keys_path, 'a') as authorized_keys:
authorized_keys.write(insecure_public_key)
import stat
os.chmod(ssh_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
os.chmod(authorized_keys_path, stat.S_IRUSR | stat.S_IWUSR)
# We can't do this directly with python, since getpwnam gets its info from the host
from bootstrapvz.common.tools import log_check_call
log_check_call(['chroot', info.root,
'chown', 'vagrant:vagrant',
'/home/vagrant/.ssh', '/home/vagrant/.ssh/authorized_keys'])
class SetRootPassword(Task):
description = 'Setting the root password to `<PASSWORD>\''
phase = phases.system_modification
@classmethod
def run(cls, info):
from bootstrapvz.common.tools import log_check_call
log_check_call(['chroot', info.root, 'chpasswd'], 'root:vagrant')
class PackageBox(Task):
description = 'Packaging the volume as a vagrant box'
phase = phases.image_registration
@classmethod
def run(cls, info):
vagrantfile_source = os.path.join(assets, 'Vagrantfile')
vagrantfile = os.path.join(info._vagrant['folder'], 'Vagrantfile')
shutil.copy(vagrantfile_source, vagrantfile)
import random
mac_address = '080027{mac:06X}'.format(mac=random.randrange(16 ** 6))
from bootstrapvz.common.tools import sed_i
sed_i(vagrantfile, '\\[MAC_ADDRESS\\]', mac_address)
vagrant_provider = info.manifest.plugins['vagrant'].get('provider', 'virtualbox')
metadata = {'provider': vagrant_provider}
if vagrant_provider == 'libvirt':
metadata['format'] = info.manifest.volume['backing']
virtual_size = info.volume.size.bytes.get_qty_in('G')
metadata['virtual_size'] = virtual_size
metadata_file = os.path.join(info._vagrant['folder'], 'metadata.json')
with open(metadata_file, 'w') as f:
json.dump(metadata, f)
from bootstrapvz.common.tools import log_check_call
if vagrant_provider == 'libvirt':
disk_name = 'box.img'
else:
disk_name = 'box-disk1.' + info.volume.extension
ovf_path = os.path.join(info._vagrant['folder'], 'box.ovf')
cls.write_ovf(info, ovf_path, mac_address, disk_name)
disk_link = os.path.join(info._vagrant['folder'], disk_name)
log_check_call(['ln', '-s', info.volume.image_path, disk_link])
box_files = os.listdir(info._vagrant['folder'])
log_check_call(['tar', '--create', '--gzip', '--dereference',
'--file', info._vagrant['box_path'],
'--directory', info._vagrant['folder']] + box_files
)
import logging
logging.getLogger(__name__).info('The vagrant box has been placed at ' + info._vagrant['box_path'])
@classmethod
def write_ovf(cls, info, destination, mac_address, disk_name):
namespaces = {'': 'http://schemas.dmtf.org/ovf/envelope/1',
'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
'rasd': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData',
'vssd': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'vbox': 'http://www.virtualbox.org/ovf/machine',
}
def attr(element, name, value=None):
for prefix, ns in namespaces.iteritems():
name = name.replace(prefix + ':', '{' + ns + '}')
if value is None:
return element.attrib[name]
else:
element.attrib[name] = str(value)
template_path = os.path.join(assets, 'box.ovf')
import xml.etree.ElementTree as ET
template = ET.parse(template_path)
root = template.getroot()
[disk_ref] = root.findall('./ovf:References/ovf:File', namespaces)
attr(disk_ref, 'ovf:href', disk_name)
# List of OVF disk format URIs
# Snatched from VBox source (src/VBox/Main/src-server/ApplianceImpl.cpp:47)
# ISOURI = "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
# VMDKStreamURI = "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
# VMDKSparseURI = "http://www.vmware.com/specifications/vmdk.html#sparse"
# VMDKCompressedURI = "http://www.vmware.com/specifications/vmdk.html#compressed"
# VMDKCompressedURI2 = "http://www.vmware.com/interfaces/specifications/vmdk.html#compressed"
# VHDURI = "http://go.microsoft.com/fwlink/?LinkId=137171"
volume_uuid = info.volume.get_uuid()
[disk] = root.findall('./ovf:DiskSection/ovf:Disk', namespaces)
attr(disk, 'ovf:capacity', info.volume.size.bytes.get_qty_in('B'))
attr(disk, 'ovf:format', info.volume.ovf_uri)
attr(disk, 'vbox:uuid', volume_uuid)
[system] = root.findall('./ovf:VirtualSystem', namespaces)
attr(system, 'ovf:id', info._vagrant['box_name'])
# Set the operating system
[os_section] = system.findall('./ovf:OperatingSystemSection', namespaces)
os_info = {'i386': {'id': 96, 'name': 'Debian'},
'amd64': {'id': 96, 'name': 'Debian_64'}
}.get(info.manifest.system['architecture'])
attr(os_section, 'ovf:id', os_info['id'])
[os_desc] = os_section.findall('./ovf:Description', namespaces)
os_desc.text = os_info['name']
[os_type] = os_section.findall('./vbox:OSType', namespaces)
os_type.text = os_info['name']
[sysid] = system.findall('./ovf:VirtualHardwareSection/ovf:System/'
'vssd:VirtualSystemIdentifier', namespaces)
sysid.text = info._vagrant['box_name']
[machine] = system.findall('./vbox:Machine', namespaces)
import uuid
attr(machine, 'ovf:uuid', uuid.uuid4())
attr(machine, 'ovf:name', info._vagrant['box_name'])
from datetime import datetime
attr(machine, 'ovf:lastStateChange', datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'))
[nic] = machine.findall('./ovf:Hardware/ovf:Network/ovf:Adapter', namespaces)
attr(machine, 'ovf:MACAddress', mac_address)
[device_img] = machine.findall('./ovf:StorageControllers'
'/ovf:StorageController[@name="SATA Controller"]'
'/ovf:AttachedDevice/ovf:Image', namespaces)
attr(device_img, 'uuid', '{' + str(volume_uuid) + '}')
template.write(destination, xml_declaration=True) # , default_namespace=namespaces['ovf']
class RemoveVagrantBoxDir(Task):
description = 'Removing the vagrant box directory'
phase = phases.cleaning
successors = [workspace.DeleteWorkspace]
@classmethod
def run(cls, info):
shutil.rmtree(info._vagrant['folder'])
del info._vagrant['folder'] | bootstrapvz/plugins/vagrant/tasks.py | from bootstrapvz.base import Task
from bootstrapvz.common import phases
from bootstrapvz.common.tasks import workspace
from bootstrapvz.common.tools import rel_path
import os
import shutil
import json
assets = rel_path(__file__, 'assets')
class CheckBoxPath(Task):
description = 'Checking if the vagrant box file already exists'
phase = phases.validation
@classmethod
def run(cls, info):
box_basename = info.manifest.name.format(**info.manifest_vars)
box_name = box_basename + '.box'
box_path = os.path.join(info.manifest.bootstrapper['workspace'], box_name)
if os.path.exists(box_path):
from bootstrapvz.common.exceptions import TaskError
msg = 'The vagrant box `{name}\' already exists at `{path}\''.format(name=box_name, path=box_path)
raise TaskError(msg)
info._vagrant['box_name'] = box_name
info._vagrant['box_path'] = box_path
class CreateVagrantBoxDir(Task):
description = 'Creating directory for the vagrant box'
phase = phases.preparation
predecessors = [workspace.CreateWorkspace]
@classmethod
def run(cls, info):
info._vagrant['folder'] = os.path.join(info.workspace, 'vagrant')
os.mkdir(info._vagrant['folder'])
class AddPackages(Task):
description = 'Add packages that vagrant depends on'
phase = phases.preparation
@classmethod
def run(cls, info):
info.packages.add('openssh-server')
info.packages.add('sudo')
info.packages.add('nfs-client')
class CreateVagrantUser(Task):
description = 'Creating the vagrant user'
phase = phases.system_modification
@classmethod
def run(cls, info):
from bootstrapvz.common.tools import log_check_call
log_check_call(['chroot', info.root,
'useradd',
'--create-home', '--shell', '/bin/bash',
'vagrant'])
class PasswordlessSudo(Task):
description = 'Allowing the vagrant user to use sudo without a password'
phase = phases.system_modification
@classmethod
def run(cls, info):
sudo_vagrant_path = os.path.join(info.root, 'etc/sudoers.d/vagrant')
with open(sudo_vagrant_path, 'w') as sudo_vagrant:
sudo_vagrant.write('vagrant ALL=(ALL) NOPASSWD:ALL')
import stat
ug_read_only = (stat.S_IRUSR | stat.S_IRGRP)
os.chmod(sudo_vagrant_path, ug_read_only)
class AddInsecurePublicKey(Task):
description = 'Adding vagrant insecure public key'
phase = phases.system_modification
predecessors = [CreateVagrantUser]
@classmethod
def run(cls, info):
ssh_dir = os.path.join(info.root, 'home/vagrant/.ssh')
os.mkdir(ssh_dir)
authorized_keys_source_path = os.path.join(assets, 'authorized_keys')
with open(authorized_keys_source_path, 'r') as authorized_keys_source:
insecure_public_key = authorized_keys_source.read()
authorized_keys_path = os.path.join(ssh_dir, 'authorized_keys')
with open(authorized_keys_path, 'a') as authorized_keys:
authorized_keys.write(insecure_public_key)
import stat
os.chmod(ssh_dir, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
os.chmod(authorized_keys_path, stat.S_IRUSR | stat.S_IWUSR)
# We can't do this directly with python, since getpwnam gets its info from the host
from bootstrapvz.common.tools import log_check_call
log_check_call(['chroot', info.root,
'chown', 'vagrant:vagrant',
'/home/vagrant/.ssh', '/home/vagrant/.ssh/authorized_keys'])
class SetRootPassword(Task):
description = 'Setting the root password to `<PASSWORD>\''
phase = phases.system_modification
@classmethod
def run(cls, info):
from bootstrapvz.common.tools import log_check_call
log_check_call(['chroot', info.root, 'chpasswd'], 'root:vagrant')
class PackageBox(Task):
description = 'Packaging the volume as a vagrant box'
phase = phases.image_registration
@classmethod
def run(cls, info):
vagrantfile_source = os.path.join(assets, 'Vagrantfile')
vagrantfile = os.path.join(info._vagrant['folder'], 'Vagrantfile')
shutil.copy(vagrantfile_source, vagrantfile)
import random
mac_address = '080027{mac:06X}'.format(mac=random.randrange(16 ** 6))
from bootstrapvz.common.tools import sed_i
sed_i(vagrantfile, '\\[MAC_ADDRESS\\]', mac_address)
vagrant_provider = info.manifest.plugins['vagrant'].get('provider', 'virtualbox')
metadata = {'provider': vagrant_provider}
if vagrant_provider == 'libvirt':
metadata['format'] = info.manifest.volume['backing']
virtual_size = info.volume.size.bytes.get_qty_in('G')
metadata['virtual_size'] = virtual_size
metadata_file = os.path.join(info._vagrant['folder'], 'metadata.json')
with open(metadata_file, 'w') as f:
json.dump(metadata, f)
from bootstrapvz.common.tools import log_check_call
if vagrant_provider == 'libvirt':
disk_name = 'box.img'
else:
disk_name = 'box-disk1.' + info.volume.extension
ovf_path = os.path.join(info._vagrant['folder'], 'box.ovf')
cls.write_ovf(info, ovf_path, mac_address, disk_name)
disk_link = os.path.join(info._vagrant['folder'], disk_name)
log_check_call(['ln', '-s', info.volume.image_path, disk_link])
box_files = os.listdir(info._vagrant['folder'])
log_check_call(['tar', '--create', '--gzip', '--dereference',
'--file', info._vagrant['box_path'],
'--directory', info._vagrant['folder']] + box_files
)
import logging
logging.getLogger(__name__).info('The vagrant box has been placed at ' + info._vagrant['box_path'])
@classmethod
def write_ovf(cls, info, destination, mac_address, disk_name):
namespaces = {'': 'http://schemas.dmtf.org/ovf/envelope/1',
'ovf': 'http://schemas.dmtf.org/ovf/envelope/1',
'rasd': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_ResourceAllocationSettingData',
'vssd': 'http://schemas.dmtf.org/wbem/wscim/1/cim-schema/2/CIM_VirtualSystemSettingData',
'xsi': 'http://www.w3.org/2001/XMLSchema-instance',
'vbox': 'http://www.virtualbox.org/ovf/machine',
}
def attr(element, name, value=None):
for prefix, ns in namespaces.iteritems():
name = name.replace(prefix + ':', '{' + ns + '}')
if value is None:
return element.attrib[name]
else:
element.attrib[name] = str(value)
template_path = os.path.join(assets, 'box.ovf')
import xml.etree.ElementTree as ET
template = ET.parse(template_path)
root = template.getroot()
[disk_ref] = root.findall('./ovf:References/ovf:File', namespaces)
attr(disk_ref, 'ovf:href', disk_name)
# List of OVF disk format URIs
# Snatched from VBox source (src/VBox/Main/src-server/ApplianceImpl.cpp:47)
# ISOURI = "http://www.ecma-international.org/publications/standards/Ecma-119.htm"
# VMDKStreamURI = "http://www.vmware.com/interfaces/specifications/vmdk.html#streamOptimized"
# VMDKSparseURI = "http://www.vmware.com/specifications/vmdk.html#sparse"
# VMDKCompressedURI = "http://www.vmware.com/specifications/vmdk.html#compressed"
# VMDKCompressedURI2 = "http://www.vmware.com/interfaces/specifications/vmdk.html#compressed"
# VHDURI = "http://go.microsoft.com/fwlink/?LinkId=137171"
volume_uuid = info.volume.get_uuid()
[disk] = root.findall('./ovf:DiskSection/ovf:Disk', namespaces)
attr(disk, 'ovf:capacity', info.volume.size.bytes.get_qty_in('B'))
attr(disk, 'ovf:format', info.volume.ovf_uri)
attr(disk, 'vbox:uuid', volume_uuid)
[system] = root.findall('./ovf:VirtualSystem', namespaces)
attr(system, 'ovf:id', info._vagrant['box_name'])
# Set the operating system
[os_section] = system.findall('./ovf:OperatingSystemSection', namespaces)
os_info = {'i386': {'id': 96, 'name': 'Debian'},
'amd64': {'id': 96, 'name': 'Debian_64'}
}.get(info.manifest.system['architecture'])
attr(os_section, 'ovf:id', os_info['id'])
[os_desc] = os_section.findall('./ovf:Description', namespaces)
os_desc.text = os_info['name']
[os_type] = os_section.findall('./vbox:OSType', namespaces)
os_type.text = os_info['name']
[sysid] = system.findall('./ovf:VirtualHardwareSection/ovf:System/'
'vssd:VirtualSystemIdentifier', namespaces)
sysid.text = info._vagrant['box_name']
[machine] = system.findall('./vbox:Machine', namespaces)
import uuid
attr(machine, 'ovf:uuid', uuid.uuid4())
attr(machine, 'ovf:name', info._vagrant['box_name'])
from datetime import datetime
attr(machine, 'ovf:lastStateChange', datetime.now().strftime('%Y-%m-%dT%H:%M:%SZ'))
[nic] = machine.findall('./ovf:Hardware/ovf:Network/ovf:Adapter', namespaces)
attr(machine, 'ovf:MACAddress', mac_address)
[device_img] = machine.findall('./ovf:StorageControllers'
'/ovf:StorageController[@name="SATA Controller"]'
'/ovf:AttachedDevice/ovf:Image', namespaces)
attr(device_img, 'uuid', '{' + str(volume_uuid) + '}')
template.write(destination, xml_declaration=True) # , default_namespace=namespaces['ovf']
class RemoveVagrantBoxDir(Task):
description = 'Removing the vagrant box directory'
phase = phases.cleaning
successors = [workspace.DeleteWorkspace]
@classmethod
def run(cls, info):
shutil.rmtree(info._vagrant['folder'])
del info._vagrant['folder'] | 0.50293 | 0.099821 |
from sqlalchemy import (
create_engine,
Column,
ForeignKey,
Integer,
String,
PrimaryKeyConstraint,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from .common import CHANNELS
Base = declarative_base()
session = None # needs setup to be called!
class Channel(Base):
__tablename__ = "channels"
id = Column(Integer, primary_key=True)
frequency = Column(Integer, nullable=False)
name = Column(String, nullable=False)
class Pilot(Base):
__tablename__ = "pilots"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
class Copter(Base):
__tablename__ = "copter"
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
pilot_id = Column(Integer, ForeignKey("pilots.id"))
pilot = relationship("Pilot")
def __init__(self, name, pilot):
self.name = name
self.pilot = pilot
def __repr__(self):
return "Copter(name=%r, id=%r, pilot_id=%r)" % (
self.name,
self.id,
self.pliot_id,
)
class Heat(Base):
__tablename__ = "heats"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
@classmethod
def active(cls):
return CurrentState.instance().heat
class HeatEntry(Base):
__tablename__ = "heat_entries"
heat_id = Column(Integer, ForeignKey("heats.id"), primary_key=True)
copter_id = Column(Integer, ForeignKey("copter.id"), primary_key=True)
channel_id = Column(Integer, ForeignKey("channels.id"), primary_key=True)
heat = relationship("Heat")
channel = relationship("Channel")
copter = relationship("Copter")
class CurrentState(Base):
__tablename__ = "current_state"
id = Column(Integer, primary_key=True)
heat_id = Column(Integer, ForeignKey("heats.id"))
heat = relationship("Heat")
@classmethod
def instance(cls):
return session.query(cls).first()
def create_master_data():
for band, frequencies in CHANNELS.items():
for index, frequency in enumerate(frequencies, start=1):
name = f"{band}{index}"
existing = session.query(Channel).\
filter(Channel.name == name).\
filter(Channel.frequency == frequency).first()
if existing is None:
channel = Channel()
channel.frequency = frequency
channel.name = name
session.add(channel)
cs_count = session.query(CurrentState).count()
assert cs_count <= 1, "Too many CurrentState entries!"
if not cs_count:
cs = CurrentState()
cs.id = 1
session.add(cs)
session.commit()
def setup(uri, *, echo=False):
global session
engine = create_engine(uri, echo=echo)
Base.metadata.create_all(engine)
session = Session(engine)
create_master_data() | src/laptimer/db.py | from sqlalchemy import (
create_engine,
Column,
ForeignKey,
Integer,
String,
PrimaryKeyConstraint,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from .common import CHANNELS
Base = declarative_base()
session = None # needs setup to be called!
class Channel(Base):
__tablename__ = "channels"
id = Column(Integer, primary_key=True)
frequency = Column(Integer, nullable=False)
name = Column(String, nullable=False)
class Pilot(Base):
__tablename__ = "pilots"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
class Copter(Base):
__tablename__ = "copter"
id = Column(Integer, primary_key=True)
name = Column(String(50), nullable=False)
pilot_id = Column(Integer, ForeignKey("pilots.id"))
pilot = relationship("Pilot")
def __init__(self, name, pilot):
self.name = name
self.pilot = pilot
def __repr__(self):
return "Copter(name=%r, id=%r, pilot_id=%r)" % (
self.name,
self.id,
self.pliot_id,
)
class Heat(Base):
__tablename__ = "heats"
id = Column(Integer, primary_key=True)
name = Column(String, nullable=False)
@classmethod
def active(cls):
return CurrentState.instance().heat
class HeatEntry(Base):
__tablename__ = "heat_entries"
heat_id = Column(Integer, ForeignKey("heats.id"), primary_key=True)
copter_id = Column(Integer, ForeignKey("copter.id"), primary_key=True)
channel_id = Column(Integer, ForeignKey("channels.id"), primary_key=True)
heat = relationship("Heat")
channel = relationship("Channel")
copter = relationship("Copter")
class CurrentState(Base):
__tablename__ = "current_state"
id = Column(Integer, primary_key=True)
heat_id = Column(Integer, ForeignKey("heats.id"))
heat = relationship("Heat")
@classmethod
def instance(cls):
return session.query(cls).first()
def create_master_data():
for band, frequencies in CHANNELS.items():
for index, frequency in enumerate(frequencies, start=1):
name = f"{band}{index}"
existing = session.query(Channel).\
filter(Channel.name == name).\
filter(Channel.frequency == frequency).first()
if existing is None:
channel = Channel()
channel.frequency = frequency
channel.name = name
session.add(channel)
cs_count = session.query(CurrentState).count()
assert cs_count <= 1, "Too many CurrentState entries!"
if not cs_count:
cs = CurrentState()
cs.id = 1
session.add(cs)
session.commit()
def setup(uri, *, echo=False):
global session
engine = create_engine(uri, echo=echo)
Base.metadata.create_all(engine)
session = Session(engine)
create_master_data() | 0.59843 | 0.236643 |
import logging
from babel import Locale
from functools import lru_cache
from flask import Blueprint, request, current_app
from flask_babel import gettext, get_locale
from elasticsearch import TransportError
from followthemoney import model
from followthemoney.exc import InvalidData
from jwt import ExpiredSignatureError, DecodeError
from aleph import __version__
from aleph.core import settings, url_for, cache, archive
from aleph.authz import Authz
from aleph.model import Collection, Role
from aleph.logic.pages import load_pages
from aleph.logic.util import collection_url
from aleph.validation import get_openapi_spec
from aleph.views.context import enable_cache, NotModified
from aleph.views.util import jsonify, render_xml
blueprint = Blueprint("base_api", __name__)
log = logging.getLogger(__name__)
@lru_cache(maxsize=None)
def _metadata_locale(locale):
# This is cached in part because latency on this endpoint is
# particularly relevant to the first render being shown to a
# user.
auth = {"oauth": settings.OAUTH}
if settings.PASSWORD_LOGIN:
auth["password_login_uri"] = url_for("sessions_api.password_login")
if settings.PASSWORD_LOGIN and not settings.MAINTENANCE:
auth["registration_uri"] = url_for("roles_api.create_code")
if settings.OAUTH:
auth["oauth_uri"] = url_for("sessions_api.oauth_init")
locales = settings.UI_LANGUAGES
locales = {loc: Locale(loc).get_language_name(loc) for loc in locales}
# This is dumb but we agreed it with ARIJ
# https://github.com/alephdata/aleph/issues/1432
app_logo = settings.APP_LOGO
if locale.startswith("ar"):
app_logo = settings.APP_LOGO_AR or app_logo
return {
"status": "ok",
"maintenance": settings.MAINTENANCE,
"app": {
"title": settings.APP_TITLE,
"version": __version__,
"banner": settings.APP_BANNER,
"ui_uri": settings.APP_UI_URL,
"publish": archive.can_publish,
"logo": app_logo,
"favicon": settings.APP_FAVICON,
"locale": locale,
"locales": locales,
},
"categories": Collection.CATEGORIES,
"frequencies": Collection.FREQUENCIES,
"pages": load_pages(locale),
"model": model.to_dict(),
"token": None,
"auth": auth,
}
@blueprint.route("/api/2/metadata")
def metadata():
"""Get operational metadata for the frontend.
---
get:
summary: Retrieve system metadata from the application.
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
tags:
- System
"""
request.rate_limit = None
locale = str(get_locale())
data = _metadata_locale(locale)
if settings.SINGLE_USER:
role = Role.load_cli_user()
authz = Authz.from_role(role)
data["token"] = authz.to_token()
return jsonify(data)
@blueprint.route("/api/openapi.json")
def openapi():
"""Generate an OpenAPI 3.0 documentation JSON file for the API."""
enable_cache(vary_user=False)
spec = get_openapi_spec(current_app)
for name, view in current_app.view_functions.items():
if name in (
"static",
"base_api.openapi",
"base_api.api_v1_message",
"sessions_api.oauth_callback",
):
continue
log.info("%s - %s", name, view.__qualname__)
spec.path(view=view)
return jsonify(spec.to_dict())
@blueprint.route("/api/2/statistics")
def statistics():
"""Get a summary of the data acessible to an anonymous user.
Changed [3.9]: Previously, this would return user-specific stats.
---
get:
summary: System-wide user statistics.
description: >
Get a summary of the data acessible to an anonymous user.
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
tags:
- System
"""
enable_cache(vary_user=False)
key = cache.key(cache.STATISTICS)
data = {"countries": [], "schemata": [], "categories": []}
data = cache.get_complex(key) or data
return jsonify(data)
@blueprint.route("/api/2/sitemap.xml")
def sitemap():
"""
---
get:
summary: Get a sitemap
description: >-
Returns a site map for search engine robots. This lists each
published collection on the current instance.
responses:
'200':
description: OK
content:
text/xml:
schema:
type: object
tags:
- System
"""
enable_cache(vary_user=False)
request.rate_limit = None
collections = []
for collection in Collection.all_authz(Authz.from_role(None)):
updated_at = collection.updated_at.date().isoformat()
updated_at = max(settings.SITEMAP_FLOOR, updated_at)
url = collection_url(collection.id)
collections.append({"url": url, "updated_at": updated_at})
return render_xml("sitemap.xml", collections=collections)
@blueprint.route("/healthz")
def healthz():
"""
---
get:
summary: Health check endpoint.
description: >
This can be used e.g. for Kubernetes health checks, but it doesn't
do any internal checks.
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: 'ok'
tags:
- System
"""
request.rate_limit = None
return jsonify({"status": "ok"})
@blueprint.app_errorhandler(NotModified)
def handle_not_modified(err):
return ("", 304)
@blueprint.app_errorhandler(400)
def handle_bad_request(err):
if err.response is not None and err.response.is_json:
return err.response
return jsonify({"status": "error", "message": err.description}, status=400)
@blueprint.app_errorhandler(403)
def handle_authz_error(err):
return jsonify(
{
"status": "error",
"message": gettext("You are not authorized to do this."),
"roles": request.authz.roles,
},
status=403,
)
@blueprint.app_errorhandler(404)
def handle_not_found_error(err):
msg = gettext("This path does not exist.")
return jsonify({"status": "error", "message": msg}, status=404)
@blueprint.app_errorhandler(500)
def handle_server_error(err):
log.exception("%s: %s", type(err).__name__, err)
msg = gettext("Internal server error.")
return jsonify({"status": "error", "message": msg}, status=500)
@blueprint.app_errorhandler(InvalidData)
def handle_invalid_data(err):
data = {"status": "error", "message": str(err), "errors": err.errors}
return jsonify(data, status=400)
@blueprint.app_errorhandler(DecodeError)
@blueprint.app_errorhandler(ExpiredSignatureError)
def handle_jwt_expired(err):
log.info("JWT Error: %s", err)
data = {"status": "error", "errors": gettext("Access token is invalid.")}
return jsonify(data, status=401)
@blueprint.app_errorhandler(TransportError)
def handle_es_error(err):
message = err.error
if hasattr(err, "info") and isinstance(err.info, dict):
error = err.info.get("error", {})
for root_cause in error.get("root_cause", []):
message = root_cause.get("reason", message)
try:
# Sometimes elasticsearch-py generates non-numeric status codes like
# "TIMEOUT", "N/A". Werkzeug converts them into status 0 which confuses
# web browsers. Replace the weird status codes with 500 instead.
status = int(err.status_code)
except ValueError:
status = 500
return jsonify({"status": "error", "message": message}, status=status) | aleph/views/base_api.py | import logging
from babel import Locale
from functools import lru_cache
from flask import Blueprint, request, current_app
from flask_babel import gettext, get_locale
from elasticsearch import TransportError
from followthemoney import model
from followthemoney.exc import InvalidData
from jwt import ExpiredSignatureError, DecodeError
from aleph import __version__
from aleph.core import settings, url_for, cache, archive
from aleph.authz import Authz
from aleph.model import Collection, Role
from aleph.logic.pages import load_pages
from aleph.logic.util import collection_url
from aleph.validation import get_openapi_spec
from aleph.views.context import enable_cache, NotModified
from aleph.views.util import jsonify, render_xml
blueprint = Blueprint("base_api", __name__)
log = logging.getLogger(__name__)
@lru_cache(maxsize=None)
def _metadata_locale(locale):
# This is cached in part because latency on this endpoint is
# particularly relevant to the first render being shown to a
# user.
auth = {"oauth": settings.OAUTH}
if settings.PASSWORD_LOGIN:
auth["password_login_uri"] = url_for("sessions_api.password_login")
if settings.PASSWORD_LOGIN and not settings.MAINTENANCE:
auth["registration_uri"] = url_for("roles_api.create_code")
if settings.OAUTH:
auth["oauth_uri"] = url_for("sessions_api.oauth_init")
locales = settings.UI_LANGUAGES
locales = {loc: Locale(loc).get_language_name(loc) for loc in locales}
# This is dumb but we agreed it with ARIJ
# https://github.com/alephdata/aleph/issues/1432
app_logo = settings.APP_LOGO
if locale.startswith("ar"):
app_logo = settings.APP_LOGO_AR or app_logo
return {
"status": "ok",
"maintenance": settings.MAINTENANCE,
"app": {
"title": settings.APP_TITLE,
"version": __version__,
"banner": settings.APP_BANNER,
"ui_uri": settings.APP_UI_URL,
"publish": archive.can_publish,
"logo": app_logo,
"favicon": settings.APP_FAVICON,
"locale": locale,
"locales": locales,
},
"categories": Collection.CATEGORIES,
"frequencies": Collection.FREQUENCIES,
"pages": load_pages(locale),
"model": model.to_dict(),
"token": None,
"auth": auth,
}
@blueprint.route("/api/2/metadata")
def metadata():
"""Get operational metadata for the frontend.
---
get:
summary: Retrieve system metadata from the application.
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
tags:
- System
"""
request.rate_limit = None
locale = str(get_locale())
data = _metadata_locale(locale)
if settings.SINGLE_USER:
role = Role.load_cli_user()
authz = Authz.from_role(role)
data["token"] = authz.to_token()
return jsonify(data)
@blueprint.route("/api/openapi.json")
def openapi():
"""Generate an OpenAPI 3.0 documentation JSON file for the API."""
enable_cache(vary_user=False)
spec = get_openapi_spec(current_app)
for name, view in current_app.view_functions.items():
if name in (
"static",
"base_api.openapi",
"base_api.api_v1_message",
"sessions_api.oauth_callback",
):
continue
log.info("%s - %s", name, view.__qualname__)
spec.path(view=view)
return jsonify(spec.to_dict())
@blueprint.route("/api/2/statistics")
def statistics():
"""Get a summary of the data acessible to an anonymous user.
Changed [3.9]: Previously, this would return user-specific stats.
---
get:
summary: System-wide user statistics.
description: >
Get a summary of the data acessible to an anonymous user.
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
tags:
- System
"""
enable_cache(vary_user=False)
key = cache.key(cache.STATISTICS)
data = {"countries": [], "schemata": [], "categories": []}
data = cache.get_complex(key) or data
return jsonify(data)
@blueprint.route("/api/2/sitemap.xml")
def sitemap():
"""
---
get:
summary: Get a sitemap
description: >-
Returns a site map for search engine robots. This lists each
published collection on the current instance.
responses:
'200':
description: OK
content:
text/xml:
schema:
type: object
tags:
- System
"""
enable_cache(vary_user=False)
request.rate_limit = None
collections = []
for collection in Collection.all_authz(Authz.from_role(None)):
updated_at = collection.updated_at.date().isoformat()
updated_at = max(settings.SITEMAP_FLOOR, updated_at)
url = collection_url(collection.id)
collections.append({"url": url, "updated_at": updated_at})
return render_xml("sitemap.xml", collections=collections)
@blueprint.route("/healthz")
def healthz():
"""
---
get:
summary: Health check endpoint.
description: >
This can be used e.g. for Kubernetes health checks, but it doesn't
do any internal checks.
responses:
'200':
description: OK
content:
application/json:
schema:
type: object
properties:
status:
type: string
example: 'ok'
tags:
- System
"""
request.rate_limit = None
return jsonify({"status": "ok"})
@blueprint.app_errorhandler(NotModified)
def handle_not_modified(err):
return ("", 304)
@blueprint.app_errorhandler(400)
def handle_bad_request(err):
if err.response is not None and err.response.is_json:
return err.response
return jsonify({"status": "error", "message": err.description}, status=400)
@blueprint.app_errorhandler(403)
def handle_authz_error(err):
return jsonify(
{
"status": "error",
"message": gettext("You are not authorized to do this."),
"roles": request.authz.roles,
},
status=403,
)
@blueprint.app_errorhandler(404)
def handle_not_found_error(err):
msg = gettext("This path does not exist.")
return jsonify({"status": "error", "message": msg}, status=404)
@blueprint.app_errorhandler(500)
def handle_server_error(err):
log.exception("%s: %s", type(err).__name__, err)
msg = gettext("Internal server error.")
return jsonify({"status": "error", "message": msg}, status=500)
@blueprint.app_errorhandler(InvalidData)
def handle_invalid_data(err):
data = {"status": "error", "message": str(err), "errors": err.errors}
return jsonify(data, status=400)
@blueprint.app_errorhandler(DecodeError)
@blueprint.app_errorhandler(ExpiredSignatureError)
def handle_jwt_expired(err):
log.info("JWT Error: %s", err)
data = {"status": "error", "errors": gettext("Access token is invalid.")}
return jsonify(data, status=401)
@blueprint.app_errorhandler(TransportError)
def handle_es_error(err):
message = err.error
if hasattr(err, "info") and isinstance(err.info, dict):
error = err.info.get("error", {})
for root_cause in error.get("root_cause", []):
message = root_cause.get("reason", message)
try:
# Sometimes elasticsearch-py generates non-numeric status codes like
# "TIMEOUT", "N/A". Werkzeug converts them into status 0 which confuses
# web browsers. Replace the weird status codes with 500 instead.
status = int(err.status_code)
except ValueError:
status = 500
return jsonify({"status": "error", "message": message}, status=status) | 0.583678 | 0.109016 |
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *
from past.builtins import basestring
from ..restsession import RestSession
from ..utils import (
check_type,
apply_path_params,
extract_and_parse_json,
pprint_request_info,
pprint_response_info,
)
import logging
from requests.exceptions import HTTPError
logger = logging.getLogger(__name__)
class CustomCaller(object):
"""DNA Center CustomCaller.
DNA Center CustomCaller allows API creation.
"""
def __init__(self, session, object_factory):
"""Initialize a new CustomCaller object with the provided RestSession.
Args:
session(RestSession): The RESTful session object to be used for
API calls to the DNA Center service.
Raises:
TypeError: If the parameter types are incorrect.
"""
check_type(session, RestSession)
super(CustomCaller, self).__init__()
self._session = session
self._object_factory = object_factory
if self._session._debug:
logger.setLevel(logging.DEBUG)
logger.propagate = True
else:
logger.addHandler(logging.NullHandler())
logger.propagate = False
def add_api(self, name, obj):
"""Adds an api call to the CustomCaller.
Args:
name (str): name you want to set to the api client, has to follow
python variable naming rule.
obj (object): api call which is actually a calling call_api
method.
"""
setattr(self, name, obj)
def call_api(self, method, resource_path, raise_exception=True,
original_response=False,
**kwargs):
"""Handles the requests and response.
Args:
method(basestring): type of request.
resource_path(basestring): URL in the request object.
raise_exception(bool): If True, http exceptions will be raised.
original_response(bool): If True, MyDict (JSON response) is
returned, else response object.
path_params(dict) (optional): Find each path_params' key in the
resource_path and replace it with path_params' value.
params (optional): Dictionary or bytes to be sent in the query
string for the Request.
data (optional): Dictionary, bytes, or file-like object to send in
the body of the Request.
json (optional): json data to send in the body of the Request.
headers (optional): Dictionary of HTTP Headers to send with the
Request.
cookies (optional): Dict or CookieJar object to send with the
Request.
files (optional): Dictionary of 'name': file-like-objects
(or {'name': ('filename', fileobj)}) for multipart encoding
upload.
auth (optional): Auth tuple to enable Basic/Digest/Custom
HTTP Auth.
timeout(float, tuple) (optional): How long to wait for the server
to send data before giving up, as a float, or a (connect
timeout, read timeout) tuple.
allow_redirects(bool) (optional): bool. Set to True if
POST/PUT/DELETE redirect following is allowed.
proxies(optional): Dictionary mapping protocol to the URL of the
proxy.
verify(bool,string) (optional): if True, the SSL cert will be
verified. A CA_BUNDLE path can also be provided as a string.
stream(optional): if False, the response content will be
immediately downloaded.
cert(basestring, tuple) (optional): if String, path to ssl client
cert file (.pem). If Tuple, (‘cert’, ‘key’) pair
Returns:
MyDict or object: If original_response is True returns the
original object response, else returns a JSON response with
access to the object's properties by using the dot notation
or the bracket notation. Defaults to False.
Raises:
TypeError: If the parameter types are incorrect.
HTTPError: If the DNA Center cloud returns an error.
"""
path_params = kwargs.pop('path_params', {})
resource_path = apply_path_params(resource_path, path_params)
# Ensure the url is an absolute URL
abs_url = self._session.abs_url(resource_path)
headers = self._session.headers
if 'headers' in kwargs:
headers.update(kwargs.pop('headers'))
verify = kwargs.pop("verify", self._session.verify)
logger.debug(pprint_request_info(abs_url, method,
headers,
**kwargs))
response = self._session._req_session.request(method,
abs_url,
headers=headers,
verify=verify,
**kwargs)
if raise_exception:
try:
response.raise_for_status()
except HTTPError as e:
logger.debug(pprint_response_info(e.response))
raise e
logger.debug(pprint_response_info(response))
if original_response:
return response
else:
stream = kwargs.get('stream', None)
json_data = extract_and_parse_json(response, ignore=stream)
return self._object_factory('bpm_custom', json_data) | dnacentersdk/api/custom_caller.py | from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
from builtins import *
from past.builtins import basestring
from ..restsession import RestSession
from ..utils import (
check_type,
apply_path_params,
extract_and_parse_json,
pprint_request_info,
pprint_response_info,
)
import logging
from requests.exceptions import HTTPError
logger = logging.getLogger(__name__)
class CustomCaller(object):
"""DNA Center CustomCaller.
DNA Center CustomCaller allows API creation.
"""
def __init__(self, session, object_factory):
"""Initialize a new CustomCaller object with the provided RestSession.
Args:
session(RestSession): The RESTful session object to be used for
API calls to the DNA Center service.
Raises:
TypeError: If the parameter types are incorrect.
"""
check_type(session, RestSession)
super(CustomCaller, self).__init__()
self._session = session
self._object_factory = object_factory
if self._session._debug:
logger.setLevel(logging.DEBUG)
logger.propagate = True
else:
logger.addHandler(logging.NullHandler())
logger.propagate = False
def add_api(self, name, obj):
"""Adds an api call to the CustomCaller.
Args:
name (str): name you want to set to the api client, has to follow
python variable naming rule.
obj (object): api call which is actually a calling call_api
method.
"""
setattr(self, name, obj)
def call_api(self, method, resource_path, raise_exception=True,
original_response=False,
**kwargs):
"""Handles the requests and response.
Args:
method(basestring): type of request.
resource_path(basestring): URL in the request object.
raise_exception(bool): If True, http exceptions will be raised.
original_response(bool): If True, MyDict (JSON response) is
returned, else response object.
path_params(dict) (optional): Find each path_params' key in the
resource_path and replace it with path_params' value.
params (optional): Dictionary or bytes to be sent in the query
string for the Request.
data (optional): Dictionary, bytes, or file-like object to send in
the body of the Request.
json (optional): json data to send in the body of the Request.
headers (optional): Dictionary of HTTP Headers to send with the
Request.
cookies (optional): Dict or CookieJar object to send with the
Request.
files (optional): Dictionary of 'name': file-like-objects
(or {'name': ('filename', fileobj)}) for multipart encoding
upload.
auth (optional): Auth tuple to enable Basic/Digest/Custom
HTTP Auth.
timeout(float, tuple) (optional): How long to wait for the server
to send data before giving up, as a float, or a (connect
timeout, read timeout) tuple.
allow_redirects(bool) (optional): bool. Set to True if
POST/PUT/DELETE redirect following is allowed.
proxies(optional): Dictionary mapping protocol to the URL of the
proxy.
verify(bool,string) (optional): if True, the SSL cert will be
verified. A CA_BUNDLE path can also be provided as a string.
stream(optional): if False, the response content will be
immediately downloaded.
cert(basestring, tuple) (optional): if String, path to ssl client
cert file (.pem). If Tuple, (‘cert’, ‘key’) pair
Returns:
MyDict or object: If original_response is True returns the
original object response, else returns a JSON response with
access to the object's properties by using the dot notation
or the bracket notation. Defaults to False.
Raises:
TypeError: If the parameter types are incorrect.
HTTPError: If the DNA Center cloud returns an error.
"""
path_params = kwargs.pop('path_params', {})
resource_path = apply_path_params(resource_path, path_params)
# Ensure the url is an absolute URL
abs_url = self._session.abs_url(resource_path)
headers = self._session.headers
if 'headers' in kwargs:
headers.update(kwargs.pop('headers'))
verify = kwargs.pop("verify", self._session.verify)
logger.debug(pprint_request_info(abs_url, method,
headers,
**kwargs))
response = self._session._req_session.request(method,
abs_url,
headers=headers,
verify=verify,
**kwargs)
if raise_exception:
try:
response.raise_for_status()
except HTTPError as e:
logger.debug(pprint_response_info(e.response))
raise e
logger.debug(pprint_response_info(response))
if original_response:
return response
else:
stream = kwargs.get('stream', None)
json_data = extract_and_parse_json(response, ignore=stream)
return self._object_factory('bpm_custom', json_data) | 0.713232 | 0.158272 |
import sys, os
import binascii, sqlite3
## Global Options
gOpts = {
"multiple" : False,
"subdirs" : False,
"force" : False
}
class Message:
def __init__( self, data ):
self.parse_data( data )
def parse_data( self, data ):
self.type = data[ 0 ]
self.address = data[ 1 ]
self.mType = data[ 2 ]
self.date = data[ 3 ]
self.rDate = data[ 4 ]
self.name = data[ 5 ]
self.body = data[ 6 ]
self.data = data[ 7 ]
self.src = data[ 8 ]
def txt( self ):
## The top bar consists of 'sent/received' and the date
txt = ( 80 * '=' ) + '\n'
if self.mType == "1":
txt += "Received on %s\n" % self.rDate
elif self.mType == "2":
txt += "Sent on %s\n" % self.rDate
else:
txt += "%s\n" % self.rDate
txt += ( 80 * '-' ) + '\n'
## The body (actual content) of the text
txt += "%s\n\n" % self.body
## If it had an image or whatever attached, let the user know
## and indicate which file it is
if self.type == "mms":
txt += "Image: %s\n" % self.src
## Cap it off with a bit of padding and add it to the list
txt += "\n\n"
return( txt )
def directory_setup( filename ):
## Create the top-level directory into which we extract the messages
try:
os.mkdir( "%s.d" % filename )
except PermissionError:
print( "ERROR: Could not create directory '%s.d'. Aborting." %
filename )
sys.exit( 1 )
except FileExistsError:
if not gOpts[ "force" ]:
print( "WARNING: Directory '%s.d' exists: Skipping" % filename )
return( None, None, True )
## Make the subdirectories names
fDir = os.path.join( "%s.d" % filename, "files" )
mDir = os.path.join( "%s.d" % filename, "messages" )
## Actually create the directories if they don't exist already
if not os.path.exists( fDir ):
os.mkdir( fDir )
if not os.path.exists( mDir ):
os.mkdir( mDir )
## Return the directories or quit if they couldn't be made
if os.path.exists( mDir ) and os.path.exists( fDir ):
return( mDir, fDir, False )
else:
print("ERROR: Could not create/find subdirectories. Aborting.")
os.rmdir( "%s.d" % filename )
sys.exit( 1 )
def extract( filename, c ):
"""
Extract all of the entries from a file opened using 'filename'. All of the
content is placed into database 'db', accessed using cursor 'c'.
"""
## Report progress
print( "Extracting content from '%s'..." % filename )
## Open the file, read it, close it
fp = open( filename, "r" )
lines = fp.readlines()
fp.close()
for l in lines:
if "<sms protocol" in l:
## Grab usable information from metadata
address = l.partition( 'address="' )[2].partition( '"' )[0]
date = int( l.partition( 'date="' )[2].partition( '"' )[0] )
rDate = l.partition( 'readable_date="' )[2].partition( '"' )[0]
body = l.partition( 'body="' )[2].partition( '" toa=' )[0]
mType = l.partition( 'type="' )[2].partition( '"' )[0]
name = l.partition( 'name="' )[2].partition( '"' )[0]
address = address.replace( '+', '' )
#if( len( address ) > 9 ):
# address = address[ ( len(address) ) - 10 : ]
## Put all of the information into a tuple
stuff = ( "sms", address, mType, date, rDate, name, body,
None, "null")
## Put it into the database
c.execute("""insert into messages values(?,?,?,?, ?, ?, ?, ?, ?)""",
stuff )
if( "image/jpeg" in l or "image/png" in l or "image/gif" in l or
"video/3gpp" in l):
## Counters
vidCount = 0
imageCount = 0
## Get the proper extension
extension = l.partition( 'ct="' )[2].partition( '"' )[0]
extension = extension.partition( '/' )[2]
if extension == "3gpp":
extension = "3gp"
elif extension == "jpeg":
extension = "jpg"
## Metadata is a couple lines up
index = lines.index( l )
meta = lines[ index - 3 ]
prevLine = lines[ index - 1 ]
nextLine = lines[ index + 1 ]
## Grab information from the metadata
address = meta.partition( 'address="' )[2].partition( '"' )[0]
date = meta.partition( 'date="' )[2].partition( '"' )[0]
rDate = meta.partition( 'readable_date="' )[2].partition( '"' )[0]
name = meta.partition( 'contact_name="' )[2].partition( '"' )[0]
## Find the mType using the m_size value; null means outgoing,
## anything else was received
if meta.partition( 'm_size="' )[2].partition( '"' )[0] == "null":
mType = '1'
else:
mType = '2'
## Fix address string
address = address.replace( '+', '' )
#if( len( address ) > 9 ):
# address = address[ ( len(address) ) - 10 : ]
## Name the file source properly... more or less
if extension == "3gp":
src = prevLine.partition( 'video src="' )[2].partition( '"' )[0]
if src == "":
vidCount += 1
src = "vid_%03d.3gp" % vidCount
else:
src = prevLine.partition( 'img src="' )[2].partition( '"' )[0]
if src == "":
imageCount += 1
src = "img_%03d.%s" % ( imageCount, extension )
## If they sent a message with the MMS
if 'text="' in nextLine:
body = nextLine.partition( 'text="' )[2].partition( '"' )[0]
else:
body = ""
## Turn the MMS base64 text into usable binary data
dataText = l.partition( 'data="' )[2].partition( '"' )[0]
data = binascii.a2b_base64( dataText )
## Put it all into a tuple
stuff = ( "mms", address, mType, date, rDate, name, body,
data, src )
## STUFF THAT FUCKER INTO THE DATABASE
c.execute("""insert into messages values(?, ?,?,?,?, ?, ?, ?, ?)""",
stuff )
def print_help():
print( "Usage: smsExtractor.py FILE.xml" )
print( """
This script extracts SMS messages and MMS files (jpg, png or 3gp) from a given
XML file, as they're read, into a subdirectory named after the file in question.
Data extracted from "mms.xml" will go into "mms.xml.d", as an example.
NOTE:
This script assumes files generated by the Android app "SMS Backup & Restore" by
<NAME>. It isn't guaranteed nor even expected to work with anything else.
You can find his program at either of the following sites:
(Developer's site)
http://android.riteshsahu.com/apps/sms-backup-restore
(Google Play store)
https://play.google.com/store/apps/details?id=com.riteshsahu.SMSBackupRestore
Options:
-h or --help: This help text
-V or --version: Version and author info
-s or --subdirs: Write files to individual subdirectories per each contact
-f or --force: Overwrite extant files, or into extant directories
-m or --multiple: Write messages to multiple (individual) files
""" )
def print_version():
print( "smsExtractor.py, version 1.3" )
print( "<NAME> <<EMAIL>>" )
def write_message_to_separate_file( mDir, address, name, message ):
## Files are named using an 'ADDRESS_NAME_DATE.txt' convention
fp = open( os.path.join( mDir, "%s_%s_%s.txt" %
( address, name, message.rDate ) ), "w" )
fp.write( message.body )
fp.close()
def write_messages_to_single_file( mDir, address, name, messages ):
## Files are named using an 'ADDRESS_NAME.txt' convention
fp = open( os.path.join( mDir, "%s_%s.txt" % ( address, name ) ), "w" )
count = 0
for m in messages:
fp.write( m.txt() )
count += 1
fp.close()
return( count )
def write_messages( filename, mDir, fDir, c ):
## Grab all of the stuff from the database
c.execute( """select * from messages order by date""" )
data = c.fetchall()
## Get the addresses, get the names, see if we've got any MMS files
addresses = []
names = {}
filesPresent = False
for d in data:
if filesPresent is False and d[7] is not None:
filesPresent = True
if d[1] not in addresses:
addresses.append( d[1] )
names[ d[1] ] = d[5]
## If there are no files, remove the files subdirectory
if not filesPresent:
os.rmdir( fDir )
print( "Found %i pieces of data total with %i unique addresses" % ( len( data ), len( addresses ) ) )
## Start up a couple of counters
smsCount = 0
mmsCount = 0
print( "Writing Message Text." )
## Write all of the text messages to disk
messages = []
for d in data:
for a in addresses:
if d[1] == a:
msg = Message( d )
messages.append( msg )
## Go through the messages list and write them to the file
if len( messages ) > 0:
if gOpts[ "multiple" ]:
for m in messages:
write_message_to_separate_file( mDir, a, names[ a ], m )
smsCount += 1
else:
n = write_messages_to_single_file( mDir, a, names[a], messages )
smsCount += n
print( "Writing Message Data." )
## Write all of the MMS files to disk
for d in data:
a = d[1]
## If it's actually an MMS file
if filesPresent and d[0] == "mms" and d[7] != None:
## Increment counter
mmsCount += 1
if gOpts[ "subdirs" ]:
fSubDir = os.path.join( fDir, "%s_%s" % ( a, names[a] ) )
if not os.path.exists( fSubDir ):
os.mkdir( fSubDir )
else:
fSubDir = fDir
## Open the file for binary writing, write the data, close the file
fp = open( os.path.join( fSubDir, d[8] ), "wb")
fp.write( d[7] )
fp.close()
## Correct the numbers a bit
smsCount -= mmsCount
## Report success
print( "%s: %d SMS and %d MMS (total: %d)" %
( filename, smsCount, mmsCount, smsCount + mmsCount ))
def create_database():
## Connect to a database that exists in RAM
db = sqlite3.connect( ":memory:" )
c = db.cursor()
## Future reference:
# 0 type sms or mms
# 1 address phone number
# 2 mType Arbitrary sender/receiver value, 1 means the
# other person, 2 means 'me'
# 3 date Date (ctime or similar, unreadable to humans)
# 4 readableDate Date that people can read
# 5 name Contact name
# 6 body Message text
# 7 data MMS data (image, video, etc.)
# 8 src Data source, used as the name of the file
c.execute( """create table messages( type text, address text, mType text, date text, readableDate text, name text, body text, data blob, src text)""" )
return( db, c )
def main():
if len( sys.argv ) == 1:
print( "ERROR: Require an SMS/MMS file to extract from" )
sys.exit( 1 )
idx = 1
for arg in sys.argv[idx:]:
## If they want help
if arg in ( "-h", "--help" ):
print_help()
sys.exit( 0 )
## If they want version/author info
if arg in ( "-V", "--version" ):
print_version()
sys.exit( 0 )
if arg in ( "-s", "--subdirs" ):
gOpts[ "subdirs" ] = True
idx += 1
if arg in ( "-f", "--force" ):
gOpts[ "force" ] = True
idx += 1
if arg in ( "-m", "--multiple" ):
gOpts[ "multiple" ] = True
idx += 1
## Normal operation
for arg in sys.argv[ idx : ]:
## Create the directories so that everything will be tidy
mDir, fDir, skip = directory_setup( arg )
## If we were successful
if not skip:
## Create the database to store all the info
db, cursor = create_database()
## Extract eveything into database
extract( arg, cursor )
## Write all of the messages to disk
write_messages( arg, mDir, fDir, cursor )
## Close the database and cap off the output with a newline
db.close()
print("")
if __name__ == "__main__":
main() | src/smsExtractor.py |
import sys, os
import binascii, sqlite3
## Global Options
gOpts = {
"multiple" : False,
"subdirs" : False,
"force" : False
}
class Message:
def __init__( self, data ):
self.parse_data( data )
def parse_data( self, data ):
self.type = data[ 0 ]
self.address = data[ 1 ]
self.mType = data[ 2 ]
self.date = data[ 3 ]
self.rDate = data[ 4 ]
self.name = data[ 5 ]
self.body = data[ 6 ]
self.data = data[ 7 ]
self.src = data[ 8 ]
def txt( self ):
## The top bar consists of 'sent/received' and the date
txt = ( 80 * '=' ) + '\n'
if self.mType == "1":
txt += "Received on %s\n" % self.rDate
elif self.mType == "2":
txt += "Sent on %s\n" % self.rDate
else:
txt += "%s\n" % self.rDate
txt += ( 80 * '-' ) + '\n'
## The body (actual content) of the text
txt += "%s\n\n" % self.body
## If it had an image or whatever attached, let the user know
## and indicate which file it is
if self.type == "mms":
txt += "Image: %s\n" % self.src
## Cap it off with a bit of padding and add it to the list
txt += "\n\n"
return( txt )
def directory_setup( filename ):
## Create the top-level directory into which we extract the messages
try:
os.mkdir( "%s.d" % filename )
except PermissionError:
print( "ERROR: Could not create directory '%s.d'. Aborting." %
filename )
sys.exit( 1 )
except FileExistsError:
if not gOpts[ "force" ]:
print( "WARNING: Directory '%s.d' exists: Skipping" % filename )
return( None, None, True )
## Make the subdirectories names
fDir = os.path.join( "%s.d" % filename, "files" )
mDir = os.path.join( "%s.d" % filename, "messages" )
## Actually create the directories if they don't exist already
if not os.path.exists( fDir ):
os.mkdir( fDir )
if not os.path.exists( mDir ):
os.mkdir( mDir )
## Return the directories or quit if they couldn't be made
if os.path.exists( mDir ) and os.path.exists( fDir ):
return( mDir, fDir, False )
else:
print("ERROR: Could not create/find subdirectories. Aborting.")
os.rmdir( "%s.d" % filename )
sys.exit( 1 )
def extract( filename, c ):
"""
Extract all of the entries from a file opened using 'filename'. All of the
content is placed into database 'db', accessed using cursor 'c'.
"""
## Report progress
print( "Extracting content from '%s'..." % filename )
## Open the file, read it, close it
fp = open( filename, "r" )
lines = fp.readlines()
fp.close()
for l in lines:
if "<sms protocol" in l:
## Grab usable information from metadata
address = l.partition( 'address="' )[2].partition( '"' )[0]
date = int( l.partition( 'date="' )[2].partition( '"' )[0] )
rDate = l.partition( 'readable_date="' )[2].partition( '"' )[0]
body = l.partition( 'body="' )[2].partition( '" toa=' )[0]
mType = l.partition( 'type="' )[2].partition( '"' )[0]
name = l.partition( 'name="' )[2].partition( '"' )[0]
address = address.replace( '+', '' )
#if( len( address ) > 9 ):
# address = address[ ( len(address) ) - 10 : ]
## Put all of the information into a tuple
stuff = ( "sms", address, mType, date, rDate, name, body,
None, "null")
## Put it into the database
c.execute("""insert into messages values(?,?,?,?, ?, ?, ?, ?, ?)""",
stuff )
if( "image/jpeg" in l or "image/png" in l or "image/gif" in l or
"video/3gpp" in l):
## Counters
vidCount = 0
imageCount = 0
## Get the proper extension
extension = l.partition( 'ct="' )[2].partition( '"' )[0]
extension = extension.partition( '/' )[2]
if extension == "3gpp":
extension = "3gp"
elif extension == "jpeg":
extension = "jpg"
## Metadata is a couple lines up
index = lines.index( l )
meta = lines[ index - 3 ]
prevLine = lines[ index - 1 ]
nextLine = lines[ index + 1 ]
## Grab information from the metadata
address = meta.partition( 'address="' )[2].partition( '"' )[0]
date = meta.partition( 'date="' )[2].partition( '"' )[0]
rDate = meta.partition( 'readable_date="' )[2].partition( '"' )[0]
name = meta.partition( 'contact_name="' )[2].partition( '"' )[0]
## Find the mType using the m_size value; null means outgoing,
## anything else was received
if meta.partition( 'm_size="' )[2].partition( '"' )[0] == "null":
mType = '1'
else:
mType = '2'
## Fix address string
address = address.replace( '+', '' )
#if( len( address ) > 9 ):
# address = address[ ( len(address) ) - 10 : ]
## Name the file source properly... more or less
if extension == "3gp":
src = prevLine.partition( 'video src="' )[2].partition( '"' )[0]
if src == "":
vidCount += 1
src = "vid_%03d.3gp" % vidCount
else:
src = prevLine.partition( 'img src="' )[2].partition( '"' )[0]
if src == "":
imageCount += 1
src = "img_%03d.%s" % ( imageCount, extension )
## If they sent a message with the MMS
if 'text="' in nextLine:
body = nextLine.partition( 'text="' )[2].partition( '"' )[0]
else:
body = ""
## Turn the MMS base64 text into usable binary data
dataText = l.partition( 'data="' )[2].partition( '"' )[0]
data = binascii.a2b_base64( dataText )
## Put it all into a tuple
stuff = ( "mms", address, mType, date, rDate, name, body,
data, src )
## STUFF THAT FUCKER INTO THE DATABASE
c.execute("""insert into messages values(?, ?,?,?,?, ?, ?, ?, ?)""",
stuff )
def print_help():
print( "Usage: smsExtractor.py FILE.xml" )
print( """
This script extracts SMS messages and MMS files (jpg, png or 3gp) from a given
XML file, as they're read, into a subdirectory named after the file in question.
Data extracted from "mms.xml" will go into "mms.xml.d", as an example.
NOTE:
This script assumes files generated by the Android app "SMS Backup & Restore" by
<NAME>. It isn't guaranteed nor even expected to work with anything else.
You can find his program at either of the following sites:
(Developer's site)
http://android.riteshsahu.com/apps/sms-backup-restore
(Google Play store)
https://play.google.com/store/apps/details?id=com.riteshsahu.SMSBackupRestore
Options:
-h or --help: This help text
-V or --version: Version and author info
-s or --subdirs: Write files to individual subdirectories per each contact
-f or --force: Overwrite extant files, or into extant directories
-m or --multiple: Write messages to multiple (individual) files
""" )
def print_version():
print( "smsExtractor.py, version 1.3" )
print( "<NAME> <<EMAIL>>" )
def write_message_to_separate_file( mDir, address, name, message ):
## Files are named using an 'ADDRESS_NAME_DATE.txt' convention
fp = open( os.path.join( mDir, "%s_%s_%s.txt" %
( address, name, message.rDate ) ), "w" )
fp.write( message.body )
fp.close()
def write_messages_to_single_file( mDir, address, name, messages ):
## Files are named using an 'ADDRESS_NAME.txt' convention
fp = open( os.path.join( mDir, "%s_%s.txt" % ( address, name ) ), "w" )
count = 0
for m in messages:
fp.write( m.txt() )
count += 1
fp.close()
return( count )
def write_messages( filename, mDir, fDir, c ):
## Grab all of the stuff from the database
c.execute( """select * from messages order by date""" )
data = c.fetchall()
## Get the addresses, get the names, see if we've got any MMS files
addresses = []
names = {}
filesPresent = False
for d in data:
if filesPresent is False and d[7] is not None:
filesPresent = True
if d[1] not in addresses:
addresses.append( d[1] )
names[ d[1] ] = d[5]
## If there are no files, remove the files subdirectory
if not filesPresent:
os.rmdir( fDir )
print( "Found %i pieces of data total with %i unique addresses" % ( len( data ), len( addresses ) ) )
## Start up a couple of counters
smsCount = 0
mmsCount = 0
print( "Writing Message Text." )
## Write all of the text messages to disk
messages = []
for d in data:
for a in addresses:
if d[1] == a:
msg = Message( d )
messages.append( msg )
## Go through the messages list and write them to the file
if len( messages ) > 0:
if gOpts[ "multiple" ]:
for m in messages:
write_message_to_separate_file( mDir, a, names[ a ], m )
smsCount += 1
else:
n = write_messages_to_single_file( mDir, a, names[a], messages )
smsCount += n
print( "Writing Message Data." )
## Write all of the MMS files to disk
for d in data:
a = d[1]
## If it's actually an MMS file
if filesPresent and d[0] == "mms" and d[7] != None:
## Increment counter
mmsCount += 1
if gOpts[ "subdirs" ]:
fSubDir = os.path.join( fDir, "%s_%s" % ( a, names[a] ) )
if not os.path.exists( fSubDir ):
os.mkdir( fSubDir )
else:
fSubDir = fDir
## Open the file for binary writing, write the data, close the file
fp = open( os.path.join( fSubDir, d[8] ), "wb")
fp.write( d[7] )
fp.close()
## Correct the numbers a bit
smsCount -= mmsCount
## Report success
print( "%s: %d SMS and %d MMS (total: %d)" %
( filename, smsCount, mmsCount, smsCount + mmsCount ))
def create_database():
## Connect to a database that exists in RAM
db = sqlite3.connect( ":memory:" )
c = db.cursor()
## Future reference:
# 0 type sms or mms
# 1 address phone number
# 2 mType Arbitrary sender/receiver value, 1 means the
# other person, 2 means 'me'
# 3 date Date (ctime or similar, unreadable to humans)
# 4 readableDate Date that people can read
# 5 name Contact name
# 6 body Message text
# 7 data MMS data (image, video, etc.)
# 8 src Data source, used as the name of the file
c.execute( """create table messages( type text, address text, mType text, date text, readableDate text, name text, body text, data blob, src text)""" )
return( db, c )
def main():
if len( sys.argv ) == 1:
print( "ERROR: Require an SMS/MMS file to extract from" )
sys.exit( 1 )
idx = 1
for arg in sys.argv[idx:]:
## If they want help
if arg in ( "-h", "--help" ):
print_help()
sys.exit( 0 )
## If they want version/author info
if arg in ( "-V", "--version" ):
print_version()
sys.exit( 0 )
if arg in ( "-s", "--subdirs" ):
gOpts[ "subdirs" ] = True
idx += 1
if arg in ( "-f", "--force" ):
gOpts[ "force" ] = True
idx += 1
if arg in ( "-m", "--multiple" ):
gOpts[ "multiple" ] = True
idx += 1
## Normal operation
for arg in sys.argv[ idx : ]:
## Create the directories so that everything will be tidy
mDir, fDir, skip = directory_setup( arg )
## If we were successful
if not skip:
## Create the database to store all the info
db, cursor = create_database()
## Extract eveything into database
extract( arg, cursor )
## Write all of the messages to disk
write_messages( arg, mDir, fDir, cursor )
## Close the database and cap off the output with a newline
db.close()
print("")
if __name__ == "__main__":
main() | 0.17075 | 0.294995 |
import logging
import uuid
from typing import Callable, Any, Union
import asyncio
from Foundation import NSData, CBUUID
from CoreBluetooth import (
CBCharacteristicWriteWithResponse,
CBCharacteristicWriteWithoutResponse,
)
from bleak.backends.client import BaseBleakClient
from bleak.backends.corebluetooth.characteristic import (
BleakGATTCharacteristicCoreBluetooth,
)
from bleak.backends.corebluetooth.descriptor import BleakGATTDescriptorCoreBluetooth
from bleak.backends.corebluetooth.scanner import BleakScannerCoreBluetooth
from bleak.backends.corebluetooth.service import BleakGATTServiceCoreBluetooth
from bleak.backends.corebluetooth.utils import cb_uuid_to_str
from bleak.backends.device import BLEDevice
from bleak.backends.service import BleakGATTServiceCollection
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.exc import BleakError
logger = logging.getLogger(__name__)
class BleakClientCoreBluetooth(BaseBleakClient):
"""CoreBluetooth class interface for BleakClient
Args:
address_or_ble_device (`BLEDevice` or str): The Bluetooth address of the BLE peripheral to connect to or the `BLEDevice` object representing it.
Keyword Args:
timeout (float): Timeout for required ``BleakScanner.find_device_by_address`` call. Defaults to 10.0.
"""
def __init__(self, address_or_ble_device: Union[BLEDevice, str], **kwargs):
super(BleakClientCoreBluetooth, self).__init__(address_or_ble_device, **kwargs)
if isinstance(address_or_ble_device, BLEDevice):
self._device_info = address_or_ble_device.details
self._central_manager_delegate = address_or_ble_device.metadata.get(
"delegate"
)
else:
self._device_info = None
self._central_manager_delegate = None
self._requester = None
self._callbacks = {}
self._services = None
def __str__(self):
return "BleakClientCoreBluetooth ({})".format(self.address)
async def connect(self, **kwargs) -> bool:
"""Connect to a specified Peripheral
Keyword Args:
timeout (float): Timeout for required ``BleakScanner.find_device_by_address`` call. Defaults to 10.0.
Returns:
Boolean representing connection status.
"""
if self._device_info is None:
timeout = kwargs.get("timeout", self._timeout)
device = await BleakScannerCoreBluetooth.find_device_by_address(
self.address, timeout=timeout
)
if device:
self._device_info = device.details
self._central_manager_delegate = device.metadata.get("delegate")
else:
raise BleakError(
"Device with address {} was not found".format(self.address)
)
# self._device_info.manager() should return a CBCentralManager
manager = self._central_manager_delegate
logger.debug("CentralManagerDelegate at {}".format(manager))
logger.debug("Connecting to BLE device @ {}".format(self.address))
await manager.connect_(self._device_info)
manager.disconnected_callback = self._disconnected_callback_client
# Now get services
await self.get_services()
return True
def _disconnected_callback_client(self):
"""
Callback for device disconnection. Bleak callback sends one argument as client. This is wrapper function
that gets called from the CentralManager and call actual disconnected_callback by sending client as argument
"""
logger.debug("Received disconnection callback...")
if self._disconnected_callback is not None:
self._disconnected_callback(self)
async def disconnect(self) -> bool:
"""Disconnect from the peripheral device"""
manager = self._central_manager_delegate
if manager is None:
return False
await manager.disconnect()
self.services = BleakGATTServiceCollection()
# Ensure that `get_services` retrieves services again, rather than using the cached object
self._services_resolved = False
self._services = None
return True
async def is_connected(self) -> bool:
"""Checks for current active connection"""
manager = self._central_manager_delegate
return manager.isConnected
async def pair(self, *args, **kwargs) -> bool:
"""Attempt to pair with a peripheral.
.. note::
This is not available on macOS since there is not explicit method to do a pairing, Instead the docs
state that it "auto-pairs" when trying to read a characteristic that requires encryption, something
Bleak cannot do apparently.
Reference:
- `Apple Docs <https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/BestPracticesForSettingUpYourIOSDeviceAsAPeripheral/BestPracticesForSettingUpYourIOSDeviceAsAPeripheral.html#//apple_ref/doc/uid/TP40013257-CH5-SW1>`_
- `Stack Overflow post #1 <https://stackoverflow.com/questions/25254932/can-you-pair-a-bluetooth-le-device-in-an-ios-app>`_
- `Stack Overflow post #2 <https://stackoverflow.com/questions/47546690/ios-bluetooth-pairing-request-dialog-can-i-know-the-users-choice>`_
Returns:
Boolean regarding success of pairing.
"""
raise NotImplementedError("Pairing is not available in Core Bluetooth.")
async def unpair(self) -> bool:
"""
Returns:
"""
raise NotImplementedError("Pairing is not available in Core Bluetooth.")
async def get_services(self) -> BleakGATTServiceCollection:
"""Get all services registered for this GATT server.
Returns:
A :py:class:`bleak.backends.service.BleakGATTServiceCollection` with this device's services tree.
"""
if self._services is not None:
return self.services
logger.debug("Retrieving services...")
manager = self._central_manager_delegate
services = await manager.connected_peripheral_delegate.discoverServices()
for service in services:
serviceUUID = service.UUID().UUIDString()
logger.debug(
"Retrieving characteristics for service {}".format(serviceUUID)
)
characteristics = (
await manager.connected_peripheral_delegate.discoverCharacteristics_(
service
)
)
self.services.add_service(BleakGATTServiceCoreBluetooth(service))
for characteristic in characteristics:
cUUID = characteristic.UUID().UUIDString()
logger.debug(
"Retrieving descriptors for characteristic {}".format(cUUID)
)
descriptors = (
await manager.connected_peripheral_delegate.discoverDescriptors_(
characteristic
)
)
self.services.add_characteristic(
BleakGATTCharacteristicCoreBluetooth(characteristic)
)
for descriptor in descriptors:
self.services.add_descriptor(
BleakGATTDescriptorCoreBluetooth(
descriptor,
cb_uuid_to_str(characteristic.UUID()),
int(characteristic.handle()),
)
)
logger.debug("Services resolved for %s", str(self))
self._services_resolved = True
self._services = services
return self.services
async def read_gatt_char(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
use_cached=False,
**kwargs
) -> bytearray:
"""Perform read operation on the specified GATT characteristic.
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to read from,
specified by either integer handle, UUID or directly by the
BleakGATTCharacteristic object representing it.
use_cached (bool): `False` forces macOS to read the value from the
device again and not use its own cached value. Defaults to `False`.
Returns:
(bytearray) The read data.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {} was not found!".format(char_specifier))
output = await manager.connected_peripheral_delegate.readCharacteristic_(
characteristic.obj, use_cached=use_cached
)
value = bytearray(output)
logger.debug("Read Characteristic {0} : {1}".format(characteristic.uuid, value))
return value
async def read_gatt_descriptor(
self, handle: int, use_cached=False, **kwargs
) -> bytearray:
"""Perform read operation on the specified GATT descriptor.
Args:
handle (int): The handle of the descriptor to read from.
use_cached (bool): `False` forces Windows to read the value from the
device again and not use its own cached value. Defaults to `False`.
Returns:
(bytearray) The read data.
"""
manager = self._central_manager_delegate
descriptor = self.services.get_descriptor(handle)
if not descriptor:
raise BleakError("Descriptor {} was not found!".format(handle))
output = await manager.connected_peripheral_delegate.readDescriptor_(
descriptor.obj, use_cached=use_cached
)
if isinstance(
output, str
): # Sometimes a `pyobjc_unicode`or `__NSCFString` is returned and they can be used as regular Python strings.
value = bytearray(output.encode("utf-8"))
else: # _NSInlineData
value = bytearray(output) # value.getBytes_length_(None, len(value))
logger.debug("Read Descriptor {0} : {1}".format(handle, value))
return value
async def write_gatt_char(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
data: bytearray,
response: bool = False,
) -> None:
"""Perform a write operation of the specified GATT characteristic.
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to write
to, specified by either integer handle, UUID or directly by the
BleakGATTCharacteristic object representing it.
data (bytes or bytearray): The data to send.
response (bool): If write-with-response operation should be done. Defaults to `False`.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {} was not found!".format(char_specifier))
value = NSData.alloc().initWithBytes_length_(data, len(data))
success = (
await manager.connected_peripheral_delegate.writeCharacteristic_value_type_(
characteristic.obj,
value,
CBCharacteristicWriteWithResponse
if response
else CBCharacteristicWriteWithoutResponse,
)
)
if success:
logger.debug(
"Write Characteristic {0} : {1}".format(characteristic.uuid, data)
)
else:
raise BleakError(
"Could not write value {0} to characteristic {1}: {2}".format(
data, characteristic.uuid, success
)
)
async def write_gatt_descriptor(self, handle: int, data: bytearray) -> None:
"""Perform a write operation on the specified GATT descriptor.
Args:
handle (int): The handle of the descriptor to read from.
data (bytes or bytearray): The data to send.
"""
manager = self._central_manager_delegate
descriptor = self.services.get_descriptor(handle)
if not descriptor:
raise BleakError("Descriptor {} was not found!".format(handle))
value = NSData.alloc().initWithBytes_length_(data, len(data))
success = await manager.connected_peripheral_delegate.writeDescriptor_value_(
descriptor.obj, value
)
if success:
logger.debug("Write Descriptor {0} : {1}".format(handle, data))
else:
raise BleakError(
"Could not write value {0} to descriptor {1}: {2}".format(
data, descriptor.uuid, success
)
)
async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
callback: Callable[[int, bytearray], None],
**kwargs
) -> None:
"""Activate notifications/indications on a characteristic.
Callbacks must accept two inputs. The first will be a integer handle of the characteristic generating the
data and the second will be a ``bytearray`` containing the data sent from the connected server.
.. code-block:: python
def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")
client.start_notify(char_uuid, callback)
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to activate
notifications/indications on a characteristic, specified by either integer handle,
UUID or directly by the BleakGATTCharacteristic object representing it.
callback (function): The function to be called on notification.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {0} not found!".format(char_specifier))
success = await manager.connected_peripheral_delegate.startNotify_cb_(
characteristic.obj, callback
)
if not success:
raise BleakError(
"Could not start notify on {0}: {1}".format(
characteristic.uuid, success
)
)
async def stop_notify(
self, char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID]
) -> None:
"""Deactivate notification/indication on a specified characteristic.
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to deactivate
notification/indication on, specified by either integer handle, UUID or
directly by the BleakGATTCharacteristic object representing it.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {} not found!".format(char_specifier))
success = await manager.connected_peripheral_delegate.stopNotify_(
characteristic.obj
)
if not success:
raise BleakError(
"Could not stop notify on {0}: {1}".format(characteristic.uuid, success)
)
async def get_rssi(self) -> int:
"""To get RSSI value in dBm of the connected Peripheral"""
self._device_info.readRSSI()
manager = self._central_manager_delegate
RSSI = manager.connected_peripheral.RSSI()
for i in range(20): # First time takes a little otherwise returns None
RSSI = manager.connected_peripheral.RSSI()
if not RSSI:
await asyncio.sleep(0.1)
else:
return int(RSSI)
if not RSSI:
return None | bleak/backends/corebluetooth/client.py | import logging
import uuid
from typing import Callable, Any, Union
import asyncio
from Foundation import NSData, CBUUID
from CoreBluetooth import (
CBCharacteristicWriteWithResponse,
CBCharacteristicWriteWithoutResponse,
)
from bleak.backends.client import BaseBleakClient
from bleak.backends.corebluetooth.characteristic import (
BleakGATTCharacteristicCoreBluetooth,
)
from bleak.backends.corebluetooth.descriptor import BleakGATTDescriptorCoreBluetooth
from bleak.backends.corebluetooth.scanner import BleakScannerCoreBluetooth
from bleak.backends.corebluetooth.service import BleakGATTServiceCoreBluetooth
from bleak.backends.corebluetooth.utils import cb_uuid_to_str
from bleak.backends.device import BLEDevice
from bleak.backends.service import BleakGATTServiceCollection
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.exc import BleakError
logger = logging.getLogger(__name__)
class BleakClientCoreBluetooth(BaseBleakClient):
"""CoreBluetooth class interface for BleakClient
Args:
address_or_ble_device (`BLEDevice` or str): The Bluetooth address of the BLE peripheral to connect to or the `BLEDevice` object representing it.
Keyword Args:
timeout (float): Timeout for required ``BleakScanner.find_device_by_address`` call. Defaults to 10.0.
"""
def __init__(self, address_or_ble_device: Union[BLEDevice, str], **kwargs):
super(BleakClientCoreBluetooth, self).__init__(address_or_ble_device, **kwargs)
if isinstance(address_or_ble_device, BLEDevice):
self._device_info = address_or_ble_device.details
self._central_manager_delegate = address_or_ble_device.metadata.get(
"delegate"
)
else:
self._device_info = None
self._central_manager_delegate = None
self._requester = None
self._callbacks = {}
self._services = None
def __str__(self):
return "BleakClientCoreBluetooth ({})".format(self.address)
async def connect(self, **kwargs) -> bool:
"""Connect to a specified Peripheral
Keyword Args:
timeout (float): Timeout for required ``BleakScanner.find_device_by_address`` call. Defaults to 10.0.
Returns:
Boolean representing connection status.
"""
if self._device_info is None:
timeout = kwargs.get("timeout", self._timeout)
device = await BleakScannerCoreBluetooth.find_device_by_address(
self.address, timeout=timeout
)
if device:
self._device_info = device.details
self._central_manager_delegate = device.metadata.get("delegate")
else:
raise BleakError(
"Device with address {} was not found".format(self.address)
)
# self._device_info.manager() should return a CBCentralManager
manager = self._central_manager_delegate
logger.debug("CentralManagerDelegate at {}".format(manager))
logger.debug("Connecting to BLE device @ {}".format(self.address))
await manager.connect_(self._device_info)
manager.disconnected_callback = self._disconnected_callback_client
# Now get services
await self.get_services()
return True
def _disconnected_callback_client(self):
"""
Callback for device disconnection. Bleak callback sends one argument as client. This is wrapper function
that gets called from the CentralManager and call actual disconnected_callback by sending client as argument
"""
logger.debug("Received disconnection callback...")
if self._disconnected_callback is not None:
self._disconnected_callback(self)
async def disconnect(self) -> bool:
"""Disconnect from the peripheral device"""
manager = self._central_manager_delegate
if manager is None:
return False
await manager.disconnect()
self.services = BleakGATTServiceCollection()
# Ensure that `get_services` retrieves services again, rather than using the cached object
self._services_resolved = False
self._services = None
return True
async def is_connected(self) -> bool:
"""Checks for current active connection"""
manager = self._central_manager_delegate
return manager.isConnected
async def pair(self, *args, **kwargs) -> bool:
"""Attempt to pair with a peripheral.
.. note::
This is not available on macOS since there is not explicit method to do a pairing, Instead the docs
state that it "auto-pairs" when trying to read a characteristic that requires encryption, something
Bleak cannot do apparently.
Reference:
- `Apple Docs <https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/BestPracticesForSettingUpYourIOSDeviceAsAPeripheral/BestPracticesForSettingUpYourIOSDeviceAsAPeripheral.html#//apple_ref/doc/uid/TP40013257-CH5-SW1>`_
- `Stack Overflow post #1 <https://stackoverflow.com/questions/25254932/can-you-pair-a-bluetooth-le-device-in-an-ios-app>`_
- `Stack Overflow post #2 <https://stackoverflow.com/questions/47546690/ios-bluetooth-pairing-request-dialog-can-i-know-the-users-choice>`_
Returns:
Boolean regarding success of pairing.
"""
raise NotImplementedError("Pairing is not available in Core Bluetooth.")
async def unpair(self) -> bool:
"""
Returns:
"""
raise NotImplementedError("Pairing is not available in Core Bluetooth.")
async def get_services(self) -> BleakGATTServiceCollection:
"""Get all services registered for this GATT server.
Returns:
A :py:class:`bleak.backends.service.BleakGATTServiceCollection` with this device's services tree.
"""
if self._services is not None:
return self.services
logger.debug("Retrieving services...")
manager = self._central_manager_delegate
services = await manager.connected_peripheral_delegate.discoverServices()
for service in services:
serviceUUID = service.UUID().UUIDString()
logger.debug(
"Retrieving characteristics for service {}".format(serviceUUID)
)
characteristics = (
await manager.connected_peripheral_delegate.discoverCharacteristics_(
service
)
)
self.services.add_service(BleakGATTServiceCoreBluetooth(service))
for characteristic in characteristics:
cUUID = characteristic.UUID().UUIDString()
logger.debug(
"Retrieving descriptors for characteristic {}".format(cUUID)
)
descriptors = (
await manager.connected_peripheral_delegate.discoverDescriptors_(
characteristic
)
)
self.services.add_characteristic(
BleakGATTCharacteristicCoreBluetooth(characteristic)
)
for descriptor in descriptors:
self.services.add_descriptor(
BleakGATTDescriptorCoreBluetooth(
descriptor,
cb_uuid_to_str(characteristic.UUID()),
int(characteristic.handle()),
)
)
logger.debug("Services resolved for %s", str(self))
self._services_resolved = True
self._services = services
return self.services
async def read_gatt_char(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
use_cached=False,
**kwargs
) -> bytearray:
"""Perform read operation on the specified GATT characteristic.
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to read from,
specified by either integer handle, UUID or directly by the
BleakGATTCharacteristic object representing it.
use_cached (bool): `False` forces macOS to read the value from the
device again and not use its own cached value. Defaults to `False`.
Returns:
(bytearray) The read data.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {} was not found!".format(char_specifier))
output = await manager.connected_peripheral_delegate.readCharacteristic_(
characteristic.obj, use_cached=use_cached
)
value = bytearray(output)
logger.debug("Read Characteristic {0} : {1}".format(characteristic.uuid, value))
return value
async def read_gatt_descriptor(
self, handle: int, use_cached=False, **kwargs
) -> bytearray:
"""Perform read operation on the specified GATT descriptor.
Args:
handle (int): The handle of the descriptor to read from.
use_cached (bool): `False` forces Windows to read the value from the
device again and not use its own cached value. Defaults to `False`.
Returns:
(bytearray) The read data.
"""
manager = self._central_manager_delegate
descriptor = self.services.get_descriptor(handle)
if not descriptor:
raise BleakError("Descriptor {} was not found!".format(handle))
output = await manager.connected_peripheral_delegate.readDescriptor_(
descriptor.obj, use_cached=use_cached
)
if isinstance(
output, str
): # Sometimes a `pyobjc_unicode`or `__NSCFString` is returned and they can be used as regular Python strings.
value = bytearray(output.encode("utf-8"))
else: # _NSInlineData
value = bytearray(output) # value.getBytes_length_(None, len(value))
logger.debug("Read Descriptor {0} : {1}".format(handle, value))
return value
async def write_gatt_char(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
data: bytearray,
response: bool = False,
) -> None:
"""Perform a write operation of the specified GATT characteristic.
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to write
to, specified by either integer handle, UUID or directly by the
BleakGATTCharacteristic object representing it.
data (bytes or bytearray): The data to send.
response (bool): If write-with-response operation should be done. Defaults to `False`.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {} was not found!".format(char_specifier))
value = NSData.alloc().initWithBytes_length_(data, len(data))
success = (
await manager.connected_peripheral_delegate.writeCharacteristic_value_type_(
characteristic.obj,
value,
CBCharacteristicWriteWithResponse
if response
else CBCharacteristicWriteWithoutResponse,
)
)
if success:
logger.debug(
"Write Characteristic {0} : {1}".format(characteristic.uuid, data)
)
else:
raise BleakError(
"Could not write value {0} to characteristic {1}: {2}".format(
data, characteristic.uuid, success
)
)
async def write_gatt_descriptor(self, handle: int, data: bytearray) -> None:
"""Perform a write operation on the specified GATT descriptor.
Args:
handle (int): The handle of the descriptor to read from.
data (bytes or bytearray): The data to send.
"""
manager = self._central_manager_delegate
descriptor = self.services.get_descriptor(handle)
if not descriptor:
raise BleakError("Descriptor {} was not found!".format(handle))
value = NSData.alloc().initWithBytes_length_(data, len(data))
success = await manager.connected_peripheral_delegate.writeDescriptor_value_(
descriptor.obj, value
)
if success:
logger.debug("Write Descriptor {0} : {1}".format(handle, data))
else:
raise BleakError(
"Could not write value {0} to descriptor {1}: {2}".format(
data, descriptor.uuid, success
)
)
async def start_notify(
self,
char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID],
callback: Callable[[int, bytearray], None],
**kwargs
) -> None:
"""Activate notifications/indications on a characteristic.
Callbacks must accept two inputs. The first will be a integer handle of the characteristic generating the
data and the second will be a ``bytearray`` containing the data sent from the connected server.
.. code-block:: python
def callback(sender: int, data: bytearray):
print(f"{sender}: {data}")
client.start_notify(char_uuid, callback)
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to activate
notifications/indications on a characteristic, specified by either integer handle,
UUID or directly by the BleakGATTCharacteristic object representing it.
callback (function): The function to be called on notification.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {0} not found!".format(char_specifier))
success = await manager.connected_peripheral_delegate.startNotify_cb_(
characteristic.obj, callback
)
if not success:
raise BleakError(
"Could not start notify on {0}: {1}".format(
characteristic.uuid, success
)
)
async def stop_notify(
self, char_specifier: Union[BleakGATTCharacteristic, int, str, uuid.UUID]
) -> None:
"""Deactivate notification/indication on a specified characteristic.
Args:
char_specifier (BleakGATTCharacteristic, int, str or UUID): The characteristic to deactivate
notification/indication on, specified by either integer handle, UUID or
directly by the BleakGATTCharacteristic object representing it.
"""
manager = self._central_manager_delegate
if not isinstance(char_specifier, BleakGATTCharacteristic):
characteristic = self.services.get_characteristic(char_specifier)
else:
characteristic = char_specifier
if not characteristic:
raise BleakError("Characteristic {} not found!".format(char_specifier))
success = await manager.connected_peripheral_delegate.stopNotify_(
characteristic.obj
)
if not success:
raise BleakError(
"Could not stop notify on {0}: {1}".format(characteristic.uuid, success)
)
async def get_rssi(self) -> int:
"""To get RSSI value in dBm of the connected Peripheral"""
self._device_info.readRSSI()
manager = self._central_manager_delegate
RSSI = manager.connected_peripheral.RSSI()
for i in range(20): # First time takes a little otherwise returns None
RSSI = manager.connected_peripheral.RSSI()
if not RSSI:
await asyncio.sleep(0.1)
else:
return int(RSSI)
if not RSSI:
return None | 0.861363 | 0.07538 |
import datetime
import pytz
from pdb import set_trace
import numpy as np
from unittest import TestCase
from .. import segmentize, check_format, compute_seeds, export_graph, \
feature_lines_to_image, compute_feature_lines, extract_training_points
from .helpers import iter_all_files
import os
__dirname__ = os.path.dirname(__file__)
line_continuity = 0
sensitivity = 5 # This will be taken from the request from client
proportion_of_hottest_area = 4 ** (sensitivity * 0.4) / 5000
proportion_of_coldest_area = 0.5
degree = 1 # This will be taken from the request from client
class TestOverallProcess(TestCase):
def test_overall_process(self):
@iter_all_files(__dirname__ + "/data/spectrogram")
def main(filepath):
def export_intermediate_data_as_graph():
filename = os.path.splitext(os.path.basename(filepath))[0]
export_graph(spectrogram,
filename + "_spectrogram") # ex: spectrogram_20190417_0910
export_graph(markers, filename + "_markers")
export_graph(segment_labels, filename + "_segment_labels")
export_graph(feature_lines_to_image(feature_lines, spectrogram.shape), filename + "_feature_lines")
# print('Now testing with ' + filepath)
spectrogram = np.load(filepath)
check_result = check_format(spectrogram)
if not check_result["is_ok"]:
print("bad format")
print(check_result['msg'])
return check_result['msg']
markers = compute_seeds(spectrogram, proportion_of_hottest_area, proportion_of_coldest_area)
segment_labels = segmentize(spectrogram, markers, line_continuity)
training_points = extract_training_points(segment_labels, spectrogram, pass_rate=0.3)
feature_lines = compute_feature_lines(training_points, degree)
export_intermediate_data_as_graph() # Optional
main() | static/server/modules/test/test_overall_process.py | import datetime
import pytz
from pdb import set_trace
import numpy as np
from unittest import TestCase
from .. import segmentize, check_format, compute_seeds, export_graph, \
feature_lines_to_image, compute_feature_lines, extract_training_points
from .helpers import iter_all_files
import os
__dirname__ = os.path.dirname(__file__)
line_continuity = 0
sensitivity = 5 # This will be taken from the request from client
proportion_of_hottest_area = 4 ** (sensitivity * 0.4) / 5000
proportion_of_coldest_area = 0.5
degree = 1 # This will be taken from the request from client
class TestOverallProcess(TestCase):
def test_overall_process(self):
@iter_all_files(__dirname__ + "/data/spectrogram")
def main(filepath):
def export_intermediate_data_as_graph():
filename = os.path.splitext(os.path.basename(filepath))[0]
export_graph(spectrogram,
filename + "_spectrogram") # ex: spectrogram_20190417_0910
export_graph(markers, filename + "_markers")
export_graph(segment_labels, filename + "_segment_labels")
export_graph(feature_lines_to_image(feature_lines, spectrogram.shape), filename + "_feature_lines")
# print('Now testing with ' + filepath)
spectrogram = np.load(filepath)
check_result = check_format(spectrogram)
if not check_result["is_ok"]:
print("bad format")
print(check_result['msg'])
return check_result['msg']
markers = compute_seeds(spectrogram, proportion_of_hottest_area, proportion_of_coldest_area)
segment_labels = segmentize(spectrogram, markers, line_continuity)
training_points = extract_training_points(segment_labels, spectrogram, pass_rate=0.3)
feature_lines = compute_feature_lines(training_points, degree)
export_intermediate_data_as_graph() # Optional
main() | 0.348978 | 0.202739 |
import os
from pathlib import Path
import requests
import errno
import shutil
import hashlib
import zipfile
import logging
from .tqdm import tqdm
logger = logging.getLogger(__name__)
__all__ = ['unzip', 'download', 'mkdir', 'check_sha1', 'raise_num_file']
def unzip(zip_file_path, root=os.path.expanduser('./')):
"""Unzips files located at `zip_file_path` into parent directory specified by `root`.
"""
folders = []
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall(root)
for name in zf.namelist():
folder = Path(name).parts[0]
if folder not in folders:
folders.append(folder)
folders = folders[0] if len(folders) == 1 else tuple(folders)
return folders
def download(url, path=None, overwrite=False, sha1_hash=None):
"""Download files from a given URL.
Parameters
----------
url : str
URL where file is located
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
overwrite : bool, optional
Whether to overwrite destination file if one already exists at this location.
sha1_hash : str, optional
Expected sha1 hash in hexadecimal digits (will ignore existing file when hash is specified
but doesn't match).
Returns
-------
str
The file path of the downloaded file.
"""
if path is None:
fname = url.split('/')[-1]
else:
path = os.path.expanduser(path)
if os.path.isdir(path):
fname = os.path.join(path, url.split('/')[-1])
else:
fname = path
if overwrite or not os.path.exists(fname) or (sha1_hash and not check_sha1(fname, sha1_hash)):
dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname)))
if not os.path.exists(dirname):
os.makedirs(dirname)
logger.info('Downloading %s from %s...'%(fname, url))
r = requests.get(url, stream=True)
if r.status_code != 200:
raise RuntimeError("Failed downloading url %s"%url)
total_length = r.headers.get('content-length')
with open(fname, 'wb') as f:
if total_length is None: # no content length header
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
else:
total_length = int(total_length)
for chunk in tqdm(r.iter_content(chunk_size=1024),
total=int(total_length / 1024. + 0.5),
unit='KB', unit_scale=False, dynamic_ncols=True):
f.write(chunk)
if sha1_hash and not check_sha1(fname, sha1_hash):
raise UserWarning('File {} is downloaded but the content hash does not match. ' \
'The repo may be outdated or download may be incomplete. ' \
'If the "repo_url" is overridden, consider switching to ' \
'the default repo.'.format(fname))
return fname
def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash.
"""
sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
while True:
data = f.read(1048576)
if not data:
break
sha1.update(data)
return sha1.hexdigest() == sha1_hash
def mkdir(path):
"""Make directory at the specified local path with special error handling.
"""
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def raise_num_file(nofile_atleast=4096):
try:
import resource as res
except ImportError: #Windows
res = None
if res is None:
return (None,)*2
# what is current ulimit -n setting?
soft,ohard = res.getrlimit(res.RLIMIT_NOFILE)
hard = ohard
# increase limit (soft and even hard) if needed
if soft < nofile_atleast:
soft = nofile_atleast
if hard<soft:
hard = soft
#logger.warning('setting soft & hard ulimit -n {} {}'.format(soft,hard))
try:
res.setrlimit(res.RLIMIT_NOFILE,(soft,hard))
except (ValueError,res.error):
try:
hard = soft
logger.warning('trouble with max limit, retrying with soft,hard {},{}'.format(soft,hard))
res.setrlimit(res.RLIMIT_NOFILE,(soft,hard))
except Exception:
logger.warning('failed to set ulimit')
soft,hard = res.getrlimit(res.RLIMIT_NOFILE)
return soft,hard
raise_num_file() | autogluon/utils/files.py | import os
from pathlib import Path
import requests
import errno
import shutil
import hashlib
import zipfile
import logging
from .tqdm import tqdm
logger = logging.getLogger(__name__)
__all__ = ['unzip', 'download', 'mkdir', 'check_sha1', 'raise_num_file']
def unzip(zip_file_path, root=os.path.expanduser('./')):
"""Unzips files located at `zip_file_path` into parent directory specified by `root`.
"""
folders = []
with zipfile.ZipFile(zip_file_path) as zf:
zf.extractall(root)
for name in zf.namelist():
folder = Path(name).parts[0]
if folder not in folders:
folders.append(folder)
folders = folders[0] if len(folders) == 1 else tuple(folders)
return folders
def download(url, path=None, overwrite=False, sha1_hash=None):
"""Download files from a given URL.
Parameters
----------
url : str
URL where file is located
path : str, optional
Destination path to store downloaded file. By default stores to the
current directory with same name as in url.
overwrite : bool, optional
Whether to overwrite destination file if one already exists at this location.
sha1_hash : str, optional
Expected sha1 hash in hexadecimal digits (will ignore existing file when hash is specified
but doesn't match).
Returns
-------
str
The file path of the downloaded file.
"""
if path is None:
fname = url.split('/')[-1]
else:
path = os.path.expanduser(path)
if os.path.isdir(path):
fname = os.path.join(path, url.split('/')[-1])
else:
fname = path
if overwrite or not os.path.exists(fname) or (sha1_hash and not check_sha1(fname, sha1_hash)):
dirname = os.path.dirname(os.path.abspath(os.path.expanduser(fname)))
if not os.path.exists(dirname):
os.makedirs(dirname)
logger.info('Downloading %s from %s...'%(fname, url))
r = requests.get(url, stream=True)
if r.status_code != 200:
raise RuntimeError("Failed downloading url %s"%url)
total_length = r.headers.get('content-length')
with open(fname, 'wb') as f:
if total_length is None: # no content length header
for chunk in r.iter_content(chunk_size=1024):
if chunk: # filter out keep-alive new chunks
f.write(chunk)
else:
total_length = int(total_length)
for chunk in tqdm(r.iter_content(chunk_size=1024),
total=int(total_length / 1024. + 0.5),
unit='KB', unit_scale=False, dynamic_ncols=True):
f.write(chunk)
if sha1_hash and not check_sha1(fname, sha1_hash):
raise UserWarning('File {} is downloaded but the content hash does not match. ' \
'The repo may be outdated or download may be incomplete. ' \
'If the "repo_url" is overridden, consider switching to ' \
'the default repo.'.format(fname))
return fname
def check_sha1(filename, sha1_hash):
"""Check whether the sha1 hash of the file content matches the expected hash.
Parameters
----------
filename : str
Path to the file.
sha1_hash : str
Expected sha1 hash in hexadecimal digits.
Returns
-------
bool
Whether the file content matches the expected hash.
"""
sha1 = hashlib.sha1()
with open(filename, 'rb') as f:
while True:
data = f.read(1048576)
if not data:
break
sha1.update(data)
return sha1.hexdigest() == sha1_hash
def mkdir(path):
"""Make directory at the specified local path with special error handling.
"""
try:
os.makedirs(path)
except OSError as exc: # Python >2.5
if exc.errno == errno.EEXIST and os.path.isdir(path):
pass
else:
raise
def raise_num_file(nofile_atleast=4096):
try:
import resource as res
except ImportError: #Windows
res = None
if res is None:
return (None,)*2
# what is current ulimit -n setting?
soft,ohard = res.getrlimit(res.RLIMIT_NOFILE)
hard = ohard
# increase limit (soft and even hard) if needed
if soft < nofile_atleast:
soft = nofile_atleast
if hard<soft:
hard = soft
#logger.warning('setting soft & hard ulimit -n {} {}'.format(soft,hard))
try:
res.setrlimit(res.RLIMIT_NOFILE,(soft,hard))
except (ValueError,res.error):
try:
hard = soft
logger.warning('trouble with max limit, retrying with soft,hard {},{}'.format(soft,hard))
res.setrlimit(res.RLIMIT_NOFILE,(soft,hard))
except Exception:
logger.warning('failed to set ulimit')
soft,hard = res.getrlimit(res.RLIMIT_NOFILE)
return soft,hard
raise_num_file() | 0.599485 | 0.144269 |
import time
import warnings
from functools import partial
import ast
import numpy as np
import scipy.sparse
from sklearn.model_selection import train_test_split, RepeatedStratifiedKFold, \
RepeatedKFold
from sklearn.utils import shuffle
import pandas as pd
from .ml import compute_estimator, train_estimator, get_classification_objective
from .config import MIN_SAMPLE_TRAIN, MEM_THRES, ETI_INI, \
SMALL_LARGE_THRES, CV_HOLDOUT_THRESHOLD, SPLIT_RATIO, N_SPLITS
from .data import concat
from .search import ParamSearch
from .training_log import training_log_reader, training_log_writer
import logging
logger = logging.getLogger(__name__)
class AutoML:
'''The AutoML class
Attributes:
model: An object with predict() and predict_proba() method (for
classification), storing the best trained model.
model_history: A dictionary of iter->model, storing the models when
the best model is updated each time
config_history: A dictionary of iter->(estimator, config, time),
storing the best estimator, config, and the time when the best
model is updated each time
classes_: A list of n_classes elements for class labels
best_iteration: An integer of the iteration number where the best
config is found
best_estimator: A string indicating the best estimator found.
best_config: A dictionary of the best configuration.
best_config_train_time: A float of the seconds taken by training the
best config
Typical usage example:
automl = AutoML()
automl_settings = {
"time_budget": 60,
"metric": 'accuracy',
"task": 'classification',
"log_file_name": 'test/mylog.log',
}
automl.fit(X_train = X_train, y_train = y_train,
**automl_settings)
'''
def __init__(self):
self._eti_ini = ETI_INI
self._custom_learners = {}
self._config_space_info = {}
self._custom_size_estimate = {}
self._track_iter = 0
@property
def model_history(self):
return self._model_history
@property
def config_history(self):
return self._config_history
@property
def model(self):
if self._trained_estimator:
return self._trained_estimator.model
else:
return None
@property
def best_estimator(self):
return self._best_estimator
@property
def best_iteration(self):
return self._best_iteration
@property
def best_config(self):
return self._selected.best_config[0]
@property
def best_loss(self):
return self._best_loss
@property
def best_config_train_time(self):
return self.best_train_time
@property
def classes_(self):
if self.label_transformer:
return self.label_transformer.classes_.tolist()
if self._trained_estimator:
return self._trained_estimator.model.classes_.tolist()
return None
def predict(self, X_test):
'''Predict label from features.
Args:
X_test: A numpy array of featurized instances, shape n*m.
Returns:
A numpy array of shape n*1 -- each element is a predicted class
label for an instance.
'''
X_test = self.preprocess(X_test)
y_pred = self._trained_estimator.predict(X_test)
if y_pred.ndim > 1:
y_pred = y_pred.flatten()
if self.label_transformer:
return self.label_transformer.inverse_transform(pd.Series(
y_pred))
else:
return y_pred
def predict_proba(self, X_test):
'''Predict the probability of each class from features, only works for
classification problems.
Args:
X_test: A numpy array of featurized instances, shape n*m.
Returns:
A numpy array of shape n*c. c is the # classes. Each element at
(i,j) is the probability for instance i to be in class j.
'''
X_test = self.preprocess(X_test)
proba = self._trained_estimator.predict_proba(X_test)
return proba
def preprocess(self, X):
if scipy.sparse.issparse(X):
X = X.tocsr()
if self.transformer:
X = self.transformer.transform(X)
return X
def _validate_data(self, X_train_all, y_train_all, dataframe, label,
X_val=None, y_val=None):
if X_train_all is not None and y_train_all is not None:
if not (isinstance(X_train_all, np.ndarray)
or scipy.sparse.issparse(X_train_all)
or isinstance(X_train_all, pd.DataFrame)
):
raise ValueError(
"X_train_all must be a numpy array, a pandas dataframe, "
"or Scipy sparse matrix.")
if not (isinstance(y_train_all, np.ndarray)
or isinstance(y_train_all, pd.Series)):
raise ValueError(
"y_train_all must be a numpy array or a pandas series.")
if X_train_all.size == 0 or y_train_all.size == 0:
raise ValueError("Input data must not be empty.")
if isinstance(y_train_all, np.ndarray):
y_train_all = y_train_all.flatten()
if X_train_all.shape[0] != y_train_all.shape[0]:
raise ValueError(
"# rows in X_train must match length of y_train.")
self.df = isinstance(X_train_all, pd.DataFrame)
self.nrow, self.ndim = X_train_all.shape
X, y = X_train_all, y_train_all
elif dataframe is not None and label is not None:
if not isinstance(dataframe, pd.DataFrame):
raise ValueError("dataframe must be a pandas DataFrame")
if not label in dataframe.columns:
raise ValueError("label must a column name in dataframe")
self.df = True
self.dataframe, self.label = dataframe, label
X = dataframe.drop(columns=label)
self.nrow, self.ndim = X.shape
y = dataframe[label]
else:
raise ValueError(
"either X_train_all+y_train_all or dataframe+label need to be provided.")
if scipy.sparse.issparse(X_train_all):
self.transformer = self.label_transformer = False
self.X_train_all, self.y_train_all = X, y
else:
from .data import DataTransformer
self.transformer = DataTransformer()
self.X_train_all, self.y_train_all = self.transformer.fit_transform(
X, y, self.task)
self.label_transformer = self.transformer.label_transformer
if X_val is not None and y_val is not None:
if not (isinstance(X_val, np.ndarray)
or scipy.sparse.issparse(X_val)
or isinstance(X_val, pd.DataFrame)
):
raise ValueError(
"X_val must be None, a numpy array, a pandas dataframe, "
"or Scipy sparse matrix.")
if not (isinstance(y_val, np.ndarray)
or isinstance(y_val, pd.Series)):
raise ValueError(
"y_val must be None, a numpy array or a pandas series.")
if X_val.size == 0 or y_val.size == 0:
raise ValueError(
"Validation data are expected to be nonempty. "
"Use None for X_val and y_val if no validation data.")
if isinstance(y_val, np.ndarray):
y_val = y_val.flatten()
if X_val.shape[0] != y_val.shape[0]:
raise ValueError(
"# rows in X_val must match length of y_val.")
if self.transformer:
self.X_val = self.transformer.transform(X_val)
else:
self.X_val = X_val
if self.label_transformer:
self.y_val = self.label_transformer.transform(y_val)
else:
self.y_val = y_val
else:
self.X_val = self.y_val = None
def _prepare_data(self,
eval_method,
split_ratio,
n_splits):
X_val, y_val = self.X_val, self.y_val
if scipy.sparse.issparse(X_val):
X_val = X_val.tocsr()
X_train_all, y_train_all = self.X_train_all, self.y_train_all
if scipy.sparse.issparse(X_train_all):
X_train_all = X_train_all.tocsr()
if self.task != 'regression':
# logger.info(f"label {pd.unique(y_train_all)}")
label_set, counts = np.unique(y_train_all, return_counts=True)
# augment rare classes
rare_threshld = 20
rare = counts < rare_threshld
rare_label, rare_counts = label_set[rare], counts[rare]
for i, label in enumerate(rare_label):
count = rare_count = rare_counts[i]
rare_index = y_train_all == label
n = len(y_train_all)
while count < rare_threshld:
if self.df:
X_train_all = concat(X_train_all,
X_train_all.iloc[:n].loc[rare_index])
else:
X_train_all = concat(X_train_all,
X_train_all[:n][rare_index, :])
if isinstance(y_train_all, pd.Series):
y_train_all = concat(y_train_all,
y_train_all.iloc[:n].loc[rare_index])
else:
y_train_all = np.concatenate([y_train_all,
y_train_all[:n][rare_index]])
count += rare_count
logger.debug(
f"class {label} augmented from {rare_count} to {count}")
X_train_all, y_train_all = shuffle(
X_train_all, y_train_all, random_state=202020)
if self.df:
X_train_all.reset_index(drop=True, inplace=True)
if isinstance(y_train_all, pd.Series):
y_train_all.reset_index(drop=True, inplace=True)
X_train, y_train = X_train_all, y_train_all
if X_val is None:
if self.task != 'regression' and eval_method == 'holdout':
label_set, first = np.unique(y_train_all, return_index=True)
rest = []
last = 0
first.sort()
for i in range(len(first)):
rest.extend(range(last, first[i]))
last = first[i] + 1
rest.extend(range(last, len(y_train_all)))
X_first = X_train_all.iloc[first] if self.df else X_train_all[
first]
X_rest = X_train_all.iloc[rest] if self.df else X_train_all[rest]
y_rest = y_train_all.iloc[rest] if isinstance(
y_train_all, pd.Series) else y_train_all[rest]
stratify = y_rest if self.split_type == 'stratified' else None
X_train, X_val, y_train, y_val = train_test_split(
X_rest,
y_rest,
test_size=split_ratio,
stratify=stratify,
random_state=1)
X_train = concat(X_first, X_train)
y_train = concat(label_set,
y_train) if self.df else np.concatenate([label_set, y_train])
X_val = concat(X_first, X_val)
y_val = concat(label_set,
y_val) if self.df else np.concatenate([label_set, y_val])
_, y_train_counts_elements = np.unique(y_train,
return_counts=True)
_, y_val_counts_elements = np.unique(y_val,
return_counts=True)
logger.debug(
f"""{self.split_type} split for y_train \
{y_train_counts_elements}, \
y_val {y_val_counts_elements}""")
elif eval_method == 'holdout' and self.task == 'regression':
X_train, X_val, y_train, y_val = train_test_split(
X_train_all,
y_train_all,
test_size=split_ratio,
random_state=1)
self.data_size = X_train.shape[0]
self.X_train, self.y_train, self.X_val, self.y_val = (
X_train, y_train, X_val, y_val)
if self.split_type == "stratified":
logger.info("Using StratifiedKFold")
self.kf = RepeatedStratifiedKFold(n_splits=n_splits, n_repeats=1,
random_state=202020)
else:
logger.info("Using RepeatedKFold")
self.kf = RepeatedKFold(n_splits=n_splits, n_repeats=1,
random_state=202020)
def prepare_sample_train_data(self, sample_size):
full_size = len(self.y_train)
if sample_size <= full_size:
if isinstance(self.X_train, pd.DataFrame):
sampled_X_train = self.X_train.iloc[:sample_size]
else:
sampled_X_train = self.X_train[:sample_size]
sampled_y_train = self.y_train[:sample_size]
else:
sampled_X_train = concat(self.X_train, self.X_val)
sampled_y_train = np.concatenate([self.y_train, self.y_val])
return sampled_X_train, sampled_y_train
def _compute_with_config_base(self,
metric,
compute_train_loss,
estimator,
config,
sample_size):
sampled_X_train, sampled_y_train = self.prepare_sample_train_data(
sample_size)
time_left = self.time_budget - self.time_from_start
budget = time_left if sample_size == self.data_size else \
time_left / 2 * sample_size / self.data_size
return compute_estimator(sampled_X_train,
sampled_y_train,
self.X_val,
self.y_val,
budget,
self.kf,
config,
self.task,
estimator,
self.eval_method,
metric,
self._best_loss,
self.n_jobs,
self._custom_learners.get(estimator),
compute_train_loss)
def _train_with_config(self, estimator, config, sample_size):
sampled_X_train, sampled_y_train = self.prepare_sample_train_data(
sample_size)
budget = None if self.time_budget is None else (self.time_budget
- self.time_from_start)
model, train_time = train_estimator(
sampled_X_train,
sampled_y_train,
config,
self.task,
estimator,
self.n_jobs,
self._custom_learners.get(estimator),
budget)
return model, train_time
def add_learner(self,
learner_name,
learner_class,
size_estimate=lambda config: 'unknown',
cost_relative2lgbm=1):
'''Add a customized learner
Args:
learner_name: A string of the learner's name
learner_class: A subclass of BaseEstimator
size_estimate: A function from a config to its memory size in float
cost_relative2lgbm: A float number for the training cost ratio with
respect to lightgbm (when both use the initial config)
'''
self._custom_learners[learner_name] = learner_class
self._eti_ini[learner_name] = cost_relative2lgbm
self._config_space_info[learner_name] = \
learner_class.params_configsearch_info
self._custom_size_estimate[learner_name] = size_estimate
def get_estimator_from_log(self, log_file_name, record_id, objective):
'''Get the estimator from log file
Args:
log_file_name: A string of the log file name
record_id: An integer of the record ID in the file,
0 corresponds to the first trial
objective: A string of the objective name,
'binary', 'multi', or 'regression'
Returns:
An estimator object for the given configuration
'''
with training_log_reader(log_file_name) as reader:
record = reader.get_record(record_id)
estimator = record.learner
config = record.config
estimator, _ = train_estimator(
None, None, config, objective, estimator,
estimator_class=self._custom_learners.get(estimator)
)
return estimator
def retrain_from_log(self,
log_file_name,
X_train=None,
y_train=None,
dataframe=None,
label=None,
time_budget=0,
task='classification',
eval_method='auto',
split_ratio=SPLIT_RATIO,
n_splits=N_SPLITS,
split_type="stratified",
n_jobs=1,
train_best=True,
train_full=False,
record_id=-1):
'''Retrain from log file
Args:
time_budget: A float number of the time budget in seconds
log_file_name: A string of the log file name
X_train: A numpy array of training data in shape n*m
y_train: A numpy array of labels in shape n*1
task: A string of the task type, e.g.,
'classification', 'regression'
eval_method: A string of resampling strategy, one of
['auto', 'cv', 'holdout']
split_ratio: A float of the validation data percentage for holdout
n_splits: An integer of the number of folds for cross-validation
n_jobs: An integer of the number of threads for training
train_best: A boolean of whether to train the best config in the
time budget; if false, train the last config in the budget
train_full: A boolean of whether to train on the full data. If true,
eval_method and sample_size in the log file will be ignored
record_id: the ID of the training log record from which the model will
be retrained. By default `record_id = -1` which means this will be
ignored. `record_id = 0` corresponds to the first trial, and
when `record_id >= 0`, `time_budget` will be ignored.
'''
self.task = task
self._validate_data(X_train, y_train, dataframe, label)
logger.info('log file name {}'.format(log_file_name))
best_config = None
best_val_loss = float('+inf')
best_estimator = None
sample_size = None
time_used = 0.0
training_duration = 0
best = None
with training_log_reader(log_file_name) as reader:
if record_id >= 0:
best = reader.get_record(record_id)
else:
for record in reader.records():
time_used = record.total_search_time
if time_used > time_budget:
break
training_duration = time_used
val_loss = record.validation_loss
if val_loss <= best_val_loss or not train_best:
if val_loss == best_val_loss and train_best:
size = record.sample_size
if size > sample_size:
best = record
best_val_loss = val_loss
sample_size = size
else:
best = record
size = record.sample_size
best_val_loss = val_loss
sample_size = size
if not training_duration:
from .model import BaseEstimator
self._trained_estimator = BaseEstimator()
self._trained_estimator.model = None
return training_duration
if not best: return
best_estimator = best.learner
best_config = best.config
sample_size = len(self.y_train_all) if train_full \
else best.sample_size
logger.info(
'estimator = {}, config = {}, #training instances = {}'.format(
best_estimator, best_config, sample_size))
# Partially copied from fit() function
# Initilize some attributes required for retrain_from_log
np.random.seed(0)
self.task = task
if self.task == 'classification':
self.task = get_classification_objective(
len(np.unique(self.y_train_all)))
assert split_type in ["stratified", "uniform"]
self.split_type = split_type
else:
self.split_type = "uniform"
if record_id >= 0:
eval_method = 'cv'
elif eval_method == 'auto':
eval_method = self._decide_eval_method(time_budget)
self.modelcount = 0
self._prepare_data(eval_method, split_ratio, n_splits)
self.time_budget = None
self.n_jobs = n_jobs
self._trained_estimator = self._train_with_config(
best_estimator, best_config, sample_size)[0]
return training_duration
def _decide_eval_method(self, time_budget):
if self.X_val is not None:
return 'holdout'
nrow, dim = self.nrow, self.ndim
if nrow * dim / 0.9 < SMALL_LARGE_THRES * (
time_budget / 3600) and nrow < CV_HOLDOUT_THRESHOLD:
# time allows or sampling can be used and cv is necessary
return 'cv'
else:
return 'holdout'
def fit(self,
X_train=None,
y_train=None,
dataframe=None,
label=None,
metric='auto',
task='classification',
n_jobs=-1,
log_file_name='default.log',
estimator_list='auto',
time_budget=60,
max_iter=1000000,
sample=True,
ensemble=False,
eval_method='auto',
log_type='better',
model_history=False,
split_ratio=SPLIT_RATIO,
n_splits=N_SPLITS,
log_training_metric=False,
mem_thres=MEM_THRES,
X_val=None,
y_val=None,
retrain_full=True,
split_type="stratified",
learner_selector='sample',
):
'''Find a model for a given task
Args:
X_train: A numpy array or a pandas dataframe of training data in
shape n*m
y_train: A numpy array or a pandas series of labels in shape n*1
dataframe: A dataframe of training data including label column
label: A str of the label column name
Note: If X_train and y_train are provided,
dataframe and label are ignored;
If not, dataframe and label must be provided.
metric: A string of the metric name or a function,
e.g., 'accuracy','roc_auc','f1','log_loss','mae','mse','r2'
if passing a customized metric function, the function needs to
have the follwing signature
def metric(X_test, y_test, estimator, labels, X_train, y_train):
return metric_to_minimize, metrics_to_log
which returns a float number as the minimization objective,
and a tuple of floats as the metrics to log
task: A string of the task type, e.g.,
'classification', 'regression'
n_jobs: An integer of the number of threads for training
log_file_name: A string of the log file name
estimator_list: A list of strings for estimator names, or 'auto'
e.g., ['lgbm', 'xgboost', 'catboost', 'rf', 'extra_tree']
time_budget: A float number of the time budget in seconds
max_iter: An integer of the maximal number of iterations
sample: A boolean of whether to sample the training data during
search
eval_method: A string of resampling strategy, one of
['auto', 'cv', 'holdout']
split_ratio: A float of the valiation data percentage for holdout
n_splits: An integer of the number of folds for cross-validation
log_type: A string of the log type, one of ['better', 'all', 'new']
'better' only logs configs with better loss than previos iters
'all' logs all the tried configs
'new' only logs non-redundant configs
model_history: A boolean of whether to keep the history of best
models in the history property. Make sure memory is large
enough if setting to True.
log_training_metric: A boolean of whether to log the training
metric for each model.
mem_thres: A float of the memory size constraint in bytes
X_val: None | a numpy array or a pandas dataframe of validation data
y_val: None | a numpy array or a pandas series of validation labels
'''
self.task = task
self._validate_data(X_train, y_train, dataframe, label, X_val, y_val)
self.start_time_flag = time.time()
np.random.seed(0)
self.learner_selector = learner_selector
if self.task == 'classification':
self.task = get_classification_objective(
len(np.unique(self.y_train_all)))
assert split_type in ["stratified", "uniform"]
self.split_type = split_type
else:
self.split_type = "uniform"
if 'auto' == estimator_list:
estimator_list = ['lgbm', 'rf', 'catboost', 'xgboost', 'extra_tree']
if 'regression' != self.task:
estimator_list += ['lrl1', ]
logger.info(
"List of ML learners in AutoML Run: {}".format(estimator_list))
if eval_method == 'auto' or self.X_val is not None:
eval_method = self._decide_eval_method(time_budget)
self.eval_method = eval_method
logger.info("Evaluation method: {}".format(eval_method))
self.retrain_full = retrain_full and (eval_method == 'holdout'
and self.X_val is None)
self.sample = sample and (eval_method != 'cv')
if 'auto' == metric:
if 'binary' in task:
metric = 'roc_auc'
elif 'multi' in task:
metric = 'log_loss'
else:
metric = 'r2'
if metric in ['r2', 'accuracy', 'roc_auc', 'f1', 'ap']:
error_metric = f"1-{metric}"
elif isinstance(metric, str):
error_metric = metric
else:
error_metric = 'customized metric'
logger.info(f'Minimizing error metric: {error_metric}')
with training_log_writer(log_file_name) as save_helper:
self.save_helper = save_helper
self._prepare_data(eval_method, split_ratio, n_splits)
self._compute_with_config = partial(AutoML._compute_with_config_base,
self,
metric,
log_training_metric)
self.time_budget = time_budget
self.estimator_list = estimator_list
self.ensemble = ensemble
self.max_iter = max_iter
self.mem_thres = mem_thres
self.log_type = log_type
self.split_ratio = split_ratio
self.save_model_history = model_history
self.n_jobs = n_jobs
self.search()
logger.info("fit succeeded")
def search(self):
self.searchers = {}
# initialize the searchers
self.eti = []
self._best_loss = float('+inf')
self.best_train_time = 0
self.time_from_start = 0
self.estimator_index = -1
self._best_iteration = 0
self._model_history = {}
self._config_history = {}
self.max_iter_per_learner = 10000 # TODO
self.iter_per_learner = dict([(e, 0) for e in self.estimator_list])
self.fullsize = False
self._trained_estimator = None
if self.ensemble:
self.best_model = {}
for self._track_iter in range(self.max_iter):
if self.estimator_index == -1:
estimator = self.estimator_list[0]
else:
estimator = self._select_estimator(self.estimator_list)
if not estimator:
break
logger.info(f"iteration {self._track_iter}"
f" current learner {estimator}")
if estimator in self.searchers:
model = self.searchers[estimator].trained_estimator
improved = self.searchers[estimator].search1step(
global_best_loss=self._best_loss,
retrain_full=self.retrain_full,
mem_thres=self.mem_thres)
else:
model = improved = None
self.searchers[estimator] = ParamSearch(
estimator,
self.data_size,
self._compute_with_config,
self._train_with_config,
self.save_helper,
MIN_SAMPLE_TRAIN if self.sample else self.data_size,
self.task,
self.log_type,
self._config_space_info.get(estimator),
self._custom_size_estimate.get(estimator),
self.split_ratio)
self.searchers[estimator].search_begin(self.time_budget,
self.start_time_flag)
if self.estimator_index == -1:
eti_base = self._eti_ini[estimator]
self.eti.append(
self.searchers[estimator]
.expected_time_improvement_search())
for e in self.estimator_list[1:]:
self.eti.append(
self._eti_ini[e] / eti_base * self.eti[0])
self.estimator_index = 0
self.time_from_start = time.time() - self.start_time_flag
# logger.info(f"{self.searchers[estimator].sample_size}, {data_size}")
if self.searchers[estimator].sample_size == self.data_size:
self.iter_per_learner[estimator] += 1
if not self.fullsize:
self.fullsize = True
if self.searchers[estimator].best_loss < self._best_loss:
self._best_loss = self.searchers[estimator].best_loss
self._best_estimator = estimator
self.best_train_time = self.searchers[estimator].train_time
self._config_history[self._track_iter] = (
estimator,
self.searchers[estimator].best_config[0],
self.time_from_start)
if self.save_model_history:
self._model_history[self._track_iter] = self.searchers[
estimator].trained_estimator.model
elif self._trained_estimator:
del self._trained_estimator
self._trained_estimator = None
self._trained_estimator = self.searchers[
estimator].trained_estimator
self._best_iteration = self._track_iter
if model and improved and not self.save_model_history:
model.cleanup()
logger.info(
" at {:.1f}s,\tbest {}'s error={:.4f},\tbest {}'s error={:.4f}".format(
self.time_from_start,
estimator,
self.searchers[estimator].best_loss,
self._best_estimator,
self._best_loss))
if self.time_from_start >= self.time_budget:
break
if self.ensemble:
time_left = self.time_from_start - self.time_budget
time_ensemble = self.searchers[self._best_estimator].train_time
if time_left < time_ensemble < 2 * time_left:
break
if self.searchers[
estimator].train_time > self.time_budget - self.time_from_start:
self.iter_per_learner[estimator] = self.max_iter_per_learner
# Add a checkpoint for the current best config to the log.
self.save_helper.checkpoint()
if self.searchers:
self._selected = self.searchers[self._best_estimator]
self._trained_estimator = self._selected.trained_estimator
self.modelcount = sum(self.searchers[estimator].model_count
for estimator in self.searchers)
logger.info(self._trained_estimator.model)
if self.ensemble:
searchers = list(self.searchers.items())
searchers.sort(key=lambda x: x[1].best_loss)
estimators = [(x[0], x[1].trained_estimator) for x in searchers[
:2]]
estimators += [(x[0], x[1].trained_estimator) for x in searchers[
2:] if x[1].best_loss < 4 * self._selected.best_loss]
logger.info(estimators)
if self.task != "regression":
from sklearn.ensemble import StackingClassifier as Stacker
for e in estimators:
e[1]._estimator_type = 'classifier'
else:
from sklearn.ensemble import StackingRegressor as Stacker
best_m = self._trained_estimator
stacker = Stacker(estimators, best_m, n_jobs=self.n_jobs,
passthrough=True)
stacker.fit(self.X_train_all, self.y_train_all)
self._trained_estimator = stacker
self._trained_estimator.model = stacker
else:
self._selected = self._trained_estimator = None
self.modelcount = 0
def __del__(self):
if hasattr(self, '_trained_estimator') and self._trained_estimator \
and hasattr(self._trained_estimator, 'cleanup'):
self._trained_estimator.cleanup()
del self._trained_estimator
def _select_estimator(self, estimator_list):
time_left = self.time_budget - self.time_from_start
if self.best_train_time < time_left < 2 * self.best_train_time:
best_searcher = self.searchers[self._best_estimator]
config_sig = best_searcher.get_hist_config_sig(
best_searcher.sample_size_full,
best_searcher.best_config[0])
if config_sig not in best_searcher.config_tried:
# trainAll
return self._best_estimator
if self.learner_selector == 'roundrobin':
self.estimator_index += 1
if self.estimator_index == len(estimator_list):
self.estimator_index = 0
return estimator_list[self.estimator_index]
min_expected_time, selected = np.Inf, None
inv = []
for i, estimator in enumerate(estimator_list):
if estimator in self.searchers:
searcher = self.searchers[estimator]
if self.iter_per_learner[estimator] >= self.max_iter_per_learner:
inv.append(0)
continue
eti_searcher = min(2 * searcher.train_time,
searcher.expected_time_improvement_search())
gap = searcher.best_loss - self._best_loss
if gap > 0 and not self.ensemble:
delta_loss = searcher.old_loss - searcher.new_loss
delta_time = searcher.old_loss_time + \
searcher.new_loss_time - searcher.old_train_time
speed = delta_loss / float(delta_time)
try:
expected_time = max(gap / speed, searcher.train_time)
except ZeroDivisionError:
warnings.warn("ZeroDivisionError: need to debug ",
"speed: {0}, "
"old_loss: {1}, "
"new_loss: {2}"
.format(speed,
searcher.old_loss,
searcher.new_loss))
expected_time = 0.0
expected_time = 2 * max(expected_time, eti_searcher)
else:
expected_time = eti_searcher
if expected_time == 0:
expected_time = 1e-10
inv.append(1 / expected_time)
else:
expected_time = self.eti[i]
inv.append(0)
if expected_time < min_expected_time:
min_expected_time = expected_time
selected = estimator
if len(self.searchers) < len(estimator_list) or not selected:
if selected not in self.searchers:
# print('select',selected,'eti',min_expected_time)
return selected
s = sum(inv)
p = np.random.random()
q = 0
for i in range(len(inv)):
if inv[i]:
q += inv[i] / s
if p < q:
return estimator_list[i] | flaml/automl.py | import time
import warnings
from functools import partial
import ast
import numpy as np
import scipy.sparse
from sklearn.model_selection import train_test_split, RepeatedStratifiedKFold, \
RepeatedKFold
from sklearn.utils import shuffle
import pandas as pd
from .ml import compute_estimator, train_estimator, get_classification_objective
from .config import MIN_SAMPLE_TRAIN, MEM_THRES, ETI_INI, \
SMALL_LARGE_THRES, CV_HOLDOUT_THRESHOLD, SPLIT_RATIO, N_SPLITS
from .data import concat
from .search import ParamSearch
from .training_log import training_log_reader, training_log_writer
import logging
logger = logging.getLogger(__name__)
class AutoML:
'''The AutoML class
Attributes:
model: An object with predict() and predict_proba() method (for
classification), storing the best trained model.
model_history: A dictionary of iter->model, storing the models when
the best model is updated each time
config_history: A dictionary of iter->(estimator, config, time),
storing the best estimator, config, and the time when the best
model is updated each time
classes_: A list of n_classes elements for class labels
best_iteration: An integer of the iteration number where the best
config is found
best_estimator: A string indicating the best estimator found.
best_config: A dictionary of the best configuration.
best_config_train_time: A float of the seconds taken by training the
best config
Typical usage example:
automl = AutoML()
automl_settings = {
"time_budget": 60,
"metric": 'accuracy',
"task": 'classification',
"log_file_name": 'test/mylog.log',
}
automl.fit(X_train = X_train, y_train = y_train,
**automl_settings)
'''
def __init__(self):
self._eti_ini = ETI_INI
self._custom_learners = {}
self._config_space_info = {}
self._custom_size_estimate = {}
self._track_iter = 0
@property
def model_history(self):
return self._model_history
@property
def config_history(self):
return self._config_history
@property
def model(self):
if self._trained_estimator:
return self._trained_estimator.model
else:
return None
@property
def best_estimator(self):
return self._best_estimator
@property
def best_iteration(self):
return self._best_iteration
@property
def best_config(self):
return self._selected.best_config[0]
@property
def best_loss(self):
return self._best_loss
@property
def best_config_train_time(self):
return self.best_train_time
@property
def classes_(self):
if self.label_transformer:
return self.label_transformer.classes_.tolist()
if self._trained_estimator:
return self._trained_estimator.model.classes_.tolist()
return None
def predict(self, X_test):
'''Predict label from features.
Args:
X_test: A numpy array of featurized instances, shape n*m.
Returns:
A numpy array of shape n*1 -- each element is a predicted class
label for an instance.
'''
X_test = self.preprocess(X_test)
y_pred = self._trained_estimator.predict(X_test)
if y_pred.ndim > 1:
y_pred = y_pred.flatten()
if self.label_transformer:
return self.label_transformer.inverse_transform(pd.Series(
y_pred))
else:
return y_pred
def predict_proba(self, X_test):
'''Predict the probability of each class from features, only works for
classification problems.
Args:
X_test: A numpy array of featurized instances, shape n*m.
Returns:
A numpy array of shape n*c. c is the # classes. Each element at
(i,j) is the probability for instance i to be in class j.
'''
X_test = self.preprocess(X_test)
proba = self._trained_estimator.predict_proba(X_test)
return proba
def preprocess(self, X):
if scipy.sparse.issparse(X):
X = X.tocsr()
if self.transformer:
X = self.transformer.transform(X)
return X
def _validate_data(self, X_train_all, y_train_all, dataframe, label,
X_val=None, y_val=None):
if X_train_all is not None and y_train_all is not None:
if not (isinstance(X_train_all, np.ndarray)
or scipy.sparse.issparse(X_train_all)
or isinstance(X_train_all, pd.DataFrame)
):
raise ValueError(
"X_train_all must be a numpy array, a pandas dataframe, "
"or Scipy sparse matrix.")
if not (isinstance(y_train_all, np.ndarray)
or isinstance(y_train_all, pd.Series)):
raise ValueError(
"y_train_all must be a numpy array or a pandas series.")
if X_train_all.size == 0 or y_train_all.size == 0:
raise ValueError("Input data must not be empty.")
if isinstance(y_train_all, np.ndarray):
y_train_all = y_train_all.flatten()
if X_train_all.shape[0] != y_train_all.shape[0]:
raise ValueError(
"# rows in X_train must match length of y_train.")
self.df = isinstance(X_train_all, pd.DataFrame)
self.nrow, self.ndim = X_train_all.shape
X, y = X_train_all, y_train_all
elif dataframe is not None and label is not None:
if not isinstance(dataframe, pd.DataFrame):
raise ValueError("dataframe must be a pandas DataFrame")
if not label in dataframe.columns:
raise ValueError("label must a column name in dataframe")
self.df = True
self.dataframe, self.label = dataframe, label
X = dataframe.drop(columns=label)
self.nrow, self.ndim = X.shape
y = dataframe[label]
else:
raise ValueError(
"either X_train_all+y_train_all or dataframe+label need to be provided.")
if scipy.sparse.issparse(X_train_all):
self.transformer = self.label_transformer = False
self.X_train_all, self.y_train_all = X, y
else:
from .data import DataTransformer
self.transformer = DataTransformer()
self.X_train_all, self.y_train_all = self.transformer.fit_transform(
X, y, self.task)
self.label_transformer = self.transformer.label_transformer
if X_val is not None and y_val is not None:
if not (isinstance(X_val, np.ndarray)
or scipy.sparse.issparse(X_val)
or isinstance(X_val, pd.DataFrame)
):
raise ValueError(
"X_val must be None, a numpy array, a pandas dataframe, "
"or Scipy sparse matrix.")
if not (isinstance(y_val, np.ndarray)
or isinstance(y_val, pd.Series)):
raise ValueError(
"y_val must be None, a numpy array or a pandas series.")
if X_val.size == 0 or y_val.size == 0:
raise ValueError(
"Validation data are expected to be nonempty. "
"Use None for X_val and y_val if no validation data.")
if isinstance(y_val, np.ndarray):
y_val = y_val.flatten()
if X_val.shape[0] != y_val.shape[0]:
raise ValueError(
"# rows in X_val must match length of y_val.")
if self.transformer:
self.X_val = self.transformer.transform(X_val)
else:
self.X_val = X_val
if self.label_transformer:
self.y_val = self.label_transformer.transform(y_val)
else:
self.y_val = y_val
else:
self.X_val = self.y_val = None
def _prepare_data(self,
eval_method,
split_ratio,
n_splits):
X_val, y_val = self.X_val, self.y_val
if scipy.sparse.issparse(X_val):
X_val = X_val.tocsr()
X_train_all, y_train_all = self.X_train_all, self.y_train_all
if scipy.sparse.issparse(X_train_all):
X_train_all = X_train_all.tocsr()
if self.task != 'regression':
# logger.info(f"label {pd.unique(y_train_all)}")
label_set, counts = np.unique(y_train_all, return_counts=True)
# augment rare classes
rare_threshld = 20
rare = counts < rare_threshld
rare_label, rare_counts = label_set[rare], counts[rare]
for i, label in enumerate(rare_label):
count = rare_count = rare_counts[i]
rare_index = y_train_all == label
n = len(y_train_all)
while count < rare_threshld:
if self.df:
X_train_all = concat(X_train_all,
X_train_all.iloc[:n].loc[rare_index])
else:
X_train_all = concat(X_train_all,
X_train_all[:n][rare_index, :])
if isinstance(y_train_all, pd.Series):
y_train_all = concat(y_train_all,
y_train_all.iloc[:n].loc[rare_index])
else:
y_train_all = np.concatenate([y_train_all,
y_train_all[:n][rare_index]])
count += rare_count
logger.debug(
f"class {label} augmented from {rare_count} to {count}")
X_train_all, y_train_all = shuffle(
X_train_all, y_train_all, random_state=202020)
if self.df:
X_train_all.reset_index(drop=True, inplace=True)
if isinstance(y_train_all, pd.Series):
y_train_all.reset_index(drop=True, inplace=True)
X_train, y_train = X_train_all, y_train_all
if X_val is None:
if self.task != 'regression' and eval_method == 'holdout':
label_set, first = np.unique(y_train_all, return_index=True)
rest = []
last = 0
first.sort()
for i in range(len(first)):
rest.extend(range(last, first[i]))
last = first[i] + 1
rest.extend(range(last, len(y_train_all)))
X_first = X_train_all.iloc[first] if self.df else X_train_all[
first]
X_rest = X_train_all.iloc[rest] if self.df else X_train_all[rest]
y_rest = y_train_all.iloc[rest] if isinstance(
y_train_all, pd.Series) else y_train_all[rest]
stratify = y_rest if self.split_type == 'stratified' else None
X_train, X_val, y_train, y_val = train_test_split(
X_rest,
y_rest,
test_size=split_ratio,
stratify=stratify,
random_state=1)
X_train = concat(X_first, X_train)
y_train = concat(label_set,
y_train) if self.df else np.concatenate([label_set, y_train])
X_val = concat(X_first, X_val)
y_val = concat(label_set,
y_val) if self.df else np.concatenate([label_set, y_val])
_, y_train_counts_elements = np.unique(y_train,
return_counts=True)
_, y_val_counts_elements = np.unique(y_val,
return_counts=True)
logger.debug(
f"""{self.split_type} split for y_train \
{y_train_counts_elements}, \
y_val {y_val_counts_elements}""")
elif eval_method == 'holdout' and self.task == 'regression':
X_train, X_val, y_train, y_val = train_test_split(
X_train_all,
y_train_all,
test_size=split_ratio,
random_state=1)
self.data_size = X_train.shape[0]
self.X_train, self.y_train, self.X_val, self.y_val = (
X_train, y_train, X_val, y_val)
if self.split_type == "stratified":
logger.info("Using StratifiedKFold")
self.kf = RepeatedStratifiedKFold(n_splits=n_splits, n_repeats=1,
random_state=202020)
else:
logger.info("Using RepeatedKFold")
self.kf = RepeatedKFold(n_splits=n_splits, n_repeats=1,
random_state=202020)
def prepare_sample_train_data(self, sample_size):
full_size = len(self.y_train)
if sample_size <= full_size:
if isinstance(self.X_train, pd.DataFrame):
sampled_X_train = self.X_train.iloc[:sample_size]
else:
sampled_X_train = self.X_train[:sample_size]
sampled_y_train = self.y_train[:sample_size]
else:
sampled_X_train = concat(self.X_train, self.X_val)
sampled_y_train = np.concatenate([self.y_train, self.y_val])
return sampled_X_train, sampled_y_train
def _compute_with_config_base(self,
metric,
compute_train_loss,
estimator,
config,
sample_size):
sampled_X_train, sampled_y_train = self.prepare_sample_train_data(
sample_size)
time_left = self.time_budget - self.time_from_start
budget = time_left if sample_size == self.data_size else \
time_left / 2 * sample_size / self.data_size
return compute_estimator(sampled_X_train,
sampled_y_train,
self.X_val,
self.y_val,
budget,
self.kf,
config,
self.task,
estimator,
self.eval_method,
metric,
self._best_loss,
self.n_jobs,
self._custom_learners.get(estimator),
compute_train_loss)
def _train_with_config(self, estimator, config, sample_size):
sampled_X_train, sampled_y_train = self.prepare_sample_train_data(
sample_size)
budget = None if self.time_budget is None else (self.time_budget
- self.time_from_start)
model, train_time = train_estimator(
sampled_X_train,
sampled_y_train,
config,
self.task,
estimator,
self.n_jobs,
self._custom_learners.get(estimator),
budget)
return model, train_time
def add_learner(self,
learner_name,
learner_class,
size_estimate=lambda config: 'unknown',
cost_relative2lgbm=1):
'''Add a customized learner
Args:
learner_name: A string of the learner's name
learner_class: A subclass of BaseEstimator
size_estimate: A function from a config to its memory size in float
cost_relative2lgbm: A float number for the training cost ratio with
respect to lightgbm (when both use the initial config)
'''
self._custom_learners[learner_name] = learner_class
self._eti_ini[learner_name] = cost_relative2lgbm
self._config_space_info[learner_name] = \
learner_class.params_configsearch_info
self._custom_size_estimate[learner_name] = size_estimate
def get_estimator_from_log(self, log_file_name, record_id, objective):
'''Get the estimator from log file
Args:
log_file_name: A string of the log file name
record_id: An integer of the record ID in the file,
0 corresponds to the first trial
objective: A string of the objective name,
'binary', 'multi', or 'regression'
Returns:
An estimator object for the given configuration
'''
with training_log_reader(log_file_name) as reader:
record = reader.get_record(record_id)
estimator = record.learner
config = record.config
estimator, _ = train_estimator(
None, None, config, objective, estimator,
estimator_class=self._custom_learners.get(estimator)
)
return estimator
def retrain_from_log(self,
log_file_name,
X_train=None,
y_train=None,
dataframe=None,
label=None,
time_budget=0,
task='classification',
eval_method='auto',
split_ratio=SPLIT_RATIO,
n_splits=N_SPLITS,
split_type="stratified",
n_jobs=1,
train_best=True,
train_full=False,
record_id=-1):
'''Retrain from log file
Args:
time_budget: A float number of the time budget in seconds
log_file_name: A string of the log file name
X_train: A numpy array of training data in shape n*m
y_train: A numpy array of labels in shape n*1
task: A string of the task type, e.g.,
'classification', 'regression'
eval_method: A string of resampling strategy, one of
['auto', 'cv', 'holdout']
split_ratio: A float of the validation data percentage for holdout
n_splits: An integer of the number of folds for cross-validation
n_jobs: An integer of the number of threads for training
train_best: A boolean of whether to train the best config in the
time budget; if false, train the last config in the budget
train_full: A boolean of whether to train on the full data. If true,
eval_method and sample_size in the log file will be ignored
record_id: the ID of the training log record from which the model will
be retrained. By default `record_id = -1` which means this will be
ignored. `record_id = 0` corresponds to the first trial, and
when `record_id >= 0`, `time_budget` will be ignored.
'''
self.task = task
self._validate_data(X_train, y_train, dataframe, label)
logger.info('log file name {}'.format(log_file_name))
best_config = None
best_val_loss = float('+inf')
best_estimator = None
sample_size = None
time_used = 0.0
training_duration = 0
best = None
with training_log_reader(log_file_name) as reader:
if record_id >= 0:
best = reader.get_record(record_id)
else:
for record in reader.records():
time_used = record.total_search_time
if time_used > time_budget:
break
training_duration = time_used
val_loss = record.validation_loss
if val_loss <= best_val_loss or not train_best:
if val_loss == best_val_loss and train_best:
size = record.sample_size
if size > sample_size:
best = record
best_val_loss = val_loss
sample_size = size
else:
best = record
size = record.sample_size
best_val_loss = val_loss
sample_size = size
if not training_duration:
from .model import BaseEstimator
self._trained_estimator = BaseEstimator()
self._trained_estimator.model = None
return training_duration
if not best: return
best_estimator = best.learner
best_config = best.config
sample_size = len(self.y_train_all) if train_full \
else best.sample_size
logger.info(
'estimator = {}, config = {}, #training instances = {}'.format(
best_estimator, best_config, sample_size))
# Partially copied from fit() function
# Initilize some attributes required for retrain_from_log
np.random.seed(0)
self.task = task
if self.task == 'classification':
self.task = get_classification_objective(
len(np.unique(self.y_train_all)))
assert split_type in ["stratified", "uniform"]
self.split_type = split_type
else:
self.split_type = "uniform"
if record_id >= 0:
eval_method = 'cv'
elif eval_method == 'auto':
eval_method = self._decide_eval_method(time_budget)
self.modelcount = 0
self._prepare_data(eval_method, split_ratio, n_splits)
self.time_budget = None
self.n_jobs = n_jobs
self._trained_estimator = self._train_with_config(
best_estimator, best_config, sample_size)[0]
return training_duration
def _decide_eval_method(self, time_budget):
if self.X_val is not None:
return 'holdout'
nrow, dim = self.nrow, self.ndim
if nrow * dim / 0.9 < SMALL_LARGE_THRES * (
time_budget / 3600) and nrow < CV_HOLDOUT_THRESHOLD:
# time allows or sampling can be used and cv is necessary
return 'cv'
else:
return 'holdout'
def fit(self,
X_train=None,
y_train=None,
dataframe=None,
label=None,
metric='auto',
task='classification',
n_jobs=-1,
log_file_name='default.log',
estimator_list='auto',
time_budget=60,
max_iter=1000000,
sample=True,
ensemble=False,
eval_method='auto',
log_type='better',
model_history=False,
split_ratio=SPLIT_RATIO,
n_splits=N_SPLITS,
log_training_metric=False,
mem_thres=MEM_THRES,
X_val=None,
y_val=None,
retrain_full=True,
split_type="stratified",
learner_selector='sample',
):
'''Find a model for a given task
Args:
X_train: A numpy array or a pandas dataframe of training data in
shape n*m
y_train: A numpy array or a pandas series of labels in shape n*1
dataframe: A dataframe of training data including label column
label: A str of the label column name
Note: If X_train and y_train are provided,
dataframe and label are ignored;
If not, dataframe and label must be provided.
metric: A string of the metric name or a function,
e.g., 'accuracy','roc_auc','f1','log_loss','mae','mse','r2'
if passing a customized metric function, the function needs to
have the follwing signature
def metric(X_test, y_test, estimator, labels, X_train, y_train):
return metric_to_minimize, metrics_to_log
which returns a float number as the minimization objective,
and a tuple of floats as the metrics to log
task: A string of the task type, e.g.,
'classification', 'regression'
n_jobs: An integer of the number of threads for training
log_file_name: A string of the log file name
estimator_list: A list of strings for estimator names, or 'auto'
e.g., ['lgbm', 'xgboost', 'catboost', 'rf', 'extra_tree']
time_budget: A float number of the time budget in seconds
max_iter: An integer of the maximal number of iterations
sample: A boolean of whether to sample the training data during
search
eval_method: A string of resampling strategy, one of
['auto', 'cv', 'holdout']
split_ratio: A float of the valiation data percentage for holdout
n_splits: An integer of the number of folds for cross-validation
log_type: A string of the log type, one of ['better', 'all', 'new']
'better' only logs configs with better loss than previos iters
'all' logs all the tried configs
'new' only logs non-redundant configs
model_history: A boolean of whether to keep the history of best
models in the history property. Make sure memory is large
enough if setting to True.
log_training_metric: A boolean of whether to log the training
metric for each model.
mem_thres: A float of the memory size constraint in bytes
X_val: None | a numpy array or a pandas dataframe of validation data
y_val: None | a numpy array or a pandas series of validation labels
'''
self.task = task
self._validate_data(X_train, y_train, dataframe, label, X_val, y_val)
self.start_time_flag = time.time()
np.random.seed(0)
self.learner_selector = learner_selector
if self.task == 'classification':
self.task = get_classification_objective(
len(np.unique(self.y_train_all)))
assert split_type in ["stratified", "uniform"]
self.split_type = split_type
else:
self.split_type = "uniform"
if 'auto' == estimator_list:
estimator_list = ['lgbm', 'rf', 'catboost', 'xgboost', 'extra_tree']
if 'regression' != self.task:
estimator_list += ['lrl1', ]
logger.info(
"List of ML learners in AutoML Run: {}".format(estimator_list))
if eval_method == 'auto' or self.X_val is not None:
eval_method = self._decide_eval_method(time_budget)
self.eval_method = eval_method
logger.info("Evaluation method: {}".format(eval_method))
self.retrain_full = retrain_full and (eval_method == 'holdout'
and self.X_val is None)
self.sample = sample and (eval_method != 'cv')
if 'auto' == metric:
if 'binary' in task:
metric = 'roc_auc'
elif 'multi' in task:
metric = 'log_loss'
else:
metric = 'r2'
if metric in ['r2', 'accuracy', 'roc_auc', 'f1', 'ap']:
error_metric = f"1-{metric}"
elif isinstance(metric, str):
error_metric = metric
else:
error_metric = 'customized metric'
logger.info(f'Minimizing error metric: {error_metric}')
with training_log_writer(log_file_name) as save_helper:
self.save_helper = save_helper
self._prepare_data(eval_method, split_ratio, n_splits)
self._compute_with_config = partial(AutoML._compute_with_config_base,
self,
metric,
log_training_metric)
self.time_budget = time_budget
self.estimator_list = estimator_list
self.ensemble = ensemble
self.max_iter = max_iter
self.mem_thres = mem_thres
self.log_type = log_type
self.split_ratio = split_ratio
self.save_model_history = model_history
self.n_jobs = n_jobs
self.search()
logger.info("fit succeeded")
def search(self):
self.searchers = {}
# initialize the searchers
self.eti = []
self._best_loss = float('+inf')
self.best_train_time = 0
self.time_from_start = 0
self.estimator_index = -1
self._best_iteration = 0
self._model_history = {}
self._config_history = {}
self.max_iter_per_learner = 10000 # TODO
self.iter_per_learner = dict([(e, 0) for e in self.estimator_list])
self.fullsize = False
self._trained_estimator = None
if self.ensemble:
self.best_model = {}
for self._track_iter in range(self.max_iter):
if self.estimator_index == -1:
estimator = self.estimator_list[0]
else:
estimator = self._select_estimator(self.estimator_list)
if not estimator:
break
logger.info(f"iteration {self._track_iter}"
f" current learner {estimator}")
if estimator in self.searchers:
model = self.searchers[estimator].trained_estimator
improved = self.searchers[estimator].search1step(
global_best_loss=self._best_loss,
retrain_full=self.retrain_full,
mem_thres=self.mem_thres)
else:
model = improved = None
self.searchers[estimator] = ParamSearch(
estimator,
self.data_size,
self._compute_with_config,
self._train_with_config,
self.save_helper,
MIN_SAMPLE_TRAIN if self.sample else self.data_size,
self.task,
self.log_type,
self._config_space_info.get(estimator),
self._custom_size_estimate.get(estimator),
self.split_ratio)
self.searchers[estimator].search_begin(self.time_budget,
self.start_time_flag)
if self.estimator_index == -1:
eti_base = self._eti_ini[estimator]
self.eti.append(
self.searchers[estimator]
.expected_time_improvement_search())
for e in self.estimator_list[1:]:
self.eti.append(
self._eti_ini[e] / eti_base * self.eti[0])
self.estimator_index = 0
self.time_from_start = time.time() - self.start_time_flag
# logger.info(f"{self.searchers[estimator].sample_size}, {data_size}")
if self.searchers[estimator].sample_size == self.data_size:
self.iter_per_learner[estimator] += 1
if not self.fullsize:
self.fullsize = True
if self.searchers[estimator].best_loss < self._best_loss:
self._best_loss = self.searchers[estimator].best_loss
self._best_estimator = estimator
self.best_train_time = self.searchers[estimator].train_time
self._config_history[self._track_iter] = (
estimator,
self.searchers[estimator].best_config[0],
self.time_from_start)
if self.save_model_history:
self._model_history[self._track_iter] = self.searchers[
estimator].trained_estimator.model
elif self._trained_estimator:
del self._trained_estimator
self._trained_estimator = None
self._trained_estimator = self.searchers[
estimator].trained_estimator
self._best_iteration = self._track_iter
if model and improved and not self.save_model_history:
model.cleanup()
logger.info(
" at {:.1f}s,\tbest {}'s error={:.4f},\tbest {}'s error={:.4f}".format(
self.time_from_start,
estimator,
self.searchers[estimator].best_loss,
self._best_estimator,
self._best_loss))
if self.time_from_start >= self.time_budget:
break
if self.ensemble:
time_left = self.time_from_start - self.time_budget
time_ensemble = self.searchers[self._best_estimator].train_time
if time_left < time_ensemble < 2 * time_left:
break
if self.searchers[
estimator].train_time > self.time_budget - self.time_from_start:
self.iter_per_learner[estimator] = self.max_iter_per_learner
# Add a checkpoint for the current best config to the log.
self.save_helper.checkpoint()
if self.searchers:
self._selected = self.searchers[self._best_estimator]
self._trained_estimator = self._selected.trained_estimator
self.modelcount = sum(self.searchers[estimator].model_count
for estimator in self.searchers)
logger.info(self._trained_estimator.model)
if self.ensemble:
searchers = list(self.searchers.items())
searchers.sort(key=lambda x: x[1].best_loss)
estimators = [(x[0], x[1].trained_estimator) for x in searchers[
:2]]
estimators += [(x[0], x[1].trained_estimator) for x in searchers[
2:] if x[1].best_loss < 4 * self._selected.best_loss]
logger.info(estimators)
if self.task != "regression":
from sklearn.ensemble import StackingClassifier as Stacker
for e in estimators:
e[1]._estimator_type = 'classifier'
else:
from sklearn.ensemble import StackingRegressor as Stacker
best_m = self._trained_estimator
stacker = Stacker(estimators, best_m, n_jobs=self.n_jobs,
passthrough=True)
stacker.fit(self.X_train_all, self.y_train_all)
self._trained_estimator = stacker
self._trained_estimator.model = stacker
else:
self._selected = self._trained_estimator = None
self.modelcount = 0
def __del__(self):
if hasattr(self, '_trained_estimator') and self._trained_estimator \
and hasattr(self._trained_estimator, 'cleanup'):
self._trained_estimator.cleanup()
del self._trained_estimator
def _select_estimator(self, estimator_list):
time_left = self.time_budget - self.time_from_start
if self.best_train_time < time_left < 2 * self.best_train_time:
best_searcher = self.searchers[self._best_estimator]
config_sig = best_searcher.get_hist_config_sig(
best_searcher.sample_size_full,
best_searcher.best_config[0])
if config_sig not in best_searcher.config_tried:
# trainAll
return self._best_estimator
if self.learner_selector == 'roundrobin':
self.estimator_index += 1
if self.estimator_index == len(estimator_list):
self.estimator_index = 0
return estimator_list[self.estimator_index]
min_expected_time, selected = np.Inf, None
inv = []
for i, estimator in enumerate(estimator_list):
if estimator in self.searchers:
searcher = self.searchers[estimator]
if self.iter_per_learner[estimator] >= self.max_iter_per_learner:
inv.append(0)
continue
eti_searcher = min(2 * searcher.train_time,
searcher.expected_time_improvement_search())
gap = searcher.best_loss - self._best_loss
if gap > 0 and not self.ensemble:
delta_loss = searcher.old_loss - searcher.new_loss
delta_time = searcher.old_loss_time + \
searcher.new_loss_time - searcher.old_train_time
speed = delta_loss / float(delta_time)
try:
expected_time = max(gap / speed, searcher.train_time)
except ZeroDivisionError:
warnings.warn("ZeroDivisionError: need to debug ",
"speed: {0}, "
"old_loss: {1}, "
"new_loss: {2}"
.format(speed,
searcher.old_loss,
searcher.new_loss))
expected_time = 0.0
expected_time = 2 * max(expected_time, eti_searcher)
else:
expected_time = eti_searcher
if expected_time == 0:
expected_time = 1e-10
inv.append(1 / expected_time)
else:
expected_time = self.eti[i]
inv.append(0)
if expected_time < min_expected_time:
min_expected_time = expected_time
selected = estimator
if len(self.searchers) < len(estimator_list) or not selected:
if selected not in self.searchers:
# print('select',selected,'eti',min_expected_time)
return selected
s = sum(inv)
p = np.random.random()
q = 0
for i in range(len(inv)):
if inv[i]:
q += inv[i] / s
if p < q:
return estimator_list[i] | 0.798737 | 0.301144 |
import copy
from django.conf import settings
from django.contrib.admin import ModelAdmin
from django.contrib.admin.views.main import ChangeList
from django.forms import ModelForm
from django.contrib import admin
from django.db import models
from suit.widgets import NumberInput, SuitSplitDateTimeWidget
from suit.compat import ct_admin
class SortableModelAdminBase(object):
"""
Base class for SortableTabularInline and SortableModelAdmin
"""
sortable = 'order'
class Media:
js = ('suit/js/sortables.js',)
class SortableListForm(ModelForm):
"""
Just Meta holder class
"""
class Meta:
widgets = {
'order': NumberInput(
attrs={'class': 'hide input-mini suit-sortable'})
}
class SortableChangeList(ChangeList):
"""
Class that forces ordering by sortable param only
"""
def get_ordering(self, request, queryset):
return [self.model_admin.sortable, '-' + self.model._meta.pk.name]
class SortableTabularInlineBase(SortableModelAdminBase):
"""
Sortable tabular inline
"""
def __init__(self, *args, **kwargs):
super(SortableTabularInlineBase, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
self.fields = self.fields or []
if self.fields and self.sortable not in self.fields:
self.fields = list(self.fields) + [self.sortable]
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == self.sortable:
kwargs['widget'] = SortableListForm.Meta.widgets['order']
return super(SortableTabularInlineBase, self).formfield_for_dbfield(
db_field, **kwargs)
class SortableTabularInline(SortableTabularInlineBase, admin.TabularInline):
pass
class SortableGenericTabularInline(SortableTabularInlineBase,
ct_admin.GenericTabularInline):
pass
class SortableStackedInlineBase(SortableModelAdminBase):
"""
Sortable stacked inline
"""
def __init__(self, *args, **kwargs):
super(SortableStackedInlineBase, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
def get_fieldsets(self, *args, **kwargs):
"""
Iterate all fieldsets and make sure sortable is in the first fieldset
Remove sortable from every other fieldset, if by some reason someone
has added it
"""
fieldsets = super(SortableStackedInlineBase, self).get_fieldsets(
*args, **kwargs)
sortable_added = False
for fieldset in fieldsets:
for line in fieldset:
if not line or not isinstance(line, dict):
continue
fields = line.get('fields')
# Some use tuples for fields however they are immutable
if isinstance(fields, tuple):
raise AssertionError(
"The fields attribute of your Inline is a tuple. "
"This must be list as we may need to modify it and "
"tuples are immutable."
)
if self.sortable in fields:
fields.remove(self.sortable)
# Add sortable field always as first
if not sortable_added:
fields.insert(0, self.sortable)
sortable_added = True
break
return fieldsets
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == self.sortable:
kwargs['widget'] = copy.deepcopy(
SortableListForm.Meta.widgets['order'])
kwargs['widget'].attrs['class'] += ' suit-sortable-stacked'
kwargs['widget'].attrs['rowclass'] = ' suit-sortable-stacked-row'
return super(SortableStackedInlineBase, self).formfield_for_dbfield(
db_field, **kwargs)
class SortableStackedInline(SortableStackedInlineBase, admin.StackedInline):
pass
class SortableGenericStackedInline(SortableStackedInlineBase,
ct_admin.GenericStackedInline):
pass
class SortableModelAdmin(SortableModelAdminBase, ModelAdmin):
"""
Sortable tabular inline
"""
list_per_page = 500
def __init__(self, *args, **kwargs):
super(SortableModelAdmin, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
if self.list_display and self.sortable not in self.list_display:
self.list_display = list(self.list_display) + [self.sortable]
self.list_editable = self.list_editable or []
if self.sortable not in self.list_editable:
self.list_editable = list(self.list_editable) + [self.sortable]
self.exclude = self.exclude or []
if self.sortable not in self.exclude:
self.exclude = list(self.exclude) + [self.sortable]
def merge_form_meta(self, form):
"""
Prepare Meta class with order field widget
"""
if not getattr(form, 'Meta', None):
form.Meta = SortableListForm.Meta
if not getattr(form.Meta, 'widgets', None):
form.Meta.widgets = {}
form.Meta.widgets[self.sortable] = SortableListForm.Meta.widgets[
'order']
def get_changelist_form(self, request, **kwargs):
form = super(SortableModelAdmin, self).get_changelist_form(request,
**kwargs)
self.merge_form_meta(form)
return form
def get_changelist(self, request, **kwargs):
return SortableChangeList
def save_model(self, request, obj, form, change):
if not obj.pk:
max_order = obj.__class__.objects.aggregate(
models.Max(self.sortable))
try:
next_order = max_order['%s__max' % self.sortable] + 1
except TypeError:
next_order = 1
setattr(obj, self.sortable, next_order)
super(SortableModelAdmin, self).save_model(request, obj, form, change)
# Quite aggressive detection and intrusion into Django CMS
# Didn't found any other solutions though
if 'cms' in settings.INSTALLED_APPS:
try:
from cms.admin.forms import PageForm
PageForm.Meta.widgets = {
'publication_date': SuitSplitDateTimeWidget,
'publication_end_date': SuitSplitDateTimeWidget,
}
except ImportError:
pass | djangoPharma/env/Lib/site-packages/suit/admin.py | import copy
from django.conf import settings
from django.contrib.admin import ModelAdmin
from django.contrib.admin.views.main import ChangeList
from django.forms import ModelForm
from django.contrib import admin
from django.db import models
from suit.widgets import NumberInput, SuitSplitDateTimeWidget
from suit.compat import ct_admin
class SortableModelAdminBase(object):
"""
Base class for SortableTabularInline and SortableModelAdmin
"""
sortable = 'order'
class Media:
js = ('suit/js/sortables.js',)
class SortableListForm(ModelForm):
"""
Just Meta holder class
"""
class Meta:
widgets = {
'order': NumberInput(
attrs={'class': 'hide input-mini suit-sortable'})
}
class SortableChangeList(ChangeList):
"""
Class that forces ordering by sortable param only
"""
def get_ordering(self, request, queryset):
return [self.model_admin.sortable, '-' + self.model._meta.pk.name]
class SortableTabularInlineBase(SortableModelAdminBase):
"""
Sortable tabular inline
"""
def __init__(self, *args, **kwargs):
super(SortableTabularInlineBase, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
self.fields = self.fields or []
if self.fields and self.sortable not in self.fields:
self.fields = list(self.fields) + [self.sortable]
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == self.sortable:
kwargs['widget'] = SortableListForm.Meta.widgets['order']
return super(SortableTabularInlineBase, self).formfield_for_dbfield(
db_field, **kwargs)
class SortableTabularInline(SortableTabularInlineBase, admin.TabularInline):
pass
class SortableGenericTabularInline(SortableTabularInlineBase,
ct_admin.GenericTabularInline):
pass
class SortableStackedInlineBase(SortableModelAdminBase):
"""
Sortable stacked inline
"""
def __init__(self, *args, **kwargs):
super(SortableStackedInlineBase, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
def get_fieldsets(self, *args, **kwargs):
"""
Iterate all fieldsets and make sure sortable is in the first fieldset
Remove sortable from every other fieldset, if by some reason someone
has added it
"""
fieldsets = super(SortableStackedInlineBase, self).get_fieldsets(
*args, **kwargs)
sortable_added = False
for fieldset in fieldsets:
for line in fieldset:
if not line or not isinstance(line, dict):
continue
fields = line.get('fields')
# Some use tuples for fields however they are immutable
if isinstance(fields, tuple):
raise AssertionError(
"The fields attribute of your Inline is a tuple. "
"This must be list as we may need to modify it and "
"tuples are immutable."
)
if self.sortable in fields:
fields.remove(self.sortable)
# Add sortable field always as first
if not sortable_added:
fields.insert(0, self.sortable)
sortable_added = True
break
return fieldsets
def formfield_for_dbfield(self, db_field, **kwargs):
if db_field.name == self.sortable:
kwargs['widget'] = copy.deepcopy(
SortableListForm.Meta.widgets['order'])
kwargs['widget'].attrs['class'] += ' suit-sortable-stacked'
kwargs['widget'].attrs['rowclass'] = ' suit-sortable-stacked-row'
return super(SortableStackedInlineBase, self).formfield_for_dbfield(
db_field, **kwargs)
class SortableStackedInline(SortableStackedInlineBase, admin.StackedInline):
pass
class SortableGenericStackedInline(SortableStackedInlineBase,
ct_admin.GenericStackedInline):
pass
class SortableModelAdmin(SortableModelAdminBase, ModelAdmin):
"""
Sortable tabular inline
"""
list_per_page = 500
def __init__(self, *args, **kwargs):
super(SortableModelAdmin, self).__init__(*args, **kwargs)
self.ordering = (self.sortable,)
if self.list_display and self.sortable not in self.list_display:
self.list_display = list(self.list_display) + [self.sortable]
self.list_editable = self.list_editable or []
if self.sortable not in self.list_editable:
self.list_editable = list(self.list_editable) + [self.sortable]
self.exclude = self.exclude or []
if self.sortable not in self.exclude:
self.exclude = list(self.exclude) + [self.sortable]
def merge_form_meta(self, form):
"""
Prepare Meta class with order field widget
"""
if not getattr(form, 'Meta', None):
form.Meta = SortableListForm.Meta
if not getattr(form.Meta, 'widgets', None):
form.Meta.widgets = {}
form.Meta.widgets[self.sortable] = SortableListForm.Meta.widgets[
'order']
def get_changelist_form(self, request, **kwargs):
form = super(SortableModelAdmin, self).get_changelist_form(request,
**kwargs)
self.merge_form_meta(form)
return form
def get_changelist(self, request, **kwargs):
return SortableChangeList
def save_model(self, request, obj, form, change):
if not obj.pk:
max_order = obj.__class__.objects.aggregate(
models.Max(self.sortable))
try:
next_order = max_order['%s__max' % self.sortable] + 1
except TypeError:
next_order = 1
setattr(obj, self.sortable, next_order)
super(SortableModelAdmin, self).save_model(request, obj, form, change)
# Quite aggressive detection and intrusion into Django CMS
# Didn't found any other solutions though
if 'cms' in settings.INSTALLED_APPS:
try:
from cms.admin.forms import PageForm
PageForm.Meta.widgets = {
'publication_date': SuitSplitDateTimeWidget,
'publication_end_date': SuitSplitDateTimeWidget,
}
except ImportError:
pass | 0.57093 | 0.142918 |
from unittest.mock import Mock, patch
from homeassistant import config_entries
from homeassistant.components import deconz
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_component
import homeassistant.components.light as light
from tests.common import mock_coro
LIGHT = {
"1": {
"id": "Light 1 id",
"name": "Light 1 name",
"state": {
"on": True, "bri": 255, "colormode": "xy", "xy": (500, 500),
"reachable": True
},
"uniqueid": "00:00:00:00:00:00:00:00-00"
},
"2": {
"id": "Light 2 id",
"name": "Light 2 name",
"state": {
"on": True, "colormode": "ct", "ct": 2500, "reachable": True
}
}
}
GROUP = {
"1": {
"id": "Group 1 id",
"name": "Group 1 name",
"type": "LightGroup",
"state": {},
"action": {},
"scenes": [],
"lights": [
"1",
"2"
],
},
"2": {
"id": "Group 2 id",
"name": "Group 2 name",
"state": {},
"action": {},
"scenes": [],
"lights": [],
},
}
SWITCH = {
"1": {
"id": "Switch 1 id",
"name": "Switch 1 name",
"type": "On/Off plug-in unit",
"state": {}
}
}
ENTRY_CONFIG = {
deconz.const.CONF_ALLOW_CLIP_SENSOR: True,
deconz.const.CONF_ALLOW_DECONZ_GROUPS: True,
deconz.config_flow.CONF_API_KEY: "ABCDEF",
deconz.config_flow.CONF_BRIDGEID: "0123456789",
deconz.config_flow.CONF_HOST: "1.2.3.4",
deconz.config_flow.CONF_PORT: 80
}
async def setup_gateway(hass, data, allow_deconz_groups=True):
"""Load the deCONZ light platform."""
from pydeconz import DeconzSession
loop = Mock()
session = Mock()
ENTRY_CONFIG[deconz.const.CONF_ALLOW_DECONZ_GROUPS] = allow_deconz_groups
config_entry = config_entries.ConfigEntry(
1, deconz.DOMAIN, 'Mock Title', ENTRY_CONFIG, 'test',
config_entries.CONN_CLASS_LOCAL_PUSH)
gateway = deconz.DeconzGateway(hass, config_entry)
gateway.api = DeconzSession(loop, session, **config_entry.data)
gateway.api.config = Mock()
hass.data[deconz.DOMAIN] = {gateway.bridgeid: gateway}
with patch('pydeconz.DeconzSession.async_get_state',
return_value=mock_coro(data)):
await gateway.api.async_load_parameters()
await hass.config_entries.async_forward_entry_setup(config_entry, 'light')
# To flush out the service call to update the group
await hass.async_block_till_done()
return gateway
async def test_platform_manually_configured(hass):
"""Test that we do not discover anything or try to set up a gateway."""
assert await async_setup_component(hass, light.DOMAIN, {
'light': {
'platform': deconz.DOMAIN
}
}) is True
assert deconz.DOMAIN not in hass.data
async def test_no_lights_or_groups(hass):
"""Test that no lights or groups entities are created."""
gateway = await setup_gateway(hass, {})
assert not hass.data[deconz.DOMAIN][gateway.bridgeid].deconz_ids
assert len(hass.states.async_all()) == 0
async def test_lights_and_groups(hass):
"""Test that lights or groups entities are created."""
with patch('pydeconz.DeconzSession.async_put_state',
return_value=mock_coro(True)):
gateway = await setup_gateway(
hass, {"lights": LIGHT, "groups": GROUP})
assert "light.light_1_name" in gateway.deconz_ids
assert "light.light_2_name" in gateway.deconz_ids
assert "light.group_1_name" in gateway.deconz_ids
assert "light.group_2_name" not in gateway.deconz_ids
assert len(hass.states.async_all()) == 4
lamp_1 = hass.states.get('light.light_1_name')
assert lamp_1 is not None
assert lamp_1.state == 'on'
assert lamp_1.attributes['brightness'] == 255
assert lamp_1.attributes['hs_color'] == (224.235, 100.0)
light_2 = hass.states.get('light.light_2_name')
assert light_2 is not None
assert light_2.state == 'on'
assert light_2.attributes['color_temp'] == 2500
gateway.api.lights['1'].async_update({})
await hass.services.async_call('light', 'turn_on', {
'entity_id': 'light.light_1_name',
'color_temp': 2500,
'brightness': 200,
'transition': 5,
'flash': 'short',
'effect': 'colorloop'
}, blocking=True)
await hass.services.async_call('light', 'turn_on', {
'entity_id': 'light.light_1_name',
'hs_color': (20, 30),
'flash': 'long',
'effect': 'None'
}, blocking=True)
await hass.services.async_call('light', 'turn_off', {
'entity_id': 'light.light_1_name',
'transition': 5,
'flash': 'short'
}, blocking=True)
await hass.services.async_call('light', 'turn_off', {
'entity_id': 'light.light_1_name',
'flash': 'long'
}, blocking=True)
async def test_add_new_light(hass):
"""Test successful creation of light entities."""
gateway = await setup_gateway(hass, {})
light = Mock()
light.name = 'name'
light.register_async_callback = Mock()
async_dispatcher_send(
hass, gateway.async_event_new_device('light'), [light])
await hass.async_block_till_done()
assert "light.name" in gateway.deconz_ids
async def test_add_new_group(hass):
"""Test successful creation of group entities."""
gateway = await setup_gateway(hass, {})
group = Mock()
group.name = 'name'
group.register_async_callback = Mock()
async_dispatcher_send(
hass, gateway.async_event_new_device('group'), [group])
await hass.async_block_till_done()
assert "light.name" in gateway.deconz_ids
async def test_do_not_add_deconz_groups(hass):
"""Test that clip sensors can be ignored."""
gateway = await setup_gateway(hass, {}, allow_deconz_groups=False)
group = Mock()
group.name = 'name'
group.register_async_callback = Mock()
async_dispatcher_send(
hass, gateway.async_event_new_device('group'), [group])
await hass.async_block_till_done()
assert len(gateway.deconz_ids) == 0
async def test_no_switch(hass):
"""Test that a switch doesn't get created as a light entity."""
gateway = await setup_gateway(hass, {"lights": SWITCH})
assert len(gateway.deconz_ids) == 0
assert len(hass.states.async_all()) == 0
async def test_unload_light(hass):
"""Test that it works to unload switch entities."""
gateway = await setup_gateway(hass, {"lights": LIGHT, "groups": GROUP})
await gateway.async_reset()
# Group.all_lights will not be removed
assert len(hass.states.async_all()) == 1 | tests/components/deconz/test_light.py | from unittest.mock import Mock, patch
from homeassistant import config_entries
from homeassistant.components import deconz
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_component
import homeassistant.components.light as light
from tests.common import mock_coro
LIGHT = {
"1": {
"id": "Light 1 id",
"name": "Light 1 name",
"state": {
"on": True, "bri": 255, "colormode": "xy", "xy": (500, 500),
"reachable": True
},
"uniqueid": "00:00:00:00:00:00:00:00-00"
},
"2": {
"id": "Light 2 id",
"name": "Light 2 name",
"state": {
"on": True, "colormode": "ct", "ct": 2500, "reachable": True
}
}
}
GROUP = {
"1": {
"id": "Group 1 id",
"name": "Group 1 name",
"type": "LightGroup",
"state": {},
"action": {},
"scenes": [],
"lights": [
"1",
"2"
],
},
"2": {
"id": "Group 2 id",
"name": "Group 2 name",
"state": {},
"action": {},
"scenes": [],
"lights": [],
},
}
SWITCH = {
"1": {
"id": "Switch 1 id",
"name": "Switch 1 name",
"type": "On/Off plug-in unit",
"state": {}
}
}
ENTRY_CONFIG = {
deconz.const.CONF_ALLOW_CLIP_SENSOR: True,
deconz.const.CONF_ALLOW_DECONZ_GROUPS: True,
deconz.config_flow.CONF_API_KEY: "ABCDEF",
deconz.config_flow.CONF_BRIDGEID: "0123456789",
deconz.config_flow.CONF_HOST: "1.2.3.4",
deconz.config_flow.CONF_PORT: 80
}
async def setup_gateway(hass, data, allow_deconz_groups=True):
"""Load the deCONZ light platform."""
from pydeconz import DeconzSession
loop = Mock()
session = Mock()
ENTRY_CONFIG[deconz.const.CONF_ALLOW_DECONZ_GROUPS] = allow_deconz_groups
config_entry = config_entries.ConfigEntry(
1, deconz.DOMAIN, 'Mock Title', ENTRY_CONFIG, 'test',
config_entries.CONN_CLASS_LOCAL_PUSH)
gateway = deconz.DeconzGateway(hass, config_entry)
gateway.api = DeconzSession(loop, session, **config_entry.data)
gateway.api.config = Mock()
hass.data[deconz.DOMAIN] = {gateway.bridgeid: gateway}
with patch('pydeconz.DeconzSession.async_get_state',
return_value=mock_coro(data)):
await gateway.api.async_load_parameters()
await hass.config_entries.async_forward_entry_setup(config_entry, 'light')
# To flush out the service call to update the group
await hass.async_block_till_done()
return gateway
async def test_platform_manually_configured(hass):
"""Test that we do not discover anything or try to set up a gateway."""
assert await async_setup_component(hass, light.DOMAIN, {
'light': {
'platform': deconz.DOMAIN
}
}) is True
assert deconz.DOMAIN not in hass.data
async def test_no_lights_or_groups(hass):
"""Test that no lights or groups entities are created."""
gateway = await setup_gateway(hass, {})
assert not hass.data[deconz.DOMAIN][gateway.bridgeid].deconz_ids
assert len(hass.states.async_all()) == 0
async def test_lights_and_groups(hass):
"""Test that lights or groups entities are created."""
with patch('pydeconz.DeconzSession.async_put_state',
return_value=mock_coro(True)):
gateway = await setup_gateway(
hass, {"lights": LIGHT, "groups": GROUP})
assert "light.light_1_name" in gateway.deconz_ids
assert "light.light_2_name" in gateway.deconz_ids
assert "light.group_1_name" in gateway.deconz_ids
assert "light.group_2_name" not in gateway.deconz_ids
assert len(hass.states.async_all()) == 4
lamp_1 = hass.states.get('light.light_1_name')
assert lamp_1 is not None
assert lamp_1.state == 'on'
assert lamp_1.attributes['brightness'] == 255
assert lamp_1.attributes['hs_color'] == (224.235, 100.0)
light_2 = hass.states.get('light.light_2_name')
assert light_2 is not None
assert light_2.state == 'on'
assert light_2.attributes['color_temp'] == 2500
gateway.api.lights['1'].async_update({})
await hass.services.async_call('light', 'turn_on', {
'entity_id': 'light.light_1_name',
'color_temp': 2500,
'brightness': 200,
'transition': 5,
'flash': 'short',
'effect': 'colorloop'
}, blocking=True)
await hass.services.async_call('light', 'turn_on', {
'entity_id': 'light.light_1_name',
'hs_color': (20, 30),
'flash': 'long',
'effect': 'None'
}, blocking=True)
await hass.services.async_call('light', 'turn_off', {
'entity_id': 'light.light_1_name',
'transition': 5,
'flash': 'short'
}, blocking=True)
await hass.services.async_call('light', 'turn_off', {
'entity_id': 'light.light_1_name',
'flash': 'long'
}, blocking=True)
async def test_add_new_light(hass):
"""Test successful creation of light entities."""
gateway = await setup_gateway(hass, {})
light = Mock()
light.name = 'name'
light.register_async_callback = Mock()
async_dispatcher_send(
hass, gateway.async_event_new_device('light'), [light])
await hass.async_block_till_done()
assert "light.name" in gateway.deconz_ids
async def test_add_new_group(hass):
"""Test successful creation of group entities."""
gateway = await setup_gateway(hass, {})
group = Mock()
group.name = 'name'
group.register_async_callback = Mock()
async_dispatcher_send(
hass, gateway.async_event_new_device('group'), [group])
await hass.async_block_till_done()
assert "light.name" in gateway.deconz_ids
async def test_do_not_add_deconz_groups(hass):
"""Test that clip sensors can be ignored."""
gateway = await setup_gateway(hass, {}, allow_deconz_groups=False)
group = Mock()
group.name = 'name'
group.register_async_callback = Mock()
async_dispatcher_send(
hass, gateway.async_event_new_device('group'), [group])
await hass.async_block_till_done()
assert len(gateway.deconz_ids) == 0
async def test_no_switch(hass):
"""Test that a switch doesn't get created as a light entity."""
gateway = await setup_gateway(hass, {"lights": SWITCH})
assert len(gateway.deconz_ids) == 0
assert len(hass.states.async_all()) == 0
async def test_unload_light(hass):
"""Test that it works to unload switch entities."""
gateway = await setup_gateway(hass, {"lights": LIGHT, "groups": GROUP})
await gateway.async_reset()
# Group.all_lights will not be removed
assert len(hass.states.async_all()) == 1 | 0.70791 | 0.477981 |
from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 843493331
"""
"""
random actions, total chaos
"""
board = gamma_new(6, 5, 4, 4)
assert board is not None
assert gamma_move(board, 1, 1, 3) == 1
assert gamma_move(board, 1, 1, 0) == 1
assert gamma_move(board, 2, 0, 1) == 1
assert gamma_move(board, 3, 2, 2) == 1
assert gamma_move(board, 3, 3, 2) == 1
assert gamma_move(board, 4, 3, 2) == 0
assert gamma_move(board, 1, 2, 2) == 0
assert gamma_free_fields(board, 1) == 25
assert gamma_move(board, 2, 0, 2) == 1
assert gamma_golden_possible(board, 2) == 1
assert gamma_move(board, 3, 3, 3) == 1
assert gamma_move(board, 3, 5, 2) == 1
assert gamma_move(board, 4, 1, 1) == 1
assert gamma_free_fields(board, 4) == 21
assert gamma_golden_possible(board, 4) == 1
assert gamma_move(board, 1, 1, 3) == 0
assert gamma_move(board, 2, 0, 4) == 1
assert gamma_golden_move(board, 2, 1, 1) == 1
assert gamma_move(board, 3, 3, 2) == 0
assert gamma_move(board, 4, 0, 4) == 0
assert gamma_free_fields(board, 4) == 20
assert gamma_move(board, 1, 1, 4) == 1
assert gamma_move(board, 1, 2, 1) == 1
board131071533 = gamma_board(board)
assert board131071533 is not None
assert board131071533 == ("21....\n"
".1.3..\n"
"2.33.3\n"
"221...\n"
".1....\n")
del board131071533
board131071533 = None
assert gamma_move(board, 2, 0, 2) == 0
assert gamma_move(board, 2, 2, 3) == 1
assert gamma_move(board, 3, 4, 2) == 1
assert gamma_move(board, 3, 1, 0) == 0
assert gamma_move(board, 4, 2, 1) == 0
assert gamma_move(board, 4, 3, 1) == 1
board186937087 = gamma_board(board)
assert board186937087 is not None
assert board186937087 == ("21....\n"
".123..\n"
"2.3333\n"
"2214..\n"
".1....\n")
del board186937087
board186937087 = None
assert gamma_move(board, 1, 4, 4) == 1
assert gamma_move(board, 1, 0, 3) == 1
assert gamma_busy_fields(board, 1) == 6
assert gamma_move(board, 2, 2, 3) == 0
assert gamma_move(board, 3, 1, 0) == 0
assert gamma_move(board, 4, 0, 3) == 0
assert gamma_move(board, 1, 3, 1) == 0
assert gamma_move(board, 1, 4, 3) == 1
assert gamma_move(board, 4, 2, 4) == 1
assert gamma_move(board, 1, 1, 3) == 0
assert gamma_golden_move(board, 1, 3, 3) == 1
board311133873 = gamma_board(board)
assert board311133873 is not None
assert board311133873 == ("214.1.\n"
"11211.\n"
"2.3333\n"
"2214..\n"
".1....\n")
del board311133873
board311133873 = None
assert gamma_move(board, 2, 5, 2) == 0
assert gamma_move(board, 3, 4, 1) == 1
assert gamma_move(board, 3, 3, 4) == 1
assert gamma_busy_fields(board, 3) == 6
assert gamma_move(board, 4, 4, 5) == 0
assert gamma_move(board, 4, 4, 1) == 0
assert gamma_busy_fields(board, 4) == 2
assert gamma_move(board, 1, 0, 1) == 0
assert gamma_move(board, 2, 3, 5) == 0
assert gamma_free_fields(board, 2) == 9
assert gamma_move(board, 3, 4, 5) == 0
assert gamma_move(board, 3, 5, 0) == 1
assert gamma_move(board, 4, 4, 5) == 0
assert gamma_move(board, 4, 5, 3) == 1
assert gamma_golden_move(board, 4, 2, 0) == 0
assert gamma_move(board, 1, 0, 0) == 1
assert gamma_move(board, 1, 1, 4) == 0
assert gamma_golden_move(board, 1, 1, 3) == 0
assert gamma_move(board, 2, 5, 0) == 0
assert gamma_move(board, 3, 1, 2) == 1
assert gamma_move(board, 3, 3, 1) == 0
assert gamma_golden_possible(board, 3) == 1
assert gamma_busy_fields(board, 4) == 3
assert gamma_move(board, 1, 4, 2) == 0
assert gamma_move(board, 2, 1, 1) == 0
assert gamma_golden_move(board, 2, 0, 1) == 0
assert gamma_move(board, 3, 3, 2) == 0
assert gamma_move(board, 3, 2, 0) == 1
assert gamma_move(board, 4, 0, 3) == 0
assert gamma_move(board, 4, 2, 0) == 0
board535852884 = gamma_board(board)
assert board535852884 is not None
assert board535852884 == ("21431.\n"
"112114\n"
"233333\n"
"22143.\n"
"113..3\n")
del board535852884
board535852884 = None
assert gamma_move(board, 1, 0, 3) == 0
assert gamma_move(board, 1, 3, 1) == 0
board883157248 = gamma_board(board)
assert board883157248 is not None
assert board883157248 == ("21431.\n"
"112114\n"
"233333\n"
"22143.\n"
"113..3\n")
del board883157248
board883157248 = None
assert gamma_move(board, 3, 1, 5) == 0
assert gamma_move(board, 3, 0, 4) == 0
assert gamma_golden_possible(board, 3) == 1
assert gamma_move(board, 4, 4, 5) == 0
assert gamma_move(board, 1, 1, 1) == 0
assert gamma_move(board, 2, 1, 2) == 0
assert gamma_busy_fields(board, 2) == 5
assert gamma_free_fields(board, 2) == 4
assert gamma_golden_possible(board, 2) == 0
assert gamma_move(board, 3, 2, 3) == 0
assert gamma_move(board, 4, 0, 3) == 0
assert gamma_golden_move(board, 4, 4, 3) == 0
assert gamma_move(board, 1, 4, 5) == 0
assert gamma_move(board, 2, 5, 0) == 0
assert gamma_move(board, 3, 1, 3) == 0
assert gamma_move(board, 4, 0, 4) == 0
assert gamma_move(board, 1, 0, 3) == 0
assert gamma_move(board, 1, 2, 0) == 0
assert gamma_golden_possible(board, 1) == 0
assert gamma_move(board, 2, 4, 4) == 0
assert gamma_move(board, 3, 0, 4) == 0
assert gamma_busy_fields(board, 3) == 9
assert gamma_busy_fields(board, 1) == 9
assert gamma_free_fields(board, 1) == 1
assert gamma_move(board, 2, 3, 0) == 1
assert gamma_move(board, 3, 2, 4) == 0
assert gamma_move(board, 3, 3, 2) == 0
assert gamma_move(board, 4, 2, 3) == 0
assert gamma_free_fields(board, 4) == 3
gamma_delete(board) | z2/part2/interactive/jm/random_fuzzy_arrows_1/843493331.py | from part1 import (
gamma_board,
gamma_busy_fields,
gamma_delete,
gamma_free_fields,
gamma_golden_move,
gamma_golden_possible,
gamma_move,
gamma_new,
)
"""
scenario: test_random_actions
uuid: 843493331
"""
"""
random actions, total chaos
"""
board = gamma_new(6, 5, 4, 4)
assert board is not None
assert gamma_move(board, 1, 1, 3) == 1
assert gamma_move(board, 1, 1, 0) == 1
assert gamma_move(board, 2, 0, 1) == 1
assert gamma_move(board, 3, 2, 2) == 1
assert gamma_move(board, 3, 3, 2) == 1
assert gamma_move(board, 4, 3, 2) == 0
assert gamma_move(board, 1, 2, 2) == 0
assert gamma_free_fields(board, 1) == 25
assert gamma_move(board, 2, 0, 2) == 1
assert gamma_golden_possible(board, 2) == 1
assert gamma_move(board, 3, 3, 3) == 1
assert gamma_move(board, 3, 5, 2) == 1
assert gamma_move(board, 4, 1, 1) == 1
assert gamma_free_fields(board, 4) == 21
assert gamma_golden_possible(board, 4) == 1
assert gamma_move(board, 1, 1, 3) == 0
assert gamma_move(board, 2, 0, 4) == 1
assert gamma_golden_move(board, 2, 1, 1) == 1
assert gamma_move(board, 3, 3, 2) == 0
assert gamma_move(board, 4, 0, 4) == 0
assert gamma_free_fields(board, 4) == 20
assert gamma_move(board, 1, 1, 4) == 1
assert gamma_move(board, 1, 2, 1) == 1
board131071533 = gamma_board(board)
assert board131071533 is not None
assert board131071533 == ("21....\n"
".1.3..\n"
"2.33.3\n"
"221...\n"
".1....\n")
del board131071533
board131071533 = None
assert gamma_move(board, 2, 0, 2) == 0
assert gamma_move(board, 2, 2, 3) == 1
assert gamma_move(board, 3, 4, 2) == 1
assert gamma_move(board, 3, 1, 0) == 0
assert gamma_move(board, 4, 2, 1) == 0
assert gamma_move(board, 4, 3, 1) == 1
board186937087 = gamma_board(board)
assert board186937087 is not None
assert board186937087 == ("21....\n"
".123..\n"
"2.3333\n"
"2214..\n"
".1....\n")
del board186937087
board186937087 = None
assert gamma_move(board, 1, 4, 4) == 1
assert gamma_move(board, 1, 0, 3) == 1
assert gamma_busy_fields(board, 1) == 6
assert gamma_move(board, 2, 2, 3) == 0
assert gamma_move(board, 3, 1, 0) == 0
assert gamma_move(board, 4, 0, 3) == 0
assert gamma_move(board, 1, 3, 1) == 0
assert gamma_move(board, 1, 4, 3) == 1
assert gamma_move(board, 4, 2, 4) == 1
assert gamma_move(board, 1, 1, 3) == 0
assert gamma_golden_move(board, 1, 3, 3) == 1
board311133873 = gamma_board(board)
assert board311133873 is not None
assert board311133873 == ("214.1.\n"
"11211.\n"
"2.3333\n"
"2214..\n"
".1....\n")
del board311133873
board311133873 = None
assert gamma_move(board, 2, 5, 2) == 0
assert gamma_move(board, 3, 4, 1) == 1
assert gamma_move(board, 3, 3, 4) == 1
assert gamma_busy_fields(board, 3) == 6
assert gamma_move(board, 4, 4, 5) == 0
assert gamma_move(board, 4, 4, 1) == 0
assert gamma_busy_fields(board, 4) == 2
assert gamma_move(board, 1, 0, 1) == 0
assert gamma_move(board, 2, 3, 5) == 0
assert gamma_free_fields(board, 2) == 9
assert gamma_move(board, 3, 4, 5) == 0
assert gamma_move(board, 3, 5, 0) == 1
assert gamma_move(board, 4, 4, 5) == 0
assert gamma_move(board, 4, 5, 3) == 1
assert gamma_golden_move(board, 4, 2, 0) == 0
assert gamma_move(board, 1, 0, 0) == 1
assert gamma_move(board, 1, 1, 4) == 0
assert gamma_golden_move(board, 1, 1, 3) == 0
assert gamma_move(board, 2, 5, 0) == 0
assert gamma_move(board, 3, 1, 2) == 1
assert gamma_move(board, 3, 3, 1) == 0
assert gamma_golden_possible(board, 3) == 1
assert gamma_busy_fields(board, 4) == 3
assert gamma_move(board, 1, 4, 2) == 0
assert gamma_move(board, 2, 1, 1) == 0
assert gamma_golden_move(board, 2, 0, 1) == 0
assert gamma_move(board, 3, 3, 2) == 0
assert gamma_move(board, 3, 2, 0) == 1
assert gamma_move(board, 4, 0, 3) == 0
assert gamma_move(board, 4, 2, 0) == 0
board535852884 = gamma_board(board)
assert board535852884 is not None
assert board535852884 == ("21431.\n"
"112114\n"
"233333\n"
"22143.\n"
"113..3\n")
del board535852884
board535852884 = None
assert gamma_move(board, 1, 0, 3) == 0
assert gamma_move(board, 1, 3, 1) == 0
board883157248 = gamma_board(board)
assert board883157248 is not None
assert board883157248 == ("21431.\n"
"112114\n"
"233333\n"
"22143.\n"
"113..3\n")
del board883157248
board883157248 = None
assert gamma_move(board, 3, 1, 5) == 0
assert gamma_move(board, 3, 0, 4) == 0
assert gamma_golden_possible(board, 3) == 1
assert gamma_move(board, 4, 4, 5) == 0
assert gamma_move(board, 1, 1, 1) == 0
assert gamma_move(board, 2, 1, 2) == 0
assert gamma_busy_fields(board, 2) == 5
assert gamma_free_fields(board, 2) == 4
assert gamma_golden_possible(board, 2) == 0
assert gamma_move(board, 3, 2, 3) == 0
assert gamma_move(board, 4, 0, 3) == 0
assert gamma_golden_move(board, 4, 4, 3) == 0
assert gamma_move(board, 1, 4, 5) == 0
assert gamma_move(board, 2, 5, 0) == 0
assert gamma_move(board, 3, 1, 3) == 0
assert gamma_move(board, 4, 0, 4) == 0
assert gamma_move(board, 1, 0, 3) == 0
assert gamma_move(board, 1, 2, 0) == 0
assert gamma_golden_possible(board, 1) == 0
assert gamma_move(board, 2, 4, 4) == 0
assert gamma_move(board, 3, 0, 4) == 0
assert gamma_busy_fields(board, 3) == 9
assert gamma_busy_fields(board, 1) == 9
assert gamma_free_fields(board, 1) == 1
assert gamma_move(board, 2, 3, 0) == 1
assert gamma_move(board, 3, 2, 4) == 0
assert gamma_move(board, 3, 3, 2) == 0
assert gamma_move(board, 4, 2, 3) == 0
assert gamma_free_fields(board, 4) == 3
gamma_delete(board) | 0.760562 | 0.8874 |
from datamart.materializers.materializer_base import MaterializerBase
import pandas as pd
import typing
import sys
import traceback
import datetime
class TradingEconomicsMarketMaterializer(MaterializerBase):
"""TradingEconomicsMaterializer class extended from Materializer class
"""
def __init__(self, **kwargs):
""" initialization and loading the city name to city id map
"""
MaterializerBase.__init__(self, **kwargs)
self.key = None
def get(self,
metadata: dict = None,
constrains: dict = None
) -> typing.Optional[pd.DataFrame]:
""" API for get a dataframe.
Args:
metadata: json schema for data_type
variables:
constrains: include some constrains like date_range, location and so on
Assuming date is in the format %Y-%m-%d
"""
if not constrains:
constrains = dict()
getUrl = metadata['url']
if "key" in constrains:
self.key = {"key": constrains["key"]}
else:
self.headers = {"key": "guest:guest"}
date_range = constrains.get("date_range", {})
datestr = ""
if date_range.get("start", None) and date_range.get("end", None):
datestr += "d1=" + date_range["start"]
datestr += '&d2=' + date_range["end"]
elif date_range.get("start", None):
datestr += "d1=" + date_range["start"]
now = datetime.datetime.now()
datestr += '&d2=' + "{}-{}-{}".format(now.year, now.month, now.day)
elif date_range.get("end", None):
datestr += "d1=" + "{}-{}-{}".format("1800", "01", "01")
datestr += '&d2=' + date_range["end"]
else:
now = datetime.datetime.now()
datestr += "d1=" + "{}-{}-{}".format("1800", "01", "01")
datestr += '&d2=' + "{}-{}-{}".format(now.year, now.month, now.day)
path = getUrl.split("&")
path[1] = datestr
getUrl = "&".join(path)
datasetConfig = {
"where_to_download": {
"frequency": "quarterly",
"method": "get",
"file_type": "csv",
"template": getUrl,
"replication": {
},
"identifier": metadata['title'].replace(' ', '_')
},
}
return self.fetch_data(getUrl, datasetConfig)
def fetch_data(self, getUrl, datasetConfig):
"""
Returns:
result: A pd.DataFrame;
"""
try:
data = pd.read_csv(getUrl, encoding='utf-16')
return data
except Exception as e:
print('exception in run', e)
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print(''.join(lines)) | datamart/materializers/tradingeconomics_market_materializer.py | from datamart.materializers.materializer_base import MaterializerBase
import pandas as pd
import typing
import sys
import traceback
import datetime
class TradingEconomicsMarketMaterializer(MaterializerBase):
"""TradingEconomicsMaterializer class extended from Materializer class
"""
def __init__(self, **kwargs):
""" initialization and loading the city name to city id map
"""
MaterializerBase.__init__(self, **kwargs)
self.key = None
def get(self,
metadata: dict = None,
constrains: dict = None
) -> typing.Optional[pd.DataFrame]:
""" API for get a dataframe.
Args:
metadata: json schema for data_type
variables:
constrains: include some constrains like date_range, location and so on
Assuming date is in the format %Y-%m-%d
"""
if not constrains:
constrains = dict()
getUrl = metadata['url']
if "key" in constrains:
self.key = {"key": constrains["key"]}
else:
self.headers = {"key": "guest:guest"}
date_range = constrains.get("date_range", {})
datestr = ""
if date_range.get("start", None) and date_range.get("end", None):
datestr += "d1=" + date_range["start"]
datestr += '&d2=' + date_range["end"]
elif date_range.get("start", None):
datestr += "d1=" + date_range["start"]
now = datetime.datetime.now()
datestr += '&d2=' + "{}-{}-{}".format(now.year, now.month, now.day)
elif date_range.get("end", None):
datestr += "d1=" + "{}-{}-{}".format("1800", "01", "01")
datestr += '&d2=' + date_range["end"]
else:
now = datetime.datetime.now()
datestr += "d1=" + "{}-{}-{}".format("1800", "01", "01")
datestr += '&d2=' + "{}-{}-{}".format(now.year, now.month, now.day)
path = getUrl.split("&")
path[1] = datestr
getUrl = "&".join(path)
datasetConfig = {
"where_to_download": {
"frequency": "quarterly",
"method": "get",
"file_type": "csv",
"template": getUrl,
"replication": {
},
"identifier": metadata['title'].replace(' ', '_')
},
}
return self.fetch_data(getUrl, datasetConfig)
def fetch_data(self, getUrl, datasetConfig):
"""
Returns:
result: A pd.DataFrame;
"""
try:
data = pd.read_csv(getUrl, encoding='utf-16')
return data
except Exception as e:
print('exception in run', e)
exc_type, exc_value, exc_traceback = sys.exc_info()
lines = traceback.format_exception(exc_type, exc_value, exc_traceback)
print(''.join(lines)) | 0.616936 | 0.184143 |
import argparse
import serrant
def main():
# Parse command line args
args = parse_args()
print("Loading resources...")
# Load Errant
annotator = serrant.load("en")
# Open output M2 file
out_m2 = open(args.out, "w")
print("Processing M2 file...")
# Open the m2 file and split it into text+edit blocks
m2 = open(args.m2_file).read().strip().split("\n\n")
# Loop through the blocks
for m2_block in m2:
m2_block = m2_block.strip().split("\n")
# Write the original text to the output M2 file
out_m2.write(m2_block[0]+"\n")
# Parse orig with spacy
orig = annotator.parse(m2_block[0][2:])
# Simplify the edits and sort by coder id
edit_dict = simplify_edits(m2_block[1:])
# Loop through coder ids
for id, raw_edits in sorted(edit_dict.items()):
# If the first edit is a noop
if raw_edits[0][2] == "noop":
# Write the noop and continue
out_m2.write(noop_edit(id)+"\n")
continue
# Apply the edits to generate the corrected text
# Also redefine the edits as orig and cor token offsets
cor, gold_edits = get_cor_and_edits(m2_block[0][2:], raw_edits)
# Parse cor with spacy
cor = annotator.parse(cor)
# Save detection edits here for auto
det_edits = []
# Loop through the gold edits
for gold_edit in gold_edits:
# Do not minimise detection edits
if gold_edit[-2] in {"Um", "UNK"}:
edit = annotator.import_edit(orig, cor, gold_edit[:-1],
min=False, old_cat=args.old_cats, annotator=args.annotator)
# Overwrite the pseudo correction and set it in the edit
edit.c_toks = annotator.parse(gold_edit[-1])
# Save the edit for auto
det_edits.append(edit)
# Write the edit for gold
if args.gold:
# Write the edit
out_m2.write(edit.to_m2(id)+"\n")
# Gold annotation
elif args.gold:
edit = annotator.import_edit(orig, cor, gold_edit[:-1],
not args.no_min, args.old_cats, annotator=args.annotator)
# Write the edit
out_m2.write(edit.to_m2(id)+"\n")
# Auto annotations
if args.auto:
# Auto edits
edits = annotator.annotate(orig, cor, args.lev, args.merge, args.annotator)
# Combine detection and auto edits and sort by orig offsets
edits = sorted(det_edits+edits, key=lambda e:(e.o_start, e.o_end))
# Write the edits to the output M2 file
for edit in edits:
out_m2.write(edit.to_m2(id)+"\n")
# Write a newline when there are no more edits
out_m2.write("\n")
# Parse command line args
def parse_args():
parser = argparse.ArgumentParser(
description = "Automatically extract and/or classify edits in an m2 file.",
formatter_class = argparse.RawTextHelpFormatter,
usage = "%(prog)s [-h] (-auto | -gold) [options] m2_file -out OUT")
parser.add_argument(
"m2_file",
help = "The path to an m2 file.")
type_group = parser.add_mutually_exclusive_group(required = True)
type_group.add_argument(
"-auto",
help = "Extract edits automatically.",
action = "store_true")
type_group.add_argument(
"-gold",
help = "Use existing edit alignments.",
action = "store_true")
parser.add_argument(
"-out",
help = "The output filepath.",
required = True)
parser.add_argument(
"-no_min",
help = "Do not minimise edit spans (gold only).",
action = "store_true")
parser.add_argument(
"-old_cats",
help = "Preserve old error types (gold only); i.e. turn off the classifier.",
action = "store_true")
parser.add_argument(
"-lev",
help = "Align using standard Levenshtein.",
action = "store_true")
parser.add_argument(
"-merge",
help = "Choose a merging strategy for automatic alignment.\n"
"rules: Use a rule-based merging strategy (default)\n"
"all-split: Merge nothing: MSSDI -> M, S, S, D, I\n"
"all-merge: Merge adjacent non-matches: MSSDI -> M, SSDI\n"
"all-equal: Merge adjacent same-type non-matches: MSSDI -> M, SS, D, I",
choices = ["rules", "all-split", "all-merge", "all-equal"],
default = "rules")
parser.add_argument(
"-annotator",
help="Choose the classifier for the annotation.\n"
"errant: original rules of errant.\n"
"sercl: pure syntactic annotation.\n"
"combined: rule-based combining of errant and sercl",
choices=["errant", "sercl", "combined"],
default="combined")
args = parser.parse_args()
return args
# Input: A list of edit lines from an m2 file
# Output: An edit dictionary; key is coder id, value is a list of edits
def simplify_edits(edits):
edit_dict = {}
for edit in edits:
edit = edit.split("|||")
span = edit[0][2:].split() # [2:] ignore the leading "A "
start = int(span[0])
end = int(span[1])
cat = edit[1]
cor = edit[2]
id = edit[-1]
# Save the useful info as a list
proc_edit = [start, end, cat, cor]
# Save the proc_edit inside the edit_dict using coder id
if id in edit_dict.keys():
edit_dict[id].append(proc_edit)
else:
edit_dict[id] = [proc_edit]
return edit_dict
# Input 1: A tokenised original text string
# Input 2: A list of edits; [o_start, o_end, cat, cor]
# Output 1: A tokenised corrected text string
# Output 2: A list of edits; [o_start, o_end, c_start, c_end, cat, cor]
def get_cor_and_edits(orig, edits):
# Copy orig; we will apply edits to it to make cor
cor = orig.split()
new_edits = []
offset = 0
# Sort the edits by offsets before processing them
edits = sorted(edits, key=lambda e:(e[0], e[1]))
# Loop through edits: [o_start, o_end, cat, cor_str]
for edit in edits:
o_start = edit[0]
o_end = edit[1]
cat = edit[2]
cor_toks = edit[3].split()
# Detection edits
if cat in {"Um", "UNK"}:
# Save the pseudo correction
det_toks = cor_toks[:]
# But temporarily overwrite it to be the same as orig
cor_toks = orig.split()[o_start:o_end]
# Apply the edits
cor[o_start+offset:o_end+offset] = cor_toks
# Get the cor token start and end offsets in cor
c_start = o_start+offset
c_end = c_start+len(cor_toks)
# Keep track of how this affects orig edit offsets
offset = offset-(o_end-o_start)+len(cor_toks)
# Detection edits: Restore the pseudo correction
if cat in {"Um", "UNK"}: cor_toks = det_toks
# Update the edit with cor span and save
new_edit = [o_start, o_end, c_start, c_end, cat, " ".join(cor_toks)]
new_edits.append(new_edit)
return " ".join(cor), new_edits
# Input: A coder id
# Output: A noop edit; i.e. text contains no edits
def noop_edit(id=0):
return "A -1 -1|||noop|||-NONE-|||REQUIRED|||-NONE-|||"+str(id) | serrant/commands/m2_to_m2.py | import argparse
import serrant
def main():
# Parse command line args
args = parse_args()
print("Loading resources...")
# Load Errant
annotator = serrant.load("en")
# Open output M2 file
out_m2 = open(args.out, "w")
print("Processing M2 file...")
# Open the m2 file and split it into text+edit blocks
m2 = open(args.m2_file).read().strip().split("\n\n")
# Loop through the blocks
for m2_block in m2:
m2_block = m2_block.strip().split("\n")
# Write the original text to the output M2 file
out_m2.write(m2_block[0]+"\n")
# Parse orig with spacy
orig = annotator.parse(m2_block[0][2:])
# Simplify the edits and sort by coder id
edit_dict = simplify_edits(m2_block[1:])
# Loop through coder ids
for id, raw_edits in sorted(edit_dict.items()):
# If the first edit is a noop
if raw_edits[0][2] == "noop":
# Write the noop and continue
out_m2.write(noop_edit(id)+"\n")
continue
# Apply the edits to generate the corrected text
# Also redefine the edits as orig and cor token offsets
cor, gold_edits = get_cor_and_edits(m2_block[0][2:], raw_edits)
# Parse cor with spacy
cor = annotator.parse(cor)
# Save detection edits here for auto
det_edits = []
# Loop through the gold edits
for gold_edit in gold_edits:
# Do not minimise detection edits
if gold_edit[-2] in {"Um", "UNK"}:
edit = annotator.import_edit(orig, cor, gold_edit[:-1],
min=False, old_cat=args.old_cats, annotator=args.annotator)
# Overwrite the pseudo correction and set it in the edit
edit.c_toks = annotator.parse(gold_edit[-1])
# Save the edit for auto
det_edits.append(edit)
# Write the edit for gold
if args.gold:
# Write the edit
out_m2.write(edit.to_m2(id)+"\n")
# Gold annotation
elif args.gold:
edit = annotator.import_edit(orig, cor, gold_edit[:-1],
not args.no_min, args.old_cats, annotator=args.annotator)
# Write the edit
out_m2.write(edit.to_m2(id)+"\n")
# Auto annotations
if args.auto:
# Auto edits
edits = annotator.annotate(orig, cor, args.lev, args.merge, args.annotator)
# Combine detection and auto edits and sort by orig offsets
edits = sorted(det_edits+edits, key=lambda e:(e.o_start, e.o_end))
# Write the edits to the output M2 file
for edit in edits:
out_m2.write(edit.to_m2(id)+"\n")
# Write a newline when there are no more edits
out_m2.write("\n")
# Parse command line args
def parse_args():
parser = argparse.ArgumentParser(
description = "Automatically extract and/or classify edits in an m2 file.",
formatter_class = argparse.RawTextHelpFormatter,
usage = "%(prog)s [-h] (-auto | -gold) [options] m2_file -out OUT")
parser.add_argument(
"m2_file",
help = "The path to an m2 file.")
type_group = parser.add_mutually_exclusive_group(required = True)
type_group.add_argument(
"-auto",
help = "Extract edits automatically.",
action = "store_true")
type_group.add_argument(
"-gold",
help = "Use existing edit alignments.",
action = "store_true")
parser.add_argument(
"-out",
help = "The output filepath.",
required = True)
parser.add_argument(
"-no_min",
help = "Do not minimise edit spans (gold only).",
action = "store_true")
parser.add_argument(
"-old_cats",
help = "Preserve old error types (gold only); i.e. turn off the classifier.",
action = "store_true")
parser.add_argument(
"-lev",
help = "Align using standard Levenshtein.",
action = "store_true")
parser.add_argument(
"-merge",
help = "Choose a merging strategy for automatic alignment.\n"
"rules: Use a rule-based merging strategy (default)\n"
"all-split: Merge nothing: MSSDI -> M, S, S, D, I\n"
"all-merge: Merge adjacent non-matches: MSSDI -> M, SSDI\n"
"all-equal: Merge adjacent same-type non-matches: MSSDI -> M, SS, D, I",
choices = ["rules", "all-split", "all-merge", "all-equal"],
default = "rules")
parser.add_argument(
"-annotator",
help="Choose the classifier for the annotation.\n"
"errant: original rules of errant.\n"
"sercl: pure syntactic annotation.\n"
"combined: rule-based combining of errant and sercl",
choices=["errant", "sercl", "combined"],
default="combined")
args = parser.parse_args()
return args
# Input: A list of edit lines from an m2 file
# Output: An edit dictionary; key is coder id, value is a list of edits
def simplify_edits(edits):
edit_dict = {}
for edit in edits:
edit = edit.split("|||")
span = edit[0][2:].split() # [2:] ignore the leading "A "
start = int(span[0])
end = int(span[1])
cat = edit[1]
cor = edit[2]
id = edit[-1]
# Save the useful info as a list
proc_edit = [start, end, cat, cor]
# Save the proc_edit inside the edit_dict using coder id
if id in edit_dict.keys():
edit_dict[id].append(proc_edit)
else:
edit_dict[id] = [proc_edit]
return edit_dict
# Input 1: A tokenised original text string
# Input 2: A list of edits; [o_start, o_end, cat, cor]
# Output 1: A tokenised corrected text string
# Output 2: A list of edits; [o_start, o_end, c_start, c_end, cat, cor]
def get_cor_and_edits(orig, edits):
# Copy orig; we will apply edits to it to make cor
cor = orig.split()
new_edits = []
offset = 0
# Sort the edits by offsets before processing them
edits = sorted(edits, key=lambda e:(e[0], e[1]))
# Loop through edits: [o_start, o_end, cat, cor_str]
for edit in edits:
o_start = edit[0]
o_end = edit[1]
cat = edit[2]
cor_toks = edit[3].split()
# Detection edits
if cat in {"Um", "UNK"}:
# Save the pseudo correction
det_toks = cor_toks[:]
# But temporarily overwrite it to be the same as orig
cor_toks = orig.split()[o_start:o_end]
# Apply the edits
cor[o_start+offset:o_end+offset] = cor_toks
# Get the cor token start and end offsets in cor
c_start = o_start+offset
c_end = c_start+len(cor_toks)
# Keep track of how this affects orig edit offsets
offset = offset-(o_end-o_start)+len(cor_toks)
# Detection edits: Restore the pseudo correction
if cat in {"Um", "UNK"}: cor_toks = det_toks
# Update the edit with cor span and save
new_edit = [o_start, o_end, c_start, c_end, cat, " ".join(cor_toks)]
new_edits.append(new_edit)
return " ".join(cor), new_edits
# Input: A coder id
# Output: A noop edit; i.e. text contains no edits
def noop_edit(id=0):
return "A -1 -1|||noop|||-NONE-|||REQUIRED|||-NONE-|||"+str(id) | 0.459804 | 0.239805 |
import jaydebeapi
import os
import logging
import sys
# Отладочный режим
# Значение True - включается автокомит после каждой транзакции, выдается больше отладочной информации на экран.
# Значение False - Режим работы в продакшене. На экран работы ничего не выдается.
# ВАЖНЫЙ МОМЕНТ! Сообщения в журнал работы (файл "main.log") пишутся в обоих режимах.
DEBUG = True
# Дата на которую генерируется отчет
REPORT_DATE = '01.03.2021 23:59:59'
# Функция для подключения к серверу DWH
def connect_to_dwh(username, password, server, port, ojdbc8_jar_file_path):
connection = jaydebeapi.connect('oracle.jdbc.driver.OracleDriver',
'jdbc:oracle:thin:{usr}/{passwd}@{serv}:{port}/deoracle'.format(usr=username,
passwd=password,
serv=server,
port=port),
[username, password],
ojdbc8_jar_file_path)
return connection
# Небольшой обработчик выхода с закрытием соединения с сервером.
def exit_hadler(sql_server_curs, sql_server_connection):
# Закрываем курсор
sql_server_curs.close()
# Если не включен отладочный режим, выполняем откат изменений сделанных в хранилище.
# Сделано специально чтобы при работе в продакшене не повредить информацию уже хранящуюся в хранилище.
if not DEBUG:
# В случае завершения работы с ошибкой - откатываетм все изменения (транзакцию).
sql_server_connection.rollback()
# Закрываем соединение
sql_server_connection.close()
# Выходим из скрипта
sys.exit()
# Получаем имя скрипта, для открытия одноимённого файла журнала
(script_name, ext) = os.path.splitext(os.path.basename(__file__))
try:
logging.basicConfig(filename=(script_name + '.log'), filemode='a', level=logging.DEBUG, encoding='utf-8',
format='%(asctime)s %(levelname)s %(message)s', datefmt='%d-%m-%Y %H:%M:%S')
except Exception as exc:
# Сообщаем об исключении и выходим.
print("Can\'t create or open log file! Abnormal termination of script execution. \n{}".format(exc))
exit()
# Подключимся к хранилищу данных DWH используя следующие параметры соединения.
stg_user_name = "DEMIPT"
password = "<PASSWORD>"
server = "de-oracle.chronosavant.ru"
port = "1521"
path = "/home/demipt/anbo/ojdbc8.jar"
try:
conn = connect_to_dwh(stg_user_name, password, server, port, path)
# Если не включен отладочный режим, то отключаем autocommit
if not DEBUG:
conn.jconn.setAutoCommit(False)
curs = conn.cursor()
# Сообщаем об успешном подключении к серверу.
logging.info("Connection to the server \"{}\" was established successfully.".format(server))
except Exception as exc:
logging.error(
"Can't connect to DWH server. Abnormal termination of script execution. \n Detailed information: {}".format(
exc))
exit()
# Сгенерируем 1 отчёт
try:
sql_req = """
INSERT INTO DEMIPT.ANBO_REP_FRAUD ( EVENT_ID, PASSPORT, FIO, PHONE, EVENT_TYPE, REPORT_DT)
SELECT DISTINCT
t1.TRANS_DATE,
t4.PASSPORT_NUM,
t4.LAST_NAME||' '||t4.FIRST_NAME||' '||t4.PATRONYMIC,
t4.PHONE,
'1',
TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
FROM DEMIPT.ANBO_DWH_FACT_TRANSACTIONS T1
INNER JOIN DEMIPT.ANBO_DWH_DIM_CARDS_HIST T2
ON T1.CARD_NUM = T2.CARD_NUM
AND t1.TRANS_DATE <= TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) -- (1)
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T2.EFFECTIVE_FROM AND T2.EFFECTIVE_TO --(2)
AND T2.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_ACCOUNTS_HIST T3
ON T2.ACCOUNT_NUM = T3.ACCOUNT_NUM
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T3.EFFECTIVE_FROM AND T3.EFFECTIVE_TO -- (2)
AND T3.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_CLIENTS_HIST T4
ON T3.CLIENT = T4.CLIENT_ID
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T4.EFFECTIVE_FROM AND T4.EFFECTIVE_TO -- (2)
AND T4.DELETED_FLG = 'N' -- (3)
WHERE 1=1
AND T4.PASSPORT_NUM IN (SELECT PASSPORT_NUM FROM ANBO_DWH_FACT_PSSPRT_BLCKLST WHERE ENTRY_DT <= TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) )
OR T4.PASSPORT_VALID_TO < TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
""".format(GENERATION_DATE=REPORT_DATE)
# Отладочное сообщение
if DEBUG:
print("Report number 1 has been generated successfully.")
curs.execute(sql_req)
logging.info("REPORT 1: Request completed successfully.")
except Exception as exc:
# Сообщаем об исключении и выходим.
if DEBUG:
print(sql_req + "\n {}".format(exc))
logging.error("REPORT 1: An error occurred while executing the request.. \n Detailed information: {}".format(exc))
exit_hadler(curs, conn)
# Сгенерируем 2 отчёт
try:
sql_req = """
INSERT INTO DEMIPT.ANBO_REP_FRAUD ( EVENT_ID, PASSPORT, FIO, PHONE, EVENT_TYPE, REPORT_DT)
SELECT DISTINCT
t1.TRANS_DATE,
t4.PASSPORT_NUM,
t4.LAST_NAME||' '||t4.FIRST_NAME||' '||t4.PATRONYMIC,
t4.PHONE,
'2',
TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
FROM DEMIPT.ANBO_DWH_FACT_TRANSACTIONS T1
INNER JOIN DEMIPT.ANBO_DWH_DIM_CARDS_HIST T2
ON T1.CARD_NUM = T2.CARD_NUM
AND t1.TRANS_DATE <= TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) -- (1)
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T2.EFFECTIVE_FROM AND T2.EFFECTIVE_TO --(2)
AND T2.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_ACCOUNTS_HIST T3
ON T2.ACCOUNT_NUM = T3.ACCOUNT_NUM
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T3.EFFECTIVE_FROM AND T3.EFFECTIVE_TO -- (2)
AND T3.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_CLIENTS_HIST T4
ON T3.CLIENT = T4.CLIENT_ID
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T4.EFFECTIVE_FROM AND T4.EFFECTIVE_TO -- (2)
AND T4.DELETED_FLG = 'N' -- (3)
WHERE 1=1
AND T3.VALID_TO < TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
""".format(GENERATION_DATE=REPORT_DATE)
# Отладочное сообщение
if DEBUG:
print("Report number 1 has been generated successfully.")
curs.execute(sql_req)
logging.info("REPORT 2: Request completed successfully.")
except Exception as exc:
# Сообщаем об исключении и выходим.
if DEBUG:
print(sql_req + "\n {}".format(exc))
logging.error("REPORT 2: An error occurred while executing the request.. \n Detailed information: {}".format(exc))
exit_hadler(curs, conn)
# ------------------------------------ Фиксируем транзакцию и закрываем соединение -------------------------------------
# Если не включен отладочный режим, то фиксируем изменения в базе
if not DEBUG:
try:
conn.commit()
logging.info("Transaction completed successfully. \n\n")
except Exception as exc:
logging.error(
"An error occurred while closing a transaction. "
"\n Detailed information: {EXCEPTION}".format(EXCEPTION=exc))
exit_hadler(curs, conn)
if DEBUG:
# Пока что фиксация транзации автоматическая, после выполнения каждого запроса.
logging.info("The script has finished running. \n\n")
# Закрываем курсор и соединение.
curs.close()
conn.close() | ANBO/reports.py | import jaydebeapi
import os
import logging
import sys
# Отладочный режим
# Значение True - включается автокомит после каждой транзакции, выдается больше отладочной информации на экран.
# Значение False - Режим работы в продакшене. На экран работы ничего не выдается.
# ВАЖНЫЙ МОМЕНТ! Сообщения в журнал работы (файл "main.log") пишутся в обоих режимах.
DEBUG = True
# Дата на которую генерируется отчет
REPORT_DATE = '01.03.2021 23:59:59'
# Функция для подключения к серверу DWH
def connect_to_dwh(username, password, server, port, ojdbc8_jar_file_path):
connection = jaydebeapi.connect('oracle.jdbc.driver.OracleDriver',
'jdbc:oracle:thin:{usr}/{passwd}@{serv}:{port}/deoracle'.format(usr=username,
passwd=password,
serv=server,
port=port),
[username, password],
ojdbc8_jar_file_path)
return connection
# Небольшой обработчик выхода с закрытием соединения с сервером.
def exit_hadler(sql_server_curs, sql_server_connection):
# Закрываем курсор
sql_server_curs.close()
# Если не включен отладочный режим, выполняем откат изменений сделанных в хранилище.
# Сделано специально чтобы при работе в продакшене не повредить информацию уже хранящуюся в хранилище.
if not DEBUG:
# В случае завершения работы с ошибкой - откатываетм все изменения (транзакцию).
sql_server_connection.rollback()
# Закрываем соединение
sql_server_connection.close()
# Выходим из скрипта
sys.exit()
# Получаем имя скрипта, для открытия одноимённого файла журнала
(script_name, ext) = os.path.splitext(os.path.basename(__file__))
try:
logging.basicConfig(filename=(script_name + '.log'), filemode='a', level=logging.DEBUG, encoding='utf-8',
format='%(asctime)s %(levelname)s %(message)s', datefmt='%d-%m-%Y %H:%M:%S')
except Exception as exc:
# Сообщаем об исключении и выходим.
print("Can\'t create or open log file! Abnormal termination of script execution. \n{}".format(exc))
exit()
# Подключимся к хранилищу данных DWH используя следующие параметры соединения.
stg_user_name = "DEMIPT"
password = "<PASSWORD>"
server = "de-oracle.chronosavant.ru"
port = "1521"
path = "/home/demipt/anbo/ojdbc8.jar"
try:
conn = connect_to_dwh(stg_user_name, password, server, port, path)
# Если не включен отладочный режим, то отключаем autocommit
if not DEBUG:
conn.jconn.setAutoCommit(False)
curs = conn.cursor()
# Сообщаем об успешном подключении к серверу.
logging.info("Connection to the server \"{}\" was established successfully.".format(server))
except Exception as exc:
logging.error(
"Can't connect to DWH server. Abnormal termination of script execution. \n Detailed information: {}".format(
exc))
exit()
# Сгенерируем 1 отчёт
try:
sql_req = """
INSERT INTO DEMIPT.ANBO_REP_FRAUD ( EVENT_ID, PASSPORT, FIO, PHONE, EVENT_TYPE, REPORT_DT)
SELECT DISTINCT
t1.TRANS_DATE,
t4.PASSPORT_NUM,
t4.LAST_NAME||' '||t4.FIRST_NAME||' '||t4.PATRONYMIC,
t4.PHONE,
'1',
TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
FROM DEMIPT.ANBO_DWH_FACT_TRANSACTIONS T1
INNER JOIN DEMIPT.ANBO_DWH_DIM_CARDS_HIST T2
ON T1.CARD_NUM = T2.CARD_NUM
AND t1.TRANS_DATE <= TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) -- (1)
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T2.EFFECTIVE_FROM AND T2.EFFECTIVE_TO --(2)
AND T2.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_ACCOUNTS_HIST T3
ON T2.ACCOUNT_NUM = T3.ACCOUNT_NUM
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T3.EFFECTIVE_FROM AND T3.EFFECTIVE_TO -- (2)
AND T3.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_CLIENTS_HIST T4
ON T3.CLIENT = T4.CLIENT_ID
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T4.EFFECTIVE_FROM AND T4.EFFECTIVE_TO -- (2)
AND T4.DELETED_FLG = 'N' -- (3)
WHERE 1=1
AND T4.PASSPORT_NUM IN (SELECT PASSPORT_NUM FROM ANBO_DWH_FACT_PSSPRT_BLCKLST WHERE ENTRY_DT <= TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) )
OR T4.PASSPORT_VALID_TO < TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
""".format(GENERATION_DATE=REPORT_DATE)
# Отладочное сообщение
if DEBUG:
print("Report number 1 has been generated successfully.")
curs.execute(sql_req)
logging.info("REPORT 1: Request completed successfully.")
except Exception as exc:
# Сообщаем об исключении и выходим.
if DEBUG:
print(sql_req + "\n {}".format(exc))
logging.error("REPORT 1: An error occurred while executing the request.. \n Detailed information: {}".format(exc))
exit_hadler(curs, conn)
# Сгенерируем 2 отчёт
try:
sql_req = """
INSERT INTO DEMIPT.ANBO_REP_FRAUD ( EVENT_ID, PASSPORT, FIO, PHONE, EVENT_TYPE, REPORT_DT)
SELECT DISTINCT
t1.TRANS_DATE,
t4.PASSPORT_NUM,
t4.LAST_NAME||' '||t4.FIRST_NAME||' '||t4.PATRONYMIC,
t4.PHONE,
'2',
TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
FROM DEMIPT.ANBO_DWH_FACT_TRANSACTIONS T1
INNER JOIN DEMIPT.ANBO_DWH_DIM_CARDS_HIST T2
ON T1.CARD_NUM = T2.CARD_NUM
AND t1.TRANS_DATE <= TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) -- (1)
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T2.EFFECTIVE_FROM AND T2.EFFECTIVE_TO --(2)
AND T2.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_ACCOUNTS_HIST T3
ON T2.ACCOUNT_NUM = T3.ACCOUNT_NUM
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T3.EFFECTIVE_FROM AND T3.EFFECTIVE_TO -- (2)
AND T3.DELETED_FLG = 'N' -- (3)
INNER JOIN DEMIPT.ANBO_DWH_DIM_CLIENTS_HIST T4
ON T3.CLIENT = T4.CLIENT_ID
AND TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' ) BETWEEN T4.EFFECTIVE_FROM AND T4.EFFECTIVE_TO -- (2)
AND T4.DELETED_FLG = 'N' -- (3)
WHERE 1=1
AND T3.VALID_TO < TO_DATE( '{GENERATION_DATE}', 'DD.MM.YYYY HH24:MI:SS' )
""".format(GENERATION_DATE=REPORT_DATE)
# Отладочное сообщение
if DEBUG:
print("Report number 1 has been generated successfully.")
curs.execute(sql_req)
logging.info("REPORT 2: Request completed successfully.")
except Exception as exc:
# Сообщаем об исключении и выходим.
if DEBUG:
print(sql_req + "\n {}".format(exc))
logging.error("REPORT 2: An error occurred while executing the request.. \n Detailed information: {}".format(exc))
exit_hadler(curs, conn)
# ------------------------------------ Фиксируем транзакцию и закрываем соединение -------------------------------------
# Если не включен отладочный режим, то фиксируем изменения в базе
if not DEBUG:
try:
conn.commit()
logging.info("Transaction completed successfully. \n\n")
except Exception as exc:
logging.error(
"An error occurred while closing a transaction. "
"\n Detailed information: {EXCEPTION}".format(EXCEPTION=exc))
exit_hadler(curs, conn)
if DEBUG:
# Пока что фиксация транзации автоматическая, после выполнения каждого запроса.
logging.info("The script has finished running. \n\n")
# Закрываем курсор и соединение.
curs.close()
conn.close() | 0.097912 | 0.185062 |
import numpy as np
import scipy.special
_POISSON = .25
_N_PROCS = 4
def get_flexure_parameter(h, E, n_dim, gamma_mantle=33000.):
"""
Calculate the flexure parameter based on some physical constants. *h* is
the Effective elastic thickness of Earth's crust (m), *E* is Young's
Modulus, and *n_dim* is the number of spatial dimensions for which the
flexure parameter is used. The number of dimension must be either 1, or
2.
Examples
--------
>>> from __future__ import print_function
>>> from landlab.components.flexure import get_flexure_parameter
>>> eet = 65000.
>>> youngs = 7e10
>>> alpha = get_flexure_parameter(eet, youngs, 1)
>>> print('%.3f' % round(alpha, 3))
119965.926
>>> alpha = get_flexure_parameter(eet, youngs, 2)
>>> print('%.2f' % alpha)
84828.72
"""
D = E * pow(h, 3) / 12. / (1. - pow(_POISSON, 2))
if n_dim not in (1, 2):
raise ValueError("n_dim must be either 1 or 2")
if n_dim == 2:
alpha = pow(D / gamma_mantle, .25)
else:
alpha = pow(4. * D / gamma_mantle, .25)
return alpha
def _calculate_distances(locs, coords):
r = pow(coords[0][:, np.newaxis] - locs[0], 2)
r += pow(coords[1][:, np.newaxis] - locs[1], 2)
return np.sqrt(r, out=r)
def _calculate_deflections(load, locs, coords, alpha, out=None, gamma_mantle=33000.):
c = -load / (2. * np.pi * gamma_mantle * pow(alpha, 2.))
r = _calculate_distances(locs, coords) / alpha
scipy.special.kei(r, out=r)
np.multiply(r, c[np.newaxis, :], out=r)
return np.sum(r, axis=1, out=out)
def subside_point_load(load, loc, coords, params=None, out=None):
"""Calculate deflection at points due a point load.
Calculate deflections on a grid, defined by the points in the *coords*
tuple, due to a point load of magnitude *load* applied at *loc*.
*x* and *y* are the x and y coordinates of each node of the solution
grid (in meters). The scalars *eet* and *youngs* define the crustal
properties.
Parameters
----------
load : float
Magnitude of the point load.
loc : float or tuple
Location of the load as either a scalar or as (*x*, *y*)
coords : ndarray
Array of points to calculate deflections at
params : dict-like
Physical parameters used for deflection calculation. Valid keys are
- *eet*: Effective elastic thickness
- *youngs*: Young's modulus
out : ndarray, optional
Array to put deflections into.
Returns
-------
out : ndarray
Array of deflections.
Examples
--------
>>> from landlab.components.flexure import subside_point_load
>>> params = dict(eet=65000., youngs=7e10)
>>> load = 1e9
Define a unifrom rectilinear grid.
>>> x = np.arange(0, 10000, 100.)
>>> y = np.arange(0, 5000, 100.)
>>> (x, y) = np.meshgrid(x, y)
>>> x.shape = (x.size, )
>>> y.shape = (y.size, )
Calculate deflections due to a load applied at position (5000., 2500.).
>>> import six
>>> x = np.arange(0, 10000, 1000.)
>>> y = np.arange(0, 5000, 1000.)
>>> (x, y) = np.meshgrid(x, y)
>>> x.shape = (x.size, )
>>> y.shape = (y.size, )
>>> dz = subside_point_load(load, (5000., 2500.), (x, y), params=params)
>>> print('%.5g' % round(dz.sum(), 9))
2.6267e-05
>>> six.print_(round(dz.min(), 9))
5.24e-07
>>> six.print_(round(dz.max(), 9))
5.26e-07
>>> dz = subside_point_load((1e9, 1e9), ((5000., 5000.), (2500., 2500.)),
... (x, y), params=params)
>>> six.print_(round(dz.min(), 9) / 2.)
5.235e-07
>>> six.print_(round(dz.max(), 9) / 2.)
5.265e-07
"""
params = params or dict(eet=6500., youngs=7.e10)
eet, youngs = params["eet"], params["youngs"]
gamma_mantle = params.get("gamma_mantle", 33000.)
load = np.asarray(load).reshape((-1,))
loc = np.asarray(loc).reshape((-1, len(load)))
coords = np.asarray(coords)
if coords.ndim == 1:
coords = np.expand_dims(coords, axis=0)
n_dim = len(loc)
if n_dim not in (1, 2):
raise ValueError("number of dimension must be 1 or 2")
if len(coords) != n_dim:
raise ValueError("number of dimensions in coordinates doesn't match loc")
if out is None:
out = np.empty(coords[0].size, dtype=np.float)
alpha = get_flexure_parameter(eet, youngs, n_dim, gamma_mantle=gamma_mantle)
if n_dim == 2:
_calculate_deflections(
load, loc, coords, alpha, out=out, gamma_mantle=gamma_mantle
)
else:
x, x0 = np.meshgrid(loc[0], coords[0])
c = load / (2. * alpha * gamma_mantle)
r = abs(x - x0) / alpha
out[:] = (c * np.exp(-r) * (np.cos(r) + np.sin(r))).sum(axis=1)
return out | landlab/components/flexure/funcs.py |
import numpy as np
import scipy.special
_POISSON = .25
_N_PROCS = 4
def get_flexure_parameter(h, E, n_dim, gamma_mantle=33000.):
"""
Calculate the flexure parameter based on some physical constants. *h* is
the Effective elastic thickness of Earth's crust (m), *E* is Young's
Modulus, and *n_dim* is the number of spatial dimensions for which the
flexure parameter is used. The number of dimension must be either 1, or
2.
Examples
--------
>>> from __future__ import print_function
>>> from landlab.components.flexure import get_flexure_parameter
>>> eet = 65000.
>>> youngs = 7e10
>>> alpha = get_flexure_parameter(eet, youngs, 1)
>>> print('%.3f' % round(alpha, 3))
119965.926
>>> alpha = get_flexure_parameter(eet, youngs, 2)
>>> print('%.2f' % alpha)
84828.72
"""
D = E * pow(h, 3) / 12. / (1. - pow(_POISSON, 2))
if n_dim not in (1, 2):
raise ValueError("n_dim must be either 1 or 2")
if n_dim == 2:
alpha = pow(D / gamma_mantle, .25)
else:
alpha = pow(4. * D / gamma_mantle, .25)
return alpha
def _calculate_distances(locs, coords):
r = pow(coords[0][:, np.newaxis] - locs[0], 2)
r += pow(coords[1][:, np.newaxis] - locs[1], 2)
return np.sqrt(r, out=r)
def _calculate_deflections(load, locs, coords, alpha, out=None, gamma_mantle=33000.):
c = -load / (2. * np.pi * gamma_mantle * pow(alpha, 2.))
r = _calculate_distances(locs, coords) / alpha
scipy.special.kei(r, out=r)
np.multiply(r, c[np.newaxis, :], out=r)
return np.sum(r, axis=1, out=out)
def subside_point_load(load, loc, coords, params=None, out=None):
"""Calculate deflection at points due a point load.
Calculate deflections on a grid, defined by the points in the *coords*
tuple, due to a point load of magnitude *load* applied at *loc*.
*x* and *y* are the x and y coordinates of each node of the solution
grid (in meters). The scalars *eet* and *youngs* define the crustal
properties.
Parameters
----------
load : float
Magnitude of the point load.
loc : float or tuple
Location of the load as either a scalar or as (*x*, *y*)
coords : ndarray
Array of points to calculate deflections at
params : dict-like
Physical parameters used for deflection calculation. Valid keys are
- *eet*: Effective elastic thickness
- *youngs*: Young's modulus
out : ndarray, optional
Array to put deflections into.
Returns
-------
out : ndarray
Array of deflections.
Examples
--------
>>> from landlab.components.flexure import subside_point_load
>>> params = dict(eet=65000., youngs=7e10)
>>> load = 1e9
Define a unifrom rectilinear grid.
>>> x = np.arange(0, 10000, 100.)
>>> y = np.arange(0, 5000, 100.)
>>> (x, y) = np.meshgrid(x, y)
>>> x.shape = (x.size, )
>>> y.shape = (y.size, )
Calculate deflections due to a load applied at position (5000., 2500.).
>>> import six
>>> x = np.arange(0, 10000, 1000.)
>>> y = np.arange(0, 5000, 1000.)
>>> (x, y) = np.meshgrid(x, y)
>>> x.shape = (x.size, )
>>> y.shape = (y.size, )
>>> dz = subside_point_load(load, (5000., 2500.), (x, y), params=params)
>>> print('%.5g' % round(dz.sum(), 9))
2.6267e-05
>>> six.print_(round(dz.min(), 9))
5.24e-07
>>> six.print_(round(dz.max(), 9))
5.26e-07
>>> dz = subside_point_load((1e9, 1e9), ((5000., 5000.), (2500., 2500.)),
... (x, y), params=params)
>>> six.print_(round(dz.min(), 9) / 2.)
5.235e-07
>>> six.print_(round(dz.max(), 9) / 2.)
5.265e-07
"""
params = params or dict(eet=6500., youngs=7.e10)
eet, youngs = params["eet"], params["youngs"]
gamma_mantle = params.get("gamma_mantle", 33000.)
load = np.asarray(load).reshape((-1,))
loc = np.asarray(loc).reshape((-1, len(load)))
coords = np.asarray(coords)
if coords.ndim == 1:
coords = np.expand_dims(coords, axis=0)
n_dim = len(loc)
if n_dim not in (1, 2):
raise ValueError("number of dimension must be 1 or 2")
if len(coords) != n_dim:
raise ValueError("number of dimensions in coordinates doesn't match loc")
if out is None:
out = np.empty(coords[0].size, dtype=np.float)
alpha = get_flexure_parameter(eet, youngs, n_dim, gamma_mantle=gamma_mantle)
if n_dim == 2:
_calculate_deflections(
load, loc, coords, alpha, out=out, gamma_mantle=gamma_mantle
)
else:
x, x0 = np.meshgrid(loc[0], coords[0])
c = load / (2. * alpha * gamma_mantle)
r = abs(x - x0) / alpha
out[:] = (c * np.exp(-r) * (np.cos(r) + np.sin(r))).sum(axis=1)
return out | 0.896007 | 0.579162 |
import logging
XPATH_EMPTY = object()
XPATH_NO_DEFAULT = object()
logger = logging.getLogger()
class X(object):
""" doc_xpath_dict_map using object
receive list of string or single string.
Will pick the first xpath matched.
"""
XPATH_NO_DEFAULT = NotImplemented
def __init__(self, *xpath, default=XPATH_NO_DEFAULT):
self.xpath_list = list(xpath)
self.default = default
def __str__(self):
default_msg = f"|default:{self.default}" if self.default is not self.XPATH_NO_DEFAULT else ''
return f"<Xpath {self.xpath_list}{default_msg}>"
def __or__(self, next_one):
if not isinstance(next_one, X):
raise NotImplementedError('Cannot operate with other types.')
return X(*(self.xpath_list + next_one.xpath_list))
def doc_xpath(doc, xpath, allow_empty=False):
"""
Xpath for document
>>> a = {'a': [{'b': {'c': ['d', 'f']}}, {'b': {'c': ['g', 'h']}}]}
>>> doc_xpath(a, 'a.b.c')
Traceback (most recent call last):
...
KeyError: "Xpath <a.b.c> failed at <b>.[{'b': {'c': ['d', 'f']}}, {'b': {'c': ['g', 'h']}}]"
>>> doc_xpath(a, 'a.[].b.c')
[['d', 'f'], ['g', 'h']]
>>> doc_xpath(a, 'a.[].b.c.[]')
['d', 'f', 'g', 'h']
"""
check_points = [doc]
for word in xpath.split('.'):
new_points = []
for point in check_points:
try:
if word == '[]':
if not isinstance(point, list):
raise KeyError(f'Xpath <{xpath}> unexpected list word at {point}')
new_points.extend(point)
else:
if point.get(word, XPATH_EMPTY) is XPATH_EMPTY:
if not allow_empty:
raise KeyError(f'Xpath <{xpath}> unexpected empty at {point}')
else:
continue
new_points.append(point[word])
except Exception as e:
raise KeyError(f'Xpath <{xpath}> failed at <{word}>.{point}') from e
check_points = new_points
return check_points
def doc_xpath_dict_map(doc, xpath_dict, default=X.XPATH_NO_DEFAULT):
"""
Xpath with dict
If default is not set, we will raise a KeyError while value can't got.
Hint: this default is general for whole map.
>>> a = {'a1': {'b1': {'c1': 'd1'}}, 'a2': {'b3': '3'}}
>>> test_dict = {'alpha': X('y', 'a1.b1.c1'), 'beta': (X('a1.b3') | X('a2.b3'), int)}
>>> doc_xpath_dict_map(a, test_dict)
{'alpha': 'd1', 'beta': 3}
"""
output = {}
for key, desc in xpath_dict.items():
if isinstance(desc, tuple):
value, func = desc
if not callable(func):
raise ValueError('%s must be callable.' % repr(func))
else:
value = desc
func = None
if isinstance(value, X):
for doc_path in value.xpath_list:
try:
xpath_value = doc_xpath(doc, doc_path, allow_empty=True)
except KeyError:
logger.info(f'Read {key} from {doc_path} failed.')
if len(xpath_value) != 0:
if len(xpath_value) == 1:
xpath_value = xpath_value[0]
output[key] = xpath_value
break
else:
output[key] = value.default if value.default is not X.XPATH_NO_DEFAULT else default
elif isinstance(value, dict):
output[key] = doc_xpath_dict_map(doc, value)
else:
output[key] = value
if func and output[key] is not X.XPATH_NO_DEFAULT:
output[key] = func(output[key])
if output[key] is X.XPATH_NO_DEFAULT:
raise KeyError(f"The {value} does not exist at origin data. \n{doc}")
return output
if __name__ == "__main__":
import doctest
doctest.testmod() | doc_xpath.py |
import logging
XPATH_EMPTY = object()
XPATH_NO_DEFAULT = object()
logger = logging.getLogger()
class X(object):
""" doc_xpath_dict_map using object
receive list of string or single string.
Will pick the first xpath matched.
"""
XPATH_NO_DEFAULT = NotImplemented
def __init__(self, *xpath, default=XPATH_NO_DEFAULT):
self.xpath_list = list(xpath)
self.default = default
def __str__(self):
default_msg = f"|default:{self.default}" if self.default is not self.XPATH_NO_DEFAULT else ''
return f"<Xpath {self.xpath_list}{default_msg}>"
def __or__(self, next_one):
if not isinstance(next_one, X):
raise NotImplementedError('Cannot operate with other types.')
return X(*(self.xpath_list + next_one.xpath_list))
def doc_xpath(doc, xpath, allow_empty=False):
"""
Xpath for document
>>> a = {'a': [{'b': {'c': ['d', 'f']}}, {'b': {'c': ['g', 'h']}}]}
>>> doc_xpath(a, 'a.b.c')
Traceback (most recent call last):
...
KeyError: "Xpath <a.b.c> failed at <b>.[{'b': {'c': ['d', 'f']}}, {'b': {'c': ['g', 'h']}}]"
>>> doc_xpath(a, 'a.[].b.c')
[['d', 'f'], ['g', 'h']]
>>> doc_xpath(a, 'a.[].b.c.[]')
['d', 'f', 'g', 'h']
"""
check_points = [doc]
for word in xpath.split('.'):
new_points = []
for point in check_points:
try:
if word == '[]':
if not isinstance(point, list):
raise KeyError(f'Xpath <{xpath}> unexpected list word at {point}')
new_points.extend(point)
else:
if point.get(word, XPATH_EMPTY) is XPATH_EMPTY:
if not allow_empty:
raise KeyError(f'Xpath <{xpath}> unexpected empty at {point}')
else:
continue
new_points.append(point[word])
except Exception as e:
raise KeyError(f'Xpath <{xpath}> failed at <{word}>.{point}') from e
check_points = new_points
return check_points
def doc_xpath_dict_map(doc, xpath_dict, default=X.XPATH_NO_DEFAULT):
"""
Xpath with dict
If default is not set, we will raise a KeyError while value can't got.
Hint: this default is general for whole map.
>>> a = {'a1': {'b1': {'c1': 'd1'}}, 'a2': {'b3': '3'}}
>>> test_dict = {'alpha': X('y', 'a1.b1.c1'), 'beta': (X('a1.b3') | X('a2.b3'), int)}
>>> doc_xpath_dict_map(a, test_dict)
{'alpha': 'd1', 'beta': 3}
"""
output = {}
for key, desc in xpath_dict.items():
if isinstance(desc, tuple):
value, func = desc
if not callable(func):
raise ValueError('%s must be callable.' % repr(func))
else:
value = desc
func = None
if isinstance(value, X):
for doc_path in value.xpath_list:
try:
xpath_value = doc_xpath(doc, doc_path, allow_empty=True)
except KeyError:
logger.info(f'Read {key} from {doc_path} failed.')
if len(xpath_value) != 0:
if len(xpath_value) == 1:
xpath_value = xpath_value[0]
output[key] = xpath_value
break
else:
output[key] = value.default if value.default is not X.XPATH_NO_DEFAULT else default
elif isinstance(value, dict):
output[key] = doc_xpath_dict_map(doc, value)
else:
output[key] = value
if func and output[key] is not X.XPATH_NO_DEFAULT:
output[key] = func(output[key])
if output[key] is X.XPATH_NO_DEFAULT:
raise KeyError(f"The {value} does not exist at origin data. \n{doc}")
return output
if __name__ == "__main__":
import doctest
doctest.testmod() | 0.47926 | 0.188007 |
import typing
from abc import ABCMeta, abstractmethod
from .skill import RuntimeConfigurationBuilder
from .dispatch_components import (
AbstractRequestHandler, AbstractRequestInterceptor,
AbstractResponseInterceptor, AbstractExceptionHandler)
from .exceptions import SkillBuilderException
if typing.TYPE_CHECKING:
from typing import Callable, TypeVar
from .skill import AbstractSkill
T = TypeVar('T')
Input = TypeVar('Input')
class AbstractSkillBuilder(object):
"""Abstract Skill Builder with helper functions for building
:py:class:`ask_sdk_runtime.skill.AbstractSkill` object.
Domain SDKs has to implement the `create` method that returns
an instance of the skill implementation for the domain type.
"""
__metaclass__ = ABCMeta
def __init__(self):
# type: () -> None
self.runtime_configuration_builder = RuntimeConfigurationBuilder()
def add_request_handler(self, request_handler):
# type: (AbstractRequestHandler) -> None
"""Register input to the request handlers list.
:param request_handler: Request Handler instance to be
registered.
:type request_handler: ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler
:return: None
"""
self.runtime_configuration_builder.add_request_handler(
request_handler)
def add_exception_handler(self, exception_handler):
# type: (AbstractExceptionHandler) -> None
"""Register input to the exception handlers list.
:param exception_handler: Exception Handler instance to be
registered.
:type exception_handler: ask_sdk_runtime.dispatch_components.request_components.AbstractExceptionHandler
:return: None
"""
self.runtime_configuration_builder.add_exception_handler(
exception_handler)
def add_global_request_interceptor(self, request_interceptor):
# type: (AbstractRequestInterceptor) -> None
"""Register input to the global request interceptors list.
:param request_interceptor: Request Interceptor instance to be
registered.
:type request_interceptor: ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor
:return: None
"""
self.runtime_configuration_builder.add_global_request_interceptor(
request_interceptor)
def add_global_response_interceptor(self, response_interceptor):
# type: (AbstractResponseInterceptor) -> None
"""Register input to the global response interceptors list.
:param response_interceptor: Response Interceptor instance to
be registered.
:type response_interceptor: ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor
:return: None
"""
self.runtime_configuration_builder.add_global_response_interceptor(
response_interceptor)
def request_handler(self, can_handle_func):
# type: (Callable[[Input], bool]) -> Callable
"""Decorator that can be used to add request handlers easily to
the builder.
The can_handle_func has to be a Callable instance, which takes
a single parameter and no varargs or kwargs. This is because
of the RequestHandler class signature restrictions. The
returned wrapper function can be applied as a decorator on any
function that returns a response object by the skill. The
function should follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler`
class.
:param can_handle_func: The function that validates if the
request can be handled.
:type can_handle_func: Callable[[Input], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Request Handler can_handle_func and handle_func "
"input parameters should be callable")
class_attributes = {
"can_handle": lambda self, handler_input: can_handle_func(
handler_input),
"handle": lambda self, handler_input: handle_func(
handler_input)
}
request_handler_class = type(
"RequestHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractRequestHandler,), class_attributes)
self.add_request_handler(request_handler=request_handler_class())
return handle_func
return wrapper
def exception_handler(self, can_handle_func):
# type: (Callable[[Input, Exception], bool]) -> Callable
"""Decorator that can be used to add exception handlers easily
to the builder.
The can_handle_func has to be a Callable instance, which takes
two parameters and no varargs or kwargs. This is because of the
ExceptionHandler class signature restrictions. The returned
wrapper function can be applied as a decorator on any function
that processes the exception raised during dispatcher and
returns a response object by the skill. The function should
follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler`
class.
:param can_handle_func: The function that validates if the
exception can be handled.
:type can_handle_func: Callable[[Input, Exception], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Exception Handler can_handle_func and handle_func input "
"parameters should be callable")
class_attributes = {
"can_handle": (
lambda self, handler_input, exception: can_handle_func(
handler_input, exception)),
"handle": lambda self, handler_input, exception: handle_func(
handler_input, exception)
}
exception_handler_class = type(
"ExceptionHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractExceptionHandler,), class_attributes)
self.add_exception_handler(
exception_handler=exception_handler_class())
return wrapper
def global_request_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global request
interceptors easily to the builder.
The returned wrapper function can be applied as a decorator on
any function that processes the input. The function should
follow the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Request Interceptor process_func input parameter "
"should be callable")
class_attributes = {
"process": lambda self, handler_input: process_func(
handler_input)
}
request_interceptor = type(
"RequestInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractRequestInterceptor,), class_attributes)
self.add_global_request_interceptor(
request_interceptor=request_interceptor())
return wrapper
def global_response_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
generated by the request handler. The function should follow
the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Response Interceptor process_func input "
"parameter should be callable")
class_attributes = {
"process": (
lambda self, handler_input, response: process_func(
handler_input, response))
}
response_interceptor = type(
"ResponseInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractResponseInterceptor,), class_attributes)
self.add_global_response_interceptor(
response_interceptor=response_interceptor())
return wrapper
@abstractmethod
def create(self):
# type: () -> AbstractSkill
"""Create a skill object using the registered components.
:return: a skill object that can be used for invocation.
:rtype: AbstractSkill
"""
raise NotImplementedError | ask-sdk-runtime/ask_sdk_runtime/skill_builder.py | import typing
from abc import ABCMeta, abstractmethod
from .skill import RuntimeConfigurationBuilder
from .dispatch_components import (
AbstractRequestHandler, AbstractRequestInterceptor,
AbstractResponseInterceptor, AbstractExceptionHandler)
from .exceptions import SkillBuilderException
if typing.TYPE_CHECKING:
from typing import Callable, TypeVar
from .skill import AbstractSkill
T = TypeVar('T')
Input = TypeVar('Input')
class AbstractSkillBuilder(object):
"""Abstract Skill Builder with helper functions for building
:py:class:`ask_sdk_runtime.skill.AbstractSkill` object.
Domain SDKs has to implement the `create` method that returns
an instance of the skill implementation for the domain type.
"""
__metaclass__ = ABCMeta
def __init__(self):
# type: () -> None
self.runtime_configuration_builder = RuntimeConfigurationBuilder()
def add_request_handler(self, request_handler):
# type: (AbstractRequestHandler) -> None
"""Register input to the request handlers list.
:param request_handler: Request Handler instance to be
registered.
:type request_handler: ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler
:return: None
"""
self.runtime_configuration_builder.add_request_handler(
request_handler)
def add_exception_handler(self, exception_handler):
# type: (AbstractExceptionHandler) -> None
"""Register input to the exception handlers list.
:param exception_handler: Exception Handler instance to be
registered.
:type exception_handler: ask_sdk_runtime.dispatch_components.request_components.AbstractExceptionHandler
:return: None
"""
self.runtime_configuration_builder.add_exception_handler(
exception_handler)
def add_global_request_interceptor(self, request_interceptor):
# type: (AbstractRequestInterceptor) -> None
"""Register input to the global request interceptors list.
:param request_interceptor: Request Interceptor instance to be
registered.
:type request_interceptor: ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor
:return: None
"""
self.runtime_configuration_builder.add_global_request_interceptor(
request_interceptor)
def add_global_response_interceptor(self, response_interceptor):
# type: (AbstractResponseInterceptor) -> None
"""Register input to the global response interceptors list.
:param response_interceptor: Response Interceptor instance to
be registered.
:type response_interceptor: ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor
:return: None
"""
self.runtime_configuration_builder.add_global_response_interceptor(
response_interceptor)
def request_handler(self, can_handle_func):
# type: (Callable[[Input], bool]) -> Callable
"""Decorator that can be used to add request handlers easily to
the builder.
The can_handle_func has to be a Callable instance, which takes
a single parameter and no varargs or kwargs. This is because
of the RequestHandler class signature restrictions. The
returned wrapper function can be applied as a decorator on any
function that returns a response object by the skill. The
function should follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestHandler`
class.
:param can_handle_func: The function that validates if the
request can be handled.
:type can_handle_func: Callable[[Input], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Request Handler can_handle_func and handle_func "
"input parameters should be callable")
class_attributes = {
"can_handle": lambda self, handler_input: can_handle_func(
handler_input),
"handle": lambda self, handler_input: handle_func(
handler_input)
}
request_handler_class = type(
"RequestHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractRequestHandler,), class_attributes)
self.add_request_handler(request_handler=request_handler_class())
return handle_func
return wrapper
def exception_handler(self, can_handle_func):
# type: (Callable[[Input, Exception], bool]) -> Callable
"""Decorator that can be used to add exception handlers easily
to the builder.
The can_handle_func has to be a Callable instance, which takes
two parameters and no varargs or kwargs. This is because of the
ExceptionHandler class signature restrictions. The returned
wrapper function can be applied as a decorator on any function
that processes the exception raised during dispatcher and
returns a response object by the skill. The function should
follow the signature of the handle function in
:py:class:`ask_sdk_runtime.dispatch_components.exception_components.AbstractExceptionHandler`
class.
:param can_handle_func: The function that validates if the
exception can be handled.
:type can_handle_func: Callable[[Input, Exception], bool]
:return: Wrapper function that can be decorated on a handle
function.
"""
def wrapper(handle_func):
if not callable(can_handle_func) or not callable(handle_func):
raise SkillBuilderException(
"Exception Handler can_handle_func and handle_func input "
"parameters should be callable")
class_attributes = {
"can_handle": (
lambda self, handler_input, exception: can_handle_func(
handler_input, exception)),
"handle": lambda self, handler_input, exception: handle_func(
handler_input, exception)
}
exception_handler_class = type(
"ExceptionHandler{}".format(
handle_func.__name__.title().replace("_", "")),
(AbstractExceptionHandler,), class_attributes)
self.add_exception_handler(
exception_handler=exception_handler_class())
return wrapper
def global_request_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global request
interceptors easily to the builder.
The returned wrapper function can be applied as a decorator on
any function that processes the input. The function should
follow the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractRequestInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Request Interceptor process_func input parameter "
"should be callable")
class_attributes = {
"process": lambda self, handler_input: process_func(
handler_input)
}
request_interceptor = type(
"RequestInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractRequestInterceptor,), class_attributes)
self.add_global_request_interceptor(
request_interceptor=request_interceptor())
return wrapper
def global_response_interceptor(self):
# type: () -> Callable
"""Decorator that can be used to add global
response interceptors easily to the builder.
The returned wrapper function can be applied as a decorator
on any function that processes the input and the response
generated by the request handler. The function should follow
the signature of the process function in
:py:class:`ask_sdk_runtime.dispatch_components.request_components.AbstractResponseInterceptor`
class.
:return: Wrapper function that can be decorated on a
interceptor process function.
"""
def wrapper(process_func):
if not callable(process_func):
raise SkillBuilderException(
"Global Response Interceptor process_func input "
"parameter should be callable")
class_attributes = {
"process": (
lambda self, handler_input, response: process_func(
handler_input, response))
}
response_interceptor = type(
"ResponseInterceptor{}".format(
process_func.__name__.title().replace("_", "")),
(AbstractResponseInterceptor,), class_attributes)
self.add_global_response_interceptor(
response_interceptor=response_interceptor())
return wrapper
@abstractmethod
def create(self):
# type: () -> AbstractSkill
"""Create a skill object using the registered components.
:return: a skill object that can be used for invocation.
:rtype: AbstractSkill
"""
raise NotImplementedError | 0.888928 | 0.140867 |
from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BaseDenseHead(nn.Module, metaclass=ABCMeta):
"""Base class for DenseHeads."""
def __init__(self):
super(BaseDenseHead, self).__init__()
@abstractmethod
def loss(self, **kwargs):
"""Compute losses of the head."""
pass
@abstractmethod
def get_bboxes(self, **kwargs):
"""Transform network output for a batch into bbox predictions."""
pass
def forward_train(self,
x,
img_metas,
gt_bboxes,
gt_labels=None,
gt_bboxes_ignore=None,
proposal_cfg=None,
**kwargs):
"""
Args:
x (list[Tensor]): Features from FPN.
img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
gt_bboxes (Tensor): Ground truth bboxes of the image,
shape (num_gts, 4).
gt_labels (Tensor): Ground truth labels of each box,
shape (num_gts,).
gt_bboxes_ignore (Tensor): Ground truth bboxes to be
ignored, shape (num_ignored_gts, 4).
proposal_cfg (mmdet.cv_core.Config): Test / postprocessing configuration,
if None, test_cfg would be used
Returns:
tuple:
losses: (dict[str, Tensor]): A dictionary of loss components.
proposal_list (list[Tensor]): Proposals of each image.
"""
outs = self(x)
if gt_labels is None:
loss_inputs = outs + (gt_bboxes, img_metas)
else:
loss_inputs = outs + (gt_bboxes, gt_labels, img_metas)
losses = self.loss(*loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)
if proposal_cfg is None:
return losses
else:
proposal_list = self.get_bboxes(*outs, img_metas, cfg=proposal_cfg)
return losses, proposal_list | mmdet/models/dense_heads/base_dense_head.py | from abc import ABCMeta, abstractmethod
import torch.nn as nn
class BaseDenseHead(nn.Module, metaclass=ABCMeta):
"""Base class for DenseHeads."""
def __init__(self):
super(BaseDenseHead, self).__init__()
@abstractmethod
def loss(self, **kwargs):
"""Compute losses of the head."""
pass
@abstractmethod
def get_bboxes(self, **kwargs):
"""Transform network output for a batch into bbox predictions."""
pass
def forward_train(self,
x,
img_metas,
gt_bboxes,
gt_labels=None,
gt_bboxes_ignore=None,
proposal_cfg=None,
**kwargs):
"""
Args:
x (list[Tensor]): Features from FPN.
img_metas (list[dict]): Meta information of each image, e.g.,
image size, scaling factor, etc.
gt_bboxes (Tensor): Ground truth bboxes of the image,
shape (num_gts, 4).
gt_labels (Tensor): Ground truth labels of each box,
shape (num_gts,).
gt_bboxes_ignore (Tensor): Ground truth bboxes to be
ignored, shape (num_ignored_gts, 4).
proposal_cfg (mmdet.cv_core.Config): Test / postprocessing configuration,
if None, test_cfg would be used
Returns:
tuple:
losses: (dict[str, Tensor]): A dictionary of loss components.
proposal_list (list[Tensor]): Proposals of each image.
"""
outs = self(x)
if gt_labels is None:
loss_inputs = outs + (gt_bboxes, img_metas)
else:
loss_inputs = outs + (gt_bboxes, gt_labels, img_metas)
losses = self.loss(*loss_inputs, gt_bboxes_ignore=gt_bboxes_ignore)
if proposal_cfg is None:
return losses
else:
proposal_list = self.get_bboxes(*outs, img_metas, cfg=proposal_cfg)
return losses, proposal_list | 0.939554 | 0.317664 |
# app.py
# Required imports
import os
import time
import json
from flask_cors import CORS
import firebase_admin
from flask import Flask, request, jsonify, redirect, session, render_template
from firebase_admin import credentials, firestore, initialize_app
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
# Initialize Flask app
app = Flask(__name__)
CORS(app)
api_key = os.environ['API_KEY']
api_secret = os.environ['API_SECRET']
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
app.secret_key = api_secret
client = Client(account_sid, auth_token)
# Initialize Firestore DB
if not firebase_admin._apps:
cred = credentials.Certificate('homework-todo-40dae-firebase-adminsdk-gb6nv-6ba33da2ab.json')
default_app = initialize_app(cred)
db = firestore.client()
todo_ref = db.collection('todos')
motivator_ref = db.collection('motivators')
@app.route('/add', methods=['POST'])
def create():
"""
create() : Add document to Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post'}
"""
try:
id = request.json['id']
todo_ref.document(id).set(request.json)
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/list', methods=['GET'])
def read():
"""
read() : Fetches documents from Firestore collection as JSON.
todo : Return document that matches query ID.
all_todos : Return all documents.
"""
try:
# Check if ID was passed to URL query
todo_id = request.args.get('id')
if todo_id:
todo = todo_ref.document(todo_id).get()
return jsonify(todo.to_dict()), 200
else:
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/update', methods=['POST', 'PUT'])
def update():
"""
update() : Update document in Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post today'}
"""
try:
id = request.json['id']
todo_ref.document(id).update(request.json)
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/delete', methods=['GET', 'DELETE'])
def delete():
"""
delete() : Delete a document from Firestore collection.
"""
try:
# Check for ID in URL query
todo_id = request.args.get('id')
todo_ref.document(todo_id).delete()
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/add-motivator', methods=['POST'])
def create_motivator():
"""
create() : Add document to Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post'}
"""
try:
id = request.json['id']
motivator_ref.document(id).set(request.json)
all_motivators = [doc.to_dict() for doc in motivator_ref.stream()]
return jsonify(all_motivators), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/list-motivator', methods=['GET'])
def read_motivator():
"""
read() : Fetches documents from Firestore collection as JSON.
todo : Return document that matches query ID.
all_todos : Return all documents.
"""
try:
# Check if ID was passed to URL query
motivator_id = request.args.get('id')
if motivator_id:
motivator = motivator_ref.document(motivator_id).get()
return jsonify(motivator.to_dict()), 200
else:
all_motivators = [doc.to_dict() for doc in motivator_ref.stream()]
return jsonify(all_motivators), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/delete-motivator', methods=['GET', 'DELETE'])
def delete_motivator():
"""
delete() : Delete a document from Firestore collection.
"""
try:
# Check for ID in URL query
motivator_id = request.args.get('id')
motivator_ref.document(motivator_id).delete()
all_motivators = [doc.to_dict() for doc in motivator_ref.stream()]
return jsonify(all_motivators), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/call-motivator', methods=['GET', 'POST'])
def call_motivator():
try:
client = Client(account_sid, auth_token)
call = client.calls.create(
twiml='<Response><Say>Call Pramo to remind her of tasks!</Say></Response>',
to='+16467326671',
from_='+15739733743'
)
return jsonify({'sid' : call.sid}), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Start our TwiML response
resp = MessagingResponse()
# Add a message
resp.message("The Robots are coming! Head for the hills!")
return str(resp)
if __name__ == '__main__':
app.run(threaded=True, debug=True) | HW1_Main.py | # app.py
# Required imports
import os
import time
import json
from flask_cors import CORS
import firebase_admin
from flask import Flask, request, jsonify, redirect, session, render_template
from firebase_admin import credentials, firestore, initialize_app
from twilio.rest import Client
from twilio.twiml.messaging_response import MessagingResponse
# Initialize Flask app
app = Flask(__name__)
CORS(app)
api_key = os.environ['API_KEY']
api_secret = os.environ['API_SECRET']
account_sid = os.environ['TWILIO_ACCOUNT_SID']
auth_token = os.environ['TWILIO_AUTH_TOKEN']
app.secret_key = api_secret
client = Client(account_sid, auth_token)
# Initialize Firestore DB
if not firebase_admin._apps:
cred = credentials.Certificate('homework-todo-40dae-firebase-adminsdk-gb6nv-6ba33da2ab.json')
default_app = initialize_app(cred)
db = firestore.client()
todo_ref = db.collection('todos')
motivator_ref = db.collection('motivators')
@app.route('/add', methods=['POST'])
def create():
"""
create() : Add document to Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post'}
"""
try:
id = request.json['id']
todo_ref.document(id).set(request.json)
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/list', methods=['GET'])
def read():
"""
read() : Fetches documents from Firestore collection as JSON.
todo : Return document that matches query ID.
all_todos : Return all documents.
"""
try:
# Check if ID was passed to URL query
todo_id = request.args.get('id')
if todo_id:
todo = todo_ref.document(todo_id).get()
return jsonify(todo.to_dict()), 200
else:
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/update', methods=['POST', 'PUT'])
def update():
"""
update() : Update document in Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post today'}
"""
try:
id = request.json['id']
todo_ref.document(id).update(request.json)
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/delete', methods=['GET', 'DELETE'])
def delete():
"""
delete() : Delete a document from Firestore collection.
"""
try:
# Check for ID in URL query
todo_id = request.args.get('id')
todo_ref.document(todo_id).delete()
all_todos = [doc.to_dict() for doc in todo_ref.stream()]
return jsonify(all_todos), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/add-motivator', methods=['POST'])
def create_motivator():
"""
create() : Add document to Firestore collection with request body.
Ensure you pass a custom ID as part of json body in post request,
e.g. json={'id': '1', 'title': 'Write a blog post'}
"""
try:
id = request.json['id']
motivator_ref.document(id).set(request.json)
all_motivators = [doc.to_dict() for doc in motivator_ref.stream()]
return jsonify(all_motivators), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/list-motivator', methods=['GET'])
def read_motivator():
"""
read() : Fetches documents from Firestore collection as JSON.
todo : Return document that matches query ID.
all_todos : Return all documents.
"""
try:
# Check if ID was passed to URL query
motivator_id = request.args.get('id')
if motivator_id:
motivator = motivator_ref.document(motivator_id).get()
return jsonify(motivator.to_dict()), 200
else:
all_motivators = [doc.to_dict() for doc in motivator_ref.stream()]
return jsonify(all_motivators), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/delete-motivator', methods=['GET', 'DELETE'])
def delete_motivator():
"""
delete() : Delete a document from Firestore collection.
"""
try:
# Check for ID in URL query
motivator_id = request.args.get('id')
motivator_ref.document(motivator_id).delete()
all_motivators = [doc.to_dict() for doc in motivator_ref.stream()]
return jsonify(all_motivators), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route('/call-motivator', methods=['GET', 'POST'])
def call_motivator():
try:
client = Client(account_sid, auth_token)
call = client.calls.create(
twiml='<Response><Say>Call Pramo to remind her of tasks!</Say></Response>',
to='+16467326671',
from_='+15739733743'
)
return jsonify({'sid' : call.sid}), 200
except Exception as e:
return f"An Error Occured: {e}"
@app.route("/sms", methods=['GET', 'POST'])
def sms_reply():
"""Respond to incoming calls with a simple text message."""
# Start our TwiML response
resp = MessagingResponse()
# Add a message
resp.message("The Robots are coming! Head for the hills!")
return str(resp)
if __name__ == '__main__':
app.run(threaded=True, debug=True) | 0.379723 | 0.08292 |
from openstack.baremetal.v1 import _common
from openstack.baremetal.v1 import allocation as _allocation
from openstack.baremetal.v1 import chassis as _chassis
from openstack.baremetal.v1 import driver as _driver
from openstack.baremetal.v1 import node as _node
from openstack.baremetal.v1 import port as _port
from openstack.baremetal.v1 import port_group as _portgroup
from openstack import proxy
from openstack import utils
class Proxy(proxy.Proxy):
retriable_status_codes = _common.RETRIABLE_STATUS_CODES
def _get_with_fields(self, resource_type, value, fields=None):
"""Fetch a bare metal resource.
:param resource_type: The type of resource to get.
:type resource_type: :class:`~openstack.resource.Resource`
:param value: The value to get. Can be either the ID of a
resource or a :class:`~openstack.resource.Resource`
subclass.
:param fields: Limit the resource fields to fetch.
:returns: The result of the ``fetch``
:rtype: :class:`~openstack.resource.Resource`
"""
res = self._get_resource(resource_type, value)
kwargs = {}
if fields:
kwargs['fields'] = _common.comma_separated_list(fields)
return res.fetch(
self,
error_message="No {resource_type} found for {value}".format(
resource_type=resource_type.__name__, value=value),
**kwargs)
def chassis(self, details=False, **query):
"""Retrieve a generator of chassis.
:param details: A boolean indicating whether the detailed information
for every chassis should be returned.
:param dict query: Optional query parameters to be sent to
restrict the chassis to be returned. Available parameters include:
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of items be
returned from the query.
* ``marker``: Specifies the ID of the last-seen chassis. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen chassis from the response as
the ``marker`` value in a subsequent limited request.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of chassis instances.
"""
return _chassis.Chassis.list(self, details=details, **query)
def create_chassis(self, **attrs):
"""Create a new chassis from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.chassis.Chassis`.
:returns: The results of chassis creation.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`.
"""
return self._create(_chassis.Chassis, **attrs)
def find_chassis(self, name_or_id, ignore_missing=True):
"""Find a single chassis.
:param str name_or_id: The ID of a chassis.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the chassis does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent chassis.
:returns: One :class:`~openstack.baremetal.v1.chassis.Chassis` object
or None.
"""
return self._find(_chassis.Chassis, name_or_id,
ignore_missing=ignore_missing)
def get_chassis(self, chassis, fields=None):
"""Get a specific chassis.
:param chassis: The value can be the ID of a chassis or a
:class:`~openstack.baremetal.v1.chassis.Chassis` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.chassis.Chassis`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
chassis matching the name or ID could be found.
"""
return self._get_with_fields(_chassis.Chassis, chassis, fields=fields)
def update_chassis(self, chassis, **attrs):
"""Update a chassis.
:param chassis: Either the ID of a chassis, or an instance
of :class:`~openstack.baremetal.v1.chassis.Chassis`.
:param dict attrs: The attributes to update on the chassis represented
by the ``chassis`` parameter.
:returns: The updated chassis.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`
"""
return self._update(_chassis.Chassis, chassis, **attrs)
def patch_chassis(self, chassis, patch):
"""Apply a JSON patch to the chassis.
:param chassis: The value can be the ID of a chassis or a
:class:`~openstack.baremetal.v1.chassis.Chassis` instance.
:param patch: JSON patch to apply.
:returns: The updated chassis.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`
"""
return self._get_resource(_chassis.Chassis, chassis).patch(self, patch)
def delete_chassis(self, chassis, ignore_missing=True):
"""Delete a chassis.
:param chassis: The value can be either the ID of a chassis or
a :class:`~openstack.baremetal.v1.chassis.Chassis` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the chassis could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
chassis.
:returns: The instance of the chassis which was deleted.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`.
"""
return self._delete(_chassis.Chassis, chassis,
ignore_missing=ignore_missing)
def drivers(self, details=False):
"""Retrieve a generator of drivers.
:param bool details: A boolean indicating whether the detailed
information for every driver should be returned.
:returns: A generator of driver instances.
"""
kwargs = {}
# NOTE(dtantsur): details are available starting with API microversion
# 1.30. Thus we do not send any value if not needed.
if details:
kwargs['details'] = True
return self._list(_driver.Driver, **kwargs)
def get_driver(self, driver):
"""Get a specific driver.
:param driver: The value can be the name of a driver or a
:class:`~openstack.baremetal.v1.driver.Driver` instance.
:returns: One :class:`~openstack.baremetal.v1.driver.Driver`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
driver matching the name could be found.
"""
return self._get(_driver.Driver, driver)
def nodes(self, details=False, **query):
"""Retrieve a generator of nodes.
:param details: A boolean indicating whether the detailed information
for every node should be returned.
:param dict query: Optional query parameters to be sent to restrict
the nodes returned. Available parameters include:
* ``associated``: Only return those which are, or are not,
associated with an ``instance_id``.
* ``conductor_group``: Only return those in the specified
``conductor_group``.
* ``driver``: Only return those with the specified ``driver``.
* ``fault``: Only return those with the specified fault type.
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``instance_id``: Only return the node with this specific instance
UUID or an empty set if not found.
* ``is_maintenance``: Only return those with ``maintenance`` set to
``True`` or ``False``.
* ``limit``: Requests at most the specified number of nodes be
returned from the query.
* ``marker``: Specifies the ID of the last-seen node. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen node from the response as
the ``marker`` value in a subsequent limited request.
* ``provision_state``: Only return those nodes with the specified
``provision_state``.
* ``resource_class``: Only return those with the specified
``resource_class``.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of :class:`~openstack.baremetal.v1.node.Node`
"""
return _node.Node.list(self, details=details, **query)
def create_node(self, **attrs):
"""Create a new node from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.node.Node`.
:returns: The results of node creation.
:rtype: :class:`~openstack.baremetal.v1.node.Node`.
"""
return self._create(_node.Node, **attrs)
def find_node(self, name_or_id, ignore_missing=True):
"""Find a single node.
:param str name_or_id: The name or ID of a node.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the node does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent node.
:returns: One :class:`~openstack.baremetal.v1.node.Node` object
or None.
"""
return self._find(_node.Node, name_or_id,
ignore_missing=ignore_missing)
def get_node(self, node, fields=None):
"""Get a specific node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.node.Node`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
node matching the name or ID could be found.
"""
return self._get_with_fields(_node.Node, node, fields=fields)
def update_node(self, node, retry_on_conflict=True, **attrs):
"""Update a node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param bool retry_on_conflict: Whether to retry HTTP CONFLICT error.
Most of the time it can be retried, since it is caused by the node
being locked. However, when setting ``instance_id``, this is
a normal code and should not be retried.
:param dict attrs: The attributes to update on the node represented
by the ``node`` parameter.
:returns: The updated node.
:rtype: :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node, **attrs)
return res.commit(self, retry_on_conflict=retry_on_conflict)
def patch_node(self, node, patch, retry_on_conflict=True):
"""Apply a JSON patch to the node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param patch: JSON patch to apply.
:param bool retry_on_conflict: Whether to retry HTTP CONFLICT error.
Most of the time it can be retried, since it is caused by the node
being locked. However, when setting ``instance_id``, this is
a normal code and should not be retried.
See `Update Node
<https://docs.openstack.org/api-ref/baremetal/?expanded=update-node-detail#update-node>`_
for details.
:returns: The updated node.
:rtype: :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.patch(self, patch, retry_on_conflict=retry_on_conflict)
def set_node_provision_state(self, node, target, config_drive=None,
clean_steps=None, rescue_password=None,
wait=False, timeout=None):
"""Run an action modifying node's provision state.
This call is asynchronous, it will return success as soon as the Bare
Metal service acknowledges the request.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param target: Provisioning action, e.g. ``active``, ``provide``.
See the Bare Metal service documentation for available actions.
:param config_drive: Config drive to pass to the node, only valid
for ``active` and ``rebuild`` targets. You can use functions from
:mod:`openstack.baremetal.configdrive` to build it.
:param clean_steps: Clean steps to execute, only valid for ``clean``
target.
:param rescue_password: Password for the rescue operation, only valid
for ``rescue`` target.
:param wait: Whether to wait for the node to get into the expected
state. The expected state is determined from a combination of
the current provision state and ``target``.
:param timeout: If ``wait`` is set to ``True``, specifies how much (in
seconds) to wait for the expected state to be reached. The value of
``None`` (the default) means no client-side timeout.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
:raises: ValueError if ``config_drive``, ``clean_steps`` or
``rescue_password`` are provided with an invalid ``target``.
"""
res = self._get_resource(_node.Node, node)
return res.set_provision_state(self, target, config_drive=config_drive,
clean_steps=clean_steps,
rescue_password=<PASSWORD>,
wait=wait, timeout=timeout)
def set_node_boot_device(self, node, boot_device, persistent=False):
"""Set node boot device
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param boot_device: Boot device to assign to the node.
:param persistent: If the boot device change is maintained after node
reboot
:return: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.set_boot_device(self, boot_device, persistent=persistent)
def wait_for_nodes_provision_state(self, nodes, expected_state,
timeout=None,
abort_on_failed_state=True):
"""Wait for the nodes to reach the expected state.
:param nodes: List of nodes - name, ID or
:class:`~openstack.baremetal.v1.node.Node` instance.
:param expected_state: The expected provisioning state to reach.
:param timeout: If ``wait`` is set to ``True``, specifies how much (in
seconds) to wait for the expected state to be reached. The value of
``None`` (the default) means no client-side timeout.
:param abort_on_failed_state: If ``True`` (the default), abort waiting
if any node reaches a failure state which does not match the
expected one. Note that the failure state for ``enroll`` ->
``manageable`` transition is ``enroll`` again.
:return: The list of :class:`~openstack.baremetal.v1.node.Node`
instances that reached the requested state.
:raises: :class:`~openstack.exceptions.ResourceFailure` if a node
reaches an error state and ``abort_on_failed_state`` is ``True``.
:raises: :class:`~openstack.exceptions.ResourceTimeout` on timeout.
"""
log_nodes = ', '.join(n.id if isinstance(n, _node.Node) else n
for n in nodes)
finished = []
remaining = nodes
for count in utils.iterate_timeout(
timeout,
"Timeout waiting for nodes %(nodes)s to reach "
"target state '%(state)s'" % {'nodes': log_nodes,
'state': expected_state}):
nodes = [self.get_node(n) for n in remaining]
remaining = []
for n in nodes:
if n._check_state_reached(self, expected_state,
abort_on_failed_state):
finished.append(n)
else:
remaining.append(n)
if not remaining:
return finished
self.log.debug(
'Still waiting for nodes %(nodes)s to reach state '
'"%(target)s"',
{'nodes': ', '.join(n.id for n in remaining),
'target': expected_state})
def set_node_power_state(self, node, target):
"""Run an action modifying node's power state.
This call is asynchronous, it will return success as soon as the Bare
Metal service acknowledges the request.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param target: Target power state, e.g. "rebooting", "power on".
See the Bare Metal service documentation for available actions.
"""
self._get_resource(_node.Node, node).set_power_state(self, target)
def wait_for_node_reservation(self, node, timeout=None):
"""Wait for a lock on the node to be released.
Bare metal nodes in ironic have a reservation lock that
is used to represent that a conductor has locked the node
while performing some sort of action, such as changing
configuration as a result of a machine state change.
This lock can occur during power syncronization, and prevents
updates to objects attached to the node, such as ports.
Note that nothing prevents a conductor from acquiring the lock again
after this call returns, so it should be treated as best effort.
Returns immediately if there is no reservation on the node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param timeout: How much (in seconds) to wait for the lock to be
released. The value of ``None`` (the default) means no timeout.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.wait_for_reservation(self, timeout=timeout)
def validate_node(self, node, required=('boot', 'deploy', 'power')):
"""Validate required information on a node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param required: List of interfaces that are required to pass
validation. The default value is the list of minimum required
interfaces for provisioning.
:return: dict mapping interface names to
:class:`~openstack.baremetal.v1.node.ValidationResult` objects.
:raises: :exc:`~openstack.exceptions.ValidationException` if validation
fails for a required interface.
"""
res = self._get_resource(_node.Node, node)
return res.validate(self, required=required)
def set_node_maintenance(self, node, reason=None):
"""Enable maintenance mode on the node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param reason: Optional reason for maintenance.
:return: This :class:`Node` instance.
"""
res = self._get_resource(_node.Node, node)
return res.set_maintenance(self, reason)
def unset_node_maintenance(self, node):
"""Disable maintenance mode on the node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:return: This :class:`Node` instance.
"""
res = self._get_resource(_node.Node, node)
return res.unset_maintenance(self)
def delete_node(self, node, ignore_missing=True):
"""Delete a node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the node could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
node.
:returns: The instance of the node which was deleted.
:rtype: :class:`~openstack.baremetal.v1.node.Node`.
"""
return self._delete(_node.Node, node, ignore_missing=ignore_missing)
def ports(self, details=False, **query):
"""Retrieve a generator of ports.
:param details: A boolean indicating whether the detailed information
for every port should be returned.
:param dict query: Optional query parameters to be sent to restrict
the ports returned. Available parameters include:
* ``address``: Only return ports with the specified physical
hardware address, typically a MAC address.
* ``driver``: Only return those with the specified ``driver``.
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of ports be
returned from the query.
* ``marker``: Specifies the ID of the last-seen port. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen port from the response as
the ``marker`` value in a subsequent limited request.
* ``node``:only return the ones associated with this specific node
(name or UUID), or an empty set if not found.
* ``node_id``:only return the ones associated with this specific
node UUID, or an empty set if not found.
* ``portgroup``: only return the ports associated with this
specific Portgroup (name or UUID), or an empty set if not
found. Added in API microversion 1.24.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of port instances.
"""
return _port.Port.list(self, details=details, **query)
def create_port(self, **attrs):
"""Create a new port from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.port.Port`.
:returns: The results of port creation.
:rtype: :class:`~openstack.baremetal.v1.port.Port`.
"""
return self._create(_port.Port, **attrs)
def find_port(self, name_or_id, ignore_missing=True):
"""Find a single port.
:param str name_or_id: The ID of a port.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent port.
:returns: One :class:`~openstack.baremetal.v1.port.Port` object
or None.
"""
return self._find(_port.Port, name_or_id,
ignore_missing=ignore_missing)
def get_port(self, port, fields=None):
"""Get a specific port.
:param port: The value can be the ID of a port or a
:class:`~openstack.baremetal.v1.port.Port` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.port.Port`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
port matching the name or ID could be found.
"""
return self._get_with_fields(_port.Port, port, fields=fields)
def update_port(self, port, **attrs):
"""Update a port.
:param port: Either the ID of a port or an instance
of :class:`~openstack.baremetal.v1.port.Port`.
:param dict attrs: The attributes to update on the port represented
by the ``port`` parameter.
:returns: The updated port.
:rtype: :class:`~openstack.baremetal.v1.port.Port`
"""
return self._update(_port.Port, port, **attrs)
def patch_port(self, port, patch):
"""Apply a JSON patch to the port.
:param port: The value can be the ID of a port or a
:class:`~openstack.baremetal.v1.port.Port` instance.
:param patch: JSON patch to apply.
:returns: The updated port.
:rtype: :class:`~openstack.baremetal.v1.port.Port`
"""
return self._get_resource(_port.Port, port).patch(self, patch)
def delete_port(self, port, ignore_missing=True):
"""Delete a port.
:param port: The value can be either the ID of a port or
a :class:`~openstack.baremetal.v1.port.Port` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
port.
:returns: The instance of the port which was deleted.
:rtype: :class:`~openstack.baremetal.v1.port.Port`.
"""
return self._delete(_port.Port, port, ignore_missing=ignore_missing)
def port_groups(self, details=False, **query):
"""Retrieve a generator of port groups.
:param details: A boolean indicating whether the detailed information
for every port group should be returned.
:param dict query: Optional query parameters to be sent to restrict
the port groups returned. Available parameters include:
* ``address``: Only return portgroups with the specified physical
hardware address, typically a MAC address.
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of portgroups
returned from the query.
* ``marker``: Specifies the ID of the last-seen portgroup. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen portgroup from the response as
the ``marker`` value in a subsequent limited request.
* ``node``:only return the ones associated with this specific node
(name or UUID), or an empty set if not found.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of port group instances.
"""
return _portgroup.PortGroup.list(self, details=details, **query)
def create_port_group(self, **attrs):
"""Create a new portgroup from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.port_group.PortGroup`.
:returns: The results of portgroup creation.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`.
"""
return self._create(_portgroup.PortGroup, **attrs)
def find_port_group(self, name_or_id, ignore_missing=True):
"""Find a single port group.
:param str name_or_id: The name or ID of a portgroup.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port group does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent port group.
:returns: One :class:`~openstack.baremetal.v1.port_group.PortGroup`
object or None.
"""
return self._find(_portgroup.PortGroup, name_or_id,
ignore_missing=ignore_missing)
def get_port_group(self, port_group, fields=None):
"""Get a specific port group.
:param port_group: The value can be the name or ID of a chassis or a
:class:`~openstack.baremetal.v1.port_group.PortGroup` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.port_group.PortGroup`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
port group matching the name or ID could be found.
"""
return self._get_with_fields(_portgroup.PortGroup, port_group,
fields=fields)
def update_port_group(self, port_group, **attrs):
"""Update a port group.
:param port_group: Either the name or the ID of a port group or
an instance of
:class:`~openstack.baremetal.v1.port_group.PortGroup`.
:param dict attrs: The attributes to update on the port group
represented by the ``port_group`` parameter.
:returns: The updated port group.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`
"""
return self._update(_portgroup.PortGroup, port_group, **attrs)
def patch_port_group(self, port_group, patch):
"""Apply a JSON patch to the port_group.
:param port_group: The value can be the ID of a port group or a
:class:`~openstack.baremetal.v1.port_group.PortGroup` instance.
:param patch: JSON patch to apply.
:returns: The updated port group.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`
"""
res = self._get_resource(_portgroup.PortGroup, port_group)
return res.patch(self, patch)
def delete_port_group(self, port_group, ignore_missing=True):
"""Delete a port group.
:param port_group: The value can be either the name or ID of
a port group or a
:class:`~openstack.baremetal.v1.port_group.PortGroup`
instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port group could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
port group.
:returns: The instance of the port group which was deleted.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`.
"""
return self._delete(_portgroup.PortGroup, port_group,
ignore_missing=ignore_missing)
def attach_vif_to_node(self, node, vif_id, retry_on_conflict=True):
"""Attach a VIF to the node.
The exact form of the VIF ID depends on the network interface used by
the node. In the most common case it is a Network service port
(NOT a Bare Metal port) ID. A VIF can only be attached to one node
at a time.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param string vif_id: Backend-specific VIF ID.
:param retry_on_conflict: Whether to retry HTTP CONFLICT errors.
This can happen when either the VIF is already used on a node or
the node is locked. Since the latter happens more often, the
default value is True.
:return: ``None``
:raises: :exc:`~openstack.exceptions.NotSupported` if the server
does not support the VIF API.
"""
res = self._get_resource(_node.Node, node)
res.attach_vif(self, vif_id, retry_on_conflict=retry_on_conflict)
def detach_vif_from_node(self, node, vif_id, ignore_missing=True):
"""Detach a VIF from the node.
The exact form of the VIF ID depends on the network interface used by
the node. In the most common case it is a Network service port
(NOT a Bare Metal port) ID.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param string vif_id: Backend-specific VIF ID.
:param bool ignore_missing: When set to ``False``
:class:`~openstack.exceptions.ResourceNotFound` will be
raised when the VIF does not exist. Otherwise, ``False``
is returned.
:return: ``True`` if the VIF was detached, otherwise ``False``.
:raises: :exc:`~openstack.exceptions.NotSupported` if the server
does not support the VIF API.
"""
res = self._get_resource(_node.Node, node)
return res.detach_vif(self, vif_id, ignore_missing=ignore_missing)
def list_node_vifs(self, node):
"""List IDs of VIFs attached to the node.
The exact form of the VIF ID depends on the network interface used by
the node. In the most common case it is a Network service port
(NOT a Bare Metal port) ID.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:return: List of VIF IDs as strings.
:raises: :exc:`~openstack.exceptions.NotSupported` if the server
does not support the VIF API.
"""
res = self._get_resource(_node.Node, node)
return res.list_vifs(self)
def allocations(self, **query):
"""Retrieve a generator of allocations.
:param dict query: Optional query parameters to be sent to restrict
the allocation to be returned. Available parameters include:
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of items be
returned from the query.
* ``marker``: Specifies the ID of the last-seen allocation. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen allocation from the response as
the ``marker`` value in a subsequent limited request.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of allocation instances.
"""
return _allocation.Allocation.list(self, **query)
def create_allocation(self, **attrs):
"""Create a new allocation from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.allocation.Allocation`.
:returns: The results of allocation creation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`.
"""
return self._create(_allocation.Allocation, **attrs)
def get_allocation(self, allocation, fields=None):
"""Get a specific allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.allocation.Allocation`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
allocation matching the name or ID could be found.
"""
return self._get_with_fields(_allocation.Allocation, allocation,
fields=fields)
def update_allocation(self, allocation, **attrs):
"""Update an allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param dict attrs: The attributes to update on the allocation
represented by the ``allocation`` parameter.
:returns: The updated allocation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`
"""
return self._update(_allocation.Allocation, allocation, **attrs)
def patch_allocation(self, allocation, patch):
"""Apply a JSON patch to the allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param patch: JSON patch to apply.
:returns: The updated allocation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`
"""
return self._get_resource(_allocation.Allocation,
allocation).patch(self, patch)
def delete_allocation(self, allocation, ignore_missing=True):
"""Delete an allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the allocation could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
allocation.
:returns: The instance of the allocation which was deleted.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`.
"""
return self._delete(_allocation.Allocation, allocation,
ignore_missing=ignore_missing)
def wait_for_allocation(self, allocation, timeout=None,
ignore_error=False):
"""Wait for the allocation to become active.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param timeout: How much (in seconds) to wait for the allocation.
The value of ``None`` (the default) means no client-side timeout.
:param ignore_error: If ``True``, this call will raise an exception
if the allocation reaches the ``error`` state. Otherwise the error
state is considered successful and the call returns.
:returns: The instance of the allocation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`.
:raises: :class:`~openstack.exceptions.ResourceFailure` if allocation
fails and ``ignore_error`` is ``False``.
:raises: :class:`~openstack.exceptions.ResourceTimeout` on timeout.
"""
res = self._get_resource(_allocation.Allocation, allocation)
return res.wait(self, timeout=timeout, ignore_error=ignore_error)
def add_node_trait(self, node, trait):
"""Add a trait to a node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param trait: trait to remove from the node.
:returns: The updated node
"""
res = self._get_resource(_node.Node, node)
return res.add_trait(self, trait)
def remove_node_trait(self, node, trait, ignore_missing=True):
"""Remove a trait from a node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param trait: trait to remove from the node.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the trait could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
trait.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.remove_trait(self, trait, ignore_missing=ignore_missing)
def set_node_traits(self, node, traits):
"""Set traits for a node.
Removes any existing traits and adds the traits passed in to this
method.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param traits: list of traits to add to the node.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.set_traits(self, traits) | openstack/baremetal/v1/_proxy.py |
from openstack.baremetal.v1 import _common
from openstack.baremetal.v1 import allocation as _allocation
from openstack.baremetal.v1 import chassis as _chassis
from openstack.baremetal.v1 import driver as _driver
from openstack.baremetal.v1 import node as _node
from openstack.baremetal.v1 import port as _port
from openstack.baremetal.v1 import port_group as _portgroup
from openstack import proxy
from openstack import utils
class Proxy(proxy.Proxy):
retriable_status_codes = _common.RETRIABLE_STATUS_CODES
def _get_with_fields(self, resource_type, value, fields=None):
"""Fetch a bare metal resource.
:param resource_type: The type of resource to get.
:type resource_type: :class:`~openstack.resource.Resource`
:param value: The value to get. Can be either the ID of a
resource or a :class:`~openstack.resource.Resource`
subclass.
:param fields: Limit the resource fields to fetch.
:returns: The result of the ``fetch``
:rtype: :class:`~openstack.resource.Resource`
"""
res = self._get_resource(resource_type, value)
kwargs = {}
if fields:
kwargs['fields'] = _common.comma_separated_list(fields)
return res.fetch(
self,
error_message="No {resource_type} found for {value}".format(
resource_type=resource_type.__name__, value=value),
**kwargs)
def chassis(self, details=False, **query):
"""Retrieve a generator of chassis.
:param details: A boolean indicating whether the detailed information
for every chassis should be returned.
:param dict query: Optional query parameters to be sent to
restrict the chassis to be returned. Available parameters include:
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of items be
returned from the query.
* ``marker``: Specifies the ID of the last-seen chassis. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen chassis from the response as
the ``marker`` value in a subsequent limited request.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of chassis instances.
"""
return _chassis.Chassis.list(self, details=details, **query)
def create_chassis(self, **attrs):
"""Create a new chassis from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.chassis.Chassis`.
:returns: The results of chassis creation.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`.
"""
return self._create(_chassis.Chassis, **attrs)
def find_chassis(self, name_or_id, ignore_missing=True):
"""Find a single chassis.
:param str name_or_id: The ID of a chassis.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the chassis does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent chassis.
:returns: One :class:`~openstack.baremetal.v1.chassis.Chassis` object
or None.
"""
return self._find(_chassis.Chassis, name_or_id,
ignore_missing=ignore_missing)
def get_chassis(self, chassis, fields=None):
"""Get a specific chassis.
:param chassis: The value can be the ID of a chassis or a
:class:`~openstack.baremetal.v1.chassis.Chassis` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.chassis.Chassis`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
chassis matching the name or ID could be found.
"""
return self._get_with_fields(_chassis.Chassis, chassis, fields=fields)
def update_chassis(self, chassis, **attrs):
"""Update a chassis.
:param chassis: Either the ID of a chassis, or an instance
of :class:`~openstack.baremetal.v1.chassis.Chassis`.
:param dict attrs: The attributes to update on the chassis represented
by the ``chassis`` parameter.
:returns: The updated chassis.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`
"""
return self._update(_chassis.Chassis, chassis, **attrs)
def patch_chassis(self, chassis, patch):
"""Apply a JSON patch to the chassis.
:param chassis: The value can be the ID of a chassis or a
:class:`~openstack.baremetal.v1.chassis.Chassis` instance.
:param patch: JSON patch to apply.
:returns: The updated chassis.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`
"""
return self._get_resource(_chassis.Chassis, chassis).patch(self, patch)
def delete_chassis(self, chassis, ignore_missing=True):
"""Delete a chassis.
:param chassis: The value can be either the ID of a chassis or
a :class:`~openstack.baremetal.v1.chassis.Chassis` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the chassis could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
chassis.
:returns: The instance of the chassis which was deleted.
:rtype: :class:`~openstack.baremetal.v1.chassis.Chassis`.
"""
return self._delete(_chassis.Chassis, chassis,
ignore_missing=ignore_missing)
def drivers(self, details=False):
"""Retrieve a generator of drivers.
:param bool details: A boolean indicating whether the detailed
information for every driver should be returned.
:returns: A generator of driver instances.
"""
kwargs = {}
# NOTE(dtantsur): details are available starting with API microversion
# 1.30. Thus we do not send any value if not needed.
if details:
kwargs['details'] = True
return self._list(_driver.Driver, **kwargs)
def get_driver(self, driver):
"""Get a specific driver.
:param driver: The value can be the name of a driver or a
:class:`~openstack.baremetal.v1.driver.Driver` instance.
:returns: One :class:`~openstack.baremetal.v1.driver.Driver`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
driver matching the name could be found.
"""
return self._get(_driver.Driver, driver)
def nodes(self, details=False, **query):
"""Retrieve a generator of nodes.
:param details: A boolean indicating whether the detailed information
for every node should be returned.
:param dict query: Optional query parameters to be sent to restrict
the nodes returned. Available parameters include:
* ``associated``: Only return those which are, or are not,
associated with an ``instance_id``.
* ``conductor_group``: Only return those in the specified
``conductor_group``.
* ``driver``: Only return those with the specified ``driver``.
* ``fault``: Only return those with the specified fault type.
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``instance_id``: Only return the node with this specific instance
UUID or an empty set if not found.
* ``is_maintenance``: Only return those with ``maintenance`` set to
``True`` or ``False``.
* ``limit``: Requests at most the specified number of nodes be
returned from the query.
* ``marker``: Specifies the ID of the last-seen node. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen node from the response as
the ``marker`` value in a subsequent limited request.
* ``provision_state``: Only return those nodes with the specified
``provision_state``.
* ``resource_class``: Only return those with the specified
``resource_class``.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of :class:`~openstack.baremetal.v1.node.Node`
"""
return _node.Node.list(self, details=details, **query)
def create_node(self, **attrs):
"""Create a new node from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.node.Node`.
:returns: The results of node creation.
:rtype: :class:`~openstack.baremetal.v1.node.Node`.
"""
return self._create(_node.Node, **attrs)
def find_node(self, name_or_id, ignore_missing=True):
"""Find a single node.
:param str name_or_id: The name or ID of a node.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the node does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent node.
:returns: One :class:`~openstack.baremetal.v1.node.Node` object
or None.
"""
return self._find(_node.Node, name_or_id,
ignore_missing=ignore_missing)
def get_node(self, node, fields=None):
"""Get a specific node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.node.Node`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
node matching the name or ID could be found.
"""
return self._get_with_fields(_node.Node, node, fields=fields)
def update_node(self, node, retry_on_conflict=True, **attrs):
"""Update a node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param bool retry_on_conflict: Whether to retry HTTP CONFLICT error.
Most of the time it can be retried, since it is caused by the node
being locked. However, when setting ``instance_id``, this is
a normal code and should not be retried.
:param dict attrs: The attributes to update on the node represented
by the ``node`` parameter.
:returns: The updated node.
:rtype: :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node, **attrs)
return res.commit(self, retry_on_conflict=retry_on_conflict)
def patch_node(self, node, patch, retry_on_conflict=True):
"""Apply a JSON patch to the node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param patch: JSON patch to apply.
:param bool retry_on_conflict: Whether to retry HTTP CONFLICT error.
Most of the time it can be retried, since it is caused by the node
being locked. However, when setting ``instance_id``, this is
a normal code and should not be retried.
See `Update Node
<https://docs.openstack.org/api-ref/baremetal/?expanded=update-node-detail#update-node>`_
for details.
:returns: The updated node.
:rtype: :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.patch(self, patch, retry_on_conflict=retry_on_conflict)
def set_node_provision_state(self, node, target, config_drive=None,
clean_steps=None, rescue_password=None,
wait=False, timeout=None):
"""Run an action modifying node's provision state.
This call is asynchronous, it will return success as soon as the Bare
Metal service acknowledges the request.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param target: Provisioning action, e.g. ``active``, ``provide``.
See the Bare Metal service documentation for available actions.
:param config_drive: Config drive to pass to the node, only valid
for ``active` and ``rebuild`` targets. You can use functions from
:mod:`openstack.baremetal.configdrive` to build it.
:param clean_steps: Clean steps to execute, only valid for ``clean``
target.
:param rescue_password: Password for the rescue operation, only valid
for ``rescue`` target.
:param wait: Whether to wait for the node to get into the expected
state. The expected state is determined from a combination of
the current provision state and ``target``.
:param timeout: If ``wait`` is set to ``True``, specifies how much (in
seconds) to wait for the expected state to be reached. The value of
``None`` (the default) means no client-side timeout.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
:raises: ValueError if ``config_drive``, ``clean_steps`` or
``rescue_password`` are provided with an invalid ``target``.
"""
res = self._get_resource(_node.Node, node)
return res.set_provision_state(self, target, config_drive=config_drive,
clean_steps=clean_steps,
rescue_password=<PASSWORD>,
wait=wait, timeout=timeout)
def set_node_boot_device(self, node, boot_device, persistent=False):
"""Set node boot device
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param boot_device: Boot device to assign to the node.
:param persistent: If the boot device change is maintained after node
reboot
:return: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.set_boot_device(self, boot_device, persistent=persistent)
def wait_for_nodes_provision_state(self, nodes, expected_state,
timeout=None,
abort_on_failed_state=True):
"""Wait for the nodes to reach the expected state.
:param nodes: List of nodes - name, ID or
:class:`~openstack.baremetal.v1.node.Node` instance.
:param expected_state: The expected provisioning state to reach.
:param timeout: If ``wait`` is set to ``True``, specifies how much (in
seconds) to wait for the expected state to be reached. The value of
``None`` (the default) means no client-side timeout.
:param abort_on_failed_state: If ``True`` (the default), abort waiting
if any node reaches a failure state which does not match the
expected one. Note that the failure state for ``enroll`` ->
``manageable`` transition is ``enroll`` again.
:return: The list of :class:`~openstack.baremetal.v1.node.Node`
instances that reached the requested state.
:raises: :class:`~openstack.exceptions.ResourceFailure` if a node
reaches an error state and ``abort_on_failed_state`` is ``True``.
:raises: :class:`~openstack.exceptions.ResourceTimeout` on timeout.
"""
log_nodes = ', '.join(n.id if isinstance(n, _node.Node) else n
for n in nodes)
finished = []
remaining = nodes
for count in utils.iterate_timeout(
timeout,
"Timeout waiting for nodes %(nodes)s to reach "
"target state '%(state)s'" % {'nodes': log_nodes,
'state': expected_state}):
nodes = [self.get_node(n) for n in remaining]
remaining = []
for n in nodes:
if n._check_state_reached(self, expected_state,
abort_on_failed_state):
finished.append(n)
else:
remaining.append(n)
if not remaining:
return finished
self.log.debug(
'Still waiting for nodes %(nodes)s to reach state '
'"%(target)s"',
{'nodes': ', '.join(n.id for n in remaining),
'target': expected_state})
def set_node_power_state(self, node, target):
"""Run an action modifying node's power state.
This call is asynchronous, it will return success as soon as the Bare
Metal service acknowledges the request.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param target: Target power state, e.g. "rebooting", "power on".
See the Bare Metal service documentation for available actions.
"""
self._get_resource(_node.Node, node).set_power_state(self, target)
def wait_for_node_reservation(self, node, timeout=None):
"""Wait for a lock on the node to be released.
Bare metal nodes in ironic have a reservation lock that
is used to represent that a conductor has locked the node
while performing some sort of action, such as changing
configuration as a result of a machine state change.
This lock can occur during power syncronization, and prevents
updates to objects attached to the node, such as ports.
Note that nothing prevents a conductor from acquiring the lock again
after this call returns, so it should be treated as best effort.
Returns immediately if there is no reservation on the node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param timeout: How much (in seconds) to wait for the lock to be
released. The value of ``None`` (the default) means no timeout.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.wait_for_reservation(self, timeout=timeout)
def validate_node(self, node, required=('boot', 'deploy', 'power')):
"""Validate required information on a node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param required: List of interfaces that are required to pass
validation. The default value is the list of minimum required
interfaces for provisioning.
:return: dict mapping interface names to
:class:`~openstack.baremetal.v1.node.ValidationResult` objects.
:raises: :exc:`~openstack.exceptions.ValidationException` if validation
fails for a required interface.
"""
res = self._get_resource(_node.Node, node)
return res.validate(self, required=required)
def set_node_maintenance(self, node, reason=None):
"""Enable maintenance mode on the node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param reason: Optional reason for maintenance.
:return: This :class:`Node` instance.
"""
res = self._get_resource(_node.Node, node)
return res.set_maintenance(self, reason)
def unset_node_maintenance(self, node):
"""Disable maintenance mode on the node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:return: This :class:`Node` instance.
"""
res = self._get_resource(_node.Node, node)
return res.unset_maintenance(self)
def delete_node(self, node, ignore_missing=True):
"""Delete a node.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the node could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
node.
:returns: The instance of the node which was deleted.
:rtype: :class:`~openstack.baremetal.v1.node.Node`.
"""
return self._delete(_node.Node, node, ignore_missing=ignore_missing)
def ports(self, details=False, **query):
"""Retrieve a generator of ports.
:param details: A boolean indicating whether the detailed information
for every port should be returned.
:param dict query: Optional query parameters to be sent to restrict
the ports returned. Available parameters include:
* ``address``: Only return ports with the specified physical
hardware address, typically a MAC address.
* ``driver``: Only return those with the specified ``driver``.
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of ports be
returned from the query.
* ``marker``: Specifies the ID of the last-seen port. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen port from the response as
the ``marker`` value in a subsequent limited request.
* ``node``:only return the ones associated with this specific node
(name or UUID), or an empty set if not found.
* ``node_id``:only return the ones associated with this specific
node UUID, or an empty set if not found.
* ``portgroup``: only return the ports associated with this
specific Portgroup (name or UUID), or an empty set if not
found. Added in API microversion 1.24.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of port instances.
"""
return _port.Port.list(self, details=details, **query)
def create_port(self, **attrs):
"""Create a new port from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.port.Port`.
:returns: The results of port creation.
:rtype: :class:`~openstack.baremetal.v1.port.Port`.
"""
return self._create(_port.Port, **attrs)
def find_port(self, name_or_id, ignore_missing=True):
"""Find a single port.
:param str name_or_id: The ID of a port.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent port.
:returns: One :class:`~openstack.baremetal.v1.port.Port` object
or None.
"""
return self._find(_port.Port, name_or_id,
ignore_missing=ignore_missing)
def get_port(self, port, fields=None):
"""Get a specific port.
:param port: The value can be the ID of a port or a
:class:`~openstack.baremetal.v1.port.Port` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.port.Port`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
port matching the name or ID could be found.
"""
return self._get_with_fields(_port.Port, port, fields=fields)
def update_port(self, port, **attrs):
"""Update a port.
:param port: Either the ID of a port or an instance
of :class:`~openstack.baremetal.v1.port.Port`.
:param dict attrs: The attributes to update on the port represented
by the ``port`` parameter.
:returns: The updated port.
:rtype: :class:`~openstack.baremetal.v1.port.Port`
"""
return self._update(_port.Port, port, **attrs)
def patch_port(self, port, patch):
"""Apply a JSON patch to the port.
:param port: The value can be the ID of a port or a
:class:`~openstack.baremetal.v1.port.Port` instance.
:param patch: JSON patch to apply.
:returns: The updated port.
:rtype: :class:`~openstack.baremetal.v1.port.Port`
"""
return self._get_resource(_port.Port, port).patch(self, patch)
def delete_port(self, port, ignore_missing=True):
"""Delete a port.
:param port: The value can be either the ID of a port or
a :class:`~openstack.baremetal.v1.port.Port` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
port.
:returns: The instance of the port which was deleted.
:rtype: :class:`~openstack.baremetal.v1.port.Port`.
"""
return self._delete(_port.Port, port, ignore_missing=ignore_missing)
def port_groups(self, details=False, **query):
"""Retrieve a generator of port groups.
:param details: A boolean indicating whether the detailed information
for every port group should be returned.
:param dict query: Optional query parameters to be sent to restrict
the port groups returned. Available parameters include:
* ``address``: Only return portgroups with the specified physical
hardware address, typically a MAC address.
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of portgroups
returned from the query.
* ``marker``: Specifies the ID of the last-seen portgroup. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen portgroup from the response as
the ``marker`` value in a subsequent limited request.
* ``node``:only return the ones associated with this specific node
(name or UUID), or an empty set if not found.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of port group instances.
"""
return _portgroup.PortGroup.list(self, details=details, **query)
def create_port_group(self, **attrs):
"""Create a new portgroup from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.port_group.PortGroup`.
:returns: The results of portgroup creation.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`.
"""
return self._create(_portgroup.PortGroup, **attrs)
def find_port_group(self, name_or_id, ignore_missing=True):
"""Find a single port group.
:param str name_or_id: The name or ID of a portgroup.
:param bool ignore_missing: When set to ``False``, an exception of
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port group does not exist. When set to `True``, None will
be returned when attempting to find a nonexistent port group.
:returns: One :class:`~openstack.baremetal.v1.port_group.PortGroup`
object or None.
"""
return self._find(_portgroup.PortGroup, name_or_id,
ignore_missing=ignore_missing)
def get_port_group(self, port_group, fields=None):
"""Get a specific port group.
:param port_group: The value can be the name or ID of a chassis or a
:class:`~openstack.baremetal.v1.port_group.PortGroup` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.port_group.PortGroup`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
port group matching the name or ID could be found.
"""
return self._get_with_fields(_portgroup.PortGroup, port_group,
fields=fields)
def update_port_group(self, port_group, **attrs):
"""Update a port group.
:param port_group: Either the name or the ID of a port group or
an instance of
:class:`~openstack.baremetal.v1.port_group.PortGroup`.
:param dict attrs: The attributes to update on the port group
represented by the ``port_group`` parameter.
:returns: The updated port group.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`
"""
return self._update(_portgroup.PortGroup, port_group, **attrs)
def patch_port_group(self, port_group, patch):
"""Apply a JSON patch to the port_group.
:param port_group: The value can be the ID of a port group or a
:class:`~openstack.baremetal.v1.port_group.PortGroup` instance.
:param patch: JSON patch to apply.
:returns: The updated port group.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`
"""
res = self._get_resource(_portgroup.PortGroup, port_group)
return res.patch(self, patch)
def delete_port_group(self, port_group, ignore_missing=True):
"""Delete a port group.
:param port_group: The value can be either the name or ID of
a port group or a
:class:`~openstack.baremetal.v1.port_group.PortGroup`
instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the port group could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
port group.
:returns: The instance of the port group which was deleted.
:rtype: :class:`~openstack.baremetal.v1.port_group.PortGroup`.
"""
return self._delete(_portgroup.PortGroup, port_group,
ignore_missing=ignore_missing)
def attach_vif_to_node(self, node, vif_id, retry_on_conflict=True):
"""Attach a VIF to the node.
The exact form of the VIF ID depends on the network interface used by
the node. In the most common case it is a Network service port
(NOT a Bare Metal port) ID. A VIF can only be attached to one node
at a time.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param string vif_id: Backend-specific VIF ID.
:param retry_on_conflict: Whether to retry HTTP CONFLICT errors.
This can happen when either the VIF is already used on a node or
the node is locked. Since the latter happens more often, the
default value is True.
:return: ``None``
:raises: :exc:`~openstack.exceptions.NotSupported` if the server
does not support the VIF API.
"""
res = self._get_resource(_node.Node, node)
res.attach_vif(self, vif_id, retry_on_conflict=retry_on_conflict)
def detach_vif_from_node(self, node, vif_id, ignore_missing=True):
"""Detach a VIF from the node.
The exact form of the VIF ID depends on the network interface used by
the node. In the most common case it is a Network service port
(NOT a Bare Metal port) ID.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:param string vif_id: Backend-specific VIF ID.
:param bool ignore_missing: When set to ``False``
:class:`~openstack.exceptions.ResourceNotFound` will be
raised when the VIF does not exist. Otherwise, ``False``
is returned.
:return: ``True`` if the VIF was detached, otherwise ``False``.
:raises: :exc:`~openstack.exceptions.NotSupported` if the server
does not support the VIF API.
"""
res = self._get_resource(_node.Node, node)
return res.detach_vif(self, vif_id, ignore_missing=ignore_missing)
def list_node_vifs(self, node):
"""List IDs of VIFs attached to the node.
The exact form of the VIF ID depends on the network interface used by
the node. In the most common case it is a Network service port
(NOT a Bare Metal port) ID.
:param node: The value can be either the name or ID of a node or
a :class:`~openstack.baremetal.v1.node.Node` instance.
:return: List of VIF IDs as strings.
:raises: :exc:`~openstack.exceptions.NotSupported` if the server
does not support the VIF API.
"""
res = self._get_resource(_node.Node, node)
return res.list_vifs(self)
def allocations(self, **query):
"""Retrieve a generator of allocations.
:param dict query: Optional query parameters to be sent to restrict
the allocation to be returned. Available parameters include:
* ``fields``: A list containing one or more fields to be returned
in the response. This may lead to some performance gain
because other fields of the resource are not refreshed.
* ``limit``: Requests at most the specified number of items be
returned from the query.
* ``marker``: Specifies the ID of the last-seen allocation. Use the
``limit`` parameter to make an initial limited request and
use the ID of the last-seen allocation from the response as
the ``marker`` value in a subsequent limited request.
* ``sort_dir``: Sorts the response by the requested sort direction.
A valid value is ``asc`` (ascending) or ``desc``
(descending). Default is ``asc``. You can specify multiple
pairs of sort key and sort direction query parameters. If
you omit the sort direction in a pair, the API uses the
natural sorting direction of the server attribute that is
provided as the ``sort_key``.
* ``sort_key``: Sorts the response by the this attribute value.
Default is ``id``. You can specify multiple pairs of sort
key and sort direction query parameters. If you omit the
sort direction in a pair, the API uses the natural sorting
direction of the server attribute that is provided as the
``sort_key``.
:returns: A generator of allocation instances.
"""
return _allocation.Allocation.list(self, **query)
def create_allocation(self, **attrs):
"""Create a new allocation from attributes.
:param dict attrs: Keyword arguments that will be used to create a
:class:`~openstack.baremetal.v1.allocation.Allocation`.
:returns: The results of allocation creation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`.
"""
return self._create(_allocation.Allocation, **attrs)
def get_allocation(self, allocation, fields=None):
"""Get a specific allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param fields: Limit the resource fields to fetch.
:returns: One :class:`~openstack.baremetal.v1.allocation.Allocation`
:raises: :class:`~openstack.exceptions.ResourceNotFound` when no
allocation matching the name or ID could be found.
"""
return self._get_with_fields(_allocation.Allocation, allocation,
fields=fields)
def update_allocation(self, allocation, **attrs):
"""Update an allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param dict attrs: The attributes to update on the allocation
represented by the ``allocation`` parameter.
:returns: The updated allocation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`
"""
return self._update(_allocation.Allocation, allocation, **attrs)
def patch_allocation(self, allocation, patch):
"""Apply a JSON patch to the allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param patch: JSON patch to apply.
:returns: The updated allocation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`
"""
return self._get_resource(_allocation.Allocation,
allocation).patch(self, patch)
def delete_allocation(self, allocation, ignore_missing=True):
"""Delete an allocation.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the allocation could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
allocation.
:returns: The instance of the allocation which was deleted.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`.
"""
return self._delete(_allocation.Allocation, allocation,
ignore_missing=ignore_missing)
def wait_for_allocation(self, allocation, timeout=None,
ignore_error=False):
"""Wait for the allocation to become active.
:param allocation: The value can be the name or ID of an allocation or
a :class:`~openstack.baremetal.v1.allocation.Allocation` instance.
:param timeout: How much (in seconds) to wait for the allocation.
The value of ``None`` (the default) means no client-side timeout.
:param ignore_error: If ``True``, this call will raise an exception
if the allocation reaches the ``error`` state. Otherwise the error
state is considered successful and the call returns.
:returns: The instance of the allocation.
:rtype: :class:`~openstack.baremetal.v1.allocation.Allocation`.
:raises: :class:`~openstack.exceptions.ResourceFailure` if allocation
fails and ``ignore_error`` is ``False``.
:raises: :class:`~openstack.exceptions.ResourceTimeout` on timeout.
"""
res = self._get_resource(_allocation.Allocation, allocation)
return res.wait(self, timeout=timeout, ignore_error=ignore_error)
def add_node_trait(self, node, trait):
"""Add a trait to a node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param trait: trait to remove from the node.
:returns: The updated node
"""
res = self._get_resource(_node.Node, node)
return res.add_trait(self, trait)
def remove_node_trait(self, node, trait, ignore_missing=True):
"""Remove a trait from a node.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param trait: trait to remove from the node.
:param bool ignore_missing: When set to ``False``, an exception
:class:`~openstack.exceptions.ResourceNotFound` will be raised
when the trait could not be found. When set to ``True``, no
exception will be raised when attempting to delete a non-existent
trait.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.remove_trait(self, trait, ignore_missing=ignore_missing)
def set_node_traits(self, node, traits):
"""Set traits for a node.
Removes any existing traits and adds the traits passed in to this
method.
:param node: The value can be the name or ID of a node or a
:class:`~openstack.baremetal.v1.node.Node` instance.
:param traits: list of traits to add to the node.
:returns: The updated :class:`~openstack.baremetal.v1.node.Node`
"""
res = self._get_resource(_node.Node, node)
return res.set_traits(self, traits) | 0.854869 | 0.383295 |
from PyQt5.QtCore import QObject, pyqtSignal, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog
from functools import partial
from PyQt5.QtGui import QIcon, QTextCursor
from .uicore import UI
from core import getPortList, myserial
import time
class MySignals(QObject):
# 定义一种信号,两个参数 类型分别是: QTextBrowser 和 字符串
# 调用 emit方法 发信号时,传入参数 必须是这里指定的 参数类型
print = pyqtSignal(str)
_serialComboBoxResetItems = pyqtSignal(list)
_serialComboBoxClear = pyqtSignal()
_setButtonText = pyqtSignal(str)
_lineClear = pyqtSignal()
print = pyqtSignal(str)
ms = MySignals()
class Action():
def __init__(self, ui: QWidget) -> None:
self.ui = ui
def _serialComboBoxResetItems(self, texts: list):
self.ui.serialComboBox.clear()
self.ui.serialComboBox.addItems(texts)
def _serialComboBoxclear(self):
self.ui.serialComboBox.clear()
def _setButtonText(self, text: str):
self.ui.connectButton.setText(text)
def _lineClear(self):
self.ui.sendEdit.clear()
def print(self, t: str):
tc = self.ui.tb.textCursor()
tc.movePosition(QTextCursor.End)
if self.ui.showTimeCheckBox.isChecked():
nowtime = time.strftime("%H:%M:%S", time.localtime())
tc.insertText("[" + nowtime + "]")
tc.insertText(t)
if self.ui.autoWrapCheckBox.isChecked():
# self.ui.tb.ensureCursorVisible()
self.ui.tb.setTextCursor(tc)
class MainWindow(QWidget):
def __init__(self):
# 从文件中加载UI定义
# 从 UI 定义中动态 创建一个相应的窗口对象
# 注意:里面的控件对象也成为窗口对象的属性了
# 比如 self.ui.button , self.ui.textEdit
super().__init__()
# 使用ui文件导入定义界面类
self.ui = UI()
self.ui.Init_UI(self)
self.a = Action(self.ui)
self.initMS()
self.ports = []
self.selectPort = ""
self.selectBund = ""
self.ser = myserial()
self.timer2 = QTimer()
self.timer2.timeout.connect(self.initSerial)
self.timer2.start(1000)
def initMS(self):
self.ui.connectButton.clicked.connect(self.openPort)
ms._serialComboBoxResetItems.connect(self.a._serialComboBoxResetItems)
ms._serialComboBoxClear.connect(self.a._serialComboBoxclear)
ms._setButtonText.connect(self.a._setButtonText)
ms.print.connect(self.a.print)
ms._lineClear.connect(self.a._lineClear)
self.ui.sendButton.clicked.connect(self.send)
self.ui.serialLabel.button_doubleclicked_signal.connect(self.showAbout)
self.ui.saveButton.clicked.connect(self.savefile)
self.ui.clearButton.clicked.connect(self.ui.tb.clear)
def initSerial(self):
ports = getPortList()
if self.ports != ports:
self.ports = ports
if self.ser.port not in [i.name for i in self.ports]:
self.ser.read_flag = False
ms._serialComboBoxResetItems.emit([i.name for i in self.ports])
if self.ser.read_flag:
ms._setButtonText.emit("断开")
else:
ms._setButtonText.emit("连接")
def openPort(self):
if self.ser.read_flag:
self.ser.stop()
else:
port = self.ui.serialComboBox.currentText()
bund = int(self.ui.baudComboBox.currentText())
if port == "":
ms.print.emit("当前未选择串口\n")
return
self.ser.set(port, bund)
d = self.ser.open(ms.print.emit)
ms.print.emit(d[1])
def send(self):
text = self.ui.sendEdit.text()
if not (text == "") or not (text is None):
if self.ser.read_flag:
self.ser.write(text)
ms._lineClear.emit()
def showAbout(self):
self.ui.msg.show()
def savefile(self):
filename = QFileDialog.getSaveFileName(
self.ui, "open file", "./", "TEXT Files(*.txt)")
# print(filename)
if filename[0] == "" or filename is None:
return
try:
with open(filename[0], "w") as f:
text = self.ui.tb.toPlainText()
f.write(text)
ms.print.emit("保存到"+filename[0])
except Exception as e:
ms.print.emit("保存失败" + str(e))
def runApp():
app = QApplication([])
mainw = MainWindow()
mainw.setWindowIcon(QIcon(':/icon.ico'))
mainw.show()
app.exec_() | ui/mainwindow.py | from PyQt5.QtCore import QObject, pyqtSignal, QTimer
from PyQt5.QtWidgets import QApplication, QWidget, QFileDialog
from functools import partial
from PyQt5.QtGui import QIcon, QTextCursor
from .uicore import UI
from core import getPortList, myserial
import time
class MySignals(QObject):
# 定义一种信号,两个参数 类型分别是: QTextBrowser 和 字符串
# 调用 emit方法 发信号时,传入参数 必须是这里指定的 参数类型
print = pyqtSignal(str)
_serialComboBoxResetItems = pyqtSignal(list)
_serialComboBoxClear = pyqtSignal()
_setButtonText = pyqtSignal(str)
_lineClear = pyqtSignal()
print = pyqtSignal(str)
ms = MySignals()
class Action():
def __init__(self, ui: QWidget) -> None:
self.ui = ui
def _serialComboBoxResetItems(self, texts: list):
self.ui.serialComboBox.clear()
self.ui.serialComboBox.addItems(texts)
def _serialComboBoxclear(self):
self.ui.serialComboBox.clear()
def _setButtonText(self, text: str):
self.ui.connectButton.setText(text)
def _lineClear(self):
self.ui.sendEdit.clear()
def print(self, t: str):
tc = self.ui.tb.textCursor()
tc.movePosition(QTextCursor.End)
if self.ui.showTimeCheckBox.isChecked():
nowtime = time.strftime("%H:%M:%S", time.localtime())
tc.insertText("[" + nowtime + "]")
tc.insertText(t)
if self.ui.autoWrapCheckBox.isChecked():
# self.ui.tb.ensureCursorVisible()
self.ui.tb.setTextCursor(tc)
class MainWindow(QWidget):
def __init__(self):
# 从文件中加载UI定义
# 从 UI 定义中动态 创建一个相应的窗口对象
# 注意:里面的控件对象也成为窗口对象的属性了
# 比如 self.ui.button , self.ui.textEdit
super().__init__()
# 使用ui文件导入定义界面类
self.ui = UI()
self.ui.Init_UI(self)
self.a = Action(self.ui)
self.initMS()
self.ports = []
self.selectPort = ""
self.selectBund = ""
self.ser = myserial()
self.timer2 = QTimer()
self.timer2.timeout.connect(self.initSerial)
self.timer2.start(1000)
def initMS(self):
self.ui.connectButton.clicked.connect(self.openPort)
ms._serialComboBoxResetItems.connect(self.a._serialComboBoxResetItems)
ms._serialComboBoxClear.connect(self.a._serialComboBoxclear)
ms._setButtonText.connect(self.a._setButtonText)
ms.print.connect(self.a.print)
ms._lineClear.connect(self.a._lineClear)
self.ui.sendButton.clicked.connect(self.send)
self.ui.serialLabel.button_doubleclicked_signal.connect(self.showAbout)
self.ui.saveButton.clicked.connect(self.savefile)
self.ui.clearButton.clicked.connect(self.ui.tb.clear)
def initSerial(self):
ports = getPortList()
if self.ports != ports:
self.ports = ports
if self.ser.port not in [i.name for i in self.ports]:
self.ser.read_flag = False
ms._serialComboBoxResetItems.emit([i.name for i in self.ports])
if self.ser.read_flag:
ms._setButtonText.emit("断开")
else:
ms._setButtonText.emit("连接")
def openPort(self):
if self.ser.read_flag:
self.ser.stop()
else:
port = self.ui.serialComboBox.currentText()
bund = int(self.ui.baudComboBox.currentText())
if port == "":
ms.print.emit("当前未选择串口\n")
return
self.ser.set(port, bund)
d = self.ser.open(ms.print.emit)
ms.print.emit(d[1])
def send(self):
text = self.ui.sendEdit.text()
if not (text == "") or not (text is None):
if self.ser.read_flag:
self.ser.write(text)
ms._lineClear.emit()
def showAbout(self):
self.ui.msg.show()
def savefile(self):
filename = QFileDialog.getSaveFileName(
self.ui, "open file", "./", "TEXT Files(*.txt)")
# print(filename)
if filename[0] == "" or filename is None:
return
try:
with open(filename[0], "w") as f:
text = self.ui.tb.toPlainText()
f.write(text)
ms.print.emit("保存到"+filename[0])
except Exception as e:
ms.print.emit("保存失败" + str(e))
def runApp():
app = QApplication([])
mainw = MainWindow()
mainw.setWindowIcon(QIcon(':/icon.ico'))
mainw.show()
app.exec_() | 0.187467 | 0.064065 |
from typing import Optional, Type
from mautrix.util.config import BaseProxyConfig, ConfigUpdateHelper
from maubot import Plugin, MessageEvent
from maubot.handlers import command
import json
import datetime
class Config(BaseProxyConfig):
def do_update(self, helper: ConfigUpdateHelper) -> None:
helper.copy("admin_secret")
helper.copy("legacy_mr")
helper.copy("reg_url")
helper.copy("reg_page")
helper.copy("admins")
helper.copy("expiration")
helper.copy("message")
helper.copy("admin_access_token")
helper.copy("admin_api_url")
class Invite(Plugin):
async def start(self) -> None:
await super().start()
self.config.load_and_update()
@classmethod
def get_config_class(cls) -> Type[BaseProxyConfig]:
return Config
async def can_manage(self, evt: MessageEvent) -> bool:
# check if access_token is defined
if self.config["admin_access_token"]:
# check if CAS SSO users are listed as admins
if 'sso:cas' in self.config["admins"]:
if await self.is_cas_user(evt):
return True
# check if sender is specifically listed as an admin
if evt.sender in self.config["admins"]:
return True
# sender cannot manage
await evt.respond("You don't have permission to manage invitations for this server.")
return False
async def is_cas_user(self, evt: MessageEvent) -> bool:
# retrieve user_profile information
headers = {
'Authorization': f"Bearer {self.config['admin_access_token']}",
'Content-Type': 'application/json'
}
try:
response = await self.http.get(f"{self.config['admin_api_url']}/_synapse/admin/v2/users/{evt.sender}", headers=headers)
status = response.status
resp_json = await response.json()
except Exception as e:
body = await response.text()
await evt.respond(f"Uh oh! I got a {status} response from your admin endpoint:<br /> \
{body}<br /> \
which prompted me to produce this error:<br /> \
<code>{e.message}</code>", allow_html=True)
return False
try:
external_ids = resp_json['external_ids']
for i in external_ids:
if i['auth_provider'] == 'cas':
return True
return False
except Exception as e:
return False
def set_api_endpoints(self) -> None:
self.config["api_url"] = self.config["reg_url"] + "/api"
if self.config["legacy_mr"] == True:
self.config["api_url"] = self.config["reg_url"]
@command.new(name="invite", help="Generate a unique invitation code to this matrix homeserver", \
require_subcommand=True)
async def invite(self, evt: MessageEvent) -> None:
pass
@invite.subcommand("generate", help="Generate a new invitation token.")
async def generate(self, evt: MessageEvent) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
ex_date = datetime.datetime.strftime( \
(datetime.date.today() + datetime.timedelta(days=self.config["expiration"])), \
"%Y-%m-%d")
# use re-ordered date if using legacy code
if self.config["legacy_mr"] == True:
ex_date = datetime.datetime.strftime( \
(datetime.date.today() + datetime.timedelta(days=self.config["expiration"])), \
"%m.%d.%Y")
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}",
'Content-Type': 'application/json'
}
try:
response = await self.http.post(f"{self.config['api_url']}/token", headers=headers, \
json={"max_usage": 1, "one_time": True, "ex_date": ex_date, "expiration_date": ex_date})
status = response.status
resp_json = await response.json()
except Exception as e:
body = await response.text()
await evt.respond(f"Uh oh! I got a {status} response from your registration endpoint:<br /> \
{body}<br /> \
which prompted me to produce this error:<br /> \
<code>{e.message}</code>", allow_html=True)
return None
try:
token = resp_json['name']
except Exception as e:
await evt.respond(f"I got a bad response back, sorry, something is borked. \n\
{resp_json}")
self.log.exception(e)
return None
msg = '<br />'.join(
[
f"Invitation token <b>{token}</b> created!",
f"",
f"Your unique url for registering is:",
f"{self.config['reg_url']}{self.config['reg_page']}?token={token}",
f"This invite token will expire in {self.config['expiration']} days.",
f"If it expires before use, you must request a new token."
])
if self.config['message']:
msg = self.config["message"].format(token=token, reg_url=self.config['reg_url'],
reg_page=self.config['reg_page'], expiration=self.config['expiration'])
await evt.respond(msg, allow_html=True)
@invite.subcommand("status", help="Return the status of an invite token.")
@command.argument("token", "Token", pass_raw=True, required=True)
async def status(self, evt: MessageEvent, token: str) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
if not token:
await evt.respond("you must supply a token to check")
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}",
'Content-Type': 'application/json'
}
try:
response = await self.http.get(f"{self.config['api_url']}/token/{token}", headers=headers)
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
# this isn't formatted nicely but i don't really care that much
await evt.respond(f"Status of token {token}: \n<pre><code format=json>{json.dumps(resp_json, indent=4)}</code></pre>", allow_html=True)
@invite.subcommand("revoke", help="Disable an existing invite token.")
@command.argument("token", "Token", pass_raw=True, required=True)
async def revoke(self, evt: MessageEvent, token: str) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
if not token:
await evt.respond("you must supply a token to revoke")
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}",
'Content-Type': 'application/json'
}
# this is a really gross way of handling legacy installs and should be cleaned up
# basically this command used to use PUT but now uses PATCH
if self.config["legacy_mr"] == True:
try:
response = await self.http.put(f"{self.config['api_url']}/token/{token}", headers=headers, \
json={"disable": True})
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
else:
try:
response = await self.http.patch(f"{self.config['api_url']}/token/{token}", headers=headers, \
json={"disabled": True})
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
# this isn't formatted nicely but i don't really care that much
await evt.respond(f"<pre><code format=json>{json.dumps(resp_json, indent=4)}</code></pre>", allow_html=True)
@invite.subcommand("list", help="List all tokens that have been generated.")
async def list(self, evt: MessageEvent) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}"
}
try:
response = await self.http.get(f"{self.config['api_url']}/token", headers=headers)
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
# this isn't formatted nicely but i don't really care that much
await evt.respond(f"<pre><code format=json>{json.dumps(resp_json, indent=4)}</code></pre>", allow_html=True) | invite.py | from typing import Optional, Type
from mautrix.util.config import BaseProxyConfig, ConfigUpdateHelper
from maubot import Plugin, MessageEvent
from maubot.handlers import command
import json
import datetime
class Config(BaseProxyConfig):
def do_update(self, helper: ConfigUpdateHelper) -> None:
helper.copy("admin_secret")
helper.copy("legacy_mr")
helper.copy("reg_url")
helper.copy("reg_page")
helper.copy("admins")
helper.copy("expiration")
helper.copy("message")
helper.copy("admin_access_token")
helper.copy("admin_api_url")
class Invite(Plugin):
async def start(self) -> None:
await super().start()
self.config.load_and_update()
@classmethod
def get_config_class(cls) -> Type[BaseProxyConfig]:
return Config
async def can_manage(self, evt: MessageEvent) -> bool:
# check if access_token is defined
if self.config["admin_access_token"]:
# check if CAS SSO users are listed as admins
if 'sso:cas' in self.config["admins"]:
if await self.is_cas_user(evt):
return True
# check if sender is specifically listed as an admin
if evt.sender in self.config["admins"]:
return True
# sender cannot manage
await evt.respond("You don't have permission to manage invitations for this server.")
return False
async def is_cas_user(self, evt: MessageEvent) -> bool:
# retrieve user_profile information
headers = {
'Authorization': f"Bearer {self.config['admin_access_token']}",
'Content-Type': 'application/json'
}
try:
response = await self.http.get(f"{self.config['admin_api_url']}/_synapse/admin/v2/users/{evt.sender}", headers=headers)
status = response.status
resp_json = await response.json()
except Exception as e:
body = await response.text()
await evt.respond(f"Uh oh! I got a {status} response from your admin endpoint:<br /> \
{body}<br /> \
which prompted me to produce this error:<br /> \
<code>{e.message}</code>", allow_html=True)
return False
try:
external_ids = resp_json['external_ids']
for i in external_ids:
if i['auth_provider'] == 'cas':
return True
return False
except Exception as e:
return False
def set_api_endpoints(self) -> None:
self.config["api_url"] = self.config["reg_url"] + "/api"
if self.config["legacy_mr"] == True:
self.config["api_url"] = self.config["reg_url"]
@command.new(name="invite", help="Generate a unique invitation code to this matrix homeserver", \
require_subcommand=True)
async def invite(self, evt: MessageEvent) -> None:
pass
@invite.subcommand("generate", help="Generate a new invitation token.")
async def generate(self, evt: MessageEvent) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
ex_date = datetime.datetime.strftime( \
(datetime.date.today() + datetime.timedelta(days=self.config["expiration"])), \
"%Y-%m-%d")
# use re-ordered date if using legacy code
if self.config["legacy_mr"] == True:
ex_date = datetime.datetime.strftime( \
(datetime.date.today() + datetime.timedelta(days=self.config["expiration"])), \
"%m.%d.%Y")
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}",
'Content-Type': 'application/json'
}
try:
response = await self.http.post(f"{self.config['api_url']}/token", headers=headers, \
json={"max_usage": 1, "one_time": True, "ex_date": ex_date, "expiration_date": ex_date})
status = response.status
resp_json = await response.json()
except Exception as e:
body = await response.text()
await evt.respond(f"Uh oh! I got a {status} response from your registration endpoint:<br /> \
{body}<br /> \
which prompted me to produce this error:<br /> \
<code>{e.message}</code>", allow_html=True)
return None
try:
token = resp_json['name']
except Exception as e:
await evt.respond(f"I got a bad response back, sorry, something is borked. \n\
{resp_json}")
self.log.exception(e)
return None
msg = '<br />'.join(
[
f"Invitation token <b>{token}</b> created!",
f"",
f"Your unique url for registering is:",
f"{self.config['reg_url']}{self.config['reg_page']}?token={token}",
f"This invite token will expire in {self.config['expiration']} days.",
f"If it expires before use, you must request a new token."
])
if self.config['message']:
msg = self.config["message"].format(token=token, reg_url=self.config['reg_url'],
reg_page=self.config['reg_page'], expiration=self.config['expiration'])
await evt.respond(msg, allow_html=True)
@invite.subcommand("status", help="Return the status of an invite token.")
@command.argument("token", "Token", pass_raw=True, required=True)
async def status(self, evt: MessageEvent, token: str) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
if not token:
await evt.respond("you must supply a token to check")
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}",
'Content-Type': 'application/json'
}
try:
response = await self.http.get(f"{self.config['api_url']}/token/{token}", headers=headers)
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
# this isn't formatted nicely but i don't really care that much
await evt.respond(f"Status of token {token}: \n<pre><code format=json>{json.dumps(resp_json, indent=4)}</code></pre>", allow_html=True)
@invite.subcommand("revoke", help="Disable an existing invite token.")
@command.argument("token", "Token", pass_raw=True, required=True)
async def revoke(self, evt: MessageEvent, token: str) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
if not token:
await evt.respond("you must supply a token to revoke")
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}",
'Content-Type': 'application/json'
}
# this is a really gross way of handling legacy installs and should be cleaned up
# basically this command used to use PUT but now uses PATCH
if self.config["legacy_mr"] == True:
try:
response = await self.http.put(f"{self.config['api_url']}/token/{token}", headers=headers, \
json={"disable": True})
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
else:
try:
response = await self.http.patch(f"{self.config['api_url']}/token/{token}", headers=headers, \
json={"disabled": True})
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
# this isn't formatted nicely but i don't really care that much
await evt.respond(f"<pre><code format=json>{json.dumps(resp_json, indent=4)}</code></pre>", allow_html=True)
@invite.subcommand("list", help="List all tokens that have been generated.")
async def list(self, evt: MessageEvent) -> None:
await evt.mark_read()
if not await self.can_manage(evt):
return
self.set_api_endpoints()
headers = {
'Authorization': f"SharedSecret {self.config['admin_secret']}"
}
try:
response = await self.http.get(f"{self.config['api_url']}/token", headers=headers)
resp_json = await response.json()
except Exception as e:
await evt.respond(f"request failed: {e.message}")
return None
# this isn't formatted nicely but i don't really care that much
await evt.respond(f"<pre><code format=json>{json.dumps(resp_json, indent=4)}</code></pre>", allow_html=True) | 0.624752 | 0.113236 |
from types import FunctionType
import pkgutil
BUILD_DIR = 'generated'
CLASS_OPTIONS = [':show-inheritance:', ':members:', ':special-members:', ':exclude-members: __init__, __weakref__']
FUNCTION_OPTIONS = []
MODULE_OPTIONS = [':show-inheritance:']
def section(name, level=0, section_levels='*=-'):
return name + '\n' + section_levels[level] * len(name) + '\n'
def walk(module):
modules = []
packages = []
for importer, modname, ispkg in pkgutil.iter_modules(module.__path__):
if ispkg:
packages.append(module.__name__ + '.' + modname)
else:
modules.append(module.__name__ + '.' + modname)
modules = sorted(modules)
packages = sorted(packages)
with open('{}/{}.rst'.format(BUILD_DIR, module.__name__), 'wt') as f:
print(section('{} package'.format(module.__name__)), file=f)
print('.. automodule:: ' + module.__name__, file=f)
for option in MODULE_OPTIONS:
print(' ' + option, file=f)
print('', file=f)
if packages:
print(section('Subpackages', level=1), file=f)
print('.. toctree::', file=f)
for p in packages:
print(' ' + p, file=f)
print('', file=f)
if modules:
print(section('Submodules', level=1), file=f)
for m in modules:
print(section('{} module'.format(m.split('.')[-1]), level=2), file=f)
print('.. automodule:: ' + m, file=f)
for option in MODULE_OPTIONS:
print(' ' + option, file=f)
print('', file=f)
module = __import__(m, fromlist='none')
for k, v in sorted(module.__dict__.items()):
if isinstance(v, (type, FunctionType)) and v.__module__ == m:
if v.__name__.startswith('_') and not v.__doc__:
continue
print('---------\n\n', file=f)
if isinstance(v, type):
print('.. autoclass:: ' + m + '.' + k, file=f)
for option in CLASS_OPTIONS:
print(' ' + option, file=f)
else:
print('.. autofunction:: ' + m + '.' + k, file=f)
for option in FUNCTION_OPTIONS:
print(' ' + option, file=f)
print('', file=f)
for packagename in packages:
package = __import__(packagename, fromlist='none')
walk(package) | docs/source/gen_apidoc.py |
from types import FunctionType
import pkgutil
BUILD_DIR = 'generated'
CLASS_OPTIONS = [':show-inheritance:', ':members:', ':special-members:', ':exclude-members: __init__, __weakref__']
FUNCTION_OPTIONS = []
MODULE_OPTIONS = [':show-inheritance:']
def section(name, level=0, section_levels='*=-'):
return name + '\n' + section_levels[level] * len(name) + '\n'
def walk(module):
modules = []
packages = []
for importer, modname, ispkg in pkgutil.iter_modules(module.__path__):
if ispkg:
packages.append(module.__name__ + '.' + modname)
else:
modules.append(module.__name__ + '.' + modname)
modules = sorted(modules)
packages = sorted(packages)
with open('{}/{}.rst'.format(BUILD_DIR, module.__name__), 'wt') as f:
print(section('{} package'.format(module.__name__)), file=f)
print('.. automodule:: ' + module.__name__, file=f)
for option in MODULE_OPTIONS:
print(' ' + option, file=f)
print('', file=f)
if packages:
print(section('Subpackages', level=1), file=f)
print('.. toctree::', file=f)
for p in packages:
print(' ' + p, file=f)
print('', file=f)
if modules:
print(section('Submodules', level=1), file=f)
for m in modules:
print(section('{} module'.format(m.split('.')[-1]), level=2), file=f)
print('.. automodule:: ' + m, file=f)
for option in MODULE_OPTIONS:
print(' ' + option, file=f)
print('', file=f)
module = __import__(m, fromlist='none')
for k, v in sorted(module.__dict__.items()):
if isinstance(v, (type, FunctionType)) and v.__module__ == m:
if v.__name__.startswith('_') and not v.__doc__:
continue
print('---------\n\n', file=f)
if isinstance(v, type):
print('.. autoclass:: ' + m + '.' + k, file=f)
for option in CLASS_OPTIONS:
print(' ' + option, file=f)
else:
print('.. autofunction:: ' + m + '.' + k, file=f)
for option in FUNCTION_OPTIONS:
print(' ' + option, file=f)
print('', file=f)
for packagename in packages:
package = __import__(packagename, fromlist='none')
walk(package) | 0.330147 | 0.070913 |
import os
import sys
import cmd
import shlex
import fnmatch
import logging
import binascii
import argparse
import traceback
import hexdump
import speakeasy
import speakeasy.winenv.arch as e_arch
from speakeasy.errors import SpeakeasyError
if sys.platform != 'win32':
import readline # noqa (used by cmd)
class DebuggerException(Exception):
pass
def get_logger():
"""
Get the default logger for speakeasy
"""
logger = logging.getLogger('sedbg')
if not logger.handlers:
sh = logging.StreamHandler()
logger.addHandler(sh)
logger.setLevel(logging.INFO)
return logger
class Breakpoint(object):
_id = 0
def __init__(self, address):
if isinstance(address, int):
self.address = address
else:
self.address = address.lower()
self.id = Breakpoint._id
Breakpoint._id += 1
class SpeakeasyDebugger(cmd.Cmd):
prompt = '(sedbg) '
file = None
def __init__(self, target=None, is_sc=False, arch=None, data=None, logger=None, se_inst=None):
super(SpeakeasyDebugger, self).__init__()
self.target = target
self.is_sc = is_sc
self.arch = arch
self.logger = logger
if not se_inst:
self.se = speakeasy.Speakeasy(logger=self.logger)
else:
self.se = se_inst
self.loaded_modules = []
self.loaded_shellcode = []
self.targets = []
self.breakpoints = {}
self.init_state()
if self.is_sc and not self.arch:
raise DebuggerException('Architecture required when debugging shellcode')
if self.target:
if not self.is_sc:
# Load the initial target module
self.load_module(self.target)
else:
self.load_shellcode(self.target, self.arch)
def init_state(self):
if self.se:
self.se.add_code_hook(self.code_hook)
self.se.add_api_hook(self.api_hook, '*', '*') # hook every API
self.step = False
self.running = False
self._do_stop = False
self.exit = False
self.step_over = 0
self.next_pc = 0
def error(self, msg):
self.logger.error('[-] ' + msg)
def info(self, msg):
self.logger.info(msg)
def log_disasm(self, addr, size):
ds = self.se.disasm(addr, size, False)[0]
out = '0x%x: %s %s' % (ds.address, ds.mnemonic, ds.op_str)
self.info(out)
def format_hexdump(self, data, address=0):
output = []
for line in hexdump.hexdump(data, result='generator'):
offset = line[: line.find(':')]
rest = line[line.find(':'):]
offset = int.from_bytes(binascii.unhexlify(offset), 'big')
if address > 0xFFFFFFFF:
fmt = r'%016X'
else:
fmt = r'%08X'
addr = fmt % (offset + address)
output.append(addr + rest)
return '\n'.join(output)
def _break(self, addr):
'''
Return execution back to the debugger and do not execute the
current instruction.
'''
self.step = False
self._do_stop = True
self.next_pc = addr
self.se.stop()
def api_hook(self, emu, api_name, func, params):
'''
Hook called for API calls
'''
rv = func(params)
addr = emu.get_ret_address()
bp = self.breakpoints.get(api_name.lower())
if bp:
self.info('\nBreakpoint %d hit for %s' % (bp.id, api_name))
self.step = True
return rv
elif '.' in api_name:
fn = api_name.split('.')[1]
bp = self.breakpoints.get(fn.lower())
if bp:
self.info('\nBreakpoint %d hit for %s' % (bp.id, api_name))
self.step = True
return rv
for addr, bp in self.breakpoints.items():
if not isinstance(addr, int):
if fnmatch.fnmatch(api_name.lower(), addr.lower()):
self.info('\nBreakpoint %d hit for %s' % (bp.id, api_name))
self.step = True
return rv
return rv
def code_hook(self, emu, addr, size, ctx):
'''
Hook called for each instruction while debugging
'''
if self._do_stop:
self.next_pc = addr
self._do_stop = False
return True
if self.breakpoints:
bp = self.breakpoints.get(addr)
if bp:
self.log_disasm(addr, size)
self.info('\nBreakpoint %d hit for 0x%x' % (bp.id, addr))
self._break(addr)
return True
if self.step:
sres, eres = emu.get_reserved_ranges()
if sres < addr < eres:
addr = emu.get_ret_address()
self.log_disasm(addr, size)
self._break(addr)
return True
def stop(self):
'''
Stop running the emulator
'''
self.se.stop()
self.running = False
def convert_bin_str(self, hstr):
'''
Convert a hex string to an int
'''
# Was a register supplied? Read it.
regs = self.se.get_all_registers()
val = regs.get(hstr.lower())
if val:
hstr = val
if hstr.startswith('0x'):
int_val = int(hstr, 16)
else:
int_val = int(hstr, 10)
return int_val
def dump_mem(self, address, length):
'''
Dump memory (until an invalid memory read or max length occurs)
'''
data = []
try:
for i in range(length):
data.append(self.se.mem_read(address + i, 1))
except SpeakeasyError:
self.error("Failed memory read at address: 0x%x" % (address + i))
return b''.join(data)
def write_mem(self, address, data):
'''
Write memory (until an invalid memory read or max length occurs)
'''
try:
for i, b in enumerate(bytes(data)):
self.se.mem_write(address + i, data[i: i + 1])
except Exception:
self.error("Failed memory write at address: 0x%x" % (address + i))
finally:
return
def do_maps(self, args):
'''
Get a list of all memory maps in the emulation space
Usage:
maps
'''
self.info('Base\t\t Size\t Tag')
for mm in self.se.get_mem_maps():
line = '0x%016x 0x%08x %s' % (mm.get_base(), mm.get_size(), mm.get_tag())
self.info(line)
def do_bl(self, args):
'''
List all current breakpoints and their IDs
Usage:
bl
'''
self.info('Breakpoints:')
for addr, bp in self.breakpoints.items():
if isinstance(addr, int):
line = '%d: 0x%016x' % (bp.id, addr)
else:
line = '%d: %s' % (bp.id, addr)
self.info(line)
def do_bp(self, args):
'''
Set a breakpoint at the specified address or API name
Usage:
bp [ <breakpoint_addr> | <api_name> ]
bp 0x10001020
'''
split_args = shlex.split(args)
address = split_args[0]
try:
address = self.convert_bin_str(address)
bp = Breakpoint(address)
msg = '[*] Breakpoint %d set at address 0x%x' % (bp.id, address)
rv = address
except Exception:
orig = address
address = address.lower()
bp = Breakpoint(address)
msg = '[*] Breakpoint %d set at %s' % (bp.id, orig)
rv = None
self.breakpoints.update({address: bp})
self.info(msg)
return rv
def do_bc(self, args):
'''
Remove a breakpoint by ID
Usage:
bc <breakpoint_id>
bc 1
'''
split_args = shlex.split(args)
try:
_id = int(split_args[0])
except Exception:
self.error('Invalid breakpoint id')
return None
for addr, bp in self.breakpoints.items():
if _id == bp.id:
self.info('[*] Removing breakpoint %d' % (_id))
self.breakpoints.pop(addr)
return addr
def do_disas(self, args):
'''
Disassemble an address
Usage:
disas <address> [length]
'''
split_args = shlex.split(args)
if not split_args:
self.error('Invalid arguments: disas <address> [size]')
return
address = ''
length = '0x10'
address = split_args[0]
try:
length = split_args[1]
except IndexError:
# Use the default length
pass
try:
addr = self.convert_bin_str(address)
length = self.convert_bin_str(length)
instrs = self.se.disasm(addr, length, False)
except ValueError:
self.error('Invalid arguments')
return
except SpeakeasyError:
self.error('Failed to disassemble at address: %s' % (address))
return
for i in instrs:
self.info('0x%x: %s %s' % (i.address, i.mnemonic, i.op_str))
def load_module(self, module):
'''
Load a module into the emulation space
'''
if not os.path.exists(module):
self.error('Can\'t find module: %s' % (module))
else:
module = self.se.load_module(module)
self.loaded_modules.append(module)
def load_shellcode(self, sc_path, arch):
'''
Load shellcode into the emulation space
'''
if self.is_sc:
arch = arch.lower()
if arch in ('x86', 'i386'):
arch = e_arch.ARCH_X86
elif arch in ('x64', 'amd64'):
arch = e_arch.ARCH_AMD64
else:
raise Exception('Unsupported architecture: %s' % arch)
if not os.path.exists(sc_path):
self.error('Can\'t find shellcode: %s' % (sc_path))
else:
sc = self.se.load_shellcode(sc_path, arch)
self.loaded_shellcode.append(sc)
return sc
def do_restart(self, arg):
'''
Restart emulation from the entry point
'''
self.se = speakeasy.Speakeasy(logger=self.logger)
if self.target:
if not self.is_sc:
# Load the initial target module
self.load_module(self.target)
else:
self.load_shellcode(self.target, self.arch)
self.init_state()
self.do_run(None)
def do_load_module(self, arg):
'''
Wrapper to load a module
'''
self.load_module(arg)
def do_eb(self, args):
'''
Edit bytes at the specified address
Usage:
eb <address> <byte_string>
Example:
eb 0x401000 9090909090c3
'''
split_args = shlex.split(args)
if len(split_args) < 2:
self.error('Invalid arguments: eb <address> <byte_string>')
return
address = split_args[0]
address = self.convert_bin_str(address)
data = ''.join(split_args[1:])
# Do some basic normalization
if data.startswith('0x'):
data = data[2:]
data = data.replace(' ', '')
if len(data) % 2:
data = '0' + data
data = binascii.unhexlify(data)
self.write_mem(address, data)
def do_db(self, args):
'''
Dump bytes from emulated memory
Usage:
db <address> [length]
Example:
db 0x401000
'''
split_args = shlex.split(args)
if len(split_args) < 1:
self.error('Invalid arguments: db <address> <size>')
return
address = split_args[0]
address = self.convert_bin_str(address)
decoy = self.se.emu.get_mod_from_addr(address)
if decoy:
self.se.emu.map_decoy(decoy)
if len(split_args) == 1:
address = split_args[0]
address = self.convert_bin_str(address)
data = self.dump_mem(address, 0x50)
elif len(split_args) == 2:
address, length = split_args
address = self.convert_bin_str(address)
length = self.convert_bin_str(length)
data = self.dump_mem(address, length)
output = self.format_hexdump(data, address=address)
self.info(output)
def do_lm(self, args):
'''
List user modules loaded into the emulation space
Usage:
lm
'''
ums = self.se.get_user_modules()
self.info('Start\t\t\tEnd\t\t\tName\t\tPath')
for um in ums:
base = '0x%016x' % um.get_base()
end = '0x%016x' % (um.get_base() + um.get_image_size())
name = um.get_base_name().ljust(16)
path = um.get_emu_path()
self.info('%s\t%s\t%s%s' % (base, end, name, path))
def do_lmk(self, args):
'''
List kernel modules loaded into the emulation space
Usage:
lmk
'''
kms = self.se.get_sys_modules()
self.info('Start\t\t\tEnd\t\t\tName\t\tPath')
for km in kms:
base = '0x%016x' % km.get_base()
end = '0x%016x' % (km.get_base() + km.get_image_size())
name = km.get_base_name().ljust(16)
path = km.get_emu_path()
self.info('%s\t%s\t%s%s' % (base, end, name, path))
def do_reg(self, arg):
'''
Read or write the contents of the emulated cpu registers
Usage:
reg
reg <reg_to_read>
reg <reg_to_write>=<value>
'''
# Is the user requesting all registers?
regs = self.se.get_all_registers()
if not arg:
o = ''
for i, (r, v) in enumerate(regs.items()):
o += '%s=%s ' % (r, v)
if not ((i + 1) % 3):
o += '\n'
self.info(o)
return
# Is the user trying to modify a register?
reg_write = [a.strip() for a in arg.split('=')]
if len(reg_write) > 1:
if len(reg_write) != 2:
self.error('Invalid register write syntax: (e.g. eax=0')
return
reg, val = reg_write
if not regs.get(reg):
self.error('Invalid register: %s' % (reg))
return
try:
int_val = self.convert_bin_str(val)
except ValueError:
self.error('Invalid write value')
return
if int_val is not None:
self.se.reg_write(reg, int_val)
return
val = regs.get(arg.lower())
if not val:
self.error('Invalid register: %s' % (arg))
else:
self.info('%s=%s' % (arg, val))
def do_run(self, arg):
'''Begin emulation of a loaded module'''
if not self.is_sc and not len(self.loaded_modules):
self.error('No modules have been loaded yet')
if not self.running:
if not self.is_sc:
if len(self.loaded_modules) == 1:
self.se.run_module(self.loaded_modules[0],
all_entrypoints=False)
else:
self.se.run_shellcode(self.loaded_shellcode[0], 0)
self.running = True
else:
self.step = False
self.se.resume(self.next_pc, count=-1)
def do_stepi(self, arg):
'''
Step into an instruction
'''
if not self.running:
self.step = True
self.running = True
if not self.is_sc:
self.se.run_module(self.loaded_modules[0],
all_entrypoints=False)
else:
self.se.run_shellcode(self.loaded_shellcode[0], 0)
else:
self.step = True
self.se.resume(self.next_pc, count=1)
def do_stack(self, arg):
'''
Show the current stack layout
'''
stack = self.se.emu.format_stack(16)
ptr_size = self.se.emu.get_ptr_size()
ptr_fmt = '0x%0' + str(ptr_size * 2) + 'x'
for loc in stack:
sp, ptr, tag = loc
if tag:
fmt = 'sp=0x%x:\t' + ptr_fmt + '\t->\t%s'
fmt = fmt % (sp, ptr, tag)
else:
fmt = 'sp=0x%x:\t' + ptr_fmt + '\t'
fmt = fmt % (sp, ptr)
self.info(fmt.expandtabs(5))
def do_strings(self, arg):
'''
Scan all memory segments for strings
'''
tgt_tag_prefixes = ('emu.stack', 'api')
for mmap in self.se.emu.get_mem_maps():
tag = mmap.get_tag()
base = mmap.get_base()
if (tag and tag.startswith(tgt_tag_prefixes) and
tag != self.se.emu.input.get('mem_tag')):
data = self.se.mem_read(mmap.get_base(), mmap.get_size()-1)
ansi_strings = self.se.emu.get_ansi_strings(data)
for offset, astr in ansi_strings:
addr = base + offset
self.info('0x%x: %s' % (addr, astr))
uni_strings = self.se.emu.get_unicode_strings(data)
for offset, wstr in uni_strings:
addr = base + offset
self.info('0x%x: %s' % (addr, wstr))
def do_exit(self, arg):
'''
Quit debugging
'''
self.exit = True
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Debug a Windows binary with speakeasy')
parser.add_argument('-t', '--target', action='store', dest='target',
required=True, help='Path to input file to emulate')
parser.add_argument('-r', '--raw', action='store_true', dest='raw',
required=False, help='Attempt to emulate file as-is '
'with no parsing (e.g. shellcode)')
parser.add_argument('-a', '--arch', action='store', dest='arch',
required=False,
help='Force architecture to use during emulation (for '
'multi-architecture files or shellcode). '
'Supported archs: [ x86 | amd64 ]')
args = parser.parse_args()
dbg = SpeakeasyDebugger(args.target, args.raw, args.arch, logger=get_logger())
dbg.info('Welcome to the speakeasy debugger')
while True:
try:
dbg.cmdloop()
if dbg.exit:
break
except KeyboardInterrupt:
dbg.info('\n[*] User exited')
break
# Catch all other exceptions here
except Exception:
dbg.info(traceback.format_exc()) | debugger/debugger.py |
import os
import sys
import cmd
import shlex
import fnmatch
import logging
import binascii
import argparse
import traceback
import hexdump
import speakeasy
import speakeasy.winenv.arch as e_arch
from speakeasy.errors import SpeakeasyError
if sys.platform != 'win32':
import readline # noqa (used by cmd)
class DebuggerException(Exception):
pass
def get_logger():
"""
Get the default logger for speakeasy
"""
logger = logging.getLogger('sedbg')
if not logger.handlers:
sh = logging.StreamHandler()
logger.addHandler(sh)
logger.setLevel(logging.INFO)
return logger
class Breakpoint(object):
_id = 0
def __init__(self, address):
if isinstance(address, int):
self.address = address
else:
self.address = address.lower()
self.id = Breakpoint._id
Breakpoint._id += 1
class SpeakeasyDebugger(cmd.Cmd):
prompt = '(sedbg) '
file = None
def __init__(self, target=None, is_sc=False, arch=None, data=None, logger=None, se_inst=None):
super(SpeakeasyDebugger, self).__init__()
self.target = target
self.is_sc = is_sc
self.arch = arch
self.logger = logger
if not se_inst:
self.se = speakeasy.Speakeasy(logger=self.logger)
else:
self.se = se_inst
self.loaded_modules = []
self.loaded_shellcode = []
self.targets = []
self.breakpoints = {}
self.init_state()
if self.is_sc and not self.arch:
raise DebuggerException('Architecture required when debugging shellcode')
if self.target:
if not self.is_sc:
# Load the initial target module
self.load_module(self.target)
else:
self.load_shellcode(self.target, self.arch)
def init_state(self):
if self.se:
self.se.add_code_hook(self.code_hook)
self.se.add_api_hook(self.api_hook, '*', '*') # hook every API
self.step = False
self.running = False
self._do_stop = False
self.exit = False
self.step_over = 0
self.next_pc = 0
def error(self, msg):
self.logger.error('[-] ' + msg)
def info(self, msg):
self.logger.info(msg)
def log_disasm(self, addr, size):
ds = self.se.disasm(addr, size, False)[0]
out = '0x%x: %s %s' % (ds.address, ds.mnemonic, ds.op_str)
self.info(out)
def format_hexdump(self, data, address=0):
output = []
for line in hexdump.hexdump(data, result='generator'):
offset = line[: line.find(':')]
rest = line[line.find(':'):]
offset = int.from_bytes(binascii.unhexlify(offset), 'big')
if address > 0xFFFFFFFF:
fmt = r'%016X'
else:
fmt = r'%08X'
addr = fmt % (offset + address)
output.append(addr + rest)
return '\n'.join(output)
def _break(self, addr):
'''
Return execution back to the debugger and do not execute the
current instruction.
'''
self.step = False
self._do_stop = True
self.next_pc = addr
self.se.stop()
def api_hook(self, emu, api_name, func, params):
'''
Hook called for API calls
'''
rv = func(params)
addr = emu.get_ret_address()
bp = self.breakpoints.get(api_name.lower())
if bp:
self.info('\nBreakpoint %d hit for %s' % (bp.id, api_name))
self.step = True
return rv
elif '.' in api_name:
fn = api_name.split('.')[1]
bp = self.breakpoints.get(fn.lower())
if bp:
self.info('\nBreakpoint %d hit for %s' % (bp.id, api_name))
self.step = True
return rv
for addr, bp in self.breakpoints.items():
if not isinstance(addr, int):
if fnmatch.fnmatch(api_name.lower(), addr.lower()):
self.info('\nBreakpoint %d hit for %s' % (bp.id, api_name))
self.step = True
return rv
return rv
def code_hook(self, emu, addr, size, ctx):
'''
Hook called for each instruction while debugging
'''
if self._do_stop:
self.next_pc = addr
self._do_stop = False
return True
if self.breakpoints:
bp = self.breakpoints.get(addr)
if bp:
self.log_disasm(addr, size)
self.info('\nBreakpoint %d hit for 0x%x' % (bp.id, addr))
self._break(addr)
return True
if self.step:
sres, eres = emu.get_reserved_ranges()
if sres < addr < eres:
addr = emu.get_ret_address()
self.log_disasm(addr, size)
self._break(addr)
return True
def stop(self):
'''
Stop running the emulator
'''
self.se.stop()
self.running = False
def convert_bin_str(self, hstr):
'''
Convert a hex string to an int
'''
# Was a register supplied? Read it.
regs = self.se.get_all_registers()
val = regs.get(hstr.lower())
if val:
hstr = val
if hstr.startswith('0x'):
int_val = int(hstr, 16)
else:
int_val = int(hstr, 10)
return int_val
def dump_mem(self, address, length):
'''
Dump memory (until an invalid memory read or max length occurs)
'''
data = []
try:
for i in range(length):
data.append(self.se.mem_read(address + i, 1))
except SpeakeasyError:
self.error("Failed memory read at address: 0x%x" % (address + i))
return b''.join(data)
def write_mem(self, address, data):
'''
Write memory (until an invalid memory read or max length occurs)
'''
try:
for i, b in enumerate(bytes(data)):
self.se.mem_write(address + i, data[i: i + 1])
except Exception:
self.error("Failed memory write at address: 0x%x" % (address + i))
finally:
return
def do_maps(self, args):
'''
Get a list of all memory maps in the emulation space
Usage:
maps
'''
self.info('Base\t\t Size\t Tag')
for mm in self.se.get_mem_maps():
line = '0x%016x 0x%08x %s' % (mm.get_base(), mm.get_size(), mm.get_tag())
self.info(line)
def do_bl(self, args):
'''
List all current breakpoints and their IDs
Usage:
bl
'''
self.info('Breakpoints:')
for addr, bp in self.breakpoints.items():
if isinstance(addr, int):
line = '%d: 0x%016x' % (bp.id, addr)
else:
line = '%d: %s' % (bp.id, addr)
self.info(line)
def do_bp(self, args):
'''
Set a breakpoint at the specified address or API name
Usage:
bp [ <breakpoint_addr> | <api_name> ]
bp 0x10001020
'''
split_args = shlex.split(args)
address = split_args[0]
try:
address = self.convert_bin_str(address)
bp = Breakpoint(address)
msg = '[*] Breakpoint %d set at address 0x%x' % (bp.id, address)
rv = address
except Exception:
orig = address
address = address.lower()
bp = Breakpoint(address)
msg = '[*] Breakpoint %d set at %s' % (bp.id, orig)
rv = None
self.breakpoints.update({address: bp})
self.info(msg)
return rv
def do_bc(self, args):
'''
Remove a breakpoint by ID
Usage:
bc <breakpoint_id>
bc 1
'''
split_args = shlex.split(args)
try:
_id = int(split_args[0])
except Exception:
self.error('Invalid breakpoint id')
return None
for addr, bp in self.breakpoints.items():
if _id == bp.id:
self.info('[*] Removing breakpoint %d' % (_id))
self.breakpoints.pop(addr)
return addr
def do_disas(self, args):
'''
Disassemble an address
Usage:
disas <address> [length]
'''
split_args = shlex.split(args)
if not split_args:
self.error('Invalid arguments: disas <address> [size]')
return
address = ''
length = '0x10'
address = split_args[0]
try:
length = split_args[1]
except IndexError:
# Use the default length
pass
try:
addr = self.convert_bin_str(address)
length = self.convert_bin_str(length)
instrs = self.se.disasm(addr, length, False)
except ValueError:
self.error('Invalid arguments')
return
except SpeakeasyError:
self.error('Failed to disassemble at address: %s' % (address))
return
for i in instrs:
self.info('0x%x: %s %s' % (i.address, i.mnemonic, i.op_str))
def load_module(self, module):
'''
Load a module into the emulation space
'''
if not os.path.exists(module):
self.error('Can\'t find module: %s' % (module))
else:
module = self.se.load_module(module)
self.loaded_modules.append(module)
def load_shellcode(self, sc_path, arch):
'''
Load shellcode into the emulation space
'''
if self.is_sc:
arch = arch.lower()
if arch in ('x86', 'i386'):
arch = e_arch.ARCH_X86
elif arch in ('x64', 'amd64'):
arch = e_arch.ARCH_AMD64
else:
raise Exception('Unsupported architecture: %s' % arch)
if not os.path.exists(sc_path):
self.error('Can\'t find shellcode: %s' % (sc_path))
else:
sc = self.se.load_shellcode(sc_path, arch)
self.loaded_shellcode.append(sc)
return sc
def do_restart(self, arg):
'''
Restart emulation from the entry point
'''
self.se = speakeasy.Speakeasy(logger=self.logger)
if self.target:
if not self.is_sc:
# Load the initial target module
self.load_module(self.target)
else:
self.load_shellcode(self.target, self.arch)
self.init_state()
self.do_run(None)
def do_load_module(self, arg):
'''
Wrapper to load a module
'''
self.load_module(arg)
def do_eb(self, args):
'''
Edit bytes at the specified address
Usage:
eb <address> <byte_string>
Example:
eb 0x401000 9090909090c3
'''
split_args = shlex.split(args)
if len(split_args) < 2:
self.error('Invalid arguments: eb <address> <byte_string>')
return
address = split_args[0]
address = self.convert_bin_str(address)
data = ''.join(split_args[1:])
# Do some basic normalization
if data.startswith('0x'):
data = data[2:]
data = data.replace(' ', '')
if len(data) % 2:
data = '0' + data
data = binascii.unhexlify(data)
self.write_mem(address, data)
def do_db(self, args):
'''
Dump bytes from emulated memory
Usage:
db <address> [length]
Example:
db 0x401000
'''
split_args = shlex.split(args)
if len(split_args) < 1:
self.error('Invalid arguments: db <address> <size>')
return
address = split_args[0]
address = self.convert_bin_str(address)
decoy = self.se.emu.get_mod_from_addr(address)
if decoy:
self.se.emu.map_decoy(decoy)
if len(split_args) == 1:
address = split_args[0]
address = self.convert_bin_str(address)
data = self.dump_mem(address, 0x50)
elif len(split_args) == 2:
address, length = split_args
address = self.convert_bin_str(address)
length = self.convert_bin_str(length)
data = self.dump_mem(address, length)
output = self.format_hexdump(data, address=address)
self.info(output)
def do_lm(self, args):
'''
List user modules loaded into the emulation space
Usage:
lm
'''
ums = self.se.get_user_modules()
self.info('Start\t\t\tEnd\t\t\tName\t\tPath')
for um in ums:
base = '0x%016x' % um.get_base()
end = '0x%016x' % (um.get_base() + um.get_image_size())
name = um.get_base_name().ljust(16)
path = um.get_emu_path()
self.info('%s\t%s\t%s%s' % (base, end, name, path))
def do_lmk(self, args):
'''
List kernel modules loaded into the emulation space
Usage:
lmk
'''
kms = self.se.get_sys_modules()
self.info('Start\t\t\tEnd\t\t\tName\t\tPath')
for km in kms:
base = '0x%016x' % km.get_base()
end = '0x%016x' % (km.get_base() + km.get_image_size())
name = km.get_base_name().ljust(16)
path = km.get_emu_path()
self.info('%s\t%s\t%s%s' % (base, end, name, path))
def do_reg(self, arg):
'''
Read or write the contents of the emulated cpu registers
Usage:
reg
reg <reg_to_read>
reg <reg_to_write>=<value>
'''
# Is the user requesting all registers?
regs = self.se.get_all_registers()
if not arg:
o = ''
for i, (r, v) in enumerate(regs.items()):
o += '%s=%s ' % (r, v)
if not ((i + 1) % 3):
o += '\n'
self.info(o)
return
# Is the user trying to modify a register?
reg_write = [a.strip() for a in arg.split('=')]
if len(reg_write) > 1:
if len(reg_write) != 2:
self.error('Invalid register write syntax: (e.g. eax=0')
return
reg, val = reg_write
if not regs.get(reg):
self.error('Invalid register: %s' % (reg))
return
try:
int_val = self.convert_bin_str(val)
except ValueError:
self.error('Invalid write value')
return
if int_val is not None:
self.se.reg_write(reg, int_val)
return
val = regs.get(arg.lower())
if not val:
self.error('Invalid register: %s' % (arg))
else:
self.info('%s=%s' % (arg, val))
def do_run(self, arg):
'''Begin emulation of a loaded module'''
if not self.is_sc and not len(self.loaded_modules):
self.error('No modules have been loaded yet')
if not self.running:
if not self.is_sc:
if len(self.loaded_modules) == 1:
self.se.run_module(self.loaded_modules[0],
all_entrypoints=False)
else:
self.se.run_shellcode(self.loaded_shellcode[0], 0)
self.running = True
else:
self.step = False
self.se.resume(self.next_pc, count=-1)
def do_stepi(self, arg):
'''
Step into an instruction
'''
if not self.running:
self.step = True
self.running = True
if not self.is_sc:
self.se.run_module(self.loaded_modules[0],
all_entrypoints=False)
else:
self.se.run_shellcode(self.loaded_shellcode[0], 0)
else:
self.step = True
self.se.resume(self.next_pc, count=1)
def do_stack(self, arg):
'''
Show the current stack layout
'''
stack = self.se.emu.format_stack(16)
ptr_size = self.se.emu.get_ptr_size()
ptr_fmt = '0x%0' + str(ptr_size * 2) + 'x'
for loc in stack:
sp, ptr, tag = loc
if tag:
fmt = 'sp=0x%x:\t' + ptr_fmt + '\t->\t%s'
fmt = fmt % (sp, ptr, tag)
else:
fmt = 'sp=0x%x:\t' + ptr_fmt + '\t'
fmt = fmt % (sp, ptr)
self.info(fmt.expandtabs(5))
def do_strings(self, arg):
'''
Scan all memory segments for strings
'''
tgt_tag_prefixes = ('emu.stack', 'api')
for mmap in self.se.emu.get_mem_maps():
tag = mmap.get_tag()
base = mmap.get_base()
if (tag and tag.startswith(tgt_tag_prefixes) and
tag != self.se.emu.input.get('mem_tag')):
data = self.se.mem_read(mmap.get_base(), mmap.get_size()-1)
ansi_strings = self.se.emu.get_ansi_strings(data)
for offset, astr in ansi_strings:
addr = base + offset
self.info('0x%x: %s' % (addr, astr))
uni_strings = self.se.emu.get_unicode_strings(data)
for offset, wstr in uni_strings:
addr = base + offset
self.info('0x%x: %s' % (addr, wstr))
def do_exit(self, arg):
'''
Quit debugging
'''
self.exit = True
return True
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Debug a Windows binary with speakeasy')
parser.add_argument('-t', '--target', action='store', dest='target',
required=True, help='Path to input file to emulate')
parser.add_argument('-r', '--raw', action='store_true', dest='raw',
required=False, help='Attempt to emulate file as-is '
'with no parsing (e.g. shellcode)')
parser.add_argument('-a', '--arch', action='store', dest='arch',
required=False,
help='Force architecture to use during emulation (for '
'multi-architecture files or shellcode). '
'Supported archs: [ x86 | amd64 ]')
args = parser.parse_args()
dbg = SpeakeasyDebugger(args.target, args.raw, args.arch, logger=get_logger())
dbg.info('Welcome to the speakeasy debugger')
while True:
try:
dbg.cmdloop()
if dbg.exit:
break
except KeyboardInterrupt:
dbg.info('\n[*] User exited')
break
# Catch all other exceptions here
except Exception:
dbg.info(traceback.format_exc()) | 0.427158 | 0.065485 |