hexsha stringlengths 40 40 | size int64 3 1.03M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 972 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 10 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 972 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 116k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 972 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 10 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 3 1.03M | avg_line_length float64 1.13 941k | max_line_length int64 2 941k | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
b984fb5f1bc2e6c00dc6e1c7dcc033b91b2aaf15 | 22,289 | py | Python | artssat/dashboard/__init__.py | simonpf/pARTS | b4d9f4c2ceac594273c5589e44fe6a3a4f8d7028 | [
"MIT"
] | 3 | 2020-09-02T08:20:42.000Z | 2020-12-18T17:19:38.000Z | artssat/dashboard/__init__.py | simonpf/pARTS | b4d9f4c2ceac594273c5589e44fe6a3a4f8d7028 | [
"MIT"
] | null | null | null | artssat/dashboard/__init__.py | simonpf/pARTS | b4d9f4c2ceac594273c5589e44fe6a3a4f8d7028 | [
"MIT"
] | null | null | null | import numpy as np
import threading
from bokeh import events
from bokeh.colors import RGB
from bokeh.server.server import Server
from bokeh.application import Application
from bokeh.application.handlers.function import FunctionHandler
from bokeh.plotting import figure, ColumnDataSource, curdoc
from bokeh.models.widgets import Div, Tabs, Panel, Select, CheckboxGroup, \
CheckboxButtonGroup, RadioButtonGroup
from bokeh.models.glyphs import Image
from bokeh.models import Range1d, LinearColorMapper, ColorBar, \
BasicTicker, PrintfTickFormatter, FuncTickFormatter, Rect
from bokeh.models.callbacks import CustomJS
from bokeh.layouts import column, row
from bokeh.palettes import RdBu, Inferno
from artssat.sensor import ActiveSensor, PassiveSensor
class BokehServer():
"""
Handles the singleton Bokeh server used to serve visualisations
if no jupyter notebook is open.
"""
def __init__(self):
self.server = None
def __del__(self):
if not self.server is None:
self.server.io_loop.stop()
self.server.stop()
def start(self, application, port = 5000):
if not self.server is None:
self.server.io_loop.stop()
self.server.stop()
self.server = Server(application, port = port)
self.server.io_loop.start()
standalone_server = BokehServer()
################################################################################
# Profile plot
################################################################################
class ProfilePlot:
"""
A profile plot displays the height distribution of an atmospheric quantity
with respect to either altitude or pressure.
"""
def __init__(self, z, p, title, name, width = 500):
def update_y_variable(attrname, old, new):
if self.y_axis_quantity.active == 0:
self.y = self.z
self.y_range = Range1d(start = self.z[0], end = self.z[-1])
if self.y_axis_quantity.active == 1:
self.y = self.p
self.y_range = Range1d(start = self.p[-1], end = self.p[0])
for s in self.sources:
s.data["y"] = self.y
fig = curdoc().get_model_by_name(self.name).children[0]
fig.y_range = self.y_range
def update_x_scale(attrname, old, new):
if self.x_axis_scale.active == 1:
for s in self.sources:
s.data["x"] = np.log10(s.data["x_"])
else:
for s in self.sources:
s.data["x"] = s.data["x_"]
def update_y_scale(attrname, old, new):
if self.y_axis_scale.active == 1:
for s in self.sources:
s.data["y"] = np.log10(self.y)
else:
for s in self.sources:
s.data["y"] = self.y
self.z = np.copy(z)
self.p = np.copy(p)
self.y = z
self.quantities = []
self.name = name
self.x_axis_scale = RadioButtonGroup(labels = ["linear", "log"],
active = 0)
self.x_axis_scale.on_change("active", update_x_scale)
self.y_axis_scale = RadioButtonGroup(labels = ["linear", "log"],
active = 0)
self.y_axis_scale.on_change("active", update_y_scale)
self.y_axis_quantity = RadioButtonGroup(labels = ["altitude", "pressure"],
active = 0)
self.y_axis_quantity.on_change("active", update_y_variable)
self.sources = []
self.fig = figure(title = title, width = width, height = 500)
def add_quantity(self, x, line_kwargs = {}):
self.sources += [ColumnDataSource(data = dict(x = x,
x_ = x,
y = self.y))]
self.fig.line("x", "y", source = self.sources[-1], **line_kwargs)
@property
def doc(self):
d1 = Div(text = "y-axis variable:", width = 200)
d2 = Div(text = "x-axis scale:", width = 200)
d3 = Div(text = "y-axis scale:", width = 200)
return column(self.fig,
row(d1, self.y_axis_quantity),
row(d2, self.x_axis_scale),
row(d3, self.y_axis_scale),
name = self.name)
class RetrievalResultPlot:
def __init__(self, z, p, retrieval):
self.z = z
self.p = p
y = z
self.retrieval = retrieval
self.retrieval_quantities = retrieval.retrieval_quantities
self.figures = dict([(rq, ProfilePlot(self.z,
self.p,
rq.name,
"rq_plot_" + rq.name,
width = 400)) for
rq in self.retrieval_quantities])
self.status = dict([(rq, True) for rq in self.retrieval_quantities])
self.sources_x = dict([(rq, []) for rq in self.retrieval_quantities])
self.sources_xa = dict([(rq, []) for rq in self.retrieval_quantities])
self.sources_x0 = dict([(rq, []) for rq in self.retrieval_quantities])
self.lines_x = dict([(rq, []) for rq in self.retrieval_quantities])
self.lines_xa = dict([(rq, []) for rq in self.retrieval_quantities])
self.lines_x0 = dict([(rq, []) for rq in self.retrieval_quantities])
#
# Get retrieval results as list.
#
if type(self.retrieval.results) is list:
results = self.retrieval.results
else:
results = [self.retrieval.results]
self.colors = Inferno[len(results) + 2][1:-1]
#
# Add plots for each retrieval quantity.
#
for i, rr in enumerate(self.retrieval.results):
for rq in self.retrieval_quantities:
xa = rr.get_result(rq, attribute = "xa")
x = rr.get_result(rq, attribute = "x")
x0 = rr.get_result(rq, attribute = "x0")
if xa is None:
continue
self.sources_x[rq] += [ColumnDataSource(data =
dict(x = x, y = y))]
self.sources_xa[rq] += [ColumnDataSource(data =
dict(x = xa, y = y))]
self.sources_x0[rq] += [ColumnDataSource(data =
dict(x = x0, y = y))]
fig = self.figures[rq]
fig.add_quantity(x, line_kwargs = dict(line_color = self.colors[i],
line_width = 2))
if i == 0:
fig.add_quantity(xa, line_kwargs = dict(line_dash = "dashed",
line_color = self.colors[i],
line_width = 2))
#fig.add_quantity(x0, line_kwargs = dict(line_dash = "dashdot",
# line_color = self.colors[i],
# line_width = 2))
self.plots = row(*[self.figures[k].doc for k in self.figures],
name = "retrieval_quantities")
def update_plots(attrname, old, new):
state = self.checks.active
plots = curdoc().get_model_by_name('retrieval_quantities')
print(state)
for i, rq in enumerate(self.retrieval_quantities):
if i in state:
if self.status[rq] == True:
continue
else:
self.status[rq] = True
plots.children.append(self.figures[rq].doc)
else:
if self.status[rq] == False:
continue
else:
fig = curdoc().get_model_by_name("rq_plot_" + rq.name)
self.status[rq] = False
plots.children.remove(fig)
print(plots.children)
print(self.status)
#
# Checkbox button to hide plots
#
labels = [rq.name for rq in self.retrieval.retrieval_quantities]
active = list(range(len(labels)))
self.checks = CheckboxButtonGroup(labels = labels, active = active)
self.checks.on_change("active", update_plots)
def make_doc(self):
title = Div(text = "<h2>Retrieved quantities</h2>")
c = column(title, self.checks, self.plots)
return c
class AVKPlot:
def __init__(self, simulation):
self.simulation = simulation
self.sources = {}
if not type(simulation.retrieval.results) is list:
result = simulation.retrieval.results
else:
result = simulation.retrieval.results[-1]
self.figures = {}
self.images = {}
rqs = simulation.retrieval.retrieval_quantities
self.panels = [self._make_avk_plot(result, rq) for rq in rqs]
def _make_avk_plot(self, result, rq):
avk = result.get_avk(rq)
x = np.arange(avk.shape[0])
xx, yy = np.meshgrid(x, x)
self.sources[rq] = ColumnDataSource(data = dict(x = xx.ravel(),
y = yy.ravel(),
z = avk.ravel()))
self.figures[rq] = figure(x_range = (x[0] - 0.5, x[-1] + 0.5),
y_range = (x[0] - 0.5, x[-1] + 0.5),
tools = ["box_zoom", "box_select", "reset"],
width = 600,
aspect_scale = 1.0,
toolbar_location = "above")
colors = RdBu[11]
clim_high = max(avk.max(), -avk.min())
clim_low = min(-avk.max(), avk.min())
mapper = LinearColorMapper(palette= colors,
low = clim_low,
high= clim_high)
self.images[rq] = self.figures[rq].rect(source = self.sources[rq],
x = "x",
y = "y",
fill_color = {'field' : 'z',
'transform' : mapper},
line_color = None,
width = 1,
height = 1)
#marker_source = ColumnDataSource(data = dict(x = np.array([x[0]]),
# y = np.array([x[0]])))
#marker = Rect(x = "x",
# y = "y",
# fill_color = None,
# line_color = RGB(0.0, 0.0, 0.0),
# width = x[-1] - x[0],
# height = 1)
#self.images[rq].add_glyph(marker_source, rect)
#axis = self.figures[rq].xaxis
#axis.major_label_overrides = dict(zip(axis.ticker,
# z[axis.ticker]))
#axis = self.figures[rq].yaxis
#axis.major_label_overrides = dict(zip(axis.ticker,
# z[axis.ticker]))
def update(attr, old, new):
print(old)
print(new)
print(self.sources[rq].selected.indices)
#
# The colorbar
#
color_bar = ColorBar(color_mapper = mapper,
#major_label_text_font_size ="5pt",
ticker = BasicTicker(desired_num_ticks = len(colors)),
formatter = PrintfTickFormatter(format="%.2f"),
label_standoff = 6,
border_line_color=None,
location=(0, 0))
self.figures[rq].add_layout(color_bar, 'right')
#
# Single altitude
#
source = ColumnDataSource(data = dict(x = x, y = avk[0]))
fig = figure(tools = ["box_zoom", "box_select", "reset"],
width = 400,
y_range = [clim_low, clim_high],
toolbar_location = "above")
line = fig.line(x = "x", y = "y", source = source)
#
# Plot callback
#
cb = CustomJS(args = dict(source_avk = self.sources[rq],
#source_marker = marker_source,
source = source), code =
"""
var x = Number(cb_obj["x"]);
var y = Number(cb_obj["y"]);
console.log(x, y);
var i = Math.floor(y);
var j = i + 1;
var n = source.data["x"].length;
source.data["y"] = [];
for (var k = 0; k < n; k++) {
source.data["y"].push(source_avk.data["z"][i * n + k]);
}
source.change.emit();
console.log(source.data["x"].length);
console.log(source.data["y"].length);
""")
self.figures[rq].js_on_event(events.Tap, cb)
r = row(self.figures[rq], fig)
return Panel(child = r, title = rq.name, width = 500)
def make_doc(self):
title = Div(text = "<h2>Averaging kernels</h2>")
t = Tabs(tabs = self.panels)
return column(title, t)
class ObservationPlot:
def __init__(self, sensor):
self.sensor = sensor
self.observations = []
def make_active_sensor_plot(self):
fig = figure(title = self.sensor.name, width = 500)
z = self.sensor.range_bins
x = self.sensor.y
z = np.ravel(0.5 * (z[1:] + z[:-1]))
if self.observations == []:
observations = [sensor.y]
else:
observations = self.observations
for o in observations:
x = o.reshape(z.size, -1)
y = z // 1e3
fig.line(x = x, y = o)
fig.circle(x = x, y = o)
fig.xaxis.axis_label = "Radar reflectivity [{0}]"\
.format(self.sensor.iy_unit)
fig.yaxis.axis_label = "Altitude [km]"
return fig
def make_passive_sensor_plot(self):
fig = figure(title = self.sensor.name, width = 500)
x = self.sensor.f_grid
y = self.sensor.y
for o in self.observations:
fig.line(x = x, y = o)
fig.circle(x = x, y = o)
return fig
def add_observation(self, o):
self.observations += [o]
def make_doc(self):
if isinstance(self.sensor, ActiveSensor):
return self.make_active_sensor_plot()
else:
return self.make_passive_sensor_plot()
################################################################################
# Atmosphere
################################################################################
def plot_temperature(simulation, data_provider):
fig = figure(title = "Temperature", width = 500)
t = simulation.workspace.t_field.value.ravel()
z = simulation.workspace.z_field.value.ravel() / 1e3
fig.line(x = t, y = z)
fig.circle(x = t, y = z)
fig.xaxis.axis_label = "Temperature [K]"
fig.yaxis.axis_label = "Altitude [km]"
return fig
def plot_absorption_species(simulation, data_provider):
fig = figure(title = "Absorption species", width = 500)
for a in simulation.atmosphere.absorbers:
i = a._wsv_index
x = simulation.workspace.vmr_field.value[i, :, :, :].ravel()
z = simulation.workspace.z_field.value.ravel() / 1e3
fig.line(x = x, y = z)
fig.circle(x = x, y = z)
fig.xaxis.axis_label = "VMR [mol/m^3]"
fig.yaxis.axis_label = "Altitude [km]"
return fig
def plot_scattering_species(simulation, data_provider):
pass
def make_atmosphere_panel(simulation, data_provider):
c = column(plot_temperature(simulation, data_provider),
plot_absorption_species(simulation, data_provider))
return Panel(child = c, title = "Atmosphere", width = 600)
################################################################################
# Retrieval
################################################################################
def plot_temperature(simulation, data_provider):
fig = figure(title = "Temperature", width = 500)
t = simulation.workspace.t_field.value.ravel()
z = simulation.workspace.z_field.value.ravel() / 1e3
fig.line(x = t, y = z)
fig.circle(x = t, y = z)
fig.xaxis.axis_label = "Temperature [K]"
fig.yaxis.axis_label = "Altitude [km]"
return fig
def plot_absorption_species(simulation, data_provider):
fig = figure(title = "Absorption species", width = 500)
for a in simulation.atmosphere.absorbers:
i = a._wsv_index
x = simulation.workspace.vmr_field.value[i, :, :, :].ravel()
z = simulation.workspace.z_field.value.ravel() / 1e3
fig.line(x = x, y = z)
fig.circle(x = x, y = z)
fig.xaxis.axis_label = "VMR [mol/m^3]"
fig.yaxis.axis_label = "Altitude [km]"
return fig
def plot_scattering_species(simulation, data_provider):
pass
def make_atmosphere_panel(simulation, data_provider):
c = column(plot_temperature(simulation, data_provider),
plot_absorption_species(simulation, data_provider))
return Panel(child = c, title = "Atmosphere", width = 600)
################################################################################
# Sensor
################################################################################
def make_sensor_plot(sensor):
fig = figure(title = sensor.name, width = 500)
if isinstance(sensor, ActiveSensor):
z = sensor.range_bins
x = sensor.y
z = 0.5 * (z[1:] + z[:-1])
for i in range(sensor.y.shape[1]):
x = sensor.y[:, i]
y = z.ravel() // 1e3
fig.line(x = x, y = y)
fig.circle(x = x, y = y)
fig.xaxis.axis_label = "Radar reflectivity [{0}]"\
.format(sensor.iy_unit)
fig.yaxis.axis_label = "Altitude [km]"
if isinstance(sensor, PassiveSensor):
x = sensor.f_grid
y = sensor.y
for i in range(sensor.y.shape[1]):
fig.line(x = x, y = y[:, i])
fig.circle(x = x, y = y[:, i])
return fig
def make_sensor_panel(sensors):
c = column(*[make_sensor_plot(s) for s in sensors],
sizing_mode = "fixed")
return Panel(child = c, title = "Measurements", width = 600)
def make_retrieval_panel(simulation):
z = np.copy(simulation.workspace.z_field.value.ravel())
p = np.copy(simulation.workspace.p_grid.value.ravel())
retrieval_result_plot = RetrievalResultPlot(z, p, simulation.retrieval)
r = retrieval_result_plot.make_doc()
if type(simulation.retrieval.results) is list:
results = simulation.retrieval.results
else:
results = [simulation.retrieval.results]
if all([not r.avk is None for r in simulation.retrieval.results]):
avks = AVKPlot(simulation)
r.children += avks.make_doc().children
return Panel(child = r, title = "Retrieval", width = 600)
observation_plots = {}
for s in simulation.sensors:
observation_plots[s] = ObservationPlot(s)
if type(simulation.retrieval.results) is list:
plots = []
for r in simulation.retrieval.results:
for s in r.sensors:
i, j = r.sensor_indices[s.name]
observation_plots[s].add_observation(r.y[i : j])
print(r.y[i:j])
observation_plots[s].add_observation(r.yf[i : j])
print(r.yf[i:j])
plot = ProfilePlot(z, p)
for q in r.retrieval_quantities:
x = r.get_result(q)
plot.add_quantity(x, r.name, dict(line_dash = "solid",
line_width = 3))
xa = r.get_result(q, "xa")
plot.add_quantity(xa, r.name, dict(line_dash = "dashed"))
x0 = r.get_result(q, "x0")
if not all(xa == x0):
plot.add_quantity(x0, r.name, dict(line_dash = "dotted"))
plots += [plot]
else:
plot = ProfilePlot(z, p)
for q in r.retrieval_quantities:
x = r.get_result(q)
plot.add(x, r.name, "blue")
plots = [plot]
title = Div(text = "<h2>Retrieved quantities</h2>")
doms = [title] + [p.make_doc() for p in plots]
title = Div(text = "<h2>Fitted measurements</h2>")
doms += [title] + [observation_plots[s].make_doc() for s in simulation.sensors]
c = column(*doms)
return Panel(child = c, title = "Retrieval", width = 600)
def make_document_factory(simulation):
def make_document(doc):
doc.title = "parts dashboard"
sensor_p = make_sensor_panel(simulation.sensors)
atmosphere_p = make_atmosphere_panel(simulation, simulation.data_provider)
retrieval_p = make_retrieval_panel(simulation)
t = Tabs(tabs = [sensor_p,
atmosphere_p,
retrieval_p])
doc.add_root(t)
return make_document
def dashboard(simulation):
apps = {'/': Application(FunctionHandler(make_document_factory(simulation)))}
standalone_server.start(apps, port = 8880)
| 34.343606 | 90 | 0.493652 |
74b3c256178c0c68669fd2e5e0fde78ac0eb3268 | 4,007 | py | Python | demo.py | hujinxinb/FCHD_head_detect | 59e2b55d358e38ae6a3f2cf69403db7aef8016f9 | [
"MIT"
] | 1 | 2019-09-05T06:20:40.000Z | 2019-09-05T06:20:40.000Z | demo.py | hujinxinb/FCHD_head_detect | 59e2b55d358e38ae6a3f2cf69403db7aef8016f9 | [
"MIT"
] | 2 | 2019-04-29T05:56:32.000Z | 2019-10-31T16:29:36.000Z | demo.py | hujinxinb/FCHD_head_detect | 59e2b55d358e38ae6a3f2cf69403db7aef8016f9 | [
"MIT"
] | null | null | null | import tensorflow as tf
import numpy as np
import cv2
import matplotlib as mpl
mpl.use('tkagg')
import matplotlib.pyplot as plt
#from cairocffi import *
import os
from os.path import join as pjoin
import sys
import copy
import detect_face
import nn4 as network
import random
import time
import sklearn
from sklearn.externals import joblib
#face detection parameters
minsize = 20 # minimum size of face
threshold = [ 0.6, 0.7, 0.7 ] # three steps's threshold
factor = 0.709 # scale factor
#facenet embedding parameters
model_dir='./model_check_point/model.ckpt-500000'#"Directory containing the graph definition and checkpoint files.")
model_def= 'models.nn4' # "Points to a module containing the definition of the inference graph.")
image_size=96 #"Image size (height, width) in pixels."
pool_type='MAX' #"The type of pooling to use for some of the inception layers {'MAX', 'L2'}.
use_lrn=False #"Enables Local Response Normalization after the first layers of the inception network."
seed=42,# "Random seed."
batch_size= None # "Number of images to process in a batch."
frame_interval=1 # frame intervals
def to_rgb(img):
w, h = img.shape
ret = np.empty((w, h, 3), dtype=np.uint8)
ret[:, :, 0] = ret[:, :, 1] = ret[:, :, 2] = img
return ret
#restore mtcnn model
print('Creating networks and loading parameters')
gpu_memory_fraction=0.3
with tf.Graph().as_default():
gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=gpu_memory_fraction)
sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options, log_device_placement=False))
with sess.as_default():
pnet, rnet, onet = detect_face.create_mtcnn(sess, './model_check_point/')
# obtaining frames from camera--->converting to gray--->converting to rgb
# --->detecting faces---->croping faces--->embedding--->classifying--->print
video_capture = cv2.VideoCapture('test_video_1.mp4')
fps = video_capture.get(cv2.cv.CV_CAP_PROP_FPS)
size = (int(video_capture.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),
int(video_capture.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
#videoWriter = cv2.VideoWriter('test_video_other.mp4',cv2.cv.CV_FOURCC('M', 'J', 'P', 'G'), fps, size)
# videoWriter = cv2.VideoWriter('test_video_other_1.flv', cv2.cv.CV_FOURCC('I','4','2','0'), fps, size)
c = 0
ret, frame = video_capture.read()
while ret:
# Capture frame-by-frame
# gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# print(frame.shape)
timeF = frame_interval
if (c % timeF == 0): # frame_interval==3, face detection every 3 frames
find_results = []
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
if gray.ndim == 2:
img = to_rgb(gray)
start = time.clock()
bounding_boxes, _ = detect_face.detect_face(img, minsize, pnet, rnet, onet, threshold, factor)
nrof_faces = bounding_boxes.shape[0] # number of faces
# print('The number of faces detected is{}'.format(nrof_faces))
for face_position in bounding_boxes:
face_position = face_position.astype(int)
# print((int(face_position[0]), int( face_position[1])))
# word_position.append((int(face_position[0]), int( face_position[1])))
cv2.rectangle(frame, (face_position[0],
face_position[1]),
(face_position[2], face_position[3]),
(0, 255, 0), 2)
end = time.clock()
time1=end-start
print time1
cv2.putText(frame, 'detected:{}'.format(find_results), (50, 100),
cv2.FONT_HERSHEY_COMPLEX_SMALL, 2, (255, 0, 0),
thickness=2, lineType=2)
# print(faces)
# videoWriter.write(frame)
cv2.imshow('Video', frame)
ret, frame = video_capture.read()
c += 1
# Display the resulting frame
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
| 28.827338 | 116 | 0.670576 |
365bab8d98fc74ac3d56ffe4666ef56e4ffcc9d9 | 43,271 | py | Python | mindspore/train/callback/_summary_collector.py | ysh329/mindspore | 754e253466a77ba5335c38a3ec7598db8ee4990a | [
"Apache-2.0"
] | null | null | null | mindspore/train/callback/_summary_collector.py | ysh329/mindspore | 754e253466a77ba5335c38a3ec7598db8ee4990a | [
"Apache-2.0"
] | null | null | null | mindspore/train/callback/_summary_collector.py | ysh329/mindspore | 754e253466a77ba5335c38a3ec7598db8ee4990a | [
"Apache-2.0"
] | null | null | null | # Copyright 2020-2021 Huawei Technologies Co., Ltd
#
# 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.
# ============================================================================
"""Summary collector callback."""
import os
import re
import json
from json.decoder import JSONDecodeError
from importlib import import_module
from collections.abc import Iterable
import numpy as np
from mindspore import log as logger
from mindspore import context
from mindspore.common.tensor import Tensor
from mindspore.common.parameter import Parameter
from mindspore.train.summary.summary_record import SummaryRecord, process_export_options
from mindspore.train.summary.enums import PluginEnum, ModeEnum
from mindspore.train.callback import Callback, ModelCheckpoint
from mindspore.train import lineage_pb2
from mindspore.train.callback._dataset_graph import DatasetGraph
from mindspore.nn.optim.optimizer import Optimizer
from mindspore.nn.loss.loss import _Loss
from mindspore.train._utils import check_value_type
HYPER_CONFIG_ENV_NAME = "MINDINSIGHT_HYPER_CONFIG"
HYPER_CONFIG_LEN_LIMIT = 100000
class LineageMetadata:
"""Initialize parameters used in model lineage management."""
train_dataset_path = 'train_dataset_path'
valid_dataset_path = 'valid_dataset_path'
train_network = 'train_network'
loss_function = 'loss_function'
loss = 'loss'
optimizer = 'optimizer'
learning_rate = 'learning_rate'
epoch = 'epoch'
step_num = 'step_num'
parallel_mode = 'parallel_mode'
device_num = 'device_num'
batch_size = 'batch_size'
model_path = 'model_path'
model_ckpt = 'model_ckpt'
model_size = 'model_size'
metrics = 'metrics'
train_dataset_size = 'train_dataset_size'
valid_dataset_size = 'valid_dataset_size'
class SummaryCollector(Callback):
"""
SummaryCollector can help you to collect some common information.
It can help you to collect loss, learning late, computational graph and so on.
SummaryCollector also enables the summary operator to collect data to summary files.
Note:
1. Multiple SummaryCollector instances in callback list are not allowed.
2. Not all information is collected at the training phase or at the eval phase.
3. SummaryCollector always record the data collected by the summary operator.
4. SummaryCollector only supports Linux systems.
Args:
summary_dir (str): The collected data will be persisted to this directory.
If the directory does not exist, it will be created automatically.
collect_freq (int): Set the frequency of data collection, it should be greater then zero,
and the unit is `step`. If a frequency is set, we will collect data
when (current steps % freq) equals to 0, and the first step will be collected at any time.
It is important to note that if the data sink mode is used, the unit will become the `epoch`.
It is not recommended to collect data too frequently, which can affect performance. Default: 10.
collect_specified_data (Union[None, dict]): Perform custom operations on the collected data.
By default, if set to None, all data is collected as the default behavior.
You can customize the collected data with a dictionary.
For example, you can set {'collect_metric': False} to control not collecting metrics.
The data that supports control is shown below. Default: None.
- collect_metric (bool): Whether to collect training metrics, currently only the loss is collected.
The first output will be treated as the loss and it will be averaged.
Optional: True/False. Default: True.
- collect_graph (bool): Whether to collect the computational graph. Currently, only
training computational graph is collected. Optional: True/False. Default: True.
- collect_train_lineage (bool): Whether to collect lineage data for the training phase,
this field will be displayed on the lineage page of Mindinsight. Optional: True/False. Default: True.
- collect_eval_lineage (bool): Whether to collect lineage data for the evaluation phase,
this field will be displayed on the lineage page of Mindinsight. Optional: True/False. Default: True.
- collect_input_data (bool): Whether to collect dataset for each training.
Currently only image data is supported.
If there are multiple columns of data in the dataset, the first column should be image data.
Optional: True/False. Default: True.
- collect_dataset_graph (bool): Whether to collect dataset graph for the training phase.
Optional: True/False. Default: True.
- histogram_regular (Union[str, None]): Collect weight and bias for parameter distribution page
and displayed in MindInsight. This field allows regular strings to control which parameters to collect.
It is not recommended to collect too many parameters at once, as it can affect performance.
Note that if you collect too many parameters and run out of memory, the training will fail.
Default: None, it means only the first five parameters are collected.
keep_default_action (bool): This field affects the collection behavior of the 'collect_specified_data' field.
True: it means that after specified data is set, non-specified data is collected as the default behavior.
False: it means that after specified data is set, only the specified data is collected,
and the others are not collected. Optional: True/False, Default: True.
custom_lineage_data (Union[dict, None]): Allows you to customize the data and present it on the MingInsight
lineage page. In the custom data, the type of the key supports str, and the type of value supports str, int
and float. Default: None, it means there is no custom data.
collect_tensor_freq (Optional[int]): The same semantics as the `collect_freq`, but controls TensorSummary only.
Because TensorSummary data is too large to be compared with other summary data, this parameter is used to
reduce its collection. By default, The maximum number of steps for collecting TensorSummary data is 20,
but it will not exceed the number of steps for collecting other summary data.
For example, given `collect_freq=10`, when the total steps is 600, TensorSummary will be collected 20 steps,
while other summary data 61 steps,
but when the total steps is 20, both TensorSummary and other summary will be collected 3 steps.
Also note that when in parallel mode, the total steps will be split evenly, which will
affect the number of steps TensorSummary will be collected.
Default: None, which means to follow the behavior as described above.
max_file_size (Optional[int]): The maximum size in bytes of each file that can be written to the disk.
For example, to write not larger than 4GB, specify `max_file_size=4*1024**3`.
Default: None, which means no limit.
export_options (Union[None, dict]): Perform custom operations on the export data.
Note that the size of export files is not limited by the max_file_size.
You can customize the export data with a dictionary. For example, you can set {'tensor_format': 'npy'}
to export tensor as npy file. The data that supports control is shown below.
Default: None, it means that the data is not exported.
- tensor_format (Union[str, None]): Customize the export tensor format. Supports ["npy", None].
Default: None, it means that the tensor is not exported.
- npy: export tensor as npy file.
Raises:
ValueError: If the parameter value is not expected.
TypeError: If the parameter type is not expected.
RuntimeError: If an error occurs during data collection.
Examples:
>>> # Simple usage:
>>> from mindspore.train import Model
>>> summary_collector = SummaryCollector(summary_dir='./summary_dir')
>>> dataset = get_dataset('/path/to/MNIST')
>>> network = LeNet5()
>>> model = Model(network)
>>> model.train(epoch=1, dataset=dataset, callbacks=summary_collector)
>>>
>>> # Do not collect metric and collect the first layer parameter, others are collected by default
>>> specified={'collect_metric': False, 'histogram_regular': '^conv1.*'}
>>> summary_collector = SummaryCollector(summary_dir='./summary_dir', collect_specified_data=specified)
>>> model.train(epoch=1, dataset=dataset, callbacks=summary_collector)
>>>
>>> # Only collect metric, custom lineage data and record data that collected by the summary operator,
>>> # others are not collected
>>> specified = {'collect_metric': True}
>>> summary_collector = SummaryCollector('./summary_dir',
>>> collect_specified_data=specified,
>>> keep_default_action=False,
>>> custom_lineage_data={'version': 'resnet50_v1'}
>>> )
>>> model.train(epoch=1, dataset=dataset, callbacks=summary_collector)
"""
_DEFAULT_SPECIFIED_DATA = {
'collect_metric': True,
'collect_graph': True,
'collect_train_lineage': True,
'collect_eval_lineage': True,
'collect_input_data': True,
'collect_dataset_graph': True,
'histogram_regular': None
}
def __init__(self,
summary_dir,
collect_freq=10,
collect_specified_data=None,
keep_default_action=True,
custom_lineage_data=None,
collect_tensor_freq=None,
max_file_size=None,
export_options=None):
super(SummaryCollector, self).__init__()
self._summary_dir = self._process_summary_dir(summary_dir)
self._record = None
self._check_positive('collect_freq', collect_freq)
self._collect_freq = collect_freq
self._check_positive('collect_tensor_freq', collect_tensor_freq, allow_none=True)
self._collect_tensor_freq = collect_tensor_freq
self._tensor_collect_range = None
self._check_positive('max_file_size', max_file_size, allow_none=True)
self._max_file_size = max_file_size
self._export_options = process_export_options(export_options)
self._check_action(keep_default_action)
self._collect_specified_data = self._process_specified_data(collect_specified_data, keep_default_action)
msg = f"For 'collect_specified_data' the value after processing is: {self._collect_specified_data}."
logger.info(msg)
self._custom_lineage_data = self._process_custom_lineage_data(custom_lineage_data)
self._temp_optimizer = None
self._has_saved_graph = False
self._has_saved_custom_data = False
self._is_parse_loss_success = True
self._first_step = True
self._dataset_sink_mode = True
def __enter__(self):
self._record = SummaryRecord(log_dir=self._summary_dir,
max_file_size=self._max_file_size,
raise_exception=False,
export_options=self._export_options)
self._first_step, self._dataset_sink_mode = True, True
return self
def __exit__(self, *err):
self._record.close()
@staticmethod
def _process_summary_dir(summary_dir):
"""Check the summary dir, and create a new directory if it not exists."""
check_value_type('summary_dir', summary_dir, str)
summary_dir = summary_dir.strip()
if not summary_dir:
raise ValueError('For `summary_dir` the value should be a valid string of path, but got empty string.')
summary_dir = os.path.realpath(summary_dir)
if not os.path.exists(summary_dir):
os.makedirs(summary_dir, exist_ok=True)
else:
if not os.path.isdir(summary_dir):
raise NotADirectoryError('For `summary_dir` it should be a directory path.')
return summary_dir
@staticmethod
def _check_positive(name, value, allow_none=False):
"""Check if the value to be int type and positive."""
if allow_none and value is None:
return
check_value_type(name, value, int)
if value <= 0:
raise ValueError(f'For `{name}` the value should be greater than 0, but got `{value}`.')
def _process_custom_lineage_data(self, custom_lineage_data):
"""
Check user custom lineage data.
Args:
custom_lineage_data (dict): The user custom defined data.
Raises:
TypeError: If the type of parameters is invalid.
"""
if custom_lineage_data is None:
custom_lineage_data = {}
self._check_custom_lineage_type('custom_lineage_data', custom_lineage_data)
auto_custom_lineage_data = self._collect_optimizer_custom_lineage_data()
self._check_custom_lineage_type('auto_custom_lineage_data', auto_custom_lineage_data)
# the priority of user defined info is higher than auto collected info
auto_custom_lineage_data.update(custom_lineage_data)
custom_lineage_data = auto_custom_lineage_data
return custom_lineage_data
def _check_custom_lineage_type(self, param_name, custom_lineage):
"""Check custom lineage type."""
check_value_type(param_name, custom_lineage, [dict, type(None)])
for key, value in custom_lineage.items():
check_value_type(f'{param_name} -> {key}', key, str)
check_value_type(f'the value of {param_name} -> {key}', value, (int, str, float))
def _collect_optimizer_custom_lineage_data(self):
"""Collect custom lineage data if mindoptimizer has set the hyper config"""
auto_custom_lineage_data = {}
hyper_config = os.environ.get(HYPER_CONFIG_ENV_NAME)
if hyper_config is None:
logger.debug("Hyper config is not in system environment.")
return auto_custom_lineage_data
if len(hyper_config) > HYPER_CONFIG_LEN_LIMIT:
logger.warning("Hyper config is too long. The length limit is %s, the length of "
"hyper_config is %s." % (HYPER_CONFIG_LEN_LIMIT, len(hyper_config)))
return auto_custom_lineage_data
try:
hyper_config = json.loads(hyper_config)
except (TypeError, JSONDecodeError) as exc:
logger.warning("Hyper config decode error. Detail: %s." % str(exc))
return auto_custom_lineage_data
custom_lineage_data = hyper_config.get("custom_lineage_data")
if custom_lineage_data is None:
logger.info("No custom lineage data in hyper config. Please check the custom lineage data "
"if custom parameters exist in the configuration file.")
auto_custom_lineage_data = custom_lineage_data if custom_lineage_data is not None else {}
return auto_custom_lineage_data
@staticmethod
def _check_action(action):
"""Check action type."""
check_value_type('keep_default_action', action, bool)
def _process_specified_data(self, specified_data, action):
"""Check specified data type and value."""
if specified_data is None:
if action:
return dict(self._DEFAULT_SPECIFIED_DATA)
return dict()
check_value_type('collect_specified_data', specified_data, [dict, type(None)])
for param_name in specified_data:
check_value_type(param_name, param_name, [str])
unexpected_params = set(specified_data) - set(self._DEFAULT_SPECIFIED_DATA)
if unexpected_params:
raise ValueError(f'For `collect_specified_data` the keys {unexpected_params} are unsupported, '
f'expect the follow keys: {list(self._DEFAULT_SPECIFIED_DATA.keys())}')
if 'histogram_regular' in specified_data:
regular = specified_data.get('histogram_regular')
check_value_type('histogram_regular', regular, (str, type(None)))
if isinstance(regular, str):
try:
re.match(regular, '')
except re.error as exc:
raise ValueError(f'For `collect_specified_data`, the value of `histogram_regular` '
f'is not a valid regular expression. Detail: {str(exc)}.')
bool_items = set(self._DEFAULT_SPECIFIED_DATA) - {'histogram_regular'}
for item in bool_items:
if item in specified_data:
check_value_type(item, specified_data.get(item), bool)
if action:
result = dict(self._DEFAULT_SPECIFIED_DATA)
result.update(specified_data)
else:
result = specified_data
return result
def begin(self, run_context):
cb_params = run_context.original_args()
self._check_callbacks(cb_params)
if cb_params.mode not in ModeEnum.to_list():
raise ValueError('Only support `train` (model.train) and `eval` (model.eval) mode, '
'but got `{cb_params.mode}` mode.')
self._record.set_mode(cb_params.mode)
self._dataset_sink_mode = cb_params.dataset_sink_mode
def step_end(self, run_context):
cb_params = run_context.original_args()
if cb_params.mode != ModeEnum.TRAIN.value:
return
if not self._has_saved_graph:
self._collect_graphs(cb_params)
self._collect_dataset_graph(cb_params)
self._has_saved_graph = True
self._record.record(cb_params.cur_step_num)
if self._custom_lineage_data and not self._has_saved_custom_data:
packaged_custom_data = self._package_custom_lineage_data(self._custom_lineage_data)
self._record.add_value('custom_lineage_data', 'custom_lineage_data', packaged_custom_data)
self._has_saved_custom_data = True
self._record.record(cb_params.cur_step_num)
if self._first_step:
self._tensor_collect_range = self._get_tensor_collect_range(cb_params, self._dataset_sink_mode)
self._collect_at_step_end(cb_params, plugin_filter=None)
self._first_step = False
self._record.flush()
else:
current = cb_params.cur_epoch_num if self._dataset_sink_mode else cb_params.cur_step_num
if current % self._collect_freq == 0 and current in self._tensor_collect_range:
self._collect_at_step_end(cb_params, plugin_filter=None)
elif current in self._tensor_collect_range:
self._collect_at_step_end(cb_params, lambda plugin: plugin == PluginEnum.TENSOR.value)
elif current % self._collect_freq == 0:
self._collect_at_step_end(cb_params, lambda plugin: plugin != PluginEnum.TENSOR.value)
def _get_tensor_collect_range(self, cb_params, dataset_sink_mode):
"""Get tensor collect range."""
total_step = cb_params.epoch_num
if not dataset_sink_mode:
total_step *= cb_params.batch_num
if self._collect_tensor_freq is not None:
# `total_step + 1`: `total_step` would be a value of `cb_params.cur_step_num`.
return range(0, total_step + 1, self._collect_tensor_freq)
summary_to_collect = len(range(0, total_step + 1, self._collect_freq))
default_tensor_summary_limit = 20
if summary_to_collect > default_tensor_summary_limit:
tensor_freq = total_step // (default_tensor_summary_limit - 1)
if tensor_freq > 1:
return range(0, total_step + 1, tensor_freq)[:default_tensor_summary_limit]
# `cb_params.cur_step_num` counting from `1`, when `1` is in the range, take `1` more steps.
return range(0, total_step + 1)[:default_tensor_summary_limit + 1]
return range(0, total_step + 1, self._collect_freq)
def _collect_at_step_end(self, cb_params, plugin_filter):
self._collect_input_data(cb_params)
self._collect_metric(cb_params)
self._collect_histogram(cb_params)
self._record.record(cb_params.cur_step_num, plugin_filter=plugin_filter)
def epoch_end(self, run_context):
self._record.flush()
def end(self, run_context):
cb_params = run_context.original_args()
if cb_params.mode == ModeEnum.TRAIN.value:
self._collect_train_lineage(cb_params)
else:
self._collect_eval_lineage(cb_params)
# This is a workaround to avoid record '_summary_tensor_cache'.
self._record.set_mode('eval')
# There's nothing special about setting step to 0 here, just to satisfy the interface call
self._record.record(step=0)
def _check_callbacks(self, cb_params):
"""Check there if there are duplicate instances of SummaryCollector."""
callbacks = cb_params.list_callback
is_find = False
for callback in callbacks:
if type(callback).__name__ == self.__class__.__name__:
if not is_find:
is_find = True
continue
raise ValueError(f"There are more than one {self.__class__.__name__} instance in callback list,"
f"but expected only one {self.__class__.__name__} instance.")
@staticmethod
def _package_custom_lineage_data(custom_lineage_data):
"""
Package user-defined lineage data into binary data.
Args:
custom_lineage_data (dict): User custom lineage data.
Returns:
UserDefinedInfo, a object of lineage_pb2.UserDefinedInfo.
"""
user_defined_info = lineage_pb2.UserDefinedInfo()
for key, value in custom_lineage_data.items():
if isinstance(value, int):
attr_name = "map_int32"
elif isinstance(value, float):
attr_name = "map_double"
else:
attr_name = "map_str"
user_info = user_defined_info.user_info.add()
getattr(user_info, attr_name)[key] = value
return user_defined_info
def _collect_input_data(self, cb_params):
"""Only support to collect image data."""
if not self._is_allowed_to_collect_input_data(cb_params):
return
input_data = getattr(cb_params, 'train_dataset_element', None)
if isinstance(input_data, (list, tuple)) and input_data:
input_data = input_data[0]
try:
self._record.add_value(PluginEnum.IMAGE.value, 'input_data/auto', input_data)
except (TypeError, ValueError):
logger.warning('The input data of network are not image, so will not collect by SummaryCollector.')
self._collect_specified_data['collect_input_data'] = False
return
def _is_allowed_to_collect_input_data(self, cb_params):
"""Check if the input data is allowed to be collected."""
if not self._collect_specified_data.get('collect_input_data'):
return False
if self._dataset_sink_mode and (context.get_context('device_target') in ('Ascend', 'GPU')):
logger.warning("On Ascend or GPU device, SummaryCollector is not supported to "
"record input data in dataset sink mode.")
self._collect_specified_data['collect_input_data'] = False
return False
input_data = getattr(cb_params, 'train_dataset_element', None)
if not isinstance(input_data, (Tensor, list, tuple)):
self._collect_specified_data['collect_input_data'] = False
logger.warning("The type of input data is not Tensor/list/tuple, "
"so SummaryCollector will not collect input data.")
return False
if not isinstance(input_data, Tensor) and not input_data:
self._collect_specified_data['collect_input_data'] = False
logger.warning("The 'train_dataset_element' in cb_params is empty, "
"so SummaryCollector will not record the input data. ")
return False
return True
def _collect_dataset_graph(self, cb_params):
"""Only collect train dataset graph."""
if not self._collect_specified_data.get('collect_dataset_graph'):
return
# After analysis, we think that the validated dataset graph and the training dataset graph
# should be consistent under normal scenarios, so only the training dataset graph is collected.
if cb_params.mode == ModeEnum.TRAIN.value:
train_dataset = cb_params.train_dataset
dataset_graph = DatasetGraph()
graph_bytes = dataset_graph.package_dataset_graph(train_dataset)
if graph_bytes is None:
return
self._record.add_value('dataset_graph', 'train_dataset', graph_bytes)
def _collect_graphs(self, cb_params):
"""Collect the graph of train network and eval network."""
if not self._collect_specified_data.get('collect_graph'):
return
network = cb_params.train_network if cb_params.mode == ModeEnum.TRAIN.value else cb_params.eval_network
graph_proto = network.get_func_graph_proto()
if graph_proto is None:
logger.warning("Can not get graph proto, it may not be 'GRAPH_MODE' in context currently, "
"so SummaryCollector will not collect graph.")
return
self._record.add_value(PluginEnum.GRAPH.value, 'train_network/auto', graph_proto)
def _collect_metric(self, cb_params):
"""Collect metric, currently only collection Loss is supported."""
if not self._collect_specified_data.get('collect_metric'):
return
loss = self._get_loss(cb_params)
if loss is None:
return
try:
self._record.add_value(PluginEnum.SCALAR.value, 'loss/auto', loss)
except ValueError:
logger.warning("The output of network is not a scalar, so SummaryCollector will not collect loss.")
self._collect_specified_data['collect_metric'] = False
def _get_loss(self, cb_params):
"""
Get loss from the network output.
Args:
cb_params (_InternalCallbackParam): Callback parameters.
Returns:
Union[Tensor, None], if parse loss success, will return a Tensor value(shape is [1]), else return None.
"""
if not self._is_parse_loss_success:
# If parsing has failed before, avoid repeating it
return None
output = cb_params.net_outputs
if output is None:
logger.warning("Can not find any output by this network, so SummaryCollector will not collect loss.")
self._is_parse_loss_success = False
return None
if isinstance(output, (int, float, Tensor)):
loss = output
elif isinstance(output, (list, tuple)) and output:
# If the output is a list, since the default network returns loss first,
# we assume that the first one is loss.
loss = output[0]
else:
logger.warning("The output type could not be identified, so no loss was recorded in SummaryCollector.")
self._is_parse_loss_success = False
return None
if not isinstance(loss, Tensor):
loss = Tensor(loss)
loss = Tensor(np.mean(loss.asnumpy()))
return loss
def _get_optimizer(self, cb_params):
"""
Get optimizer from the cb_params or parse from the network.
Args:
cb_params (_InternalCallbackParam): Callback parameters.
Returns:
Union[Optimizer, None], if parse optimizer success, will return a optimizer, else return None.
"""
# 'optimizer_failed' means find optimizer failed, so we will not collect data about optimizer.
optimizer_failed = 'Failed'
if self._temp_optimizer == optimizer_failed:
return None
if self._temp_optimizer is not None:
return self._temp_optimizer
optimizer = cb_params.optimizer
if optimizer is None:
network = cb_params.train_network if cb_params.mode == 'train' else cb_params.eval_network
optimizer = self._parse_optimizer_by_network(network)
if optimizer is None or not isinstance(optimizer, Optimizer):
logger.warning("Can not find optimizer in network, or the optimizer does not inherit MindSpore's "
"optimizer, so we will not collect data about optimizer in SummaryCollector.")
optimizer = None
self._temp_optimizer = optimizer if optimizer is not None else optimizer_failed
return optimizer
@staticmethod
def _parse_optimizer_by_network(network):
"""Parse optimizer from network, if parse success will return a optimizer, else return None."""
optimizer = None
for _, cell in network.cells_and_names():
if isinstance(cell, Optimizer):
return cell
try:
optimizer = getattr(cell, 'optimizer')
except AttributeError:
continue
if not isinstance(optimizer, Optimizer):
continue
# Optimizer found successfully
break
return optimizer
def _collect_histogram(self, cb_params):
"""Collect histogram data, contain the parameter weight and bias."""
# Note: if there is not a key named `histogram_regular` in `self._collect_specified_data`,
# it means we will not collect histogram data.
if 'histogram_regular' not in self._collect_specified_data:
return
optimizer = self._get_optimizer(cb_params)
if optimizer is None:
return
parameters = optimizer.parameters
regular = self._collect_specified_data.get('histogram_regular')
if regular is not None:
for parameter in parameters:
if re.match(regular, parameter.name):
self._record.add_value(PluginEnum.HISTOGRAM.value, parameter.name+'/auto', parameter.data)
return
# Note: If `histogram_regular` in `self._collect_specified_data` and the value is None,
# we will collect the first five parameters.
default_parameter_count = 5
for parameter in parameters[:default_parameter_count]:
self._record.add_value(PluginEnum.HISTOGRAM.value, parameter.name+'/auto', parameter.data)
@staticmethod
def _get_learning_rate(optimizer):
"""
parse the learning rate from optimizer.
Args:
optimizer (Optimizer): A optimizer which inherit the MindSpore Optimizer class.
Returns:
Union[Tensor, None], if parse learning rate success, will return a Tensor, else return None.
"""
learning_rate = optimizer.learning_rate
if not isinstance(learning_rate, Parameter):
logger.warning("The learning rate detected in the optimizer is not a Parameter type, "
"so it is not recorded. Its type is %r.", type(learning_rate).__name__)
return None
return learning_rate.data
def _collect_train_lineage(self, cb_params):
"""Collect train lineage data, the detail refer to lineage_pb2.TrainLineage."""
if not self._collect_specified_data.get('collect_train_lineage'):
return
train_lineage = {}
loss = self._get_loss(cb_params)
if loss is not None:
loss_numpy = loss.asnumpy()
loss = float(np.atleast_1d(loss_numpy)[0])
train_lineage[LineageMetadata.loss] = loss
else:
train_lineage[LineageMetadata.loss] = None
optimizer = self._get_optimizer(cb_params)
learning_rate = self._get_learning_rate(optimizer) if optimizer is not None else None
if learning_rate is not None:
train_lineage[LineageMetadata.learning_rate] = list(np.atleast_1d(learning_rate.asnumpy()))[0]
else:
train_lineage[LineageMetadata.learning_rate] = None
train_lineage[LineageMetadata.optimizer] = type(optimizer).__name__ if optimizer else None
train_lineage[LineageMetadata.train_network] = type(cb_params.network).__name__
loss_fn = self._get_loss_fn(cb_params)
train_lineage[LineageMetadata.loss_function] = type(loss_fn).__name__ if loss_fn else None
train_lineage[LineageMetadata.epoch] = cb_params.epoch_num
train_lineage[LineageMetadata.step_num] = cb_params.cur_step_num
train_lineage[LineageMetadata.parallel_mode] = cb_params.parallel_mode
train_lineage[LineageMetadata.device_num] = cb_params.device_number
ckpt_file_path = self._get_ckpt_file_path(cb_params)
train_lineage[LineageMetadata.model_path] = json.dumps(dict(ckpt=ckpt_file_path))
model_size = os.path.getsize(ckpt_file_path) if ckpt_file_path else 0
train_lineage[LineageMetadata.model_size] = model_size
self._parse_dataset(cb_params, train_lineage)
train_lineage_message = self._package_train_lineage_message(train_lineage)
self._record.add_value(PluginEnum.TRAIN_LINEAGE.value, 'train_lineage', train_lineage_message)
@staticmethod
def _package_train_lineage_message(train_lineage):
"""
Package train lineage data into binary data.
Args:
train_lineage (dict): The train lineage dict, refer to the attribute of `_collect_train_lineage` method.
Returns:
TrainLineage, a object of lineage_pb2.TrainLineage.
"""
lineage_message = lineage_pb2.TrainLineage()
if train_lineage.get(LineageMetadata.train_network) is not None:
lineage_message.algorithm.network = train_lineage.get(LineageMetadata.train_network)
if train_lineage.get(LineageMetadata.loss) is not None:
lineage_message.algorithm.loss = train_lineage.get(LineageMetadata.loss)
# Construct train_dataset message.
if train_lineage.get(LineageMetadata.train_dataset_path) is not None:
lineage_message.train_dataset.train_dataset_path = train_lineage.get(LineageMetadata.train_dataset_path)
if train_lineage.get(LineageMetadata.train_dataset_size) is not None:
lineage_message.train_dataset.train_dataset_size = train_lineage.get(LineageMetadata.train_dataset_size)
# Construct model message
lineage_message.model.path = train_lineage.get(LineageMetadata.model_path)
lineage_message.model.size = train_lineage.get(LineageMetadata.model_size)
# Construct hyper_parameters message.
if train_lineage.get(LineageMetadata.learning_rate) is not None:
lineage_message.hyper_parameters.learning_rate = train_lineage.get(LineageMetadata.learning_rate)
if train_lineage.get(LineageMetadata.optimizer) is not None:
lineage_message.hyper_parameters.optimizer = train_lineage.get(LineageMetadata.optimizer)
if train_lineage.get(LineageMetadata.loss_function) is not None:
lineage_message.hyper_parameters.loss_function = train_lineage.get(LineageMetadata.loss_function)
if train_lineage.get(LineageMetadata.parallel_mode) is not None:
lineage_message.hyper_parameters.parallel_mode = train_lineage.get(LineageMetadata.parallel_mode)
lineage_message.hyper_parameters.epoch = train_lineage.get(LineageMetadata.epoch)
lineage_message.hyper_parameters.device_num = train_lineage.get(LineageMetadata.device_num)
lineage_message.hyper_parameters.batch_size = train_lineage.get(LineageMetadata.batch_size)
return lineage_message
def _parse_dataset(self, cb_params, lineage_dict):
"""
Analyze Dataset to get the dataset path and dataset size.
Args:
cb_params (_InternalCallbackParam): Callback parameters.
lineage_dict (dict): The lineage dict, refer to the attribute
of `_collect_train_lineage` method or `_collect_eval_lineage`.
Returns:
dict, the lineage metadata.
"""
dataset = cb_params.train_dataset if cb_params.mode == ModeEnum.TRAIN.value else cb_params.valid_dataset
try:
dataset_path = self._get_dataset_path(dataset)
except IndexError:
dataset_path = None
if dataset_path and os.path.isfile(dataset_path):
dataset_dir = os.path.dirname(dataset_path)
else:
dataset_dir = dataset_path
batch_num = dataset.get_dataset_size()
batch_size = dataset.get_batch_size()
dataset_size = int(batch_num * batch_size)
lineage_dict[LineageMetadata.batch_size] = batch_size
if cb_params.mode == ModeEnum.TRAIN.value:
lineage_dict[LineageMetadata.train_dataset_path] = dataset_dir
lineage_dict[LineageMetadata.train_dataset_size] = dataset_size
else:
lineage_dict[LineageMetadata.valid_dataset_path] = dataset_dir
lineage_dict[LineageMetadata.valid_dataset_size] = dataset_size
return lineage_dict
def _get_dataset_path(self, output_dataset):
"""
Get dataset path of MindDataset object.
Args:
output_dataset (Union[Dataset, ImageFolderDataset, MnistDataset, Cifar10Dataset, Cifar100Dataset,
VOCDataset, CelebADataset, MindDataset, ManifestDataset, TFRecordDataset, TextFileDataset]):
Refer to mindspore.dataset.Dataset.
Returns:
str, dataset path.
Raises:
IndexError: it means get dataset path failed.
"""
dataset_package = import_module('mindspore.dataset')
dataset_dir_set = (dataset_package.ImageFolderDataset, dataset_package.MnistDataset,
dataset_package.Cifar10Dataset, dataset_package.Cifar100Dataset,
dataset_package.VOCDataset, dataset_package.CelebADataset)
dataset_file_set = (dataset_package.MindDataset, dataset_package.ManifestDataset)
dataset_files_set = (dataset_package.TFRecordDataset, dataset_package.TextFileDataset)
dataset_path = ''
if isinstance(output_dataset, dataset_file_set):
dataset_path = output_dataset.dataset_file
if isinstance(output_dataset, dataset_dir_set):
dataset_path = output_dataset.dataset_dir
if isinstance(output_dataset, dataset_files_set):
dataset_path = output_dataset.dataset_files[0]
if dataset_path:
if isinstance(dataset_path, str):
return dataset_path
if isinstance(dataset_path, Iterable):
return list(dataset_path)[0]
return self._get_dataset_path(output_dataset.children[0])
@staticmethod
def _get_ckpt_file_path(cb_params):
"""
Get checkpoint file path from MindSpore callback list.
Args:
cb_params (_InternalCallbackParam): Callback parameters.
Returns:
Union[str, None], if parse success will checkpoint file absolute path, else return None.
"""
callbacks = cb_params.list_callback
ckpt_file_path = None
for callback in callbacks:
if isinstance(callback, ModelCheckpoint):
ckpt_file_path = callback.latest_ckpt_file_name
if ckpt_file_path:
ckpt_file_path = os.path.realpath(ckpt_file_path)
return ckpt_file_path
@staticmethod
def _get_loss_fn(cb_params):
"""
Get loss function by cb_params and analyzing network.
Args:
cb_params (_InternalCallbackParam): Callback parameters.
Returns:
Union[Cell, None], a Cell object, if parse failed, will return None.
"""
loss_fn = cb_params.loss_fn
if loss_fn is not None:
return loss_fn
if cb_params.mode == ModeEnum.TRAIN.value:
network = cb_params.train_network
else:
network = cb_params.eval_network
for _, cell in network.cells_and_names():
if isinstance(cell, _Loss):
loss_fn = cell
break
return loss_fn
def _collect_eval_lineage(self, cb_params):
"""Collect eval lineage data, the detail refer to lineage_pb2.EvaluationLineage."""
if not self._collect_specified_data.get('collect_eval_lineage'):
return
eval_lineage = dict()
eval_lineage[LineageMetadata.metrics] = json.dumps(cb_params.metrics)
self._parse_dataset(cb_params, eval_lineage)
eval_lineage_message = self._package_eval_lineage_message(eval_lineage)
self._record.add_value(PluginEnum.EVAL_LINEAGE.value, 'eval_lineage', eval_lineage_message)
@staticmethod
def _package_eval_lineage_message(eval_lineage):
"""
Package eval lineage data into binary data.
Args:
eval_lineage (dict): The eval lineage dict, refer to the attribute of `_collect_eval_lineage` method.
Returns:
EvaluationLineage, a object of lineage_pb2.EvaluationLineage.
"""
lineage_message = lineage_pb2.EvaluationLineage()
if eval_lineage.get(LineageMetadata.metrics) is not None:
lineage_message.metric = eval_lineage.get(LineageMetadata.metrics)
if eval_lineage.get(LineageMetadata.valid_dataset_path) is not None:
lineage_message.valid_dataset.valid_dataset_path = eval_lineage.get(LineageMetadata.valid_dataset_path)
if eval_lineage.get(LineageMetadata.valid_dataset_size) is not None:
lineage_message.valid_dataset.valid_dataset_size = eval_lineage.get(LineageMetadata.valid_dataset_size)
return lineage_message
| 45.837924 | 120 | 0.668854 |
3686dc480b405b470304bef5ff912554187395d7 | 9,246 | py | Python | build/lib/vespy/fk.py | NeilWilkins/VesPy | 29b766b737a470915cf02ed70f4077cec1ff77c5 | [
"MIT"
] | 7 | 2019-05-07T14:14:41.000Z | 2022-03-24T06:30:08.000Z | vespy/fk.py | NeilWilkins/VesPy | 29b766b737a470915cf02ed70f4077cec1ff77c5 | [
"MIT"
] | null | null | null | vespy/fk.py | NeilWilkins/VesPy | 29b766b737a470915cf02ed70f4077cec1ff77c5 | [
"MIT"
] | 2 | 2019-05-07T14:14:41.000Z | 2022-01-16T23:52:16.000Z | # fk.py
# module: vespy.fk
# FK analysis functions for seismic data
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from vespy.utils import get_station_coordinates
def fk_analysis(st, smax, fmin, fmax, tmin, tmax, stat='power'):
'''
Performs frequency-wavenumber space (FK) analysis on a stream of time series data for a given slowness range, frequency band and time window.
For an input stream of length K, the output is a K x K array with values of the chosen statistic calculated on a slowness grid in the x and y spatial dimensions. This statistic can be one of:-
* 'power' - the power in frequency-domain stack
* 'semblance' - the semblance calculated in the frequency domain
* 'F' - the F-statistic calculated in the frequency domain
Before the FK analysis is performed, the seismograms are cut to a time window between tmin and tmax, and the data is bandpass-filtered between frequencies fmin and fmax.
Parameters
----------
st : ObsPy Stream object
Stream of SAC format seismograms for the seismic array, length K = no. of stations in array
smax : float
Maximum magnitude of slowness, used for constructing the slowness grid in both x and y directions
fmin : float
Lower end of frequency band to perform FK analysis over
fmax : float
Upper end of frequency band to perform FK analysis over
tmin : float
Start of time window, seismograms are cut between tmin and tmax before FK starts
tmax : int
End of time window, seismograms are cut between tmin and tmax before FK starts
stat : string
Statistic that is to be calculated over the slowness grid, either 'power', 'semblance', or 'F'
Returns
-------
fk : NumPy array
The chosen statistic calculated at each point in a K x K grid of slowness values in the x and y directions
'''
assert (stat == 'power' or stat == 'semblance' or stat == 'F'), "Argument 'stat' must be one of 'power', 'semblance' or 'F'"
st = st.copy().trim(starttime=tmin, endtime=tmax)
# Retrieve metadata: time step and number of stations to be stacked
delta = st[0].stats.delta
nbeam = len(st)
# Pre-process, and filter to frequency window
st.detrend()
st.taper(type='cosine', max_percentage=0.05)
st = st.copy().filter("bandpass", freqmin=fmin, freqmax=fmax)
npts = st[0].stats.npts
# Computer Fourier transforms for each trace
fft_st = np.zeros((nbeam, (npts / 2) + 1), dtype=complex) # Length of real FFT is only half that of time series data
for i, tr in enumerate(st):
fft_st[i, :] = np.fft.rfft(tr.data) # Only need positive frequencies, so use rfft
freqs = np.fft.fftfreq(npts, delta)[0:(npts / 2) + 1]
# Slowness grid
slow_x = np.linspace(-smax, smax, nbeam)
slow_y = np.linspace(-smax, smax, nbeam)
# Array geometry
x, y = np.split(get_station_coordinates(st)[:, :2], 2, axis=1)
# convert to km
x /= 1000.
y /= 1000.
# Calculate the F-K spectrum
fk = np.zeros((nbeam, nbeam))
for ii in range(nbeam):
for jj in range(nbeam):
dt = slow_x[jj] * x + slow_y[ii] * y
beam = np.sum(np.exp(-1j * 2 * np.pi * np.outer(dt, freqs)) * fft_st / nbeam, axis=0)
fk[ii, jj] = np.vdot(beam, beam).real
if stat == 'semblance' or stat == 'F':
tracepower = np.vdot(fft_st, fft_st).real
if stat == 'semblance':
fk_semb = nbeam * fk / tracepower
return fk_semb
elif stat == 'F':
fk_F = (nbeam - 1)* nbeam * fk / (tracepower - nbeam * fk)
return fk_F
else:
return fk
def fk_slowness_vector(st, smax, fmin, fmax, tmin, tmax, stat='power'):
'''
Returns the slowness vector (amplitude and back azimuth) for time series data from a seismic array, as calculated using FK-beamforming.
Performs frequency-wavenumber space (FK) analysis on a stream of time series data for a given slowness range, frequency band and time window.
The output is a tuple containing the scalar slowness and backazimuth of the incoming wave, determined using a grid search to maximise the chosen beamforming statistic. This can be one of:-
* 'power' - the power in frequency-domain stack
* 'semblance' - the semblance calculated in the freqency domain
* 'F' - the F-statistic calculated in the frequency domain
Before the FK analysis is performed, the seismograms are cut to a time window between tmin and tmax, and the data is bandpass-filtered between frequencies fmin and fmax.
Parameters
----------
st : ObsPy Stream object
Stream of SAC format seismograms for the seismic array, length K = no. of stations in array
smax : float
Maximum magnitude of slowness, used for constructing the slowness grid in both x and y directions
fmin : float
Lower end of frequency band to perform FK analysis over
fmax : float
Upper end of frequency band to perform FK analysis over
tmin : float
Start of time window, seismograms are cut between tmin and tmax before FK starts
tmax : int
End of time window, seismograms are cut between tmin and tmax before FK starts
stat : string
Statistic that is to be calculated over the slowness grid, either 'power', 'semblance', or 'F'
Returns
-------
slowness : float
The scalar magnitude, in s/km, of the slowness of the incident seismic wave, as determined by the FK analysis
backazimuth: float
The backazimuth, in degrees, from North back to the epicentre of the incident seismic wave, as determined by the FK analysis
'''
nbeam = len(st)
fk = fk_analysis(st, smax, fmin, fmax, tmin, tmax, stat)
# Find maximum
fkmax = np.unravel_index(np.argmax(fk), (nbeam, nbeam))
# Slowness ranges
slow_x = np.linspace(-smax, smax, nbeam)
slow_y = np.linspace(-smax, smax, nbeam)
slow_x_max = slow_x[fkmax[1]]
slow_y_max = slow_y[fkmax[0]]
slowness = np.hypot(slow_x_max, slow_y_max)
backazimuth = np.degrees(np.arctan2(slow_x_max, slow_y_max))
if backazimuth < 0:
backazimuth += 360. # For backazimuths in range 0 - 360 deg
return (slowness, backazimuth)
def fk_plot(st, smax, fmin, fmax, tmin, tmax, stat='power', outfile=None):
'''
Plots the results of FK analysis on a stream of time series data from a seismic array.
Performs frequency-wavenumber space (FK) analysis on a stream of time series data for a given slowness range, frequency band and time window.
This function plots the chosen statistic on a slowness grid in the x and y directions. The statistic can be one of:-
* 'power' - the power in frequency-domain stack
* 'semblance' - the semblance calculated in the freqency domain
* 'F' - the F-statistic calculated in the frequency domain
The title of the plot also contains the slowness and backazimuth for which the chosen statistic is maximised,
Before the FK analysis is performed, the seismograms are cut to a time window between tmin and tmax, and the data is bandpass-filtered between frequencies fmin and fmax.
Parameters
----------
st : ObsPy Stream object
Stream of SAC format seismograms for the seismic array, length K = no. of stations in array
smax : float
Maximum magnitude of slowness, used for constructing the slowness grid in both x and y directions
fmin : float
Lower end of frequency band to perform FK analysis over
fmax : float
Upper end of frequency band to perform FK analysis over
tmin : float
Start of time window, seismograms are cut between tmin and tmax before FK starts
tmax : int
End of time window, seismograms are cut between tmin and tmax before FK starts
stat : string
Statistic that is to be calculated over the slowness grid, either 'power', 'semblance', or 'F'
'''
plt.set_cmap(cm.viridis)
nbeam = len(st)
fk = fk_analysis(st, smax, fmin, fmax, tmin, tmax, stat)
# Slowness ranges
slow_x = np.linspace(-smax, smax, nbeam)
slow_y = np.linspace(-smax, smax, nbeam)
# Find maximum
fkmax = np.unravel_index(np.argmax(fk), (nbeam, nbeam))
slow_x_max = slow_x[fkmax[1]]
slow_y_max = slow_y[fkmax[0]]
slowness = np.hypot(slow_x_max, slow_y_max)
backazimuth = np.degrees(np.arctan2(slow_x_max, slow_y_max))
if backazimuth < 0:
backazimuth += 360.
fig = plt.figure(figsize=(16, 14))
fig.add_axes([0.5,0.5,0.45,0.45])
plt.contourf(slow_x, slow_y, fk, 16)
plt.grid('on', linestyle='-')
plt.xlabel('slowness east (s/km)', fontsize=16)
plt.ylabel('slowness north (s/km)', fontsize=16)
cb = plt.colorbar()
cb.set_label(stat, fontsize=16)
plt.xlim(-smax, smax);
plt.ylim(-smax, smax);
plt.tick_params(axis='both', which='major', labelsize=14)
plt.title("FK Analysis, slowness= " + '%.4f' % slowness + " s/km, backazimuth= " + '%.1f' % backazimuth + " deg", y=1.08, fontsize=18)
if outfile is not None:
plt.savefig(outfile, bbox_inches='tight')
plt.show()
| 39.512821 | 196 | 0.672399 |
ca97848e4e72a8bb9708aeb1141c84c621369f85 | 1,151 | py | Python | playground/auxiliary/tools.py | kangyifei/CloudSimPy | 45912e7ea35086b67941624102e400cb22e549ab | [
"MIT"
] | 78 | 2019-03-03T12:36:18.000Z | 2020-10-12T08:54:02.000Z | playground/Non_DAG/utils/tools.py | GengxinLiu/CloudSimPy | c103672f51d6617707501f05548a7df6090cdca5 | [
"MIT"
] | 11 | 2019-03-15T12:48:34.000Z | 2020-09-16T06:57:59.000Z | playground/Non_DAG/utils/tools.py | GengxinLiu/CloudSimPy | c103672f51d6617707501f05548a7df6090cdca5 | [
"MIT"
] | 34 | 2019-03-15T12:10:25.000Z | 2020-10-31T22:24:56.000Z | import time
import numpy as np
import tensorflow as tf
def average_completion(exp):
completion_time = 0
number_task = 0
for job in exp.simulation.cluster.jobs:
for task in job.tasks:
number_task += 1
completion_time += (task.finished_timestamp - task.started_timestamp)
return completion_time / number_task
def average_slowdown(exp):
slowdown = 0
number_task = 0
for job in exp.simulation.cluster.jobs:
for task in job.tasks:
number_task += 1
slowdown += (task.finished_timestamp - task.started_timestamp) / task.task_config.duration
return slowdown / number_task
def multiprocessing_run(episode, trajectories, makespans, average_completions, average_slowdowns):
np.random.seed(int(time.time()))
tf.random.set_random_seed(time.time())
episode.run()
trajectories.append(episode.simulation.scheduler.algorithm.current_trajectory)
makespans.append(episode.simulation.env.now)
# print(episode.simulation.env.now)
average_completions.append(average_completion(episode))
average_slowdowns.append(average_slowdown(episode))
| 32.885714 | 102 | 0.724587 |
1fad7490bfbaf75ea555b9cfcf1675e3809d61a4 | 593 | py | Python | src/pytest/__main__.py | compas-dev/ironpython-pytest | 6d0eceddce0dac91b363dd72d15d7ff00cc7c9af | [
"MIT"
] | 1 | 2020-04-25T12:09:20.000Z | 2020-04-25T12:09:20.000Z | src/pytest/__main__.py | compas-dev/ironpython-pytest | 6d0eceddce0dac91b363dd72d15d7ff00cc7c9af | [
"MIT"
] | null | null | null | src/pytest/__main__.py | compas-dev/ironpython-pytest | 6d0eceddce0dac91b363dd72d15d7ff00cc7c9af | [
"MIT"
] | null | null | null | from __future__ import print_function
import argparse
import os
from .test_runner import run
def main():
parser = argparse.ArgumentParser(description='IronPython pytest runner.')
parser.add_argument('file_or_dir', type=str, help='Directory or file to test', default=os.path.dirname(__file__))
parser.add_argument('--ignore', type=str, action='append',
help='Ignore files during testing (multiple allowed)')
args = parser.parse_args()
run(args.file_or_dir, exclude_list=args.ignore, capture_stdout=True)
if __name__ == '__main__':
main()
| 26.954545 | 117 | 0.713322 |
c115356955f3398b14f8aaf77d10159783cae6d3 | 1,670 | py | Python | BuyTokens.py | systemquant/DeFi_PanCakeSwapBot | 39665bfd095e9b571a70699926c080882e5b456d | [
"MIT"
] | 142 | 2021-08-30T19:57:29.000Z | 2022-03-30T15:03:35.000Z | BuyTokens.py | systemquant/DeFi_PanCakeSwapBot | 39665bfd095e9b571a70699926c080882e5b456d | [
"MIT"
] | 21 | 2021-09-04T20:57:31.000Z | 2022-03-02T00:09:08.000Z | BuyTokens.py | systemquant/DeFi_PanCakeSwapBot | 39665bfd095e9b571a70699926c080882e5b456d | [
"MIT"
] | 116 | 2021-09-01T13:32:46.000Z | 2022-03-29T05:17:15.000Z | import config
import time
def buyTokens(**kwargs):
symbol = kwargs.get('symbol')
web3 = kwargs.get('web3')
walletAddress = kwargs.get('walletAddress')
contractPancake = kwargs.get('contractPancake')
TokenToBuyAddress = kwargs.get('TokenToSellAddress')
WBNB_Address = kwargs.get('WBNB_Address')
toBuyBNBAmount = input(f"Enter amount of BNB you want to buy {symbol}: ")
toBuyBNBAmount = web3.toWei(toBuyBNBAmount, 'ether')
pancakeSwap_txn = contractPancake.functions.swapExactETHForTokens(0,
[WBNB_Address, TokenToBuyAddress],
walletAddress,
(int(time.time() + 10000))).buildTransaction({
'from': walletAddress,
'value': toBuyBNBAmount, # Amount of BNB
'gas': 160000,
'gasPrice': web3.toWei('5', 'gwei'),
'nonce': web3.eth.get_transaction_count(walletAddress)
})
signed_txn = web3.eth.account.sign_transaction(pancakeSwap_txn, private_key=config.YOUR_PRIVATE_KEY)
try:
tx_token = web3.eth.send_raw_transaction(signed_txn.rawTransaction)
result = [web3.toHex(tx_token), f"Bought {web3.fromWei(toBuyBNBAmount, 'ether')} BNB of {symbol}"]
return result
except ValueError as e:
if e.args[0].get('message') in 'intrinsic gas too low':
result = ["Failed", f"ERROR: {e.args[0].get('message')}"]
else:
result = ["Failed", f"ERROR: {e.args[0].get('message')} : {e.args[0].get('code')}"]
return result
| 43.947368 | 116 | 0.581437 |
cb85579d565dde442e10b14ebedfc7f13f61bd38 | 7,045 | py | Python | examples/rfcn/lib/rpn/proposal_layer.py | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 933 | 2016-08-29T14:29:20.000Z | 2022-03-20T09:03:49.000Z | examples/rfcn/lib/rpn/proposal_layer.py | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 286 | 2016-08-30T01:33:01.000Z | 2021-08-22T08:34:19.000Z | examples/rfcn/lib/rpn/proposal_layer.py | ayzk/ft-caffe-public | 888399c2fcf90c227416576a5a265b218c6be5da | [
"BSD-2-Clause"
] | 611 | 2016-08-30T07:22:04.000Z | 2021-12-18T11:53:08.000Z | # --------------------------------------------------------
# Faster R-CNN
# Copyright (c) 2015 Microsoft
# Licensed under The MIT License [see LICENSE for details]
# Written by Ross Girshick and Sean Bell
# --------------------------------------------------------
import caffe
import numpy as np
import yaml
from fast_rcnn.config import cfg
from generate_anchors import generate_anchors
from fast_rcnn.bbox_transform import bbox_transform_inv, clip_boxes
from fast_rcnn.nms_wrapper import nms
DEBUG = False
class ProposalLayer(caffe.Layer):
"""
Outputs object detection proposals by applying estimated bounding-box
transformations to a set of regular boxes (called "anchors").
"""
def setup(self, bottom, top):
# parse the layer parameter string, which must be valid YAML
layer_params = yaml.load(self.param_str)
self._feat_stride = layer_params['feat_stride']
anchor_scales = layer_params.get('scales', (8, 16, 32))
self._anchors = generate_anchors(scales=np.array(anchor_scales))
self._num_anchors = self._anchors.shape[0]
if DEBUG:
print 'feat_stride: {}'.format(self._feat_stride)
print 'anchors:'
print self._anchors
# rois blob: holds R regions of interest, each is a 5-tuple
# (n, x1, y1, x2, y2) specifying an image batch index n and a
# rectangle (x1, y1, x2, y2)
top[0].reshape(1, 5)
# scores blob: holds scores for R regions of interest
if len(top) > 1:
top[1].reshape(1, 1, 1, 1)
def forward(self, bottom, top):
# Algorithm:
#
# for each (H, W) location i
# generate A anchor boxes centered on cell i
# apply predicted bbox deltas at cell i to each of the A anchors
# clip predicted boxes to image
# remove predicted boxes with either height or width < threshold
# sort all (proposal, score) pairs by score from highest to lowest
# take top pre_nms_topN proposals before NMS
# apply NMS with threshold 0.7 to remaining proposals
# take after_nms_topN proposals after NMS
# return the top proposals (-> RoIs top, scores top)
assert bottom[0].data.shape[0] == 1, \
'Only single item batches are supported'
#cfg_key = str(self.phase) # either 'TRAIN' or 'TEST'
cfg_key = str('TRAIN' if self.phase == 0 else 'TEST')
pre_nms_topN = cfg[cfg_key].RPN_PRE_NMS_TOP_N
post_nms_topN = cfg[cfg_key].RPN_POST_NMS_TOP_N
nms_thresh = cfg[cfg_key].RPN_NMS_THRESH
min_size = cfg[cfg_key].RPN_MIN_SIZE
# the first set of _num_anchors channels are bg probs
# the second set are the fg probs, which we want
scores = bottom[0].data[:, self._num_anchors:, :, :]
bbox_deltas = bottom[1].data
im_info = bottom[2].data[0, :]
if DEBUG:
print 'im_size: ({}, {})'.format(im_info[0], im_info[1])
print 'scale: {}'.format(im_info[2])
# 1. Generate proposals from bbox deltas and shifted anchors
height, width = scores.shape[-2:]
if DEBUG:
print 'score map size: {}'.format(scores.shape)
# Enumerate all shifts
shift_x = np.arange(0, width) * self._feat_stride
shift_y = np.arange(0, height) * self._feat_stride
shift_x, shift_y = np.meshgrid(shift_x, shift_y)
shifts = np.vstack((shift_x.ravel(), shift_y.ravel(),
shift_x.ravel(), shift_y.ravel())).transpose()
# Enumerate all shifted anchors:
#
# add A anchors (1, A, 4) to
# cell K shifts (K, 1, 4) to get
# shift anchors (K, A, 4)
# reshape to (K*A, 4) shifted anchors
A = self._num_anchors
K = shifts.shape[0]
anchors = self._anchors.reshape((1, A, 4)) + \
shifts.reshape((1, K, 4)).transpose((1, 0, 2))
anchors = anchors.reshape((K * A, 4))
# Transpose and reshape predicted bbox transformations to get them
# into the same order as the anchors:
#
# bbox deltas will be (1, 4 * A, H, W) format
# transpose to (1, H, W, 4 * A)
# reshape to (1 * H * W * A, 4) where rows are ordered by (h, w, a)
# in slowest to fastest order
bbox_deltas = bbox_deltas.transpose((0, 2, 3, 1)).reshape((-1, 4))
if cfg_key == 'TRAIN' and cfg.TRAIN.RPN_NORMALIZE_TARGETS:
bbox_deltas *= cfg.TRAIN.RPN_NORMALIZE_STDS
bbox_deltas += cfg.TRAIN.RPN_NORMALIZE_MEANS
# Same story for the scores:
#
# scores are (1, A, H, W) format
# transpose to (1, H, W, A)
# reshape to (1 * H * W * A, 1) where rows are ordered by (h, w, a)
scores = scores.transpose((0, 2, 3, 1)).reshape((-1, 1))
# Convert anchors into proposals via bbox transformations
proposals = bbox_transform_inv(anchors, bbox_deltas)
# 2. clip predicted boxes to image
proposals = clip_boxes(proposals, im_info[:2])
# 3. remove predicted boxes with either height or width < threshold
# (NOTE: convert min_size to input image scale stored in im_info[2])
keep = _filter_boxes(proposals, min_size * im_info[2])
proposals = proposals[keep, :]
scores = scores[keep]
# 4. sort all (proposal, score) pairs by score from highest to lowest
# 5. take top pre_nms_topN (e.g. 6000)
order = scores.ravel().argsort()[::-1]
if pre_nms_topN > 0:
order = order[:pre_nms_topN]
proposals = proposals[order, :]
scores = scores[order]
# 6. apply nms (e.g. threshold = 0.7)
# 7. take after_nms_topN (e.g. 300)
# 8. return the top proposals (-> RoIs top)
keep = nms(np.hstack((proposals, scores)), nms_thresh)
if post_nms_topN > 0:
keep = keep[:post_nms_topN]
proposals = proposals[keep, :]
scores = scores[keep]
# Output rois blob
# Our RPN implementation only supports a single input image, so all
# batch inds are 0
batch_inds = np.zeros((proposals.shape[0], 1), dtype=np.float32)
blob = np.hstack((batch_inds, proposals.astype(np.float32, copy=False)))
top[0].reshape(*(blob.shape))
top[0].data[...] = blob
# [Optional] output scores blob
if len(top) > 1:
top[1].reshape(*(scores.shape))
top[1].data[...] = scores
def backward(self, top, propagate_down, bottom):
"""This layer does not propagate gradients."""
pass
def reshape(self, bottom, top):
"""Reshaping happens during the call to forward."""
pass
def _filter_boxes(boxes, min_size):
"""Remove all boxes with any side smaller than min_size."""
ws = boxes[:, 2] - boxes[:, 0] + 1
hs = boxes[:, 3] - boxes[:, 1] + 1
keep = np.where((ws >= min_size) & (hs >= min_size))[0]
return keep
| 38.922652 | 80 | 0.592477 |
120c3266e85ea4579f50f486a784db890fe698c8 | 259 | py | Python | tests/artificial/transf_None/trend_PolyTrend/cycle_7/ar_12/test_artificial_128_None_PolyTrend_7_12_0.py | shaido987/pyaf | b9afd089557bed6b90b246d3712c481ae26a1957 | [
"BSD-3-Clause"
] | 377 | 2016-10-13T20:52:44.000Z | 2022-03-29T18:04:14.000Z | tests/artificial/transf_None/trend_PolyTrend/cycle_7/ar_12/test_artificial_128_None_PolyTrend_7_12_0.py | ysdede/pyaf | b5541b8249d5a1cfdc01f27fdfd99b6580ed680b | [
"BSD-3-Clause"
] | 160 | 2016-10-13T16:11:53.000Z | 2022-03-28T04:21:34.000Z | tests/artificial/transf_None/trend_PolyTrend/cycle_7/ar_12/test_artificial_128_None_PolyTrend_7_12_0.py | ysdede/pyaf | b5541b8249d5a1cfdc01f27fdfd99b6580ed680b | [
"BSD-3-Clause"
] | 63 | 2017-03-09T14:51:18.000Z | 2022-03-27T20:52:57.000Z | import pyaf.Bench.TS_datasets as tsds
import tests.artificial.process_artificial_dataset as art
art.process_dataset(N = 128 , FREQ = 'D', seed = 0, trendtype = "PolyTrend", cycle_length = 7, transform = "None", sigma = 0.0, exog_count = 0, ar_order = 12); | 37 | 159 | 0.725869 |
3e7f22fb6507d867eaefb9a8afabc22c30b9b589 | 10,062 | py | Python | signac/contrib/mpipool.py | rohanbabbar04/signac | dfc28cbfdd11ea2f2e226f87719f323595e0f4ff | [
"BSD-3-Clause"
] | 100 | 2019-01-31T01:37:20.000Z | 2022-03-29T10:35:34.000Z | signac/contrib/mpipool.py | rohanbabbar04/signac | dfc28cbfdd11ea2f2e226f87719f323595e0f4ff | [
"BSD-3-Clause"
] | 607 | 2019-01-31T14:08:17.000Z | 2022-03-31T21:51:48.000Z | signac/contrib/mpipool.py | daico007/signac | a20d815bd87af3d8992c71871071024062cada07 | [
"BSD-3-Clause"
] | 31 | 2019-01-31T14:36:50.000Z | 2022-03-14T03:48:32.000Z | # The MIT License (MIT)
#
# Copyright (c) 2014, 2015 Adrian Price-Whelan & Dan Foreman-Mackey
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""MPIPool for MPI-based multiprocessing-like process pools.
This 3rd party module is copied from https://github.com/adrn/mpipool."""
from deprecation import deprecated
__all__ = ["MPIPool"]
__version__ = "0.0.1"
"""
THIS MODULE IS DEPRECATED!
"""
@deprecated(
deprecated_in="1.3",
removed_in="2.0",
current_version=__version__,
details="The mpipool module is deprecated.",
)
class MPIPool:
"""
A pool that distributes tasks over a set of MPI processes using
mpi4py. MPI is an API for distributed memory parallelism, used
by large cluster computers. This class provides a similar interface
to Python's multiprocessing Pool, but currently only supports the
:func:`map` method.
Contributed initially by `Joe Zuntz <https://github.com/joezuntz>`_.
Parameters
comm : (optional)
The ``mpi4py`` communicator.
debug : bool (optional)
If ``True``, print out a lot of status updates at each step.
loadbalance : bool (optional)
if ``True`` and the number of tasks is greater than the
number of processes, tries to loadbalance by sending out
one task to each cpu first and then sending out the rest
as the cpus get done.
"""
def __init__(self, comm=None, debug=False, loadbalance=False):
if comm is None:
# Late import of the MPI constant is necessary, to avoid
# early mpi initialization, which causes critital errors
# on badly configured systems.
from mpi4py import MPI
self.comm = MPI.COMM_WORLD
else:
self.comm = comm
self.rank = self.comm.Get_rank()
self.size = self.comm.Get_size() - 1
self.debug = debug
self.function = _error_function
self.loadbalance = loadbalance
if self.size == 0:
raise ValueError(
"Tried to create an MPI pool, but there "
"was only one MPI process available. "
"Need at least two."
)
def is_master(self):
"""
Is the current process the master?
"""
return self.rank == 0
def wait(self):
"""
If this isn't the master process, wait for instructions.
"""
from mpi4py import MPI
if self.is_master():
raise RuntimeError("Master node told to await jobs.")
status = MPI.Status()
while True:
# Event loop.
# Sit here and await instructions.
if self.debug:
print(f"Worker {self.rank} waiting for task.")
# Blocking receive to wait for instructions.
task = self.comm.recv(source=0, tag=MPI.ANY_TAG, status=status)
if self.debug:
print(f"Worker {self.rank} got task {task} with tag {status.tag}.")
# Check if message is special sentinel signaling end.
# If so, stop.
if isinstance(task, _close_pool_message):
if self.debug:
print(f"Worker {self.rank} told to quit.")
break
# Check if message is special type containing new function
# to be applied
if isinstance(task, _function_wrapper):
self.function = task.function
if self.debug:
print(
f"Worker {self.rank} replaced its task function: {self.function}."
)
continue
# If not a special message, just run the known function on
# the input and return it asynchronously.
result = self.function(task)
if self.debug:
print(
f"Worker {self.rank} sending answer {result} with tag {status.tag}."
)
self.comm.isend(result, dest=0, tag=status.tag)
def map(self, function, tasks, ntask=None, callback=None):
"""
Like the built-in :func:`map` function, apply a function to all
of the values in a list and return the list of results.
Parameters
function : callable
The function to apply to each element in the list.
tasks :
A list of tasks -- each element is passed to the input
function.
callback : callable (optional)
A callback function to call on each result.
"""
from mpi4py import MPI
if ntask is None:
ntask = len(tasks)
# If not the master just wait for instructions.
if not self.is_master():
self.wait()
return
if function is not self.function:
if self.debug:
print(f"Master replacing pool function with {function}.")
self.function = function
F = _function_wrapper(function)
# Tell all the workers what function to use.
requests = []
for i in range(self.size):
r = self.comm.isend(F, dest=i + 1)
requests.append(r)
# Wait until all of the workers have responded. See:
# https://gist.github.com/4176241
MPI.Request.waitall(requests)
if (not self.loadbalance) or (ntask <= self.size):
# Do not perform load-balancing - the default load-balancing
# scheme emcee uses.
# Send all the tasks off and wait for them to be received.
# Again, see the bug in the above gist.
requests = []
for i, task in enumerate(tasks):
worker = i % self.size + 1
if self.debug:
print(f"Sent task {task} to worker {worker} with tag {i}.")
r = self.comm.isend(task, dest=worker, tag=i)
requests.append(r)
MPI.Request.waitall(requests)
# Now wait for the answers.
results = []
for i in range(ntask):
worker = i % self.size + 1
if self.debug:
print(f"Master waiting for worker {worker} with tag {i}")
result = self.comm.recv(source=worker, tag=i)
if callback is not None:
callback(result)
results.append(result)
return results
else:
# Perform load-balancing. The order of the results are likely to
# be different from the previous case.
for i, task in enumerate(tasks[0 : self.size]):
worker = i + 1
if self.debug:
print(f"Sent task {task} to worker {worker} with tag {i}.")
# Send out the tasks asynchronously.
self.comm.isend(task, dest=worker, tag=i)
ntasks_dispatched = self.size
results = [None] * ntask
for itask in range(ntask):
status = MPI.Status()
# Receive input from workers.
result = self.comm.recv(
source=MPI.ANY_SOURCE, tag=MPI.ANY_TAG, status=status
)
worker = status.source
i = status.tag
if callback is not None:
callback(result)
results[i] = result
if self.debug:
print(f"Master received from worker {worker} with tag {i}")
# Now send the next task to this idle worker (if there are any
# left).
if ntasks_dispatched < ntask:
task = tasks[ntasks_dispatched]
i = ntasks_dispatched
if self.debug:
print(f"Sent task {task} to worker {worker} with tag {i}.")
# Send out the tasks asynchronously.
self.comm.isend(task, dest=worker, tag=i)
ntasks_dispatched += 1
return results
def bcast(self, *args, **kwargs):
"""
Equivalent to mpi4py :func:`bcast` collective operation.
"""
return self.comm.bcast(*args, **kwargs)
def close(self):
"""
Just send a message off to all the pool members which contains
the special :class:`_close_pool_message` sentinel.
"""
if self.is_master():
for i in range(self.size):
self.comm.isend(_close_pool_message(), dest=i + 1)
def __enter__(self):
return self
def __exit__(self, *args):
self.close()
class _close_pool_message:
def __repr__(self):
return "<Close pool message>"
class _function_wrapper:
def __init__(self, function):
self.function = function
def _error_function(task):
raise RuntimeError("Pool was sent tasks before being told what function to apply.")
| 33.878788 | 90 | 0.574538 |
cd22eccd13b3b20eb01aa3b2e848697c7754abd8 | 3,505 | py | Python | modules/utils/utils.py | king-menin/slavic-ner | f88e3150546fd2a49bda682396d82c749d6659bb | [
"MIT"
] | 6 | 2019-09-04T09:08:57.000Z | 2020-09-04T11:55:30.000Z | modules/utils/utils.py | king-menin/AGRR-2019 | 3bf8533cd54c018b45d809c3fcdc2a55a406248d | [
"MIT"
] | 1 | 2020-05-21T01:16:31.000Z | 2021-09-13T08:47:18.000Z | modules/utils/utils.py | king-menin/slavic-ner | f88e3150546fd2a49bda682396d82c749d6659bb | [
"MIT"
] | 2 | 2019-09-24T12:42:30.000Z | 2021-01-15T00:24:00.000Z | import __main__ as main
from collections import Counter
import numpy as np
def if_none(own, other):
return own if own is not None else other
def ipython_info():
return hasattr(main, '__file__')
def voting_choicer(tok_map, labels):
label = []
prev_idx = 0
for origin_idx in tok_map:
votes = []
for l in labels[prev_idx:origin_idx]:
vote = "I_O"
if l not in ["[CLS]", "[SEP]", "X"]:
vote = "I_" + l.split("_")[1]
if l != "X":
votes.append(vote)
vote_labels = Counter(votes)
if not len(vote_labels):
vote_labels = {"I_O": 1}
# vote_labels = Counter(c)
lb = sorted(list(vote_labels), key=lambda x: vote_labels[x])
if len(lb):
label.append(lb[-1])
prev_idx = origin_idx
if origin_idx < 0:
break
assert "[SEP]" not in label
return label
def first_choicer(tok_map, labels):
label = []
prev_idx = 0
for origin_idx in tok_map:
l = labels[prev_idx]
if l in ["X"]:
l = "B_O"
if l == "B_O":
for ll in labels[prev_idx + 1:origin_idx]:
if ll not in ["B_O", "I_O", "X"]:
l = ll
break
label.append(l)
prev_idx = origin_idx
if origin_idx < 0:
break
# assert "[SEP]" not in label
return label
def bert_labels2tokens(dl, labels, fn=voting_choicer):
res_tokens = []
res_labels = []
for f, l in zip(dl.dataset, labels):
label = fn(f.tok_map, l)
res_tokens.append(f.tokens[1:])
res_labels.append(label[1:])
return res_tokens, res_labels
def tokens2spans_(tokens_, labels_):
res = []
idx_ = 0
while idx_ < len(labels_):
label = labels_[idx_]
if label in ["I_O", "B_O", "O"]:
res.append((tokens_[idx_], "O"))
idx_ += 1
elif label == "[SEP]" or label == "<eos>":
break
elif label == "[CLS]" or label == "<bos>":
res.append((tokens_[idx_], label))
idx_ += 1
else:
span = [tokens_[idx_]]
try:
span_label = labels_[idx_].split("_")[1]
except IndexError:
print(label, labels_[idx_].split("_"))
span_label = None
idx_ += 1
while idx_ < len(labels_) and labels_[idx_] not in ["I_O", "B_O", "O"] \
and labels_[idx_].split("_")[0] == "I":
if span_label == labels_[idx_].split("_")[1]:
span.append(tokens_[idx_])
idx_ += 1
else:
break
res.append((" ".join(span), span_label))
return res
def tokens2spans(tokens, labels):
assert len(tokens) == len(labels)
return list(map(lambda x: tokens2spans_(*x), zip(tokens, labels)))
def encode_position(pos, emb_dim=10):
"""The sinusoid position encoding"""
# keep dim 0 for padding token position encoding zero vector
if pos == 0:
return np.zeros(emb_dim)
position_enc = np.array(
[pos / np.power(10000, 2 * (j // 2) / emb_dim) for j in range(emb_dim)])
# apply sin on 0th,2nd,4th...emb_dim
position_enc[0::2] = np.sin(position_enc[0::2])
# apply cos on 1st,3rd,5th...emb_dim
position_enc[1::2] = np.cos(position_enc[1::2])
return list(position_enc.reshape(-1))
| 28.495935 | 84 | 0.52525 |
17d84aa620d9dcf70eb47b7186a7f3d87ed160a5 | 11,833 | py | Python | ludwig/neuropod_export.py | jakobt/ludwig | ef8ead2f99255093e5492a2b221a472e11b228b1 | [
"Apache-2.0"
] | 1 | 2019-07-03T09:05:53.000Z | 2019-07-03T09:05:53.000Z | ludwig/neuropod_export.py | dsblank/ludwig | 29cc68b4b37730536855f8b4f31379a9d945f33b | [
"Apache-2.0"
] | null | null | null | ludwig/neuropod_export.py | dsblank/ludwig | 29cc68b4b37730536855f8b4f31379a9d945f33b | [
"Apache-2.0"
] | null | null | null | import argparse
import logging
import os
import shutil
import sys
import numpy as np
from ludwig import __file__ as ludwig_path
from ludwig.api import LudwigModel
from ludwig.constants import CATEGORY, NUMERICAL, BINARY, SEQUENCE, TEXT, SET, \
VECTOR
from ludwig.globals import MODEL_HYPERPARAMETERS_FILE_NAME, \
TRAIN_SET_METADATA_FILE_NAME, MODEL_WEIGHTS_FILE_NAME, LUDWIG_VERSION, \
MODEL_WEIGHTS_PROGRESS_FILE_NAME
from ludwig.utils.data_utils import load_json
from ludwig.utils.print_utils import logging_level_registry, print_ludwig
logger = logging.getLogger(__name__)
class LudwigNeuropodModelWrapper:
def __init__(self, data_root):
self.ludwig_model = LudwigModel.load(data_root)
def __call__(self, **kwargs):
print('__call__', file=sys.stderr)
data_dict = kwargs
for key in data_dict:
data_dict[key] = np.squeeze(data_dict[key], axis=1)
predicted = self.ludwig_model.predict(
data_dict=data_dict, return_type=dict
)
# print(predicted, file=sys.stderr)
return postprocess_for_neuropod(
predicted, self.ludwig_model.model_definition
)
def get_model(data_root):
print('get_model()', data_root, file=sys.stderr)
return LudwigNeuropodModelWrapper(data_root)
def postprocess_for_neuropod(predicted, model_definition):
postprocessed = {}
for output_feature in model_definition['output_features']:
feature_name = output_feature['name']
feature_type = output_feature['type']
if feature_type == BINARY:
postprocessed[feature_name + "_predictions"] = \
np.expand_dims(
predicted[feature_name]['predictions'].astype('str'), 1)
postprocessed[feature_name + "_probabilities"] = \
np.expand_dims(predicted[feature_name]['probabilities'], 1)
elif feature_type == NUMERICAL:
postprocessed[feature_name + "_predictions"] = \
np.expand_dims(predicted[feature_name]['predictions'], 1)
elif feature_type == CATEGORY:
postprocessed[feature_name + "_predictions"] = np.expand_dims(
np.array(predicted[feature_name]['predictions'], dtype='str'), 1
)
postprocessed[feature_name + "_probability"] = \
np.expand_dims(predicted[feature_name]['probability'], 1)
postprocessed[feature_name + "_probabilities"] = \
predicted[feature_name]['probabilities']
elif feature_type == SEQUENCE:
predictions = list(map(
lambda x: ' '.join(x),
predicted[feature_name]['predictions']
))
postprocessed[feature_name + "_predictions"] = np.expand_dims(
np.array(predictions, dtype='str'), 1
)
elif feature_type == TEXT:
predictions = list(map(
lambda x: ' '.join(x),
predicted[feature_name]['predictions']
))
postprocessed[feature_name + "_predictions"] = np.expand_dims(
np.array(predictions, dtype='str'), 1
)
elif feature_type == SET:
predictions = list(map(
lambda x: ' '.join(x),
predicted[feature_name]['predictions']
))
postprocessed[feature_name + "_predictions"] = np.expand_dims(
np.array(predictions, dtype='str'), 1
)
probability = list(map(
lambda x: ' '.join([str(e) for e in x]),
predicted[feature_name]['probability']
))
postprocessed[feature_name + "_probability"] = np.expand_dims(
np.array(probability, dtype='str'), 1
)
postprocessed[feature_name + "_probabilities"] = \
predicted[feature_name]['probabilities']
elif feature_type == VECTOR:
postprocessed[feature_name + "_predictions"] = \
predicted[feature_name]['predictions']
else:
postprocessed[feature_name + "_predictions"] = np.expand_dims(
np.array(predicted[feature_name]['predictions'], dtype='str'), 1
)
# print(postprocessed, file=sys.stderr)
return postprocessed
def export_neuropod(
ludwig_model_path,
neuropod_path,
neuropod_model_name="ludwig_model"
):
try:
from neuropod.backends.python.packager import create_python_neuropod
except ImportError:
logger.error(
'The "neuropod" package is not installed in your environment.'
)
sys.exit(-1)
data_paths = [
{
"path": os.path.join(
ludwig_model_path, MODEL_HYPERPARAMETERS_FILE_NAME
),
"packaged_name": MODEL_HYPERPARAMETERS_FILE_NAME
},
{
"path": os.path.join(
ludwig_model_path, TRAIN_SET_METADATA_FILE_NAME
),
"packaged_name": TRAIN_SET_METADATA_FILE_NAME
},
{
"path": os.path.join(
ludwig_model_path, 'checkpoint'
),
"packaged_name": 'checkpoint'
},
]
for filename in os.listdir(ludwig_model_path):
if (MODEL_WEIGHTS_FILE_NAME in filename
and MODEL_WEIGHTS_PROGRESS_FILE_NAME not in filename):
data_paths.append(
{
"path": os.path.join(
ludwig_model_path, filename
),
"packaged_name": filename
}
)
logger.debug('data_paths: {}'.format(data_paths))
ludwig_model_definition = load_json(
os.path.join(
ludwig_model_path,
MODEL_HYPERPARAMETERS_FILE_NAME
)
)
training_set_metadata = load_json(
os.path.join(
ludwig_model_path,
TRAIN_SET_METADATA_FILE_NAME
)
)
input_spec = []
for feature in ludwig_model_definition['input_features']:
input_spec.append({
"name": feature['name'],
"dtype": "str",
"shape": (None, 1)
})
logger.debug('input_spec: {}'.format(input_spec))
output_spec = []
for feature in ludwig_model_definition['output_features']:
feature_type = feature['type']
feature_name = feature['name']
if feature_type == BINARY:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "str",
"shape": (None, 1)
})
output_spec.append({
"name": feature['name'] + '_probabilities',
"dtype": "float32",
"shape": (None, 1)
})
elif feature_type == NUMERICAL:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "float32",
"shape": (None, 1)
})
elif feature_type == CATEGORY:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "str",
"shape": (None, 1)
})
output_spec.append({
"name": feature['name'] + '_probability',
"dtype": "float32",
"shape": (None, 1)
})
output_spec.append({
"name": feature['name'] + '_probabilities',
"dtype": "float32",
"shape": (
None, training_set_metadata[feature_name]['vocab_size']
)
})
elif feature_type == SEQUENCE:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "str",
"shape": (None, 1)
})
elif feature_type == TEXT:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "str",
"shape": (None, 1)
})
elif feature_type == SET:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "str",
"shape": (None, 1)
})
output_spec.append({
"name": feature['name'] + '_probability',
"dtype": "str",
"shape": (None, 1)
})
output_spec.append({
"name": feature['name'] + '_probabilities',
"dtype": "float32",
"shape": (
None, training_set_metadata[feature_name]['vocab_size']
)
})
elif feature_type == VECTOR:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "float32",
"shape": (
None, training_set_metadata[feature_name]['vector_size']
)
})
else:
output_spec.append({
"name": feature['name'] + '_predictions',
"dtype": "str",
"shape": (None, 1)
})
logger.debug('output_spec: {}'.format(output_spec))
if os.path.exists(neuropod_path):
if os.path.isfile(neuropod_path):
logger.warning('Removing file: {}'.format(neuropod_path))
os.remove(neuropod_path)
else:
logger.warning('Removing directory: {}'.format(neuropod_path))
shutil.rmtree(neuropod_path, ignore_errors=True)
from pathlib import Path
path = Path(ludwig_path)
logger.debug('python_root: {}'.format(path.parent.parent))
create_python_neuropod(
neuropod_path=neuropod_path,
model_name=neuropod_model_name,
data_paths=data_paths,
code_path_spec=[{
"python_root": path.parent.parent,
"dirs_to_package": [
"ludwig" # Package everything in the python_root
],
}],
entrypoint_package="ludwig.neuropod_export",
entrypoint="get_model",
# test_deps=['torch', 'numpy'],
skip_virtualenv=True,
input_spec=input_spec,
output_spec=output_spec
)
logger.info('Neuropod saved to: {}'.format(neuropod_path))
def cli():
parser = argparse.ArgumentParser(
description='This script exports a Ludwig model in the Neuropod format'
)
# ----------------
# Model parameters
# ----------------
parser.add_argument(
'-m',
'--ludwig_model_path',
help='path to the Ludwig model to export',
required=True
)
parser.add_argument(
'-l',
'--logging_level',
default='info',
help='the level of logging to use',
choices=['critical', 'error', 'warning', 'info', 'debug', 'notset']
)
# -------------------
# Neuropod parameters
# -------------------
parser.add_argument(
'-n',
'--neuropod_path',
help='path of the output Neuropod package file',
required=True
)
parser.add_argument(
'-nm',
'--neuropod_model_name',
help='path of the output Neuropod package file',
default='ludwig_model'
)
args = parser.parse_args()
logging.getLogger('ludwig').setLevel(
logging_level_registry[args.logging_level]
)
global logger
logger = logging.getLogger('ludwig.serve')
print_ludwig('Export Neuropod', LUDWIG_VERSION)
export_neuropod(
args.ludwig_model_path, args.neuropod_path, args.neuropod_model_name
)
if __name__ == '__main__':
# contrib_command("neuropod", *sys.argv)
cli()
| 33.426554 | 80 | 0.54686 |
0d570f6a9e434c47d03369af4f4720bcee81b4b7 | 1,469 | py | Python | descriptor/migrations/0021_auto_20200729_2203.py | alduxx/papirodocker | a1fab0d15ced07c4b03732651cffaa5158c164a4 | [
"Unlicense"
] | null | null | null | descriptor/migrations/0021_auto_20200729_2203.py | alduxx/papirodocker | a1fab0d15ced07c4b03732651cffaa5158c164a4 | [
"Unlicense"
] | null | null | null | descriptor/migrations/0021_auto_20200729_2203.py | alduxx/papirodocker | a1fab0d15ced07c4b03732651cffaa5158c164a4 | [
"Unlicense"
] | null | null | null | # Generated by Django 3.0.7 on 2020-07-29 22:03
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('descriptor', '0020_auto_20200727_1347'),
]
operations = [
migrations.AlterModelOptions(
name='service',
options={'ordering': ['name'], 'verbose_name': 'service', 'verbose_name_plural': 'services'},
),
migrations.RemoveField(
model_name='parameter',
name='parameter_group',
),
migrations.AddField(
model_name='parameter',
name='parameter_parent',
field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, related_name='parameter_children', to='descriptor.Parameter'),
),
migrations.AlterField(
model_name='parameter',
name='format',
field=models.CharField(choices=[('AN', 'Alfanumérico'), ('NB', 'Número'), ('AR', 'Array'), ('OB', 'Objeto')], max_length=2, verbose_name='format'),
),
migrations.AlterField(
model_name='parametergroup',
name='type',
field=models.CharField(choices=[('000', 'Requisição'), ('200', 'Resposta 200 - ok'), ('400', 'Resposta 400 - erro'), ('403', 'Resposta 403 - não permitido'), ('500', 'Resposta 500 - erro de servidor')], max_length=3, verbose_name='parameter type'),
),
]
| 38.657895 | 260 | 0.598366 |
891c4be2ae50199f6b3044c112e481a50bf0aca0 | 928 | py | Python | website/__init__.py | ander9991/GradSchoolZero | 89b8cf228f21ec8d258c7e906e3e1d2cccab2a8e | [
"Apache-2.0"
] | 1 | 2021-11-10T02:39:05.000Z | 2021-11-10T02:39:05.000Z | website/__init__.py | ander9991/GradSchoolZero | 89b8cf228f21ec8d258c7e906e3e1d2cccab2a8e | [
"Apache-2.0"
] | null | null | null | website/__init__.py | ander9991/GradSchoolZero | 89b8cf228f21ec8d258c7e906e3e1d2cccab2a8e | [
"Apache-2.0"
] | 1 | 2021-11-25T23:02:10.000Z | 2021-11-25T23:02:10.000Z | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
db = SQLAlchemy()
DB_NAME = "database.db"
def create_app():
app = Flask(__name__)
app.config['SECRET_KEY'] = 'hjshjhdjah kjshkjdhjs'
app.config['SQLALCHEMY_DATABASE_URI'] = f'sqlite:///{DB_NAME}'
db.init_app(app)
from .views import views
from .auth import auth
app.register_blueprint(views, url_prefix='/')
app.register_blueprint(auth, url_prefix='/')
from .models import User
create_database(app)
login_manager = LoginManager()
login_manager.login_view = 'auth.login'
login_manager.init_app(app)
@login_manager.user_loader
def load_user(id):
return User.query.get(int(id))
return app
def create_database(app):
if not path.exists('website/' + DB_NAME):
db.create_all(app=app)
print('Created Database!')
| 22.634146 | 66 | 0.697198 |
0f935293005c370b86da5bd7d30d3c4909b16069 | 791 | py | Python | setup.py | krzysztofarendt/modestga | b4a884028d7cd6ad61fa5362a8be3a08b355918c | [
"BSD-2-Clause"
] | 7 | 2018-07-22T14:45:54.000Z | 2021-01-08T14:15:04.000Z | setup.py | krzysztofarendt/modestga | b4a884028d7cd6ad61fa5362a8be3a08b355918c | [
"BSD-2-Clause"
] | 25 | 2018-06-04T18:35:33.000Z | 2022-03-12T01:03:00.000Z | setup.py | krzysztofarendt/modestga | b4a884028d7cd6ad61fa5362a8be3a08b355918c | [
"BSD-2-Clause"
] | 1 | 2021-03-25T03:40:52.000Z | 2021-03-25T03:40:52.000Z | from setuptools import setup
import setuptools
setup(name='modestga',
version='0.5.11',
description='Genetic Algorithm minimization',
url='https://github.com/krzysztofarendt/modestga',
keywords='genetic algorithm optimization',
author='Krzysztof Arendt',
author_email='krzysztof.arendt@gmail.com',
license='BSD',
platforms=['Windows', 'Linux'],
packages=setuptools.find_packages(),
include_package_data=True,
install_requires=[
'numpy>=1.18.2',
'matplotlib>=3.2.1',
'scipy>=1.4.1',
'cloudpickle'
],
classifiers = [
'Programming Language :: Python :: 3',
'Topic :: Scientific/Engineering',
'License :: OSI Approved :: BSD License'
]
)
| 29.296296 | 56 | 0.599241 |
574c3a54f31b4ee062bf60ae675094efe82543d7 | 2,967 | py | Python | test/functional/feature_logging.py | bitkin/bitkin | 0203d230d12822a972df4102b1875e9757a56d63 | [
"MIT"
] | null | null | null | test/functional/feature_logging.py | bitkin/bitkin | 0203d230d12822a972df4102b1875e9757a56d63 | [
"MIT"
] | null | null | null | test/functional/feature_logging.py | bitkin/bitkin | 0203d230d12822a972df4102b1875e9757a56d63 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
# Copyright (c) 2017-2020 The Bitkincoin Core developers
# Distributed under the MIT software license, see the accompanying
# file COPYING or http://www.opensource.org/licenses/mit-license.php.
"""Test debug logging."""
import os
from test_framework.test_framework import BitkincoinTestFramework
from test_framework.test_node import ErrorMatch
class LoggingTest(BitkincoinTestFramework):
def set_test_params(self):
self.num_nodes = 1
self.setup_clean_chain = True
def relative_log_path(self, name):
return os.path.join(self.nodes[0].datadir, self.chain, name)
def run_test(self):
# test default log file name
default_log_path = self.relative_log_path("debug.log")
assert os.path.isfile(default_log_path)
# test alternative log file name in datadir
self.restart_node(0, ["-debuglogfile=foo.log"])
assert os.path.isfile(self.relative_log_path("foo.log"))
# test alternative log file name outside datadir
tempname = os.path.join(self.options.tmpdir, "foo.log")
self.restart_node(0, ["-debuglogfile=%s" % tempname])
assert os.path.isfile(tempname)
# check that invalid log (relative) will cause error
invdir = self.relative_log_path("foo")
invalidname = os.path.join("foo", "foo.log")
self.stop_node(0)
exp_stderr = r"Error: Could not open debug log file \S+$"
self.nodes[0].assert_start_raises_init_error(["-debuglogfile=%s" % (invalidname)], exp_stderr, match=ErrorMatch.FULL_REGEX)
assert not os.path.isfile(os.path.join(invdir, "foo.log"))
# check that invalid log (relative) works after path exists
self.stop_node(0)
os.mkdir(invdir)
self.start_node(0, ["-debuglogfile=%s" % (invalidname)])
assert os.path.isfile(os.path.join(invdir, "foo.log"))
# check that invalid log (absolute) will cause error
self.stop_node(0)
invdir = os.path.join(self.options.tmpdir, "foo")
invalidname = os.path.join(invdir, "foo.log")
self.nodes[0].assert_start_raises_init_error(["-debuglogfile=%s" % invalidname], exp_stderr, match=ErrorMatch.FULL_REGEX)
assert not os.path.isfile(os.path.join(invdir, "foo.log"))
# check that invalid log (absolute) works after path exists
self.stop_node(0)
os.mkdir(invdir)
self.start_node(0, ["-debuglogfile=%s" % (invalidname)])
assert os.path.isfile(os.path.join(invdir, "foo.log"))
# check that -nodebuglogfile disables logging
self.stop_node(0)
os.unlink(default_log_path)
assert not os.path.isfile(default_log_path)
self.start_node(0, ["-nodebuglogfile"])
assert not os.path.isfile(default_log_path)
# just sanity check no crash here
self.restart_node(0, ["-debuglogfile=%s" % os.devnull])
if __name__ == '__main__':
LoggingTest().main()
| 39.56 | 131 | 0.672396 |
10e70e12eabcde4d8228bb65bd4da0385174e62b | 64 | py | Python | puppet/files/other/topology_generator/topology_generator/benchmark/__init__.py | muka/servioticy-vagrant | 9b67937d5338c8693c00caa49398f399d7ba4f98 | [
"Apache-2.0"
] | null | null | null | puppet/files/other/topology_generator/topology_generator/benchmark/__init__.py | muka/servioticy-vagrant | 9b67937d5338c8693c00caa49398f399d7ba4f98 | [
"Apache-2.0"
] | null | null | null | puppet/files/other/topology_generator/topology_generator/benchmark/__init__.py | muka/servioticy-vagrant | 9b67937d5338c8693c00caa49398f399d7ba4f98 | [
"Apache-2.0"
] | null | null | null | __author__ = 'Álvaro Villalba Navarro <alvaro.villalba@bsc.es>'
| 32 | 63 | 0.78125 |
5add12c12dfb1a6f2e1cdf5a8cc2a91188aa1154 | 518 | py | Python | client/button_blend.py | jakethedev/quantum | 218da372201d056e7cb541337475ee4fc85d9fc6 | [
"MIT"
] | null | null | null | client/button_blend.py | jakethedev/quantum | 218da372201d056e7cb541337475ee4fc85d9fc6 | [
"MIT"
] | null | null | null | client/button_blend.py | jakethedev/quantum | 218da372201d056e7cb541337475ee4fc85d9fc6 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import time
from aiy.leds import (Leds, Color)
with Leds() as leds:
print('RGB: Blend between PURPLE and BLUE over 3 seconds')
for i in range(30):
color = Color.blend(Color.BLUE, Color.PURPLE, i / 30)
leds.update(Leds.rgb_on(color))
time.sleep(0.1)
print('RGB: Blend between GREEN and BLUE over 3 seconds')
for i in range(30):
color = Color.blend(Color.BLUE, Color.GREEN, i / 30)
leds.update(Leds.rgb_on(color))
time.sleep(0.1)
| 28.777778 | 62 | 0.633205 |
72bc2d1a81293cb7fb54e8c021fb0a56410a0627 | 36,292 | py | Python | openstack_dashboard/dashboards/project/loadbalancers/tests.py | maofutian/horizon | dab92e7d2f576caea8f81c8e22a516fb45633794 | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/project/loadbalancers/tests.py | maofutian/horizon | dab92e7d2f576caea8f81c8e22a516fb45633794 | [
"Apache-2.0"
] | null | null | null | openstack_dashboard/dashboards/project/loadbalancers/tests.py | maofutian/horizon | dab92e7d2f576caea8f81c8e22a516fb45633794 | [
"Apache-2.0"
] | null | null | null | # 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 mox import IsA # noqa
from django.core.urlresolvers import reverse
from django.core.urlresolvers import reverse_lazy
from django import http
from horizon.workflows import views
from openstack_dashboard import api
from openstack_dashboard.test import helpers as test
from openstack_dashboard.dashboards.project.loadbalancers import workflows
class LoadBalancerTests(test.TestCase):
class AttributeDict(dict):
def __getattr__(self, attr):
return self[attr]
def __setattr__(self, attr, value):
self[attr] = value
DASHBOARD = 'project'
INDEX_URL = reverse_lazy('horizon:%s:loadbalancers:index' % DASHBOARD)
ADDPOOL_PATH = 'horizon:%s:loadbalancers:addpool' % DASHBOARD
ADDVIP_PATH = 'horizon:%s:loadbalancers:addvip' % DASHBOARD
ADDMEMBER_PATH = 'horizon:%s:loadbalancers:addmember' % DASHBOARD
ADDMONITOR_PATH = 'horizon:%s:loadbalancers:addmonitor' % DASHBOARD
POOL_DETAIL_PATH = 'horizon:%s:loadbalancers:pooldetails' % DASHBOARD
VIP_DETAIL_PATH = 'horizon:%s:loadbalancers:vipdetails' % DASHBOARD
MEMBER_DETAIL_PATH = 'horizon:%s:loadbalancers:memberdetails' % DASHBOARD
MONITOR_DETAIL_PATH = 'horizon:%s:loadbalancers:monitordetails' % DASHBOARD
UPDATEPOOL_PATH = 'horizon:%s:loadbalancers:updatepool' % DASHBOARD
UPDATEVIP_PATH = 'horizon:%s:loadbalancers:updatevip' % DASHBOARD
UPDATEMEMBER_PATH = 'horizon:%s:loadbalancers:updatemember' % DASHBOARD
UPDATEMONITOR_PATH = 'horizon:%s:loadbalancers:updatemonitor' % DASHBOARD
ADDASSOC_PATH = 'horizon:%s:loadbalancers:addassociation' % DASHBOARD
DELETEASSOC_PATH = 'horizon:%s:loadbalancers:deleteassociation' % DASHBOARD
def set_up_expect(self):
# retrieve pools
api.lbaas.pool_list(
IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
# retrieves members
api.lbaas.member_list(
IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.members.list())
# retrieves monitors
api.lbaas.pool_health_monitor_list(
IsA(http.HttpRequest), tenant_id=self.tenant.id).MultipleTimes() \
.AndReturn(self.monitors.list())
def set_up_expect_with_exception(self):
api.lbaas.pool_list(
IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndRaise(self.exceptions.neutron)
api.lbaas.member_list(
IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndRaise(self.exceptions.neutron)
api.lbaas.pool_health_monitor_list(
IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndRaise(self.exceptions.neutron)
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list')})
def test_index_pools(self):
self.set_up_expect()
self.mox.ReplayAll()
res = self.client.get(self.INDEX_URL)
self.assertTemplateUsed(res, '%s/loadbalancers/details_tabs.html'
% self.DASHBOARD)
self.assertTemplateUsed(res, 'horizon/common/_detail_table.html')
self.assertEqual(len(res.context['table'].data),
len(self.pools.list()))
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list')})
def test_index_members(self):
self.set_up_expect()
self.mox.ReplayAll()
res = self.client.get(self.INDEX_URL + '?tab=lbtabs__members')
self.assertTemplateUsed(res, '%s/loadbalancers/details_tabs.html'
% self.DASHBOARD)
self.assertTemplateUsed(res, 'horizon/common/_detail_table.html')
self.assertEqual(len(res.context['memberstable_table'].data),
len(self.members.list()))
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list')})
def test_index_monitors(self):
self.set_up_expect()
self.mox.ReplayAll()
res = self.client.get(self.INDEX_URL + '?tab=lbtabs__monitors')
self.assertTemplateUsed(res, '%s/loadbalancers/details_tabs.html'
% self.DASHBOARD)
self.assertTemplateUsed(res, 'horizon/common/_detail_table.html')
self.assertEqual(len(res.context['monitorstable_table'].data),
len(self.monitors.list()))
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list')})
def test_index_exception_pools(self):
self.set_up_expect_with_exception()
self.mox.ReplayAll()
res = self.client.get(self.INDEX_URL)
self.assertTemplateUsed(res,
'%s/loadbalancers/details_tabs.html'
% self.DASHBOARD)
self.assertTemplateUsed(res,
'horizon/common/_detail_table.html')
self.assertEqual(len(res.context['table'].data), 0)
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list')})
def test_index_exception_members(self):
self.set_up_expect_with_exception()
self.mox.ReplayAll()
res = self.client.get(self.INDEX_URL + '?tab=lbtabs__members')
self.assertTemplateUsed(res,
'%s/loadbalancers/details_tabs.html'
% self.DASHBOARD)
self.assertTemplateUsed(res,
'horizon/common/_detail_table.html')
self.assertEqual(len(res.context['memberstable_table'].data), 0)
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list')})
def test_index_exception_monitors(self):
self.set_up_expect_with_exception()
self.mox.ReplayAll()
res = self.client.get(self.INDEX_URL + '?tab=lbtabs__monitors')
self.assertTemplateUsed(res,
'%s/loadbalancers/details_tabs.html'
% self.DASHBOARD)
self.assertTemplateUsed(res,
'horizon/common/_detail_table.html')
self.assertEqual(len(res.context['monitorstable_table'].data), 0)
@test.create_stubs({api.neutron: ('network_list_for_tenant',
'provider_list',
'is_extension_supported'),
api.lbaas: ('pool_create', )})
def test_add_pool_post(self):
pool = self.pools.first()
subnet = self.subnets.first()
networks = [{'subnets': [subnet, ]}, ]
api.neutron.is_extension_supported(
IsA(http.HttpRequest), 'service-type').AndReturn(True)
api.neutron.network_list_for_tenant(
IsA(http.HttpRequest), self.tenant.id).AndReturn(networks)
api.neutron.provider_list(IsA(http.HttpRequest)) \
.AndReturn(self.providers.list())
form_data = {'name': pool.name,
'description': pool.description,
'subnet_id': pool.subnet_id,
'protocol': pool.protocol,
'lb_method': pool.lb_method,
'admin_state_up': pool.admin_state_up}
api.lbaas.pool_create(
IsA(http.HttpRequest), **form_data).AndReturn(pool)
self.mox.ReplayAll()
res = self.client.post(reverse(self.ADDPOOL_PATH), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.neutron: ('network_list_for_tenant',
'provider_list',
'is_extension_supported')})
def test_add_pool_get(self):
self._test_add_pool_get()
@test.create_stubs({api.neutron: ('network_list_for_tenant',
'provider_list',
'is_extension_supported')})
def test_add_pool_get_provider_list_exception(self):
self._test_add_pool_get(with_provider_exception=True)
@test.create_stubs({api.neutron: ('network_list_for_tenant',
'is_extension_supported')})
def test_add_pool_get_without_service_type_support(self):
self._test_add_pool_get(with_service_type=False)
def _test_add_pool_get(self, with_service_type=True,
with_provider_exception=False):
subnet = self.subnets.first()
default_provider = self.providers.first()['name']
networks = [{'subnets': [subnet, ]}, ]
api.neutron.is_extension_supported(
IsA(http.HttpRequest), 'service-type').AndReturn(with_service_type)
api.neutron.network_list_for_tenant(
IsA(http.HttpRequest), self.tenant.id).AndReturn(networks)
if with_service_type:
prov_list = api.neutron.provider_list(IsA(http.HttpRequest))
if with_provider_exception:
prov_list.AndRaise(self.exceptions.neutron)
else:
prov_list.AndReturn(self.providers.list())
self.mox.ReplayAll()
res = self.client.get(reverse(self.ADDPOOL_PATH))
workflow = res.context['workflow']
self.assertTemplateUsed(res, views.WorkflowView.template_name)
self.assertEqual(workflow.name, workflows.AddPool.name)
expected_objs = ['<AddPoolStep: addpoolaction>', ]
self.assertQuerysetEqual(workflow.steps, expected_objs)
if not with_service_type:
self.assertNotContains(res, default_provider)
self.assertContains(res, ('Provider for Load Balancer '
'is not supported'))
elif with_provider_exception:
self.assertNotContains(res, default_provider)
self.assertContains(res, 'No provider is available')
else:
self.assertContains(res, default_provider)
def test_add_vip_post(self):
self._test_add_vip_post()
def test_add_vip_post_no_connection_limit(self):
self._test_add_vip_post(with_conn_limit=False)
def test_add_vip_post_with_diff_subnet(self):
self._test_add_vip_post(with_diff_subnet=True)
@test.create_stubs({api.lbaas: ('pool_get', 'vip_create'),
api.neutron: (
'network_list_for_tenant', 'subnet_get', )})
def _test_add_vip_post(self, with_diff_subnet=False, with_conn_limit=True):
vip = self.vips.first()
subnet = self.subnets.first()
pool = self.pools.first()
networks = [{'subnets': [subnet, ]}, ]
api.lbaas.pool_get(
IsA(http.HttpRequest), pool.id).MultipleTimes().AndReturn(pool)
api.neutron.subnet_get(
IsA(http.HttpRequest), subnet.id).AndReturn(subnet)
api.neutron.network_list_for_tenant(
IsA(http.HttpRequest), self.tenant.id).AndReturn(networks)
params = {'name': vip.name,
'description': vip.description,
'pool_id': vip.pool_id,
'address': vip.address,
'subnet_id': pool.subnet_id,
'protocol_port': vip.protocol_port,
'protocol': vip.protocol,
'session_persistence': vip.session_persistence['type'],
'cookie_name': vip.session_persistence['cookie_name'],
'admin_state_up': vip.admin_state_up,
}
if with_conn_limit:
params['connection_limit'] = vip.connection_limit
if with_diff_subnet:
params['subnet_id'] = vip.subnet_id
api.lbaas.vip_create(
IsA(http.HttpRequest), **params).AndReturn(vip)
self.mox.ReplayAll()
form_data = {
'name': vip.name,
'description': vip.description,
'pool_id': vip.pool_id,
'address': vip.address,
'subnet_id': pool.subnet_id,
'protocol_port': vip.protocol_port,
'protocol': vip.protocol,
'session_persistence': vip.session_persistence['type'].lower(),
'cookie_name': vip.session_persistence['cookie_name'],
'admin_state_up': vip.admin_state_up}
if with_conn_limit:
form_data['connection_limit'] = vip.connection_limit
if with_diff_subnet:
params['subnet_id'] = vip.subnet_id
res = self.client.post(
reverse(self.ADDVIP_PATH, args=(pool.id,)), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('pool_get', ),
api.neutron: (
'network_list_for_tenant', 'subnet_get', )})
def test_add_vip_post_with_error(self):
vip = self.vips.first()
subnet = self.subnets.first()
pool = self.pools.first()
networks = [{'subnets': [subnet, ]}, ]
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
api.neutron.subnet_get(
IsA(http.HttpRequest), subnet.id).AndReturn(subnet)
api.neutron.network_list_for_tenant(
IsA(http.HttpRequest), self.tenant.id).AndReturn(networks)
self.mox.ReplayAll()
form_data = {
'name': vip.name,
'description': vip.description,
'pool_id': vip.pool_id,
'address': vip.address,
'subnet_id': pool.subnet_id,
'protocol_port': 65536,
'protocol': vip.protocol,
'session_persistence': vip.session_persistence['type'].lower(),
'cookie_name': vip.session_persistence['cookie_name'],
'connection_limit': -2,
'admin_state_up': vip.admin_state_up}
res = self.client.post(
reverse(self.ADDVIP_PATH, args=(pool.id,)), form_data)
self.assertFormErrors(res, 2)
def test_add_vip_get(self):
self._test_add_vip_get()
def test_add_vip_get_with_diff_subnet(self):
self._test_add_vip_get(with_diff_subnet=True)
@test.create_stubs({api.lbaas: ('pool_get', ),
api.neutron: (
'network_list_for_tenant', 'subnet_get', )})
def _test_add_vip_get(self, with_diff_subnet=False):
subnet = self.subnets.first()
pool = self.pools.first()
networks = [{'subnets': [subnet, ]}, ]
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
api.neutron.subnet_get(
IsA(http.HttpRequest), subnet.id).AndReturn(subnet)
api.neutron.network_list_for_tenant(
IsA(http.HttpRequest), self.tenant.id).AndReturn(networks)
self.mox.ReplayAll()
res = self.client.get(reverse(self.ADDVIP_PATH, args=(pool.id,)))
workflow = res.context['workflow']
self.assertTemplateUsed(res, views.WorkflowView.template_name)
self.assertEqual(workflow.name, workflows.AddVip.name)
expected_objs = ['<AddVipStep: addvipaction>', ]
self.assertQuerysetEqual(workflow.steps, expected_objs)
if with_diff_subnet:
self.assertNotEqual(networks[0], pool.subnet_id)
@test.create_stubs({api.lbaas: ('pool_health_monitor_create', )})
def test_add_monitor_post(self):
monitor = self.monitors.first()
form_data = {'type': monitor.type,
'delay': monitor.delay,
'timeout': monitor.timeout,
'max_retries': monitor.max_retries,
'http_method': monitor.http_method,
'url_path': monitor.url_path,
'expected_codes': monitor.expected_codes,
'admin_state_up': monitor.admin_state_up}
api.lbaas.pool_health_monitor_create(
IsA(http.HttpRequest), **form_data).AndReturn(monitor)
self.mox.ReplayAll()
res = self.client.post(reverse(self.ADDMONITOR_PATH), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
def test_add_monitor_post_with_error(self):
monitor = self.monitors.first()
form_data = {'type': monitor.type,
'delay': 0,
'timeout': 0,
'max_retries': 11,
'http_method': monitor.http_method,
'url_path': monitor.url_path,
'expected_codes': monitor.expected_codes,
'admin_state_up': monitor.admin_state_up}
res = self.client.post(reverse(self.ADDMONITOR_PATH), form_data)
self.assertFormErrors(res, 3)
def test_add_monitor_post_with_httpmethod_error(self):
monitor = self.monitors.first()
form_data = {'type': 'http',
'delay': monitor.delay,
'timeout': monitor.timeout,
'max_retries': monitor.max_retries,
'http_method': '',
'url_path': '',
'expected_codes': '',
'admin_state_up': monitor.admin_state_up}
res = self.client.post(reverse(self.ADDMONITOR_PATH), form_data)
self.assertFormErrors(res, 3)
def test_add_monitor_get(self):
res = self.client.get(reverse(self.ADDMONITOR_PATH))
workflow = res.context['workflow']
self.assertTemplateUsed(res, views.WorkflowView.template_name)
self.assertEqual(workflow.name, workflows.AddMonitor.name)
expected_objs = ['<AddMonitorStep: addmonitoraction>', ]
self.assertQuerysetEqual(workflow.steps, expected_objs)
def test_add_member_post(self):
self._test_add_member_post()
def test_add_member_post_without_weight(self):
self._test_add_member_post(with_weight=False)
def test_add_member_post_without_server_list(self):
self._test_add_member_post(with_server_list=False)
def test_add_member_post_multiple_ports(self):
self._test_add_member_post(mult_ports=True)
@test.create_stubs({api.lbaas: ('pool_list', 'pool_get', 'member_create'),
api.neutron: ('port_list',),
api.nova: ('server_list',)})
def _test_add_member_post(self, with_weight=True, with_server_list=True,
mult_ports=False):
member = self.members.first()
server1 = self.AttributeDict({'id':
'12381d38-c3eb-4fee-9763-12de3338042e',
'name': 'vm1'})
server2 = self.AttributeDict({'id':
'12381d38-c3eb-4fee-9763-12de3338043e',
'name': 'vm2'})
api.lbaas.pool_list(IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
api.nova.server_list(IsA(http.HttpRequest)).AndReturn(
[[server1, server2], False])
if with_server_list:
pool = self.pools.list()[1]
port1 = self.AttributeDict(
{'fixed_ips': [{'ip_address': member.address,
'subnet_id':
'e8abc972-eb0c-41f1-9edd-4bc6e3bcd8c9'}],
'network_id': '82288d84-e0a5-42ac-95be-e6af08727e42'})
api.lbaas.pool_get(
IsA(http.HttpRequest), pool.id).AndReturn(pool)
if mult_ports:
port2 = self.AttributeDict(
{'fixed_ips': [{'ip_address': '172.16.88.12',
'subnet_id':
'3f7c5d79-ee55-47b0-9213-8e669fb03009'}],
'network_id': '72c3ab6c-c80f-4341-9dc5-210fa31ac6c2'})
api.neutron.port_list(IsA(http.HttpRequest),
device_id=server1.id).AndReturn([port1, port2])
else:
api.neutron.port_list(IsA(http.HttpRequest),
device_id=server1.id).AndReturn([port1, ])
form_data = {'pool_id': member.pool_id,
'protocol_port': member.protocol_port,
'members': [server1.id],
'admin_state_up': member.admin_state_up}
if with_weight:
form_data['weight'] = member.weight
if with_server_list:
form_data['member_type'] = 'server_list'
else:
form_data['member_type'] = 'member_address'
form_data['address'] = member.address
api.lbaas.member_create(IsA(http.HttpRequest),
**form_data).AndReturn(member)
self.mox.ReplayAll()
res = self.client.post(reverse(self.ADDMEMBER_PATH), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('pool_list',),
api.nova: ('server_list',)})
def test_add_member_post_with_error(self):
member = self.members.first()
server1 = self.AttributeDict({'id':
'12381d38-c3eb-4fee-9763-12de3338042e',
'name': 'vm1'})
server2 = self.AttributeDict({'id':
'12381d38-c3eb-4fee-9763-12de3338043e',
'name': 'vm2'})
api.lbaas.pool_list(IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
api.nova.server_list(IsA(http.HttpRequest)).AndReturn([[server1,
server2],
False])
self.mox.ReplayAll()
# try to create member with invalid protocol port and weight
form_data = {'pool_id': member.pool_id,
'address': member.address,
'protocol_port': 65536,
'weight': -1,
'members': [server1.id],
'admin_state_up': member.admin_state_up}
res = self.client.post(reverse(self.ADDMEMBER_PATH), form_data)
self.assertFormErrors(res, 2)
@test.create_stubs({api.lbaas: ('pool_list',),
api.nova: ('server_list',)})
def test_add_member_get(self):
server1 = self.AttributeDict({'id':
'12381d38-c3eb-4fee-9763-12de3338042e',
'name': 'vm1'})
server2 = self.AttributeDict({'id':
'12381d38-c3eb-4fee-9763-12de3338043e',
'name': 'vm2'})
api.lbaas.pool_list(IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
api.nova.server_list(
IsA(http.HttpRequest)).AndReturn([[server1, server2], False])
self.mox.ReplayAll()
res = self.client.get(reverse(self.ADDMEMBER_PATH))
workflow = res.context['workflow']
self.assertTemplateUsed(res, views.WorkflowView.template_name)
self.assertEqual(workflow.name, workflows.AddMember.name)
expected_objs = ['<AddMemberStep: addmemberaction>', ]
self.assertQuerysetEqual(workflow.steps, expected_objs)
@test.create_stubs({api.lbaas: ('pool_get', 'pool_update')})
def test_update_pool_post(self):
pool = self.pools.first()
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
data = {'name': pool.name,
'description': pool.description,
'lb_method': pool.lb_method,
'admin_state_up': pool.admin_state_up}
api.lbaas.pool_update(IsA(http.HttpRequest), pool.id, pool=data)\
.AndReturn(pool)
self.mox.ReplayAll()
form_data = data.copy()
form_data['pool_id'] = pool.id
res = self.client.post(
reverse(self.UPDATEPOOL_PATH, args=(pool.id,)), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('pool_get',)})
def test_update_pool_get(self):
pool = self.pools.first()
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
self.mox.ReplayAll()
res = self.client.get(reverse(self.UPDATEPOOL_PATH, args=(pool.id,)))
self.assertTemplateUsed(res, 'project/loadbalancers/updatepool.html')
@test.create_stubs({api.lbaas: ('pool_list', 'vip_get',
'vip_update')})
def test_update_vip_post(self):
vip = self.vips.first()
api.lbaas.pool_list(IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
api.lbaas.vip_get(IsA(http.HttpRequest), vip.id).AndReturn(vip)
data = {'name': vip.name,
'description': vip.description,
'pool_id': vip.pool_id,
'session_persistence': {},
'connection_limit': vip.connection_limit,
'admin_state_up': vip.admin_state_up}
api.lbaas.vip_update(IsA(http.HttpRequest), vip.id, vip=data)\
.AndReturn(vip)
self.mox.ReplayAll()
form_data = data.copy()
form_data['vip_id'] = vip.id
res = self.client.post(
reverse(self.UPDATEVIP_PATH, args=(vip.id,)), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('vip_get', 'pool_list')})
def test_update_vip_get(self):
vip = self.vips.first()
api.lbaas.pool_list(IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
api.lbaas.vip_get(IsA(http.HttpRequest), vip.id).AndReturn(vip)
self.mox.ReplayAll()
res = self.client.get(reverse(self.UPDATEVIP_PATH, args=(vip.id,)))
self.assertTemplateUsed(res, 'project/loadbalancers/updatevip.html')
@test.create_stubs({api.lbaas: ('pool_list', 'member_get',
'member_update')})
def test_update_member_post(self):
member = self.members.first()
api.lbaas.pool_list(IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
api.lbaas.member_get(IsA(http.HttpRequest), member.id)\
.AndReturn(member)
data = {'pool_id': member.pool_id,
'weight': member.weight,
'admin_state_up': member.admin_state_up}
api.lbaas.member_update(IsA(http.HttpRequest), member.id, member=data)\
.AndReturn(member)
self.mox.ReplayAll()
form_data = data.copy()
form_data['member_id'] = member.id
res = self.client.post(
reverse(self.UPDATEMEMBER_PATH, args=(member.id,)), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('member_get', 'pool_list')})
def test_update_member_get(self):
member = self.members.first()
api.lbaas.pool_list(IsA(http.HttpRequest), tenant_id=self.tenant.id) \
.AndReturn(self.pools.list())
api.lbaas.member_get(IsA(http.HttpRequest), member.id)\
.AndReturn(member)
self.mox.ReplayAll()
res = self.client.get(
reverse(self.UPDATEMEMBER_PATH, args=(member.id,)))
self.assertTemplateUsed(res, 'project/loadbalancers/updatemember.html')
@test.create_stubs({api.lbaas: ('pool_health_monitor_get',
'pool_health_monitor_update')})
def test_update_monitor_post(self):
monitor = self.monitors.first()
api.lbaas.pool_health_monitor_get(IsA(http.HttpRequest), monitor.id)\
.AndReturn(monitor)
data = {'delay': monitor.delay,
'timeout': monitor.timeout,
'max_retries': monitor.max_retries,
'admin_state_up': monitor.admin_state_up}
api.lbaas.pool_health_monitor_update(
IsA(http.HttpRequest),
monitor.id, health_monitor=data).AndReturn(monitor)
self.mox.ReplayAll()
form_data = data.copy()
form_data['monitor_id'] = monitor.id
res = self.client.post(
reverse(self.UPDATEMONITOR_PATH, args=(monitor.id,)), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('pool_health_monitor_get',)})
def test_update_monitor_get(self):
monitor = self.monitors.first()
api.lbaas.pool_health_monitor_get(IsA(http.HttpRequest), monitor.id)\
.AndReturn(monitor)
self.mox.ReplayAll()
res = self.client.get(
reverse(self.UPDATEMONITOR_PATH, args=(monitor.id,)))
self.assertTemplateUsed(
res, 'project/loadbalancers/updatemonitor.html')
@test.create_stubs({api.lbaas: ('pool_get', 'pool_health_monitor_list',
'pool_monitor_association_create')})
def test_add_pool_monitor_association_post(self):
pool = self.pools.list()[1]
monitors = self.monitors.list()
monitor = self.monitors.list()[1]
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
api.lbaas.pool_health_monitor_list(
IsA(http.HttpRequest),
tenant_id=self.tenant.id).AndReturn(monitors)
form_data = {'monitor_id': monitor.id,
'pool_id': pool.id,
'pool_monitors': pool.health_monitors,
'pool_name': pool.name}
api.lbaas.pool_monitor_association_create(
IsA(http.HttpRequest), **form_data).AndReturn(None)
self.mox.ReplayAll()
res = self.client.post(
reverse(self.ADDASSOC_PATH, args=(pool.id,)), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('pool_get', 'pool_health_monitor_list')})
def test_add_pool_monitor_association_get(self):
pool = self.pools.first()
monitors = self.monitors.list()
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
api.lbaas.pool_health_monitor_list(
IsA(http.HttpRequest),
tenant_id=self.tenant.id).AndReturn(monitors)
self.mox.ReplayAll()
res = self.client.get(reverse(self.ADDASSOC_PATH, args=(pool.id,)))
workflow = res.context['workflow']
self.assertTemplateUsed(res, views.WorkflowView.template_name)
self.assertEqual(workflow.name, workflows.AddPMAssociation.name)
expected_objs = ['<AddPMAssociationStep: addpmassociationaction>', ]
self.assertQuerysetEqual(workflow.steps, expected_objs)
@test.create_stubs({api.lbaas: ('pool_get',
'pool_health_monitor_list',
'pool_monitor_association_delete')})
def test_delete_pool_monitor_association_post(self):
pool = self.pools.first()
monitors = self.monitors.list()
monitor = monitors[0]
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
api.lbaas.pool_health_monitor_list(
IsA(http.HttpRequest)).AndReturn(monitors)
form_data = {'monitor_id': monitor.id,
'pool_id': pool.id,
'pool_monitors': pool.health_monitors,
'pool_name': pool.name}
api.lbaas.pool_monitor_association_delete(
IsA(http.HttpRequest), **form_data).AndReturn(None)
self.mox.ReplayAll()
res = self.client.post(
reverse(self.DELETEASSOC_PATH, args=(pool.id,)), form_data)
self.assertNoFormErrors(res)
self.assertRedirectsNoFollow(res, str(self.INDEX_URL))
@test.create_stubs({api.lbaas: ('pool_get',
'pool_health_monitor_list')})
def test_delete_pool_monitor_association_get(self):
pool = self.pools.first()
monitors = self.monitors.list()
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
api.lbaas.pool_health_monitor_list(
IsA(http.HttpRequest)).AndReturn(monitors)
self.mox.ReplayAll()
res = self.client.get(
reverse(self.DELETEASSOC_PATH, args=(pool.id,)))
workflow = res.context['workflow']
self.assertTemplateUsed(res, views.WorkflowView.template_name)
self.assertEqual(workflow.name, workflows.DeletePMAssociation.name)
expected_objs = [
'<DeletePMAssociationStep: deletepmassociationaction>', ]
self.assertQuerysetEqual(workflow.steps, expected_objs)
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list',
'pool_delete')})
def test_delete_pool(self):
self.set_up_expect()
pool = self.pools.first()
api.lbaas.pool_delete(IsA(http.HttpRequest), pool.id)
self.mox.ReplayAll()
form_data = {"action": "poolstable__deletepool__%s" % pool.id}
res = self.client.post(self.INDEX_URL, form_data)
self.assertNoFormErrors(res)
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list',
'pool_get', 'vip_delete')})
def test_delete_vip(self):
self.set_up_expect()
pool = self.pools.first()
vip = self.vips.first()
api.lbaas.pool_get(IsA(http.HttpRequest), pool.id).AndReturn(pool)
api.lbaas.vip_delete(IsA(http.HttpRequest), vip.id)
self.mox.ReplayAll()
form_data = {"action": "poolstable__deletevip__%s" % pool.id}
res = self.client.post(self.INDEX_URL, form_data)
self.assertNoFormErrors(res)
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list',
'member_delete')})
def test_delete_member(self):
self.set_up_expect()
member = self.members.first()
api.lbaas.member_delete(IsA(http.HttpRequest), member.id)
self.mox.ReplayAll()
form_data = {"action": "memberstable__deletemember__%s" % member.id}
res = self.client.post(self.INDEX_URL, form_data)
self.assertNoFormErrors(res)
@test.create_stubs({api.lbaas: ('pool_list', 'member_list',
'pool_health_monitor_list',
'pool_health_monitor_delete')})
def test_delete_monitor(self):
self.set_up_expect()
monitor = self.monitors.first()
api.lbaas.pool_health_monitor_delete(IsA(http.HttpRequest), monitor.id)
self.mox.ReplayAll()
form_data = {"action": "monitorstable__deletemonitor__%s" % monitor.id}
res = self.client.post(self.INDEX_URL, form_data)
self.assertNoFormErrors(res)
| 39.023656 | 79 | 0.600518 |
9a2a71856dc111d77d969e3d2d8f7752d1725040 | 50,890 | py | Python | conf.py | composex/blog.composex.io | 6e84c44ccc47e2d73a44f490f2ae67c8dbee0d24 | [
"BSD-3-Clause"
] | null | null | null | conf.py | composex/blog.composex.io | 6e84c44ccc47e2d73a44f490f2ae67c8dbee0d24 | [
"BSD-3-Clause"
] | null | null | null | conf.py | composex/blog.composex.io | 6e84c44ccc47e2d73a44f490f2ae67c8dbee0d24 | [
"BSD-3-Clause"
] | 1 | 2020-06-02T08:24:52.000Z | 2020-06-02T08:24:52.000Z | # -*- coding: utf-8 -*-
import time
BLOG_AUTHOR = "https://github.com/johnpreston" # (translatable)
BLOG_TITLE = "ECS Compose-X - Blog" # (translatable)
SITE_URL = "https://blog.compose-x.io/"
# BASE_URL = "https://blog.compose-x.io/"
BLOG_EMAIL = "JohnPreston@users.noreply.github.com"
BLOG_DESCRIPTION = "Technical blog resources around ECS Compose-X." # (translatable)
DEFAULT_LANG = "en"
# What other languages do you have?
# The format is {"translationcode" : "path/to/translation" }
# the path will be used as a prefix for the generated pages location
TRANSLATIONS = {
DEFAULT_LANG: "",
# Example for another language:
# "es": "./es",
}
TRANSLATIONS_PATTERN = '{path}.{lang}.{ext}'
# Links for the sidebar / navigation bar. (translatable)
# This is a dict. The keys are languages, and values are tuples.
#
# For regular links:
# ('https://getnikola.com/', 'Nikola Homepage')
#
# For submenus:
# (
# (
# ('https://apple.com/', 'Apple'),
# ('https://orange.com/', 'Orange'),
# ),
# 'Fruits'
# )
#
# WARNING: Support for submenus is theme-dependent.
# Only one level of submenus is supported.
# WARNING: Some themes, including the default Bootstrap 4 theme,
# may present issues if the menu is too large.
# (in Bootstrap, the navbar can grow too large and cover contents.)
# WARNING: If you link to directories, make sure to follow
# ``STRIP_INDEXES``. If it’s set to ``True``, end your links
# with a ``/``, otherwise end them with ``/index.html`` — or
# else they won’t be highlighted when active.
NAVIGATION_LINKS = {
DEFAULT_LANG: (
("/archive.html", "Archive"),
("/categories/", "Tags"),
("/rss.xml", "RSS feed"),
("https://docs.compose-x.io", "ECS ComposeX Documentation")
),
}
# Alternative navigation links. Works the same way NAVIGATION_LINKS does,
# although themes may not always support them. (translatable)
# (Bootstrap 4: right-side of navbar, Bootblog 4: right side of title)
NAVIGATION_ALT_LINKS = {
DEFAULT_LANG: {}
}
# Name of the theme to use.
THEME = "bootstrap4-jinja"
# Primary color of your theme. This will be used to customize your theme.
# Must be a HEX value.
THEME_COLOR = '#5670d4'
# Theme configuration. Fully theme-dependent. (translatable)
# Examples below are for bootblog4.
# bootblog4 supports: featured_large featured_small featured_on_mobile
# featured_large_image_on_mobile featured_strip_html sidebar
# bootstrap4 supports: navbar_light (defaults to False)
THEME_CONFIG = {
DEFAULT_LANG: {
# Show the latest featured post in a large box, with the previewimage as its background.
'featured_large': False,
# Show the first (remaining) two featured posts in small boxes.
'featured_small': False,
# Show featured posts on mobile.
'featured_on_mobile': True,
# Show image in `featured_large` on mobile.
# `featured_small` displays them only on desktop.
'featured_large_image_on_mobile': True,
# Strip HTML from featured post text.
'featured_strip_html': False,
# Contents of the sidebar, If empty, the sidebar is not displayed.
'sidebar': ''
}
}
# POSTS and PAGES contains (wildcard, destination, template) tuples.
# (translatable)
#
# The wildcard is used to generate a list of source files
# (whatever/thing.rst, for example).
#
# That fragment could have an associated metadata file (whatever/thing.meta),
# and optionally translated files (example for Spanish, with code "es"):
# whatever/thing.es.rst and whatever/thing.es.meta
#
# This assumes you use the default TRANSLATIONS_PATTERN.
#
# From those files, a set of HTML fragment files will be generated:
# cache/whatever/thing.html (and maybe cache/whatever/thing.html.es)
#
# These files are combined with the template to produce rendered
# pages, which will be placed at
# output/TRANSLATIONS[lang]/destination/pagename.html
#
# where "pagename" is the "slug" specified in the metadata file.
# The page might also be placed in /destination/pagename/index.html
# if PRETTY_URLS are enabled.
#
# The difference between POSTS and PAGES is that POSTS are added
# to feeds, indexes, tag lists and archives and are considered part
# of a blog, while PAGES are just independent HTML pages.
#
# Finally, note that destination can be translated, i.e. you can
# specify a different translation folder per language. Example:
# PAGES = (
# ("pages/*.rst", {"en": "pages", "de": "seiten"}, "page.tmpl"),
# ("pages/*.md", {"en": "pages", "de": "seiten"}, "page.tmpl"),
# )
POSTS = (
("posts/*.rst", "posts", "post.tmpl"),
("posts/*.md", "posts", "post.tmpl"),
("posts/*.txt", "posts", "post.tmpl"),
("posts/*.html", "posts", "post.tmpl"),
)
PAGES = (
("pages/*.rst", "pages", "page.tmpl"),
("pages/*.md", "pages", "page.tmpl"),
("pages/*.txt", "pages", "page.tmpl"),
("pages/*.html", "pages", "page.tmpl"),
)
# Below this point, everything is optional
# Post's dates are considered in UTC by default, if you want to use
# another time zone, please set TIMEZONE to match. Check the available
# list from Wikipedia:
# https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
# (e.g. 'Europe/Zurich')
# Also, if you want to use a different time zone in some of your posts,
# you can use the ISO 8601/RFC 3339 format (ex. 2012-03-30T23:00:00+02:00)
TIMEZONE = "Etc/UTC"
# If you want to use ISO 8601 (also valid RFC 3339) throughout Nikola
# (especially in new_post), set this to True.
# Note that this does not affect DATE_FORMAT.
# FORCE_ISO8601 = False
# Date format used to display post dates. (translatable)
# Used by babel.dates, CLDR style: http://cldr.unicode.org/translation/date-time
# You can also use 'full', 'long', 'medium', or 'short'
# DATE_FORMAT = 'YYYY-MM-dd HH:mm'
# Date format used to display post dates, if local dates are used. (translatable)
# Used by moment.js: https://momentjs.com/docs/#/displaying/format/
# JS_DATE_FORMAT = 'YYYY-MM-DD HH:mm'
# Date fanciness.
#
# 0 = using DATE_FORMAT and TIMEZONE
# 1 = using JS_DATE_FORMAT and local user time (via moment.js)
# 2 = using a string like “2 days ago”
#
# Your theme must support it, Bootstrap already does.
# DATE_FANCINESS = 0
# Customize the locale/region used for a language.
# For example, to use British instead of US English: LOCALES = {'en': 'en_GB'}
# LOCALES = {}
# One or more folders containing files to be copied as-is into the output.
# The format is a dictionary of {source: relative destination}.
# Default is:
# FILES_FOLDERS = {'files': ''}
# Which means copy 'files' into 'output'
# One or more folders containing code listings to be processed and published on
# the site. The format is a dictionary of {source: relative destination}.
# Default is:
# LISTINGS_FOLDERS = {'listings': 'listings'}
# Which means process listings from 'listings' into 'output/listings'
# A mapping of languages to file-extensions that represent that language.
# Feel free to add or delete extensions to any list, but don't add any new
# compilers unless you write the interface for it yourself.
#
# 'rest' is reStructuredText
# 'markdown' is Markdown
# 'html' assumes the file is HTML and just copies it
COMPILERS = {
"rest": ('.rst', '.txt'),
"markdown": ('.md', '.mdown', '.markdown'),
"textile": ('.textile',),
"txt2tags": ('.t2t',),
"bbcode": ('.bb',),
"wiki": ('.wiki',),
"ipynb": ('.ipynb',),
"html": ('.html', '.htm'),
# PHP files are rendered the usual way (i.e. with the full templates).
# The resulting files have .php extensions, making it possible to run
# them without reconfiguring your server to recognize them.
"php": ('.php',),
# Pandoc detects the input from the source filename
# but is disabled by default as it would conflict
# with many of the others.
# "pandoc": ('.rst', '.md', '.txt'),
}
# Create by default posts in one file format?
# Set to False for two-file posts, with separate metadata.
# ONE_FILE_POSTS = True
# Preferred metadata format for new posts
# "Nikola": reST comments, wrapped in a HTML comment if needed (default)
# "YAML": YAML wrapped in "---"
# "TOML": TOML wrapped in "+++"
# "Pelican": Native markdown metadata or reST docinfo fields. Nikola style for other formats.
# METADATA_FORMAT = "Nikola"
# Use date-based path when creating posts?
# Can be enabled on a per-post basis with `nikola new_post -d`.
# The setting is ignored when creating pages.
# NEW_POST_DATE_PATH = False
# What format to use when creating posts with date paths?
# Default is '%Y/%m/%d', other possibilities include '%Y' or '%Y/%m'.
# NEW_POST_DATE_PATH_FORMAT = '%Y/%m/%d'
# If this is set to True, the DEFAULT_LANG version will be displayed for
# untranslated posts.
# If this is set to False, then posts that are not translated to a language
# LANG will not be visible at all in the pages in that language.
# SHOW_UNTRANSLATED_POSTS = True
# Nikola supports logo display. If you have one, you can put the URL here.
# Final output is <img src="LOGO_URL" id="logo" alt="BLOG_TITLE">.
# The URL may be relative to the site root.
# LOGO_URL = ''
SHOW_BLOG_TITLE = True
# Paths for different autogenerated bits. These are combined with the
# translation paths.
# Final locations are:
# output / TRANSLATION[lang] / TAG_PATH / index.html (list of tags)
# output / TRANSLATION[lang] / TAG_PATH / tag.html (list of posts for a tag)
# output / TRANSLATION[lang] / TAG_PATH / tag RSS_EXTENSION (RSS feed for a tag)
# (translatable)
# TAG_PATH = "categories"
# By default, the list of tags is stored in
# output / TRANSLATION[lang] / TAG_PATH / index.html
# (see explanation for TAG_PATH). This location can be changed to
# output / TRANSLATION[lang] / TAGS_INDEX_PATH
# with an arbitrary relative path TAGS_INDEX_PATH.
# (translatable)
# TAGS_INDEX_PATH = "tags.html"
# If TAG_PAGES_ARE_INDEXES is set to True, each tag's page will contain
# the posts themselves. If set to False, it will be just a list of links.
# TAG_PAGES_ARE_INDEXES = False
# Set descriptions for tag pages to make them more interesting. The
# default is no description. The value is used in the meta description
# and displayed underneath the tag list or index page’s title.
# TAG_DESCRIPTIONS = {
# DEFAULT_LANG: {
# "blogging": "Meta-blog posts about blogging.",
# "open source": "My contributions to my many, varied, ever-changing, and eternal libre software projects."
# },
# }
# Set special titles for tag pages. The default is "Posts about TAG".
# TAG_TITLES = {
# DEFAULT_LANG: {
# "blogging": "Meta-posts about blogging",
# "open source": "Posts about open source software"
# },
# }
# If you do not want to display a tag publicly, you can mark it as hidden.
# The tag will not be displayed on the tag list page and posts.
# Tag pages will still be generated.
HIDDEN_TAGS = ['mathjax']
# Only include tags on the tag list/overview page if there are at least
# TAGLIST_MINIMUM_POSTS number of posts or more with every tag. Every tag
# page is still generated, linked from posts, and included in the sitemap.
# However, more obscure tags can be hidden from the tag index page.
# TAGLIST_MINIMUM_POSTS = 1
# A list of dictionaries specifying tags which translate to each other.
# Format: a list of dicts {language: translation, language2: translation2, …}
# For example:
# [
# {'en': 'private', 'de': 'Privat'},
# {'en': 'work', 'fr': 'travail', 'de': 'Arbeit'},
# ]
# TAG_TRANSLATIONS = []
# If set to True, a tag in a language will be treated as a translation
# of the literally same tag in all other languages. Enable this if you
# do not translate tags, for example.
# TAG_TRANSLATIONS_ADD_DEFAULTS = True
# Final locations are:
# output / TRANSLATION[lang] / CATEGORY_PATH / index.html (list of categories)
# output / TRANSLATION[lang] / CATEGORY_PATH / CATEGORY_PREFIX category.html (list of posts for a category)
# output / TRANSLATION[lang] / CATEGORY_PATH / CATEGORY_PREFIX category RSS_EXTENSION (RSS feed for a category)
# (translatable)
# CATEGORY_PATH = "categories"
# CATEGORY_PREFIX = "cat_"
# By default, the list of categories is stored in
# output / TRANSLATION[lang] / CATEGORY_PATH / index.html
# (see explanation for CATEGORY_PATH). This location can be changed to
# output / TRANSLATION[lang] / CATEGORIES_INDEX_PATH
# with an arbitrary relative path CATEGORIES_INDEX_PATH.
# (translatable)
# CATEGORIES_INDEX_PATH = "categories.html"
# If CATEGORY_ALLOW_HIERARCHIES is set to True, categories can be organized in
# hierarchies. For a post, the whole path in the hierarchy must be specified,
# using a forward slash ('/') to separate paths. Use a backslash ('\') to escape
# a forward slash or a backslash (i.e. '\//\\' is a path specifying the
# subcategory called '\' of the top-level category called '/').
CATEGORY_ALLOW_HIERARCHIES = False
# If CATEGORY_OUTPUT_FLAT_HIERARCHY is set to True, the output written to output
# contains only the name of the leaf category and not the whole path.
CATEGORY_OUTPUT_FLAT_HIERARCHY = False
# If CATEGORY_PAGES_ARE_INDEXES is set to True, each category's page will contain
# the posts themselves. If set to False, it will be just a list of links.
# CATEGORY_PAGES_ARE_INDEXES = False
# Set descriptions for category pages to make them more interesting. The
# default is no description. The value is used in the meta description
# and displayed underneath the category list or index page’s title.
# CATEGORY_DESCRIPTIONS = {
# DEFAULT_LANG: {
# "blogging": "Meta-blog posts about blogging.",
# "open source": "My contributions to my many, varied, ever-changing, and eternal libre software projects."
# },
# }
# Set special titles for category pages. The default is "Posts about CATEGORY".
# CATEGORY_TITLES = {
# DEFAULT_LANG: {
# "blogging": "Meta-posts about blogging",
# "open source": "Posts about open source software"
# },
# }
# If you do not want to display a category publicly, you can mark it as hidden.
# The category will not be displayed on the category list page.
# Category pages will still be generated.
HIDDEN_CATEGORIES = []
# A list of dictionaries specifying categories which translate to each other.
# Format: a list of dicts {language: translation, language2: translation2, …}
# See TAG_TRANSLATIONS example above.
# CATEGORY_TRANSLATIONS = []
# If set to True, a category in a language will be treated as a translation
# of the literally same category in all other languages. Enable this if you
# do not translate categories, for example.
# CATEGORY_TRANSLATIONS_ADD_DEFAULTS = True
# If no category is specified in a post, the destination path of the post
# can be used in its place. This replaces the sections feature. Using
# category hierarchies is recommended.
# CATEGORY_DESTPATH_AS_DEFAULT = False
# If True, the prefix will be trimmed from the category name, eg. if the
# POSTS destination is "foo/bar", and the path is "foo/bar/baz/quux",
# the category will be "baz/quux" (or "baz" if only the first directory is considered).
# Note that prefixes coming from translations are always ignored.
# CATEGORY_DESTPATH_TRIM_PREFIX = False
# If True, only the first directory of a path will be used.
# CATEGORY_DESTPATH_FIRST_DIRECTORY_ONLY = True
# Map paths to prettier category names. (translatable)
# CATEGORY_DESTPATH_NAMES = {
# DEFAULT_LANG: {
# 'webdev': 'Web Development',
# 'webdev/django': 'Web Development/Django',
# 'random': 'Odds and Ends',
# },
# }
# By default, category indexes will appear in CATEGORY_PATH and use
# CATEGORY_PREFIX. If this is enabled, those settings will be ignored (except
# for the index) and instead, they will follow destination paths (eg. category
# 'foo' might appear in 'posts/foo'). If the category does not come from a
# destpath, first entry in POSTS followed by the category name will be used.
# For this setting, category hierarchies are required and cannot be flattened.
# CATEGORY_PAGES_FOLLOW_DESTPATH = False
# If ENABLE_AUTHOR_PAGES is set to True and there is more than one
# author, author pages are generated.
# ENABLE_AUTHOR_PAGES = True
# Path to author pages. Final locations are:
# output / TRANSLATION[lang] / AUTHOR_PATH / index.html (list of authors)
# output / TRANSLATION[lang] / AUTHOR_PATH / author.html (list of posts by an author)
# output / TRANSLATION[lang] / AUTHOR_PATH / author RSS_EXTENSION (RSS feed for an author)
# (translatable)
# AUTHOR_PATH = "authors"
# If AUTHOR_PAGES_ARE_INDEXES is set to True, each author's page will contain
# the posts themselves. If set to False, it will be just a list of links.
# AUTHOR_PAGES_ARE_INDEXES = False
# Set descriptions for author pages to make them more interesting. The
# default is no description. The value is used in the meta description
# and displayed underneath the author list or index page’s title.
# AUTHOR_PAGES_DESCRIPTIONS = {
# DEFAULT_LANG: {
# "Juanjo Conti": "Python coder and writer.",
# "Roberto Alsina": "Nikola father."
# },
# }
# If you do not want to display an author publicly, you can mark it as hidden.
# The author will not be displayed on the author list page and posts.
# Tag pages will still be generated.
HIDDEN_AUTHORS = ['Guest']
# Final location for the main blog page and sibling paginated pages is
# output / TRANSLATION[lang] / INDEX_PATH / index-*.html
# (translatable)
# INDEX_PATH = ""
# Optional HTML that displayed on “main” blog index.html files.
# May be used for a greeting. (translatable)
FRONT_INDEX_HEADER = {
DEFAULT_LANG: ''
}
# Create per-month archives instead of per-year
# CREATE_MONTHLY_ARCHIVE = False
# Create one large archive instead of per-year
# CREATE_SINGLE_ARCHIVE = False
# Create year, month, and day archives each with a (long) list of posts
# (overrides both CREATE_MONTHLY_ARCHIVE and CREATE_SINGLE_ARCHIVE)
# CREATE_FULL_ARCHIVES = False
# If monthly archives or full archives are created, adds also one archive per day
# CREATE_DAILY_ARCHIVE = False
# Create previous, up, next navigation links for archives
# CREATE_ARCHIVE_NAVIGATION = False
# Final locations for the archives are:
# output / TRANSLATION[lang] / ARCHIVE_PATH / ARCHIVE_FILENAME
# output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / index.html
# output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / index.html
# output / TRANSLATION[lang] / ARCHIVE_PATH / YEAR / MONTH / DAY / index.html
# (translatable)
# ARCHIVE_PATH = ""
# ARCHIVE_FILENAME = "archive.html"
# If ARCHIVES_ARE_INDEXES is set to True, each archive page which contains a list
# of posts will contain the posts themselves. If set to False, it will be just a
# list of links.
# ARCHIVES_ARE_INDEXES = False
# URLs to other posts/pages can take 3 forms:
# rel_path: a relative URL to the current page/post (default)
# full_path: a URL with the full path from the root
# absolute: a complete URL (that includes the SITE_URL)
# URL_TYPE = 'rel_path'
# Extension for RSS feed files
# RSS_EXTENSION = ".xml"
# RSS filename base (without extension); used for indexes and galleries.
# (translatable)
# RSS_FILENAME_BASE = "rss"
# Final location for the blog main RSS feed is:
# output / TRANSLATION[lang] / RSS_PATH / RSS_FILENAME_BASE RSS_EXTENSION
# (translatable)
# RSS_PATH = ""
# Final location for the blog main Atom feed is:
# output / TRANSLATION[lang] / ATOM_PATH / ATOM_FILENAME_BASE ATOM_EXTENSION
# (translatable)
# ATOM_PATH = ""
# Atom filename base (without extension); used for indexes.
# (translatable)
ATOM_FILENAME_BASE = "feed"
# Extension for Atom feed files
# ATOM_EXTENSION = ".atom"
# Slug the Tag URL. Easier for users to type, special characters are
# often removed or replaced as well.
# SLUG_TAG_PATH = True
# Slug the Author URL. Easier for users to type, special characters are
# often removed or replaced as well.
# SLUG_AUTHOR_PATH = True
# A list of redirection tuples, [("foo/from.html", "/bar/to.html")].
#
# A HTML file will be created in output/foo/from.html that redirects
# to the "/bar/to.html" URL. notice that the "from" side MUST be a
# relative URL.
#
# If you don't need any of these, just set to []
REDIRECTIONS = []
# Presets of commands to execute to deploy. Can be anything, for
# example, you may use rsync:
# "rsync -rav --delete output/ joe@my.site:/srv/www/site"
# And then do a backup, or run `nikola ping` from the `ping`
# plugin (`nikola plugin -i ping`). Or run `nikola check -l`.
# You may also want to use github_deploy (see below).
# You can define multiple presets and specify them as arguments
# to `nikola deploy`. If no arguments are specified, a preset
# named `default` will be executed. You can use as many presets
# in a `nikola deploy` command as you like.
# DEPLOY_COMMANDS = {
# 'default': [
# "rsync -rav --delete output/ joe@my.site:/srv/www/site",
# ]
# }
# github_deploy configuration
# For more details, read the manual:
# https://getnikola.com/handbook.html#deploying-to-github
# You will need to configure the deployment branch on GitHub.
GITHUB_SOURCE_BRANCH = 'src'
GITHUB_DEPLOY_BRANCH = 'master'
# The name of the remote where you wish to push to, using github_deploy.
GITHUB_REMOTE_NAME = 'origin'
# Whether or not github_deploy should commit to the source branch automatically
# before deploying.
GITHUB_COMMIT_SOURCE = True
# Where the output site should be located
# If you don't use an absolute path, it will be considered as relative
# to the location of conf.py
# OUTPUT_FOLDER = 'output'
# where the "cache" of partial generated content should be located
# default: 'cache'
# CACHE_FOLDER = 'cache'
# Filters to apply to the output.
# A directory where the keys are either: a file extensions, or
# a tuple of file extensions.
#
# And the value is a list of commands to be applied in order.
#
# Each command must be either:
#
# A string containing a '%s' which will
# be replaced with a filename. The command *must* produce output
# in place.
#
# Or:
#
# A python callable, which will be called with the filename as
# argument.
#
# By default, only .php files uses filters to inject PHP into
# Nikola’s templates. All other filters must be enabled through FILTERS.
#
# Many filters are shipped with Nikola. A list is available in the manual:
# <https://getnikola.com/handbook.html#post-processing-filters>
#
# from nikola import filters
# FILTERS = {
# ".html": [filters.typogrify],
# ".js": [filters.closure_compiler],
# ".jpg": ["jpegoptim --strip-all -m75 -v %s"],
# }
# Executable for the "yui_compressor" filter (defaults to 'yui-compressor').
# YUI_COMPRESSOR_EXECUTABLE = 'yui-compressor'
# Executable for the "closure_compiler" filter (defaults to 'closure-compiler').
# CLOSURE_COMPILER_EXECUTABLE = 'closure-compiler'
# Executable for the "optipng" filter (defaults to 'optipng').
# OPTIPNG_EXECUTABLE = 'optipng'
# Executable for the "jpegoptim" filter (defaults to 'jpegoptim').
# JPEGOPTIM_EXECUTABLE = 'jpegoptim'
# Executable for the "html_tidy_withconfig", "html_tidy_nowrap",
# "html_tidy_wrap", "html_tidy_wrap_attr" and "html_tidy_mini" filters
# (defaults to 'tidy5').
# HTML_TIDY_EXECUTABLE = 'tidy5'
# List of XPath expressions which should be used for finding headers
# ({hx} is replaced by headers h1 through h6).
# You must change this if you use a custom theme that does not use
# "e-content entry-content" as a class for post and page contents.
# HEADER_PERMALINKS_XPATH_LIST = ['*//div[@class="e-content entry-content"]//{hx}']
# Include *every* header (not recommended):
# HEADER_PERMALINKS_XPATH_LIST = ['*//{hx}']
# File blacklist for header permalinks. Contains output path
# (eg. 'output/index.html')
# HEADER_PERMALINKS_FILE_BLACKLIST = []
# Expert setting! Create a gzipped copy of each generated file. Cheap server-
# side optimization for very high traffic sites or low memory servers.
# GZIP_FILES = False
# File extensions that will be compressed
# GZIP_EXTENSIONS = ('.txt', '.htm', '.html', '.css', '.js', '.json', '.atom', '.xml')
# Use an external gzip command? None means no.
# Example: GZIP_COMMAND = "pigz -k {filename}"
# GZIP_COMMAND = None
# Make sure the server does not return a "Accept-Ranges: bytes" header for
# files compressed by this option! OR make sure that a ranged request does not
# return partial content of another representation for these resources. Do not
# use this feature if you do not understand what this means.
# #############################################################################
# Image Gallery Options
# #############################################################################
# One or more folders containing galleries. The format is a dictionary of
# {"source": "relative_destination"}, where galleries are looked for in
# "source/" and the results will be located in
# "OUTPUT_PATH/relative_destination/gallery_name"
# Default is:
# GALLERY_FOLDERS = {"galleries": "galleries"}
# More gallery options:
# THUMBNAIL_SIZE = 180
# MAX_IMAGE_SIZE = 1280
# USE_FILENAME_AS_TITLE = True
# EXTRA_IMAGE_EXTENSIONS = []
#
# If set to False, it will sort by filename instead. Defaults to True
# GALLERY_SORT_BY_DATE = True
# If set to True, EXIF data will be copied when an image is thumbnailed or
# resized. (See also EXIF_WHITELIST)
# PRESERVE_EXIF_DATA = False
# If you have enabled PRESERVE_EXIF_DATA, this option lets you choose EXIF
# fields you want to keep in images. (See also PRESERVE_EXIF_DATA)
#
# For a full list of field names, please see here:
# http://www.cipa.jp/std/documents/e/DC-008-2012_E.pdf
#
# This is a dictionary of lists. Each key in the dictionary is the
# name of a IDF, and each list item is a field you want to preserve.
# If you have a IDF with only a '*' item, *EVERY* item in it will be
# preserved. If you don't want to preserve anything in a IDF, remove it
# from the setting. By default, no EXIF information is kept.
# Setting the whitelist to anything other than {} implies
# PRESERVE_EXIF_DATA is set to True
# To preserve ALL EXIF data, set EXIF_WHITELIST to {"*": "*"}
# EXIF_WHITELIST = {}
# Some examples of EXIF_WHITELIST settings:
# Basic image information:
# EXIF_WHITELIST['0th'] = [
# "Orientation",
# "XResolution",
# "YResolution",
# ]
# If you want to keep GPS data in the images:
# EXIF_WHITELIST['GPS'] = ["*"]
# Embedded thumbnail information:
# EXIF_WHITELIST['1st'] = ["*"]
# If set to True, any ICC profile will be copied when an image is thumbnailed or
# resized.
# PRESERVE_ICC_PROFILES = False
# Folders containing images to be used in normal posts or pages.
# IMAGE_FOLDERS is a dictionary of the form {"source": "destination"},
# where "source" is the folder containing the images to be published, and
# "destination" is the folder under OUTPUT_PATH containing the images copied
# to the site. Thumbnail images will be created there as well.
# To reference the images in your posts, include a leading slash in the path.
# For example, if IMAGE_FOLDERS = {'images': 'images'}, write
#
# .. image:: /images/tesla.jpg
#
# See the Nikola Handbook for details (in the “Embedding Images” and
# “Thumbnails” sections)
# Images will be scaled down according to IMAGE_THUMBNAIL_SIZE and MAX_IMAGE_SIZE
# options, but will have to be referenced manually to be visible on the site
# (the thumbnail has ``.thumbnail`` added before the file extension by default,
# but a different naming template can be configured with IMAGE_THUMBNAIL_FORMAT).
IMAGE_FOLDERS = {'images': 'images'}
IMAGE_THUMBNAIL_SIZE = 400
IMAGE_THUMBNAIL_FORMAT = '{name}.thumbnail{ext}'
# #############################################################################
# HTML fragments and diverse things that are used by the templates
# #############################################################################
# Data about post-per-page indexes.
# INDEXES_PAGES defaults to ' old posts, page %d' or ' page %d' (translated),
# depending on the value of INDEXES_PAGES_MAIN.
#
# (translatable) If the following is empty, defaults to BLOG_TITLE:
# INDEXES_TITLE = ""
#
# (translatable) If the following is empty, defaults to ' [old posts,] page %d' (see above):
# INDEXES_PAGES = ""
#
# If the following is True, INDEXES_PAGES is also displayed on the main (the
# newest) index page (index.html):
# INDEXES_PAGES_MAIN = False
#
# If the following is True, index-1.html has the oldest posts, index-2.html the
# second-oldest posts, etc., and index.html has the newest posts. This ensures
# that all posts on index-x.html will forever stay on that page, now matter how
# many new posts are added.
# If False, index-1.html has the second-newest posts, index-2.html the third-newest,
# and index-n.html the oldest posts. When this is active, old posts can be moved
# to other index pages when new posts are added.
# INDEXES_STATIC = True
#
# (translatable) If PRETTY_URLS is set to True, this setting will be used to create
# prettier URLs for index pages, such as page/2/index.html instead of index-2.html.
# Valid values for this settings are:
# * False,
# * a list or tuple, specifying the path to be generated,
# * a dictionary mapping languages to lists or tuples.
# Every list or tuple must consist of strings which are used to combine the path;
# for example:
# ['page', '{number}', '{index_file}']
# The replacements
# {number} --> (logical) page number;
# {old_number} --> the page number inserted into index-n.html before (zero for
# the main page);
# {index_file} --> value of option INDEX_FILE
# are made.
# Note that in case INDEXES_PAGES_MAIN is set to True, a redirection will be created
# for the full URL with the page number of the main page to the normal (shorter) main
# page URL.
# INDEXES_PRETTY_PAGE_URL = False
#
# If the following is true, a page range navigation will be inserted to indices.
# Please note that this will undo the effect of INDEXES_STATIC, as all index pages
# must be recreated whenever the number of pages changes.
# SHOW_INDEX_PAGE_NAVIGATION = False
# If the following is True, a meta name="generator" tag is added to pages. The
# generator tag is used to specify the software used to generate the page
# (it promotes Nikola).
# META_GENERATOR_TAG = True
# Color scheme to be used for code blocks. If your theme provides
# "assets/css/code.css" this is ignored. Leave empty to disable.
# Can be any of:
# algol, algol_nu, autumn, borland, bw, colorful, default, emacs, friendly,
# fruity, igor, lovelace, manni, monokai, murphy, native, paraiso-dark,
# paraiso-light, pastie, perldoc, rrt, tango, trac, vim, vs, xcode
# This list MAY be incomplete since pygments adds styles every now and then.
# Check with list(pygments.styles.get_all_styles()) in an interpreter.
# CODE_COLOR_SCHEME = 'default'
# FAVICONS contains (name, file, size) tuples.
# Used to create favicon link like this:
# <link rel="name" href="file" sizes="size"/>
# FAVICONS = (
# ("icon", "/favicon.ico", "16x16"),
# ("icon", "/icon_128x128.png", "128x128"),
# )
# Show teasers (instead of full posts) in indexes? Defaults to False.
# INDEX_TEASERS = False
# HTML fragments with the Read more... links.
# The following tags exist and are replaced for you:
# {link} A link to the full post page.
# {read_more} The string “Read more” in the current language.
# {reading_time} An estimate of how long it will take to read the post.
# {remaining_reading_time} An estimate of how long it will take to read the post, sans the teaser.
# {min_remaining_read} The string “{remaining_reading_time} min remaining to read” in the current language.
# {paragraph_count} The amount of paragraphs in the post.
# {remaining_paragraph_count} The amount of paragraphs in the post, sans the teaser.
# {post_title} The title of the post.
# {{ A literal { (U+007B LEFT CURLY BRACKET)
# }} A literal } (U+007D RIGHT CURLY BRACKET)
# 'Read more...' for the index page, if INDEX_TEASERS is True (translatable)
INDEX_READ_MORE_LINK = '<p class="more"><a href="{link}">{read_more}…</a></p>'
# 'Read more...' for the feeds, if FEED_TEASERS is True (translatable)
FEED_READ_MORE_LINK = '<p><a href="{link}">{read_more}…</a> ({min_remaining_read})</p>'
# Append a URL query to the FEED_READ_MORE_LINK in Atom and RSS feeds. Advanced
# option used for traffic source tracking.
# Minimum example for use with Piwik: "pk_campaign=feed"
# The following tags exist and are replaced for you:
# {feedRelUri} A relative link to the feed.
# {feedFormat} The name of the syndication format.
# Example using replacement for use with Google Analytics:
# "utm_source={feedRelUri}&utm_medium=nikola_feed&utm_campaign={feedFormat}_feed"
FEED_LINKS_APPEND_QUERY = False
# A HTML fragment describing the license, for the sidebar.
# (translatable)
LICENSE = ""
# I recommend using the Creative Commons' wizard:
# https://creativecommons.org/choose/
# LICENSE = """
# <a rel="license" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">
# <img alt="Creative Commons License BY-NC-SA"
# style="border-width:0; margin-bottom:12px;"
# src="https://i.creativecommons.org/l/by-nc-sa/4.0/88x31.png"></a>"""
# A small copyright notice for the page footer (in HTML).
# (translatable)
CONTENT_FOOTER = 'Contents © {date} <a href="mailto:{email}">{author}</a> - Powered by <a href="https://getnikola.com" rel="nofollow">Nikola</a> {license}'
# Things that will be passed to CONTENT_FOOTER.format(). This is done
# for translatability, as dicts are not formattable. Nikola will
# intelligently format the setting properly.
# The setting takes a dict. The keys are languages. The values are
# tuples of tuples of positional arguments and dicts of keyword arguments
# to format(). For example, {'en': (('Hello'), {'target': 'World'})}
# results in CONTENT_FOOTER['en'].format('Hello', target='World').
# If you need to use the literal braces '{' and '}' in your footer text, use
# '{{' and '}}' to escape them (str.format is used)
# WARNING: If you do not use multiple languages with CONTENT_FOOTER, this
# still needs to be a dict of this format. (it can be empty if you
# do not need formatting)
# (translatable)
CONTENT_FOOTER_FORMATS = {
DEFAULT_LANG: (
(),
{
"email": BLOG_EMAIL,
"author": BLOG_AUTHOR,
"date": time.gmtime().tm_year,
"license": LICENSE
}
)
}
# A simple copyright tag for inclusion in RSS feeds that works just
# like CONTENT_FOOTER and CONTENT_FOOTER_FORMATS
RSS_COPYRIGHT = 'Contents © {date} <a href="mailto:{email}">{author}</a> {license}'
RSS_COPYRIGHT_PLAIN = 'Contents © {date} {author} {license}'
RSS_COPYRIGHT_FORMATS = CONTENT_FOOTER_FORMATS
# To use comments, you can choose between different third party comment
# systems. The following comment systems are supported by Nikola:
# disqus, facebook, intensedebate, isso, muut, commento
# You can leave this option blank to disable comments.
COMMENT_SYSTEM = "disqus"
# And you also need to add your COMMENT_SYSTEM_ID which
# depends on what comment system you use. The default is
# "nikolademo" which is a test account for Disqus. More information
# is in the manual.
COMMENT_SYSTEM_ID = "ecs-compose-x-blog"
# Create index.html for page folders?
# WARNING: if a page would conflict with the index file (usually
# caused by setting slug to `index`), the PAGE_INDEX
# will not be generated for that directory.
# PAGE_INDEX = False
# Enable comments on pages (i.e. not posts)?
# COMMENTS_IN_PAGES = False
# Enable comments on picture gallery pages?
# COMMENTS_IN_GALLERIES = False
# What file should be used for directory indexes?
# Defaults to index.html
# Common other alternatives: default.html for IIS, index.php
# INDEX_FILE = "index.html"
# If a link ends in /index.html, drop the index.html part.
# http://mysite/foo/bar/index.html => http://mysite/foo/bar/
# (Uses the INDEX_FILE setting, so if that is, say, default.html,
# it will instead /foo/default.html => /foo)
STRIP_INDEXES = False
# List of files relative to the server root (!) that will be asked to be excluded
# from indexing and other robotic spidering. * is supported. Will only be effective
# if SITE_URL points to server root. The list is used to exclude resources from
# /robots.txt and /sitemap.xml, and to inform search engines about /sitemapindex.xml.
# ROBOTS_EXCLUSIONS = ["/archive.html", "/category/*.html"]
# Instead of putting files in <slug>.html, put them in <slug>/index.html.
# No web server configuration is required. Also enables STRIP_INDEXES.
# This can be disabled on a per-page/post basis by adding
# .. pretty_url: False
# to the metadata.
PRETTY_URLS = True
# If True, publish future dated posts right away instead of scheduling them.
# Defaults to False.
# FUTURE_IS_NOW = False
# If True, future dated posts are allowed in deployed output
# Only the individual posts are published/deployed; not in indexes/sitemap
# Generally, you want FUTURE_IS_NOW and DEPLOY_FUTURE to be the same value.
# DEPLOY_FUTURE = False
# If False, draft posts will not be deployed
# DEPLOY_DRAFTS = True
# Allows scheduling of posts using the rule specified here (new_post -s)
# Specify an iCal Recurrence Rule: http://www.kanzaki.com/docs/ical/rrule.html
# SCHEDULE_RULE = ''
# If True, use the scheduling rule to all posts (not pages!) by default
# SCHEDULE_ALL = False
# Do you want a add a Mathjax config file?
# MATHJAX_CONFIG = ""
# If you want support for the $.$ syntax (which may conflict with running
# text!), just use this config:
# MATHJAX_CONFIG = """
# <script type="text/x-mathjax-config">
# MathJax.Hub.Config({
# tex2jax: {
# inlineMath: [ ['$','$'], ["\\\(","\\\)"] ],
# displayMath: [ ['$$','$$'], ["\\\[","\\\]"] ],
# processEscapes: true
# },
# displayAlign: 'center', // Change this to 'left' if you want left-aligned equations.
# "HTML-CSS": {
# styles: {'.MathJax_Display': {"margin": 0}}
# }
# });
# </script>
# """
# Want to use KaTeX instead of MathJax? While KaTeX may not support every
# feature yet, it's faster and the output looks better.
# USE_KATEX = False
# KaTeX auto-render settings. If you want support for the $.$ syntax (which may
# conflict with running text!), just use this config:
# KATEX_AUTO_RENDER = """
# delimiters: [
# {left: "$$", right: "$$", display: true},
# {left: "\\\\[", right: "\\\\]", display: true},
# {left: "\\\\begin{equation*}", right: "\\\\end{equation*}", display: true},
# {left: "$", right: "$", display: false},
# {left: "\\\\(", right: "\\\\)", display: false}
# ]
# """
# Do you want to customize the nbconversion of your IPython notebook?
# IPYNB_CONFIG = {}
# With the following example configuration you can use a custom jinja template
# called `toggle.tpl` which has to be located in your site/blog main folder:
# IPYNB_CONFIG = {'Exporter': {'template_file': 'toggle'}}
# What Markdown extensions to enable?
# You will also get gist, nikola and podcast because those are
# done in the code, hope you don't mind ;-)
# Note: most Nikola-specific extensions are done via the Nikola plugin system,
# with the MarkdownExtension class and should not be added here.
# Defaults are markdown.extensions.(fenced_code|codehilite|extra)
# markdown.extensions.meta is required for Markdown metadata.
MARKDOWN_EXTENSIONS = ['markdown.extensions.fenced_code', 'markdown.extensions.codehilite', 'markdown.extensions.extra']
# Options to be passed to markdown extensions (See https://python-markdown.github.io/reference/)
# Default is {} (no config at all)
# MARKDOWN_EXTENSION_CONFIGS = {}
# Extra options to pass to the pandoc command.
# by default, it's empty, is a list of strings, for example
# ['-F', 'pandoc-citeproc', '--bibliography=/Users/foo/references.bib']
# Pandoc does not demote headers by default. To enable this, you can use, for example
# ['--base-header-level=2']
# PANDOC_OPTIONS = []
# Social buttons. This is sample code for AddThis (which was the default for a
# long time). Insert anything you want here, or even make it empty (which is
# the default right now)
# (translatable)
# SOCIAL_BUTTONS_CODE = """
# <!-- Social buttons -->
# <div id="addthisbox" class="addthis_toolbox addthis_peekaboo_style addthis_default_style addthis_label_style addthis_32x32_style">
# <a class="addthis_button_more">Share</a>
# <ul><li><a class="addthis_button_facebook"></a>
# <li><a class="addthis_button_google_plusone_share"></a>
# <li><a class="addthis_button_linkedin"></a>
# <li><a class="addthis_button_twitter"></a>
# </ul>
# </div>
# <script src="https://s7.addthis.com/js/300/addthis_widget.js#pubid=ra-4f7088a56bb93798"></script>
# <!-- End of social buttons -->
# """
# Show link to source for the posts?
# SHOW_SOURCELINK = True
# Copy the source files for your pages?
# Setting it to False implies SHOW_SOURCELINK = False
# COPY_SOURCES = True
# Modify the number of Post per Index Page
# Defaults to 10
# INDEX_DISPLAY_POST_COUNT = 10
# By default, Nikola generates RSS files for the website and for tags, and
# links to it. Set this to False to disable everything RSS-related.
# GENERATE_RSS = True
# By default, Nikola does not generates Atom files for indexes and links to
# them. Generate Atom for tags by setting TAG_PAGES_ARE_INDEXES to True.
# Atom feeds are built based on INDEX_DISPLAY_POST_COUNT and not FEED_LENGTH
# Switch between plain-text summaries and full HTML content using the
# FEED_TEASER option. FEED_LINKS_APPEND_QUERY is also respected. Atom feeds
# are generated even for old indexes and have pagination link relations
# between each other. Old Atom feeds with no changes are marked as archived.
# GENERATE_ATOM = False
# Only include teasers in Atom and RSS feeds. Disabling include the full
# content. Defaults to True.
# FEED_TEASERS = True
# Strip HTML from Atom and RSS feed summaries and content. Defaults to False.
# FEED_PLAIN = False
# Number of posts in Atom and RSS feeds.
# FEED_LENGTH = 10
# RSS_LINK is a HTML fragment to link the RSS or Atom feeds. If set to None,
# the base.tmpl will use the feed Nikola generates. However, you may want to
# change it for a FeedBurner feed or something else.
# RSS_LINK = None
# A search form to search this site, for the sidebar. You can use a Google
# custom search (https://www.google.com/cse/)
# Or a DuckDuckGo search: https://duckduckgo.com/search_box.html
# Default is no search form.
# (translatable)
# SEARCH_FORM = ""
#
# This search form works for any site and looks good in the "site" theme where
# it appears on the navigation bar:
#
# SEARCH_FORM = """
# <!-- DuckDuckGo custom search -->
# <form method="get" id="search" action="https://duckduckgo.com/"
# class="navbar-form pull-left">
# <input type="hidden" name="sites" value="%s">
# <input type="hidden" name="k8" value="#444444">
# <input type="hidden" name="k9" value="#D51920">
# <input type="hidden" name="kt" value="h">
# <input type="text" name="q" maxlength="255"
# placeholder="Search…" class="span2" style="margin-top: 4px;">
# <input type="submit" value="DuckDuckGo Search" style="visibility: hidden;">
# </form>
# <!-- End of custom search -->
# """ % SITE_URL
#
# If you prefer a Google search form, here's an example that should just work:
# SEARCH_FORM = """
# <!-- Google custom search -->
# <form method="get" action="https://www.google.com/search" class="navbar-form navbar-right" role="search">
# <div class="form-group">
# <input type="text" name="q" class="form-control" placeholder="Search">
# </div>
# <button type="submit" class="btn btn-primary">
# <span class="glyphicon glyphicon-search"></span>
# </button>
# <input type="hidden" name="sitesearch" value="%s">
# </form>
# <!-- End of custom search -->
# """ % SITE_URL
# Use content distribution networks for jQuery, twitter-bootstrap css and js,
# and html5shiv (for older versions of Internet Explorer)
# If this is True, jQuery and html5shiv are served from the Google CDN and
# Bootstrap is served from BootstrapCDN (provided by MaxCDN)
# Set this to False if you want to host your site without requiring access to
# external resources.
# USE_CDN = False
# Check for USE_CDN compatibility.
# If you are using custom themes, have configured the CSS properly and are
# receiving warnings about incompatibility but believe they are incorrect, you
# can set this to False.
# USE_CDN_WARNING = True
# Extra things you want in the pages HEAD tag. This will be added right
# before </head>
# (translatable)
# EXTRA_HEAD_DATA = ""
# Google Analytics or whatever else you use. Added to the bottom of <body>
# in the default template (base.tmpl).
# (translatable)
# BODY_END = """
# <!-- Global site tag (gtag.js) - Google Analytics -->
# <script async src="https://www.googletagmanager.com/gtag/js?id=UA-86753837-4"></script>
# <script>
# window.dataLayer = window.dataLayer || [];
# function gtag(){dataLayer.push(arguments);}
# gtag('js', new Date());
#
# gtag('config', 'UA-86753837-4');
# </script>
#
# """
# regular expression.
# To make it work you need to name parts of your regular expression.
# The following names will be used to extract metadata:
# - title
# - slug
# - date
# - tags
# - link
# - description
#
# An example re is the following:
# '.*\/(?P<date>\d{4}-\d{2}-\d{2})-(?P<slug>.*)-(?P<title>.*)\.rst'
# (Note the '.*\/' in the beginning -- matches source paths relative to conf.py)
# FILE_METADATA_REGEXP = None
# Should titles fetched from file metadata be unslugified (made prettier?)
# FILE_METADATA_UNSLUGIFY_TITLES = True
# If enabled, extract metadata from docinfo fields in reST documents.
# If your text files start with a level 1 heading, it will be treated as the
# document title and will be removed from the text.
# USE_REST_DOCINFO_METADATA = False
# If enabled, hide docinfo fields in reST document output
# HIDE_REST_DOCINFO = False
# Map metadata from other formats to Nikola names.
# Supported formats: yaml, toml, rest_docinfo, markdown_metadata
# METADATA_MAPPING = {}
#
# Example for Pelican compatibility:
# METADATA_MAPPING = {
# "rest_docinfo": {"summary": "description", "modified": "updated"},
# "markdown_metadata": {"summary": "description", "modified": "updated"}
# }
# Other examples: https://getnikola.com/handbook.html#mapping-metadata-from-other-formats
# Map metadata between types/values. (Runs after METADATA_MAPPING.)
# Supported formats: nikola, yaml, toml, rest_docinfo, markdown_metadata
# The value on the right should be a dict of callables.
# METADATA_VALUE_MAPPING = {}
# Examples:
# METADATA_VALUE_MAPPING = {
# "yaml": {"keywords": lambda value: ', '.join(value)}, # yaml: 'keywords' list -> str
# "nikola": {
# "widgets": lambda value: value.split(', '), # nikola: 'widgets' comma-separated string -> list
# "tags": str.lower # nikola: force lowercase 'tags' (input would be string)
# }
# }
# Additional metadata that is added to a post when creating a new_post
# ADDITIONAL_METADATA = {}
# Nikola supports Twitter Card summaries, but they are disabled by default.
# They make it possible for you to attach media to Tweets that link
# to your content.
#
# Uncomment and modify to following lines to match your accounts.
# Images displayed come from the `previewimage` meta tag.
# You can specify the card type by using the `card` parameter in TWITTER_CARD.
# TWITTER_CARD = {
# # 'use_twitter_cards': True, # enable Twitter Cards
# # 'card': 'summary', # Card type, you can also use 'summary_large_image',
# # see https://dev.twitter.com/cards/types
# # 'site': '@website', # twitter nick for the website
# # 'creator': '@username', # Username for the content creator / author.
# }
# Bundle JS and CSS into single files to make site loading faster in a HTTP/1.1
# environment but is not recommended for HTTP/2.0 when caching is used.
# Defaults to True.
USE_BUNDLES = False
# Plugins you don't want to use. Be careful :-)
# DISABLED_PLUGINS = ["render_galleries"]
# Special settings to disable only parts of the indexes plugin.
# Use with care.
# DISABLE_INDEXES = False
# DISABLE_MAIN_ATOM_FEED = False
# DISABLE_MAIN_RSS_FEED = False
# Add the absolute paths to directories containing plugins to use them.
# For example, the `plugins` directory of your clone of the Nikola plugins
# repository.
# EXTRA_PLUGINS_DIRS = []
# Add the absolute paths to directories containing themes to use them.
# For example, the `v7` directory of your clone of the Nikola themes
# repository.
# EXTRA_THEMES_DIRS = []
# List of regular expressions, links matching them will always be considered
# valid by "nikola check -l"
# LINK_CHECK_WHITELIST = []
# If set to True, enable optional hyphenation in your posts (requires pyphen)
# Enabling hyphenation has been shown to break math support in some cases,
# use with caution.
# HYPHENATE = False
# The <hN> tags in HTML generated by certain compilers (reST/Markdown)
# will be demoted by that much (1 → h1 will become h2 and so on)
# This was a hidden feature of the Markdown and reST compilers in the
# past. Useful especially if your post titles are in <h1> tags too, for
# example.
# (defaults to 1.)
# DEMOTE_HEADERS = 1
# If you don’t like slugified file names ([a-z0-9] and a literal dash),
# and would prefer to use all the characters your file system allows.
# USE WITH CARE! This is also not guaranteed to be perfect, and may
# sometimes crash Nikola, your web server, or eat your cat.
# USE_SLUGIFY = True
# If set to True, the tags 'draft', 'mathjax' and 'private' have special
# meaning. If set to False, these tags are handled like regular tags.
USE_TAG_METADATA = False
# If set to True, a warning is issued if one of the 'draft', 'mathjax'
# and 'private' tags are found in a post. Useful for checking that
# migration was successful.
WARN_ABOUT_TAG_METADATA = False
# Templates will use those filters, along with the defaults.
# Consult your engine's documentation on filters if you need help defining
# those.
# TEMPLATE_FILTERS = {}
# Put in global_context things you want available on all your templates.
# It can be anything, data, functions, modules, etc.
GLOBAL_CONTEXT = {}
GLOBAL_CONTEXT['HACK_VARIANT'] = 'dark-grey'
# Add functions here and they will be called with template
# GLOBAL_CONTEXT as parameter when the template is about to be
# rendered
GLOBAL_CONTEXT_FILLER = []
| 40.229249 | 184 | 0.710041 |
99142119456ed12e16e927f5af2032a916fcd744 | 1,083 | py | Python | examples/python/web-service/webservice.py | andrestone/cdk8s | 473b5ef7f442b932e9c4c4356945b91e8e1bc4e4 | [
"Apache-2.0"
] | 2,160 | 2020-03-02T23:56:13.000Z | 2021-03-15T12:02:14.000Z | examples/python/web-service/webservice.py | andrestone/cdk8s | 473b5ef7f442b932e9c4c4356945b91e8e1bc4e4 | [
"Apache-2.0"
] | 454 | 2020-03-03T06:31:02.000Z | 2021-03-10T12:12:31.000Z | examples/python/web-service/webservice.py | andrestone/cdk8s | 473b5ef7f442b932e9c4c4356945b91e8e1bc4e4 | [
"Apache-2.0"
] | 178 | 2020-03-03T06:25:09.000Z | 2021-03-03T17:58:57.000Z | #!/usr/bin/env python3
from constructs import Construct, Node
from imports import k8s
class WebService(Construct):
def __init__(self, scope: Construct, id: str, *, image: str, replicas=1, port=80, containerPort=8080, **kwargs):
super().__init__(scope, id)
label = {"app": Node.of(self).id}
k8s.Service(self, "service",
spec=k8s.ServiceSpec(
type="LoadBalancer",
ports=[k8s.ServicePort(port=port, target_port=k8s.IntOrString.from_number(containerPort))],
selector=label))
k8s.Deployment(self, "deployment",
spec=k8s.DeploymentSpec(
replicas=replicas,
selector=k8s.LabelSelector(match_labels=label),
template=k8s.PodTemplateSpec(
metadata=k8s.ObjectMeta(labels=label),
spec=k8s.PodSpec(containers=[
k8s.Container(
name="web",
image=image,
ports=[k8s.ContainerPort(container_port=containerPort)])]))))
| 36.1 | 116 | 0.573407 |
11a87a59efb8a2e18b3774caba2d720d14aaa43c | 21,905 | py | Python | bioinformatics-programs/getDomainsFromHMMScanOrRpsAndTm.py | dengzq1234/TREND | 0374da1fbdd3b5236445d62f07ea84485074b437 | [
"MIT"
] | null | null | null | bioinformatics-programs/getDomainsFromHMMScanOrRpsAndTm.py | dengzq1234/TREND | 0374da1fbdd3b5236445d62f07ea84485074b437 | [
"MIT"
] | null | null | null | bioinformatics-programs/getDomainsFromHMMScanOrRpsAndTm.py | dengzq1234/TREND | 0374da1fbdd3b5236445d62f07ea84485074b437 | [
"MIT"
] | null | null | null | #!/usr/bin/python
import sys, getopt, re
import collections
import traceback
import json
import math
from subprocess import call
from Bio import SeqIO
USAGE = "\n\nThe script extracts domain information from the results of hmmscan or rpsblast.\n\n" + \
"python " + sys.argv[0] + '''
-h - help
-i || --ifile - input protein fasta file
-p || --iprocess - 'hmmscan' or 'rpsblast'
-r || --ofourth - output file for hmmscan or rpsblast (and input for rpcbproc)
-f || --ofifth - output file for rpcbproc
-x || --osixth - output file for tmhmmscan
-a || --oseventh - output file for segmasker
[-A || --hmmscanDbPath] - path to hmmscan database
[-B || --rpsblastDbPath] - path to rpsblast database
[-C || --rpsprocDbPath] - path to database for rpcbproc
[-D || --dbname] - domain prediction database name
[-H || --hmmscanPath] - hmmscan program full path
[-R || --rpsblastPath] - rpsblast program full path
[-P || --rpsbprocPath] - rpsbproc program full path
[-T || --tmhmm2Path] - tmhmm2 program full path
[-S || --segmaskerPath]- segmasker program full path
[-E || --runSegmasker] - run or not segmasker
[-e || --evalue] - e-value threshold of a recognized domain
[-y || --probability] - probability for hmmscan
[-t || --tabformat] - output file format as tab delimited file (yes||y or no||n, default no)
[-j || --jsonformat] - output file format as json (yes||y or no||n, default yes)
[-u || --cpu] - number of threads for hmmscan or rpsblast; default=4
[-m || --sites] - shoud protein sites be included to the resulting file, default False
[-o || --ofile] - output file with domain information for each protein in tab delimited text format
[-n || --osecond] - output file with counts of each domain architecture variant in tab delimited text format
[-b || --othird] - output file with domain information for each protein in json format
'''
#Programs with full paths
HMMSCAN_PROGRAM = None
RPSBLAST_PROGRAM = None
RPSBPROC_PROGRAM = None
TMHMMSCAN_PROGRAM = None
SEGMASKER_PROGRAM = None
# Global parameters specified via program arguments
PROTEIN_TO_DOMAININFO_FILE = "protein-to-domain-info.txt"
DOMAIN_ARCHITECT_TO_COUNT_FILE = "domainArchitec-to-count.txt"
PROTEIN_TO_DOMAININFO_JSONFILE = "proteinToDomainJson.json"
PROTEIN_TO_SITES_FILE = "proteinToSites.txt"
GET_JSON = True
GET_TAB = False
JOIN_STRING = True
RUN_SEGMASKER = False
SEQUENCE_LINE_LEN = 60
INPUT_FILE_FASTA = None
PROCESS_TYPE = None
OUTPUT_RPSBLAST_OR_HMMSCAN = "HMMSCAN_RESULT"
OUTPUT_RPSBPROC = "RPSBPROC_RESULT"
OUTPUT_TMHMMSCAN = "TMHMMSCan_RESULT"
HMMSCAN_DB_PATH = "/home/vadim/UTOakRidge/Soft/hmmer3_data/Pfam31/Pfam-A.hmm"
RPSBLAST_DB_PATH = "/home/vadim/Softs/rpsblastdb/"
RPSBPROC_DB_PATH = "/home/vadim/Softs/rpsbproc/data/Cdd_NCBI"
DB_NAME = ""
CPU = 4
PROTEIN_SITES_INCLUDE = False
EVAL_THRESHOLD = 0.01
HMMSCAN_PROBABILITY = 50
# Global parameters
BORDER_STYLES = ["jagged", "curved"]
HMMSCAN = "hmmscan"
RPSBLAST = "rpsblast"
DOMAIN = "DOMAIN"
PROTEIN_SITE = "PROTEIN_SITE"
# Global datastructures which are got initialized and manipulated by the program
PROTREF_TO_DOMAIN_INFO = collections.defaultdict(list)
PROTREF_TO_DOMAINS = dict()
PROT_NAME_TO_LENGTH = dict()
DOMAIN_ARCHITECT_TO_COUNT_DICT = collections.defaultdict(int)
PROTEIN_TO_SITES = collections.defaultdict(list)
PROTEINS_TO_SEQUENCES = dict()
def initialyze(argv):
global HMMSCAN_PROGRAM, RPSBLAST_PROGRAM, RPSBPROC_PROGRAM, TMHMMSCAN_PROGRAM, SEGMASKER_PROGRAM, INPUT_FILE_FASTA, PROCESS_TYPE, OUTPUT_RPSBLAST_OR_HMMSCAN, \
OUTPUT_RPSBPROC, OUTPUT_TMHMMSCAN, OUTPUT_SEGMASKER, HMMSCAN_DB_PATH, RPSBLAST_DB_PATH, RPSBPROC_DB_PATH, DB_NAME, CPU, EVAL_THRESHOLD, HMMSCAN_PROBABILITY, \
GET_TAB, GET_JSON, RUN_SEGMASKER, PROTEIN_TO_DOMAININFO_FILE, DOMAIN_ARCHITECT_TO_COUNT_FILE, PROTEIN_TO_DOMAININFO_JSONFILE, PROTEIN_SITES_INCLUDE
try:
opts, args = getopt.getopt(argv[1:],"hi:p:r:f:x:a:A:B:C:D:H:R:P:T:S:E:e:y:t:j:u:m:o:n:b:",["ifile=", "iprocess=", "ofourth=", "ofifth=", "osixth=", "oseventh", "hmmscanDbPath=", \
"rpsblastDbPath=", "rpsprocDbPath=", "dbname=", "hmmscanPath=", "rpsblastPath", "rpsbprocPath", "tmhmm2Path", "segmaskerPath", "runSegmasker", "evalue=", "tabformat=", "jsonformat=", "cpu=", "sites=", "ofile=", "osecond=", "othird="])
if len(opts) == 0:
raise getopt.GetoptError("Options are required\n")
except getopt.GetoptError as e:
print "===========ERROR==========\n " + str(e) + USAGE
sys.exit(2)
try:
for opt, arg in opts:
if opt == '-h':
print USAGE
sys.exit()
elif opt in ("-i", "--ifile"):
INPUT_FILE_FASTA = str(arg).strip()
elif opt in ("-p", "--iprocess"):
processType = str(arg).strip()
if processType in ["hmmscan", "rpsblast"]:
PROCESS_TYPE = processType
else:
raise Exception("-p || --iprocess argument should be 'hmmscan' or 'rpsblast'")
elif opt in ("-u", "--cpu"):
CPU = str(arg).strip()
elif opt in ("-r", "--ofourth"):
OUTPUT_RPSBLAST_OR_HMMSCAN = str(arg).strip()
elif opt in ("-f", "--ofifth"):
OUTPUT_RPSBPROC = str(arg).strip()
elif opt in ("-x", "--osixth"):
OUTPUT_TMHMMSCAN = str(arg).strip()
elif opt in ("-a", "--oseventh"):
OUTPUT_SEGMASKER = str(arg).strip()
elif opt in ("-A", "--hmmscanDbPath"):
HMMSCAN_DB_PATH = str(arg).strip()
elif opt in ("-B", "--rpsblastDbPath"):
RPSBLAST_DB_PATH = str(arg).strip()
elif opt in ("-C", "--rpsprocDbPath"):
RPSBPROC_DB_PATH = str(arg).strip()
elif opt in ("-D", "--dbname"):
DB_NAME = str(arg).strip()
elif opt in ("-H", "--hmmscanPath"):
HMMSCAN_PROGRAM = str(arg).strip()
elif opt in ("-R", "--rpsblastPath"):
RPSBLAST_PROGRAM = str(arg).strip()
elif opt in ("-P", "--rpsbprocPath"):
RPSBPROC_PROGRAM = str(arg).strip()
elif opt in ("-T", "--tmhmm2Path"):
TMHMMSCAN_PROGRAM = str(arg).strip()
elif opt in ("-S", "--segmaskerPath"):
SEGMASKER_PROGRAM = str(arg).strip()
elif opt in ("-E", "--runSegmasker"):
if str(arg).strip() == "true":
RUN_SEGMASKER = True
elif opt in ("-e", "--evalue"):
EVAL_THRESHOLD = float(arg)
elif opt in ("-y", "--probability"):
HMMSCAN_PROBABILITY = float(arg)
elif opt in ("-t", "--tabformat"):
if str(arg) in ["no", "n"]:
GET_TAB = False
elif str(arg) in ["yes", "y"]:
GET_TAB = True
else:
raise Exception("-t || --tabformat argument should be 'yes||y' or 'no||n'")
elif opt in ("-j", "--jsonformat"):
if str(arg) in ["no", "n"]:
GET_JSON = False
elif str(arg) in ["yes", "y"]:
GET_JSON = True
else:
raise Exception("-j || --jsonformat argument should be 'yes||y' or 'no||n'")
elif opt in ("-o", "--ofile"):
PROTEIN_TO_DOMAININFO_FILE = str(arg).strip()
elif opt in ("-n", "--osecond"):
DOMAIN_ARCHITECT_TO_COUNT_FILE = str(arg).strip()
elif opt in ("-b", "--othird"):
PROTEIN_TO_DOMAININFO_JSONFILE = str(arg).strip()
elif opt in ("-m", "--sites"):
PROTEIN_SITES_INCLUDE = True
if PROCESS_TYPE == None:
raise Exception("-p || --iprocess is a mandatory parameter")
if PROCESS_TYPE == RPSBLAST:
if OUTPUT_RPSBLAST_OR_HMMSCAN == None or OUTPUT_RPSBPROC == None:
raise Exception("-r and -f (||--ofourth and --ofifth) are both mandatory parameters if -p(||--iprocess) is 'rpsblast'")
except Exception as e:
print "===========ERROR==========\n " + str(e) + USAGE
sys.exit(2)
class Protein(object):
def __init__(self, length = None):
self.domains = []
self.tmInfo = dict()
self.lowComplexity = []
self.sites = []
self.length = length
self.sequence = ""
def setRpsRegion(self, regionData, regionType):
if regionType == DOMAIN:
region = RpsDomainRegion()
region.domainName = regionData[9]
region.aliStart = int(regionData[4])
region.aliEnd = int(regionData[5])
region.source = regionData[8]
region.predictor = "RpsBlast"
#Need to change
region.dbName = None
region.eValue = float(regionData[6])
region.bitscore = float(regionData[7])
region.superfamily_pssmId = regionData[11]
domainEnds = regionData[10]
if domainEnds == "-":
region.alignmentToModelType = "[]"
elif domainEnds == "N":
region.alignmentToModelType = ".]"
elif domainEnds == "C":
region.alignmentToModelType = "[."
elif domainEnds == "NC":
region.alignmentToModelType = ".."
self.domains.append(region)
elif regionType == PROTEIN_SITE:
region = RpsSiteRegion()
region.name = regionData[3]
region.sitePositions.append(regionData[4].split(","))
region.complete_size = regionData[5]
region.mapped_size = regionData[6]
region.source_domain_pssmId = regionData[7]
self.sites.append(region)
def setHmmscanRegion(self, regionData, domain, description, regionType):
if regionType == DOMAIN:
region = HmmscanDomainRegion()
alignmentToModelType = regionData[8]
modelStart = int(regionData[6])
modelEnd = int(regionData[7])
modelLen = modelEnd - modelStart + 1
region.modelStart = modelStart
region.modelEnd = modelEnd
region.aliStart = int(regionData[9])
region.aliEnd = int(regionData[10])
region.ceValue = float(regionData[4])
region.ieValue = float(regionData[5])
region.probability = float(regionData[2])
region.modelLength = modelLen
region.envStart = int(regionData[12])
region.envEnd = int(regionData[13])
region.predictor = "Hmmer"
region.dbName = "pfamA"
region.description = description
region.domainName = domain
region.alignmentToModelType = alignmentToModelType
self.domains.append(region)
def setTmInfo(self, first60=None, possibSigPep=None, tm=None, tmTopology=None):
self.tmInfo["first60"] = first60
self.tmInfo["possibSigPep"] = possibSigPep
self.tmInfo["tmTopology"] = tmTopology
self.tmInfo["tm"] = tm
self.tmInfo["tmRegions"] = []
def setTmRegions(self, tmStart, tmEnd):
self.tmInfo["tmRegions"].append(TmRegion(tmStart, tmEnd))
def setLowComplexityRegions(self, lowCompStart, lowCompEnd):
self.lowComplexity.append(LowComplexityRegion(lowCompStart, lowCompEnd))
def setSequence(sequence):
self.sequence = sequence
class HmmscanDomainRegion(object):
def __init__(self):
self.domainName = None
self.modelStart = None
self.modelEnd = None
self.aliStart = None
self.aliEnd = None
self.envStart = None
self.envEnd = None
self.colour = None
self.alignmentToModelType = None
self.display = None
self.description = None
self.modelLength = None
self.predictor = None
self.dbName = None
self.ceValue = None
self.ieValue = None
self.probability = None
class RpsSiteRegion(object):
def __init__(self):
self.name = None
self.complete_size = None
self.mapped_size = None
self.source_domain_pssmId = None
self.sitePositions = []
class RpsDomainRegion(object):
def __init__(self):
self.domainName = None
self.aliStart = None
self.aliEnd = None
self.colour = None
self.alignmentToModelType = None
self.display = None
self.description = None
self.source = None
self.predictor = None
self.dbName = None
self.eValue = None
self.bitscore = None
self.superfamily_pssmId = None
class TmRegion(object):
def __init__(self, tmStart, tmEnd):
self.start = tmStart
self.end = tmEnd
class LowComplexityRegion(object):
def __init__(self, lowCompSart, lowCompEnd):
self.start = lowCompSart
self.end = lowCompEnd
def processHmmscan():
domainListBegan = False
hitFound = False
currentQuery = None
proteinObject = None
proteinName = None
regex = re.compile(r"\s")
try:
with open(OUTPUT_RPSBLAST_OR_HMMSCAN, "r") as hmmscanFile:
for record in hmmscanFile:
#Will work only if words in protein names do not have spaces
if proteinObject and not len(proteinObject.sequence) and currentQuery:
proteinObject.sequence = PROTEINS_TO_SEQUENCES[currentQuery]
record = record.strip()
recSplitted = record.split(":")
if recSplitted[0] == "Query":
proteinAndLengthList = recSplitted[1].rpartition("[")
#If record is UniprotKb; need to investigate this
if "|" in recSplitted[1]:
if recSplitted[1][:2] == 'tr':
currentQuery = proteinAndLengthList[0].split("|")[2].strip()
else:
currentQuery = proteinAndLengthList[0].split("|")[3].strip()
else:
currentQuery = proteinAndLengthList[0].strip()
proteinlen = proteinAndLengthList[2].strip().rstrip("]")
PROT_NAME_TO_LENGTH[currentQuery] = proteinlen
if GET_JSON:
proteinObject = Protein(proteinlen.split("=")[1])
PROTREF_TO_DOMAINS[currentQuery] = proteinObject
elif recSplitted[0] == "Description":
record = record.replace("Description: ", "")
# If query should be joined in one string
if JOIN_STRING:
currentQueryOld = currentQuery
currentQuery = currentQuery + "_" + record.replace(" ", "_").strip()
else:
currentQueryOld = currentQuery
currentQuery = currentQuery + " " + record.strip()
PROT_NAME_TO_LENGTH[currentQuery] = PROT_NAME_TO_LENGTH[currentQueryOld]
del PROT_NAME_TO_LENGTH[currentQueryOld]
if GET_JSON:
PROTREF_TO_DOMAINS[currentQuery] = proteinObject
del PROTREF_TO_DOMAINS[currentQueryOld]
elif record[:2] == ">>":
hitFound = True
domain = record.split(" ")[1] #identifier and text
domainDescription = " ".join(record.split(" ")[2:]).strip() #description
elif hitFound and record[:3] == "---":
domainListBegan = True
elif len(record) > 0 and "#" not in record and record[0] != "[":
if hitFound and domainListBegan and record != 'Alignments for each domain:' and record != "Internal pipeline statistics summary:":
recordListWithoutSpaces = [elem for elem in record.split(" ") if len(elem) > 0]
if float(recordListWithoutSpaces[5]) < EVAL_THRESHOLD and float(recordListWithoutSpaces[2]) >= HMMSCAN_PROBABILITY:
envStart = int(recordListWithoutSpaces[12])
envEnd = int(recordListWithoutSpaces[13])
if GET_JSON:
proteinObject.setHmmscanRegion(recordListWithoutSpaces, domain, domainDescription, DOMAIN)
PROTREF_TO_DOMAIN_INFO[currentQuery].append([domain, envStart, envEnd])
if record == "Alignments for each domain:" or record == "Internal pipeline statistics summary:":
hitFound = False
domainListBegan = False
except Exception, e:
print "Problem happened: ", traceback.print_exc()
print "record", record
finally:
hmmscanFile.close()
def processRpsbproc():
domainListBegan = False
siteListBegan = False
proteinObject = None
with open(OUTPUT_RPSBPROC, "r") as rpsbprocFile:
for record in rpsbprocFile:
if proteinObject and not len(proteinObject.sequence) and query:
proteinObject.sequence = PROTEINS_TO_SEQUENCES[query]
recordList = record.strip().split("\t")
if recordList[0] == "QUERY":
proteinLength = recordList[3]
query = recordList[4]
if JOIN_STRING:
query = recordList[4].replace(" ", "_")
if GET_TAB:
PROT_NAME_TO_LENGTH[query] = proteinLength
if GET_JSON:
proteinObject = Protein(proteinLength)
PROTREF_TO_DOMAINS[query] = proteinObject
elif recordList[0] == "DOMAINS":
domainListBegan = True
elif recordList[0] != "ENDDOMAINS" and domainListBegan:
if float(recordList[6]) < EVAL_THRESHOLD:
if GET_TAB:
domainName = recordList[9]
start = recordList[4]
end = recordList[5]
PROTREF_TO_DOMAIN_INFO[query].append([domainName, start, end])
if GET_JSON:
proteinObject.setRpsRegion(recordList, DOMAIN)
elif recordList[0] == "ENDDOMAINS":
domainListBegan = False
elif PROTEIN_SITES_INCLUDE and recordList[0] == "SITES":
siteListBegan = True
elif PROTEIN_SITES_INCLUDE and recordList[0] != "ENDSITES" and siteListBegan:
if GET_TAB:
siteName = recordList[3]
sites = recordList[4]
completeSize = recordList[5]
mappedSize = recordList[6]
sorceDomainPssmId = recordList[7]
PROTEIN_TO_SITES[query].append([siteName, sites, completeSize, mappedSize, sorceDomainPssmId])
if GET_JSON:
proteinObject.setRpsRegion(recordList, PROTEIN_SITE)
elif PROTEIN_SITES_INCLUDE and recordList[0] == "ENDSITES":
siteListBegan = False
def processTmscan():
with open(OUTPUT_TMHMMSCAN, "r") as tmmscanFile:
for line in tmmscanFile:
possibSigPep = "no"
tm = "no"
tmTopology = None
topologyCoords = None
line = line.strip().split("\t")
if JOIN_STRING:
query = line[0].replace(" ", "_")
proteinLen = line[1].split("=")[1]
numberOfHelices = float(line[4].split("=")[1])
first60AA = line[3].split("=")
first60 = first60AA[1]
if float(first60AA[1]) > 10:
possibSigPep = "yes"
if numberOfHelices > 0:
tm = "yes"
tmTopology = line[5].split("=")[1].replace("o", "i").strip("i")
topologyCoords = tmTopology.split("i")
#set Tm info on the existing protein object
PROTREF_TO_DOMAINS[query].setTmInfo(first60, possibSigPep, tm, tmTopology)
for coordPair in topologyCoords:
PROTREF_TO_DOMAINS[query].setTmRegions(coordPair.split("-")[0], coordPair.split("-")[1])
def processSegmasker():
with open(OUTPUT_SEGMASKER, "r") as segmaskerFile:
currentProtein = None
for record in segmaskerFile:
recordSplitted = record.strip().split(">")
if len(recordSplitted) > 1:
currentProtein = recordSplitted[1]
elif len(recordSplitted) == 1:
coords = record.strip().split(" - ")
PROTREF_TO_DOMAINS[currentProtein].setLowComplexityRegions(int(coords[0]) + 1, int(coords[1]) + 1)
def formatSequence(sequence):
stringWithSpaceChars = ""
piece = int(math.floor(len(sequence)/SEQUENCE_LINE_LEN))
for ind in xrange(piece):
stringWithSpaceChars = stringWithSpaceChars + " " + sequence[ind*SEQUENCE_LINE_LEN:(ind+1)*SEQUENCE_LINE_LEN]
return (stringWithSpaceChars + " " + sequence[(ind+1)*SEQUENCE_LINE_LEN:]).strip()
def addFastaToDict():
with open(INPUT_FILE_FASTA, "r") as seqs:
for sequence in SeqIO.parse(seqs, "fasta"):
PROTEINS_TO_SEQUENCES[sequence.description.strip()] = formatSequence(str(sequence.seq))
def main(argv):
initialyze(argv)
addFastaToDict()
if PROCESS_TYPE == HMMSCAN:
hmmscan()
processHmmscan()
elif PROCESS_TYPE == RPSBLAST:
rpsBlast()
processRpsbproc()
tmhmm2scan()
processTmscan()
if RUN_SEGMASKER:
segMasker()
processSegmasker()
if GET_TAB:
with open(PROTEIN_TO_DOMAININFO_FILE, "w") as proteinToDomainFile:
for proteint in PROT_NAME_TO_LENGTH:
domainArchitecture = getDomainArchitecture(proteint, PROTREF_TO_DOMAIN_INFO)
readyList = getListOfDomains(proteint, PROTREF_TO_DOMAIN_INFO)
protLen = PROT_NAME_TO_LENGTH[proteint]
proteinToDomainFile.write("\t".join([proteint, domainArchitecture, protLen, ";".join(readyList)]) + "\n")
with open(DOMAIN_ARCHITECT_TO_COUNT_FILE, "w") as domainArchToCountFile:
domainToCountList = sorted(DOMAIN_ARCHITECT_TO_COUNT_DICT.items(), key=lambda a: a[1], reverse=True)
for domainArchitect in domainToCountList:
domainArchToCountFile.write(domainArchitect[0] + "\t" + str(domainArchitect[1]) + "\n")
with open(PROTEIN_TO_SITES_FILE, "w") as proteinToSitesFile:
for protein in PROTEIN_TO_SITES:
for site in PROTEIN_TO_SITES[protein]:
proteinToSitesFile.write(protein + "\t" + "\t".join(site) + "\n")
if GET_JSON:
with open(PROTEIN_TO_DOMAININFO_JSONFILE, "w") as proteinToDomainJson:
json.dump(PROTREF_TO_DOMAINS, proteinToDomainJson,
default=lambda o: o.__dict__,
sort_keys=True, indent=4)
def getSortedListOfDomains(proteint, protRefToDomainInfo):
return sorted(protRefToDomainInfo[proteint], key=lambda a: a[1])
def getListOfDomains(proteint, protRefToDomainInfo):
sortedListOfDomains = getSortedListOfDomains(proteint, protRefToDomainInfo)
readyList = [sublst[0] + ':' + str(sublst[1]) + '-' + str(sublst[2]) for sublst in sortedListOfDomains]
return readyList
#prepare proteins and their domains information for writing to the file
def getDomainArchitecture(proteint, protRefToDomainInfo):
sortedListOfDomains = getSortedListOfDomains(proteint, protRefToDomainInfo)
domainArchitecture = "-".join([sublst[0] for sublst in sortedListOfDomains])
DOMAIN_ARCHITECT_TO_COUNT_DICT[domainArchitecture]+=1
return domainArchitecture
def hmmscan():
#if hmmscan is in the linux path, this will be resloved
hmmscan = "hmmscan"
#If hmmscan is not in the linux path then give it the program full path as a parameter. The same for 'rpsblast', 'rpsbproc' and 'tmhmm' programs
if HMMSCAN_PROGRAM != None:
hmmscan = HMMSCAN_PROGRAM
runSubProcess(" ".join([hmmscan, "--noali", "--cpu", str(CPU), HMMSCAN_DB_PATH+DB_NAME, INPUT_FILE_FASTA, ">", OUTPUT_RPSBLAST_OR_HMMSCAN]))
def rpsBlast():
rpsblast = "rpsblast"
rpsbproc = "rpsbproc"
if RPSBLAST_PROGRAM != None:
rpsblast = RPSBLAST_PROGRAM
if RPSBPROC_PROGRAM != None:
rpsbproc = RPSBPROC_PROGRAM
runSubProcess(" ".join([rpsblast, "-num_threads", CPU, "-evalue", "0.01", "-seg", "no", "-outfmt", "5", "-db", RPSBLAST_DB_PATH+DB_NAME, "-query", INPUT_FILE_FASTA, "-out", OUTPUT_RPSBLAST_OR_HMMSCAN]))
runSubProcess(" ".join([rpsbproc, "-d", RPSBPROC_DB_PATH, "-i", OUTPUT_RPSBLAST_OR_HMMSCAN, "-o", OUTPUT_RPSBPROC]))
def tmhmm2scan():
tmhmm = "/home/vadim/Softs/tmhmm-2.0c/bin/tmhmm"
if TMHMMSCAN_PROGRAM != None:
tmhmm = TMHMMSCAN_PROGRAM
runSubProcess(" ".join([tmhmm, "--short", INPUT_FILE_FASTA, ">", OUTPUT_TMHMMSCAN]))
def segMasker():
segmasker = "segmasker"
if SEGMASKER_PROGRAM != None:
segmasker = SEGMASKER_PROGRAM
runSubProcess(" ".join([segmasker, "-infmt", "fasta", "-outfmt", "interval", "-in", INPUT_FILE_FASTA, "-out", OUTPUT_SEGMASKER]))
def runSubProcess(command):
try:
call(command, shell=True)
except OSError, osError:
print "osError " + osError
print traceback.print_exc()
if __name__ == "__main__":
main(sys.argv)
| 38.633157 | 236 | 0.699795 |
40242de03e1f2ff3a2b7ea61853b2eb8e39ac2a7 | 16,206 | py | Python | assets/html_data.py | luzpaz/KiCad-Diff | 4552c1776a7242b72b70776a1a40ecc11ad618e1 | [
"MIT"
] | 182 | 2017-08-17T01:56:41.000Z | 2022-03-27T20:05:53.000Z | assets/html_data.py | luzpaz/KiCad-Diff | 4552c1776a7242b72b70776a1a40ecc11ad618e1 | [
"MIT"
] | 76 | 2018-10-03T17:32:38.000Z | 2022-03-25T23:05:10.000Z | assets/html_data.py | luzpaz/KiCad-Diff | 4552c1776a7242b72b70776a1a40ecc11ad618e1 | [
"MIT"
] | 37 | 2018-03-24T01:27:41.000Z | 2022-03-17T22:51:41.000Z | # HTML Data
# Intermediate approach before something better
indexHead = """
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="http://127.0.0.1:9092/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<title>{board_title}</title>
</head>
<div class="responsivefull">
<table style="border-color: #555555; width: 100%; height: 2px;" border="2px" cellspacing="2px" cellpadding="3px">
<tbody>
<tr>
<td colspan="3" rowspan="3" width="45%">
<div class="title"> {board_title} </div>
<div class="details"> Company: {board_company} </div>
</td>
<td width="25%">
<div class="versions">Thickness (mm)</div>
</td>
<td width="15%">
<div class="versions green">{thickness1}</div>
</td>
<td width="15%">
<div class="versions red">{thickness2}</div>
</td>
</tr>
<td width="25%">
<div class="versions">Modules</div>
</td>
<td width="15%">
<div class="versions green">{modules1}</div>
</td>
<td width="15%">
<div class="versions red">{modules2}</div>
</td>
<tr>
<td width="25%">
<div class="versions">Drawings</div>
</td>
<td width="15%">
<div class="versions green">{drawings1}</div>
</td>
<td width="15%">
<div class="versions red">{drawings2}</div>
</td>
</tr>
<tr>
<td width="15%">
<div class="versions">Version</div>
</td>
<td width="15%">
<div class="versions green">{hash1}</div>
</td>
<td width="15%">
<div class="versions red">{hash2}</div>
</td>
<td width="25%">
<div class="versions">Nets</div>
</td>
<td width="15%">
<div class="versions green">{nets1}</div>
</td>
<td width="15%">
<div class="versions red">{nets2}</div>
</td>
</tr>
<tr>
<td width="15%">
<div class="versions">Date</div>
</td>
<td width="15%">
<div class="versions green">{date1}</div>
</td>
<td width="15%">
<div class="versions red">{date2}</div>
</td>
<td width="25%">
<div class="versions">Tracks</div>
</td>
<td width="15%">
<div class="versions green">{tracks1}</div>
</td>
<td width="15%">
<div class="versions red">{tracks2}</div>
</td>
</tr>
<tr>
<td width="15%">
<div class="versions">Time</div>
</td>
<td width="15%">
<div class="versions green">{time1}</div>
</td>
<td width="15%">
<div class="versions red">{time2}</div>
</td>
<td width="25%">
<div class="versions">Zones</div>
</td>
<td width="15%">
<div class="versions green">{zones1}</div>
</td>
<td width="15%">
<div class="versions red">{zones2}</div>
</td>
</tr>
</tbody>
</table>
</div>
"""
outfile = """
<div class="responsive">
<div class="gallery">
<a target="_blank" href="../{hash1}/{filename_svg}">
<a href="./triptych/{triptych_html}">
<img class="{layer_class}" src="../{hash1}/{filename_svg}" height="200">
</a>
</a>
<div class="desc">{index} - {layer_name}</div>
</div>
</div>
"""
triptychHTML = """
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="http://127.0.0.1:9092/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="../favicon.ico" type="image/x-icon" />
<script integrity="" src="https://code.jquery.com/jquery-3.5.0.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<script integrity="" src="https://code.iconify.design/1/1.0.7/iconify.min.js"></script>
<link rel="stylesheet" type="text/css" href="../style.css" media="screen" />
<title>{board_title} - {layer_name}</title>
<style>
div.responsive {{
padding: 0 6px;
float: left;
width: 49.99%;
}}
</style>
<script src="https://cdn.jsdelivr.net/npm/svg-pan-zoom@3.6.1/dist/svg-pan-zoom.min.js"></script>
<script type="text/javascript">
var keysDown = {{}};
window.onkeydown = function(e) {{
keysDown[e.key] = true;
if (keysDown.ArrowLeft) {{
keysDown = {{}};
document.location.href = "{previous_page}";
}};
if (keysDown.ArrowRight) {{
keysDown = {{}};
document.location.href = "{next_page}";
}};
if (keysDown.h || keysDown.H || e.which === 32) {{
keysDown = {{}};
document.location.href = "../../../{homebase}";
}};
}}
</script>
</head>
<body>
<div id="compo-container" style="width: 100%; height: 600px; position: relative;">
<div style="position: absolute; width: 100%; height: inherit;">
<svg id="svg-compo-diff" xmlns="http://www.w3.org/2000/svg" style="display: inline; width: inherit; min-width: inherit; max-width: inherit; height: inherit; min-height: inherit; max-height: inherit;" version="1.1">
<g>
<svg id="compo1">
<defs>
<filter id="f1">
<feColorMatrix id="c1" type="matrix"
values="1 0 0 0 0
0 1 0 1 0
0 0 1 1 0
0 0 0 1 0" />
</filter>
</defs>
<image x="0" y="0" height="100%" width="100%" filter="url(#f1)" xlink:href="../../{hash1}/{filename_svg}" />
</svg>
<svg id="compo2">
<defs>
<filter id="f2">
<feColorMatrix id="c2" type="matrix"
values="1 0 0 1 0
0 1 0 0 0
0 0 1 0 0
0 0 0 .5 0" />
</filter>
</defs>
<image x="0" y="0" height="100%" width="100%" filter="url(#f2)" xlink:href="../../{hash2}/{filename_svg}" />
</svg>
</g>
</svg>
</div>
<div style="background: rgba(255, 0, 0, 0.0); z-index: 10; position: absolute; margin-top: 10px">
<span class="title">{board_title}</span><br>
<span class="subtitle">{index}. {layer_name}</span>
</div>
<div class="diff-controls" style="background: rgba(255, 0, 0, 0.0); z-index: 10; position: absolute; top:10px; right: 0px; padding-right: 10px">
<button class="btn btn-dark" id="diff-zoom-in">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="akar-icons:zoom-in" data-inline="false"></span>
</button>
<button class="btn btn-dark" id="diff-zoom-out">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="akar-icons:zoom-out" data-inline="false"></span>
</button>
<button class="btn btn-dark" id="diff-reset">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="carbon:center-to-fit" data-inline="false"></span>
</button>
</div>
</div>
<div id="sbs-container" style="position:relative; width: 100%; background-color: #222; text-align: center; display: flex;">
<div id="image1-container" style="border: 1px solid #555; width: 50%; height: 250px">
<div style="background: rgba(255, 0, 0, 0.0); z-index: 10; position: absolute; padding-left: 10px" class="subtitle">{hash1}</div>
<div style="width: 100%; height: 250px">
<svg id="svg-img1-id" xmlns="http://www.w3.org/2000/svg"
style="display: inline; width: 100%; min-width: 100%; max-width: 100%; height: 100%; min-height: 100%; max-height: 100%;"
version="1.1" class="{layer_class}">
<svg id="image_1">
<image x="0" y="0" height="100%" width="100%" xlink:href="../../{hash1}/{filename_svg}"/>
</svg>
</svg>
<div class="hash1-controls" style="background: rgba(255, 0, 0, 0.0); z-index: 10; position: absolute; top:10px; right: 50%; padding-right: 10px">
<button class="btn btn-dark" id="hash1-zoom-in">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="akar-icons:zoom-in" data-inline="false"></span>
</button>
<button class="btn btn-dark" id="hash1-zoom-out">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="akar-icons:zoom-out" data-inline="false"></span>
</button>
<button class="btn btn-dark" id="hash1-reset">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="carbon:center-to-fit" data-inline="false"></span>
</button>
</div>
</div>
</div>
<div id="image2-container" style="border: 1px solid #555; width: 50%; height: 250px">
<div style="background: rgba(255, 0, 0, 0.0); z-index: 10; position: absolute; padding-left: 10px" class="subtitle">{hash2}</div>
<div style="width: 100%; height: 250px">
<svg id="svg-img2-id" xmlns="http://www.w3.org/2000/svg" style="display: inline; width: 100%; min-width: 100%; max-width: 100%;
height: 100%; min-height: 100%; max-height: 100%;"
version="1.1" class="{layer_class}">
<svg id="image_2">
<image x="0" y="0" height="100%" width="100%" xlink:href="../../{hash2}/{filename_svg}"/>
</svg>
</svg>
</div>
<div class="hash2-controls" style="background: rgba(255, 0, 0, 0.0); z-index: 10; position: absolute; top:10px; right: 0px; padding-right: 10px">
<button class="btn btn-dark" id="hash2-zoom-in">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="akar-icons:zoom-in" data-inline="false"></span>
</button>
<button class="btn btn-dark" id="hash2-zoom-out">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="akar-icons:zoom-out" data-inline="false"></span>
</button>
<button class="btn btn-dark" id="hash2-reset">
<span class="iconify" style="width: 20px; height: 20px;" data-icon="carbon:center-to-fit" data-inline="false"></span>
</button>
</div>
</div>
</div>
"""
twopane = """
<script>
var pan_zoom_diff;
var pan_zoom_hash1;
var pan_zoom_hash2;
window.onload = function() {
pan_zoom_diff = svgPanZoom(
'#svg-compo-diff', {
zoomEnabled: true,
center: true,
minZoom: 1.0,
maxZoom: 20,
controlIconsEnabled: false,
zoomScaleSensitivity: 0.1,
fit: false
}
);
document.getElementById('diff-zoom-in').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_diff.zoomIn();
console.log("diff-zoom-in");
}
);
document.getElementById('diff-zoom-out').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_diff.zoomOut();
console.log("diff-zoom-out");
}
);
document.getElementById('diff-reset').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_diff.resetZoom();
console.log("diff-zoom-reset");
}
);
/***************************************************/
pan_zoom_hash1 = svgPanZoom(
'#image_1', {
zoomEnabled: true,
center: true,
minZoom: 1.0,
maxZoom: 20,
controlIconsEnabled: false,
zoomScaleSensitivity: 0.1,
fit: false
}
);
document.getElementById('hash1-zoom-in').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_hash1.zoomIn();
console.log("hash1-zoom-in");
}
);
document.getElementById('hash1-zoom-out').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_hash1.zoomOut();
console.log("hash1-zoom-out");
}
);
document.getElementById('hash1-reset').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_hash1.resetZoom();
console.log("hash1-zoom-reset");
}
);
/***************************************************/
pan_zoom_hash2 = svgPanZoom(
'#image_2', {
zoomEnabled: true,
center: true,
minZoom: 1.0,
maxZoom: 20,
controlIconsEnabled: false,
zoomScaleSensitivity: 0.1,
fit: false
}
);
document.getElementById('hash2-zoom-in').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_hash2.zoomIn();
console.log("hash2-zoom-in");
}
);
document.getElementById('hash2-zoom-out').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_hash2.zoomOut();
console.log("hash2-zoom-out");
}
);
document.getElementById('hash2-reset').addEventListener(
'click', function(ev) {
ev.preventDefault();
pan_zoom_hash2.resetZoom();
console.log("hash2-zoom-reset");
}
);
/***************************************************/
};
</script>
</body>
</html>
"""
tail = """
<div class="clearfix"></div>
<div style="padding:6px;"></div>
"""
| 39.334951 | 226 | 0.451499 |
3342d2471229a6b44e0b675ec2f9d024547041ec | 86,911 | py | Python | pynetdicom3/dimse_primitives.py | sisobus/pynetdicom3 | c9d3d1b52f17a107566f31e63e0e4d0e8aaacbab | [
"MIT"
] | 2 | 2019-02-07T08:02:30.000Z | 2019-03-20T04:00:20.000Z | pynetdicom3/dimse_primitives.py | sisobus/pynetdicom3 | c9d3d1b52f17a107566f31e63e0e4d0e8aaacbab | [
"MIT"
] | null | null | null | pynetdicom3/dimse_primitives.py | sisobus/pynetdicom3 | c9d3d1b52f17a107566f31e63e0e4d0e8aaacbab | [
"MIT"
] | 1 | 2019-04-11T07:39:06.000Z | 2019-04-11T07:39:06.000Z | """
Define the DIMSE-C and DIMSE-N service parameter primitives.
Notes:
* The class member names must match their corresponding DICOM element keyword
in order for the DIMSE messages/primitives to be created correctly.
TODO: Implement properties for DIMSE-N parameters
TODO: Implement status related parameters for DIMSE-N classes
TODO: Add string output for the DIMSE-C classes
"""
import codecs
try:
from collections.abc import MutableSequence
except ImportError:
from collections import MutableSequence
from io import BytesIO
import logging
from pydicom.tag import Tag
from pydicom.uid import UID
from pynetdicom3.utils import validate_ae_title
LOGGER = logging.getLogger('pynetdicom3.dimse_primitives')
# pylint: disable=invalid-name
# pylint: disable=attribute-defined-outside-init
# pylint: disable=too-many-instance-attributes
class DIMSEPrimitive(object):
"""Base class for the DIMSE primitives."""
STATUS_OPTIONAL_KEYWORDS = ()
REQUEST_KEYWORDS = ()
RESPONSE_KEYWORDS = ('MessageIDBeingRespondedTo', 'Status')
@property
def AffectedSOPClassUID(self):
"""Return the *Affected SOP Class UID*."""
return self._affected_sop_class_uid
@AffectedSOPClassUID.setter
def AffectedSOPClassUID(self, value):
"""Set the *Affected SOP Class UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Class UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Class UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Class UID is an invalid UID")
raise ValueError("Affected SOP Class UID is an invalid UID")
self._affected_sop_class_uid = value
@property
def _dataset_variant(self):
"""Return the Dataset-like parameter value.
Used for EventInformation, EventReply, AttributeList,
ActionInformation, ActionReply, DataSet, Identifier and
ModificationList dataset-like parameter values.
Returns
-------
BytesIO or None
"""
return self._dataset
@_dataset_variant.setter
def _dataset_variant(self, value):
"""Set the Dataset-like parameter.
Used for EventInformation, EventReply, AttributeList,
ActionInformation, ActionReply, DataSet, Identifier and
ModificationList dataset-like parameter values.
Parameters
----------
value : tuple
The (dataset, variant name) to set, where dataset is either None
or BytesIO and variant name is str.
"""
if value[0] is None:
self._dataset = value[0]
elif isinstance(value[0], BytesIO):
self._dataset = value[0]
else:
raise TypeError(
"'{}' parameter must be a BytesIO object".format(value[1])
)
@property
def is_valid_request(self):
"""Return True if the request is valid, False otherwise."""
for keyword in self.REQUEST_KEYWORDS:
if getattr(self, keyword) is None:
return False
return True
@property
def is_valid_response(self):
"""Return True if the response is valid, False otherwise."""
for keyword in self.RESPONSE_KEYWORDS:
if getattr(self, keyword) is None:
return False
return True
@property
def MessageID(self):
"""Return the DIMSE *Message ID*."""
return self._message_id
@MessageID.setter
def MessageID(self, value):
"""Set the DIMSE *Message ID*."""
if isinstance(value, int):
if 0 <= value < 2**16:
self._message_id = value
else:
raise ValueError("Message ID must be between 0 and 65535, "
"inclusive")
elif value is None:
self._message_id = value
else:
raise TypeError("Message ID must be an int")
@property
def MessageIDBeingRespondedTo(self):
"""Return the *Message ID Being Responded To*."""
return self._message_id_being_responded_to
@MessageIDBeingRespondedTo.setter
def MessageIDBeingRespondedTo(self, value):
"""Set the *Message ID Being Responded To*."""
if isinstance(value, int):
if 0 <= value < 2**16:
self._message_id_being_responded_to = value
else:
raise ValueError("Message ID Being Responded To must be "
"between 0 and 65535, inclusive")
elif value is None:
self._message_id_being_responded_to = value
else:
raise TypeError("Message ID Being Responded To must be an int")
@property
def Status(self):
"""Return the *Status*."""
return self._status
@Status.setter
def Status(self, value):
"""Set the *Status*."""
if isinstance(value, int) or value is None:
self._status = value
else:
raise TypeError("DIMSE primitive's 'Status' must be an int")
# DIMSE-C Service Primitives
class C_STORE(DIMSEPrimitive):
"""Represents a C-STORE primitive.
+------------------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+==========================================+=========+==========+
| Message ID | M | U |
+------------------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+------------------------------------------+---------+----------+
| Affected SOP Class UID | M | U(=) |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | M | U(=) |
+------------------------------------------+---------+----------+
| Priority | M | \- |
+------------------------------------------+---------+----------+
| Move Originator Application Entity Title | U | \- |
+------------------------------------------+---------+----------+
| Move Originator Message ID | U | \- |
+------------------------------------------+---------+----------+
| Data Set | M | \- |
+------------------------------------------+---------+----------+
| Status | \- | M |
+------------------------------------------+---------+----------+
| Offending Element | \- | C |
+------------------------------------------+---------+----------+
| Error Comment | \- | C |
+------------------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
AffectedSOPInstanceUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Instance
for storage. If included in the response/confirmation, it shall be
equal to the value in the request/indication
Priority : int
The priority of the C-STORE operation. It shall be one of the
following:
* 0: Medium
* 1: High
* 2: Low (Default)
MoveOriginatorApplicationEntityTitle : bytes
The DICOM AE Title of the AE that invoked the C-MOVE operation
from which this C-STORE sub-operation is being performed
MoveOriginatorMessageID : int
The Message ID of the C-MOVE request/indication primitive from
which this C-STORE sub-operation is being performed
DataSet : io.BytesIO
The pydicom Dataset containing the Attributes of the Composite
SOP Instance to be stored, encoded as a BytesIO object
Status : int
The error or success notification of the operation.
OffendingElement : list of int or None
An optional status related field containing a list of the
elements in which an error was detected.
ErrorComment : str or None
An optional status related field containing a text description
of the error detected. 64 characters maximum.
"""
STATUS_OPTIONAL_KEYWORDS = ('OffendingElement', 'ErrorComment', )
REQUEST_KEYWORDS = (
'MessageID', 'AffectedSOPClassUID', 'AffectedSOPInstanceUID',
'Priority', 'DataSet'
)
def __init__(self):
# Variable names need to match the corresponding DICOM Element keywords
# in order for the DIMSE Message classes to be built correctly.
# Changes to the variable names can be made provided the DIMSEMessage()
# class' message_to_primitive() and primitive_to_message() methods
# are also changed
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.AffectedSOPClassUID = None
self.AffectedSOPInstanceUID = None
self.Priority = 0x02
self.MoveOriginatorApplicationEntityTitle = None
self.MoveOriginatorMessageID = None
self.DataSet = None
self.Status = None
# Optional Command Set elements used with specific Status values
# For Warning statuses 0xB000, 0xB006, 0xB007
# For Failure statuses 0xCxxx, 0xA9xx,
self.OffendingElement = None
# For Warning statuses 0xB000, 0xB006, 0xB007
# For Failure statuses 0xCxxx, 0xA9xx, 0xA7xx, 0x0122, 0x0124
self.ErrorComment = None
# For Failure statuses 0x0117
# self.AffectedSOPInstanceUID
@property
def AffectedSOPInstanceUID(self):
"""Return the *Affected SOP Instance UID*."""
return self._affected_sop_instance_uid
@AffectedSOPInstanceUID.setter
def AffectedSOPInstanceUID(self, value):
"""Set the *Affected SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Class UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Instance UID is an invalid UID")
raise ValueError("Affected SOP Instance UID is an invalid UID")
self._affected_sop_instance_uid = value
@property
def Priority(self):
"""Return the *Priority*."""
return self._priority
@Priority.setter
def Priority(self, value):
"""Set the *Priority*."""
if value in [0, 1, 2]:
self._priority = value
else:
LOGGER.warning("Attempted to set C-STORE Priority parameter to "
"an invalid value")
raise ValueError("C-STORE Priority must be 0, 1, or 2")
@property
def MoveOriginatorApplicationEntityTitle(self):
"""Return the *Move Originator Application Entity Title*."""
return self._move_originator_application_entity_title
@MoveOriginatorApplicationEntityTitle.setter
def MoveOriginatorApplicationEntityTitle(self, value):
"""Set the *Move Originator Application Entity Title*.
Parameters
----------
value : str or bytes
The Move Originator AE Title as a string or bytes object. Cannot be
an empty string and will be truncated to 16 characters long
"""
if isinstance(value, str):
value = codecs.encode(value, 'ascii')
if value is not None:
self._move_originator_application_entity_title = validate_ae_title(
value
)
else:
self._move_originator_application_entity_title = None
@property
def MoveOriginatorMessageID(self):
"""Return the *Move Originator Message ID*."""
return self._move_originator_message_id
@MoveOriginatorMessageID.setter
def MoveOriginatorMessageID(self, value):
"""Set the *Move Originator Message ID*."""
if isinstance(value, int):
if 0 <= value < 2**16:
self._move_originator_message_id = value
else:
raise ValueError("Move Originator Message ID To must be "
"between 0 and 65535, inclusive")
elif value is None:
self._move_originator_message_id = value
else:
raise TypeError("Move Originator Message ID To must be an int")
@property
def DataSet(self):
"""Return the *Data Set*."""
return self._dataset_variant
@DataSet.setter
def DataSet(self, value):
"""Set the *Data Set*."""
self._dataset_variant = (value, 'DataSet')
class C_FIND(DIMSEPrimitive):
"""Represents a C-FIND primitive.
+-------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+===============================+=========+==========+
| Message ID | M | U |
+-------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+-------------------------------+---------+----------+
| Affected SOP Class UID | M | U(=) |
+-------------------------------+---------+----------+
| Priority | M | \- |
+-------------------------------+---------+----------+
| Identifier | M | C |
+-------------------------------+---------+----------+
| Status | \- | M |
+-------------------------------+---------+----------+
| Offending Element | \- | C |
+-------------------------------+---------+----------+
| Error Comment | \- | C |
+-------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which
this response/confirmation applies.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class
for storage. If included in the response/confirmation, it shall be
equal to the value in the request/indication
Priority : int
The priority of the C-STORE operation. It shall be one of the
following:
* 0: Medium
* 1: High
* 2: Low (Default)
Identifier : io.BytesIO
A list of Attributes (in the form of an encoded pydicom
Dataset) to be matched against the values of the Attributes in the
instances of the composite objects known to the performing DIMSE
service-user.
Status : int
The error or success notification of the operation.
OffendingElement : list of int or None
An optional status related field containing a list of the
elements in which an error was detected.
ErrorComment : str or None
An optional status related field containing a text
description of the error detected. 64 characters maximum.
"""
STATUS_OPTIONAL_KEYWORDS = ('OffendingElement', 'ErrorComment', )
REQUEST_KEYWORDS = (
'MessageID', 'AffectedSOPClassUID', 'Priority', 'Identifier'
)
def __init__(self):
# Variable names need to match the corresponding DICOM Element keywords
# in order for the DIMSE Message classes to be built correctly.
# Changes to the variable names can be made provided the DIMSEMessage()
# class' message_to_primitive() and primitive_to_message() methods
# are also changed
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.AffectedSOPClassUID = None
self.Priority = 0x02
self.Identifier = None
self.Status = None
# Optional Command Set elements used in with specific Status values
# For Failure statuses 0xA900, 0xCxxx
self.OffendingElement = None
# For Failure statuses 0xA900, 0xA700, 0x0122, 0xCxxx
self.ErrorComment = None
@property
def Priority(self):
"""Return the *Priority*."""
return self._priority
@Priority.setter
def Priority(self, value):
"""Set the *Priority*."""
if value in [0, 1, 2]:
self._priority = value
else:
LOGGER.warning("Attempted to set C-FIND Priority parameter to an "
"invalid value")
raise ValueError("Priority must be 0, 1, or 2")
@property
def Identifier(self):
"""Return the *Identifier*."""
return self._dataset_variant
@Identifier.setter
def Identifier(self, value):
"""Set the *Identifier*."""
self._dataset_variant = (value, 'Identifier')
class C_GET(DIMSEPrimitive):
"""Represents a C-GET primitive.
+-------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+===============================+=========+==========+
| Message ID | M | U |
+-------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+-------------------------------+---------+----------+
| Affected SOP Class UID | M | U(=) |
+-------------------------------+---------+----------+
| Priority | M | \- |
+-------------------------------+---------+----------+
| Identifier | M | U |
+-------------------------------+---------+----------+
| Status | \- | M |
+-------------------------------+---------+----------+
| Number of Remaining Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Number of Completed Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Number of Failed Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Number of Warning Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Offending Element | \- | C |
+-------------------------------+---------+----------+
| Error Comment | \- | C |
+-------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which
this response/confirmation applies.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class
for storage. If included in the response/confirmation, it shall be
equal to the value in the request/indication
Priority : int
The priority of the C-STORE operation. It shall be one of the
following:
* 0: Medium
* 1: High
* 2: Low (Default)
Identifier : io.BytesIO
The pydicom Dataset containing the list of Attributes to be
matched against the values of Attributes of known composite SOP
Instances of the performing DIMSE service-user, encoded as a BytesIO
object. For the list of allowed Attributes and the rules defining their
usage see the section corresponding to the service class in the DICOM
Standard, Part 4.
Status : int
The error or success notification of the operation.
NumberOfRemainingSuboperations : int
The number of remaining C-STORE sub-operations to be invoked
by this C-GET operation. It may be included in any response and shall
be included if the status is Pending
NumberOfCompletedSuboperations : int
The number of C-STORE sub-operations that have completed
successfully. It may be included in any response and shall be included
if the status is Pending
NumberOfFailedSuboperations : int
The number of C-STORE sub-operations that have failed. It may
be included in any response and shall be included if the status is
Pending
NumberOfWarningSuboperations : int
The number of C-STORE operations that generated Warning
responses. It may be included in any response and shall be included if
the status is Pending
OffendingElement : list of int or None
An optional status related field containing a list of the
elements in which an error was detected.
ErrorComment : str or None
An optional status related field containing a text
description of the error detected. 64 characters maximum.
"""
STATUS_OPTIONAL_KEYWORDS = (
'ErrorComment', 'OffendingElement', 'NumberOfRemainingSuboperations',
'NumberOfCompletedSuboperations', 'NumberOfFailedSuboperations',
'NumberOfWarningSuboperations'
)
REQUEST_KEYWORDS = (
'MessageID', 'AffectedSOPClassUID', 'Priority', 'Identifier'
)
def __init__(self):
# Variable names need to match the corresponding DICOM Element keywords
# in order for the DIMSE Message classes to be built correctly.
# Changes to the variable names can be made provided the DIMSEMessage()
# class' message_to_primitive() and primitive_to_message() methods
# are also changed
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.AffectedSOPClassUID = None
self.Priority = 0x02
self.Identifier = None
self.Status = None
self.NumberOfRemainingSuboperations = None
self.NumberOfCompletedSuboperations = None
self.NumberOfFailedSuboperations = None
self.NumberOfWarningSuboperations = None
# For Failure statuses 0xA701, 0xA900
self.ErrorComment = None
self.OffendingElement = None
# For 0xA702, 0xFE00, 0xB000, 0x0000
# self.NumberOfRemainingSuboperations
# self.NumberOfCompletedSuboperations
# self.NumberOfFailedSuboperations
# self.NumberOfWarningSuboperations
@property
def Priority(self):
"""Return the *Priority*."""
return self._priority
@Priority.setter
def Priority(self, value):
"""Set the *Priority*."""
if value in [0, 1, 2]:
self._priority = value
else:
LOGGER.warning("Attempted to set C-FIND Priority parameter to an "
"invalid value")
raise ValueError("Priority must be 0, 1, or 2")
@property
def Identifier(self):
"""Return the *Identifier*."""
return self._dataset_variant
@Identifier.setter
def Identifier(self, value):
"""Set the *Identifier*."""
self._dataset_variant = (value, 'Identifier')
@property
def NumberOfRemainingSuboperations(self):
"""Return the *Number of Remaining Suboperations*."""
return self._number_of_remaining_suboperations
@NumberOfRemainingSuboperations.setter
def NumberOfRemainingSuboperations(self, value):
"""Set the *Number of Remaining Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_remaining_suboperations = value
else:
raise ValueError("Number of Remaining Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_remaining_suboperations = value
else:
raise TypeError("Number of Remaining Suboperations must be an int")
@property
def NumberOfCompletedSuboperations(self):
"""Return the *Number of Completed Suboperations*."""
return self._number_of_completed_suboperations
@NumberOfCompletedSuboperations.setter
def NumberOfCompletedSuboperations(self, value):
"""Set the *Number of Completed Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_completed_suboperations = value
else:
raise ValueError("Number of Completed Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_completed_suboperations = value
else:
raise TypeError("Number of Completed Suboperations must be an int")
@property
def NumberOfFailedSuboperations(self):
"""Return the *Number of Failed Suboperations*."""
return self._number_of_failed_suboperations
@NumberOfFailedSuboperations.setter
def NumberOfFailedSuboperations(self, value):
"""Set the *Number of Failed Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_failed_suboperations = value
else:
raise ValueError("Number of Failed Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_failed_suboperations = value
else:
raise TypeError("Number of Failed Suboperations must be an int")
@property
def NumberOfWarningSuboperations(self):
"""Return the *Number of Warning Suboperations*."""
return self._number_of_warning_suboperations
@NumberOfWarningSuboperations.setter
def NumberOfWarningSuboperations(self, value):
"""Set the *Number of Warning Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_warning_suboperations = value
else:
raise ValueError("Number of Warning Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_warning_suboperations = value
else:
raise TypeError("Number of Warning Suboperations must be an int")
class C_MOVE(DIMSEPrimitive):
"""Represents a C-MOVE primitive.
+-------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+===============================+=========+==========+
| Message ID | M | U |
+-------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+-------------------------------+---------+----------+
| Affected SOP Class UID | M | U(=) |
+-------------------------------+---------+----------+
| Priority | M | \- |
+-------------------------------+---------+----------+
| Move Destination | M | \- |
+-------------------------------+---------+----------+
| Identifier | M | U |
+-------------------------------+---------+----------+
| Status | \- | M |
+-------------------------------+---------+----------+
| Number of Remaining Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Number of Completed Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Number of Failed Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Number of Warning Sub-ops | \- | C |
+-------------------------------+---------+----------+
| Offending Element | \- | C |
+-------------------------------+---------+----------+
| Error Comment | \- | C |
+-------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which
this response/confirmation applies.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class
for storage. If included in the response/confirmation, it shall be
equal to the value in the request/indication
Priority : int
The priority of the C-STORE operation. It shall be one of the
following:
* 0: Medium
* 1: High
* 2: Low (Default)
MoveDestination : bytes or str
Specifies the DICOM AE Title of the destination DICOM AE to
which the C-STORE sub-operations are being performed.
Identifier : io.BytesIO
The pydicom Dataset containing the list of Attributes to be
matched against the values of Attributes of known composite SOP
Instances of the performing DIMSE service-user, encoded as a BytesIO
object. For the list of allowed Attributes and the rules defining their
usage see the section corresponding to the service class in the DICOM
Standard, Part 4.
Status : int
The error or success notification of the operation.
NumberOfRemainingSuboperations : int
The number of remaining C-STORE sub-operations to be invoked
by this C-MOVE operation. It may be included in any response and shall
be included if the status is Pending
NumberOfCompletedSuboperations : int
The number of C-STORE sub-operations that have completed
successfully. It may be included in any response and shall be included
if the status is Pending
NumberOfFailedSuboperations : int
The number of C-STORE sub-operations that have failed. It may
be included in any response and shall be included if the status is
Pending
NumberOfWarningSuboperations : int
The number of C-STORE operations that generated Warning
responses. It may be included in any response and shall be included if
the status is Pending
OffendingElement : list of int or None
An optional status related field containing a list of the
elements in which an error was detected.
ErrorComment : str or None
An optional status related field containing a text
description of the error detected. 64 characters maximum.
"""
STATUS_OPTIONAL_KEYWORDS = (
'ErrorComment', 'OffendingElement', 'NumberOfRemainingSuboperations',
'NumberOfCompletedSuboperations', 'NumberOfFailedSuboperations',
'NumberOfWarningSuboperations'
)
REQUEST_KEYWORDS = (
'MessageID', 'AffectedSOPClassUID', 'Priority', 'Identifier',
'MoveDestination'
)
def __init__(self):
# Variable names need to match the corresponding DICOM Element keywords
# in order for the DIMSE Message classes to be built correctly.
# Changes to the variable names can be made provided the DIMSEMessage()
# class' message_to_primitive() and primitive_to_message() methods
# are also changed
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.AffectedSOPClassUID = None
self.Priority = 0x02
self.MoveDestination = None
self.Identifier = None
self.Status = None
self.NumberOfRemainingSuboperations = None
self.NumberOfCompletedSuboperations = None
self.NumberOfFailedSuboperations = None
self.NumberOfWarningSuboperations = None
# Optional Command Set elements used in with specific Status values
# For Failure statuses 0xA900
self.OffendingElement = None
# For Failure statuses 0xA801, 0xA701, 0xA702, 0x0122, 0xA900, 0xCxxx
# 0x0124
self.ErrorComment = None
@property
def Priority(self):
"""Return the *Priority*."""
return self._priority
@Priority.setter
def Priority(self, value):
"""Set the *Priority*."""
if value in [0, 1, 2]:
self._priority = value
else:
LOGGER.warning("Attempted to set C-FIND Priority parameter to an "
"invalid value")
raise ValueError("Priority must be 0, 1, or 2")
@property
def MoveDestination(self):
"""Return the *Move Destination*."""
return self._move_destination
@MoveDestination.setter
def MoveDestination(self, value):
"""Set the *Move Destination*.
Parameters
----------
value : str or bytes
The Move Destination AE Title as a string or bytes object. Cannot
be an empty string and will be truncated to 16 characters long
"""
if isinstance(value, str):
value = codecs.encode(value, 'ascii')
if value is not None:
self._move_destination = validate_ae_title(value)
else:
self._move_destination = None
@property
def Identifier(self):
"""Return the *Identifier*."""
return self._dataset_variant
@Identifier.setter
def Identifier(self, value):
"""Set the *Identifier*."""
self._dataset_variant = (value, 'Identifier')
@property
def NumberOfRemainingSuboperations(self):
"""Return the *Number of Remaining Suboperations*."""
return self._number_of_remaining_suboperations
@NumberOfRemainingSuboperations.setter
def NumberOfRemainingSuboperations(self, value):
"""Set the *Number of Remaining Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_remaining_suboperations = value
else:
raise ValueError("Number of Remaining Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_remaining_suboperations = value
else:
raise TypeError("Number of Remaining Suboperations must be an int")
@property
def NumberOfCompletedSuboperations(self):
"""Return the *Number of Completed Suboperations*."""
return self._number_of_completed_suboperations
@NumberOfCompletedSuboperations.setter
def NumberOfCompletedSuboperations(self, value):
"""Set the *Number of Completed Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_completed_suboperations = value
else:
raise ValueError("Number of Completed Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_completed_suboperations = value
else:
raise TypeError("Number of Completed Suboperations must be an int")
@property
def NumberOfFailedSuboperations(self):
"""Return the *Number of Failed Suboperations*."""
return self._number_of_failed_suboperations
@NumberOfFailedSuboperations.setter
def NumberOfFailedSuboperations(self, value):
"""Set the *Number of Failed Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_failed_suboperations = value
else:
raise ValueError("Number of Failed Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_failed_suboperations = value
else:
raise TypeError("Number of Failed Suboperations must be an int")
@property
def NumberOfWarningSuboperations(self):
"""Return the *Number of Warning Suboperations*."""
return self._number_of_warning_suboperations
@NumberOfWarningSuboperations.setter
def NumberOfWarningSuboperations(self, value):
"""Set the *Number of Warning Suboperations*."""
if isinstance(value, int):
if value >= 0:
self._number_of_warning_suboperations = value
else:
raise ValueError("Number of Warning Suboperations must be "
"greater than or equal to 0")
elif value is None:
self._number_of_warning_suboperations = value
else:
raise TypeError("Number of Warning Suboperations must be an int")
class C_ECHO(DIMSEPrimitive):
"""Represents a C-ECHO primitive.
+-------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+===============================+=========+==========+
| Message ID | M | U |
+-------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+-------------------------------+---------+----------+
| Affected SOP Class UID | M | U(=) |
+-------------------------------+---------+----------+
| Status | \- | M |
+-------------------------------+---------+----------+
| Error Comment | \- | C |
+-------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int or None
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int or None
The Message ID of the operation request/indication to which this
response/confirmation applies.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str or None
For the request/indication this specifies the SOP Class for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
Status : int or None
The error or success notification of the operation.
ErrorComment : str or None
An optional status related field containing a text description
of the error detected. 64 characters maximum.
"""
STATUS_OPTIONAL_KEYWORDS = ('ErrorComment', )
REQUEST_KEYWORDS = ('MessageID', 'AffectedSOPClassUID')
def __init__(self):
# Variable names need to match the corresponding DICOM Element keywords
# in order for the DIMSE Message classes to be built correctly.
# Changes to the variable names can be made provided the DIMSEMessage()
# class' message_to_primitive() and primitive_to_message() methods
# are also changed
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.AffectedSOPClassUID = None
self.Status = None
# (Optional) for Failure status 0x0122
self.ErrorComment = None
class C_CANCEL(object):
"""Represents a C-CANCEL primitive.
+-------------------------------+---------+
| Parameter | Req/ind |
+===============================+=========+
| Message ID Being Responded To | M |
+-------------------------------+---------+
| (=) - The value of the parameter is equal to the value of the parameter in
the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
References
----------
* DICOM Standard, Part 7, Section 9.3.2.3-4
"""
def __init__(self):
"""Initialise the C_CANCEL"""
# Variable names need to match the corresponding DICOM Element keywords
# in order for the DIMSE Message classes to be built correctly.
# Changes to the variable names can be made provided the DIMSEMessage()
# class' message_to_primitive() and primitive_to_message() methods
# are also changed
self.MessageIDBeingRespondedTo = None
@property
def MessageIDBeingRespondedTo(self):
"""Return the *Message ID Being Responded To*."""
return self._message_id_being_responded_to
@MessageIDBeingRespondedTo.setter
def MessageIDBeingRespondedTo(self, value):
"""Set the *Message ID Being Responded To*."""
if isinstance(value, int):
if 0 <= value < 2**16:
self._message_id_being_responded_to = value
else:
raise ValueError("Message ID Being Responded To must be "
"between 0 and 65535, inclusive")
elif value is None:
self._message_id_being_responded_to = value
else:
raise TypeError("Message ID Being Responded To must be an int")
# DIMSE-N Service Primitives
class N_EVENT_REPORT(DIMSEPrimitive):
"""Represents a N-EVENT-REPORT primitive.
+------------------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+==========================================+=========+==========+
| Message ID | M | \- |
+------------------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+------------------------------------------+---------+----------+
| Affected SOP Class UID | M | U(=) |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | M | U(=) |
+------------------------------------------+---------+----------+
| Event Type ID | M | C(=) |
+------------------------------------------+---------+----------+
| Event Information | U | \- |
+------------------------------------------+---------+----------+
| Event Reply | \- | C |
+------------------------------------------+---------+----------+
| Status | \- | M |
+------------------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
AffectedSOPInstanceUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Instance
for storage. If included in the response/confirmation, it shall be
equal to the value in the request/indication
EventTypeID : int
The type of event being reported, depends on the Service Class
specification. Shall be included if Event Reply is included.
EventInformation : io.BytesIO
Contains information the invoking DIMSE user is able to supply about
the event. An encoded DICOM Dataset containing additional Service
Class specific information related to the operation.
EventReply : io.BytesIO
Contains the optional reply to the event report. An encoded DICOM
Dataset containing additional Service Class specific information.
Status : int
The error or success notification of the operation.
"""
# Optional status element keywords other than 'Status'
STATUS_OPTIONAL_KEYWORDS = (
'AffectedSOPClassUID', 'AffectedSOPInstanceUID', 'EventTypeID',
'EventInformation', 'ErrorComment', 'ErrorID'
)
REQUEST_KEYWORDS = (
'MessageID', 'AffectedSOPClassUID', 'EventTypeID',
'AffectedSOPInstanceUID'
)
def __init__(self):
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.AffectedSOPClassUID = None
self.AffectedSOPInstanceUID = None
self.EventTypeID = None
self.EventInformation = None
self.EventReply = None
self.Status = None
# Optional status elements
self.ErrorComment = None
self.ErrorID = None
@property
def AffectedSOPInstanceUID(self):
"""Return the *Affected SOP Instance UID*."""
return self._affected_sop_instance_uid
@AffectedSOPInstanceUID.setter
def AffectedSOPInstanceUID(self, value):
"""Set the *Affected SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Instance UID is an invalid UID")
raise ValueError("Affected SOP Instance UID is an invalid UID")
self._affected_sop_instance_uid = value
@property
def EventInformation(self):
"""Return the *Event Information*."""
return self._dataset_variant
@EventInformation.setter
def EventInformation(self, value):
"""Set the *Event Information*."""
self._dataset_variant = (value, 'EventInformation')
@property
def EventReply(self):
"""Return the *Event Reply*."""
return self._dataset_variant
@EventReply.setter
def EventReply(self, value):
"""Set the *Event Reply*."""
self._dataset_variant = (value, 'EventReply')
@property
def EventTypeID(self):
"""Return the *Event Type ID*."""
return self._event_type_id
@EventTypeID.setter
def EventTypeID(self, value):
"""Set the *Event Type ID*."""
if isinstance(value, int) or value is None:
self._event_type_id = value
else:
raise TypeError("'N_EVENT_REPORT.EventTypeID' must be an int.")
class N_GET(DIMSEPrimitive):
"""Represents an N-GET primitive.
+------------------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+==========================================+=========+==========+
| Message ID | M | \- |
+------------------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+------------------------------------------+---------+----------+
| Requested SOP Class UID | M | \- |
+------------------------------------------+---------+----------+
| Requested SOP Instance UID | M | \- |
+------------------------------------------+---------+----------+
| Attribute Identifier List | U | \- |
+------------------------------------------+---------+----------+
| Affected SOP Class UID | \- | U |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | \- | U |
+------------------------------------------+---------+----------+
| Attribute List | \- | C |
+------------------------------------------+---------+----------+
| Status | \- | M |
+------------------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
RequestedSOPClassUID : pydicom.uid.UID, bytes or str
The UID of the SOP Class for which attribute values are to be
retrieved.
RequestedSOPInstanceUID : pydicom.uid.UID, bytes or str
The SOP Instance for which attribute values are to be retrieved.
AttributeIdentifierList : list of pydicom.tag.Tag
A list of attribute tags to be sent to the peer.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
The SOP Class UID of the SOP Instance for which the attributes were
retrieved.
AffectedSOPInstanceUID : pydicom.uid.UID, bytes or str
The SOP Instance UID of the SOP Instance for which the attributes were
retrieved.
AttributeList : pydicom.dataset.Dataset
A dataset containing elements matching those supplied in
AttributeIdentifierList.
Status : int
The error or success notification of the operation.
"""
STATUS_OPTIONAL_KEYWORDS = ('ErrorComment', 'ErrorID', )
REQUEST_KEYWORDS = (
'MessageID', 'RequestedSOPClassUID', 'RequestedSOPInstanceUID'
)
def __init__(self):
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.RequestedSOPClassUID = None
self.RequestedSOPInstanceUID = None
self.AttributeIdentifierList = None
self.AffectedSOPClassUID = None
self.AffectedSOPInstanceUID = None
self.AttributeList = None
self.Status = None
# (Optional) elements for specific status values
self.ErrorComment = None
self.ErrorID = None
@property
def AffectedSOPInstanceUID(self):
"""Return the *Affected SOP Instance UID*."""
return self._affected_sop_instance_uid
@AffectedSOPInstanceUID.setter
def AffectedSOPInstanceUID(self, value):
"""Set the *Affected SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Instance UID is an invalid UID")
raise ValueError("Affected SOP Instance UID is an invalid UID")
self._affected_sop_instance_uid = value
@property
def AttributeIdentifierList(self):
"""Return the value of (0000,1005) *Attribute Identifier List*."""
return self._attribute_identifier_list
@AttributeIdentifierList.setter
def AttributeIdentifierList(self, value):
"""Set the value of (0000,1005) *Attribute Identifier List*.
Parameters
----------
value : list of pydicom.tag.Tag
A list of pydicom Tags or any values acceptable for creating a new
pydicom Tag object.
"""
if value:
if not isinstance(value, (list, MutableSequence)):
value = [value]
try:
self._attribute_identifier_list = [Tag(tag) for tag in value]
except (TypeError, ValueError):
raise ValueError(
"Attribute Identifier List must be a list of pydicom Tags"
)
elif value is None:
self._attribute_identifier_list = None
else:
raise ValueError(
"Attribute Identifier List must be a list of pydicom Tags"
)
@property
def AttributeList(self):
"""Return the *Attribute List*."""
return self._dataset_variant
@AttributeList.setter
def AttributeList(self, value):
"""Set the *Attribute List*."""
self._dataset_variant = (value, 'AttributeList')
@property
def RequestedSOPClassUID(self):
"""Return the *Requested SOP Class UID*."""
return self._requested_sop_class_uid
@RequestedSOPClassUID.setter
def RequestedSOPClassUID(self, value):
"""Set the *Requested SOP Class UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Class UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Class UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Class UID is an invalid UID")
raise ValueError("Requested SOP Class UID is an invalid UID")
self._requested_sop_class_uid = value
@property
def RequestedSOPInstanceUID(self):
"""Return the *Requested SOP Instance UID*."""
return self._requested_sop_instance_uid
@RequestedSOPInstanceUID.setter
def RequestedSOPInstanceUID(self, value):
"""Set the *Requested SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Instance UID is an invalid UID")
raise ValueError("Requested SOP Instance UID is an invalid UID")
self._requested_sop_instance_uid = value
class N_SET(DIMSEPrimitive):
"""Represents a N-SET primitive.
+------------------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+==========================================+=========+==========+
| Message ID | M | \- |
+------------------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+------------------------------------------+---------+----------+
| Requested SOP Class UID | M | \- |
+------------------------------------------+---------+----------+
| Requested SOP Instance UID | M | \- |
+------------------------------------------+---------+----------+
| Modification List | M | \- |
+------------------------------------------+---------+----------+
| Attribute List | \- | U |
+------------------------------------------+---------+----------+
| Affected SOP Class UID | \- | U |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | \- | U |
+------------------------------------------+---------+----------+
| Status | \- | M |
+------------------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
RequestedSOPClassUID : pydicom.uid.UID, bytes or str
The UID of the SOP Class for which attribute values are to be
modified.
RequestedSOPInstanceUID : pydicom.uid.UID, bytes or str
The SOP Instance for which attribute values are to be modified.
ModificationList : pydicom.dataset.Dataset
A dataset containing the attributes and values that are to be used
to modify the SOP Instance.
AttributeList : pydicom.dataset.Dataset
A dataset containing the attributes and values that were used to
modify the SOP Instance.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
The SOP Class UID of the modified SOP Instance.
AffectedSOPInstanceUID : pydicom.uid.UID, bytes or str
The SOP Instance UID of the modified SOP Instance.
Status : int
The error or success notification of the operation.
"""
STATUS_OPTIONAL_KEYWORDS = (
'ErrorComment', 'ErrorID', 'AttributeIdentifierList'
)
REQUEST_KEYWORDS = (
'MessageID', 'RequestedSOPClassUID', 'RequestedSOPInstanceUID',
'ModificationList'
)
def __init__(self):
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.RequestedSOPClassUID = None
self.RequestedSOPInstanceUID = None
self.ModificationList = None
self.AttributeList = None
self.AffectedSOPClassUID = None
self.AffectedSOPInstanceUID = None
self.Status = None
# Optional
self.ErrorComment = None
self.ErrorID = None
self.AttributeIdentifierList = None
@property
def AffectedSOPInstanceUID(self):
"""Return the *Affected SOP Instance UID*."""
return self._affected_sop_instance_uid
@AffectedSOPInstanceUID.setter
def AffectedSOPInstanceUID(self, value):
"""Set the *Affected SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Instance UID is an invalid UID")
raise ValueError("Affected SOP Instance UID is an invalid UID")
self._affected_sop_instance_uid = value
@property
def AttributeList(self):
"""Return the *Attribute List*."""
return self._dataset_variant
@AttributeList.setter
def AttributeList(self, value):
"""Set the *Attribute List*."""
self._dataset_variant = (value, 'AttributeList')
@property
def ModificationList(self):
"""Return the *Modification List*."""
return self._dataset_variant
@ModificationList.setter
def ModificationList(self, value):
"""Set the *Modification List*."""
self._dataset_variant = (value, 'ModificationList')
@property
def RequestedSOPClassUID(self):
"""Return the *Requested SOP Class UID*."""
return self._requested_sop_class_uid
@RequestedSOPClassUID.setter
def RequestedSOPClassUID(self, value):
"""Set the *Requested SOP Class UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Class UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Class UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Class UID is an invalid UID")
raise ValueError("Requested SOP Class UID is an invalid UID")
self._requested_sop_class_uid = value
@property
def RequestedSOPInstanceUID(self):
"""Return the *Requested SOP Instance UID*."""
return self._requested_sop_instance_uid
@RequestedSOPInstanceUID.setter
def RequestedSOPInstanceUID(self, value):
"""Set the *Requested SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Instance UID is an invalid UID")
raise ValueError("Requested SOP Instance UID is an invalid UID")
self._requested_sop_instance_uid = value
class N_ACTION(DIMSEPrimitive):
"""Represents a N-ACTION primitive.
+------------------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+==========================================+=========+==========+
| Message ID | M | \- |
+------------------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+------------------------------------------+---------+----------+
| Requested SOP Class UID | M | \- |
+------------------------------------------+---------+----------+
| Requested SOP Instance UID | M | \- |
+------------------------------------------+---------+----------+
| Action Type ID | M | C(=) |
+------------------------------------------+---------+----------+
| Action Information | U | \- |
+------------------------------------------+---------+----------+
| Affected SOP Class UID | \- | U |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | \- | U |
+------------------------------------------+---------+----------+
| Action Reply | \- | C |
+------------------------------------------+---------+----------+
| Status | \- | M |
+------------------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
RequestedSOPClassUID : pydicom.uid.UID, bytes or str
The SOP Class for which the action is to be performed.
RequestedSOPInstanceUID : pydicom.uid.UID, bytes or str
The SOP Instance for which the action is to be performed.
ActionTypeID : int
The type of action that is to be performed.
ActionInformation : pydicom.dataset.Dataset
Extra information required to perform the action.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
AffectedSOPInstanceUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Instance for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
ActionReply : pydicom.dataset.Dataset
The reply to the action.
Status : int
The error or success notification of the operation.
"""
STATUS_OPTIONAL_KEYWORDS = (
'ErrorComment', 'ErrorID', 'AttributeIdentifierList'
)
REQUEST_KEYWORDS = (
'MessageID', 'RequestedSOPClassUID', 'RequestedSOPInstanceUID',
'ActionTypeID'
)
def __init__(self):
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.RequestedSOPClassUID = None
self.RequestedSOPInstanceUID = None
self.ActionTypeID = None
self.ActionInformation = None
self.AffectedSOPClassUID = None
self.AffectedSOPInstanceUID = None
self.ActionReply = None
self.Status = None
# Optional status elements
self.ErrorComment = None
self.ErrorID = None
@property
def AffectedSOPInstanceUID(self):
"""Return the *Affected SOP Instance UID*."""
return self._affected_sop_instance_uid
@AffectedSOPInstanceUID.setter
def AffectedSOPInstanceUID(self, value):
"""Set the *Affected SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Instance UID is an invalid UID")
raise ValueError("Affected SOP Instance UID is an invalid UID")
self._affected_sop_instance_uid = value
@property
def ActionInformation(self):
"""Return the *Action Information*."""
return self._dataset_variant
@ActionInformation.setter
def ActionInformation(self, value):
"""Set the *Action Information*."""
self._dataset_variant = (value, 'ActionInformation')
@property
def ActionReply(self):
"""Return the *Action Reply*."""
return self._dataset_variant
@ActionReply.setter
def ActionReply(self, value):
"""Set the *Action Reply List*."""
self._dataset_variant = (value, 'ActionReply')
@property
def RequestedSOPClassUID(self):
"""Return the *Requested SOP Class UID*."""
return self._requested_sop_class_uid
@RequestedSOPClassUID.setter
def RequestedSOPClassUID(self, value):
"""Set the *Requested SOP Class UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Class UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Class UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Class UID is an invalid UID")
raise ValueError("Requested SOP Class UID is an invalid UID")
self._requested_sop_class_uid = value
@property
def RequestedSOPInstanceUID(self):
"""Return the *Requested SOP Instance UID*."""
return self._requested_sop_instance_uid
@RequestedSOPInstanceUID.setter
def RequestedSOPInstanceUID(self, value):
"""Set the *Requested SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Instance UID is an invalid UID")
raise ValueError("Requested SOP Instance UID is an invalid UID")
self._requested_sop_instance_uid = value
@property
def ActionTypeID(self):
"""Return the *Action Type ID*."""
return self._action_type_id
@ActionTypeID.setter
def ActionTypeID(self, value):
"""Set the *Action Type ID*."""
if isinstance(value, int) or value is None:
self._action_type_id = value
else:
raise TypeError("'N_ACTION.ActionTypeID' must be an int.")
class N_CREATE(DIMSEPrimitive):
"""Represents a N-CREATE primitive.
+------------------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+==========================================+=========+==========+
| Message ID | M | \- |
+------------------------------------------+---------+----------+
+------------------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
| Affected SOP Class UID | M | U(=) |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | U | C |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | U | U |
+------------------------------------------+---------+----------+
| Status | \- | M |
+------------------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
AffectedSOPInstanceUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Instance for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
AttributeList : pydicom.dataset.Dataset
A set of attributes and values that are to be assigned to the new
SOP Instance.
Status : int
The error or success notification of the operation. It shall be
one of the following values:
"""
STATUS_OPTIONAL_KEYWORDS = ('ErrorComment', 'ErrorID', )
REQUEST_KEYWORDS = ('MessageID', 'AffectedSOPClassUID')
def __init__(self):
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.AffectedSOPClassUID = None
self.AffectedSOPInstanceUID = None
self.AttributeList = None
self.Status = None
# Optional elements
self.ErrorComment = None
self.ErrorID = None
@property
def AffectedSOPInstanceUID(self):
"""Return the *Affected SOP Instance UID*."""
return self._affected_sop_instance_uid
@AffectedSOPInstanceUID.setter
def AffectedSOPInstanceUID(self, value):
"""Set the *Affected SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Instance UID is an invalid UID")
raise ValueError("Affected SOP Instance UID is an invalid UID")
self._affected_sop_instance_uid = value
@property
def AttributeList(self):
"""Return the *Attribute List*."""
return self._dataset_variant
@AttributeList.setter
def AttributeList(self, value):
"""Set the *Attribute List*."""
self._dataset_variant = (value, 'AttributeList')
class N_DELETE(DIMSEPrimitive):
"""Represents a N-DELETE primitive.
+------------------------------------------+---------+----------+
| Parameter | Req/ind | Rsp/conf |
+==========================================+=========+==========+
| Message ID | M | \- |
+------------------------------------------+---------+----------+
| Message ID Being Responded To | \- | M |
+------------------------------------------+---------+----------+
| Requested SOP Class UID | M | \- |
+------------------------------------------+---------+----------+
| Requested SOP Instance UID | M | \- |
+------------------------------------------+---------+----------+
| Affected SOP Class UID | \- | U |
+------------------------------------------+---------+----------+
| Affected SOP Instance UID | \- | U |
+------------------------------------------+---------+----------+
| Status | \- | M |
+------------------------------------------+---------+----------+
| (=) - The value of the parameter is equal to the value of the parameter
in the column to the left
| C - The parameter is conditional.
| M - Mandatory
| MF - Mandatory with a fixed value
| U - The use of this parameter is a DIMSE service user option
| UF - User option with a fixed value
Attributes
----------
MessageID : int
Identifies the operation and is used to distinguish this
operation from other notifications or operations that may be in
progress. No two identical values for the Message ID shall be used for
outstanding operations.
MessageIDBeingRespondedTo : int
The Message ID of the operation request/indication to which this
response/confirmation applies.
RequestedSOPClassUID : pydicom.uid.UID, bytes or str
The UID of the SOP Class to be deleted.
RequestedSOPInstanceUID : pydicom.uid.UID, bytes or str
The SOP Instance to be deleted.
AffectedSOPClassUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Class for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
AffectedSOPInstanceUID : pydicom.uid.UID, bytes or str
For the request/indication this specifies the SOP Instance for
storage. If included in the response/confirmation, it shall be equal
to the value in the request/indication
Status : int
The error or success notification of the operation.
"""
STATUS_OPTIONAL_KEYWORDS = ('ErrorComment', 'ErrorID', )
REQUEST_KEYWORDS = (
'MessageID', 'RequestedSOPClassUID', 'RequestedSOPInstanceUID'
)
def __init__(self):
self.MessageID = None
self.MessageIDBeingRespondedTo = None
self.RequestedSOPClassUID = None
self.RequestedSOPInstanceUID = None
self.AffectedSOPClassUID = None
self.AffectedSOPInstanceUID = None
self.Status = None
# Optional
self.ErrorComment = None
self.ErrorID = None
@property
def AffectedSOPInstanceUID(self):
"""Return the *Affected SOP Instance UID*."""
return self._affected_sop_instance_uid
@AffectedSOPInstanceUID.setter
def AffectedSOPInstanceUID(self, value):
"""Set the *Affected SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Affected SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Affected SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Affected SOP Instance UID is an invalid UID")
raise ValueError("Affected SOP Instance UID is an invalid UID")
self._affected_sop_instance_uid = value
@property
def RequestedSOPClassUID(self):
"""Return the *Requested SOP Class UID*."""
return self._requested_sop_class_uid
@RequestedSOPClassUID.setter
def RequestedSOPClassUID(self, value):
"""Set the *Requested SOP Class UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Class UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Class UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Class UID is an invalid UID")
raise ValueError("Requested SOP Class UID is an invalid UID")
self._requested_sop_class_uid = value
@property
def RequestedSOPInstanceUID(self):
"""Return the *Requested SOP Instance UID*."""
return self._requested_sop_instance_uid
@RequestedSOPInstanceUID.setter
def RequestedSOPInstanceUID(self, value):
"""Set the *Requested SOP Instance UID*.
Parameters
----------
value : pydicom.uid.UID, bytes or str
The value for the Requested SOP Instance UID
"""
if isinstance(value, UID):
pass
elif isinstance(value, str):
value = UID(value)
elif isinstance(value, bytes):
value = UID(value.decode('ascii'))
elif value is None:
pass
else:
raise TypeError("Requested SOP Instance UID must be a "
"pydicom.uid.UID, str or bytes")
if value is not None and not value.is_valid:
LOGGER.error("Requested SOP Instance UID is an invalid UID")
raise ValueError("Requested SOP Instance UID is an invalid UID")
self._requested_sop_instance_uid = value
| 39.758005 | 80 | 0.548527 |
6ceaecebfb602bc889bc6a72c55decf7264493d4 | 2,700 | py | Python | videos/grid_paths/grid_move_up.py | ryu577/pyray | 860b71463e2729a85b1319b5c3571c0b8f3ba50c | [
"MIT"
] | 715 | 2018-01-13T04:29:10.000Z | 2022-03-24T12:15:08.000Z | videos/grid_paths/grid_move_up.py | ryu577/pyray | 860b71463e2729a85b1319b5c3571c0b8f3ba50c | [
"MIT"
] | 8 | 2018-01-14T07:48:41.000Z | 2020-07-14T09:56:27.000Z | videos/grid_paths/grid_move_up.py | ryu577/pyray | 860b71463e2729a85b1319b5c3571c0b8f3ba50c | [
"MIT"
] | 111 | 2018-01-13T06:47:24.000Z | 2021-04-01T05:58:28.000Z | import numpy as np
from PIL import Image, ImageDraw, ImageFont, ImageMath
from pyray.rotation import general_rotation, planar_rotation, axis_rotation,\
rotate_point_about_axis
from pyray.shapes.twod.plot import Canvas
from pyray.axes import ZigZagPath
import pyray.grid as grd
def tst(basedir=".\\"):
for i in range(11):
im=Image.new("RGB", (512, 512), (0,0,0))
draw = ImageDraw.Draw(im,'RGBA')
end1=np.array([6.0,6.0])
end2=np.array([4.0,8.0])
end=end1*(1-i/10.0)+end2*(i/10.0)
gg=grd.Grid(end=end,\
center=np.array([0,0]),origin=np.array([40,256]),
rot=planar_rotation(-np.pi/4),scale=32)
pt2=gg.get_grid_pt(end[0],end[1])
gg.draw(draw,width=3)
## Draw horizontal line corresponding to the main diagonal.
pt1=gg.get_grid_pt(0,0)
pt2=gg.get_grid_pt(6,6)
draw.ellipse((pt2[0]-5, pt2[1]-5, pt2[0]+5, \
pt2[1]+5),fill='red')
draw.line((0,pt2[1],512,pt2[1]), fill="orange", width=3)
draw.line((0,pt1[1],512,pt1[1]), fill="purple", width=3)
draw.ellipse((pt1[0]-5, pt1[1]-5, pt1[0]+5, \
pt1[1]+5),fill='blue')
## Draw horizontal line corresponding to one above the main diagonal.
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
#draw.line((pt1[0],pt1[1],pt2[0],pt2[1]), fill="orange", width=2)
im.save(basedir + "im" + str(i) + ".png")
#######
for i in range(13):
im=Image.new("RGB", (512, 512), (0,0,0))
draw = ImageDraw.Draw(im,'RGBA')
end2=np.array([4.0,8.0])
gg=grd.Grid(end=end2,\
center=np.array([2,-4]),origin=np.array([90,280]),
rot=planar_rotation(-np.pi/4-np.pi*(i/12.0)),scale=32)
gg.draw(draw,width=3)
pt2=gg.get_grid_pt(end2[0],end2[1])
draw.ellipse((pt2[0]-5, pt2[1]-5, pt2[0]+5, \
pt2[1]+5),fill='red')
draw.line((0,pt2[1],512,pt2[1]), fill="orange", width=3)
## Draw horizontal line corresponding to the main diagonal.
pt1=gg.get_grid_pt(0,0)
pt2=gg.get_grid_pt(6,6)
draw.line((0,pt1[1],512,pt1[1]), fill="purple", width=3)
draw.ellipse((pt1[0]-5, pt1[1]-5, pt1[0]+5, \
pt1[1]+5),fill='blue')
## Draw horizontal line corresponding to one above the main diagonal.
pt1=gg.get_grid_pt(0,1)
pt2=gg.get_grid_pt(5,6)
#draw.line((pt1[0],pt1[1],pt2[0],pt2[1]), fill="orange", width=2)
pts=[gg.get_grid_pt(a,b) for a,b in [(0,0),(0,3),(2,3),(2,8),(4,8)]]
zg=ZigZagPath(pts)
zg.draw_lines(draw,prop_dist=1.0)
im.save(basedir + "im" + str(i) + ".png")
| 40.909091 | 77 | 0.565185 |
811697bd2ceeb780d9f5578640a12746b2af2fc7 | 861 | py | Python | yatube/posts/urls.py | pakodev28/yatube_project | ae58943b3eee1536d46292f9539b22961530ee6d | [
"MIT"
] | null | null | null | yatube/posts/urls.py | pakodev28/yatube_project | ae58943b3eee1536d46292f9539b22961530ee6d | [
"MIT"
] | null | null | null | yatube/posts/urls.py | pakodev28/yatube_project | ae58943b3eee1536d46292f9539b22961530ee6d | [
"MIT"
] | null | null | null | from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("follow/", views.follow_index, name="follow_index"),
path(
"<str:username>/follow/", views.profile_follow, name="profile_follow"
),
path("new/", views.new_post, name="new_post"),
path(
"<str:username>/<int:post_id>/edit/",
views.post_edit,
name="post_edit"
),
path("<str:username>/<int:post_id>/", views.post_view, name="post"),
path("<str:username>/", views.profile, name="profile"),
path("group/<slug:slug>/", views.group_posts, name="slug"),
path(
"<username>/<int:post_id>/comment/",
views.add_comment,
name="add_comment"
),
path(
"<str:username>/unfollow/",
views.profile_unfollow,
name="profile_unfollow"
),
]
| 27.774194 | 77 | 0.594657 |
004ff51901f6de4abf9b5fb86fe0903112ba4d98 | 531 | py | Python | PSMS/migrations/0006_auto_20181218_0130.py | hellen6654/DataBase_CGHP | d4e393d3994c3a7b576c651ad2ac7ef919a3f386 | [
"MIT"
] | null | null | null | PSMS/migrations/0006_auto_20181218_0130.py | hellen6654/DataBase_CGHP | d4e393d3994c3a7b576c651ad2ac7ef919a3f386 | [
"MIT"
] | null | null | null | PSMS/migrations/0006_auto_20181218_0130.py | hellen6654/DataBase_CGHP | d4e393d3994c3a7b576c651ad2ac7ef919a3f386 | [
"MIT"
] | null | null | null | # Generated by Django 2.1.3 on 2018-12-17 17:30
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('PSMS', '0005_auto_20181218_0125'),
]
operations = [
migrations.AlterField(
model_name='pizza',
name='kind_chose',
field=models.CharField(choices=[('Beef', '牛肉'), ('Chicken', '雞肉'), ('Mix', '混合'), ('Pork', '豬肉'), ('Seafood', '海鮮'), ('Vegetable', '蔬菜')], max_length=5, null=True, verbose_name='種類'),
),
]
| 27.947368 | 195 | 0.574388 |
74b940a1b9afe48516d7d212f05ceeac4f8512bd | 6,876 | py | Python | biosteam/units/_batch_bioreactor.py | rupert-br/biosteam | 2fda82749b23aeb62877257836cd1d7bd8a87638 | [
"MIT"
] | null | null | null | biosteam/units/_batch_bioreactor.py | rupert-br/biosteam | 2fda82749b23aeb62877257836cd1d7bd8a87638 | [
"MIT"
] | null | null | null | biosteam/units/_batch_bioreactor.py | rupert-br/biosteam | 2fda82749b23aeb62877257836cd1d7bd8a87638 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
# BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules
# Copyright (C) 2020-2021, Yoel Cortes-Pena <yoelcortes@gmail.com>
#
# This module is under the UIUC open-source license. See
# github.com/BioSTEAMDevelopmentGroup/biosteam/blob/master/LICENSE.txt
# for license details.
"""
"""
import numpy as np
from .. import Unit
from .design_tools import size_batch
from .decorators import cost
import flexsolve as flx
from math import ceil
__all__ = ('BatchBioreactor',)
@cost('Reactor volume', 'Cleaning in place', CE=521.9,
cost=421e3, S=3785, n=0.6, BM=1.8)
@cost('Reactor volume', 'Agitators', CE=521.9, cost=52500,
S=3785, n=0.5, kW=22.371, BM=1.5, N='Number of reactors')
@cost('Reactor volume', 'Reactors', CE=521.9, cost=844000,
S=3785, n=0.5, BM=1.5, N='Number of reactors')
@cost('Reactor duty', 'Heat exchangers', CE=522, cost=23900,
S=20920000.0, n=0.7, BM=2.2, N='Number of reactors') # Based on a similar heat exchanger
class BatchBioreactor(Unit, isabstract=True):
"""
Abstract Bioreactor class. Conversion is based on reaction time, `tau`.
Cleaning and unloading time,`tau_0`, fraction of working volume, `V_wf`,
and number of reactors, `N_reactors`, are attributes that can be changed.
The cost of a reactor is based on the NREL batch fermentation tank cost
assuming volumetric scaling with a 6/10th exponent [1]_.
**Abstract methods**
kinetic_model(z, t, *kinetic_constants):
A staticmethod that returns effluent concentrations (z_t; kg/m^3)
given the starting concentration (z; kg/m^3), reaction time (t; hr),
and kinetic constants.
_run():
Must set outlet stream flows.
_cost():
Must set purchase cost results.
Parameters
----------
ins : streams
Inlet fluids to be mixed into the reactor.
outs : stream sequence
* [0] Vent
* [1] Effluent
tau : float
Reaction time [hr].
N : int, optional
Number of batch reactors
V : float, optional
Target volume of reactors [m^3].
T=305.15 : float
Operating temperature of reactor [K].
P=101325 : float
Operating pressure of reactor [Pa].
Nmin=2 : int
Minimum number of fermentors.
Nmax=36: int
Maximum number of fermentors.
Notes
-----
Either N or V must be given.
References
----------
.. [1] D. Humbird, R. Davis, L. Tao, C. Kinchin, D. Hsu, and A.
Aden National. Renewable Energy Laboratory Golden, Colorado. P.
Schoen, J. Lukas, B. Olthof, M. Worley, D. Sexton, and D. Dudgeon.
Harris Group Inc. Seattle, Washington and Atlanta, Georgia. Process
Design and Economics for Biochemical Conversion of Lignocellulosic
Biomass to Ethanol Dilute-Acid Pretreatment and Enzymatic Hydrolysis
of Corn Stover. May 2011. Technical Report NREL/TP-5100-47764
"""
_units = {'Reactor volume': 'm3',
'Cycle time': 'hr',
'Batch time': 'hr',
'Loading time': 'hr',
'Total dead time': 'hr',
'Reactor duty': 'kJ/hr'}
_N_ins = _N_outs = 2
_N_heat_utilities = 1
#: [bool] If True, number of reactors (N) is chosen as to minimize installation cost in every simulation. Otherwise, N remains constant.
autoselect_N = False
#: [float] Cleaning and unloading time (hr).
tau_0 = 3
#: [float] Fraction of filled tank to total tank volume.
V_wf = 0.9
def _get_design_info(self):
return (('Cleaning and unloading time', self.tau_0, 'hr'),
('Working volume fraction', self.V_wf, ''))
def __init__(self, ID='', ins=None, outs=(), thermo=None, *,
tau, N=None, V=None, T=305.15, P=101325,
Nmin=2, Nmax=36):
Unit.__init__(self, ID, ins, outs, thermo)
self._N = N; self._V = V
#: [float] Reaction time [hr].
self.tau = tau
#: [int] Number of batch reactors
if N: self.N = N
#: [float] Target volume of a fermentor
if V: self.V = V
#: [float] Operating temperature of reactor [K].
self.T = T
#: [float] Operating pressure of reactor [Pa].
self.P = P
#: [int] Minimum number of fermentors
self.Nmin = Nmin
#: [int] Maximum number of fermentors
self.Nmax = Nmax
def _setup(self):
super()._setup()
vent, effluent = self.outs
vent.phase = 'g'
vent.T = effluent.T = self.T
vent.P = effluent.P = self.P
@property
def N(self):
"""[int] Number of reactor."""
return self._N
@N.setter
def N(self, N):
if N <= 1:
raise ValueError(f"number of reactors must be greater than 1, value {N} is infeasible")
assert not self._V, 'cannot specify both reactor volume and number of reactors'
self._N = ceil(N)
@property
def V(self):
"""[float] Reactor volume."""
return self._V
@V.setter
def V(self, V):
if V <= 1:
raise ValueError(f"reactor volume must be greater than 1, value {V} is infeasible")
assert not self._N, 'cannot specify both reactor volume and number of reactors'
self._V = V
@property
def tau(self):
return self._tau
@tau.setter
def tau(self, tau):
self._tau = tau
@property
def N_at_minimum_capital_cost(self):
cost_old = np.inf
self.autoselect_N = False
self._N, N = 2, self._N
cost_new = self.purchase_cost
self._summary()
while cost_new < cost_old:
self._N += 1
self._summary()
cost_old = cost_new
cost_new = self.purchase_cost
self._N, N = N, self._N
self.autoselect_N = True
return N - 1
def _design(self):
effluent = self.outs[1]
v_0 = effluent.F_vol
tau = self._tau
tau_0 = self.tau_0
V_wf = self.V_wf
Design = self.design_results
if self.autoselect_N:
N = self.N_at_minimum_capital_cost
elif self.V:
f = lambda N: v_0 / N / V_wf * (tau + tau_0) / (1 - 1 / N) - self.V
N = flx.IQ_interpolation(f, self.Nmin, self.Nmax,
xtol=0.01, ytol=0.5, checkbounds=False)
N = ceil(N)
else:
N = self._N
Design.update(size_batch(v_0, tau, tau_0, N, V_wf))
Design['Number of reactors'] = N
duty = self.Hnet
Design['Reactor duty'] = abs(duty)
self.heat_utilities[0](duty, self.T)
| 33.057692 | 140 | 0.578389 |
62af06de52912d5d504893308cd7a5cf09b06f4e | 1,245 | py | Python | video/migrations/0001_initial.py | ChoiJunsik/Sumalyze | 2387f6c6512a2da106d2579b1df08ee2311e2602 | [
"MIT"
] | 2 | 2019-05-09T10:43:28.000Z | 2019-05-20T07:50:45.000Z | video/migrations/0001_initial.py | ChoiJunsik/Sumalyze | 2387f6c6512a2da106d2579b1df08ee2311e2602 | [
"MIT"
] | 3 | 2021-09-08T01:01:39.000Z | 2022-03-11T23:47:50.000Z | video/migrations/0001_initial.py | ChoiJunsik/Sumalyze | 2387f6c6512a2da106d2579b1df08ee2311e2602 | [
"MIT"
] | 1 | 2020-04-09T13:41:56.000Z | 2020-04-09T13:41:56.000Z | # Generated by Django 2.1.5 on 2019-05-26 06:10
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
]
operations = [
migrations.CreateModel(
name='VideoPost',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('title', models.CharField(max_length=200)),
('url', models.CharField(max_length=300)),
('content', models.TextField()),
('category', models.CharField(max_length=200)),
('lang', models.CharField(max_length=200)),
('keyword', models.TextField()),
('relevance', models.TextField()),
('category_ibm', models.TextField()),
('created', models.DateTimeField(default=django.utils.timezone.now)),
('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),
],
),
]
| 35.571429 | 120 | 0.603213 |
63f95a3badf645cb4fa922c79fe13896b0c31982 | 8,945 | py | Python | rl_coach/architectures/tensorflow_components/heads/ppo_head.py | jl45621/coach | 9a895a1ac73aff44b2e6eb8e4d01e8ec35ceb084 | [
"Apache-2.0"
] | 1,960 | 2017-10-19T10:31:24.000Z | 2020-11-07T18:19:23.000Z | rl_coach/architectures/tensorflow_components/heads/ppo_head.py | jl45621/coach | 9a895a1ac73aff44b2e6eb8e4d01e8ec35ceb084 | [
"Apache-2.0"
] | 349 | 2017-10-21T17:17:18.000Z | 2020-10-17T13:39:56.000Z | rl_coach/architectures/tensorflow_components/heads/ppo_head.py | jl45621/coach | 9a895a1ac73aff44b2e6eb8e4d01e8ec35ceb084 | [
"Apache-2.0"
] | 428 | 2017-10-21T01:32:58.000Z | 2020-11-07T13:49:49.000Z | #
# Copyright (c) 2017 Intel Corporation
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
import numpy as np
import tensorflow as tf
from rl_coach.architectures.tensorflow_components.layers import Dense
from rl_coach.architectures.tensorflow_components.heads.head import Head, normalized_columns_initializer
from rl_coach.base_parameters import AgentParameters, DistributedTaskParameters
from rl_coach.core_types import ActionProbabilities
from rl_coach.spaces import BoxActionSpace, DiscreteActionSpace
from rl_coach.spaces import SpacesDefinition
from rl_coach.utils import eps
class PPOHead(Head):
def __init__(self, agent_parameters: AgentParameters, spaces: SpacesDefinition, network_name: str,
head_idx: int = 0, loss_weight: float = 1., is_local: bool = True, activation_function: str='tanh',
dense_layer=Dense):
super().__init__(agent_parameters, spaces, network_name, head_idx, loss_weight, is_local, activation_function,
dense_layer=dense_layer)
self.name = 'ppo_head'
self.return_type = ActionProbabilities
# used in regular PPO
self.use_kl_regularization = agent_parameters.algorithm.use_kl_regularization
if self.use_kl_regularization:
# kl coefficient and its corresponding assignment operation and placeholder
self.kl_coefficient = tf.Variable(agent_parameters.algorithm.initial_kl_coefficient,
trainable=False, name='kl_coefficient')
self.kl_coefficient_ph = tf.placeholder('float', name='kl_coefficient_ph')
self.assign_kl_coefficient = tf.assign(self.kl_coefficient, self.kl_coefficient_ph)
self.kl_cutoff = 2 * agent_parameters.algorithm.target_kl_divergence
self.high_kl_penalty_coefficient = agent_parameters.algorithm.high_kl_penalty_coefficient
self.clip_likelihood_ratio_using_epsilon = agent_parameters.algorithm.clip_likelihood_ratio_using_epsilon
self.beta = agent_parameters.algorithm.beta_entropy
def _build_module(self, input_layer):
if isinstance(self.spaces.action, DiscreteActionSpace):
self._build_discrete_net(input_layer, self.spaces.action)
elif isinstance(self.spaces.action, BoxActionSpace):
self._build_continuous_net(input_layer, self.spaces.action)
else:
raise ValueError("only discrete or continuous action spaces are supported for PPO")
self.action_probs_wrt_policy = self.policy_distribution.log_prob(self.actions)
self.action_probs_wrt_old_policy = self.old_policy_distribution.log_prob(self.actions)
self.entropy = tf.reduce_mean(self.policy_distribution.entropy())
# Used by regular PPO only
# add kl divergence regularization
self.kl_divergence = tf.reduce_mean(tf.distributions.kl_divergence(self.old_policy_distribution, self.policy_distribution))
if self.use_kl_regularization:
# no clipping => use kl regularization
self.weighted_kl_divergence = tf.multiply(self.kl_coefficient, self.kl_divergence)
self.regularizations += [self.weighted_kl_divergence + self.high_kl_penalty_coefficient * \
tf.square(tf.maximum(0.0, self.kl_divergence - self.kl_cutoff))]
# calculate surrogate loss
self.advantages = tf.placeholder(tf.float32, [None], name="advantages")
self.target = self.advantages
# action_probs_wrt_old_policy != 0 because it is e^...
self.likelihood_ratio = tf.exp(self.action_probs_wrt_policy - self.action_probs_wrt_old_policy)
if self.clip_likelihood_ratio_using_epsilon is not None:
self.clip_param_rescaler = tf.placeholder(tf.float32, ())
self.input.append(self.clip_param_rescaler)
max_value = 1 + self.clip_likelihood_ratio_using_epsilon * self.clip_param_rescaler
min_value = 1 - self.clip_likelihood_ratio_using_epsilon * self.clip_param_rescaler
self.clipped_likelihood_ratio = tf.clip_by_value(self.likelihood_ratio, min_value, max_value)
self.scaled_advantages = tf.minimum(self.likelihood_ratio * self.advantages,
self.clipped_likelihood_ratio * self.advantages)
else:
self.scaled_advantages = self.likelihood_ratio * self.advantages
# minus sign is in order to set an objective to minimize (we actually strive for maximizing the surrogate loss)
self.surrogate_loss = -tf.reduce_mean(self.scaled_advantages)
if self.is_local:
# add entropy regularization
if self.beta:
self.entropy = tf.reduce_mean(self.policy_distribution.entropy())
self.regularizations += [-tf.multiply(self.beta, self.entropy, name='entropy_regularization')]
self.loss = self.surrogate_loss
tf.losses.add_loss(self.loss)
def _build_discrete_net(self, input_layer, action_space):
num_actions = len(action_space.actions)
self.actions = tf.placeholder(tf.int32, [None], name="actions")
self.old_policy_mean = tf.placeholder(tf.float32, [None, num_actions], "old_policy_mean")
self.old_policy_std = tf.placeholder(tf.float32, [None, num_actions], "old_policy_std")
# Policy Head
self.input = [self.actions, self.old_policy_mean]
policy_values = self.dense_layer(num_actions)(input_layer, name='policy_fc')
self.policy_mean = tf.nn.softmax(policy_values, name="policy")
# define the distributions for the policy and the old policy
self.policy_distribution = tf.contrib.distributions.Categorical(probs=self.policy_mean)
self.old_policy_distribution = tf.contrib.distributions.Categorical(probs=self.old_policy_mean)
self.output = self.policy_mean
def _build_continuous_net(self, input_layer, action_space):
num_actions = action_space.shape[0]
self.actions = tf.placeholder(tf.float32, [None, num_actions], name="actions")
self.old_policy_mean = tf.placeholder(tf.float32, [None, num_actions], "old_policy_mean")
self.old_policy_std = tf.placeholder(tf.float32, [None, num_actions], "old_policy_std")
self.input = [self.actions, self.old_policy_mean, self.old_policy_std]
self.policy_mean = self.dense_layer(num_actions)(input_layer, name='policy_mean',
kernel_initializer=normalized_columns_initializer(0.01))
# for local networks in distributed settings, we need to move variables we create manually to the
# tf.GraphKeys.LOCAL_VARIABLES collection, since the variable scope custom getter which is set in
# Architecture does not apply to them
if self.is_local and isinstance(self.ap.task_parameters, DistributedTaskParameters):
self.policy_logstd = tf.Variable(np.zeros((1, num_actions)), dtype='float32',
collections=[tf.GraphKeys.LOCAL_VARIABLES], name="policy_log_std")
else:
self.policy_logstd = tf.Variable(np.zeros((1, num_actions)), dtype='float32', name="policy_log_std")
self.policy_std = tf.tile(tf.exp(self.policy_logstd), [tf.shape(input_layer)[0], 1], name='policy_std')
# define the distributions for the policy and the old policy
self.policy_distribution = tf.contrib.distributions.MultivariateNormalDiag(self.policy_mean, self.policy_std + eps)
self.old_policy_distribution = tf.contrib.distributions.MultivariateNormalDiag(self.old_policy_mean, self.old_policy_std + eps)
self.output = [self.policy_mean, self.policy_std]
def __str__(self):
action_head_mean_result = []
if isinstance(self.spaces.action, DiscreteActionSpace):
# create a discrete action network (softmax probabilities output)
action_head_mean_result.append("Dense (num outputs = {})".format(len(self.spaces.action.actions)))
action_head_mean_result.append("Softmax")
elif isinstance(self.spaces.action, BoxActionSpace):
# create a continuous action network (bounded mean and stdev outputs)
action_head_mean_result.append("Dense (num outputs = {})".format(self.spaces.action.shape))
return '\n'.join(action_head_mean_result)
| 56.974522 | 135 | 0.710788 |
12e55d73497293b90fe73e601aec08f4577850f4 | 639 | py | Python | hata/discord/guild/__init__.py | WizzyBots/hata | f6991afc0bebf7dad932888a536f4d010f8663c7 | [
"0BSD"
] | 1 | 2022-03-02T03:59:57.000Z | 2022-03-02T03:59:57.000Z | hata/discord/guild/__init__.py | m0nk3ybraindead/hata | f87ed3d7009eeae31d6ea158772efd33775c7b1c | [
"0BSD"
] | 1 | 2022-02-08T16:54:39.000Z | 2022-02-08T16:54:39.000Z | hata/discord/guild/__init__.py | WizzyBots/hata | f6991afc0bebf7dad932888a536f4d010f8663c7 | [
"0BSD"
] | null | null | null | from .audit_logs import *
from .discovery import *
from .embedded_activity_state import *
from .event_types import *
from .flags import *
from .guild import *
from .preinstanced import *
from .preview import *
from .utils import *
from .verification_screen import *
from .welcome_screen import *
from .widget import *
__all__ = (
*audit_logs.__all__,
*discovery.__all__,
*event_types.__all__,
*embedded_activity_state.__all__,
*flags.__all__,
*guild.__all__,
*preinstanced.__all__,
*preview.__all__,
*utils.__all__,
*verification_screen.__all__,
*welcome_screen.__all__,
*widget.__all__,
)
| 22.821429 | 38 | 0.72457 |
44b872881d5f00a9e1af8ddc135331008805ee58 | 4,453 | py | Python | scripts/study_case/ID_4/torch_geometric/datasets/modelnet.py | kzbnb/numerical_bugs | bc22e72bcc06df6ce7889a25e0aeed027bde910b | [
"Apache-2.0"
] | 8 | 2021-06-30T06:55:14.000Z | 2022-03-18T01:57:14.000Z | scripts/study_case/ID_4/torch_geometric/datasets/modelnet.py | kzbnb/numerical_bugs | bc22e72bcc06df6ce7889a25e0aeed027bde910b | [
"Apache-2.0"
] | 1 | 2021-06-30T03:08:15.000Z | 2021-06-30T03:08:15.000Z | scripts/study_case/ID_4/torch_geometric/datasets/modelnet.py | kzbnb/numerical_bugs | bc22e72bcc06df6ce7889a25e0aeed027bde910b | [
"Apache-2.0"
] | 2 | 2021-11-17T11:19:48.000Z | 2021-11-18T03:05:58.000Z | import os
import os.path as osp
import glob
import torch
from scripts.study_case.ID_4.torch_geometric.data import InMemoryDataset, download_url, extract_zip
from scripts.study_case.ID_4.torch_geometric.read import read_off
class ModelNet(InMemoryDataset):
r"""The ModelNet10/40 datasets from the `"3D ShapeNets: A Deep
Representation for Volumetric Shapes"
<https://people.csail.mit.edu/khosla/papers/cvpr2015_wu.pdf>`_ paper,
containing CAD models of 10 and 40 categories, respectively.
.. note::
Data objects hold mesh faces instead of edge indices.
To convert the mesh to a graph, use the
:obj:`torch_geometric.transforms.FaceToEdge` as :obj:`pre_transform`.
To convert the mesh to a point cloud, use the
:obj:`torch_geometric.transforms.SamplePoints` as :obj:`transform` to
sample a fixed number of points on the mesh faces according to their
face area.
Args:
root (string): Root directory where the dataset should be saved.
name (string, optional): The name of the dataset (:obj:`"10"` for
ModelNet10, :obj:`"40"` for ModelNet40). (default: :obj:`"10"`)
train (bool, optional): If :obj:`True`, loads the training dataset,
otherwise the test dataset. (default: :obj:`True`)
transform (callable, optional): A function/transform that takes in an
:obj:`torch_geometric.data.Data` object and returns a transformed
version. The data object will be transformed before every access.
(default: :obj:`None`)
pre_transform (callable, optional): A function/transform that takes in
an :obj:`torch_geometric.data.Data` object and returns a
transformed version. The data object will be transformed before
being saved to disk. (default: :obj:`None`)
pre_filter (callable, optional): A function that takes in an
:obj:`torch_geometric.data.Data` object and returns a boolean
value, indicating whether the data object should be included in the
final dataset. (default: :obj:`None`)
"""
urls = {
'10':
'http://vision.princeton.edu/projects/2014/3DShapeNets/ModelNet10.zip',
'40': 'http://modelnet.cs.princeton.edu/ModelNet40.zip'
}
def __init__(self,
root,
name='10',
train=True,
transform=None,
pre_transform=None,
pre_filter=None):
assert name in ['10', '40']
self.name = name
super(ModelNet, self).__init__(root, transform, pre_transform,
pre_filter)
path = self.processed_paths[0] if train else self.processed_paths[1]
self.data, self.slices = torch.load(path)
@property
def raw_file_names(self):
return [
'bathtub', 'bed', 'chair', 'desk', 'dresser', 'monitor',
'night_stand', 'sofa', 'table', 'toilet'
]
@property
def processed_file_names(self):
return ['training.pt', 'test.pt']
def download(self):
path = download_url(self.urls[self.name], self.root)
extract_zip(path, self.root)
os.unlink(path)
folder = osp.join(self.root, 'ModelNet{}'.format(self.name))
os.rename(folder, self.raw_dir)
def process(self):
torch.save(self.process_set('train'), self.processed_paths[0])
torch.save(self.process_set('test'), self.processed_paths[1])
def process_set(self, dataset):
categories = glob.glob(osp.join(self.raw_dir, '*', ''))
categories = sorted([x.split(os.sep)[-2] for x in categories])
data_list = []
for target, category in enumerate(categories):
folder = osp.join(self.raw_dir, category, dataset)
paths = glob.glob('{}/{}_*.off'.format(folder, category))
for path in paths:
data = read_off(path)
data.y = torch.tensor([target])
data_list.append(data)
if self.pre_filter is not None:
data_list = [d for d in data_list if self.pre_filter(d)]
if self.pre_transform is not None:
data_list = [self.pre_transform(d) for d in data_list]
return self.collate(data_list)
def __repr__(self):
return '{}{}({})'.format(self.__class__.__name__, self.name, len(self))
| 40.117117 | 99 | 0.621379 |
ab45eb2d92419abc2788b5c1663b427111e8a8a7 | 6,993 | py | Python | dag.py | airlaunch-ch/airflow-dags-demo-industry | a07fdca734694c9ba5ae06a4b4fa95c51289ee7f | [
"Apache-2.0"
] | null | null | null | dag.py | airlaunch-ch/airflow-dags-demo-industry | a07fdca734694c9ba5ae06a4b4fa95c51289ee7f | [
"Apache-2.0"
] | null | null | null | dag.py | airlaunch-ch/airflow-dags-demo-industry | a07fdca734694c9ba5ae06a4b4fa95c51289ee7f | [
"Apache-2.0"
] | null | null | null | from datetime import datetime, timedelta
import queue
from dateutil.parser import parse
from io import BytesIO
import pandas as pd
from sqlalchemy.types import DateTime, Float, Text
from airflow import DAG
from providers.airlaunch.opcua.transfers.opcua_to_postgres import OPCUAToPostgresOperator
from airflow.operators.python import PythonOperator
from airflow.providers.ftp.hooks.ftp import FTPHook
from airflow.providers.postgres.hooks.postgres import PostgresHook
floationColumns = [
{"airflowNodeId": "1008", "levelNodeId": "1015", "colNo": 1},
{"airflowNodeId": "1009", "levelNodeId": "1016", "colNo": 2},
{"airflowNodeId": "1010", "levelNodeId": "1017", "colNo": 3},
{"airflowNodeId": "1011", "levelNodeId": "1018", "colNo": 4},
{"airflowNodeId": "1012", "levelNodeId": "1019", "colNo": 5},
{"airflowNodeId": "1013", "levelNodeId": "1020", "colNo": 6},
{"airflowNodeId": "1014", "levelNodeId": "1021", "colNo": 7},
]
def extract_xlsx_from_ftp(postgres_conn_id: str, postgres_table: str, ftp_conn_id: str, remote_full_path: str, sheet_name: str, column_names: list, dtype: dict, start_time: str, end_time: str):
ftp_hook = FTPHook(
ftp_conn_id
)
buff = BytesIO()
ftp_hook.retrieve_file(
remote_full_path=remote_full_path,
local_full_path_or_buffer=buff
)
excel_object = pd.ExcelFile(buff, engine='openpyxl')
df = excel_object.parse(sheet_name = sheet_name, index_col = 0)
df = df[(df.index >= start_time) & (df.index < end_time)]
df.reset_index(drop=False, inplace=True)
df.columns = column_names
pg_hook = PostgresHook(postgres_conn_id=postgres_conn_id)
df.to_sql(postgres_table, pg_hook.get_sqlalchemy_engine(), if_exists='append', index=False, dtype=dtype)
def extract_postgres_table(source_postgres_conn_id: str, source_table: str, dest_postgres_conn_id: str, dest_table: str, start_time: str, end_time: str):
source_hook = PostgresHook(source_postgres_conn_id)
destination_hook = PostgresHook(dest_postgres_conn_id)
records = source_hook.get_pandas_df("""SELECT * FROM "{}" WHERE datetime >= '{}' AND datetime < '{}'""".format(source_table, start_time, end_time))
records.to_sql(dest_table, destination_hook.get_sqlalchemy_engine(), if_exists='append', index=False)
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'email': ['hello@airlaunch.ch'],
'email_on_failure': False,
'email_on_retry': False,
'retries': 10,
'retry_delay': timedelta(minutes=2),
}
with DAG(
'opc',
default_args=default_args,
description='Extract Production Data',
schedule_interval=timedelta(hours=12),
start_date=datetime(2022, 1, 16, 1, 0, 0),
catchup=True,
) as dag:
fetchInputQuality = PythonOperator(
task_id='extract_input_quality',
python_callable=extract_xlsx_from_ftp,
queue='local',
op_kwargs={
"postgres_table": "input_quality",
"column_names": ['datetime', 'percent_iron_feed', 'percent_silica_feed'],
"dtype": {"datetime": DateTime, "percent_iron_feed": Float, "percent_silica_feed": Float},
"ftp_conn_id": "ftp_lab",
"remote_full_path": "/data/input_quality_shifted.xlsx",
"sheet_name": 'Sheet1',
"start_time": "{{ data_interval_start.to_datetime_string() }}",
"end_time": "{{ data_interval_end.to_datetime_string() }}",
"postgres_conn_id": "postgres_warehouse"
}
)
fetchIncidentReports = PythonOperator(
task_id='fetch_incident_reports',
python_callable=extract_xlsx_from_ftp,
queue='local',
op_kwargs={
"postgres_table": "incident_reports",
"column_names": ['datetime', 'device', 'reason', 'category', 'severity'],
"dtype": {"datetime": DateTime, "reason": Text, "category": Text, "device": Text, 'severity': Text},
"ftp_conn_id": "ftp_lab",
"remote_full_path": "/data/incident_reports_shifted.xlsx",
"sheet_name": 'Sheet1',
"start_time": "{{ data_interval_start.to_datetime_string() }}",
"end_time": "{{ data_interval_end.to_datetime_string() }}",
"postgres_conn_id": "postgres_warehouse"
}
)
for column in floationColumns:
extractColumnAirflow = OPCUAToPostgresOperator(
task_id='extract_opc_column_airflow_{}'.format(column["colNo"]),
queue='local',
opcua_node="ns=0;i={}".format(column["airflowNodeId"]),
opcua_conn_id="opc",
if_exists='append',
opcua_startdate="{{ data_interval_start.to_datetime_string() }}",
opcua_enddate="{{ data_interval_end.to_datetime_string() }}",
postgres_table='column_airflow',
static_columns={
'column': column["colNo"]
},
postgres_conn_id="postgres_warehouse",
)
extractColumnLevel = OPCUAToPostgresOperator(
task_id='extract_opc_column_level_{}'.format(column["colNo"]),
queue='local',
opcua_node="ns=0;i={}".format(column["levelNodeId"]),
opcua_conn_id="opc",
if_exists='append',
opcua_startdate="{{ data_interval_start.to_datetime_string() }}",
opcua_enddate="{{ data_interval_end.to_datetime_string() }}",
postgres_table='column_level',
static_columns={
'column': column["colNo"]
},
postgres_conn_id="postgres_warehouse",
)
fetchOutputQuality = PythonOperator(
task_id='extract_output_quality',
python_callable=extract_xlsx_from_ftp,
queue='local',
op_kwargs={
"postgres_table": "output_quality",
"column_names": ['datetime', 'percent_iron_concentrate', 'percent_silica_concentrate'],
"dtype": {"datetime": DateTime, "percent_iron_concentrate": Float, "percent_silica_concentrate": Float},
"ftp_conn_id": "ftp_lab",
"remote_full_path": "/data/output_quality_shifted.xlsx",
"sheet_name": 'Sheet1',
"start_time": "{{ data_interval_start.to_datetime_string() }}",
"end_time": "{{ data_interval_end.to_datetime_string() }}",
"postgres_conn_id": "postgres_warehouse"
}
)
fetchInputProperties = PythonOperator(
task_id='load_input_properties',
python_callable=extract_postgres_table,
queue='local',
op_kwargs={
"source_postgres_conn_id": 'postgres_quality',
"source_table": "input_quality_shifted",
"dest_postgres_conn_id": 'postgres_warehouse',
"dest_table": "input_properties",
"start_time": "{{ data_interval_start.to_datetime_string() }}",
"end_time": "{{ data_interval_end.to_datetime_string() }}",
}
)
if __name__ == "__main__":
dag.cli() | 41.135294 | 193 | 0.646504 |
fef529ee6976c46e1b793865ed5fa4dbcd0509c7 | 1,604 | py | Python | notion_renderer/__main__.py | ruucm/notion_renderer | dede1b1b3c38fd5a741acfd5dc1171b4bc5afb84 | [
"MIT"
] | null | null | null | notion_renderer/__main__.py | ruucm/notion_renderer | dede1b1b3c38fd5a741acfd5dc1171b4bc5afb84 | [
"MIT"
] | null | null | null | notion_renderer/__main__.py | ruucm/notion_renderer | dede1b1b3c38fd5a741acfd5dc1171b4bc5afb84 | [
"MIT"
] | null | null | null | # type: ignore[attr-defined]
from typing import Optional
from enum import Enum
from random import choice
import typer
from rich.console import Console
from notion_renderer import version
from notion_renderer.example import hello
from notion_renderer.notion_to_mdx import convert
class Color(str, Enum):
white = "white"
red = "red"
cyan = "cyan"
magenta = "magenta"
yellow = "yellow"
green = "green"
app = typer.Typer(
name="notion_renderer",
help="notion-py to MDX and REST API",
add_completion=False,
)
console = Console()
def version_callback(print_version: bool) -> None:
"""Print the version of the package."""
if print_version:
console.print(
f"[yellow]notion_renderer[/] version: [bold blue]{version}[/]")
raise typer.Exit()
@app.command(name="")
def main(
name: str = typer.Option(..., help="Person to greet."),
color: Optional[Color] = typer.Option(
None,
"-c",
"--color",
"--colour",
case_sensitive=False,
help="Color for print. If not specified then choice will be random.",
),
print_version: bool = typer.Option(
None,
"-v",
"--version",
callback=version_callback,
is_eager=True,
help="Prints the version of the notion_renderer package.",
),
) -> None:
"""Print a greeting with a giving name."""
if color is None:
color = choice(list(Color))
greeting: str = hello(name)
console.print(f"[bold {color}]{greeting}[/]")
convert()
if __name__ == "__main__":
app()
| 22.591549 | 77 | 0.622818 |
1ec2b7d40e4e99d1c36be1700f6aa6a00fb595ba | 309 | py | Python | data/multilingual/Latn.IBO/Sun-ExtA_8/pdf_to_json_test_Latn.IBO_Sun-ExtA_8.py | antoinecarme/pdf_to_json_tests | d57a024fde862e698d916a1178f285883d7a3b2f | [
"BSD-3-Clause"
] | 1 | 2021-09-19T19:47:35.000Z | 2021-09-19T19:47:35.000Z | data/multilingual/Latn.IBO/Sun-ExtA_8/pdf_to_json_test_Latn.IBO_Sun-ExtA_8.py | antoinecarme/pdf_to_json_tests | d57a024fde862e698d916a1178f285883d7a3b2f | [
"BSD-3-Clause"
] | null | null | null | data/multilingual/Latn.IBO/Sun-ExtA_8/pdf_to_json_test_Latn.IBO_Sun-ExtA_8.py | antoinecarme/pdf_to_json_tests | d57a024fde862e698d916a1178f285883d7a3b2f | [
"BSD-3-Clause"
] | null | null | null | import pdf_to_json as p2j
import json
url = "file:data/multilingual/Latn.IBO/Sun-ExtA_8/udhr_Latn.IBO_Sun-ExtA_8.pdf"
lConverter = p2j.pdf_to_json.pdf_to_json_converter()
lConverter.mImageHashOnly = True
lDict = lConverter.convert(url)
print(json.dumps(lDict, indent=4, ensure_ascii=False, sort_keys=True))
| 30.9 | 79 | 0.809061 |
1752e4274d45dc490a84d01cc552e700c7805568 | 10,514 | py | Python | script.module.nanscrapers/lib/nanscrapers/scraperplugins/wrzcraft.py | TheWardoctor/wardoctors-repo | 893f646d9e27251ffc00ca5f918e4eb859a5c8f0 | [
"Apache-2.0"
] | 1 | 2019-03-05T09:37:15.000Z | 2019-03-05T09:37:15.000Z | script.module.nanscrapers/lib/nanscrapers/scraperplugins/wrzcraft.py | TheWardoctor/wardoctors-repo | 893f646d9e27251ffc00ca5f918e4eb859a5c8f0 | [
"Apache-2.0"
] | null | null | null | script.module.nanscrapers/lib/nanscrapers/scraperplugins/wrzcraft.py | TheWardoctor/wardoctors-repo | 893f646d9e27251ffc00ca5f918e4eb859a5c8f0 | [
"Apache-2.0"
] | 1 | 2021-11-05T22:16:08.000Z | 2021-11-05T22:16:08.000Z | # -*- coding: utf-8 -*-
'''
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re,urllib,urlparse,random
from BeautifulSoup import BeautifulSoup
from ..common import clean_title, random_agent, clean_search, replaceHTMLCodes, filter_host, get_rd_domains
from ..scraper import Scraper
import requests
import xbmc
class Wzrcraft(Scraper):
domains = ['wzrcraft.net']
name = "wzrcraft"
def __init__(self):
self.domains = ['wrzcraft.net']
self.base_link = 'http://wrzcraft.net'
self.search_link = '/search/%s+%s/feed/rss2/'
def scrape_movie(self, title, year, imdb, debrid=False):
try:
if not debrid:
return []
url = self.movie(imdb, title, year)
sources = self.sources(url, [], [])
for source in sources:
source["scraper"] = source["provider"]
return sources
except:
return []
def scrape_episode(self, title, show_year, year, season, episode,
imdb, tvdb, debrid=False):
try:
if not debrid:
return []
show_url = self.tvshow(imdb, tvdb, title, show_year)
url = self.episode(show_url, imdb, tvdb, title,
year, season, episode)
sources = self.sources(url, [], [])
for source in sources:
source["scraper"] = source["provider"]
return sources
except:
return []
def movie(self, imdb, title, year):
self.elysium_url = []
try:
title = clean_search(title)
cleanmovie = clean_title(title)
titlecheck = cleanmovie+year
query = self.search_link % (
urllib.quote_plus(title.replace("'", "")), year)
query = urlparse.urljoin(self.base_link, query)
print ("WRZCRAFT QUERY", query)
r = requests.get(query).content
posts = parse_dom(r, 'item')
for post in posts:
try:
t = parse_dom(post, 'title')[0]
t = t.encode('utf-8')
check = clean_title(t)
if titlecheck not in check:
continue
c = parse_dom(post, 'content.+?')[0]
u = parse_dom(c, 'p')
u = [parse_dom(i, 'a', ret='href') for i in u]
u = [i[0] for i in u if len(i) == 1]
if not u:
raise Exception()
u = [(t, i) for i in u]
self.elysium_url += u
# self.elysium_url.append([links,t])
except:
pass
print ("WRZCRAFT PASSED", self.elysium_url)
return self.elysium_url
except:
return
def tvshow(self, imdb, tvdb, tvshowtitle, year):
try:
url = {'tvshowtitle': tvshowtitle, 'year': year}
url = urllib.urlencode(url)
return url
except:
return
def episode(self, url, imdb, tvdb, title, premiered, season, episode):
self.elysium_url = []
try:
data = urlparse.parse_qs(url)
data = dict([(i, data[i][0]) if data[i] else (i, '') for i in data])
title = data['tvshowtitle'] if 'tvshowtitle' in data else data['title']
title = clean_search(title)
cleanmovie = clean_title(title)
data['season'], data['episode'] = season, episode
episodecheck = 'S%02dE%02d' % (int(data['season']), int(data['episode']))
episodecheck = episodecheck.lower()
titlecheck = cleanmovie+episodecheck
query = 'S%02dE%02d' % (int(data['season']), int(data['episode']))
query = self.search_link % (
urllib.quote_plus(title.replace("'", "")), query)
query = urlparse.urljoin(self.base_link, query)
print ("WRZCRAFT SHOW", query)
r = requests.get(query).content
posts = parse_dom(r, 'item')
for post in posts:
try:
t = parse_dom(post, 'title')[0]
t = t.encode('utf-8')
check = clean_title(t)
if titlecheck not in check:
continue
c = parse_dom(post, 'content.+?')[0]
u = parse_dom(c, 'p')
u = [parse_dom(i, 'a', ret='href') for i in u]
u = [i[0] for i in u if len(i) == 1]
if not u:
raise Exception()
u = [(t, i) for i in u]
self.elysium_url += u
except:
pass
print ("WRZCRAFT PASSED", self.elysium_url)
return self.elysium_url
except:
return
def sources(self, url, hostDict, hostprDict):
try:
sources = []
for title, url in self.elysium_url:
quality = "SD"
quality = quality_tag(title)
if "1080p" in url.lower():
quality = "1080p"
elif "720p" in url.lower():
quality = "HD"
info = ''
if "hevc" in title.lower():
info = "HEVC"
loc = urlparse.urlparse(url).netloc
if not filter_host(loc):
rd_domains = get_rd_domains()
if loc not in rd_domains:
continue
try:
host = re.findall('([\w]+[.][\w]+)$', urlparse.urlparse(url.strip().lower()).netloc)[0]
except:
host = 'Videomega'
url = replaceHTMLCodes(url)
url = url.encode('utf-8')
sources.append({'source': host, 'quality': quality,
'provider': 'Wrzcraft', 'url': url,
'info': info, 'direct': False,
'debridonly': True})
return sources
except:
return sources
def resolve(self, url):
return url
def _getDOMContent(html, name, match, ret):
end_str = "</%s" % (name)
start_str = '<%s' % (name)
start = html.find(match)
end = html.find(end_str, start)
pos = html.find(start_str, start + 1)
while pos < end and pos != -1: # Ignore too early </endstr> return
tend = html.find(end_str, end + len(end_str))
if tend != -1:
end = tend
pos = html.find(start_str, pos + 1)
if start == -1 and end == -1:
result = ''
elif start > -1 and end > -1:
result = html[start + len(match):end]
elif end > -1:
result = html[:end]
elif start > -1:
result = html[start + len(match):]
else:
result = ''
if ret:
endstr = html[end:html.find(">", html.find(end_str)) + 1]
result = match + result + endstr
return result
def _getDOMAttributes(match, name, ret):
pattern = '''<%s[^>]* %s\s*=\s*(?:(['"])(.*?)\\1|([^'"].*?)(?:>|\s))''' % (name, ret)
results = re.findall(pattern, match, re.I | re.M | re.S)
return [result[1] if result[1] else result[2] for result in results]
def _getDOMElements(item, name, attrs):
if not attrs:
pattern = '(<%s(?: [^>]*>|/?>))' % (name)
this_list = re.findall(pattern, item, re.M | re.S | re.I)
else:
last_list = None
for key in attrs:
pattern = '''(<%s [^>]*%s=['"]%s['"][^>]*>)''' % (name, key, attrs[key])
this_list = re.findall(pattern, item, re.M | re. S | re.I)
if not this_list and ' ' not in attrs[key]:
pattern = '''(<%s [^>]*%s=%s[^>]*>)''' % (name, key, attrs[key])
this_list = re.findall(pattern, item, re.M | re. S | re.I)
if last_list is None:
last_list = this_list
else:
last_list = [item for item in this_list if item in last_list]
this_list = last_list
return this_list
def parse_dom(html, name='', attrs=None, ret=False):
if attrs is None:
attrs = {}
if isinstance(html, str):
try:
html = [html.decode("utf-8")] # Replace with chardet thingy
except:
print "none"
try:
html = [html.decode("utf-8", "replace")]
except:
html = [html]
elif isinstance(html, unicode):
html = [html]
elif not isinstance(html, list):
return ''
if not name.strip():
return ''
if not isinstance(attrs, dict):
return ''
ret_lst = []
for item in html:
for match in re.findall('(<[^>]*\n[^>]*>)', item):
item = item.replace(match, match.replace('\n', ' ').replace('\r', ' '))
lst = _getDOMElements(item, name, attrs)
if isinstance(ret, str):
lst2 = []
for match in lst:
lst2 += _getDOMAttributes(match, name, ret)
lst = lst2
else:
lst2 = []
for match in lst:
temp = _getDOMContent(item, name, match, ret).strip()
item = item[item.find(temp, item.find(match)):]
lst2.append(temp)
lst = lst2
ret_lst += lst
# log_utils.log("Done: " + repr(ret_lst), xbmc.LOGDEBUG)
return ret_lst
def quality_tag(txt):
if any(value in txt for value in ['1080', '1080p','1080P']):
quality = "1080p"
elif any(value in txt for value in ['720', '720p','720P']):
quality = "HD"
else:
quality = "SD"
return quality
| 33.484076 | 107 | 0.494769 |
043927b6fdbc6e4cc830f3d803f908b1c56faff0 | 11,200 | py | Python | main.py | Shamos99/supahands-coding-test | 12e6ba7b811ad550c69273f017300f23fcf53c70 | [
"MIT"
] | null | null | null | main.py | Shamos99/supahands-coding-test | 12e6ba7b811ad550c69273f017300f23fcf53c70 | [
"MIT"
] | null | null | null | main.py | Shamos99/supahands-coding-test | 12e6ba7b811ad550c69273f017300f23fcf53c70 | [
"MIT"
] | null | null | null | import copy
class Constants:
"""
I don't think its needed for a project of this scale, but its the "right" way of doing this and I'm, a good boy
I would normally put these in a separate constants.py file, but I want to keep the entire solution in one file so yeah
"""
DEFAULT_STAM = 3
DEFAULT_BOAR = 3
DEFAULT_STAM_REGEN = 2
GROUP_KILL_STAM_DRAIN = 1
SOLO_KILL_STAM_DRAIN = 2
class Intent:
"""
Utility class with a few flags for determining hunter actions
"""
REST = 0
HUNT_SOLO = 1
HUNT_GROUP = 2
MOVE = 3
class Node:
"""
Represents each node on the map, along with some useful methods
"""
def __init__(self, idx):
self._idx = idx # index of the node in an adjacency list representation of the map (which is a graph)
self.boars = Constants.DEFAULT_BOAR
self.active_players = []
def __eq__(self, other):
if isinstance(other, Node):
return self._idx == other._idx
return False
def __ne__(self, other):
return not self.__eq__(other)
def get_alphabetical_representation(self):
"""
Returns the original alphabet representing this node
"""
return chr(self._idx + 65)
def boar_hunted(self):
self.boars -= 1
def has_game(self):
return self.boars > 0
def player_entered(self, player):
self.active_players.append(player)
def player_exiting(self, player):
self.active_players.remove(player)
def has_multiple_active_players(self):
return len(self.active_players) > 1
def group_kill_possibility(self, player):
"""
For a player to find out if someone else can perform a group kill with them
"""
for hunter in self.active_players:
if player != hunter and hunter.stamina >= Constants.GROUP_KILL_STAM_DRAIN:
return True
return False
class Hunter:
"""
Represents the player in this program.
"""
def __init__(self, name, path):
self.name = name
self.path = path # list of nodes representing the path this hunter will take
self.stamina = Constants.DEFAULT_STAM
self.cur_node_idx = 0
self.get_cur_node().player_entered(self)
def __eq__(self, other):
if isinstance(other, Hunter):
return self.name == other.name
return False
def __ne__(self, other):
return not self.__eq__(other)
def reduce_stamina(self, n):
self.stamina = (self.stamina - n) % Constants.DEFAULT_STAM
def increase_stamina(self, n):
self.stamina = (self.stamina + n) % Constants.DEFAULT_STAM
def get_cur_node(self):
return self.path[self.cur_node_idx]
def rest(self):
self.increase_stamina(Constants.DEFAULT_STAM_REGEN)
def in_the_choppa(self):
"""
To know if they listened to Arnold and GOT TO THE CHOPAAA
"""
return self.get_cur_node() == self.path[-1] and not self.get_cur_node().has_game()
def hunt_solo(self):
self.reduce_stamina(Constants.SOLO_KILL_STAM_DRAIN)
def hunt_group(self):
self.reduce_stamina(Constants.GROUP_KILL_STAM_DRAIN)
def traverse(self):
"""
Move on to the next node
"""
self.get_cur_node().player_exiting(self)
self.cur_node_idx += 1
self.get_cur_node().player_entered(self)
self.reduce_stamina(1)
def can_group_hunt(self):
if self.get_cur_node().has_game() and self.get_cur_node().group_kill_possibility(
self) and self.stamina >= Constants.GROUP_KILL_STAM_DRAIN:
return True
return False
def can_solo_hunt(self):
if self.get_cur_node().has_game() and self.stamina >= Constants.SOLO_KILL_STAM_DRAIN:
return True
return False
def play_turn(self):
"""
This is called for the hunter each turn for them to handle their own logic, and return an Intent Flag
representing what they want to do that turn
This can be modified ofc for different behaviors
"""
if self.can_group_hunt():
return Intent.HUNT_GROUP
elif self.can_solo_hunt():
return Intent.HUNT_SOLO
elif not self.get_cur_node().has_game() and self.stamina >= Constants.GROUP_KILL_STAM_DRAIN and not self.in_the_choppa():
return Intent.MOVE
else:
return Intent.REST
class Map:
"""
Represents the game world
"""
def __init__(self, raw_hunting_map):
self.adjacency_list = self._convert_to_adjacency_list(raw_hunting_map)
self.nodes = [Node(idx) for idx in range(len(self.adjacency_list))]
def _convert_to_adjacency_list(self, raw_hunting_map):
"""
converts the raw representation to an adjacency list
assumes that nodes are alphabets starting from 'A'
"""
adjacency_list = [] * len(raw_hunting_map)
for key in raw_hunting_map:
adjacency_list.append([])
for adjacent_vertex in raw_hunting_map[key]:
adjacency_list[-1].append(ord(adjacent_vertex) - 65)
return adjacency_list
def _gen_optimal_path(self, visited):
"""
This will return to us the path (represented as a list of node indices) that given the current state of
the "visited" list, maximises the number of new nodes visited.
The path will start from node "A" and end with node "K"
The algo works using BFS
"""
queue = [(0, visited[0], [self.nodes[0]])]
best_path = queue[0]
while len(queue) > 0:
vertex, n_unique_nodes, path = queue.pop()
if n_unique_nodes > best_path[1] or len(path) > len(best_path[2]):
best_path = (vertex, n_unique_nodes, path)
for adjacent_node in self.adjacency_list[vertex]:
path_copy = copy.copy(path)
path_copy.append(self.nodes[adjacent_node])
queue.append((adjacent_node, n_unique_nodes + visited[adjacent_node], path_copy))
return best_path
def get_n_paths(self, n):
"""
Return n paths where the number of unique nodes across paths is maximised
Called to initialise the paths for the players of the game
Essentially gives us the path each of the n players can follow to maximise nodes visited, in turm maximising
boars hunted
Ofc they path does not have to be the optimal one for board hunting, maybe the players chicken out and wanna
get out ASAP. That logic can be altered here ofc but I like boar so yeah :p
"""
visited = [1] * len(self.nodes) # assign a "score/weight" to each vertex
paths = []
for _ in range(n):
vertex, n_unique_nodes, path = self._gen_optimal_path(visited)
paths.append(path)
# for this new path, mark the corresponding nodes as visited, by changing their value to 0
for node in path:
visited[node._idx] = 0
return paths
class Game:
"""
This will actually setup and run the game, and is in charge of carrying out players intents
"""
def __init__(self, raw_hunting_map, player_list):
"""
:param raw_hunting_map: a dict representing an graph, with nodes represented as alphabets from 'A' to 'K'
ex {'A':['B' ....]}
:param player_list: list of names (string) representing the players of this game
"""
self.map = Map(raw_hunting_map)
# now need to init players with paths
self.players = [Hunter(name, path) for name, path in
zip(player_list, self.map.get_n_paths(len(player_list)))]
self.kill_count = 0
self.combined_paths = self._get_combined_paths()
def _get_combined_paths(self):
"""
Each players path may not be the same, and the final output requires the final path to be printed onto a
single line, so this will essentially let us know of all nodes visited sequentially as a whole
so if the two paths are: ['A', 'B', 'C'] and ['A', 'D', 'C']
the output will be something like ['A', 'B', 'D', 'C']
yes I know this function looks ugly I don't like it either
"""
combined_paths = []
path_1 = self.players[0].path
path_2 = self.players[1].path
for i in range(max(len(path_1), len(path_2))):
if i < len(path_1) and i < len(path_2):
if path_1[i] == path_2[i]:
combined_paths.append(path_1[i].get_alphabetical_representation())
else:
combined_paths.append(path_1[i].get_alphabetical_representation())
combined_paths.append(path_2[i].get_alphabetical_representation())
continue
if i < len(path_1):
combined_paths.append(path_1[i].get_alphabetical_representation())
if i < len(path_2):
combined_paths.append(path_2[i].get_alphabetical_representation())
return combined_paths
def _game_ended(self):
for player in self.players:
if not player.in_the_choppa():
return False
return True
def run(self):
n_turns = 0
# main program loop, run until everyone got to the CHOPPAAA
while not self._game_ended():
# get each players intent and try to accommodate their request
for player in self.players:
intent = player.play_turn()
if intent == Intent.HUNT_GROUP:
# if this guy wants to hunt as a group we will grant this request, perform the group kill
# and move on to the next turn, yes I know this won't work if
# we have >2 players (we are making a hard assumption
# that that is the case), but the requirement is 2 players so yeah
for hunter in self.players:
hunter.hunt_group()
self.players[0].get_cur_node().boar_hunted()
self.kill_count += 1
elif intent == Intent.HUNT_SOLO:
player.hunt_solo()
self.kill_count += 1
player.get_cur_node().boar_hunted()
elif intent == Intent.REST:
player.rest()
elif intent == Intent.MOVE:
player.traverse()
n_turns += 1
def main():
prey = 0
hunting_map = {
'A': ['B', 'C', 'K'],
'B': ['D', 'E'],
'C': ['E', 'G', 'H'],
'D': ['E', 'F'],
'E': ['G', 'I', 'F'],
'F': ['I', 'J'],
'G': ['I', 'K'],
'H': ['I', 'F'],
'I': ['K'],
'J': ['K'],
'K': []
}
# init out game with
game = Game(hunting_map, ["Dutch", "Dylan"])
game.run()
# print the required output
print(game.kill_count)
print(game.combined_paths)
if __name__ == '__main__':
main()
| 33.333333 | 129 | 0.599196 |
5e583f8102fe03db4adda1c922704a51e9376f0b | 13,861 | py | Python | pyiron_base/generic/units.py | pyiron/pyiron_base | 3f62c6c59b90b774a04a61dd6d8a461fc6ef5bd1 | [
"BSD-3-Clause"
] | 7 | 2020-09-12T11:01:09.000Z | 2022-03-01T20:59:46.000Z | pyiron_base/generic/units.py | pyiron/pyiron_base | 3f62c6c59b90b774a04a61dd6d8a461fc6ef5bd1 | [
"BSD-3-Clause"
] | 417 | 2018-07-03T12:44:00.000Z | 2022-03-31T14:25:31.000Z | pyiron_base/generic/units.py | pyiron/pyiron_base | 3f62c6c59b90b774a04a61dd6d8a461fc6ef5bd1 | [
"BSD-3-Clause"
] | 8 | 2018-04-03T05:21:07.000Z | 2021-12-27T09:55:19.000Z | # coding: utf-8
# Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department
# Distributed under the terms of "New BSD License", see the LICENSE file.
import functools
import numpy as np
import pint
Q_ = pint.Quantity
__author__ = "Sudarsan Surendralal"
__copyright__ = (
"Copyright 2021, Max-Planck-Institut für Eisenforschung GmbH - "
"Computational Materials Design (CM) Department"
)
class PyironUnitRegistry:
"""
Module to record units for physical quantities within pyiron. This module is used for defining the units
for different pyiron submodules.
Useage:
>>> import pint
>>> from pyiron_base.generic.units import PyironUnitRegistry
>>> pint_registry = pint.UnitRegistry()
After instantiating, the `pint` units for different physical quantities can be registered as follows
>>> base_registry = PyironUnitRegistry()
>>> base_registry.add_quantity(quantity="energy", unit=pint_registry.eV, data_type=float)
Labels corresponding to a particular physical quantity can also be registered
>>> base_registry.add_labels(labels=["energy_tot", "energy_pot"], quantity="energy")
For more information on working with `pint`, see: https://pint.readthedocs.io/en/0.10.1/tutorial.html
"""
def __init__(self):
"""
Attributes:
self.quantity_dict
self.unit_dict
self.dtype_dict
"""
self._quantity_dict = dict()
self._dtype_dict = dict()
self._unit_dict = dict()
@property
def quantity_dict(self):
"""
A dictionary of the different labels stored and the physical quantity they correspond to
Returns:
dict
"""
return self._quantity_dict
@property
def dtype_dict(self):
"""
A dictionary of the names of the different physical quantities to the corresponding datatype in which they are
to be stored
Returns:
dict
"""
return self._dtype_dict
@property
def unit_dict(self):
"""
A dictionary of the different physical quantities and the corresponding `pint` unit
Returns:
dict
"""
return self._unit_dict
def add_quantity(self, quantity, unit, data_type=float):
"""
Add a quantity to a registry
Args:
quantity (str): The physical quantity
unit (pint.unit.Unit/pint.quantity.Quantity): `pint` unit or quantity
data_type (type): Data type in which the quantity has to be stored
"""
if not isinstance(unit, (pint.unit.Unit, pint.quantity.Quantity)):
raise ValueError("The unit should be a `pint` unit or quantity")
self._unit_dict[quantity] = unit
self._dtype_dict[quantity] = data_type
def add_labels(self, labels, quantity):
"""
Maps quantities with different labels to quantities already defined in the registry
Args:
labels (list/ndarray): List of labels
quantity (str): Physical quantity associated with the labels
Raises:
KeyError: If quantity is not yet added with :method:`.add_quantity()`
Note: `quantity` should already be a key of unit_dict
"""
for label in labels:
if quantity in self.unit_dict.keys():
self._quantity_dict[label] = quantity
else:
raise KeyError("Quantity {} is not defined. "
"Use `add_quantity` to register the unit of this label".format(quantity))
def __getitem__(self, item):
"""
Getter to return corresponding `pint` unit for a given quantity
Args:
item (str):
Returns:
pint.unit.Unit/pint.quantity.Quantity: The corresponding `pint` unit/quantity
Raises:
KeyError: If quantity is not yet added with :method:`.add_quantity()` or :method:`.add_labels()`
"""
if item in self._unit_dict.keys():
return self._unit_dict[item]
elif item in self._quantity_dict.keys():
return self._unit_dict[self._quantity_dict[item]]
else:
raise KeyError("Quantity/label '{}' not registered in this unit registry".format(item))
def get_dtype(self, quantity):
"""
Returns the data type in which the quantity will be stored
Args:
quantity (str): The quantity
Returns:
type: Corresponding data type
Raises:
KeyError: If quantity is not yet added with :method:`.add_quantity()` or :method:`.add_labels()`
"""
if quantity in self._unit_dict.keys():
return self._dtype_dict[quantity]
elif quantity in self._quantity_dict.keys():
return self._dtype_dict[self._quantity_dict[quantity]]
else:
raise KeyError("Quantity/label '{}' not registered in this unit registry".format(quantity))
class UnitConverter:
"""
Module to handle conversions between two different unit registries mainly use to convert units between codes and
pyiron submodules.
To instantiate this class, you need two units registries: a base units registry and a code registry:
>>> import pint
>>> pint_registry = pint.UnitRegistry()
>>> base = PyironUnitRegistry()
>>> base.add_quantity(quantity="energy", unit=pint_registry.eV)
>>> code = PyironUnitRegistry()
>>> code.add_quantity(quantity="energy",
... unit=pint_registry.kilocal / (pint_registry.mol * pint_registry.N_A))
>>> unit_converter = UnitConverter(base_registry=base, code_registry=code)
The unit converter instance can then be used to obtain conversion factors between code and base units either as a
`pint` quantity:
>>> print(unit_converter.code_to_base_pint("energy"))
0.04336410424180094 electron_volt
or as a scalar:
>>> print(unit_converter.code_to_base_value("energy"))
0.04336410424180094
Alternatively, the unit converter can also be used as decorators for functions that return an array scaled into
appropriate units:
>>> @unit_converter.code_to_base(quantity="energy")
... def return_ones():
... return np.ones(5)
>>> print(return_ones())
[0.0433641 0.0433641 0.0433641 0.0433641 0.0433641]
The decorator can also be used to assign units for numpy arrays
(for more info see https://pint.readthedocs.io/en/0.10.1/numpy.html)
>>> @unit_converter.base_units(quantity="energy")
... def return_ones_ev():
... return np.ones(5)
>>> print(return_ones_ev())
[1.0 1.0 1.0 1.0 1.0] electron_volt
"""
def __init__(self, base_registry, code_registry):
"""
Args:
base_registry (:class:`pyiron_base.generic.units.PyironUnitRegistry`): Base unit registry
code_registry (:class:`pyiron_base.generic.units.PyironUnitRegistry`): Code specific unit registry
"""
self._base_registry = base_registry
self._code_registry = code_registry
self._check_quantities()
self._check_dimensionality()
def _check_quantities(self):
base_quant = list(self._base_registry.unit_dict.keys())
for quant in self._code_registry.unit_dict.keys():
if quant not in base_quant:
raise ValueError("quantity {} is not defined in the base registry".format(quant))
def _check_dimensionality(self):
for quant in self._code_registry.unit_dict.keys():
if not self._base_registry[quant].dimensionality == self._code_registry[quant].dimensionality:
raise pint.DimensionalityError(self._base_registry[quant], self._code_registry[quant],
extra_msg="\n Dimensional inequality: Quantity {} has dimensionality {} "
"in the base registry but {} in the code "
"registry".format(quant,
self._base_registry[quant].dimensionality,
self._code_registry[quant].dimensionality))
def code_to_base_pint(self, quantity):
"""
Get the conversion factor as a `pint` quantity from code to base units
Args:
quantity (str): Name of quantity
Returns:
pint.quantity.Quantity: Conversion factor as a `pint` quantity
"""
return (1 * self._code_registry[quantity]).to(self._base_registry[quantity])
def base_to_code_pint(self, quantity):
"""
Get the conversion factor as a `pint` quantity from base to code units
Args:
quantity (str): Name of quantity
Returns:
pint.quantity.Quantity: Conversion factor as a `pint` quantity
"""
return (1 * self._base_registry[quantity]).to(self._code_registry[quantity])
def code_to_base_value(self, quantity):
"""
Get the conversion factor as a scalar from code to base units
Args:
quantity (str): Name of quantity
Returns:
float: Conversion factor as a float
"""
return self.code_to_base_pint(quantity).magnitude
def base_to_code_value(self, quantity):
"""
Get the conversion factor as a scalar from base to code units
Args:
quantity (str): Name of quantity
Returns:
float: Conversion factor as a float
"""
return self.base_to_code_pint(quantity).magnitude
def __call__(self, conversion, quantity):
"""
Function call operator used as a decorator for functions that return numpy array
Args:
conversion (str): Conversion type which should be one of
'code_to_base' To multiply by the code to base units conversion factor
'base_to_code' To multiply by the base to code units conversion factor
'code_units' To assign code units to the nunpy array returned by the decorated function
'base_units' To assign base units to the nunpy array returned by the decorated function
quantity (str): Name of quantity
Returns:
function: Decorated function
"""
if conversion == "code_to_base":
def _decorate_to_base(function):
@functools.wraps(function)
def dec(*args, **kwargs):
return np.array(function(*args, **kwargs) * self.code_to_base_value(quantity),
dtype=self._base_registry.get_dtype(quantity))
return dec
return _decorate_to_base
elif conversion == "base_to_code":
def _decorate_to_code(function):
@functools.wraps(function)
def dec(*args, **kwargs):
return np.array(function(*args, **kwargs) * self.base_to_code_value(quantity),
dtype=self._code_registry.get_dtype(quantity))
return dec
return _decorate_to_code
elif conversion == "base_units":
def _decorate_base_units(function):
@functools.wraps(function)
def dec(*args, **kwargs):
return Q_(np.array(function(*args, **kwargs), dtype=self._base_registry.get_dtype(quantity)),
self._base_registry[quantity])
return dec
return _decorate_base_units
elif conversion == "code_units":
def _decorate_code_units(function):
@functools.wraps(function)
def dec(*args, **kwargs):
return Q_(np.array(function(*args, **kwargs), dtype=self._code_registry.get_dtype(quantity)),
self._code_registry[quantity])
return dec
return _decorate_code_units
else:
raise ValueError("Conversion type {} not implemented!".format(conversion))
def code_to_base(self, quantity):
"""
Decorator for functions that returns a numpy array. Multiples the function output by the code to base units
conversion factor
Args:
quantity (str): Name of the quantity
Returns:
function: Decorated function
"""
return self(quantity=quantity, conversion="code_to_base")
def base_to_code(self, quantity):
"""
Decorator for functions that returns a numpy array. Multiples the function output by the base to code units
conversion factor
Args:
quantity (str): Name of the quantity
Returns:
function: Decorated function
"""
return self(quantity=quantity, conversion="base_to_code")
def code_units(self, quantity):
"""
Decorator for functions that returns a numpy array. Assigns the code unit of the quantity to the function output
Args:
quantity (str): Name of the quantity
Returns:
function: Decorated function
"""
return self(quantity=quantity, conversion="code_units")
def base_units(self, quantity):
"""
Decorator for functions that returns a numpy array. Assigns the base unit of the quantity to the function output
Args:
quantity (str): Name of the quantity
Returns:
function: Decorated function
"""
return self(quantity=quantity, conversion="base_units")
| 35.632391 | 120 | 0.614674 |
b2f318a25b3b3c40124fd3cc2f8848aa210fcdb9 | 8,603 | py | Python | azext_keyvault/keyvault/custom/http_message_security.py | jdmartinez36/azure-keyvault-cli-extension | 4dc674b9c30cac13e27347782c49b3ed7dca2e2f | [
"MIT"
] | 2 | 2019-06-12T13:44:34.000Z | 2020-06-01T13:24:04.000Z | azext_keyvault/keyvault/custom/http_message_security.py | jdmartinez36/azure-keyvault-cli-extension | 4dc674b9c30cac13e27347782c49b3ed7dca2e2f | [
"MIT"
] | 5 | 2018-04-26T01:14:29.000Z | 2021-01-05T00:45:39.000Z | azext_keyvault/keyvault/custom/http_message_security.py | jdmartinez36/azure-keyvault-cli-extension | 4dc674b9c30cac13e27347782c49b3ed7dca2e2f | [
"MIT"
] | 8 | 2018-04-24T22:52:48.000Z | 2021-11-16T06:29:28.000Z | #---------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
#---------------------------------------------------------------------------------------------
import json
import time
import os
from .internal import _a128cbc_hs256_encrypt, _a128cbc_hs256_decrypt, _JwsHeader, _JwsObject, \
_JweHeader, _JweObject, _str_to_b64url, _bstr_to_b64url, _b64_to_bstr, _RsaKey
def generate_pop_key():
"""
Generates a key which can be used for Proof Of Possession token authentication.
:return:
"""
return _RsaKey.generate()
class HttpMessageSecurity(object):
"""
Used for message authorization, encryption and decrtyption.
This class is intended for internal use only. Details are subject to non-compatible changes, consumers of the
azure-keyvault module should not take dependencies on this class or its current implementation.
"""
def __init__(self, client_security_token=None,
client_signature_key=None,
client_encryption_key=None,
server_signature_key=None,
server_encryption_key=None):
self.client_security_token = client_security_token
self.client_signature_key = client_signature_key
self.client_encryption_key = client_encryption_key
self.server_signature_key = server_signature_key
self.server_encryption_key = server_encryption_key
def protect_request(self, request):
"""
Adds authorization header, and encrypts and signs the request if supported on the specific request.
:param request: unprotected request to apply security protocol
:return: protected request with appropriate security protocal applied
"""
# Setup the auth header on the request
# Due to limitations in the service we hard code the auth scheme to 'Bearer' as the service will fail with any
# other scheme or a different casing such as 'bearer', once this is fixed the following line should be replaced:
# request.headers['Authorization'] = '{} {}'.format(auth[0], auth[1])
request.headers['Authorization'] = '{} {}'.format('Bearer', self.client_security_token)
# if the current message security doesn't support message protection, or the body is empty
# skip protection and return the original request
if not self.supports_protection() or len(request.body) == 0:
return request
plain_text = request.body
# if the client encryption key is specified add it to the body of the request
if self.client_encryption_key:
# note that this assumes that the body is already json and not simple string content
# this is true for all requests which currently support message encryption, but might
# need to be revisited when the types of
body_dict = json.loads(plain_text)
body_dict['rek'] = {'jwk': self.client_encryption_key.to_jwk().serialize()}
plain_text = json.dumps(body_dict).encode(encoding='utf8')
# build the header for the jws body
jws_header = _JwsHeader()
jws_header.alg = 'RS256'
jws_header.kid = self.client_signature_key.kid
jws_header.at = self.client_security_token
jws_header.ts = int(time.time())
jws_header.typ = 'PoP'
jws = _JwsObject()
jws.protected = jws_header.to_compact_header()
jws.payload = self._protect_payload(plain_text)
data = (jws.protected + '.' + jws.payload).encode('ascii')
jws.signature = _bstr_to_b64url(self.client_signature_key.sign(data))
request.headers['Content-Type'] = 'application/jose+json'
request.prepare_body(data=jws.to_flattened_jws(), files=None)
return request
def unprotect_response(self, response, **kwargs):
"""
Removes protection from the specified response
:param request: response from the key vault service
:return: unprotected response with any security protocal encryption removed
"""
body = response.content
# if the current message security doesn't support message protection, the body is empty, or the request failed
# skip protection and return the original response
if not self.supports_protection() or len(response.content) == 0 or response.status_code != 200:
return response
# ensure the content-type is application/jose+json
if 'application/jose+json' not in response.headers.get('content-type', '').lower():
raise ValueError('Invalid protected response')
# deserialize the response into a JwsObject, using response.text so requests handles the encoding
jws = _JwsObject().deserialize(body)
# deserialize the protected header
jws_header = _JwsHeader.from_compact_header(jws.protected)
# ensure the jws signature kid matches the key from original challenge
# and the alg matches expected signature alg
if jws_header.kid != self.server_signature_key.kid \
or jws_header.alg != 'RS256':
raise ValueError('Invalid protected response')
# validate the signature of the jws
data = (jws.protected + '.' + jws.payload).encode('ascii')
# verify will raise an InvalidSignature exception if the signature doesn't match
self.server_signature_key.verify(signature=_b64_to_bstr(jws.signature), data=data)
# get the unprotected response body
decrypted = self._unprotect_payload(jws.payload)
response._content = decrypted
response.headers['Content-Type'] = 'application/json'
return response
def supports_protection(self):
"""
Determines if the the current HttpMessageSecurity object supports the message protection protocol.
:return: True if the current object supports protection, otherwise False
"""
return self.client_signature_key \
and self.client_encryption_key \
and self.server_signature_key \
and self.server_encryption_key
def _protect_payload(self, plaintext):
# create the jwe header for the payload
kek = self.server_encryption_key
jwe_header = _JweHeader()
jwe_header.alg = 'RSA-OAEP'
jwe_header.kid = kek.kid
jwe_header.enc = 'A128CBC-HS256'
# create the jwe object
jwe = _JweObject()
jwe.protected = jwe_header.to_compact_header()
# generate the content encryption key and iv
cek = os.urandom(32)
iv = os.urandom(16)
jwe.iv = _bstr_to_b64url(iv)
# wrap the cek using the server encryption key
wrapped = _bstr_to_b64url(kek.encrypt(cek))
jwe.encrypted_key = wrapped
# encrypt the plaintext body with the cek using the protected header
# as the authdata to get the ciphertext and the authtag
ciphertext, tag = _a128cbc_hs256_encrypt(cek, iv, plaintext, jwe.protected.encode('ascii'))
jwe.ciphertext = _bstr_to_b64url(ciphertext)
jwe.tag = _bstr_to_b64url(tag)
# flatten and encode the jwe for the final jws payload content
flat = jwe.to_flattened_jwe()
return _str_to_b64url(flat)
def _unprotect_payload(self, payload):
# deserialize the payload
jwe = _JweObject().deserialize_b64(payload)
# deserialize the payload header
jwe_header = _JweHeader.from_compact_header(jwe.protected)
# ensure the kid matches the specified client encryption key
# and the key wrap alg and the data encryption enc match the expected
if self.client_encryption_key.kid != jwe_header.kid \
or jwe_header.alg != 'RSA-OAEP' \
or jwe_header.enc != 'A128CBC-HS256':
raise ValueError('Invalid protected response')
# unwrap the cek using the client encryption key
cek = self.client_encryption_key.decrypt(_b64_to_bstr(jwe.encrypted_key))
# decrypt the cipher text to get the unprotected body content
return _a128cbc_hs256_decrypt(cek,
_b64_to_bstr(jwe.iv),
_b64_to_bstr(jwe.ciphertext),
jwe.protected.encode('ascii'),
_b64_to_bstr(jwe.tag)) | 44.807292 | 120 | 0.654539 |
76e2cf3e2e3f13da61d00dd1332f195aba94446e | 157 | py | Python | py-env/bin/django-admin.py | ipmLessing/dj-cms | ed061e4c33a99f6505d19ce2e0cd54363aa62b0b | [
"MIT"
] | null | null | null | py-env/bin/django-admin.py | ipmLessing/dj-cms | ed061e4c33a99f6505d19ce2e0cd54363aa62b0b | [
"MIT"
] | 5 | 2020-06-06T01:00:13.000Z | 2021-06-09T18:49:18.000Z | py-env/bin/django-admin.py | ipmLessing/dj-cms | ed061e4c33a99f6505d19ce2e0cd54363aa62b0b | [
"MIT"
] | null | null | null | #!/home/kasengchou/git/dj-cms/py-env/bin/python3.6
from django.core import management
if __name__ == "__main__":
management.execute_from_command_line()
| 26.166667 | 50 | 0.770701 |
d92271cdc28aee2176b4be04f707808fdc195ea9 | 248 | py | Python | Ibis/settings.py | Ronkiro/Ibis | 40dbf0590ec098715ca7d6d16b6dc5a60f9ff5e5 | [
"MIT"
] | 1 | 2020-07-06T15:08:53.000Z | 2020-07-06T15:08:53.000Z | Ibis/settings.py | Ronkiro/Ibis | 40dbf0590ec098715ca7d6d16b6dc5a60f9ff5e5 | [
"MIT"
] | 1 | 2019-06-21T13:46:16.000Z | 2019-06-21T13:46:16.000Z | Ibis/settings.py | Ronkiro/Ibis | 40dbf0590ec098715ca7d6d16b6dc5a60f9ff5e5 | [
"MIT"
] | null | null | null | """ This file changes the global settings logic.
Do not do any changes here, unless you know what you
are doing.
"""
# Mode standard is 'f'
MODE='f'
FILE_TARGET='your file.ext' # Target file, where the software writes the buffer.
LOG=True
| 24.8 | 80 | 0.709677 |
03d455ddaf56eb3cf9e7b5582c16a6667bcb7108 | 3,080 | py | Python | tests/test_filters.py | Jmillan-Dev/drf-query-filter | e86c412996ba68f5dfa6edff7f46d15c6b87f56e | [
"MIT"
] | 4 | 2021-01-21T06:10:31.000Z | 2021-03-17T00:21:41.000Z | tests/test_filters.py | Jmillan-Dev/drf-query-filter | e86c412996ba68f5dfa6edff7f46d15c6b87f56e | [
"MIT"
] | null | null | null | tests/test_filters.py | Jmillan-Dev/drf-query-filter | e86c412996ba68f5dfa6edff7f46d15c6b87f56e | [
"MIT"
] | null | null | null | from django.db.models import Q
from django.test import TestCase
from rest_framework.exceptions import ValidationError
from drf_query_filter import fields, filters
from drf_query_filter.utils import ConnectorType
class SimpleView:
query_params = [
fields.IntegerField('id') & fields.ChoicesField('state', choices=['A', 'S', 'N']),
fields.Field('search', ['name__icontains', 'category__name'],
connector=ConnectorType.OR)
]
def __init__(self, raise_exceptions=False, **kwargs):
self.query_raise_exceptions = raise_exceptions
if 'query_params' in kwargs:
self.query_params = kwargs.get('query_params')
class FakeQuerySet:
def __init__(self):
self.query = list()
self.annotate = list()
def annotate(self, **kwargs):
self.annotate.append(kwargs)
return self
def filter(self, query):
self.query.append(query)
return self
class FakeRequest:
def __init__(self, **kwargs):
self.query_params = kwargs
class FilterTests(TestCase):
def test_with_normal_filter(self):
f = filters.QueryParamFilter()
queryset = FakeQuerySet()
view = SimpleView()
f.filter_queryset(
request=FakeRequest(id='10', state='A', search='simon jefa!'),
view=view, queryset=queryset
)
self.assertEqual(len(queryset.query), 2)
self.assertEqual(queryset.query[0], Q(id=10) & Q(state='A'))
self.assertEqual(
queryset.query[1],
Q(name__icontains='simon jefa!') | Q(category__name='simon jefa!')
)
queryset = FakeQuerySet()
f.filter_queryset(
request=FakeRequest(id='28', state='None'),
view=view, queryset=queryset
)
self.assertEqual(len(queryset.query), 1)
self.assertEqual(queryset.query[0], Q(id=28))
queryset = FakeQuerySet()
f.filter_queryset(
request=FakeRequest(search='sis'),
view=view, queryset=queryset
)
self.assertEqual(len(queryset.query), 1)
self.assertEqual(queryset.query[0],
Q(name__icontains='sis') | Q(category__name='sis'))
def test_with_filter_validations(self):
f = filters.QueryParamFilter()
queryset = FakeQuerySet()
with self.assertRaises(ValidationError):
f.filter_queryset(
request=FakeRequest(id='id', state='None', search=''),
view=SimpleView(raise_exceptions=True), queryset=queryset
)
with self.assertRaises(ValidationError):
f.filter_queryset(
request=FakeRequest(id='10', state='a'),
view=SimpleView(raise_exceptions=True), queryset=queryset
)
def test_with_no_query_param_fields(self):
f = filters.QueryParamFilter()
queryset = FakeQuerySet()
view = SimpleView(query_params=None)
f.filter_queryset(request=FakeRequest(ignore=True),view=view, queryset=queryset)
| 32.083333 | 90 | 0.621753 |
33ca08877b963a108c8a2866afef94d3e8686285 | 3,407 | py | Python | pyleecan/Methods/Simulation/Magnetics/store_output.py | BonneelP/pyleecan | 29e6b4358420754993af1a43048aa12d1538774e | [
"Apache-2.0"
] | 2 | 2020-08-28T14:54:55.000Z | 2021-03-13T19:34:45.000Z | pyleecan/Methods/Simulation/Magnetics/store_output.py | BonneelP/pyleecan | 29e6b4358420754993af1a43048aa12d1538774e | [
"Apache-2.0"
] | null | null | null | pyleecan/Methods/Simulation/Magnetics/store_output.py | BonneelP/pyleecan | 29e6b4358420754993af1a43048aa12d1538774e | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from numpy import mean, max as np_max, min as np_min
from SciDataTool import DataTime, VectorField, Data1D
from ....Functions.Winding.gen_phase_list import gen_name
def store_output(self, output, out_dict, axes_dict):
"""Store the standard outputs of Magnetics that are temporarily in out_dict as arrays into OutMag as Data object
Parameters
----------
self : Magnetic
a Magnetic object
output : Output
an Output object (to update)
out_dict : dict
Dict containing all magnetic quantities that have been calculated in comp_flux_airgap
axes_dict: {Data}
Dict of axes used for magnetic calculation
"""
# Get time axis
Time = axes_dict["Time"]
# Store airgap flux as VectorField object
# Axes for each airgap flux component
axis_list = [Time, axes_dict["Angle"]]
# Create VectorField with empty components
output.mag.B = VectorField(
name="Airgap flux density",
symbol="B",
)
# Radial flux component
if "Br" in out_dict:
output.mag.B.components["radial"] = DataTime(
name="Airgap radial flux density",
unit="T",
symbol="B_r",
axes=axis_list,
values=out_dict.pop("Br"),
)
# Tangential flux component
if "Bt" in out_dict:
output.mag.B.components["tangential"] = DataTime(
name="Airgap tangential flux density",
unit="T",
symbol="B_t",
axes=axis_list,
values=out_dict.pop("Bt"),
)
# Axial flux component
if "Bz" in out_dict:
output.mag.B.components["axial"] = DataTime(
name="Airgap axial flux density",
unit="T",
symbol="B_z",
axes=axis_list,
values=out_dict.pop("Bz"),
)
# Store electromagnetic torque over time, and global values: average, peak to peak and ripple
if "Tem" in out_dict:
Tem = out_dict.pop("Tem")
output.mag.Tem = DataTime(
name="Electromagnetic torque",
unit="Nm",
symbol="T_{em}",
axes=[axes_dict["Time_Tem"]],
values=Tem,
)
# Calculate average torque in Nm
output.mag.Tem_av = mean(Tem)
self.get_logger().debug("Average Torque: " + str(output.mag.Tem_av) + " N.m")
# Calculate peak to peak torque in absolute value Nm
output.mag.Tem_rip_pp = abs(np_max(Tem) - np_min(Tem)) # [N.m]
# Calculate torque ripple in percentage
if output.mag.Tem_av != 0:
output.mag.Tem_rip_norm = output.mag.Tem_rip_pp / output.mag.Tem_av # []
else:
output.mag.Tem_rip_norm = None
# Store stator winding flux and calculate electromotive force
if "Phi_wind_stator" in out_dict:
# Store stator winding flux
qs = self.parent.machine.stator.winding.qs
Phase = Data1D(
name="phase",
unit="",
values=gen_name(qs),
is_components=True,
)
output.mag.Phi_wind_stator = DataTime(
name="Stator Winding Flux",
unit="Wb",
symbol="Phi_{wind}",
axes=[Time, Phase],
values=out_dict.pop("Phi_wind_stator"),
)
# Electromotive force computation
output.mag.comp_emf()
| 30.150442 | 116 | 0.584679 |
6fd581f2984656586d1703779ad9b183265a64f3 | 721 | py | Python | HookerScraping/Class/Scraping.py | HookerMen/webscraping-challenge | 4eb2acf82be93d33f22c3340d4b6d0191a1c8d79 | [
"MIT"
] | null | null | null | HookerScraping/Class/Scraping.py | HookerMen/webscraping-challenge | 4eb2acf82be93d33f22c3340d4b6d0191a1c8d79 | [
"MIT"
] | null | null | null | HookerScraping/Class/Scraping.py | HookerMen/webscraping-challenge | 4eb2acf82be93d33f22c3340d4b6d0191a1c8d79 | [
"MIT"
] | null | null | null | import requests
from bs4 import BeautifulSoup
import re
# Unica super clase de la aplicación. Sirve como estructura para las siguientes clases
class Scraping(object):
# Recibe una URL
def __init__(self,url):
# Obtener la URL
self.__url = url
# Realizamos una petición y la respuesta la convertimos en texto.
self.__request = requests.get(self.__url).text
# Creamos un objeto de soup para realizar el web scraping formateando lo resultante como un fichero HTML.
self.__soup = BeautifulSoup(self.__request, 'html.parser')
# GETTER'S
@property
def url(self):
return self.__url
@property
def soup(self):
return self.__soup
| 31.347826 | 113 | 0.678225 |
d6f1e6711ea5735b811ed03983c8aa332571651d | 1,321 | py | Python | var/spack/repos/builtin/packages/r-statmod/package.py | varioustoxins/spack | cab0e4cb240f34891a6d753f3393e512f9a99e9a | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | var/spack/repos/builtin/packages/r-statmod/package.py | varioustoxins/spack | cab0e4cb240f34891a6d753f3393e512f9a99e9a | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 6 | 2022-01-08T08:41:11.000Z | 2022-03-14T19:28:07.000Z | var/spack/repos/builtin/packages/r-statmod/package.py | foeroyingur/spack | 5300cbbb2e569190015c72d0970d25425ea38647 | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | null | null | null | # Copyright 2013-2022 Lawrence Livermore National Security, LLC and other
# Spack Project Developers. See the top-level COPYRIGHT file for details.
#
# SPDX-License-Identifier: (Apache-2.0 OR MIT)
from spack import *
class RStatmod(RPackage):
"""Statistical Modeling
A collection of algorithms and functions to aid statistical modeling.
Includes limiting dilution analysis (aka ELDA), growth curve comparisons,
mixed linear models, heteroscedastic regression, inverse-Gaussian
probability calculations, Gauss quadrature and a secure convergence
algorithm for nonlinear models. Also includes advanced generalized linear
model functions including Tweedie and Digamma distributional families and a
secure convergence algorithm."""
homepage = "https://cloud.r-project.org/package=statmod"
url = "https://cloud.r-project.org/src/contrib/statmod_1.4.30.tar.gz"
list_url = "https://cloud.r-project.org/src/contrib/Archive/statmod"
version('1.4.35', sha256='de5e428f81c306849af47b9ae583362855e166b1da62893734f1154cb5b3f8fe')
version('1.4.32', sha256='2f67a1cfa66126e6345f8a40564a3077d08f1748f17cb8c8fb05c94ed0f57e20')
version('1.4.30', sha256='9d2c1722a85f53623a9ee9f73d835119ae22ae2b8ec7b50d675401e314ea641f')
depends_on('r@3.0.0:', type=('build', 'run'))
| 45.551724 | 96 | 0.769871 |
79ce24902b80a882e705eeed77b1dbd5be394d1e | 5,703 | py | Python | fltk/util/config/arguments.py | ReubenJ/fltk-testbed | 8b18ba0638af1e1d905343e9a52fbf522fc8303f | [
"BSD-2-Clause"
] | 2 | 2021-10-15T18:22:48.000Z | 2021-11-20T21:24:49.000Z | fltk/util/config/arguments.py | ReubenJ/fltk-testbed | 8b18ba0638af1e1d905343e9a52fbf522fc8303f | [
"BSD-2-Clause"
] | 1 | 2021-09-10T07:20:48.000Z | 2021-09-10T07:20:48.000Z | fltk/util/config/arguments.py | ReubenJ/fltk-testbed | 8b18ba0638af1e1d905343e9a52fbf522fc8303f | [
"BSD-2-Clause"
] | 45 | 2021-09-06T08:50:49.000Z | 2021-09-28T12:10:13.000Z | from argparse import Namespace
from dataclasses import dataclass
from typing import List, Tuple, Type, Dict, T
import torch.distributed as dist
import torch.nn
import fltk.nets as nets
from fltk.datasets import CIFAR10Dataset, FashionMNISTDataset, CIFAR100Dataset, MNIST
from fltk.datasets.dataset import Dataset
CLIENT_ARGS: List[Tuple[str, str, str, type]] = \
[("model", "md", "Which model to train", str),
("dataset", "ds", "Which dataset to train the model on", str),
("batch_size", "bs",
"Number that are 'batched' together in a single forward/backward pass during the optimization steps.", int),
("max_epoch", "ep",
"Maximum number of times that the 'training' set instances can be used during the optimization steps", int),
("learning_rate", "lr", "Factor to limit the step size that is taken during each gradient descent step.", float),
("decay", 'dc',
"Rate at which the learning rate decreases (i.e. the optimization takes smaller steps", float),
("loss", 'ls', "Loss function to use for optimization steps", str),
("optimizer", 'op', "Which optimizer to use during the training process", str)
]
@dataclass(frozen=True)
class LearningParameters:
model: str
dataset: str
batch_size: int
max_epoch: int
learning_rate: float
learning_decay: float
loss: str
optimizer: str
_available_nets = {
"CIFAR100RESNET": nets.Cifar100ResNet,
"CIFAR100VGG": nets.Cifar100VGG,
"CIFAR10CNN": nets.Cifar10CNN,
"CIFAR10RESNET": nets.Cifar10ResNet,
"FASHIONMNISTCNN": nets.FashionMNISTCNN,
"FASHIONMNISTRESNET": nets.FashionMNISTResNet
}
_available_data = {
"CIFAR10": CIFAR10Dataset,
"CIFAR100": CIFAR100Dataset,
"FASHIONMNIST": FashionMNISTDataset,
"MNIST": MNIST
}
_available_loss = {
"CROSSENTROPY": torch.nn.CrossEntropyLoss
}
_available_optimizer = {
"ADAM": torch.optim.SGD
}
@staticmethod
def __safe_get(lookup: Dict[str, T], keyword: str) -> T:
"""
Static function to 'safe' get elements from a dictionary, to prevent issues with Capitalization in the code.
@param lookup: Lookup dictionary to 'safe get' from.
@type lookup: dict
@param keyword: Keyword to 'get' from the Lookup dictionary.
@type keyword: str
@return: Lookup value from 'safe get' request.
@rtype: T
"""
safe_keyword = str.upper(keyword)
return lookup.get(safe_keyword)
def get_model_class(self) -> Type[torch.nn.Module]:
"""
Function to obtain the model class that was given via commandline.
@return: Type corresponding to the model that was passed as argument.
@rtype: Type[torch.nn.Module]
"""
return self.__safe_get(self._available_nets, self.model)
def get_dataset_class(self) -> Type[Dataset]:
"""
Function to obtain the dataset class that was given via commandline.
@return: Type corresponding to the dataset that was passed as argument.
@rtype: Type[Dataset]
"""
return self.__safe_get(self._available_data, self.dataset)
def get_loss(self) -> Type:
"""
Function to obtain the loss function Type that was given via commandline to be used during the training
execution.
@return: Type corresponding to the loss function that was passed as argument.
@rtype: Type
"""
return self.__safe_get(self._available_loss, self.loss)
def get_optimizer(self) -> Type[torch.optim.Optimizer]:
"""
Function to obtain the loss function Type that was given via commandline to be used during the training
execution.
@return: Type corresponding to the Optimizer to be used during training.
@rtype: Type[torch.optim.Optimizer]
"""
return self.__safe_get(self._available_optimizer, self.optimizer)
def extract_learning_parameters(args: Namespace) -> LearningParameters:
"""
Function to extract the learning hyper-parameters from the Namespace object for the passed arguments.
@param args: Namespace environment for running the Client.
@type args: Namespace
@return: Parsed learning parameters.
@rtype: LearningParameters
"""
model = args.model
dataset = args.dataset
batch_size = args.batch_size
epoch = args.max_epoch
lr = args.learning_rate
decay = args.decay
loss = args.loss
optimizer = args.optimizer
return LearningParameters(model, dataset, batch_size, epoch, lr, decay, loss, optimizer)
def create_extractor_parser(subparsers):
extractor_parser = subparsers.add_parser('extractor')
extractor_parser.add_argument('config', type=str)
def create_client_parser(subparsers) -> None:
client_parser = subparsers.add_parser('client')
client_parser.add_argument('config', type=str)
client_parser.add_argument('task_id', type=str)
# Add hyper-parameters
for long, short, hlp, tpe in CLIENT_ARGS:
client_parser.add_argument(f'-{short}', f'--{long}', type=tpe, help=hlp, required=True)
# Add parameter parser for backend
client_parser.add_argument('--backend', type=str, help='Distributed backend',
choices=[dist.Backend.GLOO, dist.Backend.NCCL, dist.Backend.MPI],
default=dist.Backend.GLOO)
def create_cluster_parser(subparsers) -> None:
cluster_parser = subparsers.add_parser('cluster')
cluster_parser.add_argument('config', type=str)
cluster_parser.add_argument('-l', '--local', type=bool, default=False)
| 37.032468 | 118 | 0.674733 |
4d16532806442ed808fead9f12e15e7cbebc4eb2 | 1,091 | py | Python | tests/test_make_charge_scalar.py | adelabriere/matchms | a580539e6db3f4f00e12097983b85b2d494159ba | [
"Apache-2.0"
] | 64 | 2020-06-22T14:59:21.000Z | 2022-03-30T00:50:13.000Z | tests/test_make_charge_scalar.py | adelabriere/matchms | a580539e6db3f4f00e12097983b85b2d494159ba | [
"Apache-2.0"
] | 561 | 2020-03-19T14:35:59.000Z | 2022-03-29T10:11:12.000Z | tests/test_make_charge_scalar.py | adelabriere/matchms | a580539e6db3f4f00e12097983b85b2d494159ba | [
"Apache-2.0"
] | 32 | 2020-05-06T07:35:59.000Z | 2022-03-10T09:03:45.000Z | import numpy
import pytest
from matchms import Spectrum
from matchms.filtering import make_charge_scalar
@pytest.mark.parametrize("input_charge, corrected_charge", [('+1', 1),
('1', 1),
(' 1 ', 1),
('-1', -1),
([-1, "stuff"], -1)])
def test_make_charge_scalar(input_charge, corrected_charge):
"""Test if example inputs are correctly converted"""
spectrum_in = Spectrum(mz=numpy.array([100, 200.]),
intensities=numpy.array([0.7, 0.1]),
metadata={'charge': input_charge})
spectrum = make_charge_scalar(spectrum_in)
assert(spectrum.get("charge") == corrected_charge), "Expected different charge integer"
def test_empty_spectrum():
spectrum_in = None
spectrum = make_charge_scalar(spectrum_in)
assert spectrum is None, "Expected different handling of None spectrum."
| 40.407407 | 91 | 0.528873 |
760f45fbebf8cf509c66720a8f8c9e8b328a7a58 | 1,053 | py | Python | nemo/collections/cv/__init__.py | ParikhKadam/NeMo | ee11f7c4666d410d91f9da33c61f4819ea625013 | [
"Apache-2.0"
] | 1 | 2021-06-23T19:24:47.000Z | 2021-06-23T19:24:47.000Z | nemo/collections/cv/__init__.py | ParikhKadam/NeMo | ee11f7c4666d410d91f9da33c61f4819ea625013 | [
"Apache-2.0"
] | 1 | 2020-06-11T00:54:42.000Z | 2020-06-11T00:54:42.000Z | nemo/collections/cv/__init__.py | ParikhKadam/NeMo | ee11f7c4666d410d91f9da33c61f4819ea625013 | [
"Apache-2.0"
] | 1 | 2019-11-20T00:51:38.000Z | 2019-11-20T00:51:38.000Z | # =============================================================================
# Copyright (c) 2020 NVIDIA. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# =============================================================================
from nemo.collections.cv.modules import *
from nemo.package_info import __version__ as nemo_version
# Set collection version equal to NeMo version.
__version__ = nemo_version
# Authorship.
__author__ = "NVIDIA Corporation"
# Set collection name.
__description__ = "Computer Vision collection"
| 37.607143 | 79 | 0.65717 |
addc0c2dd23100606fd61b087a419ffe95b62a92 | 25,059 | py | Python | main.py | shashi278/skyshare | 36c900abe48d4d6585cfb7b0ca4f36c48de4d47e | [
"MIT"
] | 1 | 2021-06-23T05:02:46.000Z | 2021-06-23T05:02:46.000Z | main.py | shashi278/skyshare | 36c900abe48d4d6585cfb7b0ca4f36c48de4d47e | [
"MIT"
] | null | null | null | main.py | shashi278/skyshare | 36c900abe48d4d6585cfb7b0ca4f36c48de4d47e | [
"MIT"
] | 1 | 2021-06-23T05:02:47.000Z | 2021-06-23T05:02:47.000Z | from kivy.app import App
from kivy.uix.button import Button
from kivy.uix.anchorlayout import AnchorLayout
from kivy.logger import Logger
from kivy.lang.builder import Builder
from kivy.properties import (
BooleanProperty,
ListProperty,
NumericProperty,
ObjectProperty,
OptionProperty,
StringProperty,
)
from kivy.uix.behaviors import ButtonBehavior
from kivy.animation import Animation
from kivy.clock import Clock, mainthread
from kivy.uix.recycleview.views import _clean_cache
from kivy.uix.screenmanager import SlideTransition
from kivyauth.google_auth import initialize_google, login_google, logout_google
from kivyauth.facebook_auth import initialize_fb, login_facebook, logout_facebook
from kivyauth.providers import login_providers
from jnius import autoclass, cast, JavaException
from android import python_act
from android.activity import bind as result_bind
from android.permissions import request_permissions, Permission, check_permission, PERMISSION_GRANTED
from android.runnable import run_on_ui_thread
from kivymd.app import MDApp
from kivymd.uix.button import RectangularElevationBehavior, MDRectangleFlatIconButton
from kivymd.theming import ThemableBehavior
from kivymd.uix.behaviors import RectangularRippleBehavior
from kivymd.uix.floatlayout import MDFloatLayout
from kivymd.uix.button import MDFlatButton
from kivymd.uix.dialog import MDDialog
import threading
import certifi
import siaskynet
import os
import time
os.environ['SSL_CERT_FILE']= certifi.where()
Intent= autoclass("android.content.Intent")
Activity= autoclass("android.app.Activity")
MediaStore= autoclass("android.provider.MediaStore$Images$Media")
Context= autoclass("android.content.Context")
Uri= autoclass("android.net.Uri")
CharSequence= autoclass('java.lang.CharSequence')
String = autoclass('java.lang.String')
Toast= autoclass('android.widget.Toast')
LayoutParams= autoclass('android.view.WindowManager$LayoutParams')
AndroidColor= autoclass('android.graphics.Color')
PICK_IMAGE=1019
RC_SIGN_IN=2029
context= python_act.mActivity
#Logger.info("Hahaha: {}".format(help(siaskynet)))
skynet= siaskynet
app_directory= "/storage/emulated/0/SkyShare"
download_directory= app_directory+"/downloads"
kv="""
ScreenManager:
LoginScreen:
id: login_screen
UploadScreen:
id: upload_screen
DownloadScreen:
id: download_screen
<LoginScreen@Screen>:
name:"loginscreen"
canvas:
Color:
rgba: 1,1,1,.3
Rectangle:
pos: self.x, max(root.width, root.height)/2 - min(root.width, root.height)/2
size: min(root.width, root.height), min(root.width, root.height)
source: "skynet_logo_big.png"
BoxLayout:
pos_hint: {"center_x":.5, "center_y":.5}
orientation:"vertical"
BoxLayout:
size_hint_y: None
height: self.minimum_height
MDToolbar:
title:"SkyShare"
elevation: 10
right_action_items: [["information-outline", lambda x: None]]
BoxLayout:
size_hint_y: None
height: self.minimum_height+dp(50)
padding: 0,dp(60),0,0
MDLabel:
text: "Continue SkyShare with"
halign:"center"
bold:True
theme_text_color:"Custom"
text_color: .2,.2,.2,.7
BoxLayout:
orientation:"vertical"
LoginButton:
text: "Google"
icon: "google"
text_color: 1,1,1,1
can_color: 66/255, 133/255, 244/255, 1
release_action: app.gl_login
LoginButton:
text: "Facebook"
icon: "facebook-box"
text_color: 1,1,1,1
can_color: 59/255, 89/255, 152/255, 1
release_action: app.fb_login
BoxLayout:
size_hint_y: None
height: self.minimum_height+dp(50)
MDLabel:
text:"---or---"
halign: "center"
bold:True
theme_text_color:"Custom"
text_color: .2,.2,.2,.7
BoxLayout:
size_hint_y:None
height: self.minimum_height+dp(50)
padding: 0,dp(30),0,0
LoginButton:
text: "As Guest"
icon: "account-circle"
text_color: 1,1,1,1
can_color: app.theme_cls.primary_color
release_action: app.guest_login
Widget:
<LoginButton@AnchorLayout>:
text:""
icon: ""
text_color: [0,0,0,1]
can_color: 1,1,1,1
release_action: print
RectangleRaisedIconButton:
elevation:8
width: dp(150)
height: dp(50)
canvas.before:
Color:
rgba: root.can_color
Rectangle:
pos: self.pos
size: self.size
icon: root.icon
text: root.text
font_size: dp(8)
text_color: root.text_color
halign: "center"
on_release:
if root.release_action: root.release_action()
<UploadScreen@Screen>:
name:"upload_screen"
BoxLayout:
pos_hint: {"center_x":.5, "center_y":.5}
orientation: "vertical"
MDToolbar:
title: "Upload Images"
elevation: 10
left_action_items: [["menu", lambda x: None]]
right_action_items: [["download", lambda x: app.change_screen('download_screen')],["plus", lambda x: app.add_image()]]
# RecycleView:
# id:rv
# viewclass: 'SmartTiles'
# #data: [{'source':"https://i.ibb.co/cbQQcmz/chat.png"}]
# # {'source':"/storage/emulated/0/DCIM/Camera/IMG_20200722_114758.jpg"},\
# # {'source': "/storage/emulated/0/DCIM/Camera/IMG_20200722_115751.jpg"},\
# # {'source': "/storage/emulated/0/DCIM/Camera/IMG_20200722_114758.jpg"}\
# # ]
# RecycleGridLayout:
# default_size: None, (root.width-dp(16))/3
# default_size_hint: 1, None
# size_hint_y: None
# height: self.minimum_height
# cols: 3
# padding: dp(4), dp(4)
# spacing: dp(4)
ScrollView:
MDGridLayout:
id: grid
cols: 2
adaptive_height: True
padding: dp(4), dp(4)
spacing: dp(4)
<DownloadScreen@Screen>:
name:"download_screen"
on_enter:
app.create_download_directory()
BoxLayout:
pos_hint: {"center_x":.5, "center_y":.5}
orientation: "vertical"
MDToolbar:
title: "Download Images"
elevation: 10
left_action_items: [["menu", lambda x: None]]
right_action_items: [["upload", lambda x: app.change_screen('upload_screen')], ["plus", lambda x: app.show_link_popup()]]
ScrollView:
MDGridLayout:
id: grid
cols: 2
adaptive_height: True
padding: dp(4), dp(4)
spacing: dp(4)
<SmartTiles>
_img_widget: img
_img_overlay: img_overlay
_box_overlay: box
tile_no: 0
size_hint_y: None
height: self.width
on_release:
app.tiles_touched(self) if root.upload_done else None
FitImage:
id: img
source: root.source
x: root.x
y: root.y if root.overlap or root.box_position == 'header' else box.top
BoxLayout:
id: img_overlay
size_hint: img.size_hint
size: img.size
pos: img.pos
MDFloatLayout:
orientation: "vertical"
id: box
md_bg_color: [0,0,0, root.box_color_alpha]
x: root.x
y: root.y
BoxLayout:
pos_hint: {"center_x":.5, "center_y":root.box_y}
opacity: root.box_opacity
AnchorLayout:
MDIconButton:
icon: "delete"
theme_text_color: "Custom"
text_color: 1,1,1,1
user_font_size: "20sp"
BoxLayout:
AnchorLayout:
MDIconButton:
icon: "share"
theme_text_color: "Custom"
text_color: 1,1,1,1
user_font_size: "25sp"
on_release:
app.share_skylink(root)
MDFloatLayout:
orientation: "vertical"
id: spinner_box
md_bg_color: [0,0,0, root.spinner_box_alpha]
x: root.x
y: root.y
MDSpinner:
id: spinner
size_hint: None, None
size: dp(46), dp(46)
pos_hint: {'center_x': .5, 'center_y': .5}
active: root.spinner_active
MDLabel:
text:root.spinner_text
font_style:"Caption"
halign: "center"
pos_hint: {'center_x': .5, 'center_y': .15}
theme_text_color: "Custom"
text_color: 1, 1, 1, .8
<Content>:
size_hint_y: None
height: "70dp"
MDTextField:
id:link
hint_text: "Skylink"
"""
def get_permission():
if not check_permission(Permission.WRITE_EXTERNAL_STORAGE):
request_permissions([Permission.WRITE_EXTERNAL_STORAGE])
get_permission()
@run_on_ui_thread
def show_toast(text):
t= Toast.makeText(context, cast(CharSequence, String(text)), Toast.LENGTH_SHORT)
t.show()
@run_on_ui_thread
def set_statusbar_color(color):
window= context.getWindow()
window.addFlags(LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
window.setStatusBarColor(AndroidColor.parseColor(color))
def get_file_path(uri):
filePath=""
try:
cursor = context.getContentResolver().query(uri, None, None, None, None)
if cursor.moveToFirst():
column_index = cursor.getColumnIndexOrThrow("_data")
filePathUri = Uri.parse(cursor.getString(column_index))
filePath= filePathUri.getPath()
Logger.info("Hahaha: filePath={}".format(filePath))
cursor.close()
except JavaException:
Logger.info("Hahaha: _data wala error")
filePath= "/storage/emulated/0/"+Uri.parse(uri.toString()).getPath().split(":")[-1]
if not filePath:
return None
return filePath
class RectangleRaisedIconButton(MDRectangleFlatIconButton, RectangularElevationBehavior):
elevation_normal=16
class SmartTiles(
ThemableBehavior, ButtonBehavior, MDFloatLayout
):
"""
A tile for more complex needs.
Includes an image, a container to place overlays and a box that can act
as a header or a footer, as described in the Material Design specs.
"""
box_color_alpha = NumericProperty(0)
spinner_box_alpha= NumericProperty(0.4)
"""
Sets the color and opacity for the information box.
:attr:`box_color` is a :class:`~kivy.properties.ListProperty`
and defaults to `(0, 0, 0, 0.5)`.
"""
box_position = OptionProperty("footer", options=["footer", "header"])
"""
Determines wether the information box acts as a header or footer to the
image. Available are options: `'footer'`, `'header'`.
:attr:`box_position` is a :class:`~kivy.properties.OptionProperty`
and defaults to `'footer'`.
"""
lines = OptionProperty(1, options=[1, 2])
"""
Number of lines in the `header/footer`. As per `Material Design specs`,
only 1 and 2 are valid values. Available are options: ``1``, ``2``.
:attr:`lines` is a :class:`~kivy.properties.OptionProperty`
and defaults to `1`.
"""
overlap = BooleanProperty(True)
spinner_active= BooleanProperty(True)
"""
Determines if the `header/footer` overlaps on top of the image or not.
:attr:`overlap` is a :class:`~kivy.properties.BooleanProperty`
and defaults to `True`.
"""
source = StringProperty()
"""
Path to tile image. See :attr:`~kivy.uix.image.Image.source`.
:attr:`source` is a :class:`~kivy.properties.StringProperty`
and defaults to `''`.
"""
box_y= NumericProperty(-.3)
box_opacity= NumericProperty(0)
upload_done= BooleanProperty(False)
skylink= StringProperty()
spinner_text= StringProperty("Uploading...")
_img_widget = ObjectProperty()
_img_overlay = ObjectProperty()
_box_overlay = ObjectProperty()
_box_label = ObjectProperty()
def reload(self):
self._img_widget.reload()
class Content(AnchorLayout):
pass
class SaveImageApp(MDApp):
current_provider=""
previous_tile_inst= ObjectProperty()
selected_images=[]
dialog= None
def build(self):
if not os.path.exists(app_directory):
os.makedirs(app_directory)
initialize_google(self.after_login, self.error_listener)
initialize_fb(self.after_login, self.cancel_listener, self.error_listener)
self.theme_cls.primary_palette = "Green"
return Builder.load_string(kv)
def on_resume(self, *args):
#super().on_resume()
return True
def on_start(self):
primary_clr= self.theme_cls.primary_dark
hex_color= '#%02x%02x%02x' % (int(primary_clr[0]*255), int(primary_clr[1]*255), int(primary_clr[2]*255))
set_statusbar_color(hex_color)
def change_screen(self, scrn_name):
if scrn_name=="download_screen":
self.root.transition= SlideTransition(direction="down")
Logger.info("Hahaha: heererereererererereere")
else:
self.root.transition= SlideTransition(direction="up")
self.root.current= scrn_name
self.root.transition= SlideTransition(direction="right")
def fb_login(self, *args):
login_facebook()
self.current_provider= login_providers.facebook
def gl_login(self, *args):
# Logger.info("Hahaha: Cannot login google")
# show_toast("Logging in using google")
login_google()
self.current_provider= login_providers.google
def guest_login(self):
# Logger.info("Hahaha: Cannot login")
# show_toast("Logging in as guest")
self.root.current= "upload_screen"
def open_gallery(self, *args):
self.selected_images=[]
gallery = Intent()
gallery.setType("image/*")
gallery.setAction(Intent.ACTION_GET_CONTENT)
#gallery.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, True)
result_bind(on_activity_result=self.activity_result_gallery)
context.startActivityForResult(gallery, PICK_IMAGE)
def activity_result_gallery(self, request_code, result_code, data):
if request_code==PICK_IMAGE and result_code==Activity.RESULT_OK:
#grid= self.root.ids.upload_screen.ids.grid
uri = data.getData()
mClipData = data.getClipData()
if uri:
Logger.info("Hahaha: uri={}".format(uri))
file_path= get_file_path(uri)
Logger.info("Hahaha: uri_path={}".format(file_path))
if file_path not in self.selected_images:
t = threading.Thread(
target=self.upload_images, args=(file_path,)
)
t.start()
self.selected_images.append(file_path)
elif mClipData:
Logger.info("Hahaha: mClip={}".format(mClipData))
for i in range(mClipData.getItemCount()):
item = mClipData.getItemAt(i)
uri = item.getUri()
file_path= get_file_path(uri)
Logger.info("Hahaha: mClipUri_{}_path={}".format(i, file_path))
if file_path not in self.selected_images:
t = threading.Thread(
target=self.upload_images, args=(file_path, )
)
t.start()
self.selected_images.append(file_path)
else:
Logger.info("Hahaha: Cancelled")
def logout_(self):
if self.current_provider==login_providers.google:
logout_google(self.after_logout)
if self.current_provider==login_providers.facebook:
logout_facebook(self.after_logout)
else:
self.root.current= "loginscreen"
def after_login(self, name, email, photo_uri):
#show_toast('Logged in using {}'.format(current_provider))
self.root.current= 'upload_screen'
self.update_ui(name, email, photo_uri)
def after_logout(self):
self.update_ui('','','')
self.root.current= 'loginscreen'
#show_toast('Logged out from {} login'.format(current_provider))
def update_ui(self, name, email, photo_uri):
pass
#self.root.ids.upload_screen.ids.user_name.title= name
#self.root.ids.upload_screen.ids.user_email.text= "Your Email: {}".format(email)
def cancel_listener(self):
show_toast("Login cancelled")
def error_listener(self):
show_toast("Error logging in.")
def tiles_touched(self, inst):
Logger.info("Hahaha: Tile Number={}".format(inst.tile_no))
if self.previous_tile_inst:
self.hide_box_anim(self.previous_tile_inst)
if inst.box_y==.5:
self.hide_box_anim(inst)
else:
self.show_box_anim(inst)
self.previous_tile_inst= inst
def show_box_anim(self, widget):
anim= Animation(
d=.1,
box_color_alpha=.4,
t= "out_back"
)
anim+= Animation(
d=.15,
box_y=.5,
box_opacity=1,
t="out_back"
)
anim.stop_all(widget)
anim.start(widget)
def hide_box_anim(self, widget):
anim= Animation(
d=.15,
box_y=-.3,
box_opacity=0,
t="in_cubic"
)
anim+= Animation(
d=.1,
box_color_alpha=0,
t= "in_cubic"
)
anim.stop_all(widget)
anim.start(widget)
def add_image(self):
if PERMISSION_GRANTED==0:
self.open_gallery()
else:
show_toast("Cannot work without providing this permission")
def upload_images(self, file_path):
'''
if not self.selected_images_dummy==self.selected_images:
data=[]
for file_path in self.selected_images:
skylink= skynet.upload_file(file_path)
Logger.info("Hahaha: SkyLink={}".format(skylink))
tmp={
'source': file_path,
'skylink': "https://siasky.net/"+skynet.strip_prefix(skylink),
'spinner_text': "",
'spinner_active':False,
'spinner_box_alpha':0,
'upload_done':True
}
data.append(tmp)
new_data= self.root.ids.upload_screen.ids.rv.data+data
self.root.ids.upload_screen.ids.rv.data= []
self.root.ids.upload_screen.ids.rv.data.extend(new_data)
Logger.info("Hahaha: RV_DATA_after= {}".format(self.root.ids.upload_screen.ids.rv.data))
self.selected_images_dummy=self.selected_images'''
#data= self.root.ids.upload_screen.ids.rv.data[idx]
#data['source']= "https://siasky.net/"+skynet.strip_prefix(skylink)
# data['skylink']= "https://siasky.net/"+skynet.strip_prefix(skylink)
# data[]=
# data[]=
# data[]=0
# data[]= True
#_clean_cache()
#self.root.ids.upload_screen.ids.rv.data.append(data)
#self.root.ids.upload_screen.ids.rv.data.reverse()
#self.root.ids.upload_screen.ids.rv.refresh_from_data()
#self.root.ids.upload_screen.ids.rv.refresh_from_data()
#self.root.ids.upload_screen.ids.rv.refresh_from_layout()
#Logger.info("Hahaha: RV_DATA_after= {}".format(self.root.ids.upload_screen.ids.rv.data))
grid= self.root.ids.upload_screen.ids.grid
tile= SmartTiles()
tile.source= file_path
grid.add_widget(tile)
skylink= skynet.upload_file(file_path)
Logger.info("Hahaha: SkyLink={}".format(skylink))
tile.skylink= "https://siasky.net/"+self.strip_prefix(skylink)
tile.spinner_text= ""
tile.spinner_active= False
tile.spinner_box_alpha= 0
tile.upload_done= True
def strip_prefix(self, string):
if string.startswith(skynet.uri_skynet_prefix()):
return string[len(skynet.uri_skynet_prefix()):]
return string
def create_download_directory(self):
if not os.path.exists(download_directory):
os.makedirs(download_directory)
def make_skylink(self, link):
if link.startswith("https://siasky.net/"):
return skynet.uri_skynet_prefix()+link[len("https://siasky.net/"):]
return link
def share_skylink(self, inst):
skylink= inst.skylink
if skylink:
send_intent= Intent()
send_intent.setAction(Intent.ACTION_SEND)
send_intent.putExtra(Intent.EXTRA_TEXT, String(skylink))
send_intent.setType(String("text/*"))
share_intent = Intent.createChooser(send_intent, cast(CharSequence, String("Send SkyLink")))
context.startActivity(share_intent)
self.hide_box_anim(inst)
def show_link_popup(self):
if not self.dialog:
self.dialog = MDDialog(
title="Image Link",
type="custom",
content_cls=Content(),
buttons=[
MDFlatButton(
text="CANCEL",
text_color=self.theme_cls.primary_color,
on_release=self.cancel_dialog
),
MDFlatButton(
text="OK",
text_color=self.theme_cls.primary_color,
on_release= self._download_image
),
],
)
self.dialog.auto_dismiss= False
self.dialog.open()
def _download_image(self, *args):
self.cancel_dialog()
#self.download_image()
# t = threading.Thread(
# target=self.download_image
# )
# t.start()
Clock.schedule_once(self.download_image, .3)
def download_image(self, *args):
grid= self.root.ids.download_screen.ids.grid
tile= SmartTiles()
tile.source= "placeholder.jpg"
tile.spinner_text= "Downloading..."
grid.add_widget(tile)
link= self.dialog.content_cls.children[0].text
self.dialog.content_cls.children[0].text=""
skylink= self.make_skylink(link)
Logger.info("Hahaha: {}".format(skylink))
file_path= download_directory+"/"+time.strftime("%d%m%Y_%H%M%S")+".jpg"
try:
# t= threading.Thread(
# target= lambda *args: func(file_path, skylink, tile, grid)
# )
# t.start()
#t.join()
skynet.download_file(file_path, skylink)
tile.source=file_path
tile.skylink= "https://siasky.net/"+self.strip_prefix(skylink)
tile.spinner_text= ""
tile.spinner_active= False
tile.spinner_box_alpha= 0
tile.upload_done= True
except:
grid.remove_widget(tile)
show_toast("Error in downloading. Maybe an invalid link")
def cancel_dialog(self, *args):
self.dialog.dismiss()
def func(self, file_path, skylink, tile, grid):
# tile.source= "/storage/emulated/0/SkyShare/downloads/17082020_121003.jpg"
# tile.spinner_text= "Downloading..."
# grid.add_widget(tile)
skynet.download_file(file_path, skylink)
'''
tile= SmartTiles()
grid.remove_widget(tile)
Logger.info("Hahaha: source={}".format(file_path))
tile.source= ""
Logger.info("Hahaha: source={}".format(tile.source))
tile.skylink= "https://siasky.net/"+self.strip_prefix(skylink)
tile.spinner_text= ""
tile.spinner_active= False
tile.spinner_box_alpha= 0
tile.upload_done= True
grid.add_widget(tile)'''
if __name__ == "__main__":
SaveImageApp().run() | 32.126923 | 133 | 0.585059 |
b1d1bc65a3d88886d3f9075ed9c76c12996bdaea | 496 | py | Python | evaluate/previous_works/svsyn/spherical/weights.py | Syniez/Joint_360depth | 4f28c3b5b7f648173480052e205e898c6c7a5151 | [
"MIT"
] | 92 | 2019-09-08T09:55:05.000Z | 2022-02-21T21:29:40.000Z | spherical/weights.py | zjsprit/SphericalViewSynthesis | fcdec95bf3ad109767d27396434b51cf3aad2b4b | [
"BSD-2-Clause"
] | 4 | 2020-05-12T02:29:36.000Z | 2021-11-26T07:49:43.000Z | spherical/weights.py | zjsprit/SphericalViewSynthesis | fcdec95bf3ad109767d27396434b51cf3aad2b4b | [
"BSD-2-Clause"
] | 26 | 2019-09-16T02:26:33.000Z | 2021-10-21T03:55:02.000Z | import torch
from .grid import *
def phi_confidence(sgrid): # fading towards horizontal singularities
return torch.abs(torch.sin(phi(sgrid)))
def theta_confidence(sgrid): # fading towards vertical singularities
return torch.abs(torch.cos(theta(sgrid)))
def spherical_confidence(sgrid, zero_low=0.0, one_high=1.0):
weights = phi_confidence(sgrid) * theta_confidence(sgrid)
weights[weights < zero_low] = 0.0
weights[weights > one_high] = 1.0
return weights | 33.066667 | 69 | 0.72379 |
c3cb2cac8ff4726da19b06299035e2f53522ef63 | 47,439 | py | Python | diofant/ntheory/factor_.py | rajkk1/diofant | 6b361334569e4ec2e8c7d30dc324387a4ad417c2 | [
"BSD-3-Clause"
] | null | null | null | diofant/ntheory/factor_.py | rajkk1/diofant | 6b361334569e4ec2e8c7d30dc324387a4ad417c2 | [
"BSD-3-Clause"
] | null | null | null | diofant/ntheory/factor_.py | rajkk1/diofant | 6b361334569e4ec2e8c7d30dc324387a4ad417c2 | [
"BSD-3-Clause"
] | null | null | null | """
Integer factorization
"""
import math
import numbers
import random
from ..core import Function, Integer, Mul, Pow, Rational, integer_nthroot
from ..core.compatibility import as_int
from ..core.evalf import bitcount
from ..core.sympify import sympify
from .generate import nextprime, primerange, sieve
from .primetest import isprime
small_trailing = [i and max(int(not i % 2**j) and j for j in range(1, 8))
for i in range(256)]
def smoothness(n):
"""Return the B-smooth and B-power smooth values of n.
The smoothness of n is the largest prime factor of n; the power-
smoothness is the largest divisor raised to its multiplicity.
>>> smoothness(2**7*3**2)
(3, 128)
>>> smoothness(2**4*13)
(13, 16)
>>> smoothness(2)
(2, 2)
See Also
========
factorint, smoothness_p
"""
if n == 1:
return (1, 1) # not prime, but otherwise this causes headaches
facs = factorint(n)
return max(facs), max(m**facs[m] for m in facs)
def smoothness_p(n, m=-1, power=0, visual=None):
r"""
Return a list of [m, (p, (M, sm(p + m), psm(p + m)))...]
where:
1. p**M is the base-p divisor of n
2. sm(p + m) is the smoothness of p + m (m = -1 by default)
3. psm(p + m) is the power smoothness of p + m
The list is sorted according to smoothness (default) or by power smoothness
if power=1.
The smoothness of the numbers to the left (m = -1) or right (m = 1) of a
factor govern the results that are obtained from the p +/- 1 type factoring
methods.
>>> smoothness_p(10431, m=1)
(1, [(3, (2, 2, 4)), (19, (1, 5, 5)), (61, (1, 31, 31))])
>>> smoothness_p(10431)
(-1, [(3, (2, 2, 2)), (19, (1, 3, 9)), (61, (1, 5, 5))])
>>> smoothness_p(10431, power=1)
(-1, [(3, (2, 2, 2)), (61, (1, 5, 5)), (19, (1, 3, 9))])
If visual=True then an annotated string will be returned:
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
This string can also be generated directly from a factorization dictionary
and vice versa:
>>> f = factorint(17*9)
>>> f
{3: 2, 17: 1}
>>> smoothness_p(f)
'p**i=3**2 has p-1 B=2, B-pow=2\np**i=17**1 has p-1 B=2, B-pow=16'
>>> smoothness_p(_)
{3: 2, 17: 1}
The table of the output logic is:
====== ====== ======= =======
| Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict str tuple str
str str tuple dict
tuple str tuple str
n str tuple tuple
mul str tuple tuple
====== ====== ======= =======
See Also
========
factorint, smoothness
"""
from ..utilities import flatten
# visual must be True, False or other (stored as None)
if visual in (1, 0):
visual = bool(visual)
if visual not in (True, False):
visual = None
if type(n) is str:
if visual:
return n
d = {}
for li in n.splitlines():
k, v = [int(i) for i in
li.split('has')[0].split('=')[1].split('**')]
d[k] = v
if visual is not True and visual is not False:
return d
return smoothness_p(d, visual=False)
elif type(n) is not tuple:
facs = factorint(n, visual=False)
if power:
k = -1
else:
k = 1
if type(n) is not tuple:
rv = (m, sorted(((f, tuple([M] + list(smoothness(f + m))))
for f, M in list(facs.items())),
key=lambda x: (x[1][k], x[0])))
else:
rv = n
if visual is False or (visual is not True) and (type(n) in [int, Mul]):
return rv
lines = []
for dat in rv[1]:
dat = flatten(dat)
dat.insert(2, m)
lines.append('p**i=%i**%i has p%+i B=%i, B-pow=%i' % tuple(dat)) # noqa: SFS101
return '\n'.join(lines)
def trailing(n):
"""Count the number of trailing zero digits in the binary
representation of n, i.e. determine the largest power of 2
that divides n.
Examples
========
>>> trailing(128)
7
>>> trailing(63)
0
"""
n = int(n)
if not n:
return 0
low_byte = n & 0xff
if low_byte:
return small_trailing[low_byte]
# 2**m is quick for z up through 2**30
z = bitcount(n) - 1
if n == 1 << z:
return z
t = 0
p = 8
while not n & 1:
while not n & ((1 << p) - 1):
n >>= p
t += p
p *= 2
p //= 2
return t
def multiplicity(p, n):
"""Find the greatest integer m such that p**m divides n.
Examples
========
>>> [multiplicity(5, n) for n in [8, 5, 25, 125, 250]]
[0, 1, 2, 3, 3]
>>> multiplicity(3, Rational(1, 9))
-2
"""
try:
p, n = as_int(p), as_int(n)
except ValueError:
if all(isinstance(i, (numbers.Integral, Rational)) for i in (p, n)):
p, n = Rational(p), Rational(n)
if p.denominator == 1:
if n.numerator == 1:
return -multiplicity(p.numerator, n.denominator)
return Integer(0)
elif p.numerator == 1:
return multiplicity(p.denominator, n.denominator)
else:
like = min(multiplicity(p.numerator, n.numerator), multiplicity(p.denominator, n.denominator))
cross = min(multiplicity(p.denominator, n.numerator), multiplicity(p.numerator, n.denominator))
return like - cross
raise ValueError(f'expecting ints or fractions, got {p} and {n}')
if n == 0:
raise ValueError('multiplicity of 0 is not defined')
if p == 2:
return trailing(n)
if p < 2:
raise ValueError(f'p must be an integer, 2 or larger, but got {p}')
if p == n:
return 1
m = 0
n, rem = divmod(n, p)
while not rem:
m += 1
if m > 5:
# The multiplicity could be very large. Better
# to increment in powers of two
e = 2
while 1:
ppow = p**e
if ppow < n:
nnew, rem = divmod(n, ppow)
if not rem:
m += e
e *= 2
n = nnew
continue
return m + multiplicity(p, n)
n, rem = divmod(n, p)
return m
def perfect_power(n, candidates=None, big=True, factor=True):
"""
Return ``(b, e)`` such that ``n`` == ``b**e`` if ``n`` is a
perfect power; otherwise return ``False``.
By default, the base is recursively decomposed and the exponents
collected so the largest possible ``e`` is sought. If ``big=False``
then the smallest possible ``e`` (thus prime) will be chosen.
If ``candidates`` for exponents are given, they are assumed to be sorted
and the first one that is larger than the computed maximum will signal
failure for the routine.
If ``factor=True`` then simultaneous factorization of n is attempted
since finding a factor indicates the only possible root for n. This
is True by default since only a few small factors will be tested in
the course of searching for the perfect power.
Examples
========
>>> perfect_power(16)
(2, 4)
>>> perfect_power(16, big=False)
(4, 2)
"""
n = int(n)
if n < 3:
return False
logn = math.log(n, 2)
max_possible = int(logn) + 2 # only check values less than this
not_square = n % 10 in [2, 3, 7, 8] # squares cannot end in 2, 3, 7, 8
if not candidates:
candidates = primerange(2 + not_square, max_possible)
afactor = 2 + n % 2
for e in candidates:
if e < 3:
if e == 1 or e == 2 and not_square:
continue
if e > max_possible:
return False
# see if there is a factor present
if factor:
if n % afactor == 0:
# find what the potential power is
if afactor == 2:
e = trailing(n)
else:
e = multiplicity(afactor, n)
# if it's a trivial power we are done
if e == 1:
return False
# maybe the bth root of n is exact
r, exact = integer_nthroot(n, e)
if not exact:
# then remove this factor and check to see if
# any of e's factors are a common exponent; if
# not then it's not a perfect power
n //= afactor**e
m = perfect_power(n, candidates=primefactors(e), big=big)
if m is False:
return False
else:
r, m = m
# adjust the two exponents so the bases can
# be combined
g = math.gcd(m, e)
if g == 1:
return False
m //= g
e //= g
r, e = r**m*afactor**e, g
if not big:
e0 = primefactors(e)
if len(e0) > 1 or e0[0] != e:
e0 = e0[0]
r, e = r**(e//e0), e0
return r, e
else:
# get the next factor ready for the next pass through the loop
afactor = nextprime(afactor)
# Weed out downright impossible candidates
if logn/e < 40:
b = 2.0**(logn/e)
if abs(int(b + 0.5) - b) > 0.01:
continue
# now see if the plausible e makes a perfect power
r, exact = integer_nthroot(n, e)
if exact:
if big:
m = perfect_power(r, big=big, factor=factor)
if m is not False:
r, e = m[0], e*m[1]
return int(r), e
return False
def pollard_rho(n, s=2, a=1, retries=5, seed=1234, max_steps=None, F=None):
r"""
Use Pollard's rho method to try to extract a nontrivial factor
of ``n``. The returned factor may be a composite number. If no
factor is found, ``None`` is returned.
The algorithm generates pseudo-random values of x with a generator
function, replacing x with F(x). If F is not supplied then the
function x**2 + ``a`` is used. The first value supplied to F(x) is ``s``.
Upon failure (if ``retries`` is > 0) a new ``a`` and ``s`` will be
supplied; the ``a`` will be ignored if F was supplied.
The sequence of numbers generated by such functions generally have a
a lead-up to some number and then loop around back to that number and
begin to repeat the sequence, e.g. 1, 2, 3, 4, 5, 3, 4, 5 -- this leader
and loop look a bit like the Greek letter rho, and thus the name, 'rho'.
For a given function, very different leader-loop values can be obtained
so it is a good idea to allow for retries:
>>> n = 16843009
>>> def F(x):
... return (2048*pow(x, 2, n) + 32767) % n
>>> for s in range(5):
... print('loop length = %4i; leader length = %3i' % next(cycle_length(F, s)))
...
loop length = 2489; leader length = 42
loop length = 78; leader length = 120
loop length = 1482; leader length = 99
loop length = 1482; leader length = 285
loop length = 1482; leader length = 100
Here is an explicit example where there is a two element leadup to
a sequence of 3 numbers (11, 14, 4) that then repeat:
>>> x = 2
>>> for i in range(9):
... x = (x**2 + 12) % 17
... print(x)
...
16
13
11
14
4
11
14
4
11
>>> next(cycle_length(lambda x: (x**2+12) % 17, 2))
(3, 2)
>>> list(cycle_length(lambda x: (x**2+12) % 17, 2, values=True))
[16, 13, 11, 14, 4]
Instead of checking the differences of all generated values for a gcd
with n, only the kth and 2*kth numbers are checked, e.g. 1st and 2nd,
2nd and 4th, 3rd and 6th until it has been detected that the loop has been
traversed. Loops may be many thousands of steps long before rho finds a
factor or reports failure. If ``max_steps`` is specified, the iteration
is cancelled with a failure after the specified number of steps.
Examples
========
>>> n = 16843009
>>> def F(x):
... return (2048*pow(x, 2, n) + 32767) % n
>>> pollard_rho(n, F=F)
257
Use the default setting with a bad value of ``a`` and no retries:
>>> pollard_rho(n, a=n-2, retries=0)
If retries is > 0 then perhaps the problem will correct itself when
new values are generated for a:
>>> pollard_rho(n, a=n-2, retries=1)
257
References
==========
* Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 229-231
"""
n = int(n)
if n < 5:
raise ValueError('pollard_rho should receive n > 4')
prng = random.Random(seed + retries)
V = s
for i in range(retries + 1):
U = V
if not F:
def F(x):
return (pow(x, 2, n) + a) % n
j = 0
while 1:
if max_steps and (j > max_steps):
break
j += 1
U = F(U)
V = F(F(V)) # V is 2x further along than U
g = math.gcd(U - V, n)
if g == 1:
continue
if g == n:
break
return int(g)
V = prng.randint(0, n - 1)
a = prng.randint(1, n - 3) # for x**2 + a, a%n should not be 0 or -2
F = None
def pollard_pm1(n, B=10, a=2, retries=0, seed=1234):
"""
Use Pollard's p-1 method to try to extract a nontrivial factor
of ``n``. Either a divisor (perhaps composite) or ``None`` is returned.
The value of ``a`` is the base that is used in the test gcd(a**M - 1, n).
The default is 2. If ``retries`` > 0 then if no factor is found after the
first attempt, a new ``a`` will be generated randomly (using the ``seed``)
and the process repeated.
Note: the value of M is lcm(1..B) = reduce(lcm, range(2, B + 1)).
A search is made for factors next to even numbers having a power smoothness
less than ``B``. Choosing a larger B increases the likelihood of finding a
larger factor but takes longer. Whether a factor of n is found or not
depends on ``a`` and the power smoothness of the even mumber just less than
the factor p (hence the name p - 1).
Although some discussion of what constitutes a good ``a`` some
descriptions are hard to interpret. At the modular.math site referenced
below it is stated that if gcd(a**M - 1, n) = N then a**M % q**r is 1
for every prime power divisor of N. But consider the following:
>>> n = 257*1009
>>> smoothness_p(n)
(-1, [(257, (1, 2, 256)), (1009, (1, 7, 16))])
So we should (and can) find a root with B=16:
>>> pollard_pm1(n, B=16, a=3)
1009
If we attempt to increase B to 256 we find that it doesn't work:
>>> pollard_pm1(n, B=256)
>>>
But if the value of ``a`` is changed we find that only multiples of
257 work, e.g.:
>>> pollard_pm1(n, B=256, a=257)
1009
Checking different ``a`` values shows that all the ones that didn't
work had a gcd value not equal to ``n`` but equal to one of the
factors:
>>> M = 1
>>> for i in range(2, 256):
... M = math.lcm(M, i)
...
>>> {math.gcd(pow(a, M, n) - 1, n) for a in range(2, 256) if
... math.gcd(pow(a, M, n) - 1, n) != n}
{1009}
But does aM % d for every divisor of n give 1?
>>> am = pow(255, M, n)
>>> [(d, am % Pow(*d.args)) for d in factorint(n, visual=True).args]
[(257**1, 1), (1009**1, 1)]
No, only one of them. So perhaps the principle is that a root will
be found for a given value of B provided that:
1) the power smoothness of the p - 1 value next to the root
does not exceed B
2) a**M % p != 1 for any of the divisors of n.
By trying more than one ``a`` it is possible that one of them
will yield a factor.
Examples
========
With the default smoothness bound, this number can't be cracked:
>>> pollard_pm1(21477639576571)
Increasing the smoothness bound helps:
>>> pollard_pm1(21477639576571, B=2000)
4410317
Looking at the smoothness of the factors of this number we find:
>>> print(smoothness_p(21477639576571, visual=1))
p**i=4410317**1 has p-1 B=1787, B-pow=1787
p**i=4869863**1 has p-1 B=2434931, B-pow=2434931
The B and B-pow are the same for the p - 1 factorizations of the divisors
because those factorizations had a very large prime factor:
>>> factorint(4410317 - 1)
{2: 2, 617: 1, 1787: 1}
>>> factorint(4869863-1)
{2: 1, 2434931: 1}
Note that until B reaches the B-pow value of 1787, the number is not cracked;
>>> pollard_pm1(21477639576571, B=1786)
>>> pollard_pm1(21477639576571, B=1787)
4410317
The B value has to do with the factors of the number next to the divisor,
not the divisors themselves. A worst case scenario is that the number next
to the factor p has a large prime divisisor or is a perfect power. If these
conditions apply then the power-smoothness will be about p/2 or p. The more
realistic is that there will be a large prime factor next to p requiring
a B value on the order of p/2. Although primes may have been searched for
up to this level, the p/2 is a factor of p - 1, something that we don't
know. The modular.math reference below states that 15% of numbers in the
range of 10**15 to 15**15 + 10**4 are 10**6 power smooth so a B of 10**6
will fail 85% of the time in that range. From 10**8 to 10**8 + 10**3 the
percentages are nearly reversed...but in that range the simple trial
division is quite fast.
References
==========
* Richard Crandall & Carl Pomerance (2005), "Prime Numbers:
A Computational Perspective", Springer, 2nd edition, 236-238
* https://web.archive.org/web/20150716201437/http://modular.math.washington.edu/edu/2007/spring/ent/ent-html/node81.html
* https://web.archive.org/web/20170830055619/http://www.cs.toronto.edu/~yuvalf/Factorization.pdf
"""
n = int(n)
if n < 4 or B < 3:
raise ValueError('pollard_pm1 should receive n > 3 and B > 2')
prng = random.Random(seed + B)
# computing a**lcm(1,2,3,..B) % n for B > 2
# it looks weird, but it's right: primes run [2, B]
# and the answer's not right until the loop is done.
for i in range(retries + 1):
aM = a
for p in sieve.primerange(2, B + 1):
e = int(math.log(B, p))
aM = pow(aM, pow(p, e), n)
g = math.gcd(aM - 1, n)
if 1 < g < n:
return int(g)
# get a new a:
# since the exponent, lcm(1..B), is even, if we allow 'a' to be 'n-1'
# then (n - 1)**even % n will be 1 which will give a g of 0 and 1 will
# give a zero, too, so we set the range as [2, n-2]. Some references
# say 'a' should be coprime to n, but either will detect factors.
a = prng.randint(2, n - 2)
def _trial(factors, n, candidates, verbose=False):
"""
Helper function for integer factorization. Trial factors ``n`
against all integers given in the sequence ``candidates``
and updates the dict ``factors`` in-place. Returns the reduced
value of ``n`` and a flag indicating whether any factors were found.
"""
if verbose:
factors0 = list(factors)
nfactors = len(factors)
for d in candidates:
if n % d == 0:
m = multiplicity(d, n)
n //= d**m
factors[d] = m
if verbose:
for k in sorted(set(factors).difference(set(factors0))):
print(factor_msg % (k, factors[k]))
return int(n), len(factors) != nfactors
def _check_termination(factors, n, limitp1, use_trial, use_rho, use_pm1,
verbose):
"""
Helper function for integer factorization. Checks if ``n``
is a prime or a perfect power, and in those cases updates
the factorization and raises ``StopIteration``.
"""
if verbose:
print('Check for termination')
# since we've already been factoring there is no need to do
# simultaneous factoring with the power check
p = perfect_power(n, factor=False)
if p is not False:
base, exp = p
if limitp1:
limit = limitp1 - 1
else:
limit = limitp1
facs = factorint(base, limit, use_trial, use_rho, use_pm1,
verbose=False)
for b, e in facs.items():
if verbose:
print(factor_msg % (b, e))
factors[b] = exp*e
return True
if isprime(n):
factors[int(n)] = 1
return True
if n == 1:
return True
return False
trial_int_msg = 'Trial division with ints [%i ... %i] and fail_max=%i'
trial_msg = 'Trial division with primes [%i ... %i]'
rho_msg = "Pollard's rho with retries %i, max_steps %i and seed %i"
pm1_msg = "Pollard's p-1 with smoothness bound %i and seed %i"
factor_msg = '\t%i ** %i'
fermat_msg = 'Close factors satisying Fermat condition found.'
complete_msg = 'Factorization is complete.'
def _factorint_small(factors, n, limit, fail_max):
"""
Return the value of n and either a 0 (indicating that factorization up
to the limit was complete) or else the next near-prime that would have
been tested.
Factoring stops if there are fail_max unsuccessful tests in a row.
If factors of n were found they will be in the factors dictionary as
{factor: multiplicity} and the returned value of n will have had those
factors removed. The factors dictionary is modified in-place.
"""
def done(n, d):
"""Return n, d if the sqrt(n) wasn't reached yet, else
n, 0 indicating that factoring is done.
"""
if d*d <= n:
return n, d
return n, 0
d = 2
m = trailing(n)
if m:
factors[d] = m
n >>= m
d = 3
if limit < d:
if n > 1:
factors[n] = 1
return done(n, d)
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
# when d*d exceeds maxx or n we are done; if limit**2 is greater
# than n then maxx is set to zero so the value of n will flag the finish
if limit*limit > n:
maxx = 0
else:
maxx = limit*limit
dd = maxx or n
d = 5
fails = 0
while fails < fail_max:
if d*d > dd:
break
# d = 6*i - 1
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
dd = maxx or n
fails = 0
else:
fails += 1
d += 2
if d*d > dd:
break
# d = 6*i - 1
# reduce
m = 0
while n % d == 0:
n //= d
m += 1
if m == 20:
mm = multiplicity(d, n)
m += mm
n //= d**mm
break
if m:
factors[d] = m
dd = maxx or n
fails = 0
else:
fails += 1
# d = 6*(i+1) - 1
d += 4
return done(n, d)
def factorint(n, limit=None, use_trial=True, use_rho=True, use_pm1=True,
verbose=False, visual=None):
r"""
Given a positive integer ``n``, ``factorint(n)`` returns a dict containing
the prime factors of ``n`` as keys and their respective multiplicities
as values. For example:
>>> factorint(2000) # 2000 = (2**4) * (5**3)
{2: 4, 5: 3}
>>> factorint(65537) # This number is prime
{65537: 1}
For input less than 2, factorint behaves as follows:
- ``factorint(1)`` returns the empty factorization, ``{}``
- ``factorint(0)`` returns ``{0:1}``
- ``factorint(-n)`` adds ``-1:1`` to the factors and then factors ``n``
Partial Factorization:
If ``limit`` (> 3) is specified, the search is stopped after performing
trial division up to (and including) the limit (or taking a
corresponding number of rho/p-1 steps). This is useful if one has
a large number and only is interested in finding small factors (if
any). Note that setting a limit does not prevent larger factors
from being found early; it simply means that the largest factor may
be composite. Since checking for perfect power is relatively cheap, it is
done regardless of the limit setting.
This number, for example, has two small factors and a huge
semi-prime factor that cannot be reduced easily:
>>> a = 1407633717262338957430697921446883
>>> f = factorint(a, limit=10000)
>>> f
{7: 1, 991: 1, 202916782076162456022877024859: 1}
>>> isprime(max(f))
False
This number has a small factor and a residual perfect power whose
base is greater than the limit:
>>> factorint(3*101**7, limit=5)
{3: 1, 101: 7}
Visual Factorization:
If ``visual`` is set to ``True``, then it will return a visual
factorization of the integer. For example:
>>> pprint(factorint(4200, visual=True), use_unicode=False)
3 1 2 1
2 *3 *5 *7
Note that this is achieved by using the evaluate=False flag in Mul
and Pow. If you do other manipulations with an expression where
evaluate=False, it may evaluate. Therefore, you should use the
visual option only for visualization, and use the normal dictionary
returned by visual=False if you want to perform operations on the
factors.
You can easily switch between the two forms by sending them back to
factorint:
>>> regular = factorint(1764)
>>> regular
{2: 2, 3: 2, 7: 2}
>>> pprint(factorint(regular), use_unicode=False)
2 2 2
2 *3 *7
>>> visual = factorint(1764, visual=True)
>>> pprint(visual, use_unicode=False)
2 2 2
2 *3 *7
>>> print(factorint(visual))
{2: 2, 3: 2, 7: 2}
If you want to send a number to be factored in a partially factored form
you can do so with a dictionary or unevaluated expression:
>>> factorint(factorint({4: 2, 12: 3})) # twice to toggle to dict form
{2: 10, 3: 3}
>>> factorint(Mul(4, 12, evaluate=False))
{2: 4, 3: 1}
The table of the output logic is:
====== ====== ======= =======
Visual
------ ----------------------
Input True False other
====== ====== ======= =======
dict mul dict mul
n mul dict dict
mul mul dict dict
====== ====== ======= =======
Notes
=====
The function switches between multiple algorithms. Trial division
quickly finds small factors (of the order 1-5 digits), and finds
all large factors if given enough time. The Pollard rho and p-1
algorithms are used to find large factors ahead of time; they
will often find factors of the order of 10 digits within a few
seconds:
>>> factors = factorint(12345678910111213141516)
>>> for base, exp in sorted(factors.items()):
... print('%s %s' % (base, exp))
...
2 2
2507191691 1
1231026625769 1
Any of these methods can optionally be disabled with the following
boolean parameters:
- ``use_trial``: Toggle use of trial division
- ``use_rho``: Toggle use of Pollard's rho method
- ``use_pm1``: Toggle use of Pollard's p-1 method
``factorint`` also periodically checks if the remaining part is
a prime number or a perfect power, and in those cases stops.
If ``verbose`` is set to ``True``, detailed progress is printed.
See Also
========
smoothness, smoothness_p, divisors
"""
factordict = {}
if visual and not isinstance(n, Mul) and not isinstance(n, dict):
factordict = factorint(n, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose, visual=False)
elif isinstance(n, Mul):
factordict = {int(k): int(v) for k, v in
list(n.as_powers_dict().items())}
elif isinstance(n, dict):
factordict = n
if factordict and (isinstance(n, Mul) or isinstance(n, dict)):
# check it
for k in list(factordict):
if isprime(k):
continue
e = factordict.pop(k)
d = factorint(k, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
for k, v in d.items():
if k in factordict:
factordict[k] += v*e
else:
factordict[k] = v*e
if visual or (type(n) is dict and
visual is not True and
visual is not False):
if factordict == {}:
return Integer(1)
if -1 in factordict:
factordict.pop(-1)
args = [Integer(-1)]
else:
args = []
args.extend([Pow(*i, evaluate=False)
for i in sorted(factordict.items())])
return Mul(*args, evaluate=False)
elif isinstance(n, dict) or isinstance(n, Mul):
return factordict
assert use_trial or use_rho or use_pm1
n = as_int(n)
if limit:
limit = int(limit)
# special cases
if n < 0:
factors = factorint(
-n, limit=limit, use_trial=use_trial, use_rho=use_rho,
use_pm1=use_pm1, verbose=verbose, visual=False)
factors[-1] = 1
return factors
if limit and limit < 2:
if n == 1:
return {}
return {n: 1}
elif n < 10:
# doing this we are assured of getting a limit > 2
# when we have to compute it later
return [{0: 1}, {}, {2: 1}, {3: 1}, {2: 2}, {5: 1},
{2: 1, 3: 1}, {7: 1}, {2: 3}, {3: 2}][n]
factors = {}
# do simplistic factorization
if verbose:
sn = str(n)
if len(sn) > 50:
print(f'Factoring {sn[:5]}'
f'..({str(len(sn) - 10) + sn[-5:]} other digits)..')
else:
print('Factoring', n)
if use_trial:
# this is the preliminary factorization for small factors
small = 2**15
fail_max = 600
small = min(small, limit or small)
if verbose:
print(trial_int_msg % (2, small, fail_max))
n, next_p = _factorint_small(factors, n, small, fail_max)
else:
next_p = 2
if factors and verbose:
for k in sorted(factors):
print(factor_msg % (k, factors[k]))
if next_p == 0:
if n > 1:
factors[int(n)] = 1
if verbose:
print(complete_msg)
return factors
# continue with more advanced factorization methods
# first check if the simplistic run didn't finish
# because of the limit and check for a perfect
# power before exiting
if limit and next_p > limit:
if verbose:
print('Exceeded limit:', limit)
if _check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose):
if verbose:
print(complete_msg)
return factors
factors[int(n)] = 1
return factors
else:
# Before quitting (or continuing on)...
# ...do a Fermat test since it's so easy and we need the
# square root anyway. Finding 2 factors is easy if they are
# "close enough." This is the big root equivalent of dividing by
# 2, 3, 5.
sqrt_n = integer_nthroot(n, 2)[0]
a = sqrt_n + 1
a2 = a**2
b2 = a2 - n
for i in range(3):
b, fermat = integer_nthroot(b2, 2)
if fermat:
break
b2 += 2*a + 1 # equiv to (a+1)**2 - n
a += 1
if fermat:
if verbose:
print(fermat_msg)
if limit:
limit -= 1
for r in [a - b, a + b]:
facs = factorint(r, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose)
factors.update(facs)
if verbose:
print(complete_msg)
return factors
# ...see if factorization can be terminated
if _check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose):
if verbose:
print(complete_msg)
return factors
# these are the limits for trial division which will
# be attempted in parallel with pollard methods
low, high = next_p, 2*next_p
limit = limit or sqrt_n
# add 1 to make sure limit is reached in primerange calls
limit += 1
while 1:
high_ = high
if limit < high_:
high_ = limit
# Trial division
if use_trial:
if verbose:
print(trial_msg % (low, high_))
ps = sieve.primerange(low, high_)
n, found_trial = _trial(factors, n, ps, verbose)
if found_trial:
if _check_termination(factors, n, limit, use_trial, use_rho,
use_pm1, verbose):
if verbose:
print(complete_msg)
return factors
else:
found_trial = False
if high > limit:
if verbose:
print('Exceeded limit:', limit)
factors[int(n)] = 1
if verbose:
print(complete_msg)
return factors
# Only used advanced methods when no small factors were found
if not found_trial:
if use_pm1 or use_rho:
high_root = max(int(math.log(high_**0.7)), low, 3)
# Pollard p-1
if use_pm1:
if verbose:
print(pm1_msg % (high_root, high_))
c = pollard_pm1(n, B=high_root, seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
if _check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose):
if verbose:
print(complete_msg)
return factors
# Pollard rho
if use_rho:
max_steps = high_root
if verbose:
print(rho_msg % (1, max_steps, high_))
c = pollard_rho(n, retries=1, max_steps=max_steps,
seed=high_)
if c:
# factor it and let _trial do the update
ps = factorint(c, limit=limit - 1,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose)
n, _ = _trial(factors, n, ps, verbose=False)
if _check_termination(factors, n, limit, use_trial,
use_rho, use_pm1, verbose):
if verbose:
print(complete_msg)
return factors
low, high = high, high*2
def factorrat(rat, limit=None, use_trial=True, use_rho=True, use_pm1=True,
verbose=False, visual=None):
r"""
Given a Rational ``r``, ``factorrat(r)`` returns a dict containing
the prime factors of ``r`` as keys and their respective multiplicities
as values. For example:
>>> factorrat(Rational(8, 9)) # = (2**3) * (3**-2)
{2: 3, 3: -2}
>>> factorrat(Rational(-1, 987)) # = -1 * (3**-1) * (7**-1) * (47**-1)
{-1: 1, 3: -1, 7: -1, 47: -1}
Please see the docstring for ``factorint`` for detailed explanations
and examples of the following keywords:
- ``limit``: Integer limit up to which trial division is done
- ``use_trial``: Toggle use of trial division
- ``use_rho``: Toggle use of Pollard's rho method
- ``use_pm1``: Toggle use of Pollard's p-1 method
- ``verbose``: Toggle detailed printing of progress
- ``visual``: Toggle product form of output
"""
from collections import defaultdict
f = factorint(rat.numerator, limit=limit, use_trial=use_trial,
use_rho=use_rho, use_pm1=use_pm1,
verbose=verbose).copy()
f = defaultdict(int, f)
for p, e in factorint(rat.denominator, limit=limit,
use_trial=use_trial,
use_rho=use_rho,
use_pm1=use_pm1,
verbose=verbose).items():
f[p] += -e
if not visual:
return dict(f)
else:
if -1 in f:
f.pop(-1)
args = [Integer(-1)]
else:
args = []
args.extend([Pow(*i, evaluate=False)
for i in sorted(f.items())])
return Mul(*args, evaluate=False)
def primefactors(n, limit=None, verbose=False):
"""Return a sorted list of n's prime factors, ignoring multiplicity
and any composite factor that remains if the limit was set too low
for complete factorization. Unlike factorint(), primefactors() does
not return -1 or 0.
Examples
========
>>> primefactors(6)
[2, 3]
>>> primefactors(-5)
[5]
>>> sorted(factorint(123456).items())
[(2, 6), (3, 1), (643, 1)]
>>> primefactors(123456)
[2, 3, 643]
>>> sorted(factorint(10000000001, limit=200).items())
[(101, 1), (99009901, 1)]
>>> isprime(99009901)
False
>>> primefactors(10000000001, limit=300)
[101]
See Also
========
divisors
"""
n = int(n)
factors = sorted(factorint(n, limit=limit, verbose=verbose))
s = [f for f in factors[:-1:] if f not in [-1, 0, 1]]
if factors and isprime(factors[-1]):
s += [factors[-1]]
return s
def _divisors(n):
"""Helper function for divisors which generates the divisors."""
factordict = factorint(n)
ps = sorted(factordict)
def rec_gen(n=0):
if n == len(ps):
yield 1
else:
pows = [1]
for j in range(factordict[ps[n]]):
pows.append(pows[-1] * ps[n])
for q in rec_gen(n + 1):
for p in pows:
yield p * q
for p in rec_gen():
yield p
def divisors(n, generator=False):
r"""Return all divisors of n.
Divisors are sorted from 1..n by default. If generator is True an
unordered generator is returned.
The number of divisors of n can be quite large if there are many
prime factors (counting repeated factors). If only the number of
factors is desired use divisor_count(n).
Examples
========
>>> divisors(24)
[1, 2, 3, 4, 6, 8, 12, 24]
>>> divisor_count(24)
8
>>> list(divisors(120, generator=True))
[1, 2, 4, 8, 3, 6, 12, 24, 5, 10, 20, 40, 15, 30, 60, 120]
See Also
========
primefactors, factorint, divisor_count
References
==========
* https://stackoverflow.com/questions/1010381/python-factorization
"""
n = as_int(abs(n))
if isprime(n):
return [1, n]
if n == 1:
return [1]
if n == 0:
return []
rv = _divisors(n)
if not generator:
return sorted(rv)
return rv
def divisor_count(n, modulus=1):
"""Return the number of divisors of ``n``.
If ``modulus`` is not 1 then only those that are divisible by
``modulus`` are counted.
References
==========
* https://web.archive.org/web/20130629014824/http://www.mayer.dial.pipex.com:80/maths/formulae.htm
Examples
========
>>> divisor_count(6)
4
See Also
========
factorint, divisors, totient
"""
if not modulus:
return 0
elif modulus != 1:
n, r = divmod(n, modulus)
if r:
return 0
if n == 0:
return 0
return Mul(*[v + 1 for k, v in factorint(n).items() if k > 1])
def _antidivisors(n):
"""Helper function for antidivisors which generates the antidivisors."""
for d in _divisors(n):
y = 2*d
if n > y and n % y:
yield y
for d in _divisors(2*n-1):
if n > d >= 2 and n % d:
yield d
for d in _divisors(2*n+1):
if n > d >= 2 and n % d:
yield d
def antidivisors(n, generator=False):
r"""Return all antidivisors of n sorted from 1..n by default.
Antidivisors of n are numbers that do not divide n by the largest
possible margin. If generator is True an unordered generator is returned.
References
==========
* definition is described in http://oeis.org/A066272/a066272a.html
Examples
========
>>> antidivisors(24)
[7, 16]
>>> sorted(antidivisors(128, generator=True))
[3, 5, 15, 17, 51, 85]
See Also
========
primefactors, factorint, divisors, divisor_count, antidivisor_count
"""
n = as_int(abs(n))
if n <= 2:
return []
rv = _antidivisors(n)
if not generator:
return sorted(rv)
return rv
def antidivisor_count(n):
"""Return the number of antidivisors of ``n``.
References
==========
* formula from https://oeis.org/A066272
Examples
========
>>> antidivisor_count(13)
4
>>> antidivisor_count(27)
5
See Also
========
factorint, divisors, antidivisors, divisor_count, totient
"""
n = as_int(abs(n))
if n <= 2:
return 0
return divisor_count(2*n-1) + divisor_count(2*n+1) + \
divisor_count(n) - divisor_count(n, 2) - 5
class totient(Function):
"""Calculate the Euler totient function phi(n)
>>> totient(1)
1
>>> totient(25)
20
See Also
========
divisor_count
"""
@classmethod
def eval(cls, n):
n = sympify(n)
if n.is_Integer:
if n < 1:
raise ValueError('n must be a positive integer')
factors = factorint(n)
t = 1
for p, k in factors.items():
t *= (p - 1) * p**(k - 1)
return t
def _eval_is_integer(self):
if self.args[0].is_integer and self.args[0].is_positive:
return True
class divisor_sigma(Function):
r"""Calculate the divisor function `\sigma_k(n)` for positive integer n.
``divisor_sigma(n, k)`` is equal to ``sum(x**k for x in divisors(n))``
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
\sigma_k(n) = \prod_{i=1}^\omega (1+p_i^k+p_i^{2k}+\cdots
+ p_i^{m_ik}).
Parameters
==========
k : power of divisors in the sum
for k = 0, 1:
``divisor_sigma(n, 0)`` is equal to ``divisor_count(n)``
``divisor_sigma(n, 1)`` is equal to ``sum(divisors(n))``
Default for k is 1.
References
==========
* https://en.wikipedia.org/wiki/Divisor_function
Examples
========
>>> divisor_sigma(18, 0)
6
>>> divisor_sigma(39, 1)
56
>>> divisor_sigma(12, 2)
210
>>> divisor_sigma(37)
38
See Also
========
divisor_count, totient, divisors, factorint
"""
@classmethod
def eval(cls, n, k=1):
n = sympify(n)
k = sympify(k)
if n.is_prime:
return 1 + n**k
if n.is_Integer:
if n <= 0:
raise ValueError('n must be a positive integer')
else:
return Mul(*[(p**(k*(e + 1)) - 1)/(p**k - 1) if k != 0
else e + 1 for p, e in factorint(n).items()])
def core(n, t=2):
r"""Calculate core(n,t) = `core_t(n)` of a positive integer n.
``core_2(n)`` is equal to the squarefree part of n
If n's prime factorization is:
.. math ::
n = \prod_{i=1}^\omega p_i^{m_i},
then
.. math ::
core_t(n) = \prod_{i=1}^\omega p_i^{m_i \mod t}.
Parameters
==========
t : core(n,t) calculates the t-th power free part of n
``core(n, 2)`` is the squarefree part of ``n``
``core(n, 3)`` is the cubefree part of ``n``
Default for t is 2.
References
==========
* https://en.wikipedia.org/wiki/Square-free_integer#Squarefree_core
Examples
========
>>> from diofant.ntheory.factor_ import core
>>> core(24, 2)
6
>>> core(9424, 3)
1178
>>> core(379238)
379238
>>> core(15**11, 10)
15
See Also
========
factorint, diofant.solvers.diophantine.square_factor
"""
n = as_int(n)
t = as_int(t)
if n <= 0:
raise ValueError('n must be a positive integer')
elif t <= 1:
raise ValueError('t must be >= 2')
else:
y = 1
for p, e in factorint(n).items():
y *= p**(e % t)
return y
def square_factor(a):
r"""
Returns an integer `c` s.t. `a = c^2k, \ c,k \in Z`. Here `k` is square
free. `a` can be given as an integer or a dictionary of factors.
Examples
========
>>> square_factor(24)
2
>>> square_factor(-36*3)
6
>>> square_factor(1)
1
>>> square_factor({3: 2, 2: 1, -1: 1})
3
See Also
========
diofant.solvers.diophantine.reconstruct
diofant.ntheory.factor_.core
"""
f = a if isinstance(a, dict) else factorint(a)
return math.prod(p**(e//2) for p, e in f.items())
| 29.575436 | 124 | 0.531925 |
1f558305bb6543f624de3fb58846017ba16f96dd | 9,276 | py | Python | sdk/python/pulumi_azure_native/cache/v20171001/patch_schedule.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/cache/v20171001/patch_schedule.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_azure_native/cache/v20171001/patch_schedule.py | sebtelko/pulumi-azure-native | 711ec021b5c73da05611c56c8a35adb0ce3244e4 | [
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi SDK Generator. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union, overload
from ... import _utilities
from . import outputs
from ._enums import *
from ._inputs import *
__all__ = ['PatchScheduleArgs', 'PatchSchedule']
@pulumi.input_type
class PatchScheduleArgs:
def __init__(__self__, *,
name: pulumi.Input[str],
resource_group_name: pulumi.Input[str],
schedule_entries: pulumi.Input[Sequence[pulumi.Input['ScheduleEntryArgs']]],
default: Optional[pulumi.Input[str]] = None):
"""
The set of arguments for constructing a PatchSchedule resource.
:param pulumi.Input[str] name: The name of the Redis cache.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Sequence[pulumi.Input['ScheduleEntryArgs']]] schedule_entries: List of patch schedules for a Redis cache.
:param pulumi.Input[str] default: Default string modeled as parameter for auto generation to work correctly.
"""
pulumi.set(__self__, "name", name)
pulumi.set(__self__, "resource_group_name", resource_group_name)
pulumi.set(__self__, "schedule_entries", schedule_entries)
if default is not None:
pulumi.set(__self__, "default", default)
@property
@pulumi.getter
def name(self) -> pulumi.Input[str]:
"""
The name of the Redis cache.
"""
return pulumi.get(self, "name")
@name.setter
def name(self, value: pulumi.Input[str]):
pulumi.set(self, "name", value)
@property
@pulumi.getter(name="resourceGroupName")
def resource_group_name(self) -> pulumi.Input[str]:
"""
The name of the resource group.
"""
return pulumi.get(self, "resource_group_name")
@resource_group_name.setter
def resource_group_name(self, value: pulumi.Input[str]):
pulumi.set(self, "resource_group_name", value)
@property
@pulumi.getter(name="scheduleEntries")
def schedule_entries(self) -> pulumi.Input[Sequence[pulumi.Input['ScheduleEntryArgs']]]:
"""
List of patch schedules for a Redis cache.
"""
return pulumi.get(self, "schedule_entries")
@schedule_entries.setter
def schedule_entries(self, value: pulumi.Input[Sequence[pulumi.Input['ScheduleEntryArgs']]]):
pulumi.set(self, "schedule_entries", value)
@property
@pulumi.getter
def default(self) -> Optional[pulumi.Input[str]]:
"""
Default string modeled as parameter for auto generation to work correctly.
"""
return pulumi.get(self, "default")
@default.setter
def default(self, value: Optional[pulumi.Input[str]]):
pulumi.set(self, "default", value)
class PatchSchedule(pulumi.CustomResource):
@overload
def __init__(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
default: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
schedule_entries: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ScheduleEntryArgs']]]]] = None,
__props__=None):
"""
Response to put/get patch schedules for Redis cache.
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] default: Default string modeled as parameter for auto generation to work correctly.
:param pulumi.Input[str] name: The name of the Redis cache.
:param pulumi.Input[str] resource_group_name: The name of the resource group.
:param pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ScheduleEntryArgs']]]] schedule_entries: List of patch schedules for a Redis cache.
"""
...
@overload
def __init__(__self__,
resource_name: str,
args: PatchScheduleArgs,
opts: Optional[pulumi.ResourceOptions] = None):
"""
Response to put/get patch schedules for Redis cache.
:param str resource_name: The name of the resource.
:param PatchScheduleArgs args: The arguments to use to populate this resource's properties.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
...
def __init__(__self__, resource_name: str, *args, **kwargs):
resource_args, opts = _utilities.get_resource_args_opts(PatchScheduleArgs, pulumi.ResourceOptions, *args, **kwargs)
if resource_args is not None:
__self__._internal_init(resource_name, opts, **resource_args.__dict__)
else:
__self__._internal_init(resource_name, *args, **kwargs)
def _internal_init(__self__,
resource_name: str,
opts: Optional[pulumi.ResourceOptions] = None,
default: Optional[pulumi.Input[str]] = None,
name: Optional[pulumi.Input[str]] = None,
resource_group_name: Optional[pulumi.Input[str]] = None,
schedule_entries: Optional[pulumi.Input[Sequence[pulumi.Input[pulumi.InputType['ScheduleEntryArgs']]]]] = None,
__props__=None):
if opts is None:
opts = pulumi.ResourceOptions()
if not isinstance(opts, pulumi.ResourceOptions):
raise TypeError('Expected resource options to be a ResourceOptions instance')
if opts.version is None:
opts.version = _utilities.get_version()
if opts.id is None:
if __props__ is not None:
raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
__props__ = PatchScheduleArgs.__new__(PatchScheduleArgs)
__props__.__dict__["default"] = default
if name is None and not opts.urn:
raise TypeError("Missing required property 'name'")
__props__.__dict__["name"] = name
if resource_group_name is None and not opts.urn:
raise TypeError("Missing required property 'resource_group_name'")
__props__.__dict__["resource_group_name"] = resource_group_name
if schedule_entries is None and not opts.urn:
raise TypeError("Missing required property 'schedule_entries'")
__props__.__dict__["schedule_entries"] = schedule_entries
__props__.__dict__["type"] = None
alias_opts = pulumi.ResourceOptions(aliases=[pulumi.Alias(type_="azure-nextgen:cache/v20171001:PatchSchedule"), pulumi.Alias(type_="azure-native:cache:PatchSchedule"), pulumi.Alias(type_="azure-nextgen:cache:PatchSchedule"), pulumi.Alias(type_="azure-native:cache/v20180301:PatchSchedule"), pulumi.Alias(type_="azure-nextgen:cache/v20180301:PatchSchedule"), pulumi.Alias(type_="azure-native:cache/v20190701:PatchSchedule"), pulumi.Alias(type_="azure-nextgen:cache/v20190701:PatchSchedule"), pulumi.Alias(type_="azure-native:cache/v20200601:PatchSchedule"), pulumi.Alias(type_="azure-nextgen:cache/v20200601:PatchSchedule")])
opts = pulumi.ResourceOptions.merge(opts, alias_opts)
super(PatchSchedule, __self__).__init__(
'azure-native:cache/v20171001:PatchSchedule',
resource_name,
__props__,
opts)
@staticmethod
def get(resource_name: str,
id: pulumi.Input[str],
opts: Optional[pulumi.ResourceOptions] = None) -> 'PatchSchedule':
"""
Get an existing PatchSchedule resource's state with the given name, id, and optional extra
properties used to qualify the lookup.
:param str resource_name: The unique name of the resulting resource.
:param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
:param pulumi.ResourceOptions opts: Options for the resource.
"""
opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))
__props__ = PatchScheduleArgs.__new__(PatchScheduleArgs)
__props__.__dict__["name"] = None
__props__.__dict__["schedule_entries"] = None
__props__.__dict__["type"] = None
return PatchSchedule(resource_name, opts=opts, __props__=__props__)
@property
@pulumi.getter
def name(self) -> pulumi.Output[str]:
"""
Resource name.
"""
return pulumi.get(self, "name")
@property
@pulumi.getter(name="scheduleEntries")
def schedule_entries(self) -> pulumi.Output[Sequence['outputs.ScheduleEntryResponse']]:
"""
List of patch schedules for a Redis cache.
"""
return pulumi.get(self, "schedule_entries")
@property
@pulumi.getter
def type(self) -> pulumi.Output[str]:
"""
Resource type.
"""
return pulumi.get(self, "type")
| 44.382775 | 632 | 0.655347 |
dc84ca1feda0f27ebd688040f503cd78a1f4903e | 20,880 | py | Python | salt/cloud/clouds/softlayer_hw.py | kev009/salt | aecd53203eca51e150128ae7c9ad2a979d004127 | [
"Apache-2.0"
] | null | null | null | salt/cloud/clouds/softlayer_hw.py | kev009/salt | aecd53203eca51e150128ae7c9ad2a979d004127 | [
"Apache-2.0"
] | null | null | null | salt/cloud/clouds/softlayer_hw.py | kev009/salt | aecd53203eca51e150128ae7c9ad2a979d004127 | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
'''
SoftLayer HW Cloud Module
=========================
The SoftLayer HW cloud module is used to control access to the SoftLayer
hardware cloud system
Use of this module only requires the ``apikey`` parameter. Set up the cloud
configuration at:
``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/softlayer.conf``:
.. code-block:: yaml
my-softlayer-config:
# SoftLayer account api key
user: MYLOGIN
apikey: JVkbSJDGHSDKUKSDJfhsdklfjgsjdkflhjlsdfffhgdgjkenrtuinv
provider: softlayer_hw
The SoftLayer Python Library needs to be installed in order to use the
SoftLayer salt.cloud modules. See: https://pypi.python.org/pypi/SoftLayer
:depends: softlayer
'''
# pylint: disable=E0102
from __future__ import absolute_import
# Import python libs
import copy
import pprint
import logging
import time
import decimal
# Import salt cloud libs
import salt.utils.cloud
import salt.config as config
from salt.exceptions import SaltCloudSystemExit
# Attempt to import softlayer lib
try:
import SoftLayer
HAS_SLLIBS = True
except ImportError:
HAS_SLLIBS = False
# Get logging started
log = logging.getLogger(__name__)
# Only load in this module if the SoftLayer configurations are in place
def __virtual__():
'''
Check for SoftLayer configurations.
'''
if not HAS_SLLIBS:
return False
if get_configured_provider() is False:
return False
return True
def get_configured_provider():
'''
Return the first configured instance.
'''
return config.is_provider_configured(
__opts__,
__active_provider_name__ or 'softlayer_hw',
('apikey',)
)
def script(vm_):
'''
Return the script deployment object
'''
deploy_script = salt.utils.cloud.os_script(
config.get_cloud_config_value('script', vm_, __opts__),
vm_,
__opts__,
salt.utils.cloud.salt_config_to_yaml(
salt.utils.cloud.minion_config(__opts__, vm_)
)
)
return deploy_script
def get_conn(service='SoftLayer_Hardware'):
'''
Return a conn object for the passed VM data
'''
client = SoftLayer.Client(
username=config.get_cloud_config_value(
'user', get_configured_provider(), __opts__, search_global=False
),
api_key=config.get_cloud_config_value(
'apikey', get_configured_provider(), __opts__, search_global=False
),
)
return client[service]
def avail_locations(call=None):
'''
List all available locations
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_locations function must be called with '
'-f or --function, or with the --list-locations option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
locations = conn.getLocations(id=50)
for location in locations:
ret[location['id']] = {
'id': location['id'],
'name': location['name'],
'location': location['longName'],
}
available = conn.getAvailableLocations(id=50)
for location in available:
if location.get('isAvailable', 0) is 0:
continue
ret[location['locationId']]['available'] = True
return ret
def avail_sizes(call=None):
'''
Return a dict of all available VM sizes on the cloud provider with
relevant data. This data is provided in three dicts.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_sizes function must be called with '
'-f or --function, or with the --list-sizes option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'server_core':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
pprint.pprint(category)
return ret
def avail_images(call=None):
'''
Return a dict of all available VM images on the cloud provider.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The avail_images function must be called with '
'-f or --function, or with the --list-images option'
)
ret = {}
conn = get_conn(service='SoftLayer_Product_Package')
for category in conn.getCategories(id=50):
if category['categoryCode'] != 'os':
continue
for group in category['groups']:
for price in group['prices']:
ret[price['id']] = price['item'].copy()
del ret[price['id']]['id']
pprint.pprint(category)
return ret
def get_location(vm_=None):
'''
Return the location to use, in this order:
- CLI parameter
- VM parameter
- Cloud profile setting
'''
return __opts__.get(
'location',
config.get_cloud_config_value(
'location',
vm_ or get_configured_provider(),
__opts__,
#default=DEFAULT_LOCATION,
search_global=False
)
)
def create(vm_):
'''
Create a single VM from a data dict
'''
salt.utils.cloud.fire_event(
'event',
'starting create',
'salt/cloud/{0}/creating'.format(vm_['name']),
{
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['provider'],
},
transport=__opts__['transport']
)
log.info('Creating Cloud VM {0}'.format(vm_['name']))
conn = get_conn(service='SoftLayer_Product_Order')
kwargs = {
'complexType': 'SoftLayer_Container_Product_Order_Hardware_Server',
'quantity': 1,
'hardware': [{
'hostname': vm_['name'],
'domain': vm_['domain'],
}],
'packageId': 50, # Baremetal Package
'prices': [
# Size Ex: 1921: 2 x 2.0 GHz Core Bare Metal Instance - 2 GB Ram
{'id': vm_['size']},
# HDD Ex: 19: 250GB SATA II
{'id': vm_['hdd']},
# Image Ex: 13963: CentOS 6.0 - Minimal Install (64 bit)
{'id': vm_['image']},
# The following items are currently required
# Reboot / Remote Console
{'id': '905'},
# 1 IP Address
{'id': '21'},
# Host Ping Monitoring
{'id': '55'},
# Email and Ticket Notifications
{'id': '57'},
# Automated Notification Response
{'id': '58'},
# Unlimited SSL VPN Users & 1 PPTP VPN User per account
{'id': '420'},
# Nessus Vulnerability Assessment & Reporting
{'id': '418'},
],
}
optional_products = config.get_cloud_config_value(
'optional_products', vm_, __opts__, default=True
)
for product in optional_products:
kwargs['prices'].append({'id': product})
# Default is 273 (100 Mbps Public & Private Networks)
port_speed = config.get_cloud_config_value(
'port_speed', vm_, __opts__, default=273
)
kwargs['prices'].append({'id': port_speed})
# Default is 248 (5000 GB Bandwidth)
bandwidth = config.get_cloud_config_value(
'bandwidth', vm_, __opts__, default=248
)
kwargs['prices'].append({'id': bandwidth})
vlan_id = config.get_cloud_config_value(
'vlan', vm_, __opts__, default=False
)
if vlan_id:
kwargs['primaryNetworkComponent'] = {
'networkVlan': {
'id': vlan_id,
}
}
location = get_location(vm_)
if location:
kwargs['location'] = location
salt.utils.cloud.fire_event(
'event',
'requesting instance',
'salt/cloud/{0}/requesting'.format(vm_['name']),
{'kwargs': kwargs},
transport=__opts__['transport']
)
try:
response = conn.placeOrder(kwargs)
# Leaving the following line in, commented, for easy debugging
#response = conn.verifyOrder(kwargs)
except Exception as exc:
log.error(
'Error creating {0} on SoftLayer\n\n'
'The following exception was thrown when trying to '
'run the initial deployment: \n{1}'.format(
vm_['name'], str(exc)
),
# Show the traceback if the debug logging level is enabled
exc_info_on_loglevel=logging.DEBUG
)
return False
def wait_for_ip():
'''
Wait for the IP address to become available
'''
nodes = list_nodes_full()
if 'primaryIpAddress' in nodes[vm_['name']]:
return nodes[vm_['name']]['primaryIpAddress']
time.sleep(1)
return False
ip_address = salt.utils.cloud.wait_for_fun(
wait_for_ip,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
ssh_connect_timeout = config.get_cloud_config_value(
'ssh_connect_timeout', vm_, __opts__, 900 # 15 minutes
)
if not salt.utils.cloud.wait_for_port(ip_address,
timeout=ssh_connect_timeout):
raise SaltCloudSystemExit(
'Failed to authenticate against remote ssh'
)
pass_conn = get_conn(service='SoftLayer_Account')
mask = {
'virtualGuests': {
'powerState': '',
'operatingSystem': {
'passwords': ''
},
},
}
def get_passwd():
'''
Wait for the password to become available
'''
node_info = pass_conn.getVirtualGuests(id=response['id'], mask=mask)
for node in node_info:
if node['id'] == response['id']:
if 'passwords' in node['operatingSystem'] and len(node['operatingSystem']['passwords']) > 0:
return node['operatingSystem']['passwords'][0]['password']
time.sleep(5)
return False
passwd = salt.utils.cloud.wait_for_fun(
get_passwd,
timeout=config.get_cloud_config_value(
'wait_for_fun_timeout', vm_, __opts__, default=15 * 60),
)
response['password'] = passwd
response['public_ip'] = ip_address
ssh_username = config.get_cloud_config_value(
'ssh_username', vm_, __opts__, default='root'
)
ret = {}
if config.get_cloud_config_value('deploy', vm_, __opts__) is True:
deploy_script = script(vm_)
deploy_kwargs = {
'opts': __opts__,
'host': ip_address,
'username': ssh_username,
'password': passwd,
'script': deploy_script,
'name': vm_['name'],
'tmp_dir': config.get_cloud_config_value(
'tmp_dir', vm_, __opts__, default='/tmp/.saltcloud'
),
'deploy_command': config.get_cloud_config_value(
'deploy_command', vm_, __opts__,
default='/tmp/.saltcloud/deploy.sh',
),
'start_action': __opts__['start_action'],
'parallel': __opts__['parallel'],
'sock_dir': __opts__['sock_dir'],
'conf_file': __opts__['conf_file'],
'minion_pem': vm_['priv_key'],
'minion_pub': vm_['pub_key'],
'keep_tmp': __opts__['keep_tmp'],
'preseed_minion_keys': vm_.get('preseed_minion_keys', None),
'sudo': config.get_cloud_config_value(
'sudo', vm_, __opts__, default=(ssh_username != 'root')
),
'sudo_password': config.get_cloud_config_value(
'sudo_password', vm_, __opts__, default=None
),
'tty': config.get_cloud_config_value(
'tty', vm_, __opts__, default=False
),
'display_ssh_output': config.get_cloud_config_value(
'display_ssh_output', vm_, __opts__, default=True
),
'script_args': config.get_cloud_config_value(
'script_args', vm_, __opts__
),
'script_env': config.get_cloud_config_value('script_env', vm_, __opts__),
'minion_conf': salt.utils.cloud.minion_config(__opts__, vm_)
}
# Deploy salt-master files, if necessary
if config.get_cloud_config_value('make_master', vm_, __opts__) is True:
deploy_kwargs['make_master'] = True
deploy_kwargs['master_pub'] = vm_['master_pub']
deploy_kwargs['master_pem'] = vm_['master_pem']
master_conf = salt.utils.cloud.master_config(__opts__, vm_)
deploy_kwargs['master_conf'] = master_conf
if master_conf.get('syndic_master', None):
deploy_kwargs['make_syndic'] = True
deploy_kwargs['make_minion'] = config.get_cloud_config_value(
'make_minion', vm_, __opts__, default=True
)
# Check for Windows install params
win_installer = config.get_cloud_config_value('win_installer', vm_, __opts__)
if win_installer:
deploy_kwargs['win_installer'] = win_installer
minion = salt.utils.cloud.minion_config(__opts__, vm_)
deploy_kwargs['master'] = minion['master']
deploy_kwargs['username'] = config.get_cloud_config_value(
'win_username', vm_, __opts__, default='Administrator'
)
deploy_kwargs['password'] = config.get_cloud_config_value(
'win_password', vm_, __opts__, default=''
)
# Store what was used to the deploy the VM
event_kwargs = copy.deepcopy(deploy_kwargs)
del event_kwargs['minion_pem']
del event_kwargs['minion_pub']
del event_kwargs['sudo_password']
if 'password' in event_kwargs:
del event_kwargs['password']
ret['deploy_kwargs'] = event_kwargs
salt.utils.cloud.fire_event(
'event',
'executing deploy script',
'salt/cloud/{0}/deploying'.format(vm_['name']),
{'kwargs': event_kwargs},
transport=__opts__['transport']
)
deployed = False
if win_installer:
deployed = salt.utils.cloud.deploy_windows(**deploy_kwargs)
else:
deployed = salt.utils.cloud.deploy_script(**deploy_kwargs)
if deployed:
log.info('Salt installed on {0}'.format(vm_['name']))
else:
log.error(
'Failed to start Salt on Cloud VM {0}'.format(
vm_['name']
)
)
log.info('Created Cloud VM {0[name]!r}'.format(vm_))
log.debug(
'{0[name]!r} VM creation details:\n{1}'.format(
vm_, pprint.pformat(response)
)
)
ret.update(response)
salt.utils.cloud.fire_event(
'event',
'created instance',
'salt/cloud/{0}/created'.format(vm_['name']),
{
'name': vm_['name'],
'profile': vm_['profile'],
'provider': vm_['provider'],
},
transport=__opts__['transport']
)
return ret
def list_nodes_full(mask='mask[id, hostname, primaryIpAddress, \
primaryBackendIpAddress, processorPhysicalCoreAmount, memoryCount]',
call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes_full function must be called with -f or --function.'
)
ret = {}
conn = get_conn(service='Account')
response = conn.getHardware(mask=mask)
for node in response:
ret[node['hostname']] = node
salt.utils.cloud.cache_node_list(ret, __active_provider_name__.split(':')[0], __opts__)
return ret
def list_nodes(call=None):
'''
Return a list of the VMs that are on the provider
'''
if call == 'action':
raise SaltCloudSystemExit(
'The list_nodes function must be called with -f or --function.'
)
ret = {}
nodes = list_nodes_full()
if 'error' in nodes:
raise SaltCloudSystemExit(
'An error occurred while listing nodes: {0}'.format(
nodes['error']['Errors']['Error']['Message']
)
)
for node in nodes:
ret[node] = {
'id': nodes[node]['hostname'],
'ram': nodes[node]['memoryCount'],
'cpus': nodes[node]['processorPhysicalCoreAmount'],
}
if 'primaryIpAddress' in nodes[node]:
ret[node]['public_ips'] = nodes[node]['primaryIpAddress']
if 'primaryBackendIpAddress' in nodes[node]:
ret[node]['private_ips'] = nodes[node]['primaryBackendIpAddress']
return ret
def list_nodes_select(call=None):
'''
Return a list of the VMs that are on the provider, with select fields
'''
return salt.utils.cloud.list_nodes_select(
list_nodes_full(), __opts__['query.selection'], call,
)
def show_instance(name, call=None):
'''
Show the details from SoftLayer concerning a guest
'''
if call != 'action':
raise SaltCloudSystemExit(
'The show_instance action must be called with -a or --action.'
)
nodes = list_nodes_full()
salt.utils.cloud.cache_node(nodes[name], __active_provider_name__, __opts__)
return nodes[name]
def destroy(name, call=None):
'''
Destroy a node.
CLI Example:
.. code-block:: bash
salt-cloud --destroy mymachine
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
)
salt.utils.cloud.fire_event(
'event',
'destroying instance',
'salt/cloud/{0}/destroying'.format(name),
{'name': name},
transport=__opts__['transport']
)
node = show_instance(name, call='action')
conn = get_conn(service='SoftLayer_Ticket')
response = conn.createCancelServerTicket(
{
'id': node['id'],
'reason': 'Salt Cloud Hardware Server Cancellation',
'content': 'Please cancel this server',
'cancelAssociatedItems': True,
'attachmentType': 'HARDWARE',
}
)
salt.utils.cloud.fire_event(
'event',
'destroyed instance',
'salt/cloud/{0}/destroyed'.format(name),
{'name': name},
transport=__opts__['transport']
)
if __opts__.get('update_cachedir', False) is True:
salt.utils.cloud.delete_minion_cachedir(name, __active_provider_name__.split(':')[0], __opts__)
return response
def list_vlans(call=None):
'''
List all VLANs associated with the account
'''
if call != 'function':
raise SaltCloudSystemExit(
'The list_vlans function must be called with -f or --function.'
)
conn = get_conn(service='Account')
return conn.getNetworkVlans()
def show_pricing(kwargs=None, call=None):
'''
Show pricing for a particular profile. This is only an estimate, based on
unofficial pricing sources.
CLI Examples:
.. code-block:: bash
salt-cloud -f show_pricing my-softlayerhw-config profile=my-profile
If pricing sources have not been cached, they will be downloaded. Once they
have been cached, they will not be updated automatically. To manually update
all prices, use the following command:
.. code-block:: bash
salt-cloud -f update_pricing <provider>
.. versionadded:: Beryllium
'''
profile = __opts__['profiles'].get(kwargs['profile'], {})
if not profile:
return {'Error': 'The requested profile was not found'}
# Make sure the profile belongs to Softlayer HW
provider = profile.get('provider', '0:0')
comps = provider.split(':')
if len(comps) < 2 or comps[1] != 'softlayer_hw':
return {'Error': 'The requested profile does not belong to Softlayer HW'}
raw = {}
ret = {}
ret['per_hour'] = 0
conn = get_conn(service='SoftLayer_Product_Item_Price')
for item in profile:
if item in ('profile', 'provider', 'location'):
continue
price = conn.getObject(id=profile[item])
raw[item] = price
ret['per_hour'] += decimal.Decimal(price.get('hourlyRecurringFee', 0))
ret['per_day'] = ret['per_hour'] * 24
ret['per_week'] = ret['per_day'] * 7
ret['per_month'] = ret['per_day'] * 30
ret['per_year'] = ret['per_week'] * 52
if kwargs.get('raw', False):
ret['_raw'] = raw
return {profile['profile']: ret}
| 30.348837 | 108 | 0.587931 |
6ba0f5ad790d80ee2e51d9e25a6aeeec885ce9e2 | 248 | py | Python | sites/manage.py | cmwaura/Final_Red_Scrap | 6b1b78de7d1129cda787e9f4688ddd409af39eb5 | [
"MIT"
] | null | null | null | sites/manage.py | cmwaura/Final_Red_Scrap | 6b1b78de7d1129cda787e9f4688ddd409af39eb5 | [
"MIT"
] | null | null | null | sites/manage.py | cmwaura/Final_Red_Scrap | 6b1b78de7d1129cda787e9f4688ddd409af39eb5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import os
import sys
if __name__ == "__main__":
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "sites.settings")
from django.core.management import execute_from_command_line
execute_from_command_line(sys.argv)
| 22.545455 | 69 | 0.770161 |
822e14762f7b038d41e0746a898ecc27a1d19fba | 835 | py | Python | pet_ros2_lcd_pkg/util/i2c_lib.py | Pet-Series/pet_ros2_lcd_pkg | 64b9d7313361a27627e1c5dddaad310685ba412f | [
"MIT"
] | null | null | null | pet_ros2_lcd_pkg/util/i2c_lib.py | Pet-Series/pet_ros2_lcd_pkg | 64b9d7313361a27627e1c5dddaad310685ba412f | [
"MIT"
] | null | null | null | pet_ros2_lcd_pkg/util/i2c_lib.py | Pet-Series/pet_ros2_lcd_pkg | 64b9d7313361a27627e1c5dddaad310685ba412f | [
"MIT"
] | null | null | null | import smbus
from time import *
class i2c_device:
def __init__(self, addr, port=1):
self.addr = addr
self.bus = smbus.SMBus(port)
# Write a single command
def write_cmd(self, cmd):
self.bus.write_byte(self.addr, cmd)
sleep(0.0001)
# Write a command and argument
def write_cmd_arg(self, cmd, data):
self.bus.write_byte_data(self.addr, cmd, data)
sleep(0.0001)
# Write a block of data
def write_block_data(self, cmd, data):
self.bus.write_block_data(self.addr, cmd, data)
sleep(0.0001)
# Read a single byte
def read(self):
return self.bus.read_byte(self.addr)
# Read
def read_data(self, cmd):
return self.bus.read_byte_data(self.addr, cmd)
# Read a block of data
def read_block_data(self, cmd):
return self.bus.read_block_data(self.addr, cmd) | 24.558824 | 53 | 0.674251 |
962de2a6b4f2b7c706d935e98ba124706d1a218e | 310 | py | Python | constants.py | sagge-miky/Super-HUGS-Revolution-98 | 00443e7da399db9faad7dd12b0656e8fd6fb33b0 | [
"BSD-2-Clause"
] | null | null | null | constants.py | sagge-miky/Super-HUGS-Revolution-98 | 00443e7da399db9faad7dd12b0656e8fd6fb33b0 | [
"BSD-2-Clause"
] | null | null | null | constants.py | sagge-miky/Super-HUGS-Revolution-98 | 00443e7da399db9faad7dd12b0656e8fd6fb33b0 | [
"BSD-2-Clause"
] | null | null | null | ############################################
# Created on 1-10-2013. Miguel Angel Astor #
############################################
# Debug constant. Set to False to turn off debugging messages.
DEBUG = False
# Number of players in the game. Should always be greater than or equal to one.
NUM_PLAYERS = 1
| 31 | 79 | 0.529032 |
58330de0e6cf3350e09345262493d726c4b28e45 | 1,236 | py | Python | src/orion/algo/random.py | christopher-beckham/orion | fc4aa14dd58bf50196aa6ad3a2869e3d86ca1a45 | [
"BSD-3-Clause"
] | null | null | null | src/orion/algo/random.py | christopher-beckham/orion | fc4aa14dd58bf50196aa6ad3a2869e3d86ca1a45 | [
"BSD-3-Clause"
] | null | null | null | src/orion/algo/random.py | christopher-beckham/orion | fc4aa14dd58bf50196aa6ad3a2869e3d86ca1a45 | [
"BSD-3-Clause"
] | null | null | null | # -*- coding: utf-8 -*-
"""
:mod:`orion.algo.random` -- Random sampler as optimization algorithm
======================================================================
.. module:: random
:platform: Unix
:synopsis: Draw and deliver samples from prior defined in problem's domain.
"""
from orion.algo.base import BaseAlgorithm
class Random(BaseAlgorithm):
"""Implement a algorithm that samples randomly from the problem's space."""
def __init__(self, space):
"""Random sampler takes no other hyperparameter that the problem's space
itself.
"""
super(Random, self).__init__(space)
def suggest(self, num=1):
"""Suggest a `num` of new sets of parameters. Randomly draw samples
from the import space and return them.
:param num: how many sets to be suggested.
.. note:: New parameters must be compliant with the problem's domain
`orion.algo.space.Space`.
"""
return self.space.sample(num)
def observe(self, points, results):
"""Observe evaluation `results` corresponding to list of `points` in
space.
A simple random sampler though does not take anything into account.
"""
pass
| 29.428571 | 80 | 0.609223 |
29783949a6bc7d614a6ce1bb0be393d91e00431a | 1,222 | py | Python | netbox_aws/filters.py | lampwins/interop2020-netbox-plugins | e983b1875c58230228448deca6b129be9fc40c1e | [
"Apache-2.0"
] | 4 | 2020-10-06T19:00:01.000Z | 2021-04-26T19:37:00.000Z | netbox_aws/filters.py | lampwins/interop2020-netbox-plugins | e983b1875c58230228448deca6b129be9fc40c1e | [
"Apache-2.0"
] | null | null | null | netbox_aws/filters.py | lampwins/interop2020-netbox-plugins | e983b1875c58230228448deca6b129be9fc40c1e | [
"Apache-2.0"
] | 1 | 2021-04-16T15:24:24.000Z | 2021-04-16T15:24:24.000Z | import django_filters
from django.db.models import Q
from utilities.filters import BaseFilterSet
from ipam.models import Prefix
from netbox_aws.models import VPC
from netbox_aws.choices import VPCRegionChoices
class VPCFilterSet(BaseFilterSet):
q = django_filters.CharFilter(
method='search',
label='Search',
)
region = django_filters.MultipleChoiceFilter(
choices=VPCRegionChoices,
null_value=None
)
container_prefix_id = django_filters.ModelMultipleChoiceFilter(
queryset=Prefix.objects.all(),
label='Prefix (ID)',
)
container_prefix = django_filters.ModelMultipleChoiceFilter(
field_name='container_prefix__prefix',
queryset=Prefix.objects.all(),
to_field_name='prefix',
label='Prefix',
)
class Meta:
model = VPC
fields = [
'id', 'name', 'slug', 'description'
]
def search(self, queryset, name, value):
if not value.strip():
return queryset
qs_filter = (
Q(name__icontains=value) |
Q(name__icontains=value) |
Q(description__icontains=value)
)
return queryset.filter(qs_filter)
| 26.565217 | 67 | 0.643208 |
749bba2d64b24763676674bf43c5e57434110130 | 1,722 | py | Python | data/lccc/process.py | gmftbyGMFTBY/HashRetrieval | 08c8998a802d1237aada7e30d440d34d92788173 | [
"MIT"
] | 1 | 2021-12-08T12:40:24.000Z | 2021-12-08T12:40:24.000Z | data/lccc/process.py | gmftbyGMFTBY/HashRetrieval | 08c8998a802d1237aada7e30d440d34d92788173 | [
"MIT"
] | null | null | null | data/lccc/process.py | gmftbyGMFTBY/HashRetrieval | 08c8998a802d1237aada7e30d440d34d92788173 | [
"MIT"
] | null | null | null | from tqdm import tqdm
import ipdb, json, random, csv, torch
def read_file(path, mode='train'):
with open(path) as f:
data = json.load(f)
if mode == 'train':
data = data[mode]
data = [[''.join(j.split()) for j in i] for i in data]
responses = [i[-1] for i in data]
dialogs = []
for i in tqdm(data):
i = [''.join(j.split()) for j in i]
if mode == 'train':
neg = random.choice(responses)
dialogs.append((i, i[:-1] + [neg]))
else:
neg = [i[:-1] + [j] for j in random.sample(responses, 9)]
dialogs.append((i, neg))
return dialogs
def write_file(dataset, path, mode='train'):
with open(path, 'w') as f:
for data in tqdm(dataset):
pos_data, neg_data = data
pos_data = '\t'.join(pos_data)
if mode == 'train':
neg_data = '\t'.join(neg_data)
f.write(f'1\t{pos_data}\n')
f.write(f'0\t{neg_data}\n')
else:
neg_data = ['\t'.join(i) for i in neg_data]
f.write(f'1\t{pos_data}\n')
for i in neg_data:
f.write(f'0\t{i}\n')
if __name__ == '__main__':
seed = 50
random.seed(seed)
torch.manual_seed(seed)
if torch.cuda.is_available():
torch.cuda.manual_seed_all(seed)
train_cut_size = 2000000
dataset = read_file('LCCC-base.json', mode='train')
dataset = random.sample(dataset, train_cut_size)
write_file(dataset, 'train.txt', mode='train')
dataset = read_file('LCCC-base_test.json', mode='test')
write_file(dataset, 'test.txt', mode='test')
| 34.44 | 73 | 0.52381 |
e5033799202a9feaa1d630b9ae92754ca6af73be | 855 | py | Python | src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spynnaker/pyNN/models/utility_models/delay_extension_partitioned_vertex.py | Roboy/LSM_SpiNNaker_MyoArm | 04fa1eaf78778edea3ba3afa4c527d20c491718e | [
"BSD-3-Clause"
] | 2 | 2020-11-01T13:22:11.000Z | 2020-11-01T13:22:20.000Z | src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spynnaker/pyNN/models/utility_models/delay_extension_partitioned_vertex.py | Roboy/LSM_SpiNNaker_MyoArm | 04fa1eaf78778edea3ba3afa4c527d20c491718e | [
"BSD-3-Clause"
] | null | null | null | src/spinnaker_ros_lsm/venv/lib/python2.7/site-packages/spynnaker/pyNN/models/utility_models/delay_extension_partitioned_vertex.py | Roboy/LSM_SpiNNaker_MyoArm | 04fa1eaf78778edea3ba3afa4c527d20c491718e | [
"BSD-3-Clause"
] | null | null | null | from pacman.model.partitioned_graph.partitioned_vertex import PartitionedVertex
from spinn_front_end_common.interface.provenance\
.provides_provenance_data_from_machine_impl \
import ProvidesProvenanceDataFromMachineImpl
from enum import Enum
class DelayExtensionPartitionedVertex(
PartitionedVertex, ProvidesProvenanceDataFromMachineImpl):
_DELAY_EXTENSION_REGIONS = Enum(
value="DELAY_EXTENSION_REGIONS",
names=[('SYSTEM', 0),
('DELAY_PARAMS', 1),
('PROVENANCE_REGION', 2)])
def __init__(self, resources_required, label, constraints=None):
PartitionedVertex.__init__(
self, resources_required, label, constraints=constraints)
ProvidesProvenanceDataFromMachineImpl.__init__(
self, self._DELAY_EXTENSION_REGIONS.PROVENANCE_REGION.value, 0)
| 37.173913 | 79 | 0.745029 |
fc109238e788efdf34f7664f82f7c70eb8fe7d8f | 3,329 | py | Python | students/K33402/Krivoshapkina_Aitalina/LR_2/PR_2.2/django_project_Krivoshapkina/settings.py | aytakr/ITMO_ICT_WebDevelopment_2021-2022 | 57c0eef5e1f413c7f031ee001d59e5122f990f26 | [
"MIT"
] | null | null | null | students/K33402/Krivoshapkina_Aitalina/LR_2/PR_2.2/django_project_Krivoshapkina/settings.py | aytakr/ITMO_ICT_WebDevelopment_2021-2022 | 57c0eef5e1f413c7f031ee001d59e5122f990f26 | [
"MIT"
] | null | null | null | students/K33402/Krivoshapkina_Aitalina/LR_2/PR_2.2/django_project_Krivoshapkina/settings.py | aytakr/ITMO_ICT_WebDevelopment_2021-2022 | 57c0eef5e1f413c7f031ee001d59e5122f990f26 | [
"MIT"
] | null | null | null | """
Django settings for django_project_Krivoshapkina project.
Generated by 'django-admin startproject' using Django 4.0.
For more information on this file, see
https://docs.djangoproject.com/en/4.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.0/ref/settings/
"""
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-=31g+is9emhk+#eani9_s01kmzos(4eck$s7#lr@8lq-a5uujo'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'project_first_app'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'django_project_Krivoshapkina.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [BASE_DIR/"templates"],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'django_project_Krivoshapkina.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
| 26.632 | 91 | 0.709522 |
53bb2c260f6316a060aa69a9ca70882ac1037f01 | 7,884 | py | Python | ImageAnalysis/ImageAnalysis/python/references/bead-designer-test/gui/beadgui.py | mikebourbeauart/PerlerPrinter | 8c5023de6bb9b3cbe2bc28c1c823030dfd708db4 | [
"MIT"
] | null | null | null | ImageAnalysis/ImageAnalysis/python/references/bead-designer-test/gui/beadgui.py | mikebourbeauart/PerlerPrinter | 8c5023de6bb9b3cbe2bc28c1c823030dfd708db4 | [
"MIT"
] | 2 | 2021-09-07T23:43:53.000Z | 2022-01-13T00:39:55.000Z | ImageAnalysis/ImageAnalysis/python/references/bead-designer-test/gui/beadgui.py | mikebourbeauart/PerlerPrinter | 8c5023de6bb9b3cbe2bc28c1c823030dfd708db4 | [
"MIT"
] | 1 | 2019-10-21T17:12:07.000Z | 2019-10-21T17:12:07.000Z | # -*- coding: utf-8 -*-
###########################################################################
## Python code generated with wxFormBuilder (version Jun 30 2011)
## http://www.wxformbuilder.org/
##
## PLEASE DO "NOT" EDIT THIS FILE!
###########################################################################
import wx
import wx.xrc
###########################################################################
## Class Designer
###########################################################################
class Designer ( wx.Frame ):
def __init__( self, parent ):
wx.Frame.__init__ ( self, parent, id = wx.ID_ANY, title = u"Bead Pattern Generator v1.0", pos = wx.DefaultPosition, size = wx.Size( 780,550 ), style = wx.DEFAULT_FRAME_STYLE|wx.TAB_TRAVERSAL )
self.SetSizeHintsSz( wx.Size( 600,400 ), wx.DefaultSize )
bSizer1 = wx.BoxSizer( wx.VERTICAL )
self.m_panel1 = wx.Panel( self, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer2 = wx.BoxSizer( wx.VERTICAL )
bSizer3 = wx.BoxSizer( wx.HORIZONTAL )
self.m_panel3 = wx.Panel( self.m_panel1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
self.m_panel3.SetMinSize( wx.Size( 300,-1 ) )
self.m_panel3.SetMaxSize( wx.Size( 300,-1 ) )
bSizer4 = wx.BoxSizer( wx.VERTICAL )
sbSizer2 = wx.StaticBoxSizer( wx.StaticBox( self.m_panel3, wx.ID_ANY, u"Image File" ), wx.VERTICAL )
self.m_filePicker1 = wx.FilePickerCtrl( self.m_panel3, wx.ID_ANY, wx.EmptyString, u"Select a file", u"*.gif; *.jpg; *.jpeg; *.png", wx.DefaultPosition, wx.DefaultSize, wx.FLP_DEFAULT_STYLE )
sbSizer2.Add( self.m_filePicker1, 0, wx.ALL|wx.EXPAND, 5 )
bSizer4.Add( sbSizer2, 0, wx.ALL|wx.EXPAND, 5 )
sbSizer21 = wx.StaticBoxSizer( wx.StaticBox( self.m_panel3, wx.ID_ANY, u"Bead Options" ), wx.HORIZONTAL )
bSizer8 = wx.BoxSizer( wx.VERTICAL )
self.m_cb_hama = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Hama", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_cb_hama.SetValue(True)
bSizer8.Add( self.m_cb_hama, 0, wx.ALL, 5 )
self.m_cb_perler = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Perler", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer8.Add( self.m_cb_perler, 0, wx.ALL, 5 )
self.m_cb_nabbi = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Nabbi", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer8.Add( self.m_cb_nabbi, 0, wx.ALL, 5 )
self.m_cb_hobby = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"PictureBeads", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer8.Add( self.m_cb_hobby, 0, wx.ALL, 5 )
sbSizer21.Add( bSizer8, 2, wx.ALL|wx.EXPAND, 5 )
bSizer9 = wx.BoxSizer( wx.VERTICAL )
self.m_cb_standard = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Include Standard Beads", wx.DefaultPosition, wx.DefaultSize, 0 )
self.m_cb_standard.SetValue(True)
bSizer9.Add( self.m_cb_standard, 0, wx.ALL, 5 )
self.m_cb_metal = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Include Metalic Beads", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer9.Add( self.m_cb_metal, 0, wx.ALL, 5 )
self.m_cb_glitter = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Include Glitter Beads", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer9.Add( self.m_cb_glitter, 0, wx.ALL, 5 )
self.m_cb_neon = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Include Neon Beads", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer9.Add( self.m_cb_neon, 0, wx.ALL, 5 )
self.m_cb_trans = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Include Translucent Beads", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer9.Add( self.m_cb_trans, 0, wx.ALL, 5 )
self.m_cb_flour = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Include Flourescent Beads", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer9.Add( self.m_cb_flour, 0, wx.ALL, 5 )
self.m_cb_glow = wx.CheckBox( self.m_panel3, wx.ID_ANY, u"Glow in the Dark", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer9.Add( self.m_cb_glow, 0, wx.ALL, 5 )
sbSizer21.Add( bSizer9, 3, wx.EXPAND, 5 )
bSizer4.Add( sbSizer21, 1, wx.ALL|wx.EXPAND, 5 )
bSizer13 = wx.BoxSizer( wx.VERTICAL )
self.m_generate = wx.Button( self.m_panel3, wx.ID_ANY, u"Generate Design", wx.DefaultPosition, wx.DefaultSize, 0 )
bSizer13.Add( self.m_generate, 0, 0, 5 )
bSizer4.Add( bSizer13, 0, wx.ALL|wx.EXPAND, 5 )
self.m_panel3.SetSizer( bSizer4 )
self.m_panel3.Layout()
bSizer4.Fit( self.m_panel3 )
bSizer3.Add( self.m_panel3, 0, wx.EXPAND, 5 )
self.m_panel2 = wx.Panel( self.m_panel1, wx.ID_ANY, wx.DefaultPosition, wx.DefaultSize, wx.TAB_TRAVERSAL )
bSizer5 = wx.BoxSizer( wx.VERTICAL )
sbSizer1 = wx.StaticBoxSizer( wx.StaticBox( self.m_panel2, wx.ID_ANY, u"Design View" ), wx.VERTICAL )
self.previewPane = wx.BoxSizer( wx.VERTICAL )
sbSizer1.Add( self.previewPane, 1, wx.EXPAND, 5 )
bSizer5.Add( sbSizer1, 1, wx.ALL|wx.EXPAND, 5 )
bSizer11 = wx.BoxSizer( wx.HORIZONTAL )
self.m_radioBtn3 = wx.RadioButton( self.m_panel2, wx.ID_ANY, u"Design View", wx.DefaultPosition, wx.DefaultSize, wx.RB_GROUP )
self.m_radioBtn3.SetValue( True )
bSizer11.Add( self.m_radioBtn3, 0, wx.ALL, 5 )
self.m_radioBtn4 = wx.RadioButton( self.m_panel2, wx.ID_ANY, u"Materials View", wx.DefaultPosition, wx.DefaultSize, wx.RB_GROUP )
bSizer11.Add( self.m_radioBtn4, 0, wx.ALL, 5 )
bSizer5.Add( bSizer11, 0, wx.ALL|wx.EXPAND, 5 )
self.m_panel2.SetSizer( bSizer5 )
self.m_panel2.Layout()
bSizer5.Fit( self.m_panel2 )
bSizer3.Add( self.m_panel2, 1, wx.EXPAND, 5 )
bSizer2.Add( bSizer3, 1, wx.EXPAND, 5 )
self.m_panel1.SetSizer( bSizer2 )
self.m_panel1.Layout()
bSizer2.Fit( self.m_panel1 )
bSizer1.Add( self.m_panel1, 1, wx.EXPAND, 5 )
self.SetSizer( bSizer1 )
self.Layout()
self.m_menubar1 = wx.MenuBar( 0 )
self.m_menu1 = wx.Menu()
self.m_menuItem1 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u"Load Image from File", wx.EmptyString, wx.ITEM_NORMAL )
self.m_menu1.AppendItem( self.m_menuItem1 )
self.m_menuItem2 = wx.MenuItem( self.m_menu1, wx.ID_ANY, u"Exit", wx.EmptyString, wx.ITEM_NORMAL )
self.m_menu1.AppendItem( self.m_menuItem2 )
self.m_menubar1.Append( self.m_menu1, u"File" )
self.m_menu4 = wx.Menu()
self.m_menuItem3 = wx.MenuItem( self.m_menu4, wx.ID_ANY, u"Generate Design", wx.EmptyString, wx.ITEM_NORMAL )
self.m_menu4.AppendItem( self.m_menuItem3 )
self.m_menubar1.Append( self.m_menu4, u"Generate" )
self.m_menu5 = wx.Menu()
self.m_menuItem4 = wx.MenuItem( self.m_menu5, wx.ID_ANY, u"Design View", wx.EmptyString, wx.ITEM_NORMAL )
self.m_menu5.AppendItem( self.m_menuItem4 )
self.m_menuItem5 = wx.MenuItem( self.m_menu5, wx.ID_ANY, u"Materials View", wx.EmptyString, wx.ITEM_NORMAL )
self.m_menu5.AppendItem( self.m_menuItem5 )
self.m_menubar1.Append( self.m_menu5, u"View" )
self.m_menu6 = wx.Menu()
self.m_menuItem6 = wx.MenuItem( self.m_menu6, wx.ID_ANY, u"About", wx.EmptyString, wx.ITEM_NORMAL )
self.m_menu6.AppendItem( self.m_menuItem6 )
self.m_menubar1.Append( self.m_menu6, u"Help" )
self.SetMenuBar( self.m_menubar1 )
self.Centre( wx.BOTH )
# Connect Events
self.m_filePicker1.Bind( wx.EVT_FILEPICKER_CHANGED, self.onImageSelect )
self.m_generate.Bind( wx.EVT_BUTTON, self.onGenerate )
self.Bind( wx.EVT_MENU, self.onLoadImage, id = self.m_menuItem1.GetId() )
self.Bind( wx.EVT_MENU, self.onExit, id = self.m_menuItem2.GetId() )
self.Bind( wx.EVT_MENU, self.onGenerate, id = self.m_menuItem3.GetId() )
self.Bind( wx.EVT_MENU, self.onAbout, id = self.m_menuItem6.GetId() )
def __del__( self ):
pass
# Virtual event handlers, overide them in your derived class
def onImageSelect( self, event ):
event.Skip()
def onGenerate( self, event ):
event.Skip()
def onLoadImage( self, event ):
event.Skip()
def onExit( self, event ):
event.Skip()
def onAbout( self, event ):
event.Skip()
| 38.458537 | 194 | 0.67656 |
f4555a3ba69e21bc2142f801353a2d1227719ad5 | 893 | py | Python | objectdata.py | Retropunchout/Triton | 3845f07add811b32d3ada5d2f9cf0169c326b58d | [
"MIT"
] | null | null | null | objectdata.py | Retropunchout/Triton | 3845f07add811b32d3ada5d2f9cf0169c326b58d | [
"MIT"
] | null | null | null | objectdata.py | Retropunchout/Triton | 3845f07add811b32d3ada5d2f9cf0169c326b58d | [
"MIT"
] | null | null | null | objectdata = """
---
!!python/object:__main__.item
name: bandage
description: "A Bandage, used for binding wounds"
static: False
wearable: False
wieldable: False
getable: True
classrestr: Medic
rarity: 1
dmgmod: 0
defmod: 0
useaction: itemheal()
---
!!python/object:__main__.item
name: pipe
description: "A rusty pipe"
static: False
wearable: False
wieldable: True
getable: True
classrestr: Medic, Engineer, Marine
rarity: 1
dmgmod: 2
defmod: 0
useaction: itembash()
---
!!python/object:__main__.item
name: medical bench
description: "A standard medical bench"
static: False
wearable: False
wieldable: True
getable: False
classrestr: Medic, Engineer, Marine
rarity: 1
dmgmod: 2
defmod: 0
useaction: None
"""
| 21.261905 | 54 | 0.602464 |
d9b761c0f7b2718acaf7735ac60f83f0001f1fd5 | 1,239 | py | Python | repos/system_upgrade/el7toel8/actors/scancpu/tests/test_scancpu.py | panovotn/leapp-repository | e80bdbf65393e68bc2e91b43b46fdd9b9b787878 | [
"Apache-2.0"
] | null | null | null | repos/system_upgrade/el7toel8/actors/scancpu/tests/test_scancpu.py | panovotn/leapp-repository | e80bdbf65393e68bc2e91b43b46fdd9b9b787878 | [
"Apache-2.0"
] | null | null | null | repos/system_upgrade/el7toel8/actors/scancpu/tests/test_scancpu.py | panovotn/leapp-repository | e80bdbf65393e68bc2e91b43b46fdd9b9b787878 | [
"Apache-2.0"
] | null | null | null | import os
from leapp.libraries.actor import cpu
from leapp.libraries.common import testutils
from leapp.libraries.stdlib import api
from leapp.models import CPUInfo
class mocked_get_cpuinfo(object):
def __init__(self, filename):
self.filename = filename
def __call__(self):
"""
Return lines of the self.filename test file located in the files directory.
Those files contain /proc/cpuinfo content from several machines.
"""
with open(os.path.join('tests/files', self.filename), 'rb') as fp:
return fp.readlines()
def test_machine_type(monkeypatch):
# cpuinfo doesn't contain a machine field
mocked_cpuinfo = mocked_get_cpuinfo('cpuinfo_x86_64')
monkeypatch.setattr(cpu, '_get_cpuinfo', mocked_cpuinfo)
monkeypatch.setattr(api, 'produce', testutils.produce_mocked())
cpu.process()
assert api.produce.called == 1
assert CPUInfo() == api.produce.model_instances[0]
# cpuinfo contains a machine field
api.produce.called = 0
api.produce.model_instances = []
mocked_cpuinfo.filename = 'cpuinfo_s390x'
cpu.process()
assert api.produce.called == 1
assert CPUInfo(machine_type=2827) == api.produce.model_instances[0]
| 31.769231 | 83 | 0.709443 |
71ac960e38e33083ba09a5a435ae4c640892e7e9 | 263 | py | Python | 00_note.py | twtrubiks/leetcode-python | b75d84cefc3d11e43c2648cb9156e65587e398eb | [
"MIT"
] | 25 | 2018-01-15T00:09:02.000Z | 2022-01-27T02:29:15.000Z | 00_note.py | twtrubiks/leetcode-python | b75d84cefc3d11e43c2648cb9156e65587e398eb | [
"MIT"
] | null | null | null | 00_note.py | twtrubiks/leetcode-python | b75d84cefc3d11e43c2648cb9156e65587e398eb | [
"MIT"
] | 18 | 2018-01-07T09:36:42.000Z | 2021-12-14T11:08:05.000Z | Reverse_Linked_List_206
136 Single Number
137 Single Number II
168 Excel Sheet Column Title
171 Excel Sheet Column Number
190 Reverse Bits
231 Power of Two
258 Add Digits
263 Ugly Number
292 Nim Game
326 Power of Three
Add_Binary_067
Count_and_Say_038 | 10.52 | 29 | 0.806084 |
dd0b584f365eac7af8820ca188dac1d77baf0735 | 4,252 | py | Python | language_model/word_frequency.py | naderabdalghani/project-rev | 3205d42a2220372783ab49ce8c3c70a4c4b9ad7e | [
"Apache-2.0"
] | 2 | 2021-12-13T04:19:30.000Z | 2022-02-16T16:27:20.000Z | language_model/word_frequency.py | MuhanadAtef/project-rev | 3205d42a2220372783ab49ce8c3c70a4c4b9ad7e | [
"Apache-2.0"
] | null | null | null | language_model/word_frequency.py | MuhanadAtef/project-rev | 3205d42a2220372783ab49ce8c3c70a4c4b9ad7e | [
"Apache-2.0"
] | 2 | 2021-08-17T06:25:36.000Z | 2021-08-17T12:45:33.000Z | import pickle
import string
from collections import Counter
from .utils import parse_into_words
class WordFrequency:
def __init__(self):
self._dictionary = Counter()
self._total_words = 0
self._unique_words = 0
self._letters = set()
self._longest_word_length = 0
self._tokenizer = parse_into_words
def __contains__(self, key):
""" Check if dictionary contains key """
key = key.lower()
return key in self._dictionary
def __getitem__(self, key):
""" Get frequency """
key = key.lower()
return self._dictionary[key]
def __iter__(self):
""" iter support """
for word in self._dictionary:
yield word
def pop(self, key, default=None):
""" Delete the key and return the associated value or default if not
found
Args:
key (str): The key to remove
default (obj): The value to return if key is not present """
key = key.lower()
return self._dictionary.pop(key, default)
@property
def dictionary(self):
""" Counter: A counting dictionary of all words in the corpus and the \
number of times each has been seen
Note:
Not settable """
return self._dictionary
@property
def total_words(self):
""" int: The sum of all word occurrences in the word frequency \
dictionary
Note:
Not settable """
return self._total_words
@property
def unique_words(self):
""" int: The total number of unique words in the word frequency list
Note:
Not settable """
return self._unique_words
@property
def letters(self):
""" str: The listing of all letters found within the corpus
Note:
Not settable """
return self._letters
@property
def longest_word_length(self):
""" int: The longest word length in the dictionary
Note:
Not settable """
return self._longest_word_length
def keys(self):
""" Iterator over the key of the dictionary
Yields:
str: The next key in the dictionary"""
for key in self._dictionary.keys():
yield key
def words(self):
""" Iterator over the words in the dictionary
Yields:
str: The next word in the dictionary
"""
for word in self._dictionary.keys():
yield word
def items(self):
""" Iterator over the words in the dictionary
Yields:
str: The next word in the dictionary
int: The number of instances in the dictionary
Note:
This is the same as `dict.items()` """
for word in self._dictionary.keys():
yield word, self._dictionary[word]
def load_dictionary(self, filename):
""" Load in a pre-built word frequency list
Args:
filename (str): The filepath to the json (optionally gzipped) \
file to be loaded """
self._dictionary.update(pickle.load(open(filename, 'rb')))
self._update_dictionary()
def remove_by_threshold(self, threshold=5):
""" Remove all words at, or below, the provided threshold
Args:
threshold (int): The threshold at which a word is to be removed """
keys = [x for x in self._dictionary.keys()]
for key in keys:
if self._dictionary[key] <= threshold:
self._dictionary.pop(key)
self._update_dictionary()
def _update_dictionary(self):
""" Update the word frequency object """
self._longest_word_length = 0
self._total_words = sum(self._dictionary.values())
self._unique_words = len(self._dictionary.keys())
self._letters = set()
for key in self._dictionary:
if len(key[0]) > self._longest_word_length:
self._longest_word_length = len(key[0])
self._longest_word = key[0]
self._letters.update(string.ascii_lowercase)
| 31.969925 | 83 | 0.574553 |
3c2ac7d7d5f7f110839e752f7816d637cf26fc0f | 4,314 | py | Python | flexget/tests/test_npo_watchlist.py | ksurl/flexget | a54dc25780b62f80d2e638278277a945428ffd05 | [
"MIT"
] | null | null | null | flexget/tests/test_npo_watchlist.py | ksurl/flexget | a54dc25780b62f80d2e638278277a945428ffd05 | [
"MIT"
] | 13 | 2022-03-28T03:25:30.000Z | 2022-03-28T10:25:44.000Z | flexget/tests/test_npo_watchlist.py | aidan-/Flexget | 5622436a412918ef204c51e9f984cd9fe784ea7c | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
import pytest
@pytest.mark.online
class TestNpoWatchlistInfo:
config = """
tasks:
test:
npo_watchlist:
email: '8h3ga3+7nzf7xueal70o@sharklasers.com'
password: 'Fl3xg3t!'
"""
def test_npowatchlist_lookup(self, execute_task):
"""npo_watchlist: Test npo watchlist lookup (ONLINE)"""
task = execute_task('test')
entry = task.find_entry(
url='https://www.npostart.nl/zondag-met-lubach/09-11-2014/VPWON_1220631'
) # s01e01
assert entry['npo_id'] == 'VPWON_1220631'
assert entry['npo_url'] == 'https://www.npostart.nl/zondag-met-lubach/VPWON_1250334'
assert entry['npo_name'] == 'Zondag met Lubach'
assert (
entry['npo_description']
== 'Zeven dagen nieuws in dertig minuten, satirisch geremixt door Arjen Lubach. Nog actueler, nog satirischer en nog vaker nog het woord nog.'
)
assert entry['npo_runtime'] == '32'
assert entry['npo_premium'] is False
assert (
entry['npo_version'] == 'NPO.6586736ba8ccc16e4f9288118f71dbd3c81e21e8'
) # specify for which version of NPO website we did run this unittest
entry = (
task.find_entry(url='https://www.npostart.nl/14-01-2014/VARA_101348553') is None
) # episode with weird (and broken) URL and should be skipped
entry = task.find_entry(
url='https://www.npostart.nl/zembla/12-12-2013/VARA_101320582'
) # check that the next episode it there though
assert entry['npo_id'] == 'VARA_101320582'
assert entry['npo_url'] == 'https://www.npostart.nl/zembla/VARA_101377863'
assert entry['npo_name'] == 'Zembla'
entry = task.find_entry(
url='https://www.npostart.nl/typisch-overvecht/24-05-2018/BV_101388144'
)
assert entry['npo_id'] == 'BV_101388144'
assert entry['npo_url'] == 'https://www.npostart.nl/typisch/BV_101386658'
assert entry['npo_name'] == 'Typisch'
entry = task.find_entry(
url='https://www.npostart.nl/zembla/14-10-2007/VARA_101153941'
) # episode without a running time
assert entry['npo_runtime'] == '0'
assert (
task.find_entry(url='https://www.npostart.nl/11-04-2014/KN_1656572') is None
) # episode without a name (and broken URL) that should be skipped
assert (
task.find_entry(
url='https://www.npostart.nl/zondag-met-lubach-westeros-the-series/04-09-2017/WO_VPRO_10651334'
)
is None
) # a trailer for the series, that should not be listed
@pytest.mark.online
class TestNpoWatchlistPremium:
config = """
tasks:
test:
npo_watchlist:
email: '8h3ga3+7nzf7xueal70o@sharklasers.com'
password: 'Fl3xg3t!'
download_premium: yes
"""
def test_npowatchlist_lookup(self, execute_task):
"""npo_watchlist: Test npo watchlist lookup (ONLINE)"""
task = execute_task('test')
entry = task.find_entry(
url='https://www.npostart.nl/hollands-hoop/08-02-2020/BV_101396963'
) # a premium serie
assert entry['npo_id'] == 'BV_101396963'
assert entry['npo_url'] == 'https://www.npostart.nl/hollands-hoop/BV_101385153'
assert entry['npo_name'] == 'Hollands Hoop'
assert entry['npo_runtime'] == '53'
assert entry['npo_premium'] is True
@pytest.mark.online
class TestNpoWatchlistLanguageTheTVDBLookup:
config = """
tasks:
test:
npo_watchlist:
email: '8h3ga3+7nzf7xueal70o@sharklasers.com'
password: 'Fl3xg3t!'
thetvdb_lookup: yes
"""
def test_tvdblang_lookup(self, execute_task):
"""npo_watchlist: Test npo_watchlist tvdb language lookup (ONLINE)"""
task = execute_task('test')
entry = task.find_entry(
url='https://www.npostart.nl/zondag-met-lubach/09-11-2014/VPWON_1220631'
) # s01e01
assert entry['npo_language'] == 'nl'
assert entry['language'] == 'nl'
assert entry['tvdb_id'] == 288799
assert entry['tvdb_language'] == 'nl'
| 36.559322 | 154 | 0.605471 |
1640502d99bdbd3e6a5b8490187de0fe3278749c | 297 | py | Python | project.py | soxoj/maigret-maltego | 01ad6409622fd6b777b89452eb5112b27724a34e | [
"Apache-2.0"
] | 18 | 2021-12-22T21:14:05.000Z | 2022-03-25T00:34:14.000Z | project.py | extracru/maltego-transformation-template | 44fb514871bd406a8a401a48d85d7bc3f4aac34c | [
"Apache-2.0"
] | 2 | 2022-02-08T21:20:43.000Z | 2022-02-23T14:40:26.000Z | project.py | extracru/maltego-transformation-template | 44fb514871bd406a8a401a48d85d7bc3f4aac34c | [
"Apache-2.0"
] | 3 | 2022-02-26T02:52:54.000Z | 2022-03-25T00:34:15.000Z | import sys
import transforms
from maltego_trx.registry import register_transform_function, register_transform_classes
from maltego_trx.server import app, application
from maltego_trx.handler import handle_run
register_transform_classes(transforms)
handle_run(__name__, sys.argv, app)
| 27 | 89 | 0.841751 |
4d18da6f83a233de5db88a60e6f2db921a6eda95 | 583 | py | Python | chat_classifier/views.py | tanaysh7/Classifier_Service | e8641a579aa50018c5368e4974c14bb052a3ad5b | [
"MIT"
] | null | null | null | chat_classifier/views.py | tanaysh7/Classifier_Service | e8641a579aa50018c5368e4974c14bb052a3ad5b | [
"MIT"
] | null | null | null | chat_classifier/views.py | tanaysh7/Classifier_Service | e8641a579aa50018c5368e4974c14bb052a3ad5b | [
"MIT"
] | null | null | null | # from django.shortcuts import render
from django.http import JsonResponse
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
import requests
from .model import predict
@csrf_exempt
def home(request):
#response = requests.get('http://freegeoip.net/json/')
#geodata = response.json()
return JsonResponse({
"dermalogica.com": {
"name":"livechat-classifier",
"version":"1.0.0"
}
})
@csrf_exempt
def predict_chat(request, chat_string):
return JsonResponse(predict(chat_string))
| 17.666667 | 58 | 0.692967 |
e4a37ed8173afa0f9650aeb065a9fd4a1f68b2b0 | 63,426 | py | Python | coloredlogs/__init__.py | cclloyd/python-coloredlogs | 4a3683ff7ead6298c8ac9d3b5dded535ebc7ff79 | [
"MIT"
] | null | null | null | coloredlogs/__init__.py | cclloyd/python-coloredlogs | 4a3683ff7ead6298c8ac9d3b5dded535ebc7ff79 | [
"MIT"
] | null | null | null | coloredlogs/__init__.py | cclloyd/python-coloredlogs | 4a3683ff7ead6298c8ac9d3b5dded535ebc7ff79 | [
"MIT"
] | null | null | null | # Colored terminal output for Python's logging module.
#
# Author: Peter Odding <peter@peterodding.com>
# Last Change: February 16, 2020
# URL: https://coloredlogs.readthedocs.io
"""
Colored terminal output for Python's :mod:`logging` module.
.. contents::
:local:
Getting started
===============
The easiest way to get started is by importing :mod:`coloredlogs` and calling
:mod:`coloredlogs.install()` (similar to :func:`logging.basicConfig()`):
>>> import coloredlogs, logging
>>> coloredlogs.install(level='DEBUG')
>>> logger = logging.getLogger('some.module.name')
>>> logger.info("this is an informational message")
2015-10-22 19:13:52 peter-macbook some.module.name[28036] INFO this is an informational message
The :mod:`~coloredlogs.install()` function creates a :class:`ColoredFormatter`
that injects `ANSI escape sequences`_ into the log output.
.. _ANSI escape sequences: https://en.wikipedia.org/wiki/ANSI_escape_code#Colors
Environment variables
=====================
The following environment variables can be used to configure the
:mod:`coloredlogs` module without writing any code:
============================= ============================ ==================================
Environment variable Default value Type of value
============================= ============================ ==================================
``$COLOREDLOGS_AUTO_INSTALL`` 'false' a boolean that controls whether
:func:`auto_install()` is called
``$COLOREDLOGS_LOG_LEVEL`` 'INFO' a log level name
``$COLOREDLOGS_LOG_FORMAT`` :data:`DEFAULT_LOG_FORMAT` a log format string
``$COLOREDLOGS_DATE_FORMAT`` :data:`DEFAULT_DATE_FORMAT` a date/time format string
``$COLOREDLOGS_LEVEL_STYLES`` :data:`DEFAULT_LEVEL_STYLES` see :func:`parse_encoded_styles()`
``$COLOREDLOGS_FIELD_STYLES`` :data:`DEFAULT_FIELD_STYLES` see :func:`parse_encoded_styles()`
============================= ============================ ==================================
Examples of customization
=========================
Here we'll take a look at some examples of how you can customize
:mod:`coloredlogs` using environment variables.
.. contents::
:local:
About the defaults
------------------
Here's a screen shot of the default configuration for easy comparison with the
screen shots of the following customizations (this is the same screen shot that
is shown in the introduction):
.. image:: images/defaults.png
:alt: Screen shot of colored logging with defaults.
The screen shot above was taken from ``urxvt`` which doesn't support faint text
colors, otherwise the color of green used for `debug` messages would have
differed slightly from the color of green used for `spam` messages.
Apart from the `faint` style of the `spam` level, the default configuration of
`coloredlogs` sticks to the eight color palette defined by the original ANSI
standard, in order to provide a somewhat consistent experience across terminals
and terminal emulators.
Available text styles and colors
--------------------------------
Of course you are free to customize the default configuration, in this case you
can use any text style or color that you know is supported by your terminal.
You can use the ``humanfriendly --demo`` command to try out the supported text
styles and colors:
.. image:: http://humanfriendly.readthedocs.io/en/latest/_images/ansi-demo.png
:alt: Screen shot of the 'humanfriendly --demo' command.
Changing the log format
-----------------------
The simplest customization is to change the log format, for example:
.. literalinclude:: examples/custom-log-format.txt
:language: console
Here's what that looks like in a terminal (I always work in terminals with a
black background and white text):
.. image:: images/custom-log-format.png
:alt: Screen shot of colored logging with custom log format.
Changing the date/time format
-----------------------------
You can also change the date/time format, for example you can remove the date
part and leave only the time:
.. literalinclude:: examples/custom-datetime-format.txt
:language: console
Here's what it looks like in a terminal:
.. image:: images/custom-datetime-format.png
:alt: Screen shot of colored logging with custom date/time format.
Changing the colors/styles
--------------------------
Finally you can customize the colors and text styles that are used:
.. literalinclude:: examples/custom-colors.txt
:language: console
Here's an explanation of the features used here:
- The numbers used in ``$COLOREDLOGS_LEVEL_STYLES`` demonstrate the use of 256
color mode (the numbers refer to the 256 color mode palette which is fixed).
- The `success` level demonstrates the use of a text style (bold).
- The `critical` level demonstrates the use of a background color (red).
Of course none of this can be seen in the shell transcript quoted above, but
take a look at the following screen shot:
.. image:: images/custom-colors.png
:alt: Screen shot of colored logging with custom colors.
.. _notes about log levels:
Some notes about log levels
===========================
With regards to the handling of log levels, the :mod:`coloredlogs` package
differs from Python's :mod:`logging` module in two aspects:
1. While the :mod:`logging` module uses the default logging level
:data:`logging.WARNING`, the :mod:`coloredlogs` package has always used
:data:`logging.INFO` as its default log level.
2. When logging to the terminal or system log is initialized by
:func:`install()` or :func:`.enable_system_logging()` the effective
level [#]_ of the selected logger [#]_ is compared against the requested
level [#]_ and if the effective level is more restrictive than the requested
level, the logger's level will be set to the requested level (this happens
in :func:`adjust_level()`). The reason for this is to work around a
combination of design choices in Python's :mod:`logging` module that can
easily confuse people who aren't already intimately familiar with it:
- All loggers are initialized with the level :data:`logging.NOTSET`.
- When a logger's level is set to :data:`logging.NOTSET` the
:func:`~logging.Logger.getEffectiveLevel()` method will
fall back to the level of the parent logger.
- The parent of all loggers is the root logger and the root logger has its
level set to :data:`logging.WARNING` by default (after importing the
:mod:`logging` module).
Effectively all user defined loggers inherit the default log level
:data:`logging.WARNING` from the root logger, which isn't very intuitive for
those who aren't already familiar with the hierarchical nature of the
:mod:`logging` module.
By avoiding this potentially confusing behavior (see `#14`_, `#18`_, `#21`_,
`#23`_ and `#24`_), while at the same time allowing the caller to specify a
logger object, my goal and hope is to provide sane defaults that can easily
be changed when the need arises.
.. [#] Refer to :func:`logging.Logger.getEffectiveLevel()` for details.
.. [#] The logger that is passed as an argument by the caller or the root
logger which is selected as a default when no logger is provided.
.. [#] The log level that is passed as an argument by the caller or the
default log level :data:`logging.INFO` when no level is provided.
.. _#14: https://github.com/xolox/python-coloredlogs/issues/14
.. _#18: https://github.com/xolox/python-coloredlogs/issues/18
.. _#21: https://github.com/xolox/python-coloredlogs/pull/21
.. _#23: https://github.com/xolox/python-coloredlogs/pull/23
.. _#24: https://github.com/xolox/python-coloredlogs/issues/24
Classes and functions
=====================
"""
# Standard library modules.
import collections
import logging
import os
import re
import socket
import sys
# External dependencies.
from humanfriendly import coerce_boolean
from humanfriendly.compat import coerce_string, is_string, on_windows
from humanfriendly.terminal import ANSI_COLOR_CODES, ansi_wrap, enable_ansi_support, terminal_supports_colors
from humanfriendly.text import format, split
# Semi-standard module versioning.
__version__ = '14.0'
DEFAULT_LOG_LEVEL = logging.INFO
"""The default log level for :mod:`coloredlogs` (:data:`logging.INFO`)."""
DEFAULT_LOG_FORMAT = '%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s'
"""The default log format for :class:`ColoredFormatter` objects (a string)."""
DEFAULT_DATE_FORMAT = '%Y-%m-%d %H:%M:%S'
"""The default date/time format for :class:`ColoredFormatter` objects (a string)."""
CHROOT_FILES = ['/etc/debian_chroot']
"""A list of filenames that indicate a chroot and contain the name of the chroot."""
DEFAULT_FIELD_STYLES = dict(
asctime=dict(color='green'),
hostname=dict(color='magenta'),
levelname=dict(color='black', bold=True),
name=dict(color='blue'),
programname=dict(color='cyan'),
username=dict(color='yellow'),
)
"""Mapping of log format names to default font styles."""
DEFAULT_LEVEL_STYLES = dict(
spam=dict(color='green', faint=True),
debug=dict(color='green'),
verbose=dict(color='blue'),
info=dict(),
notice=dict(color='magenta'),
warning=dict(color='yellow'),
success=dict(color='green', bold=True),
error=dict(color='red'),
critical=dict(color='red', bold=True),
)
"""Mapping of log level names to default font styles."""
DEFAULT_FORMAT_STYLE = '%'
"""The default logging format style (a single character)."""
FORMAT_STYLE_PATTERNS = {
'%': r'%\((\w+)\)[#0 +-]*\d*(?:\.\d+)?[hlL]?[diouxXeEfFgGcrs%]',
'{': r'{(\w+)[^}]*}',
'$': r'\$(\w+)|\${(\w+)}',
}
"""
A dictionary that maps the `style` characters ``%``, ``{`` and ``$`` (see the
documentation of the :class:`python3:logging.Formatter` class in Python 3.2+)
to strings containing regular expression patterns that can be used to parse
format strings in the corresponding style:
``%``
A string containing a regular expression that matches a "percent conversion
specifier" as defined in the `String Formatting Operations`_ section of the
Python documentation. Here's an example of a logging format string in this
format: ``%(levelname)s:%(name)s:%(message)s``.
``{``
A string containing a regular expression that matches a "replacement field" as
defined in the `Format String Syntax`_ section of the Python documentation.
Here's an example of a logging format string in this format:
``{levelname}:{name}:{message}``.
``$``
A string containing a regular expression that matches a "substitution
placeholder" as defined in the `Template Strings`_ section of the Python
documentation. Here's an example of a logging format string in this format:
``$levelname:$name:$message``.
These regular expressions are used by :class:`FormatStringParser` to introspect
and manipulate logging format strings.
.. _String Formatting Operations: https://docs.python.org/2/library/stdtypes.html#string-formatting
.. _Format String Syntax: https://docs.python.org/2/library/string.html#formatstrings
.. _Template Strings: https://docs.python.org/3/library/string.html#template-strings
"""
def auto_install():
"""
Automatically call :func:`install()` when ``$COLOREDLOGS_AUTO_INSTALL`` is set.
The `coloredlogs` package includes a `path configuration file`_ that
automatically imports the :mod:`coloredlogs` module and calls
:func:`auto_install()` when the environment variable
``$COLOREDLOGS_AUTO_INSTALL`` is set.
This function uses :func:`~humanfriendly.coerce_boolean()` to check whether
the value of ``$COLOREDLOGS_AUTO_INSTALL`` should be considered :data:`True`.
.. _path configuration file: https://docs.python.org/2/library/site.html#module-site
"""
if coerce_boolean(os.environ.get('COLOREDLOGS_AUTO_INSTALL', 'false')):
install()
def install(level=None, **kw):
"""
Enable colored terminal output for Python's :mod:`logging` module.
:param level: The default logging level (an integer or a string with a
level name, defaults to :data:`DEFAULT_LOG_LEVEL`).
:param logger: The logger to which the stream handler should be attached (a
:class:`~logging.Logger` object, defaults to the root logger).
:param fmt: Set the logging format (a string like those accepted by
:class:`~logging.Formatter`, defaults to
:data:`DEFAULT_LOG_FORMAT`).
:param datefmt: Set the date/time format (a string, defaults to
:data:`DEFAULT_DATE_FORMAT`).
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`). See the documentation of the
:class:`python3:logging.Formatter` class in Python 3.2+. On
older Python versions only ``%`` is supported.
:param milliseconds: :data:`True` to show milliseconds like :mod:`logging`
does by default, :data:`False` to hide milliseconds
(the default is :data:`False`, see `#16`_).
:param level_styles: A dictionary with custom level styles (defaults to
:data:`DEFAULT_LEVEL_STYLES`).
:param field_styles: A dictionary with custom field styles (defaults to
:data:`DEFAULT_FIELD_STYLES`).
:param stream: The stream where log messages should be written to (a
file-like object). This defaults to :data:`None` which
means :class:`StandardErrorHandler` is used.
:param isatty: :data:`True` to use a :class:`ColoredFormatter`,
:data:`False` to use a normal :class:`~logging.Formatter`
(defaults to auto-detection using
:func:`~humanfriendly.terminal.terminal_supports_colors()`).
:param reconfigure: If :data:`True` (the default) multiple calls to
:func:`coloredlogs.install()` will each override
the previous configuration.
:param use_chroot: Refer to :class:`HostNameFilter`.
:param programname: Refer to :class:`ProgramNameFilter`.
:param username: Refer to :class:`UserNameFilter`.
:param syslog: If :data:`True` then :func:`.enable_system_logging()` will
be called without arguments (defaults to :data:`False`). The
`syslog` argument may also be a number or string, in this
case it is assumed to be a logging level which is passed on
to :func:`.enable_system_logging()`.
The :func:`coloredlogs.install()` function is similar to
:func:`logging.basicConfig()`, both functions take a lot of optional
keyword arguments but try to do the right thing by default:
1. If `reconfigure` is :data:`True` (it is by default) and an existing
:class:`~logging.StreamHandler` is found that is connected to either
:data:`~sys.stdout` or :data:`~sys.stderr` the handler will be removed.
This means that first calling :func:`logging.basicConfig()` and then
calling :func:`coloredlogs.install()` will replace the stream handler
instead of adding a duplicate stream handler. If `reconfigure` is
:data:`False` and an existing handler is found no further steps are
taken (to avoid installing a duplicate stream handler).
2. A :class:`~logging.StreamHandler` is created and connected to the stream
given by the `stream` keyword argument (:data:`sys.stderr` by
default). The stream handler's level is set to the value of the `level`
keyword argument.
3. A :class:`ColoredFormatter` is created if the `isatty` keyword argument
allows it (or auto-detection allows it), otherwise a normal
:class:`~logging.Formatter` is created. The formatter is initialized
with the `fmt` and `datefmt` keyword arguments (or their computed
defaults).
4. :func:`HostNameFilter.install()`, :func:`ProgramNameFilter.install()`
and :func:`UserNameFilter.install()` are called to enable the use of
additional fields in the log format.
5. If the logger's level is too restrictive it is relaxed (refer to `notes
about log levels`_ for details).
6. The formatter is added to the handler and the handler is added to the
logger.
.. _#16: https://github.com/xolox/python-coloredlogs/issues/16
"""
logger = kw.get('logger') or logging.getLogger()
reconfigure = kw.get('reconfigure', True)
stream = kw.get('stream', None)
style = check_style(kw.get('style') or DEFAULT_FORMAT_STYLE)
# Get the log level from an argument, environment variable or default and
# convert the names of log levels to numbers to enable numeric comparison.
if level is None:
level = os.environ.get('COLOREDLOGS_LOG_LEVEL', DEFAULT_LOG_LEVEL)
level = level_to_number(level)
# Remove any existing stream handler that writes to stdout or stderr, even
# if the stream handler wasn't created by coloredlogs because multiple
# stream handlers (in the same hierarchy) writing to stdout or stderr would
# create duplicate output. `None' is a synonym for the possibly dynamic
# value of the stderr attribute of the sys module.
match_streams = ([sys.stdout, sys.stderr]
if stream in [sys.stdout, sys.stderr, None]
else [stream])
match_handler = lambda handler: match_stream_handler(handler, match_streams)
handler, logger = replace_handler(logger, match_handler, reconfigure)
# Make sure reconfiguration is allowed or not relevant.
if not (handler and not reconfigure):
# Make it easy to enable system logging.
syslog_enabled = kw.get('syslog')
# We ignore the value `None' because it means the caller didn't opt in
# to system logging and `False' because it means the caller explicitly
# opted out of system logging.
#
# We never enable system logging on Windows because it is my impression
# that SysLogHandler isn't intended to be used on Windows; I've had
# reports of coloredlogs spewing extremely verbose errno 10057 warning
# messages to the console (once for each log message I suppose).
if syslog_enabled not in (None, False) and not on_windows():
from coloredlogs.syslog import enable_system_logging
if syslog_enabled is True:
# If the caller passed syslog=True then we leave the choice of
# default log level up to the coloredlogs.syslog module.
enable_system_logging()
else:
# Values other than (None, True, False) are assumed to
# represent a logging level for system logging.
enable_system_logging(level=syslog_enabled)
# Figure out whether we can use ANSI escape sequences.
use_colors = kw.get('isatty', None)
if use_colors or use_colors is None:
# Try to enable Windows native ANSI support or Colorama.
if on_windows():
use_colors = enable_ansi_support()
# Disable ANSI escape sequences if 'stream' isn't connected to a terminal.
if use_colors or use_colors is None:
use_colors = terminal_supports_colors(stream)
# Create a stream handler.
handler = logging.StreamHandler(stream) if stream else StandardErrorHandler()
handler.setLevel(level)
# Prepare the arguments to the formatter, allowing the caller to
# customize the values of `fmt', `datefmt' and `style' as desired.
formatter_options = dict(fmt=kw.get('fmt'), datefmt=kw.get('datefmt'))
# Only pass the `style' argument to the formatter when the caller
# provided an alternative logging format style. This prevents
# TypeError exceptions on Python versions before 3.2.
if style != DEFAULT_FORMAT_STYLE:
formatter_options['style'] = style
# Come up with a default log format?
if not formatter_options['fmt']:
# Use the log format defined by the environment variable
# $COLOREDLOGS_LOG_FORMAT or fall back to the default.
formatter_options['fmt'] = os.environ.get('COLOREDLOGS_LOG_FORMAT') or DEFAULT_LOG_FORMAT
# If the caller didn't specify a date/time format we'll use the format
# defined by the environment variable $COLOREDLOGS_DATE_FORMAT (or fall
# back to the default).
if not formatter_options['datefmt']:
formatter_options['datefmt'] = os.environ.get('COLOREDLOGS_DATE_FORMAT') or DEFAULT_DATE_FORMAT
# Python's logging module shows milliseconds by default through special
# handling in the logging.Formatter.formatTime() method [1]. Because
# coloredlogs always defines a `datefmt' it bypasses this special
# handling, which is fine because ever since publishing coloredlogs
# I've never needed millisecond precision ;-). However there are users
# of coloredlogs that do want milliseconds to be shown [2] so we
# provide a shortcut to make it easy.
#
# [1] https://stackoverflow.com/questions/6290739/python-logging-use-milliseconds-in-time-format
# [2] https://github.com/xolox/python-coloredlogs/issues/16
if kw.get('milliseconds'):
parser = FormatStringParser(style=style)
if not (parser.contains_field(formatter_options['fmt'], 'msecs')
or '%f' in formatter_options['datefmt']):
pattern = parser.get_pattern('asctime')
replacements = {'%': '%(msecs)03d', '{': '{msecs:03}', '$': '${msecs}'}
formatter_options['fmt'] = pattern.sub(
r'\g<0>,' + replacements[style],
formatter_options['fmt'],
)
# Do we need to make %(hostname) available to the formatter?
HostNameFilter.install(
fmt=formatter_options['fmt'],
handler=handler,
style=style,
use_chroot=kw.get('use_chroot', True),
)
# Do we need to make %(programname) available to the formatter?
ProgramNameFilter.install(
fmt=formatter_options['fmt'],
handler=handler,
programname=kw.get('programname'),
style=style,
)
# Do we need to make %(username) available to the formatter?
UserNameFilter.install(
fmt=formatter_options['fmt'],
handler=handler,
username=kw.get('username'),
style=style,
)
# Inject additional formatter arguments specific to ColoredFormatter?
if use_colors:
for name, environment_name in (('field_styles', 'COLOREDLOGS_FIELD_STYLES'),
('level_styles', 'COLOREDLOGS_LEVEL_STYLES')):
value = kw.get(name)
if value is None:
# If no styles have been specified we'll fall back
# to the styles defined by the environment variable.
environment_value = os.environ.get(environment_name)
if environment_value is not None:
value = parse_encoded_styles(environment_value)
if value is not None:
formatter_options[name] = value
# Create a (possibly colored) formatter.
formatter_type = ColoredFormatter if use_colors else BasicFormatter
handler.setFormatter(formatter_type(**formatter_options))
# Adjust the level of the selected logger.
adjust_level(logger, level)
# Install the stream handler.
logger.addHandler(handler)
def check_style(value):
"""
Validate a logging format style.
:param value: The logging format style to validate (any value).
:returns: The logging format character (a string of one character).
:raises: :exc:`~exceptions.ValueError` when the given style isn't supported.
On Python 3.2+ this function accepts the logging format styles ``%``, ``{``
and ``$`` while on older versions only ``%`` is accepted (because older
Python versions don't support alternative logging format styles).
"""
if sys.version_info[:2] >= (3, 2):
if value not in FORMAT_STYLE_PATTERNS:
msg = "Unsupported logging format style! (%r)"
raise ValueError(format(msg, value))
elif value != DEFAULT_FORMAT_STYLE:
msg = "Format string styles other than %r require Python 3.2+!"
raise ValueError(msg, DEFAULT_FORMAT_STYLE)
return value
def increase_verbosity():
"""
Increase the verbosity of the root handler by one defined level.
Understands custom logging levels like defined by my ``verboselogs``
module.
"""
defined_levels = sorted(set(find_defined_levels().values()))
current_index = defined_levels.index(get_level())
selected_index = max(0, current_index - 1)
set_level(defined_levels[selected_index])
def decrease_verbosity():
"""
Decrease the verbosity of the root handler by one defined level.
Understands custom logging levels like defined by my ``verboselogs``
module.
"""
defined_levels = sorted(set(find_defined_levels().values()))
current_index = defined_levels.index(get_level())
selected_index = min(current_index + 1, len(defined_levels) - 1)
set_level(defined_levels[selected_index])
def is_verbose():
"""
Check whether the log level of the root handler is set to a verbose level.
:returns: ``True`` if the root handler is verbose, ``False`` if not.
"""
return get_level() < DEFAULT_LOG_LEVEL
def get_level():
"""
Get the logging level of the root handler.
:returns: The logging level of the root handler (an integer) or
:data:`DEFAULT_LOG_LEVEL` (if no root handler exists).
"""
handler, logger = find_handler(logging.getLogger(), match_stream_handler)
return handler.level if handler else DEFAULT_LOG_LEVEL
def set_level(level):
"""
Set the logging level of the root handler.
:param level: The logging level to filter on (an integer or string).
If no root handler exists yet this automatically calls :func:`install()`.
"""
handler, logger = find_handler(logging.getLogger(), match_stream_handler)
if handler and logger:
# Change the level of the existing handler.
handler.setLevel(level_to_number(level))
# Adjust the level of the selected logger.
adjust_level(logger, level)
else:
# Create a new handler with the given level.
install(level=level)
def adjust_level(logger, level):
"""
Increase a logger's verbosity up to the requested level.
:param logger: The logger to change (a :class:`~logging.Logger` object).
:param level: The log level to enable (a string or number).
This function is used by functions like :func:`install()`,
:func:`increase_verbosity()` and :func:`.enable_system_logging()` to adjust
a logger's level so that log messages up to the requested log level are
propagated to the configured output handler(s).
It uses :func:`logging.Logger.getEffectiveLevel()` to check whether
`logger` propagates or swallows log messages of the requested `level` and
sets the logger's level to the requested level if it would otherwise
swallow log messages.
Effectively this function will "widen the scope of logging" when asked to
do so but it will never "narrow the scope of logging". This is because I am
convinced that filtering of log messages should (primarily) be decided by
handlers.
"""
level = level_to_number(level)
if logger.getEffectiveLevel() > level:
logger.setLevel(level)
def find_defined_levels():
"""
Find the defined logging levels.
:returns: A dictionary with level names as keys and integers as values.
Here's what the result looks like by default (when
no custom levels or level names have been defined):
>>> find_defined_levels()
{'NOTSET': 0,
'DEBUG': 10,
'INFO': 20,
'WARN': 30,
'WARNING': 30,
'ERROR': 40,
'FATAL': 50,
'CRITICAL': 50}
"""
defined_levels = {}
for name in dir(logging):
if name.isupper():
value = getattr(logging, name)
if isinstance(value, int):
defined_levels[name] = value
return defined_levels
def level_to_number(value):
"""
Coerce a logging level name to a number.
:param value: A logging level (integer or string).
:returns: The number of the log level (an integer).
This function translates log level names into their numeric values..
"""
if is_string(value):
try:
defined_levels = find_defined_levels()
value = defined_levels[value.upper()]
except KeyError:
# Don't fail on unsupported log levels.
value = DEFAULT_LOG_LEVEL
return value
def find_level_aliases():
"""
Find log level names which are aliases of each other.
:returns: A dictionary that maps aliases to their canonical name.
.. note:: Canonical names are chosen to be the alias with the longest
string length so that e.g. ``WARN`` is an alias for ``WARNING``
instead of the other way around.
Here's what the result looks like by default (when
no custom levels or level names have been defined):
>>> from coloredlogs import find_level_aliases
>>> find_level_aliases()
{'WARN': 'WARNING', 'FATAL': 'CRITICAL'}
"""
mapping = collections.defaultdict(list)
for name, value in find_defined_levels().items():
mapping[value].append(name)
aliases = {}
for value, names in mapping.items():
if len(names) > 1:
names = sorted(names, key=lambda n: len(n))
canonical_name = names.pop()
for alias in names:
aliases[alias] = canonical_name
return aliases
def parse_encoded_styles(text, normalize_key=None):
"""
Parse text styles encoded in a string into a nested data structure.
:param text: The encoded styles (a string).
:returns: A dictionary in the structure of the :data:`DEFAULT_FIELD_STYLES`
and :data:`DEFAULT_LEVEL_STYLES` dictionaries.
Here's an example of how this function works:
>>> from coloredlogs import parse_encoded_styles
>>> from pprint import pprint
>>> encoded_styles = 'debug=green;warning=yellow;error=red;critical=red,bold'
>>> pprint(parse_encoded_styles(encoded_styles))
{'debug': {'color': 'green'},
'warning': {'color': 'yellow'},
'error': {'color': 'red'},
'critical': {'bold': True, 'color': 'red'}}
"""
parsed_styles = {}
for assignment in split(text, ';'):
name, _, styles = assignment.partition('=')
target = parsed_styles.setdefault(name, {})
for token in split(styles, ','):
# When this code was originally written, setting background colors
# wasn't supported yet, so there was no need to disambiguate
# between the text color and background color. This explains why
# a color name or number implies setting the text color (for
# backwards compatibility).
if token.isdigit():
target['color'] = int(token)
elif token in ANSI_COLOR_CODES:
target['color'] = token
elif '=' in token:
name, _, value = token.partition('=')
if name in ('color', 'background'):
if value.isdigit():
target[name] = int(value)
elif value in ANSI_COLOR_CODES:
target[name] = value
else:
target[token] = True
return parsed_styles
def find_hostname(use_chroot=True):
"""
Find the host name to include in log messages.
:param use_chroot: Use the name of the chroot when inside a chroot?
(boolean, defaults to :data:`True`)
:returns: A suitable host name (a string).
Looks for :data:`CHROOT_FILES` that have a nonempty first line (taken to be
the chroot name). If none are found then :func:`socket.gethostname()` is
used as a fall back.
"""
for chroot_file in CHROOT_FILES:
try:
with open(chroot_file) as handle:
first_line = next(handle)
name = first_line.strip()
if name:
return name
except Exception:
pass
return socket.gethostname()
def find_program_name():
"""
Select a suitable program name to embed in log messages.
:returns: One of the following strings (in decreasing order of preference):
1. The base name of the currently running Python program or
script (based on the value at index zero of :data:`sys.argv`).
2. The base name of the Python executable (based on
:data:`sys.executable`).
3. The string 'python'.
"""
# Gotcha: sys.argv[0] is '-c' if Python is started with the -c option.
return ((os.path.basename(sys.argv[0]) if sys.argv and sys.argv[0] != '-c' else '')
or (os.path.basename(sys.executable) if sys.executable else '')
or 'python')
def find_username():
"""
Find the username to include in log messages.
:returns: A suitable username (a string).
On UNIX systems this uses the :mod:`pwd` module which means ``root`` will
be reported when :man:`sudo` is used (as it should). If this fails (for
example on Windows) then :func:`getpass.getuser()` is used as a fall back.
"""
try:
import pwd
uid = os.getuid()
entry = pwd.getpwuid(uid)
return entry.pw_name
except Exception:
import getpass
return getpass.getuser()
def replace_handler(logger, match_handler, reconfigure):
"""
Prepare to replace a handler.
:param logger: Refer to :func:`find_handler()`.
:param match_handler: Refer to :func:`find_handler()`.
:param reconfigure: :data:`True` if an existing handler should be replaced,
:data:`False` otherwise.
:returns: A tuple of two values:
1. The matched :class:`~logging.Handler` object or :data:`None`
if no handler was matched.
2. The :class:`~logging.Logger` to which the matched handler was
attached or the logger given to :func:`replace_handler()`.
"""
handler, other_logger = find_handler(logger, match_handler)
if handler and other_logger and reconfigure:
# Remove the existing handler from the logger that its attached to
# so that we can install a new handler that behaves differently.
other_logger.removeHandler(handler)
# Switch to the logger that the existing handler was attached to so
# that reconfiguration doesn't narrow the scope of logging.
logger = other_logger
return handler, logger
def find_handler(logger, match_handler):
"""
Find a (specific type of) handler in the propagation tree of a logger.
:param logger: The logger to check (a :class:`~logging.Logger` object).
:param match_handler: A callable that receives a :class:`~logging.Handler`
object and returns :data:`True` to match a handler or
:data:`False` to skip that handler and continue
searching for a match.
:returns: A tuple of two values:
1. The matched :class:`~logging.Handler` object or :data:`None`
if no handler was matched.
2. The :class:`~logging.Logger` object to which the handler is
attached or :data:`None` if no handler was matched.
This function finds a logging handler (of the given type) attached to a
logger or one of its parents (see :func:`walk_propagation_tree()`). It uses
the undocumented :class:`~logging.Logger.handlers` attribute to find
handlers attached to a logger, however it won't raise an exception if the
attribute isn't available. The advantages of this approach are:
- This works regardless of whether :mod:`coloredlogs` attached the handler
or other Python code attached the handler.
- This will correctly recognize the situation where the given logger has no
handlers but :attr:`~logging.Logger.propagate` is enabled and the logger
has a parent logger that does have a handler attached.
"""
for logger in walk_propagation_tree(logger):
for handler in getattr(logger, 'handlers', []):
if match_handler(handler):
return handler, logger
return None, None
def match_stream_handler(handler, streams=[]):
"""
Identify stream handlers writing to the given streams(s).
:param handler: The :class:`~logging.Handler` class to check.
:param streams: A sequence of streams to match (defaults to matching
:data:`~sys.stdout` and :data:`~sys.stderr`).
:returns: :data:`True` if the handler is a :class:`~logging.StreamHandler`
logging to the given stream(s), :data:`False` otherwise.
This function can be used as a callback for :func:`find_handler()`.
"""
return (isinstance(handler, logging.StreamHandler)
and getattr(handler, 'stream') in (streams or (sys.stdout, sys.stderr)))
def walk_propagation_tree(logger):
"""
Walk through the propagation hierarchy of the given logger.
:param logger: The logger whose hierarchy to walk (a
:class:`~logging.Logger` object).
:returns: A generator of :class:`~logging.Logger` objects.
.. note:: This uses the undocumented :class:`logging.Logger.parent`
attribute to find higher level loggers, however it won't
raise an exception if the attribute isn't available.
"""
while isinstance(logger, logging.Logger):
# Yield the logger to our caller.
yield logger
# Check if the logger has propagation enabled.
if logger.propagate:
# Continue with the parent logger. We use getattr() because the
# `parent' attribute isn't documented so properly speaking we
# shouldn't break if it's not available.
logger = getattr(logger, 'parent', None)
else:
# The propagation chain stops here.
logger = None
class BasicFormatter(logging.Formatter):
"""
Log :class:`~logging.Formatter` that supports ``%f`` for millisecond formatting.
This class extends :class:`~logging.Formatter` to enable the use of ``%f``
for millisecond formatting in date/time strings, to allow for the type of
flexibility requested in issue `#45`_.
.. _#45: https://github.com/xolox/python-coloredlogs/issues/45
"""
def formatTime(self, record, datefmt=None):
"""
Format the date/time of a log record.
:param record: A :class:`~logging.LogRecord` object.
:param datefmt: A date/time format string (defaults to :data:`DEFAULT_DATE_FORMAT`).
:returns: The formatted date/time (a string).
This method overrides :func:`~logging.Formatter.formatTime()` to set
`datefmt` to :data:`DEFAULT_DATE_FORMAT` when the caller hasn't
specified a date format.
When `datefmt` contains the token ``%f`` it will be replaced by the
value of ``%(msecs)03d`` (refer to issue `#45`_ for use cases).
"""
# The default value of the following argument is defined here so
# that Sphinx doesn't embed the default value in the generated
# documentation (because the result is awkward to read).
datefmt = datefmt or DEFAULT_DATE_FORMAT
# Replace %f with the value of %(msecs)03d.
if '%f' in datefmt:
datefmt = datefmt.replace('%f', '%03d' % record.msecs)
# Delegate the actual date/time formatting to the base formatter.
return logging.Formatter.formatTime(self, record, datefmt)
class ColoredFormatter(BasicFormatter):
"""
Log :class:`~logging.Formatter` that uses `ANSI escape sequences`_ to create colored logs.
:class:`ColoredFormatter` inherits from :class:`BasicFormatter` to enable
the use of ``%f`` for millisecond formatting in date/time strings.
.. note:: If you want to use :class:`ColoredFormatter` on Windows then you
need to call :func:`~humanfriendly.terminal.enable_ansi_support()`.
This is done for you when you call :func:`coloredlogs.install()`.
"""
def __init__(self, fmt=None, datefmt=None, style=DEFAULT_FORMAT_STYLE, level_styles=None, field_styles=None):
"""
Initialize a :class:`ColoredFormatter` object.
:param fmt: A log format string (defaults to :data:`DEFAULT_LOG_FORMAT`).
:param datefmt: A date/time format string (defaults to :data:`None`,
but see the documentation of
:func:`BasicFormatter.formatTime()`).
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`)
:param level_styles: A dictionary with custom level styles
(defaults to :data:`DEFAULT_LEVEL_STYLES`).
:param field_styles: A dictionary with custom field styles
(defaults to :data:`DEFAULT_FIELD_STYLES`).
:raises: Refer to :func:`check_style()`.
This initializer uses :func:`colorize_format()` to inject ANSI escape
sequences in the log format string before it is passed to the
initializer of the base class.
"""
self.nn = NameNormalizer()
# The default values of the following arguments are defined here so
# that Sphinx doesn't embed the default values in the generated
# documentation (because the result is awkward to read).
fmt = fmt or DEFAULT_LOG_FORMAT
self.level_styles = self.nn.normalize_keys(DEFAULT_LEVEL_STYLES if level_styles is None else level_styles)
self.field_styles = self.nn.normalize_keys(DEFAULT_FIELD_STYLES if field_styles is None else field_styles)
# Rewrite the format string to inject ANSI escape sequences.
kw = dict(fmt=self.colorize_format(fmt, style), datefmt=datefmt)
# If we were given a non-default logging format style we pass it on
# to our superclass. At this point check_style() will have already
# complained that the use of alternative logging format styles
# requires Python 3.2 or newer.
if style != DEFAULT_FORMAT_STYLE:
kw['style'] = style
# Initialize the superclass with the rewritten format string.
logging.Formatter.__init__(self, **kw)
def colorize_format(self, fmt, style=DEFAULT_FORMAT_STYLE):
"""
Rewrite a logging format string to inject ANSI escape sequences.
:param fmt: The log format string.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:returns: The logging format string with ANSI escape sequences.
This method takes a logging format string like the ones you give to
:class:`logging.Formatter` and processes it as follows:
1. First the logging format string is separated into formatting
directives versus surrounding text (according to the given `style`).
2. Then formatting directives and surrounding text are grouped
based on whitespace delimiters (in the surrounding text).
3. For each group styling is selected as follows:
1. If the group contains a single formatting directive that has
a style defined then the whole group is styled accordingly.
2. If the group contains multiple formatting directives that
have styles defined then each formatting directive is styled
individually and surrounding text isn't styled.
As an example consider the default log format (:data:`DEFAULT_LOG_FORMAT`)::
%(asctime)s %(hostname)s %(name)s[%(process)d] %(levelname)s %(message)s
The default field styles (:data:`DEFAULT_FIELD_STYLES`) define a style for the
`name` field but not for the `process` field, however because both fields
are part of the same whitespace delimited token they'll be highlighted
together in the style defined for the `name` field.
"""
result = []
parser = FormatStringParser(style=style)
for group in parser.get_grouped_pairs(fmt):
applicable_styles = [self.nn.get(self.field_styles, token.name) for token in group if token.name]
if sum(map(bool, applicable_styles)) == 1:
# If exactly one (1) field style is available for the group of
# tokens then all of the tokens will be styled the same way.
# This provides a limited form of backwards compatibility with
# the (intended) behavior of coloredlogs before the release of
# version 10.
result.append(ansi_wrap(
''.join(token.text for token in group),
**next(s for s in applicable_styles if s)
))
else:
for token in group:
text = token.text
if token.name:
field_styles = self.nn.get(self.field_styles, token.name)
if field_styles:
text = ansi_wrap(text, **field_styles)
result.append(text)
return ''.join(result)
def format(self, record):
"""
Apply level-specific styling to log records.
:param record: A :class:`~logging.LogRecord` object.
:returns: The result of :func:`logging.Formatter.format()`.
This method injects ANSI escape sequences that are specific to the
level of each log record (because such logic cannot be expressed in the
syntax of a log format string). It works by making a copy of the log
record, changing the `msg` field inside the copy and passing the copy
into the :func:`~logging.Formatter.format()` method of the base
class.
"""
output = ""
for line in str(record.msg).splitlines():
style = self.nn.get(self.level_styles, record.levelname)
# After the introduction of the `Empty' class it was reported in issue
# 33 that format() can be called when `Empty' has already been garbage
# collected. This explains the (otherwise rather out of place) `Empty
# is not None' check in the following `if' statement. The reasoning
# here is that it's much better to log a message without formatting
# then to raise an exception ;-).
#
# For more details refer to issue 33 on GitHub:
# https://github.com/xolox/python-coloredlogs/issues/33
if style and Empty is not None:
# Due to the way that Python's logging module is structured and
# documented the only (IMHO) clean way to customize its behavior is
# to change incoming LogRecord objects before they get to the base
# formatter. However we don't want to break other formatters and
# handlers, so we copy the log record.
#
# In the past this used copy.copy() but as reported in issue 29
# (which is reproducible) this can cause deadlocks. The following
# Python voodoo is intended to accomplish the same thing as
# copy.copy() without all of the generalization and overhead that
# we don't need for our -very limited- use case.
#
# For more details refer to issue 29 on GitHub:
# https://github.com/xolox/python-coloredlogs/issues/29
copy = Empty()
copy.__class__ = record.__class__
copy.__dict__.update(record.__dict__)
copy.msg = ansi_wrap(coerce_string(line), **style)
record = copy
# Delegate the remaining formatting to the base formatter.
output += logging.Formatter.format(self, record) + "\n"
return output[:-1]
class Empty(object):
"""An empty class used to copy :class:`~logging.LogRecord` objects without reinitializing them."""
class HostNameFilter(logging.Filter):
"""
Log filter to enable the ``%(hostname)s`` format.
Python's :mod:`logging` module doesn't expose the system's host name while
I consider this to be a valuable addition. Fortunately it's very easy to
expose additional fields in format strings: :func:`filter()` simply sets
the ``hostname`` attribute of each :class:`~logging.LogRecord` object it
receives and this is enough to enable the use of the ``%(hostname)s``
expression in format strings.
You can install this log filter as follows::
>>> import coloredlogs, logging
>>> handler = logging.StreamHandler()
>>> handler.addFilter(coloredlogs.HostNameFilter())
>>> handler.setFormatter(logging.Formatter('[%(hostname)s] %(message)s'))
>>> logger = logging.getLogger()
>>> logger.addHandler(handler)
>>> logger.setLevel(logging.INFO)
>>> logger.info("Does it work?")
[peter-macbook] Does it work?
Of course :func:`coloredlogs.install()` does all of this for you :-).
"""
@classmethod
def install(cls, handler, fmt=None, use_chroot=True, style=DEFAULT_FORMAT_STYLE):
"""
Install the :class:`HostNameFilter` on a log handler (only if needed).
:param fmt: The log format string to check for ``%(hostname)``.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:param handler: The logging handler on which to install the filter.
:param use_chroot: Refer to :func:`find_hostname()`.
If `fmt` is given the filter will only be installed if `fmt` uses the
``hostname`` field. If `fmt` is not given the filter is installed
unconditionally.
"""
if fmt:
parser = FormatStringParser(style=style)
if not parser.contains_field(fmt, 'hostname'):
return
handler.addFilter(cls(use_chroot))
def __init__(self, use_chroot=True):
"""
Initialize a :class:`HostNameFilter` object.
:param use_chroot: Refer to :func:`find_hostname()`.
"""
self.hostname = find_hostname(use_chroot)
def filter(self, record):
"""Set each :class:`~logging.LogRecord`'s `hostname` field."""
# Modify the record.
record.hostname = self.hostname
# Don't filter the record.
return 1
class ProgramNameFilter(logging.Filter):
"""
Log filter to enable the ``%(programname)s`` format.
Python's :mod:`logging` module doesn't expose the name of the currently
running program while I consider this to be a useful addition. Fortunately
it's very easy to expose additional fields in format strings:
:func:`filter()` simply sets the ``programname`` attribute of each
:class:`~logging.LogRecord` object it receives and this is enough to enable
the use of the ``%(programname)s`` expression in format strings.
Refer to :class:`HostNameFilter` for an example of how to manually install
these log filters.
"""
@classmethod
def install(cls, handler, fmt, programname=None, style=DEFAULT_FORMAT_STYLE):
"""
Install the :class:`ProgramNameFilter` (only if needed).
:param fmt: The log format string to check for ``%(programname)``.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:param handler: The logging handler on which to install the filter.
:param programname: Refer to :func:`__init__()`.
If `fmt` is given the filter will only be installed if `fmt` uses the
``programname`` field. If `fmt` is not given the filter is installed
unconditionally.
"""
if fmt:
parser = FormatStringParser(style=style)
if not parser.contains_field(fmt, 'programname'):
return
handler.addFilter(cls(programname))
def __init__(self, programname=None):
"""
Initialize a :class:`ProgramNameFilter` object.
:param programname: The program name to use (defaults to the result of
:func:`find_program_name()`).
"""
self.programname = programname or find_program_name()
def filter(self, record):
"""Set each :class:`~logging.LogRecord`'s `programname` field."""
# Modify the record.
record.programname = self.programname
# Don't filter the record.
return 1
class UserNameFilter(logging.Filter):
"""
Log filter to enable the ``%(username)s`` format.
Python's :mod:`logging` module doesn't expose the username of the currently
logged in user as requested in `#76`_. Given that :class:`HostNameFilter`
and :class:`ProgramNameFilter` are already provided by `coloredlogs` it
made sense to provide :class:`UserNameFilter` as well.
Refer to :class:`HostNameFilter` for an example of how to manually install
these log filters.
.. _#76: https://github.com/xolox/python-coloredlogs/issues/76
"""
@classmethod
def install(cls, handler, fmt, username=None, style=DEFAULT_FORMAT_STYLE):
"""
Install the :class:`UserNameFilter` (only if needed).
:param fmt: The log format string to check for ``%(username)``.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:param handler: The logging handler on which to install the filter.
:param username: Refer to :func:`__init__()`.
If `fmt` is given the filter will only be installed if `fmt` uses the
``username`` field. If `fmt` is not given the filter is installed
unconditionally.
"""
if fmt:
parser = FormatStringParser(style=style)
if not parser.contains_field(fmt, 'username'):
return
handler.addFilter(cls(username))
def __init__(self, username=None):
"""
Initialize a :class:`UserNameFilter` object.
:param username: The username to use (defaults to the
result of :func:`find_username()`).
"""
self.username = username or find_username()
def filter(self, record):
"""Set each :class:`~logging.LogRecord`'s `username` field."""
# Modify the record.
record.username = self.username
# Don't filter the record.
return 1
class StandardErrorHandler(logging.StreamHandler):
"""
A :class:`~logging.StreamHandler` that gets the value of :data:`sys.stderr` for each log message.
The :class:`StandardErrorHandler` class enables `monkey patching of
sys.stderr <https://github.com/xolox/python-coloredlogs/pull/31>`_. It's
basically the same as the ``logging._StderrHandler`` class present in
Python 3 but it will be available regardless of Python version. This
handler is used by :func:`coloredlogs.install()` to improve compatibility
with the Python standard library.
"""
def __init__(self, level=logging.NOTSET):
"""Initialize a :class:`StandardErrorHandler` object."""
logging.Handler.__init__(self, level)
@property
def stream(self):
"""Get the value of :data:`sys.stderr` (a file-like object)."""
return sys.stderr
class FormatStringParser(object):
"""
Shallow logging format string parser.
This class enables introspection and manipulation of logging format strings
in the three styles supported by the :mod:`logging` module starting from
Python 3.2 (``%``, ``{`` and ``$``).
"""
def __init__(self, style=DEFAULT_FORMAT_STYLE):
"""
Initialize a :class:`FormatStringParser` object.
:param style: One of the characters ``%``, ``{`` or ``$`` (defaults to
:data:`DEFAULT_FORMAT_STYLE`).
:raises: Refer to :func:`check_style()`.
"""
self.style = check_style(style)
self.capturing_pattern = FORMAT_STYLE_PATTERNS[style]
# Remove the capture group around the mapping key / field name.
self.raw_pattern = self.capturing_pattern.replace(r'(\w+)', r'\w+')
# After removing the inner capture group we add an outer capture group
# to make the pattern suitable for simple tokenization using re.split().
self.tokenize_pattern = re.compile('(%s)' % self.raw_pattern, re.VERBOSE)
# Compile a regular expression for finding field names.
self.name_pattern = re.compile(self.capturing_pattern, re.VERBOSE)
def contains_field(self, format_string, field_name):
"""
Get the field names referenced by a format string.
:param format_string: The logging format string.
:returns: A list of strings with field names.
"""
return field_name in self.get_field_names(format_string)
def get_field_names(self, format_string):
"""
Get the field names referenced by a format string.
:param format_string: The logging format string.
:returns: A list of strings with field names.
"""
return self.name_pattern.findall(format_string)
def get_grouped_pairs(self, format_string):
"""
Group the results of :func:`get_pairs()` separated by whitespace.
:param format_string: The logging format string.
:returns: A list of lists of :class:`FormatStringToken` objects.
"""
# Step 1: Split simple tokens (without a name) into
# their whitespace parts and non-whitespace parts.
separated = []
pattern = re.compile(r'(\s+)')
for token in self.get_pairs(format_string):
if token.name:
separated.append(token)
else:
separated.extend(
FormatStringToken(name=None, text=text)
for text in pattern.split(token.text) if text
)
# Step 2: Group tokens together based on whitespace.
current_group = []
grouped_pairs = []
for token in separated:
if token.text.isspace():
if current_group:
grouped_pairs.append(current_group)
grouped_pairs.append([token])
current_group = []
else:
current_group.append(token)
if current_group:
grouped_pairs.append(current_group)
return grouped_pairs
def get_pairs(self, format_string):
"""
Tokenize a logging format string and extract field names from tokens.
:param format_string: The logging format string.
:returns: A generator of :class:`FormatStringToken` objects.
"""
for token in self.get_tokens(format_string):
match = self.name_pattern.search(token)
name = match.group(1) if match else None
yield FormatStringToken(name=name, text=token)
def get_pattern(self, field_name):
"""
Get a regular expression to match a formatting directive that references the given field name.
:param field_name: The name of the field to match (a string).
:returns: A compiled regular expression object.
"""
return re.compile(self.raw_pattern.replace(r'\w+', field_name), re.VERBOSE)
def get_tokens(self, format_string):
"""
Tokenize a logging format string.
:param format_string: The logging format string.
:returns: A list of strings with formatting directives separated from surrounding text.
"""
return [t for t in self.tokenize_pattern.split(format_string) if t]
class FormatStringToken(collections.namedtuple('FormatStringToken', 'text, name')):
"""
A named tuple for the results of :func:`FormatStringParser.get_pairs()`.
.. attribute:: name
The field name referenced in `text` (a string). If `text` doesn't
contain a formatting directive this will be :data:`None`.
.. attribute:: text
The text extracted from the logging format string (a string).
"""
class NameNormalizer(object):
"""Responsible for normalizing field and level names."""
def __init__(self):
"""Initialize a :class:`NameNormalizer` object."""
self.aliases = {k.lower(): v.lower() for k, v in find_level_aliases().items()}
def normalize_name(self, name):
"""
Normalize a field or level name.
:param name: The field or level name (a string).
:returns: The normalized name (a string).
Transforms all strings to lowercase and resolves level name aliases
(refer to :func:`find_level_aliases()`) to their canonical name:
>>> from coloredlogs import NameNormalizer
>>> from humanfriendly import format_table
>>> nn = NameNormalizer()
>>> sample_names = ['DEBUG', 'INFO', 'WARN', 'WARNING', 'ERROR', 'FATAL', 'CRITICAL']
>>> print(format_table([(n, nn.normalize_name(n)) for n in sample_names]))
-----------------------
| DEBUG | debug |
| INFO | info |
| WARN | warning |
| WARNING | warning |
| ERROR | error |
| FATAL | critical |
| CRITICAL | critical |
-----------------------
"""
name = name.lower()
if name in self.aliases:
name = self.aliases[name]
return name
def normalize_keys(self, value):
"""
Normalize the keys of a dictionary using :func:`normalize_name()`.
:param value: The dictionary to normalize.
:returns: A dictionary with normalized keys.
"""
return {self.normalize_name(k): v for k, v in value.items()}
def get(self, normalized_dict, name):
"""
Get a value from a dictionary after normalizing the key.
:param normalized_dict: A dictionary produced by :func:`normalize_keys()`.
:param name: A key to normalize and get from the dictionary.
:returns: The value of the normalized key (if any).
"""
return normalized_dict.get(self.normalize_name(name))
| 42.199601 | 114 | 0.64617 |
b1040cddb32f33b183a9eceb6bee29bfcf56554b | 1,076 | py | Python | web/src/stadistic/__init__.py | frhumanes/consulting | 400df4fc59240d2cd1c5807feaabacd056fdce03 | [
"Apache-2.0"
] | null | null | null | web/src/stadistic/__init__.py | frhumanes/consulting | 400df4fc59240d2cd1c5807feaabacd056fdce03 | [
"Apache-2.0"
] | null | null | null | web/src/stadistic/__init__.py | frhumanes/consulting | 400df4fc59240d2cd1c5807feaabacd056fdce03 | [
"Apache-2.0"
] | null | null | null | class StadisticRouter(object):
"""A router to control all database operations on models in
the stadistic application"""
def db_for_read(self, model, **hints):
"Point all operations on myapp models to 'other'"
if model._meta.app_label == 'stadistic':
return 'nonrel'
return 'default'
def db_for_write(self, model, **hints):
"Point all operations on stadistic models to 'other'"
if model._meta.app_label == 'stadistic':
return 'nonrel'
return 'default'
def allow_relation(self, obj1, obj2, **hints):
"Deny any relation if a model in stadistic is involved"
if obj1._meta.app_label == 'stadistic' or obj2._meta.app_label == 'stadistic':
return True
return True
def allow_syncdb(self, db, model):
"Make sure the stadistic app only appears on the 'nonrel' db"
if db == 'nonrel':
return model._meta.app_label == 'stadistic'
elif model._meta.app_label == 'stadistic':
return False
return True | 37.103448 | 86 | 0.621747 |
fd1a38de4492b05c2b2aebb3fdae9d16e80d3dd3 | 2,682 | py | Python | tests/test_simple_aspp.py | crnbaker/MONAI | a4b1144efdc27b197410033ae08bd587c8a1634a | [
"Apache-2.0"
] | null | null | null | tests/test_simple_aspp.py | crnbaker/MONAI | a4b1144efdc27b197410033ae08bd587c8a1634a | [
"Apache-2.0"
] | null | null | null | tests/test_simple_aspp.py | crnbaker/MONAI | a4b1144efdc27b197410033ae08bd587c8a1634a | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 MONAI Consortium
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
import torch
from parameterized import parameterized
from monai.networks import eval_mode
from monai.networks.blocks import SimpleASPP
TEST_CASES = [
[ # 32-channel 2D, batch 7
{"spatial_dims": 2, "in_channels": 32, "conv_out_channels": 3},
(7, 32, 18, 20),
(7, 12, 18, 20),
],
[ # 4-channel 1D, batch 16
{"spatial_dims": 1, "in_channels": 4, "conv_out_channels": 8},
(16, 4, 17),
(16, 32, 17),
],
[ # 3-channel 3D, batch 16
{"spatial_dims": 3, "in_channels": 3, "conv_out_channels": 2},
(16, 3, 17, 18, 19),
(16, 8, 17, 18, 19),
],
[ # 3-channel 3D, batch 16
{
"spatial_dims": 3,
"in_channels": 3,
"conv_out_channels": 2,
"kernel_sizes": (1, 3, 3),
"dilations": (1, 2, 4),
},
(16, 3, 17, 18, 19),
(16, 6, 17, 18, 19),
],
]
TEST_ILL_CASES = [
[ # 3-channel 3D, batch 16, wrong k and d sizes.
{"spatial_dims": 3, "in_channels": 3, "conv_out_channels": 2, "kernel_sizes": (1, 3, 3), "dilations": (1, 2)},
(16, 3, 17, 18, 19),
ValueError,
],
[ # 3-channel 3D, batch 16, wrong k and d sizes.
{
"spatial_dims": 3,
"in_channels": 3,
"conv_out_channels": 2,
"kernel_sizes": (1, 3, 4),
"dilations": (1, 2, 3),
},
(16, 3, 17, 18, 19),
NotImplementedError, # unknown padding k=4, d=3
],
]
class TestChannelSELayer(unittest.TestCase):
@parameterized.expand(TEST_CASES)
def test_shape(self, input_param, input_shape, expected_shape):
net = SimpleASPP(**input_param)
with eval_mode(net):
result = net(torch.randn(input_shape))
self.assertEqual(result.shape, expected_shape)
@parameterized.expand(TEST_ILL_CASES)
def test_ill_args(self, input_param, input_shape, error_type):
with self.assertRaises(error_type):
SimpleASPP(**input_param)
if __name__ == "__main__":
unittest.main()
| 31.552941 | 118 | 0.594333 |
dfdee2abf9718f4c545e45daf4ce01f5f73ea0a6 | 5,072 | py | Python | readthedocs/builds/views.py | agarwalrounak/readthedocs.org | 4911600c230809bd6fb3585d1903121db2928ad6 | [
"MIT"
] | 2 | 2019-11-19T20:50:25.000Z | 2021-04-26T21:59:29.000Z | readthedocs/builds/views.py | agarwalrounak/readthedocs.org | 4911600c230809bd6fb3585d1903121db2928ad6 | [
"MIT"
] | 12 | 2019-12-05T04:47:01.000Z | 2022-01-09T00:56:58.000Z | readthedocs/builds/views.py | agarwalrounak/readthedocs.org | 4911600c230809bd6fb3585d1903121db2928ad6 | [
"MIT"
] | 1 | 2020-01-09T02:35:45.000Z | 2020-01-09T02:35:45.000Z | # -*- coding: utf-8 -*-
"""Views for builds app."""
import logging
import textwrap
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from django.http import (
HttpResponseForbidden,
HttpResponsePermanentRedirect,
HttpResponseRedirect,
)
from django.shortcuts import get_object_or_404
from django.urls import reverse
from django.utils.decorators import method_decorator
from django.views.generic import DetailView, ListView
from requests.utils import quote
from urllib.parse import urlparse
from readthedocs.doc_builder.exceptions import BuildEnvironmentError
from readthedocs.builds.models import Build, Version
from readthedocs.core.permissions import AdminPermission
from readthedocs.core.utils import trigger_build
from readthedocs.projects.models import Project
log = logging.getLogger(__name__)
class BuildBase:
model = Build
def get_queryset(self):
self.project_slug = self.kwargs.get('project_slug', None)
self.project = get_object_or_404(
Project.objects.protected(self.request.user),
slug=self.project_slug,
)
queryset = Build.objects.public(
user=self.request.user,
project=self.project,
)
return queryset
class BuildTriggerMixin:
@method_decorator(login_required)
def post(self, request, project_slug):
project = get_object_or_404(Project, slug=project_slug)
if not AdminPermission.is_admin(request.user, project):
return HttpResponseForbidden()
version_slug = request.POST.get('version_slug')
version = get_object_or_404(
Version,
project=project,
slug=version_slug,
)
update_docs_task, build = trigger_build(
project=project,
version=version,
)
if (update_docs_task, build) == (None, None):
# Build was skipped
messages.add_message(
request,
messages.WARNING,
"This project is currently disabled and can't trigger new builds.",
)
return HttpResponseRedirect(
reverse('builds_project_list', args=[project.slug]),
)
return HttpResponseRedirect(
reverse('builds_detail', args=[project.slug, build.pk]),
)
class BuildList(BuildBase, BuildTriggerMixin, ListView):
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
active_builds = self.get_queryset().exclude(
state='finished',
).values('id')
context['project'] = self.project
context['active_builds'] = active_builds
context['versions'] = Version.objects.public(
user=self.request.user,
project=self.project,
)
context['build_qs'] = self.get_queryset()
return context
class BuildDetail(BuildBase, DetailView):
pk_url_kwarg = 'build_pk'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['project'] = self.project
build = self.get_object()
if build.error != BuildEnvironmentError.GENERIC_WITH_BUILD_ID.format(build_id=build.pk):
# Do not suggest to open an issue if the error is not generic
return context
scheme = (
'https://github.com/rtfd/readthedocs.org/issues/new'
'?title={title}{build_id}'
'&body={body}'
)
# TODO: we could use ``.github/ISSUE_TEMPLATE.md`` here, but we would
# need to add some variables to it which could impact in the UX when
# filling an issue from the web
body = """
## Details:
* Project URL: https://readthedocs.org/projects/{project_slug}/
* Build URL(if applicable): https://readthedocs.org{build_path}
* Read the Docs username(if applicable): {username}
## Expected Result
*A description of what you wanted to happen*
## Actual Result
*A description of what actually happened*""".format(
project_slug=self.project,
build_path=self.request.path,
username=self.request.user,
)
scheme_dict = {
'title': quote('Build error with build id #'),
'build_id': context['build'].id,
'body': quote(textwrap.dedent(body)),
}
issue_url = scheme.format(**scheme_dict)
issue_url = urlparse(issue_url).geturl()
context['issue_url'] = issue_url
return context
# Old build view redirects
def builds_redirect_list(request, project_slug): # pylint: disable=unused-argument
return HttpResponsePermanentRedirect(
reverse('builds_project_list', args=[project_slug]),
)
def builds_redirect_detail(request, project_slug, pk): # pylint: disable=unused-argument
return HttpResponsePermanentRedirect(
reverse('builds_detail', args=[project_slug, pk]),
)
| 29.835294 | 96 | 0.644716 |
dd3c1441f8f8b26473d15889198abb3593edfa51 | 11,618 | py | Python | legacy/ctr/avazu_data_processer.py | FrancisLiang/models-1 | e14d5bc1ab36d0dd11977f27cff54605bf99c945 | [
"Apache-2.0"
] | 4 | 2020-01-04T13:15:02.000Z | 2021-07-21T07:50:02.000Z | legacy/ctr/avazu_data_processer.py | FrancisLiang/models-1 | e14d5bc1ab36d0dd11977f27cff54605bf99c945 | [
"Apache-2.0"
] | 2 | 2019-06-26T03:21:49.000Z | 2019-09-19T09:43:42.000Z | legacy/ctr/avazu_data_processer.py | FrancisLiang/models-1 | e14d5bc1ab36d0dd11977f27cff54605bf99c945 | [
"Apache-2.0"
] | 3 | 2019-10-31T07:18:49.000Z | 2020-01-13T03:18:39.000Z | import sys
import csv
import cPickle
import argparse
import os
import numpy as np
from utils import logger, TaskMode
parser = argparse.ArgumentParser(description="PaddlePaddle CTR example")
parser.add_argument(
'--data_path', type=str, required=True, help="path of the Avazu dataset")
parser.add_argument(
'--output_dir', type=str, required=True, help="directory to output")
parser.add_argument(
'--num_lines_to_detect',
type=int,
default=500000,
help="number of records to detect dataset's meta info")
parser.add_argument(
'--test_set_size',
type=int,
default=10000,
help="size of the validation dataset(default: 10000)")
parser.add_argument(
'--train_size',
type=int,
default=100000,
help="size of the trainset (default: 100000)")
args = parser.parse_args()
'''
The fields of the dataset are:
0. id: ad identifier
1. click: 0/1 for non-click/click
2. hour: format is YYMMDDHH, so 14091123 means 23:00 on Sept. 11, 2014 UTC.
3. C1 -- anonymized categorical variable
4. banner_pos
5. site_id
6. site_domain
7. site_category
8. app_id
9. app_domain
10. app_category
11. device_id
12. device_ip
13. device_model
14. device_type
15. device_conn_type
16. C14-C21 -- anonymized categorical variables
We will treat the following fields as categorical features:
- C1
- banner_pos
- site_category
- app_category
- device_type
- device_conn_type
and some other features as id features:
- id
- site_id
- app_id
- device_id
The `hour` field will be treated as a continuous feature and will be transformed
to one-hot representation which has 24 bits.
This script will output 3 files:
1. train.txt
2. test.txt
3. infer.txt
all the files are for demo.
'''
feature_dims = {}
categorial_features = (
'C1 banner_pos site_category app_category ' + 'device_type device_conn_type'
).split()
id_features = 'id site_id app_id device_id _device_id_cross_site_id'.split()
def get_all_field_names(mode=0):
'''
@mode: int
0 for train, 1 for test
@return: list of str
'''
return categorial_features + ['hour'] + id_features + ['click'] \
if mode == 0 else []
class CategoryFeatureGenerator(object):
'''
Generator category features.
Register all records by calling `register` first, then call `gen` to generate
one-hot representation for a record.
'''
def __init__(self):
self.dic = {'unk': 0}
self.counter = 1
def register(self, key):
'''
Register record.
'''
if key not in self.dic:
self.dic[key] = self.counter
self.counter += 1
def size(self):
return len(self.dic)
def gen(self, key):
'''
Generate one-hot representation for a record.
'''
if key not in self.dic:
res = self.dic['unk']
else:
res = self.dic[key]
return [res]
def __repr__(self):
return '<CategoryFeatureGenerator %d>' % len(self.dic)
class IDfeatureGenerator(object):
def __init__(self, max_dim, cross_fea0=None, cross_fea1=None):
'''
@max_dim: int
Size of the id elements' space
'''
self.max_dim = max_dim
self.cross_fea0 = cross_fea0
self.cross_fea1 = cross_fea1
def gen(self, key):
'''
Generate one-hot representation for records
'''
return [hash(key) % self.max_dim]
def gen_cross_fea(self, fea1, fea2):
key = str(fea1) + str(fea2)
return self.gen(key)
def size(self):
return self.max_dim
class ContinuousFeatureGenerator(object):
def __init__(self, n_intervals):
self.min = sys.maxint
self.max = sys.minint
self.n_intervals = n_intervals
def register(self, val):
self.min = min(self.minint, val)
self.max = max(self.maxint, val)
def gen(self, val):
self.len_part = (self.max - self.min) / self.n_intervals
return (val - self.min) / self.len_part
# init all feature generators
fields = {}
for key in categorial_features:
fields[key] = CategoryFeatureGenerator()
for key in id_features:
# for cross features
if 'cross' in key:
feas = key[1:].split('_cross_')
fields[key] = IDfeatureGenerator(10000000, *feas)
# for normal ID features
else:
fields[key] = IDfeatureGenerator(10000)
# used as feed_dict in PaddlePaddle
field_index = dict((key, id)
for id, key in enumerate(['dnn_input', 'lr_input', 'click']))
def detect_dataset(path, topn, id_fea_space=10000):
'''
Parse the first `topn` records to collect meta information of this dataset.
NOTE the records should be randomly shuffled first.
'''
# create categorical statis objects.
logger.warning('detecting dataset')
with open(path, 'rb') as csvfile:
reader = csv.DictReader(csvfile)
for row_id, row in enumerate(reader):
if row_id > topn:
break
for key in categorial_features:
fields[key].register(row[key])
for key, item in fields.items():
feature_dims[key] = item.size()
feature_dims['hour'] = 24
feature_dims['click'] = 1
feature_dims['dnn_input'] = np.sum(
feature_dims[key] for key in categorial_features + ['hour']) + 1
feature_dims['lr_input'] = np.sum(feature_dims[key]
for key in id_features) + 1
return feature_dims
def load_data_meta(meta_path):
'''
Load dataset's meta infomation.
'''
feature_dims, fields = cPickle.load(open(meta_path, 'rb'))
return feature_dims, fields
def concat_sparse_vectors(inputs, dims):
'''
Concaterate more than one sparse vectors into one.
@inputs: list
list of sparse vector
@dims: list of int
dimention of each sparse vector
'''
res = []
assert len(inputs) == len(dims)
start = 0
for no, vec in enumerate(inputs):
for v in vec:
res.append(v + start)
start += dims[no]
return res
class AvazuDataset(object):
'''
Load AVAZU dataset as train set.
'''
def __init__(self,
train_path,
n_records_as_test=-1,
fields=None,
feature_dims=None):
self.train_path = train_path
self.n_records_as_test = n_records_as_test
self.fields = fields
# default is train mode.
self.mode = TaskMode.create_train()
self.categorial_dims = [
feature_dims[key] for key in categorial_features + ['hour']
]
self.id_dims = [feature_dims[key] for key in id_features]
def train(self):
'''
Load trainset.
'''
logger.info("load trainset from %s" % self.train_path)
self.mode = TaskMode.create_train()
with open(self.train_path) as f:
reader = csv.DictReader(f)
for row_id, row in enumerate(reader):
# skip top n lines
if self.n_records_as_test > 0 and row_id < self.n_records_as_test:
continue
rcd = self._parse_record(row)
if rcd:
yield rcd
def test(self):
'''
Load testset.
'''
logger.info("load testset from %s" % self.train_path)
self.mode = TaskMode.create_test()
with open(self.train_path) as f:
reader = csv.DictReader(f)
for row_id, row in enumerate(reader):
# skip top n lines
if self.n_records_as_test > 0 and row_id > self.n_records_as_test:
break
rcd = self._parse_record(row)
if rcd:
yield rcd
def infer(self):
'''
Load inferset.
'''
logger.info("load inferset from %s" % self.train_path)
self.mode = TaskMode.create_infer()
with open(self.train_path) as f:
reader = csv.DictReader(f)
for row_id, row in enumerate(reader):
rcd = self._parse_record(row)
if rcd:
yield rcd
def _parse_record(self, row):
'''
Parse a CSV row and get a record.
'''
record = []
for key in categorial_features:
record.append(self.fields[key].gen(row[key]))
record.append([int(row['hour'][-2:])])
dense_input = concat_sparse_vectors(record, self.categorial_dims)
record = []
for key in id_features:
if 'cross' not in key:
record.append(self.fields[key].gen(row[key]))
else:
fea0 = self.fields[key].cross_fea0
fea1 = self.fields[key].cross_fea1
record.append(self.fields[key].gen_cross_fea(row[fea0], row[
fea1]))
sparse_input = concat_sparse_vectors(record, self.id_dims)
record = [dense_input, sparse_input]
if not self.mode.is_infer():
record.append(list((int(row['click']), )))
return record
def ids2dense(vec, dim):
return vec
def ids2sparse(vec):
return ["%d:1" % x for x in vec]
detect_dataset(args.data_path, args.num_lines_to_detect)
dataset = AvazuDataset(
args.data_path,
args.test_set_size,
fields=fields,
feature_dims=feature_dims)
output_trainset_path = os.path.join(args.output_dir, 'train.txt')
output_testset_path = os.path.join(args.output_dir, 'test.txt')
output_infer_path = os.path.join(args.output_dir, 'infer.txt')
output_meta_path = os.path.join(args.output_dir, 'data.meta.txt')
with open(output_trainset_path, 'w') as f:
for id, record in enumerate(dataset.train()):
if id and id % 10000 == 0:
logger.info("load %d records" % id)
if id > args.train_size:
break
dnn_input, lr_input, click = record
dnn_input = ids2dense(dnn_input, feature_dims['dnn_input'])
lr_input = ids2sparse(lr_input)
line = "%s\t%s\t%d\n" % (' '.join(map(str, dnn_input)),
' '.join(map(str, lr_input)), click[0])
f.write(line)
logger.info('write to %s' % output_trainset_path)
with open(output_testset_path, 'w') as f:
for id, record in enumerate(dataset.test()):
dnn_input, lr_input, click = record
dnn_input = ids2dense(dnn_input, feature_dims['dnn_input'])
lr_input = ids2sparse(lr_input)
line = "%s\t%s\t%d\n" % (' '.join(map(str, dnn_input)),
' '.join(map(str, lr_input)), click[0])
f.write(line)
logger.info('write to %s' % output_testset_path)
with open(output_infer_path, 'w') as f:
for id, record in enumerate(dataset.infer()):
dnn_input, lr_input = record
dnn_input = ids2dense(dnn_input, feature_dims['dnn_input'])
lr_input = ids2sparse(lr_input)
line = "%s\t%s\n" % (
' '.join(map(str, dnn_input)),
' '.join(map(str, lr_input)), )
f.write(line)
if id > args.test_set_size:
break
logger.info('write to %s' % output_infer_path)
with open(output_meta_path, 'w') as f:
lines = [
"dnn_input_dim: %d" % feature_dims['dnn_input'],
"lr_input_dim: %d" % feature_dims['lr_input']
]
f.write('\n'.join(lines))
logger.info('write data meta into %s' % output_meta_path)
| 27.995181 | 82 | 0.599587 |
9d312da6b9468a825b1e5682e680b82cf68aabe1 | 9,388 | py | Python | sdk/python/pulumi_aws/elasticbeanstalk/environment.py | Charliekenney23/pulumi-aws | 55bd0390160d27350b297834026fee52114a2d41 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_aws/elasticbeanstalk/environment.py | Charliekenney23/pulumi-aws | 55bd0390160d27350b297834026fee52114a2d41 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | sdk/python/pulumi_aws/elasticbeanstalk/environment.py | Charliekenney23/pulumi-aws | 55bd0390160d27350b297834026fee52114a2d41 | [
"ECL-2.0",
"Apache-2.0"
] | null | null | null | # coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***
import json
import warnings
import pulumi
import pulumi.runtime
from .. import utilities, tables
class Environment(pulumi.CustomResource):
all_settings: pulumi.Output[list]
"""
List of all option settings configured in the Environment. These
are a combination of default settings and their overrides from `setting` in
the configuration.
"""
application: pulumi.Output[str]
"""
Name of the application that contains the version
to be deployed
"""
arn: pulumi.Output[str]
autoscaling_groups: pulumi.Output[list]
"""
The autoscaling groups used by this environment.
"""
cname: pulumi.Output[str]
"""
Fully qualified DNS name for the Environment.
"""
cname_prefix: pulumi.Output[str]
"""
Prefix to use for the fully qualified DNS name of
the Environment.
"""
description: pulumi.Output[str]
"""
Short description of the Environment
"""
instances: pulumi.Output[list]
"""
Instances used by this environment.
"""
launch_configurations: pulumi.Output[list]
"""
Launch configurations in use by this environment.
"""
load_balancers: pulumi.Output[list]
"""
Elastic load balancers in use by this environment.
"""
name: pulumi.Output[str]
"""
A unique name for this Environment. This name is used
in the application URL
"""
platform_arn: pulumi.Output[str]
"""
The [ARN][2] of the Elastic Beanstalk [Platform][3]
to use in deployment
"""
poll_interval: pulumi.Output[str]
"""
The time between polling the AWS API to
check if changes have been applied. Use this to adjust the rate of API calls
for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to
use the default behavior, which is an exponential backoff
"""
queues: pulumi.Output[list]
"""
SQS queues in use by this environment.
"""
settings: pulumi.Output[list]
"""
Option settings to configure the new Environment. These
override specific values that are set as defaults. The format is detailed
below in Option Settings
"""
solution_stack_name: pulumi.Output[str]
"""
A solution stack to base your environment
off of. Example stacks can be found in the [Amazon API documentation][1]
"""
tags: pulumi.Output[dict]
"""
A set of tags to apply to the Environment.
"""
template_name: pulumi.Output[str]
"""
The name of the Elastic Beanstalk Configuration
template to use in deployment
"""
tier: pulumi.Output[str]
"""
Elastic Beanstalk Environment tier. Valid values are `Worker`
or `WebServer`. If tier is left blank `WebServer` will be used.
"""
triggers: pulumi.Output[list]
"""
Autoscaling triggers in use by this environment.
"""
version: pulumi.Output[str]
"""
The name of the Elastic Beanstalk Application Version
to use in deployment.
"""
wait_for_ready_timeout: pulumi.Output[str]
"""
The maximum
[duration](https://golang.org/pkg/time/#ParseDuration) that Terraform should
wait for an Elastic Beanstalk Environment to be in a ready state before timing
out.
"""
def __init__(__self__, resource_name, opts=None, application=None, cname_prefix=None, description=None, name=None, platform_arn=None, poll_interval=None, settings=None, solution_stack_name=None, tags=None, template_name=None, tier=None, version=None, wait_for_ready_timeout=None, __name__=None, __opts__=None):
"""
Provides an Elastic Beanstalk Environment Resource. Elastic Beanstalk allows
you to deploy and manage applications in the AWS cloud without worrying about
the infrastructure that runs those applications.
Environments are often things such as `development`, `integration`, or
`production`.
## Option Settings
Some options can be stack-specific, check [AWS Docs](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html)
for supported options and examples.
The `setting` and `all_settings` mappings support the following format:
* `namespace` - unique namespace identifying the option's associated AWS resource
* `name` - name of the configuration option
* `value` - value for the configuration option
* `resource` - (Optional) resource name for [scheduled action](https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/command-options-general.html#command-options-general-autoscalingscheduledaction)
:param str resource_name: The name of the resource.
:param pulumi.ResourceOptions opts: Options for the resource.
:param pulumi.Input[str] application: Name of the application that contains the version
to be deployed
:param pulumi.Input[str] cname_prefix: Prefix to use for the fully qualified DNS name of
the Environment.
:param pulumi.Input[str] description: Short description of the Environment
:param pulumi.Input[str] name: A unique name for this Environment. This name is used
in the application URL
:param pulumi.Input[str] platform_arn: The [ARN][2] of the Elastic Beanstalk [Platform][3]
to use in deployment
:param pulumi.Input[str] poll_interval: The time between polling the AWS API to
check if changes have been applied. Use this to adjust the rate of API calls
for any `create` or `update` action. Minimum `10s`, maximum `180s`. Omit this to
use the default behavior, which is an exponential backoff
:param pulumi.Input[list] settings: Option settings to configure the new Environment. These
override specific values that are set as defaults. The format is detailed
below in Option Settings
:param pulumi.Input[str] solution_stack_name: A solution stack to base your environment
off of. Example stacks can be found in the [Amazon API documentation][1]
:param pulumi.Input[dict] tags: A set of tags to apply to the Environment.
:param pulumi.Input[str] template_name: The name of the Elastic Beanstalk Configuration
template to use in deployment
:param pulumi.Input[str] tier: Elastic Beanstalk Environment tier. Valid values are `Worker`
or `WebServer`. If tier is left blank `WebServer` will be used.
:param pulumi.Input[str] version: The name of the Elastic Beanstalk Application Version
to use in deployment.
:param pulumi.Input[str] wait_for_ready_timeout: The maximum
[duration](https://golang.org/pkg/time/#ParseDuration) that Terraform should
wait for an Elastic Beanstalk Environment to be in a ready state before timing
out.
"""
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()
if application is None:
raise TypeError("Missing required property 'application'")
__props__['application'] = application
__props__['cname_prefix'] = cname_prefix
__props__['description'] = description
__props__['name'] = name
__props__['platform_arn'] = platform_arn
__props__['poll_interval'] = poll_interval
__props__['settings'] = settings
__props__['solution_stack_name'] = solution_stack_name
__props__['tags'] = tags
__props__['template_name'] = template_name
__props__['tier'] = tier
__props__['version'] = version
__props__['wait_for_ready_timeout'] = wait_for_ready_timeout
__props__['all_settings'] = None
__props__['arn'] = None
__props__['autoscaling_groups'] = None
__props__['cname'] = None
__props__['instances'] = None
__props__['launch_configurations'] = None
__props__['load_balancers'] = None
__props__['queues'] = None
__props__['triggers'] = None
super(Environment, __self__).__init__(
'aws:elasticbeanstalk/environment:Environment',
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
| 40.119658 | 314 | 0.669046 |
d0e804ed604e751008f49c463abf0c9aa3edb433 | 4,736 | py | Python | rdr_service/lib_fhir/fhirclient_3_0_0/models/operationdefinition_tests.py | all-of-us/raw-data-repository | d28ad957557587b03ff9c63d55dd55e0508f91d8 | [
"BSD-3-Clause"
] | 39 | 2017-10-13T19:16:27.000Z | 2021-09-24T16:58:21.000Z | rdr_service/lib_fhir/fhirclient_3_0_0/models/operationdefinition_tests.py | all-of-us/raw-data-repository | d28ad957557587b03ff9c63d55dd55e0508f91d8 | [
"BSD-3-Clause"
] | 312 | 2017-09-08T15:42:13.000Z | 2022-03-23T18:21:40.000Z | rdr_service/lib_fhir/fhirclient_3_0_0/models/operationdefinition_tests.py | all-of-us/raw-data-repository | d28ad957557587b03ff9c63d55dd55e0508f91d8 | [
"BSD-3-Clause"
] | 19 | 2017-09-15T13:58:00.000Z | 2022-02-07T18:33:20.000Z | #!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Generated from FHIR 3.0.0.11832 on 2017-03-22.
# 2017, SMART Health IT.
import io
import json
import os
import unittest
from . import operationdefinition
from .fhirdate import FHIRDate
class OperationDefinitionTests(unittest.TestCase):
def instantiate_from(self, filename):
datadir = os.environ.get('FHIR_UNITTEST_DATADIR') or ''
with io.open(os.path.join(datadir, filename), 'r', encoding='utf-8') as handle:
js = json.load(handle)
self.assertEqual("OperationDefinition", js["resourceType"])
return operationdefinition.OperationDefinition(js)
def testOperationDefinition1(self):
inst = self.instantiate_from("operationdefinition-example.json")
self.assertIsNotNone(inst, "Must have instantiated a OperationDefinition instance")
self.implOperationDefinition1(inst)
js = inst.as_json()
self.assertEqual("OperationDefinition", js["resourceType"])
inst2 = operationdefinition.OperationDefinition(js)
self.implOperationDefinition1(inst2)
def implOperationDefinition1(self, inst):
self.assertEqual(inst.code, "populate")
self.assertEqual(inst.comment, "Only implemented for Labs and Medications so far")
self.assertEqual(inst.contact[0].name, "System Administrator")
self.assertEqual(inst.contact[0].telecom[0].system, "email")
self.assertEqual(inst.contact[0].telecom[0].value, "beep@coyote.acme.com")
self.assertEqual(inst.date.date, FHIRDate("2015-08-04").date)
self.assertEqual(inst.date.as_json(), "2015-08-04")
self.assertEqual(inst.description, "Limited implementation of the Populate Questionnaire implemenation")
self.assertEqual(inst.id, "example")
self.assertTrue(inst.instance)
self.assertEqual(inst.jurisdiction[0].coding[0].code, "GB")
self.assertEqual(inst.jurisdiction[0].coding[0].display, "United Kingdom of Great Britain and Northern Ireland (the)")
self.assertEqual(inst.jurisdiction[0].coding[0].system, "urn:iso:std:iso:3166")
self.assertEqual(inst.kind, "operation")
self.assertEqual(inst.name, "Populate Questionnaire")
self.assertEqual(inst.overload[0].parameterName[0], "subject")
self.assertEqual(inst.overload[0].parameterName[1], "local")
self.assertEqual(inst.overload[1].comment, "local defaults to false when not passed as a parameter")
self.assertEqual(inst.overload[1].parameterName[0], "subject")
self.assertEqual(inst.parameter[0].max, "1")
self.assertEqual(inst.parameter[0].min, 1)
self.assertEqual(inst.parameter[0].name, "subject")
self.assertEqual(inst.parameter[0].type, "Reference")
self.assertEqual(inst.parameter[0].use, "in")
self.assertEqual(inst.parameter[1].documentation, "If the *local* parameter is set to true, server information about the specified subject will be used to populate the instance.")
self.assertEqual(inst.parameter[1].max, "1")
self.assertEqual(inst.parameter[1].min, 0)
self.assertEqual(inst.parameter[1].name, "local")
self.assertEqual(inst.parameter[1].type, "Reference")
self.assertEqual(inst.parameter[1].use, "in")
self.assertEqual(inst.parameter[2].documentation, "The partially (or fully)-populated set of answers for the specified Questionnaire")
self.assertEqual(inst.parameter[2].max, "1")
self.assertEqual(inst.parameter[2].min, 1)
self.assertEqual(inst.parameter[2].name, "return")
self.assertEqual(inst.parameter[2].type, "QuestionnaireResponse")
self.assertEqual(inst.parameter[2].use, "out")
self.assertEqual(inst.publisher, "Acme Healthcare Services")
self.assertEqual(inst.resource[0], "Questionnaire")
self.assertEqual(inst.status, "draft")
self.assertFalse(inst.system)
self.assertEqual(inst.text.status, "generated")
self.assertFalse(inst.type)
self.assertEqual(inst.url, "http://h7.org/fhir/OperationDefinition/example")
self.assertEqual(inst.useContext[0].code.code, "venue")
self.assertEqual(inst.useContext[0].code.display, "Clinical Venue")
self.assertEqual(inst.useContext[0].code.system, "http://build.fhir.org/codesystem-usage-context-type")
self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].code, "IMP")
self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].display, "inpatient encounter")
self.assertEqual(inst.useContext[0].valueCodeableConcept.coding[0].system, "http://hl7.org/fhir/v3/ActCode")
self.assertEqual(inst.version, "B")
| 54.436782 | 187 | 0.699958 |
249cc25f23c0af32f7bcdc69dd89d7dc39754b33 | 346 | py | Python | etc/launch_common_scf.py | rubel75/aiida-wien2k | 255c4aa72a6d503b72b502371758605242b0a673 | [
"MIT"
] | 1 | 2022-03-19T00:08:35.000Z | 2022-03-19T00:08:35.000Z | etc/launch_common_scf.py | rubel75/aiida-wien2k | 255c4aa72a6d503b72b502371758605242b0a673 | [
"MIT"
] | null | null | null | etc/launch_common_scf.py | rubel75/aiida-wien2k | 255c4aa72a6d503b72b502371758605242b0a673 | [
"MIT"
] | null | null | null | from aiida_common_workflows.workflows.relax.wien2k import Wien2kCommonRelaxWorkChain
inputgen = Wien2kCommonRelaxWorkChain.get_input_generator()
from aiida.engine import submit, run
builder = inputgen.get_builder(structure=load_node(73739),engines= {
'relax': {
'code': 'wien2k-run123_lapw@localhost'
}
})
run(builder) | 38.444444 | 84 | 0.757225 |
a0f7aa91517d82b34123e11c2477b7efc701c103 | 9,417 | py | Python | akshare/stock/stock_info.py | X-Mars/akshare | 5483fd649b7a7cfc0520b0cbaaf2d76b076855d5 | [
"MIT"
] | null | null | null | akshare/stock/stock_info.py | X-Mars/akshare | 5483fd649b7a7cfc0520b0cbaaf2d76b076855d5 | [
"MIT"
] | null | null | null | akshare/stock/stock_info.py | X-Mars/akshare | 5483fd649b7a7cfc0520b0cbaaf2d76b076855d5 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding:utf-8 -*-
"""
Date: 2021/7/6 20:31
Desc: 股票基本信息
"""
import json
import warnings
from io import BytesIO
import pandas as pd
import requests
def stock_info_sz_name_code(indicator: str = "A股列表") -> pd.DataFrame:
"""
深圳证券交易所-股票列表
http://www.szse.cn/market/product/stock/list/index.html
:param indicator: choice of {"A股列表", "B股列表", "CDR列表", "AB股列表"}
:type indicator: str
:return: 指定 indicator 的数据
:rtype: pandas.DataFrame
"""
url = "http://www.szse.cn/api/report/ShowReport"
indicator_map = {"A股列表": "tab1", "B股列表": "tab2", "CDR列表": "tab3", "AB股列表": "tab4"}
params = {
"SHOWTYPE": "xlsx",
"CATALOGID": "1110",
"TABKEY": indicator_map[indicator],
"random": "0.6935816432433362",
}
r = requests.get(url, params=params)
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
temp_df = pd.read_excel(BytesIO(r.content))
if len(temp_df) > 10:
if indicator == "A股列表":
temp_df["A股代码"] = temp_df["A股代码"].astype(str).str.split('.', expand=True).iloc[:, 0].str.zfill(6).str.replace("000nan", "")
temp_df = temp_df[[
'板块',
'A股代码',
'A股简称',
'A股上市日期',
'A股总股本',
'A股流通股本',
'所属行业',
]]
elif indicator == "B股列表":
temp_df["B股代码"] = temp_df["B股代码"].astype(str).str.split('.', expand=True).iloc[:, 0].str.zfill(6).str.replace("000nan", "")
temp_df = temp_df[[
'板块',
'B股代码',
'B股简称',
'B股上市日期',
'B股总股本',
'B股流通股本',
'所属行业',
]]
elif indicator == "AB股列表":
temp_df["A股代码"] = temp_df["A股代码"].astype(str).str.split('.', expand=True).iloc[:, 0].str.zfill(6).str.replace("000nan", "")
temp_df["B股代码"] = temp_df["B股代码"].astype(str).str.split('.', expand=True).iloc[:, 0].str.zfill(6).str.replace("000nan", "")
temp_df = temp_df[[
'板块',
'A股代码',
'A股简称',
'A股上市日期',
'B股代码',
'B股简称',
'B股上市日期',
'所属行业',
]]
return temp_df
else:
return temp_df
def stock_info_sh_name_code(indicator: str = "主板A股") -> pd.DataFrame:
"""
上海证券交易所-股票列表
http://www.sse.com.cn/assortment/stock/list/share/
:param indicator: choice of {"主板A股": "1", "主板B股": "2", "科创板": "8"}
:type indicator: str
:return: 指定 indicator 的数据
:rtype: pandas.DataFrame
"""
indicator_map = {"主板A股": "1", "主板B股": "2", "科创板": "8"}
url = "http://query.sse.com.cn/security/stock/getStockListData.do"
headers = {
"Host": "query.sse.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.sse.com.cn/assortment/stock/list/share/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
}
params = {
"jsonCallBack": "jsonpCallback66942",
"isPagination": "true",
"stockCode": "",
"csrcCode": "",
"areaName": "",
"stockType": indicator_map[indicator],
"pageHelp.cacheSize": "1",
"pageHelp.beginPage": "1",
"pageHelp.pageSize": "2000",
"pageHelp.pageNo": "1",
"pageHelp.endPage": "11",
"_": "1589881387934",
}
r = requests.get(url, params=params, headers=headers)
text_data = r.text
json_data = json.loads(text_data[text_data.find("{"):-1])
temp_df = pd.DataFrame(json_data["result"])
return temp_df
def stock_info_sh_delist(indicator: str = "暂停上市公司"):
"""
上海证券交易所-暂停上市公司-终止上市公司
http://www.sse.com.cn/assortment/stock/list/firstissue/
:param indicator: choice of {"终止上市公司": "5", "暂停上市公司": "4"}
:type indicator: str
:return: 暂停上市公司 or 终止上市公司 的数据
:rtype: pandas.DataFrame
"""
indicator_map = {"终止上市公司": "5", "暂停上市公司": "4"}
url = "http://query.sse.com.cn/security/stock/getStockListData2.do"
headers = {
"Host": "query.sse.com.cn",
"Pragma": "no-cache",
"Referer": "http://www.sse.com.cn/assortment/stock/list/share/",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.138 Safari/537.36",
}
params = {
"jsonCallBack": "jsonpCallback66942",
"isPagination": "true",
"stockCode": "",
"csrcCode": "",
"areaName": "",
"stockType": indicator_map[indicator],
"pageHelp.cacheSize": "1",
"pageHelp.beginPage": "1",
"pageHelp.pageSize": "2000",
"pageHelp.pageNo": "1",
"pageHelp.endPage": "11",
"_": "1589881387934",
}
r = requests.get(url, params=params, headers=headers)
text_data = r.text
json_data = json.loads(text_data[text_data.find("{"):-1])
temp_df = pd.DataFrame(json_data["result"])
return temp_df
def stock_info_sz_delist(indicator: str = "暂停上市公司") -> pd.DataFrame:
"""
深证证券交易所-暂停上市公司-终止上市公司
http://www.szse.cn/market/stock/suspend/index.html
:param indicator: choice of {"暂停上市公司", "终止上市公司"}
:type indicator: str
:return: 暂停上市公司 or 终止上市公司 的数据
:rtype: pandas.DataFrame
"""
indicator_map = {"暂停上市公司": "tab1", "终止上市公司": "tab2"}
url = "http://www.szse.cn/api/report/ShowReport"
params = {
"SHOWTYPE": "xlsx",
"CATALOGID": "1793_ssgs",
"TABKEY": indicator_map[indicator],
"random": "0.6935816432433362",
}
r = requests.get(url, params=params)
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
temp_df = pd.read_excel(BytesIO(r.content))
temp_df["证券代码"] = temp_df["证券代码"].astype("str").str.zfill(6)
return temp_df
def stock_info_sz_change_name(indicator: str = "全称变更") -> pd.DataFrame:
"""
深证证券交易所-更名公司
http://www.szse.cn/market/companys/changename/index.html
:param indicator: choice of {"全称变更": "tab1", "简称变更": "tab2"}
:type indicator: str
:return: 全称变更 or 简称变更 的数据
:rtype: pandas.DataFrame
"""
indicator_map = {"全称变更": "tab1", "简称变更": "tab2"}
url = "http://www.szse.cn/api/report/ShowReport"
params = {
"SHOWTYPE": "xlsx",
"CATALOGID": "SSGSGMXX",
"TABKEY": indicator_map[indicator],
"random": "0.6935816432433362",
}
r = requests.get(url, params=params)
with warnings.catch_warnings(record=True):
warnings.simplefilter("always")
temp_df = pd.read_excel(BytesIO(r.content))
temp_df["证券代码"] = temp_df["证券代码"].astype("str").str.zfill(6)
return temp_df
def stock_info_change_name(stock: str = "688588") -> pd.DataFrame:
"""
新浪财经-股票曾用名
http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpInfo/stockid/300378.phtml
:param stock: 股票代码
:type stock: str
:return: 股票曾用名列表
:rtype: list
"""
url = f"http://vip.stock.finance.sina.com.cn/corp/go.php/vCI_CorpInfo/stockid/{stock}.phtml"
r = requests.get(url)
temp_df = pd.read_html(r.text)[3].iloc[:, :2]
temp_df.dropna(inplace=True)
temp_df.columns = ["item", "value"]
temp_df["item"] = temp_df["item"].str.split(":", expand=True)[0]
try:
name_list = temp_df[temp_df["item"] == "证券简称更名历史"].value.tolist()[0].split(" ")
return name_list
except:
return None
def stock_info_a_code_name() -> pd.DataFrame:
"""
沪深 A 股列表
:return: 沪深 A 股数据
:rtype: pandas.DataFrame
"""
big_df = pd.DataFrame()
stock_sh = stock_info_sh_name_code(indicator="主板A股")
stock_sh = stock_sh[["SECURITY_CODE_A", "SECURITY_ABBR_A"]]
stock_sh.columns = ["公司代码", "公司简称"]
stock_sz = stock_info_sz_name_code(indicator="A股列表")
stock_sz["A股代码"] = stock_sz["A股代码"].astype(str).str.zfill(6)
big_df = big_df.append(stock_sz[["A股代码", "A股简称"]], ignore_index=True)
big_df.columns = ["公司代码", "公司简称"]
stock_kcb = stock_info_sh_name_code(indicator="科创板")
stock_kcb = stock_kcb[["SECURITY_CODE_A", "SECURITY_ABBR_A"]]
stock_kcb.columns = ["公司代码", "公司简称"]
big_df = big_df.append(stock_sh, ignore_index=True)
big_df = big_df.append(stock_kcb, ignore_index=True)
big_df.columns = ["code", "name"]
return big_df
if __name__ == '__main__':
stock_info_sz_df = stock_info_sz_name_code(indicator="A股列表")
print(stock_info_sz_df)
stock_info_sz_df = stock_info_sz_name_code(indicator="B股列表")
print(stock_info_sz_df)
stock_info_sz_df = stock_info_sz_name_code(indicator="AB股列表")
print(stock_info_sz_df)
stock_info_sz_df = stock_info_sz_name_code(indicator="CDR列表")
print(stock_info_sz_df)
stock_info_sh_delist_df = stock_info_sh_delist(indicator="终止上市公司")
print(stock_info_sh_delist_df)
stock_info_sz_delist_df = stock_info_sz_delist(indicator="终止上市公司")
print(stock_info_sz_delist_df)
stock_info_sz_change_name_df = stock_info_sz_change_name(indicator="全称变更")
print(stock_info_sz_change_name_df)
stock_info_change_name_list = stock_info_change_name(stock="000503")
print(stock_info_change_name_list)
stock_info_a_code_name_df = stock_info_a_code_name()
print(stock_info_a_code_name_df)
| 33.874101 | 140 | 0.59966 |
35713ea27f62abd8d5a0f82e0c546714203e8775 | 2,031 | py | Python | lib/sparseconvnet/__init__.py | reinforcementdriving/JS3C-Net | 40326fdbebc688c10a6247f46ed08463de0db206 | [
"MIT"
] | 136 | 2020-12-07T16:05:13.000Z | 2022-03-28T11:42:23.000Z | lib/sparseconvnet/__init__.py | reinforcementdriving/JS3C-Net | 40326fdbebc688c10a6247f46ed08463de0db206 | [
"MIT"
] | 14 | 2021-01-14T13:06:06.000Z | 2022-03-19T07:20:16.000Z | lib/sparseconvnet/__init__.py | reinforcementdriving/JS3C-Net | 40326fdbebc688c10a6247f46ed08463de0db206 | [
"MIT"
] | 23 | 2020-12-26T12:01:12.000Z | 2022-01-20T01:24:23.000Z | # Copyright 2016-present, Facebook, Inc.
# All rights reserved.
#
# This source code is licensed under the BSD-style license found in the
# LICENSE file in the root directory of this source tree.
forward_pass_multiplyAdd_count = 0
forward_pass_hidden_states = 0
from .abstract import abstract
from .add import Add_fun, Add2_fun
from .activations import Tanh, Sigmoid, ReLU, LeakyReLU, ELU, SELU, BatchNormELU
from .averagePooling import AveragePooling
from .batchNormalization import BatchNormalization, BatchNormReLU, BatchNormLeakyReLU, MeanOnlyBNLeakyReLU
from .classificationTrainValidate import ClassificationTrainValidate
from .convolution import Convolution
from .deconvolution import Deconvolution
from .denseToSparse import DenseToSparse
from .densedeconvolution import DenseDeconvolution
from .dropout import Dropout, BatchwiseDropout
from .fullConvolution import FullConvolution, TransposeConvolution
from .identity import Identity
from .inputBatch import InputBatch
from .ioLayers import InputLayer, OutputLayer, BLInputLayer, BLOutputLayer, InputLayerInput
from .linear import Linear
from .maxPooling import MaxPooling
from .metadata import Metadata
from .networkArchitectures import *
from .networkInNetwork import NetworkInNetwork
from .permutohedralSubmanifoldConvolution import PermutohedralSubmanifoldConvolution, permutohedral_basis
from .randomizedStrideConvolution import RandomizedStrideConvolution
from .randomizedStrideMaxPooling import RandomizedStrideMaxPooling
from .sequential import Sequential, CheckpointedSequential
from .sparseConvNetTensor import SparseConvNetTensor
from .sparseToDense import SparseToDense
from .sparsify import Sparsify, SparsifyFCS
from .spectral_norm import spectral_norm
from .submanifoldConvolution import SubmanifoldConvolution, ValidConvolution
from .tables import *
from .unPooling import UnPooling
from .utils import append_tensors, AddCoords, add_feature_planes, concatenate_feature_planes, compare_sparse
from .shapeContext import ShapeContext, MultiscaleShapeContext
| 48.357143 | 108 | 0.866076 |
fdee345e80a0871b57fa37a3daf0f39bad8e17d5 | 2,274 | py | Python | app/routers/webhooks.py | NewShadesDAO/api | 1e66336f0ea526f245918ecdc328c9a66280be91 | [
"CC0-1.0"
] | 1 | 2022-03-21T07:37:02.000Z | 2022-03-21T07:37:02.000Z | app/routers/webhooks.py | NewShadesDAO/api | 1e66336f0ea526f245918ecdc328c9a66280be91 | [
"CC0-1.0"
] | 25 | 2022-01-16T13:18:21.000Z | 2022-03-29T13:08:19.000Z | app/routers/webhooks.py | NewShadesDAO/api | 1e66336f0ea526f245918ecdc328c9a66280be91 | [
"CC0-1.0"
] | 1 | 2022-01-15T21:42:00.000Z | 2022-01-15T21:42:00.000Z | import logging
from typing import Optional
from fastapi import APIRouter, Body, Header, HTTPException, Request
from sentry_sdk import capture_exception
from starlette import status
from app.helpers.queue_utils import queue_bg_task
from app.helpers.websockets import pusher_client
from app.models.webhook import Webhook
from app.schemas.messages import WebhookMessageCreateSchema
from app.services.crud import get_item_by_id
from app.services.messages import create_webhook_message
from app.services.webhooks import handle_pusher_event
logger = logging.getLogger(__name__)
router = APIRouter()
@router.post("/pusher", include_in_schema=False)
async def post_pusher_webhooks(
request: Request, x_pusher_key: Optional[str] = Header(None), x_pusher_signature: Optional[str] = Header(None)
):
# need to use raw body
data = await request.body()
try:
webhook = pusher_client.validate_webhook(key=x_pusher_key, signature=x_pusher_signature, body=data)
if not webhook:
raise Exception("No valid webhook extracted.")
except Exception:
logger.exception("Error validating webhook signature.")
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate webhook",
)
[await queue_bg_task(handle_pusher_event, event) for event in webhook["events"]]
return {"received": "ok"}
@router.post("/{webhook_id}/{secret}")
async def post_create_webhook_message_with_secret(
webhook_id: str, secret: str, message: WebhookMessageCreateSchema = Body(...)
):
webhook = await get_item_by_id(id_=webhook_id, result_obj=Webhook)
if not webhook:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Could not found webhook")
if webhook.secret != secret:
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN)
app = await webhook.app.fetch()
message.channel = webhook.channel
message.app = str(app.pk)
message.webhook = webhook_id
try:
# TODO queue this
await create_webhook_message(message_model=message, current_app=app)
except Exception as e:
logger.exception(e)
capture_exception(e)
return {"status": "not ok"}
return {"status": "ok"}
| 32.485714 | 114 | 0.734828 |
f4c21b8a026dcc3a2c50438037f289f8282004d8 | 5,153 | py | Python | manila_tempest_tests/tests/api/admin/test_share_types_extra_specs.py | raissaa/manila-tempest-plugin | 3dd627bdec282071450694bf5399d53e9f9abd5b | [
"Apache-2.0"
] | null | null | null | manila_tempest_tests/tests/api/admin/test_share_types_extra_specs.py | raissaa/manila-tempest-plugin | 3dd627bdec282071450694bf5399d53e9f9abd5b | [
"Apache-2.0"
] | null | null | null | manila_tempest_tests/tests/api/admin/test_share_types_extra_specs.py | raissaa/manila-tempest-plugin | 3dd627bdec282071450694bf5399d53e9f9abd5b | [
"Apache-2.0"
] | 1 | 2021-12-22T13:14:59.000Z | 2021-12-22T13:14:59.000Z | # Copyright 2014 OpenStack Foundation
# All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import copy
import ddt
from tempest import config
from tempest.lib.common.utils import data_utils
from testtools import testcase as tc
from manila_tempest_tests.tests.api import base
CONF = config.CONF
LATEST_MICROVERSION = CONF.share.max_api_microversion
class ExtraSpecsReadAdminTest(base.BaseSharesAdminTest):
@classmethod
def resource_setup(cls):
super(ExtraSpecsReadAdminTest, cls).resource_setup()
cls.share_type_name = data_utils.rand_name("share-type")
cls.required_extra_specs = cls.add_extra_specs_to_dict()
cls.share_type = cls.create_share_type(
cls.share_type_name, extra_specs=cls.required_extra_specs)
cls.st_id = cls.share_type["share_type"]["id"]
cls.custom_extra_specs = {"key1": "value1", "key2": "value2"}
cls.expected_extra_specs = copy.copy(cls.custom_extra_specs)
cls.expected_extra_specs.update(cls.required_extra_specs)
cls.shares_client.create_share_type_extra_specs(
cls.st_id, cls.custom_extra_specs)
@tc.attr(base.TAG_POSITIVE, base.TAG_API)
def test_get_one_share_type_extra_spec(self):
es_get_one = self.shares_client.get_share_type_extra_spec(
self.st_id, "key1")
self.assertEqual({"key1": self.custom_extra_specs["key1"]}, es_get_one)
@tc.attr(base.TAG_POSITIVE, base.TAG_API)
def test_get_all_share_type_extra_specs(self):
es_get_all = self.shares_client.get_share_type_extra_specs(self.st_id)
self.assertEqual(self.expected_extra_specs, es_get_all)
@ddt.ddt
class ExtraSpecsWriteAdminTest(base.BaseSharesAdminTest):
def setUp(self):
super(ExtraSpecsWriteAdminTest, self).setUp()
self.required_extra_specs = self.add_extra_specs_to_dict()
self.custom_extra_specs = {"key1": "value1", "key2": "value2"}
self.share_type_name = data_utils.rand_name("share-type")
# Create share type
self.share_type = self.create_share_type(
self.share_type_name, extra_specs=self.required_extra_specs)
self.st_id = self.share_type['share_type']['id']
# Create extra specs for share type
self.shares_client.create_share_type_extra_specs(
self.st_id, self.custom_extra_specs)
@tc.attr(base.TAG_POSITIVE, base.TAG_API)
def test_update_one_share_type_extra_spec(self):
self.custom_extra_specs["key1"] = "fake_value1_updated"
# Update extra specs of share type
update_one = self.shares_client.update_share_type_extra_spec(
self.st_id, "key1", self.custom_extra_specs["key1"])
self.assertEqual({"key1": self.custom_extra_specs["key1"]}, update_one)
get = self.shares_client.get_share_type_extra_specs(self.st_id)
expected_extra_specs = self.custom_extra_specs
expected_extra_specs.update(self.required_extra_specs)
self.assertEqual(self.custom_extra_specs, get)
@tc.attr(base.TAG_POSITIVE, base.TAG_API)
def test_update_all_share_type_extra_specs(self):
self.custom_extra_specs["key2"] = "value2_updated"
# Update extra specs of share type
update_all = self.shares_client.update_share_type_extra_specs(
self.st_id, self.custom_extra_specs)
self.assertEqual(self.custom_extra_specs, update_all)
get = self.shares_client.get_share_type_extra_specs(self.st_id)
expected_extra_specs = self.custom_extra_specs
expected_extra_specs.update(self.required_extra_specs)
self.assertEqual(self.custom_extra_specs, get)
@tc.attr(base.TAG_POSITIVE, base.TAG_API)
def test_delete_one_share_type_extra_spec(self):
# Delete one extra spec for share type
self.shares_client.delete_share_type_extra_spec(self.st_id, "key1")
# Get metadata
get = self.shares_client.get_share_type_extra_specs(self.st_id)
self.assertNotIn('key1', get)
@tc.attr(base.TAG_POSITIVE, base.TAG_API)
@ddt.data(*set(['2.24', LATEST_MICROVERSION]))
def test_delete_snapshot_support_extra_spec(self, version):
self.skip_if_microversion_not_supported(version)
# Delete one extra spec for share type
self.shares_v2_client.delete_share_type_extra_spec(
self.st_id, 'snapshot_support', version=version)
# Get metadata
share_type_extra_specs = self.shares_client.get_share_type_extra_specs(
self.st_id)
self.assertNotIn('snapshot_support', share_type_extra_specs)
| 38.744361 | 79 | 0.725015 |
d9463f7c3fc4946afa43dd826f48da8f7af15a96 | 995 | py | Python | Alternative_Notebooks/get_assignments.py | gdsa-upc/2017-Team4 | 4a4fb9aaa0703e1269e1e4353a6fcaff576d4e6a | [
"MIT"
] | null | null | null | Alternative_Notebooks/get_assignments.py | gdsa-upc/2017-Team4 | 4a4fb9aaa0703e1269e1e4353a6fcaff576d4e6a | [
"MIT"
] | null | null | null | Alternative_Notebooks/get_assignments.py | gdsa-upc/2017-Team4 | 4a4fb9aaa0703e1269e1e4353a6fcaff576d4e6a | [
"MIT"
] | 2 | 2017-12-16T19:48:38.000Z | 2017-12-22T20:24:14.000Z | from train_codebook import train_codebook
from get_local_features import get_local_features
from scipy.cluster.vq import vq, whiten
import matplotlib.pyplot as plt
import sys
import os.path as path
#dir = sys.path.insert(0,'./home/PycharmProjects/GDSA/Projecte/')
dir = path.dirname(__file__)
#dir = sys.path.insert(0,__file__)
def get_assignments(codebook, descriptors):
#norm_descriptores = whiten(descriptores) # Normaliza descriptores
#Con KMeans
#assignments,_ = vq(descriptores, codebook)
#Con MiniBatchKMeans
assignments= codebook.predict(descriptors)
return assignments
if __name__== "__main__":
descriptor1 = get_local_features("TerrassaBuildings900/train/images/aaeoeolbth.jpg")
codebook = train_codebook(5, descriptor1)
descriptor2 = get_local_features("TerrassaBuildings900/val/images/aalfirydrf.jpg")
assig = get_assignments(codebook, descriptor2)
print(assig)
print "Longitud del assignments= " + str(len(assig))
| 27.638889 | 88 | 0.759799 |
6d62852792a1e6b61d9d4353fe9a83a933add27c | 5,524 | py | Python | homework13.py | WillSkywalker/core-python-programming | 8c8b36beb7dce6b09fc2cec17c844bcf519101c0 | [
"Apache-2.0"
] | 1 | 2015-11-12T15:10:35.000Z | 2015-11-12T15:10:35.000Z | homework13.py | WillSkywalker/core-python-programming | 8c8b36beb7dce6b09fc2cec17c844bcf519101c0 | [
"Apache-2.0"
] | null | null | null | homework13.py | WillSkywalker/core-python-programming | 8c8b36beb7dce6b09fc2cec17c844bcf519101c0 | [
"Apache-2.0"
] | null | null | null | #!usr/bin/env python
# Author: Will Skyywalker
# Core Python Programming - Homework 13
from math import sqrt, atan, pi
from time import ctime
class MoneyFmt(float): # 13-3, 13-17
def __init__(self, amount, bracket=False):
super(MoneyFmt, self).__init__()
self._amount = amount
self._bracket = bracket
def __str__(self):
if self._bracket and repr(self._amount)[0] == '-':
string = '<'+str(round(self._amount, 2))[1:]+'>'
else:
string = str(round(self._amount, 2))
formed = list(string.split('.')[0])
for i in xrange(len(formed)-3, 0, -3):
formed.insert(i, ',')
return '$'+''.join(formed)+'.'+string.split('.')[1]
def __repr__(self):
return str(round(self._amount, 2))
def __add__(self, another):
return MoneyFmt(self._amount + another)
def __sub__(self, another):
return MoneyFmt(self._amount - another)
def __abs__(self):
return MoneyFmt(abs(self._amount))
def __mul__(self, another):
return MoneyFmt(self._amount * another)
def __div__(self, another):
return MoneyFmt(self._amount / another)
def __pow__(self, another):
return MoneyFmt(self._amount ** another)
def __nonzero__(self):
return True if self._amount != 0 else False
def update(self, new):
self._amount = new
class Point(object): # 13-5
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __add__(self, another):
return self.__class__(self.x+another.x,
self.y+another.y)
def __sub__(self, another):
return self.__class__(self.x-another.x,
self.y-another.y)
def __abs__(self):
if self.x >= 0 and self.y >= 0:
return self
return self.__class__(abs(self.x), abs(self.y))
def __pow__(self, another):
return sqrt((self-another).x**2 + \
(self-another).y**2)
def __str__(self):
return str((self.x, self.y))
__repr__ = __str__
class StraightLine(object): # 13-6
def __init__(self, point_1, point_2):
self._point_1 = point_1
self._point_2 = point_2
def __str__(self):
return str(((self._point_1), (self._point_2)))
def length(self):
return self._point_1 ** self._point_2
def slope(self):
return atan(abs(self._point_1-self._point_2).x/\
abs(self._point_1-self._point_2).y)/pi*180
class Date(object): # 13-7
def __init__(self, now=ctime()):
self._now = now
def update(self, now=ctime()):
self._now = now
def display(self, mode='MDY'):
times = self._now.split()
# print times
for c in mode:
if c == 'M':
print times[1],
elif c == 'D':
print times[2],
elif c == 'Y':
print times[4],
elif c == 'O':
print times[0],
class PanStack(list): # 13-10
"""docstring for Stack"""
def __init__(self, arg):
super(PanStack, self).__init__(arg)
# self.arg = arg
def pop(self):
return super(PanStack, self).pop(-1)
def push(self, value):
super(PanStack, self).append(value)
def shift(self):
return super(PanStack, self).pop(0)
def unshift(self, value):
super(PanStack, self).insert(0, value)
def peek(self):
return self[0]
def isempty(self):
return bool(self)
class CapOpen(object): # 13-16
def __init__(self, fn, mode='r', buf=-1):
self.file = open(fn, mode, buf)
def __str__(self):
return str(self.file)
def __repr__(self):
return repr(self)
def write(self, line):
self.file.write(line.upper())
def writelines(self, sequence, sep=''):
for line in sequence:
self.file.write(line.upper()+sep)
def __getattr__(self, attr):
return getattr(self.file, attr)
class SimDict(dict): # 13-19
def __init__(self, arg):
super(SimDict, self).__init__(arg)
def keys(self):
return sorted(super(SimDict, self).keys())
class Time60(object):
def __init__(self, *args, **kwargs):
self.hr = 0
self.mint = 0
if kwargs:
self.hr = kwargs['hr']
self.mint = kwargs['min']
if len(args) == 1:
if isinstance(args[0],str):
temp_list = args[0].split(':')
self.hr = int(temp_list[0])
self.mint = int(temp_list[1])
else:
self.hr = args[0][0]
self.mint = args[0][1]
elif len(args) >= 2:
self.hr = args[0]
self.mint = args[1]
def __str__(self):
return '%02d:%02d' % (self.hr, self.mint)
def __repr__():
return str([self.hr, self.mint])
def __add__(self, other):
output = divmod(self.mint+other.mint, 60)
return self.__class__(self.hr + other.hr + output[0],
output[1])
def __iadd__(self, other):
output = divmod(self.mint+other.mint, 60)
self.hr += other.hr + output[0]
self.mint = output[1]
return self
if __name__ == '__main__':
a = Time60('17:55')
b = Time60('5:37')
# a.writelines('euidwh ufyo you fucking sob', '\n')
# print a * 3
print a + b
| 24.995475 | 61 | 0.542361 |
e43608fd33081461199e20cc093779ca67fd8543 | 132 | py | Python | pythonExercicios/ex014.py | Yhago-Carvalho/CursoPython | 343ccabb1a61e16c6078de9672c78c56deed2589 | [
"MIT"
] | null | null | null | pythonExercicios/ex014.py | Yhago-Carvalho/CursoPython | 343ccabb1a61e16c6078de9672c78c56deed2589 | [
"MIT"
] | null | null | null | pythonExercicios/ex014.py | Yhago-Carvalho/CursoPython | 343ccabb1a61e16c6078de9672c78c56deed2589 | [
"MIT"
] | null | null | null | c = float(input('Digite a temperatura em Ceusius: '))
f = (9*c + 160)/5
print(f'A temperatura de {c:.1f}ºC corresponde a {f:.1f}ºF') | 44 | 60 | 0.659091 |
fc74cb91cc134ffb0195b4d2b8941e11a49396d0 | 13,259 | py | Python | cloud_utils/gke.py | alecgunny/cloud-utils | 41df732633ed9e5180bdca50c4ad5ed8cf72a093 | [
"MIT"
] | null | null | null | cloud_utils/gke.py | alecgunny/cloud-utils | 41df732633ed9e5180bdca50c4ad5ed8cf72a093 | [
"MIT"
] | null | null | null | cloud_utils/gke.py | alecgunny/cloud-utils | 41df732633ed9e5180bdca50c4ad5ed8cf72a093 | [
"MIT"
] | null | null | null | import logging
import math
import re
import time
import typing
from contextlib import contextmanager
import attr
import google
from google.auth.transport.requests import Request as AuthRequest
from google.cloud import container_v1 as container
from google.oauth2 import service_account
from cloud_utils.k8s import K8sApiClient
from cloud_utils.utils import wait_for
_credentials_type = typing.Optional[
typing.Union[str, service_account.Credentials]
]
def snakeify(name: str) -> str:
return re.sub("(?<!^)(?=[A-Z])", "_", name).lower()
def make_credentials(
service_account_key_file: str,
scopes: typing.Optional[typing.List[str]] = None,
):
"""
Cheap wrapper around service account creation
class method to simplify a couple gotchas. Might
either be overkill or may be better built as a
class with more functionality, not sure yet.
"""
scopes = scopes or ["https://www.googleapis.com/auth/cloud-platform"]
credentials = service_account.Credentials.from_service_account_file(
service_account_key_file,
scopes=scopes,
)
credentials.refresh(AuthRequest())
return credentials
class ThrottledClient:
def __init__(
self, credentials: _credentials_type = None, throttle_secs: float = 1.0
):
if isinstance(credentials, str):
credentials = make_credentials(credentials)
self.credentials = credentials
self._client = container.ClusterManagerClient(
credentials=self.credentials
)
self.throttle_secs = throttle_secs
self._last_request_time = time.time()
@property
def client(self):
return self
@property
def name(self):
return ""
def make_request(self, request, **kwargs):
request_type = type(request).__name__.replace("Request", "")
request_fn_name = snakeify(request_type)
request_fn = getattr(self._client, request_fn_name)
while (time.time() - self._last_request_time) < self.throttle_secs:
time.sleep(0.01)
return request_fn(request=request, **kwargs)
@attr.s(auto_attribs=True)
class Resource:
_name: str
parent: "Resource"
@property
def client(self):
return self.parent.client
@property
def resource_type(self):
return type(self).__name__
@property
def name(self):
resource_type = self.resource_type
camel = resource_type[0].lower() + resource_type[1:]
return self.parent.name + "/{}/{}".format(camel, self._name)
@classmethod
def create(cls, resource, parent, **kwargs):
resource_type = type(resource).__name__
if resource_type == "Cluster":
cls = Cluster
elif resource_type == "NodePool":
cls = NodePool
else:
raise TypeError(f"Unknown GKE resource type {resource_type}")
obj = cls(resource.name, parent, **kwargs)
create_request_cls = getattr(
container, f"Create{obj.resource_type}Request"
)
resource_type = snakeify(obj.resource_type)
kwargs = {resource_type: resource, "parent": parent.name}
create_request = create_request_cls(**kwargs)
try:
obj.client.make_request(create_request)
except google.api_core.exceptions.AlreadyExists:
pass
return obj
def delete(self):
delete_request_cls = getattr(
container, f"Delete{self.resource_type}Request"
)
delete_request = delete_request_cls(name=self.name)
return self.client.make_request(delete_request)
def get(self, timeout=None):
get_request_cls = getattr(container, f"Get{self.resource_type}Request")
get_request = get_request_cls(name=self.name)
try:
return self.client.make_request(get_request, timeout=timeout)
except google.api_core.exceptions.NotFound:
raise ValueError(f"Couldn't get resource {self.name}")
def _raise_bad_status(self, response):
raise RuntimeError(
f"Resource {self.name} reached status {response.status} "
f"while deleting with conditions {response.conditions}"
)
def is_ready(self) -> bool:
response = self.get(timeout=5)
if response.status == 2:
return True
elif response.status > 2:
self._raise_bad_status(response)
return False
def submit_delete(self) -> bool:
"""
Attempt to submit a delete request for a resource.
Returns `True` if the request is successfully
submitted or if the resource can't be found,
and `False` if the request can't be submitted
"""
try:
self.delete()
return True
except google.api_core.exceptions.NotFound:
# resource is gone, so we're good
return True
except google.api_core.exceptions.BadRequest:
# Resource is tied up, so indicate that
# the user will need to try again later
return False
def is_deleted(self) -> bool:
"""
check if a submitted delete request has completed
"""
try:
response = self.get(timeout=5)
except ValueError as e:
if str(e) != f"Couldn't get resource {self.name}":
raise
# couldn't find the resource, so assume
# the deletion went off swimmingly
return True
if response.status > 5:
self._raise_bad_status(response)
return False
@attr.s(auto_attribs=True)
class NodePool(Resource):
timeout: typing.Optional[float] = None
def __attrs_post_init__(self):
self._init_time = time.time()
def is_ready(self):
response = self.get(timeout=5)
if response.status == 2:
return True
elif response.status == 6:
code = response.conditions[0].code
stockout = code == container.StatusCondition.Code.GCE_STOCKOUT
if not stockout:
self._raise_bad_status(response)
if (
self.timeout is None
or (time.time() > self._init_time) < self.timeout
):
raise RuntimeError(
f"Resource {self.name} encountered GCE stockout "
"on creation and timed out"
)
elif response.status > 2:
self._raise_bad_status(response)
return False
@attr.s
class ManagerResource(Resource):
def __attrs_post_init__(self):
self._resources = {}
mrts = self.managed_resource_type.__name__ + "s"
snaked = snakeify(mrts)
list_request_cls = getattr(container, f"List{mrts}Request")
list_resource_request = list_request_cls(parent=self.name)
list_resource_fn = getattr(self.client._client, f"list_{snaked}")
try:
response = list_resource_fn(list_resource_request)
except google.api_core.exceptions.NotFound:
return
resources = getattr(response, snaked)
for resource in resources:
self._resources[resource.name] = self.managed_resource_type(
resource.name, self
)
@property
def managed_resource_type(self):
raise NotImplementedError
@property
def resources(self):
# TODO: in light of the `managed_resource_type` property,
# can sub-resources rightfully belong to resources higher
# up the tree? I don't think we need this recursion
resources = self._resources.copy()
for resource_name, resource in self._resources.items():
try:
subresources = resource.resources
except AttributeError:
continue
for subname, subresource in subresources.items():
resources[subname] = subresource
return resources
def _make_resource_message(self, resource):
resource_type = snakeify(resource.resource_type).replace("_", " ")
return resource_type + " " + resource.name
def create_resource(self, resource):
if type(resource).__name__ != self.managed_resource_type.__name__:
raise TypeError(
"{} cannot manage resource {}".format(
type(self).__name__, type(resource).__name__
)
)
resource = Resource.create(resource, self)
resource_msg = self._make_resource_message(resource)
wait_for(
resource.is_ready,
f"Waiting for {resource_msg} to become ready",
f"{resource_msg} ready",
)
self._resources[resource.name] = resource
return resource
def delete_resource(self, resource):
resource_msg = self._make_resource_message(resource)
wait_for(
resource.submit_delete,
f"Waiting for {resource_msg} to become available to delete",
f"{resource_msg} delete request submitted",
)
wait_for(
resource.is_deleted,
f"Waiting for {resource_msg} to delete",
f"{resource_msg} deleted",
)
self._resources.pop(resource.name)
@contextmanager
def manage_resource(self, resource, keep=False, **kwargs):
resource = self.create_resource(resource, **kwargs)
resource_msg = self._make_resource_message(resource)
try:
yield resource
except Exception as e:
if not keep:
logging.error(
"Encountered error, removing {}: {}".format(
resource_msg, str(e)
)
)
raise
finally:
if not keep:
self.delete_resource(resource)
@attr.s
class Cluster(ManagerResource):
def __attrs_post_init__(self):
self._k8s_client = None
super().__attrs_post_init__()
@property
def managed_resource_type(self):
return NodePool
@property
def k8s_client(self):
# try to create the client this way because otherwise we
# would need to wait until the cluster is ready at
# initialization time in order to get the endpoint. If you're
# not going to call `wait_for(cluster.is_ready)`, make sure to
# wrap this in a catch for a RuntimeError
# TODO: is it worth starting to introduce custom errors here
# to make catching more intelligible?
if self._k8s_client is None:
self._k8s_client = K8sApiClient(self)
return self._k8s_client
def deploy(
self,
file: str,
repo: typing.Optional[str] = None,
branch: typing.Optional[str] = None,
namespace: str = "default",
ignore_if_exists: bool = True,
**kwargs,
):
return self.k8s_client.create_from_yaml(
file, repo, branch, namespace, ignore_if_exists, **kwargs
)
def remove_deployment(self, name: str, namespace: str = "default"):
return self.k8s_client.remove_deployment(name, namespace)
def deploy_gpu_drivers(self) -> None:
self.deploy(
"nvidia-driver-installer/cos/daemonset-preloaded.yaml",
repo="GoogleCloudPlatform/container-engine-accelerators",
branch="master",
ignore_if_exists=True,
)
self.k8s_client.wait_for_daemon_set(name="nvidia-driver-installer")
class GKEClusterManager(ManagerResource):
def __init__(
self, project: str, zone: str, credentials: _credentials_type = None
) -> None:
parent = ThrottledClient(credentials)
name = f"projects/{project}/locations/{zone}"
super().__init__(name, parent)
@property
def managed_resource_type(self):
return Cluster
@property
def name(self):
return self._name
def create_gpu_node_pool_config(
vcpus: int, gpus: int, gpu_type: str, **kwargs
) -> container.NodeConfig:
if (math.log2(vcpus) % 1 != 0 and vcpus != 96) or vcpus > 96:
raise ValueError(f"Can't configure node pool with {vcpus} vcpus")
if gpus < 1 or gpus > 8:
raise ValueError(f"Can't configure node pool with {gpus} gpus")
if gpu_type not in ["t4", "v100", "p100", "p4", "k80"]:
raise ValueError(
"Can't configure n1 standard node pool "
f"with unknown gpu type {gpu_type}"
)
return container.NodeConfig(
machine_type=f"n1-standard-{vcpus}",
oauth_scopes=[
"https://www.googleapis.com/auth/devstorage.read_only",
"https://www.googleapis.com/auth/logging.write",
"https://www.googleapis.com/auth/monitoring",
"https://www.googleapis.com/auth/service.management.readonly",
"https://www.googleapis.com/auth/servicecontrol",
"https://www.googleapis.com/auth/trace.append",
],
accelerators=[
container.AcceleratorConfig(
accelerator_count=gpus,
accelerator_type=f"nvidia-tesla-{gpu_type}",
)
],
**kwargs,
)
| 32.104116 | 79 | 0.617317 |
299523a629d06b024a413e1072eb4a740b9da72b | 686 | py | Python | mgnemu/models/check_comment.py | 0xporky/mgnemu | 7bbb27d945b416d08b31c92608a431e4652b2be4 | [
"MIT"
] | 1 | 2017-07-12T19:43:13.000Z | 2017-07-12T19:43:13.000Z | mgnemu/models/check_comment.py | 0xporky/mgnemu-python | 7bbb27d945b416d08b31c92608a431e4652b2be4 | [
"MIT"
] | null | null | null | mgnemu/models/check_comment.py | 0xporky/mgnemu-python | 7bbb27d945b416d08b31c92608a431e4652b2be4 | [
"MIT"
] | null | null | null | # -*- coding: utf-8 -*-
"""
Model of check comment, needed for zero checks.
"""
from mgnemu.models.base_model import BaseModel
from mgnemu.models.sales_types import COMMENT_TYPE
from mgnemu.models.sales_types import COMMENT
class CheckComment(BaseModel):
def __init__(self, data):
BaseModel.__init__(self, COMMENT_TYPE)
if COMMENT in list(data.keys()):
self.__cm = data[COMMENT]
else:
self.__cm = ''
@property
def cm(self):
return self.__cm
def dumps(self):
return {
'id': BaseModel.check_id(),
self.model_type: {
COMMENT: self.__cm,
}
}
| 20.787879 | 50 | 0.587464 |
769eb226ac894bb66bbc593b436f61620ab66da1 | 1,785 | py | Python | Project Assignment-2/app/models.py | vedant-jad99/Cloud-Computing-Projects-and-Assignments-CS356 | c5040e6a3b99b7da56651c0b9d6c54f134aca33e | [
"Apache-2.0"
] | null | null | null | Project Assignment-2/app/models.py | vedant-jad99/Cloud-Computing-Projects-and-Assignments-CS356 | c5040e6a3b99b7da56651c0b9d6c54f134aca33e | [
"Apache-2.0"
] | null | null | null | Project Assignment-2/app/models.py | vedant-jad99/Cloud-Computing-Projects-and-Assignments-CS356 | c5040e6a3b99b7da56651c0b9d6c54f134aca33e | [
"Apache-2.0"
] | null | null | null | from app import db, login_manager
from flask_login import UserMixin
from datetime import datetime
@login_manager.user_loader
def load_user(userid):
return User.query.get(int(userid))
class User(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
first_name = db.Column(db.String(40), unique=False, nullable=True)
last_name = db.Column(db.String(40), unique=False, nullable=True)
username = db.Column(db.String(20), unique=True, nullable=False)
email = db.Column(db.String(100), unique=True, nullable=False)
password = db.Column(db.String(80), unique=False, nullable=False)
account_created = db.Column(db.DateTime, nullable=False, default=datetime.now())
info = db.relationship('UserInfo', backref='info', lazy=True)
def __repr__(self):
return "User details - Name: {}, Username: {}, Email: {}".format(self.first_name + " " + self.last_name, self.username, self.email)
class UserInfo(db.Model, UserMixin):
id = db.Column(db.Integer, primary_key=True)
about = db.Column(db.String(750), unique=False, nullable=True)
link1 = db.Column(db.String(500), unique=False, nullable=True)
link2 = db.Column(db.String(500), unique=False, nullable=True)
link3 = db.Column(db.String(500), unique=False, nullable=True)
link4 = db.Column(db.String(500), unique=False, nullable=True)
profession = db.Column(db.String(100), unique=False, nullable=True)
profile = db.Column(db.String(100), unique=False, nullable=True, default='profile.png')
recovery_mail = db.Column(db.String(100), unique=False, nullable=True)
user_id = db.Column(db.Integer, db.ForeignKey('user.id'), unique=True, nullable=False)
def __repr__(self):
return "Profession - {} Id- {}".format(self.profession, self.id) | 48.243243 | 139 | 0.709244 |
2ecc55ca99985aa96f6ec15e1c8de910fe574848 | 3,044 | py | Python | lib/cmds/w_succ.py | poharrison/westpa | 8618ab598f9bb38a7bc1479932f5332b137dfcbc | [
"MIT"
] | 140 | 2015-01-07T23:30:36.000Z | 2022-03-28T17:15:30.000Z | lib/cmds/w_succ.py | burntyellow/westpa | 9dc62478fcef0001b9c038cd56a40b6be1b9d64a | [
"MIT"
] | 157 | 2015-01-03T03:38:36.000Z | 2022-03-31T14:12:16.000Z | lib/cmds/w_succ.py | burntyellow/westpa | 9dc62478fcef0001b9c038cd56a40b6be1b9d64a | [
"MIT"
] | 56 | 2015-01-02T21:21:40.000Z | 2022-03-03T16:27:54.000Z |
import sys, argparse
import numpy
import west, westpa
from oldtools.aframe import WESTAnalysisTool, WESTDataReaderMixin, CommonOutputMixin, BinningMixin, IterRangeMixin
import logging
log = logging.getLogger('w_succ')
class WSucc(CommonOutputMixin,WESTDataReaderMixin,WESTAnalysisTool):
def __init__(self):
super(WSucc,self).__init__()
self.include_args['CommonOutputMixin']['print_bin_labels'] = False
self.output_file = sys.stdout
def find_successful_trajs(self):
pcoord_formats = {'u8': '%20d',
'i8': '%20d',
'u4': '%10d',
'i4': '%11d',
'u2': '%5d',
'i2': '%6d',
'f4': '%14.7g',
'f8': '%23.15g'}
if not self.output_suppress_headers:
self.output_file.write('''\
# successful (recycled) segments
# column 0: iteration
# column 1: seg_id
# column 2: weight
# column>2: final progress coordinate value
''')
for n_iter in range(1, self.data_manager.current_iteration):
seg_index = self.get_seg_index(n_iter)
all_seg_ids = numpy.arange(len(seg_index), dtype=numpy.int_)
recycled_seg_ids = all_seg_ids[seg_index[:]['endpoint_type'] == west.Segment.SEG_ENDPOINT_RECYCLED]
if len(recycled_seg_ids) == 0:
# Attemping to retrieve a 0-length selection from HDF5 (the pcoords below) fails
continue
pcoord_ds = self.get_pcoord_dataset(n_iter)
pcoord_len = pcoord_ds.shape[1]
pcoord_ndim = pcoord_ds.shape[2]
final_pcoords = self.get_pcoord_dataset(n_iter)[recycled_seg_ids,pcoord_len-1,:]
# The above HDF5 selection always returns a vector; we want a 2-d array
final_pcoords.shape = (len(recycled_seg_ids),pcoord_ndim)
for (ipc, seg_id) in enumerate(recycled_seg_ids):
self.output_file.write('%8d %8d %20.14g' % (n_iter, seg_id, seg_index[seg_id]['weight']))
fields = ['']
for field in final_pcoords[ipc]:
fields.append(pcoord_formats.get(field.dtype.str[1:], '%s') % field)
self.output_file.write(' '.join(fields))
self.output_file.write('\n')
wsucc = WSucc()
parser = argparse.ArgumentParser('w_succ', description='''\
List segments which successfully reach a target state''')
westpa.rc.add_args(parser)
wsucc.add_args(parser)
parser.add_argument('-o', '--output', dest='output_file',
help='Store output in OUTPUT_FILE (default: write to standard output).',
type=argparse.FileType('wt'), default=sys.stdout)
args = parser.parse_args()
westpa.rc.process_args(args, config_required=False)
wsucc.process_args(args)
wsucc.output_file = args.output_file
wsucc.find_successful_trajs()
| 40.052632 | 114 | 0.595926 |
351904c8b8a2f0310da01347179effdbea1ad233 | 30,113 | py | Python | tests/common/fixtures/advanced_reboot.py | xwjiang2021/sonic-mgmt | 82c446b9fb016eb070af765aa9d9999e55b27342 | [
"Apache-2.0"
] | 2 | 2021-11-24T09:33:41.000Z | 2021-12-03T09:08:29.000Z | tests/common/fixtures/advanced_reboot.py | xwjiang2021/sonic-mgmt | 82c446b9fb016eb070af765aa9d9999e55b27342 | [
"Apache-2.0"
] | null | null | null | tests/common/fixtures/advanced_reboot.py | xwjiang2021/sonic-mgmt | 82c446b9fb016eb070af765aa9d9999e55b27342 | [
"Apache-2.0"
] | null | null | null | import copy
import ipaddress
import itertools
import json
import logging
import pytest
import time
import os
from tests.common.mellanox_data import is_mellanox_device as isMellanoxDevice
from tests.common.platform.ssh_utils import prepare_testbed_ssh_keys as prepareTestbedSshKeys
from tests.common.reboot import reboot as rebootDut
from tests.common.helpers.sad_path import SadOperation
from tests.ptf_runner import ptf_runner
from tests.common.helpers.assertions import pytest_assert
from tests.common.utilities import InterruptableThread
logger = logging.getLogger(__name__)
# Globals
HOST_MAX_COUNT = 126
TIME_BETWEEN_SUCCESSIVE_TEST_OPER = 420
PTFRUNNER_QLEN = 1000
REBOOT_CASE_TIMEOUT = 1800
class AdvancedReboot:
'''
AdvancedReboot is used to perform reboot dut while running preboot/inboot operations
This class collects information about the current testbed. This information is used by test cases to build
inboot/preboot list. The class transfers number of configuration files to the dut/ptf in preparation for reboot test.
Test cases can trigger test start utilizing runRebootTestcase API.
'''
def __init__(self, request, duthost, ptfhost, localhost, tbinfo, creds, **kwargs):
'''
Class constructor.
@param request: pytest request object
@param duthost: AnsibleHost instance of DUT
@param ptfhost: PTFHost for interacting with PTF through ansible
@param localhost: Localhost for interacting with localhost through ansible
@param tbinfo: fixture provides information about testbed
@param kwargs: extra parameters including reboot type
'''
assert 'rebootType' in kwargs and kwargs['rebootType'] in ['fast-reboot', 'warm-reboot', 'warm-reboot -f'], (
"Please set rebootType var."
)
if duthost.facts['platform'] == 'x86_64-kvm_x86_64-r0':
# Fast and Warm-reboot procedure now test if "docker exec" works.
# The timeout for check_docker_exec test is 1s. This timeout is good
# enough for test in physical devices. However, the KVM devices are
# inherently slow, and the 1s timeout for check_docker_exec test has
# intermittently failed in Azure Pipeline PR tests.
# Therefore, the 1s timeout is increased to 5s for KVM testing.
# 5s timeout is believed to be generous enough for the KVM device,
# however more test results are needed to prove this.
cmd_format = "sed -i 's/{}/{}/' {}"
warmboot_script_path = duthost.shell('which warm-reboot')['stdout']
original_line = 'timeout 1s docker exec $container echo "success"'
replaced_line = 'timeout 5s docker exec $container echo "success"'
replace_cmd = cmd_format.format(original_line, replaced_line, warmboot_script_path)
logger.info("Increase docker exec timeout from 1s to 5s in {}".format(warmboot_script_path))
duthost.shell(replace_cmd)
self.kvmTest = True
device_marks = [arg for mark in request.node.iter_markers(name='device_type') for arg in mark.args]
if 'vs' not in device_marks:
pytest.skip('Testcase not supported for kvm')
else:
self.kvmTest = False
self.request = request
self.duthost = duthost
self.ptfhost = ptfhost
self.localhost = localhost
self.tbinfo = tbinfo
self.creds = creds
self.moduleIgnoreErrors = kwargs["allow_fail"] if "allow_fail" in kwargs else False
self.allowMacJump = kwargs["allow_mac_jumping"] if "allow_mac_jumping" in kwargs else False
self.advanceboot_loganalyzer = kwargs["advanceboot_loganalyzer"] if "advanceboot_loganalyzer" in kwargs else None
self.__dict__.update(kwargs)
self.__extractTestParam()
self.rebootData = {}
self.hostMaxLen = 0
self.lagMemberCnt = 0
self.vlanMaxCnt = 0
self.hostMaxCnt = HOST_MAX_COUNT
self.__buildTestbedData(tbinfo)
def __extractTestParam(self):
'''
Extract test parameters from pytest request object. Note that all the parameters have default values.
'''
self.vnet = self.request.config.getoption("--vnet")
self.vnetPkts = self.request.config.getoption("--vnet_pkts")
self.rebootLimit = self.request.config.getoption("--reboot_limit")
self.sniffTimeIncr = self.request.config.getoption("--sniff_time_incr")
self.allowVlanFlooding = self.request.config.getoption("--allow_vlan_flooding")
self.stayInTargetImage = self.request.config.getoption("--stay_in_target_image")
self.newSonicImage = self.request.config.getoption("--new_sonic_image")
self.cleanupOldSonicImages = self.request.config.getoption("--cleanup_old_sonic_images")
self.readyTimeout = self.request.config.getoption("--ready_timeout")
self.replaceFastRebootScript = self.request.config.getoption("--replace_fast_reboot_script")
self.postRebootCheckScript = self.request.config.getoption("--post_reboot_check_script")
self.bgpV4V6TimeDiff = self.request.config.getoption("--bgp_v4_v6_time_diff")
# Set default reboot limit if it is not given
if self.rebootLimit is None:
if self.kvmTest:
self.rebootLimit = 200 # Default reboot limit for kvm
elif 'warm-reboot' in self.rebootType:
self.rebootLimit = 0
else:
self.rebootLimit = 30 # Default reboot limit for physical devices
def getHostMaxLen(self):
'''
Accessor method for hostMaxLen
'''
# Number of VMS - 1
return self.hostMaxLen
def getlagMemberCnt(self):
'''
Accessor method for lagMemberCnt
'''
return self.lagMemberCnt
def getVlanMaxCnt(self):
'''
Accessor method for vlanMaxCnt
'''
return self.vlanMaxCnt
def getHostMaxCnt(self):
'''
Accessor method for hostMaxCnt
'''
return self.hostMaxCnt
def getTestbedType(self):
'''
Accessor method for testbed's topology name
'''
return self.tbinfo['topo']['name']
def __buildTestbedData(self, tbinfo):
'''
Build testbed data that are needed by ptf advanced-reboot.ReloadTest class
'''
self.mgFacts = self.duthost.get_extended_minigraph_facts(tbinfo)
self.rebootData['arista_vms'] = [
attr['mgmt_addr'] for dev, attr in self.mgFacts['minigraph_devices'].items() if attr['hwsku'] == 'Arista-VM'
]
self.hostMaxLen = len(self.rebootData['arista_vms']) - 1
self.lagMemberCnt = len(self.mgFacts['minigraph_portchannels'].values()[0]['members'])
self.vlanMaxCnt = len(self.mgFacts['minigraph_vlans'].values()[0]['members']) - 1
self.rebootData['dut_hostname'] = self.mgFacts['minigraph_mgmt_interface']['addr']
self.rebootData['dut_mac'] = self.duthost.facts['router_mac']
vlan_ip_range = dict()
for vlan in self.mgFacts['minigraph_vlan_interfaces']:
if type(ipaddress.ip_network(vlan['subnet'])) is ipaddress.IPv4Network:
vlan_ip_range[vlan['attachto']] = vlan['subnet']
self.rebootData['vlan_ip_range'] = json.dumps(vlan_ip_range)
self.rebootData['dut_username'] = self.creds['sonicadmin_user']
self.rebootData['dut_password'] = self.creds['sonicadmin_password']
# Change network of the dest IP addresses (used by VM servers) to be different from Vlan network
prefixLen = self.mgFacts['minigraph_vlan_interfaces'][0]['prefixlen'] - 3
testNetwork = ipaddress.ip_address(self.mgFacts['minigraph_vlan_interfaces'][0]['addr']) + (1 << (32 - prefixLen))
self.rebootData['default_ip_range'] = str(
ipaddress.ip_interface(unicode(str(testNetwork) + '/{0}'.format(prefixLen))).network
)
for intf in self.mgFacts['minigraph_lo_interfaces']:
if ipaddress.ip_interface(intf['addr']).ip.version == 6:
self.rebootData['lo_v6_prefix'] = str(ipaddress.ip_interface(intf['addr'] + '/64').network)
break
def __updateNextHopIps(self):
'''
Update next hop IPs
'''
if self.inbootList is not None:
self.rebootData['nexthop_ips'] = [
self.tbinfo['topo']['properties']['configuration_properties']['common']['nhipv4'],
self.tbinfo['topo']['properties']['configuration_properties']['common']['nhipv6'],
]
else:
self.rebootData['nexthop_ips'] = None
def __validateAndBuildSadList(self):
'''
Validate sad list (preboot/inboot lists) member data
'''
prebootList = [] if self.prebootList is None else self.prebootList
inbootList = [] if self.inbootList is None else self.inbootList
sadList = [item for item in itertools.chain(prebootList, inbootList)]
for item in sadList:
# TODO: Move all sad path logic out of ptf script to pytest.
# Once done, we can make a sad_operation fixture.
if isinstance(item, SadOperation):
continue
if ':' not in item:
continue
itemCnt = int(item.split(':')[-1])
if 'bgp_down' in item:
assert itemCnt <= self.hostMaxLen, (
'Bgp neigh down count is greater than or equal to number of VM hosts '
'Current val = {0} Max val = {1}'
).format(itemCnt, self.hostMaxLen)
if 'lag_down' in item:
assert itemCnt <= self.hostMaxLen, (
'Lag count is greater than or equal to number of VM hosts. '
'Current val = {0} Max val = {1}'
).format(itemCnt, self.hostMaxLen)
if 'routing' in item:
assert itemCnt <= self.hostMaxCnt, (
'Number of prefixes is greater than allowed max. '
'Current val = {0} Max val = {1}'
).format(itemCnt, self.hostMaxCnt)
# Adding None item if the sadList is empty in order to run the test case once when sad list is empty
self.rebootData['sadList'] = sadList if len(sadList) > 0 else [None]
def __transferTestDataFiles(self, data, ansibleHost):
'''
Convert data into json format and transfers json file to ansible host (ptfhost/duthost)
@param data: map that includedata source and json file name
@param ansibleHost: Ansible host that is receiving this data
'''
for item in data:
data_source = item['source']
filename = '/tmp/' + item['name'] + '.json'
with open(filename, 'w') as file:
file.write(json.dumps(data_source))
logger.info('Transferring {0} to {1}'.format(filename, ansibleHost.hostname))
ansibleHost.copy(src=filename, dest='/tmp/')
self.rebootData[item['name'] + '_file'] = filename
def __runScript(self, scripts, ansibleHost):
'''
Run script on an Ansibl host
@param scripts: list of script names to be run on Ansible host
@param ansibleHost: Ansible host to run the scripts on
'''
# this could be done using script API from ansible modules
for script in scripts:
logger.info('Running script {0} on {1}'.format(script, ansibleHost.hostname))
ansibleHost.script('scripts/' + script)
def __prepareTestbedSshKeys(self):
'''
Prepares testbed ssh keys by generating ssh key on ptf host and adding this key to known_hosts on duthost
'''
prepareTestbedSshKeys(self.duthost, self.ptfhost, self.rebootData['dut_username'])
def __handleMellanoxDut(self):
'''
Handle Mellanox DUT reboot when upgrading from SONiC-OS-201803 to SONiC-OS-201811
'''
if self.newSonicImage is not None and \
self.rebootType == 'fast-reboot' and \
isMellanoxDevice(self.duthost):
logger.info('Handle Mellanox platform')
nextImage = self.duthost.shell('sonic_installer list | grep Next | cut -f2 -d " "')['stdout']
if 'SONiC-OS-201803' in self.currentImage and 'SONiC-OS-201811' in nextImage:
self.__runScript(['upgrade_mlnx_fw.sh'], self.duthost)
def __updateAndRestartArpResponder(self, item=None):
'''
Update ARP responder configuration data based on the inboot/preboot operation (item)
@param item: inboot/preboot operation
'''
arp_responder_args = '-e'
if item is not None:
arp_responder_args += ' -c /tmp/from_t1_{0}.json'.format(item)
self.ptfhost.host.options['variable_manager'].extra_vars.update({'arp_responder_args': arp_responder_args})
logger.info('Copying arp responder config file to {0}'.format(self.ptfhost.hostname))
self.ptfhost.template(src='arp_responder.conf.j2', dest='/etc/supervisor/conf.d/arp_responder.conf')
logger.info('Refreshing supervisor control and starting arp_responder')
self.ptfhost.shell('supervisorctl reread && supervisorctl update')
def __handleRebootImage(self):
'''
Download and install new image to DUT
'''
if self.newSonicImage is None:
self.newImage = False
return
self.currentImage = self.duthost.shell('sonic_installer list | grep Current | cut -f2 -d " "')['stdout']
tempfile = self.duthost.shell('mktemp')['stdout']
logger.info('Download SONiC image')
self.duthost.shell('curl {0} --output {1}'.format(self.newSonicImage, tempfile))
self.binaryVersion = self.duthost.shell('sonic_installer binary_version {}'.format(tempfile))['stdout']
logger.info('Cleanup sonic images that is not current and/or next')
if self.cleanupOldSonicImages:
self.duthost.shell('sonic_installer cleanup -y')
if self.binaryVersion == self.currentImage:
logger.info("Skipping image installation: new SONiC image is installed and set to current")
self.newImage = False
return
self.newImage = True
logger.info('Installing new SONiC image')
self.duthost.shell('sonic_installer install -y {0}'.format(tempfile))
logger.info('Remove config_db.json so the new image will reload minigraph')
self.duthost.shell('rm -f /host/old_config/config_db.json')
logger.info('Remove downloaded tempfile')
self.duthost.shell('rm -f {}'.format(tempfile))
def __setupTestbed(self):
'''
Sets testbed up. It tranfers test data files, ARP responder, and runs script to update IPs and MAC addresses.
'''
self.__runScript(['remove_ip.sh'], self.ptfhost)
self.__prepareTestbedSshKeys()
logger.info('Copy ARP responder to the PTF container {}'.format(self.ptfhost.hostname))
self.ptfhost.copy(src='scripts/arp_responder.py', dest='/opt')
self.ptfhost.copy(src='scripts/dual_tor_sniffer.py', dest="/root/ptftests/advanced_reboot_sniffer.py")
# Replace fast-reboot script
if self.replaceFastRebootScript:
logger.info('Replace fast-reboot script on DUT {}'.format(self.duthost.hostname))
self.duthost.copy(src='scripts/fast-reboot', dest='/usr/bin/')
def __clearArpAndFdbTables(self):
'''
Clears ARP and FDB entries
'''
logger.info('Clearing arp entries on DUT {}'.format(self.duthost.hostname))
self.duthost.shell('sonic-clear arp')
logger.info('Clearing all fdb entries on DUT {}'.format(self.duthost.hostname))
self.duthost.shell('sonic-clear fdb all')
def __fetchTestLogs(self, rebootOper=None):
'''
Fetch test logs from duthost and ptfhost after individual test run
'''
if rebootOper:
dir_name = "{}_{}".format(self.request.node.name, rebootOper)
else:
dir_name = self.request.node.name
report_file_dir = os.path.realpath((os.path.join(os.path.dirname(__file__),\
"../../logs/platform_tests/")))
log_dir = os.path.join(report_file_dir, dir_name)
if not os.path.exists(log_dir):
os.makedirs(log_dir)
log_dir = log_dir + "/"
if rebootOper is None:
rebootLog = '/tmp/{0}.log'.format(self.rebootType)
rebootReport = '/tmp/{0}-report.json'.format(self.rebootType)
capturePcap = '/tmp/capture.pcap'
filterPcap = '/tmp/capture_filtered.pcap'
syslogFile = '/tmp/syslog'
sairedisRec = '/tmp/sairedis.rec'
swssRec = '/tmp/swss.rec'
else:
rebootLog = '/tmp/{0}-{1}.log'.format(self.rebootType, rebootOper)
rebootReport = '/tmp/{0}-{1}-report.json'.format(self.rebootType, rebootOper)
capturePcap = '/tmp/capture_{0}.pcap'.format(rebootOper)
filterPcap = '/tmp/capture_filtered_{0}.pcap'.format(rebootOper)
syslogFile = '/tmp/syslog_{0}'.format(rebootOper)
sairedisRec = '/tmp/sairedis.rec.{0}'.format(rebootOper)
swssRec = '/tmp/swss.rec.{0}'.format(rebootOper)
logger.info('Extract log files on dut host')
dutLogFiles = [
{'directory': '/var/log', 'file_prefix': 'syslog', 'start_string': 'Linux version', 'target_filename': syslogFile},
{'directory': '/var/log/swss', 'file_prefix': 'sairedis.rec', 'start_string': 'recording on:', 'target_filename': sairedisRec},
{'directory': '/var/log/swss', 'file_prefix': 'swss.rec', 'start_string': 'recording started', 'target_filename': swssRec},
]
for logFile in dutLogFiles:
self.duthost.extract_log(**logFile)
logger.info('Fetching log files from ptf and dut hosts')
logFiles = {
self.ptfhost: [
{'src': rebootLog, 'dest': log_dir, 'flat': True, 'fail_on_missing': False},
{'src': rebootReport, 'dest': log_dir, 'flat': True, 'fail_on_missing': False},
{'src': capturePcap, 'dest': log_dir, 'flat': True, 'fail_on_missing': False},
{'src': filterPcap, 'dest': log_dir, 'flat': True, 'fail_on_missing': False},
],
self.duthost: [
{'src': syslogFile, 'dest': log_dir, 'flat': True},
{'src': sairedisRec, 'dest': log_dir, 'flat': True},
{'src': swssRec, 'dest': log_dir, 'flat': True},
],
}
for host, logs in logFiles.items():
for log in logs:
host.fetch(**log)
return log_dir
def imageInstall(self, prebootList=None, inbootList=None, prebootFiles=None):
'''
This method validates and prepares test bed for reboot test case.
@param prebootList: list of operation to run before reboot process
@param inbootList: list of operation to run during reboot prcoess
@param prebootFiles: preboot files
'''
self.prebootList = prebootList
self.inbootList = inbootList
self.prebootFiles = prebootFiles
# Validating contents of preboot and inboot list and building sadList
self.__validateAndBuildSadList()
# Update next hop IP based on Inboot list
self.__updateNextHopIps()
# Collect test data and set up testbed with required files/services
self.__setupTestbed()
# Download and install new sonic image
self.__handleRebootImage()
# Handle mellanox platform
self.__handleMellanoxDut()
def runRebootTest(self):
# Run advanced-reboot.ReloadTest for item in preboot/inboot list
count = 0
result = True
failed_list = list()
for rebootOper in self.rebootData['sadList']:
count += 1
try:
if self.advanceboot_loganalyzer:
pre_reboot_analysis, post_reboot_analysis = self.advanceboot_loganalyzer
marker = pre_reboot_analysis()
self.__setupRebootOper(rebootOper)
thread = InterruptableThread(
target=self.__runPtfRunner,
kwargs={"rebootOper": rebootOper})
thread.daemon = True
thread.start()
# give the test REBOOT_CASE_TIMEOUT (1800s) to complete the reboot with IO,
# and then additional 300s to examine the pcap, logs and generate reports
ptf_timeout = REBOOT_CASE_TIMEOUT + 300
thread.join(timeout=ptf_timeout, suppress_exception=True)
self.ptfhost.shell("pkill -f 'ptftests advanced-reboot.ReloadTest'", module_ignore_errors=True)
# the thread might still be running, and to catch any exceptions after pkill allow 10s to join
thread.join(timeout=10)
self.__verifyRebootOper(rebootOper)
except Exception:
logger.error("Exception caught while running advanced-reboot test on ptf")
failed_list.append(rebootOper)
finally:
# always capture the test logs
log_dir = self.__fetchTestLogs(rebootOper)
self.__clearArpAndFdbTables()
self.__revertRebootOper(rebootOper)
if self.advanceboot_loganalyzer:
post_reboot_analysis(marker, reboot_oper=rebootOper, log_dir=log_dir)
if len(self.rebootData['sadList']) > 1 and count != len(self.rebootData['sadList']):
time.sleep(TIME_BETWEEN_SUCCESSIVE_TEST_OPER)
pytest_assert(len(failed_list) == 0,\
"Advanced-reboot failure. Failed test: {}, sub-cases: {}".format(self.request.node.name, failed_list))
return result
def runRebootTestcase(self, prebootList=None, inbootList=None,
prebootFiles='peer_dev_info,neigh_port_info'):
'''
This method validates and prepares test bed for reboot test case. It runs the reboot test case using provided
test arguments
@param prebootList: list of operation to run before reboot process
@param inbootList: list of operation to run during reboot prcoess
@param prebootFiles: preboot files
'''
self.imageInstall(prebootList, inbootList, prebootFiles)
return self.runRebootTest()
def __setupRebootOper(self, rebootOper):
testData = {
'portchannel_interfaces': copy.deepcopy(self.mgFacts['minigraph_portchannels']),
'vlan_interfaces': copy.deepcopy(self.mgFacts['minigraph_vlans']),
'ports': copy.deepcopy(self.mgFacts['minigraph_ptf_indices']),
'peer_dev_info': copy.deepcopy(self.mgFacts['minigraph_devices']),
'neigh_port_info': copy.deepcopy(self.mgFacts['minigraph_neighbors']),
}
if isinstance(rebootOper, SadOperation):
logger.info('Running setup handler for reboot operation {}'.format(rebootOper))
rebootOper.setup(testData)
# TODO: remove this parameter. Arista VMs can be read by ptf from peer_dev_info.
self.rebootData['arista_vms'] = [
attr['mgmt_addr'] for dev, attr in testData['peer_dev_info'].items() if attr['hwsku'] == 'Arista-VM'
]
self.hostMaxLen = len(self.rebootData['arista_vms']) - 1
testDataFiles = [{'source': source, 'name': name} for name, source in testData.items()]
self.__transferTestDataFiles(testDataFiles, self.ptfhost)
def __verifyRebootOper(self, rebootOper):
if isinstance(rebootOper, SadOperation):
logger.info('Running verify handler for reboot operation {}'.format(rebootOper))
rebootOper.verify()
def __revertRebootOper(self, rebootOper):
if isinstance(rebootOper, SadOperation):
logger.info('Running revert handler for reboot operation {}'.format(rebootOper))
rebootOper.revert()
def __runPtfRunner(self, rebootOper=None):
'''
Run single PTF advanced-reboot.ReloadTest
@param rebootOper:Reboot operation to conduct before/during reboot process
'''
logger.info("Running PTF runner on PTF host: {0}".format(self.ptfhost))
params={
"dut_username" : self.rebootData['dut_username'],
"dut_password" : self.rebootData['dut_password'],
"dut_hostname" : self.rebootData['dut_hostname'],
"reboot_limit_in_seconds" : self.rebootLimit,
"reboot_type" : self.rebootType,
"portchannel_ports_file" : self.rebootData['portchannel_interfaces_file'],
"vlan_ports_file" : self.rebootData['vlan_interfaces_file'],
"ports_file" : self.rebootData['ports_file'],
"dut_mac" : self.rebootData['dut_mac'],
"default_ip_range" : self.rebootData['default_ip_range'],
"vlan_ip_range" : self.rebootData['vlan_ip_range'],
"lo_v6_prefix" : self.rebootData['lo_v6_prefix'],
"arista_vms" : self.rebootData['arista_vms'],
"nexthop_ips" : self.rebootData['nexthop_ips'],
"allow_vlan_flooding" : self.allowVlanFlooding,
"sniff_time_incr" : self.sniffTimeIncr,
"setup_fdb_before_test" : True,
"vnet" : self.vnet,
"vnet_pkts" : self.vnetPkts,
"bgp_v4_v6_time_diff": self.bgpV4V6TimeDiff,
"asic_type": self.duthost.facts["asic_type"],
"allow_mac_jumping": self.allowMacJump,
"preboot_files" : self.prebootFiles,
"alt_password": self.duthost.host.options['variable_manager']._hostvars[self.duthost.hostname].get("ansible_altpassword")
}
if not isinstance(rebootOper, SadOperation):
# Non-routing neighbor/dut lag/bgp, vlan port up/down operation is performed before dut reboot process
# lack of routing indicates it is preboot operation
prebootOper = rebootOper if rebootOper is not None and 'routing' not in rebootOper else None
# Routing add/remove is performed during dut reboot process
# presence of routing in reboot operation indicates it is during reboot operation (inboot)
inbootOper = rebootOper if rebootOper is not None and 'routing' in rebootOper else None
params.update({
"preboot_oper" : prebootOper,
"inboot_oper" : inbootOper,
})
else:
params.update({'logfile_suffix': str(rebootOper)})
self.__updateAndRestartArpResponder(rebootOper)
logger.info('Run advanced-reboot ReloadTest on the PTF host. TestCase: {}, sub-case: {}'.format(\
self.request.node.name, str(rebootOper)))
result = ptf_runner(
self.ptfhost,
"ptftests",
"advanced-reboot.ReloadTest",
qlen=PTFRUNNER_QLEN,
platform_dir="ptftests",
platform="remote",
params=params,
log_file=u'/tmp/advanced-reboot.ReloadTest.log',
module_ignore_errors=self.moduleIgnoreErrors,
timeout=REBOOT_CASE_TIMEOUT
)
return result
def __restorePrevImage(self):
'''
Restore previous image and reboot DUT
'''
currentImage = self.duthost.shell('sonic_installer list | grep Current | cut -f2 -d " "')['stdout']
if currentImage != self.currentImage:
logger.info('Restore current image')
self.duthost.shell('sonic_installer set_default {0}'.format(self.currentImage))
rebootDut(
self.duthost,
self.localhost,
reboot_type=self.rebootType.replace('-reboot', ''),
wait = self.readyTimeout
)
def tearDown(self):
'''
Tears down test case. It also verifies that config_db.json exists.
'''
logger.info('Running test tear down')
if 'warm-reboot' in self.rebootType and self.newSonicImage is not None:
logger.info('Save configuration after warm rebooting into new image')
self.duthost.shell('config save -y')
result = self.duthost.shell('stat /etc/sonic/config_db.json')
assert len(result['stderr_lines']) == 0, '/etc/sonic/config_db.json is missing'
self.__runScript(['remove_ip.sh'], self.ptfhost)
if self.postRebootCheckScript:
logger.info('Run the post reboot check script')
self.__runScript([self.postRebootCheckScript], self.duthost)
if not self.stayInTargetImage:
self.__restorePrevImage()
@pytest.fixture
def get_advanced_reboot(request, duthosts, rand_one_dut_hostname, ptfhost, localhost, tbinfo, creds):
'''
Pytest test fixture that provides access to AdvancedReboot test fixture
@param request: pytest request object
@param duthost: AnsibleHost instance of DUT
@param ptfhost: PTFHost for interacting with PTF through ansible
@param localhost: Localhost for interacting with localhost through ansible
@param tbinfo: fixture provides information about testbed
'''
duthost = duthosts[rand_one_dut_hostname]
instances = []
def get_advanced_reboot(**kwargs):
'''
API that returns instances of AdvancedReboot class
'''
assert len(instances) == 0, "Only one instance of reboot data is allowed"
advancedReboot = AdvancedReboot(request, duthost, ptfhost, localhost, tbinfo, creds, **kwargs)
instances.append(advancedReboot)
return advancedReboot
yield get_advanced_reboot
# Perform clean up
for s in instances:
s.tearDown()
| 45.834094 | 139 | 0.635108 |
ce5fb0db275052c1e486cb697e9dadf06ad38787 | 355 | py | Python | tests/test_models.py | andytwoods/django-gitabix | c72867675364072d32be94d31c197430c1d46ae4 | [
"MIT"
] | null | null | null | tests/test_models.py | andytwoods/django-gitabix | c72867675364072d32be94d31c197430c1d46ae4 | [
"MIT"
] | null | null | null | tests/test_models.py | andytwoods/django-gitabix | c72867675364072d32be94d31c197430c1d46ae4 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
test_django-gitabix
------------
Tests for `django-gitabix` models module.
"""
from django.test import TestCase
from django_gitabix import models
class TestDjango_gitabix(TestCase):
def setUp(self):
pass
def test_something(self):
pass
def tearDown(self):
pass
| 13.653846 | 41 | 0.633803 |
a6c0674addb6370a6e8e652709d85eb54543e11e | 21,733 | py | Python | pipe/network/sample_pyramid_add_kpn_NoRefine.py | dong1015323606/tof_mpi_remove | 11ecac5db4b30affbb1785ac01397e7aa53f22cf | [
"MIT"
] | 6 | 2020-08-24T02:03:56.000Z | 2021-12-10T02:39:41.000Z | pipe/network/sample_pyramid_add_kpn_NoRefine.py | dong1015323606/tof_mpi_remove | 11ecac5db4b30affbb1785ac01397e7aa53f22cf | [
"MIT"
] | 1 | 2020-10-16T02:15:36.000Z | 2021-06-05T02:25:36.000Z | pipe/network/sample_pyramid_add_kpn_NoRefine.py | dong1015323606/tof_mpi_remove | 11ecac5db4b30affbb1785ac01397e7aa53f22cf | [
"MIT"
] | 6 | 2020-09-25T12:20:44.000Z | 2021-11-25T03:13:36.000Z | import sys
sys.path.insert(0, './module/')
import tensorflow as tf
from dataset import *
from activation import *
from conv import conv
from dfus_block import dfus_block_add_output_conv
tf.logging.set_verbosity(tf.logging.INFO)
PI = 3.14159265358979323846
flg = False
dtype = tf.float32
def feature_extractor_subnet(x, flg, regular):
"""Build a U-Net architecture"""
""" Args: x is the input, 4-D tensor (BxHxWxC)
flg represent weather add the BN
regular represent the regularizer number
Return: output is 4-D Tensor (BxHxWxC)
"""
pref = 'feature_extractor_subnet_'
# whether to train flag
train_ae = flg
# define initializer for the network
keys = ['conv', 'upsample']
keys_avoid = ['OptimizeLoss']
inits = []
init_net = None
if init_net != None:
for name in init_net.get_variable_names():
# select certain variables
flag_init = False
for key in keys:
if key in name:
flag_init = True
for key in keys_avoid:
if key in name:
flag_init = False
if flag_init:
name_f = name.replace('/', '_')
num = str(init_net.get_variable_value(name).tolist())
# self define the initializer function
from tensorflow.python.framework import dtypes
from tensorflow.python.ops.init_ops import Initializer
exec(
"class " + name_f + "(Initializer):\n def __init__(self,dtype=tf.float32): self.dtype=dtype \n def __call__(self,shape,dtype=None,partition_info=None): return tf.cast(np.array(" + num + "),dtype=self.dtype)\n def get_config(self):return {\"dtype\": self.dtype.name}")
inits.append(name_f)
# autoencoder
n_filters = [
16, 16,
32, 32,
64, 64,
96, 96,
128, 128,
192, 192,
]
filter_sizes = [
3, 3,
3, 3,
3, 3,
3, 3,
3, 3,
3, 3,
]
pool_sizes = [ \
1, 1,
2, 1,
2, 1,
2, 1,
2, 1,
2, 1,
]
pool_strides = [
1, 1,
2, 1,
2, 1,
2, 1,
2, 1,
2, 1,
]
skips = [ \
False, False,
True, False,
True, False,
True, False,
True, False,
True, False,
]
# change space
ae_inputs = tf.identity(x, name='ae_inputs')
# prepare input
current_input = tf.identity(ae_inputs, name="input")
####################################################################################################################
# convolutional layers: feature extractor
features = []
for i in range(0, len(n_filters)):
name = pref + "conv_" + str(i)
# define the initializer
if name + '_bias' in inits:
bias_init = eval(name + '_bias()')
else:
bias_init = tf.zeros_initializer()
if name + '_kernel' in inits:
kernel_init = eval(name + '_kernel()')
else:
kernel_init = None
# convolution
current_input = tf.layers.conv2d(
inputs=current_input,
filters=n_filters[i],
kernel_size=[filter_sizes[i], filter_sizes[i]],
padding="same",
activation=relu,
trainable=train_ae,
kernel_initializer=kernel_init,
bias_initializer=bias_init,
name=name,
)
if pool_sizes[i] == 1 and pool_strides[i] == 1:
current_input = current_input
if (i == len(n_filters) - 1) or (pool_sizes[i + 1] == 2 and pool_strides[i + 1] == 2):
features.append(current_input)
else:
current_input = tf.layers.max_pooling2d( \
inputs=current_input,
pool_size=[pool_sizes[i], pool_sizes[i]],
strides=pool_strides[i],
name=pref + "pool_" + str(i)
)
return features
def depth_residual_regresssion_subnet(x, flg, regular, subnet_num):
"""Build a U-Net architecture"""
""" Args: x is the input, 4-D tensor (BxHxWxC)
flg represent weather add the BN
regular represent the regularizer number
Return: output is 4-D Tensor (BxHxWxC)
"""
pref = 'depth_regression_subnet_' + str(subnet_num) + '_'
# whether to train flag
train_ae = flg
# define initializer for the network
keys = ['conv', 'upsample']
keys_avoid = ['OptimizeLoss']
inits = []
init_net = None
if init_net != None:
for name in init_net.get_variable_names():
# select certain variables
flag_init = False
for key in keys:
if key in name:
flag_init = True
for key in keys_avoid:
if key in name:
flag_init = False
if flag_init:
name_f = name.replace('/', '_')
num = str(init_net.get_variable_value(name).tolist())
# self define the initializer function
from tensorflow.python.framework import dtypes
from tensorflow.python.ops.init_ops import Initializer
exec(
"class " + name_f + "(Initializer):\n def __init__(self,dtype=tf.float32): self.dtype=dtype \n def __call__(self,shape,dtype=None,partition_info=None): return tf.cast(np.array(" + num + "),dtype=self.dtype)\n def get_config(self):return {\"dtype\": self.dtype.name}")
inits.append(name_f)
# autoencoder
n_filters = [
128, 96,
64, 32,
16, 1,
]
filter_sizes = [
3, 3,
3, 3,
3, 3,
]
pool_sizes = [ \
1, 1,
1, 1,
1, 1,
]
pool_strides = [
1, 1,
1, 1,
1, 1,
]
skips = [ \
False, False,
False, False,
False, False,
]
# change space
ae_inputs = tf.identity(x, name='ae_inputs')
# prepare input
current_input = tf.identity(ae_inputs, name="input")
####################################################################################################################
# convolutional layers: depth regression
feature = []
for i in range(0, len(n_filters)):
name = pref + "conv_" + str(i)
# define the initializer
if name + '_bias' in inits:
bias_init = eval(name + '_bias()')
else:
bias_init = tf.zeros_initializer()
if name + '_kernel' in inits:
kernel_init = eval(name + '_kernel()')
else:
kernel_init = None
if i == (len(n_filters) - 1):
activation = None
else:
activation = relu
# convolution
current_input = tf.layers.conv2d(
inputs=current_input,
filters=n_filters[i],
kernel_size=[filter_sizes[i], filter_sizes[i]],
padding="same",
activation=activation,
trainable=train_ae,
kernel_initializer=kernel_init,
bias_initializer=bias_init,
name=name,
)
if pool_sizes[i] == 1 and pool_strides[i] == 1:
feature.append(current_input)
else:
feature.append(
tf.layers.max_pooling2d( \
inputs=current_input,
pool_size=[pool_sizes[i], pool_sizes[i]],
strides=pool_strides[i],
name=pref + "pool_" + str(i)
)
)
current_input = feature[-1]
depth_coarse = tf.identity(feature[-1], name='depth_coarse_output')
return depth_coarse
def unet_subnet(x, flg, regular):
"""Build a U-Net architecture"""
""" Args: x is the input, 4-D tensor (BxHxWxC)
flg represent weather add the BN
regular represent the regularizer number
Return: output is 4-D Tensor (BxHxWxC)
"""
pref = 'unet_subnet_'
# whether to train flag
train_ae = flg
# define initializer for the network
keys = ['conv', 'upsample']
keys_avoid = ['OptimizeLoss']
inits = []
init_net = None
if init_net != None:
for name in init_net.get_variable_names():
# select certain variables
flag_init = False
for key in keys:
if key in name:
flag_init = True
for key in keys_avoid:
if key in name:
flag_init = False
if flag_init:
name_f = name.replace('/', '_')
num = str(init_net.get_variable_value(name).tolist())
# self define the initializer function
from tensorflow.python.framework import dtypes
from tensorflow.python.ops.init_ops import Initializer
exec(
"class " + name_f + "(Initializer):\n def __init__(self,dtype=tf.float32): self.dtype=dtype \n def __call__(self,shape,dtype=None,partition_info=None): return tf.cast(np.array(" + num + "),dtype=self.dtype)\n def get_config(self):return {\"dtype\": self.dtype.name}")
inits.append(name_f)
# autoencoder
n_filters = [
16, 16,
32, 32,
64, 64,
128, 128,
]
filter_sizes = [
3, 3,
3, 3,
3, 3,
3, 3,
]
pool_sizes = [ \
1, 1,
2, 1,
2, 1,
2, 1,
]
pool_strides = [
1, 1,
2, 1,
2, 1,
2, 1,
]
skips = [ \
False, False,
True, False,
True, False,
True, False,
]
# change space
ae_inputs = tf.identity(x, name='ae_inputs')
# prepare input
current_input = tf.identity(ae_inputs, name="input")
####################################################################################################################
# convolutional layers: encoder
conv = []
pool = [current_input]
for i in range(0, len(n_filters)):
name = pref + "conv_" + str(i)
# define the initializer
if name + '_bias' in inits:
bias_init = eval(name + '_bias()')
else:
bias_init = tf.zeros_initializer()
if name + '_kernel' in inits:
kernel_init = eval(name + '_kernel()')
else:
kernel_init = None
# convolution
conv.append( \
tf.layers.conv2d( \
inputs=current_input,
filters=n_filters[i],
kernel_size=[filter_sizes[i], filter_sizes[i]],
padding="same",
activation=relu,
trainable=train_ae,
kernel_initializer=kernel_init,
bias_initializer=bias_init,
name=name,
)
)
if pool_sizes[i] == 1 and pool_strides[i] == 1:
pool.append(conv[-1])
else:
pool.append( \
tf.layers.max_pooling2d( \
inputs=conv[-1],
pool_size=[pool_sizes[i], pool_sizes[i]],
strides=pool_strides[i],
name=pref + "pool_" + str(i)
)
)
current_input = pool[-1]
####################################################################################################################
# convolutional layer: decoder
# upsampling
upsamp = []
current_input = pool[-1]
for i in range((len(n_filters) - 1) - 1, 0, -1):
name = pref + "upsample_" + str(i)
# define the initializer
if name + '_bias' in inits:
bias_init = eval(name + '_bias()')
else:
bias_init = tf.zeros_initializer()
if name + '_kernel' in inits:
kernel_init = eval(name + '_kernel()')
else:
kernel_init = None
## change the kernel size in upsample process
if skips[i] == False and skips[i + 1] == True:
filter_sizes[i] = 4
# upsampling
current_input = tf.layers.conv2d_transpose( \
inputs=current_input,
filters=n_filters[i],
kernel_size=[filter_sizes[i], filter_sizes[i]],
strides=(pool_strides[i], pool_strides[i]),
padding="same",
activation=relu,
trainable=train_ae,
kernel_initializer=kernel_init,
bias_initializer=bias_init,
name=name
)
upsamp.append(current_input)
# skip connection
if skips[i] == False and skips[i - 1] == True:
current_input = tf.concat([current_input, pool[i + 1]], axis=-1)
####################################################################################################################
features = tf.identity(upsamp[-1], name='ae_output')
return features
def depth_output_subnet(inputs, flg, regular, kernel_size): ## x (B,H,W,1), features:(B,H,W,64), samples:(B,H,W,9)
pref = 'depth_output_subnet_'
# whether to train flag
train_ae = flg
current_input = inputs
# define initializer for the network
keys = ['conv', 'upsample']
keys_avoid = ['OptimizeLoss']
inits = []
init_net = None
if init_net != None:
for name in init_net.get_variable_names():
# select certain variables
flag_init = False
for key in keys:
if key in name:
flag_init = True
for key in keys_avoid:
if key in name:
flag_init = False
if flag_init:
name_f = name.replace('/', '_')
num = str(init_net.get_variable_value(name).tolist())
# self define the initializer function
from tensorflow.python.framework import dtypes
from tensorflow.python.ops.init_ops import Initializer
exec(
"class " + name_f + "(Initializer):\n def __init__(self,dtype=tf.float32): self.dtype=dtype \n def __call__(self,shape,dtype=None,partition_info=None): return tf.cast(np.array(" + num + "),dtype=self.dtype)\n def get_config(self):return {\"dtype\": self.dtype.name}")
inits.append(name_f)
n_filters_mix = [kernel_size ** 2]
filter_sizes_mix = [1]
mix = []
for i in range(len(n_filters_mix)):
name = pref + "conv_" + str(i)
# define the initializer
if name + '_bias' in inits:
bias_init = eval(name + '_bias()')
else:
bias_init = tf.zeros_initializer()
if name + '_kernel' in inits:
kernel_init = eval(name + '_kernel()')
else:
kernel_init = None
if i == (len(n_filters_mix) - 1):
activation = sigmoid
else:
activation = relu
# convolution
mix.append( \
tf.layers.conv2d( \
inputs=current_input,
filters=n_filters_mix[i],
kernel_size=[filter_sizes_mix[i], filter_sizes_mix[i]],
padding="same",
activation=activation,
trainable=train_ae,
kernel_initializer=kernel_init,
bias_initializer=bias_init,
name=name,
)
)
current_input = mix[-1]
return current_input
def dear_kpn(x, flg, regular):
kernel_size = 3
features = unet_subnet(x, flg, regular)
weights = depth_output_subnet(features, flg, regular, kernel_size=kernel_size)
weights = weights / tf.reduce_sum(tf.abs(weights) + 1e-6, axis=-1, keep_dims=True)
column = im2col(x, kernel_size=kernel_size)
current_output = tf.reduce_sum(column * weights, axis=-1, keep_dims=True)
depth_output = tf.identity(current_output, name='depth_output')
return depth_output
def residual_output_subnet(x, flg, regular, subnet_num):
"""Build a U-Net architecture"""
""" Args: x is the input, 4-D tensor (BxHxWxC)
flg represent weather add the BN
regular represent the regularizer number
Return: output is 4-D Tensor (BxHxWxC)
"""
pref = 'residual_output_subnet_' + str(subnet_num) + '_'
# whether to train flag
train_ae = flg
# define initializer for the network
keys = ['conv', 'upsample']
keys_avoid = ['OptimizeLoss']
inits = []
init_net = None
if init_net != None:
for name in init_net.get_variable_names():
# select certain variables
flag_init = False
for key in keys:
if key in name:
flag_init = True
for key in keys_avoid:
if key in name:
flag_init = False
if flag_init:
name_f = name.replace('/', '_')
num = str(init_net.get_variable_value(name).tolist())
# self define the initializer function
from tensorflow.python.framework import dtypes
from tensorflow.python.ops.init_ops import Initializer
exec(
"class " + name_f + "(Initializer):\n def __init__(self,dtype=tf.float32): self.dtype=dtype \n def __call__(self,shape,dtype=None,partition_info=None): return tf.cast(np.array(" + num + "),dtype=self.dtype)\n def get_config(self):return {\"dtype\": self.dtype.name}")
inits.append(name_f)
# autoencoder
n_filters = [
1
]
filter_sizes = [
1
]
pool_sizes = [ \
1
]
pool_strides = [
1
]
skips = [ \
False
]
# change space
ae_inputs = tf.identity(x, name='ae_inputs')
# prepare input
current_input = tf.identity(ae_inputs, name="input")
####################################################################################################################
# convolutional layers: depth regression
feature = []
for i in range(0, len(n_filters)):
name = pref + "conv_" + str(i)
# define the initializer
if name + '_bias' in inits:
bias_init = eval(name + '_bias()')
else:
bias_init = tf.zeros_initializer()
if name + '_kernel' in inits:
kernel_init = eval(name + '_kernel()')
else:
kernel_init = None
if i == (len(n_filters) - 1):
activation = None
else:
activation = relu
# convolution
current_input = tf.layers.conv2d(
inputs=current_input,
filters=n_filters[i],
kernel_size=[filter_sizes[i], filter_sizes[i]],
padding="same",
activation=activation,
trainable=train_ae,
kernel_initializer=kernel_init,
bias_initializer=bias_init,
name=name,
)
if pool_sizes[i] == 1 and pool_strides[i] == 1:
feature.append(current_input)
else:
feature.append(
tf.layers.max_pooling2d( \
inputs=current_input,
pool_size=[pool_sizes[i], pool_sizes[i]],
strides=pool_strides[i],
name=pref + "pool_" + str(i)
)
)
current_input = feature[-1]
depth_residual_coarse = tf.identity(feature[-1], name='depth_coarse_residual_output')
return depth_residual_coarse
def sample_pyramid_add_kpn_NoRefine(x, flg, regular, batch_size, deformable_range):
depth_residual = []
depth_residual_input = []
depth_refine = []
offsets_scale = []
depth_residual_weight = [0.32, 0.08, 0.02, 0.01, 0.005]
h_max = tf.shape(x)[1]
w_max = tf.shape(x)[2]
depth = tf.expand_dims(x[:, :, :, 0], axis=-1)
depth_and_amplitude = x[:, :, :, 0:2]
rgb = x[:, :, :, 2:5]
features = feature_extractor_subnet(depth_and_amplitude, flg, regular)
for i in range(1, len(features) + 1):
if i == 1:
inputs = features[len(features) - i]
else:
feature_input = features[len(features) - i]
h_max_low_scale = tf.shape(feature_input)[1]
w_max_low_scale = tf.shape(feature_input)[2]
depth_coarse_input = tf.image.resize_bicubic(depth_residual[-1], size=(h_max_low_scale, w_max_low_scale),
align_corners=True)
inputs = tf.concat([feature_input, depth_coarse_input], axis=-1)
current_depth_residual = depth_residual_regresssion_subnet(inputs, flg, regular, subnet_num=i)
depth_residual.append(current_depth_residual)
current_depth_residual_input = tf.image.resize_bicubic(current_depth_residual, size=(h_max, w_max),
align_corners=True)
depth_residual_input.append(current_depth_residual_input)
depth_coarse_residual_input = tf.concat(depth_residual_input, axis=-1)
final_depth_residual_output = residual_output_subnet(depth_coarse_residual_input, flg, regular, subnet_num=0)
current_final_depth_output = depth + final_depth_residual_output
final_depth_output = current_final_depth_output
depth_residual_input.append(final_depth_residual_output)
depth_residual_input.append(final_depth_output - current_final_depth_output)
return final_depth_output, depth_residual_input | 32.632132 | 287 | 0.528781 |
f3620b66f17c9d86090322d9f2ba0c3695dd0947 | 492 | py | Python | annotypes/py2_examples/reusecls.py | thomascobb/annotypes | 3dac2e2970a67f667b707b0d248f58ac9a06551b | [
"Apache-2.0"
] | 2 | 2019-08-16T11:40:21.000Z | 2019-10-25T12:43:48.000Z | annotypes/py2_examples/reusecls.py | thomascobb/annotypes | 3dac2e2970a67f667b707b0d248f58ac9a06551b | [
"Apache-2.0"
] | 3 | 2019-03-12T11:03:23.000Z | 2019-07-02T10:24:28.000Z | annotypes/py2_examples/reusecls.py | thomascobb/annotypes | 3dac2e2970a67f667b707b0d248f58ac9a06551b | [
"Apache-2.0"
] | 1 | 2020-08-14T13:52:01.000Z | 2020-08-14T13:52:01.000Z | import time
from annotypes import WithCallTypes, add_call_types, Anno
from .simple import Simple
with Anno("Parameters to take"):
ASimple = Simple
class ReuseCls(WithCallTypes):
@add_call_types
def validate(self, params):
# type: (ASimple) -> ASimple
if params.exposure < 0.4:
params.exposure = 0.4
return params
@add_call_types
def configure(self, params):
# type: (ASimple) -> None
time.sleep(params.exposure)
| 19.68 | 57 | 0.646341 |
3d93f98fc67dd0c9bae1a7789476c63b9f5f5603 | 2,456 | py | Python | geist/keyboard.py | thetestpeople/Geist | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | [
"MIT"
] | 5 | 2015-05-01T15:58:48.000Z | 2017-04-19T03:38:25.000Z | geist/keyboard.py | tonysimpson/Geist | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | [
"MIT"
] | 1 | 2016-08-05T17:05:02.000Z | 2016-08-05T17:05:02.000Z | geist/keyboard.py | tonysimpson/Geist | a1ef16d8b4c3777735008b671a50acfde3ce7bf1 | [
"MIT"
] | 2 | 2016-09-27T13:45:31.000Z | 2017-05-21T14:08:57.000Z | def keyboard_layout_factory(layout_name):
if layout_name != 'default':
raise ValueError('unsupported keyboard layout %r' % (layout_name,))
return CouldDoBetterKeyboardLayout()
def _key_down_up(name):
return [KeyDown(name), KeyUp(name)]
class CouldDoBetterKeyboardLayout(object):
"""Converts single characters into keypresses
This is a very osteer version, and this mechanism my be replaced with a
better one.
"""
CHAR_TO_NAME_MAP = {
# Passed char: (char symbol, needs shift)
'\n': ('return', False),
' ': ('space', False),
'\t': ('tab', False),
'.': ('period', False),
'!': ('exclam', True),
'"': ('quotedbl', True),
"'": ('apostrophe', False),
'@': ('at', True),
'&': ('ampersand', True),
'-': ('minus', False),
':': ('colon', True),
'\\': ('backslash', False),
'_': ('underscore', True),
'/': ('fslash', False),
'>': ('greaterthan', True),
'<': ('lessthan', True),
',': ('comma', False),
'[': ('lsquarebracket', False),
']': ('rsquarebracket', False),
'{': ('lcurlybracket', True),
'}': ('rcurlybracket', True),
'+': ('plus', True),
'=': ('equals', False),
'#': ('hash', False),
'?': ('questionmk', True)}
def __call__(self, char):
if char in CouldDoBetterKeyboardLayout.CHAR_TO_NAME_MAP:
key, shifting = CouldDoBetterKeyboardLayout.CHAR_TO_NAME_MAP[char]
if shifting:
return [SHIFT_DOWN] + _key_down_up(key) + [SHIFT_UP]
return _key_down_up(key)
elif char.isalnum():
if char.isupper():
return [SHIFT_DOWN] + _key_down_up(char.lower()) + [SHIFT_UP]
else:
return _key_down_up(char)
else:
raise ValueError('unsupported character %r' % (char,))
class KeyDown(object):
def __init__(self, keyname):
self._keyname = keyname
def __str__(self):
return self._keyname
class KeyUp(object):
def __init__(self, keyname):
self._keyname = keyname
def __str__(self):
return self._keyname
class KeyDownUp(object):
def __init__(self, keyname):
self._keyname = keyname
def __str__(self):
return self._keyname
KeyPress = KeyDownUp
SHIFT_DOWN = KeyDown('shift')
SHIFT_UP = KeyUp('shift')
| 27.909091 | 78 | 0.551303 |
5c35760686627614867cae48f3af027817ac514c | 3,990 | py | Python | meshmodapi/settings.py | CoHutso/mesh-mod-api | 80d206aec1c1aecba672240ecaeadf3d3c9883d3 | [
"MIT"
] | null | null | null | meshmodapi/settings.py | CoHutso/mesh-mod-api | 80d206aec1c1aecba672240ecaeadf3d3c9883d3 | [
"MIT"
] | null | null | null | meshmodapi/settings.py | CoHutso/mesh-mod-api | 80d206aec1c1aecba672240ecaeadf3d3c9883d3 | [
"MIT"
] | null | null | null | """
Django settings for meshmodapi project.
Generated by 'django-admin startproject' using Django 3.2.6.
For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""
from pathlib import Path
import os
import dj_database_url
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', 'django-insecure-q-u-e3*c5!k_5ykul36+e2#%m0i3m3+#+4oy(pq+fgp2ewk)ul')
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = False
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'datacollection.apps.DatacollectionConfig',
'rest_framework',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'whitenoise.middleware.WhiteNoiseMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'meshmodapi.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'meshmodapi.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# Heroku: Update database configuration from $DATABASE_URL.
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
# The absolute path to the directory where collectstatic will collect static files for deployment.
STATIC_ROOT = BASE_DIR / 'staticfiles'
# The URL to use when referring to static files (where they will be served from)
STATIC_URL = '/static/'
# Simplified static file serving.
# https://warehouse.python.org/project/whitenoise/
STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'
| 27.517241 | 118 | 0.720802 |
b61e67eca1b6c87768e531194c09351b0e466655 | 1,647 | py | Python | pinax/teams/decorators.py | auto-mat/pinax-teams | 6d05f5c161fa51cc5ebe87cdea03d821ea1d424c | [
"MIT"
] | null | null | null | pinax/teams/decorators.py | auto-mat/pinax-teams | 6d05f5c161fa51cc5ebe87cdea03d821ea1d424c | [
"MIT"
] | null | null | null | pinax/teams/decorators.py | auto-mat/pinax-teams | 6d05f5c161fa51cc5ebe87cdea03d821ea1d424c | [
"MIT"
] | null | null | null | from __future__ import unicode_literals
import functools
from django.http import Http404
from django.shortcuts import get_object_or_404
from django.utils.decorators import available_attrs
from account.decorators import login_required
from .models import Membership, Team
def team_required(func=None):
"""
Decorator for views that require a team be supplied wither via a slug in the
url pattern or already set on the request object from the TeamMiddleware
"""
def decorator(view_func):
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
slug = kwargs.pop("slug", None)
if not getattr(request, "team", None):
request.team = get_object_or_404(Team, slug=slug)
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator
def manager_required(func=None):
"""
Decorator for views that require not only a team but also that a user be
logged in and be the manager or owner of that team.
"""
def decorator(view_func):
@team_required
@login_required
@functools.wraps(view_func, assigned=available_attrs(view_func))
def _wrapped_view(request, *args, **kwargs):
role = request.team.role_for(request.user)
if role not in [Membership.ROLE_MANAGER, Membership.ROLE_OWNER]:
raise Http404()
return view_func(request, *args, **kwargs)
return _wrapped_view
if func:
return decorator(func)
return decorator
| 32.94 | 80 | 0.681846 |
29278f4a616ec7759cec64dd8c8fa3be31882b7e | 20,220 | py | Python | foiamachine/apps/mail/models.py | saizai/foiamachine | 344007d57b47ac93df637e4a282c4d87cc6f78e3 | [
"Unlicense",
"MIT"
] | 9 | 2017-08-02T16:28:10.000Z | 2021-07-19T09:51:46.000Z | foiamachine/apps/mail/models.py | saizai/foiamachine | 344007d57b47ac93df637e4a282c4d87cc6f78e3 | [
"Unlicense",
"MIT"
] | null | null | null | foiamachine/apps/mail/models.py | saizai/foiamachine | 344007d57b47ac93df637e4a282c4d87cc6f78e3 | [
"Unlicense",
"MIT"
] | 5 | 2017-10-10T23:15:02.000Z | 2021-07-19T09:51:48.000Z | from django.db import models
from django.db.models import Q
from django.conf import settings
from django_extensions.db.fields import AutoSlugField
from django.core.files.uploadedfile import InMemoryUploadedFile
from django.utils import timezone
from werkzeug.datastructures import MultiDict
from time import mktime
import simplejson as json
from datetime import datetime
from StringIO import StringIO
from email.utils import parseaddr, parsedate
from dateutil.parser import parse
from attachment import *
from apps.requests.models import Request
from apps.core.models import EmailAddress
import django
import mimetypes
import requests
import poplib
import email
import logging
import boto
import re
logger = logging.getLogger('default')
thread_pattern = re.compile("LOOKUP:[a-zA-Z1234567890]*")
MSG_DIRECTIONS = (
('S', 'SENT'),
('R', "RECEIVED")
)
class MessageId(models.Model):
#messageid should never be more than 250, we do 512 just in case
#http://www.imc.org/ietf-usefor/2000/Jun/0020.html
idd = models.CharField(max_length=255, unique=True)
@property
def get_msg_id(self):
return self.idd
class MailManager(models.Manager):
def get_query_set(self):
return super(MailManager, self).get_query_set().filter(deprecated__isnull=True)
class MailMessage(models.Model):
email_from = models.EmailField(max_length=256)
reply_to = models.EmailField(blank=True, null=True)
to = models.ManyToManyField(EmailAddress, blank=True, null=True, related_name='message_to')
cc = models.ManyToManyField(EmailAddress, blank=True, null=True, related_name='message_cc')
bcc = models.ManyToManyField(EmailAddress, blank=True, null=True, related_name='message_bcc')
body = models.TextField(blank=True, null=True)
subject = models.CharField(max_length=1024)
attachments = models.ManyToManyField(Attachment, blank=True, null=True, related_name='message_attachments')
request = models.ForeignKey(Request, blank=True, null=True)
replies = models.ManyToManyField("self", null=True, blank=True, related_name='prior_thread')
#if it is a reply, then time it was received by mail server otherwise NOW
dated = models.DateTimeField(null=True, blank=True)
#when message was created on our database, if sent by us then created == dated
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
slug = AutoSlugField(populate_from=('subject',), overwrite=False)
direction = models.CharField(max_length=1, choices=MSG_DIRECTIONS,)
message_id = models.CharField(max_length=255, blank=True, null=True)
#todo move to using the MessageId class
received_header = models.TextField(null=True, blank=True)
references = models.ManyToManyField(MessageId, blank=True, null=True, related_name='message_references')
deprecated = models.DateTimeField(null=True)
was_fwded = models.BooleanField('this message was sent by a user to this thread', default=False)
objects = MailManager()
@staticmethod
def get_notes():
#message id is set by mailgun / mail server so unsent messages or user notes have no id
return MailMessage.objects.filter(message_id__isnull=True)
def get_mailboxes(self):
return self.mailbox_messages.all()
def get_email_addresses(self):
retval = []
retval = retval + [address.get_email for address in self.to.all()]
retval = retval + [address.get_email for address in self.cc.all()]
retval = retval + [address.get_email for address in self.bcc.all()]
retval = retval + [self.email_from]
retval = retval + [self.reply_to]
retval = [address for address in retval if address] # Remove any 'Nones'
return retval
@property
def get_references_hdr(self):
retval = [reference.get_msg_id for reference in self.references.all()]
return "\t".join(retval)
@property
def get_reference_ids(self):
return [reference.get_msg_id for reference in self.references.all()]
def add_references(self, references):
for reference in references:
self.references.add(reference)
@property
def get_from_email(self):
return self.email_from
@property
def get_to_emails(self):
return [to.content for to in self.to.all()]
@property
def get_cc_emails(self):
return [cc.content for cc in self.cc.all()]
@property
def plain_text_body(self):
from HTMLParser import HTMLParser
class MLStripper(HTMLParser):
def __init__(self):
self.reset()
self.fed = []
def handle_data(self, d):
self.fed.append(d)
def get_data(self):
return ''.join(self.fed)
s = MLStripper()
s.feed(self.body)
return s.get_data()
@property
def get_body(self):
return self.body.replace("\r", "<br/>")
def send(self, provisioned_address, references=None):
data = {"from": self.email_from,
"to": [addr.get_email for addr in self.to.all()] + ([provisioned_address] if hasattr(settings, 'MG_ROUTE') else []),
"subject": self.subject,
#"h:reply-to": self.reply_to,
"html": self.body
}
if references is not None:
data['h:References'] = references
if self.bcc.all().count() > 0:
data['bcc'] = [addr.get_email for addr in self.bcc.all()]
if self.cc.all().count() > 0:
data['cc'] = [addr.get_email for addr in self.cc.all()]
resp = requests.post(
settings.MG_POST_URL,
files=MultiDict([("attachment", attachment.file) for attachment in self.attachments.all()]),
auth=("api", settings.MAILGUN_KEY),
data=data)
content = json.loads(resp.content)
self.dated = timezone.now()
logging.info('MESSAGE SEND STATUS:%s' % resp.content)
retval = None
if "id" in content.keys():
logger.info("SENT MESSAGE message_id=%s" % content['id'])
self.message_id = content['id']
retval = content['id']
self.save()
return retval
class MailBox(models.Model):
usr = models.ForeignKey(django.contrib.auth.models.User)
messages = models.ManyToManyField(MailMessage, blank=True, null=True, related_name='mailbox_messages')
created = models.DateTimeField(auto_now_add=True)
provisioned_email = models.EmailField(blank=True, null=True)
def get_orphaned_messages(self):
return self.messages.filter(request__id=None).order_by('-dated')
@staticmethod
def get_root(request_id):
return MailMessage.objects.filter(request__id=request_id).order_by('dated')[0]
def get_threads(self, request_id):
#roots = self.messages.filter(request__id=request_id).order_by('dated')
roots = MailMessage.objects.filter(request__id=request_id).order_by('dated')
logger.debug("getting threads len=%s request_id=%s" % (roots.count(), request_id))
if roots.count() <= 0:
return list()
if roots.count() > 0:
return [roots[0]] + [mail_msg for mail_msg in roots[0].replies.all().order_by('dated')]
if roots[0].dated is not None and roots[0].dated >= datetime(month=3, day=18, year=2013):
retval = [reply for reply in roots[0].replies.all()]
retval.insert(0, roots[0])
return retval
return []
def add_message(self, message):
self.messages.add(message)
def check_and_save_mail(self):
messages = self.check_mail()
for message in messages:
try:
mail_msg, inreply = self.parse_message_poptres(message)
self.store_message(mail_msg, inreply)
except Exception as e:
logger.exception(e)
return True
def check_mail(self):
'''
TODO I need to delete messages that have been stored
which should be taken care of with a wrapper method
that deletes messages after I have stored them
'''
M = poplib.POP3(settings.MAILGUN_POP)
M.user(self.get_provisioned_email())
M.pass_(self.get_password())
numMessages = len(M.list()[1])
retval = list()
for i in range(numMessages):
msg = M.retr(i+1)[1]
mail = email.message_from_string('\n'.join(msg))
retval.append(mail)
return retval
def parse_message_poptres(self, message):
'''
http://www.ietf.org/rfc/rfc2822.txt
'''
body = None
html = None
subject = message['Subject']
from_email = parseaddr(message.get('From'))[1]
tos = [EmailAddress.objects.get_or_create(content=parseaddr(msg)[1])[0]
for msg in message.get_all('to', [])]
ccs = [EmailAddress.objects.get_or_create(content=parseaddr(msg)[1])[0]
for msg in message.get_all('cc', [])]
dt = parsedate(message.get('Date'))
datet = datetime.fromtimestamp(mktime(dt)) if dt is not None else dt
inreply = message.get('In-Reply-To', None)
message_id = message.get('Message-Id', None)
raw_header = ""
for key in message.keys():
raw_header += '\n' + message.get(key)
attachments = list()
for part in message.walk():
content_disposition = part.get("Content-Disposition", None)
if content_disposition:
atch = self.parse_attachments_poptres(content_disposition, part)
attachments.append(atch)
elif part.get_content_type() == "text/plain":
if body is None:
body = ""
body += unicode(
part.get_payload(decode=True),
part.get_content_charset(),
'replace'
).encode('utf8', 'replace')
elif part.get_content_type() == "text/html":
if html is None:
html = ""
html += unicode(
part.get_payload(decode=True),
part.get_content_charset(),
'replace'
).encode('utf8', 'replace')
body = html if html is not None else body
#don't save messages we already have
if MailMessage.objects.filter(message_id=message_id).count() > 0:
logger.debug('duplicate message found message_id=%s' % message_id)
return None
if MailMessage.objects.filter(body=body).count() > 0:
ids = [obj.message_id for obj in MailMessage.objects.filter(body=body)]
logger.debug('duplicate body found, ignoring message_id=%s' % ids)
return None
references = message.get('References', None)
references = [MessageId.objects.get_or_create(idd=reference)[0]
for reference in references.split("\t")] if references is not None else []
logger.debug('message_id=%s' % message_id)
mail_msg = MailMessage(subject=subject, email_from=from_email,
direction=MSG_DIRECTIONS[1][0], dated=datet, message_id=message_id,
received_header=raw_header)
mail_msg.body = body
mail_msg.save()
mail_msg.references = references
mail_msg.attachments = attachments
mail_msg.to = tos
mail_msg.cc = ccs
mail_msg.dated = datet
self.messages.add(mail_msg)
return (mail_msg, inreply)
@staticmethod
def parse_message_http(keyvals):
try:
from_email = keyvals['sender'] if 'sender' in keyvals.keys() else ''
message_id = keyvals['Message-Id'] if 'Message-Id' in keyvals.keys() else ''
references = keyvals['References'] if 'References' in keyvals.keys() else ''
inreply = keyvals['In-Reply-To'] if 'In-Reply-To' in keyvals.keys() else ''
text_body = keyvals['body-plain'] if 'body-plain' in keyvals.keys() else ''
html_body = keyvals['body-html'] if 'body-html' in keyvals.keys() else ''
body = text_body if not html_body else html_body
subject = keyvals['subject'] if 'subject' in keyvals.keys() else ''
dt = keyvals['Date'] if 'Date' in keyvals.keys() else None
datet = parse(dt) if dt is not None else dt
raw_header = ''
logger.info('message parsed id=%s' % message_id)
tosi = keyvals['To'].split(',') if 'To' in keyvals.keys() else []
ccsi = keyvals['Cc'].split(',') if 'Cc' in keyvals.keys() else []
from_email = parseaddr(from_email)[1]
tos = [EmailAddress.objects.get_or_create(content=parseaddr(msg)[1])[0]
for msg in tosi]
ccs = [EmailAddress.objects.get_or_create(content=parseaddr(msg)[1])[0]
for msg in ccsi]
logger.info('PREREFERENCES=%s' % references)
references = [MessageId.objects.get_or_create(idd=reference)[0]
for reference in references.split()] if references is not None else []
logger.info('REFERENCES=%s' % references)
mail_msg = MailMessage(subject=subject, email_from=from_email,
direction=MSG_DIRECTIONS[1][0], dated=datet, message_id=message_id,
received_header=raw_header)
mail_msg.body = body
mail_msg.save()
logger.info('message saved pk=%s' % mail_msg.id)
mail_msg.references = references
mail_msg.to = tos
mail_msg.cc = ccs
#self.messages.add(mail_msg)
return (mail_msg, inreply)
except Exception as e:
logger.exception("error parsing message e=%s" % (e))
return (None)
def store_message(self, mail_msg, inreply, files):
#mail_msg, inreply = self.parse_message_poptres(message)
attachments = []
try:
for key in files:
f = files[key]
logger.info('FILE=%s' % f)
atch = Attachment()
atch.user = self.usr
atch.file.save(f.name, f)
atch.save()
attachments.append(atch)
except Exception as e:
logger.exception('cant parse attachment e=%s' % e)
mail_msg.attachments = attachments
if inreply:
try:
logger.info('this message=%s looking up message in reply to: %s' % (mail_msg.message_id, inreply))
refs = mail_msg.get_reference_ids
logger.info('REFERENCES = %s' % refs)
'''
Email RFC details the references header
http://tools.ietf.org/html/rfc2822#section-3.6.4
it is how we create a thread in this app
find all messages referred to in the references header
find the oldest one and add THIS message to its replies
'''
threads = self.messages.filter(message_id__in=refs).order_by('dated')
rthreads = filter(lambda x: x.request is not None, threads)
thread = rthreads[0] if len(rthreads) > 0 else threads[0] if threads.count() > 0 else None
if thread is None:
self.lookup_thread(mail_msg)
else:
if thread.request is not None:
thread = MailMessage.objects.filter(request__id=thread.request.id).order_by('dated')[0]
thread.replies.add(mail_msg)
#mail_msg.request = thread.request
mail_msg.save()
#make sure all messages know about each other
mail_msg.add_references(thread.references.all())
thread.add_references(mail_msg.references.all())
logger.info('FOUND thread message_id=%s' % thread.message_id)
logger.info('THREADS request %s' % thread.request)
logger.info('THREADS replies %s' % [mm.message_id for mm in thread.replies.all()])
mail_msg.reply_to = self.get_provisioned_email()
mail_msg.was_fwded = True#update the fact the message was forwarded
#self.lookup_thread(mail_msg)
cnt = thread.replies.all().filter(message_id__isnull=False).count()
#if this is the first reply
#if cnt == 1:
# status = thread.request.set_status("Response received (but not complete)")
except Exception as e:
logger.exception('tried to lookup root message and send but failed e=%s' % e)
self.lookup_thread(mail_msg)
else:
self.lookup_thread(mail_msg)
return mail_msg
def lookup_thread(self, mail_msg):
any_matches = [thread_pattern.findall(mail_msg.body), thread_pattern.findall(mail_msg.subject)]
for any_match in any_matches:
for match in any_match:
logger.debug("FOUND MATCH =%s" % match)
for req in Request.objects.filter(thread_lookup=match):
threads = self.get_threads(req.id)
logger.debug("LOOKUP CODE THREAD COUNT =%s" % len(threads))
if len(threads) > 0:#messages have been sent!
thread = threads[0]
thread.replies.add(mail_msg)
mail_msg.add_references(thread.references.all())
mail_msg.was_fwded = True
thread.add_references(mail_msg.references.all())
else:#message was never sent
mail_msg.request = req
mail_msg.save()
return mail_msg
def parse_attachments_poptres(self, content_disposition, part):
dispositions = content_disposition.strip().split(";")
if bool(content_disposition and dispositions[0].lower() == "attachment"):
file_data = part.get_payload(decode=True)
attachment = StringIO(file_data)
attachment.content_type = part.get_content_type()
attachment.size = len(file_data)
attachment.name = None
attachment.create_date = None
attachment.mod_date = None
attachment.read_date = None
for param in dispositions[1:]:
name, value = param.split("=")
name = name.lower().strip()
value = value.replace('"', '').strip()
if name == "filename":
attachment.name = value
elif name == "create-date":
attachment.create_date = value
elif name == "modification-date":
attachment.mod_date = value
elif name == "read-date":
attachment.read_date = value
attachment.seek(0, 2)
f = InMemoryUploadedFile(attachment, "", attachment.name, attachment.content_type, attachment.tell(), None)
atch = Attachment()
atch.user = self.usr
atch.file.save(attachment.name, f)
atch.save()
return atch
def get_provisioned_email(self):
if hasattr(settings, 'MG_ROUTE'):
# Fix this beore commit
thisaddress = "%s@%s.%s" % (self.usr.username.split("@")[0], settings.MG_ROUTE, settings.MG_DOMAIN)
else:
thisaddress = "%s@%s" % (self.usr.username.split("@")[0], settings.MG_DOMAIN)
logger.info("THIS address=%s" % thisaddress)
if self.provisioned_email is None or self.provisioned_email != thisaddress:
self.provisioned_email = thisaddress
self.save()
return self.provisioned_email
def get_registered_email(self):
return self.usr.email
| 41.349693 | 128 | 0.601039 |
237c9ee8c09c9ccf9f21f574ffec9a903f7b08e1 | 4,277 | py | Python | web/app.py | DewaldOosthuizen/article_project1 | 68522180239ff6986966b4fc9385c52b312d171f | [
"MIT"
] | 7 | 2019-03-27T06:14:38.000Z | 2020-08-03T19:14:35.000Z | web/app.py | DewaldOosthuizen/article_project1 | 68522180239ff6986966b4fc9385c52b312d171f | [
"MIT"
] | 1 | 2020-06-13T08:22:22.000Z | 2020-06-13T17:59:11.000Z | web/app.py | DewaldOosthuizen/article_project1 | 68522180239ff6986966b4fc9385c52b312d171f | [
"MIT"
] | 5 | 2019-09-18T19:25:24.000Z | 2021-09-20T20:32:53.000Z | # import functools
import bcrypt
from flask import Flask, jsonify, request
from flask_restful import Api, Resource
from pymongo import MongoClient
# print = functools.partial(print, flush=True)
app = Flask(__name__)
api = Api(app)
client = MongoClient("mongodb://my_db:27017")
db = client.projectDB
users = db["Users"]
invalid_user_json = {"status": 301, "msg": "Invalid Username"}
invalid_password_json = {"status": 302, "msg": "Invalid password"}
"""
HELPER FUNCTIONS
"""
def user_exist(username):
return users.find({"Username": username}).count() > 0
def verify_user(username, password):
if not user_exist(username):
return False
user_hashed_pw = users.find({
"Username": username
})[0]["Password"]
return bcrypt.checkpw(password.encode('utf8'), user_hashed_pw)
def get_user_messages(username):
# get the messages
return users.find({
"Username": username,
})[0]["Messages"]
"""
RESOURCES
"""
@api.representation('application/json')
class Hello(Resource):
"""
This is the Hello resource class
"""
def get(self):
return "Hello World!"
@api.representation('application/json')
class Register(Resource):
"""
This is the Register resource class
"""
def post(self):
# Get posted data from request
data = request.get_json()
username = data["username"]
password = data["password"]
# check if user exists
if user_exist(username):
return jsonify(invalid_user_json)
# encrypt password
hashed_pw = bcrypt.hashpw(password.encode('utf8'), bcrypt.gensalt())
# Insert record
users.insert({
"Username": username,
"Password": hashed_pw,
"Messages": []
})
# Return successful result
ret_json = {
"status": 200,
"msg": "Registration successful"
}
return jsonify(ret_json)
@api.representation('application/json')
class Retrieve(Resource):
"""
This is the Retrieve resource class
"""
def post(self):
# Get posted data from request
data = request.get_json()
# get data
username = data["username"]
password = data["password"]
# check if user exists
if not user_exist(username):
return jsonify(invalid_user_json)
# check password
correct_pw = verify_user(username, password)
if not correct_pw:
return jsonify(invalid_password_json)
# get the messages
messages = get_user_messages(username)
# Build successful response
ret_json = {
"status": 200,
"obj": messages
}
return jsonify(ret_json)
@api.representation('application/json')
class Save(Resource):
"""
This is the Save resource class
"""
def post(self):
# Get posted data from request
data = request.get_json()
# get data
username = data["username"]
password = data["password"]
message = data["message"]
# check if user exists
if not user_exist(username):
return jsonify(invalid_user_json)
# check password
correct_pw = verify_user(username, password)
if not correct_pw:
return jsonify(invalid_password_json)
if not message:
ret_json = {
"status": 303,
"msg": "Please supply a valid message"
}
return jsonify(ret_json)
# get the messages
messages = get_user_messages(username)
# add new message
messages.append(message)
# save the new user message
users.update({
"Username": username
}, {
"$set": {
"Messages": messages
}
})
ret_json = {
"status": 200,
"msg": "Message has been saved successfully"
}
return jsonify(ret_json)
api.add_resource(Hello, '/hello')
api.add_resource(Register, '/register')
api.add_resource(Retrieve, '/retrieve')
api.add_resource(Save, '/save')
if __name__ == "__main__":
app.run(host='0.0.0.0', debug=False, port=5000)
| 22.62963 | 76 | 0.589432 |
7dd4d00a8c45e99629a7a2b0a827f07a0c5ec9b5 | 85,144 | py | Python | docusign_esign/models/envelope_id.py | Thinkful/docusign-esign-python-client | d4e84468cfc502fc4a99277cd7440e2f42e66443 | [
"MIT"
] | null | null | null | docusign_esign/models/envelope_id.py | Thinkful/docusign-esign-python-client | d4e84468cfc502fc4a99277cd7440e2f42e66443 | [
"MIT"
] | null | null | null | docusign_esign/models/envelope_id.py | Thinkful/docusign-esign-python-client | d4e84468cfc502fc4a99277cd7440e2f42e66443 | [
"MIT"
] | null | null | null | # coding: utf-8
"""
DocuSign REST API
The DocuSign REST API provides you with a powerful, convenient, and simple Web services API for interacting with DocuSign. # noqa: E501
OpenAPI spec version: v2.1
Contact: devcenter@docusign.com
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re # noqa: F401
import six
class EnvelopeId(object):
"""NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
"""
"""
Attributes:
swagger_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.
"""
swagger_types = {
'anchor_allow_white_space_in_characters': 'str',
'anchor_allow_white_space_in_characters_metadata': 'PropertyMetadata',
'anchor_case_sensitive': 'str',
'anchor_case_sensitive_metadata': 'PropertyMetadata',
'anchor_horizontal_alignment': 'str',
'anchor_horizontal_alignment_metadata': 'PropertyMetadata',
'anchor_ignore_if_not_present': 'str',
'anchor_ignore_if_not_present_metadata': 'PropertyMetadata',
'anchor_match_whole_word': 'str',
'anchor_match_whole_word_metadata': 'PropertyMetadata',
'anchor_string': 'str',
'anchor_string_metadata': 'PropertyMetadata',
'anchor_tab_processor_version': 'str',
'anchor_tab_processor_version_metadata': 'PropertyMetadata',
'anchor_units': 'str',
'anchor_units_metadata': 'PropertyMetadata',
'anchor_x_offset': 'str',
'anchor_x_offset_metadata': 'PropertyMetadata',
'anchor_y_offset': 'str',
'anchor_y_offset_metadata': 'PropertyMetadata',
'bold': 'str',
'bold_metadata': 'PropertyMetadata',
'conditional_parent_label': 'str',
'conditional_parent_label_metadata': 'PropertyMetadata',
'conditional_parent_value': 'str',
'conditional_parent_value_metadata': 'PropertyMetadata',
'custom_tab_id': 'str',
'custom_tab_id_metadata': 'PropertyMetadata',
'document_id': 'str',
'document_id_metadata': 'PropertyMetadata',
'error_details': 'ErrorDetails',
'font': 'str',
'font_color': 'str',
'font_color_metadata': 'PropertyMetadata',
'font_metadata': 'PropertyMetadata',
'font_size': 'str',
'font_size_metadata': 'PropertyMetadata',
'form_order': 'str',
'form_order_metadata': 'PropertyMetadata',
'form_page_label': 'str',
'form_page_label_metadata': 'PropertyMetadata',
'form_page_number': 'str',
'form_page_number_metadata': 'PropertyMetadata',
'height': 'str',
'height_metadata': 'PropertyMetadata',
'italic': 'str',
'italic_metadata': 'PropertyMetadata',
'locale_policy': 'LocalePolicyTab',
'merge_field': 'MergeField',
'merge_field_xml': 'str',
'name': 'str',
'name_metadata': 'PropertyMetadata',
'page_number': 'str',
'page_number_metadata': 'PropertyMetadata',
'recipient_id': 'str',
'recipient_id_guid': 'str',
'recipient_id_guid_metadata': 'PropertyMetadata',
'recipient_id_metadata': 'PropertyMetadata',
'smart_contract_information': 'SmartContractInformation',
'source': 'str',
'status': 'str',
'status_metadata': 'PropertyMetadata',
'tab_group_labels': 'list[str]',
'tab_group_labels_metadata': 'PropertyMetadata',
'tab_id': 'str',
'tab_id_metadata': 'PropertyMetadata',
'tab_label': 'str',
'tab_label_metadata': 'PropertyMetadata',
'tab_order': 'str',
'tab_order_metadata': 'PropertyMetadata',
'tab_type': 'str',
'tab_type_metadata': 'PropertyMetadata',
'template_locked': 'str',
'template_locked_metadata': 'PropertyMetadata',
'template_required': 'str',
'template_required_metadata': 'PropertyMetadata',
'tooltip': 'str',
'tool_tip_metadata': 'PropertyMetadata',
'underline': 'str',
'underline_metadata': 'PropertyMetadata',
'width': 'str',
'width_metadata': 'PropertyMetadata',
'x_position': 'str',
'x_position_metadata': 'PropertyMetadata',
'y_position': 'str',
'y_position_metadata': 'PropertyMetadata'
}
attribute_map = {
'anchor_allow_white_space_in_characters': 'anchorAllowWhiteSpaceInCharacters',
'anchor_allow_white_space_in_characters_metadata': 'anchorAllowWhiteSpaceInCharactersMetadata',
'anchor_case_sensitive': 'anchorCaseSensitive',
'anchor_case_sensitive_metadata': 'anchorCaseSensitiveMetadata',
'anchor_horizontal_alignment': 'anchorHorizontalAlignment',
'anchor_horizontal_alignment_metadata': 'anchorHorizontalAlignmentMetadata',
'anchor_ignore_if_not_present': 'anchorIgnoreIfNotPresent',
'anchor_ignore_if_not_present_metadata': 'anchorIgnoreIfNotPresentMetadata',
'anchor_match_whole_word': 'anchorMatchWholeWord',
'anchor_match_whole_word_metadata': 'anchorMatchWholeWordMetadata',
'anchor_string': 'anchorString',
'anchor_string_metadata': 'anchorStringMetadata',
'anchor_tab_processor_version': 'anchorTabProcessorVersion',
'anchor_tab_processor_version_metadata': 'anchorTabProcessorVersionMetadata',
'anchor_units': 'anchorUnits',
'anchor_units_metadata': 'anchorUnitsMetadata',
'anchor_x_offset': 'anchorXOffset',
'anchor_x_offset_metadata': 'anchorXOffsetMetadata',
'anchor_y_offset': 'anchorYOffset',
'anchor_y_offset_metadata': 'anchorYOffsetMetadata',
'bold': 'bold',
'bold_metadata': 'boldMetadata',
'conditional_parent_label': 'conditionalParentLabel',
'conditional_parent_label_metadata': 'conditionalParentLabelMetadata',
'conditional_parent_value': 'conditionalParentValue',
'conditional_parent_value_metadata': 'conditionalParentValueMetadata',
'custom_tab_id': 'customTabId',
'custom_tab_id_metadata': 'customTabIdMetadata',
'document_id': 'documentId',
'document_id_metadata': 'documentIdMetadata',
'error_details': 'errorDetails',
'font': 'font',
'font_color': 'fontColor',
'font_color_metadata': 'fontColorMetadata',
'font_metadata': 'fontMetadata',
'font_size': 'fontSize',
'font_size_metadata': 'fontSizeMetadata',
'form_order': 'formOrder',
'form_order_metadata': 'formOrderMetadata',
'form_page_label': 'formPageLabel',
'form_page_label_metadata': 'formPageLabelMetadata',
'form_page_number': 'formPageNumber',
'form_page_number_metadata': 'formPageNumberMetadata',
'height': 'height',
'height_metadata': 'heightMetadata',
'italic': 'italic',
'italic_metadata': 'italicMetadata',
'locale_policy': 'localePolicy',
'merge_field': 'mergeField',
'merge_field_xml': 'mergeFieldXml',
'name': 'name',
'name_metadata': 'nameMetadata',
'page_number': 'pageNumber',
'page_number_metadata': 'pageNumberMetadata',
'recipient_id': 'recipientId',
'recipient_id_guid': 'recipientIdGuid',
'recipient_id_guid_metadata': 'recipientIdGuidMetadata',
'recipient_id_metadata': 'recipientIdMetadata',
'smart_contract_information': 'smartContractInformation',
'source': 'source',
'status': 'status',
'status_metadata': 'statusMetadata',
'tab_group_labels': 'tabGroupLabels',
'tab_group_labels_metadata': 'tabGroupLabelsMetadata',
'tab_id': 'tabId',
'tab_id_metadata': 'tabIdMetadata',
'tab_label': 'tabLabel',
'tab_label_metadata': 'tabLabelMetadata',
'tab_order': 'tabOrder',
'tab_order_metadata': 'tabOrderMetadata',
'tab_type': 'tabType',
'tab_type_metadata': 'tabTypeMetadata',
'template_locked': 'templateLocked',
'template_locked_metadata': 'templateLockedMetadata',
'template_required': 'templateRequired',
'template_required_metadata': 'templateRequiredMetadata',
'tooltip': 'tooltip',
'tool_tip_metadata': 'toolTipMetadata',
'underline': 'underline',
'underline_metadata': 'underlineMetadata',
'width': 'width',
'width_metadata': 'widthMetadata',
'x_position': 'xPosition',
'x_position_metadata': 'xPositionMetadata',
'y_position': 'yPosition',
'y_position_metadata': 'yPositionMetadata'
}
def __init__(self, anchor_allow_white_space_in_characters=None, anchor_allow_white_space_in_characters_metadata=None, anchor_case_sensitive=None, anchor_case_sensitive_metadata=None, anchor_horizontal_alignment=None, anchor_horizontal_alignment_metadata=None, anchor_ignore_if_not_present=None, anchor_ignore_if_not_present_metadata=None, anchor_match_whole_word=None, anchor_match_whole_word_metadata=None, anchor_string=None, anchor_string_metadata=None, anchor_tab_processor_version=None, anchor_tab_processor_version_metadata=None, anchor_units=None, anchor_units_metadata=None, anchor_x_offset=None, anchor_x_offset_metadata=None, anchor_y_offset=None, anchor_y_offset_metadata=None, bold=None, bold_metadata=None, conditional_parent_label=None, conditional_parent_label_metadata=None, conditional_parent_value=None, conditional_parent_value_metadata=None, custom_tab_id=None, custom_tab_id_metadata=None, document_id=None, document_id_metadata=None, error_details=None, font=None, font_color=None, font_color_metadata=None, font_metadata=None, font_size=None, font_size_metadata=None, form_order=None, form_order_metadata=None, form_page_label=None, form_page_label_metadata=None, form_page_number=None, form_page_number_metadata=None, height=None, height_metadata=None, italic=None, italic_metadata=None, locale_policy=None, merge_field=None, merge_field_xml=None, name=None, name_metadata=None, page_number=None, page_number_metadata=None, recipient_id=None, recipient_id_guid=None, recipient_id_guid_metadata=None, recipient_id_metadata=None, smart_contract_information=None, source=None, status=None, status_metadata=None, tab_group_labels=None, tab_group_labels_metadata=None, tab_id=None, tab_id_metadata=None, tab_label=None, tab_label_metadata=None, tab_order=None, tab_order_metadata=None, tab_type=None, tab_type_metadata=None, template_locked=None, template_locked_metadata=None, template_required=None, template_required_metadata=None, tooltip=None, tool_tip_metadata=None, underline=None, underline_metadata=None, width=None, width_metadata=None, x_position=None, x_position_metadata=None, y_position=None, y_position_metadata=None): # noqa: E501
"""EnvelopeId - a model defined in Swagger""" # noqa: E501
self._anchor_allow_white_space_in_characters = None
self._anchor_allow_white_space_in_characters_metadata = None
self._anchor_case_sensitive = None
self._anchor_case_sensitive_metadata = None
self._anchor_horizontal_alignment = None
self._anchor_horizontal_alignment_metadata = None
self._anchor_ignore_if_not_present = None
self._anchor_ignore_if_not_present_metadata = None
self._anchor_match_whole_word = None
self._anchor_match_whole_word_metadata = None
self._anchor_string = None
self._anchor_string_metadata = None
self._anchor_tab_processor_version = None
self._anchor_tab_processor_version_metadata = None
self._anchor_units = None
self._anchor_units_metadata = None
self._anchor_x_offset = None
self._anchor_x_offset_metadata = None
self._anchor_y_offset = None
self._anchor_y_offset_metadata = None
self._bold = None
self._bold_metadata = None
self._conditional_parent_label = None
self._conditional_parent_label_metadata = None
self._conditional_parent_value = None
self._conditional_parent_value_metadata = None
self._custom_tab_id = None
self._custom_tab_id_metadata = None
self._document_id = None
self._document_id_metadata = None
self._error_details = None
self._font = None
self._font_color = None
self._font_color_metadata = None
self._font_metadata = None
self._font_size = None
self._font_size_metadata = None
self._form_order = None
self._form_order_metadata = None
self._form_page_label = None
self._form_page_label_metadata = None
self._form_page_number = None
self._form_page_number_metadata = None
self._height = None
self._height_metadata = None
self._italic = None
self._italic_metadata = None
self._locale_policy = None
self._merge_field = None
self._merge_field_xml = None
self._name = None
self._name_metadata = None
self._page_number = None
self._page_number_metadata = None
self._recipient_id = None
self._recipient_id_guid = None
self._recipient_id_guid_metadata = None
self._recipient_id_metadata = None
self._smart_contract_information = None
self._source = None
self._status = None
self._status_metadata = None
self._tab_group_labels = None
self._tab_group_labels_metadata = None
self._tab_id = None
self._tab_id_metadata = None
self._tab_label = None
self._tab_label_metadata = None
self._tab_order = None
self._tab_order_metadata = None
self._tab_type = None
self._tab_type_metadata = None
self._template_locked = None
self._template_locked_metadata = None
self._template_required = None
self._template_required_metadata = None
self._tooltip = None
self._tool_tip_metadata = None
self._underline = None
self._underline_metadata = None
self._width = None
self._width_metadata = None
self._x_position = None
self._x_position_metadata = None
self._y_position = None
self._y_position_metadata = None
self.discriminator = None
if anchor_allow_white_space_in_characters is not None:
self.anchor_allow_white_space_in_characters = anchor_allow_white_space_in_characters
if anchor_allow_white_space_in_characters_metadata is not None:
self.anchor_allow_white_space_in_characters_metadata = anchor_allow_white_space_in_characters_metadata
if anchor_case_sensitive is not None:
self.anchor_case_sensitive = anchor_case_sensitive
if anchor_case_sensitive_metadata is not None:
self.anchor_case_sensitive_metadata = anchor_case_sensitive_metadata
if anchor_horizontal_alignment is not None:
self.anchor_horizontal_alignment = anchor_horizontal_alignment
if anchor_horizontal_alignment_metadata is not None:
self.anchor_horizontal_alignment_metadata = anchor_horizontal_alignment_metadata
if anchor_ignore_if_not_present is not None:
self.anchor_ignore_if_not_present = anchor_ignore_if_not_present
if anchor_ignore_if_not_present_metadata is not None:
self.anchor_ignore_if_not_present_metadata = anchor_ignore_if_not_present_metadata
if anchor_match_whole_word is not None:
self.anchor_match_whole_word = anchor_match_whole_word
if anchor_match_whole_word_metadata is not None:
self.anchor_match_whole_word_metadata = anchor_match_whole_word_metadata
if anchor_string is not None:
self.anchor_string = anchor_string
if anchor_string_metadata is not None:
self.anchor_string_metadata = anchor_string_metadata
if anchor_tab_processor_version is not None:
self.anchor_tab_processor_version = anchor_tab_processor_version
if anchor_tab_processor_version_metadata is not None:
self.anchor_tab_processor_version_metadata = anchor_tab_processor_version_metadata
if anchor_units is not None:
self.anchor_units = anchor_units
if anchor_units_metadata is not None:
self.anchor_units_metadata = anchor_units_metadata
if anchor_x_offset is not None:
self.anchor_x_offset = anchor_x_offset
if anchor_x_offset_metadata is not None:
self.anchor_x_offset_metadata = anchor_x_offset_metadata
if anchor_y_offset is not None:
self.anchor_y_offset = anchor_y_offset
if anchor_y_offset_metadata is not None:
self.anchor_y_offset_metadata = anchor_y_offset_metadata
if bold is not None:
self.bold = bold
if bold_metadata is not None:
self.bold_metadata = bold_metadata
if conditional_parent_label is not None:
self.conditional_parent_label = conditional_parent_label
if conditional_parent_label_metadata is not None:
self.conditional_parent_label_metadata = conditional_parent_label_metadata
if conditional_parent_value is not None:
self.conditional_parent_value = conditional_parent_value
if conditional_parent_value_metadata is not None:
self.conditional_parent_value_metadata = conditional_parent_value_metadata
if custom_tab_id is not None:
self.custom_tab_id = custom_tab_id
if custom_tab_id_metadata is not None:
self.custom_tab_id_metadata = custom_tab_id_metadata
if document_id is not None:
self.document_id = document_id
if document_id_metadata is not None:
self.document_id_metadata = document_id_metadata
if error_details is not None:
self.error_details = error_details
if font is not None:
self.font = font
if font_color is not None:
self.font_color = font_color
if font_color_metadata is not None:
self.font_color_metadata = font_color_metadata
if font_metadata is not None:
self.font_metadata = font_metadata
if font_size is not None:
self.font_size = font_size
if font_size_metadata is not None:
self.font_size_metadata = font_size_metadata
if form_order is not None:
self.form_order = form_order
if form_order_metadata is not None:
self.form_order_metadata = form_order_metadata
if form_page_label is not None:
self.form_page_label = form_page_label
if form_page_label_metadata is not None:
self.form_page_label_metadata = form_page_label_metadata
if form_page_number is not None:
self.form_page_number = form_page_number
if form_page_number_metadata is not None:
self.form_page_number_metadata = form_page_number_metadata
if height is not None:
self.height = height
if height_metadata is not None:
self.height_metadata = height_metadata
if italic is not None:
self.italic = italic
if italic_metadata is not None:
self.italic_metadata = italic_metadata
if locale_policy is not None:
self.locale_policy = locale_policy
if merge_field is not None:
self.merge_field = merge_field
if merge_field_xml is not None:
self.merge_field_xml = merge_field_xml
if name is not None:
self.name = name
if name_metadata is not None:
self.name_metadata = name_metadata
if page_number is not None:
self.page_number = page_number
if page_number_metadata is not None:
self.page_number_metadata = page_number_metadata
if recipient_id is not None:
self.recipient_id = recipient_id
if recipient_id_guid is not None:
self.recipient_id_guid = recipient_id_guid
if recipient_id_guid_metadata is not None:
self.recipient_id_guid_metadata = recipient_id_guid_metadata
if recipient_id_metadata is not None:
self.recipient_id_metadata = recipient_id_metadata
if smart_contract_information is not None:
self.smart_contract_information = smart_contract_information
if source is not None:
self.source = source
if status is not None:
self.status = status
if status_metadata is not None:
self.status_metadata = status_metadata
if tab_group_labels is not None:
self.tab_group_labels = tab_group_labels
if tab_group_labels_metadata is not None:
self.tab_group_labels_metadata = tab_group_labels_metadata
if tab_id is not None:
self.tab_id = tab_id
if tab_id_metadata is not None:
self.tab_id_metadata = tab_id_metadata
if tab_label is not None:
self.tab_label = tab_label
if tab_label_metadata is not None:
self.tab_label_metadata = tab_label_metadata
if tab_order is not None:
self.tab_order = tab_order
if tab_order_metadata is not None:
self.tab_order_metadata = tab_order_metadata
if tab_type is not None:
self.tab_type = tab_type
if tab_type_metadata is not None:
self.tab_type_metadata = tab_type_metadata
if template_locked is not None:
self.template_locked = template_locked
if template_locked_metadata is not None:
self.template_locked_metadata = template_locked_metadata
if template_required is not None:
self.template_required = template_required
if template_required_metadata is not None:
self.template_required_metadata = template_required_metadata
if tooltip is not None:
self.tooltip = tooltip
if tool_tip_metadata is not None:
self.tool_tip_metadata = tool_tip_metadata
if underline is not None:
self.underline = underline
if underline_metadata is not None:
self.underline_metadata = underline_metadata
if width is not None:
self.width = width
if width_metadata is not None:
self.width_metadata = width_metadata
if x_position is not None:
self.x_position = x_position
if x_position_metadata is not None:
self.x_position_metadata = x_position_metadata
if y_position is not None:
self.y_position = y_position
if y_position_metadata is not None:
self.y_position_metadata = y_position_metadata
@property
def anchor_allow_white_space_in_characters(self):
"""Gets the anchor_allow_white_space_in_characters of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The anchor_allow_white_space_in_characters of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_allow_white_space_in_characters
@anchor_allow_white_space_in_characters.setter
def anchor_allow_white_space_in_characters(self, anchor_allow_white_space_in_characters):
"""Sets the anchor_allow_white_space_in_characters of this EnvelopeId.
# noqa: E501
:param anchor_allow_white_space_in_characters: The anchor_allow_white_space_in_characters of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_allow_white_space_in_characters = anchor_allow_white_space_in_characters
@property
def anchor_allow_white_space_in_characters_metadata(self):
"""Gets the anchor_allow_white_space_in_characters_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_allow_white_space_in_characters_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_allow_white_space_in_characters_metadata
@anchor_allow_white_space_in_characters_metadata.setter
def anchor_allow_white_space_in_characters_metadata(self, anchor_allow_white_space_in_characters_metadata):
"""Sets the anchor_allow_white_space_in_characters_metadata of this EnvelopeId.
:param anchor_allow_white_space_in_characters_metadata: The anchor_allow_white_space_in_characters_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_allow_white_space_in_characters_metadata = anchor_allow_white_space_in_characters_metadata
@property
def anchor_case_sensitive(self):
"""Gets the anchor_case_sensitive of this EnvelopeId. # noqa: E501
When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**. # noqa: E501
:return: The anchor_case_sensitive of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_case_sensitive
@anchor_case_sensitive.setter
def anchor_case_sensitive(self, anchor_case_sensitive):
"""Sets the anchor_case_sensitive of this EnvelopeId.
When set to **true**, the anchor string does not consider case when matching strings in the document. The default value is **true**. # noqa: E501
:param anchor_case_sensitive: The anchor_case_sensitive of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_case_sensitive = anchor_case_sensitive
@property
def anchor_case_sensitive_metadata(self):
"""Gets the anchor_case_sensitive_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_case_sensitive_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_case_sensitive_metadata
@anchor_case_sensitive_metadata.setter
def anchor_case_sensitive_metadata(self, anchor_case_sensitive_metadata):
"""Sets the anchor_case_sensitive_metadata of this EnvelopeId.
:param anchor_case_sensitive_metadata: The anchor_case_sensitive_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_case_sensitive_metadata = anchor_case_sensitive_metadata
@property
def anchor_horizontal_alignment(self):
"""Gets the anchor_horizontal_alignment of this EnvelopeId. # noqa: E501
Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**. # noqa: E501
:return: The anchor_horizontal_alignment of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_horizontal_alignment
@anchor_horizontal_alignment.setter
def anchor_horizontal_alignment(self, anchor_horizontal_alignment):
"""Sets the anchor_horizontal_alignment of this EnvelopeId.
Specifies the alignment of anchor tabs with anchor strings. Possible values are **left** or **right**. The default value is **left**. # noqa: E501
:param anchor_horizontal_alignment: The anchor_horizontal_alignment of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_horizontal_alignment = anchor_horizontal_alignment
@property
def anchor_horizontal_alignment_metadata(self):
"""Gets the anchor_horizontal_alignment_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_horizontal_alignment_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_horizontal_alignment_metadata
@anchor_horizontal_alignment_metadata.setter
def anchor_horizontal_alignment_metadata(self, anchor_horizontal_alignment_metadata):
"""Sets the anchor_horizontal_alignment_metadata of this EnvelopeId.
:param anchor_horizontal_alignment_metadata: The anchor_horizontal_alignment_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_horizontal_alignment_metadata = anchor_horizontal_alignment_metadata
@property
def anchor_ignore_if_not_present(self):
"""Gets the anchor_ignore_if_not_present of this EnvelopeId. # noqa: E501
When set to **true**, this tab is ignored if anchorString is not found in the document. # noqa: E501
:return: The anchor_ignore_if_not_present of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_ignore_if_not_present
@anchor_ignore_if_not_present.setter
def anchor_ignore_if_not_present(self, anchor_ignore_if_not_present):
"""Sets the anchor_ignore_if_not_present of this EnvelopeId.
When set to **true**, this tab is ignored if anchorString is not found in the document. # noqa: E501
:param anchor_ignore_if_not_present: The anchor_ignore_if_not_present of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_ignore_if_not_present = anchor_ignore_if_not_present
@property
def anchor_ignore_if_not_present_metadata(self):
"""Gets the anchor_ignore_if_not_present_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_ignore_if_not_present_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_ignore_if_not_present_metadata
@anchor_ignore_if_not_present_metadata.setter
def anchor_ignore_if_not_present_metadata(self, anchor_ignore_if_not_present_metadata):
"""Sets the anchor_ignore_if_not_present_metadata of this EnvelopeId.
:param anchor_ignore_if_not_present_metadata: The anchor_ignore_if_not_present_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_ignore_if_not_present_metadata = anchor_ignore_if_not_present_metadata
@property
def anchor_match_whole_word(self):
"""Gets the anchor_match_whole_word of this EnvelopeId. # noqa: E501
When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**. # noqa: E501
:return: The anchor_match_whole_word of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_match_whole_word
@anchor_match_whole_word.setter
def anchor_match_whole_word(self, anchor_match_whole_word):
"""Sets the anchor_match_whole_word of this EnvelopeId.
When set to **true**, the anchor string in this tab matches whole words only (strings embedded in other strings are ignored.) The default value is **true**. # noqa: E501
:param anchor_match_whole_word: The anchor_match_whole_word of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_match_whole_word = anchor_match_whole_word
@property
def anchor_match_whole_word_metadata(self):
"""Gets the anchor_match_whole_word_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_match_whole_word_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_match_whole_word_metadata
@anchor_match_whole_word_metadata.setter
def anchor_match_whole_word_metadata(self, anchor_match_whole_word_metadata):
"""Sets the anchor_match_whole_word_metadata of this EnvelopeId.
:param anchor_match_whole_word_metadata: The anchor_match_whole_word_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_match_whole_word_metadata = anchor_match_whole_word_metadata
@property
def anchor_string(self):
"""Gets the anchor_string of this EnvelopeId. # noqa: E501
Anchor text information for a radio button. # noqa: E501
:return: The anchor_string of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_string
@anchor_string.setter
def anchor_string(self, anchor_string):
"""Sets the anchor_string of this EnvelopeId.
Anchor text information for a radio button. # noqa: E501
:param anchor_string: The anchor_string of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_string = anchor_string
@property
def anchor_string_metadata(self):
"""Gets the anchor_string_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_string_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_string_metadata
@anchor_string_metadata.setter
def anchor_string_metadata(self, anchor_string_metadata):
"""Sets the anchor_string_metadata of this EnvelopeId.
:param anchor_string_metadata: The anchor_string_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_string_metadata = anchor_string_metadata
@property
def anchor_tab_processor_version(self):
"""Gets the anchor_tab_processor_version of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The anchor_tab_processor_version of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_tab_processor_version
@anchor_tab_processor_version.setter
def anchor_tab_processor_version(self, anchor_tab_processor_version):
"""Sets the anchor_tab_processor_version of this EnvelopeId.
# noqa: E501
:param anchor_tab_processor_version: The anchor_tab_processor_version of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_tab_processor_version = anchor_tab_processor_version
@property
def anchor_tab_processor_version_metadata(self):
"""Gets the anchor_tab_processor_version_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_tab_processor_version_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_tab_processor_version_metadata
@anchor_tab_processor_version_metadata.setter
def anchor_tab_processor_version_metadata(self, anchor_tab_processor_version_metadata):
"""Sets the anchor_tab_processor_version_metadata of this EnvelopeId.
:param anchor_tab_processor_version_metadata: The anchor_tab_processor_version_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_tab_processor_version_metadata = anchor_tab_processor_version_metadata
@property
def anchor_units(self):
"""Gets the anchor_units of this EnvelopeId. # noqa: E501
Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches. # noqa: E501
:return: The anchor_units of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_units
@anchor_units.setter
def anchor_units(self, anchor_units):
"""Sets the anchor_units of this EnvelopeId.
Specifies units of the X and Y offset. Units could be pixels, millimeters, centimeters, or inches. # noqa: E501
:param anchor_units: The anchor_units of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_units = anchor_units
@property
def anchor_units_metadata(self):
"""Gets the anchor_units_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_units_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_units_metadata
@anchor_units_metadata.setter
def anchor_units_metadata(self, anchor_units_metadata):
"""Sets the anchor_units_metadata of this EnvelopeId.
:param anchor_units_metadata: The anchor_units_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_units_metadata = anchor_units_metadata
@property
def anchor_x_offset(self):
"""Gets the anchor_x_offset of this EnvelopeId. # noqa: E501
Specifies the X axis location of the tab, in anchorUnits, relative to the anchorString. # noqa: E501
:return: The anchor_x_offset of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_x_offset
@anchor_x_offset.setter
def anchor_x_offset(self, anchor_x_offset):
"""Sets the anchor_x_offset of this EnvelopeId.
Specifies the X axis location of the tab, in anchorUnits, relative to the anchorString. # noqa: E501
:param anchor_x_offset: The anchor_x_offset of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_x_offset = anchor_x_offset
@property
def anchor_x_offset_metadata(self):
"""Gets the anchor_x_offset_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_x_offset_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_x_offset_metadata
@anchor_x_offset_metadata.setter
def anchor_x_offset_metadata(self, anchor_x_offset_metadata):
"""Sets the anchor_x_offset_metadata of this EnvelopeId.
:param anchor_x_offset_metadata: The anchor_x_offset_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_x_offset_metadata = anchor_x_offset_metadata
@property
def anchor_y_offset(self):
"""Gets the anchor_y_offset of this EnvelopeId. # noqa: E501
Specifies the Y axis location of the tab, in anchorUnits, relative to the anchorString. # noqa: E501
:return: The anchor_y_offset of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._anchor_y_offset
@anchor_y_offset.setter
def anchor_y_offset(self, anchor_y_offset):
"""Sets the anchor_y_offset of this EnvelopeId.
Specifies the Y axis location of the tab, in anchorUnits, relative to the anchorString. # noqa: E501
:param anchor_y_offset: The anchor_y_offset of this EnvelopeId. # noqa: E501
:type: str
"""
self._anchor_y_offset = anchor_y_offset
@property
def anchor_y_offset_metadata(self):
"""Gets the anchor_y_offset_metadata of this EnvelopeId. # noqa: E501
:return: The anchor_y_offset_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._anchor_y_offset_metadata
@anchor_y_offset_metadata.setter
def anchor_y_offset_metadata(self, anchor_y_offset_metadata):
"""Sets the anchor_y_offset_metadata of this EnvelopeId.
:param anchor_y_offset_metadata: The anchor_y_offset_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._anchor_y_offset_metadata = anchor_y_offset_metadata
@property
def bold(self):
"""Gets the bold of this EnvelopeId. # noqa: E501
When set to **true**, the information in the tab is bold. # noqa: E501
:return: The bold of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._bold
@bold.setter
def bold(self, bold):
"""Sets the bold of this EnvelopeId.
When set to **true**, the information in the tab is bold. # noqa: E501
:param bold: The bold of this EnvelopeId. # noqa: E501
:type: str
"""
self._bold = bold
@property
def bold_metadata(self):
"""Gets the bold_metadata of this EnvelopeId. # noqa: E501
:return: The bold_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._bold_metadata
@bold_metadata.setter
def bold_metadata(self, bold_metadata):
"""Sets the bold_metadata of this EnvelopeId.
:param bold_metadata: The bold_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._bold_metadata = bold_metadata
@property
def conditional_parent_label(self):
"""Gets the conditional_parent_label of this EnvelopeId. # noqa: E501
For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility. # noqa: E501
:return: The conditional_parent_label of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._conditional_parent_label
@conditional_parent_label.setter
def conditional_parent_label(self, conditional_parent_label):
"""Sets the conditional_parent_label of this EnvelopeId.
For conditional fields this is the TabLabel of the parent tab that controls this tab's visibility. # noqa: E501
:param conditional_parent_label: The conditional_parent_label of this EnvelopeId. # noqa: E501
:type: str
"""
self._conditional_parent_label = conditional_parent_label
@property
def conditional_parent_label_metadata(self):
"""Gets the conditional_parent_label_metadata of this EnvelopeId. # noqa: E501
:return: The conditional_parent_label_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._conditional_parent_label_metadata
@conditional_parent_label_metadata.setter
def conditional_parent_label_metadata(self, conditional_parent_label_metadata):
"""Sets the conditional_parent_label_metadata of this EnvelopeId.
:param conditional_parent_label_metadata: The conditional_parent_label_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._conditional_parent_label_metadata = conditional_parent_label_metadata
@property
def conditional_parent_value(self):
"""Gets the conditional_parent_value of this EnvelopeId. # noqa: E501
For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active. # noqa: E501
:return: The conditional_parent_value of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._conditional_parent_value
@conditional_parent_value.setter
def conditional_parent_value(self, conditional_parent_value):
"""Sets the conditional_parent_value of this EnvelopeId.
For conditional fields, this is the value of the parent tab that controls the tab's visibility. If the parent tab is a Checkbox, Radio button, Optional Signature, or Optional Initial use \"on\" as the value to show that the parent tab is active. # noqa: E501
:param conditional_parent_value: The conditional_parent_value of this EnvelopeId. # noqa: E501
:type: str
"""
self._conditional_parent_value = conditional_parent_value
@property
def conditional_parent_value_metadata(self):
"""Gets the conditional_parent_value_metadata of this EnvelopeId. # noqa: E501
:return: The conditional_parent_value_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._conditional_parent_value_metadata
@conditional_parent_value_metadata.setter
def conditional_parent_value_metadata(self, conditional_parent_value_metadata):
"""Sets the conditional_parent_value_metadata of this EnvelopeId.
:param conditional_parent_value_metadata: The conditional_parent_value_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._conditional_parent_value_metadata = conditional_parent_value_metadata
@property
def custom_tab_id(self):
"""Gets the custom_tab_id of this EnvelopeId. # noqa: E501
The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties. # noqa: E501
:return: The custom_tab_id of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._custom_tab_id
@custom_tab_id.setter
def custom_tab_id(self, custom_tab_id):
"""Sets the custom_tab_id of this EnvelopeId.
The DocuSign generated custom tab ID for the custom tab to be applied. This can only be used when adding new tabs for a recipient. When used, the new tab inherits all the custom tab properties. # noqa: E501
:param custom_tab_id: The custom_tab_id of this EnvelopeId. # noqa: E501
:type: str
"""
self._custom_tab_id = custom_tab_id
@property
def custom_tab_id_metadata(self):
"""Gets the custom_tab_id_metadata of this EnvelopeId. # noqa: E501
:return: The custom_tab_id_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._custom_tab_id_metadata
@custom_tab_id_metadata.setter
def custom_tab_id_metadata(self, custom_tab_id_metadata):
"""Sets the custom_tab_id_metadata of this EnvelopeId.
:param custom_tab_id_metadata: The custom_tab_id_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._custom_tab_id_metadata = custom_tab_id_metadata
@property
def document_id(self):
"""Gets the document_id of this EnvelopeId. # noqa: E501
Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute. # noqa: E501
:return: The document_id of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._document_id
@document_id.setter
def document_id(self, document_id):
"""Sets the document_id of this EnvelopeId.
Specifies the document ID number that the tab is placed on. This must refer to an existing Document's ID attribute. # noqa: E501
:param document_id: The document_id of this EnvelopeId. # noqa: E501
:type: str
"""
self._document_id = document_id
@property
def document_id_metadata(self):
"""Gets the document_id_metadata of this EnvelopeId. # noqa: E501
:return: The document_id_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._document_id_metadata
@document_id_metadata.setter
def document_id_metadata(self, document_id_metadata):
"""Sets the document_id_metadata of this EnvelopeId.
:param document_id_metadata: The document_id_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._document_id_metadata = document_id_metadata
@property
def error_details(self):
"""Gets the error_details of this EnvelopeId. # noqa: E501
:return: The error_details of this EnvelopeId. # noqa: E501
:rtype: ErrorDetails
"""
return self._error_details
@error_details.setter
def error_details(self, error_details):
"""Sets the error_details of this EnvelopeId.
:param error_details: The error_details of this EnvelopeId. # noqa: E501
:type: ErrorDetails
"""
self._error_details = error_details
@property
def font(self):
"""Gets the font of this EnvelopeId. # noqa: E501
The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default. # noqa: E501
:return: The font of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._font
@font.setter
def font(self, font):
"""Sets the font of this EnvelopeId.
The font to be used for the tab value. Supported Fonts: Arial, Arial, ArialNarrow, Calibri, CourierNew, Garamond, Georgia, Helvetica, LucidaConsole, Tahoma, TimesNewRoman, Trebuchet, Verdana, MSGothic, MSMincho, Default. # noqa: E501
:param font: The font of this EnvelopeId. # noqa: E501
:type: str
"""
self._font = font
@property
def font_color(self):
"""Gets the font_color of this EnvelopeId. # noqa: E501
The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White. # noqa: E501
:return: The font_color of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._font_color
@font_color.setter
def font_color(self, font_color):
"""Sets the font_color of this EnvelopeId.
The font color used for the information in the tab. Possible values are: Black, BrightBlue, BrightRed, DarkGreen, DarkRed, Gold, Green, NavyBlue, Purple, or White. # noqa: E501
:param font_color: The font_color of this EnvelopeId. # noqa: E501
:type: str
"""
self._font_color = font_color
@property
def font_color_metadata(self):
"""Gets the font_color_metadata of this EnvelopeId. # noqa: E501
:return: The font_color_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._font_color_metadata
@font_color_metadata.setter
def font_color_metadata(self, font_color_metadata):
"""Sets the font_color_metadata of this EnvelopeId.
:param font_color_metadata: The font_color_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._font_color_metadata = font_color_metadata
@property
def font_metadata(self):
"""Gets the font_metadata of this EnvelopeId. # noqa: E501
:return: The font_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._font_metadata
@font_metadata.setter
def font_metadata(self, font_metadata):
"""Sets the font_metadata of this EnvelopeId.
:param font_metadata: The font_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._font_metadata = font_metadata
@property
def font_size(self):
"""Gets the font_size of this EnvelopeId. # noqa: E501
The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72. # noqa: E501
:return: The font_size of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._font_size
@font_size.setter
def font_size(self, font_size):
"""Sets the font_size of this EnvelopeId.
The font size used for the information in the tab. Possible values are: Size7, Size8, Size9, Size10, Size11, Size12, Size14, Size16, Size18, Size20, Size22, Size24, Size26, Size28, Size36, Size48, or Size72. # noqa: E501
:param font_size: The font_size of this EnvelopeId. # noqa: E501
:type: str
"""
self._font_size = font_size
@property
def font_size_metadata(self):
"""Gets the font_size_metadata of this EnvelopeId. # noqa: E501
:return: The font_size_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._font_size_metadata
@font_size_metadata.setter
def font_size_metadata(self, font_size_metadata):
"""Sets the font_size_metadata of this EnvelopeId.
:param font_size_metadata: The font_size_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._font_size_metadata = font_size_metadata
@property
def form_order(self):
"""Gets the form_order of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The form_order of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._form_order
@form_order.setter
def form_order(self, form_order):
"""Sets the form_order of this EnvelopeId.
# noqa: E501
:param form_order: The form_order of this EnvelopeId. # noqa: E501
:type: str
"""
self._form_order = form_order
@property
def form_order_metadata(self):
"""Gets the form_order_metadata of this EnvelopeId. # noqa: E501
:return: The form_order_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._form_order_metadata
@form_order_metadata.setter
def form_order_metadata(self, form_order_metadata):
"""Sets the form_order_metadata of this EnvelopeId.
:param form_order_metadata: The form_order_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._form_order_metadata = form_order_metadata
@property
def form_page_label(self):
"""Gets the form_page_label of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The form_page_label of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._form_page_label
@form_page_label.setter
def form_page_label(self, form_page_label):
"""Sets the form_page_label of this EnvelopeId.
# noqa: E501
:param form_page_label: The form_page_label of this EnvelopeId. # noqa: E501
:type: str
"""
self._form_page_label = form_page_label
@property
def form_page_label_metadata(self):
"""Gets the form_page_label_metadata of this EnvelopeId. # noqa: E501
:return: The form_page_label_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._form_page_label_metadata
@form_page_label_metadata.setter
def form_page_label_metadata(self, form_page_label_metadata):
"""Sets the form_page_label_metadata of this EnvelopeId.
:param form_page_label_metadata: The form_page_label_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._form_page_label_metadata = form_page_label_metadata
@property
def form_page_number(self):
"""Gets the form_page_number of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The form_page_number of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._form_page_number
@form_page_number.setter
def form_page_number(self, form_page_number):
"""Sets the form_page_number of this EnvelopeId.
# noqa: E501
:param form_page_number: The form_page_number of this EnvelopeId. # noqa: E501
:type: str
"""
self._form_page_number = form_page_number
@property
def form_page_number_metadata(self):
"""Gets the form_page_number_metadata of this EnvelopeId. # noqa: E501
:return: The form_page_number_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._form_page_number_metadata
@form_page_number_metadata.setter
def form_page_number_metadata(self, form_page_number_metadata):
"""Sets the form_page_number_metadata of this EnvelopeId.
:param form_page_number_metadata: The form_page_number_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._form_page_number_metadata = form_page_number_metadata
@property
def height(self):
"""Gets the height of this EnvelopeId. # noqa: E501
Height of the tab in pixels. # noqa: E501
:return: The height of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._height
@height.setter
def height(self, height):
"""Sets the height of this EnvelopeId.
Height of the tab in pixels. # noqa: E501
:param height: The height of this EnvelopeId. # noqa: E501
:type: str
"""
self._height = height
@property
def height_metadata(self):
"""Gets the height_metadata of this EnvelopeId. # noqa: E501
:return: The height_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._height_metadata
@height_metadata.setter
def height_metadata(self, height_metadata):
"""Sets the height_metadata of this EnvelopeId.
:param height_metadata: The height_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._height_metadata = height_metadata
@property
def italic(self):
"""Gets the italic of this EnvelopeId. # noqa: E501
When set to **true**, the information in the tab is italic. # noqa: E501
:return: The italic of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._italic
@italic.setter
def italic(self, italic):
"""Sets the italic of this EnvelopeId.
When set to **true**, the information in the tab is italic. # noqa: E501
:param italic: The italic of this EnvelopeId. # noqa: E501
:type: str
"""
self._italic = italic
@property
def italic_metadata(self):
"""Gets the italic_metadata of this EnvelopeId. # noqa: E501
:return: The italic_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._italic_metadata
@italic_metadata.setter
def italic_metadata(self, italic_metadata):
"""Sets the italic_metadata of this EnvelopeId.
:param italic_metadata: The italic_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._italic_metadata = italic_metadata
@property
def locale_policy(self):
"""Gets the locale_policy of this EnvelopeId. # noqa: E501
:return: The locale_policy of this EnvelopeId. # noqa: E501
:rtype: LocalePolicyTab
"""
return self._locale_policy
@locale_policy.setter
def locale_policy(self, locale_policy):
"""Sets the locale_policy of this EnvelopeId.
:param locale_policy: The locale_policy of this EnvelopeId. # noqa: E501
:type: LocalePolicyTab
"""
self._locale_policy = locale_policy
@property
def merge_field(self):
"""Gets the merge_field of this EnvelopeId. # noqa: E501
:return: The merge_field of this EnvelopeId. # noqa: E501
:rtype: MergeField
"""
return self._merge_field
@merge_field.setter
def merge_field(self, merge_field):
"""Sets the merge_field of this EnvelopeId.
:param merge_field: The merge_field of this EnvelopeId. # noqa: E501
:type: MergeField
"""
self._merge_field = merge_field
@property
def merge_field_xml(self):
"""Gets the merge_field_xml of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The merge_field_xml of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._merge_field_xml
@merge_field_xml.setter
def merge_field_xml(self, merge_field_xml):
"""Sets the merge_field_xml of this EnvelopeId.
# noqa: E501
:param merge_field_xml: The merge_field_xml of this EnvelopeId. # noqa: E501
:type: str
"""
self._merge_field_xml = merge_field_xml
@property
def name(self):
"""Gets the name of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The name of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._name
@name.setter
def name(self, name):
"""Sets the name of this EnvelopeId.
# noqa: E501
:param name: The name of this EnvelopeId. # noqa: E501
:type: str
"""
self._name = name
@property
def name_metadata(self):
"""Gets the name_metadata of this EnvelopeId. # noqa: E501
:return: The name_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._name_metadata
@name_metadata.setter
def name_metadata(self, name_metadata):
"""Sets the name_metadata of this EnvelopeId.
:param name_metadata: The name_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._name_metadata = name_metadata
@property
def page_number(self):
"""Gets the page_number of this EnvelopeId. # noqa: E501
Specifies the page number on which the tab is located. # noqa: E501
:return: The page_number of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._page_number
@page_number.setter
def page_number(self, page_number):
"""Sets the page_number of this EnvelopeId.
Specifies the page number on which the tab is located. # noqa: E501
:param page_number: The page_number of this EnvelopeId. # noqa: E501
:type: str
"""
self._page_number = page_number
@property
def page_number_metadata(self):
"""Gets the page_number_metadata of this EnvelopeId. # noqa: E501
:return: The page_number_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._page_number_metadata
@page_number_metadata.setter
def page_number_metadata(self, page_number_metadata):
"""Sets the page_number_metadata of this EnvelopeId.
:param page_number_metadata: The page_number_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._page_number_metadata = page_number_metadata
@property
def recipient_id(self):
"""Gets the recipient_id of this EnvelopeId. # noqa: E501
Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document. # noqa: E501
:return: The recipient_id of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._recipient_id
@recipient_id.setter
def recipient_id(self, recipient_id):
"""Sets the recipient_id of this EnvelopeId.
Unique for the recipient. It is used by the tab element to indicate which recipient is to sign the Document. # noqa: E501
:param recipient_id: The recipient_id of this EnvelopeId. # noqa: E501
:type: str
"""
self._recipient_id = recipient_id
@property
def recipient_id_guid(self):
"""Gets the recipient_id_guid of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The recipient_id_guid of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._recipient_id_guid
@recipient_id_guid.setter
def recipient_id_guid(self, recipient_id_guid):
"""Sets the recipient_id_guid of this EnvelopeId.
# noqa: E501
:param recipient_id_guid: The recipient_id_guid of this EnvelopeId. # noqa: E501
:type: str
"""
self._recipient_id_guid = recipient_id_guid
@property
def recipient_id_guid_metadata(self):
"""Gets the recipient_id_guid_metadata of this EnvelopeId. # noqa: E501
:return: The recipient_id_guid_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._recipient_id_guid_metadata
@recipient_id_guid_metadata.setter
def recipient_id_guid_metadata(self, recipient_id_guid_metadata):
"""Sets the recipient_id_guid_metadata of this EnvelopeId.
:param recipient_id_guid_metadata: The recipient_id_guid_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._recipient_id_guid_metadata = recipient_id_guid_metadata
@property
def recipient_id_metadata(self):
"""Gets the recipient_id_metadata of this EnvelopeId. # noqa: E501
:return: The recipient_id_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._recipient_id_metadata
@recipient_id_metadata.setter
def recipient_id_metadata(self, recipient_id_metadata):
"""Sets the recipient_id_metadata of this EnvelopeId.
:param recipient_id_metadata: The recipient_id_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._recipient_id_metadata = recipient_id_metadata
@property
def smart_contract_information(self):
"""Gets the smart_contract_information of this EnvelopeId. # noqa: E501
:return: The smart_contract_information of this EnvelopeId. # noqa: E501
:rtype: SmartContractInformation
"""
return self._smart_contract_information
@smart_contract_information.setter
def smart_contract_information(self, smart_contract_information):
"""Sets the smart_contract_information of this EnvelopeId.
:param smart_contract_information: The smart_contract_information of this EnvelopeId. # noqa: E501
:type: SmartContractInformation
"""
self._smart_contract_information = smart_contract_information
@property
def source(self):
"""Gets the source of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The source of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._source
@source.setter
def source(self, source):
"""Sets the source of this EnvelopeId.
# noqa: E501
:param source: The source of this EnvelopeId. # noqa: E501
:type: str
"""
self._source = source
@property
def status(self):
"""Gets the status of this EnvelopeId. # noqa: E501
Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later. # noqa: E501
:return: The status of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._status
@status.setter
def status(self, status):
"""Sets the status of this EnvelopeId.
Indicates the envelope status. Valid values are: * sent - The envelope is sent to the recipients. * created - The envelope is saved as a draft and can be modified and sent later. # noqa: E501
:param status: The status of this EnvelopeId. # noqa: E501
:type: str
"""
self._status = status
@property
def status_metadata(self):
"""Gets the status_metadata of this EnvelopeId. # noqa: E501
:return: The status_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._status_metadata
@status_metadata.setter
def status_metadata(self, status_metadata):
"""Sets the status_metadata of this EnvelopeId.
:param status_metadata: The status_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._status_metadata = status_metadata
@property
def tab_group_labels(self):
"""Gets the tab_group_labels of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The tab_group_labels of this EnvelopeId. # noqa: E501
:rtype: list[str]
"""
return self._tab_group_labels
@tab_group_labels.setter
def tab_group_labels(self, tab_group_labels):
"""Sets the tab_group_labels of this EnvelopeId.
# noqa: E501
:param tab_group_labels: The tab_group_labels of this EnvelopeId. # noqa: E501
:type: list[str]
"""
self._tab_group_labels = tab_group_labels
@property
def tab_group_labels_metadata(self):
"""Gets the tab_group_labels_metadata of this EnvelopeId. # noqa: E501
:return: The tab_group_labels_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._tab_group_labels_metadata
@tab_group_labels_metadata.setter
def tab_group_labels_metadata(self, tab_group_labels_metadata):
"""Sets the tab_group_labels_metadata of this EnvelopeId.
:param tab_group_labels_metadata: The tab_group_labels_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._tab_group_labels_metadata = tab_group_labels_metadata
@property
def tab_id(self):
"""Gets the tab_id of this EnvelopeId. # noqa: E501
The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. # noqa: E501
:return: The tab_id of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._tab_id
@tab_id.setter
def tab_id(self, tab_id):
"""Sets the tab_id of this EnvelopeId.
The unique identifier for the tab. The tabid can be retrieved with the [ML:GET call]. # noqa: E501
:param tab_id: The tab_id of this EnvelopeId. # noqa: E501
:type: str
"""
self._tab_id = tab_id
@property
def tab_id_metadata(self):
"""Gets the tab_id_metadata of this EnvelopeId. # noqa: E501
:return: The tab_id_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._tab_id_metadata
@tab_id_metadata.setter
def tab_id_metadata(self, tab_id_metadata):
"""Sets the tab_id_metadata of this EnvelopeId.
:param tab_id_metadata: The tab_id_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._tab_id_metadata = tab_id_metadata
@property
def tab_label(self):
"""Gets the tab_label of this EnvelopeId. # noqa: E501
The label string associated with the tab. # noqa: E501
:return: The tab_label of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._tab_label
@tab_label.setter
def tab_label(self, tab_label):
"""Sets the tab_label of this EnvelopeId.
The label string associated with the tab. # noqa: E501
:param tab_label: The tab_label of this EnvelopeId. # noqa: E501
:type: str
"""
self._tab_label = tab_label
@property
def tab_label_metadata(self):
"""Gets the tab_label_metadata of this EnvelopeId. # noqa: E501
:return: The tab_label_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._tab_label_metadata
@tab_label_metadata.setter
def tab_label_metadata(self, tab_label_metadata):
"""Sets the tab_label_metadata of this EnvelopeId.
:param tab_label_metadata: The tab_label_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._tab_label_metadata = tab_label_metadata
@property
def tab_order(self):
"""Gets the tab_order of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The tab_order of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._tab_order
@tab_order.setter
def tab_order(self, tab_order):
"""Sets the tab_order of this EnvelopeId.
# noqa: E501
:param tab_order: The tab_order of this EnvelopeId. # noqa: E501
:type: str
"""
self._tab_order = tab_order
@property
def tab_order_metadata(self):
"""Gets the tab_order_metadata of this EnvelopeId. # noqa: E501
:return: The tab_order_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._tab_order_metadata
@tab_order_metadata.setter
def tab_order_metadata(self, tab_order_metadata):
"""Sets the tab_order_metadata of this EnvelopeId.
:param tab_order_metadata: The tab_order_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._tab_order_metadata = tab_order_metadata
@property
def tab_type(self):
"""Gets the tab_type of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The tab_type of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._tab_type
@tab_type.setter
def tab_type(self, tab_type):
"""Sets the tab_type of this EnvelopeId.
# noqa: E501
:param tab_type: The tab_type of this EnvelopeId. # noqa: E501
:type: str
"""
self._tab_type = tab_type
@property
def tab_type_metadata(self):
"""Gets the tab_type_metadata of this EnvelopeId. # noqa: E501
:return: The tab_type_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._tab_type_metadata
@tab_type_metadata.setter
def tab_type_metadata(self, tab_type_metadata):
"""Sets the tab_type_metadata of this EnvelopeId.
:param tab_type_metadata: The tab_type_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._tab_type_metadata = tab_type_metadata
@property
def template_locked(self):
"""Gets the template_locked of this EnvelopeId. # noqa: E501
When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients. # noqa: E501
:return: The template_locked of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._template_locked
@template_locked.setter
def template_locked(self, template_locked):
"""Sets the template_locked of this EnvelopeId.
When set to **true**, the sender cannot change any attributes of the recipient. Used only when working with template recipients. # noqa: E501
:param template_locked: The template_locked of this EnvelopeId. # noqa: E501
:type: str
"""
self._template_locked = template_locked
@property
def template_locked_metadata(self):
"""Gets the template_locked_metadata of this EnvelopeId. # noqa: E501
:return: The template_locked_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._template_locked_metadata
@template_locked_metadata.setter
def template_locked_metadata(self, template_locked_metadata):
"""Sets the template_locked_metadata of this EnvelopeId.
:param template_locked_metadata: The template_locked_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._template_locked_metadata = template_locked_metadata
@property
def template_required(self):
"""Gets the template_required of this EnvelopeId. # noqa: E501
When set to **true**, the sender may not remove the recipient. Used only when working with template recipients. # noqa: E501
:return: The template_required of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._template_required
@template_required.setter
def template_required(self, template_required):
"""Sets the template_required of this EnvelopeId.
When set to **true**, the sender may not remove the recipient. Used only when working with template recipients. # noqa: E501
:param template_required: The template_required of this EnvelopeId. # noqa: E501
:type: str
"""
self._template_required = template_required
@property
def template_required_metadata(self):
"""Gets the template_required_metadata of this EnvelopeId. # noqa: E501
:return: The template_required_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._template_required_metadata
@template_required_metadata.setter
def template_required_metadata(self, template_required_metadata):
"""Sets the template_required_metadata of this EnvelopeId.
:param template_required_metadata: The template_required_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._template_required_metadata = template_required_metadata
@property
def tooltip(self):
"""Gets the tooltip of this EnvelopeId. # noqa: E501
# noqa: E501
:return: The tooltip of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._tooltip
@tooltip.setter
def tooltip(self, tooltip):
"""Sets the tooltip of this EnvelopeId.
# noqa: E501
:param tooltip: The tooltip of this EnvelopeId. # noqa: E501
:type: str
"""
self._tooltip = tooltip
@property
def tool_tip_metadata(self):
"""Gets the tool_tip_metadata of this EnvelopeId. # noqa: E501
:return: The tool_tip_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._tool_tip_metadata
@tool_tip_metadata.setter
def tool_tip_metadata(self, tool_tip_metadata):
"""Sets the tool_tip_metadata of this EnvelopeId.
:param tool_tip_metadata: The tool_tip_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._tool_tip_metadata = tool_tip_metadata
@property
def underline(self):
"""Gets the underline of this EnvelopeId. # noqa: E501
When set to **true**, the information in the tab is underlined. # noqa: E501
:return: The underline of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._underline
@underline.setter
def underline(self, underline):
"""Sets the underline of this EnvelopeId.
When set to **true**, the information in the tab is underlined. # noqa: E501
:param underline: The underline of this EnvelopeId. # noqa: E501
:type: str
"""
self._underline = underline
@property
def underline_metadata(self):
"""Gets the underline_metadata of this EnvelopeId. # noqa: E501
:return: The underline_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._underline_metadata
@underline_metadata.setter
def underline_metadata(self, underline_metadata):
"""Sets the underline_metadata of this EnvelopeId.
:param underline_metadata: The underline_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._underline_metadata = underline_metadata
@property
def width(self):
"""Gets the width of this EnvelopeId. # noqa: E501
Width of the tab in pixels. # noqa: E501
:return: The width of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._width
@width.setter
def width(self, width):
"""Sets the width of this EnvelopeId.
Width of the tab in pixels. # noqa: E501
:param width: The width of this EnvelopeId. # noqa: E501
:type: str
"""
self._width = width
@property
def width_metadata(self):
"""Gets the width_metadata of this EnvelopeId. # noqa: E501
:return: The width_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._width_metadata
@width_metadata.setter
def width_metadata(self, width_metadata):
"""Sets the width_metadata of this EnvelopeId.
:param width_metadata: The width_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._width_metadata = width_metadata
@property
def x_position(self):
"""Gets the x_position of this EnvelopeId. # noqa: E501
This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position. # noqa: E501
:return: The x_position of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._x_position
@x_position.setter
def x_position(self, x_position):
"""Sets the x_position of this EnvelopeId.
This indicates the horizontal offset of the object on the page. DocuSign uses 72 DPI when determining position. # noqa: E501
:param x_position: The x_position of this EnvelopeId. # noqa: E501
:type: str
"""
self._x_position = x_position
@property
def x_position_metadata(self):
"""Gets the x_position_metadata of this EnvelopeId. # noqa: E501
:return: The x_position_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._x_position_metadata
@x_position_metadata.setter
def x_position_metadata(self, x_position_metadata):
"""Sets the x_position_metadata of this EnvelopeId.
:param x_position_metadata: The x_position_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._x_position_metadata = x_position_metadata
@property
def y_position(self):
"""Gets the y_position of this EnvelopeId. # noqa: E501
This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position. # noqa: E501
:return: The y_position of this EnvelopeId. # noqa: E501
:rtype: str
"""
return self._y_position
@y_position.setter
def y_position(self, y_position):
"""Sets the y_position of this EnvelopeId.
This indicates the vertical offset of the object on the page. DocuSign uses 72 DPI when determining position. # noqa: E501
:param y_position: The y_position of this EnvelopeId. # noqa: E501
:type: str
"""
self._y_position = y_position
@property
def y_position_metadata(self):
"""Gets the y_position_metadata of this EnvelopeId. # noqa: E501
:return: The y_position_metadata of this EnvelopeId. # noqa: E501
:rtype: PropertyMetadata
"""
return self._y_position_metadata
@y_position_metadata.setter
def y_position_metadata(self, y_position_metadata):
"""Sets the y_position_metadata of this EnvelopeId.
:param y_position_metadata: The y_position_metadata of this EnvelopeId. # noqa: E501
:type: PropertyMetadata
"""
self._y_position_metadata = y_position_metadata
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_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
if issubclass(EnvelopeId, dict):
for key, value in self.items():
result[key] = 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, EnvelopeId):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 35.329461 | 2,170 | 0.672848 |
4807b9388e4c5a401b1a1522fc93591862cd5f5e | 13,246 | py | Python | pyof/v0x04/common/action.py | lucasgsfelix/python-openflow | d46fbf78ffc7693aafb179185b7c2d3c8988b151 | [
"MIT"
] | null | null | null | pyof/v0x04/common/action.py | lucasgsfelix/python-openflow | d46fbf78ffc7693aafb179185b7c2d3c8988b151 | [
"MIT"
] | null | null | null | pyof/v0x04/common/action.py | lucasgsfelix/python-openflow | d46fbf78ffc7693aafb179185b7c2d3c8988b151 | [
"MIT"
] | null | null | null | """Defines actions that may be associated with flows packets."""
# System imports
from enum import IntEnum
from math import ceil
# Local source tree imports
from pyof.foundation.base import GenericStruct
from pyof.foundation.basic_types import (
FixedTypeList, Pad, UBInt8, UBInt16, UBInt32)
from pyof.v0x04.common.flow_match import OxmTLV
# Third-party imports
__all__ = ('ActionExperimenterHeader', 'ActionGroup', 'ActionHeader',
'ActionCopyTTLIn', 'ActionCopyTTLOut', 'ActionDecMPLSTTL',
'ActionSetMPLSTTL', 'ActionDecNWTTL', 'ActionSetNWTTL',
'ActionOutput', 'ActionPopMPLS', 'ActionPopPBB', 'ActionPopVLAN',
'ActionPush', 'ActionSetField', 'ActionSetQueue', 'ActionType',
'ControllerMaxLen', 'ListOfActions')
# Enums
class ActionType(IntEnum):
"""Actions associated with flows and packets."""
#: Output to switch port.
OFPAT_OUTPUT = 0
#: Copy TTL "outwards" -- from next-to-outermost to outermost
OFPAT_COPY_TTL_OUT = 11
#: Copy TTL "inwards" -- from outermost to next-to-outermost
OFPAT_COPY_TTL_IN = 12
#: MPLS TTL
OFPAT_SET_MPLS_TTL = 15
#: Decrement MPLS TTL
OFPAT_DEC_MPLS_TTL = 16
#: Push a new VLAN tag
OFPAT_PUSH_VLAN = 17
#: Pop the outer VLAN tag
OFPAT_POP_VLAN = 18
#: Push a new MPLS tag
OFPAT_PUSH_MPLS = 19
#: Pop the outer MPLS tag
OFPAT_POP_MPLS = 20
#: Set queue id when outputting to a port
OFPAT_SET_QUEUE = 21
#: Apply group.
OFPAT_GROUP = 22
#: IP TTL.
OFPAT_SET_NW_TTL = 23
#: Decrement IP TTL.
OFPAT_DEC_NW_TTL = 24
#: Set a header field using OXM TLV format.
OFPAT_SET_FIELD = 25
#: Push a new PBB service tag (I-TAG)
OFPAT_PUSH_PBB = 26
#: Pop the outer PBB service tag (I-TAG)
OFPAT_POP_PBB = 27
#: Experimenter type
OFPAT_EXPERIMENTER = 0xffff
class ControllerMaxLen(IntEnum):
"""A max_len of OFPCML_NO_BUFFER means not to buffer.
The packet should be sent.
"""
#: maximum max_len value which can be used to request a specific byte
#: length.
OFPCML_MAX = 0xffe5
#: indicates that no buffering should be applied and the whole packet is to
#: be sent to the controller.
OFPCML_NO_BUFFER = 0xffff
# Classes
class ActionHeader(GenericStruct):
"""Action header that is common to all actions.
The length includes the header and any padding used to make the action
64-bit aligned.
NB: The length of an action *must* always be a multiple of eight.
"""
#: One of OFPAT_*.
action_type = UBInt16(enum_ref=ActionType)
#: Length of action, including this header. This is the length of actions,
#: including any padding to make it 64-bit aligned.
length = UBInt16()
# Pad for 64-bit alignment.
# This should not be implemented, as each action type has its own padding.
# pad = Pad(4)
_allowed_types = ()
def __init__(self, action_type=None, length=None):
"""Create an ActionHeader with the optional parameters below.
Args:
action_type (~pyof.v0x04.common.action.ActionType):
The type of the action.
length (int): Length of action, including this header.
"""
super().__init__()
self.action_type = action_type
self.length = length
def get_size(self, value=None):
"""Return the action length including the padding (multiple of 8)."""
if isinstance(value, ActionHeader):
return value.get_size()
elif value is None:
current_size = super().get_size()
return ceil(current_size / 8) * 8
raise ValueError(f'Invalid value "{value}" for Action*.get_size()')
def unpack(self, buff, offset=0):
"""Unpack a binary message into this object's attributes.
Unpack the binary value *buff* and update this object attributes based
on the results.
Args:
buff (bytes): Binary data package to be unpacked.
offset (int): Where to begin unpacking.
Raises:
Exception: If there is a struct unpacking error.
"""
self.action_type = UBInt16(enum_ref=ActionType)
self.action_type.unpack(buff, offset)
for cls in ActionHeader.__subclasses__():
if self.action_type.value in cls.get_allowed_types():
self.__class__ = cls
break
super().unpack(buff, offset)
@classmethod
def get_allowed_types(cls):
"""Return allowed types for the class."""
return cls._allowed_types
class ActionExperimenterHeader(ActionHeader):
"""Action structure for OFPAT_EXPERIMENTER."""
experimenter = UBInt32()
_allowed_types = ActionType.OFPAT_EXPERIMENTER,
def __init__(self, length=None, experimenter=None):
"""Create ActionExperimenterHeader with the optional parameters below.
Args:
experimenter (int): The experimenter field is the Experimenter ID,
which takes the same form as in struct ofp_experimenter.
"""
super().__init__(action_type=ActionType.OFPAT_EXPERIMENTER)
self.length = length
self.experimenter = experimenter
class ActionGroup(ActionHeader):
"""Action structure for OFPAT_GROUP."""
group_id = UBInt32()
_allowed_types = ActionType.OFPAT_GROUP,
def __init__(self, group_id=None):
"""Create an ActionGroup with the optional parameters below.
Args:
group_id (int): The group_id indicates the group used to process
this packet. The set of buckets to apply depends on the group
type.
"""
super().__init__(action_type=ActionType.OFPAT_GROUP, length=8)
self.group_id = group_id
class ActionDecMPLSTTL(ActionHeader):
"""Action structure for OFPAT_DEC_MPLS_TTL."""
pad = Pad(4)
_allowed_types = ActionType.OFPAT_DEC_MPLS_TTL,
def __init__(self):
"""Create an ActionDecMPLSTTL."""
super().__init__(action_type=ActionType.OFPAT_DEC_MPLS_TTL, length=8)
class ActionSetMPLSTTL(ActionHeader):
"""Action structure for OFPAT_SET_MPLS_TTL."""
mpls_ttl = UBInt8()
pad = Pad(3)
_allowed_types = ActionType.OFPAT_SET_MPLS_TTL,
def __init__(self, mpls_ttl=None):
"""Create an ActionSetMPLSTTL with the optional parameters below.
Args:
mpls_ttl (int): The mpls_ttl field is the MPLS TTL to set.
"""
super().__init__(action_type=ActionType.OFPAT_SET_MPLS_TTL, length=8)
self.mpls_ttl = mpls_ttl
class ActionCopyTTLIn(ActionHeader):
"""Action structure for OFPAT_COPY_TTL_IN."""
pad = Pad(4)
_allowed_types = ActionType.OFPAT_COPY_TTL_IN,
def __init__(self):
"""Create an ActionCopyTTLIn."""
super().__init__(action_type=ActionType.OFPAT_COPY_TTL_IN, length=8)
class ActionCopyTTLOut(ActionHeader):
"""Action structure for OFPAT_COPY_TTL_OUT."""
pad = Pad(4)
_allowed_types = ActionType.OFPAT_COPY_TTL_OUT,
def __init__(self):
"""Create an ActionCopyTTLOut."""
super().__init__(action_type=ActionType.OFPAT_COPY_TTL_OUT, length=8)
class ActionPopVLAN(ActionHeader):
"""Action structure for OFPAT_POP_VLAN."""
pad = Pad(4)
_allowed_types = ActionType.OFPAT_POP_VLAN,
def __init__(self):
"""Create an ActionPopVLAN."""
super().__init__(action_type=ActionType.OFPAT_POP_VLAN, length=8)
class ActionPopPBB(ActionHeader):
"""Action structure for OFPAT_POP_PBB."""
pad = Pad(4)
_allowed_types = ActionType.OFPAT_POP_PBB,
def __init__(self):
"""Create an ActionPopPBB."""
super().__init__(action_type=ActionType.OFPAT_POP_PBB, length=8)
class ActionDecNWTTL(ActionHeader):
"""Action structure for OFPAT_DEC_NW_TTL."""
pad = Pad(4)
_allowed_types = ActionType.OFPAT_DEC_NW_TTL,
def __init__(self):
"""Create a ActionDecNWTTL."""
super().__init__(action_type=ActionType.OFPAT_DEC_NW_TTL, length=8)
class ActionSetNWTTL(ActionHeader):
"""Action structure for OFPAT_SET_NW_TTL."""
nw_ttl = UBInt8()
pad = Pad(3)
_allowed_types = ActionType.OFPAT_SET_NW_TTL,
def __init__(self, nw_ttl=None):
"""Create an ActionSetNWTTL with the optional parameters below.
Args:
nw_ttl (int): the TTL address to set in the IP header.
"""
super().__init__(action_type=ActionType.OFPAT_SET_NW_TTL, length=8)
self.nw_ttl = nw_ttl
class ActionOutput(ActionHeader):
"""Defines the actions output.
Action structure for :attr:`ActionType.OFPAT_OUTPUT`, which sends packets
out :attr:`port`. When the :attr:`port` is the
:attr:`.Port.OFPP_CONTROLLER`, :attr:`max_length` indicates the max number
of bytes to send. A :attr:`max_length` of zero means no bytes of the packet
should be sent.
"""
port = UBInt32()
max_length = UBInt16()
pad = Pad(6)
_allowed_types = ActionType.OFPAT_OUTPUT,
def __init__(self, port=None,
max_length=ControllerMaxLen.OFPCML_NO_BUFFER):
"""Create a ActionOutput with the optional parameters below.
Args:
port (:class:`Port` or :class:`int`): Output port.
max_length (int): Max length to send to controller.
"""
super().__init__(action_type=ActionType.OFPAT_OUTPUT, length=16)
self.port = port
self.max_length = max_length
class ActionPopMPLS(ActionHeader):
"""Action structure for OFPAT_POP_MPLS."""
ethertype = UBInt16()
pad = Pad(2)
_allowed_types = ActionType.OFPAT_POP_MPLS,
def __init__(self, ethertype=None):
"""Create an ActionPopMPLS with the optional parameters below.
Args:
ethertype (int): indicates the Ethertype of the payload.
"""
super().__init__(action_type=ActionType.OFPAT_POP_MPLS)
self.ethertype = ethertype
class ActionPush(ActionHeader):
"""Action structure for OFPAT_PUSH_[VLAN/MPLS/PBB]."""
ethertype = UBInt16()
pad = Pad(2)
_allowed_types = (ActionType.OFPAT_PUSH_VLAN, ActionType.OFPAT_PUSH_MPLS,
ActionType.OFPAT_PUSH_PBB)
def __init__(self, action_type=None, ethertype=None):
"""Create a ActionPush with the optional parameters below.
Args:
action_type (:class:`ActionType`): indicates which tag will be
pushed (VLAN, MPLS, PBB).
ethertype (int): indicates the Ethertype of the new tag.
"""
super().__init__(action_type, length=8)
self.ethertype = ethertype
class ActionSetField(ActionHeader):
"""Action structure for OFPAT_SET_FIELD."""
field = OxmTLV()
_allowed_types = ActionType.OFPAT_SET_FIELD,
def __init__(self, field=None):
"""Create a ActionSetField with the optional parameters below.
Args:
length (int): length padded to 64 bits, followed by exactly
oxm_len bytes containing a single OXM TLV, then
exactly ((oxm_len + 4) + 7)/8*8 - (oxm_len + 4)
(between 0 and 7) bytes of all-zero bytes
field (:class:`OxmTLV`): OXM field and value.
"""
super().__init__(action_type=ActionType.OFPAT_SET_FIELD)
self.field = OxmTLV() if field is None else field
def pack(self, value=None):
"""Pack this structure updating the length and padding it."""
self._update_length()
packet = super().pack()
return self._complete_last_byte(packet)
def _update_length(self):
"""Update the length field of the struct."""
action_length = 4 + len(self.field.pack())
overflow = action_length % 8
self.length = action_length
if overflow:
self.length = action_length + 8 - overflow
def _complete_last_byte(self, packet):
"""Pad until the packet length is a multiple of 8 (bytes)."""
padded_size = self.length
padding_bytes = padded_size - len(packet)
if padding_bytes > 0:
packet += Pad(padding_bytes).pack()
return packet
class ActionSetQueue(ActionHeader):
"""Action structure for OFPAT_SET_QUEUE."""
queue_id = UBInt32()
_allowed_types = ActionType.OFPAT_SET_QUEUE,
def __init__(self, queue_id=None):
"""Create an ActionSetQueue with the optional parameters below.
Args:
queue_id (int): The queue_id send packets to given queue on port.
"""
super().__init__(action_type=ActionType.OFPAT_SET_QUEUE, length=8)
self.queue_id = queue_id
class ListOfActions(FixedTypeList):
"""List of actions.
Represented by instances of ActionHeader and used on ActionHeader objects.
"""
def __init__(self, items=None):
"""Create a ListOfActions with the optional parameters below.
Args:
items (~pyof.v0x04.common.action.ActionHeader):
Instance or a list of instances.
"""
super().__init__(pyof_class=ActionHeader, items=items)
| 30.242009 | 79 | 0.653858 |
9ecce7387941b55e41e17aaf82876bd985c89ccb | 22,213 | py | Python | generated/ansible-collection/batchcertificate.py | audevbot/autorest.devops.debug | a507fb6e2dd7826212537f27d583f203aac1c28f | [
"MIT"
] | null | null | null | generated/ansible-collection/batchcertificate.py | audevbot/autorest.devops.debug | a507fb6e2dd7826212537f27d583f203aac1c28f | [
"MIT"
] | null | null | null | generated/ansible-collection/batchcertificate.py | audevbot/autorest.devops.debug | a507fb6e2dd7826212537f27d583f203aac1c28f | [
"MIT"
] | null | null | null | #!/usr/bin/python
#
# Copyright (c) 2019 Zim Kalinowski, (@zikalino)
#
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: batchcertificate
version_added: '2.9'
short_description: Manage Azure Certificate instance.
description:
- 'Create, update and delete instance of Azure Certificate.'
options:
resource_group:
description:
- The name of the resource group that contains the Batch account.
required: true
type: str
account_name:
description:
- The name of the Batch account.
required: true
type: str
name:
description:
- >-
The identifier for the certificate. This must be made up of algorithm
and thumbprint separated by a dash, and must match the certificate data
in the request. For example SHA1-a3d1c5.
required: true
type: str
thumbprint_algorithm:
description:
- >-
This must match the first portion of the certificate name. Currently
required to be 'SHA1'.
type: str
thumbprint:
description:
- This must match the thumbprint from the name.
type: str
format:
description:
- >-
The format of the certificate - either Pfx or Cer. If omitted, the
default is Pfx.
type: str
data:
description:
- The maximum size is 10KB.
required: true
type: str
password:
description:
- >-
This is required if the certificate format is pfx and must be omitted if
the certificate format is cer.
type: str
provisioning_state_transition_time:
description:
- undefined
type: datetime
previous_provisioning_state:
description:
- The previous provisioned state of the resource
type: str
previous_provisioning_state_transition_time:
description:
- undefined
type: datetime
public_data:
description:
- The public key of the certificate.
type: str
delete_certificate_error:
description:
- >-
This is only returned when the certificate provisioningState is
'Failed'.
type: dict
suboptions:
code:
description:
- >-
An identifier for the error. Codes are invariant and are intended to
be consumed programmatically.
required: true
type: str
message:
description:
- >-
A message describing the error, intended to be suitable for display
in a user interface.
required: true
type: str
target:
description:
- >-
The target of the particular error. For example, the name of the
property in error.
type: str
details:
description:
- A list of additional details about the error.
type: list
suboptions:
code:
description:
- >-
An identifier for the error. Codes are invariant and are
intended to be consumed programmatically.
required: true
type: str
message:
description:
- >-
A message describing the error, intended to be suitable for
display in a user interface.
required: true
type: str
target:
description:
- >-
The target of the particular error. For example, the name of the
property in error.
type: str
details:
description:
- A list of additional details about the error.
type: list
suboptions:
code:
description:
- >-
An identifier for the error. Codes are invariant and are
intended to be consumed programmatically.
required: true
type: str
message:
description:
- >-
A message describing the error, intended to be suitable for
display in a user interface.
required: true
type: str
target:
description:
- >-
The target of the particular error. For example, the name of
the property in error.
type: str
details:
description:
- A list of additional details about the error.
type: list
id:
description:
- The ID of the resource.
type: str
etag:
description:
- 'The ETag of the resource, used for concurrency statements.'
type: str
state:
description:
- Assert the state of the Certificate.
- >-
Use C(present) to create or update an Certificate and C(absent) to
delete it.
default: present
choices:
- absent
- present
extends_documentation_fragment:
- azure
author:
- Zim Kalinowski (@zikalino)
'''
EXAMPLES = '''
- name: CreateCertificate - Minimal Pfx
azure.rm.batchcertificate:
resource_group: myResourceGroup
account_name: myBatchAccount
name: myCertificate
data: MIIJsgIBAzCCCW4GCSqGSIb3DQE...
password: KG0UY40e...
- name: CreateCertificate - Minimal Cer
azure.rm.batchcertificate:
resource_group: myResourceGroup
account_name: myBatchAccount
name: myCertificate
format: Cer
data: MIICrjCCAZagAwI...
- name: CreateCertificate - Full
azure.rm.batchcertificate:
resource_group: myResourceGroup
account_name: myBatchAccount
name: myCertificate
thumbprint_algorithm: SHA1
thumbprint: 0A0E4F50D51BEADEAC1D35AFC5116098E7902E6E
format: Pfx
data: MIIJsgIBAzCCCW4GCSqGSIb3DQE...
password: KG0UY40e...
- name: UpdateCertificate
azure.rm.batchcertificate:
resource_group: myResourceGroup
account_name: myBatchAccount
name: myCertificate
data: MIIJsgIBAzCCCW4GCSqGSIb3DQE...
password: KG0UY40e...
- name: CertificateDelete
azure.rm.batchcertificate:
resource_group: myResourceGroup
account_name: myBatchAccount
name: myCertificate
state: absent
'''
RETURN = '''
id:
description:
- The ID of the resource.
returned: always
type: str
sample: null
name:
description:
- The name of the resource.
returned: always
type: str
sample: null
type:
description:
- The type of the resource.
returned: always
type: str
sample: null
etag:
description:
- 'The ETag of the resource, used for concurrency statements.'
returned: always
type: str
sample: null
properties:
description:
- The properties associated with the certificate.
returned: always
type: dict
sample: null
contains:
thumbprint_algorithm:
description:
- >-
This must match the first portion of the certificate name. Currently
required to be 'SHA1'.
returned: always
type: str
sample: null
thumbprint:
description:
- This must match the thumbprint from the name.
returned: always
type: str
sample: null
format:
description:
- >-
The format of the certificate - either Pfx or Cer. If omitted, the
default is Pfx.
returned: always
type: str
sample: null
provisioning_state:
description:
- ''
returned: always
type: str
sample: null
provisioning_state_transition_time:
description:
- ''
returned: always
type: datetime
sample: null
previous_provisioning_state:
description:
- The previous provisioned state of the resource
returned: always
type: str
sample: null
previous_provisioning_state_transition_time:
description:
- ''
returned: always
type: datetime
sample: null
public_data:
description:
- The public key of the certificate.
returned: always
type: str
sample: null
delete_certificate_error:
description:
- >-
This is only returned when the certificate provisioningState is
'Failed'.
returned: always
type: dict
sample: null
contains:
code:
description:
- >-
An identifier for the error. Codes are invariant and are intended
to be consumed programmatically.
returned: always
type: str
sample: null
message:
description:
- >-
A message describing the error, intended to be suitable for
display in a user interface.
returned: always
type: str
sample: null
target:
description:
- >-
The target of the particular error. For example, the name of the
property in error.
returned: always
type: str
sample: null
details:
description:
- A list of additional details about the error.
returned: always
type: dict
sample: null
contains:
code:
description:
- >-
An identifier for the error. Codes are invariant and are
intended to be consumed programmatically.
returned: always
type: str
sample: null
message:
description:
- >-
A message describing the error, intended to be suitable for
display in a user interface.
returned: always
type: str
sample: null
target:
description:
- >-
The target of the particular error. For example, the name of
the property in error.
returned: always
type: str
sample: null
details:
description:
- A list of additional details about the error.
returned: always
type: dict
sample: null
contains:
code:
description:
- >-
An identifier for the error. Codes are invariant and are
intended to be consumed programmatically.
returned: always
type: str
sample: null
message:
description:
- >-
A message describing the error, intended to be suitable
for display in a user interface.
returned: always
type: str
sample: null
target:
description:
- >-
The target of the particular error. For example, the name
of the property in error.
returned: always
type: str
sample: null
details:
description:
- A list of additional details about the error.
returned: always
type: dict
sample: null
'''
import time
import json
import re
from ansible.module_utils.azure_rm_common_ext import AzureRMModuleBaseExt
from ansible.module_utils.azure_rm_common_rest import GenericRestClient
from copy import deepcopy
try:
from msrestazure.azure_exceptions import CloudError
except ImportError:
# this is handled in azure_rm_common
pass
class Actions:
NoAction, Create, Update, Delete = range(4)
class AzureRMCertificate(AzureRMModuleBaseExt):
def __init__(self):
self.module_arg_spec = dict(
resource_group=dict(
type='str',
updatable=False,
disposition='resourceGroupName',
required=true
),
account_name=dict(
type='str',
updatable=False,
disposition='accountName',
required=true
),
name=dict(
type='str',
updatable=False,
disposition='certificateName',
required=true
),
thumbprint_algorithm=dict(
type='str',
disposition='/properties/thumbprintAlgorithm'
),
thumbprint=dict(
type='str',
disposition='/properties/*'
),
format=dict(
type='str',
disposition='/properties/*',
choices=['Pfx',
'Cer']
),
data=dict(
type='str',
disposition='/properties/*',
required=true
),
password=dict(
type='str',
no_log=True,
disposition='/properties/*'
),
state=dict(
type='str',
default='present',
choices=['present', 'absent']
)
)
self.resource_group = None
self.account_name = None
self.name = None
self.id = None
self.etag = None
self.results = dict(changed=False)
self.mgmt_client = None
self.state = None
self.url = None
self.status_code = [200, 201, 202]
self.to_do = Actions.NoAction
self.body = {}
self.query_parameters = {}
self.query_parameters['api-version'] = '2018-12-01'
self.header_parameters = {}
self.header_parameters['Content-Type'] = 'application/json; charset=utf-8'
super(AzureRMCertificate, self).__init__(derived_arg_spec=self.module_arg_spec,
supports_check_mode=True,
supports_tags=True)
def exec_module(self, **kwargs):
for key in list(self.module_arg_spec.keys()):
if hasattr(self, key):
setattr(self, key, kwargs[key])
elif kwargs[key] is not None:
self.body[key] = kwargs[key]
self.inflate_parameters(self.module_arg_spec, self.body, 0)
old_response = None
response = None
self.mgmt_client = self.get_mgmt_svc_client(GenericRestClient,
base_url=self._cloud_environment.endpoints.resource_manager)
resource_group = self.get_resource_group(self.resource_group)
self.url = ('/subscriptions' +
'/{{ subscription_id }}' +
'/resourceGroups' +
'/{{ resource_group }}' +
'/providers' +
'/Microsoft.Batch' +
'/batchAccounts' +
'/{{ batch_account_name }}' +
'/certificates' +
'/{{ certificate_name }}')
self.url = self.url.replace('{{ subscription_id }}', self.subscription_id)
self.url = self.url.replace('{{ resource_group }}', self.resource_group)
self.url = self.url.replace('{{ batch_account_name }}', self.batch_account_name)
self.url = self.url.replace('{{ certificate_name }}', self.name)
old_response = self.get_resource()
if not old_response:
self.log("Certificate instance doesn't exist")
if self.state == 'absent':
self.log("Old instance didn't exist")
else:
self.to_do = Actions.Create
else:
self.log('Certificate instance already exists')
if self.state == 'absent':
self.to_do = Actions.Delete
else:
modifiers = {}
self.create_compare_modifiers(self.module_arg_spec, '', modifiers)
self.results['modifiers'] = modifiers
self.results['compare'] = []
self.create_compare_modifiers(self.module_arg_spec, '', modifiers)
if not self.default_compare(modifiers, self.body, old_response, '', self.results):
self.to_do = Actions.Update
if (self.to_do == Actions.Create) or (self.to_do == Actions.Update):
self.log('Need to Create / Update the Certificate instance')
if self.check_mode:
self.results['changed'] = True
return self.results
response = self.create_update_resource()
# if not old_response:
self.results['changed'] = True
# else:
# self.results['changed'] = old_response.__ne__(response)
self.log('Creation / Update done')
elif self.to_do == Actions.Delete:
self.log('Certificate instance deleted')
self.results['changed'] = True
if self.check_mode:
return self.results
self.delete_resource()
# make sure instance is actually deleted, for some Azure resources, instance is hanging around
# for some time after deletion -- this should be really fixed in Azure
while self.get_resource():
time.sleep(20)
else:
self.log('Certificate instance unchanged')
self.results['changed'] = False
response = old_response
if response:
self.results["id"] = response["id"]
self.results["name"] = response["name"]
self.results["type"] = response["type"]
self.results["etag"] = response["etag"]
self.results["properties"] = response["properties"]
return self.results
def create_update_resource(self):
# self.log('Creating / Updating the Certificate instance {0}'.format(self.))
try:
if self.to_do == Actions.Create:
response = self.mgmt_client.query(self.url,
'PUT',
self.query_parameters,
self.header_parameters,
self.body,
self.status_code,
600,
30)
else:
response = self.mgmt_client.query(self.url,
'PUT',
self.query_parameters,
self.header_parameters,
self.body,
self.status_code,
600,
30)
except CloudError as exc:
self.log('Error attempting to create the Certificate instance.')
self.fail('Error creating the Certificate instance: {0}'.format(str(exc)))
try:
response = json.loads(response.text)
except Exception:
response = {'text': response.text}
pass
return response
def delete_resource(self):
# self.log('Deleting the Certificate instance {0}'.format(self.))
try:
response = self.mgmt_client.query(self.url,
'DELETE',
self.query_parameters,
self.header_parameters,
None,
self.status_code,
600,
30)
except CloudError as e:
self.log('Error attempting to delete the Certificate instance.')
self.fail('Error deleting the Certificate instance: {0}'.format(str(e)))
return True
def get_resource(self):
# self.log('Checking if the Certificate instance {0} is present'.format(self.))
found = False
try:
response = self.mgmt_client.query(self.url,
'GET',
self.query_parameters,
self.header_parameters,
None,
self.status_code,
600,
30)
found = True
self.log("Response : {0}".format(response))
# self.log("Certificate instance : {0} found".format(response.name))
except CloudError as e:
self.log('Did not find the Certificate instance.')
if found is True:
return response
return False
def main():
AzureRMCertificate()
if __name__ == '__main__':
main()
| 32.286337 | 113 | 0.510242 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.