hexsha stringlengths 40 40 | size int64 2 1.02M | ext stringclasses 10
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 245 | max_stars_repo_name stringlengths 6 130 | max_stars_repo_head_hexsha stringlengths 40 40 | 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 4 245 | max_issues_repo_name stringlengths 6 130 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count int64 1 67k ⌀ | 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 4 245 | max_forks_repo_name stringlengths 6 130 | max_forks_repo_head_hexsha stringlengths 40 40 | 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 2 1.02M | avg_line_length float64 1 417k | max_line_length int64 1 987k | alphanum_fraction float64 0 1 | content_no_comment stringlengths 0 1.01M | is_comment_constant_removed bool 1
class | is_sharp_comment_removed bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1c3ddaae3fe121c87354bcd3992a74f10c1bbeb1 | 1,527 | py | Python | winsspi/utils/ldap3_gssapi_patch.py | skelsec/winsspi | 94ee686053908774069335e38ff4f39f27ada8dc | [
"MIT"
] | 13 | 2019-03-07T14:50:23.000Z | 2021-08-14T14:27:03.000Z | winsspi/utils/ldap3_gssapi_patch.py | skelsec/winsspi | 94ee686053908774069335e38ff4f39f27ada8dc | [
"MIT"
] | 1 | 2020-03-27T10:13:28.000Z | 2020-03-27T10:13:28.000Z | winsspi/utils/ldap3_gssapi_patch.py | skelsec/winsspi | 94ee686053908774069335e38ff4f39f27ada8dc | [
"MIT"
] | 4 | 2019-02-23T18:33:09.000Z | 2020-05-15T01:59:40.000Z | from minikerberos.sspi.kerberosspi import KerberosSSPI, SSPIResult
from ldap3.protocol.sasl.sasl import send_sasl_negotiation, abort_sasl_negotiation
import socket
def sasl_gssapi(connection, controls):
print('MONKEY!')
print(connection)
print(controls)
target_name = None
authz_id = b""
raw_creds = None
creds = None
if connection.sasl_credentials:
if len(connection.sasl_credentials) >= 1 and connection.sasl_credentials[0]:
if connection.sasl_credentials[0] is True:
hostname = socket.gethostbyaddr(connection.socket.getpeername()[0])[0]
target_name = 'ldap@' + hostname
else:
target_name = 'ldap@' + connection.sasl_credentials[0]
if len(connection.sasl_credentials) >= 2 and connection.sasl_credentials[1]:
authz_id = connection.sasl_credentials[1].encode("utf-8")
if len(connection.sasl_credentials) >= 3 and connection.sasl_credentials[2]:
raw_creds = connection.sasl_credentials[2]
if target_name is None:
target_name = 'ldap@' + connection.server.host
print('target_name : %s' % target_name)
print('authz_id : %s' % authz_id)
print('raw_creds : %s' % raw_creds)
target = 'ldap/WIN2019AD.test.corp'
#target = target_name
ksspi = KerberosSSPI(target)
in_token = None
res = None
#while True:
#result = send_sasl_negotiation(connection, controls, '')
while res != SSPIResult.OK:
res, out_token = ksspi.init_ctx(in_token)
print(out_token)
result = send_sasl_negotiation(connection, controls, out_token)
in_token = result['saslCreds']
print(in_token)
| 32.489362 | 82 | 0.747872 | from minikerberos.sspi.kerberosspi import KerberosSSPI, SSPIResult
from ldap3.protocol.sasl.sasl import send_sasl_negotiation, abort_sasl_negotiation
import socket
def sasl_gssapi(connection, controls):
print('MONKEY!')
print(connection)
print(controls)
target_name = None
authz_id = b""
raw_creds = None
creds = None
if connection.sasl_credentials:
if len(connection.sasl_credentials) >= 1 and connection.sasl_credentials[0]:
if connection.sasl_credentials[0] is True:
hostname = socket.gethostbyaddr(connection.socket.getpeername()[0])[0]
target_name = 'ldap@' + hostname
else:
target_name = 'ldap@' + connection.sasl_credentials[0]
if len(connection.sasl_credentials) >= 2 and connection.sasl_credentials[1]:
authz_id = connection.sasl_credentials[1].encode("utf-8")
if len(connection.sasl_credentials) >= 3 and connection.sasl_credentials[2]:
raw_creds = connection.sasl_credentials[2]
if target_name is None:
target_name = 'ldap@' + connection.server.host
print('target_name : %s' % target_name)
print('authz_id : %s' % authz_id)
print('raw_creds : %s' % raw_creds)
target = 'ldap/WIN2019AD.test.corp'
ksspi = KerberosSSPI(target)
in_token = None
res = None
while res != SSPIResult.OK:
res, out_token = ksspi.init_ctx(in_token)
print(out_token)
result = send_sasl_negotiation(connection, controls, out_token)
in_token = result['saslCreds']
print(in_token)
| true | true |
1c3ddb1960991927d108aa95bfbcf63e207d85f0 | 203 | py | Python | gia_events/gia_events/doctype/speaker_form/speaker_form.py | the-bantoo/GIA-Global-Events | 5b3da47fdb9778bb388d611c77e04ee8747db6f8 | [
"MIT"
] | null | null | null | gia_events/gia_events/doctype/speaker_form/speaker_form.py | the-bantoo/GIA-Global-Events | 5b3da47fdb9778bb388d611c77e04ee8747db6f8 | [
"MIT"
] | null | null | null | gia_events/gia_events/doctype/speaker_form/speaker_form.py | the-bantoo/GIA-Global-Events | 5b3da47fdb9778bb388d611c77e04ee8747db6f8 | [
"MIT"
] | null | null | null | # Copyright (c) 2021, Bantoo Accounting and contributors
# For license information, please see license.txt
# import frappe
from frappe.model.document import Document
class SpeakerForm(Document):
pass
| 22.555556 | 56 | 0.79803 |
from frappe.model.document import Document
class SpeakerForm(Document):
pass
| true | true |
1c3ddd9bc4360810fc5af17352303a8714378b5e | 546 | py | Python | test/python/visualization/__init__.py | lerongil/qiskit-terra | a25af2a2378bc3d4f5ec73b948d048d1b707454c | [
"Apache-2.0"
] | 22 | 2019-08-15T04:39:15.000Z | 2022-03-06T05:17:04.000Z | test/python/visualization/__init__.py | lerongil/qiskit-terra | a25af2a2378bc3d4f5ec73b948d048d1b707454c | [
"Apache-2.0"
] | 4 | 2019-05-13T15:28:46.000Z | 2019-12-19T20:47:02.000Z | test/python/visualization/__init__.py | lerongil/qiskit-terra | a25af2a2378bc3d4f5ec73b948d048d1b707454c | [
"Apache-2.0"
] | 9 | 2019-09-05T05:33:00.000Z | 2021-10-09T16:04:53.000Z | # -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2018.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""Tests for visualization tools."""
| 34.125 | 77 | 0.736264 | true | true | |
1c3dde5532276b413dd243da3e87cec978e21524 | 18,803 | py | Python | exact_solvers/acoustics_demos.py | katrinleinweber/riemann_book | 0bd2320765a459249d938c6913cc39339cddb3fb | [
"BSD-3-Clause"
] | null | null | null | exact_solvers/acoustics_demos.py | katrinleinweber/riemann_book | 0bd2320765a459249d938c6913cc39339cddb3fb | [
"BSD-3-Clause"
] | null | null | null | exact_solvers/acoustics_demos.py | katrinleinweber/riemann_book | 0bd2320765a459249d938c6913cc39339cddb3fb | [
"BSD-3-Clause"
] | null | null | null | """
Additional functions and demos for acoustics equations.
"""
from clawpack import pyclaw
from clawpack import riemann
from matplotlib import animation
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from ipywidgets import widgets, interact
from IPython.display import display
import sys
sys.path.append('../utils')
from utils import riemann_tools
from . import acoustics
colors = ['g','orange']
def decompose_q_interactive():
"""plots interactive decomposed eigenvectors."""
pwidget = widgets.FloatSlider(min=-1,max=1,value=1.)
uwidget = widgets.FloatSlider(min=-1,max=1,value=0.)
rhowidget = widgets.FloatSlider(min=0.1,max=2,value=1.,description=r'$\rho$')
Kwidget = widgets.FloatSlider(min=0.1,max=2,value=1.)
interact_gui = widgets.VBox([widgets.HBox([pwidget, rhowidget]),
widgets.HBox([uwidget, Kwidget])]);
mainwidget = interact(decompose_q, p=pwidget, u=uwidget, rho=rhowidget, K=Kwidget);
mainwidget.widget.close()
display(interact_gui)
display(mainwidget.widget.out)
def decompose_q(p,u,K,rho):
r"""Plotting function for decompose_q_interactive. It
should also print the eigenvectors and the values w_1, w_2."""
Z = np.sqrt(K*rho)
fig, axes = plt.subplots(1,2,figsize=(8,4))
axes[0].arrow(0,0,-Z,1,head_width=0.05, head_length=0.1, color=colors[0])
axes[0].arrow(0,0,Z,1, head_width=0.05, head_length=0.1, color=colors[1])
l1 = axes[0].plot([],[],colors[0])
l2 = axes[0].plot([],[],'-',color=colors[1])
axes[0].set_xlim(-2,2)
axes[0].set_ylim(-2,2)
axes[0].set_aspect('equal')
axes[0].set_title('Eigenvectors')
axes[0].legend(['$r_1$','$r_2$'],loc=3)
axes[0].plot([0,0],[-2,2],'--k',alpha=0.2)
axes[0].plot([-2,2],[0,0],'--k',alpha=0.2)
axes[1].plot([0,p],[0,u],'k',lw=3)
alpha1 = (Z*u-p)/(2.*Z)
alpha2 = (Z*u+p)/(2.*Z)
axes[1].plot([0,-Z*alpha1],[0,1*alpha1], color=colors[0], lw=3)
axes[1].plot([-Z*alpha1,-Z*alpha1+Z*alpha2],[1*alpha1,alpha1+alpha2], color=colors[1], lw=3)
axes[1].set_xlim(-1.2,1.2)
axes[1].set_ylim(-1.2,1.2)
axes[1].legend(['$q$',r'$w_1 r_1$',r'$w_2 r_2$'],loc='best')
axes[1].plot([0,0],[-2,2],'--k',alpha=0.2)
axes[1].plot([-2,2],[0,0],'--k',alpha=0.2)
plt.tight_layout()
def char_solution_interactive():
"""Plots interactive characteristics solution."""
twidget = widgets.FloatSlider(min=0.,max=1.2,value=0.)
rhowidget = widgets.FloatSlider(min=0.1,max=2,value=1.,description=r'$\rho$')
Kwidget = widgets.FloatSlider(min=0.1,max=2,value=1.)
interact_gui = widgets.HBox([widgets.VBox([twidget]), widgets.VBox([rhowidget, Kwidget])]);
mainwidget = interact(char_solution, t=twidget, rho=rhowidget, K=Kwidget);
mainwidget.widget.close()
display(interact_gui)
display(mainwidget.widget.out)
def char_solution(t, K, rho):
"""Plotting function for char_solution_interactive."""
fig, axes = plt.subplots(1,2,figsize=(8,4))
c = np.sqrt(K/rho)
x = np.linspace(-2*c-1,2*c+1,41)
tt = np.linspace(0,1.2,20)
for ix in x:
axes[0].plot(ix-c*tt,tt,'-k',lw=0.5,color=colors[0])
axes[0].plot(ix+c*tt,tt,'-k',lw=0.5,color=colors[1])
axes[0].set_xlim(-1,1)
axes[0].set_ylim(-0.2,1.2)
axes[0].set_title('Characteristics')
axes[0].set_xlabel('$x$')
axes[0].set_ylabel('$t$')
xx = np.linspace(-2*c-1,2*c+1,1000)
w120 = lambda x: -0.1*np.exp(-50*x**2)
w220 = lambda x: 0.1*np.exp(-50*x**2)
spacing = 1
l1, = axes[0].plot(xx,w120(xx+c*spacing*t)+spacing*t,color=colors[0],lw=2,label='$w_{1}$')
l2, = axes[0].plot(xx,w220(xx-c*spacing*t)+spacing*t,color=colors[1],lw=2,label='$w_{2}$')
axes[0].legend(handles=[l1,l2], loc=4)
axes[1].plot(xx,w120(xx-c*spacing*t)+w220(xx+c*spacing*t)+spacing*t,'-k',lw=2)
axes[1].set_xlim(-1,1)
axes[1].set_ylim(-0.2,1.2)
axes[1].set_title('Velocity')
axes[1].set_xlabel('$x$')
#axes[1].set_ylabel('$t$')
plt.tight_layout()
def phase_plane_plot():
"""Plots phase plane, also used by interactive_phase_plane
since it returns phase plane function ready to use with interact."""
def plot_function(pl,ul,pr,ur,rho,bulk,
xmin=0,xmax=6,ymin=-6,ymax=6):
"Subfunction required for interactive (function of only interactive parameters)."
# Define parameters
dp = pr - pl
du = ur - ul
c = np.sqrt(bulk/rho)
Z = rho*c
# Define eigenvectors and functions
eig1 = np.array([-Z, 1])
eig2 = np.array([Z, 1])
lin1l = lambda p: ul - 1./Z*(p-pl)
lin2l = lambda p: ul + 1./Z*(p-pl)
lin1r = lambda p: ur - 1./Z*(p-pr)
lin2r = lambda p: ur + 1./Z*(p-pr)
# Solve Riemann problem
al1 = (-dp + du*Z)/(2*Z)
pm = pl - al1*Z
um = ul + al1
# Set plot bounds
fig, ax = plt.subplots(figsize=(5,4))
x = (pl, pr, pm)
y = (ul, ur, um)
dx, dy = xmax - xmin, ymax - ymin
ax.set_xlim(min(0.00000001,xmin),xmax)
ax.set_ylim(ymin,ymax)
ax.set_xlabel('Pressure (p)', fontsize=15)
ax.set_ylabel('Velocity (u)', fontsize=15)
p = np.linspace(xmin,xmax,500)
# Plot incorrect solutions
ax.plot(p,lin2l(p),'--k')
ax.plot(p,lin1r(p),'--k')
# Plot physical solution
ax.plot(p,lin1l(p),'-k')
ax.plot(p,lin2r(p),'-k')
if (pm>=0 and pm <= xmax and um > ymin and um < ymax):
ax.plot(pm, um, '-ok', markersize=10)
ax.text(x[2] + 0.03*dx,y[2] + 0.03*dy, '$q_m$', fontsize=15)
# Plot initial states and markers
ax.plot(pl, ul, '-ok', markersize=10)
ax.plot(pr, ur, '-ok', markersize=10)
for i,label in enumerate(('$q_l$', '$q_r$')):
ax.text(x[i] + 0.03*dx,y[i] + 0.03*dy,label, fontsize=15)
plt.show()
return plot_function
def interactive_phase_plane(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
"""Plots interactive phase plane plot."""
# Create plot function for interact
pp_plot = phase_plane_plot()
# Declare all widget sliders
ql1_widget = widgets.FloatSlider(value=ql[0],min=0.01,max=10.0, description='$p_l$')
ql2_widget = widgets.FloatSlider(value=ql[1],min=-10,max=10.0, description='$u_l$')
qr1_widget = widgets.FloatSlider(value=qr[0],min=0.01,max=10.0, description='$p_r$')
qr2_widget = widgets.FloatSlider(value=qr[1],min=-10,max=10.0, description='$u_r$')
rho_widget = widgets.FloatSlider(value=rho,min=0.01,max=10.0, description=r'$\rho$')
bulk_widget = widgets.FloatSlider(value=bulk,min=0.01,max=10.0, description='$K$')
xmin_widget = widgets.BoundedFloatText(value=0.0000001, description='$p_{min}:$')
xmax_widget = widgets.FloatText(value=10, description='$p_{max}:$')
ymin_widget = widgets.FloatText(value=-5, description='$u_{min}:$')
ymax_widget = widgets.FloatText(value=5, description='$u_{max}:$')
# Allow for dependent widgets to update
def update_xmin(*args):
ql1_widget.min = xmin_widget.value
qr1_widget.min = xmin_widget.value
def update_xmax(*args):
ql1_widget.max = xmax_widget.value
qr1_widget.max = xmax_widget.value
def update_ymin(*args):
ql2_widget.min = ymin_widget.value
qr2_widget.min = ymin_widget.value
def update_ymax(*args):
ql2_widget.max = ymax_widget.value
qr2_widget.max = ymax_widget.value
xmin_widget.observe(update_xmin, 'value')
xmax_widget.observe(update_xmax, 'value')
ymin_widget.observe(update_ymin, 'value')
ymax_widget.observe(update_ymax, 'value')
# Organize slider widgets into boxes
qleftright = widgets.VBox([widgets.HBox([ql1_widget, ql2_widget, rho_widget]),
widgets.HBox([qr1_widget, qr2_widget, bulk_widget])])
plot_opts = widgets.VBox([widgets.HBox([xmin_widget, xmax_widget]),
widgets.HBox([ymin_widget, ymax_widget])])
# Set up interactive GUI (tab style)
interact_gui = widgets.Tab(children=[qleftright, plot_opts])
interact_gui.set_title(0, 'Left and right states')
interact_gui.set_title(1, 'Plot options')
# Define interactive widget and run GUI
ppwidget = interact(pp_plot, pl=ql1_widget, ul=ql2_widget,
pr=qr1_widget, ur=qr2_widget,
rho=rho_widget, bulk=bulk_widget,
xmin=xmin_widget, xmax=xmax_widget,
ymin=ymin_widget, ymax=ymax_widget)
ppwidget.widget.close()
display(interact_gui)
display(ppwidget.widget.out)
def full_riemann_solution_plot():
"""Plots full Riemann solution, including the phase plane, also used by
full_riemann_interactive and riemann_plot_func_pplane since it returns plot
function ready to use with interact."""
def plot_function(t,pl,ul,pr,ur,rho,bulk,which_char, xmin=0,xmax=6,ymin=-6,ymax=6):
"Subfunction required for interactive (function of only interactive parameters)."
# Define parameters
dp = pr - pl
du = ur - ul
c = np.sqrt(bulk/rho)
Z = rho*c
# Define eigenvectors and functions
eig1 = np.array([-Z, 1])
eig2 = np.array([Z, 1])
lin1l = lambda p: ul - 1./Z*(p-pl)
lin2l = lambda p: ul + 1./Z*(p-pl)
lin1r = lambda p: ur - 1./Z*(p-pr)
lin2r = lambda p: ur + 1./Z*(p-pr)
# Solve Riemann problem
aux = [rho,bulk]
states, speeds, riemann_eval = acoustics.exact_riemann_solution(np.array([pl,ul]), np.array([pr,ur]), aux)
pm = states[0][1]
um = states[1][1]
# Set figure grid
fig = plt.figure(figsize=(10,5)) #figsize=(11.5, 5.5))
outer_grid = gridspec.GridSpec(1, 2, wspace=0.15, hspace=0.15)
inner_grid = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=outer_grid[0], wspace=0.0, hspace=0.0)
ax1 = plt.Subplot(fig, inner_grid[0]) # x-t plane
ax2 = plt.Subplot(fig, inner_grid[1]) # x vs pressure
ax3 = plt.Subplot(fig, inner_grid[2]) # x vs velocity
ax4 = plt.Subplot(fig, outer_grid[1]) # phase plane
ax1.set_ylabel("t", fontsize=10)
ax2.set_ylabel("pressure", fontsize=10)
ax3.set_ylabel("velocity", fontsize=10)
ax3.set_xlabel("x", fontsize=10)
ax1.set_xticks([])
ax2.set_xticks([])
# Plot Riemann solution on ax1, ax2 and ax3
ax = np.array([ax1, ax2, ax3])
riemann_tools.plot_riemann(states, speeds, riemann_eval, wave_types=None, t=t, ax=ax,
layout='vertical', variable_names=['pressure', 'velocity'])
# Plot characteristics on ax1 if required
if which_char:
plot_chars=[acoustics.lambda1, acoustics.lambda2]
riemann_tools.plot_characteristics(riemann_eval, plot_chars[which_char-1],
aux=(np.array(aux),np.array(aux)), axes=ax[0], speeds=speeds)
# Plot solution in phase plane plot ion ax4
x = (pl, pr, pm)
y = (ul, ur, um)
dx, dy = xmax - xmin, ymax - ymin
ax4.set_xlim(min(0.00000001,xmin),xmax)
ax4.set_ylim(ymin,ymax)
ax4.set_xlabel('Pressure (p)', fontsize=10)
ax4.set_ylabel('Velocity (u)', fontsize=10)
ax4.set_title('Phase plane', fontsize=12)
p = np.linspace(xmin,xmax,500)
# Plot incorrect solution
ax4.plot(p,lin2l(p),'--k')
ax4.plot(p,lin1r(p),'--k')
# Plot physical solution
ax4.plot(p,lin1l(p),'-k')
ax4.plot(p,lin2r(p),'-k')
if (pm>=0 and pm <= xmax and um > ymin and um < ymax):
ax4.plot(pm, um, '-ok', markersize=10)
ax4.text(x[2] + 0.03*dx,y[2] + 0.03*dy, '$q_m$', fontsize=15)
# Plot initial states and markers
ax4.plot(pl, ul, '-ok', markersize=10)
ax4.plot(pr, ur, '-ok', markersize=10)
for i,label in enumerate(('$q_l$', '$q_r$')):
ax4.text(x[i] + 0.03*dx,y[i] + 0.03*dy,label, fontsize=15)
# Add all plots to fig and show
fig.add_subplot(ax1)
fig.add_subplot(ax2)
fig.add_subplot(ax3)
fig.add_subplot(ax4)
plt.show()
return plot_function
def riemann_plot_pplane(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
"""Plots interactive riemann solution with time dependence and phase plane plot."""
# Create plot function for interact
pp_plot = full_riemann_solution_plot()
# Declare all widget sliders
t_widget = widgets.FloatSlider(value=0,min=0.0,max=1.0, description='$t$')
which_char_widget = widgets.Dropdown(options=[None,1,2],description='Characs.')
# Set up interactive GUI
interact_gui = widgets.HBox([t_widget, which_char_widget])
# Define interactive widget and run GUI
ppwidget = interact(pp_plot, t=t_widget,
pl=ql[0], ul=ql[1],
pr=qr[0], ur=qr[1],
rho=rho, bulk=bulk,
which_char=which_char_widget)
ppwidget.widget.close()
display(interact_gui)
display(ppwidget.widget.out)
def full_riemann_interactive(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
"""Plots interactive full riemann solution with phase plane plot."""
# Create plot function for interact
pp_plot = full_riemann_solution_plot()
# Declare all widget sliders
t_widget = widgets.FloatSlider(value=0,min=0.0,max=1.0, description='$t$')
ql1_widget = widgets.FloatSlider(value=ql[0],min=0.01,max=50.0, description='$p_l$')
ql2_widget = widgets.FloatSlider(value=ql[1],min=-30,max=30.0, description='$u_l$')
qr1_widget = widgets.FloatSlider(value=qr[0],min=0.01,max=50.0, description='$p_r$')
qr2_widget = widgets.FloatSlider(value=qr[1],min=-30,max=30.0, description='$u_r$')
rho_widget = widgets.FloatSlider(value=rho,min=0.01,max=10.0, description=r'$\rho$')
bulk_widget = widgets.FloatSlider(value=bulk,min=0.01,max=10.0, description='$K$')
xmin_widget = widgets.BoundedFloatText(value=0.0000001, description='$p_{min}:$')
xmax_widget = widgets.FloatText(value=50, description='$p_{max}:$')
ymin_widget = widgets.FloatText(value=-30, description='$u_{min}:$')
ymax_widget = widgets.FloatText(value=30, description='$u_{max}:$')
which_char_widget = widgets.Dropdown(options=[None,1,2],description='Characs.')
# Allow for dependent widgets to update
def update_xmin(*args):
ql1_widget.min = xmin_widget.value
qr1_widget.min = xmin_widget.value
def update_xmax(*args):
ql1_widget.max = xmax_widget.value
qr1_widget.max = xmax_widget.value
def update_ymin(*args):
ql2_widget.min = ymin_widget.value
qr2_widget.min = ymin_widget.value
def update_ymax(*args):
ql2_widget.max = ymax_widget.value
qr2_widget.max = ymax_widget.value
xmin_widget.observe(update_xmin, 'value')
xmax_widget.observe(update_xmax, 'value')
ymin_widget.observe(update_ymin, 'value')
ymax_widget.observe(update_ymax, 'value')
# Organize slider widgets into boxes
qleftright = widgets.VBox([widgets.HBox([t_widget, which_char_widget]),
widgets.HBox([ql1_widget, ql2_widget, rho_widget]),
widgets.HBox([qr1_widget, qr2_widget, bulk_widget])])
plot_opts = widgets.VBox([widgets.HBox([xmin_widget, xmax_widget]),
widgets.HBox([ymin_widget, ymax_widget])])
# Set up interactive GUI (tab style)
interact_gui = widgets.Tab(children=[qleftright, plot_opts])
interact_gui.set_title(0, 'Left and right states')
interact_gui.set_title(1, 'Plot options')
# Define interactive widget and run GUI
ppwidget = interact(pp_plot, t=t_widget,
pl=ql1_widget, ul=ql2_widget,
pr=qr1_widget, ur=qr2_widget,
rho=rho_widget, bulk=bulk_widget,
which_char=which_char_widget,
xmin=xmin_widget, xmax=xmax_widget,
ymin=ymin_widget, ymax=ymax_widget)
ppwidget.widget.close()
display(interact_gui)
display(ppwidget.widget.out)
def bump_animation(numframes):
"""Plots animation of solution with bump initial condition,
using pyclaw (calls bump_pyclaw)."""
x, frames = bump_pyclaw(numframes)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(9,4))
ax1.set_xlim(-2, 2)
ax1.set_ylim(-3, 5)
ax1.set_xlabel('$x$')
ax1.set_ylabel('Pressure: $p$')
ax2.set_xlim(-2, 2)
ax2.set_ylim(-3, 3)
ax2.set_xlabel('$x$')
ax2.set_ylabel('Velocity: $u$')
line1, = ax1.plot([], [], '-k', lw=2)
line2, = ax2.plot([], [], '-k', lw=2)
line = [line1, line2]
def fplot(frame_number):
frame = frames[frame_number]
pressure = frame.q[0,:]
velocity = frame.q[1,:]
line[0].set_data(x,pressure)
line[1].set_data(x,velocity)
return line,
return animation.FuncAnimation(fig, fplot, frames=len(frames), interval=30)
def bump_pyclaw(numframes):
"""Returns pyclaw solution of bump initial condition."""
# Set pyclaw for burgers equation 1D
claw = pyclaw.Controller()
claw.tfinal = 5.0 # Set final time
claw.keep_copy = True # Keep solution data in memory for plotting
claw.output_format = None # Don't write solution data to file
claw.num_output_times = numframes # Number of output frames
claw.solver = pyclaw.ClawSolver1D(riemann.acoustics_1D) # Choose acoustics 1D Riemann solver
claw.solver.all_bcs = pyclaw.BC.wall # Choose periodic BCs
claw.verbosity = False # Don't print pyclaw output
domain = pyclaw.Domain( (-2.,), (2.,), (800,)) # Choose domain and mesh resolution
claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain)
# Set initial condition
x=domain.grid.x.centers
claw.solution.q[0,:] = 4.0*np.exp(-10 * (x-1.0)**2)
claw.solution.q[1,:] = 0.0
claw.solver.dt_initial = 1.e99
# Set parameters
rho = 1.0
bulk = 1.0
claw.solution.problem_data['rho'] = rho
claw.solution.problem_data['bulk'] = bulk
claw.solution.problem_data['zz'] = np.sqrt(rho*bulk)
claw.solution.problem_data['cc'] = np.sqrt(bulk/rho)
# Run pyclaw
status = claw.run()
return x, claw.frames
| 40.349785 | 114 | 0.61453 | from clawpack import pyclaw
from clawpack import riemann
from matplotlib import animation
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import numpy as np
from ipywidgets import widgets, interact
from IPython.display import display
import sys
sys.path.append('../utils')
from utils import riemann_tools
from . import acoustics
colors = ['g','orange']
def decompose_q_interactive():
pwidget = widgets.FloatSlider(min=-1,max=1,value=1.)
uwidget = widgets.FloatSlider(min=-1,max=1,value=0.)
rhowidget = widgets.FloatSlider(min=0.1,max=2,value=1.,description=r'$\rho$')
Kwidget = widgets.FloatSlider(min=0.1,max=2,value=1.)
interact_gui = widgets.VBox([widgets.HBox([pwidget, rhowidget]),
widgets.HBox([uwidget, Kwidget])]);
mainwidget = interact(decompose_q, p=pwidget, u=uwidget, rho=rhowidget, K=Kwidget);
mainwidget.widget.close()
display(interact_gui)
display(mainwidget.widget.out)
def decompose_q(p,u,K,rho):
Z = np.sqrt(K*rho)
fig, axes = plt.subplots(1,2,figsize=(8,4))
axes[0].arrow(0,0,-Z,1,head_width=0.05, head_length=0.1, color=colors[0])
axes[0].arrow(0,0,Z,1, head_width=0.05, head_length=0.1, color=colors[1])
l1 = axes[0].plot([],[],colors[0])
l2 = axes[0].plot([],[],'-',color=colors[1])
axes[0].set_xlim(-2,2)
axes[0].set_ylim(-2,2)
axes[0].set_aspect('equal')
axes[0].set_title('Eigenvectors')
axes[0].legend(['$r_1$','$r_2$'],loc=3)
axes[0].plot([0,0],[-2,2],'--k',alpha=0.2)
axes[0].plot([-2,2],[0,0],'--k',alpha=0.2)
axes[1].plot([0,p],[0,u],'k',lw=3)
alpha1 = (Z*u-p)/(2.*Z)
alpha2 = (Z*u+p)/(2.*Z)
axes[1].plot([0,-Z*alpha1],[0,1*alpha1], color=colors[0], lw=3)
axes[1].plot([-Z*alpha1,-Z*alpha1+Z*alpha2],[1*alpha1,alpha1+alpha2], color=colors[1], lw=3)
axes[1].set_xlim(-1.2,1.2)
axes[1].set_ylim(-1.2,1.2)
axes[1].legend(['$q$',r'$w_1 r_1$',r'$w_2 r_2$'],loc='best')
axes[1].plot([0,0],[-2,2],'--k',alpha=0.2)
axes[1].plot([-2,2],[0,0],'--k',alpha=0.2)
plt.tight_layout()
def char_solution_interactive():
twidget = widgets.FloatSlider(min=0.,max=1.2,value=0.)
rhowidget = widgets.FloatSlider(min=0.1,max=2,value=1.,description=r'$\rho$')
Kwidget = widgets.FloatSlider(min=0.1,max=2,value=1.)
interact_gui = widgets.HBox([widgets.VBox([twidget]), widgets.VBox([rhowidget, Kwidget])]);
mainwidget = interact(char_solution, t=twidget, rho=rhowidget, K=Kwidget);
mainwidget.widget.close()
display(interact_gui)
display(mainwidget.widget.out)
def char_solution(t, K, rho):
fig, axes = plt.subplots(1,2,figsize=(8,4))
c = np.sqrt(K/rho)
x = np.linspace(-2*c-1,2*c+1,41)
tt = np.linspace(0,1.2,20)
for ix in x:
axes[0].plot(ix-c*tt,tt,'-k',lw=0.5,color=colors[0])
axes[0].plot(ix+c*tt,tt,'-k',lw=0.5,color=colors[1])
axes[0].set_xlim(-1,1)
axes[0].set_ylim(-0.2,1.2)
axes[0].set_title('Characteristics')
axes[0].set_xlabel('$x$')
axes[0].set_ylabel('$t$')
xx = np.linspace(-2*c-1,2*c+1,1000)
w120 = lambda x: -0.1*np.exp(-50*x**2)
w220 = lambda x: 0.1*np.exp(-50*x**2)
spacing = 1
l1, = axes[0].plot(xx,w120(xx+c*spacing*t)+spacing*t,color=colors[0],lw=2,label='$w_{1}$')
l2, = axes[0].plot(xx,w220(xx-c*spacing*t)+spacing*t,color=colors[1],lw=2,label='$w_{2}$')
axes[0].legend(handles=[l1,l2], loc=4)
axes[1].plot(xx,w120(xx-c*spacing*t)+w220(xx+c*spacing*t)+spacing*t,'-k',lw=2)
axes[1].set_xlim(-1,1)
axes[1].set_ylim(-0.2,1.2)
axes[1].set_title('Velocity')
axes[1].set_xlabel('$x$')
plt.tight_layout()
def phase_plane_plot():
def plot_function(pl,ul,pr,ur,rho,bulk,
xmin=0,xmax=6,ymin=-6,ymax=6):
dp = pr - pl
du = ur - ul
c = np.sqrt(bulk/rho)
Z = rho*c
eig1 = np.array([-Z, 1])
eig2 = np.array([Z, 1])
lin1l = lambda p: ul - 1./Z*(p-pl)
lin2l = lambda p: ul + 1./Z*(p-pl)
lin1r = lambda p: ur - 1./Z*(p-pr)
lin2r = lambda p: ur + 1./Z*(p-pr)
al1 = (-dp + du*Z)/(2*Z)
pm = pl - al1*Z
um = ul + al1
fig, ax = plt.subplots(figsize=(5,4))
x = (pl, pr, pm)
y = (ul, ur, um)
dx, dy = xmax - xmin, ymax - ymin
ax.set_xlim(min(0.00000001,xmin),xmax)
ax.set_ylim(ymin,ymax)
ax.set_xlabel('Pressure (p)', fontsize=15)
ax.set_ylabel('Velocity (u)', fontsize=15)
p = np.linspace(xmin,xmax,500)
ax.plot(p,lin2l(p),'--k')
ax.plot(p,lin1r(p),'--k')
ax.plot(p,lin1l(p),'-k')
ax.plot(p,lin2r(p),'-k')
if (pm>=0 and pm <= xmax and um > ymin and um < ymax):
ax.plot(pm, um, '-ok', markersize=10)
ax.text(x[2] + 0.03*dx,y[2] + 0.03*dy, '$q_m$', fontsize=15)
ax.plot(pl, ul, '-ok', markersize=10)
ax.plot(pr, ur, '-ok', markersize=10)
for i,label in enumerate(('$q_l$', '$q_r$')):
ax.text(x[i] + 0.03*dx,y[i] + 0.03*dy,label, fontsize=15)
plt.show()
return plot_function
def interactive_phase_plane(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
pp_plot = phase_plane_plot()
ql1_widget = widgets.FloatSlider(value=ql[0],min=0.01,max=10.0, description='$p_l$')
ql2_widget = widgets.FloatSlider(value=ql[1],min=-10,max=10.0, description='$u_l$')
qr1_widget = widgets.FloatSlider(value=qr[0],min=0.01,max=10.0, description='$p_r$')
qr2_widget = widgets.FloatSlider(value=qr[1],min=-10,max=10.0, description='$u_r$')
rho_widget = widgets.FloatSlider(value=rho,min=0.01,max=10.0, description=r'$\rho$')
bulk_widget = widgets.FloatSlider(value=bulk,min=0.01,max=10.0, description='$K$')
xmin_widget = widgets.BoundedFloatText(value=0.0000001, description='$p_{min}:$')
xmax_widget = widgets.FloatText(value=10, description='$p_{max}:$')
ymin_widget = widgets.FloatText(value=-5, description='$u_{min}:$')
ymax_widget = widgets.FloatText(value=5, description='$u_{max}:$')
def update_xmin(*args):
ql1_widget.min = xmin_widget.value
qr1_widget.min = xmin_widget.value
def update_xmax(*args):
ql1_widget.max = xmax_widget.value
qr1_widget.max = xmax_widget.value
def update_ymin(*args):
ql2_widget.min = ymin_widget.value
qr2_widget.min = ymin_widget.value
def update_ymax(*args):
ql2_widget.max = ymax_widget.value
qr2_widget.max = ymax_widget.value
xmin_widget.observe(update_xmin, 'value')
xmax_widget.observe(update_xmax, 'value')
ymin_widget.observe(update_ymin, 'value')
ymax_widget.observe(update_ymax, 'value')
qleftright = widgets.VBox([widgets.HBox([ql1_widget, ql2_widget, rho_widget]),
widgets.HBox([qr1_widget, qr2_widget, bulk_widget])])
plot_opts = widgets.VBox([widgets.HBox([xmin_widget, xmax_widget]),
widgets.HBox([ymin_widget, ymax_widget])])
interact_gui = widgets.Tab(children=[qleftright, plot_opts])
interact_gui.set_title(0, 'Left and right states')
interact_gui.set_title(1, 'Plot options')
ppwidget = interact(pp_plot, pl=ql1_widget, ul=ql2_widget,
pr=qr1_widget, ur=qr2_widget,
rho=rho_widget, bulk=bulk_widget,
xmin=xmin_widget, xmax=xmax_widget,
ymin=ymin_widget, ymax=ymax_widget)
ppwidget.widget.close()
display(interact_gui)
display(ppwidget.widget.out)
def full_riemann_solution_plot():
def plot_function(t,pl,ul,pr,ur,rho,bulk,which_char, xmin=0,xmax=6,ymin=-6,ymax=6):
dp = pr - pl
du = ur - ul
c = np.sqrt(bulk/rho)
Z = rho*c
eig1 = np.array([-Z, 1])
eig2 = np.array([Z, 1])
lin1l = lambda p: ul - 1./Z*(p-pl)
lin2l = lambda p: ul + 1./Z*(p-pl)
lin1r = lambda p: ur - 1./Z*(p-pr)
lin2r = lambda p: ur + 1./Z*(p-pr)
aux = [rho,bulk]
states, speeds, riemann_eval = acoustics.exact_riemann_solution(np.array([pl,ul]), np.array([pr,ur]), aux)
pm = states[0][1]
um = states[1][1]
fig = plt.figure(figsize=(10,5))
outer_grid = gridspec.GridSpec(1, 2, wspace=0.15, hspace=0.15)
inner_grid = gridspec.GridSpecFromSubplotSpec(3, 1, subplot_spec=outer_grid[0], wspace=0.0, hspace=0.0)
ax1 = plt.Subplot(fig, inner_grid[0])
ax2 = plt.Subplot(fig, inner_grid[1])
ax3 = plt.Subplot(fig, inner_grid[2])
ax4 = plt.Subplot(fig, outer_grid[1])
ax1.set_ylabel("t", fontsize=10)
ax2.set_ylabel("pressure", fontsize=10)
ax3.set_ylabel("velocity", fontsize=10)
ax3.set_xlabel("x", fontsize=10)
ax1.set_xticks([])
ax2.set_xticks([])
ax = np.array([ax1, ax2, ax3])
riemann_tools.plot_riemann(states, speeds, riemann_eval, wave_types=None, t=t, ax=ax,
layout='vertical', variable_names=['pressure', 'velocity'])
if which_char:
plot_chars=[acoustics.lambda1, acoustics.lambda2]
riemann_tools.plot_characteristics(riemann_eval, plot_chars[which_char-1],
aux=(np.array(aux),np.array(aux)), axes=ax[0], speeds=speeds)
x = (pl, pr, pm)
y = (ul, ur, um)
dx, dy = xmax - xmin, ymax - ymin
ax4.set_xlim(min(0.00000001,xmin),xmax)
ax4.set_ylim(ymin,ymax)
ax4.set_xlabel('Pressure (p)', fontsize=10)
ax4.set_ylabel('Velocity (u)', fontsize=10)
ax4.set_title('Phase plane', fontsize=12)
p = np.linspace(xmin,xmax,500)
ax4.plot(p,lin2l(p),'--k')
ax4.plot(p,lin1r(p),'--k')
ax4.plot(p,lin1l(p),'-k')
ax4.plot(p,lin2r(p),'-k')
if (pm>=0 and pm <= xmax and um > ymin and um < ymax):
ax4.plot(pm, um, '-ok', markersize=10)
ax4.text(x[2] + 0.03*dx,y[2] + 0.03*dy, '$q_m$', fontsize=15)
ax4.plot(pl, ul, '-ok', markersize=10)
ax4.plot(pr, ur, '-ok', markersize=10)
for i,label in enumerate(('$q_l$', '$q_r$')):
ax4.text(x[i] + 0.03*dx,y[i] + 0.03*dy,label, fontsize=15)
fig.add_subplot(ax1)
fig.add_subplot(ax2)
fig.add_subplot(ax3)
fig.add_subplot(ax4)
plt.show()
return plot_function
def riemann_plot_pplane(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
pp_plot = full_riemann_solution_plot()
t_widget = widgets.FloatSlider(value=0,min=0.0,max=1.0, description='$t$')
which_char_widget = widgets.Dropdown(options=[None,1,2],description='Characs.')
interact_gui = widgets.HBox([t_widget, which_char_widget])
ppwidget = interact(pp_plot, t=t_widget,
pl=ql[0], ul=ql[1],
pr=qr[0], ur=qr[1],
rho=rho, bulk=bulk,
which_char=which_char_widget)
ppwidget.widget.close()
display(interact_gui)
display(ppwidget.widget.out)
def full_riemann_interactive(ql=(10.0, -5.0), qr=(40.0, 5.0), rho=2.0, bulk=1.0):
pp_plot = full_riemann_solution_plot()
t_widget = widgets.FloatSlider(value=0,min=0.0,max=1.0, description='$t$')
ql1_widget = widgets.FloatSlider(value=ql[0],min=0.01,max=50.0, description='$p_l$')
ql2_widget = widgets.FloatSlider(value=ql[1],min=-30,max=30.0, description='$u_l$')
qr1_widget = widgets.FloatSlider(value=qr[0],min=0.01,max=50.0, description='$p_r$')
qr2_widget = widgets.FloatSlider(value=qr[1],min=-30,max=30.0, description='$u_r$')
rho_widget = widgets.FloatSlider(value=rho,min=0.01,max=10.0, description=r'$\rho$')
bulk_widget = widgets.FloatSlider(value=bulk,min=0.01,max=10.0, description='$K$')
xmin_widget = widgets.BoundedFloatText(value=0.0000001, description='$p_{min}:$')
xmax_widget = widgets.FloatText(value=50, description='$p_{max}:$')
ymin_widget = widgets.FloatText(value=-30, description='$u_{min}:$')
ymax_widget = widgets.FloatText(value=30, description='$u_{max}:$')
which_char_widget = widgets.Dropdown(options=[None,1,2],description='Characs.')
def update_xmin(*args):
ql1_widget.min = xmin_widget.value
qr1_widget.min = xmin_widget.value
def update_xmax(*args):
ql1_widget.max = xmax_widget.value
qr1_widget.max = xmax_widget.value
def update_ymin(*args):
ql2_widget.min = ymin_widget.value
qr2_widget.min = ymin_widget.value
def update_ymax(*args):
ql2_widget.max = ymax_widget.value
qr2_widget.max = ymax_widget.value
xmin_widget.observe(update_xmin, 'value')
xmax_widget.observe(update_xmax, 'value')
ymin_widget.observe(update_ymin, 'value')
ymax_widget.observe(update_ymax, 'value')
qleftright = widgets.VBox([widgets.HBox([t_widget, which_char_widget]),
widgets.HBox([ql1_widget, ql2_widget, rho_widget]),
widgets.HBox([qr1_widget, qr2_widget, bulk_widget])])
plot_opts = widgets.VBox([widgets.HBox([xmin_widget, xmax_widget]),
widgets.HBox([ymin_widget, ymax_widget])])
interact_gui = widgets.Tab(children=[qleftright, plot_opts])
interact_gui.set_title(0, 'Left and right states')
interact_gui.set_title(1, 'Plot options')
ppwidget = interact(pp_plot, t=t_widget,
pl=ql1_widget, ul=ql2_widget,
pr=qr1_widget, ur=qr2_widget,
rho=rho_widget, bulk=bulk_widget,
which_char=which_char_widget,
xmin=xmin_widget, xmax=xmax_widget,
ymin=ymin_widget, ymax=ymax_widget)
ppwidget.widget.close()
display(interact_gui)
display(ppwidget.widget.out)
def bump_animation(numframes):
x, frames = bump_pyclaw(numframes)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(9,4))
ax1.set_xlim(-2, 2)
ax1.set_ylim(-3, 5)
ax1.set_xlabel('$x$')
ax1.set_ylabel('Pressure: $p$')
ax2.set_xlim(-2, 2)
ax2.set_ylim(-3, 3)
ax2.set_xlabel('$x$')
ax2.set_ylabel('Velocity: $u$')
line1, = ax1.plot([], [], '-k', lw=2)
line2, = ax2.plot([], [], '-k', lw=2)
line = [line1, line2]
def fplot(frame_number):
frame = frames[frame_number]
pressure = frame.q[0,:]
velocity = frame.q[1,:]
line[0].set_data(x,pressure)
line[1].set_data(x,velocity)
return line,
return animation.FuncAnimation(fig, fplot, frames=len(frames), interval=30)
def bump_pyclaw(numframes):
claw = pyclaw.Controller()
claw.tfinal = 5.0
claw.keep_copy = True
claw.output_format = None
claw.num_output_times = numframes # Number of output frames
claw.solver = pyclaw.ClawSolver1D(riemann.acoustics_1D) # Choose acoustics 1D Riemann solver
claw.solver.all_bcs = pyclaw.BC.wall # Choose periodic BCs
claw.verbosity = False # Don't print pyclaw output
domain = pyclaw.Domain( (-2.,), (2.,), (800,))
claw.solution = pyclaw.Solution(claw.solver.num_eqn, domain)
x=domain.grid.x.centers
claw.solution.q[0,:] = 4.0*np.exp(-10 * (x-1.0)**2)
claw.solution.q[1,:] = 0.0
claw.solver.dt_initial = 1.e99
rho = 1.0
bulk = 1.0
claw.solution.problem_data['rho'] = rho
claw.solution.problem_data['bulk'] = bulk
claw.solution.problem_data['zz'] = np.sqrt(rho*bulk)
claw.solution.problem_data['cc'] = np.sqrt(bulk/rho)
status = claw.run()
return x, claw.frames
| true | true |
1c3ddea1fdb0257b48f8bd38591ead6a99fa5151 | 5,600 | py | Python | denoising.py | ozgurkara99/ISNAS-DIP | bfe3c41459f8803de552a2549266074b84fe1e17 | [
"MIT"
] | 6 | 2022-03-28T19:00:17.000Z | 2022-03-31T19:30:52.000Z | denoising.py | ozgurkara99/ISNAS-DIP | bfe3c41459f8803de552a2549266074b84fe1e17 | [
"MIT"
] | null | null | null | denoising.py | ozgurkara99/ISNAS-DIP | bfe3c41459f8803de552a2549266074b84fe1e17 | [
"MIT"
] | null | null | null | import argparse
import warnings
warnings.filterwarnings("ignore")
import torch
import torch.optim as optim
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
import utils.funcs as fn
import utils.basic_utils as bu
import utils.image_utils as imu
import utils.model_utils as mu
import utils.denoising_utils as du
from utils.common_utils import get_image_grid
from utils.gpu_utils import gpu_filter
from utils.paths import ROOT, IMG_EXT
from utils.common_types import *
from utils.keywords import *
def parse_args():
parser = argparse.ArgumentParser(description='NAS-DIP Denoising')
parser.add_argument('--gpu_index', default=None, type=int)
parser.add_argument('--num_gpu', type=int, default=12)
parser.add_argument('--cpu', action='store_true')
parser.add_argument('--check', action='store_true')
parser.add_argument('img_stem', type=str)
parser.add_argument('--sigma', default=25, type=int)
parser.add_argument('--exp_weight', default=0.99, type=float)
parser.add_argument('--lr', default=0.01, type=float)
parser.add_argument('--reg_noise_std', default=1./30., type=float)
parser.add_argument('--num_iter', default=4000, type=int)
parser.add_argument('--atleast', type=int, default=500)
parser.add_argument('--show_every', default=1, type=int)
args = parser.parse_args()
return args
def main():
args = parse_args()
GPU_INDEX = args.gpu_index
NUM_GPU = args.num_gpu
CPU = args.cpu
DTYPE = torch.FloatTensor if CPU else torch.cuda.FloatTensor
CHECK = args.check
IMG_STEM = args.img_stem
IMG_NAME = f'{IMG_STEM}{IMG_EXT}'
SIGMA: int = args.sigma # this is for images with pixel values in the range [0, 255]
EXP_WEIGHT = args.exp_weight
LR = args.lr
REG_NOISE_STD = args.reg_noise_std
NUM_ITER = args.num_iter
ATLEAST = args.atleast
SHOW_EVERY = args.show_every
# stem is the name of a file without its extension
img_name = IMG_STEM + IMG_EXT
# load the image
img_true_np = bu.read_true_image(DENOISING, IMG_STEM)
img_noisy_np, _ = bu.read_noisy_image(IMG_STEM, sigma=SIGMA)
img_true_np_psd_db_norm = fn.psd_db_norm(img_true_np)
img_noisy_np_psd_db_norm = fn.psd_db_norm(img_noisy_np)
img_true_torch = imu.np_to_torch(img_true_np).type(DTYPE)
img_noisy_torch = imu.np_to_torch(img_noisy_np).type(DTYPE)
psnr_noisy = fn.psnr(img_true_np, img_noisy_np)
out_channels = img_noisy_np.shape[0]
print(f'Image {img_name} is loaded.')
print(f'Shape: {img_true_np.shape}.')
print(f'PSNR of the noisy image: {psnr_noisy:.2f} dB.')
print()
# we will use the same input noise on all models
input_noise = du.get_noise_like(img_true_torch, 1/10, 'uniform').detach()
input_noise_np = imu.torch_to_np(input_noise)
input_noise_np_psd_db_norm = fn.psd_db_norm(input_noise_np)
in_channels = input_noise_np.shape[0]
print(f'input noise shape: {input_noise.shape}.')
print()
# read the models
model_names = gpu_filter(GPU_INDEX, NUM_GPU)
num_models = len(model_names)
print(f'{num_models} models will be processed.\n')
# we will save the results here
datadir = ROOT[BENCHMARK][DENOISING][SIGMA][IMG_STEM]
# start to train the models
print(f'Starting the DIP process...')
for i, model_name in enumerate(model_names, start=1):
print('{:03}/{:03}: {}'.format(i, len(model_names), model_name))
# we will save the results here
modeldir = datadir[DATA][model_name]
# check whether the necessary files allready exists
if CHECK and \
modeldir['htr.pkl'].exists() and \
modeldir['grid.png'].exists() and \
modeldir['img_noisy.npy'].exists() and \
modeldir['input_noise.npy'].exists() and \
modeldir['psnr_noisy.pkl'].exists():
print('Necessary files already exists - skipped.\n')
continue
# create the model
model = mu.create_model(
model_name, in_channels=in_channels, out_channels=out_channels
).type(DTYPE)
print('Model is created.')
print('Starting optimization with ADAM.')
optimizer = optim.Adam(model.parameters(), lr=LR)
# denoising
htr = du.denoising(
model=model,
optimizer=optimizer,
img_true_np=img_true_np,
img_noisy_torch=img_noisy_torch,
input_noise=input_noise,
num_iter=NUM_ITER,
atleast=ATLEAST,
exp_weight=EXP_WEIGHT,
reg_noise_std=REG_NOISE_STD,
show_every=SHOW_EVERY
)
grid = get_image_grid(
[
input_noise_np,
img_true_np,
img_noisy_np,
htr['best_out'],
htr['best_out_sm'],
input_noise_np_psd_db_norm,
img_true_np_psd_db_norm,
img_noisy_np_psd_db_norm,
fn.psd_db_norm(htr['best_out']),
fn.psd_db_norm(htr['best_out_sm'])
],
nrow=5
)
# save the results
modeldir['htr.pkl'].save(htr)
modeldir['img_noisy.npy'].save(img_noisy_np)
modeldir['input_noise.npy'].save(input_noise_np)
modeldir['psnr_noisy.pkl'].save(psnr_noisy)
modeldir['grid.png'].save(grid)
print('Results are saved.\n')
if __name__ == '__main__':
main()
| 30.939227 | 88 | 0.650536 | import argparse
import warnings
warnings.filterwarnings("ignore")
import torch
import torch.optim as optim
torch.backends.cudnn.enabled = True
torch.backends.cudnn.benchmark = True
torch.backends.cudnn.deterministic = True
import utils.funcs as fn
import utils.basic_utils as bu
import utils.image_utils as imu
import utils.model_utils as mu
import utils.denoising_utils as du
from utils.common_utils import get_image_grid
from utils.gpu_utils import gpu_filter
from utils.paths import ROOT, IMG_EXT
from utils.common_types import *
from utils.keywords import *
def parse_args():
parser = argparse.ArgumentParser(description='NAS-DIP Denoising')
parser.add_argument('--gpu_index', default=None, type=int)
parser.add_argument('--num_gpu', type=int, default=12)
parser.add_argument('--cpu', action='store_true')
parser.add_argument('--check', action='store_true')
parser.add_argument('img_stem', type=str)
parser.add_argument('--sigma', default=25, type=int)
parser.add_argument('--exp_weight', default=0.99, type=float)
parser.add_argument('--lr', default=0.01, type=float)
parser.add_argument('--reg_noise_std', default=1./30., type=float)
parser.add_argument('--num_iter', default=4000, type=int)
parser.add_argument('--atleast', type=int, default=500)
parser.add_argument('--show_every', default=1, type=int)
args = parser.parse_args()
return args
def main():
args = parse_args()
GPU_INDEX = args.gpu_index
NUM_GPU = args.num_gpu
CPU = args.cpu
DTYPE = torch.FloatTensor if CPU else torch.cuda.FloatTensor
CHECK = args.check
IMG_STEM = args.img_stem
IMG_NAME = f'{IMG_STEM}{IMG_EXT}'
SIGMA: int = args.sigma
EXP_WEIGHT = args.exp_weight
LR = args.lr
REG_NOISE_STD = args.reg_noise_std
NUM_ITER = args.num_iter
ATLEAST = args.atleast
SHOW_EVERY = args.show_every
img_name = IMG_STEM + IMG_EXT
img_true_np = bu.read_true_image(DENOISING, IMG_STEM)
img_noisy_np, _ = bu.read_noisy_image(IMG_STEM, sigma=SIGMA)
img_true_np_psd_db_norm = fn.psd_db_norm(img_true_np)
img_noisy_np_psd_db_norm = fn.psd_db_norm(img_noisy_np)
img_true_torch = imu.np_to_torch(img_true_np).type(DTYPE)
img_noisy_torch = imu.np_to_torch(img_noisy_np).type(DTYPE)
psnr_noisy = fn.psnr(img_true_np, img_noisy_np)
out_channels = img_noisy_np.shape[0]
print(f'Image {img_name} is loaded.')
print(f'Shape: {img_true_np.shape}.')
print(f'PSNR of the noisy image: {psnr_noisy:.2f} dB.')
print()
input_noise = du.get_noise_like(img_true_torch, 1/10, 'uniform').detach()
input_noise_np = imu.torch_to_np(input_noise)
input_noise_np_psd_db_norm = fn.psd_db_norm(input_noise_np)
in_channels = input_noise_np.shape[0]
print(f'input noise shape: {input_noise.shape}.')
print()
model_names = gpu_filter(GPU_INDEX, NUM_GPU)
num_models = len(model_names)
print(f'{num_models} models will be processed.\n')
datadir = ROOT[BENCHMARK][DENOISING][SIGMA][IMG_STEM]
print(f'Starting the DIP process...')
for i, model_name in enumerate(model_names, start=1):
print('{:03}/{:03}: {}'.format(i, len(model_names), model_name))
modeldir = datadir[DATA][model_name]
if CHECK and \
modeldir['htr.pkl'].exists() and \
modeldir['grid.png'].exists() and \
modeldir['img_noisy.npy'].exists() and \
modeldir['input_noise.npy'].exists() and \
modeldir['psnr_noisy.pkl'].exists():
print('Necessary files already exists - skipped.\n')
continue
model = mu.create_model(
model_name, in_channels=in_channels, out_channels=out_channels
).type(DTYPE)
print('Model is created.')
print('Starting optimization with ADAM.')
optimizer = optim.Adam(model.parameters(), lr=LR)
htr = du.denoising(
model=model,
optimizer=optimizer,
img_true_np=img_true_np,
img_noisy_torch=img_noisy_torch,
input_noise=input_noise,
num_iter=NUM_ITER,
atleast=ATLEAST,
exp_weight=EXP_WEIGHT,
reg_noise_std=REG_NOISE_STD,
show_every=SHOW_EVERY
)
grid = get_image_grid(
[
input_noise_np,
img_true_np,
img_noisy_np,
htr['best_out'],
htr['best_out_sm'],
input_noise_np_psd_db_norm,
img_true_np_psd_db_norm,
img_noisy_np_psd_db_norm,
fn.psd_db_norm(htr['best_out']),
fn.psd_db_norm(htr['best_out_sm'])
],
nrow=5
)
modeldir['htr.pkl'].save(htr)
modeldir['img_noisy.npy'].save(img_noisy_np)
modeldir['input_noise.npy'].save(input_noise_np)
modeldir['psnr_noisy.pkl'].save(psnr_noisy)
modeldir['grid.png'].save(grid)
print('Results are saved.\n')
if __name__ == '__main__':
main()
| true | true |
1c3ddf686a055a85019d69299232396b150b648f | 1,869 | py | Python | K-Means Clustering in Python/friend-of-the-bank.py | debug314/coursework | beb732d0d06b5a338ba8115d59ed1c75edbb1bdb | [
"BSD-3-Clause"
] | null | null | null | K-Means Clustering in Python/friend-of-the-bank.py | debug314/coursework | beb732d0d06b5a338ba8115d59ed1c75edbb1bdb | [
"BSD-3-Clause"
] | null | null | null | K-Means Clustering in Python/friend-of-the-bank.py | debug314/coursework | beb732d0d06b5a338ba8115d59ed1c75edbb1bdb | [
"BSD-3-Clause"
] | null | null | null | # Foundations of Data Science: K-Means Clustering in Python
# by University of London & Goldsmiths, Coursera
# Week 5: A Data Clustering Project
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patch
from sklearn.cluster import KMeans
# V1. Variance of Wavelet Transformed image (continuous) 1. Real - 762
# V2. Skewness of Wavelet Transformed image (continuous) 2. Fake - 610
df = pd.read_csv('files/banknote-authentication.csv')
# Computing K-Means Clustering
no_of_clusters = 2
clustered = KMeans(n_clusters=no_of_clusters).fit(df)
k_means = clustered.cluster_centers_
k_label = clustered.labels_
df['c'] = k_label
df_k0 = df.where(df['c'] == 0).dropna()
df_k1 = df.where(df['c'] == 1).dropna()
print(df)
# Exploratory Data Analysis
df_mean = np.mean(df, 0)
df_stdv = np.std(df, 0)
df_k0_mean = np.mean(df_k0, 0)
df_k0_stdv = np.std(df_k0, 0)
df_k1_mean = np.mean(df_k1, 0)
df_k1_stdv = np.std(df_k1, 0)
# Start of Plotting
fig, graph = plt.subplots()
plt.title('Friend of the Bank')
plt.xlabel('V1. Variance')
plt.ylabel('V2. Skewness')
# Plotting the Datapoints
for i in range(no_of_clusters):
plot_sd = 2
dfc = df.where(df['c'] == i).dropna()
dfc_mean = np.mean(dfc, 0)
dfc_stdv = np.std(dfc, 0)
graph.scatter(dfc['V1'], dfc['V2'], alpha=0.4, label=f"Cluster {i+1}")
graph.add_patch(
patch.Ellipse(
[dfc_mean['V1'], dfc_mean['V2']], # x and y coordinates
dfc_stdv['V1'] * plot_sd, # stdv of x, i.e. width
dfc_stdv['V2'] * plot_sd, # stdv of y, i.e. height
ec='r',
ls=':',
fill=False,
alpha=1
)
)
# Plotting CLUSTER Means
graph.scatter(k_means[:,0], k_means[:,1], c='black', s=25, alpha=0.75, label='Cluster means')
# Plotting GLOBAL Mean
graph.scatter(df_mean['V1'], df_mean['V2'], c='red', s=50, alpha=1, label='Global mean')
plt.legend()
plt.show() | 24.92 | 93 | 0.688068 |
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.patches as patch
from sklearn.cluster import KMeans
df = pd.read_csv('files/banknote-authentication.csv')
no_of_clusters = 2
clustered = KMeans(n_clusters=no_of_clusters).fit(df)
k_means = clustered.cluster_centers_
k_label = clustered.labels_
df['c'] = k_label
df_k0 = df.where(df['c'] == 0).dropna()
df_k1 = df.where(df['c'] == 1).dropna()
print(df)
df_mean = np.mean(df, 0)
df_stdv = np.std(df, 0)
df_k0_mean = np.mean(df_k0, 0)
df_k0_stdv = np.std(df_k0, 0)
df_k1_mean = np.mean(df_k1, 0)
df_k1_stdv = np.std(df_k1, 0)
fig, graph = plt.subplots()
plt.title('Friend of the Bank')
plt.xlabel('V1. Variance')
plt.ylabel('V2. Skewness')
for i in range(no_of_clusters):
plot_sd = 2
dfc = df.where(df['c'] == i).dropna()
dfc_mean = np.mean(dfc, 0)
dfc_stdv = np.std(dfc, 0)
graph.scatter(dfc['V1'], dfc['V2'], alpha=0.4, label=f"Cluster {i+1}")
graph.add_patch(
patch.Ellipse(
[dfc_mean['V1'], dfc_mean['V2']],
dfc_stdv['V1'] * plot_sd,
dfc_stdv['V2'] * plot_sd,
ec='r',
ls=':',
fill=False,
alpha=1
)
)
graph.scatter(k_means[:,0], k_means[:,1], c='black', s=25, alpha=0.75, label='Cluster means')
graph.scatter(df_mean['V1'], df_mean['V2'], c='red', s=50, alpha=1, label='Global mean')
plt.legend()
plt.show() | true | true |
1c3ddfbfc34418740f119f97361c08eeda52cba6 | 3,759 | py | Python | kobart/utils.py | sulungsLim/KoBART | 9bb9ea3143ecd407428897e6a9b3d1e14042787c | [
"MIT"
] | null | null | null | kobart/utils.py | sulungsLim/KoBART | 9bb9ea3143ecd407428897e6a9b3d1e14042787c | [
"MIT"
] | null | null | null | kobart/utils.py | sulungsLim/KoBART | 9bb9ea3143ecd407428897e6a9b3d1e14042787c | [
"MIT"
] | 1 | 2021-12-07T01:59:21.000Z | 2021-12-07T01:59:21.000Z | # coding=utf-8
# Modified MIT License
# Software Copyright (c) 2020 SK telecom
# 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 above copyright notice and this permission notice need not be included
# with content created by the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
# BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE
# OR OTHER DEALINGS IN THE SOFTWARE.
import os
import sys
import requests
import hashlib
from zipfile import ZipFile
from transformers import PreTrainedTokenizerFast
tokenizer = {
'url':
'https://kobert.blob.core.windows.net/models/kobart/kobart_base_tokenizer_cased_a432df8fec.zip',
'fname': 'kobart_base_tokenizer_cased_a432df8fec.zip',
'chksum': 'a432df8fec'
}
def download(url, filename, chksum, cachedir='~/kogpt2/'):
f_cachedir = os.path.expanduser(cachedir)
os.makedirs(f_cachedir, exist_ok=True)
file_path = os.path.join(f_cachedir, filename)
if os.path.isfile(file_path):
if hashlib.md5(open(file_path,
'rb').read()).hexdigest()[:10] == chksum:
print('using cached model')
return file_path
with open(file_path, 'wb') as f:
response = requests.get(url, stream=True)
total = response.headers.get('content-length')
if total is None:
f.write(response.content)
else:
downloaded = 0
total = int(total)
for data in response.iter_content(
chunk_size=max(int(total / 1000), 1024 * 1024)):
downloaded += len(data)
f.write(data)
done = int(50 * downloaded / total)
sys.stdout.write('\r[{}{}]'.format('█' * done,
'.' * (50 - done)))
sys.stdout.flush()
sys.stdout.write('\n')
assert chksum == hashlib.md5(open(
file_path, 'rb').read()).hexdigest()[:10], 'corrupted file!'
return file_path
def get_kobart_tokenizer(cachedir='~/kobart/'):
"""Get KoGPT2 Tokenizer file path after downloading
"""
global tokenizer
model_info = tokenizer
file_path = download(model_info['url'],
model_info['fname'],
model_info['chksum'],
cachedir=cachedir)
cachedir_full = os.path.expanduser(cachedir)
if not os.path.exists(os.path.join(cachedir_full, 'emji_tokenizer')):
zipf = ZipFile(os.path.expanduser(file_path))
zipf.extractall(path=cachedir_full)
tok_path = os.path.join(cachedir_full, 'emji_tokenizer/model.json')
tokenizer_obj = PreTrainedTokenizerFast(tokenizer_file=tok_path,
bos_token='<s>', eos_token='</s>', unk_token='<unk>',
pad_token='<pad>', mask_token='<mask>')
return tokenizer_obj
| 42.235955 | 106 | 0.649641 |
import os
import sys
import requests
import hashlib
from zipfile import ZipFile
from transformers import PreTrainedTokenizerFast
tokenizer = {
'url':
'https://kobert.blob.core.windows.net/models/kobart/kobart_base_tokenizer_cased_a432df8fec.zip',
'fname': 'kobart_base_tokenizer_cased_a432df8fec.zip',
'chksum': 'a432df8fec'
}
def download(url, filename, chksum, cachedir='~/kogpt2/'):
f_cachedir = os.path.expanduser(cachedir)
os.makedirs(f_cachedir, exist_ok=True)
file_path = os.path.join(f_cachedir, filename)
if os.path.isfile(file_path):
if hashlib.md5(open(file_path,
'rb').read()).hexdigest()[:10] == chksum:
print('using cached model')
return file_path
with open(file_path, 'wb') as f:
response = requests.get(url, stream=True)
total = response.headers.get('content-length')
if total is None:
f.write(response.content)
else:
downloaded = 0
total = int(total)
for data in response.iter_content(
chunk_size=max(int(total / 1000), 1024 * 1024)):
downloaded += len(data)
f.write(data)
done = int(50 * downloaded / total)
sys.stdout.write('\r[{}{}]'.format('█' * done,
'.' * (50 - done)))
sys.stdout.flush()
sys.stdout.write('\n')
assert chksum == hashlib.md5(open(
file_path, 'rb').read()).hexdigest()[:10], 'corrupted file!'
return file_path
def get_kobart_tokenizer(cachedir='~/kobart/'):
global tokenizer
model_info = tokenizer
file_path = download(model_info['url'],
model_info['fname'],
model_info['chksum'],
cachedir=cachedir)
cachedir_full = os.path.expanduser(cachedir)
if not os.path.exists(os.path.join(cachedir_full, 'emji_tokenizer')):
zipf = ZipFile(os.path.expanduser(file_path))
zipf.extractall(path=cachedir_full)
tok_path = os.path.join(cachedir_full, 'emji_tokenizer/model.json')
tokenizer_obj = PreTrainedTokenizerFast(tokenizer_file=tok_path,
bos_token='<s>', eos_token='</s>', unk_token='<unk>',
pad_token='<pad>', mask_token='<mask>')
return tokenizer_obj
| true | true |
1c3de08e891050fa23299ea86b3e843612abc738 | 610 | py | Python | migrations/2017_06_07_133517_create_files_table.py | alanjimenez1/qualibrate-api | d005e35029303ac9dfd8e66cb09c79393a472cad | [
"MIT"
] | null | null | null | migrations/2017_06_07_133517_create_files_table.py | alanjimenez1/qualibrate-api | d005e35029303ac9dfd8e66cb09c79393a472cad | [
"MIT"
] | null | null | null | migrations/2017_06_07_133517_create_files_table.py | alanjimenez1/qualibrate-api | d005e35029303ac9dfd8e66cb09c79393a472cad | [
"MIT"
] | null | null | null | from orator.migrations import Migration
class CreateFilesTable(Migration):
def up(self):
"""
Run the migrations.
"""
with self.schema.create('files') as table:
table.increments('id')
table.string('uuid')
table.string('name')
table.string('path')
table.string('mime')
table.integer('user_id')
table.timestamps()
table.foreign('user_id').references('id').on('users')
def down(self):
"""
Revert the migrations.
"""
self.schema.drop('files')
| 24.4 | 65 | 0.52459 | from orator.migrations import Migration
class CreateFilesTable(Migration):
def up(self):
with self.schema.create('files') as table:
table.increments('id')
table.string('uuid')
table.string('name')
table.string('path')
table.string('mime')
table.integer('user_id')
table.timestamps()
table.foreign('user_id').references('id').on('users')
def down(self):
self.schema.drop('files')
| true | true |
1c3de0a8162572462a5485b734fecb83efc1c1c9 | 116 | py | Python | run_dev.py | LandRegistry/property-frontend-alpha | bde928c802a7efd8a0e18c041341e54d4cc89bc1 | [
"MIT"
] | null | null | null | run_dev.py | LandRegistry/property-frontend-alpha | bde928c802a7efd8a0e18c041341e54d4cc89bc1 | [
"MIT"
] | null | null | null | run_dev.py | LandRegistry/property-frontend-alpha | bde928c802a7efd8a0e18c041341e54d4cc89bc1 | [
"MIT"
] | 1 | 2021-04-11T06:06:39.000Z | 2021-04-11T06:06:39.000Z | from propertyfrontend.server import app
import os
app.run(host="0.0.0.0", port=int(os.environ['PORT']), debug=True)
| 29 | 65 | 0.741379 | from propertyfrontend.server import app
import os
app.run(host="0.0.0.0", port=int(os.environ['PORT']), debug=True)
| true | true |
1c3de1efb89c939886af9238d6fd6108b6c5dfac | 576 | py | Python | Dynamic Programming/063. Unique Paths II.py | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 138 | 2020-02-08T05:25:26.000Z | 2021-11-04T11:59:28.000Z | Dynamic Programming/063. Unique Paths II.py | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | null | null | null | Dynamic Programming/063. Unique Paths II.py | beckswu/Leetcode | 480e8dc276b1f65961166d66efa5497d7ff0bdfd | [
"MIT"
] | 24 | 2021-01-02T07:18:43.000Z | 2022-03-20T08:17:54.000Z | """
63. Unique Paths II
"""
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
if len(obstacleGrid) == 0 or obstacleGrid[0][0] == 1:
return 0
n, m = len(obstacleGrid), len(obstacleGrid[0])
if obstacleGrid[n-1][m-1] == 1 : return 0
table = [0]*m
for i, x in enumerate(obstacleGrid):
for j, y in enumerate(x):
table[j] = (table[j] if y!=1 and i>0 else 0) + (table[j-1] if y!= 1 and j>0 else 0) + (1 if i == 0 and j == 0 else 0)
return table[m-1]
| 36 | 134 | 0.519097 |
class Solution:
def uniquePathsWithObstacles(self, obstacleGrid):
if len(obstacleGrid) == 0 or obstacleGrid[0][0] == 1:
return 0
n, m = len(obstacleGrid), len(obstacleGrid[0])
if obstacleGrid[n-1][m-1] == 1 : return 0
table = [0]*m
for i, x in enumerate(obstacleGrid):
for j, y in enumerate(x):
table[j] = (table[j] if y!=1 and i>0 else 0) + (table[j-1] if y!= 1 and j>0 else 0) + (1 if i == 0 and j == 0 else 0)
return table[m-1]
| true | true |
1c3de458a4aac0b5d0c70b86684f49d6c6db58f9 | 308 | py | Python | vmraid/patches/v5_0/clear_website_group_and_notifications.py | sowrisurya/vmraid | f833e00978019dad87af80b41279c0146c063ed5 | [
"MIT"
] | null | null | null | vmraid/patches/v5_0/clear_website_group_and_notifications.py | sowrisurya/vmraid | f833e00978019dad87af80b41279c0146c063ed5 | [
"MIT"
] | null | null | null | vmraid/patches/v5_0/clear_website_group_and_notifications.py | sowrisurya/vmraid | f833e00978019dad87af80b41279c0146c063ed5 | [
"MIT"
] | null | null | null | from __future__ import unicode_literals
import vmraid
def execute():
vmraid.delete_doc("DocType", "Post")
vmraid.delete_doc("DocType", "Website Group")
vmraid.delete_doc("DocType", "Website Route Permission")
vmraid.delete_doc("DocType", "User Vote")
vmraid.delete_doc("DocType", "Notification Count")
| 30.8 | 57 | 0.766234 | from __future__ import unicode_literals
import vmraid
def execute():
vmraid.delete_doc("DocType", "Post")
vmraid.delete_doc("DocType", "Website Group")
vmraid.delete_doc("DocType", "Website Route Permission")
vmraid.delete_doc("DocType", "User Vote")
vmraid.delete_doc("DocType", "Notification Count")
| true | true |
1c3de626512a29b75c62d014fa702750d999e9a6 | 3,395 | py | Python | rigetti_result_analysis.py | filipmazurek/Quantum-Workspace | e2df6cfafa8664cd5fba8786ccf6e0540a0584fd | [
"MIT"
] | null | null | null | rigetti_result_analysis.py | filipmazurek/Quantum-Workspace | e2df6cfafa8664cd5fba8786ccf6e0540a0584fd | [
"MIT"
] | null | null | null | rigetti_result_analysis.py | filipmazurek/Quantum-Workspace | e2df6cfafa8664cd5fba8786ccf6e0540a0584fd | [
"MIT"
] | null | null | null | """
Filip Mazurek - 9/1/2019
Utility to make analyzing results from pyquil easier
"""
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
def convert_result(measurements):
# TODO: please note the endian-ness and how that affects everything else. Right now least significant bit is on left
# TODO: rewrite using numpy.vstack instead of this mess
"""
:param measurements: results from run_and_measure() using pyquil
:return: Counter object. May need to use most_common function.
"""
num_qubits = len(measurements)
num_trials = len(measurements[0])
results_per_trial = [[-1 for y in range(num_qubits)] for x in range(num_trials)]
for i in range(len(measurements)): # number of trials
for j in range(len(measurements[0])): # number of qubits
results_per_trial[j][i] = measurements[i][j]
# a hack so that we can use the Counter. Counter will take in tuples, but not lists
tupled_result = [tuple(result) for result in results_per_trial]
return Counter(tupled_result)
def plot_state_histogram(states_with_probs):
states = np.array(states_with_probs)[:,0]
probs = np.array(states_with_probs)[:,1].astype(float)
n = len(states_with_probs)
plt.barh(range(n), probs, tick_label=states)
plt.show()
def error_binary_state_to_points_order(binary_state):
"""
A modification on MS's original function. This will sort out the erroneous results as such, and will
only keep the results which make sense
Transforms the the order of points from the binary representation: [1,0,0,0,1,0,0,0,1],
to the standard one: [0, 1, 2]
Transforms [1,1,0,0] to erroneous
NOTE: This method assumes that the binary state is a matrix row-by-row.
:param binary_state:
:return: standard lists
"""
points_order = []
number_of_points = int(np.sqrt(len(binary_state)))
column_points = []
error_rep = [-1]
for p in range(number_of_points):
row_done = False
for j in range(number_of_points):
if binary_state[number_of_points * p + j] == 1:
if row_done: # there is already a 1 in this row
return error_rep
elif p in column_points: # there is already a 1 in this column
return error_rep
else:
points_order.append(j)
row_done = True
column_points.append(p)
if len(points_order) != number_of_points: # there were not enough ones
return error_rep
else:
return points_order
def tsp_convert_raw_to_order(sampling_results): # TODO: check for usage and delete
"""
:param raw_sampling: the result of the quantum computer running the tsp algorithm
:return: show which sensible results are left. Discard nonsensical answers (two cities at the same time, etc.)
"""
all_solutions = sampling_results.keys()
naive_distribution = {}
for sol in all_solutions:
points_order_solution = error_binary_state_to_points_order(sol)
if tuple(points_order_solution) in naive_distribution.keys(): # Can this ever be true?
naive_distribution[tuple(points_order_solution)] += sampling_results[sol]
else:
naive_distribution[tuple(points_order_solution)] = sampling_results[sol]
pass
| 36.505376 | 120 | 0.676878 |
from collections import Counter
import numpy as np
import matplotlib.pyplot as plt
def convert_result(measurements):
num_qubits = len(measurements)
num_trials = len(measurements[0])
results_per_trial = [[-1 for y in range(num_qubits)] for x in range(num_trials)]
for i in range(len(measurements)):
for j in range(len(measurements[0])):
results_per_trial[j][i] = measurements[i][j]
tupled_result = [tuple(result) for result in results_per_trial]
return Counter(tupled_result)
def plot_state_histogram(states_with_probs):
states = np.array(states_with_probs)[:,0]
probs = np.array(states_with_probs)[:,1].astype(float)
n = len(states_with_probs)
plt.barh(range(n), probs, tick_label=states)
plt.show()
def error_binary_state_to_points_order(binary_state):
points_order = []
number_of_points = int(np.sqrt(len(binary_state)))
column_points = []
error_rep = [-1]
for p in range(number_of_points):
row_done = False
for j in range(number_of_points):
if binary_state[number_of_points * p + j] == 1:
if row_done:
return error_rep
elif p in column_points:
return error_rep
else:
points_order.append(j)
row_done = True
column_points.append(p)
if len(points_order) != number_of_points:
return error_rep
else:
return points_order
def tsp_convert_raw_to_order(sampling_results):
all_solutions = sampling_results.keys()
naive_distribution = {}
for sol in all_solutions:
points_order_solution = error_binary_state_to_points_order(sol)
if tuple(points_order_solution) in naive_distribution.keys():
naive_distribution[tuple(points_order_solution)] += sampling_results[sol]
else:
naive_distribution[tuple(points_order_solution)] = sampling_results[sol]
pass
| true | true |
1c3de6a7f2c7ec0bf1595cc539b4d1a6ab81a114 | 7,430 | py | Python | IPython/testing/globalipapp.py | ivanov/ipython | 62cc379d3b454923cb48e94663f385f54ec806cc | [
"BSD-3-Clause-Clear"
] | 2 | 2015-04-21T12:12:43.000Z | 2015-04-21T12:12:54.000Z | IPython/testing/globalipapp.py | ivanov/ipython | 62cc379d3b454923cb48e94663f385f54ec806cc | [
"BSD-3-Clause-Clear"
] | 1 | 2015-07-16T22:26:53.000Z | 2015-07-16T22:26:53.000Z | IPython/testing/globalipapp.py | ivanov/ipython | 62cc379d3b454923cb48e94663f385f54ec806cc | [
"BSD-3-Clause-Clear"
] | null | null | null | """Global IPython app to support test running.
We must start our own ipython object and heavily muck with it so that all the
modifications IPython makes to system behavior don't send the doctest machinery
into a fit. This code should be considered a gross hack, but it gets the job
done.
"""
from __future__ import absolute_import
from __future__ import print_function
#-----------------------------------------------------------------------------
# Copyright (C) 2009-2010 The IPython Development Team
#
# Distributed under the terms of the BSD License. The full license is in
# the file COPYING, distributed as part of this software.
#-----------------------------------------------------------------------------
#-----------------------------------------------------------------------------
# Imports
#-----------------------------------------------------------------------------
# stdlib
import __builtin__
import os
import sys
from types import MethodType
# our own
from . import tools
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
#-----------------------------------------------------------------------------
# Functions
#-----------------------------------------------------------------------------
# Hack to modify the %run command so we can sync the user's namespace with the
# test globals. Once we move over to a clean magic system, this will be done
# with much less ugliness.
class py_file_finder(object):
def __init__(self,test_filename):
self.test_filename = test_filename
def __call__(self,name):
from IPython.utils.path import get_py_filename
try:
return get_py_filename(name)
except IOError:
test_dir = os.path.dirname(self.test_filename)
new_path = os.path.join(test_dir,name)
return get_py_filename(new_path)
def _run_ns_sync(self,arg_s,runner=None):
"""Modified version of %run that syncs testing namespaces.
This is strictly needed for running doctests that call %run.
"""
#print('in run_ns_sync', arg_s, file=sys.stderr) # dbg
finder = py_file_finder(arg_s)
return get_ipython().magic_run_ori(arg_s, runner, finder)
class ipnsdict(dict):
"""A special subclass of dict for use as an IPython namespace in doctests.
This subclass adds a simple checkpointing capability so that when testing
machinery clears it (we use it as the test execution context), it doesn't
get completely destroyed.
In addition, it can handle the presence of the '_' key in a special manner,
which is needed because of how Python's doctest machinery operates with
'_'. See constructor and :meth:`update` for details.
"""
def __init__(self,*a):
dict.__init__(self,*a)
self._savedict = {}
# If this flag is True, the .update() method will unconditionally
# remove a key named '_'. This is so that such a dict can be used as a
# namespace in doctests that call '_'.
self.protect_underscore = False
def clear(self):
dict.clear(self)
self.update(self._savedict)
def _checkpoint(self):
self._savedict.clear()
self._savedict.update(self)
def update(self,other):
self._checkpoint()
dict.update(self,other)
if self.protect_underscore:
# If '_' is in the namespace, python won't set it when executing
# code *in doctests*, and we have multiple doctests that use '_'.
# So we ensure that the namespace is always 'clean' of it before
# it's used for test code execution.
# This flag is only turned on by the doctest machinery, so that
# normal test code can assume the _ key is updated like any other
# key and can test for its presence after cell executions.
self.pop('_', None)
# The builtins namespace must *always* be the real __builtin__ module,
# else weird stuff happens. The main ipython code does have provisions
# to ensure this after %run, but since in this class we do some
# aggressive low-level cleaning of the execution namespace, we need to
# correct for that ourselves, to ensure consitency with the 'real'
# ipython.
self['__builtins__'] = __builtin__
def get_ipython():
# This will get replaced by the real thing once we start IPython below
return start_ipython()
# A couple of methods to override those in the running IPython to interact
# better with doctest (doctest captures on raw stdout, so we need to direct
# various types of output there otherwise it will miss them).
def xsys(self, cmd):
"""Replace the default system call with a capturing one for doctest.
"""
# We use getoutput, but we need to strip it because pexpect captures
# the trailing newline differently from commands.getoutput
print(self.getoutput(cmd, split=False).rstrip(), end='', file=sys.stdout)
sys.stdout.flush()
def _showtraceback(self, etype, evalue, stb):
"""Print the traceback purely on stdout for doctest to capture it.
"""
print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
def start_ipython():
"""Start a global IPython shell, which we need for IPython-specific syntax.
"""
global get_ipython
# This function should only ever run once!
if hasattr(start_ipython, 'already_called'):
return
start_ipython.already_called = True
# Store certain global objects that IPython modifies
_displayhook = sys.displayhook
_excepthook = sys.excepthook
_main = sys.modules.get('__main__')
# Create custom argv and namespaces for our IPython to be test-friendly
config = tools.default_config()
# Create and initialize our test-friendly IPython instance.
shell = TerminalInteractiveShell.instance(config=config,
user_ns=ipnsdict(),
user_global_ns={}
)
# A few more tweaks needed for playing nicely with doctests...
# These traps are normally only active for interactive use, set them
# permanently since we'll be mocking interactive sessions.
shell.builtin_trap.activate()
# Modify the IPython system call with one that uses getoutput, so that we
# can capture subcommands and print them to Python's stdout, otherwise the
# doctest machinery would miss them.
shell.system = MethodType(xsys, shell, TerminalInteractiveShell)
shell._showtraceback = MethodType(_showtraceback, shell,
TerminalInteractiveShell)
# IPython is ready, now clean up some global state...
# Deactivate the various python system hooks added by ipython for
# interactive convenience so we don't confuse the doctest system
sys.modules['__main__'] = _main
sys.displayhook = _displayhook
sys.excepthook = _excepthook
# So that ipython magics and aliases can be doctested (they work by making
# a call into a global _ip object). Also make the top-level get_ipython
# now return this without recursively calling here again.
_ip = shell
get_ipython = _ip.get_ipython
__builtin__._ip = _ip
__builtin__.get_ipython = get_ipython
return _ip
| 37.908163 | 79 | 0.637954 | from __future__ import absolute_import
from __future__ import print_function
import __builtin__
import os
import sys
from types import MethodType
from . import tools
from IPython.frontend.terminal.interactiveshell import TerminalInteractiveShell
# test globals. Once we move over to a clean magic system, this will be done
# with much less ugliness.
class py_file_finder(object):
def __init__(self,test_filename):
self.test_filename = test_filename
def __call__(self,name):
from IPython.utils.path import get_py_filename
try:
return get_py_filename(name)
except IOError:
test_dir = os.path.dirname(self.test_filename)
new_path = os.path.join(test_dir,name)
return get_py_filename(new_path)
def _run_ns_sync(self,arg_s,runner=None):
#print('in run_ns_sync', arg_s, file=sys.stderr) # dbg
finder = py_file_finder(arg_s)
return get_ipython().magic_run_ori(arg_s, runner, finder)
class ipnsdict(dict):
def __init__(self,*a):
dict.__init__(self,*a)
self._savedict = {}
# If this flag is True, the .update() method will unconditionally
# remove a key named '_'. This is so that such a dict can be used as a
# namespace in doctests that call '_'.
self.protect_underscore = False
def clear(self):
dict.clear(self)
self.update(self._savedict)
def _checkpoint(self):
self._savedict.clear()
self._savedict.update(self)
def update(self,other):
self._checkpoint()
dict.update(self,other)
if self.protect_underscore:
# If '_' is in the namespace, python won't set it when executing
# This flag is only turned on by the doctest machinery, so that
# normal test code can assume the _ key is updated like any other
# key and can test for its presence after cell executions.
self.pop('_', None)
# The builtins namespace must *always* be the real __builtin__ module,
# else weird stuff happens. The main ipython code does have provisions
# to ensure this after %run, but since in this class we do some
# aggressive low-level cleaning of the execution namespace, we need to
# correct for that ourselves, to ensure consitency with the 'real'
# ipython.
self['__builtins__'] = __builtin__
def get_ipython():
# This will get replaced by the real thing once we start IPython below
return start_ipython()
# A couple of methods to override those in the running IPython to interact
# better with doctest (doctest captures on raw stdout, so we need to direct
# various types of output there otherwise it will miss them).
def xsys(self, cmd):
# We use getoutput, but we need to strip it because pexpect captures
# the trailing newline differently from commands.getoutput
print(self.getoutput(cmd, split=False).rstrip(), end='', file=sys.stdout)
sys.stdout.flush()
def _showtraceback(self, etype, evalue, stb):
print(self.InteractiveTB.stb2text(stb), file=sys.stdout)
def start_ipython():
global get_ipython
# This function should only ever run once!
if hasattr(start_ipython, 'already_called'):
return
start_ipython.already_called = True
# Store certain global objects that IPython modifies
_displayhook = sys.displayhook
_excepthook = sys.excepthook
_main = sys.modules.get('__main__')
# Create custom argv and namespaces for our IPython to be test-friendly
config = tools.default_config()
# Create and initialize our test-friendly IPython instance.
shell = TerminalInteractiveShell.instance(config=config,
user_ns=ipnsdict(),
user_global_ns={}
)
# A few more tweaks needed for playing nicely with doctests...
# These traps are normally only active for interactive use, set them
# permanently since we'll be mocking interactive sessions.
shell.builtin_trap.activate()
# doctest machinery would miss them.
shell.system = MethodType(xsys, shell, TerminalInteractiveShell)
shell._showtraceback = MethodType(_showtraceback, shell,
TerminalInteractiveShell)
# IPython is ready, now clean up some global state...
# Deactivate the various python system hooks added by ipython for
# interactive convenience so we don't confuse the doctest system
sys.modules['__main__'] = _main
sys.displayhook = _displayhook
sys.excepthook = _excepthook
_ip = shell
get_ipython = _ip.get_ipython
__builtin__._ip = _ip
__builtin__.get_ipython = get_ipython
return _ip
| true | true |
1c3de74bd608376894fa6007ef978539a4ad6235 | 1,632 | py | Python | apps/zmq-app-template/setup.py | mattreduce/threatbus | 95b1d13e87fbcd1b442458ba13349c4817d5990b | [
"BSD-3-Clause"
] | null | null | null | apps/zmq-app-template/setup.py | mattreduce/threatbus | 95b1d13e87fbcd1b442458ba13349c4817d5990b | [
"BSD-3-Clause"
] | null | null | null | apps/zmq-app-template/setup.py | mattreduce/threatbus | 95b1d13e87fbcd1b442458ba13349c4817d5990b | [
"BSD-3-Clause"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
author="Tenzir",
author_email="engineering@tenzir.com",
classifiers=[
# https://pypi.org/classifiers/
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX :: Linux",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator",
"Topic :: Security",
"Topic :: Software Development :: Object Brokering",
"Topic :: System :: Distributed Computing",
],
description="Application template to connect to Threat Bus via ZeroMQ",
entry_points={
"console_scripts": ["zmq-app-template=zmq_app_template.template:main"]
},
include_package_data=True,
install_requires=[
"black >= 19.10b",
"dynaconf >= 3.1.4",
"pyzmq >= 19",
"stix2 >= 3.0",
"threatbus >= 2021.11.22",
],
keywords=[
"open source",
"threatbus",
"Threat Bus",
"threat intelligence",
"TI",
"TI dissemination",
],
license="BSD 3-clause",
long_description=long_description,
long_description_content_type="text/markdown",
name="zmq-app-template",
packages=["zmq_app_template"],
python_requires=">=3.7",
setup_requires=["setuptools", "wheel"],
url="https://github.com/tenzir/threatbus",
version="2021.11.22",
)
| 30.222222 | 82 | 0.601103 |
from setuptools import setup
with open("README.md", "r") as fh:
long_description = fh.read()
setup(
author="Tenzir",
author_email="engineering@tenzir.com",
classifiers=[
"Development Status :: 3 - Alpha",
"License :: OSI Approved :: BSD License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX :: Linux",
"Topic :: Scientific/Engineering :: Information Analysis",
"Topic :: Scientific/Engineering :: Interface Engine/Protocol Translator",
"Topic :: Security",
"Topic :: Software Development :: Object Brokering",
"Topic :: System :: Distributed Computing",
],
description="Application template to connect to Threat Bus via ZeroMQ",
entry_points={
"console_scripts": ["zmq-app-template=zmq_app_template.template:main"]
},
include_package_data=True,
install_requires=[
"black >= 19.10b",
"dynaconf >= 3.1.4",
"pyzmq >= 19",
"stix2 >= 3.0",
"threatbus >= 2021.11.22",
],
keywords=[
"open source",
"threatbus",
"Threat Bus",
"threat intelligence",
"TI",
"TI dissemination",
],
license="BSD 3-clause",
long_description=long_description,
long_description_content_type="text/markdown",
name="zmq-app-template",
packages=["zmq_app_template"],
python_requires=">=3.7",
setup_requires=["setuptools", "wheel"],
url="https://github.com/tenzir/threatbus",
version="2021.11.22",
)
| true | true |
1c3de93ba96df4fa632533d25ab7b90e5bd16d6d | 348 | py | Python | Hackerrank_python/16.XML/97.XML 1 - Find the Score.py | manish1822510059/Hackerrank | 7c6e4553f033f067e04dc6c756ef90cb43f3c4a8 | [
"MIT"
] | 39 | 2020-09-27T05:32:05.000Z | 2022-01-08T18:04:05.000Z | Hackerrank_python/16.XML/97.XML 1 - Find the Score.py | manish1822510059/Hackerrank | 7c6e4553f033f067e04dc6c756ef90cb43f3c4a8 | [
"MIT"
] | 5 | 2020-10-02T13:33:00.000Z | 2021-03-01T14:06:08.000Z | Hackerrank_python/16.XML/97.XML 1 - Find the Score.py | manish1822510059/Hackerrank | 7c6e4553f033f067e04dc6c756ef90cb43f3c4a8 | [
"MIT"
] | 6 | 2020-10-03T04:04:55.000Z | 2021-10-18T04:07:53.000Z | import sys
import xml.etree.ElementTree as etree
def get_attr_number(node):
# your code goes here
return etree.tostring(node).count(b'=')
if __name__ == '__main__':
sys.stdin.readline()
xml = sys.stdin.read()
tree = etree.ElementTree(etree.fromstring(xml))
root = tree.getroot()
print(get_attr_number(root))
| 21.75 | 51 | 0.672414 | import sys
import xml.etree.ElementTree as etree
def get_attr_number(node):
return etree.tostring(node).count(b'=')
if __name__ == '__main__':
sys.stdin.readline()
xml = sys.stdin.read()
tree = etree.ElementTree(etree.fromstring(xml))
root = tree.getroot()
print(get_attr_number(root))
| true | true |
1c3deb66177764b3d0e21e645719a7444b4a50cc | 2,345 | py | Python | files/strategies/cohort-1/level-2/riley_strategy_level_2.py | eurisko-us/eurisko-us.github.io | 74d9d426bc7a965574fbbf76d6528d47b4286fa0 | [
"MIT"
] | null | null | null | files/strategies/cohort-1/level-2/riley_strategy_level_2.py | eurisko-us/eurisko-us.github.io | 74d9d426bc7a965574fbbf76d6528d47b4286fa0 | [
"MIT"
] | null | null | null | files/strategies/cohort-1/level-2/riley_strategy_level_2.py | eurisko-us/eurisko-us.github.io | 74d9d426bc7a965574fbbf76d6528d47b4286fa0 | [
"MIT"
] | 1 | 2020-08-19T17:27:44.000Z | 2020-08-19T17:27:44.000Z |
class RileyStrategyLevel2:
def __init__(self, player_num):
self.player_num = player_num
def decide_ship_movement(self, unit_index, hidden_game_state):
myself = hidden_game_state['players'][self.player_num]
opponent_index = 1 - self.player_num
opponent = hidden_game_state['players'][opponent_index]
unit = myself['units'][unit_index]
x_unit, y_unit = unit['coords']
x_opp, y_opp = opponent['home_coords']
if unit_index >= 9:
best_translation = self.best_move(unit, opponent)
else:
if hidden_game_state['turn'] < 10:
best_translation = (0,0)
else:
best_translation = self.best_move(unit, opponent)
return best_translation
def best_move(self,unit, opponent):
x_unit, y_unit = unit['coords']
x_opp, y_opp = opponent['home_coords']
translations = [(0,0), (1,0), (-1,0), (0,1), (0,-1)]
best_translation = (0,0)
smallest_distance_to_opponent = 999999999999
for translation in translations:
delta_x, delta_y = translation
x = x_unit + delta_x
y = x_unit + delta_y
dist = abs(x - x_opp) + abs(y - y_opp)
if dist < smallest_distance_to_opponent:
best_translation = translation
smallest_distance_to_opponent = dist
return best_translation
def decide_which_unit_to_attack(self, combat_state, coords, attacker_index):
# attack opponent's first ship in combat order
combat_order = combat_state[coords]
player_indices = [unit['player'] for unit in combat_order]
opponent_index = 1 - self.player_num
for combat_index, unit in enumerate(combat_order):
if unit['player'] == opponent_index:
return combat_index
def decide_purchases(self,game_state):
units = []
tech = []
sc = ['Scout',6]
spawn_loc = game_state['players'][self.player_num]['home_coords']
cp = game_state['players'][self.player_num]['cp']
ship_choice = sc
while cp >= ship_choice[1]:
units.append({'type':ship_choice[0], 'coords':spawn_loc})
cp -= ship_choice[1]
return {'units':units,'technology':tech}
| 36.076923 | 80 | 0.604264 |
class RileyStrategyLevel2:
def __init__(self, player_num):
self.player_num = player_num
def decide_ship_movement(self, unit_index, hidden_game_state):
myself = hidden_game_state['players'][self.player_num]
opponent_index = 1 - self.player_num
opponent = hidden_game_state['players'][opponent_index]
unit = myself['units'][unit_index]
x_unit, y_unit = unit['coords']
x_opp, y_opp = opponent['home_coords']
if unit_index >= 9:
best_translation = self.best_move(unit, opponent)
else:
if hidden_game_state['turn'] < 10:
best_translation = (0,0)
else:
best_translation = self.best_move(unit, opponent)
return best_translation
def best_move(self,unit, opponent):
x_unit, y_unit = unit['coords']
x_opp, y_opp = opponent['home_coords']
translations = [(0,0), (1,0), (-1,0), (0,1), (0,-1)]
best_translation = (0,0)
smallest_distance_to_opponent = 999999999999
for translation in translations:
delta_x, delta_y = translation
x = x_unit + delta_x
y = x_unit + delta_y
dist = abs(x - x_opp) + abs(y - y_opp)
if dist < smallest_distance_to_opponent:
best_translation = translation
smallest_distance_to_opponent = dist
return best_translation
def decide_which_unit_to_attack(self, combat_state, coords, attacker_index):
combat_order = combat_state[coords]
player_indices = [unit['player'] for unit in combat_order]
opponent_index = 1 - self.player_num
for combat_index, unit in enumerate(combat_order):
if unit['player'] == opponent_index:
return combat_index
def decide_purchases(self,game_state):
units = []
tech = []
sc = ['Scout',6]
spawn_loc = game_state['players'][self.player_num]['home_coords']
cp = game_state['players'][self.player_num]['cp']
ship_choice = sc
while cp >= ship_choice[1]:
units.append({'type':ship_choice[0], 'coords':spawn_loc})
cp -= ship_choice[1]
return {'units':units,'technology':tech}
| true | true |
1c3dec0f609efe04d70c61e6046774ecc554680d | 4,845 | py | Python | pyflocker/ciphers/backends/cryptodome_/asymmetric.py | fossabot/pyflocker | 293df31e32fb796df5c7fba803846c9872e67485 | [
"MIT"
] | null | null | null | pyflocker/ciphers/backends/cryptodome_/asymmetric.py | fossabot/pyflocker | 293df31e32fb796df5c7fba803846c9872e67485 | [
"MIT"
] | null | null | null | pyflocker/ciphers/backends/cryptodome_/asymmetric.py | fossabot/pyflocker | 293df31e32fb796df5c7fba803846c9872e67485 | [
"MIT"
] | null | null | null | from __future__ import annotations
from types import MappingProxyType
from typing import TYPE_CHECKING
from Cryptodome.Cipher import PKCS1_OAEP
from Cryptodome.Signature import DSS, pss
from .. import asymmetric
if TYPE_CHECKING: # pragma: no cover
from ... import base
def get_OAEP(key, padding: base.BaseAsymmetricPadding):
"""Construct a Cryptodome specific OAEP object.
Args:
key: Public/Private key (from the Cryptodome backend).
padding (OAEP): An OAEP object.
Returns:
OAEP object:
An OAEP encryptor/decryptor object depending on the key, from the
Cryptodome backend.
"""
if not isinstance(padding, asymmetric.OAEP):
raise TypeError("padding must be an OAEP object")
if not isinstance(padding.mgf, asymmetric.MGF1):
raise TypeError("mgf must be an MGF1 instance")
return PKCS1_OAEP.new(
key,
padding.hashfunc.new(), # type: ignore
lambda x, y: pss.MGF1(
x,
y,
padding.mgf.hashfunc.new(), # type: ignore
),
padding.label or b"",
)
def get_PSS(key, padding: base.BaseAsymmetricPadding):
"""Construct a Cryptodome specific PSS object.
Args:
key: Public/Private key (from the Cryptodome backend).
padding (PSS): A PSS object.
Returns:
PSS object: An PSS signer/verifier object, depending on the key.
"""
if not isinstance(padding, asymmetric.PSS):
raise TypeError("padding must be a PSS object")
if not isinstance(padding.mgf, asymmetric.MGF1):
raise TypeError("mgf must be an MGF1 instance")
if padding.salt_length is None:
return _SaltLengthMaximizer(key, padding)
return pss.new(
key,
mask_func=lambda x, y: pss.MGF1( # type: ignore
x,
y,
padding.mgf.hashfunc.new(), # type: ignore
),
salt_bytes=padding.salt_length,
)
def get_DSS(key, mode, encoding):
"""Construct a Cryptodome specific DSS object.
Args:
key: The private/public key from Cryptodome backend.
mode (str):
The mode can be:
- 'fips-186-3'
- 'deterministic-rfc6979'
encoding:
How the signature is encoded. Values are:
- 'binary'
- 'der'
Returns:
DSS object: DSS object from Cryptodome backend.
Raises:
ValueError: if the mode or encoding is invalid.
"""
try:
return DSS.new(
key,
mode=DSS_MODES[mode],
encoding=DSS_ENCODINGS[encoding],
)
except KeyError as e:
raise ValueError(f"The mode or encoding is invalid: {e.args}")
class _SaltLengthMaximizer:
"""
Custom sign/verify wrapper over PSS to preserve consistency:
pyca/cryptography follows the OpenSSL quirk where the default
salt length is maximized and doesn't match with the size of the
digest applied to the message.
"""
def __init__(self, key, padding):
self._key = key
self._padding = padding
def _sign_or_verify(self, msghash, signature=None):
salt_length = self._key.size_in_bytes() - msghash.digest_size - 2
pss = get_PSS(
self._key,
type(self._padding)(self._padding.mgf, salt_length),
)
if signature is None:
return pss.sign(msghash)
return pss.verify(msghash, signature)
def sign(self, msghash):
if not self._key.has_private():
raise TypeError("The key is not a private key.")
return self._sign_or_verify(msghash)
def verify(self, msghash, signature):
return self._sign_or_verify(msghash, signature)
PADDINGS = MappingProxyType(
{
asymmetric.OAEP: get_OAEP,
asymmetric.PSS: get_PSS,
}
)
ENCODINGS = MappingProxyType(
{
"PEM": "PEM",
"DER": "DER",
"OpenSSH": "OpenSSH",
}
)
FORMATS = MappingProxyType(
{
"PKCS1": 1,
"PKCS8": 8,
}
)
# PKCS8 password derivation mechanisms
PROTECTION_SCHEMES = frozenset(
(
"PBKDF2WithHMAC-SHA1AndAES128-CBC",
"PBKDF2WithHMAC-SHA1AndAES192-CBC",
"PBKDF2WithHMAC-SHA1AndAES256-CBC",
"PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC",
"scryptAndAES128-CBC",
"scryptAndAES192-CBC",
"scryptAndAES256-CBC",
)
)
DSS_ENCODINGS = MappingProxyType(
{
"binary": "binary",
"der": "der",
}
)
DSS_MODES = MappingProxyType(
{
"fips-186-3": "fips-186-3",
"deterministic-rfc6979": "deterministic-rfc6979",
}
)
def get_padding_func(padding):
"""Return the appropriate padding factory function based on ``padding``."""
return PADDINGS[type(padding)]
del MappingProxyType
| 24.974227 | 79 | 0.615686 | from __future__ import annotations
from types import MappingProxyType
from typing import TYPE_CHECKING
from Cryptodome.Cipher import PKCS1_OAEP
from Cryptodome.Signature import DSS, pss
from .. import asymmetric
if TYPE_CHECKING:
from ... import base
def get_OAEP(key, padding: base.BaseAsymmetricPadding):
if not isinstance(padding, asymmetric.OAEP):
raise TypeError("padding must be an OAEP object")
if not isinstance(padding.mgf, asymmetric.MGF1):
raise TypeError("mgf must be an MGF1 instance")
return PKCS1_OAEP.new(
key,
padding.hashfunc.new(),
lambda x, y: pss.MGF1(
x,
y,
padding.mgf.hashfunc.new(),
),
padding.label or b"",
)
def get_PSS(key, padding: base.BaseAsymmetricPadding):
if not isinstance(padding, asymmetric.PSS):
raise TypeError("padding must be a PSS object")
if not isinstance(padding.mgf, asymmetric.MGF1):
raise TypeError("mgf must be an MGF1 instance")
if padding.salt_length is None:
return _SaltLengthMaximizer(key, padding)
return pss.new(
key,
mask_func=lambda x, y: pss.MGF1(
x,
y,
padding.mgf.hashfunc.new(),
),
salt_bytes=padding.salt_length,
)
def get_DSS(key, mode, encoding):
try:
return DSS.new(
key,
mode=DSS_MODES[mode],
encoding=DSS_ENCODINGS[encoding],
)
except KeyError as e:
raise ValueError(f"The mode or encoding is invalid: {e.args}")
class _SaltLengthMaximizer:
def __init__(self, key, padding):
self._key = key
self._padding = padding
def _sign_or_verify(self, msghash, signature=None):
salt_length = self._key.size_in_bytes() - msghash.digest_size - 2
pss = get_PSS(
self._key,
type(self._padding)(self._padding.mgf, salt_length),
)
if signature is None:
return pss.sign(msghash)
return pss.verify(msghash, signature)
def sign(self, msghash):
if not self._key.has_private():
raise TypeError("The key is not a private key.")
return self._sign_or_verify(msghash)
def verify(self, msghash, signature):
return self._sign_or_verify(msghash, signature)
PADDINGS = MappingProxyType(
{
asymmetric.OAEP: get_OAEP,
asymmetric.PSS: get_PSS,
}
)
ENCODINGS = MappingProxyType(
{
"PEM": "PEM",
"DER": "DER",
"OpenSSH": "OpenSSH",
}
)
FORMATS = MappingProxyType(
{
"PKCS1": 1,
"PKCS8": 8,
}
)
PROTECTION_SCHEMES = frozenset(
(
"PBKDF2WithHMAC-SHA1AndAES128-CBC",
"PBKDF2WithHMAC-SHA1AndAES192-CBC",
"PBKDF2WithHMAC-SHA1AndAES256-CBC",
"PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC",
"scryptAndAES128-CBC",
"scryptAndAES192-CBC",
"scryptAndAES256-CBC",
)
)
DSS_ENCODINGS = MappingProxyType(
{
"binary": "binary",
"der": "der",
}
)
DSS_MODES = MappingProxyType(
{
"fips-186-3": "fips-186-3",
"deterministic-rfc6979": "deterministic-rfc6979",
}
)
def get_padding_func(padding):
return PADDINGS[type(padding)]
del MappingProxyType
| true | true |
1c3dee6f69920e802052e38cde5bafb4a5698576 | 575 | py | Python | app/cadastros/helpers.py | Leodma/sisAre | 2d41528bdb457b5e6ca77d29df4d67b0a661d179 | [
"bzip2-1.0.6"
] | null | null | null | app/cadastros/helpers.py | Leodma/sisAre | 2d41528bdb457b5e6ca77d29df4d67b0a661d179 | [
"bzip2-1.0.6"
] | null | null | null | app/cadastros/helpers.py | Leodma/sisAre | 2d41528bdb457b5e6ca77d29df4d67b0a661d179 | [
"bzip2-1.0.6"
] | null | null | null | def tira_paragrafo(texto):
return texto.replace('\r\n',';')
def cria_lista(texto):
return texto.strip().replace('\r\n',';').split(';')
def lista_para_texto(lista):
texto = ';'.join(lista)
return texto
def cria_lista_db(texto):
return texto.strip().split(';')
def cria_texto_formulario(texto):
return texto.strip().replace(';','\n')
def troca_por_nulo(valor):
if valor == ' ' or '' or "" or " ":
valor = None
return valor
def porcentagem(valor, total):
if valor and total:
return (valor*100)//total
return 1
| 20.535714 | 55 | 0.615652 | def tira_paragrafo(texto):
return texto.replace('\r\n',';')
def cria_lista(texto):
return texto.strip().replace('\r\n',';').split(';')
def lista_para_texto(lista):
texto = ';'.join(lista)
return texto
def cria_lista_db(texto):
return texto.strip().split(';')
def cria_texto_formulario(texto):
return texto.strip().replace(';','\n')
def troca_por_nulo(valor):
if valor == ' ' or '' or "" or " ":
valor = None
return valor
def porcentagem(valor, total):
if valor and total:
return (valor*100)//total
return 1
| true | true |
1c3dee89e4e7a075047b3b7211c4bba5e5b0daf7 | 1,176 | py | Python | var/spack/repos/builtin/packages/flit/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 11 | 2015-10-04T02:17:46.000Z | 2018-02-07T18:23:00.000Z | var/spack/repos/builtin/packages/flit/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 22 | 2017-08-01T22:45:10.000Z | 2022-03-10T07:46:31.000Z | var/spack/repos/builtin/packages/flit/package.py | player1537-forks/spack | 822b7632222ec5a91dc7b7cda5fc0e08715bd47c | [
"ECL-2.0",
"Apache-2.0",
"MIT-0",
"MIT"
] | 4 | 2016-06-10T17:57:39.000Z | 2018-09-11T04:59:38.000Z | # 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 Flit(MakefilePackage):
"""Floating-point Litmus Tests (FLiT) is a C++ test infrastructure for
detecting variability in floating-point code caused by variations in
compiler code generation, hardware and execution environments."""
homepage = "https://pruners.github.io/flit"
url = "https://github.com/PRUNERS/FLiT/archive/v2.1.0.tar.gz"
git = "https://github.com/PRUNERS/FLiT.git"
tags = ['e4s']
version('develop', branch='devel')
version('2.1.0', sha256='b31ffa02fda1ab0f5555acdc6edc353d93d53ae8ef85e099f83bcf1c83e70885')
maintainers = ['mikebentley15']
# Add dependencies
depends_on('python@3:', type='run')
depends_on('py-toml', type='run')
depends_on('py-pyelftools', type='run', when='@:2.1.0')
depends_on('gmake', type=('run', 'build'))
depends_on('sqlite@3:', type='run')
def edit(self, spec, prefix):
env['PREFIX'] = prefix
| 33.6 | 95 | 0.669218 |
from spack import *
class Flit(MakefilePackage):
homepage = "https://pruners.github.io/flit"
url = "https://github.com/PRUNERS/FLiT/archive/v2.1.0.tar.gz"
git = "https://github.com/PRUNERS/FLiT.git"
tags = ['e4s']
version('develop', branch='devel')
version('2.1.0', sha256='b31ffa02fda1ab0f5555acdc6edc353d93d53ae8ef85e099f83bcf1c83e70885')
maintainers = ['mikebentley15']
depends_on('python@3:', type='run')
depends_on('py-toml', type='run')
depends_on('py-pyelftools', type='run', when='@:2.1.0')
depends_on('gmake', type=('run', 'build'))
depends_on('sqlite@3:', type='run')
def edit(self, spec, prefix):
env['PREFIX'] = prefix
| true | true |
1c3deec1aa2d40b6d2cb3e0da544725b1e510827 | 2,221 | py | Python | prepare/prepare_3D_RS_dense_NN_rgb_3.py | KelvinTao/pointSIFT_Age2 | b0684ee989b5f6f3dca25e9bbf15b3c5fd8cf1cf | [
"Apache-2.0"
] | null | null | null | prepare/prepare_3D_RS_dense_NN_rgb_3.py | KelvinTao/pointSIFT_Age2 | b0684ee989b5f6f3dca25e9bbf15b3c5fd8cf1cf | [
"Apache-2.0"
] | null | null | null | prepare/prepare_3D_RS_dense_NN_rgb_3.py | KelvinTao/pointSIFT_Age2 | b0684ee989b5f6f3dca25e9bbf15b3c5fd8cf1cf | [
"Apache-2.0"
] | null | null | null | import numpy as np
import glob
# train data
## collect points
def mkdata(NUM_CLASS,ids,ageNN):
#ids=np.loadtxt(filePath,dtype=str,skiprows=1,delimiter=',',usecols=0)
points_set=[]
rgb_set=[]
for i,idi in enumerate(ids):
points_set.append(np.loadtxt(path+'/points/21000_xyzrgb/'+idi+'.xyz.txt',delimiter=' '))
rgb_set.append(np.loadtxt(path+'/points/21000_xyzrgb/'+idi+'.rgb.txt',delimiter=' '))#
print(i)
#if i>10:break
## produce label
##age_threths:0-99; age range: 0-100
#ageNN=np.round(np.loadtxt(filePath,skiprows=1,delimiter=',',usecols=4))
ageNN=np.array([int(i) for i in ageNN])
assert not len(ageNN[ageNN<0])
age_label_set=[]
rows=NUM_CLASS//2
for a in ageNN:
age_label=np.zeros((rows,2))
age_label[0:int(a),0]=1
age_label[int(a):,1]=1
age_label_set.append(age_label)
return ids,np.array(points_set),np.array(rgb_set),np.array(age_label_set)
def getUse(path,filePath):
files=glob.glob(path+'/points/21000_xyzrgb/*.xyz.txt')
imgIds=[i.replace('.xyz.txt','').replace(path+'/points/21000_xyzrgb/','') for i in files]
##train
#filePath=path+'/phe/sampleTrain_NN_21000.csv'
idAge=np.loadtxt(filePath,dtype=str,skiprows=1,delimiter=',',usecols=[0,4])
tarIds=[i.replace('1.31024e+11','131024000000') for i in idAge[:,0]]
idAge[:,0]=tarIds
##
idUse=list(set(imgIds).intersection(set(tarIds)))
ageUse=[]
for idi in idUse:
for j in range(idAge.shape[0]):
if idAge[j,0]==idi:
ageUse.append(idAge[j,1])
return idUse,ageUse
##
##
path='/data/taoxm/pointSIFT_age/RS_age'
NUM_CLASS=38*2
##train data
filePath=path+'/phe/sampleTrain_NN_rgb_21000.csv'
idUse,ageUse=getUse(path,filePath)
ids,points,rgb,label=mkdata(NUM_CLASS,idUse,ageUse)
np.savez(path+'/data/sampleTrain_NN_idage_xyzrgb_21000.npz',ids=idUse,ages=ageUse,rgb_set=rgb,points_set=points,age_label_set=label)
##test
filePath=path+'/phe/sampleTest1000page_NN_rgb_21000.csv'
idUse,ageUse=getUse(path,filePath)
ids,points,rgb,label=mkdata(NUM_CLASS,idUse,ageUse)
np.savez(path+'/data/sampleTest1000page_NN_idage_xyzrgb_21000.npz',ids=idUse,ages=ageUse,rgb_set=rgb,points_set=points,age_label_set=label)
| 34.169231 | 139 | 0.703737 | import numpy as np
import glob
CLASS,ids,ageNN):
points_set=[]
rgb_set=[]
for i,idi in enumerate(ids):
points_set.append(np.loadtxt(path+'/points/21000_xyzrgb/'+idi+'.xyz.txt',delimiter=' '))
rgb_set.append(np.loadtxt(path+'/points/21000_xyzrgb/'+idi+'.rgb.txt',delimiter=' '))
print(i)
NN])
assert not len(ageNN[ageNN<0])
age_label_set=[]
rows=NUM_CLASS//2
for a in ageNN:
age_label=np.zeros((rows,2))
age_label[0:int(a),0]=1
age_label[int(a):,1]=1
age_label_set.append(age_label)
return ids,np.array(points_set),np.array(rgb_set),np.array(age_label_set)
def getUse(path,filePath):
files=glob.glob(path+'/points/21000_xyzrgb/*.xyz.txt')
imgIds=[i.replace('.xyz.txt','').replace(path+'/points/21000_xyzrgb/','') for i in files]
idAge=np.loadtxt(filePath,dtype=str,skiprows=1,delimiter=',',usecols=[0,4])
tarIds=[i.replace('1.31024e+11','131024000000') for i in idAge[:,0]]
idAge[:,0]=tarIds
idUse=list(set(imgIds).intersection(set(tarIds)))
ageUse=[]
for idi in idUse:
for j in range(idAge.shape[0]):
if idAge[j,0]==idi:
ageUse.append(idAge[j,1])
return idUse,ageUse
path='/data/taoxm/pointSIFT_age/RS_age'
NUM_CLASS=38*2
ath+'/phe/sampleTrain_NN_rgb_21000.csv'
idUse,ageUse=getUse(path,filePath)
ids,points,rgb,label=mkdata(NUM_CLASS,idUse,ageUse)
np.savez(path+'/data/sampleTrain_NN_idage_xyzrgb_21000.npz',ids=idUse,ages=ageUse,rgb_set=rgb,points_set=points,age_label_set=label)
Path=path+'/phe/sampleTest1000page_NN_rgb_21000.csv'
idUse,ageUse=getUse(path,filePath)
ids,points,rgb,label=mkdata(NUM_CLASS,idUse,ageUse)
np.savez(path+'/data/sampleTest1000page_NN_idage_xyzrgb_21000.npz',ids=idUse,ages=ageUse,rgb_set=rgb,points_set=points,age_label_set=label)
| true | true |
1c3defd2101b508f1a5eb460f42e097d74389927 | 1,217 | py | Python | invites/forms.py | phildini/bockus | 004508166f5b1a7c3c4d8accf32578a80379b385 | [
"MIT"
] | 3 | 2015-07-15T05:29:17.000Z | 2021-06-23T21:50:25.000Z | invites/forms.py | phildini/bockus | 004508166f5b1a7c3c4d8accf32578a80379b385 | [
"MIT"
] | 4 | 2020-02-11T22:15:04.000Z | 2021-06-10T17:41:51.000Z | invites/forms.py | phildini/bockus | 004508166f5b1a7c3c4d8accf32578a80379b385 | [
"MIT"
] | null | null | null | from django import forms
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
from .models import Invitation
class InvitationForm(forms.ModelForm):
class Meta:
model = Invitation
fields = ['email']
def clean(self):
try:
existing_user = User.objects.get(
email=self.cleaned_data.get('email'),
)
except User.DoesNotExist:
existing_user = None
if existing_user:
raise forms.ValidationError('User with email already exists!')
return self.cleaned_data
def save(self, *args, **kwargs):
self.instance.key = get_random_string(32).lower()
return super(InvitationForm, self).save(*args, **kwargs)
class InvitationAdminAddForm(forms.ModelForm):
class Meta:
model = Invitation
fields = ['email', 'library', 'sender', 'status']
def save(self, *args, **kwargs):
self.instance.key = get_random_string(32).lower()
return super(InvitationAdminAddForm, self).save(*args, **kwargs)
class InvitationAdminUpdateForm(forms.ModelForm):
class Meta:
model = Invitation
fields = '__all__'
| 26.456522 | 74 | 0.644207 | from django import forms
from django.contrib.auth.models import User
from django.utils.crypto import get_random_string
from .models import Invitation
class InvitationForm(forms.ModelForm):
class Meta:
model = Invitation
fields = ['email']
def clean(self):
try:
existing_user = User.objects.get(
email=self.cleaned_data.get('email'),
)
except User.DoesNotExist:
existing_user = None
if existing_user:
raise forms.ValidationError('User with email already exists!')
return self.cleaned_data
def save(self, *args, **kwargs):
self.instance.key = get_random_string(32).lower()
return super(InvitationForm, self).save(*args, **kwargs)
class InvitationAdminAddForm(forms.ModelForm):
class Meta:
model = Invitation
fields = ['email', 'library', 'sender', 'status']
def save(self, *args, **kwargs):
self.instance.key = get_random_string(32).lower()
return super(InvitationAdminAddForm, self).save(*args, **kwargs)
class InvitationAdminUpdateForm(forms.ModelForm):
class Meta:
model = Invitation
fields = '__all__'
| true | true |
1c3df03a42ca51c25dbdef75ed38729db3871c67 | 1,630 | py | Python | tests/test_sklearn_label_encoder_converter.py | vumichien/hummingbird | 8981e11ce2536167c329a5d9d20e81125a792fe4 | [
"MIT"
] | 2,772 | 2020-05-04T21:03:40.000Z | 2022-03-30T11:00:03.000Z | tests/test_sklearn_label_encoder_converter.py | vumichien/hummingbird | 8981e11ce2536167c329a5d9d20e81125a792fe4 | [
"MIT"
] | 486 | 2020-05-05T00:45:44.000Z | 2022-03-15T01:02:31.000Z | tests/test_sklearn_label_encoder_converter.py | vumichien/hummingbird | 8981e11ce2536167c329a5d9d20e81125a792fe4 | [
"MIT"
] | 232 | 2019-11-02T22:06:38.000Z | 2022-03-25T07:36:17.000Z | """
Tests sklearn LabelEncoder converter
"""
import unittest
import numpy as np
import torch
from sklearn.preprocessing import LabelEncoder
import hummingbird.ml
from onnxconverter_common.data_types import Int32TensorType
class TestSklearnLabelEncoderConverter(unittest.TestCase):
def test_model_label_encoder(self):
model = LabelEncoder()
data = np.array([1, 4, 5, 2, 0, 2], dtype=np.int32)
model.fit(data)
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06)
def test_model_label_encoder_str(self):
model = LabelEncoder()
data = [
"paris",
"tokyo",
"amsterdam",
"tokyo",
]
model.fit(data)
torch_model = hummingbird.ml.convert(model, "torch")
np.testing.assert_allclose(model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06)
# if the user gives unseen string input, we should get a failed assert
def test_skl_label_encoder_converter_raises_err(self):
model = LabelEncoder()
data = [
"paris",
"tokyo",
"amsterdam",
"tokyo",
]
model.fit(data)
torch_model = hummingbird.ml.convert(model, "torch")
# this isn't in the input data and should give an error.
data[0] = "milan"
self.assertRaises(AssertionError, torch_model.transform, data)
if __name__ == "__main__":
unittest.main()
| 28.103448 | 110 | 0.639264 | import unittest
import numpy as np
import torch
from sklearn.preprocessing import LabelEncoder
import hummingbird.ml
from onnxconverter_common.data_types import Int32TensorType
class TestSklearnLabelEncoderConverter(unittest.TestCase):
def test_model_label_encoder(self):
model = LabelEncoder()
data = np.array([1, 4, 5, 2, 0, 2], dtype=np.int32)
model.fit(data)
torch_model = hummingbird.ml.convert(model, "torch")
self.assertTrue(torch_model is not None)
np.testing.assert_allclose(model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06)
def test_model_label_encoder_str(self):
model = LabelEncoder()
data = [
"paris",
"tokyo",
"amsterdam",
"tokyo",
]
model.fit(data)
torch_model = hummingbird.ml.convert(model, "torch")
np.testing.assert_allclose(model.transform(data), torch_model.transform(data), rtol=1e-06, atol=1e-06)
def test_skl_label_encoder_converter_raises_err(self):
model = LabelEncoder()
data = [
"paris",
"tokyo",
"amsterdam",
"tokyo",
]
model.fit(data)
torch_model = hummingbird.ml.convert(model, "torch")
data[0] = "milan"
self.assertRaises(AssertionError, torch_model.transform, data)
if __name__ == "__main__":
unittest.main()
| true | true |
1c3df251962b43184bf8b5caa1dd0219ced3dfc3 | 86 | py | Python | VOPP_web/VOPP_web/setup.py | kingeta/VOPP | 2d1b80cf9be9f035cb9bda7f0b8f82fbda9bf226 | [
"MIT"
] | 4 | 2020-10-24T18:37:06.000Z | 2020-10-25T19:48:17.000Z | VOPP_web/VOPP_web/setup.py | kingeta/VOPP | 2d1b80cf9be9f035cb9bda7f0b8f82fbda9bf226 | [
"MIT"
] | null | null | null | VOPP_web/VOPP_web/setup.py | kingeta/VOPP | 2d1b80cf9be9f035cb9bda7f0b8f82fbda9bf226 | [
"MIT"
] | null | null | null | #import subprocess
#import pymongo
#client = pymongo.MongoClient()
#db = client.notes | 17.2 | 31 | 0.767442 | true | true | |
1c3df49e4607ba924b05a533daf763f35573c581 | 9,506 | py | Python | src/bin/sintact.py | ohmono/analizador-lexico | 7179a123987ad497c008dfc295482759eb238e5f | [
"MIT"
] | null | null | null | src/bin/sintact.py | ohmono/analizador-lexico | 7179a123987ad497c008dfc295482759eb238e5f | [
"MIT"
] | null | null | null | src/bin/sintact.py | ohmono/analizador-lexico | 7179a123987ad497c008dfc295482759eb238e5f | [
"MIT"
] | null | null | null |
class grammar():
terminals = {
"ELSE": "ELSE",
"IF": "IF",
"BOOL": "T",
"INT": "T",
"FLOAT": "T",
"STRING": "T",
"IDENTIFY": "V",
"CHARCONST": "V",
"FLOATCONST": "D",
"INTCONST": "D",
"PLUS": "O",
"MINUS": "O",
"MULTIPLICATION": "O",
"DIVISION": "O",
"ASIGNATION": "=",
"BOOLCOPARISON": "B",
"MINOR": "B",
"MINOREQUAL": "B",
"DIFFERENT": "B",
"HIGHER": "B",
"HIGHEREQUAL": "B",
"OPENPARENTHESIS": "(",
"CLOSEPARENTHESIS": ")",
"OPENBRACKETS": "{",
"CLOSEBRACKETS": "}",
"SEMICOLON": ";",
}
def descendente(terminals=terminals, tokens=[]):
parcial = ""
secuencia = []
try:
for token in tokens:
secuencia.append(
[f"{terminals[token[0]]}", token[1].replace(' ', '')])
except:
parcial += token[1]+' <-- unespected token '
return parcial
def NTZ(secuencia, parcial):
print(parcial+'z')
if secuencia[0][0] == 'O':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == 'B':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
def NTX(secuencia, parcial):
print(parcial+'x')
if secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == 'D':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == '(':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
secuencia, parcial = NTX(secuencia, parcial)
secuencia, parcial = NTZ(secuencia, parcial)
secuencia, parcial = NTX(secuencia, parcial)
if secuencia[0][0] == ')':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
else:
return f'<-- token {secuencia[0][1]} no esperado'
def NTB(secuencia, parcial):
print(parcial+'b')
if secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == 'D':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
def NTA(secuencia, parcial):
print(parcial+'a')
try:
if secuencia[0][0] == '=':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
secuencia, parcial = NTB(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == ';':
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
except:
return secuencia, parcial
def NTS(secuencia, parcial):
print(parcial+'s')
try:
if secuencia[0][0] == 'T':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
if secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTA(secuencia, parcial)
if secuencia[0][0] == ';':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
if secuencia[0][0] == '=':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTX(secuencia, parcial)
if secuencia[0][0] == ';':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == 'IF':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
if secuencia[0][0] == '(':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTX(secuencia, parcial)
if secuencia[0][0] == ')':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == '{':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
if secuencia[0][0] == '}':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == 'ELSE':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == '{':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
if secuencia[0][0] == '}':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == ';':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == '}':
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
except:
return secuencia, parcial
def start(secuencia, parcial):
secuencia, parcial = NTS(secuencia, parcial)
if(len(secuencia) == 0):
parcial += ' <-- Ejecutado con exito'
return parcial
else:
return parcial
return start(secuencia, parcial)
| 40.623932 | 95 | 0.411004 |
class grammar():
terminals = {
"ELSE": "ELSE",
"IF": "IF",
"BOOL": "T",
"INT": "T",
"FLOAT": "T",
"STRING": "T",
"IDENTIFY": "V",
"CHARCONST": "V",
"FLOATCONST": "D",
"INTCONST": "D",
"PLUS": "O",
"MINUS": "O",
"MULTIPLICATION": "O",
"DIVISION": "O",
"ASIGNATION": "=",
"BOOLCOPARISON": "B",
"MINOR": "B",
"MINOREQUAL": "B",
"DIFFERENT": "B",
"HIGHER": "B",
"HIGHEREQUAL": "B",
"OPENPARENTHESIS": "(",
"CLOSEPARENTHESIS": ")",
"OPENBRACKETS": "{",
"CLOSEBRACKETS": "}",
"SEMICOLON": ";",
}
def descendente(terminals=terminals, tokens=[]):
parcial = ""
secuencia = []
try:
for token in tokens:
secuencia.append(
[f"{terminals[token[0]]}", token[1].replace(' ', '')])
except:
parcial += token[1]+' <-- unespected token '
return parcial
def NTZ(secuencia, parcial):
print(parcial+'z')
if secuencia[0][0] == 'O':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == 'B':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
def NTX(secuencia, parcial):
print(parcial+'x')
if secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == 'D':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == '(':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
secuencia, parcial = NTX(secuencia, parcial)
secuencia, parcial = NTZ(secuencia, parcial)
secuencia, parcial = NTX(secuencia, parcial)
if secuencia[0][0] == ')':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
else:
return f'<-- token {secuencia[0][1]} no esperado'
def NTB(secuencia, parcial):
print(parcial+'b')
if secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
elif secuencia[0][0] == 'D':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
def NTA(secuencia, parcial):
print(parcial+'a')
try:
if secuencia[0][0] == '=':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
secuencia, parcial = NTB(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == ';':
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
except:
return secuencia, parcial
def NTS(secuencia, parcial):
print(parcial+'s')
try:
if secuencia[0][0] == 'T':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
if secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTA(secuencia, parcial)
if secuencia[0][0] == ';':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == 'V':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
if secuencia[0][0] == '=':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTX(secuencia, parcial)
if secuencia[0][0] == ';':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == 'IF':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
if secuencia[0][0] == '(':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTX(secuencia, parcial)
if secuencia[0][0] == ')':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == '{':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
if secuencia[0][0] == '}':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == 'ELSE':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == '{':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
if secuencia[0][0] == '}':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
if secuencia[0][0] == ';':
parcial += f"{secuencia[0][1]} "
del secuencia[0]
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
secuencia, parcial = NTS(secuencia, parcial)
return secuencia, parcial
elif secuencia[0][0] == '}':
return secuencia, parcial
else:
parcial += f'{secuencia[0][1]} <-- token {secuencia[0][1]} no esperado'
return secuencia, parcial
except:
return secuencia, parcial
def start(secuencia, parcial):
secuencia, parcial = NTS(secuencia, parcial)
if(len(secuencia) == 0):
parcial += ' <-- Ejecutado con exito'
return parcial
else:
return parcial
return start(secuencia, parcial)
| true | true |
1c3df651ee2881b7471116529c801f4e1e132326 | 1,304 | py | Python | tests/test_graph.py | SkamDart/codegrapher | b5191efcfadb933e846ae1d9e3136c07c4da6a8f | [
"MIT"
] | 11 | 2015-01-07T02:54:31.000Z | 2019-04-16T21:43:02.000Z | tests/test_graph.py | SkamDart/codegrapher | b5191efcfadb933e846ae1d9e3136c07c4da6a8f | [
"MIT"
] | 2 | 2019-02-08T20:28:35.000Z | 2020-12-15T05:29:16.000Z | tests/test_graph.py | SkamDart/codegrapher | b5191efcfadb933e846ae1d9e3136c07c4da6a8f | [
"MIT"
] | 4 | 2015-01-06T07:39:05.000Z | 2019-02-08T20:25:49.000Z | import os
from click.testing import CliRunner
from cli.script import cli
def get_graph_code():
return '''
from copy import deepcopy as dc
class StringCopier(object):
def __init__(self):
self.copied_strings = set()
def copy(self):
string1 = 'this'
string2 = dc(string1)
string1.add(string1)
return string2
class DoSomething(object):
def something(self):
copier = StringCopier()
copied_string = copier.copy()
'''
def test_produce_graph():
runner = CliRunner()
with runner.isolated_filesystem():
with open('code.py', 'w') as f:
f.write(get_graph_code())
runner.invoke(cli, ['code.py', '--output', 'code_output'])
assert 'code_output' in os.listdir(os.path.curdir)
assert 'code_output.pdf' in os.listdir(os.path.curdir)
def test_file_extension():
runner = CliRunner()
with runner.isolated_filesystem():
with open('code.py', 'w') as f:
f.write(get_graph_code())
runner.invoke(cli, ['code.py', '--output', 'code_output', '--output-format', 'png'])
assert 'code_output' in os.listdir(os.path.curdir)
assert 'code_output.png' in os.listdir(os.path.curdir)
assert 'code_output.pdf' not in os.listdir(os.path.curdir)
| 26.08 | 92 | 0.633436 | import os
from click.testing import CliRunner
from cli.script import cli
def get_graph_code():
return '''
from copy import deepcopy as dc
class StringCopier(object):
def __init__(self):
self.copied_strings = set()
def copy(self):
string1 = 'this'
string2 = dc(string1)
string1.add(string1)
return string2
class DoSomething(object):
def something(self):
copier = StringCopier()
copied_string = copier.copy()
'''
def test_produce_graph():
runner = CliRunner()
with runner.isolated_filesystem():
with open('code.py', 'w') as f:
f.write(get_graph_code())
runner.invoke(cli, ['code.py', '--output', 'code_output'])
assert 'code_output' in os.listdir(os.path.curdir)
assert 'code_output.pdf' in os.listdir(os.path.curdir)
def test_file_extension():
runner = CliRunner()
with runner.isolated_filesystem():
with open('code.py', 'w') as f:
f.write(get_graph_code())
runner.invoke(cli, ['code.py', '--output', 'code_output', '--output-format', 'png'])
assert 'code_output' in os.listdir(os.path.curdir)
assert 'code_output.png' in os.listdir(os.path.curdir)
assert 'code_output.pdf' not in os.listdir(os.path.curdir)
| true | true |
1c3df7222086a65563b75ff7f70519dd7c3720fe | 360 | py | Python | setup.py | shlnz/poe_tempest_iteminfo | 60acc4beec3e1856e738ccf2d26c918e91c863cc | [
"MIT"
] | null | null | null | setup.py | shlnz/poe_tempest_iteminfo | 60acc4beec3e1856e738ccf2d26c918e91c863cc | [
"MIT"
] | 1 | 2015-08-07T16:23:38.000Z | 2015-08-07T16:23:38.000Z | setup.py | shlnz/poe_tempest_iteminfo | 60acc4beec3e1856e738ccf2d26c918e91c863cc | [
"MIT"
] | null | null | null | from distutils.core import setup
import py2exe
setup(
name="POE Tempests",
author="Jens Thom",
version="0.2.1",
options={'py2exe': {'bundle_files': 1, 'compressed': True}},
zipfile=None,
console=[{"script": "poe_tempest.py",
"icon_resources": [(1, "icon.ico")],
"dest_base":"poe_tempest"
}],)
| 25.714286 | 64 | 0.563889 | from distutils.core import setup
import py2exe
setup(
name="POE Tempests",
author="Jens Thom",
version="0.2.1",
options={'py2exe': {'bundle_files': 1, 'compressed': True}},
zipfile=None,
console=[{"script": "poe_tempest.py",
"icon_resources": [(1, "icon.ico")],
"dest_base":"poe_tempest"
}],)
| true | true |
1c3df7d38b0ca5eef734240429ccf4f6a7a6e064 | 11,117 | py | Python | experiments/train_IRCR_spread.py | baicenxiao/Shaping-Advice | a5de626792dc691f301ae6c5c4384931318c0aba | [
"MIT"
] | null | null | null | experiments/train_IRCR_spread.py | baicenxiao/Shaping-Advice | a5de626792dc691f301ae6c5c4384931318c0aba | [
"MIT"
] | null | null | null | experiments/train_IRCR_spread.py | baicenxiao/Shaping-Advice | a5de626792dc691f301ae6c5c4384931318c0aba | [
"MIT"
] | null | null | null | import argparse
import numpy as np
import tensorflow as tf
import time
import pickle
import os
import maddpg.common.tf_util as U
from maddpg.trainer.maddpg import MADDPGAgentTrainer
import tensorflow.contrib.layers as layers
def parse_args():
parser = argparse.ArgumentParser("Reinforcement Learning experiments for multiagent environments")
# Environment
parser.add_argument("--scenario", type=str, default="simple", help="name of the scenario script")
parser.add_argument("--max-episode-len", type=int, default=25, help="maximum episode length")
parser.add_argument("--num-episodes", type=int, default=60000, help="number of episodes")
parser.add_argument("--num-adversaries", type=int, default=0, help="number of adversaries")
parser.add_argument("--good-policy", type=str, default="maddpg", help="policy for good agents")
parser.add_argument("--adv-policy", type=str, default="maddpg", help="policy of adversaries")
# Core training parameters
parser.add_argument("--lr", type=float, default=1e-2, help="learning rate for Adam optimizer")
parser.add_argument("--gamma", type=float, default=0.95, help="discount factor")
parser.add_argument("--batch-size", type=int, default=1024, help="number of episodes to optimize at the same time")
parser.add_argument("--num-units", type=int, default=64, help="number of units in the mlp")
# Checkpointing
parser.add_argument("--exp-name", type=str, default=None, help="name of the experiment")
parser.add_argument("--save-dir", type=str, default="/tmp/policy/", help="directory in which training state and model should be saved")
parser.add_argument("--save-rate", type=int, default=1000, help="save model once every time this many episodes are completed")
parser.add_argument("--load-dir", type=str, default="", help="directory in which training state and model are loaded")
# Evaluation
parser.add_argument("--restore", action="store_true", default=False)
parser.add_argument("--display", action="store_true", default=False)
parser.add_argument("--benchmark", action="store_true", default=False)
parser.add_argument("--benchmark-iters", type=int, default=100000, help="number of iterations run for benchmarking")
parser.add_argument("--benchmark-dir", type=str, default="./benchmark_files/", help="directory where benchmark data is saved")
parser.add_argument("--plots-dir", type=str, default="./learning_curves/", help="directory where plot data is saved")
return parser.parse_args()
def mlp_model(input, num_outputs, scope, reuse=False, num_units=64, rnn_cell=None):
# This model takes as input an observation and returns values of all actions
with tf.variable_scope(scope, reuse=reuse):
out = input
out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)
out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)
out = layers.fully_connected(out, num_outputs=num_outputs, activation_fn=None)
return out
def make_env(scenario_name, arglist, benchmark=False):
from multiagent.environment import MultiAgentEnv
import multiagent.scenarios as scenarios
# load scenario from script
scenario = scenarios.load(scenario_name + ".py").Scenario()
# create world
world = scenario.make_world()
# create multiagent environment
if benchmark:
env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation, scenario.benchmark_data)
else:
env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation)
return env
def get_trainers(env, num_adversaries, obs_shape_n, arglist):
trainers = []
model = mlp_model
trainer = MADDPGAgentTrainer
for i in range(num_adversaries):
trainers.append(trainer(
"agent_%d" % i, model, obs_shape_n, env.action_space, i, arglist,
local_q_func=(arglist.adv_policy=='ddpg')))
for i in range(num_adversaries, env.n):
trainers.append(trainer(
"agent_%d" % i, model, obs_shape_n, env.action_space, i, arglist,
local_q_func=(arglist.good_policy=='ddpg')))
return trainers
def train(arglist):
with U.single_threaded_session():
# Create environment
env = make_env(arglist.scenario, arglist, arglist.benchmark)
# Create agent trainers
obs_shape_n = [env.observation_space[i].shape for i in range(env.n)]
num_adversaries = min(env.n, arglist.num_adversaries)
trainers = get_trainers(env, num_adversaries, obs_shape_n, arglist)
print('Using good policy {} and adv policy {}'.format(arglist.good_policy, arglist.adv_policy))
# Initialize
U.initialize()
# Load previous results, if necessary
if arglist.load_dir == "":
arglist.load_dir = arglist.save_dir
if arglist.display or arglist.restore or arglist.benchmark:
print('Loading previous state...')
U.load_state(arglist.load_dir)
episode_rewards = [0.0] # sum of rewards for all agents
agent_rewards = [[0.0] for _ in range(env.n)] # individual agent reward
final_ep_rewards = [] # sum of rewards for training curve
final_ep_ag_rewards = [] # agent rewards for training curve
agent_info = [[[]]] # placeholder for benchmarking info
saver = tf.train.Saver()
obs_n = env.reset()
episode_step = 0
train_step = 0
t_start = time.time()
print('Starting iterations...')
###################################
obs_temp, action_temp, new_obs_temp, done_temp, terminal_temp = [], [], [], [], []
min_r = [1000000000]*env.n
max_r = [-1000000000]*env.n
###################################
while True:
# get action
action_n = [agent.action(obs) for agent, obs in zip(trainers,obs_n)]
# environment step
new_obs_n, rew_n, done_n, info_n = env.step(action_n)
episode_step += 1
done = all(done_n)
terminal = (episode_step >= arglist.max_episode_len)
# collect experience
# for i, agent in enumerate(trainers):
# agent.experience(obs_n[i], action_n[i], rew_n[i], new_obs_n[i], done_n[i], terminal)
###########################################################
obs_temp.append(obs_n)
action_temp.append(action_n)
new_obs_temp.append(new_obs_n)
done_temp.append(done_n)
terminal_temp.append(terminal)
###########################################################
obs_n = new_obs_n
for i, rew in enumerate(rew_n):
episode_rewards[-1] += rew
agent_rewards[i][-1] += rew
if done or terminal:
###############################################
for i, agent in enumerate(trainers):
min_r[i] = min(min_r[i], agent_rewards[i][-1])
max_r[i] = max(max_r[i], agent_rewards[i][-1])
agent.replay_buffer.min = min_r[i]
agent.replay_buffer.max = max_r[i]
for tt in range(arglist.max_episode_len):
agent.experience(obs_temp[tt][i], action_temp[tt][i], agent_rewards[i][-1], new_obs_temp[tt][i], done_temp[tt][i], terminal_temp[tt])
obs_temp, action_temp, new_obs_temp, done_temp, terminal_temp = [], [], [], [], []
###############################################
obs_n = env.reset()
episode_step = 0
episode_rewards.append(0)
for a in agent_rewards:
a.append(0)
agent_info.append([[]])
# increment global step counter
train_step += 1
# for benchmarking learned policies
if arglist.benchmark:
for i, info in enumerate(info_n):
agent_info[-1][i].append(info_n['n'])
if train_step > arglist.benchmark_iters and (done or terminal):
file_name = arglist.benchmark_dir + arglist.exp_name + '.pkl'
print('Finished benchmarking, now saving...')
with open(file_name, 'wb') as fp:
pickle.dump(agent_info[:-1], fp)
break
continue
# for displaying learned policies
if arglist.display:
time.sleep(0.1)
env.render()
continue
# update all trainers, if not in display or benchmark mode
loss = None
for agent in trainers:
agent.preupdate()
for agent in trainers:
loss = agent.update(trainers, train_step)
# save model, display training output
if terminal and (len(episode_rewards) % arglist.save_rate == 0):
U.save_state(arglist.save_dir, saver=saver)
# print statement depends on whether or not there are adversaries
if num_adversaries == 0:
print("steps: {}, episodes: {}, mean episode reward: {}, time: {}".format(
train_step, len(episode_rewards), np.mean(episode_rewards[-arglist.save_rate:]), round(time.time()-t_start, 3)))
else:
print("steps: {}, episodes: {}, mean episode reward: {}, agent episode reward: {}, time: {}".format(
train_step, len(episode_rewards), np.mean(episode_rewards[-arglist.save_rate:]),
[np.mean(rew[-arglist.save_rate:]) for rew in agent_rewards], round(time.time()-t_start, 3)))
t_start = time.time()
# Keep track of final episode reward
final_ep_rewards.append(np.mean(episode_rewards[-arglist.save_rate:]))
for rew in agent_rewards:
final_ep_ag_rewards.append(np.mean(rew[-arglist.save_rate:]))
# saves final episode reward for plotting training curve later
if len(episode_rewards) > arglist.num_episodes:
rew_file_name = arglist.plots_dir + arglist.exp_name + '/_rewards.pkl'
os.makedirs(os.path.dirname(rew_file_name), exist_ok=True)
with open(rew_file_name, 'wb') as fp:
pickle.dump(final_ep_rewards, fp)
agrew_file_name = arglist.plots_dir + arglist.exp_name + '/_agrewards.pkl'
os.makedirs(os.path.dirname(agrew_file_name), exist_ok=True)
with open(agrew_file_name, 'wb') as fp:
pickle.dump(final_ep_ag_rewards, fp)
print('...Finished total of {} episodes.'.format(len(episode_rewards)))
break
if __name__ == '__main__':
arglist = parse_args()
train(arglist)
| 49.190265 | 157 | 0.602321 | import argparse
import numpy as np
import tensorflow as tf
import time
import pickle
import os
import maddpg.common.tf_util as U
from maddpg.trainer.maddpg import MADDPGAgentTrainer
import tensorflow.contrib.layers as layers
def parse_args():
parser = argparse.ArgumentParser("Reinforcement Learning experiments for multiagent environments")
parser.add_argument("--scenario", type=str, default="simple", help="name of the scenario script")
parser.add_argument("--max-episode-len", type=int, default=25, help="maximum episode length")
parser.add_argument("--num-episodes", type=int, default=60000, help="number of episodes")
parser.add_argument("--num-adversaries", type=int, default=0, help="number of adversaries")
parser.add_argument("--good-policy", type=str, default="maddpg", help="policy for good agents")
parser.add_argument("--adv-policy", type=str, default="maddpg", help="policy of adversaries")
parser.add_argument("--lr", type=float, default=1e-2, help="learning rate for Adam optimizer")
parser.add_argument("--gamma", type=float, default=0.95, help="discount factor")
parser.add_argument("--batch-size", type=int, default=1024, help="number of episodes to optimize at the same time")
parser.add_argument("--num-units", type=int, default=64, help="number of units in the mlp")
parser.add_argument("--exp-name", type=str, default=None, help="name of the experiment")
parser.add_argument("--save-dir", type=str, default="/tmp/policy/", help="directory in which training state and model should be saved")
parser.add_argument("--save-rate", type=int, default=1000, help="save model once every time this many episodes are completed")
parser.add_argument("--load-dir", type=str, default="", help="directory in which training state and model are loaded")
parser.add_argument("--restore", action="store_true", default=False)
parser.add_argument("--display", action="store_true", default=False)
parser.add_argument("--benchmark", action="store_true", default=False)
parser.add_argument("--benchmark-iters", type=int, default=100000, help="number of iterations run for benchmarking")
parser.add_argument("--benchmark-dir", type=str, default="./benchmark_files/", help="directory where benchmark data is saved")
parser.add_argument("--plots-dir", type=str, default="./learning_curves/", help="directory where plot data is saved")
return parser.parse_args()
def mlp_model(input, num_outputs, scope, reuse=False, num_units=64, rnn_cell=None):
with tf.variable_scope(scope, reuse=reuse):
out = input
out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)
out = layers.fully_connected(out, num_outputs=num_units, activation_fn=tf.nn.relu)
out = layers.fully_connected(out, num_outputs=num_outputs, activation_fn=None)
return out
def make_env(scenario_name, arglist, benchmark=False):
from multiagent.environment import MultiAgentEnv
import multiagent.scenarios as scenarios
scenario = scenarios.load(scenario_name + ".py").Scenario()
world = scenario.make_world()
if benchmark:
env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation, scenario.benchmark_data)
else:
env = MultiAgentEnv(world, scenario.reset_world, scenario.reward, scenario.observation)
return env
def get_trainers(env, num_adversaries, obs_shape_n, arglist):
trainers = []
model = mlp_model
trainer = MADDPGAgentTrainer
for i in range(num_adversaries):
trainers.append(trainer(
"agent_%d" % i, model, obs_shape_n, env.action_space, i, arglist,
local_q_func=(arglist.adv_policy=='ddpg')))
for i in range(num_adversaries, env.n):
trainers.append(trainer(
"agent_%d" % i, model, obs_shape_n, env.action_space, i, arglist,
local_q_func=(arglist.good_policy=='ddpg')))
return trainers
def train(arglist):
with U.single_threaded_session():
env = make_env(arglist.scenario, arglist, arglist.benchmark)
obs_shape_n = [env.observation_space[i].shape for i in range(env.n)]
num_adversaries = min(env.n, arglist.num_adversaries)
trainers = get_trainers(env, num_adversaries, obs_shape_n, arglist)
print('Using good policy {} and adv policy {}'.format(arglist.good_policy, arglist.adv_policy))
U.initialize()
if arglist.load_dir == "":
arglist.load_dir = arglist.save_dir
if arglist.display or arglist.restore or arglist.benchmark:
print('Loading previous state...')
U.load_state(arglist.load_dir)
episode_rewards = [0.0]
agent_rewards = [[0.0] for _ in range(env.n)]
final_ep_rewards = []
final_ep_ag_rewards = []
agent_info = [[[]]]
saver = tf.train.Saver()
obs_n = env.reset()
episode_step = 0
train_step = 0
t_start = time.time()
print('Starting iterations...')
| true | true |
1c3df8f0bc4a6c6784aa88020c984a8f205a872b | 3,632 | py | Python | app/scripts/management/commands/notify_pairwise.py | Sirius-social/TMTM | 5b4d426e358fc9fd6cff7ec84861c0388d3785ce | [
"Apache-2.0"
] | null | null | null | app/scripts/management/commands/notify_pairwise.py | Sirius-social/TMTM | 5b4d426e358fc9fd6cff7ec84861c0388d3785ce | [
"Apache-2.0"
] | null | null | null | app/scripts/management/commands/notify_pairwise.py | Sirius-social/TMTM | 5b4d426e358fc9fd6cff7ec84861c0388d3785ce | [
"Apache-2.0"
] | null | null | null | import asyncio
import logging
from typing import List
import sirius_sdk
from sirius_sdk.agent.wallet import NYMRole
from django.conf import settings
from channels.db import database_sync_to_async
from django.core.management.base import BaseCommand
from ui.models import PairwiseRecord
from wrapper.models import Ledger, Transaction
class Command(BaseCommand):
help = 'Notify pairwise with message'
STATISTIC_TEXT = 'Статистика'
UNSUBSCRIBE_TEXT = 'Отписаться'
SUBSCRIBE_TEXT = 'Подписаться'
def add_arguments(self, parser):
parser.add_argument('message', type=str)
def handle(self, *args, **options):
message = options['message']
async def run(theirs: List[str]):
async def process_pairwise(their_did: str):
to = await sirius_sdk.PairwiseList.load_for_did(their_did)
if to:
question = sirius_sdk.aries_rfc.Question(
valid_responses=[self.STATISTIC_TEXT, self.UNSUBSCRIBE_TEXT],
question_text='Новое событие',
question_detail=message
)
question.set_ttl(60)
success, answer = await sirius_sdk.aries_rfc.ask_and_wait_answer(question, to)
if success and isinstance(answer, sirius_sdk.aries_rfc.Answer):
await self.process_answer(answer, to)
coros = [process_pairwise(did) for did in theirs]
await asyncio.wait(coros, timeout=120, return_when=asyncio.ALL_COMPLETED)
dids = [rec.their_did for rec in PairwiseRecord.objects.filter(subscribe=True).all()]
if dids:
asyncio.get_event_loop().run_until_complete(run(dids))
@classmethod
async def process_answer(cls, answer: sirius_sdk.aries_rfc.Answer, their: sirius_sdk.Pairwise):
def set_subscription(their_did: str, flag: bool):
rec = PairwiseRecord.objects.filter(their_did=their_did).first()
if rec:
rec.subscribe = flag
rec.save()
def load_statistic():
return Ledger.objects.count(), Transaction.objects.count()
if answer.response == cls.UNSUBSCRIBE_TEXT:
await database_sync_to_async(set_subscription)(their.their.did, False)
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='Вы отписаны от уведомлений.',
locale='ru'
),
to=their
)
elif answer.response == cls.SUBSCRIBE_TEXT:
await database_sync_to_async(set_subscription)(their.their.did, True)
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='Вы подписаны на уведомления.',
locale='ru'
),
to=their
)
elif answer.response == cls.STATISTIC_TEXT:
ledger_cnt, txn_cnt = await database_sync_to_async(load_statistic)()
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='На текущий момент в системе:\nКонтейнеров: %d\nНакладных: %d' % (ledger_cnt, txn_cnt),
locale='ru'
),
to=their
)
else:
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='Неизвестный ответ',
locale='ru'
),
to=their
)
| 37.061224 | 115 | 0.591685 | import asyncio
import logging
from typing import List
import sirius_sdk
from sirius_sdk.agent.wallet import NYMRole
from django.conf import settings
from channels.db import database_sync_to_async
from django.core.management.base import BaseCommand
from ui.models import PairwiseRecord
from wrapper.models import Ledger, Transaction
class Command(BaseCommand):
help = 'Notify pairwise with message'
STATISTIC_TEXT = 'Статистика'
UNSUBSCRIBE_TEXT = 'Отписаться'
SUBSCRIBE_TEXT = 'Подписаться'
def add_arguments(self, parser):
parser.add_argument('message', type=str)
def handle(self, *args, **options):
message = options['message']
async def run(theirs: List[str]):
async def process_pairwise(their_did: str):
to = await sirius_sdk.PairwiseList.load_for_did(their_did)
if to:
question = sirius_sdk.aries_rfc.Question(
valid_responses=[self.STATISTIC_TEXT, self.UNSUBSCRIBE_TEXT],
question_text='Новое событие',
question_detail=message
)
question.set_ttl(60)
success, answer = await sirius_sdk.aries_rfc.ask_and_wait_answer(question, to)
if success and isinstance(answer, sirius_sdk.aries_rfc.Answer):
await self.process_answer(answer, to)
coros = [process_pairwise(did) for did in theirs]
await asyncio.wait(coros, timeout=120, return_when=asyncio.ALL_COMPLETED)
dids = [rec.their_did for rec in PairwiseRecord.objects.filter(subscribe=True).all()]
if dids:
asyncio.get_event_loop().run_until_complete(run(dids))
@classmethod
async def process_answer(cls, answer: sirius_sdk.aries_rfc.Answer, their: sirius_sdk.Pairwise):
def set_subscription(their_did: str, flag: bool):
rec = PairwiseRecord.objects.filter(their_did=their_did).first()
if rec:
rec.subscribe = flag
rec.save()
def load_statistic():
return Ledger.objects.count(), Transaction.objects.count()
if answer.response == cls.UNSUBSCRIBE_TEXT:
await database_sync_to_async(set_subscription)(their.their.did, False)
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='Вы отписаны от уведомлений.',
locale='ru'
),
to=their
)
elif answer.response == cls.SUBSCRIBE_TEXT:
await database_sync_to_async(set_subscription)(their.their.did, True)
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='Вы подписаны на уведомления.',
locale='ru'
),
to=their
)
elif answer.response == cls.STATISTIC_TEXT:
ledger_cnt, txn_cnt = await database_sync_to_async(load_statistic)()
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='На текущий момент в системе:\nКонтейнеров: %d\nНакладных: %d' % (ledger_cnt, txn_cnt),
locale='ru'
),
to=their
)
else:
await sirius_sdk.send_to(
message=sirius_sdk.aries_rfc.Message(
content='Неизвестный ответ',
locale='ru'
),
to=their
)
| true | true |
1c3df9651bbbf8ab9a666c63c99033113a2e4ee7 | 14,917 | py | Python | deepxde/model.py | ziyi-yang/deepxde | 61af63c3eeb6ea625670b2886be1bf51fa1df554 | [
"Apache-2.0"
] | null | null | null | deepxde/model.py | ziyi-yang/deepxde | 61af63c3eeb6ea625670b2886be1bf51fa1df554 | [
"Apache-2.0"
] | null | null | null | deepxde/model.py | ziyi-yang/deepxde | 61af63c3eeb6ea625670b2886be1bf51fa1df554 | [
"Apache-2.0"
] | 1 | 2021-04-06T07:16:23.000Z | 2021-04-06T07:16:23.000Z | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from . import display
from . import losses as losses_module
from . import metrics as metrics_module
from . import train as train_module
from .backend import tf
from .callbacks import CallbackList
from .utils import guarantee_initialized_variables, timing
class Model(object):
"""The ``Model`` class trains a ``Map`` on a ``Data``.
Args:
data: ``deepxde.data.Data`` instance.
net: ``deepxde.maps.Map`` instance.
"""
def __init__(self, data, net):
self.data = data
self.net = net
self.optimizer = None
self.batch_size = None
self.losses = None
self.totalloss = None
self.train_op = None
self.metrics = None
self.sess = None
self.saver = None
self.train_state = TrainState()
self.losshistory = LossHistory()
self.stop_training = False
self.callbacks = None
def close(self):
self._close_tfsession()
@timing
def compile(
self,
optimizer,
lr=None,
loss="MSE",
metrics=None,
decay=None,
loss_weights=None,
):
"""Configures the model for training.
Args:
optimizer: String. Name of optimizer.
lr: A Tensor or a floating point value. The learning rate.
loss: String (name of objective function) or objective function.
metrics: List of metrics to be evaluated by the model during training.
decay: Tuple. Name and parameters of decay to the initial learning rate. One of the following options:
- `inverse time decay <https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/inverse_time_decay>`_: ("inverse time", decay_steps, decay_rate)
- `cosine decay <https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/cosine_decay>`_: ("cosine", decay_steps, alpha)
loss_weights: A list specifying scalar coefficients (Python floats)
to weight the loss contributions. The loss value that will be minimized by the model
will then be the weighted sum of all individual losses,
weighted by the loss_weights coefficients.
"""
print("Compiling model...")
if not self.net.built:
self.net.build()
self._open_tfsession()
self.optimizer = optimizer
loss = losses_module.get(loss)
self.losses = self.data.losses(self.net.targets, self.net.outputs, loss, self)
if self.net.regularizer is not None:
self.losses.append(tf.losses.get_regularization_loss())
self.losses = tf.convert_to_tensor(self.losses)
if loss_weights is not None:
self.losses *= loss_weights
self.losshistory.set_loss_weights(loss_weights)
self.totalloss = tf.reduce_sum(self.losses)
self.train_op = train_module.get_train_op(
self.totalloss, self.optimizer, lr=lr, decay=decay
)
metrics = metrics or []
self.metrics = [metrics_module.get(m) for m in metrics]
@timing
def train(
self,
epochs=None,
batch_size=None,
display_every=1000,
uncertainty=False,
disregard_previous_best=False,
callbacks=None,
model_restore_path=None,
model_save_path=None,
print_model=False,
):
"""Trains the model for a fixed number of epochs (iterations on a dataset).
Args:
epochs: Integer. Number of epochs to train the model.
batch_size: Integer or ``None``. Not fully supported yet.
display_every: Integer. Print the loss and metrics every this steps.
uncertainty: Boolean. If ``True``, use Monte-Carlo Dropout to estimate uncertainty.
disregard_previous_best: If ``True``, disregard the previous saved best model.
callbacks: List of ``deepxde.callbacks.Callback`` instances.
List of callbacks to apply during training.
model_restore_path: String. Path where parameters were previously saved.
See ``save_path`` in `tf.train.Saver.restore <https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Saver#restore>`_.
model_save_path: String. Prefix of filenames created for the checkpoint.
See ``save_path`` in `tf.train.Saver.save <https://www.tensorflow.org/api_docs/python/tf/compat/v1/train/Saver#save>`_.
print_model: If ``True``, print the values of all variables.
"""
self.batch_size = batch_size
self.callbacks = CallbackList(callbacks=callbacks)
self.callbacks.set_model(self)
if disregard_previous_best:
self.train_state.disregard_best()
if self.train_state.step == 0:
print("Initializing variables...")
self.sess.run(tf.global_variables_initializer())
else:
guarantee_initialized_variables(self.sess)
if model_restore_path is not None:
print("Restoring model from {} ...".format(model_restore_path))
self.saver.restore(self.sess, model_restore_path)
print("Training model...\n")
self.stop_training = False
self.train_state.set_data_train(*self.data.train_next_batch(self.batch_size))
self.train_state.set_data_test(*self.data.test())
self._test(uncertainty)
self.callbacks.on_train_begin()
if train_module.is_scipy_opts(self.optimizer):
self._train_scipy(display_every, uncertainty)
else:
if epochs is None:
raise ValueError("No epochs for {}.".format(self.optimizer))
self._train_sgd(epochs, display_every, uncertainty)
self.callbacks.on_train_end()
print("")
display.training_display.summary(self.train_state)
if print_model:
self._print_model()
if model_save_path is not None:
self.save(model_save_path, verbose=1)
return self.losshistory, self.train_state
def evaluate(self, x, y, callbacks=None):
"""Returns the loss values & metrics values for the model in test mode.
"""
raise NotImplementedError(
"Model.evaluate to be implemented. Alternatively, use Model.predict."
)
@timing
def predict(self, x, operator=None, callbacks=None):
"""Generates output predictions for the input samples.
"""
print("Predicting...")
self.callbacks = CallbackList(callbacks=callbacks)
self.callbacks.set_model(self)
self.callbacks.on_predict_begin()
if operator is None:
y = self.sess.run(
self.net.outputs, feed_dict=self.net.feed_dict(False, False, 2, x)
)
else:
y = self.sess.run(
operator(self.net.inputs, self.net.outputs),
feed_dict=self.net.feed_dict(False, False, 2, x),
)
self.callbacks.on_predict_end()
return y
def _open_tfsession(self):
if self.sess is not None:
return
tfconfig = tf.ConfigProto()
tfconfig.gpu_options.allow_growth = True
self.sess = tf.Session(config=tfconfig)
self.saver = tf.train.Saver(max_to_keep=None)
self.train_state.set_tfsession(self.sess)
def _close_tfsession(self):
self.sess.close()
def _train_sgd(self, epochs, display_every, uncertainty):
for i in range(epochs):
self.callbacks.on_epoch_begin()
self.callbacks.on_batch_begin()
self.train_state.set_data_train(
*self.data.train_next_batch(self.batch_size)
)
self.sess.run(
self.train_op,
feed_dict=self.net.feed_dict(
True, True, 0, self.train_state.X_train, self.train_state.y_train
),
)
self.train_state.epoch += 1
self.train_state.step += 1
if self.train_state.step % display_every == 0 or i + 1 == epochs:
self._test(uncertainty)
self.callbacks.on_batch_end()
self.callbacks.on_epoch_end()
if self.stop_training:
break
def _train_scipy(self, display_every, uncertainty):
def loss_callback(loss_train):
self.train_state.epoch += 1
self.train_state.step += 1
self.train_state.loss_train = loss_train
self.train_state.loss_test = None
self.train_state.metrics_test = None
self.losshistory.append(
self.train_state.step, self.train_state.loss_train, None, None
)
if self.train_state.step % display_every == 0:
display.training_display(self.train_state)
self.train_state.set_data_train(*self.data.train_next_batch(self.batch_size))
self.train_op.minimize(
self.sess,
feed_dict=self.net.feed_dict(
True, True, 0, self.train_state.X_train, self.train_state.y_train
),
fetches=[self.losses],
loss_callback=loss_callback,
)
self._test(uncertainty)
def _test(self, uncertainty):
self.train_state.loss_train, self.train_state.y_pred_train = self.sess.run(
[self.losses, self.net.outputs],
feed_dict=self.net.feed_dict(
False, False, 0, self.train_state.X_train, self.train_state.y_train
),
)
if uncertainty:
# TODO: support multi outputs
losses, y_preds = [], []
for _ in range(1000):
loss_one, y_pred_test_one = self.sess.run(
[self.losses, self.net.outputs],
feed_dict=self.net.feed_dict(
False, True, 1, self.train_state.X_test, self.train_state.y_test
),
)
losses.append(loss_one)
y_preds.append(y_pred_test_one)
self.train_state.loss_test = np.mean(losses, axis=0)
self.train_state.y_pred_test = np.mean(y_preds, axis=0)
self.train_state.y_std_test = np.std(y_preds, axis=0)
else:
self.train_state.loss_test, self.train_state.y_pred_test = self.sess.run(
[self.losses, self.net.outputs],
feed_dict=self.net.feed_dict(
False, False, 1, self.train_state.X_test, self.train_state.y_test
),
)
if isinstance(self.net.targets, (list, tuple)):
self.train_state.metrics_test = [
m(self.train_state.y_test[i], self.train_state.y_pred_test[i])
for m in self.metrics
for i in range(len(self.net.targets))
]
else:
self.train_state.metrics_test = [
m(self.train_state.y_test, self.train_state.y_pred_test)
for m in self.metrics
]
self.train_state.update_best()
self.losshistory.append(
self.train_state.step,
self.train_state.loss_train,
self.train_state.loss_test,
self.train_state.metrics_test,
)
display.training_display(self.train_state)
def _print_model(self):
variables_names = [v.name for v in tf.trainable_variables()]
values = self.sess.run(variables_names)
for k, v in zip(variables_names, values):
print("Variable: {}, Shape: {}".format(k, v.shape))
print(v)
def save(self, save_path, verbose=0):
if verbose > 0:
print(
"Epoch {}: saving model to {}-{} ...\n".format(
self.train_state.epoch, save_path, self.train_state.epoch
)
)
self.saver.save(self.sess, save_path, global_step=self.train_state.epoch)
def restore(self, save_path, verbose=0):
if verbose > 0:
print("Restoring model from {} ...\n".format(save_path))
self.saver.restore(self.sess, save_path)
class TrainState(object):
def __init__(self):
self.epoch, self.step = 0, 0
self.sess = None
# Data
self.X_train, self.y_train = None, None
self.X_test, self.y_test = None, None
# Results of current step
self.y_pred_train = None
self.loss_train, self.loss_test = None, None
self.y_pred_test, self.y_std_test = None, None
self.metrics_test = None
# The best results correspond to the min train loss
self.best_step = 0
self.best_loss_train, self.best_loss_test = np.inf, np.inf
self.best_y, self.best_ystd = None, None
self.best_metrics = None
def set_tfsession(self, sess):
self.sess = sess
def set_data_train(self, X_train, y_train):
self.X_train, self.y_train = X_train, y_train
def set_data_test(self, X_test, y_test):
self.X_test, self.y_test = X_test, y_test
def update_best(self):
if self.best_loss_train > np.sum(self.loss_train):
self.best_step = self.step
self.best_loss_train = np.sum(self.loss_train)
self.best_loss_test = np.sum(self.loss_test)
self.best_y, self.best_ystd = self.y_pred_test, self.y_std_test
self.best_metrics = self.metrics_test
def disregard_best(self):
self.best_loss_train = np.inf
def packed_data(self):
def merge_values(values):
if values is None:
return None
return np.hstack(values) if isinstance(values, (list, tuple)) else values
X_train = merge_values(self.X_train)
y_train = merge_values(self.y_train)
X_test = merge_values(self.X_test)
y_test = merge_values(self.y_test)
best_y = merge_values(self.best_y)
best_ystd = merge_values(self.best_ystd)
return X_train, y_train, X_test, y_test, best_y, best_ystd
class LossHistory(object):
def __init__(self):
self.steps = []
self.loss_train = []
self.loss_test = []
self.metrics_test = []
self.loss_weights = 1
def set_loss_weights(self, loss_weights):
self.loss_weights = loss_weights
def append(self, step, loss_train, loss_test, metrics_test):
self.steps.append(step)
self.loss_train.append(loss_train)
if loss_test is None:
loss_test = self.loss_test[-1]
if metrics_test is None:
metrics_test = self.metrics_test[-1]
self.loss_test.append(loss_test)
self.metrics_test.append(metrics_test)
| 36.923267 | 165 | 0.609104 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from . import display
from . import losses as losses_module
from . import metrics as metrics_module
from . import train as train_module
from .backend import tf
from .callbacks import CallbackList
from .utils import guarantee_initialized_variables, timing
class Model(object):
def __init__(self, data, net):
self.data = data
self.net = net
self.optimizer = None
self.batch_size = None
self.losses = None
self.totalloss = None
self.train_op = None
self.metrics = None
self.sess = None
self.saver = None
self.train_state = TrainState()
self.losshistory = LossHistory()
self.stop_training = False
self.callbacks = None
def close(self):
self._close_tfsession()
@timing
def compile(
self,
optimizer,
lr=None,
loss="MSE",
metrics=None,
decay=None,
loss_weights=None,
):
print("Compiling model...")
if not self.net.built:
self.net.build()
self._open_tfsession()
self.optimizer = optimizer
loss = losses_module.get(loss)
self.losses = self.data.losses(self.net.targets, self.net.outputs, loss, self)
if self.net.regularizer is not None:
self.losses.append(tf.losses.get_regularization_loss())
self.losses = tf.convert_to_tensor(self.losses)
if loss_weights is not None:
self.losses *= loss_weights
self.losshistory.set_loss_weights(loss_weights)
self.totalloss = tf.reduce_sum(self.losses)
self.train_op = train_module.get_train_op(
self.totalloss, self.optimizer, lr=lr, decay=decay
)
metrics = metrics or []
self.metrics = [metrics_module.get(m) for m in metrics]
@timing
def train(
self,
epochs=None,
batch_size=None,
display_every=1000,
uncertainty=False,
disregard_previous_best=False,
callbacks=None,
model_restore_path=None,
model_save_path=None,
print_model=False,
):
self.batch_size = batch_size
self.callbacks = CallbackList(callbacks=callbacks)
self.callbacks.set_model(self)
if disregard_previous_best:
self.train_state.disregard_best()
if self.train_state.step == 0:
print("Initializing variables...")
self.sess.run(tf.global_variables_initializer())
else:
guarantee_initialized_variables(self.sess)
if model_restore_path is not None:
print("Restoring model from {} ...".format(model_restore_path))
self.saver.restore(self.sess, model_restore_path)
print("Training model...\n")
self.stop_training = False
self.train_state.set_data_train(*self.data.train_next_batch(self.batch_size))
self.train_state.set_data_test(*self.data.test())
self._test(uncertainty)
self.callbacks.on_train_begin()
if train_module.is_scipy_opts(self.optimizer):
self._train_scipy(display_every, uncertainty)
else:
if epochs is None:
raise ValueError("No epochs for {}.".format(self.optimizer))
self._train_sgd(epochs, display_every, uncertainty)
self.callbacks.on_train_end()
print("")
display.training_display.summary(self.train_state)
if print_model:
self._print_model()
if model_save_path is not None:
self.save(model_save_path, verbose=1)
return self.losshistory, self.train_state
def evaluate(self, x, y, callbacks=None):
raise NotImplementedError(
"Model.evaluate to be implemented. Alternatively, use Model.predict."
)
@timing
def predict(self, x, operator=None, callbacks=None):
print("Predicting...")
self.callbacks = CallbackList(callbacks=callbacks)
self.callbacks.set_model(self)
self.callbacks.on_predict_begin()
if operator is None:
y = self.sess.run(
self.net.outputs, feed_dict=self.net.feed_dict(False, False, 2, x)
)
else:
y = self.sess.run(
operator(self.net.inputs, self.net.outputs),
feed_dict=self.net.feed_dict(False, False, 2, x),
)
self.callbacks.on_predict_end()
return y
def _open_tfsession(self):
if self.sess is not None:
return
tfconfig = tf.ConfigProto()
tfconfig.gpu_options.allow_growth = True
self.sess = tf.Session(config=tfconfig)
self.saver = tf.train.Saver(max_to_keep=None)
self.train_state.set_tfsession(self.sess)
def _close_tfsession(self):
self.sess.close()
def _train_sgd(self, epochs, display_every, uncertainty):
for i in range(epochs):
self.callbacks.on_epoch_begin()
self.callbacks.on_batch_begin()
self.train_state.set_data_train(
*self.data.train_next_batch(self.batch_size)
)
self.sess.run(
self.train_op,
feed_dict=self.net.feed_dict(
True, True, 0, self.train_state.X_train, self.train_state.y_train
),
)
self.train_state.epoch += 1
self.train_state.step += 1
if self.train_state.step % display_every == 0 or i + 1 == epochs:
self._test(uncertainty)
self.callbacks.on_batch_end()
self.callbacks.on_epoch_end()
if self.stop_training:
break
def _train_scipy(self, display_every, uncertainty):
def loss_callback(loss_train):
self.train_state.epoch += 1
self.train_state.step += 1
self.train_state.loss_train = loss_train
self.train_state.loss_test = None
self.train_state.metrics_test = None
self.losshistory.append(
self.train_state.step, self.train_state.loss_train, None, None
)
if self.train_state.step % display_every == 0:
display.training_display(self.train_state)
self.train_state.set_data_train(*self.data.train_next_batch(self.batch_size))
self.train_op.minimize(
self.sess,
feed_dict=self.net.feed_dict(
True, True, 0, self.train_state.X_train, self.train_state.y_train
),
fetches=[self.losses],
loss_callback=loss_callback,
)
self._test(uncertainty)
def _test(self, uncertainty):
self.train_state.loss_train, self.train_state.y_pred_train = self.sess.run(
[self.losses, self.net.outputs],
feed_dict=self.net.feed_dict(
False, False, 0, self.train_state.X_train, self.train_state.y_train
),
)
if uncertainty:
losses, y_preds = [], []
for _ in range(1000):
loss_one, y_pred_test_one = self.sess.run(
[self.losses, self.net.outputs],
feed_dict=self.net.feed_dict(
False, True, 1, self.train_state.X_test, self.train_state.y_test
),
)
losses.append(loss_one)
y_preds.append(y_pred_test_one)
self.train_state.loss_test = np.mean(losses, axis=0)
self.train_state.y_pred_test = np.mean(y_preds, axis=0)
self.train_state.y_std_test = np.std(y_preds, axis=0)
else:
self.train_state.loss_test, self.train_state.y_pred_test = self.sess.run(
[self.losses, self.net.outputs],
feed_dict=self.net.feed_dict(
False, False, 1, self.train_state.X_test, self.train_state.y_test
),
)
if isinstance(self.net.targets, (list, tuple)):
self.train_state.metrics_test = [
m(self.train_state.y_test[i], self.train_state.y_pred_test[i])
for m in self.metrics
for i in range(len(self.net.targets))
]
else:
self.train_state.metrics_test = [
m(self.train_state.y_test, self.train_state.y_pred_test)
for m in self.metrics
]
self.train_state.update_best()
self.losshistory.append(
self.train_state.step,
self.train_state.loss_train,
self.train_state.loss_test,
self.train_state.metrics_test,
)
display.training_display(self.train_state)
def _print_model(self):
variables_names = [v.name for v in tf.trainable_variables()]
values = self.sess.run(variables_names)
for k, v in zip(variables_names, values):
print("Variable: {}, Shape: {}".format(k, v.shape))
print(v)
def save(self, save_path, verbose=0):
if verbose > 0:
print(
"Epoch {}: saving model to {}-{} ...\n".format(
self.train_state.epoch, save_path, self.train_state.epoch
)
)
self.saver.save(self.sess, save_path, global_step=self.train_state.epoch)
def restore(self, save_path, verbose=0):
if verbose > 0:
print("Restoring model from {} ...\n".format(save_path))
self.saver.restore(self.sess, save_path)
class TrainState(object):
def __init__(self):
self.epoch, self.step = 0, 0
self.sess = None
self.X_train, self.y_train = None, None
self.X_test, self.y_test = None, None
self.y_pred_train = None
self.loss_train, self.loss_test = None, None
self.y_pred_test, self.y_std_test = None, None
self.metrics_test = None
self.best_step = 0
self.best_loss_train, self.best_loss_test = np.inf, np.inf
self.best_y, self.best_ystd = None, None
self.best_metrics = None
def set_tfsession(self, sess):
self.sess = sess
def set_data_train(self, X_train, y_train):
self.X_train, self.y_train = X_train, y_train
def set_data_test(self, X_test, y_test):
self.X_test, self.y_test = X_test, y_test
def update_best(self):
if self.best_loss_train > np.sum(self.loss_train):
self.best_step = self.step
self.best_loss_train = np.sum(self.loss_train)
self.best_loss_test = np.sum(self.loss_test)
self.best_y, self.best_ystd = self.y_pred_test, self.y_std_test
self.best_metrics = self.metrics_test
def disregard_best(self):
self.best_loss_train = np.inf
def packed_data(self):
def merge_values(values):
if values is None:
return None
return np.hstack(values) if isinstance(values, (list, tuple)) else values
X_train = merge_values(self.X_train)
y_train = merge_values(self.y_train)
X_test = merge_values(self.X_test)
y_test = merge_values(self.y_test)
best_y = merge_values(self.best_y)
best_ystd = merge_values(self.best_ystd)
return X_train, y_train, X_test, y_test, best_y, best_ystd
class LossHistory(object):
def __init__(self):
self.steps = []
self.loss_train = []
self.loss_test = []
self.metrics_test = []
self.loss_weights = 1
def set_loss_weights(self, loss_weights):
self.loss_weights = loss_weights
def append(self, step, loss_train, loss_test, metrics_test):
self.steps.append(step)
self.loss_train.append(loss_train)
if loss_test is None:
loss_test = self.loss_test[-1]
if metrics_test is None:
metrics_test = self.metrics_test[-1]
self.loss_test.append(loss_test)
self.metrics_test.append(metrics_test)
| true | true |
1c3df9e5cb7a2ba8fc0b5c99848d68ddb59a0111 | 3,095 | py | Python | pypureclient/flasharray/FA_2_5/models/alert_response.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 14 | 2018-12-07T18:30:27.000Z | 2022-02-22T09:12:33.000Z | pypureclient/flasharray/FA_2_5/models/alert_response.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 28 | 2019-09-17T21:03:52.000Z | 2022-03-29T22:07:35.000Z | pypureclient/flasharray/FA_2_5/models/alert_response.py | Flav-STOR-WL/py-pure-client | 03b889c997d90380ac5d6380ca5d5432792d3e89 | [
"BSD-2-Clause"
] | 15 | 2020-06-11T15:50:08.000Z | 2022-03-21T09:27:25.000Z | # coding: utf-8
"""
FlashArray REST API
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: 2.5
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_5 import models
class AlertResponse(object):
"""
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 = {
'items': 'list[Alert]'
}
attribute_map = {
'items': 'items'
}
required_args = {
}
def __init__(
self,
items=None, # type: List[models.Alert]
):
"""
Keyword args:
items (list[Alert])
"""
if items is not None:
self.items = items
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `AlertResponse`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def to_dict(self):
"""Returns the model properties as a dict"""
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
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(AlertResponse, 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, AlertResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
"""Returns true if both objects are not equal"""
return not self == other
| 27.633929 | 105 | 0.53958 |
import pprint
import re
import six
import typing
from ....properties import Property
if typing.TYPE_CHECKING:
from pypureclient.flasharray.FA_2_5 import models
class AlertResponse(object):
swagger_types = {
'items': 'list[Alert]'
}
attribute_map = {
'items': 'items'
}
required_args = {
}
def __init__(
self,
items=None,
):
if items is not None:
self.items = items
def __setattr__(self, key, value):
if key not in self.attribute_map:
raise KeyError("Invalid key `{}` for `AlertResponse`".format(key))
self.__dict__[key] = value
def __getattribute__(self, item):
value = object.__getattribute__(self, item)
if isinstance(value, Property):
raise AttributeError
else:
return value
def to_dict(self):
result = {}
for attr, _ in six.iteritems(self.swagger_types):
if hasattr(self, attr):
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(AlertResponse, dict):
for key, value in self.items():
result[key] = value
return result
def to_str(self):
return pprint.pformat(self.to_dict())
def __repr__(self):
return self.to_str()
def __eq__(self, other):
if not isinstance(other, AlertResponse):
return False
return self.__dict__ == other.__dict__
def __ne__(self, other):
return not self == other
| true | true |
1c3dfc60d521dd6aa652983f8187c2ac98919135 | 4,860 | py | Python | allennlp/data/dataset_readers/coreference_resolution/preco.py | apmoore1/allennlp | bdb29a831ed68cb948b18b42fa61646b9ec11bf8 | [
"Apache-2.0"
] | null | null | null | allennlp/data/dataset_readers/coreference_resolution/preco.py | apmoore1/allennlp | bdb29a831ed68cb948b18b42fa61646b9ec11bf8 | [
"Apache-2.0"
] | null | null | null | allennlp/data/dataset_readers/coreference_resolution/preco.py | apmoore1/allennlp | bdb29a831ed68cb948b18b42fa61646b9ec11bf8 | [
"Apache-2.0"
] | 1 | 2020-02-19T11:34:32.000Z | 2020-02-19T11:34:32.000Z | import json
import logging
from typing import Dict, List, Optional, Tuple
from overrides import overrides
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.coreference_resolution.util import make_coref_instance
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.instance import Instance
from allennlp.data.tokenizers import PretrainedTransformerTokenizer
from allennlp.data.token_indexers import SingleIdTokenIndexer, TokenIndexer
logger = logging.getLogger(__name__)
@DatasetReader.register("preco")
class PrecoReader(DatasetReader):
"""
Reads a single JSON-lines file for [the PreCo dataset](https://www.aclweb.org/anthology/D18-1016.pdf).
Each line contains a "sentences" key for a list of sentences and a "mention_clusters" key
for the clusters.
Returns a `Dataset` where the `Instances` have four fields : `text`, a `TextField`
containing the full document text, `spans`, a `ListField[SpanField]` of inclusive start and
end indices for span candidates, and `metadata`, a `MetadataField` that stores the instance's
original text. For data with gold cluster labels, we also include the original `clusters`
(a list of list of index pairs) and a `SequenceLabelField` of cluster ids for every span
candidate.
# Parameters
max_span_width : `int`, required.
The maximum width of candidate spans to consider.
token_indexers : `Dict[str, TokenIndexer]`, optional
This is used to index the words in the document. See :class:`TokenIndexer`.
Default is `{"tokens": SingleIdTokenIndexer()}`.
wordpiece_modeling_tokenizer: `PretrainedTransformerTokenizer`, optional (default = None)
If not None, this dataset reader does subword tokenization using the supplied tokenizer
and distribute the labels to the resulting wordpieces. All the modeling will be based on
wordpieces. If this is set to `False` (default), the user is expected to use
`PretrainedTransformerMismatchedIndexer` and `PretrainedTransformerMismatchedEmbedder`,
and the modeling will be on the word-level.
max_sentences: int, optional (default = None)
The maximum number of sentences in each document to keep. By default keeps all sentences.
remove_singleton_clusters : `bool`, optional (default = False)
Some datasets contain clusters that are singletons (i.e. no coreferents). This option allows
the removal of them.
"""
def __init__(
self,
max_span_width: int,
token_indexers: Dict[str, TokenIndexer] = None,
wordpiece_modeling_tokenizer: Optional[PretrainedTransformerTokenizer] = None,
max_sentences: int = None,
remove_singleton_clusters: bool = True,
**kwargs,
) -> None:
super().__init__(**kwargs)
self._max_span_width = max_span_width
self._token_indexers = token_indexers or {"tokens": SingleIdTokenIndexer()}
self._wordpiece_modeling_tokenizer = wordpiece_modeling_tokenizer
self._max_sentences = max_sentences
self._remove_singleton_clusters = remove_singleton_clusters
@overrides
def _read(self, file_path: str):
# if `file_path` is a URL, redirect to the cache
file_path = cached_path(file_path)
with open(file_path, "r") as preco_file:
for line in preco_file:
example = json.loads(line)
yield self.text_to_instance(example["sentences"], example["mention_clusters"])
@overrides
def text_to_instance(
self, # type: ignore
sentences: List[List[str]],
gold_clusters: Optional[List[List[Tuple[int, int, int]]]] = None,
) -> Instance:
sentence_offsets = [0]
for sentence in sentences[:-1]:
sent_length = len(sentence)
if sentence == [" "]: # paragraph separator
sent_length = 0 # we ignore them
sentence_offsets.append(sentence_offsets[-1] + sent_length)
sentences = [sentence for sentence in sentences if sentence != [" "]]
# Convert (sent_idx, rel_start, rel_exclusive_end) to (abs_start, abs_inclusive_end)
for cluster in gold_clusters:
for mention_id, (sent_idx, start, end) in enumerate(cluster):
start = start + sentence_offsets[sent_idx]
end = end + sentence_offsets[sent_idx] - 1 # exclusive -> inclusive
cluster[mention_id] = (start, end) # type: ignore
return make_coref_instance(
sentences,
self._token_indexers,
self._max_span_width,
gold_clusters, # type: ignore
self._wordpiece_modeling_tokenizer,
self._max_sentences,
self._remove_singleton_clusters,
)
| 45 | 106 | 0.69177 | import json
import logging
from typing import Dict, List, Optional, Tuple
from overrides import overrides
from allennlp.common.file_utils import cached_path
from allennlp.data.dataset_readers.coreference_resolution.util import make_coref_instance
from allennlp.data.dataset_readers.dataset_reader import DatasetReader
from allennlp.data.instance import Instance
from allennlp.data.tokenizers import PretrainedTransformerTokenizer
from allennlp.data.token_indexers import SingleIdTokenIndexer, TokenIndexer
logger = logging.getLogger(__name__)
@DatasetReader.register("preco")
class PrecoReader(DatasetReader):
def __init__(
self,
max_span_width: int,
token_indexers: Dict[str, TokenIndexer] = None,
wordpiece_modeling_tokenizer: Optional[PretrainedTransformerTokenizer] = None,
max_sentences: int = None,
remove_singleton_clusters: bool = True,
**kwargs,
) -> None:
super().__init__(**kwargs)
self._max_span_width = max_span_width
self._token_indexers = token_indexers or {"tokens": SingleIdTokenIndexer()}
self._wordpiece_modeling_tokenizer = wordpiece_modeling_tokenizer
self._max_sentences = max_sentences
self._remove_singleton_clusters = remove_singleton_clusters
@overrides
def _read(self, file_path: str):
file_path = cached_path(file_path)
with open(file_path, "r") as preco_file:
for line in preco_file:
example = json.loads(line)
yield self.text_to_instance(example["sentences"], example["mention_clusters"])
@overrides
def text_to_instance(
self,
sentences: List[List[str]],
gold_clusters: Optional[List[List[Tuple[int, int, int]]]] = None,
) -> Instance:
sentence_offsets = [0]
for sentence in sentences[:-1]:
sent_length = len(sentence)
if sentence == [" "]:
sent_length = 0
sentence_offsets.append(sentence_offsets[-1] + sent_length)
sentences = [sentence for sentence in sentences if sentence != [" "]]
for cluster in gold_clusters:
for mention_id, (sent_idx, start, end) in enumerate(cluster):
start = start + sentence_offsets[sent_idx]
end = end + sentence_offsets[sent_idx] - 1
cluster[mention_id] = (start, end)
return make_coref_instance(
sentences,
self._token_indexers,
self._max_span_width,
gold_clusters,
self._wordpiece_modeling_tokenizer,
self._max_sentences,
self._remove_singleton_clusters,
)
| true | true |
1c3dfc8ade0f758b624c2912f8e557641f3525bb | 883 | py | Python | schemas/users.py | iliadmitriev/auth-fapi | a219efd5a8daa9d5f876355cde6b974021ca7890 | [
"MIT"
] | null | null | null | schemas/users.py | iliadmitriev/auth-fapi | a219efd5a8daa9d5f876355cde6b974021ca7890 | [
"MIT"
] | 131 | 2021-09-29T06:07:18.000Z | 2022-03-31T08:29:30.000Z | schemas/users.py | iliadmitriev/auth-fapi | a219efd5a8daa9d5f876355cde6b974021ca7890 | [
"MIT"
] | null | null | null | from typing import Optional
from datetime import datetime
from pydantic import BaseModel, EmailStr
# base shared properties
class UserBase(BaseModel):
email: Optional[EmailStr] = None
is_active: Optional[bool] = True
is_superuser: bool = False
confirmed: bool = False
# user create query
class UserCreate(UserBase):
email: EmailStr
password: str
# update user query
class UserUpdate(UserBase):
password: Optional[str] = None
# output user
class UserOut(UserBase):
id: Optional[int] = None
created: Optional[datetime] = None
last_login: Optional[datetime] = None
class Config:
orm_mode = True
# user attributes stored in db
class UserDB(UserBase):
id: Optional[int] = None
password: str
created: Optional[datetime] = None
last_login: Optional[datetime] = None
class Config:
orm_mode = True
| 19.195652 | 41 | 0.698754 | from typing import Optional
from datetime import datetime
from pydantic import BaseModel, EmailStr
class UserBase(BaseModel):
email: Optional[EmailStr] = None
is_active: Optional[bool] = True
is_superuser: bool = False
confirmed: bool = False
class UserCreate(UserBase):
email: EmailStr
password: str
class UserUpdate(UserBase):
password: Optional[str] = None
class UserOut(UserBase):
id: Optional[int] = None
created: Optional[datetime] = None
last_login: Optional[datetime] = None
class Config:
orm_mode = True
class UserDB(UserBase):
id: Optional[int] = None
password: str
created: Optional[datetime] = None
last_login: Optional[datetime] = None
class Config:
orm_mode = True
| true | true |
1c3dfcce6e7c7c8b0e519b4019603b5e00de96af | 77 | py | Python | problemtools/_version.py | mzuenni/problemtools | 6e147959f237c3637f77103c2fa642096f862ae4 | [
"MIT"
] | 84 | 2015-03-25T19:13:38.000Z | 2022-03-20T18:19:01.000Z | problemtools/_version.py | mzuenni/problemtools | 6e147959f237c3637f77103c2fa642096f862ae4 | [
"MIT"
] | 151 | 2015-03-29T18:28:28.000Z | 2021-12-10T21:35:04.000Z | problemtools/_version.py | mzuenni/problemtools | 6e147959f237c3637f77103c2fa642096f862ae4 | [
"MIT"
] | 60 | 2015-01-20T21:50:46.000Z | 2022-03-27T10:00:07.000Z | # Auto-generated from git changelog, do not edit!
__version__ = '1.20210928'
| 25.666667 | 49 | 0.753247 |
__version__ = '1.20210928'
| true | true |
1c3dfd5ff463099a6195658c5168eb89b1302e89 | 387 | py | Python | horas/wsgi.py | fabianabarca/horas | 526c065803f1487a39644eb54f65b7b4f3a036ee | [
"MIT"
] | null | null | null | horas/wsgi.py | fabianabarca/horas | 526c065803f1487a39644eb54f65b7b4f3a036ee | [
"MIT"
] | 2 | 2022-03-14T17:29:15.000Z | 2022-03-14T17:46:17.000Z | horas/wsgi.py | fabianabarca/horas | 526c065803f1487a39644eb54f65b7b4f3a036ee | [
"MIT"
] | null | null | null | """
WSGI config for horas project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'horas.settings')
application = get_wsgi_application()
| 22.764706 | 78 | 0.782946 |
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'horas.settings')
application = get_wsgi_application()
| true | true |
1c3dffbc46c058f6a60aeb5cb2b10a350cef6bc9 | 3,627 | py | Python | homeassistant/generated/config_flows.py | chboland/homassistant-core | 1df6eb124789213f7175a513729c4272e46736bd | [
"Apache-2.0"
] | null | null | null | homeassistant/generated/config_flows.py | chboland/homassistant-core | 1df6eb124789213f7175a513729c4272e46736bd | [
"Apache-2.0"
] | 1 | 2022-03-17T15:09:09.000Z | 2022-03-17T15:09:09.000Z | homeassistant/generated/config_flows.py | chboland/homassistant-core | 1df6eb124789213f7175a513729c4272e46736bd | [
"Apache-2.0"
] | null | null | null | """Automatically generated by hassfest.
To update, run python3 -m script.hassfest
"""
# fmt: off
FLOWS = [
"abode",
"accuweather",
"acmeda",
"adguard",
"advantage_air",
"agent_dvr",
"airly",
"airvisual",
"alarmdecoder",
"almond",
"ambiclimate",
"ambient_station",
"arcam_fmj",
"atag",
"august",
"avri",
"awair",
"axis",
"azure_devops",
"blebox",
"blink",
"bond",
"braviatv",
"broadlink",
"brother",
"bsblan",
"canary",
"cast",
"cert_expiry",
"cloudflare",
"control4",
"coolmaster",
"coronavirus",
"daikin",
"deconz",
"denonavr",
"devolo_home_control",
"dexcom",
"dialogflow",
"directv",
"doorbird",
"dunehd",
"dynalite",
"eafm",
"ecobee",
"elgato",
"elkm1",
"emulated_roku",
"enocean",
"esphome",
"flick_electric",
"flo",
"flume",
"flunearyou",
"forked_daapd",
"freebox",
"fritzbox",
"garmin_connect",
"gdacs",
"geofency",
"geonetnz_quakes",
"geonetnz_volcano",
"gios",
"glances",
"goalzero",
"gogogate2",
"gpslogger",
"gree",
"griddy",
"guardian",
"hangouts",
"harmony",
"heos",
"hisense_aehw4a1",
"hlk_sw16",
"home_connect",
"homekit",
"homekit_controller",
"homematicip_cloud",
"huawei_lte",
"hue",
"hunterdouglas_powerview",
"hvv_departures",
"iaqualink",
"icloud",
"ifttt",
"insteon",
"ios",
"ipma",
"ipp",
"iqvia",
"islamic_prayer_times",
"isy994",
"izone",
"juicenet",
"kodi",
"konnected",
"life360",
"lifx",
"local_ip",
"locative",
"logi_circle",
"luftdaten",
"mailgun",
"melcloud",
"met",
"meteo_france",
"metoffice",
"mikrotik",
"mill",
"minecraft_server",
"mobile_app",
"monoprice",
"mqtt",
"myq",
"neato",
"nest",
"netatmo",
"nexia",
"nightscout",
"notion",
"nuheat",
"nut",
"nws",
"nzbget",
"omnilogic",
"onewire",
"onvif",
"opentherm_gw",
"openuv",
"openweathermap",
"ovo_energy",
"owntracks",
"ozw",
"panasonic_viera",
"pi_hole",
"plaato",
"plex",
"plugwise",
"plum_lightpad",
"point",
"poolsense",
"powerwall",
"profiler",
"progettihwsw",
"ps4",
"pvpc_hourly_pricing",
"rachio",
"rainmachine",
"rfxtrx",
"ring",
"risco",
"roku",
"roomba",
"roon",
"rpi_power",
"ruckus_unleashed",
"samsungtv",
"sense",
"sentry",
"sharkiq",
"shelly",
"shopping_list",
"simplisafe",
"smappee",
"smart_meter_texas",
"smarthab",
"smartthings",
"smhi",
"sms",
"solaredge",
"solarlog",
"soma",
"somfy",
"sonarr",
"songpal",
"sonos",
"speedtestdotnet",
"spider",
"spotify",
"squeezebox",
"starline",
"syncthru",
"synology_dsm",
"tado",
"tasmota",
"tellduslive",
"tesla",
"tibber",
"tile",
"toon",
"totalconnect",
"tplink",
"traccar",
"tradfri",
"transmission",
"tuya",
"twentemilieu",
"twilio",
"unifi",
"upb",
"upcloud",
"upnp",
"velbus",
"vera",
"vesync",
"vilfo",
"vizio",
"volumio",
"waterkotte",
"wemo",
"wiffi",
"wilight",
"withings",
"wled",
"wolflink",
"xbox",
"xiaomi_aqara",
"xiaomi_miio",
"yeelight",
"zerproc",
"zha",
"zwave"
]
| 15.566524 | 41 | 0.498484 |
FLOWS = [
"abode",
"accuweather",
"acmeda",
"adguard",
"advantage_air",
"agent_dvr",
"airly",
"airvisual",
"alarmdecoder",
"almond",
"ambiclimate",
"ambient_station",
"arcam_fmj",
"atag",
"august",
"avri",
"awair",
"axis",
"azure_devops",
"blebox",
"blink",
"bond",
"braviatv",
"broadlink",
"brother",
"bsblan",
"canary",
"cast",
"cert_expiry",
"cloudflare",
"control4",
"coolmaster",
"coronavirus",
"daikin",
"deconz",
"denonavr",
"devolo_home_control",
"dexcom",
"dialogflow",
"directv",
"doorbird",
"dunehd",
"dynalite",
"eafm",
"ecobee",
"elgato",
"elkm1",
"emulated_roku",
"enocean",
"esphome",
"flick_electric",
"flo",
"flume",
"flunearyou",
"forked_daapd",
"freebox",
"fritzbox",
"garmin_connect",
"gdacs",
"geofency",
"geonetnz_quakes",
"geonetnz_volcano",
"gios",
"glances",
"goalzero",
"gogogate2",
"gpslogger",
"gree",
"griddy",
"guardian",
"hangouts",
"harmony",
"heos",
"hisense_aehw4a1",
"hlk_sw16",
"home_connect",
"homekit",
"homekit_controller",
"homematicip_cloud",
"huawei_lte",
"hue",
"hunterdouglas_powerview",
"hvv_departures",
"iaqualink",
"icloud",
"ifttt",
"insteon",
"ios",
"ipma",
"ipp",
"iqvia",
"islamic_prayer_times",
"isy994",
"izone",
"juicenet",
"kodi",
"konnected",
"life360",
"lifx",
"local_ip",
"locative",
"logi_circle",
"luftdaten",
"mailgun",
"melcloud",
"met",
"meteo_france",
"metoffice",
"mikrotik",
"mill",
"minecraft_server",
"mobile_app",
"monoprice",
"mqtt",
"myq",
"neato",
"nest",
"netatmo",
"nexia",
"nightscout",
"notion",
"nuheat",
"nut",
"nws",
"nzbget",
"omnilogic",
"onewire",
"onvif",
"opentherm_gw",
"openuv",
"openweathermap",
"ovo_energy",
"owntracks",
"ozw",
"panasonic_viera",
"pi_hole",
"plaato",
"plex",
"plugwise",
"plum_lightpad",
"point",
"poolsense",
"powerwall",
"profiler",
"progettihwsw",
"ps4",
"pvpc_hourly_pricing",
"rachio",
"rainmachine",
"rfxtrx",
"ring",
"risco",
"roku",
"roomba",
"roon",
"rpi_power",
"ruckus_unleashed",
"samsungtv",
"sense",
"sentry",
"sharkiq",
"shelly",
"shopping_list",
"simplisafe",
"smappee",
"smart_meter_texas",
"smarthab",
"smartthings",
"smhi",
"sms",
"solaredge",
"solarlog",
"soma",
"somfy",
"sonarr",
"songpal",
"sonos",
"speedtestdotnet",
"spider",
"spotify",
"squeezebox",
"starline",
"syncthru",
"synology_dsm",
"tado",
"tasmota",
"tellduslive",
"tesla",
"tibber",
"tile",
"toon",
"totalconnect",
"tplink",
"traccar",
"tradfri",
"transmission",
"tuya",
"twentemilieu",
"twilio",
"unifi",
"upb",
"upcloud",
"upnp",
"velbus",
"vera",
"vesync",
"vilfo",
"vizio",
"volumio",
"waterkotte",
"wemo",
"wiffi",
"wilight",
"withings",
"wled",
"wolflink",
"xbox",
"xiaomi_aqara",
"xiaomi_miio",
"yeelight",
"zerproc",
"zha",
"zwave"
]
| true | true |
1c3e000d20f4633684abe2743e374d7c75e798ce | 1,668 | py | Python | lib/naf.py | KelvinKan/CP-Flow | d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1 | [
"MIT"
] | 64 | 2021-02-22T21:24:39.000Z | 2022-03-25T20:30:39.000Z | lib/naf.py | KelvinKan/CP-Flow | d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1 | [
"MIT"
] | null | null | null | lib/naf.py | KelvinKan/CP-Flow | d01303cb4ebeb5a0bbfca638ffaf5b7a8ec22fb1 | [
"MIT"
] | 9 | 2021-02-24T15:12:40.000Z | 2022-03-05T06:14:17.000Z | # noinspection PyPep8Naming
from torch.nn import functional as F
from lib.functional import *
def sigmoid_flow(x, logdet=0, ndim=4, params=None, delta=DELTA, logit_end=True):
"""
element-wise sigmoidal flow described in `Neural Autoregressive Flows` (https://arxiv.org/pdf/1804.00779.pdf)
:param x: input
:param logdet: accumulation of log-determinant of jacobian
:param ndim: number of dimensions of the transform
:param params: parameters of the transform (batch_size x dimensionality of features x ndim*3 parameters)
:param delta: small value to deal with numerical stability
:param logit_end: whether to logit-transform it back to the real space
:return: transformed data (and log-determinant of jacobian accumulates)
"""
assert params is not None, 'parameters not provided'
assert params.size(2) == ndim*3, 'params shape[2] does not match ndim * 3'
a = act_a(params[:, :, 0 * ndim: 1 * ndim])
b = act_b(params[:, :, 1 * ndim: 2 * ndim])
w = act_w(params[:, :, 2 * ndim: 3 * ndim])
pre_sigm = a * x[:, :, None] + b
sigm = torch.sigmoid(pre_sigm)
x_pre = torch.sum(w * sigm, dim=2)
logj = F.log_softmax(
params[:, :, 2 * ndim: 3 * ndim], dim=2) + logsigmoid(pre_sigm) + logsigmoid(-pre_sigm) + log(a)
logj = log_sum_exp(logj, 2).sum(2)
if not logit_end:
return x_pre, logj.sum(1) + logdet
x_pre_clipped = x_pre * (1 - delta) + delta * 0.5
x_ = log(x_pre_clipped) - log(1 - x_pre_clipped)
xnew = x_
logdet_ = logj + np.log(1 - delta) - (log(x_pre_clipped) + log(-x_pre_clipped + 1))
logdet = logdet_.sum(1) + logdet
return xnew, logdet
| 39.714286 | 113 | 0.660671 |
from torch.nn import functional as F
from lib.functional import *
def sigmoid_flow(x, logdet=0, ndim=4, params=None, delta=DELTA, logit_end=True):
assert params is not None, 'parameters not provided'
assert params.size(2) == ndim*3, 'params shape[2] does not match ndim * 3'
a = act_a(params[:, :, 0 * ndim: 1 * ndim])
b = act_b(params[:, :, 1 * ndim: 2 * ndim])
w = act_w(params[:, :, 2 * ndim: 3 * ndim])
pre_sigm = a * x[:, :, None] + b
sigm = torch.sigmoid(pre_sigm)
x_pre = torch.sum(w * sigm, dim=2)
logj = F.log_softmax(
params[:, :, 2 * ndim: 3 * ndim], dim=2) + logsigmoid(pre_sigm) + logsigmoid(-pre_sigm) + log(a)
logj = log_sum_exp(logj, 2).sum(2)
if not logit_end:
return x_pre, logj.sum(1) + logdet
x_pre_clipped = x_pre * (1 - delta) + delta * 0.5
x_ = log(x_pre_clipped) - log(1 - x_pre_clipped)
xnew = x_
logdet_ = logj + np.log(1 - delta) - (log(x_pre_clipped) + log(-x_pre_clipped + 1))
logdet = logdet_.sum(1) + logdet
return xnew, logdet
| true | true |
1c3e0022c9597e37f4aceb94b28551f921fce1b4 | 2,048 | py | Python | feather/constants.py | oluwaseunladeinde/yellowfeather | 134783fdd90d6f4118eae1d1dad029a245773106 | [
"MIT"
] | null | null | null | feather/constants.py | oluwaseunladeinde/yellowfeather | 134783fdd90d6f4118eae1d1dad029a245773106 | [
"MIT"
] | null | null | null | feather/constants.py | oluwaseunladeinde/yellowfeather | 134783fdd90d6f4118eae1d1dad029a245773106 | [
"MIT"
] | null | null | null | from django.utils.translation import ugettext_lazy as _
TYPES = (
('house', _('Houses')),
('villa', _('Villas')),
('penthouse', _('Penthouses')),
('apartment', _('Apartments')),
('residencial-land', _('Residential Land')),
('corporate-office', _('Corporate Offices')),
('commercial-office', _('Commercial Offices')),
('commercial-space', _('Commercial Space')),
('industrial-building', _('Industrial Buildings')),
('commercial-warehouses', _('Commercial Warehouses')),
('commercial-land', _('Commercial Land')),
)
BATHROOMS_RANGE = (
('', '--'),
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
('6', '6+'),
)
BEDROOMS_RANGE = (
('', '--'),
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
('6', '6+'),
)
LOCATION_STREET = 'street'
LOCATION_SECTOR = 'sector'
LOCATION_CITY = 'city'
LOCATION_STATE = 'state'
LOCATION_TYPES = (
(LOCATION_STREET, _('Street')),
(LOCATION_SECTOR, _('Sector')),
(LOCATION_CITY, _('City')),
(LOCATION_STATE, _('State/Province')),
)
OFFERS = (
('', '--'),
('buy', _('For Sale')),
('rent', _('For Rent')),
('buy-rent', _('For Sale/For Rent'))
)
NIGERIA_STATES = (
('abia', 'Abia'), ('abuja', 'Abuja FCT'), ('adamawa', 'Adamawa'), ('akwaibom', 'Akwa Ibom'), ('anambra', 'Anambra'),
('bauchi', 'Bauchi'), ('bayelsa', 'Bayelsa'), ('benue', 'Benue'), ('borno', 'Borno'), ('crossriver', 'Cross River'),
('delta', 'Delta'), ('ebonyi', 'Ebonyi'), ('edo', 'Edo'), ('ekiti', 'Ekiti'), ('enugu', 'Enugu'),
('gombe', 'Gombe'), ('imo', 'Imo'), ('jigawa', 'Jigawa'), ('kaduna', 'Kaduna'), ('kano', 'Kano'),
('katsina', 'Katsina'), ('kebbi', 'Kebbi'), ('kogi', 'Kogi'), ('kwara', 'Kwara'), ('lagos', 'Lagos'),
('nassarawa', 'Nassarawa'), ('niger', 'Niger'), ('ogun', 'Ogun'), ('osun', 'Osun'), ('oyo', 'Oyo'),
('plateau', 'Plateau'), ('rivers', 'Rivers'), ('sokoto', 'Sokoto'), ('taraba', 'Taraba'),
('yobe', 'Yobe'), ('zamfara', 'Zamfara'),
)
| 31.030303 | 120 | 0.514648 | from django.utils.translation import ugettext_lazy as _
TYPES = (
('house', _('Houses')),
('villa', _('Villas')),
('penthouse', _('Penthouses')),
('apartment', _('Apartments')),
('residencial-land', _('Residential Land')),
('corporate-office', _('Corporate Offices')),
('commercial-office', _('Commercial Offices')),
('commercial-space', _('Commercial Space')),
('industrial-building', _('Industrial Buildings')),
('commercial-warehouses', _('Commercial Warehouses')),
('commercial-land', _('Commercial Land')),
)
BATHROOMS_RANGE = (
('', '--'),
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
('6', '6+'),
)
BEDROOMS_RANGE = (
('', '--'),
('1', '1'),
('2', '2'),
('3', '3'),
('4', '4'),
('5', '5'),
('6', '6+'),
)
LOCATION_STREET = 'street'
LOCATION_SECTOR = 'sector'
LOCATION_CITY = 'city'
LOCATION_STATE = 'state'
LOCATION_TYPES = (
(LOCATION_STREET, _('Street')),
(LOCATION_SECTOR, _('Sector')),
(LOCATION_CITY, _('City')),
(LOCATION_STATE, _('State/Province')),
)
OFFERS = (
('', '--'),
('buy', _('For Sale')),
('rent', _('For Rent')),
('buy-rent', _('For Sale/For Rent'))
)
NIGERIA_STATES = (
('abia', 'Abia'), ('abuja', 'Abuja FCT'), ('adamawa', 'Adamawa'), ('akwaibom', 'Akwa Ibom'), ('anambra', 'Anambra'),
('bauchi', 'Bauchi'), ('bayelsa', 'Bayelsa'), ('benue', 'Benue'), ('borno', 'Borno'), ('crossriver', 'Cross River'),
('delta', 'Delta'), ('ebonyi', 'Ebonyi'), ('edo', 'Edo'), ('ekiti', 'Ekiti'), ('enugu', 'Enugu'),
('gombe', 'Gombe'), ('imo', 'Imo'), ('jigawa', 'Jigawa'), ('kaduna', 'Kaduna'), ('kano', 'Kano'),
('katsina', 'Katsina'), ('kebbi', 'Kebbi'), ('kogi', 'Kogi'), ('kwara', 'Kwara'), ('lagos', 'Lagos'),
('nassarawa', 'Nassarawa'), ('niger', 'Niger'), ('ogun', 'Ogun'), ('osun', 'Osun'), ('oyo', 'Oyo'),
('plateau', 'Plateau'), ('rivers', 'Rivers'), ('sokoto', 'Sokoto'), ('taraba', 'Taraba'),
('yobe', 'Yobe'), ('zamfara', 'Zamfara'),
)
| true | true |
1c3e00789415d4f86dc0f0402e28330ecb03abe5 | 677 | py | Python | Tree/SumofLeftLeaves.py | PK-100/Competitive_Programming | d0863feaaa99462b2999e85dcf115f7a6c08bb8d | [
"MIT"
] | 70 | 2018-06-25T21:20:15.000Z | 2022-03-24T03:55:17.000Z | Tree/Sum-of-Left-Leaves.py | An3sha/Competitive_Programming | ee7eadf51939a360d0b004d787ebabda583e92f0 | [
"MIT"
] | 4 | 2018-09-04T13:12:20.000Z | 2021-06-20T08:29:12.000Z | Tree/Sum-of-Left-Leaves.py | An3sha/Competitive_Programming | ee7eadf51939a360d0b004d787ebabda583e92f0 | [
"MIT"
] | 24 | 2018-12-26T05:15:32.000Z | 2022-01-23T23:04:54.000Z | # Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
result = 0
if root:
if root.left and not root.left.left and not root.left.right:
result += root.left.val # if left node is leaf
else:
result += self.sumOfLeftLeaves(root.left) # otherwise recurse down to left
result += self.sumOfLeftLeaves(root.right) # then to right side, because we have to check full tree
return result
| 39.823529 | 111 | 0.602659 |
class Solution:
def sumOfLeftLeaves(self, root: TreeNode) -> int:
result = 0
if root:
if root.left and not root.left.left and not root.left.right:
result += root.left.val
else:
result += self.sumOfLeftLeaves(root.left)
result += self.sumOfLeftLeaves(root.right)
return result
| true | true |
1c3e011942f345472ff9a4ff308d85d8c4906208 | 13,815 | py | Python | epistasis/pyplot/coefs.py | harmsm/epistasis | 741b25b3e28015aeeba8d4efc94af1e1d811cd63 | [
"Unlicense"
] | null | null | null | epistasis/pyplot/coefs.py | harmsm/epistasis | 741b25b3e28015aeeba8d4efc94af1e1d811cd63 | [
"Unlicense"
] | null | null | null | epistasis/pyplot/coefs.py | harmsm/epistasis | 741b25b3e28015aeeba8d4efc94af1e1d811cd63 | [
"Unlicense"
] | 2 | 2020-04-02T00:58:24.000Z | 2021-11-16T13:30:30.000Z | __description__ = \
"""
Plot barplot with epistatic coefficients.
"""
__author__ = "Zach Sailer"
import gpmap
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import matplotlib as mpl
import numpy as np
from scipy.stats import norm as scipy_norm
class Bunch:
"""
Classic bunch object for constructing empty objects. Used to make readable
options.color etc.
"""
def __init__(self, **kwds):
self.__dict__.update(kwds)
def update(self, **kwargs):
"""
Turn a dictionary into an object with
"""
types = dict([(key, type(val)) for key, val in self.__dict__.items()])
for key, value in kwargs.items():
typed = types[key]
if typed == np.ufunc:
typed_val = value
elif self.__dict__[key] is None:
typed_val = value
else:
typed_val = types[key](value)
setattr(self, key, typed_val)
def plot_coefs(model,**kwargs):
"""Create a barplot with the values from model, drawing the x-axis as a
grid of boxes indicating the coordinate of the epistatic parameter.
Should automatically generate an almost publication-quality figure.
Parameters
----------
model: BaseModel object
epistasis model.
Keyword arguments
-----------------
order_colors :
list/tuple of colors for each order (rgb,html string-like)
significance :
how to treat signifiance. should be
1. "bon" -> Bonferroni corrected p-values (default)
2. "p" -> raw p-values
3. None -> ignore significance
significance_cutoff :
value above which to consider a term significant
sigmas :
number of sigmas to show for each error bar
y_scalar :
how much to scale the y-axis above and beyond y-max
y_axis_name :
what to put on the y-axis of the barplot
figsize :
tuple of figure width,height
height_ratio :
how much to scale barplot relative to xbox
star_cutoffs :
signifiance cutoffs for star stack. should go from highest
p to lowest p (least to most significant)
star_spacer :
constant that scales how closely stacked stars are from one
another
ybounds : tuple (default=None)
bar_borders : bool (default=True)
xgrid : bool (default=True)
ecolor : color (default='black')
elinewidth : float (default=1)
capthick : float (default=1)
capsize : float (default=1)
gridlines : float (default=1)
x grid linewidth
Returns
-------
fig : matplotlib.pyplot.Figure
Figure object
ax : matplotlib.pyplot.Axes
Axes object
"""
# Some sanity checks.
sites = model.epistasis.sites[1:]
values = model.epistasis.values[1:]
# Set up plotting user options. Type check the options to make sure nothing
# will break. Also helps with widgets.
sites = list(sites)
# Prepare an cycle of colors
order = len(sites[-1:])
prop_cycle = plt.rcParams['axes.prop_cycle']
color_cycle = prop_cycle.by_key()['color']
color_scalar = int(order / len(color_cycle)) + 1
color_cycle *= color_scalar
defaults = {
"order_colors": color_cycle,
"logbase": np.log10,
"log_transform": False,
"significance": "bon",
"significance_cutoff": 0.05,
"sigmas": 0,
"log_space": False,
"y_scalar": 1.5,
"y_axis_name": "",
"figwidth": 5,
"figheight": 3,
"figsize": (5, 3),
"height_ratio": 12,
"star_cutoffs": (0.05, 0.01, 0.001),
"star_spacer": 0.0075,
"ybounds": None,
"bar_borders": True,
"xgrid": True,
"ecolor": "black",
"capthick": 1,
"capsize": 1,
"elinewidth": 1,
"save": False,
"fname": "figure.svg",
"format": "svg",
"gridlines": 1,
}
# types = dict([(key, type(val)) for key, val in defaults.items()])
# defaults.update(kwargs)
# options = objectify(defaults)
options = Bunch(**defaults)
options.update(**kwargs)
# Construct keyword arguments
error_kw = {
"ecolor": options.ecolor,
"capsize": options.capsize,
"elinewidth": options.elinewidth,
"capthick": options.capthick,
}
if "figsize" in kwargs:
options.figsize = kwargs["figsize"]
else:
options.figsize = (options.figwidth, options.figheight)
# Name all variables that matter for this function
if sites[0] == [0]:
sites = sites[1:]
values = values[1:]
options.sigmas = 0
# Sanity check on the errors
if options.sigmas == 0:
significance = None
elif options.significance is None:
sigmas = 0
# Figure out the length of the x-axis and the highest epistasis observed
num_terms = len(sites)
highest_order = max([len(l) for l in sites])
# Figure out how many sites are in the dataset (in case of non-binary
# system)
all_sites = []
for l in sites:
all_sites.extend(l)
all_sites = list(dict([(s, []) for s in all_sites]).keys())
all_sites.sort()
num_sites = len(all_sites)
# Figure out how to color each order
if options.order_colors is None:
options.order_colors = ["gray" for i in range(highest_order + 1)]
else:
if len(options.order_colors) < highest_order:
raise ValueError("order_colors has too few entries "
"(at least {:d} needed)\n".format(highest_order))
# Stick gray in the 0 position for insignificant values
options.order_colors = list(options.order_colors)
options.order_colors.insert(0, "gray")
# ---------------------- #
# Deal with significance #
# ---------------------- #
# NEED TO RETURN TO SIGNIFICANCE FUNCTIONS
if options.sigmas == 0:
options.significance = None
else:
# If log transformed, need to get raw values for normal distribution
if options.log_transform:
z_score = abs((values - 1) / upper)
# else, just grab standard values
else:
z_score = abs((values) / upper)
# if z_score is > 5, set z_score to largest possible range
# where p-value is within floating point
z_score[z_score > 8.2] = 8.2
# straight p-values
if options.significance == "p":
p_values = 2 * (1 - scipy_norm.cdf(z_score))
# bonferroni corrected p-values
elif options.significance == "bon":
p_values = 2 * (1 - scipy_norm.cdf(z_score)) * len(values)
# ignore p-values and color everything
elif options.significance is None:
p_values = [0 for i in range(len(sites))]
options.significance_cutoff = 1.0
# or die
else:
raise ValueError("signifiance argument {:s} not "
"recognized\n".format(options.significance))
# Create color array based on significance
color_array = np.zeros((len(sites)), dtype=int)
for i, l in enumerate(sites):
if p_values[i] < options.significance_cutoff:
color_array[i] = len(l) - 1
else:
color_array[i] = -1
# ---------------- #
# Create the plots #
# ---------------- #
# Make a color map
cmap = mpl.colors.ListedColormap(colors=options.order_colors)
# set the 'bad' values (nan) to be white and transparent
cmap.set_bad(color='w', alpha=0)
bounds = range(-1, len(options.order_colors))
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
if options.xgrid is True:
fig = plt.figure(figsize=options.figsize)
n_coefs = len(sites)
n_sites = max([max(l) for l in sites])
# Calculate the height_ratio of the grid and the bar graph
box_size = options.figsize[0] / float(n_coefs)
grid_height = box_size * n_sites
bar_height = options.figsize[1] - grid_height
height_ratio = bar_height / grid_height
# Create a plot with an upper and lower panel, sharing the x-axis
gs = mpl.gridspec.GridSpec(2, 1,
height_ratios=[height_ratio, 1],
hspace=0.00)
ax = [plt.subplot(gs[0])]
ax.append(plt.subplot(gs[1], sharex=ax[0]))
bar_axis = ax[0]
grid_axis = ax[1]
# Create the box-array x-axis
# path codes for drawing the boxes
box_codes = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY]
color_vector = options.order_colors
for i in range(n_coefs):
for j in range(n_sites):
color = "None"
if j + 1 in sites[i]:
color = color_vector[len(sites[i])]
# vertices for a given square
verts = [
(i, n_coefs - j),
(i, n_coefs - j - 1),
(i + 1, n_coefs - j - 1),
(i + 1, n_coefs - j),
(i, n_coefs - j),
]
# Create a patch for a square
path = Path(verts, box_codes)
patch = patches.PathPatch(path,
facecolor=color,
lw=options.gridlines)
grid_axis.add_patch(patch)
grid_axis.axis('equal')
grid_axis.axis('off')
else:
fig, ax = plt.subplots(figsize=options.figsize)
bar_axis = ax
# ------------------ #
# Create the barplot #
# ------------------ #
# set up bar colors
# prop_cycle = plt.rcParams['axes.prop_cycle']
# colors_for_bar = prop_cycle.by_key()['color']
colors_for_bar = np.array([mpl.colors.colorConverter.to_rgba(
options.order_colors[(i + 1)]) for i in color_array])
# Plot without errors
if options.sigmas == 0:
if options.log_space:
bar_y = options.logbase(values)
else:
bar_y = values
bar_axis.bar(np.arange(len(bar_y)) + .55, bar_y, width=.9,
color=colors_for_bar, edgecolor="none")
# plot with errors
else:
bar_y = values
upper = options.sigmas * upper
lower = options.sigmas * lower # Plot the graph on a log scale
if options.log_space:
new_bar_y = options.logbase(bar_y)
new_upper = gpmap.errors.upper_transform(bar_y, upper,
options.logbase)
new_lower = gpmap.errors.lower_transform(bar_y, lower,
options.logbase)
# else if the space is log transformed,
# plot the non-log interaction values
else:
new_upper = upper
new_lower = lower
new_bar_y = bar_y
yerr = [new_lower, new_upper]
# Plot
bar_axis.bar(np.arange(len(bar_y)) + 0.05, new_bar_y,
width=0.9,
yerr=yerr,
color=colors_for_bar,
error_kw=error_kw,
edgecolor="none",
linewidth=2)
# Add horizontal lines for each order
bar_axis.hlines(0, 0, len(values), linewidth=1, linestyle="-", zorder=0)
# Label barplot y-axis
bar_axis.set_ylabel(options.y_axis_name, fontsize=14)
# Set barplot y-scale
if options.ybounds is None:
ymin = -options.y_scalar * max(abs(bar_y))
ymax = options.y_scalar * max(abs(bar_y))
else:
ymin = options.ybounds[0]
ymax = options.ybounds[1]
# Make axes pretty pretty
bar_axis.axis([-1, len(bar_y) + 1, ymin, ymax])
bar_axis.set_frame_on(False) # axis("off")
bar_axis.get_xaxis().set_visible(False)
bar_axis.get_yaxis().tick_left()
bar_axis.get_yaxis().set_tick_params(direction='out')
bar_axis.add_artist(mpl.lines.Line2D((-1, -1),
(bar_axis.get_yticks()
[1], bar_axis.get_yticks()[-2]),
color='black', linewidth=1))
# add vertical lines between order breaks
previous_order = 1
for i in range(len(sites)):
if len(sites[i]) != previous_order:
bar_axis.add_artist(mpl.lines.Line2D((i, i),
(ymin, ymax),
color="black",
linestyle=":",
linewidth=1))
previous_order = len(sites[i])
# ------------------------- #
# Create significance stars #
# ------------------------- #
if options.sigmas != 0:
min_offset = options.star_spacer * (ymax - ymin)
for i in range(len(p_values)):
star_counter = 0
for j in range(len(options.star_cutoffs)):
if p_values[i] < options.star_cutoffs[j]:
star_counter += 1
else:
break
for j in range(star_counter):
bar_axis.text(x=(i + 0),
y=ymin + (j * min_offset),
s="*", fontsize=16)
# remove x tick labels
try:
plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)
except IndexError:
pass
# Draw the final figure
# fig.tight_layout()
if options.save:
fig.savefig(options.fname, format=options.format)
return fig, ax
| 31.541096 | 79 | 0.552081 | __description__ = \
"""
Plot barplot with epistatic coefficients.
"""
__author__ = "Zach Sailer"
import gpmap
import matplotlib.pyplot as plt
from matplotlib.path import Path
import matplotlib.patches as patches
import matplotlib as mpl
import numpy as np
from scipy.stats import norm as scipy_norm
class Bunch:
def __init__(self, **kwds):
self.__dict__.update(kwds)
def update(self, **kwargs):
types = dict([(key, type(val)) for key, val in self.__dict__.items()])
for key, value in kwargs.items():
typed = types[key]
if typed == np.ufunc:
typed_val = value
elif self.__dict__[key] is None:
typed_val = value
else:
typed_val = types[key](value)
setattr(self, key, typed_val)
def plot_coefs(model,**kwargs):
sites = model.epistasis.sites[1:]
values = model.epistasis.values[1:]
sites = list(sites)
order = len(sites[-1:])
prop_cycle = plt.rcParams['axes.prop_cycle']
color_cycle = prop_cycle.by_key()['color']
color_scalar = int(order / len(color_cycle)) + 1
color_cycle *= color_scalar
defaults = {
"order_colors": color_cycle,
"logbase": np.log10,
"log_transform": False,
"significance": "bon",
"significance_cutoff": 0.05,
"sigmas": 0,
"log_space": False,
"y_scalar": 1.5,
"y_axis_name": "",
"figwidth": 5,
"figheight": 3,
"figsize": (5, 3),
"height_ratio": 12,
"star_cutoffs": (0.05, 0.01, 0.001),
"star_spacer": 0.0075,
"ybounds": None,
"bar_borders": True,
"xgrid": True,
"ecolor": "black",
"capthick": 1,
"capsize": 1,
"elinewidth": 1,
"save": False,
"fname": "figure.svg",
"format": "svg",
"gridlines": 1,
}
options = Bunch(**defaults)
options.update(**kwargs)
error_kw = {
"ecolor": options.ecolor,
"capsize": options.capsize,
"elinewidth": options.elinewidth,
"capthick": options.capthick,
}
if "figsize" in kwargs:
options.figsize = kwargs["figsize"]
else:
options.figsize = (options.figwidth, options.figheight)
if sites[0] == [0]:
sites = sites[1:]
values = values[1:]
options.sigmas = 0
if options.sigmas == 0:
significance = None
elif options.significance is None:
sigmas = 0
num_terms = len(sites)
highest_order = max([len(l) for l in sites])
all_sites = []
for l in sites:
all_sites.extend(l)
all_sites = list(dict([(s, []) for s in all_sites]).keys())
all_sites.sort()
num_sites = len(all_sites)
if options.order_colors is None:
options.order_colors = ["gray" for i in range(highest_order + 1)]
else:
if len(options.order_colors) < highest_order:
raise ValueError("order_colors has too few entries "
"(at least {:d} needed)\n".format(highest_order))
options.order_colors = list(options.order_colors)
options.order_colors.insert(0, "gray")
if options.sigmas == 0:
options.significance = None
else:
if options.log_transform:
z_score = abs((values - 1) / upper)
else:
z_score = abs((values) / upper)
z_score[z_score > 8.2] = 8.2
if options.significance == "p":
p_values = 2 * (1 - scipy_norm.cdf(z_score))
elif options.significance == "bon":
p_values = 2 * (1 - scipy_norm.cdf(z_score)) * len(values)
elif options.significance is None:
p_values = [0 for i in range(len(sites))]
options.significance_cutoff = 1.0
else:
raise ValueError("signifiance argument {:s} not "
"recognized\n".format(options.significance))
color_array = np.zeros((len(sites)), dtype=int)
for i, l in enumerate(sites):
if p_values[i] < options.significance_cutoff:
color_array[i] = len(l) - 1
else:
color_array[i] = -1
cmap = mpl.colors.ListedColormap(colors=options.order_colors)
cmap.set_bad(color='w', alpha=0)
bounds = range(-1, len(options.order_colors))
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)
if options.xgrid is True:
fig = plt.figure(figsize=options.figsize)
n_coefs = len(sites)
n_sites = max([max(l) for l in sites])
box_size = options.figsize[0] / float(n_coefs)
grid_height = box_size * n_sites
bar_height = options.figsize[1] - grid_height
height_ratio = bar_height / grid_height
gs = mpl.gridspec.GridSpec(2, 1,
height_ratios=[height_ratio, 1],
hspace=0.00)
ax = [plt.subplot(gs[0])]
ax.append(plt.subplot(gs[1], sharex=ax[0]))
bar_axis = ax[0]
grid_axis = ax[1]
box_codes = [Path.MOVETO,
Path.LINETO,
Path.LINETO,
Path.LINETO,
Path.CLOSEPOLY]
color_vector = options.order_colors
for i in range(n_coefs):
for j in range(n_sites):
color = "None"
if j + 1 in sites[i]:
color = color_vector[len(sites[i])]
verts = [
(i, n_coefs - j),
(i, n_coefs - j - 1),
(i + 1, n_coefs - j - 1),
(i + 1, n_coefs - j),
(i, n_coefs - j),
]
path = Path(verts, box_codes)
patch = patches.PathPatch(path,
facecolor=color,
lw=options.gridlines)
grid_axis.add_patch(patch)
grid_axis.axis('equal')
grid_axis.axis('off')
else:
fig, ax = plt.subplots(figsize=options.figsize)
bar_axis = ax
colors_for_bar = np.array([mpl.colors.colorConverter.to_rgba(
options.order_colors[(i + 1)]) for i in color_array])
if options.sigmas == 0:
if options.log_space:
bar_y = options.logbase(values)
else:
bar_y = values
bar_axis.bar(np.arange(len(bar_y)) + .55, bar_y, width=.9,
color=colors_for_bar, edgecolor="none")
else:
bar_y = values
upper = options.sigmas * upper
lower = options.sigmas * lower
if options.log_space:
new_bar_y = options.logbase(bar_y)
new_upper = gpmap.errors.upper_transform(bar_y, upper,
options.logbase)
new_lower = gpmap.errors.lower_transform(bar_y, lower,
options.logbase)
else:
new_upper = upper
new_lower = lower
new_bar_y = bar_y
yerr = [new_lower, new_upper]
bar_axis.bar(np.arange(len(bar_y)) + 0.05, new_bar_y,
width=0.9,
yerr=yerr,
color=colors_for_bar,
error_kw=error_kw,
edgecolor="none",
linewidth=2)
bar_axis.hlines(0, 0, len(values), linewidth=1, linestyle="-", zorder=0)
bar_axis.set_ylabel(options.y_axis_name, fontsize=14)
if options.ybounds is None:
ymin = -options.y_scalar * max(abs(bar_y))
ymax = options.y_scalar * max(abs(bar_y))
else:
ymin = options.ybounds[0]
ymax = options.ybounds[1]
bar_axis.axis([-1, len(bar_y) + 1, ymin, ymax])
bar_axis.set_frame_on(False)
bar_axis.get_xaxis().set_visible(False)
bar_axis.get_yaxis().tick_left()
bar_axis.get_yaxis().set_tick_params(direction='out')
bar_axis.add_artist(mpl.lines.Line2D((-1, -1),
(bar_axis.get_yticks()
[1], bar_axis.get_yticks()[-2]),
color='black', linewidth=1))
previous_order = 1
for i in range(len(sites)):
if len(sites[i]) != previous_order:
bar_axis.add_artist(mpl.lines.Line2D((i, i),
(ymin, ymax),
color="black",
linestyle=":",
linewidth=1))
previous_order = len(sites[i])
if options.sigmas != 0:
min_offset = options.star_spacer * (ymax - ymin)
for i in range(len(p_values)):
star_counter = 0
for j in range(len(options.star_cutoffs)):
if p_values[i] < options.star_cutoffs[j]:
star_counter += 1
else:
break
for j in range(star_counter):
bar_axis.text(x=(i + 0),
y=ymin + (j * min_offset),
s="*", fontsize=16)
try:
plt.setp([a.get_xticklabels() for a in fig.axes[:-1]], visible=False)
except IndexError:
pass
if options.save:
fig.savefig(options.fname, format=options.format)
return fig, ax
| true | true |
1c3e02269e6e2d82f9b5467c72c8bd2643a182c4 | 3,781 | py | Python | pex/tools/commands/digraph.py | alexey-tereshenkov-oxb/pex | 2e2d1e50e604fdee48b0d51aea482ca255521ff0 | [
"Apache-2.0"
] | null | null | null | pex/tools/commands/digraph.py | alexey-tereshenkov-oxb/pex | 2e2d1e50e604fdee48b0d51aea482ca255521ff0 | [
"Apache-2.0"
] | null | null | null | pex/tools/commands/digraph.py | alexey-tereshenkov-oxb/pex | 2e2d1e50e604fdee48b0d51aea482ca255521ff0 | [
"Apache-2.0"
] | null | null | null | # Copyright 2020 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import absolute_import
from pex.typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import IO, Dict, List, Mapping, Optional, Tuple
Value = Optional[str]
Attributes = Mapping[str, Value]
class DiGraph(object):
"""Renders a dot digraph built up from nodes and edges."""
@staticmethod
def _render_ID(value):
# type: (str) -> str
# See https://graphviz.org/doc/info/lang.html for the various forms of `ID`.
return '"{}"'.format(value.replace('"', '\\"'))
@classmethod
def _render_a_list(cls, attributes):
# type: (Attributes) -> str
# See https://graphviz.org/doc/info/lang.html for the `a_list` production.
return ", ".join(
"{name}={value}".format(name=name, value=cls._render_ID(value))
for name, value in attributes.items()
if value is not None
)
def __init__(
self,
name, # type: str
strict=True, # type: bool
**attributes # type: Value
):
# type: (...) -> None
"""
:param name: A name for the graph.
:param strict: Whether or not duplicate edges are collapsed into one edge.
"""
self._name = name
self._strict = strict
self._attributes = attributes # type: Attributes
self._nodes = {} # type: Dict[str, Attributes]
self._edges = [] # type: List[Tuple[str, str, Attributes]]
@property
def name(self):
return self._name
def add_node(
self,
name, # type: str
**attributes # type: Value
):
# type: (...) -> None
"""Adds a node to the graph.
This is done implicitly by add_edge for the nodes the edge connects, but may be useful when
the node is either isolated or else needs to be decorated with attributes.
:param name: The name of the node.
"""
self._nodes[name] = attributes
def add_edge(
self,
start, # type: str
end, # type: str
**attributes # type: Value
):
# type: (...) -> None
"""
:param start: The name of the start node.
:param end: The name of the end node.
:param attributes: Any extra attributes for the edge connecting the start node to the end
node.
"""
self._edges.append((start, end, attributes))
def emit(self, out):
# type: (IO[str]) -> None
"""Render the current state of this digraph to the given `out` stream.
:param out: A stream to render this digraph to. N/B.: Will not be flushed or closed.
"""
def emit_attr_stmt(
stmt, # type: str
attributes, # type: Attributes
):
# type: (...) -> None
# See https://graphviz.org/doc/info/lang.html for the `attr_stmt` production.
out.write(
"{statement} [{a_list}];\n".format(
statement=stmt, a_list=self._render_a_list(attributes)
)
)
if self._strict:
out.write("strict ")
out.write("digraph {name} {{\n".format(name=self._render_ID(self._name)))
emit_attr_stmt("graph", self._attributes)
for node, attributes in self._nodes.items():
emit_attr_stmt(self._render_ID(node), attributes)
for start, end, attributes in self._edges:
emit_attr_stmt(
"{start} -> {end}".format(start=self._render_ID(start), end=self._render_ID(end)),
attributes,
)
out.write("}\n")
| 32.316239 | 99 | 0.56493 |
from __future__ import absolute_import
from pex.typing import TYPE_CHECKING
if TYPE_CHECKING:
from typing import IO, Dict, List, Mapping, Optional, Tuple
Value = Optional[str]
Attributes = Mapping[str, Value]
class DiGraph(object):
@staticmethod
def _render_ID(value):
return '"{}"'.format(value.replace('"', '\\"'))
@classmethod
def _render_a_list(cls, attributes):
return ", ".join(
"{name}={value}".format(name=name, value=cls._render_ID(value))
for name, value in attributes.items()
if value is not None
)
def __init__(
self,
name,
strict=True,
**attributes
):
self._name = name
self._strict = strict
self._attributes = attributes
self._nodes = {}
self._edges = []
@property
def name(self):
return self._name
def add_node(
self,
name,
**attributes
):
self._nodes[name] = attributes
def add_edge(
self,
start,
end,
**attributes
):
self._edges.append((start, end, attributes))
def emit(self, out):
def emit_attr_stmt(
stmt,
attributes,
):
out.write(
"{statement} [{a_list}];\n".format(
statement=stmt, a_list=self._render_a_list(attributes)
)
)
if self._strict:
out.write("strict ")
out.write("digraph {name} {{\n".format(name=self._render_ID(self._name)))
emit_attr_stmt("graph", self._attributes)
for node, attributes in self._nodes.items():
emit_attr_stmt(self._render_ID(node), attributes)
for start, end, attributes in self._edges:
emit_attr_stmt(
"{start} -> {end}".format(start=self._render_ID(start), end=self._render_ID(end)),
attributes,
)
out.write("}\n")
| true | true |
1c3e0255111886053eae804e26db41e82e52d72c | 1,047 | py | Python | .github/workflows/dev/codemeta2citation.py | jurysek/lstmcpipe-1 | 978143b60ef7d9851d91626666ca65113764c4d9 | [
"MIT"
] | null | null | null | .github/workflows/dev/codemeta2citation.py | jurysek/lstmcpipe-1 | 978143b60ef7d9851d91626666ca65113764c4d9 | [
"MIT"
] | null | null | null | .github/workflows/dev/codemeta2citation.py | jurysek/lstmcpipe-1 | 978143b60ef7d9851d91626666ca65113764c4d9 | [
"MIT"
] | null | null | null | from pathlib import Path
from ruamel.yaml import YAML
import json
def codemeta2citation(codemeta_path='codemeta.json', citation_path='CITATION.cff'):
codemeta = json.load(open(codemeta_path))
citation = {'title': codemeta['name'],
'type': 'software',
'authors': [],
'message': 'If you use this software, please cite it using Zenodo from https://doi.org/10.5281/zenodo.6460727',
'license': 'MIT',
}
for author in codemeta['author']:
citation['authors'].append({
'family-names': author['familyName'],
'given-names': author['givenName'],
'orcid': author['@id'],
'email': author['email']
}
)
yaml = YAML()
yaml.dump(citation, open(citation_path, 'w'))
if __name__ == '__main__':
codemeta_path = Path(__file__).parents[3].joinpath('codemeta.json')
citation_path = Path(__file__).parents[3].joinpath('CITATION.cff')
codemeta2citation(codemeta_path, citation_path)
| 33.774194 | 127 | 0.601719 | from pathlib import Path
from ruamel.yaml import YAML
import json
def codemeta2citation(codemeta_path='codemeta.json', citation_path='CITATION.cff'):
codemeta = json.load(open(codemeta_path))
citation = {'title': codemeta['name'],
'type': 'software',
'authors': [],
'message': 'If you use this software, please cite it using Zenodo from https://doi.org/10.5281/zenodo.6460727',
'license': 'MIT',
}
for author in codemeta['author']:
citation['authors'].append({
'family-names': author['familyName'],
'given-names': author['givenName'],
'orcid': author['@id'],
'email': author['email']
}
)
yaml = YAML()
yaml.dump(citation, open(citation_path, 'w'))
if __name__ == '__main__':
codemeta_path = Path(__file__).parents[3].joinpath('codemeta.json')
citation_path = Path(__file__).parents[3].joinpath('CITATION.cff')
codemeta2citation(codemeta_path, citation_path)
| true | true |
1c3e0257c6ac580b52b8817dfc6134af8071cfa3 | 5,287 | py | Python | pulsar-client-cpp/python/pulsar/schema/definition.py | ganeshs/pulsar | 4f43bdad798a74970489be450338078bc4684d72 | [
"Apache-2.0"
] | null | null | null | pulsar-client-cpp/python/pulsar/schema/definition.py | ganeshs/pulsar | 4f43bdad798a74970489be450338078bc4684d72 | [
"Apache-2.0"
] | null | null | null | pulsar-client-cpp/python/pulsar/schema/definition.py | ganeshs/pulsar | 4f43bdad798a74970489be450338078bc4684d72 | [
"Apache-2.0"
] | null | null | null | #
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you 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 abc import abstractmethod, ABCMeta
from enum import Enum, EnumMeta
from collections import OrderedDict
from six import with_metaclass
def _check_record_or_field(x):
if (type(x) is type and not issubclass(x, Record)) \
and not isinstance(x, Field):
raise Exception('Argument ' + x + ' is not a Record or a Field')
class RecordMeta(type):
def __new__(metacls, name, parents, dct):
if name != 'Record':
# Do not apply this logic to the base class itself
dct['_fields'] = RecordMeta._get_fields(dct)
return type.__new__(metacls, name, parents, dct)
@classmethod
def _get_fields(cls, dct):
# Build a set of valid fields for this record
fields = OrderedDict()
for name, value in dct.items():
if issubclass(type(value), EnumMeta):
# Wrap Python enums
value = _Enum(value)
elif type(value) == RecordMeta:
# We expect an instance of a record rather than the class itself
value = value()
if isinstance(value, Record) or isinstance(value, Field):
fields[name] = value
return fields
class Record(with_metaclass(RecordMeta, object)):
def __init__(self, *args, **kwargs):
if args:
# Only allow keyword args
raise TypeError('Non-keyword arguments not allowed when initializing Records')
for k, value in self._fields.items():
if k in kwargs:
# Value was overridden at constructor
self.__setattr__(k, kwargs[k])
else:
# Set field to default value
self.__setattr__(k, value.default())
@classmethod
def schema(cls):
schema = {
'name': str(cls.__name__),
'type': 'record',
'fields': []
}
for name in sorted(cls._fields.keys()):
schema['fields'].append({
'name': name,
'type': cls._fields[name].schema()
})
return schema
def __setattr__(self, key, value):
if key not in self._fields:
raise AttributeError('Cannot set undeclared field ' + key + ' on record')
super(Record, self).__setattr__(key, value)
def __eq__(self, other):
for field in self._fields:
if self.__getattribute__(field) != other.__getattribute__(field):
return False
return True
def __str__(self):
return str(self.__dict__)
class Field(object):
def __init__(self, default=None):
self._default = default
@abstractmethod
def type(self):
pass
def schema(self):
# For primitive types, the schema would just be the type itself
return self.type()
def default(self):
return self._default
# All types
class Null(Field):
def type(self):
return 'null'
class Boolean(Field):
def type(self):
return 'boolean'
class Integer(Field):
def type(self):
return 'int'
class Long(Field):
def type(self):
return 'long'
class Float(Field):
def type(self):
return 'float'
class Double(Field):
def type(self):
return 'double'
class Bytes(Field):
def type(self):
return 'bytes'
class String(Field):
def type(self):
return 'string'
# Complex types
class _Enum(Field):
def __init__(self, enum_type):
if not issubclass(enum_type, Enum):
raise Exception(enum_type + " is not a valid Enum type")
self.enum_type = enum_type
def type(self):
return 'enum'
def schema(self):
return {
'type': self.type(),
'name': self.enum_type.__name__,
'symbols': [x.name for x in self.enum_type]
}
class Array(Field):
def __init__(self, array_type):
_check_record_or_field(array_type)
self.array_type = array_type
def type(self):
return 'array'
def schema(self):
return {
'type': self.type(),
'items': self.array_type.schema()
}
class Map(Field):
def __init__(self, value_type):
_check_record_or_field(value_type)
self.value_type = value_type
def type(self):
return 'map'
def schema(self):
return {
'type': self.type(),
'values': self.value_type.schema()
}
| 25.541063 | 90 | 0.603367 |
from abc import abstractmethod, ABCMeta
from enum import Enum, EnumMeta
from collections import OrderedDict
from six import with_metaclass
def _check_record_or_field(x):
if (type(x) is type and not issubclass(x, Record)) \
and not isinstance(x, Field):
raise Exception('Argument ' + x + ' is not a Record or a Field')
class RecordMeta(type):
def __new__(metacls, name, parents, dct):
if name != 'Record':
dct['_fields'] = RecordMeta._get_fields(dct)
return type.__new__(metacls, name, parents, dct)
@classmethod
def _get_fields(cls, dct):
fields = OrderedDict()
for name, value in dct.items():
if issubclass(type(value), EnumMeta):
value = _Enum(value)
elif type(value) == RecordMeta:
value = value()
if isinstance(value, Record) or isinstance(value, Field):
fields[name] = value
return fields
class Record(with_metaclass(RecordMeta, object)):
def __init__(self, *args, **kwargs):
if args:
raise TypeError('Non-keyword arguments not allowed when initializing Records')
for k, value in self._fields.items():
if k in kwargs:
self.__setattr__(k, kwargs[k])
else:
self.__setattr__(k, value.default())
@classmethod
def schema(cls):
schema = {
'name': str(cls.__name__),
'type': 'record',
'fields': []
}
for name in sorted(cls._fields.keys()):
schema['fields'].append({
'name': name,
'type': cls._fields[name].schema()
})
return schema
def __setattr__(self, key, value):
if key not in self._fields:
raise AttributeError('Cannot set undeclared field ' + key + ' on record')
super(Record, self).__setattr__(key, value)
def __eq__(self, other):
for field in self._fields:
if self.__getattribute__(field) != other.__getattribute__(field):
return False
return True
def __str__(self):
return str(self.__dict__)
class Field(object):
def __init__(self, default=None):
self._default = default
@abstractmethod
def type(self):
pass
def schema(self):
return self.type()
def default(self):
return self._default
class Null(Field):
def type(self):
return 'null'
class Boolean(Field):
def type(self):
return 'boolean'
class Integer(Field):
def type(self):
return 'int'
class Long(Field):
def type(self):
return 'long'
class Float(Field):
def type(self):
return 'float'
class Double(Field):
def type(self):
return 'double'
class Bytes(Field):
def type(self):
return 'bytes'
class String(Field):
def type(self):
return 'string'
class _Enum(Field):
def __init__(self, enum_type):
if not issubclass(enum_type, Enum):
raise Exception(enum_type + " is not a valid Enum type")
self.enum_type = enum_type
def type(self):
return 'enum'
def schema(self):
return {
'type': self.type(),
'name': self.enum_type.__name__,
'symbols': [x.name for x in self.enum_type]
}
class Array(Field):
def __init__(self, array_type):
_check_record_or_field(array_type)
self.array_type = array_type
def type(self):
return 'array'
def schema(self):
return {
'type': self.type(),
'items': self.array_type.schema()
}
class Map(Field):
def __init__(self, value_type):
_check_record_or_field(value_type)
self.value_type = value_type
def type(self):
return 'map'
def schema(self):
return {
'type': self.type(),
'values': self.value_type.schema()
}
| true | true |
1c3e02814e38959fa7456f32b8249967ebd21bab | 127 | py | Python | src/battery.py | MITEVT/soc-modeling | 8827c6b7c019ded63f1c12dfd4e599f95af11441 | [
"MIT"
] | 1 | 2019-02-04T14:32:18.000Z | 2019-02-04T14:32:18.000Z | src/battery.py | MITEVT/soc-modeling | 8827c6b7c019ded63f1c12dfd4e599f95af11441 | [
"MIT"
] | null | null | null | src/battery.py | MITEVT/soc-modeling | 8827c6b7c019ded63f1c12dfd4e599f95af11441 | [
"MIT"
] | null | null | null | class Battery(object):
def __init__(self, capacity_ah):
self.capacity_ah = capacity_ah
self.available_ah = capacity_ah
| 15.875 | 33 | 0.76378 | class Battery(object):
def __init__(self, capacity_ah):
self.capacity_ah = capacity_ah
self.available_ah = capacity_ah
| true | true |
1c3e02a05a300cac523962bae33502cc594c7744 | 238 | py | Python | mmdet/models/backbones/__init__.py | greathope/NDL-image-detection-3rd-solution | 0cb13e38be0a00d7ab4ceed60dac40d60a56a4dd | [
"MIT"
] | 2 | 2020-03-21T06:47:32.000Z | 2021-11-12T07:50:21.000Z | mmdet/models/backbones/__init__.py | greathope/NDL-image-detection-3rd-solution | 0cb13e38be0a00d7ab4ceed60dac40d60a56a4dd | [
"MIT"
] | 4 | 2021-03-19T11:32:25.000Z | 2022-03-12T00:19:27.000Z | mmdet/models/backbones/__init__.py | greathope/NDL-image-detection-3rd-solution | 0cb13e38be0a00d7ab4ceed60dac40d60a56a4dd | [
"MIT"
] | 1 | 2020-03-25T02:29:36.000Z | 2020-03-25T02:29:36.000Z | from .hrnet import HRNet
from .resnet import ResNet, make_res_layer
from .resnext import ResNeXt
from .ssd_vgg import SSDVGG
from .seresnet import SeResNet
__all__ = ['ResNet', 'make_res_layer', 'ResNeXt', 'SSDVGG', 'HRNet', 'SeResNet']
| 29.75 | 80 | 0.764706 | from .hrnet import HRNet
from .resnet import ResNet, make_res_layer
from .resnext import ResNeXt
from .ssd_vgg import SSDVGG
from .seresnet import SeResNet
__all__ = ['ResNet', 'make_res_layer', 'ResNeXt', 'SSDVGG', 'HRNet', 'SeResNet']
| true | true |
1c3e02bccffcb2afb3f53a11942cc753b7afffb8 | 2,638 | py | Python | tools/sosreport/tower.py | mhurron/awx | 97a7eeb3c86ec4bc4b6303533207150cb1dbac9d | [
"Apache-2.0"
] | 1 | 2019-01-30T20:38:53.000Z | 2019-01-30T20:38:53.000Z | tools/sosreport/tower.py | mhurron/awx | 97a7eeb3c86ec4bc4b6303533207150cb1dbac9d | [
"Apache-2.0"
] | 2 | 2020-06-18T15:00:24.000Z | 2022-03-02T04:00:36.000Z | tools/sosreport/tower.py | mhurron/awx | 97a7eeb3c86ec4bc4b6303533207150cb1dbac9d | [
"Apache-2.0"
] | 5 | 2020-12-14T20:43:58.000Z | 2022-03-24T16:30:54.000Z | # Copyright (c) 2016 Ansible, Inc.
# All Rights Reserved.
import sos
from distutils.version import LooseVersion
SOSREPORT_TOWER_COMMANDS = [
"ansible --version", # ansible core version
"awx-manage --version", # tower version
"awx-manage list_instances", # tower cluster configuration
"awx-manage run_dispatcher --status", # tower dispatch worker status
"supervisorctl status", # tower process status
"rabbitmqctl status",
"rabbitmqctl cluster_status",
"/var/lib/awx/venv/awx/bin/pip freeze", # pip package list
"/var/lib/awx/venv/awx/bin/pip freeze -l", # pip package list without globally-installed packages
"/var/lib/awx/venv/ansible/bin/pip freeze", # pip package list
"/var/lib/awx/venv/ansible/bin/pip freeze -l", # pip package list without globally-installed packages
"tree -d /var/lib/awx", # show me the dirs
"ls -ll /var/lib/awx", # check permissions
"ls -ll /var/lib/awx/venv", # list all venvs
"ls -ll /etc/tower",
"umask -p" # check current umask
]
SOSREPORT_TOWER_DIRS = [
"/etc/tower/",
"/etc/ansible/",
"/etc/supervisord.d/",
"/etc/nginx/",
"/var/log/tower",
"/var/log/nginx",
"/var/log/rabbitmq",
"/var/log/supervisor",
"/var/log/syslog",
"/var/log/udev",
"/var/log/kern*",
"/var/log/dist-upgrade",
"/var/log/installer",
"/var/log/unattended-upgrades",
"/var/log/apport.log"
]
SOSREPORT_FORBIDDEN_PATHS = [
"/etc/tower/SECRET_KEY",
"/etc/tower/tower.key",
"/etc/tower/awx.key",
"/etc/tower/tower.cert",
"/etc/tower/awx.cert"
]
if LooseVersion(sos.__version__) >= LooseVersion('3.0'):
from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin
class tower(Plugin, RedHatPlugin, UbuntuPlugin):
'''Collect Ansible Tower related information'''
plugin_name = "tower"
def setup(self):
for path in SOSREPORT_TOWER_DIRS:
self.add_copy_spec(path)
for path in SOSREPORT_FORBIDDEN_PATHS:
self.add_forbidden_path(path)
for command in SOSREPORT_TOWER_COMMANDS:
self.add_cmd_output(command)
else:
import sos.plugintools
class tower(sos.plugintools.PluginBase):
'''Collect Ansible Tower related information'''
def setup(self):
for path in SOSREPORT_TOWER_DIRS:
self.addCopySpec(path)
for path in SOSREPORT_FORBIDDEN_PATHS:
self.addForbiddenPath(path)
for command in SOSREPORT_TOWER_COMMANDS:
self.collectExtOutput(command)
| 30.321839 | 105 | 0.636846 |
import sos
from distutils.version import LooseVersion
SOSREPORT_TOWER_COMMANDS = [
"ansible --version",
"awx-manage --version",
"awx-manage list_instances",
"awx-manage run_dispatcher --status",
"supervisorctl status",
"rabbitmqctl status",
"rabbitmqctl cluster_status",
"/var/lib/awx/venv/awx/bin/pip freeze",
"/var/lib/awx/venv/awx/bin/pip freeze -l",
"/var/lib/awx/venv/ansible/bin/pip freeze",
"/var/lib/awx/venv/ansible/bin/pip freeze -l",
"tree -d /var/lib/awx",
"ls -ll /var/lib/awx",
"ls -ll /var/lib/awx/venv",
"ls -ll /etc/tower",
"umask -p"
]
SOSREPORT_TOWER_DIRS = [
"/etc/tower/",
"/etc/ansible/",
"/etc/supervisord.d/",
"/etc/nginx/",
"/var/log/tower",
"/var/log/nginx",
"/var/log/rabbitmq",
"/var/log/supervisor",
"/var/log/syslog",
"/var/log/udev",
"/var/log/kern*",
"/var/log/dist-upgrade",
"/var/log/installer",
"/var/log/unattended-upgrades",
"/var/log/apport.log"
]
SOSREPORT_FORBIDDEN_PATHS = [
"/etc/tower/SECRET_KEY",
"/etc/tower/tower.key",
"/etc/tower/awx.key",
"/etc/tower/tower.cert",
"/etc/tower/awx.cert"
]
if LooseVersion(sos.__version__) >= LooseVersion('3.0'):
from sos.plugins import Plugin, RedHatPlugin, UbuntuPlugin
class tower(Plugin, RedHatPlugin, UbuntuPlugin):
plugin_name = "tower"
def setup(self):
for path in SOSREPORT_TOWER_DIRS:
self.add_copy_spec(path)
for path in SOSREPORT_FORBIDDEN_PATHS:
self.add_forbidden_path(path)
for command in SOSREPORT_TOWER_COMMANDS:
self.add_cmd_output(command)
else:
import sos.plugintools
class tower(sos.plugintools.PluginBase):
'''Collect Ansible Tower related information'''
def setup(self):
for path in SOSREPORT_TOWER_DIRS:
self.addCopySpec(path)
for path in SOSREPORT_FORBIDDEN_PATHS:
self.addForbiddenPath(path)
for command in SOSREPORT_TOWER_COMMANDS:
self.collectExtOutput(command)
| true | true |
1c3e04c42e464fd07858dbd7a510a64ff6926daf | 280 | py | Python | src/django_dag_admin/formset.py | bva-icx/django-dag-admin | ab8e2df2ae93b3afff81e0cb70bd87f9d60644ee | [
"Apache-2.0"
] | null | null | null | src/django_dag_admin/formset.py | bva-icx/django-dag-admin | ab8e2df2ae93b3afff81e0cb70bd87f9d60644ee | [
"Apache-2.0"
] | null | null | null | src/django_dag_admin/formset.py | bva-icx/django-dag-admin | ab8e2df2ae93b3afff81e0cb70bd87f9d60644ee | [
"Apache-2.0"
] | null | null | null | # -*- coding: utf-8 -*-
from django.forms.models import BaseInlineFormSet
class DjangoDagAdminFormSet(BaseInlineFormSet):
def get_form_kwargs(self, index):
kwargs = super().get_form_kwargs(index)
kwargs['parent_object'] = self.instance
return kwargs
| 28 | 49 | 0.707143 |
from django.forms.models import BaseInlineFormSet
class DjangoDagAdminFormSet(BaseInlineFormSet):
def get_form_kwargs(self, index):
kwargs = super().get_form_kwargs(index)
kwargs['parent_object'] = self.instance
return kwargs
| true | true |
1c3e05d2179e991c8fd1730a01795aa8e342575a | 2,283 | py | Python | cdips/lcproc/period_find_for_cluster.py | lgbouma/cdips | 187e15e620cd44160372dbfa9da989d38722c3e5 | [
"MIT"
] | 1 | 2019-10-04T02:03:25.000Z | 2019-10-04T02:03:25.000Z | cdips/lcproc/period_find_for_cluster.py | lgbouma/cdips | 187e15e620cd44160372dbfa9da989d38722c3e5 | [
"MIT"
] | 3 | 2019-08-17T20:33:23.000Z | 2021-08-18T17:55:10.000Z | cdips/lcproc/period_find_for_cluster.py | lgbouma/cdips | 187e15e620cd44160372dbfa9da989d38722c3e5 | [
"MIT"
] | null | null | null | """
after get_lightcurves_for_cluster_stars, you can run some period-finding
routines
"""
import numpy as np, pandas as pd
from astropy.io import fits
from glob import glob
import os
from astrobase import periodbase, checkplot
def do_period_finding_fitslc(lcpath, fluxap='TFA2', period_min=0.5, outdir=None):
if not outdir:
outdir = os.path.dirname(lcpath)
outfile = os.path.basename(lcpath).replace(
'.fits', '_spdm_blsp_checkplot.png'
)
outpath = os.path.join(outdir, outfile)
if os.path.exists(outpath):
print('found & skipped {}'.format(outpath))
return
hdulist = fits.open(lcpath)
hdr, lc = hdulist[0].header, hdulist[1].data
times, mags, errs = (
lc['TMID_BJD'],
lc[fluxap],
np.ones_like(lc[fluxap])*np.nanmedian(lc[fluxap])/1000
)
#glsp = periodbase.pgen_lsp(times,mags,errs)
spdm = periodbase.stellingwerf_pdm(times, mags, errs)
blsp = periodbase.bls_parallel_pfind(times, mags, errs, startp=period_min,
get_stats=False)
objectinfo = {}
keys = ['objectid','ra','decl','pmra','pmdecl','teff','gmag']
hdrkeys = ['Gaia-ID', 'RA[deg]', 'Dec[deg]', 'PM_RA[mas/yr]',
'PM_Dec[mas/year]', 'teff_val', 'phot_g_mean_mag']
for k,hk in zip(keys,hdrkeys):
if hk in hdr:
objectinfo[k] = hdr[hk]
else:
objectinfo[k] = np.nan
cp = checkplot.twolsp_checkplot_png(blsp, spdm, times, mags, errs,
objectinfo=objectinfo,
outfile=outpath,
sigclip=[50.,5.],
plotdpi=100,
phasebin=3e-2,
phasems=6.0,
phasebinms=12.0,
unphasedms=6.0)
print('did {}'.format(outpath))
def do_period_finding_cluster(clustername, runname, ap=2):
lcdir = (
'../data/cluster_data/lightcurves/{}_{}'.format(clustername, runname)
)
lcpaths = glob(os.path.join(lcdir,'*_llc.fits'))
for lcpath in lcpaths:
do_period_finding_fitslc(lcpath)
| 33.086957 | 81 | 0.549277 | import numpy as np, pandas as pd
from astropy.io import fits
from glob import glob
import os
from astrobase import periodbase, checkplot
def do_period_finding_fitslc(lcpath, fluxap='TFA2', period_min=0.5, outdir=None):
if not outdir:
outdir = os.path.dirname(lcpath)
outfile = os.path.basename(lcpath).replace(
'.fits', '_spdm_blsp_checkplot.png'
)
outpath = os.path.join(outdir, outfile)
if os.path.exists(outpath):
print('found & skipped {}'.format(outpath))
return
hdulist = fits.open(lcpath)
hdr, lc = hdulist[0].header, hdulist[1].data
times, mags, errs = (
lc['TMID_BJD'],
lc[fluxap],
np.ones_like(lc[fluxap])*np.nanmedian(lc[fluxap])/1000
)
spdm = periodbase.stellingwerf_pdm(times, mags, errs)
blsp = periodbase.bls_parallel_pfind(times, mags, errs, startp=period_min,
get_stats=False)
objectinfo = {}
keys = ['objectid','ra','decl','pmra','pmdecl','teff','gmag']
hdrkeys = ['Gaia-ID', 'RA[deg]', 'Dec[deg]', 'PM_RA[mas/yr]',
'PM_Dec[mas/year]', 'teff_val', 'phot_g_mean_mag']
for k,hk in zip(keys,hdrkeys):
if hk in hdr:
objectinfo[k] = hdr[hk]
else:
objectinfo[k] = np.nan
cp = checkplot.twolsp_checkplot_png(blsp, spdm, times, mags, errs,
objectinfo=objectinfo,
outfile=outpath,
sigclip=[50.,5.],
plotdpi=100,
phasebin=3e-2,
phasems=6.0,
phasebinms=12.0,
unphasedms=6.0)
print('did {}'.format(outpath))
def do_period_finding_cluster(clustername, runname, ap=2):
lcdir = (
'../data/cluster_data/lightcurves/{}_{}'.format(clustername, runname)
)
lcpaths = glob(os.path.join(lcdir,'*_llc.fits'))
for lcpath in lcpaths:
do_period_finding_fitslc(lcpath)
| true | true |
1c3e06d700fd8d978fa4cb832a94077e2ac73f9e | 184 | py | Python | fog/cli/reporting/__init__.py | Yomguithereal/fog | 0b2defd7c413b55766c4368e17e1238dfc3c8b81 | [
"MIT"
] | 17 | 2018-04-26T15:37:45.000Z | 2021-05-18T05:58:10.000Z | fog/cli/reporting/__init__.py | Yomguithereal/fog | 0b2defd7c413b55766c4368e17e1238dfc3c8b81 | [
"MIT"
] | 29 | 2018-04-27T14:54:20.000Z | 2021-05-27T15:30:14.000Z | fog/cli/reporting/__init__.py | Yomguithereal/fog | 0b2defd7c413b55766c4368e17e1238dfc3c8b81 | [
"MIT"
] | 1 | 2019-11-27T18:14:49.000Z | 2019-11-27T18:14:49.000Z | from fog.cli.reporting.html import print_html_report
from fog.cli.reporting.toml import print_toml_report
RENDERERS = {
'html': print_html_report,
'toml': print_toml_report
}
| 23 | 52 | 0.777174 | from fog.cli.reporting.html import print_html_report
from fog.cli.reporting.toml import print_toml_report
RENDERERS = {
'html': print_html_report,
'toml': print_toml_report
}
| true | true |
1c3e06f946e218c016a2141becd3929738d428e9 | 15,736 | py | Python | python/plot3d/face.py | nasa/Plot3D_utilities | f71d612ff1c6969059cc199b4b84c2d85fdf0a87 | [
"MIT"
] | 11 | 2021-08-12T06:40:43.000Z | 2022-03-15T08:31:49.000Z | python/plot3d/face.py | nasa/Plot3D_utilities | f71d612ff1c6969059cc199b4b84c2d85fdf0a87 | [
"MIT"
] | 9 | 2021-09-30T05:39:25.000Z | 2022-02-01T18:14:15.000Z | python/plot3d/face.py | nasa/Plot3D_utilities | f71d612ff1c6969059cc199b4b84c2d85fdf0a87 | [
"MIT"
] | 7 | 2021-08-11T18:54:02.000Z | 2021-12-15T15:53:12.000Z | import itertools
from typing import Dict, List, Tuple
import numpy as np
from numpy.lib import math
from .block import Block
class Face:
"""Defines a Face of a block for example IMIN,JMIN,JMIN to IMAX,JMIN,JMIN
"""
def __init__(self,nvertex:int=4):
""" Defines a face using nvertex 4 = quad 3 = triangles
Args:
nvertex (int, optional): Number of vertices. Defaults to 4.
id (int, optional): A unique index indentifying a face
"""
self.x = np.zeros(4)
self.y = np.zeros(4)
self.z = np.zeros(4)
self.I = np.zeros(4,dtype=np.int64)
self.J = np.zeros(4,dtype=np.int64)
self.K = np.zeros(4,dtype=np.int64)
self.cx = 0 # centroid
self.cy = 0
self.cz = 0
self.nvertex=0
self.blockIndex = 0 # not really needed except in periodicity
def to_dict(self):
"""Returns a dictionary representaon of a face
"""
return {'IMIN':min(self.I), 'JMIN':min(self.J), 'KMIN':min(self.K),
'IMAX':max(self.I), 'JMAX':max(self.J), 'KMAX':max(self.K),
'id':0, 'block_index':self.blockIndex}
@property
def IMIN(self):
return self.I.min()
@property
def JMIN(self):
return self.J.min()
@property
def KMIN(self):
return self.K.min()
@property
def IMAX(self):
return self.I.max()
@property
def JMAX(self):
return self.J.max()
@property
def KMAX(self):
return self.K.max()
@property
def BlockIndex(self):
return self.blockIndex
@property
def isEdge(self):
"""check if the face is actually an edge. This is an edge if two indicies IMIN == IMAX or JMIN=JMAX or KMIN=KMAX
Returns:
[bool]: True if face is really an edge
"""
return (int(self.IMIN == self.IMAX) + int(self.JMIN == self.JMAX) + int(self.KMIN == self.KMAX)) > 1
@property
def isPoint(self):
"""check if the face is actually an edge. This is an edge if two indicies IMIN == IMAX or JMIN=JMAX or KMIN=KMAX
Returns:
[type]: True if face is really a point
"""
return (int(self.IMIN == self.IMAX) + int(self.JMIN == self.JMAX) + int(self.KMIN == self.KMAX)) > 2
@property
def get_val(self,i_val:int,j_val:int,k_val:int):
"""Get the value where key (I,J,K) is equal to val
Args:
i_val (int): value of I
j_val (int): value of J
k_val (int): value of K
Returns:
[float]: x value
[float]: y value
[float]: z value
"""
indx_i = np.where(self.I == i_val).tolist()
indx_j = np.where(self.J == j_val).tolist()
indx_k = np.where(self.K == k_val).tolist()
indx_i.extend(indx_j)
indx_i.extend(indx_k)
indx = list(set([indx_i]))[0] # Get the common one through a union
return self.x[indx], self.y[indx], self.z[indx]
def add_vertex(self, x:float,y:float,z:float, i:int, j:int, k:int):
"""Add vertex to define a face
Args:
x (float): x-coordinate
y (float): y-coordinate
z (float): z-coordinate
i (int): i-th index of the coordinates (x,y,z)
j (int): j-th index of the coordinates (x,y,z)
k (int): k-th index of the coordinates (x,y,z)
"""
self.x[self.nvertex] = x
self.y[self.nvertex] = y
self.z[self.nvertex] = z
self.I[self.nvertex] = i
self.J[self.nvertex] = j
self.K[self.nvertex] = k
self.nvertex+=1
if self.nvertex==4:
self.cx = self.x.mean()
self.cy = self.y.mean()
self.cz = self.z.mean()
@property
def size(self):
if self.IMIN==self.IMAX:
return (self.JMAX- self.JMIN)*(self.KMAX-self.KMIN)
elif (self.JMIN==self.JMAX):
return (self.IMAX-self.IMIN)*(self.KMAX-self.KMIN)
elif (self.KMIN==self.KMAX):
return (self.IMAX-self.IMIN)*(self.JMAX- self.JMIN)
else:
return (self.IMAX-self.IMIN)*(self.JMAX- self.JMIN)*(self.KMAX-self.KMIN)
def set_block_index(self,val):
self.blockIndex = val
def __normal__(self):
"""Computes the normal vector of the face
not really used but if anyone wants it.
"""
if (self.I[0]!=self.I[1]) and (self.I[0]!=self.I[2]):
indx = np.argsort(self.I)
elif (self.J[0]!=self.J[1]) and (self.J[0]!=self.J[2]):
indx = np.argsort(self.J)
elif (self.K[0]!=self.K[1]) and (self.K[0]!=self.K[2]):
indx = np.argsort(self.K)
self.x = self.x[indx]
self.y = self.y[indx]
self.z = self.z[indx]
self.I = self.I[indx]
self.J = self.J[indx]
self.K = self.K[indx]
x1 = self.x[1]-self.x[0]; y1 = self.y[1]-self.y[0]; z1 = self.z[1]-self.z[0]
x2 = self.x[2]-self.x[0]; y2 = self.y[2]-self.y[0]; z2 = self.z[2]-self.z[0]
nx = y1*z2-y2*z1; ny = -1*(x1*z2-x2*z1); nz = x1*y2-x2*y1
self.nx = nx
self.ny = ny
self.nz = nz
def match_indices(self,f):
"""Check to see if two faces are the same. Checks to see if any of vertices x,y,z match
Normally this is used by Face1==Face2
Args:
f (Face): another face
Returns:
List[(int,int)]: list of indicies where there's a match.
"""
matched_vertices = list()
tol = 1E-6
matchedIndices = list()
for i in range(self.nvertex):
for j in range(f.nvertex):
dx = abs(self.x[i] - f.x[j])
dy = abs(self.y[i] - f.y[j])
dz = abs(self.z[i] - f.z[j])
if (dx<tol and dy<tol and dz<tol and (j not in matched_vertices)):
matchedIndices.append([i,j])
matched_vertices.append(j) # This vertex has been matched, remove from list
break # each index can only have a single match
return matchedIndices
def __eq__(self, f):
"""Check to see if two faces are the same by looking at the I,J,K
Checks to see if any of vertices x,y,z match
Args:
f (Face): another face
Returns:
Boolean: True if faces match, False if no match is found
"""
# matchedIndices = self.match_indices(f)
# (len(matchedIndices)==self.nvertex) and
return ((self.BlockIndex == f.BlockIndex)
and (self.IMIN == f.IMIN) and (self.IMAX == f.IMAX)
and (self.JMIN == f.JMIN) and (self.JMAX == f.JMAX)
and (self.KMIN == f.KMIN) and (self.KMAX == f.KMAX) )
def vertices_equals(self,f):
"""Checks to see if two faces are the same by looking at the vertices
Args:
f (Face): Another face
Returns:
bool: True = face vertices are equal
"""
matchedIndices = self.match_indices(f)
return (len(matchedIndices)==self.nvertex)
def __ne__(self,f):
"""Checks if two faces are not equal
Args:
f (Face): another face
Returns:
Boolean: True if faces match, False if no match is found
"""
match = self.__eq__(f)
return not match
def index_equals(self,f2):
"""Check to see of the face indices are equal
Args:
f2 ([type]): [description]
"""
if (self.IMIN == f2.IMIN and
self.JMIN == f2.JMIN and
self.KMIN == f2.KMIN and
self.IMAX == f2.IMAX and
self.JMAX == f2.JMAX and
self.KMAX == f2.KMAX):
return True
def __hash__(self):
if (len(self.I)>0):
return hash((self.I[0], self.J[0], self.K[0], self.I[-1], self.J[-1], self.K[-1]))
else:
return hash((0, 0, 0, 0, 0, 0))
def __str__(self):
if (len(self.I)>0):
return 'blk: {:d} [{:d},{:d},{:d},{:d},{:d},{:d}]'.format(self.blockIndex,self.IMIN, self.JMIN, self.KMIN, self.IMAX, self.JMAX, self.KMAX)
else:
return 'blk: {:d} [{:d},{:d},{:d},{:d},{:d},{:d}]'.format(self.blockIndex,0,0,0,0,0,0)
def __repr__(self):
return str(self)
@property
def diagonal_length(self) -> float:
"""Returns the diagonal length of the face
Returns:
float: diagonal length computed using IMIN, IMAX, JMIN, JMAX, KMIN, KMAX
"""
minIndx = 0; maxIndx = 0
for indx in range(len(self.I)):
if self.I[indx] == self.IMIN and self.J[indx] == self.JMIN and self.K[indx] == self.KMIN:
minIndx = indx
if self.I[indx] == self.IMAX and self.J[indx] == self.JMAX and self.K[indx] == self.KMAX:
maxIndx = indx
dx = self.x[minIndx] - self.x[maxIndx]
dy = self.y[minIndx] - self.y[maxIndx]
dz = self.z[minIndx] - self.z[maxIndx]
return math.sqrt(dx*dx + dy*dy + dz*dz)
def get_corners(self) -> Tuple:
"""Get the corners defined by (IMIN,JMIN,KMIN), (IMAX,JMAX,KMAX),
Returns:
Tuple: containing
- **(x,y,z)** (float,float,float): at IMIN,JMIN,KMIN
- **(x,y,z)** (float,float,float): at IMAX,JMAX,KMAX
Reference:
- GlennHT source code https://gitlab.grc.nasa.gov/lte-turbo/GlennHT/-/blob/master/src/M_ccMBMesh.F function computeLRT
"""
minIndx = 0; maxIndx = 0
for indx in range(len(self.I)):
if self.I[indx] == self.IMIN and self.J[indx] == self.JMIN and self.K[indx] == self.KMIN:
minIndx = indx
if self.I[indx] == self.IMAX and self.J[indx] == self.JMAX and self.K[indx] == self.KMAX:
maxIndx = indx
return (self.x[minIndx],self.y[minIndx], self.z[minIndx]),(self.x[maxIndx],self.y[maxIndx], self.z[maxIndx])
def create_face_from_diagonals(block:Block,imin:int,jmin:int,kmin:int,imax:int,jmax:int,kmax:int):
"""Creates a face on a block given a the diagonals defined as (IMIN,JMIN,KMIN), (IMAX, JMAX, KMAX)
Args:
block (Block): Block to create a face on
imin (int): Lower Corner IMIN
jmin (int): Lower Corner JMIN
kmin (int): Lower Corner KMIN
imax (int): Upper Corner IMAX
jmax (int): Upper Corner JMAX
kmax (int): Upper Corner
Returns:
(Face): Face created from diagonals
"""
newFace = Face(4) # This is because two of the corners either imin or imax can be equal
if imin==imax:
i = imin
for j in [jmin,jmax]:
for k in [kmin,kmax]:
x = block.X[i,j,k]
y = block.Y[i,j,k]
z = block.Z[i,j,k]
newFace.add_vertex(x,y,z,i,j,k)
elif jmin==jmax:
j = jmin
for i in [imin,imax]:
for k in [kmin,kmax]:
x = block.X[i,j,k]
y = block.Y[i,j,k]
z = block.Z[i,j,k]
newFace.add_vertex(x,y,z,i,j,k)
elif kmin==kmax:
k = kmin
for i in [imin,imax]:
for j in [jmin,jmax]:
x = block.X[i,j,k]
y = block.Y[i,j,k]
z = block.Z[i,j,k]
newFace.add_vertex(x,y,z,i,j,k)
return newFace
def split_face(face_to_split:Face, block:Block,imin:int,jmin:int,kmin:int,imax:int,jmax:int,kmax:int):
"""Splits a face with another face within the same block
picture the split as a two rectangles inside each other
Args:
face_to_split (Face): Face on the block to be split
block (Block): Block the split is occuring on
imin (int): IMIN index of the split (diagonals)
jmin (int): JMIN index of the split (diagonals)
kmin (int): KMIN index of the split (diagonals)
imax (int): IMAX index of the split
jmax (int): JMAX index of the split
kmax (int): KMAX index of the split
::
left face top face right face
________ __ __ __
| __ | | | |__| | | __
| |__| | | | __ | | |__| face_to_split/center face
|________| |__| |__| |__|
bottom face
Returns:
[List[Faces]]: List of unique faces from the split
"""
center_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=kmin,kmax=kmax)
if kmin == kmax:
# In the picture above Horizontal = i, vertical = j
left_face = create_face_from_diagonals(block,
imin=face_to_split.IMIN,imax=imin,
jmin=face_to_split.JMIN,jmax=face_to_split.JMAX,
kmin=kmin, kmax=kmax)
right_face = create_face_from_diagonals(block,
imin=imax, imax=face_to_split.IMAX,
jmin=face_to_split.JMIN, jmax=face_to_split.JMAX,
kmin=kmin, kmax=kmax)
top_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmax,jmax=face_to_split.JMAX,
kmin=kmin,kmax=kmax)
bottom_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=face_to_split.JMIN,jmax=jmin,
kmin=kmin,kmax=kmax)
elif (imin==imax):
# In the picture above Horizontal = j, vertical = k
left_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=face_to_split.JMIN, jmax=jmin,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
right_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmax, jmax=face_to_split.JMAX,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
top_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=kmax,kmax=face_to_split.KMAX)
bottom_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=face_to_split.KMIN,kmax=kmin)
elif (jmin==jmax):
# In the picture above Horizontal = i, vertical = k
left_face = create_face_from_diagonals(block,
imin=face_to_split.IMIN,imax=imin,
jmin=jmin,jmax=jmax,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
right_face = create_face_from_diagonals(block,
imin=imax,imax=face_to_split.IMAX,
jmin=jmin,jmax=jmax,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
top_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=kmax,kmax=face_to_split.KMAX)
bottom_face = create_face_from_diagonals(block,
imin=imin, imax=imax,
jmin=jmin, jmax=jmax,
kmin=face_to_split.KMIN, kmax=kmin)
faces = [top_face,bottom_face,left_face,right_face]
faces = [f for f in faces if not f.isEdge and not f.index_equals(center_face)] # Remove edges
[f.set_block_index(face_to_split.blockIndex) for f in faces]
return faces | 35.203579 | 151 | 0.540036 | import itertools
from typing import Dict, List, Tuple
import numpy as np
from numpy.lib import math
from .block import Block
class Face:
def __init__(self,nvertex:int=4):
self.x = np.zeros(4)
self.y = np.zeros(4)
self.z = np.zeros(4)
self.I = np.zeros(4,dtype=np.int64)
self.J = np.zeros(4,dtype=np.int64)
self.K = np.zeros(4,dtype=np.int64)
self.cx = 0
self.cy = 0
self.cz = 0
self.nvertex=0
self.blockIndex = 0
def to_dict(self):
return {'IMIN':min(self.I), 'JMIN':min(self.J), 'KMIN':min(self.K),
'IMAX':max(self.I), 'JMAX':max(self.J), 'KMAX':max(self.K),
'id':0, 'block_index':self.blockIndex}
@property
def IMIN(self):
return self.I.min()
@property
def JMIN(self):
return self.J.min()
@property
def KMIN(self):
return self.K.min()
@property
def IMAX(self):
return self.I.max()
@property
def JMAX(self):
return self.J.max()
@property
def KMAX(self):
return self.K.max()
@property
def BlockIndex(self):
return self.blockIndex
@property
def isEdge(self):
return (int(self.IMIN == self.IMAX) + int(self.JMIN == self.JMAX) + int(self.KMIN == self.KMAX)) > 1
@property
def isPoint(self):
return (int(self.IMIN == self.IMAX) + int(self.JMIN == self.JMAX) + int(self.KMIN == self.KMAX)) > 2
@property
def get_val(self,i_val:int,j_val:int,k_val:int):
indx_i = np.where(self.I == i_val).tolist()
indx_j = np.where(self.J == j_val).tolist()
indx_k = np.where(self.K == k_val).tolist()
indx_i.extend(indx_j)
indx_i.extend(indx_k)
indx = list(set([indx_i]))[0]
return self.x[indx], self.y[indx], self.z[indx]
def add_vertex(self, x:float,y:float,z:float, i:int, j:int, k:int):
self.x[self.nvertex] = x
self.y[self.nvertex] = y
self.z[self.nvertex] = z
self.I[self.nvertex] = i
self.J[self.nvertex] = j
self.K[self.nvertex] = k
self.nvertex+=1
if self.nvertex==4:
self.cx = self.x.mean()
self.cy = self.y.mean()
self.cz = self.z.mean()
@property
def size(self):
if self.IMIN==self.IMAX:
return (self.JMAX- self.JMIN)*(self.KMAX-self.KMIN)
elif (self.JMIN==self.JMAX):
return (self.IMAX-self.IMIN)*(self.KMAX-self.KMIN)
elif (self.KMIN==self.KMAX):
return (self.IMAX-self.IMIN)*(self.JMAX- self.JMIN)
else:
return (self.IMAX-self.IMIN)*(self.JMAX- self.JMIN)*(self.KMAX-self.KMIN)
def set_block_index(self,val):
self.blockIndex = val
def __normal__(self):
if (self.I[0]!=self.I[1]) and (self.I[0]!=self.I[2]):
indx = np.argsort(self.I)
elif (self.J[0]!=self.J[1]) and (self.J[0]!=self.J[2]):
indx = np.argsort(self.J)
elif (self.K[0]!=self.K[1]) and (self.K[0]!=self.K[2]):
indx = np.argsort(self.K)
self.x = self.x[indx]
self.y = self.y[indx]
self.z = self.z[indx]
self.I = self.I[indx]
self.J = self.J[indx]
self.K = self.K[indx]
x1 = self.x[1]-self.x[0]; y1 = self.y[1]-self.y[0]; z1 = self.z[1]-self.z[0]
x2 = self.x[2]-self.x[0]; y2 = self.y[2]-self.y[0]; z2 = self.z[2]-self.z[0]
nx = y1*z2-y2*z1; ny = -1*(x1*z2-x2*z1); nz = x1*y2-x2*y1
self.nx = nx
self.ny = ny
self.nz = nz
def match_indices(self,f):
matched_vertices = list()
tol = 1E-6
matchedIndices = list()
for i in range(self.nvertex):
for j in range(f.nvertex):
dx = abs(self.x[i] - f.x[j])
dy = abs(self.y[i] - f.y[j])
dz = abs(self.z[i] - f.z[j])
if (dx<tol and dy<tol and dz<tol and (j not in matched_vertices)):
matchedIndices.append([i,j])
matched_vertices.append(j)
break
return matchedIndices
def __eq__(self, f):
return ((self.BlockIndex == f.BlockIndex)
and (self.IMIN == f.IMIN) and (self.IMAX == f.IMAX)
and (self.JMIN == f.JMIN) and (self.JMAX == f.JMAX)
and (self.KMIN == f.KMIN) and (self.KMAX == f.KMAX) )
def vertices_equals(self,f):
matchedIndices = self.match_indices(f)
return (len(matchedIndices)==self.nvertex)
def __ne__(self,f):
match = self.__eq__(f)
return not match
def index_equals(self,f2):
if (self.IMIN == f2.IMIN and
self.JMIN == f2.JMIN and
self.KMIN == f2.KMIN and
self.IMAX == f2.IMAX and
self.JMAX == f2.JMAX and
self.KMAX == f2.KMAX):
return True
def __hash__(self):
if (len(self.I)>0):
return hash((self.I[0], self.J[0], self.K[0], self.I[-1], self.J[-1], self.K[-1]))
else:
return hash((0, 0, 0, 0, 0, 0))
def __str__(self):
if (len(self.I)>0):
return 'blk: {:d} [{:d},{:d},{:d},{:d},{:d},{:d}]'.format(self.blockIndex,self.IMIN, self.JMIN, self.KMIN, self.IMAX, self.JMAX, self.KMAX)
else:
return 'blk: {:d} [{:d},{:d},{:d},{:d},{:d},{:d}]'.format(self.blockIndex,0,0,0,0,0,0)
def __repr__(self):
return str(self)
@property
def diagonal_length(self) -> float:
minIndx = 0; maxIndx = 0
for indx in range(len(self.I)):
if self.I[indx] == self.IMIN and self.J[indx] == self.JMIN and self.K[indx] == self.KMIN:
minIndx = indx
if self.I[indx] == self.IMAX and self.J[indx] == self.JMAX and self.K[indx] == self.KMAX:
maxIndx = indx
dx = self.x[minIndx] - self.x[maxIndx]
dy = self.y[minIndx] - self.y[maxIndx]
dz = self.z[minIndx] - self.z[maxIndx]
return math.sqrt(dx*dx + dy*dy + dz*dz)
def get_corners(self) -> Tuple:
minIndx = 0; maxIndx = 0
for indx in range(len(self.I)):
if self.I[indx] == self.IMIN and self.J[indx] == self.JMIN and self.K[indx] == self.KMIN:
minIndx = indx
if self.I[indx] == self.IMAX and self.J[indx] == self.JMAX and self.K[indx] == self.KMAX:
maxIndx = indx
return (self.x[minIndx],self.y[minIndx], self.z[minIndx]),(self.x[maxIndx],self.y[maxIndx], self.z[maxIndx])
def create_face_from_diagonals(block:Block,imin:int,jmin:int,kmin:int,imax:int,jmax:int,kmax:int):
newFace = Face(4)
if imin==imax:
i = imin
for j in [jmin,jmax]:
for k in [kmin,kmax]:
x = block.X[i,j,k]
y = block.Y[i,j,k]
z = block.Z[i,j,k]
newFace.add_vertex(x,y,z,i,j,k)
elif jmin==jmax:
j = jmin
for i in [imin,imax]:
for k in [kmin,kmax]:
x = block.X[i,j,k]
y = block.Y[i,j,k]
z = block.Z[i,j,k]
newFace.add_vertex(x,y,z,i,j,k)
elif kmin==kmax:
k = kmin
for i in [imin,imax]:
for j in [jmin,jmax]:
x = block.X[i,j,k]
y = block.Y[i,j,k]
z = block.Z[i,j,k]
newFace.add_vertex(x,y,z,i,j,k)
return newFace
def split_face(face_to_split:Face, block:Block,imin:int,jmin:int,kmin:int,imax:int,jmax:int,kmax:int):
center_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=kmin,kmax=kmax)
if kmin == kmax:
left_face = create_face_from_diagonals(block,
imin=face_to_split.IMIN,imax=imin,
jmin=face_to_split.JMIN,jmax=face_to_split.JMAX,
kmin=kmin, kmax=kmax)
right_face = create_face_from_diagonals(block,
imin=imax, imax=face_to_split.IMAX,
jmin=face_to_split.JMIN, jmax=face_to_split.JMAX,
kmin=kmin, kmax=kmax)
top_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmax,jmax=face_to_split.JMAX,
kmin=kmin,kmax=kmax)
bottom_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=face_to_split.JMIN,jmax=jmin,
kmin=kmin,kmax=kmax)
elif (imin==imax):
left_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=face_to_split.JMIN, jmax=jmin,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
right_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmax, jmax=face_to_split.JMAX,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
top_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=kmax,kmax=face_to_split.KMAX)
bottom_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=face_to_split.KMIN,kmax=kmin)
elif (jmin==jmax):
left_face = create_face_from_diagonals(block,
imin=face_to_split.IMIN,imax=imin,
jmin=jmin,jmax=jmax,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
right_face = create_face_from_diagonals(block,
imin=imax,imax=face_to_split.IMAX,
jmin=jmin,jmax=jmax,
kmin=face_to_split.KMIN,kmax=face_to_split.KMAX)
top_face = create_face_from_diagonals(block,
imin=imin,imax=imax,
jmin=jmin,jmax=jmax,
kmin=kmax,kmax=face_to_split.KMAX)
bottom_face = create_face_from_diagonals(block,
imin=imin, imax=imax,
jmin=jmin, jmax=jmax,
kmin=face_to_split.KMIN, kmax=kmin)
faces = [top_face,bottom_face,left_face,right_face]
faces = [f for f in faces if not f.isEdge and not f.index_equals(center_face)]
[f.set_block_index(face_to_split.blockIndex) for f in faces]
return faces | true | true |
1c3e0768350d6a99e4f2e5e7c9299a051bd00318 | 1,234 | py | Python | piquipe/__init__.py | conn/python-piquipe | 9a8046473af2ec4c6b9eaf1df875af10f910a364 | [
"BSD-3-Clause"
] | null | null | null | piquipe/__init__.py | conn/python-piquipe | 9a8046473af2ec4c6b9eaf1df875af10f910a364 | [
"BSD-3-Clause"
] | null | null | null | piquipe/__init__.py | conn/python-piquipe | 9a8046473af2ec4c6b9eaf1df875af10f910a364 | [
"BSD-3-Clause"
] | null | null | null | import os
import threading
import queue
VERSION = '0.0.0'
def _forward_stream_to_queue(stream, queue_):
for line in iter(stream.readline, b''):
queue_.put(line)
def _forward_queue_to_stream(queue_, stream):
for line in iter(queue_.get, b''):
stream.write(line)
def _forward_p2q(read_fd, queue_):
read_stream = os.fdopen(read_fd, mode='rb', buffering=0)
_forward_stream_to_queue(read_stream, queue_)
queue_.put(b'')
read_stream.close()
def _forward_q2p(queue_, write_fd):
write_stream = os.fdopen(write_fd, mode='wb', buffering=0)
_forward_queue_to_stream(queue_, write_stream)
write_stream.close()
def _setup_forward_p2q_thread(read_fd, queue_):
thread = threading.Thread(target=_forward_p2q, args=(read_fd, queue_), daemon=True)
thread.start()
def _setup_forward_q2p_thread(queue_, write_fd):
thread = threading.Thread(target=_forward_q2p, args=(queue_, write_fd), daemon=True)
thread.start()
def pipe():
p2qread_fd, p2qwrite_fd = os.pipe()
q2pread_fd, q2pwrite_fd = os.pipe()
queue_ = queue.Queue()
_setup_forward_p2q_thread(p2qread_fd, queue_)
_setup_forward_q2p_thread(queue_, q2pwrite_fd)
return q2pread_fd, p2qwrite_fd
| 24.68 | 88 | 0.725284 | import os
import threading
import queue
VERSION = '0.0.0'
def _forward_stream_to_queue(stream, queue_):
for line in iter(stream.readline, b''):
queue_.put(line)
def _forward_queue_to_stream(queue_, stream):
for line in iter(queue_.get, b''):
stream.write(line)
def _forward_p2q(read_fd, queue_):
read_stream = os.fdopen(read_fd, mode='rb', buffering=0)
_forward_stream_to_queue(read_stream, queue_)
queue_.put(b'')
read_stream.close()
def _forward_q2p(queue_, write_fd):
write_stream = os.fdopen(write_fd, mode='wb', buffering=0)
_forward_queue_to_stream(queue_, write_stream)
write_stream.close()
def _setup_forward_p2q_thread(read_fd, queue_):
thread = threading.Thread(target=_forward_p2q, args=(read_fd, queue_), daemon=True)
thread.start()
def _setup_forward_q2p_thread(queue_, write_fd):
thread = threading.Thread(target=_forward_q2p, args=(queue_, write_fd), daemon=True)
thread.start()
def pipe():
p2qread_fd, p2qwrite_fd = os.pipe()
q2pread_fd, q2pwrite_fd = os.pipe()
queue_ = queue.Queue()
_setup_forward_p2q_thread(p2qread_fd, queue_)
_setup_forward_q2p_thread(queue_, q2pwrite_fd)
return q2pread_fd, p2qwrite_fd
| true | true |
1c3e0827f9792364d112de37b17170787e658b1d | 160 | py | Python | opendata_parser/parser/tokyo_covid19_patients_parser.py | sandfishfactory/opendata_parser | fc382978f62fe08c4c571827a233082d87e5d552 | [
"MIT"
] | null | null | null | opendata_parser/parser/tokyo_covid19_patients_parser.py | sandfishfactory/opendata_parser | fc382978f62fe08c4c571827a233082d87e5d552 | [
"MIT"
] | null | null | null | opendata_parser/parser/tokyo_covid19_patients_parser.py | sandfishfactory/opendata_parser | fc382978f62fe08c4c571827a233082d87e5d552 | [
"MIT"
] | null | null | null | from parser.base_parser import BaseParser
class TokyoCovid19PatientsParser(BaseParser):
def parse(self):
print("echo TokyoCovid19PatientsParser")
| 22.857143 | 48 | 0.78125 | from parser.base_parser import BaseParser
class TokyoCovid19PatientsParser(BaseParser):
def parse(self):
print("echo TokyoCovid19PatientsParser")
| true | true |
1c3e091a255af12b065fb8335e7ec92451820295 | 2,794 | py | Python | Image-Analysis/main.py | prashanth-acsq/Azure-Cognitive-Services | 69fc4317561c2b7fc469945d7e6c175c539d6e16 | [
"MIT"
] | 1 | 2022-03-21T10:29:17.000Z | 2022-03-21T10:29:17.000Z | Image-Analysis/main.py | prashanth-acsq/Azure-Cognitive-Services | 69fc4317561c2b7fc469945d7e6c175c539d6e16 | [
"MIT"
] | null | null | null | Image-Analysis/main.py | prashanth-acsq/Azure-Cognitive-Services | 69fc4317561c2b7fc469945d7e6c175c539d6e16 | [
"MIT"
] | 1 | 2022-03-13T10:27:30.000Z | 2022-03-13T10:27:30.000Z | """
Only Describing done in this script
"""
import os
import sys
import time
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
from array import array
from PIL import Image
READ_PATH = "Files"
def breaker(num: int = 50, char: str = "*") -> None:
print("\n" + num*char + "\n")
def main():
subscription_key: str = None
endpoint: str = None
# read_image_url: str = "https://raw.githubusercontent.com/Azure-Samples/cognitive-services-sample-data-files/master/ComputerVision/Images/landmark.jpg"
read_image_url: str = None
filename: str = "Test.jpg"
args_1: tuple = ("--subscription-key", "-skey")
args_2: tuple = ("--endpoint", "-endp")
args_3: tuple = ("--url", "-u")
args_4: tuple = ("--file", "-f")
if args_1[0] in sys.argv: subscription_key = sys.argv[sys.argv.index(args_1[0]) + 1]
if args_1[1] in sys.argv: subscription_key = sys.argv[sys.argv.index(args_1[1]) + 1]
if args_2[0] in sys.argv: endpoint = sys.argv[sys.argv.index(args_2[0]) + 1]
if args_2[1] in sys.argv: endpoint = sys.argv[sys.argv.index(args_2[1]) + 1]
if args_3[0] in sys.argv: read_image_url = sys.argv[sys.argv.index(args_3[0]) + 1]
if args_3[1] in sys.argv: read_image_url = sys.argv[sys.argv.index(args_3[1]) + 1]
if args_4[0] in sys.argv: filename = sys.argv[sys.argv.index(args_4[0]) + 1]
if args_4[1] in sys.argv: filename = sys.argv[sys.argv.index(args_4[1]) + 1]
# subscription_key: str = os.environ.get("COMPUTER_VISION_SUBSCRIPTION_KEY")
# endpoint: str = os.environ.get("COMPUTER_VISION_ENDPOINT")
assert subscription_key is not None, "subscription_key is not set"
assert endpoint is not None, "endpoint is not set"
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
# Call API
if read_image_url is not None:
description_results = computervision_client.describe_image(read_image_url)
else:
description_results = computervision_client.describe_image_in_stream(open(os.path.join(READ_PATH, filename), "rb"))
# Get the captions (descriptions) from the response, with confidence level
breaker()
print("Description of Image \n")
if len(description_results.captions) == 0:
print("No description detected !!!")
else:
for caption in description_results.captions:
print(f"'{caption.text.title()}' with confidence {caption.confidence * 100:.2f}")
breaker()
if __name__ == "__main__":
sys.exit(main() or 0)
| 36.285714 | 156 | 0.705082 |
import os
import sys
import time
from azure.cognitiveservices.vision.computervision import ComputerVisionClient
from azure.cognitiveservices.vision.computervision.models import OperationStatusCodes
from azure.cognitiveservices.vision.computervision.models import VisualFeatureTypes
from msrest.authentication import CognitiveServicesCredentials
from array import array
from PIL import Image
READ_PATH = "Files"
def breaker(num: int = 50, char: str = "*") -> None:
print("\n" + num*char + "\n")
def main():
subscription_key: str = None
endpoint: str = None
read_image_url: str = None
filename: str = "Test.jpg"
args_1: tuple = ("--subscription-key", "-skey")
args_2: tuple = ("--endpoint", "-endp")
args_3: tuple = ("--url", "-u")
args_4: tuple = ("--file", "-f")
if args_1[0] in sys.argv: subscription_key = sys.argv[sys.argv.index(args_1[0]) + 1]
if args_1[1] in sys.argv: subscription_key = sys.argv[sys.argv.index(args_1[1]) + 1]
if args_2[0] in sys.argv: endpoint = sys.argv[sys.argv.index(args_2[0]) + 1]
if args_2[1] in sys.argv: endpoint = sys.argv[sys.argv.index(args_2[1]) + 1]
if args_3[0] in sys.argv: read_image_url = sys.argv[sys.argv.index(args_3[0]) + 1]
if args_3[1] in sys.argv: read_image_url = sys.argv[sys.argv.index(args_3[1]) + 1]
if args_4[0] in sys.argv: filename = sys.argv[sys.argv.index(args_4[0]) + 1]
if args_4[1] in sys.argv: filename = sys.argv[sys.argv.index(args_4[1]) + 1]
assert subscription_key is not None, "subscription_key is not set"
assert endpoint is not None, "endpoint is not set"
computervision_client = ComputerVisionClient(endpoint, CognitiveServicesCredentials(subscription_key))
if read_image_url is not None:
description_results = computervision_client.describe_image(read_image_url)
else:
description_results = computervision_client.describe_image_in_stream(open(os.path.join(READ_PATH, filename), "rb"))
breaker()
print("Description of Image \n")
if len(description_results.captions) == 0:
print("No description detected !!!")
else:
for caption in description_results.captions:
print(f"'{caption.text.title()}' with confidence {caption.confidence * 100:.2f}")
breaker()
if __name__ == "__main__":
sys.exit(main() or 0)
| true | true |
1c3e0925cbef89bed35f6999c5f306e7ff61d067 | 22,630 | py | Python | pyrs/proto/core_pb2.py | drbob/pyrs | 9adc07ff3bda6c382e73c47cb61c5be2000715ba | [
"BSD-3-Clause"
] | 3 | 2016-10-08T10:41:25.000Z | 2021-11-30T00:12:28.000Z | pyrs/proto/core_pb2.py | drbob/pyrs | 9adc07ff3bda6c382e73c47cb61c5be2000715ba | [
"BSD-3-Clause"
] | 1 | 2016-02-07T21:19:33.000Z | 2016-02-07T21:27:29.000Z | pyrs/proto/core_pb2.py | drbob/pyrs | 9adc07ff3bda6c382e73c47cb61c5be2000715ba | [
"BSD-3-Clause"
] | null | null | null | # Generated by the protocol buffer compiler. DO NOT EDIT!
from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
DESCRIPTOR = descriptor.FileDescriptor(
name='core.proto',
package='rsctrl.core',
serialized_pb='\n\ncore.proto\x12\x0brsctrl.core\"\xb0\x01\n\x06Status\x12,\n\x04\x63ode\x18\x01 \x02(\x0e\x32\x1e.rsctrl.core.Status.StatusCode\x12\x0b\n\x03msg\x18\x02 \x01(\t\"k\n\nStatusCode\x12\n\n\x06\x46\x41ILED\x10\x00\x12\x0f\n\x0bNO_IMPL_YET\x10\x01\x12\x11\n\rINVALID_QUERY\x10\x02\x12\x13\n\x0fPARTIAL_SUCCESS\x10\x03\x12\x0b\n\x07SUCCESS\x10\x04\x12\x0b\n\x07READMSG\x10\x05\")\n\x06IpAddr\x12\x0e\n\x04\x61\x64\x64r\x18\x01 \x02(\t:\x00\x12\x0f\n\x04port\x18\x02 \x02(\r:\x01\x30\"\xc3\x01\n\x08Location\x12\x0e\n\x06ssl_id\x18\x01 \x02(\t\x12\x10\n\x08location\x18\x02 \x02(\t\x12&\n\tlocaladdr\x18\x03 \x02(\x0b\x32\x13.rsctrl.core.IpAddr\x12$\n\x07\x65xtaddr\x18\x04 \x02(\x0b\x32\x13.rsctrl.core.IpAddr\x12\r\n\x05state\x18\x05 \x02(\r\"8\n\nStateFlags\x12\n\n\x06ONLINE\x10\x01\x12\r\n\tCONNECTED\x10\x02\x12\x0f\n\x0bUNREACHABLE\x10\x04\"\xe0\x01\n\x06Person\x12\x0e\n\x06gpg_id\x18\x01 \x02(\t\x12\x0c\n\x04name\x18\x02 \x02(\t\x12\x32\n\x08relation\x18\x03 \x02(\x0e\x32 .rsctrl.core.Person.Relationship\x12(\n\tlocations\x18\x04 \x03(\x0b\x32\x15.rsctrl.core.Location\"Z\n\x0cRelationship\x12\n\n\x06\x46RIEND\x10\x01\x12\x1a\n\x16\x46RIEND_OF_MANY_FRIENDS\x10\x02\x12\x15\n\x11\x46RIEND_OF_FRIENDS\x10\x03\x12\x0b\n\x07UNKNOWN\x10\x04\"0\n\x04\x46ile\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x0c\n\x04hash\x18\x02 \x02(\t\x12\x0c\n\x04size\x18\x03 \x02(\x04\"f\n\x03\x44ir\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x0c\n\x04path\x18\x02 \x02(\t\x12!\n\x07subdirs\x18\x03 \x03(\x0b\x32\x10.rsctrl.core.Dir\x12 \n\x05\x66iles\x18\x04 \x03(\x0b\x32\x11.rsctrl.core.File\"\xfa\x01\n\x0cSystemStatus\x12\x35\n\nnet_status\x18\x01 \x02(\x0e\x32!.rsctrl.core.SystemStatus.NetCode\x12\x0b\n\x03msg\x18\x02 \x01(\t\"\xa5\x01\n\x07NetCode\x12\x0f\n\x0b\x42\x41\x44_UNKNOWN\x10\x00\x12\x0f\n\x0b\x42\x41\x44_OFFLINE\x10\x01\x12\x0e\n\nBAD_NATSYM\x10\x02\x12\x11\n\rBAD_NODHT_NAT\x10\x03\x12\x13\n\x0fWARNING_RESTART\x10\x04\x12\x12\n\x0eWARNING_NATTED\x10\x05\x12\x11\n\rWARNING_NODHT\x10\x06\x12\x08\n\x04GOOD\x10\x07\x12\x0f\n\x0b\x41\x44V_FORWARD\x10\x08\"3\n\tBandwidth\x12\n\n\x02up\x18\x01 \x02(\x02\x12\x0c\n\x04\x64own\x18\x02 \x02(\x02\x12\x0c\n\x04name\x18\x03 \x01(\t\":\n\x0c\x42\x61ndwidthSet\x12*\n\nbandwidths\x18\x01 \x03(\x0b\x32\x16.rsctrl.core.Bandwidth*\x17\n\x0b\x45xtensionId\x12\x08\n\x04\x43ORE\x10\x00*M\n\tPackageId\x12\t\n\x05PEERS\x10\x01\x12\n\n\x06SYSTEM\x10\x02\x12\x08\n\x04\x43HAT\x10\x03\x12\n\n\x06SEARCH\x10\x04\x12\t\n\x05\x46ILES\x10\x05\x12\x08\n\x03GXS\x10\xe8\x07')
_EXTENSIONID = descriptor.EnumDescriptor(
name='ExtensionId',
full_name='rsctrl.core.ExtensionId',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='CORE', index=0, number=0,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=1194,
serialized_end=1217,
)
_PACKAGEID = descriptor.EnumDescriptor(
name='PackageId',
full_name='rsctrl.core.PackageId',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='PEERS', index=0, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='SYSTEM', index=1, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='CHAT', index=2, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='SEARCH', index=3, number=4,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='FILES', index=4, number=5,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='GXS', index=5, number=1000,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=1219,
serialized_end=1296,
)
CORE = 0
PEERS = 1
SYSTEM = 2
CHAT = 3
SEARCH = 4
FILES = 5
GXS = 1000
_STATUS_STATUSCODE = descriptor.EnumDescriptor(
name='StatusCode',
full_name='rsctrl.core.Status.StatusCode',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='FAILED', index=0, number=0,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='NO_IMPL_YET', index=1, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='INVALID_QUERY', index=2, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='PARTIAL_SUCCESS', index=3, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='SUCCESS', index=4, number=4,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='READMSG', index=5, number=5,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=97,
serialized_end=204,
)
_LOCATION_STATEFLAGS = descriptor.EnumDescriptor(
name='StateFlags',
full_name='rsctrl.core.Location.StateFlags',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='ONLINE', index=0, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='CONNECTED', index=1, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='UNREACHABLE', index=2, number=4,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=389,
serialized_end=445,
)
_PERSON_RELATIONSHIP = descriptor.EnumDescriptor(
name='Relationship',
full_name='rsctrl.core.Person.Relationship',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='FRIEND', index=0, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='FRIEND_OF_MANY_FRIENDS', index=1, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='FRIEND_OF_FRIENDS', index=2, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='UNKNOWN', index=3, number=4,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=582,
serialized_end=672,
)
_SYSTEMSTATUS_NETCODE = descriptor.EnumDescriptor(
name='NetCode',
full_name='rsctrl.core.SystemStatus.NetCode',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='BAD_UNKNOWN', index=0, number=0,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='BAD_OFFLINE', index=1, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='BAD_NATSYM', index=2, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='BAD_NODHT_NAT', index=3, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='WARNING_RESTART', index=4, number=4,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='WARNING_NATTED', index=5, number=5,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='WARNING_NODHT', index=6, number=6,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='GOOD', index=7, number=7,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='ADV_FORWARD', index=8, number=8,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=914,
serialized_end=1079,
)
_STATUS = descriptor.Descriptor(
name='Status',
full_name='rsctrl.core.Status',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='code', full_name='rsctrl.core.Status.code', index=0,
number=1, type=14, cpp_type=8, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='msg', full_name='rsctrl.core.Status.msg', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_STATUS_STATUSCODE,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=28,
serialized_end=204,
)
_IPADDR = descriptor.Descriptor(
name='IpAddr',
full_name='rsctrl.core.IpAddr',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='addr', full_name='rsctrl.core.IpAddr.addr', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=True, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='port', full_name='rsctrl.core.IpAddr.port', index=1,
number=2, type=13, cpp_type=3, label=2,
has_default_value=True, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=206,
serialized_end=247,
)
_LOCATION = descriptor.Descriptor(
name='Location',
full_name='rsctrl.core.Location',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='ssl_id', full_name='rsctrl.core.Location.ssl_id', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='location', full_name='rsctrl.core.Location.location', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='localaddr', full_name='rsctrl.core.Location.localaddr', index=2,
number=3, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='extaddr', full_name='rsctrl.core.Location.extaddr', index=3,
number=4, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='state', full_name='rsctrl.core.Location.state', index=4,
number=5, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_LOCATION_STATEFLAGS,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=250,
serialized_end=445,
)
_PERSON = descriptor.Descriptor(
name='Person',
full_name='rsctrl.core.Person',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='gpg_id', full_name='rsctrl.core.Person.gpg_id', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.Person.name', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='relation', full_name='rsctrl.core.Person.relation', index=2,
number=3, type=14, cpp_type=8, label=2,
has_default_value=False, default_value=1,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='locations', full_name='rsctrl.core.Person.locations', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_PERSON_RELATIONSHIP,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=448,
serialized_end=672,
)
_FILE = descriptor.Descriptor(
name='File',
full_name='rsctrl.core.File',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.File.name', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='hash', full_name='rsctrl.core.File.hash', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='size', full_name='rsctrl.core.File.size', index=2,
number=3, type=4, cpp_type=4, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=674,
serialized_end=722,
)
_DIR = descriptor.Descriptor(
name='Dir',
full_name='rsctrl.core.Dir',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.Dir.name', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='path', full_name='rsctrl.core.Dir.path', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='subdirs', full_name='rsctrl.core.Dir.subdirs', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='files', full_name='rsctrl.core.Dir.files', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=724,
serialized_end=826,
)
_SYSTEMSTATUS = descriptor.Descriptor(
name='SystemStatus',
full_name='rsctrl.core.SystemStatus',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='net_status', full_name='rsctrl.core.SystemStatus.net_status', index=0,
number=1, type=14, cpp_type=8, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='msg', full_name='rsctrl.core.SystemStatus.msg', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_SYSTEMSTATUS_NETCODE,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=829,
serialized_end=1079,
)
_BANDWIDTH = descriptor.Descriptor(
name='Bandwidth',
full_name='rsctrl.core.Bandwidth',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='up', full_name='rsctrl.core.Bandwidth.up', index=0,
number=1, type=2, cpp_type=6, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='down', full_name='rsctrl.core.Bandwidth.down', index=1,
number=2, type=2, cpp_type=6, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.Bandwidth.name', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=1081,
serialized_end=1132,
)
_BANDWIDTHSET = descriptor.Descriptor(
name='BandwidthSet',
full_name='rsctrl.core.BandwidthSet',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='bandwidths', full_name='rsctrl.core.BandwidthSet.bandwidths', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=1134,
serialized_end=1192,
)
_STATUS.fields_by_name['code'].enum_type = _STATUS_STATUSCODE
_STATUS_STATUSCODE.containing_type = _STATUS;
_LOCATION.fields_by_name['localaddr'].message_type = _IPADDR
_LOCATION.fields_by_name['extaddr'].message_type = _IPADDR
_LOCATION_STATEFLAGS.containing_type = _LOCATION;
_PERSON.fields_by_name['relation'].enum_type = _PERSON_RELATIONSHIP
_PERSON.fields_by_name['locations'].message_type = _LOCATION
_PERSON_RELATIONSHIP.containing_type = _PERSON;
_DIR.fields_by_name['subdirs'].message_type = _DIR
_DIR.fields_by_name['files'].message_type = _FILE
_SYSTEMSTATUS.fields_by_name['net_status'].enum_type = _SYSTEMSTATUS_NETCODE
_SYSTEMSTATUS_NETCODE.containing_type = _SYSTEMSTATUS;
_BANDWIDTHSET.fields_by_name['bandwidths'].message_type = _BANDWIDTH
DESCRIPTOR.message_types_by_name['Status'] = _STATUS
DESCRIPTOR.message_types_by_name['IpAddr'] = _IPADDR
DESCRIPTOR.message_types_by_name['Location'] = _LOCATION
DESCRIPTOR.message_types_by_name['Person'] = _PERSON
DESCRIPTOR.message_types_by_name['File'] = _FILE
DESCRIPTOR.message_types_by_name['Dir'] = _DIR
DESCRIPTOR.message_types_by_name['SystemStatus'] = _SYSTEMSTATUS
DESCRIPTOR.message_types_by_name['Bandwidth'] = _BANDWIDTH
DESCRIPTOR.message_types_by_name['BandwidthSet'] = _BANDWIDTHSET
class Status(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _STATUS
# @@protoc_insertion_point(class_scope:rsctrl.core.Status)
class IpAddr(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _IPADDR
# @@protoc_insertion_point(class_scope:rsctrl.core.IpAddr)
class Location(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _LOCATION
# @@protoc_insertion_point(class_scope:rsctrl.core.Location)
class Person(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _PERSON
# @@protoc_insertion_point(class_scope:rsctrl.core.Person)
class File(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _FILE
# @@protoc_insertion_point(class_scope:rsctrl.core.File)
class Dir(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _DIR
# @@protoc_insertion_point(class_scope:rsctrl.core.Dir)
class SystemStatus(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _SYSTEMSTATUS
# @@protoc_insertion_point(class_scope:rsctrl.core.SystemStatus)
class Bandwidth(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _BANDWIDTH
# @@protoc_insertion_point(class_scope:rsctrl.core.Bandwidth)
class BandwidthSet(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _BANDWIDTHSET
# @@protoc_insertion_point(class_scope:rsctrl.core.BandwidthSet)
# @@protoc_insertion_point(module_scope)
| 33.575668 | 2,514 | 0.715422 |
from google.protobuf import descriptor
from google.protobuf import message
from google.protobuf import reflection
from google.protobuf import descriptor_pb2
DESCRIPTOR = descriptor.FileDescriptor(
name='core.proto',
package='rsctrl.core',
serialized_pb='\n\ncore.proto\x12\x0brsctrl.core\"\xb0\x01\n\x06Status\x12,\n\x04\x63ode\x18\x01 \x02(\x0e\x32\x1e.rsctrl.core.Status.StatusCode\x12\x0b\n\x03msg\x18\x02 \x01(\t\"k\n\nStatusCode\x12\n\n\x06\x46\x41ILED\x10\x00\x12\x0f\n\x0bNO_IMPL_YET\x10\x01\x12\x11\n\rINVALID_QUERY\x10\x02\x12\x13\n\x0fPARTIAL_SUCCESS\x10\x03\x12\x0b\n\x07SUCCESS\x10\x04\x12\x0b\n\x07READMSG\x10\x05\")\n\x06IpAddr\x12\x0e\n\x04\x61\x64\x64r\x18\x01 \x02(\t:\x00\x12\x0f\n\x04port\x18\x02 \x02(\r:\x01\x30\"\xc3\x01\n\x08Location\x12\x0e\n\x06ssl_id\x18\x01 \x02(\t\x12\x10\n\x08location\x18\x02 \x02(\t\x12&\n\tlocaladdr\x18\x03 \x02(\x0b\x32\x13.rsctrl.core.IpAddr\x12$\n\x07\x65xtaddr\x18\x04 \x02(\x0b\x32\x13.rsctrl.core.IpAddr\x12\r\n\x05state\x18\x05 \x02(\r\"8\n\nStateFlags\x12\n\n\x06ONLINE\x10\x01\x12\r\n\tCONNECTED\x10\x02\x12\x0f\n\x0bUNREACHABLE\x10\x04\"\xe0\x01\n\x06Person\x12\x0e\n\x06gpg_id\x18\x01 \x02(\t\x12\x0c\n\x04name\x18\x02 \x02(\t\x12\x32\n\x08relation\x18\x03 \x02(\x0e\x32 .rsctrl.core.Person.Relationship\x12(\n\tlocations\x18\x04 \x03(\x0b\x32\x15.rsctrl.core.Location\"Z\n\x0cRelationship\x12\n\n\x06\x46RIEND\x10\x01\x12\x1a\n\x16\x46RIEND_OF_MANY_FRIENDS\x10\x02\x12\x15\n\x11\x46RIEND_OF_FRIENDS\x10\x03\x12\x0b\n\x07UNKNOWN\x10\x04\"0\n\x04\x46ile\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x0c\n\x04hash\x18\x02 \x02(\t\x12\x0c\n\x04size\x18\x03 \x02(\x04\"f\n\x03\x44ir\x12\x0c\n\x04name\x18\x01 \x02(\t\x12\x0c\n\x04path\x18\x02 \x02(\t\x12!\n\x07subdirs\x18\x03 \x03(\x0b\x32\x10.rsctrl.core.Dir\x12 \n\x05\x66iles\x18\x04 \x03(\x0b\x32\x11.rsctrl.core.File\"\xfa\x01\n\x0cSystemStatus\x12\x35\n\nnet_status\x18\x01 \x02(\x0e\x32!.rsctrl.core.SystemStatus.NetCode\x12\x0b\n\x03msg\x18\x02 \x01(\t\"\xa5\x01\n\x07NetCode\x12\x0f\n\x0b\x42\x41\x44_UNKNOWN\x10\x00\x12\x0f\n\x0b\x42\x41\x44_OFFLINE\x10\x01\x12\x0e\n\nBAD_NATSYM\x10\x02\x12\x11\n\rBAD_NODHT_NAT\x10\x03\x12\x13\n\x0fWARNING_RESTART\x10\x04\x12\x12\n\x0eWARNING_NATTED\x10\x05\x12\x11\n\rWARNING_NODHT\x10\x06\x12\x08\n\x04GOOD\x10\x07\x12\x0f\n\x0b\x41\x44V_FORWARD\x10\x08\"3\n\tBandwidth\x12\n\n\x02up\x18\x01 \x02(\x02\x12\x0c\n\x04\x64own\x18\x02 \x02(\x02\x12\x0c\n\x04name\x18\x03 \x01(\t\":\n\x0c\x42\x61ndwidthSet\x12*\n\nbandwidths\x18\x01 \x03(\x0b\x32\x16.rsctrl.core.Bandwidth*\x17\n\x0b\x45xtensionId\x12\x08\n\x04\x43ORE\x10\x00*M\n\tPackageId\x12\t\n\x05PEERS\x10\x01\x12\n\n\x06SYSTEM\x10\x02\x12\x08\n\x04\x43HAT\x10\x03\x12\n\n\x06SEARCH\x10\x04\x12\t\n\x05\x46ILES\x10\x05\x12\x08\n\x03GXS\x10\xe8\x07')
_EXTENSIONID = descriptor.EnumDescriptor(
name='ExtensionId',
full_name='rsctrl.core.ExtensionId',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='CORE', index=0, number=0,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=1194,
serialized_end=1217,
)
_PACKAGEID = descriptor.EnumDescriptor(
name='PackageId',
full_name='rsctrl.core.PackageId',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='PEERS', index=0, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='SYSTEM', index=1, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='CHAT', index=2, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='SEARCH', index=3, number=4,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='FILES', index=4, number=5,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='GXS', index=5, number=1000,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=1219,
serialized_end=1296,
)
CORE = 0
PEERS = 1
SYSTEM = 2
CHAT = 3
SEARCH = 4
FILES = 5
GXS = 1000
_STATUS_STATUSCODE = descriptor.EnumDescriptor(
name='StatusCode',
full_name='rsctrl.core.Status.StatusCode',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='FAILED', index=0, number=0,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='NO_IMPL_YET', index=1, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='INVALID_QUERY', index=2, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='PARTIAL_SUCCESS', index=3, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='SUCCESS', index=4, number=4,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='READMSG', index=5, number=5,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=97,
serialized_end=204,
)
_LOCATION_STATEFLAGS = descriptor.EnumDescriptor(
name='StateFlags',
full_name='rsctrl.core.Location.StateFlags',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='ONLINE', index=0, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='CONNECTED', index=1, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='UNREACHABLE', index=2, number=4,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=389,
serialized_end=445,
)
_PERSON_RELATIONSHIP = descriptor.EnumDescriptor(
name='Relationship',
full_name='rsctrl.core.Person.Relationship',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='FRIEND', index=0, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='FRIEND_OF_MANY_FRIENDS', index=1, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='FRIEND_OF_FRIENDS', index=2, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='UNKNOWN', index=3, number=4,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=582,
serialized_end=672,
)
_SYSTEMSTATUS_NETCODE = descriptor.EnumDescriptor(
name='NetCode',
full_name='rsctrl.core.SystemStatus.NetCode',
filename=None,
file=DESCRIPTOR,
values=[
descriptor.EnumValueDescriptor(
name='BAD_UNKNOWN', index=0, number=0,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='BAD_OFFLINE', index=1, number=1,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='BAD_NATSYM', index=2, number=2,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='BAD_NODHT_NAT', index=3, number=3,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='WARNING_RESTART', index=4, number=4,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='WARNING_NATTED', index=5, number=5,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='WARNING_NODHT', index=6, number=6,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='GOOD', index=7, number=7,
options=None,
type=None),
descriptor.EnumValueDescriptor(
name='ADV_FORWARD', index=8, number=8,
options=None,
type=None),
],
containing_type=None,
options=None,
serialized_start=914,
serialized_end=1079,
)
_STATUS = descriptor.Descriptor(
name='Status',
full_name='rsctrl.core.Status',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='code', full_name='rsctrl.core.Status.code', index=0,
number=1, type=14, cpp_type=8, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='msg', full_name='rsctrl.core.Status.msg', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_STATUS_STATUSCODE,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=28,
serialized_end=204,
)
_IPADDR = descriptor.Descriptor(
name='IpAddr',
full_name='rsctrl.core.IpAddr',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='addr', full_name='rsctrl.core.IpAddr.addr', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=True, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='port', full_name='rsctrl.core.IpAddr.port', index=1,
number=2, type=13, cpp_type=3, label=2,
has_default_value=True, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=206,
serialized_end=247,
)
_LOCATION = descriptor.Descriptor(
name='Location',
full_name='rsctrl.core.Location',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='ssl_id', full_name='rsctrl.core.Location.ssl_id', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='location', full_name='rsctrl.core.Location.location', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='localaddr', full_name='rsctrl.core.Location.localaddr', index=2,
number=3, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='extaddr', full_name='rsctrl.core.Location.extaddr', index=3,
number=4, type=11, cpp_type=10, label=2,
has_default_value=False, default_value=None,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='state', full_name='rsctrl.core.Location.state', index=4,
number=5, type=13, cpp_type=3, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_LOCATION_STATEFLAGS,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=250,
serialized_end=445,
)
_PERSON = descriptor.Descriptor(
name='Person',
full_name='rsctrl.core.Person',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='gpg_id', full_name='rsctrl.core.Person.gpg_id', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.Person.name', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='relation', full_name='rsctrl.core.Person.relation', index=2,
number=3, type=14, cpp_type=8, label=2,
has_default_value=False, default_value=1,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='locations', full_name='rsctrl.core.Person.locations', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_PERSON_RELATIONSHIP,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=448,
serialized_end=672,
)
_FILE = descriptor.Descriptor(
name='File',
full_name='rsctrl.core.File',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.File.name', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='hash', full_name='rsctrl.core.File.hash', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='size', full_name='rsctrl.core.File.size', index=2,
number=3, type=4, cpp_type=4, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=674,
serialized_end=722,
)
_DIR = descriptor.Descriptor(
name='Dir',
full_name='rsctrl.core.Dir',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.Dir.name', index=0,
number=1, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='path', full_name='rsctrl.core.Dir.path', index=1,
number=2, type=9, cpp_type=9, label=2,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='subdirs', full_name='rsctrl.core.Dir.subdirs', index=2,
number=3, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='files', full_name='rsctrl.core.Dir.files', index=3,
number=4, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=724,
serialized_end=826,
)
_SYSTEMSTATUS = descriptor.Descriptor(
name='SystemStatus',
full_name='rsctrl.core.SystemStatus',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='net_status', full_name='rsctrl.core.SystemStatus.net_status', index=0,
number=1, type=14, cpp_type=8, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='msg', full_name='rsctrl.core.SystemStatus.msg', index=1,
number=2, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
_SYSTEMSTATUS_NETCODE,
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=829,
serialized_end=1079,
)
_BANDWIDTH = descriptor.Descriptor(
name='Bandwidth',
full_name='rsctrl.core.Bandwidth',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='up', full_name='rsctrl.core.Bandwidth.up', index=0,
number=1, type=2, cpp_type=6, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='down', full_name='rsctrl.core.Bandwidth.down', index=1,
number=2, type=2, cpp_type=6, label=2,
has_default_value=False, default_value=0,
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
descriptor.FieldDescriptor(
name='name', full_name='rsctrl.core.Bandwidth.name', index=2,
number=3, type=9, cpp_type=9, label=1,
has_default_value=False, default_value=unicode("", "utf-8"),
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=1081,
serialized_end=1132,
)
_BANDWIDTHSET = descriptor.Descriptor(
name='BandwidthSet',
full_name='rsctrl.core.BandwidthSet',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
descriptor.FieldDescriptor(
name='bandwidths', full_name='rsctrl.core.BandwidthSet.bandwidths', index=0,
number=1, type=11, cpp_type=10, label=3,
has_default_value=False, default_value=[],
message_type=None, enum_type=None, containing_type=None,
is_extension=False, extension_scope=None,
options=None),
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
serialized_start=1134,
serialized_end=1192,
)
_STATUS.fields_by_name['code'].enum_type = _STATUS_STATUSCODE
_STATUS_STATUSCODE.containing_type = _STATUS;
_LOCATION.fields_by_name['localaddr'].message_type = _IPADDR
_LOCATION.fields_by_name['extaddr'].message_type = _IPADDR
_LOCATION_STATEFLAGS.containing_type = _LOCATION;
_PERSON.fields_by_name['relation'].enum_type = _PERSON_RELATIONSHIP
_PERSON.fields_by_name['locations'].message_type = _LOCATION
_PERSON_RELATIONSHIP.containing_type = _PERSON;
_DIR.fields_by_name['subdirs'].message_type = _DIR
_DIR.fields_by_name['files'].message_type = _FILE
_SYSTEMSTATUS.fields_by_name['net_status'].enum_type = _SYSTEMSTATUS_NETCODE
_SYSTEMSTATUS_NETCODE.containing_type = _SYSTEMSTATUS;
_BANDWIDTHSET.fields_by_name['bandwidths'].message_type = _BANDWIDTH
DESCRIPTOR.message_types_by_name['Status'] = _STATUS
DESCRIPTOR.message_types_by_name['IpAddr'] = _IPADDR
DESCRIPTOR.message_types_by_name['Location'] = _LOCATION
DESCRIPTOR.message_types_by_name['Person'] = _PERSON
DESCRIPTOR.message_types_by_name['File'] = _FILE
DESCRIPTOR.message_types_by_name['Dir'] = _DIR
DESCRIPTOR.message_types_by_name['SystemStatus'] = _SYSTEMSTATUS
DESCRIPTOR.message_types_by_name['Bandwidth'] = _BANDWIDTH
DESCRIPTOR.message_types_by_name['BandwidthSet'] = _BANDWIDTHSET
class Status(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _STATUS
# @@protoc_insertion_point(class_scope:rsctrl.core.Status)
class IpAddr(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _IPADDR
# @@protoc_insertion_point(class_scope:rsctrl.core.IpAddr)
class Location(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _LOCATION
# @@protoc_insertion_point(class_scope:rsctrl.core.Location)
class Person(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _PERSON
# @@protoc_insertion_point(class_scope:rsctrl.core.Person)
class File(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _FILE
# @@protoc_insertion_point(class_scope:rsctrl.core.File)
class Dir(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _DIR
# @@protoc_insertion_point(class_scope:rsctrl.core.Dir)
class SystemStatus(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _SYSTEMSTATUS
# @@protoc_insertion_point(class_scope:rsctrl.core.SystemStatus)
class Bandwidth(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _BANDWIDTH
# @@protoc_insertion_point(class_scope:rsctrl.core.Bandwidth)
class BandwidthSet(message.Message):
__metaclass__ = reflection.GeneratedProtocolMessageType
DESCRIPTOR = _BANDWIDTHSET
# @@protoc_insertion_point(class_scope:rsctrl.core.BandwidthSet)
# @@protoc_insertion_point(module_scope)
| true | true |
1c3e09b70eb2285e5866f9dbf407ea948980790e | 29,195 | py | Python | kivy/uix/tabbedpanel.py | Galland/kivy | 95a6bf279883d706f645e4629c16d5ee1038f0ec | [
"MIT"
] | 6 | 2020-04-10T14:36:25.000Z | 2021-04-25T13:11:32.000Z | kivy/uix/tabbedpanel.py | Galland/kivy | 95a6bf279883d706f645e4629c16d5ee1038f0ec | [
"MIT"
] | 6 | 2020-01-31T18:04:48.000Z | 2021-06-05T10:53:55.000Z | kivy/uix/tabbedpanel.py | Galland/kivy | 95a6bf279883d706f645e4629c16d5ee1038f0ec | [
"MIT"
] | 1 | 2021-04-08T19:51:07.000Z | 2021-04-08T19:51:07.000Z | '''
TabbedPanel
===========
.. image:: images/tabbed_panel.jpg
:align: right
.. versionadded:: 1.3.0
The `TabbedPanel` widget manages different widgets in tabs, with a header area
for the actual tab buttons and a content area for showing the current tab
content.
The :class:`TabbedPanel` provides one default tab.
Simple example
--------------
.. include:: ../../examples/widgets/tabbedpanel.py
:literal:
.. note::
A new class :class:`TabbedPanelItem` has been introduced in 1.5.0 for
convenience. So now one can simply add a :class:`TabbedPanelItem` to a
:class:`TabbedPanel` and `content` to the :class:`TabbedPanelItem`
as in the example provided above.
Customize the Tabbed Panel
--------------------------
You can choose the position in which the tabs are displayed::
tab_pos = 'top_mid'
An individual tab is called a TabbedPanelHeader. It is a special button
containing a `content` property. You add the TabbedPanelHeader first, and set
its `content` property separately::
tp = TabbedPanel()
th = TabbedPanelHeader(text='Tab2')
tp.add_widget(th)
An individual tab, represented by a TabbedPanelHeader, needs its content set.
This content can be any widget. It could be a layout with a deep
hierarchy of widgets, or it could be an individual widget, such as a label or a
button::
th.content = your_content_instance
There is one "shared" main content area active at any given time, for all
the tabs. Your app is responsible for adding the content of individual tabs
and for managing them, but it's not responsible for content switching. The
tabbed panel handles switching of the main content object as per user action.
There is a default tab added when the tabbed panel is instantiated.
Tabs that you add individually as above, are added in addition to the default
tab. Thus, depending on your needs and design, you will want to customize the
default tab::
tp.default_tab_text = 'Something Specific To Your Use'
The default tab machinery requires special consideration and management.
Accordingly, an `on_default_tab` event is provided for associating a callback::
tp.bind(default_tab = my_default_tab_callback)
It's important to note that by default, :attr:`default_tab_cls` is of type
:class:`TabbedPanelHeader` and thus has the same properties as other tabs.
Since 1.5.0, it is now possible to disable the creation of the
:attr:`default_tab` by setting :attr:`do_default_tab` to False.
Tabs and content can be removed in several ways::
tp.remove_widget(widget/tabbed_panel_header)
or
tp.clear_widgets() # to clear all the widgets in the content area
or
tp.clear_tabs() # to remove the TabbedPanelHeaders
To access the children of the tabbed panel, use content.children::
tp.content.children
To access the list of tabs::
tp.tab_list
To change the appearance of the main tabbed panel content::
background_color = (1, 0, 0, .5) #50% translucent red
border = [0, 0, 0, 0]
background_image = 'path/to/background/image'
To change the background of a individual tab, use these two properties::
tab_header_instance.background_normal = 'path/to/tab_head/img'
tab_header_instance.background_down = 'path/to/tab_head/img_pressed'
A TabbedPanelStrip contains the individual tab headers. To change the
appearance of this tab strip, override the canvas of TabbedPanelStrip.
For example, in the kv language:
.. code-block:: kv
<TabbedPanelStrip>
canvas:
Color:
rgba: (0, 1, 0, 1) # green
Rectangle:
size: self.size
pos: self.pos
By default the tabbed panel strip takes its background image and color from the
tabbed panel's background_image and background_color.
'''
__all__ = ('StripLayout', 'TabbedPanel', 'TabbedPanelContent',
'TabbedPanelHeader', 'TabbedPanelItem', 'TabbedPanelStrip',
'TabbedPanelException')
from functools import partial
from kivy.clock import Clock
from kivy.compat import string_types
from kivy.factory import Factory
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.logger import Logger
from kivy.metrics import dp
from kivy.properties import ObjectProperty, StringProperty, OptionProperty, \
ListProperty, NumericProperty, AliasProperty, BooleanProperty
class TabbedPanelException(Exception):
'''The TabbedPanelException class.
'''
pass
class TabbedPanelHeader(ToggleButton):
'''A Base for implementing a Tabbed Panel Head. A button intended to be
used as a Heading/Tab for a TabbedPanel widget.
You can use this TabbedPanelHeader widget to add a new tab to a
TabbedPanel.
'''
content = ObjectProperty(None, allownone=True)
'''Content to be loaded when this tab header is selected.
:attr:`content` is an :class:`~kivy.properties.ObjectProperty` and defaults
to None.
'''
# only allow selecting the tab if not already selected
def on_touch_down(self, touch):
if self.state == 'down':
# dispatch to children, not to self
for child in self.children:
child.dispatch('on_touch_down', touch)
return
else:
super(TabbedPanelHeader, self).on_touch_down(touch)
def on_release(self, *largs):
# Tabbed panel header is a child of tab_strib which has a
# `tabbed_panel` property
if self.parent:
self.parent.tabbed_panel.switch_to(self)
else:
# tab removed before we could switch to it. Switch back to
# previous tab
self.panel.switch_to(self.panel.current_tab)
class TabbedPanelItem(TabbedPanelHeader):
'''This is a convenience class that provides a header of type
TabbedPanelHeader and links it with the content automatically. Thus
facilitating you to simply do the following in kv language:
.. code-block:: kv
<TabbedPanel>:
# ...other settings
TabbedPanelItem:
BoxLayout:
Label:
text: 'Second tab content area'
Button:
text: 'Button that does nothing'
.. versionadded:: 1.5.0
'''
def add_widget(self, widget, index=0):
self.content = widget
if not self.parent:
return
panel = self.parent.tabbed_panel
if panel.current_tab == self:
panel.switch_to(self)
def remove_widget(self, widget):
self.content = None
if not self.parent:
return
panel = self.parent.tabbed_panel
if panel.current_tab == self:
panel.remove_widget(widget)
class TabbedPanelStrip(GridLayout):
'''A strip intended to be used as background for Heading/Tab.
This does not cover the blank areas in case the tabs don't cover
the entire width/height of the TabbedPanel(use :class:`StripLayout`
for that).
'''
tabbed_panel = ObjectProperty(None)
'''Link to the panel that the tab strip is a part of.
:attr:`tabbed_panel` is an :class:`~kivy.properties.ObjectProperty` and
defaults to None .
'''
class StripLayout(GridLayout):
''' The main layout that is used to house the entire tabbedpanel strip
including the blank areas in case the tabs don't cover the entire
width/height.
.. versionadded:: 1.8.0
'''
border = ListProperty([4, 4, 4, 4])
'''Border property for the :attr:`background_image`.
:attr:`border` is a :class:`~kivy.properties.ListProperty` and defaults
to [4, 4, 4, 4]
'''
background_image = StringProperty(
'atlas://data/images/defaulttheme/action_view')
'''Background image to be used for the Strip layout of the TabbedPanel.
:attr:`background_image` is a :class:`~kivy.properties.StringProperty` and
defaults to a transparent image.
'''
class TabbedPanelContent(FloatLayout):
'''The TabbedPanelContent class.
'''
pass
class TabbedPanel(GridLayout):
'''The TabbedPanel class. See module documentation for more information.
'''
background_color = ListProperty([1, 1, 1, 1])
'''Background color, in the format (r, g, b, a).
:attr:`background_color` is a :class:`~kivy.properties.ListProperty` and
defaults to [1, 1, 1, 1].
'''
border = ListProperty([16, 16, 16, 16])
'''Border used for :class:`~kivy.graphics.vertex_instructions.BorderImage`
graphics instruction, used itself for :attr:`background_image`.
Can be changed for a custom background.
It must be a list of four values: (bottom, right, top, left). Read the
BorderImage instructions for more information.
:attr:`border` is a :class:`~kivy.properties.ListProperty` and
defaults to (16, 16, 16, 16)
'''
background_image = StringProperty('atlas://data/images/defaulttheme/tab')
'''Background image of the main shared content object.
:attr:`background_image` is a :class:`~kivy.properties.StringProperty` and
defaults to 'atlas://data/images/defaulttheme/tab'.
'''
background_disabled_image = StringProperty(
'atlas://data/images/defaulttheme/tab_disabled')
'''Background image of the main shared content object when disabled.
.. versionadded:: 1.8.0
:attr:`background_disabled_image` is a
:class:`~kivy.properties.StringProperty` and defaults to
'atlas://data/images/defaulttheme/tab'.
'''
strip_image = StringProperty(
'atlas://data/images/defaulttheme/action_view')
'''Background image of the tabbed strip.
.. versionadded:: 1.8.0
:attr:`strip_image` is a :class:`~kivy.properties.StringProperty`
and defaults to a empty image.
'''
strip_border = ListProperty([4, 4, 4, 4])
'''Border to be used on :attr:`strip_image`.
.. versionadded:: 1.8.0
:attr:`strip_border` is a :class:`~kivy.properties.ListProperty` and
defaults to [4, 4, 4, 4].
'''
_current_tab = ObjectProperty(None)
def get_current_tab(self):
return self._current_tab
current_tab = AliasProperty(get_current_tab, None, bind=('_current_tab', ))
'''Links to the currently selected or active tab.
.. versionadded:: 1.4.0
:attr:`current_tab` is an :class:`~kivy.AliasProperty`, read-only.
'''
tab_pos = OptionProperty(
'top_left',
options=('left_top', 'left_mid', 'left_bottom', 'top_left',
'top_mid', 'top_right', 'right_top', 'right_mid',
'right_bottom', 'bottom_left', 'bottom_mid', 'bottom_right'))
'''Specifies the position of the tabs relative to the content.
Can be one of: `left_top`, `left_mid`, `left_bottom`, `top_left`,
`top_mid`, `top_right`, `right_top`, `right_mid`, `right_bottom`,
`bottom_left`, `bottom_mid`, `bottom_right`.
:attr:`tab_pos` is an :class:`~kivy.properties.OptionProperty` and
defaults to 'top_left'.
'''
tab_height = NumericProperty('40dp')
'''Specifies the height of the tab header.
:attr:`tab_height` is a :class:`~kivy.properties.NumericProperty` and
defaults to 40.
'''
tab_width = NumericProperty('100dp', allownone=True)
'''Specifies the width of the tab header.
:attr:`tab_width` is a :class:`~kivy.properties.NumericProperty` and
defaults to 100.
'''
do_default_tab = BooleanProperty(True)
'''Specifies whether a default_tab head is provided.
.. versionadded:: 1.5.0
:attr:`do_default_tab` is a :class:`~kivy.properties.BooleanProperty` and
defaults to 'True'.
'''
default_tab_text = StringProperty('Default tab')
'''Specifies the text displayed on the default tab header.
:attr:`default_tab_text` is a :class:`~kivy.properties.StringProperty` and
defaults to 'default tab'.
'''
default_tab_cls = ObjectProperty(TabbedPanelHeader)
'''Specifies the class to use for the styling of the default tab.
.. versionadded:: 1.4.0
.. warning::
`default_tab_cls` should be subclassed from `TabbedPanelHeader`
:attr:`default_tab_cls` is an :class:`~kivy.properties.ObjectProperty`
and defaults to `TabbedPanelHeader`. If you set a string, the
:class:`~kivy.factory.Factory` will be used to resolve the class.
.. versionchanged:: 1.8.0
The :class:`~kivy.factory.Factory` will resolve the class if a string
is set.
'''
def get_tab_list(self):
if self._tab_strip:
return self._tab_strip.children
return 1.
tab_list = AliasProperty(get_tab_list, None)
'''List of all the tab headers.
:attr:`tab_list` is an :class:`~kivy.properties.AliasProperty` and is
read-only.
'''
content = ObjectProperty(None)
'''This is the object holding (current_tab's content is added to this)
the content of the current tab. To Listen to the changes in the content
of the current tab, you should bind to current_tabs `content` property.
:attr:`content` is an :class:`~kivy.properties.ObjectProperty` and
defaults to 'None'.
'''
_default_tab = ObjectProperty(None, allow_none=True)
def get_def_tab(self):
return self._default_tab
def set_def_tab(self, new_tab):
if not issubclass(new_tab.__class__, TabbedPanelHeader):
raise TabbedPanelException('`default_tab_class` should be\
subclassed from `TabbedPanelHeader`')
if self._default_tab == new_tab:
return
oltab = self._default_tab
self._default_tab = new_tab
self.remove_widget(oltab)
self._original_tab = None
self.switch_to(new_tab)
new_tab.state = 'down'
default_tab = AliasProperty(get_def_tab, set_def_tab,
bind=('_default_tab', ))
'''Holds the default tab.
.. Note:: For convenience, the automatically provided default tab is
deleted when you change default_tab to something else.
As of 1.5.0, this behaviour has been extended to every
`default_tab` for consistency and not just the automatically
provided one.
:attr:`default_tab` is an :class:`~kivy.properties.AliasProperty`.
'''
def get_def_tab_content(self):
return self.default_tab.content
def set_def_tab_content(self, *l):
self.default_tab.content = l[0]
default_tab_content = AliasProperty(get_def_tab_content,
set_def_tab_content)
'''Holds the default tab content.
:attr:`default_tab_content` is an :class:`~kivy.properties.AliasProperty`.
'''
_update_top_ev = _update_tab_ev = _update_tabs_ev = None
def __init__(self, **kwargs):
# these variables need to be initialized before the kv lang is
# processed setup the base layout for the tabbed panel
self._childrens = []
self._tab_layout = StripLayout(rows=1)
self.rows = 1
self._tab_strip = TabbedPanelStrip(
tabbed_panel=self,
rows=1, size_hint=(None, None),
height=self.tab_height, width=self.tab_width)
self._partial_update_scrollview = None
self.content = TabbedPanelContent()
self._current_tab = self._original_tab \
= self._default_tab = TabbedPanelHeader()
super(TabbedPanel, self).__init__(**kwargs)
self.fbind('size', self._reposition_tabs)
if not self.do_default_tab:
Clock.schedule_once(self._switch_to_first_tab)
return
self._setup_default_tab()
self.switch_to(self.default_tab)
def switch_to(self, header, do_scroll=False):
'''Switch to a specific panel header.
.. versionchanged:: 1.10.0
If used with `do_scroll=True`, it scrolls
to the header's tab too.
'''
header_content = header.content
self._current_tab.state = 'normal'
header.state = 'down'
self._current_tab = header
self.clear_widgets()
if header_content is None:
return
# if content has a previous parent remove it from that parent
parent = header_content.parent
if parent:
parent.remove_widget(header_content)
self.add_widget(header_content)
if do_scroll:
tabs = self._tab_strip
tabs.parent.scroll_to(header)
def clear_tabs(self, *l):
self_tabs = self._tab_strip
self_tabs.clear_widgets()
if self.do_default_tab:
self_default_tab = self._default_tab
self_tabs.add_widget(self_default_tab)
self_tabs.width = self_default_tab.width
self._reposition_tabs()
def add_widget(self, widget, index=0):
content = self.content
if content is None:
return
parent = widget.parent
if parent:
parent.remove_widget(widget)
if widget in (content, self._tab_layout):
super(TabbedPanel, self).add_widget(widget, index)
elif isinstance(widget, TabbedPanelHeader):
self_tabs = self._tab_strip
self_tabs.add_widget(widget, index)
widget.group = '__tab%r__' % self_tabs.uid
self.on_tab_width()
else:
widget.pos_hint = {'x': 0, 'top': 1}
self._childrens.append(widget)
content.disabled = self.current_tab.disabled
content.add_widget(widget, index)
def remove_widget(self, widget):
content = self.content
if content is None:
return
if widget in (content, self._tab_layout):
super(TabbedPanel, self).remove_widget(widget)
elif isinstance(widget, TabbedPanelHeader):
if not (self.do_default_tab and widget is self._default_tab):
self_tabs = self._tab_strip
self_tabs.width -= widget.width
self_tabs.remove_widget(widget)
if widget.state == 'down' and self.do_default_tab:
self._default_tab.on_release()
self._reposition_tabs()
else:
Logger.info('TabbedPanel: default tab! can\'t be removed.\n' +
'Change `default_tab` to a different tab.')
else:
if widget in self._childrens:
self._childrens.remove(widget)
if widget in content.children:
content.remove_widget(widget)
def clear_widgets(self, **kwargs):
content = self.content
if content is None:
return
if kwargs.get('do_super', False):
super(TabbedPanel, self).clear_widgets()
else:
content.clear_widgets()
def on_strip_image(self, instance, value):
if not self._tab_layout:
return
self._tab_layout.background_image = value
def on_strip_border(self, instance, value):
if not self._tab_layout:
return
self._tab_layout.border = value
def on_do_default_tab(self, instance, value):
if not value:
dft = self.default_tab
if dft in self.tab_list:
self.remove_widget(dft)
self._switch_to_first_tab()
self._default_tab = self._current_tab
else:
self._current_tab.state = 'normal'
self._setup_default_tab()
def on_default_tab_text(self, *args):
self._default_tab.text = self.default_tab_text
def on_tab_width(self, *l):
ev = self._update_tab_ev
if ev is None:
ev = self._update_tab_ev = Clock.create_trigger(
self._update_tab_width, 0)
ev()
def on_tab_height(self, *l):
self._tab_layout.height = self._tab_strip.height = self.tab_height
self._reposition_tabs()
def on_tab_pos(self, *l):
# ensure canvas
self._reposition_tabs()
def _setup_default_tab(self):
if self._default_tab in self.tab_list:
return
content = self._default_tab.content
_tabs = self._tab_strip
cls = self.default_tab_cls
if isinstance(cls, string_types):
cls = Factory.get(cls)
if not issubclass(cls, TabbedPanelHeader):
raise TabbedPanelException('`default_tab_class` should be\
subclassed from `TabbedPanelHeader`')
# no need to instantiate if class is TabbedPanelHeader
if cls != TabbedPanelHeader:
self._current_tab = self._original_tab = self._default_tab = cls()
default_tab = self.default_tab
if self._original_tab == self.default_tab:
default_tab.text = self.default_tab_text
default_tab.height = self.tab_height
default_tab.group = '__tab%r__' % _tabs.uid
default_tab.state = 'down'
default_tab.width = self.tab_width if self.tab_width else 100
default_tab.content = content
tl = self.tab_list
if default_tab not in tl:
_tabs.add_widget(default_tab, len(tl))
if default_tab.content:
self.clear_widgets()
self.add_widget(self.default_tab.content)
else:
Clock.schedule_once(self._load_default_tab_content)
self._current_tab = default_tab
def _switch_to_first_tab(self, *l):
ltl = len(self.tab_list) - 1
if ltl > -1:
self._current_tab = dt = self._original_tab \
= self.tab_list[ltl]
self.switch_to(dt)
def _load_default_tab_content(self, dt):
if self.default_tab:
self.switch_to(self.default_tab)
def _reposition_tabs(self, *l):
ev = self._update_tabs_ev
if ev is None:
ev = self._update_tabs_ev = Clock.create_trigger(
self._update_tabs, 0)
ev()
def _update_tabs(self, *l):
self_content = self.content
if not self_content:
return
# cache variables for faster access
tab_pos = self.tab_pos
tab_layout = self._tab_layout
tab_layout.clear_widgets()
scrl_v = ScrollView(size_hint=(None, 1))
tabs = self._tab_strip
parent = tabs.parent
if parent:
parent.remove_widget(tabs)
scrl_v.add_widget(tabs)
scrl_v.pos = (0, 0)
self_update_scrollview = self._update_scrollview
# update scrlv width when tab width changes depends on tab_pos
if self._partial_update_scrollview is not None:
tabs.unbind(width=self._partial_update_scrollview)
self._partial_update_scrollview = partial(
self_update_scrollview, scrl_v)
tabs.bind(width=self._partial_update_scrollview)
# remove all widgets from the tab_strip
self.clear_widgets(do_super=True)
tab_height = self.tab_height
widget_list = []
tab_list = []
pos_letter = tab_pos[0]
if pos_letter == 'b' or pos_letter == 't':
# bottom or top positions
# one col containing the tab_strip and the content
self.cols = 1
self.rows = 2
# tab_layout contains the scrollview containing tabs and two blank
# dummy widgets for spacing
tab_layout.rows = 1
tab_layout.cols = 3
tab_layout.size_hint = (1, None)
tab_layout.height = (tab_height + tab_layout.padding[1] +
tab_layout.padding[3] + dp(2))
self_update_scrollview(scrl_v)
if pos_letter == 'b':
# bottom
if tab_pos == 'bottom_mid':
tab_list = (Widget(), scrl_v, Widget())
widget_list = (self_content, tab_layout)
else:
if tab_pos == 'bottom_left':
tab_list = (scrl_v, Widget(), Widget())
elif tab_pos == 'bottom_right':
# add two dummy widgets
tab_list = (Widget(), Widget(), scrl_v)
widget_list = (self_content, tab_layout)
else:
# top
if tab_pos == 'top_mid':
tab_list = (Widget(), scrl_v, Widget())
elif tab_pos == 'top_left':
tab_list = (scrl_v, Widget(), Widget())
elif tab_pos == 'top_right':
tab_list = (Widget(), Widget(), scrl_v)
widget_list = (tab_layout, self_content)
elif pos_letter == 'l' or pos_letter == 'r':
# left ot right positions
# one row containing the tab_strip and the content
self.cols = 2
self.rows = 1
# tab_layout contains two blank dummy widgets for spacing
# "vertically" and the scatter containing scrollview
# containing tabs
tab_layout.rows = 3
tab_layout.cols = 1
tab_layout.size_hint = (None, 1)
tab_layout.width = tab_height
scrl_v.height = tab_height
self_update_scrollview(scrl_v)
# rotate the scatter for vertical positions
rotation = 90 if tab_pos[0] == 'l' else -90
sctr = Scatter(do_translation=False,
rotation=rotation,
do_rotation=False,
do_scale=False,
size_hint=(None, None),
auto_bring_to_front=False,
size=scrl_v.size)
sctr.add_widget(scrl_v)
lentab_pos = len(tab_pos)
# Update scatter's top when its pos changes.
# Needed for repositioning scatter to the correct place after its
# added to the parent. Use clock_schedule_once to ensure top is
# calculated after the parent's pos on canvas has been calculated.
# This is needed for when tab_pos changes to correctly position
# scatter. Without clock.schedule_once the positions would look
# fine but touch won't translate to the correct position
if tab_pos[lentab_pos - 4:] == '_top':
# on positions 'left_top' and 'right_top'
sctr.bind(pos=partial(self._update_top, sctr, 'top', None))
tab_list = (sctr, )
elif tab_pos[lentab_pos - 4:] == '_mid':
# calculate top of scatter
sctr.bind(pos=partial(self._update_top, sctr, 'mid',
scrl_v.width))
tab_list = (Widget(), sctr, Widget())
elif tab_pos[lentab_pos - 7:] == '_bottom':
tab_list = (Widget(), Widget(), sctr)
if pos_letter == 'l':
widget_list = (tab_layout, self_content)
else:
widget_list = (self_content, tab_layout)
# add widgets to tab_layout
add = tab_layout.add_widget
for widg in tab_list:
add(widg)
# add widgets to self
add = self.add_widget
for widg in widget_list:
add(widg)
def _update_tab_width(self, *l):
if self.tab_width:
for tab in self.tab_list:
tab.size_hint_x = 1
tsw = self.tab_width * len(self._tab_strip.children)
else:
# tab_width = None
tsw = 0
for tab in self.tab_list:
if tab.size_hint_x:
# size_hint_x: x/.xyz
tab.size_hint_x = 1
# drop to default tab_width
tsw += 100
else:
# size_hint_x: None
tsw += tab.width
self._tab_strip.width = tsw
self._reposition_tabs()
def _update_top(self, *args):
sctr, top, scrl_v_width, x, y = args
ev = self._update_top_ev
if ev is not None:
ev.cancel()
ev = self._update_top_ev = Clock.schedule_once(
partial(self._updt_top, sctr, top, scrl_v_width), 0)
def _updt_top(self, sctr, top, scrl_v_width, *args):
if top[0] == 't':
sctr.top = self.top
else:
sctr.top = self.top - (self.height - scrl_v_width) / 2
def _update_scrollview(self, scrl_v, *l):
self_tab_pos = self.tab_pos
self_tabs = self._tab_strip
if self_tab_pos[0] == 'b' or self_tab_pos[0] == 't':
# bottom or top
scrl_v.width = min(self.width, self_tabs.width)
# required for situations when scrl_v's pos is calculated
# when it has no parent
scrl_v.top += 1
scrl_v.top -= 1
else:
# left or right
scrl_v.width = min(self.height, self_tabs.width)
self_tabs.pos = (0, 0)
| 34.306698 | 79 | 0.623703 |
__all__ = ('StripLayout', 'TabbedPanel', 'TabbedPanelContent',
'TabbedPanelHeader', 'TabbedPanelItem', 'TabbedPanelStrip',
'TabbedPanelException')
from functools import partial
from kivy.clock import Clock
from kivy.compat import string_types
from kivy.factory import Factory
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.widget import Widget
from kivy.uix.scatter import Scatter
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.logger import Logger
from kivy.metrics import dp
from kivy.properties import ObjectProperty, StringProperty, OptionProperty, \
ListProperty, NumericProperty, AliasProperty, BooleanProperty
class TabbedPanelException(Exception):
pass
class TabbedPanelHeader(ToggleButton):
content = ObjectProperty(None, allownone=True)
def on_touch_down(self, touch):
if self.state == 'down':
for child in self.children:
child.dispatch('on_touch_down', touch)
return
else:
super(TabbedPanelHeader, self).on_touch_down(touch)
def on_release(self, *largs):
if self.parent:
self.parent.tabbed_panel.switch_to(self)
else:
self.panel.switch_to(self.panel.current_tab)
class TabbedPanelItem(TabbedPanelHeader):
def add_widget(self, widget, index=0):
self.content = widget
if not self.parent:
return
panel = self.parent.tabbed_panel
if panel.current_tab == self:
panel.switch_to(self)
def remove_widget(self, widget):
self.content = None
if not self.parent:
return
panel = self.parent.tabbed_panel
if panel.current_tab == self:
panel.remove_widget(widget)
class TabbedPanelStrip(GridLayout):
tabbed_panel = ObjectProperty(None)
class StripLayout(GridLayout):
border = ListProperty([4, 4, 4, 4])
background_image = StringProperty(
'atlas://data/images/defaulttheme/action_view')
class TabbedPanelContent(FloatLayout):
pass
class TabbedPanel(GridLayout):
background_color = ListProperty([1, 1, 1, 1])
border = ListProperty([16, 16, 16, 16])
background_image = StringProperty('atlas://data/images/defaulttheme/tab')
background_disabled_image = StringProperty(
'atlas://data/images/defaulttheme/tab_disabled')
strip_image = StringProperty(
'atlas://data/images/defaulttheme/action_view')
strip_border = ListProperty([4, 4, 4, 4])
_current_tab = ObjectProperty(None)
def get_current_tab(self):
return self._current_tab
current_tab = AliasProperty(get_current_tab, None, bind=('_current_tab', ))
tab_pos = OptionProperty(
'top_left',
options=('left_top', 'left_mid', 'left_bottom', 'top_left',
'top_mid', 'top_right', 'right_top', 'right_mid',
'right_bottom', 'bottom_left', 'bottom_mid', 'bottom_right'))
tab_height = NumericProperty('40dp')
tab_width = NumericProperty('100dp', allownone=True)
do_default_tab = BooleanProperty(True)
default_tab_text = StringProperty('Default tab')
default_tab_cls = ObjectProperty(TabbedPanelHeader)
def get_tab_list(self):
if self._tab_strip:
return self._tab_strip.children
return 1.
tab_list = AliasProperty(get_tab_list, None)
content = ObjectProperty(None)
_default_tab = ObjectProperty(None, allow_none=True)
def get_def_tab(self):
return self._default_tab
def set_def_tab(self, new_tab):
if not issubclass(new_tab.__class__, TabbedPanelHeader):
raise TabbedPanelException('`default_tab_class` should be\
subclassed from `TabbedPanelHeader`')
if self._default_tab == new_tab:
return
oltab = self._default_tab
self._default_tab = new_tab
self.remove_widget(oltab)
self._original_tab = None
self.switch_to(new_tab)
new_tab.state = 'down'
default_tab = AliasProperty(get_def_tab, set_def_tab,
bind=('_default_tab', ))
def get_def_tab_content(self):
return self.default_tab.content
def set_def_tab_content(self, *l):
self.default_tab.content = l[0]
default_tab_content = AliasProperty(get_def_tab_content,
set_def_tab_content)
_update_top_ev = _update_tab_ev = _update_tabs_ev = None
def __init__(self, **kwargs):
self._childrens = []
self._tab_layout = StripLayout(rows=1)
self.rows = 1
self._tab_strip = TabbedPanelStrip(
tabbed_panel=self,
rows=1, size_hint=(None, None),
height=self.tab_height, width=self.tab_width)
self._partial_update_scrollview = None
self.content = TabbedPanelContent()
self._current_tab = self._original_tab \
= self._default_tab = TabbedPanelHeader()
super(TabbedPanel, self).__init__(**kwargs)
self.fbind('size', self._reposition_tabs)
if not self.do_default_tab:
Clock.schedule_once(self._switch_to_first_tab)
return
self._setup_default_tab()
self.switch_to(self.default_tab)
def switch_to(self, header, do_scroll=False):
header_content = header.content
self._current_tab.state = 'normal'
header.state = 'down'
self._current_tab = header
self.clear_widgets()
if header_content is None:
return
parent = header_content.parent
if parent:
parent.remove_widget(header_content)
self.add_widget(header_content)
if do_scroll:
tabs = self._tab_strip
tabs.parent.scroll_to(header)
def clear_tabs(self, *l):
self_tabs = self._tab_strip
self_tabs.clear_widgets()
if self.do_default_tab:
self_default_tab = self._default_tab
self_tabs.add_widget(self_default_tab)
self_tabs.width = self_default_tab.width
self._reposition_tabs()
def add_widget(self, widget, index=0):
content = self.content
if content is None:
return
parent = widget.parent
if parent:
parent.remove_widget(widget)
if widget in (content, self._tab_layout):
super(TabbedPanel, self).add_widget(widget, index)
elif isinstance(widget, TabbedPanelHeader):
self_tabs = self._tab_strip
self_tabs.add_widget(widget, index)
widget.group = '__tab%r__' % self_tabs.uid
self.on_tab_width()
else:
widget.pos_hint = {'x': 0, 'top': 1}
self._childrens.append(widget)
content.disabled = self.current_tab.disabled
content.add_widget(widget, index)
def remove_widget(self, widget):
content = self.content
if content is None:
return
if widget in (content, self._tab_layout):
super(TabbedPanel, self).remove_widget(widget)
elif isinstance(widget, TabbedPanelHeader):
if not (self.do_default_tab and widget is self._default_tab):
self_tabs = self._tab_strip
self_tabs.width -= widget.width
self_tabs.remove_widget(widget)
if widget.state == 'down' and self.do_default_tab:
self._default_tab.on_release()
self._reposition_tabs()
else:
Logger.info('TabbedPanel: default tab! can\'t be removed.\n' +
'Change `default_tab` to a different tab.')
else:
if widget in self._childrens:
self._childrens.remove(widget)
if widget in content.children:
content.remove_widget(widget)
def clear_widgets(self, **kwargs):
content = self.content
if content is None:
return
if kwargs.get('do_super', False):
super(TabbedPanel, self).clear_widgets()
else:
content.clear_widgets()
def on_strip_image(self, instance, value):
if not self._tab_layout:
return
self._tab_layout.background_image = value
def on_strip_border(self, instance, value):
if not self._tab_layout:
return
self._tab_layout.border = value
def on_do_default_tab(self, instance, value):
if not value:
dft = self.default_tab
if dft in self.tab_list:
self.remove_widget(dft)
self._switch_to_first_tab()
self._default_tab = self._current_tab
else:
self._current_tab.state = 'normal'
self._setup_default_tab()
def on_default_tab_text(self, *args):
self._default_tab.text = self.default_tab_text
def on_tab_width(self, *l):
ev = self._update_tab_ev
if ev is None:
ev = self._update_tab_ev = Clock.create_trigger(
self._update_tab_width, 0)
ev()
def on_tab_height(self, *l):
self._tab_layout.height = self._tab_strip.height = self.tab_height
self._reposition_tabs()
def on_tab_pos(self, *l):
# ensure canvas
self._reposition_tabs()
def _setup_default_tab(self):
if self._default_tab in self.tab_list:
return
content = self._default_tab.content
_tabs = self._tab_strip
cls = self.default_tab_cls
if isinstance(cls, string_types):
cls = Factory.get(cls)
if not issubclass(cls, TabbedPanelHeader):
raise TabbedPanelException('`default_tab_class` should be\
subclassed from `TabbedPanelHeader`')
# no need to instantiate if class is TabbedPanelHeader
if cls != TabbedPanelHeader:
self._current_tab = self._original_tab = self._default_tab = cls()
default_tab = self.default_tab
if self._original_tab == self.default_tab:
default_tab.text = self.default_tab_text
default_tab.height = self.tab_height
default_tab.group = '__tab%r__' % _tabs.uid
default_tab.state = 'down'
default_tab.width = self.tab_width if self.tab_width else 100
default_tab.content = content
tl = self.tab_list
if default_tab not in tl:
_tabs.add_widget(default_tab, len(tl))
if default_tab.content:
self.clear_widgets()
self.add_widget(self.default_tab.content)
else:
Clock.schedule_once(self._load_default_tab_content)
self._current_tab = default_tab
def _switch_to_first_tab(self, *l):
ltl = len(self.tab_list) - 1
if ltl > -1:
self._current_tab = dt = self._original_tab \
= self.tab_list[ltl]
self.switch_to(dt)
def _load_default_tab_content(self, dt):
if self.default_tab:
self.switch_to(self.default_tab)
def _reposition_tabs(self, *l):
ev = self._update_tabs_ev
if ev is None:
ev = self._update_tabs_ev = Clock.create_trigger(
self._update_tabs, 0)
ev()
def _update_tabs(self, *l):
self_content = self.content
if not self_content:
return
# cache variables for faster access
tab_pos = self.tab_pos
tab_layout = self._tab_layout
tab_layout.clear_widgets()
scrl_v = ScrollView(size_hint=(None, 1))
tabs = self._tab_strip
parent = tabs.parent
if parent:
parent.remove_widget(tabs)
scrl_v.add_widget(tabs)
scrl_v.pos = (0, 0)
self_update_scrollview = self._update_scrollview
# update scrlv width when tab width changes depends on tab_pos
if self._partial_update_scrollview is not None:
tabs.unbind(width=self._partial_update_scrollview)
self._partial_update_scrollview = partial(
self_update_scrollview, scrl_v)
tabs.bind(width=self._partial_update_scrollview)
# remove all widgets from the tab_strip
self.clear_widgets(do_super=True)
tab_height = self.tab_height
widget_list = []
tab_list = []
pos_letter = tab_pos[0]
if pos_letter == 'b' or pos_letter == 't':
# bottom or top positions
# one col containing the tab_strip and the content
self.cols = 1
self.rows = 2
# tab_layout contains the scrollview containing tabs and two blank
# dummy widgets for spacing
tab_layout.rows = 1
tab_layout.cols = 3
tab_layout.size_hint = (1, None)
tab_layout.height = (tab_height + tab_layout.padding[1] +
tab_layout.padding[3] + dp(2))
self_update_scrollview(scrl_v)
if pos_letter == 'b':
# bottom
if tab_pos == 'bottom_mid':
tab_list = (Widget(), scrl_v, Widget())
widget_list = (self_content, tab_layout)
else:
if tab_pos == 'bottom_left':
tab_list = (scrl_v, Widget(), Widget())
elif tab_pos == 'bottom_right':
# add two dummy widgets
tab_list = (Widget(), Widget(), scrl_v)
widget_list = (self_content, tab_layout)
else:
# top
if tab_pos == 'top_mid':
tab_list = (Widget(), scrl_v, Widget())
elif tab_pos == 'top_left':
tab_list = (scrl_v, Widget(), Widget())
elif tab_pos == 'top_right':
tab_list = (Widget(), Widget(), scrl_v)
widget_list = (tab_layout, self_content)
elif pos_letter == 'l' or pos_letter == 'r':
# left ot right positions
# one row containing the tab_strip and the content
self.cols = 2
self.rows = 1
# tab_layout contains two blank dummy widgets for spacing
# "vertically" and the scatter containing scrollview
# containing tabs
tab_layout.rows = 3
tab_layout.cols = 1
tab_layout.size_hint = (None, 1)
tab_layout.width = tab_height
scrl_v.height = tab_height
self_update_scrollview(scrl_v)
# rotate the scatter for vertical positions
rotation = 90 if tab_pos[0] == 'l' else -90
sctr = Scatter(do_translation=False,
rotation=rotation,
do_rotation=False,
do_scale=False,
size_hint=(None, None),
auto_bring_to_front=False,
size=scrl_v.size)
sctr.add_widget(scrl_v)
lentab_pos = len(tab_pos)
# Update scatter's top when its pos changes.
# This is needed for when tab_pos changes to correctly position
# scatter. Without clock.schedule_once the positions would look
# fine but touch won't translate to the correct position
if tab_pos[lentab_pos - 4:] == '_top':
sctr.bind(pos=partial(self._update_top, sctr, 'top', None))
tab_list = (sctr, )
elif tab_pos[lentab_pos - 4:] == '_mid':
sctr.bind(pos=partial(self._update_top, sctr, 'mid',
scrl_v.width))
tab_list = (Widget(), sctr, Widget())
elif tab_pos[lentab_pos - 7:] == '_bottom':
tab_list = (Widget(), Widget(), sctr)
if pos_letter == 'l':
widget_list = (tab_layout, self_content)
else:
widget_list = (self_content, tab_layout)
add = tab_layout.add_widget
for widg in tab_list:
add(widg)
add = self.add_widget
for widg in widget_list:
add(widg)
def _update_tab_width(self, *l):
if self.tab_width:
for tab in self.tab_list:
tab.size_hint_x = 1
tsw = self.tab_width * len(self._tab_strip.children)
else:
tsw = 0
for tab in self.tab_list:
if tab.size_hint_x:
tab.size_hint_x = 1
tsw += 100
else:
tsw += tab.width
self._tab_strip.width = tsw
self._reposition_tabs()
def _update_top(self, *args):
sctr, top, scrl_v_width, x, y = args
ev = self._update_top_ev
if ev is not None:
ev.cancel()
ev = self._update_top_ev = Clock.schedule_once(
partial(self._updt_top, sctr, top, scrl_v_width), 0)
def _updt_top(self, sctr, top, scrl_v_width, *args):
if top[0] == 't':
sctr.top = self.top
else:
sctr.top = self.top - (self.height - scrl_v_width) / 2
def _update_scrollview(self, scrl_v, *l):
self_tab_pos = self.tab_pos
self_tabs = self._tab_strip
if self_tab_pos[0] == 'b' or self_tab_pos[0] == 't':
scrl_v.width = min(self.width, self_tabs.width)
# when it has no parent
scrl_v.top += 1
scrl_v.top -= 1
else:
# left or right
scrl_v.width = min(self.height, self_tabs.width)
self_tabs.pos = (0, 0)
| true | true |
1c3e0b2b666c83d76275ef9410b970cce34e2b9b | 28,588 | py | Python | packages/python/yap_kernel/yap_ipython/lib/pretty.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 90 | 2015-03-09T01:24:15.000Z | 2022-02-24T13:56:25.000Z | packages/python/yap_kernel/yap_ipython/lib/pretty.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 52 | 2016-02-14T08:59:37.000Z | 2022-03-14T16:39:35.000Z | packages/python/yap_kernel/yap_ipython/lib/pretty.py | ryandesign/yap | 9a50d1a3d985ec559ebfbb8e9f4d4c6b88b30214 | [
"Artistic-1.0-Perl",
"ClArtistic"
] | 27 | 2015-11-19T02:45:49.000Z | 2021-11-25T19:47:58.000Z | # -*- coding: utf-8 -*-
"""
Python advanced pretty printer. This pretty printer is intended to
replace the old `pprint` python module which does not allow developers
to provide their own pretty print callbacks.
This module is based on ruby's `prettyprint.rb` library by `Tanaka Akira`.
Example Usage
-------------
To directly print the representation of an object use `pprint`::
from pretty import pprint
pprint(complex_object)
To get a string of the output use `pretty`::
from pretty import pretty
string = pretty(complex_object)
Extending
---------
The pretty library allows developers to add pretty printing rules for their
own objects. This process is straightforward. All you have to do is to
add a `_repr_pretty_` method to your object and call the methods on the
pretty printer passed::
class MyObject(object):
def _repr_pretty_(self, p, cycle):
...
Here is an example implementation of a `_repr_pretty_` method for a list
subclass::
class MyList(list):
def _repr_pretty_(self, p, cycle):
if cycle:
p.text('MyList(...)')
else:
with p.group(8, 'MyList([', '])'):
for idx, item in enumerate(self):
if idx:
p.text(',')
p.breakable()
p.pretty(item)
The `cycle` parameter is `True` if pretty detected a cycle. You *have* to
react to that or the result is an infinite loop. `p.text()` just adds
non breaking text to the output, `p.breakable()` either adds a whitespace
or breaks here. If you pass it an argument it's used instead of the
default space. `p.pretty` prettyprints another object using the pretty print
method.
The first parameter to the `group` function specifies the extra indentation
of the next line. In this example the next item will either be on the same
line (if the items are short enough) or aligned with the right edge of the
opening bracket of `MyList`.
If you just want to indent something you can use the group function
without open / close parameters. You can also use this code::
with p.indent(2):
...
Inheritance diagram:
.. inheritance-diagram:: yap_ipython.lib.pretty
:parts: 3
:copyright: 2007 by Armin Ronacher.
Portions (c) 2009 by Robert Kern.
:license: BSD License.
"""
from contextlib import contextmanager
import datetime
import os
import re
import sys
import types
from collections import deque
from io import StringIO
from warnings import warn
from yap_ipython.utils.decorators import undoc
from yap_ipython.utils.py3compat import PYPY
from yap_ipython.utils.signatures import signature
__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
'for_type', 'for_type_by_name']
MAX_SEQ_LENGTH = 1000
# The language spec says that dicts preserve order from 3.7, but CPython
# does so from 3.6, so it seems likely that people will expect that.
DICT_IS_ORDERED = sys.version_info >= (3, 6)
_re_pattern_type = type(re.compile(''))
def _safe_getattr(obj, attr, default=None):
"""Safe version of getattr.
Same as getattr, but will return ``default`` on any Exception,
rather than raising.
"""
try:
return getattr(obj, attr, default)
except Exception:
return default
@undoc
class CUnicodeIO(StringIO):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warn(("CUnicodeIO is deprecated since IPython 6.0. "
"Please use io.StringIO instead."),
DeprecationWarning, stacklevel=2)
def _sorted_for_pprint(items):
"""
Sort the given items for pretty printing. Since some predictable
sorting is better than no sorting at all, we sort on the string
representation if normal sorting fails.
"""
items = list(items)
try:
return sorted(items)
except Exception:
try:
return sorted(items, key=str)
except Exception:
return items
def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
"""
Pretty print the object's representation.
"""
stream = StringIO()
printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
printer.pretty(obj)
printer.flush()
return stream.getvalue()
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
"""
Like `pretty` but print to stdout.
"""
printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
printer.pretty(obj)
printer.flush()
sys.stdout.write(newline)
sys.stdout.flush()
class _PrettyPrinterBase(object):
@contextmanager
def indent(self, indent):
"""with statement support for indenting/dedenting."""
self.indentation += indent
try:
yield
finally:
self.indentation -= indent
@contextmanager
def group(self, indent=0, open='', close=''):
"""like begin_group / end_group but for the with statement."""
self.begin_group(indent, open)
try:
yield
finally:
self.end_group(indent, close)
class PrettyPrinter(_PrettyPrinterBase):
"""
Baseclass for the `RepresentationPrinter` prettyprinter that is used to
generate pretty reprs of objects. Contrary to the `RepresentationPrinter`
this printer knows nothing about the default pprinters or the `_repr_pretty_`
callback method.
"""
def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
self.output = output
self.max_width = max_width
self.newline = newline
self.max_seq_length = max_seq_length
self.output_width = 0
self.buffer_width = 0
self.buffer = deque()
root_group = Group(0)
self.group_stack = [root_group]
self.group_queue = GroupQueue(root_group)
self.indentation = 0
def _break_outer_groups(self):
while self.max_width < self.output_width + self.buffer_width:
group = self.group_queue.deq()
if not group:
return
while group.breakables:
x = self.buffer.popleft()
self.output_width = x.output(self.output, self.output_width)
self.buffer_width -= x.width
while self.buffer and isinstance(self.buffer[0], Text):
x = self.buffer.popleft()
self.output_width = x.output(self.output, self.output_width)
self.buffer_width -= x.width
def text(self, obj):
"""Add literal text to the output."""
width = len(obj)
if self.buffer:
text = self.buffer[-1]
if not isinstance(text, Text):
text = Text()
self.buffer.append(text)
text.add(obj, width)
self.buffer_width += width
self._break_outer_groups()
else:
self.output.write(obj)
self.output_width += width
def breakable(self, sep=' '):
"""
Add a breakable separator to the output. This does not mean that it
will automatically break here. If no breaking on this position takes
place the `sep` is inserted which default to one space.
"""
width = len(sep)
group = self.group_stack[-1]
if group.want_break:
self.flush()
self.output.write(self.newline)
self.output.write(' ' * self.indentation)
self.output_width = self.indentation
self.buffer_width = 0
else:
self.buffer.append(Breakable(sep, width, self))
self.buffer_width += width
self._break_outer_groups()
def break_(self):
"""
Explicitly insert a newline into the output, maintaining correct indentation.
"""
self.flush()
self.output.write(self.newline)
self.output.write(' ' * self.indentation)
self.output_width = self.indentation
self.buffer_width = 0
def begin_group(self, indent=0, open=''):
"""
Begin a group. If you want support for python < 2.5 which doesn't has
the with statement this is the preferred way:
p.begin_group(1, '{')
...
p.end_group(1, '}')
The python 2.5 expression would be this:
with p.group(1, '{', '}'):
...
The first parameter specifies the indentation for the next line (usually
the width of the opening text), the second the opening text. All
parameters are optional.
"""
if open:
self.text(open)
group = Group(self.group_stack[-1].depth + 1)
self.group_stack.append(group)
self.group_queue.enq(group)
self.indentation += indent
def _enumerate(self, seq):
"""like enumerate, but with an upper limit on the number of items"""
for idx, x in enumerate(seq):
if self.max_seq_length and idx >= self.max_seq_length:
self.text(',')
self.breakable()
self.text('...')
return
yield idx, x
def end_group(self, dedent=0, close=''):
"""End a group. See `begin_group` for more details."""
self.indentation -= dedent
group = self.group_stack.pop()
if not group.breakables:
self.group_queue.remove(group)
if close:
self.text(close)
def flush(self):
"""Flush data that is left in the buffer."""
for data in self.buffer:
self.output_width += data.output(self.output, self.output_width)
self.buffer.clear()
self.buffer_width = 0
def _get_mro(obj_class):
""" Get a reasonable method resolution order of a class and its superclasses
for both old-style and new-style classes.
"""
if not hasattr(obj_class, '__mro__'):
# Old-style class. Mix in object to make a fake new-style class.
try:
obj_class = type(obj_class.__name__, (obj_class, object), {})
except TypeError:
# Old-style extension type that does not descend from object.
# FIXME: try to construct a more thorough MRO.
mro = [obj_class]
else:
mro = obj_class.__mro__[1:-1]
else:
mro = obj_class.__mro__
return mro
class RepresentationPrinter(PrettyPrinter):
"""
Special pretty printer that has a `pretty` method that calls the pretty
printer for a python object.
This class stores processing data on `self` so you must *never* use
this class in a threaded environment. Always lock it or reinstanciate
it.
Instances also have a verbose flag callbacks can access to control their
output. For example the default instance repr prints all attributes and
methods that are not prefixed by an underscore if the printer is in
verbose mode.
"""
def __init__(self, output, verbose=False, max_width=79, newline='\n',
singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
max_seq_length=MAX_SEQ_LENGTH):
PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
self.verbose = verbose
self.stack = []
if singleton_pprinters is None:
singleton_pprinters = _singleton_pprinters.copy()
self.singleton_pprinters = singleton_pprinters
if type_pprinters is None:
type_pprinters = _type_pprinters.copy()
self.type_pprinters = type_pprinters
if deferred_pprinters is None:
deferred_pprinters = _deferred_type_pprinters.copy()
self.deferred_pprinters = deferred_pprinters
def pretty(self, obj):
"""Pretty print the given object."""
obj_id = id(obj)
cycle = obj_id in self.stack
self.stack.append(obj_id)
self.begin_group()
try:
obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
# First try to find registered singleton printers for the type.
try:
printer = self.singleton_pprinters[obj_id]
except (TypeError, KeyError):
pass
else:
return printer(obj, self, cycle)
# Next walk the mro and check for either:
# 1) a registered printer
# 2) a _repr_pretty_ method
for cls in _get_mro(obj_class):
if cls in self.type_pprinters:
# printer registered in self.type_pprinters
return self.type_pprinters[cls](obj, self, cycle)
else:
# deferred printer
printer = self._in_deferred_types(cls)
if printer is not None:
return printer(obj, self, cycle)
else:
# Finally look for special method names.
# Some objects automatically create any requested
# attribute. Try to ignore most of them by checking for
# callability.
if '_repr_pretty_' in cls.__dict__:
meth = cls._repr_pretty_
if callable(meth):
return meth(obj, self, cycle)
if cls is not object \
and callable(cls.__dict__.get('__repr__')):
return _repr_pprint(obj, self, cycle)
return _default_pprint(obj, self, cycle)
finally:
self.end_group()
self.stack.pop()
def _in_deferred_types(self, cls):
"""
Check if the given class is specified in the deferred type registry.
Returns the printer from the registry if it exists, and None if the
class is not in the registry. Successful matches will be moved to the
regular type registry for future use.
"""
mod = _safe_getattr(cls, '__module__', None)
name = _safe_getattr(cls, '__name__', None)
key = (mod, name)
printer = None
if key in self.deferred_pprinters:
# Move the printer over to the regular registry.
printer = self.deferred_pprinters.pop(key)
self.type_pprinters[cls] = printer
return printer
class Printable(object):
def output(self, stream, output_width):
return output_width
class Text(Printable):
def __init__(self):
self.objs = []
self.width = 0
def output(self, stream, output_width):
for obj in self.objs:
stream.write(obj)
return output_width + self.width
def add(self, obj, width):
self.objs.append(obj)
self.width += width
class Breakable(Printable):
def __init__(self, seq, width, pretty):
self.obj = seq
self.width = width
self.pretty = pretty
self.indentation = pretty.indentation
self.group = pretty.group_stack[-1]
self.group.breakables.append(self)
def output(self, stream, output_width):
self.group.breakables.popleft()
if self.group.want_break:
stream.write(self.pretty.newline)
stream.write(' ' * self.indentation)
return self.indentation
if not self.group.breakables:
self.pretty.group_queue.remove(self.group)
stream.write(self.obj)
return output_width + self.width
class Group(Printable):
def __init__(self, depth):
self.depth = depth
self.breakables = deque()
self.want_break = False
class GroupQueue(object):
def __init__(self, *groups):
self.queue = []
for group in groups:
self.enq(group)
def enq(self, group):
depth = group.depth
while depth > len(self.queue) - 1:
self.queue.append([])
self.queue[depth].append(group)
def deq(self):
for stack in self.queue:
for idx, group in enumerate(reversed(stack)):
if group.breakables:
del stack[idx]
group.want_break = True
return group
for group in stack:
group.want_break = True
del stack[:]
def remove(self, group):
try:
self.queue[group.depth].remove(group)
except ValueError:
pass
def _default_pprint(obj, p, cycle):
"""
The default print function. Used if an object does not provide one and
it's none of the builtin objects.
"""
klass = _safe_getattr(obj, '__class__', None) or type(obj)
if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
# A user-provided repr. Find newlines and replace them with p.break_()
_repr_pprint(obj, p, cycle)
return
p.begin_group(1, '<')
p.pretty(klass)
p.text(' at 0x%x' % id(obj))
if cycle:
p.text(' ...')
elif p.verbose:
first = True
for key in dir(obj):
if not key.startswith('_'):
try:
value = getattr(obj, key)
except AttributeError:
continue
if isinstance(value, types.MethodType):
continue
if not first:
p.text(',')
p.breakable()
p.text(key)
p.text('=')
step = len(key) + 1
p.indentation += step
p.pretty(value)
p.indentation -= step
first = False
p.end_group(1, '>')
def _seq_pprinter_factory(start, end):
"""
Factory that returns a pprint function useful for sequences. Used by
the default pprint for tuples, dicts, and lists.
"""
def inner(obj, p, cycle):
if cycle:
return p.text(start + '...' + end)
step = len(start)
p.begin_group(step, start)
for idx, x in p._enumerate(obj):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
if len(obj) == 1 and type(obj) is tuple:
# Special case for 1-item tuples.
p.text(',')
p.end_group(step, end)
return inner
def _set_pprinter_factory(start, end):
"""
Factory that returns a pprint function useful for sets and frozensets.
"""
def inner(obj, p, cycle):
if cycle:
return p.text(start + '...' + end)
if len(obj) == 0:
# Special case.
p.text(type(obj).__name__ + '()')
else:
step = len(start)
p.begin_group(step, start)
# Like dictionary keys, we will try to sort the items if there aren't too many
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
items = _sorted_for_pprint(obj)
else:
items = obj
for idx, x in p._enumerate(items):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
p.end_group(step, end)
return inner
def _dict_pprinter_factory(start, end):
"""
Factory that returns a pprint function used by the default pprint of
dicts and dict proxies.
"""
def inner(obj, p, cycle):
if cycle:
return p.text('{...}')
step = len(start)
p.begin_group(step, start)
keys = obj.keys()
# if dict isn't large enough to be truncated, sort keys before displaying
# From Python 3.7, dicts preserve order by definition, so we don't sort.
if not DICT_IS_ORDERED \
and not (p.max_seq_length and len(obj) >= p.max_seq_length):
keys = _sorted_for_pprint(keys)
for idx, key in p._enumerate(keys):
if idx:
p.text(',')
p.breakable()
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
p.end_group(step, end)
return inner
def _super_pprint(obj, p, cycle):
"""The pprint for the super type."""
p.begin_group(8, '<super: ')
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
if PYPY: # In PyPy, super() objects don't have __self__ attributes
dself = obj.__repr__.__self__
p.pretty(None if dself is obj else dself)
else:
p.pretty(obj.__self__)
p.end_group(8, '>')
def _re_pattern_pprint(obj, p, cycle):
"""The pprint function for regular expression patterns."""
p.text('re.compile(')
pattern = repr(obj.pattern)
if pattern[:1] in 'uU':
pattern = pattern[1:]
prefix = 'ur'
else:
prefix = 'r'
pattern = prefix + pattern.replace('\\\\', '\\')
p.text(pattern)
if obj.flags:
p.text(',')
p.breakable()
done_one = False
for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
'UNICODE', 'VERBOSE', 'DEBUG'):
if obj.flags & getattr(re, flag):
if done_one:
p.text('|')
p.text('re.' + flag)
done_one = True
p.text(')')
def _type_pprint(obj, p, cycle):
"""The pprint for classes and types."""
# Heap allocated types might not have the module attribute,
# and others may set it to None.
# Checks for a __repr__ override in the metaclass. Can't compare the
# type(obj).__repr__ directly because in PyPy the representation function
# inherited from type isn't the same type.__repr__
if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
_repr_pprint(obj, p, cycle)
return
mod = _safe_getattr(obj, '__module__', None)
try:
name = obj.__qualname__
if not isinstance(name, str):
# This can happen if the type implements __qualname__ as a property
# or other descriptor in Python 2.
raise Exception("Try __name__")
except Exception:
name = obj.__name__
if not isinstance(name, str):
name = '<unknown type>'
if mod in (None, '__builtin__', 'builtins', 'exceptions'):
p.text(name)
else:
p.text(mod + '.' + name)
def _repr_pprint(obj, p, cycle):
"""A pprint that just redirects to the normal repr function."""
# Find newlines and replace them with p.break_()
output = repr(obj)
for idx,output_line in enumerate(output.splitlines()):
if idx:
p.break_()
p.text(output_line)
def _function_pprint(obj, p, cycle):
"""Base pprint for all functions and builtin functions."""
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
try:
func_def = name + str(signature(obj))
except ValueError:
func_def = name
p.text('<function %s>' % func_def)
def _exception_pprint(obj, p, cycle):
"""Base pprint for all exceptions."""
name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
name = '%s.%s' % (obj.__class__.__module__, name)
step = len(name) + 1
p.begin_group(step, name + '(')
for idx, arg in enumerate(getattr(obj, 'args', ())):
if idx:
p.text(',')
p.breakable()
p.pretty(arg)
p.end_group(step, ')')
#: the exception base
try:
_exception_base = BaseException
except NameError:
_exception_base = Exception
#: printers for builtin types
_type_pprinters = {
int: _repr_pprint,
float: _repr_pprint,
str: _repr_pprint,
tuple: _seq_pprinter_factory('(', ')'),
list: _seq_pprinter_factory('[', ']'),
dict: _dict_pprinter_factory('{', '}'),
set: _set_pprinter_factory('{', '}'),
frozenset: _set_pprinter_factory('frozenset({', '})'),
super: _super_pprint,
_re_pattern_type: _re_pattern_pprint,
type: _type_pprint,
types.FunctionType: _function_pprint,
types.BuiltinFunctionType: _function_pprint,
types.MethodType: _repr_pprint,
datetime.datetime: _repr_pprint,
datetime.timedelta: _repr_pprint,
_exception_base: _exception_pprint
}
# render os.environ like a dict
_env_type = type(os.environ)
# future-proof in case os.environ becomes a plain dict?
if _env_type is not dict:
_type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
try:
# In PyPy, types.DictProxyType is dict, setting the dictproxy printer
# using dict.setdefault avoids overwritting the dict printer
_type_pprinters.setdefault(types.DictProxyType,
_dict_pprinter_factory('dict_proxy({', '})'))
_type_pprinters[types.ClassType] = _type_pprint
_type_pprinters[types.SliceType] = _repr_pprint
except AttributeError: # Python 3
_type_pprinters[types.MappingProxyType] = \
_dict_pprinter_factory('mappingproxy({', '})')
_type_pprinters[slice] = _repr_pprint
try:
_type_pprinters[long] = _repr_pprint
_type_pprinters[unicode] = _repr_pprint
except NameError:
_type_pprinters[range] = _repr_pprint
_type_pprinters[bytes] = _repr_pprint
#: printers for types specified by name
_deferred_type_pprinters = {
}
def for_type(typ, func):
"""
Add a pretty printer for a given type.
"""
oldfunc = _type_pprinters.get(typ, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore Nones.
_type_pprinters[typ] = func
return oldfunc
def for_type_by_name(type_module, type_name, func):
"""
Add a pretty printer for a type specified by the module and name of a type
rather than the type object itself.
"""
key = (type_module, type_name)
oldfunc = _deferred_type_pprinters.get(key, None)
if func is not None:
# To support easy restoration of old pprinters, we need to ignore Nones.
_deferred_type_pprinters[key] = func
return oldfunc
#: printers for the default singletons
_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
NotImplemented]), _repr_pprint)
def _defaultdict_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(obj.default_factory)
p.text(',')
p.breakable()
p.pretty(dict(obj))
def _ordereddict_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(list(obj.items()))
def _deque_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(list(obj))
def _counter_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(dict(obj))
for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
for_type_by_name('collections', 'deque', _deque_pprint)
for_type_by_name('collections', 'Counter', _counter_pprint)
if __name__ == '__main__':
from random import randrange
class Foo(object):
def __init__(self):
self.foo = 1
self.bar = re.compile(r'\s+')
self.blub = dict.fromkeys(range(30), randrange(1, 40))
self.hehe = 23424.234234
self.list = ["blub", "blah", self]
def get_foo(self):
print("foo")
pprint(Foo(), verbose=True)
| 32.784404 | 107 | 0.592661 |
from contextlib import contextmanager
import datetime
import os
import re
import sys
import types
from collections import deque
from io import StringIO
from warnings import warn
from yap_ipython.utils.decorators import undoc
from yap_ipython.utils.py3compat import PYPY
from yap_ipython.utils.signatures import signature
__all__ = ['pretty', 'pprint', 'PrettyPrinter', 'RepresentationPrinter',
'for_type', 'for_type_by_name']
MAX_SEQ_LENGTH = 1000
DICT_IS_ORDERED = sys.version_info >= (3, 6)
_re_pattern_type = type(re.compile(''))
def _safe_getattr(obj, attr, default=None):
try:
return getattr(obj, attr, default)
except Exception:
return default
@undoc
class CUnicodeIO(StringIO):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
warn(("CUnicodeIO is deprecated since IPython 6.0. "
"Please use io.StringIO instead."),
DeprecationWarning, stacklevel=2)
def _sorted_for_pprint(items):
items = list(items)
try:
return sorted(items)
except Exception:
try:
return sorted(items, key=str)
except Exception:
return items
def pretty(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
stream = StringIO()
printer = RepresentationPrinter(stream, verbose, max_width, newline, max_seq_length=max_seq_length)
printer.pretty(obj)
printer.flush()
return stream.getvalue()
def pprint(obj, verbose=False, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
printer = RepresentationPrinter(sys.stdout, verbose, max_width, newline, max_seq_length=max_seq_length)
printer.pretty(obj)
printer.flush()
sys.stdout.write(newline)
sys.stdout.flush()
class _PrettyPrinterBase(object):
@contextmanager
def indent(self, indent):
self.indentation += indent
try:
yield
finally:
self.indentation -= indent
@contextmanager
def group(self, indent=0, open='', close=''):
self.begin_group(indent, open)
try:
yield
finally:
self.end_group(indent, close)
class PrettyPrinter(_PrettyPrinterBase):
def __init__(self, output, max_width=79, newline='\n', max_seq_length=MAX_SEQ_LENGTH):
self.output = output
self.max_width = max_width
self.newline = newline
self.max_seq_length = max_seq_length
self.output_width = 0
self.buffer_width = 0
self.buffer = deque()
root_group = Group(0)
self.group_stack = [root_group]
self.group_queue = GroupQueue(root_group)
self.indentation = 0
def _break_outer_groups(self):
while self.max_width < self.output_width + self.buffer_width:
group = self.group_queue.deq()
if not group:
return
while group.breakables:
x = self.buffer.popleft()
self.output_width = x.output(self.output, self.output_width)
self.buffer_width -= x.width
while self.buffer and isinstance(self.buffer[0], Text):
x = self.buffer.popleft()
self.output_width = x.output(self.output, self.output_width)
self.buffer_width -= x.width
def text(self, obj):
width = len(obj)
if self.buffer:
text = self.buffer[-1]
if not isinstance(text, Text):
text = Text()
self.buffer.append(text)
text.add(obj, width)
self.buffer_width += width
self._break_outer_groups()
else:
self.output.write(obj)
self.output_width += width
def breakable(self, sep=' '):
width = len(sep)
group = self.group_stack[-1]
if group.want_break:
self.flush()
self.output.write(self.newline)
self.output.write(' ' * self.indentation)
self.output_width = self.indentation
self.buffer_width = 0
else:
self.buffer.append(Breakable(sep, width, self))
self.buffer_width += width
self._break_outer_groups()
def break_(self):
self.flush()
self.output.write(self.newline)
self.output.write(' ' * self.indentation)
self.output_width = self.indentation
self.buffer_width = 0
def begin_group(self, indent=0, open=''):
if open:
self.text(open)
group = Group(self.group_stack[-1].depth + 1)
self.group_stack.append(group)
self.group_queue.enq(group)
self.indentation += indent
def _enumerate(self, seq):
for idx, x in enumerate(seq):
if self.max_seq_length and idx >= self.max_seq_length:
self.text(',')
self.breakable()
self.text('...')
return
yield idx, x
def end_group(self, dedent=0, close=''):
self.indentation -= dedent
group = self.group_stack.pop()
if not group.breakables:
self.group_queue.remove(group)
if close:
self.text(close)
def flush(self):
for data in self.buffer:
self.output_width += data.output(self.output, self.output_width)
self.buffer.clear()
self.buffer_width = 0
def _get_mro(obj_class):
if not hasattr(obj_class, '__mro__'):
try:
obj_class = type(obj_class.__name__, (obj_class, object), {})
except TypeError:
mro = [obj_class]
else:
mro = obj_class.__mro__[1:-1]
else:
mro = obj_class.__mro__
return mro
class RepresentationPrinter(PrettyPrinter):
def __init__(self, output, verbose=False, max_width=79, newline='\n',
singleton_pprinters=None, type_pprinters=None, deferred_pprinters=None,
max_seq_length=MAX_SEQ_LENGTH):
PrettyPrinter.__init__(self, output, max_width, newline, max_seq_length=max_seq_length)
self.verbose = verbose
self.stack = []
if singleton_pprinters is None:
singleton_pprinters = _singleton_pprinters.copy()
self.singleton_pprinters = singleton_pprinters
if type_pprinters is None:
type_pprinters = _type_pprinters.copy()
self.type_pprinters = type_pprinters
if deferred_pprinters is None:
deferred_pprinters = _deferred_type_pprinters.copy()
self.deferred_pprinters = deferred_pprinters
def pretty(self, obj):
obj_id = id(obj)
cycle = obj_id in self.stack
self.stack.append(obj_id)
self.begin_group()
try:
obj_class = _safe_getattr(obj, '__class__', None) or type(obj)
try:
printer = self.singleton_pprinters[obj_id]
except (TypeError, KeyError):
pass
else:
return printer(obj, self, cycle)
for cls in _get_mro(obj_class):
if cls in self.type_pprinters:
return self.type_pprinters[cls](obj, self, cycle)
else:
printer = self._in_deferred_types(cls)
if printer is not None:
return printer(obj, self, cycle)
else:
if '_repr_pretty_' in cls.__dict__:
meth = cls._repr_pretty_
if callable(meth):
return meth(obj, self, cycle)
if cls is not object \
and callable(cls.__dict__.get('__repr__')):
return _repr_pprint(obj, self, cycle)
return _default_pprint(obj, self, cycle)
finally:
self.end_group()
self.stack.pop()
def _in_deferred_types(self, cls):
mod = _safe_getattr(cls, '__module__', None)
name = _safe_getattr(cls, '__name__', None)
key = (mod, name)
printer = None
if key in self.deferred_pprinters:
printer = self.deferred_pprinters.pop(key)
self.type_pprinters[cls] = printer
return printer
class Printable(object):
def output(self, stream, output_width):
return output_width
class Text(Printable):
def __init__(self):
self.objs = []
self.width = 0
def output(self, stream, output_width):
for obj in self.objs:
stream.write(obj)
return output_width + self.width
def add(self, obj, width):
self.objs.append(obj)
self.width += width
class Breakable(Printable):
def __init__(self, seq, width, pretty):
self.obj = seq
self.width = width
self.pretty = pretty
self.indentation = pretty.indentation
self.group = pretty.group_stack[-1]
self.group.breakables.append(self)
def output(self, stream, output_width):
self.group.breakables.popleft()
if self.group.want_break:
stream.write(self.pretty.newline)
stream.write(' ' * self.indentation)
return self.indentation
if not self.group.breakables:
self.pretty.group_queue.remove(self.group)
stream.write(self.obj)
return output_width + self.width
class Group(Printable):
def __init__(self, depth):
self.depth = depth
self.breakables = deque()
self.want_break = False
class GroupQueue(object):
def __init__(self, *groups):
self.queue = []
for group in groups:
self.enq(group)
def enq(self, group):
depth = group.depth
while depth > len(self.queue) - 1:
self.queue.append([])
self.queue[depth].append(group)
def deq(self):
for stack in self.queue:
for idx, group in enumerate(reversed(stack)):
if group.breakables:
del stack[idx]
group.want_break = True
return group
for group in stack:
group.want_break = True
del stack[:]
def remove(self, group):
try:
self.queue[group.depth].remove(group)
except ValueError:
pass
def _default_pprint(obj, p, cycle):
klass = _safe_getattr(obj, '__class__', None) or type(obj)
if _safe_getattr(klass, '__repr__', None) is not object.__repr__:
_repr_pprint(obj, p, cycle)
return
p.begin_group(1, '<')
p.pretty(klass)
p.text(' at 0x%x' % id(obj))
if cycle:
p.text(' ...')
elif p.verbose:
first = True
for key in dir(obj):
if not key.startswith('_'):
try:
value = getattr(obj, key)
except AttributeError:
continue
if isinstance(value, types.MethodType):
continue
if not first:
p.text(',')
p.breakable()
p.text(key)
p.text('=')
step = len(key) + 1
p.indentation += step
p.pretty(value)
p.indentation -= step
first = False
p.end_group(1, '>')
def _seq_pprinter_factory(start, end):
def inner(obj, p, cycle):
if cycle:
return p.text(start + '...' + end)
step = len(start)
p.begin_group(step, start)
for idx, x in p._enumerate(obj):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
if len(obj) == 1 and type(obj) is tuple:
p.text(',')
p.end_group(step, end)
return inner
def _set_pprinter_factory(start, end):
def inner(obj, p, cycle):
if cycle:
return p.text(start + '...' + end)
if len(obj) == 0:
p.text(type(obj).__name__ + '()')
else:
step = len(start)
p.begin_group(step, start)
if not (p.max_seq_length and len(obj) >= p.max_seq_length):
items = _sorted_for_pprint(obj)
else:
items = obj
for idx, x in p._enumerate(items):
if idx:
p.text(',')
p.breakable()
p.pretty(x)
p.end_group(step, end)
return inner
def _dict_pprinter_factory(start, end):
def inner(obj, p, cycle):
if cycle:
return p.text('{...}')
step = len(start)
p.begin_group(step, start)
keys = obj.keys()
# if dict isn't large enough to be truncated, sort keys before displaying
if not DICT_IS_ORDERED \
and not (p.max_seq_length and len(obj) >= p.max_seq_length):
keys = _sorted_for_pprint(keys)
for idx, key in p._enumerate(keys):
if idx:
p.text(',')
p.breakable()
p.pretty(key)
p.text(': ')
p.pretty(obj[key])
p.end_group(step, end)
return inner
def _super_pprint(obj, p, cycle):
p.begin_group(8, '<super: ')
p.pretty(obj.__thisclass__)
p.text(',')
p.breakable()
if PYPY: # In PyPy, super() objects don't have __self__ attributes
dself = obj.__repr__.__self__
p.pretty(None if dself is obj else dself)
else:
p.pretty(obj.__self__)
p.end_group(8, '>')
def _re_pattern_pprint(obj, p, cycle):
p.text('re.compile(')
pattern = repr(obj.pattern)
if pattern[:1] in 'uU':
pattern = pattern[1:]
prefix = 'ur'
else:
prefix = 'r'
pattern = prefix + pattern.replace('\\\\', '\\')
p.text(pattern)
if obj.flags:
p.text(',')
p.breakable()
done_one = False
for flag in ('TEMPLATE', 'IGNORECASE', 'LOCALE', 'MULTILINE', 'DOTALL',
'UNICODE', 'VERBOSE', 'DEBUG'):
if obj.flags & getattr(re, flag):
if done_one:
p.text('|')
p.text('re.' + flag)
done_one = True
p.text(')')
def _type_pprint(obj, p, cycle):
# type(obj).__repr__ directly because in PyPy the representation function
# inherited from type isn't the same type.__repr__
if [m for m in _get_mro(type(obj)) if "__repr__" in vars(m)][:1] != [type]:
_repr_pprint(obj, p, cycle)
return
mod = _safe_getattr(obj, '__module__', None)
try:
name = obj.__qualname__
if not isinstance(name, str):
raise Exception("Try __name__")
except Exception:
name = obj.__name__
if not isinstance(name, str):
name = '<unknown type>'
if mod in (None, '__builtin__', 'builtins', 'exceptions'):
p.text(name)
else:
p.text(mod + '.' + name)
def _repr_pprint(obj, p, cycle):
output = repr(obj)
for idx,output_line in enumerate(output.splitlines()):
if idx:
p.break_()
p.text(output_line)
def _function_pprint(obj, p, cycle):
name = _safe_getattr(obj, '__qualname__', obj.__name__)
mod = obj.__module__
if mod and mod not in ('__builtin__', 'builtins', 'exceptions'):
name = mod + '.' + name
try:
func_def = name + str(signature(obj))
except ValueError:
func_def = name
p.text('<function %s>' % func_def)
def _exception_pprint(obj, p, cycle):
name = getattr(obj.__class__, '__qualname__', obj.__class__.__name__)
if obj.__class__.__module__ not in ('exceptions', 'builtins'):
name = '%s.%s' % (obj.__class__.__module__, name)
step = len(name) + 1
p.begin_group(step, name + '(')
for idx, arg in enumerate(getattr(obj, 'args', ())):
if idx:
p.text(',')
p.breakable()
p.pretty(arg)
p.end_group(step, ')')
try:
_exception_base = BaseException
except NameError:
_exception_base = Exception
_type_pprinters = {
int: _repr_pprint,
float: _repr_pprint,
str: _repr_pprint,
tuple: _seq_pprinter_factory('(', ')'),
list: _seq_pprinter_factory('[', ']'),
dict: _dict_pprinter_factory('{', '}'),
set: _set_pprinter_factory('{', '}'),
frozenset: _set_pprinter_factory('frozenset({', '})'),
super: _super_pprint,
_re_pattern_type: _re_pattern_pprint,
type: _type_pprint,
types.FunctionType: _function_pprint,
types.BuiltinFunctionType: _function_pprint,
types.MethodType: _repr_pprint,
datetime.datetime: _repr_pprint,
datetime.timedelta: _repr_pprint,
_exception_base: _exception_pprint
}
_env_type = type(os.environ)
if _env_type is not dict:
_type_pprinters[_env_type] = _dict_pprinter_factory('environ{', '}')
try:
_type_pprinters.setdefault(types.DictProxyType,
_dict_pprinter_factory('dict_proxy({', '})'))
_type_pprinters[types.ClassType] = _type_pprint
_type_pprinters[types.SliceType] = _repr_pprint
except AttributeError:
_type_pprinters[types.MappingProxyType] = \
_dict_pprinter_factory('mappingproxy({', '})')
_type_pprinters[slice] = _repr_pprint
try:
_type_pprinters[long] = _repr_pprint
_type_pprinters[unicode] = _repr_pprint
except NameError:
_type_pprinters[range] = _repr_pprint
_type_pprinters[bytes] = _repr_pprint
_deferred_type_pprinters = {
}
def for_type(typ, func):
oldfunc = _type_pprinters.get(typ, None)
if func is not None:
_type_pprinters[typ] = func
return oldfunc
def for_type_by_name(type_module, type_name, func):
key = (type_module, type_name)
oldfunc = _deferred_type_pprinters.get(key, None)
if func is not None:
_deferred_type_pprinters[key] = func
return oldfunc
_singleton_pprinters = dict.fromkeys(map(id, [None, True, False, Ellipsis,
NotImplemented]), _repr_pprint)
def _defaultdict_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(obj.default_factory)
p.text(',')
p.breakable()
p.pretty(dict(obj))
def _ordereddict_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(list(obj.items()))
def _deque_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
else:
p.pretty(list(obj))
def _counter_pprint(obj, p, cycle):
name = obj.__class__.__name__
with p.group(len(name) + 1, name + '(', ')'):
if cycle:
p.text('...')
elif len(obj):
p.pretty(dict(obj))
for_type_by_name('collections', 'defaultdict', _defaultdict_pprint)
for_type_by_name('collections', 'OrderedDict', _ordereddict_pprint)
for_type_by_name('collections', 'deque', _deque_pprint)
for_type_by_name('collections', 'Counter', _counter_pprint)
if __name__ == '__main__':
from random import randrange
class Foo(object):
def __init__(self):
self.foo = 1
self.bar = re.compile(r'\s+')
self.blub = dict.fromkeys(range(30), randrange(1, 40))
self.hehe = 23424.234234
self.list = ["blub", "blah", self]
def get_foo(self):
print("foo")
pprint(Foo(), verbose=True)
| true | true |
1c3e0c62fd5d4fd2b2c4c22ae84670c0a04b08a8 | 4,115 | py | Python | UI/CommandTypeEdit.py | mjbogusz/BTSerial | 141d37caaab860ba420c9584a2844c63bce401e3 | [
"MIT"
] | null | null | null | UI/CommandTypeEdit.py | mjbogusz/BTSerial | 141d37caaab860ba420c9584a2844c63bce401e3 | [
"MIT"
] | null | null | null | UI/CommandTypeEdit.py | mjbogusz/BTSerial | 141d37caaab860ba420c9584a2844c63bce401e3 | [
"MIT"
] | null | null | null | from PyQt5.QtWidgets import QDialog, QInputDialog
from Commands.CommandType import CommandType
from Layouts.CommandTypeEditWidget import Ui_BTSerialCommandTypeEditDialog
class CommandTypeEdit(QDialog):
textType = True
def __init__(self, parent = None, name = None, code = None, description = None, textType = True):
QDialog.__init__(self, parent)
self.ui = Ui_BTSerialCommandTypeEditDialog()
self.ui.setupUi(self)
self.setupUIActions()
self.applyValues(name, code, description, textType)
def setupUIActions(self):
self.ui.radioButtonText.toggled.connect(self.commandTypeToggled)
self.ui.toolButtonAddByte.clicked.connect(self.addItemByte)
self.ui.toolButtonAddParam.clicked.connect(self.addItemParam)
self.ui.toolButtonMoveDown.clicked.connect(self.moveItemDown)
self.ui.toolButtonMoveUp.clicked.connect(self.moveItemUp)
self.ui.toolButtonRemove.clicked.connect(self.removeItem)
self.ui.groupBoxCommandBytes.setVisible(False)
self.adjustSize()
def applyValues(self, name, code, description, textType):
if name is not None:
self.ui.lineEditName.setText(str(name))
if description is not None:
self.ui.lineEditDescription.setText(str(description))
self.textType = bool(textType)
if not self.textType:
self.ui.radioButtonByte.toggle()
if code is not None:
if self.textType:
self.ui.lineEditCodeString.setText(str(code))
else:
for i in range(len(code)):
if code[i] == '%':
self.ui.listWidgetBytes.addItem("%" + str(code[i+1]))
elif (i == 0) or (code[i-1] != '%'):
self.ui.listWidgetBytes.addItem(str(code[i]))
def commandTypeToggled(self, textType = True):
self.ui.lineEditCodeString.setVisible(textType)
self.ui.groupBoxCommandBytes.setVisible(not textType)
self.adjustSize()
self.textType = textType
def addItemByte(self):
inputOk = True
byteValue, inputOk = QInputDialog.getInt(self, "BTSerial - enter byte value", "Enter command byte value (0 - 255).", min = 0, max = 255)
if inputOk == False:
return
self.ui.listWidgetBytes.addItem(str(byteValue))
def addItemParam(self):
inputOk = True
paramLen, inputOk = QInputDialog.getInt(self, "BTSerial - enter byte value", "Enter param length in bytes (1 - 4).", min = 1, max = 4)
if inputOk == False:
return
self.ui.listWidgetBytes.addItem("%" + str(paramLen))
def moveItemDown(self):
count = self.ui.listWidgetBytes.count()
row = self.ui.listWidgetBytes.currentRow()
if (count <= 1) or (row == count - 1) or (row < 0):
return
commandItem = self.ui.listWidgetBytes.takeItem(row)
self.ui.listWidgetBytes.insertItem(row + 1, commandItem)
self.ui.listWidgetBytes.setCurrentRow(row + 1)
def moveItemUp(self):
count = self.ui.listWidgetBytes.count()
row = self.ui.listWidgetBytes.currentRow()
if (count <= 1) or (row <= 0):
return
commandItem = self.ui.listWidgetBytes.takeItem(row)
self.ui.listWidgetBytes.insertItem(row - 1, commandItem)
self.ui.listWidgetBytes.setCurrentRow(row - 1)
def removeItem(self):
row = self.ui.listWidgetBytes.currentRow()
if row == -1:
return
self.ui.listWidgetBytes.takeItem(row)
def getName(self):
return self.ui.lineEditName.text()
def getDescription(self):
return self.ui.lineEditDescription.text()
def getIstextType(self):
return self.ui.radioButtonText.isChecked()
def getCode(self):
if(self.getIstextType()):
return self.ui.lineEditCodeString.text()
else:
code = ""
for i in range(self.ui.listWidgetBytes.count()):
itemText = self.ui.listWidgetBytes.item(i).text()
if itemText[0] == '%':
code += itemText
else:
code += chr(int(itemText))
return code
@staticmethod
def getCommandType(parent = None, name = None, code = None, description = None, textType = True):
newCommandDialog = CommandTypeEdit(parent, name, code, description, textType)
accepted = newCommandDialog.exec_()
if accepted == QDialog.Rejected:
return (None, False)
name = newCommandDialog.getName()
code = newCommandDialog.getCode()
description = newCommandDialog.getDescription()
return (CommandType(name, code, description), True)
| 34.291667 | 138 | 0.730012 | from PyQt5.QtWidgets import QDialog, QInputDialog
from Commands.CommandType import CommandType
from Layouts.CommandTypeEditWidget import Ui_BTSerialCommandTypeEditDialog
class CommandTypeEdit(QDialog):
textType = True
def __init__(self, parent = None, name = None, code = None, description = None, textType = True):
QDialog.__init__(self, parent)
self.ui = Ui_BTSerialCommandTypeEditDialog()
self.ui.setupUi(self)
self.setupUIActions()
self.applyValues(name, code, description, textType)
def setupUIActions(self):
self.ui.radioButtonText.toggled.connect(self.commandTypeToggled)
self.ui.toolButtonAddByte.clicked.connect(self.addItemByte)
self.ui.toolButtonAddParam.clicked.connect(self.addItemParam)
self.ui.toolButtonMoveDown.clicked.connect(self.moveItemDown)
self.ui.toolButtonMoveUp.clicked.connect(self.moveItemUp)
self.ui.toolButtonRemove.clicked.connect(self.removeItem)
self.ui.groupBoxCommandBytes.setVisible(False)
self.adjustSize()
def applyValues(self, name, code, description, textType):
if name is not None:
self.ui.lineEditName.setText(str(name))
if description is not None:
self.ui.lineEditDescription.setText(str(description))
self.textType = bool(textType)
if not self.textType:
self.ui.radioButtonByte.toggle()
if code is not None:
if self.textType:
self.ui.lineEditCodeString.setText(str(code))
else:
for i in range(len(code)):
if code[i] == '%':
self.ui.listWidgetBytes.addItem("%" + str(code[i+1]))
elif (i == 0) or (code[i-1] != '%'):
self.ui.listWidgetBytes.addItem(str(code[i]))
def commandTypeToggled(self, textType = True):
self.ui.lineEditCodeString.setVisible(textType)
self.ui.groupBoxCommandBytes.setVisible(not textType)
self.adjustSize()
self.textType = textType
def addItemByte(self):
inputOk = True
byteValue, inputOk = QInputDialog.getInt(self, "BTSerial - enter byte value", "Enter command byte value (0 - 255).", min = 0, max = 255)
if inputOk == False:
return
self.ui.listWidgetBytes.addItem(str(byteValue))
def addItemParam(self):
inputOk = True
paramLen, inputOk = QInputDialog.getInt(self, "BTSerial - enter byte value", "Enter param length in bytes (1 - 4).", min = 1, max = 4)
if inputOk == False:
return
self.ui.listWidgetBytes.addItem("%" + str(paramLen))
def moveItemDown(self):
count = self.ui.listWidgetBytes.count()
row = self.ui.listWidgetBytes.currentRow()
if (count <= 1) or (row == count - 1) or (row < 0):
return
commandItem = self.ui.listWidgetBytes.takeItem(row)
self.ui.listWidgetBytes.insertItem(row + 1, commandItem)
self.ui.listWidgetBytes.setCurrentRow(row + 1)
def moveItemUp(self):
count = self.ui.listWidgetBytes.count()
row = self.ui.listWidgetBytes.currentRow()
if (count <= 1) or (row <= 0):
return
commandItem = self.ui.listWidgetBytes.takeItem(row)
self.ui.listWidgetBytes.insertItem(row - 1, commandItem)
self.ui.listWidgetBytes.setCurrentRow(row - 1)
def removeItem(self):
row = self.ui.listWidgetBytes.currentRow()
if row == -1:
return
self.ui.listWidgetBytes.takeItem(row)
def getName(self):
return self.ui.lineEditName.text()
def getDescription(self):
return self.ui.lineEditDescription.text()
def getIstextType(self):
return self.ui.radioButtonText.isChecked()
def getCode(self):
if(self.getIstextType()):
return self.ui.lineEditCodeString.text()
else:
code = ""
for i in range(self.ui.listWidgetBytes.count()):
itemText = self.ui.listWidgetBytes.item(i).text()
if itemText[0] == '%':
code += itemText
else:
code += chr(int(itemText))
return code
@staticmethod
def getCommandType(parent = None, name = None, code = None, description = None, textType = True):
newCommandDialog = CommandTypeEdit(parent, name, code, description, textType)
accepted = newCommandDialog.exec_()
if accepted == QDialog.Rejected:
return (None, False)
name = newCommandDialog.getName()
code = newCommandDialog.getCode()
description = newCommandDialog.getDescription()
return (CommandType(name, code, description), True)
| true | true |
1c3e0c75f4c827241f9bc863cb01c17d1d23dd11 | 1,271 | py | Python | test/test_user_interface.py | t-keazirian/tic-tac-toe | df557aaa6f01e3bfaf68dea96f9994bc3815067b | [
"MIT"
] | null | null | null | test/test_user_interface.py | t-keazirian/tic-tac-toe | df557aaa6f01e3bfaf68dea96f9994bc3815067b | [
"MIT"
] | 5 | 2022-03-18T19:07:56.000Z | 2022-03-25T17:00:50.000Z | test/test_user_interface.py | t-keazirian/tic-tac-toe | df557aaa6f01e3bfaf68dea96f9994bc3815067b | [
"MIT"
] | null | null | null | import unittest
from unittest.mock import patch
from src.user_interface import UserInterface
class TestUserInterface(unittest.TestCase):
@patch("builtins.print")
def test_display_message_prints_welcome_message_passed_in(self, mock_print):
user_interface = UserInterface()
message = "Welcome to Tic Tac Toe"
user_interface.display_message(message)
mock_print.assert_called_with("Welcome to Tic Tac Toe")
@patch("builtins.print")
def test_display_board_prints_board(self, mock_print):
user_interface = UserInterface()
board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
user_interface.display_board(board)
mock_print.assert_called_with(["1", "2", "3", "4", "5", "6", "7", "8", "9"])
@patch("builtins.input", side_effect=["3"])
def test_get_user_input_returns_input(self, mock_input):
user_interface = UserInterface()
result = user_interface.get_user_input()
self.assertEqual("3", result)
@patch("builtins.input", side_effect=["5"])
def test_gets_user_input_function_not_returning_false_positive(self, mock_input):
user_interface = UserInterface()
output = user_interface.get_user_input()
self.assertNotEqual(output, "3")
| 38.515152 | 85 | 0.685287 | import unittest
from unittest.mock import patch
from src.user_interface import UserInterface
class TestUserInterface(unittest.TestCase):
@patch("builtins.print")
def test_display_message_prints_welcome_message_passed_in(self, mock_print):
user_interface = UserInterface()
message = "Welcome to Tic Tac Toe"
user_interface.display_message(message)
mock_print.assert_called_with("Welcome to Tic Tac Toe")
@patch("builtins.print")
def test_display_board_prints_board(self, mock_print):
user_interface = UserInterface()
board = ["1", "2", "3", "4", "5", "6", "7", "8", "9"]
user_interface.display_board(board)
mock_print.assert_called_with(["1", "2", "3", "4", "5", "6", "7", "8", "9"])
@patch("builtins.input", side_effect=["3"])
def test_get_user_input_returns_input(self, mock_input):
user_interface = UserInterface()
result = user_interface.get_user_input()
self.assertEqual("3", result)
@patch("builtins.input", side_effect=["5"])
def test_gets_user_input_function_not_returning_false_positive(self, mock_input):
user_interface = UserInterface()
output = user_interface.get_user_input()
self.assertNotEqual(output, "3")
| true | true |
1c3e0c870e78906f9031bc7fd02077d893973103 | 208 | py | Python | arcade/sprite_list/__init__.py | Mr-Coxall/arcade | 7767e9c7d7395c0dd35479744052f18ac8c86679 | [
"MIT"
] | null | null | null | arcade/sprite_list/__init__.py | Mr-Coxall/arcade | 7767e9c7d7395c0dd35479744052f18ac8c86679 | [
"MIT"
] | null | null | null | arcade/sprite_list/__init__.py | Mr-Coxall/arcade | 7767e9c7d7395c0dd35479744052f18ac8c86679 | [
"MIT"
] | null | null | null | from .sprite_list import SpriteList
from .spatial_hash import (
get_closest_sprite,
check_for_collision,
check_for_collision_with_list,
get_sprites_at_point,
get_sprites_at_exact_point,
)
| 23.111111 | 35 | 0.793269 | from .sprite_list import SpriteList
from .spatial_hash import (
get_closest_sprite,
check_for_collision,
check_for_collision_with_list,
get_sprites_at_point,
get_sprites_at_exact_point,
)
| true | true |
1c3e1011b841b916457c3c5d7830debe6c5af1cb | 2,060 | py | Python | setup.py | SynetoNet/graphite-api | 97f48ba73f4e08296e6eb6edb357e4a83d229066 | [
"Apache-2.0"
] | null | null | null | setup.py | SynetoNet/graphite-api | 97f48ba73f4e08296e6eb6edb357e4a83d229066 | [
"Apache-2.0"
] | null | null | null | setup.py | SynetoNet/graphite-api | 97f48ba73f4e08296e6eb6edb357e4a83d229066 | [
"Apache-2.0"
] | null | null | null | # coding: utf-8
import sys
from setuptools import setup, find_packages
install_requires = [
'Flask',
'PyYAML',
'cairocffi',
'pyparsing',
'pytz',
'six',
'structlog',
'tzlocal',
]
if sys.version_info < (2, 7):
install_requires.append('importlib')
install_requires.append('logutils')
install_requires.append('ordereddict')
with open('README.rst') as f:
long_description = f.read()
setup(
name='graphite-api',
version='1.0.1',
url='https://github.com/brutasse/graphite-api',
author="Bruno Renié, based on Chris Davis's graphite-web",
author_email='bruno@renie.fr',
license='Apache Software License 2.0',
description=('Graphite-web, without the interface. '
'Just the rendering HTTP API.'),
long_description=long_description,
packages=find_packages(exclude=['tests']),
include_package_data=True,
install_requires=install_requires,
extras_require={
'sentry': ['raven[flask]'],
'cyanite': ['cyanite'],
'cache': ['Flask-Cache'],
'statsd': ['statsd'],
},
zip_safe=False,
platforms='any',
classifiers=(
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Flask',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Scientific/Engineering :: Visualization',
'Topic :: System :: Monitoring',
),
test_suite='tests',
)
| 30.294118 | 66 | 0.61068 |
import sys
from setuptools import setup, find_packages
install_requires = [
'Flask',
'PyYAML',
'cairocffi',
'pyparsing',
'pytz',
'six',
'structlog',
'tzlocal',
]
if sys.version_info < (2, 7):
install_requires.append('importlib')
install_requires.append('logutils')
install_requires.append('ordereddict')
with open('README.rst') as f:
long_description = f.read()
setup(
name='graphite-api',
version='1.0.1',
url='https://github.com/brutasse/graphite-api',
author="Bruno Renié, based on Chris Davis's graphite-web",
author_email='bruno@renie.fr',
license='Apache Software License 2.0',
description=('Graphite-web, without the interface. '
'Just the rendering HTTP API.'),
long_description=long_description,
packages=find_packages(exclude=['tests']),
include_package_data=True,
install_requires=install_requires,
extras_require={
'sentry': ['raven[flask]'],
'cyanite': ['cyanite'],
'cache': ['Flask-Cache'],
'statsd': ['statsd'],
},
zip_safe=False,
platforms='any',
classifiers=(
'Development Status :: 4 - Beta',
'Environment :: Web Environment',
'Framework :: Flask',
'Intended Audience :: Developers',
'Intended Audience :: System Administrators',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 2',
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
'Programming Language :: Python :: 3',
'Programming Language :: Python :: 3.2',
'Programming Language :: Python :: 3.3',
'Programming Language :: Python :: 3.4',
'Topic :: Scientific/Engineering :: Information Analysis',
'Topic :: Scientific/Engineering :: Visualization',
'Topic :: System :: Monitoring',
),
test_suite='tests',
)
| true | true |
1c3e103d8d9475f8cb7885293553b2416f9c9bf0 | 6,097 | py | Python | Lib/site-packages/PIL/SgiImagePlugin.py | F4Ruke/FF14FishingBot | 53f73b9db8a95b2b718a36a9746471046c45117d | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | Lib/site-packages/PIL/SgiImagePlugin.py | F4Ruke/FF14FishingBot | 53f73b9db8a95b2b718a36a9746471046c45117d | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | Lib/site-packages/PIL/SgiImagePlugin.py | F4Ruke/FF14FishingBot | 53f73b9db8a95b2b718a36a9746471046c45117d | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | #
# The Python Imaging Library.
# $Id$
#
# SGI image file handling
#
# See "The SGI Image File Format (Draft version 0.97)", Paul Haeberli.
# <ftp://ftp.sgi.com/graphics/SGIIMAGESPEC>
#
#
# History:
# 2017-22-07 mb Add RLE decompression
# 2016-16-10 mb Add save method without compression
# 1995-09-10 fl Created
#
# Copyright (c) 2016 by Mickael Bonfill.
# Copyright (c) 2008 by Karsten Hiddemann.
# Copyright (c) 1997 by Secret Labs AB.
# Copyright (c) 1995 by Fredrik Lundh.
#
# See the README file for information on usage and redistribution.
#
import os
import struct
from . import Image, ImageFile
from ._binary import i16be as i16
from ._binary import o8
def _accept(prefix):
return len(prefix) >= 2 and i16(prefix) == 474
MODES = {
(1, 1, 1): "L",
(1, 2, 1): "L",
(2, 1, 1): "L;16B",
(2, 2, 1): "L;16B",
(1, 3, 3): "RGB",
(2, 3, 3): "RGB;16B",
(1, 3, 4): "RGBA",
(2, 3, 4): "RGBA;16B",
}
##
# Image plugin for SGI images.
class SgiImageFile(ImageFile.ImageFile):
format = "SGI"
format_description = "SGI Image File Format"
def _open(self):
# HEAD
headlen = 512
s = self.fp.read(headlen)
if not _accept(s):
raise ValueError("Not an SGI image file")
# compression : verbatim or RLE
compression = s[2]
# bpc : 1 or 2 bytes (8bits or 16bits)
bpc = s[3]
# dimension : 1, 2 or 3 (depending on xsize, ysize and zsize)
dimension = i16(s, 4)
# xsize : width
xsize = i16(s, 6)
# ysize : HEIGHT
ysize = i16(s, 8)
# zsize : channels count
zsize = i16(s, 10)
# layout
layout = bpc, dimension, zsize
# determine mode from bits/zsize
rawmode = ""
try:
rawmode = MODES[layout]
except KeyError:
pass
if rawmode == "":
raise ValueError("Unsupported SGI image mode")
self._size = xsize, ysize
self.mode = rawmode.split(";")[0]
if self.mode == "RGB":
self.custom_mimetype = "image/rgb"
# orientation -1 : scanlines begins at the bottom-left corner
orientation = -1
# decoder info
if compression == 0:
pagesize = xsize * ysize * bpc
if bpc == 2:
self.tile = [
("SGI16", (0, 0) + self.size, headlen, (self.mode, 0, orientation))
]
else:
self.tile = []
offset = headlen
for layer in self.mode:
self.tile.append(
("raw", (0, 0) + self.size, offset, (layer, 0, orientation))
)
offset += pagesize
elif compression == 1:
self.tile = [
("sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc))
]
def _save(im, fp, filename):
if im.mode != "RGB" and im.mode != "RGBA" and im.mode != "L":
raise ValueError("Unsupported SGI image mode")
# Get the keyword arguments
info = im.encoderinfo
# Byte-per-pixel precision, 1 = 8bits per pixel
bpc = info.get("bpc", 1)
if bpc not in (1, 2):
raise ValueError("Unsupported number of bytes per pixel")
# Flip the image, since the origin of SGI file is the bottom-left corner
orientation = -1
# Define the file as SGI File Format
magicNumber = 474
# Run-Length Encoding Compression - Unsupported at this time
rle = 0
# Number of dimensions (x,y,z)
dim = 3
# X Dimension = width / Y Dimension = HEIGHT
x, y = im.size
if im.mode == "L" and y == 1:
dim = 1
elif im.mode == "L":
dim = 2
# Z Dimension: Number of channels
z = len(im.mode)
if dim == 1 or dim == 2:
z = 1
# assert we've got the right number of bands.
if len(im.getbands()) != z:
raise ValueError(
f"incorrect number of bands in SGI write: {z} vs {len(im.getbands())}"
)
# Minimum Byte value
pinmin = 0
# Maximum Byte value (255 = 8bits per pixel)
pinmax = 255
# Image name (79 characters max, truncated below in write)
imgName = os.path.splitext(os.path.basename(filename))[0]
imgName = imgName.encode("ascii", "ignore")
# Standard representation of pixel in the file
colormap = 0
fp.write(struct.pack(">h", magicNumber))
fp.write(o8(rle))
fp.write(o8(bpc))
fp.write(struct.pack(">H", dim))
fp.write(struct.pack(">H", x))
fp.write(struct.pack(">H", y))
fp.write(struct.pack(">H", z))
fp.write(struct.pack(">l", pinmin))
fp.write(struct.pack(">l", pinmax))
fp.write(struct.pack("4s", b"")) # dummy
fp.write(struct.pack("79s", imgName)) # truncates to 79 chars
fp.write(struct.pack("s", b"")) # force null byte after imgname
fp.write(struct.pack(">l", colormap))
fp.write(struct.pack("404s", b"")) # dummy
rawmode = "L"
if bpc == 2:
rawmode = "L;16B"
for channel in im.split():
fp.write(channel.tobytes("raw", rawmode, 0, orientation))
if hasattr(fp, "flush"):
fp.flush()
class SGI16Decoder(ImageFile.PyDecoder):
_pulls_fd = True
def decode(self, buffer):
rawmode, stride, orientation = self.args
pagesize = self.state.xsize * self.state.ysize
zsize = len(self.mode)
self.fd.seek(512)
for band in range(zsize):
channel = Image.new("L", (self.state.xsize, self.state.ysize))
channel.frombytes(
self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation
)
self.im.putband(channel.im, band)
return -1, 0
#
# registry
Image.register_decoder("SGI16", SGI16Decoder)
Image.register_open(SgiImageFile.format, SgiImageFile, _accept)
Image.register_save(SgiImageFile.format, _save)
Image.register_mime(SgiImageFile.format, "image/sgi")
Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])
# End of file
| 26.393939 | 87 | 0.567656 |
import os
import struct
from . import Image, ImageFile
from ._binary import i16be as i16
from ._binary import o8
def _accept(prefix):
return len(prefix) >= 2 and i16(prefix) == 474
MODES = {
(1, 1, 1): "L",
(1, 2, 1): "L",
(2, 1, 1): "L;16B",
(2, 2, 1): "L;16B",
(1, 3, 3): "RGB",
(2, 3, 3): "RGB;16B",
(1, 3, 4): "RGBA",
(2, 3, 4): "RGBA;16B",
}
class SgiImageFile(ImageFile.ImageFile):
format = "SGI"
format_description = "SGI Image File Format"
def _open(self):
headlen = 512
s = self.fp.read(headlen)
if not _accept(s):
raise ValueError("Not an SGI image file")
compression = s[2]
bpc = s[3]
dimension = i16(s, 4)
xsize = i16(s, 6)
ysize = i16(s, 8)
zsize = i16(s, 10)
layout = bpc, dimension, zsize
rawmode = ""
try:
rawmode = MODES[layout]
except KeyError:
pass
if rawmode == "":
raise ValueError("Unsupported SGI image mode")
self._size = xsize, ysize
self.mode = rawmode.split(";")[0]
if self.mode == "RGB":
self.custom_mimetype = "image/rgb"
orientation = -1
if compression == 0:
pagesize = xsize * ysize * bpc
if bpc == 2:
self.tile = [
("SGI16", (0, 0) + self.size, headlen, (self.mode, 0, orientation))
]
else:
self.tile = []
offset = headlen
for layer in self.mode:
self.tile.append(
("raw", (0, 0) + self.size, offset, (layer, 0, orientation))
)
offset += pagesize
elif compression == 1:
self.tile = [
("sgi_rle", (0, 0) + self.size, headlen, (rawmode, orientation, bpc))
]
def _save(im, fp, filename):
if im.mode != "RGB" and im.mode != "RGBA" and im.mode != "L":
raise ValueError("Unsupported SGI image mode")
info = im.encoderinfo
bpc = info.get("bpc", 1)
if bpc not in (1, 2):
raise ValueError("Unsupported number of bytes per pixel")
orientation = -1
magicNumber = 474
rle = 0
dim = 3
x, y = im.size
if im.mode == "L" and y == 1:
dim = 1
elif im.mode == "L":
dim = 2
z = len(im.mode)
if dim == 1 or dim == 2:
z = 1
if len(im.getbands()) != z:
raise ValueError(
f"incorrect number of bands in SGI write: {z} vs {len(im.getbands())}"
)
# Minimum Byte value
pinmin = 0
# Maximum Byte value (255 = 8bits per pixel)
pinmax = 255
# Image name (79 characters max, truncated below in write)
imgName = os.path.splitext(os.path.basename(filename))[0]
imgName = imgName.encode("ascii", "ignore")
# Standard representation of pixel in the file
colormap = 0
fp.write(struct.pack(">h", magicNumber))
fp.write(o8(rle))
fp.write(o8(bpc))
fp.write(struct.pack(">H", dim))
fp.write(struct.pack(">H", x))
fp.write(struct.pack(">H", y))
fp.write(struct.pack(">H", z))
fp.write(struct.pack(">l", pinmin))
fp.write(struct.pack(">l", pinmax))
fp.write(struct.pack("4s", b"")) # dummy
fp.write(struct.pack("79s", imgName)) # truncates to 79 chars
fp.write(struct.pack("s", b"")) # force null byte after imgname
fp.write(struct.pack(">l", colormap))
fp.write(struct.pack("404s", b"")) # dummy
rawmode = "L"
if bpc == 2:
rawmode = "L;16B"
for channel in im.split():
fp.write(channel.tobytes("raw", rawmode, 0, orientation))
if hasattr(fp, "flush"):
fp.flush()
class SGI16Decoder(ImageFile.PyDecoder):
_pulls_fd = True
def decode(self, buffer):
rawmode, stride, orientation = self.args
pagesize = self.state.xsize * self.state.ysize
zsize = len(self.mode)
self.fd.seek(512)
for band in range(zsize):
channel = Image.new("L", (self.state.xsize, self.state.ysize))
channel.frombytes(
self.fd.read(2 * pagesize), "raw", "L;16B", stride, orientation
)
self.im.putband(channel.im, band)
return -1, 0
#
# registry
Image.register_decoder("SGI16", SGI16Decoder)
Image.register_open(SgiImageFile.format, SgiImageFile, _accept)
Image.register_save(SgiImageFile.format, _save)
Image.register_mime(SgiImageFile.format, "image/sgi")
Image.register_extensions(SgiImageFile.format, [".bw", ".rgb", ".rgba", ".sgi"])
# End of file
| true | true |
1c3e1095736ca8d72a8d9945a79daf052743ef96 | 4,760 | py | Python | tests/test_validation.py | Pascal-Bliem/tox-block-api | 31bde9a018a6efdd7c887bfd5ef5f04f0a14fd8f | [
"MIT"
] | null | null | null | tests/test_validation.py | Pascal-Bliem/tox-block-api | 31bde9a018a6efdd7c887bfd5ef5f04f0a14fd8f | [
"MIT"
] | null | null | null | tests/test_validation.py | Pascal-Bliem/tox-block-api | 31bde9a018a6efdd7c887bfd5ef5f04f0a14fd8f | [
"MIT"
] | null | null | null | import json
def test_validate_multiple_inputs(flask_test_client):
# setup
no_list = 123
list_with_empty_string = ["a","","b"]
list_with_no_string = ["a",1,"b"]
empty_list = []
valid_list_of_strings = ["Hi","I'm","Pascal"]
# action
res_no_list = flask_test_client.post("/v1/make_predictions",
json={"input_data": no_list})
res_list_with_empty_string = flask_test_client.post("/v1/make_predictions",
json={"input_data": list_with_empty_string})
res_list_with_no_string = flask_test_client.post("/v1/make_predictions",
json={"input_data": list_with_no_string})
res_empty_list = flask_test_client.post("/v1/make_predictions",
json={"input_data": empty_list})
res_wrong_key = flask_test_client.post("/v1/make_predictions",
json={"wrong_key": valid_list_of_strings})
res_valid_list_of_strings = flask_test_client.post("/v1/make_predictions",
json={"input_data": valid_list_of_strings})
# assertions
assert res_no_list.status_code == 400
assert res_no_list.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The passed object is not a list of strings.</p>
"""
assert res_list_with_empty_string.status_code == 400
assert res_list_with_empty_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The list item at position 1 is an empty string.</p>
"""
assert res_list_with_no_string.status_code == 400
assert res_list_with_no_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The list item at position 1 is not a string.</p>
"""
assert res_empty_list.status_code == 400
assert res_empty_list.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: Passed an empty list.</p>
"""
assert res_wrong_key.status_code == 400
assert res_wrong_key.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: "The key 'input_data' was not found in the received JSON."</p>
"""
assert res_valid_list_of_strings.status_code == 200
valid_response = res_valid_list_of_strings.get_json()
api_version = valid_response.get("api_version", None)
model_version = valid_response.get("model_version", None)
predictions = valid_response.get("predictions", None)
assert not api_version is None
assert not model_version is None
assert not predictions is None
assert len(predictions) == len(valid_list_of_strings)
def test_validate_single_input(flask_test_client):
# setup
no_string = 123
empty_string = ""
valid_string = "Hi, I'm Pascal"
# action
res_no_string = flask_test_client.post("/v1/make_single_prediction",
json={"input_data": no_string})
res_empty_string = flask_test_client.post("/v1/make_single_prediction",
json={"input_data": empty_string})
res_valid_string = flask_test_client.post("/v1/make_single_prediction",
json={"input_data": valid_string})
# assertions
assert res_no_string.status_code == 400
assert res_no_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The passed object is not a string.</p>
"""
assert res_empty_string.status_code == 400
assert res_empty_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: Passed an empty string.</p>
"""
assert res_valid_string.status_code == 200
valid_response = res_valid_string.get_json()
api_version = valid_response.get("api_version", None)
model_version = valid_response.get("model_version", None)
predictions = valid_response.get("predictions", None)
assert not api_version is None
assert not model_version is None
assert not predictions is None | 45.769231 | 123 | 0.668908 | import json
def test_validate_multiple_inputs(flask_test_client):
no_list = 123
list_with_empty_string = ["a","","b"]
list_with_no_string = ["a",1,"b"]
empty_list = []
valid_list_of_strings = ["Hi","I'm","Pascal"]
# action
res_no_list = flask_test_client.post("/v1/make_predictions",
json={"input_data": no_list})
res_list_with_empty_string = flask_test_client.post("/v1/make_predictions",
json={"input_data": list_with_empty_string})
res_list_with_no_string = flask_test_client.post("/v1/make_predictions",
json={"input_data": list_with_no_string})
res_empty_list = flask_test_client.post("/v1/make_predictions",
json={"input_data": empty_list})
res_wrong_key = flask_test_client.post("/v1/make_predictions",
json={"wrong_key": valid_list_of_strings})
res_valid_list_of_strings = flask_test_client.post("/v1/make_predictions",
json={"input_data": valid_list_of_strings})
# assertions
assert res_no_list.status_code == 400
assert res_no_list.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The passed object is not a list of strings.</p>
"""
assert res_list_with_empty_string.status_code == 400
assert res_list_with_empty_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The list item at position 1 is an empty string.</p>
"""
assert res_list_with_no_string.status_code == 400
assert res_list_with_no_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The list item at position 1 is not a string.</p>
"""
assert res_empty_list.status_code == 400
assert res_empty_list.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: Passed an empty list.</p>
"""
assert res_wrong_key.status_code == 400
assert res_wrong_key.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: "The key 'input_data' was not found in the received JSON."</p>
"""
assert res_valid_list_of_strings.status_code == 200
valid_response = res_valid_list_of_strings.get_json()
api_version = valid_response.get("api_version", None)
model_version = valid_response.get("model_version", None)
predictions = valid_response.get("predictions", None)
assert not api_version is None
assert not model_version is None
assert not predictions is None
assert len(predictions) == len(valid_list_of_strings)
def test_validate_single_input(flask_test_client):
# setup
no_string = 123
empty_string = ""
valid_string = "Hi, I'm Pascal"
res_no_string = flask_test_client.post("/v1/make_single_prediction",
json={"input_data": no_string})
res_empty_string = flask_test_client.post("/v1/make_single_prediction",
json={"input_data": empty_string})
res_valid_string = flask_test_client.post("/v1/make_single_prediction",
json={"input_data": valid_string})
assert res_no_string.status_code == 400
assert res_no_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: The passed object is not a string.</p>
"""
assert res_empty_string.status_code == 400
assert res_empty_string.data == b"""<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>400 Bad Request</title>
<h1>Bad Request</h1>
<p>Errors occurred when validating the input data: Passed an empty string.</p>
"""
assert res_valid_string.status_code == 200
valid_response = res_valid_string.get_json()
api_version = valid_response.get("api_version", None)
model_version = valid_response.get("model_version", None)
predictions = valid_response.get("predictions", None)
assert not api_version is None
assert not model_version is None
assert not predictions is None | true | true |
1c3e119050a4066467abd713ce404ac251447abd | 3,734 | py | Python | unit_tests/shared_functions_unittests.py | NOAA-OWP/inundation-mapping | 1820af99d91cede1de1b618fb5bca77bdd3e4b42 | [
"Info-ZIP"
] | 2 | 2022-02-11T21:34:47.000Z | 2022-02-11T21:34:49.000Z | unit_tests/shared_functions_unittests.py | NOAA-OWP/inundation-mapping | 1820af99d91cede1de1b618fb5bca77bdd3e4b42 | [
"Info-ZIP"
] | 35 | 2022-02-04T15:36:57.000Z | 2022-03-30T21:13:11.000Z | unit_tests/shared_functions_unittests.py | NOAA-OWP/inundation-mapping | 1820af99d91cede1de1b618fb5bca77bdd3e4b42 | [
"Info-ZIP"
] | 4 | 2022-02-11T21:46:49.000Z | 2022-03-24T08:42:56.000Z | #!/usr/bin/env python3
import inspect
import os
import sys
import argparse
import json
import warnings
import unittest
import unit_tests_utils as helpers
# importing python folders in other directories
sys.path.append('/foss_fim/src/utils')
import shared_functions as src
# NOTE: This goes directly to the function.
# Ultimately, it should emulate going through command line (not import -> direct function call)
class test_shared_functions(unittest.TestCase):
'''
Allows the params to be loaded one and used for all test methods
'''
@classmethod
def setUpClass(self):
warnings.simplefilter('ignore')
params_file_path = '/foss_fim/unit_tests/shared_functions_params.json'
with open(params_file_path) as params_file:
self.params = json.load(params_file)
def test_append_id_to_file_name_single_identifier_success(self):
'''
Pass in a file name with the single identifier and get the single adjusted file name back
'''
#global params_file
helpers.print_unit_test_function_header()
params = self.params["append_append_id_to_file_name_single_identifier_valid"].copy()
expected_output = "/output/myfolder/a_raster_13090001.tif"
actual_output = src.append_id_to_file_name(file_name = params["file_name"],
identifier = params["identifier"])
err_msg = "actual output does not match expected output"
self.assertEqual(expected_output, actual_output, err_msg)
print(f"Test Success: {inspect.currentframe().f_code.co_name}")
print("*************************************************************")
def test_append_id_to_file_name_indentifer_list_success(self):
'''
Pass in a file name with the list of identifiers and get a file name back with multiple identifers added
'''
#global params_file
helpers.print_unit_test_function_header()
params = self.params["append_append_id_to_file_name_identifier_list_valid"].copy()
expected_output = "/output/myfolder/a_raster_13090001_05010204.tif"
actual_output = src.append_id_to_file_name(file_name = params["file_name"],
identifier = params["identifier"])
#print(actual_output)
err_msg = "actual output does not match expected output"
self.assertEqual(expected_output, actual_output, err_msg)
print(f"Test Success: {inspect.currentframe().f_code.co_name}")
print("*************************************************************")
def test_append_id_to_file_name_no_file_name_success(self):
'''
Pass in an non existant file name and get None back
'''
#global params_file
helpers.print_unit_test_function_header()
params = self.params["append_append_id_to_file_name_single_identifier_valid"].copy()
actual_output = src.append_id_to_file_name(None,
identifier = params["identifier"])
if (actual_output is not None):
raise Exception("actual output should not have a value")
print(f"Test Success: {inspect.currentframe().f_code.co_name}")
print("*************************************************************")
if __name__ == '__main__':
script_file_name = os.path.basename(__file__)
print("*****************************")
print(f"Start of {script_file_name} tests")
print()
unittest.main()
print()
print(f"End of {script_file_name} tests")
| 31.91453 | 112 | 0.616229 |
import inspect
import os
import sys
import argparse
import json
import warnings
import unittest
import unit_tests_utils as helpers
sys.path.append('/foss_fim/src/utils')
import shared_functions as src
class test_shared_functions(unittest.TestCase):
@classmethod
def setUpClass(self):
warnings.simplefilter('ignore')
params_file_path = '/foss_fim/unit_tests/shared_functions_params.json'
with open(params_file_path) as params_file:
self.params = json.load(params_file)
def test_append_id_to_file_name_single_identifier_success(self):
helpers.print_unit_test_function_header()
params = self.params["append_append_id_to_file_name_single_identifier_valid"].copy()
expected_output = "/output/myfolder/a_raster_13090001.tif"
actual_output = src.append_id_to_file_name(file_name = params["file_name"],
identifier = params["identifier"])
err_msg = "actual output does not match expected output"
self.assertEqual(expected_output, actual_output, err_msg)
print(f"Test Success: {inspect.currentframe().f_code.co_name}")
print("*************************************************************")
def test_append_id_to_file_name_indentifer_list_success(self):
helpers.print_unit_test_function_header()
params = self.params["append_append_id_to_file_name_identifier_list_valid"].copy()
expected_output = "/output/myfolder/a_raster_13090001_05010204.tif"
actual_output = src.append_id_to_file_name(file_name = params["file_name"],
identifier = params["identifier"])
err_msg = "actual output does not match expected output"
self.assertEqual(expected_output, actual_output, err_msg)
print(f"Test Success: {inspect.currentframe().f_code.co_name}")
print("*************************************************************")
def test_append_id_to_file_name_no_file_name_success(self):
helpers.print_unit_test_function_header()
params = self.params["append_append_id_to_file_name_single_identifier_valid"].copy()
actual_output = src.append_id_to_file_name(None,
identifier = params["identifier"])
if (actual_output is not None):
raise Exception("actual output should not have a value")
print(f"Test Success: {inspect.currentframe().f_code.co_name}")
print("*************************************************************")
if __name__ == '__main__':
script_file_name = os.path.basename(__file__)
print("*****************************")
print(f"Start of {script_file_name} tests")
print()
unittest.main()
print()
print(f"End of {script_file_name} tests")
| true | true |
1c3e12b5ec7e97e8a36c17cdf57ad8beb2b7828d | 558 | py | Python | problems/problem39.py | nolanwrightdev/blind-75-python | b92ef3449eb0143c760ddd339897a3f0a2972830 | [
"MIT"
] | 6 | 2020-02-01T23:29:51.000Z | 2022-02-20T20:46:56.000Z | problems/problem39.py | nolanwrightdev/blind-75-python | b92ef3449eb0143c760ddd339897a3f0a2972830 | [
"MIT"
] | null | null | null | problems/problem39.py | nolanwrightdev/blind-75-python | b92ef3449eb0143c760ddd339897a3f0a2972830 | [
"MIT"
] | null | null | null | '''
Blind Curated 75 - Problem 39
=============================
Find Minimum in Rotated Sorted Array
------------
Find the minimum element of an array sorted in ascending order but subsequently
rotated at some unknown pivot.
[→ LeetCode][1]
[1]: https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/
'''
def solution(nums):
'''
Perform a simple binary search.
'''
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
| 19.241379 | 79 | 0.625448 |
def solution(nums):
left, right = 0, len(nums) - 1
while left < right:
mid = (left + right) // 2
if nums[mid] > nums[right]:
left = mid + 1
else:
right = mid
return nums[left]
| true | true |
1c3e131d6b733d9550a9bf60e9bd68c91290d5f5 | 2,555 | py | Python | fix-requirements.py | geekinutah/docker-openstack-keystone-mitaka | 1b2ef17d916bd83bce36bd22a74dab9a2d1bef08 | [
"MIT"
] | null | null | null | fix-requirements.py | geekinutah/docker-openstack-keystone-mitaka | 1b2ef17d916bd83bce36bd22a74dab9a2d1bef08 | [
"MIT"
] | null | null | null | fix-requirements.py | geekinutah/docker-openstack-keystone-mitaka | 1b2ef17d916bd83bce36bd22a74dab9a2d1bef08 | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import re
import argparse
import sys
from os import unlink
from shutil import copyfile
def get_vers(lines=[]):
version_map = {}
#lines look like this: alabaster (0.7.6)
r = re.compile('^(.+)\ \((.+)\)')
for l in lines:
m = r.match(l)
version_map[m.group(1)] = m.group(2)
return version_map
def fix_reqs(requirements, version_map, die_on_errors=False):
to_return = []
split_chars = re.compile('\<|\!|\>|\=')
valid_version = re.compile('^(\d+)+(\.\d+)?(\.\d+)?$')
for r in requirements:
result = split_chars.split(r)
if result[0] in version_map:
#This means that we need to replace it with what is in version_map
to_return.append('%s==%s' % (result[0], version_map[result[0]]))
if not valid_version.search(version_map[result[0]]):
sys.stderr.write("ERROR: Authoritative versions has %s for package" \
" %s. This will most likely break things!\n" %
(version_map[result[0]], result[0]))
if die_on_errors:
sys.exit(1)
else:
sys.stderr.write("ERROR: '%s' found in requirements, but not in" \
" authoritative map!\n" % result[0].rstrip())
to_return.append(r.rstrip())
if die_on_errors:
sys.exit(1)
return to_return
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--requirements_file', default='requirements.txt',
help='Path to a pip style requirements.txt file.')
parser.add_argument('--map_file', default='libs.vers',
help='The output of `pip list` from some authoritative source.')
parser.add_argument('--inplace', default=False, action='store_true',
help='Used to modify REQUIREMENTS_FILE in-place. Creates a backup.')
parser.add_argument('--no_ignore_errors', default=False, action='store_true',
help='Stop execution instead of just printing errors.')
args = parser.parse_args()
map_file = open(args.map_file, 'r')
req_file = open(args.requirements_file, 'r')
vs = get_vers(map_file.readlines())
new_reqs = fix_reqs(req_file.readlines(), vs, args.no_ignore_errors)
if args.inplace is True:
req_file.close()
copyfile(args.requirements_file, '%s~' % args.requirements_file)
unlink(args.requirements_file)
f = open(args.requirements_file,'w')
for l in new_reqs:
f.write('%s\n' % l)
f.close()
else:
for i in new_reqs:
print(i)
| 32.75641 | 79 | 0.642661 |
import re
import argparse
import sys
from os import unlink
from shutil import copyfile
def get_vers(lines=[]):
version_map = {}
r = re.compile('^(.+)\ \((.+)\)')
for l in lines:
m = r.match(l)
version_map[m.group(1)] = m.group(2)
return version_map
def fix_reqs(requirements, version_map, die_on_errors=False):
to_return = []
split_chars = re.compile('\<|\!|\>|\=')
valid_version = re.compile('^(\d+)+(\.\d+)?(\.\d+)?$')
for r in requirements:
result = split_chars.split(r)
if result[0] in version_map:
to_return.append('%s==%s' % (result[0], version_map[result[0]]))
if not valid_version.search(version_map[result[0]]):
sys.stderr.write("ERROR: Authoritative versions has %s for package" \
" %s. This will most likely break things!\n" %
(version_map[result[0]], result[0]))
if die_on_errors:
sys.exit(1)
else:
sys.stderr.write("ERROR: '%s' found in requirements, but not in" \
" authoritative map!\n" % result[0].rstrip())
to_return.append(r.rstrip())
if die_on_errors:
sys.exit(1)
return to_return
if __name__ == '__main__':
parser = argparse.ArgumentParser(
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument('--requirements_file', default='requirements.txt',
help='Path to a pip style requirements.txt file.')
parser.add_argument('--map_file', default='libs.vers',
help='The output of `pip list` from some authoritative source.')
parser.add_argument('--inplace', default=False, action='store_true',
help='Used to modify REQUIREMENTS_FILE in-place. Creates a backup.')
parser.add_argument('--no_ignore_errors', default=False, action='store_true',
help='Stop execution instead of just printing errors.')
args = parser.parse_args()
map_file = open(args.map_file, 'r')
req_file = open(args.requirements_file, 'r')
vs = get_vers(map_file.readlines())
new_reqs = fix_reqs(req_file.readlines(), vs, args.no_ignore_errors)
if args.inplace is True:
req_file.close()
copyfile(args.requirements_file, '%s~' % args.requirements_file)
unlink(args.requirements_file)
f = open(args.requirements_file,'w')
for l in new_reqs:
f.write('%s\n' % l)
f.close()
else:
for i in new_reqs:
print(i)
| true | true |
1c3e1651db307de81ae66cc41cae8fbdf44bba86 | 13,906 | py | Python | tsdf/tsdf.py | changgyhub/semantic-tsdf | 4767d92a768af577f75ab05229c9fc87dda9681e | [
"BSD-2-Clause"
] | 9 | 2020-05-07T14:50:20.000Z | 2021-12-03T16:20:34.000Z | tsdf/tsdf.py | irsisyphus/semantic-tsdf | 4767d92a768af577f75ab05229c9fc87dda9681e | [
"BSD-2-Clause"
] | 1 | 2020-11-16T02:10:30.000Z | 2020-11-17T06:40:03.000Z | tsdf/tsdf.py | irsisyphus/semantic-tsdf | 4767d92a768af577f75ab05229c9fc87dda9681e | [
"BSD-2-Clause"
] | 1 | 2020-11-15T18:30:02.000Z | 2020-11-15T18:30:02.000Z | '''
TSDF fusion.
'''
import numpy as np
from skimage import measure
try:
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
TSDF_GPU_MODE = 1
except Exception as err:
print('Warning: %s'%(str(err)))
print('Failed to import PyCUDA. Running tsdf fusion in CPU mode.')
TSDF_GPU_MODE = 0
class TSDFVolume(object):
def __init__(self, vol_bnds, voxel_size):
# Define voxel volume parameters.
self._vol_bnds = vol_bnds # 3x2, rows: (x, y, z), columns: (min, max) in world coordinates in meters
self._voxel_size = voxel_size # in meters (determines volume discretization and resolution)
self._trunc_margin = self._voxel_size * 5 # truncation on SDF
# Adjust volume bounds.
self._vol_dim = np.ceil((self._vol_bnds[:, 1] - self._vol_bnds[:, 0]) / self._voxel_size).copy(order='C').astype(int) # ensure C-order contigous
self._vol_bnds[:,1] = self._vol_bnds[:, 0] + self._vol_dim * self._voxel_size
self._vol_origin = self._vol_bnds[:, 0].copy(order='C').astype(np.float32) # ensure C-order contigous
print("Voxel volume size: {:d} x {:d} x {:d}".format(self._vol_dim[0], self._vol_dim[1], self._vol_dim[2]))
# Initialize pointers to voxel volume in CPU memory.
self._tsdf_vol_cpu = np.ones(self._vol_dim).astype(np.float32)
self._weight_vol_cpu = np.zeros(self._vol_dim).astype(np.float32) # for computing the cumulative moving average of observations per voxel
self._color_vol_cpu = np.zeros(self._vol_dim).astype(np.float32)
# Copy voxel volumes to GPU.
if TSDF_GPU_MODE:
self._tsdf_vol_gpu = cuda.mem_alloc(self._tsdf_vol_cpu.nbytes)
cuda.memcpy_htod(self._tsdf_vol_gpu,self._tsdf_vol_cpu)
self._weight_vol_gpu = cuda.mem_alloc(self._weight_vol_cpu.nbytes)
cuda.memcpy_htod(self._weight_vol_gpu,self._weight_vol_cpu)
self._color_vol_gpu = cuda.mem_alloc(self._color_vol_cpu.nbytes)
cuda.memcpy_htod(self._color_vol_gpu,self._color_vol_cpu)
# Cuda kernel function (C++)
self._cuda_src_mod = SourceModule("""
__global__ void integrate(float * tsdf_vol,
float * weight_vol,
float * color_vol,
float * vol_dim,
float * vol_origin,
float * cam_intr,
float * cam_pose,
float * other_params,
float * color_im,
float * depth_im) {
// Get voxel index.
int gpu_loop_idx = (int) other_params[0];
int max_threads_per_block = blockDim.x;
int block_idx = blockIdx.z * gridDim.y * gridDim.x + blockIdx.y * gridDim.x + blockIdx.x;
int voxel_idx = gpu_loop_idx * gridDim.x * gridDim.y * gridDim.z * max_threads_per_block + block_idx * max_threads_per_block + threadIdx.x;
int vol_dim_x = (int)vol_dim[0];
int vol_dim_y = (int)vol_dim[1];
int vol_dim_z = (int)vol_dim[2];
if (voxel_idx > vol_dim_x * vol_dim_y * vol_dim_z)
return;
// Get voxel grid coordinates.
float voxel_x = floorf(((float)voxel_idx) / ((float)(vol_dim_y * vol_dim_z)));
float voxel_y = floorf(((float)(voxel_idx - ((int)voxel_x) * vol_dim_y * vol_dim_z)) / ((float)vol_dim_z));
float voxel_z = (float)(voxel_idx - ((int)voxel_x) * vol_dim_y * vol_dim_z - ((int)voxel_y) * vol_dim_z);
// Voxel grid coordinates to world coordinates.
float voxel_size = other_params[1];
float pt_x = vol_origin[0] + voxel_x * voxel_size;
float pt_y = vol_origin[1] + voxel_y * voxel_size;
float pt_z = vol_origin[2] + voxel_z * voxel_size;
// World coordinates to camera coordinates.
float tmp_pt_x = pt_x - cam_pose[0*4+3];
float tmp_pt_y = pt_y - cam_pose[1*4+3];
float tmp_pt_z = pt_z - cam_pose[2*4+3];
float cam_pt_x = cam_pose[0*4+0] * tmp_pt_x + cam_pose[1*4+0] * tmp_pt_y + cam_pose[2*4+0] * tmp_pt_z;
float cam_pt_y = cam_pose[0*4+1] * tmp_pt_x + cam_pose[1*4+1] * tmp_pt_y + cam_pose[2*4+1] * tmp_pt_z;
float cam_pt_z = cam_pose[0*4+2] * tmp_pt_x + cam_pose[1*4+2] * tmp_pt_y + cam_pose[2*4+2] * tmp_pt_z;
// Camera coordinates to image pixels.
int pixel_x = (int) roundf(cam_intr[0*3+0] * (cam_pt_x / cam_pt_z) + cam_intr[0*3+2]);
int pixel_y = (int) roundf(cam_intr[1*3+1] * (cam_pt_y / cam_pt_z) + cam_intr[1*3+2]);
// Skip if outside view frustum.
int im_h = (int) other_params[2];
int im_w = (int) other_params[3];
if (pixel_x < 0 || pixel_x >= im_w || pixel_y < 0 || pixel_y >= im_h || cam_pt_z < 0)
return;
// Skip invalid depth.
float depth_value = depth_im[pixel_y*im_w+pixel_x];
if (depth_value == 0)
return;
// Integrate TSDF.
float trunc_margin = other_params[4];
float depth_diff = depth_value-cam_pt_z;
if (depth_diff < -trunc_margin)
return;
float dist = fmin(1.0f, depth_diff / trunc_margin);
float w_old = weight_vol[voxel_idx];
float obs_weight = other_params[5];
float w_new = w_old + obs_weight;
weight_vol[voxel_idx] = w_new;
tsdf_vol[voxel_idx] = (tsdf_vol[voxel_idx] * w_old + dist) / w_new;
// Integrate color.
float old_color = color_vol[voxel_idx];
float old_b = floorf(old_color / (256 * 256));
float old_g = floorf((old_color - old_b * 256 * 256) / 256);
float old_r = old_color - old_b * 256 * 256 - old_g * 256;
float new_color = color_im[pixel_y*im_w+pixel_x];
float new_b = floorf(new_color / (256 * 256));
float new_g = floorf((new_color - new_b * 256 * 256) / 256);
float new_r = new_color - new_b * 256 * 256 - new_g * 256;
new_b = fmin(roundf((old_b*w_old + new_b) / w_new), 255.0f);
new_g = fmin(roundf((old_g*w_old + new_g) / w_new), 255.0f);
new_r = fmin(roundf((old_r*w_old + new_r) / w_new), 255.0f);
color_vol[voxel_idx] = new_b * 256 * 256 + new_g * 256 + new_r;
}""")
self._cuda_integrate = self._cuda_src_mod.get_function("integrate")
# Determine block/grid size on GPU.
gpu_dev = cuda.Device(0)
self._max_gpu_threads_per_block = gpu_dev.MAX_THREADS_PER_BLOCK
n_blocks = int(np.ceil(float(np.prod(self._vol_dim)) / float(self._max_gpu_threads_per_block)))
grid_dim_x = min(gpu_dev.MAX_GRID_DIM_X, int(np.floor(np.cbrt(n_blocks))))
grid_dim_y = min(gpu_dev.MAX_GRID_DIM_Y, int(np.floor(np.sqrt(n_blocks / grid_dim_x))))
grid_dim_z = min(gpu_dev.MAX_GRID_DIM_Z, int(np.ceil(float(n_blocks) / float(grid_dim_x*grid_dim_y))))
self._max_gpu_grid_dim = np.array([grid_dim_x, grid_dim_y, grid_dim_z]).astype(int)
self._n_gpu_loops = int(np.ceil(float(np.prod(self._vol_dim)) / float(np.prod(self._max_gpu_grid_dim) * self._max_gpu_threads_per_block)))
def integrate(self,color_im,depth_im,cam_intr,cam_pose,obs_weight=1.):
im_h = depth_im.shape[0]
im_w = depth_im.shape[1]
# Fold RGB color image into a single channel image.
color_im = color_im.astype(np.float32)
color_im = np.floor(color_im[:, :, 2] * 256 * 256 + color_im[:, :, 1] * 256 + color_im[:, :, 0])
# GPU mode: integrate voxel volume (calls CUDA kernel).
if TSDF_GPU_MODE:
for gpu_loop_idx in range(self._n_gpu_loops):
self._cuda_integrate(self._tsdf_vol_gpu,
self._weight_vol_gpu,
self._color_vol_gpu,
cuda.InOut(self._vol_dim.astype(np.float32)),
cuda.InOut(self._vol_origin.astype(np.float32)),
cuda.InOut(cam_intr.reshape(-1).astype(np.float32)),
cuda.InOut(cam_pose.reshape(-1).astype(np.float32)),
cuda.InOut(np.asarray([gpu_loop_idx, self._voxel_size, im_h, im_w, self._trunc_margin, obs_weight], np.float32)),
cuda.InOut(color_im.reshape(-1).astype(np.float32)),
cuda.InOut(depth_im.reshape(-1).astype(np.float32)),
block=(self._max_gpu_threads_per_block, 1, 1), grid=(int(self._max_gpu_grid_dim[0]), int(self._max_gpu_grid_dim[1]), int(self._max_gpu_grid_dim[2])))
# CPU mode: integrate voxel volume (vectorized implementation).
else:
# Get voxel grid coordinates.
xv, yv, zv = np.meshgrid(range(self._vol_dim[0]), range(self._vol_dim[1]), range(self._vol_dim[2]), indexing='ij')
vox_coords = np.concatenate((xv.reshape(1, -1), yv.reshape(1, -1), zv.reshape(1, -1)), axis=0).astype(int)
# Voxel coordinates to world coordinates.
world_pts = self._vol_origin.reshape(-1, 1) + vox_coords.astype(float) * self._voxel_size
# World coordinates to camera coordinates.
world2cam = np.linalg.inv(cam_pose)
cam_pts = np.dot(world2cam[:3, :3], world_pts) + np.tile(world2cam[:3, 3].reshape(3, 1), (1, world_pts.shape[1]))
# Camera coordinates to image pixels.
pix_x = np.round(cam_intr[0, 0] * (cam_pts[0, :] / cam_pts[2, :]) + cam_intr[0, 2]).astype(int)
pix_y = np.round(cam_intr[1, 1] * (cam_pts[1, :] / cam_pts[2, :]) + cam_intr[1, 2]).astype(int)
# Skip if outside view frustum.
valid_pix = np.logical_and(pix_x >= 0,
np.logical_and(pix_x < im_w,
np.logical_and(pix_y >= 0,
np.logical_and(pix_y < im_h,
cam_pts[2,:] > 0))))
depth_val = np.zeros(pix_x.shape)
depth_val[valid_pix] = depth_im[pix_y[valid_pix], pix_x[valid_pix]]
# Integrate TSDF.
depth_diff = depth_val - cam_pts[2,:]
valid_pts = np.logical_and(depth_val > 0, depth_diff >= -self._trunc_margin)
dist = np.minimum(1., np.divide(depth_diff, self._trunc_margin))
w_old = self._weight_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]]
w_new = w_old + obs_weight
self._weight_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]] = w_new
tsdf_vals = self._tsdf_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]]
self._tsdf_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]] = np.divide(np.multiply(tsdf_vals, w_old) + dist[valid_pts], w_new)
# Integrate color.
old_color = self._color_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]]
old_b = np.floor(old_color / (256. * 256.))
old_g = np.floor((old_color - old_b * 256. * 256.) / 256.)
old_r = old_color - old_b * 256. * 256. - old_g * 256.
new_color = color_im[pix_y[valid_pts], pix_x[valid_pts]]
new_b = np.floor(new_color / (256. * 256.))
new_g = np.floor((new_color - new_b * 256. * 256.) / 256.)
new_r = new_color - new_b * 256. * 256. - new_g * 256.
new_b = np.minimum(np.round(np.divide(np.multiply(old_b, w_old) + new_b, w_new)), 255.)
new_g = np.minimum(np.round(np.divide(np.multiply(old_g, w_old) + new_g, w_new)), 255.)
new_r = np.minimum(np.round(np.divide(np.multiply(old_r, w_old) + new_r, w_new)), 255.)
self._color_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]] = new_b * 256. * 256. + new_g * 256. + new_r
# Copy voxel volume to CPU.
def get_volume(self):
if TSDF_GPU_MODE:
cuda.memcpy_dtoh(self._tsdf_vol_cpu, self._tsdf_vol_gpu)
cuda.memcpy_dtoh(self._color_vol_cpu, self._color_vol_gpu)
return self._tsdf_vol_cpu, self._color_vol_cpu
# Get mesh of voxel volume via marching cubes.
def get_mesh(self):
tsdf_vol, color_vol = self.get_volume()
# Marching cubes.
verts, faces, norms, _ = measure.marching_cubes_lewiner(tsdf_vol, level=0)
verts_ind = np.round(verts).astype(int)
verts = verts * self._voxel_size + self._vol_origin # voxel grid coordinates to world coordinates
# Get vertex colors.
rgb_vals = color_vol[verts_ind[:, 0], verts_ind[:, 1], verts_ind[:, 2]]
colors_b = np.floor(rgb_vals / (256 * 256))
colors_g = np.floor((rgb_vals - colors_b * 256 * 256) / 256)
colors_r = rgb_vals - colors_b * 256 * 256 - colors_g * 256
colors = np.floor(np.asarray([colors_r, colors_g, colors_b])).T
colors = colors.astype(np.uint8)
return verts, faces, norms, colors
| 56.299595 | 186 | 0.577161 |
import numpy as np
from skimage import measure
try:
import pycuda.driver as cuda
import pycuda.autoinit
from pycuda.compiler import SourceModule
TSDF_GPU_MODE = 1
except Exception as err:
print('Warning: %s'%(str(err)))
print('Failed to import PyCUDA. Running tsdf fusion in CPU mode.')
TSDF_GPU_MODE = 0
class TSDFVolume(object):
def __init__(self, vol_bnds, voxel_size):
self._vol_bnds = vol_bnds
self._voxel_size = voxel_size
self._trunc_margin = self._voxel_size * 5
self._vol_dim = np.ceil((self._vol_bnds[:, 1] - self._vol_bnds[:, 0]) / self._voxel_size).copy(order='C').astype(int)
self._vol_bnds[:,1] = self._vol_bnds[:, 0] + self._vol_dim * self._voxel_size
self._vol_origin = self._vol_bnds[:, 0].copy(order='C').astype(np.float32)
print("Voxel volume size: {:d} x {:d} x {:d}".format(self._vol_dim[0], self._vol_dim[1], self._vol_dim[2]))
self._tsdf_vol_cpu = np.ones(self._vol_dim).astype(np.float32)
self._weight_vol_cpu = np.zeros(self._vol_dim).astype(np.float32)
self._color_vol_cpu = np.zeros(self._vol_dim).astype(np.float32)
if TSDF_GPU_MODE:
self._tsdf_vol_gpu = cuda.mem_alloc(self._tsdf_vol_cpu.nbytes)
cuda.memcpy_htod(self._tsdf_vol_gpu,self._tsdf_vol_cpu)
self._weight_vol_gpu = cuda.mem_alloc(self._weight_vol_cpu.nbytes)
cuda.memcpy_htod(self._weight_vol_gpu,self._weight_vol_cpu)
self._color_vol_gpu = cuda.mem_alloc(self._color_vol_cpu.nbytes)
cuda.memcpy_htod(self._color_vol_gpu,self._color_vol_cpu)
self._cuda_src_mod = SourceModule("""
__global__ void integrate(float * tsdf_vol,
float * weight_vol,
float * color_vol,
float * vol_dim,
float * vol_origin,
float * cam_intr,
float * cam_pose,
float * other_params,
float * color_im,
float * depth_im) {
// Get voxel index.
int gpu_loop_idx = (int) other_params[0];
int max_threads_per_block = blockDim.x;
int block_idx = blockIdx.z * gridDim.y * gridDim.x + blockIdx.y * gridDim.x + blockIdx.x;
int voxel_idx = gpu_loop_idx * gridDim.x * gridDim.y * gridDim.z * max_threads_per_block + block_idx * max_threads_per_block + threadIdx.x;
int vol_dim_x = (int)vol_dim[0];
int vol_dim_y = (int)vol_dim[1];
int vol_dim_z = (int)vol_dim[2];
if (voxel_idx > vol_dim_x * vol_dim_y * vol_dim_z)
return;
// Get voxel grid coordinates.
float voxel_x = floorf(((float)voxel_idx) / ((float)(vol_dim_y * vol_dim_z)));
float voxel_y = floorf(((float)(voxel_idx - ((int)voxel_x) * vol_dim_y * vol_dim_z)) / ((float)vol_dim_z));
float voxel_z = (float)(voxel_idx - ((int)voxel_x) * vol_dim_y * vol_dim_z - ((int)voxel_y) * vol_dim_z);
// Voxel grid coordinates to world coordinates.
float voxel_size = other_params[1];
float pt_x = vol_origin[0] + voxel_x * voxel_size;
float pt_y = vol_origin[1] + voxel_y * voxel_size;
float pt_z = vol_origin[2] + voxel_z * voxel_size;
// World coordinates to camera coordinates.
float tmp_pt_x = pt_x - cam_pose[0*4+3];
float tmp_pt_y = pt_y - cam_pose[1*4+3];
float tmp_pt_z = pt_z - cam_pose[2*4+3];
float cam_pt_x = cam_pose[0*4+0] * tmp_pt_x + cam_pose[1*4+0] * tmp_pt_y + cam_pose[2*4+0] * tmp_pt_z;
float cam_pt_y = cam_pose[0*4+1] * tmp_pt_x + cam_pose[1*4+1] * tmp_pt_y + cam_pose[2*4+1] * tmp_pt_z;
float cam_pt_z = cam_pose[0*4+2] * tmp_pt_x + cam_pose[1*4+2] * tmp_pt_y + cam_pose[2*4+2] * tmp_pt_z;
// Camera coordinates to image pixels.
int pixel_x = (int) roundf(cam_intr[0*3+0] * (cam_pt_x / cam_pt_z) + cam_intr[0*3+2]);
int pixel_y = (int) roundf(cam_intr[1*3+1] * (cam_pt_y / cam_pt_z) + cam_intr[1*3+2]);
// Skip if outside view frustum.
int im_h = (int) other_params[2];
int im_w = (int) other_params[3];
if (pixel_x < 0 || pixel_x >= im_w || pixel_y < 0 || pixel_y >= im_h || cam_pt_z < 0)
return;
// Skip invalid depth.
float depth_value = depth_im[pixel_y*im_w+pixel_x];
if (depth_value == 0)
return;
// Integrate TSDF.
float trunc_margin = other_params[4];
float depth_diff = depth_value-cam_pt_z;
if (depth_diff < -trunc_margin)
return;
float dist = fmin(1.0f, depth_diff / trunc_margin);
float w_old = weight_vol[voxel_idx];
float obs_weight = other_params[5];
float w_new = w_old + obs_weight;
weight_vol[voxel_idx] = w_new;
tsdf_vol[voxel_idx] = (tsdf_vol[voxel_idx] * w_old + dist) / w_new;
// Integrate color.
float old_color = color_vol[voxel_idx];
float old_b = floorf(old_color / (256 * 256));
float old_g = floorf((old_color - old_b * 256 * 256) / 256);
float old_r = old_color - old_b * 256 * 256 - old_g * 256;
float new_color = color_im[pixel_y*im_w+pixel_x];
float new_b = floorf(new_color / (256 * 256));
float new_g = floorf((new_color - new_b * 256 * 256) / 256);
float new_r = new_color - new_b * 256 * 256 - new_g * 256;
new_b = fmin(roundf((old_b*w_old + new_b) / w_new), 255.0f);
new_g = fmin(roundf((old_g*w_old + new_g) / w_new), 255.0f);
new_r = fmin(roundf((old_r*w_old + new_r) / w_new), 255.0f);
color_vol[voxel_idx] = new_b * 256 * 256 + new_g * 256 + new_r;
}""")
self._cuda_integrate = self._cuda_src_mod.get_function("integrate")
gpu_dev = cuda.Device(0)
self._max_gpu_threads_per_block = gpu_dev.MAX_THREADS_PER_BLOCK
n_blocks = int(np.ceil(float(np.prod(self._vol_dim)) / float(self._max_gpu_threads_per_block)))
grid_dim_x = min(gpu_dev.MAX_GRID_DIM_X, int(np.floor(np.cbrt(n_blocks))))
grid_dim_y = min(gpu_dev.MAX_GRID_DIM_Y, int(np.floor(np.sqrt(n_blocks / grid_dim_x))))
grid_dim_z = min(gpu_dev.MAX_GRID_DIM_Z, int(np.ceil(float(n_blocks) / float(grid_dim_x*grid_dim_y))))
self._max_gpu_grid_dim = np.array([grid_dim_x, grid_dim_y, grid_dim_z]).astype(int)
self._n_gpu_loops = int(np.ceil(float(np.prod(self._vol_dim)) / float(np.prod(self._max_gpu_grid_dim) * self._max_gpu_threads_per_block)))
def integrate(self,color_im,depth_im,cam_intr,cam_pose,obs_weight=1.):
im_h = depth_im.shape[0]
im_w = depth_im.shape[1]
color_im = color_im.astype(np.float32)
color_im = np.floor(color_im[:, :, 2] * 256 * 256 + color_im[:, :, 1] * 256 + color_im[:, :, 0])
if TSDF_GPU_MODE:
for gpu_loop_idx in range(self._n_gpu_loops):
self._cuda_integrate(self._tsdf_vol_gpu,
self._weight_vol_gpu,
self._color_vol_gpu,
cuda.InOut(self._vol_dim.astype(np.float32)),
cuda.InOut(self._vol_origin.astype(np.float32)),
cuda.InOut(cam_intr.reshape(-1).astype(np.float32)),
cuda.InOut(cam_pose.reshape(-1).astype(np.float32)),
cuda.InOut(np.asarray([gpu_loop_idx, self._voxel_size, im_h, im_w, self._trunc_margin, obs_weight], np.float32)),
cuda.InOut(color_im.reshape(-1).astype(np.float32)),
cuda.InOut(depth_im.reshape(-1).astype(np.float32)),
block=(self._max_gpu_threads_per_block, 1, 1), grid=(int(self._max_gpu_grid_dim[0]), int(self._max_gpu_grid_dim[1]), int(self._max_gpu_grid_dim[2])))
else:
xv, yv, zv = np.meshgrid(range(self._vol_dim[0]), range(self._vol_dim[1]), range(self._vol_dim[2]), indexing='ij')
vox_coords = np.concatenate((xv.reshape(1, -1), yv.reshape(1, -1), zv.reshape(1, -1)), axis=0).astype(int)
world_pts = self._vol_origin.reshape(-1, 1) + vox_coords.astype(float) * self._voxel_size
world2cam = np.linalg.inv(cam_pose)
cam_pts = np.dot(world2cam[:3, :3], world_pts) + np.tile(world2cam[:3, 3].reshape(3, 1), (1, world_pts.shape[1]))
pix_x = np.round(cam_intr[0, 0] * (cam_pts[0, :] / cam_pts[2, :]) + cam_intr[0, 2]).astype(int)
pix_y = np.round(cam_intr[1, 1] * (cam_pts[1, :] / cam_pts[2, :]) + cam_intr[1, 2]).astype(int)
valid_pix = np.logical_and(pix_x >= 0,
np.logical_and(pix_x < im_w,
np.logical_and(pix_y >= 0,
np.logical_and(pix_y < im_h,
cam_pts[2,:] > 0))))
depth_val = np.zeros(pix_x.shape)
depth_val[valid_pix] = depth_im[pix_y[valid_pix], pix_x[valid_pix]]
depth_diff = depth_val - cam_pts[2,:]
valid_pts = np.logical_and(depth_val > 0, depth_diff >= -self._trunc_margin)
dist = np.minimum(1., np.divide(depth_diff, self._trunc_margin))
w_old = self._weight_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]]
w_new = w_old + obs_weight
self._weight_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]] = w_new
tsdf_vals = self._tsdf_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]]
self._tsdf_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]] = np.divide(np.multiply(tsdf_vals, w_old) + dist[valid_pts], w_new)
old_color = self._color_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]]
old_b = np.floor(old_color / (256. * 256.))
old_g = np.floor((old_color - old_b * 256. * 256.) / 256.)
old_r = old_color - old_b * 256. * 256. - old_g * 256.
new_color = color_im[pix_y[valid_pts], pix_x[valid_pts]]
new_b = np.floor(new_color / (256. * 256.))
new_g = np.floor((new_color - new_b * 256. * 256.) / 256.)
new_r = new_color - new_b * 256. * 256. - new_g * 256.
new_b = np.minimum(np.round(np.divide(np.multiply(old_b, w_old) + new_b, w_new)), 255.)
new_g = np.minimum(np.round(np.divide(np.multiply(old_g, w_old) + new_g, w_new)), 255.)
new_r = np.minimum(np.round(np.divide(np.multiply(old_r, w_old) + new_r, w_new)), 255.)
self._color_vol_cpu[vox_coords[0, valid_pts], vox_coords[1, valid_pts], vox_coords[2, valid_pts]] = new_b * 256. * 256. + new_g * 256. + new_r
def get_volume(self):
if TSDF_GPU_MODE:
cuda.memcpy_dtoh(self._tsdf_vol_cpu, self._tsdf_vol_gpu)
cuda.memcpy_dtoh(self._color_vol_cpu, self._color_vol_gpu)
return self._tsdf_vol_cpu, self._color_vol_cpu
def get_mesh(self):
tsdf_vol, color_vol = self.get_volume()
verts, faces, norms, _ = measure.marching_cubes_lewiner(tsdf_vol, level=0)
verts_ind = np.round(verts).astype(int)
verts = verts * self._voxel_size + self._vol_origin
rgb_vals = color_vol[verts_ind[:, 0], verts_ind[:, 1], verts_ind[:, 2]]
colors_b = np.floor(rgb_vals / (256 * 256))
colors_g = np.floor((rgb_vals - colors_b * 256 * 256) / 256)
colors_r = rgb_vals - colors_b * 256 * 256 - colors_g * 256
colors = np.floor(np.asarray([colors_r, colors_g, colors_b])).T
colors = colors.astype(np.uint8)
return verts, faces, norms, colors
| true | true |
1c3e169c43cdac142a1f05ac316cda7f81e2b59b | 2,997 | py | Python | YoloV3 SIMS/utils/bbox.py | bostankhan6/Object-Detection-YoloV3-RetinaNet-FasterRCNN | 81b79063f6ec5a76960018bdc1c37b17ce12dc67 | [
"MIT"
] | 4 | 2020-05-23T21:56:11.000Z | 2021-12-06T10:54:43.000Z | YoloV3 SIMS/utils/bbox.py | bostankhan6/Object-Detection-YoloV3-RetinaNet-FasterRCNN | 81b79063f6ec5a76960018bdc1c37b17ce12dc67 | [
"MIT"
] | 5 | 2020-09-26T01:05:55.000Z | 2022-02-10T01:31:21.000Z | YoloV3 SIMS/utils/bbox.py | bostankhan6/Object-Detection-YoloV3-RetinaNet-FasterRCNN | 81b79063f6ec5a76960018bdc1c37b17ce12dc67 | [
"MIT"
] | 1 | 2021-03-10T10:58:00.000Z | 2021-03-10T10:58:00.000Z | import numpy as np
import os
import cv2
from .colors import get_color
class BoundBox:
def __init__(self, xmin, ymin, xmax, ymax, c = None, classes = None):
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
self.c = c
self.classes = classes
self.label = -1
self.score = -1
def get_label(self):
if self.label == -1:
self.label = np.argmax(self.classes)
return self.label
def get_score(self):
if self.score == -1:
self.score = self.classes[self.get_label()]
return self.score
def _interval_overlap(interval_a, interval_b):
x1, x2 = interval_a
x3, x4 = interval_b
if x3 < x1:
if x4 < x1:
return 0
else:
return min(x2,x4) - x1
else:
if x2 < x3:
return 0
else:
return min(x2,x4) - x3
def bbox_iou(box1, box2):
intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax])
intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax])
intersect = intersect_w * intersect_h
w1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin
w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin
union = w1*h1 + w2*h2 - intersect
return float(intersect) / union
def draw_boxes(image, boxes, labels, obj_thresh, quiet=True):
for box in boxes:
label_str = ''
label = -1
for i in range(len(labels)):
if box.classes[i] > obj_thresh:
if label_str != '': label_str += ', '
label_str += (labels[i] + ' ' + str(round(box.get_score()*100, 2)) + '%')
label = i
if not quiet: print(label_str)
if label >= 0:
text_size = cv2.getTextSize(label_str, cv2.FONT_HERSHEY_SIMPLEX, 1.1e-3 * image.shape[0], 5)
width, height = text_size[0][0], text_size[0][1]
region = np.array([[box.xmin-3, box.ymin],
[box.xmin-3, box.ymin-height-26],
[box.xmin+width+13, box.ymin-height-26],
[box.xmin+width+13, box.ymin]], dtype='int32')
cv2.rectangle(img=image, pt1=(box.xmin,box.ymin), pt2=(box.xmax,box.ymax), color=get_color(label), thickness=5)
cv2.fillPoly(img=image, pts=[region], color=get_color(label))
cv2.putText(img=image,
text=label_str,
org=(box.xmin+13, box.ymin - 13),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1e-3 * image.shape[0],
color=(0,0,0),
thickness=2)
return image | 33.674157 | 124 | 0.495162 | import numpy as np
import os
import cv2
from .colors import get_color
class BoundBox:
def __init__(self, xmin, ymin, xmax, ymax, c = None, classes = None):
self.xmin = xmin
self.ymin = ymin
self.xmax = xmax
self.ymax = ymax
self.c = c
self.classes = classes
self.label = -1
self.score = -1
def get_label(self):
if self.label == -1:
self.label = np.argmax(self.classes)
return self.label
def get_score(self):
if self.score == -1:
self.score = self.classes[self.get_label()]
return self.score
def _interval_overlap(interval_a, interval_b):
x1, x2 = interval_a
x3, x4 = interval_b
if x3 < x1:
if x4 < x1:
return 0
else:
return min(x2,x4) - x1
else:
if x2 < x3:
return 0
else:
return min(x2,x4) - x3
def bbox_iou(box1, box2):
intersect_w = _interval_overlap([box1.xmin, box1.xmax], [box2.xmin, box2.xmax])
intersect_h = _interval_overlap([box1.ymin, box1.ymax], [box2.ymin, box2.ymax])
intersect = intersect_w * intersect_h
w1, h1 = box1.xmax-box1.xmin, box1.ymax-box1.ymin
w2, h2 = box2.xmax-box2.xmin, box2.ymax-box2.ymin
union = w1*h1 + w2*h2 - intersect
return float(intersect) / union
def draw_boxes(image, boxes, labels, obj_thresh, quiet=True):
for box in boxes:
label_str = ''
label = -1
for i in range(len(labels)):
if box.classes[i] > obj_thresh:
if label_str != '': label_str += ', '
label_str += (labels[i] + ' ' + str(round(box.get_score()*100, 2)) + '%')
label = i
if not quiet: print(label_str)
if label >= 0:
text_size = cv2.getTextSize(label_str, cv2.FONT_HERSHEY_SIMPLEX, 1.1e-3 * image.shape[0], 5)
width, height = text_size[0][0], text_size[0][1]
region = np.array([[box.xmin-3, box.ymin],
[box.xmin-3, box.ymin-height-26],
[box.xmin+width+13, box.ymin-height-26],
[box.xmin+width+13, box.ymin]], dtype='int32')
cv2.rectangle(img=image, pt1=(box.xmin,box.ymin), pt2=(box.xmax,box.ymax), color=get_color(label), thickness=5)
cv2.fillPoly(img=image, pts=[region], color=get_color(label))
cv2.putText(img=image,
text=label_str,
org=(box.xmin+13, box.ymin - 13),
fontFace=cv2.FONT_HERSHEY_SIMPLEX,
fontScale=1e-3 * image.shape[0],
color=(0,0,0),
thickness=2)
return image | true | true |
1c3e1708ed91858e89b23f3225922ba20d396cb2 | 418 | py | Python | ray_tracer/tests/test_lights.py | jjason/RayTracerChallenge | ab3cea8968407426bddfa9e11319664fc0b595f6 | [
"MIT"
] | 1 | 2020-05-13T03:54:00.000Z | 2020-05-13T03:54:00.000Z | ray_tracer/tests/test_lights.py | jjason/RayTracerChallenge | ab3cea8968407426bddfa9e11319664fc0b595f6 | [
"MIT"
] | null | null | null | ray_tracer/tests/test_lights.py | jjason/RayTracerChallenge | ab3cea8968407426bddfa9e11319664fc0b595f6 | [
"MIT"
] | null | null | null | import unittest
from color import Color
from lights import PointLight
from point import Point
class TestPointLight(unittest.TestCase):
def test_create(self):
p = Point(x=0, y=0, z=0)
i = Color(red=1, green=1, blue=1)
l = PointLight(position=p, intensity=i)
self.assertEqual(p, l.position)
self.assertEqual(i, l.intensity)
if __name__ == '__main__':
unittest.main()
| 22 | 47 | 0.662679 | import unittest
from color import Color
from lights import PointLight
from point import Point
class TestPointLight(unittest.TestCase):
def test_create(self):
p = Point(x=0, y=0, z=0)
i = Color(red=1, green=1, blue=1)
l = PointLight(position=p, intensity=i)
self.assertEqual(p, l.position)
self.assertEqual(i, l.intensity)
if __name__ == '__main__':
unittest.main()
| true | true |
1c3e17e0fd18466449bd191129c98cee3777bac0 | 184 | py | Python | configs/fp16/pspnet_r101-d8_512x1024_80k_fp16_cityscapes.py | vietawake/mmSegmentation | 1f643d6d81708ebf5726c48f66d02c70fe99fe00 | [
"Apache-2.0"
] | null | null | null | configs/fp16/pspnet_r101-d8_512x1024_80k_fp16_cityscapes.py | vietawake/mmSegmentation | 1f643d6d81708ebf5726c48f66d02c70fe99fe00 | [
"Apache-2.0"
] | null | null | null | configs/fp16/pspnet_r101-d8_512x1024_80k_fp16_cityscapes.py | vietawake/mmSegmentation | 1f643d6d81708ebf5726c48f66d02c70fe99fe00 | [
"Apache-2.0"
] | null | null | null | _base_ = '../pspnet/pspnet_r101-d8_512x1024_80k_cityscapes.py'
# fp16 settings
optimizer_config = dict(type='Fp16OptimizerHook', loss_scale=512.)
# fp16 placeholder
fp16 = dict()
| 30.666667 | 67 | 0.76087 | _base_ = '../pspnet/pspnet_r101-d8_512x1024_80k_cityscapes.py'
optimizer_config = dict(type='Fp16OptimizerHook', loss_scale=512.)
fp16 = dict()
| true | true |
1c3e1874abca09d7b3e122e2d6b52a8efec05ea1 | 97,128 | py | Python | mitogen/parent.py | percygrunwald/mitogen | 99c5cece3a69381cb02cf861d53045c8ea7e5369 | [
"BSD-3-Clause"
] | 4 | 2019-12-04T06:02:18.000Z | 2019-12-18T05:38:44.000Z | mitogen/parent.py | percygrunwald/mitogen | 99c5cece3a69381cb02cf861d53045c8ea7e5369 | [
"BSD-3-Clause"
] | 12 | 2020-05-13T18:56:22.000Z | 2021-12-21T17:51:11.000Z | mitogen/parent.py | eamanu/python-mitogen | e93c7aae83b130abe1ef2dcf829d32e40f9fe8b1 | [
"BSD-3-Clause"
] | 6 | 2020-05-13T12:08:41.000Z | 2021-03-31T21:40:57.000Z | # Copyright 2019, David Wilson
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
# this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
# this list of conditions and the following disclaimer in the documentation
# and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
# !mitogen: minify_safe
"""
This module defines functionality common to master and parent processes. It is
sent to any child context that is due to become a parent, due to recursive
connection.
"""
import codecs
import errno
import fcntl
import getpass
import heapq
import inspect
import logging
import os
import re
import signal
import socket
import struct
import subprocess
import sys
import termios
import textwrap
import threading
import zlib
# Absolute imports for <2.5.
select = __import__('select')
try:
import thread
except ImportError:
import threading as thread
import mitogen.core
from mitogen.core import b
from mitogen.core import bytes_partition
from mitogen.core import IOLOG
LOG = logging.getLogger(__name__)
# #410: we must avoid the use of socketpairs if SELinux is enabled.
try:
fp = open('/sys/fs/selinux/enforce', 'rb')
try:
SELINUX_ENABLED = bool(int(fp.read()))
finally:
fp.close()
except IOError:
SELINUX_ENABLED = False
try:
next
except NameError:
# Python 2.4/2.5
from mitogen.core import next
itervalues = getattr(dict, 'itervalues', dict.values)
if mitogen.core.PY3:
xrange = range
closure_attr = '__closure__'
IM_SELF_ATTR = '__self__'
else:
closure_attr = 'func_closure'
IM_SELF_ATTR = 'im_self'
try:
SC_OPEN_MAX = os.sysconf('SC_OPEN_MAX')
except ValueError:
SC_OPEN_MAX = 1024
BROKER_SHUTDOWN_MSG = (
'Connection cancelled because the associated Broker began to shut down.'
)
OPENPTY_MSG = (
"Failed to create a PTY: %s. It is likely the maximum number of PTYs has "
"been reached. Consider increasing the 'kern.tty.ptmx_max' sysctl on OS "
"X, the 'kernel.pty.max' sysctl on Linux, or modifying your configuration "
"to avoid PTY use."
)
SYS_EXECUTABLE_MSG = (
"The Python sys.executable variable is unset, indicating Python was "
"unable to determine its original program name. Unless explicitly "
"configured otherwise, child contexts will be started using "
"'/usr/bin/python'"
)
_sys_executable_warning_logged = False
def _ioctl_cast(n):
"""
Linux ioctl() request parameter is unsigned, whereas on BSD/Darwin it is
signed. Until 2.5 Python exclusively implemented the BSD behaviour,
preventing use of large unsigned int requests like the TTY layer uses
below. So on 2.4, we cast our unsigned to look like signed for Python.
"""
if sys.version_info < (2, 5):
n, = struct.unpack('i', struct.pack('I', n))
return n
# If not :data:`None`, called prior to exec() of any new child process. Used by
# :func:`mitogen.utils.reset_affinity` to allow the child to be freely
# scheduled.
_preexec_hook = None
# Get PTY number; asm-generic/ioctls.h
LINUX_TIOCGPTN = _ioctl_cast(2147767344)
# Lock/unlock PTY; asm-generic/ioctls.h
LINUX_TIOCSPTLCK = _ioctl_cast(1074025521)
IS_LINUX = os.uname()[0] == 'Linux'
SIGNAL_BY_NUM = dict(
(getattr(signal, name), name)
for name in sorted(vars(signal), reverse=True)
if name.startswith('SIG') and not name.startswith('SIG_')
)
_core_source_lock = threading.Lock()
_core_source_partial = None
def get_log_level():
return (LOG.getEffectiveLevel() or logging.INFO)
def get_sys_executable():
"""
Return :data:`sys.executable` if it is set, otherwise return
``"/usr/bin/python"`` and log a warning.
"""
if sys.executable:
return sys.executable
global _sys_executable_warning_logged
if not _sys_executable_warning_logged:
LOG.warn(SYS_EXECUTABLE_MSG)
_sys_executable_warning_logged = True
return '/usr/bin/python'
def _get_core_source():
"""
In non-masters, simply fetch the cached mitogen.core source code via the
import mechanism. In masters, this function is replaced with a version that
performs minification directly.
"""
return inspect.getsource(mitogen.core)
def get_core_source_partial():
"""
_get_core_source() is expensive, even with @lru_cache in minify.py, threads
can enter it simultaneously causing severe slowdowns.
"""
global _core_source_partial
if _core_source_partial is None:
_core_source_lock.acquire()
try:
if _core_source_partial is None:
_core_source_partial = PartialZlib(
_get_core_source().encode('utf-8')
)
finally:
_core_source_lock.release()
return _core_source_partial
def get_default_remote_name():
"""
Return the default name appearing in argv[0] of remote machines.
"""
s = u'%s@%s:%d'
s %= (getpass.getuser(), socket.gethostname(), os.getpid())
# In mixed UNIX/Windows environments, the username may contain slashes.
return s.translate({
ord(u'\\'): ord(u'_'),
ord(u'/'): ord(u'_')
})
def is_immediate_child(msg, stream):
"""
Handler policy that requires messages to arrive only from immediately
connected children.
"""
return msg.src_id == stream.protocol.remote_id
def flags(names):
"""
Return the result of ORing a set of (space separated) :py:mod:`termios`
module constants together.
"""
return sum(getattr(termios, name, 0)
for name in names.split())
def cfmakeraw(tflags):
"""
Given a list returned by :py:func:`termios.tcgetattr`, return a list
modified in a manner similar to the `cfmakeraw()` C library function, but
additionally disabling local echo.
"""
# BSD: github.com/freebsd/freebsd/blob/master/lib/libc/gen/termios.c#L162
# Linux: github.com/lattera/glibc/blob/master/termios/cfmakeraw.c#L20
iflag, oflag, cflag, lflag, ispeed, ospeed, cc = tflags
iflag &= ~flags('IMAXBEL IXOFF INPCK BRKINT PARMRK '
'ISTRIP INLCR ICRNL IXON IGNPAR')
iflag &= ~flags('IGNBRK BRKINT PARMRK')
oflag &= ~flags('OPOST')
lflag &= ~flags('ECHO ECHOE ECHOK ECHONL ICANON ISIG '
'IEXTEN NOFLSH TOSTOP PENDIN')
cflag &= ~flags('CSIZE PARENB')
cflag |= flags('CS8 CREAD')
return [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
def disable_echo(fd):
old = termios.tcgetattr(fd)
new = cfmakeraw(old)
flags = getattr(termios, 'TCSASOFT', 0)
if not mitogen.core.IS_WSL:
# issue #319: Windows Subsystem for Linux as of July 2018 throws EINVAL
# if TCSAFLUSH is specified.
flags |= termios.TCSAFLUSH
termios.tcsetattr(fd, flags, new)
def create_socketpair(size=None):
"""
Create a :func:`socket.socketpair` for use as a child's UNIX stdio
channels. As socketpairs are bidirectional, they are economical on file
descriptor usage as one descriptor can be used for ``stdin`` and
``stdout``. As they are sockets their buffers are tunable, allowing large
buffers to improve file transfer throughput and reduce IO loop iterations.
"""
if size is None:
size = mitogen.core.CHUNK_SIZE
parentfp, childfp = socket.socketpair()
for fp in parentfp, childfp:
fp.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, size)
return parentfp, childfp
def create_best_pipe(escalates_privilege=False):
"""
By default we prefer to communicate with children over a UNIX socket, as a
single file descriptor can represent bidirectional communication, and a
cross-platform API exists to align buffer sizes with the needs of the
library.
SELinux prevents us setting up a privileged process to inherit an AF_UNIX
socket, a facility explicitly designed as a better replacement for pipes,
because at some point in the mid 90s it might have been commonly possible
for AF_INET sockets to end up undesirably connected to a privileged
process, so let's make up arbitrary rules breaking all sockets instead.
If SELinux is detected, fall back to using pipes.
:param bool escalates_privilege:
If :data:`True`, the target program may escalate privileges, causing
SELinux to disconnect AF_UNIX sockets, so avoid those.
:returns:
`(parent_rfp, child_wfp, child_rfp, parent_wfp)`
"""
if (not escalates_privilege) or (not SELINUX_ENABLED):
parentfp, childfp = create_socketpair()
return parentfp, childfp, childfp, parentfp
parent_rfp, child_wfp = mitogen.core.pipe()
try:
child_rfp, parent_wfp = mitogen.core.pipe()
return parent_rfp, child_wfp, child_rfp, parent_wfp
except:
parent_rfp.close()
child_wfp.close()
raise
def popen(**kwargs):
"""
Wrap :class:`subprocess.Popen` to ensure any global :data:`_preexec_hook`
is invoked in the child.
"""
real_preexec_fn = kwargs.pop('preexec_fn', None)
def preexec_fn():
if _preexec_hook:
_preexec_hook()
if real_preexec_fn:
real_preexec_fn()
return subprocess.Popen(preexec_fn=preexec_fn, **kwargs)
def create_child(args, merge_stdio=False, stderr_pipe=False,
escalates_privilege=False, preexec_fn=None):
"""
Create a child process whose stdin/stdout is connected to a socket.
:param list args:
Program argument vector.
:param bool merge_stdio:
If :data:`True`, arrange for `stderr` to be connected to the `stdout`
socketpair, rather than inherited from the parent process. This may be
necessary to ensure that no TTY is connected to any stdio handle, for
instance when using LXC.
:param bool stderr_pipe:
If :data:`True` and `merge_stdio` is :data:`False`, arrange for
`stderr` to be connected to a separate pipe, to allow any ongoing debug
logs generated by e.g. SSH to be output as the session progresses,
without interfering with `stdout`.
:param bool escalates_privilege:
If :data:`True`, the target program may escalate privileges, causing
SELinux to disconnect AF_UNIX sockets, so avoid those.
:param function preexec_fn:
If not :data:`None`, a function to run within the post-fork child
before executing the target program.
:returns:
:class:`Process` instance.
"""
parent_rfp, child_wfp, child_rfp, parent_wfp = create_best_pipe(
escalates_privilege=escalates_privilege
)
stderr = None
stderr_r = None
if merge_stdio:
stderr = child_wfp
elif stderr_pipe:
stderr_r, stderr = mitogen.core.pipe()
mitogen.core.set_cloexec(stderr_r.fileno())
try:
proc = popen(
args=args,
stdin=child_rfp,
stdout=child_wfp,
stderr=stderr,
close_fds=True,
preexec_fn=preexec_fn,
)
except:
child_rfp.close()
child_wfp.close()
parent_rfp.close()
parent_wfp.close()
if stderr_pipe:
stderr.close()
stderr_r.close()
raise
child_rfp.close()
child_wfp.close()
if stderr_pipe:
stderr.close()
return PopenProcess(
proc=proc,
stdin=parent_wfp,
stdout=parent_rfp,
stderr=stderr_r,
)
def _acquire_controlling_tty():
os.setsid()
if sys.platform in ('linux', 'linux2'):
# On Linux, the controlling tty becomes the first tty opened by a
# process lacking any prior tty.
os.close(os.open(os.ttyname(2), os.O_RDWR))
if hasattr(termios, 'TIOCSCTTY') and not mitogen.core.IS_WSL:
# #550: prehistoric WSL does not like TIOCSCTTY.
# On BSD an explicit ioctl is required. For some inexplicable reason,
# Python 2.6 on Travis also requires it.
fcntl.ioctl(2, termios.TIOCSCTTY)
def _linux_broken_devpts_openpty():
"""
#462: On broken Linux hosts with mismatched configuration (e.g. old
/etc/fstab template installed), /dev/pts may be mounted without the gid=
mount option, causing new slave devices to be created with the group ID of
the calling process. This upsets glibc, whose openpty() is required by
specification to produce a slave owned by a special group ID (which is
always the 'tty' group).
Glibc attempts to use "pt_chown" to fix ownership. If that fails, it
chown()s the PTY directly, which fails due to non-root, causing openpty()
to fail with EPERM ("Operation not permitted"). Since we don't need the
magical TTY group to run sudo and su, open the PTY ourselves in this case.
"""
master_fd = None
try:
# Opening /dev/ptmx causes a PTY pair to be allocated, and the
# corresponding slave /dev/pts/* device to be created, owned by UID/GID
# matching this process.
master_fd = os.open('/dev/ptmx', os.O_RDWR)
# Clear the lock bit from the PTY. This a prehistoric feature from a
# time when slave device files were persistent.
fcntl.ioctl(master_fd, LINUX_TIOCSPTLCK, struct.pack('i', 0))
# Since v4.13 TIOCGPTPEER exists to open the slave in one step, but we
# must support older kernels. Ask for the PTY number.
pty_num_s = fcntl.ioctl(master_fd, LINUX_TIOCGPTN,
struct.pack('i', 0))
pty_num, = struct.unpack('i', pty_num_s)
pty_name = '/dev/pts/%d' % (pty_num,)
# Now open it with O_NOCTTY to ensure it doesn't change our controlling
# TTY. Otherwise when we close the FD we get killed by the kernel, and
# the child we spawn that should really attach to it will get EPERM
# during _acquire_controlling_tty().
slave_fd = os.open(pty_name, os.O_RDWR|os.O_NOCTTY)
return master_fd, slave_fd
except OSError:
if master_fd is not None:
os.close(master_fd)
e = sys.exc_info()[1]
raise mitogen.core.StreamError(OPENPTY_MSG, e)
def openpty():
"""
Call :func:`os.openpty`, raising a descriptive error if the call fails.
:raises mitogen.core.StreamError:
Creating a PTY failed.
:returns:
`(master_fp, slave_fp)` file-like objects.
"""
try:
master_fd, slave_fd = os.openpty()
except OSError:
e = sys.exc_info()[1]
if not (IS_LINUX and e.args[0] == errno.EPERM):
raise mitogen.core.StreamError(OPENPTY_MSG, e)
master_fd, slave_fd = _linux_broken_devpts_openpty()
master_fp = os.fdopen(master_fd, 'r+b', 0)
slave_fp = os.fdopen(slave_fd, 'r+b', 0)
disable_echo(master_fd)
disable_echo(slave_fd)
mitogen.core.set_block(slave_fd)
return master_fp, slave_fp
def tty_create_child(args):
"""
Return a file descriptor connected to the master end of a pseudo-terminal,
whose slave end is connected to stdin/stdout/stderr of a new child process.
The child is created such that the pseudo-terminal becomes its controlling
TTY, ensuring access to /dev/tty returns a new file descriptor open on the
slave end.
:param list args:
Program argument vector.
:returns:
:class:`Process` instance.
"""
master_fp, slave_fp = openpty()
try:
proc = popen(
args=args,
stdin=slave_fp,
stdout=slave_fp,
stderr=slave_fp,
preexec_fn=_acquire_controlling_tty,
close_fds=True,
)
except:
master_fp.close()
slave_fp.close()
raise
slave_fp.close()
return PopenProcess(
proc=proc,
stdin=master_fp,
stdout=master_fp,
)
def hybrid_tty_create_child(args, escalates_privilege=False):
"""
Like :func:`tty_create_child`, except attach stdin/stdout to a socketpair
like :func:`create_child`, but leave stderr and the controlling TTY
attached to a TTY.
This permits high throughput communication with programs that are reached
via some program that requires a TTY for password input, like many
configurations of sudo. The UNIX TTY layer tends to have tiny (no more than
14KiB) buffers, forcing many IO loop iterations when transferring bulk
data, causing significant performance loss.
:param bool escalates_privilege:
If :data:`True`, the target program may escalate privileges, causing
SELinux to disconnect AF_UNIX sockets, so avoid those.
:param list args:
Program argument vector.
:returns:
:class:`Process` instance.
"""
master_fp, slave_fp = openpty()
try:
parent_rfp, child_wfp, child_rfp, parent_wfp = create_best_pipe(
escalates_privilege=escalates_privilege,
)
try:
mitogen.core.set_block(child_rfp)
mitogen.core.set_block(child_wfp)
proc = popen(
args=args,
stdin=child_rfp,
stdout=child_wfp,
stderr=slave_fp,
preexec_fn=_acquire_controlling_tty,
close_fds=True,
)
except:
parent_rfp.close()
child_wfp.close()
parent_wfp.close()
child_rfp.close()
raise
except:
master_fp.close()
slave_fp.close()
raise
slave_fp.close()
child_rfp.close()
child_wfp.close()
return PopenProcess(
proc=proc,
stdin=parent_wfp,
stdout=parent_rfp,
stderr=master_fp,
)
class Timer(object):
"""
Represents a future event.
"""
#: Set to :data:`False` if :meth:`cancel` has been called, or immediately
#: prior to being executed by :meth:`TimerList.expire`.
active = True
def __init__(self, when, func):
self.when = when
self.func = func
def __repr__(self):
return 'Timer(%r, %r)' % (self.when, self.func)
def __eq__(self, other):
return self.when == other.when
def __lt__(self, other):
return self.when < other.when
def __le__(self, other):
return self.when <= other.when
def cancel(self):
"""
Cancel this event. If it has not yet executed, it will not execute
during any subsequent :meth:`TimerList.expire` call.
"""
self.active = False
class TimerList(object):
"""
Efficiently manage a list of cancellable future events relative to wall
clock time. An instance of this class is installed as
:attr:`mitogen.master.Broker.timers` by default, and as
:attr:`mitogen.core.Broker.timers` in children after a call to
:func:`mitogen.parent.upgrade_router`.
You can use :class:`TimerList` to cause the broker to wake at arbitrary
future moments, useful for implementing timeouts and polling in an
asynchronous context.
:class:`TimerList` methods can only be called from asynchronous context,
for example via :meth:`mitogen.core.Broker.defer`.
The broker automatically adjusts its sleep delay according to the installed
timer list, and arranges for timers to expire via automatic calls to
:meth:`expire`. The main user interface to :class:`TimerList` is
:meth:`schedule`.
"""
_now = mitogen.core.now
def __init__(self):
self._lst = []
def get_timeout(self):
"""
Return the floating point seconds until the next event is due.
:returns:
Floating point delay, or 0.0, or :data:`None` if no events are
scheduled.
"""
while self._lst and not self._lst[0].active:
heapq.heappop(self._lst)
if self._lst:
return max(0, self._lst[0].when - self._now())
def schedule(self, when, func):
"""
Schedule a future event.
:param float when:
UNIX time in seconds when event should occur.
:param callable func:
Callable to invoke on expiry.
:returns:
A :class:`Timer` instance, exposing :meth:`Timer.cancel`, which may
be used to cancel the future invocation.
"""
timer = Timer(when, func)
heapq.heappush(self._lst, timer)
return timer
def expire(self):
"""
Invoke callbacks for any events in the past.
"""
now = self._now()
while self._lst and self._lst[0].when <= now:
timer = heapq.heappop(self._lst)
if timer.active:
timer.active = False
timer.func()
class PartialZlib(object):
"""
Because the mitogen.core source has a line appended to it during bootstrap,
it must be recompressed for each connection. This is not a problem for a
small number of connections, but it amounts to 30 seconds CPU time by the
time 500 targets are in use.
For that reason, build a compressor containing mitogen.core and flush as
much of it as possible into an initial buffer. Then to append the custom
line, clone the compressor and compress just that line.
A full compression costs ~6ms on a modern machine, this method costs ~35
usec.
"""
def __init__(self, s):
self.s = s
if sys.version_info > (2, 5):
self._compressor = zlib.compressobj(9)
self._out = self._compressor.compress(s)
self._out += self._compressor.flush(zlib.Z_SYNC_FLUSH)
else:
self._compressor = None
def append(self, s):
"""
Append the bytestring `s` to the compressor state and return the
final compressed output.
"""
if self._compressor is None:
return zlib.compress(self.s + s, 9)
else:
compressor = self._compressor.copy()
out = self._out
out += compressor.compress(s)
return out + compressor.flush()
def _upgrade_broker(broker):
"""
Extract the poller state from Broker and replace it with the industrial
strength poller for this OS. Must run on the Broker thread.
"""
# This function is deadly! The act of calling start_receive() generates log
# messages which must be silenced as the upgrade progresses, otherwise the
# poller state will change as it is copied, resulting in write fds that are
# lost. (Due to LogHandler->Router->Stream->Protocol->Broker->Poller, where
# Stream only calls start_transmit() when transitioning from empty to
# non-empty buffer. If the start_transmit() is lost, writes from the child
# hang permanently).
root = logging.getLogger()
old_level = root.level
root.setLevel(logging.CRITICAL)
try:
old = broker.poller
new = PREFERRED_POLLER()
for fd, data in old.readers:
new.start_receive(fd, data)
for fd, data in old.writers:
new.start_transmit(fd, data)
old.close()
broker.poller = new
finally:
root.setLevel(old_level)
broker.timers = TimerList()
LOG.debug('upgraded %r with %r (new: %d readers, %d writers; '
'old: %d readers, %d writers)', old, new,
len(new.readers), len(new.writers),
len(old.readers), len(old.writers))
@mitogen.core.takes_econtext
def upgrade_router(econtext):
if not isinstance(econtext.router, Router): # TODO
econtext.broker.defer(_upgrade_broker, econtext.broker)
econtext.router.__class__ = Router # TODO
econtext.router.upgrade(
importer=econtext.importer,
parent=econtext.parent,
)
def get_connection_class(name):
"""
Given the name of a Mitogen connection method, import its implementation
module and return its Stream subclass.
"""
if name == u'local':
name = u'parent'
module = mitogen.core.import_module(u'mitogen.' + name)
return module.Connection
@mitogen.core.takes_econtext
def _proxy_connect(name, method_name, kwargs, econtext):
"""
Implements the target portion of Router._proxy_connect() by upgrading the
local process to a parent if it was not already, then calling back into
Router._connect() using the arguments passed to the parent's
Router.connect().
:returns:
Dict containing:
* ``id``: :data:`None`, or integer new context ID.
* ``name``: :data:`None`, or string name attribute of new Context.
* ``msg``: :data:`None`, or StreamError exception text.
"""
upgrade_router(econtext)
try:
context = econtext.router._connect(
klass=get_connection_class(method_name),
name=name,
**kwargs
)
except mitogen.core.StreamError:
return {
u'id': None,
u'name': None,
u'msg': 'error occurred on host %s: %s' % (
socket.gethostname(),
sys.exc_info()[1],
),
}
return {
u'id': context.context_id,
u'name': context.name,
u'msg': None,
}
def returncode_to_str(n):
"""
Parse and format a :func:`os.waitpid` exit status.
"""
if n < 0:
return 'exited due to signal %d (%s)' % (-n, SIGNAL_BY_NUM.get(-n))
return 'exited with return code %d' % (n,)
class EofError(mitogen.core.StreamError):
"""
Raised by :class:`Connection` when an empty read is detected from the
remote process before bootstrap completes.
"""
# inherits from StreamError to maintain compatibility.
pass
class CancelledError(mitogen.core.StreamError):
"""
Raised by :class:`Connection` when :meth:`mitogen.core.Broker.shutdown` is
called before bootstrap completes.
"""
pass
class Argv(object):
"""
Wrapper to defer argv formatting when debug logging is disabled.
"""
def __init__(self, argv):
self.argv = argv
must_escape = frozenset('\\$"`!')
must_escape_or_space = must_escape | frozenset(' ')
def escape(self, x):
if not self.must_escape_or_space.intersection(x):
return x
s = '"'
for c in x:
if c in self.must_escape:
s += '\\'
s += c
s += '"'
return s
def __str__(self):
return ' '.join(map(self.escape, self.argv))
class CallSpec(object):
"""
Wrapper to defer call argument formatting when debug logging is disabled.
"""
def __init__(self, func, args, kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def _get_name(self):
bits = [self.func.__module__]
if inspect.ismethod(self.func):
im_self = getattr(self.func, IM_SELF_ATTR)
bits.append(getattr(im_self, '__name__', None) or
getattr(type(im_self), '__name__', None))
bits.append(self.func.__name__)
return u'.'.join(bits)
def _get_args(self):
return u', '.join(repr(a) for a in self.args)
def _get_kwargs(self):
s = u''
if self.kwargs:
s = u', '.join('%s=%r' % (k, v) for k, v in self.kwargs.items())
if self.args:
s = u', ' + s
return s
def __repr__(self):
return '%s(%s%s)' % (
self._get_name(),
self._get_args(),
self._get_kwargs(),
)
class PollPoller(mitogen.core.Poller):
"""
Poller based on the POSIX :linux:man2:`poll` interface. Not available on
some versions of OS X, otherwise it is the preferred poller for small FD
counts, as there is no setup/teardown/configuration system call overhead.
"""
SUPPORTED = hasattr(select, 'poll')
_repr = 'PollPoller()'
def __init__(self):
super(PollPoller, self).__init__()
self._pollobj = select.poll()
# TODO: no proof we dont need writemask too
_readmask = (
getattr(select, 'POLLIN', 0) |
getattr(select, 'POLLHUP', 0)
)
def _update(self, fd):
mask = (((fd in self._rfds) and self._readmask) |
((fd in self._wfds) and select.POLLOUT))
if mask:
self._pollobj.register(fd, mask)
else:
try:
self._pollobj.unregister(fd)
except KeyError:
pass
def _poll(self, timeout):
if timeout:
timeout *= 1000
events, _ = mitogen.core.io_op(self._pollobj.poll, timeout)
for fd, event in events:
if event & self._readmask:
IOLOG.debug('%r: POLLIN|POLLHUP for %r', self, fd)
data, gen = self._rfds.get(fd, (None, None))
if gen and gen < self._generation:
yield data
if event & select.POLLOUT:
IOLOG.debug('%r: POLLOUT for %r', self, fd)
data, gen = self._wfds.get(fd, (None, None))
if gen and gen < self._generation:
yield data
class KqueuePoller(mitogen.core.Poller):
"""
Poller based on the FreeBSD/Darwin :freebsd:man2:`kqueue` interface.
"""
SUPPORTED = hasattr(select, 'kqueue')
_repr = 'KqueuePoller()'
def __init__(self):
super(KqueuePoller, self).__init__()
self._kqueue = select.kqueue()
self._changelist = []
def close(self):
super(KqueuePoller, self).close()
self._kqueue.close()
def _control(self, fd, filters, flags):
mitogen.core._vv and IOLOG.debug(
'%r._control(%r, %r, %r)', self, fd, filters, flags)
# TODO: at shutdown it is currently possible for KQ_EV_ADD/KQ_EV_DEL
# pairs to be pending after the associated file descriptor has already
# been closed. Fixing this requires maintaining extra state, or perhaps
# making fd closure the poller's responsibility. In the meantime,
# simply apply changes immediately.
# self._changelist.append(select.kevent(fd, filters, flags))
changelist = [select.kevent(fd, filters, flags)]
events, _ = mitogen.core.io_op(self._kqueue.control, changelist, 0, 0)
assert not events
def start_receive(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_receive(%r, %r)',
self, fd, data)
if fd not in self._rfds:
self._control(fd, select.KQ_FILTER_READ, select.KQ_EV_ADD)
self._rfds[fd] = (data or fd, self._generation)
def stop_receive(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_receive(%r)', self, fd)
if fd in self._rfds:
self._control(fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE)
del self._rfds[fd]
def start_transmit(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_transmit(%r, %r)',
self, fd, data)
if fd not in self._wfds:
self._control(fd, select.KQ_FILTER_WRITE, select.KQ_EV_ADD)
self._wfds[fd] = (data or fd, self._generation)
def stop_transmit(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_transmit(%r)', self, fd)
if fd in self._wfds:
self._control(fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE)
del self._wfds[fd]
def _poll(self, timeout):
changelist = self._changelist
self._changelist = []
events, _ = mitogen.core.io_op(self._kqueue.control,
changelist, 32, timeout)
for event in events:
fd = event.ident
if event.flags & select.KQ_EV_ERROR:
LOG.debug('ignoring stale event for fd %r: errno=%d: %s',
fd, event.data, errno.errorcode.get(event.data))
elif event.filter == select.KQ_FILTER_READ:
data, gen = self._rfds.get(fd, (None, None))
# Events can still be read for an already-discarded fd.
if gen and gen < self._generation:
mitogen.core._vv and IOLOG.debug('%r: POLLIN: %r', self, fd)
yield data
elif event.filter == select.KQ_FILTER_WRITE and fd in self._wfds:
data, gen = self._wfds.get(fd, (None, None))
if gen and gen < self._generation:
mitogen.core._vv and IOLOG.debug('%r: POLLOUT: %r', self, fd)
yield data
class EpollPoller(mitogen.core.Poller):
"""
Poller based on the Linux :linux:man2:`epoll` interface.
"""
SUPPORTED = hasattr(select, 'epoll')
_repr = 'EpollPoller()'
def __init__(self):
super(EpollPoller, self).__init__()
self._epoll = select.epoll(32)
self._registered_fds = set()
def close(self):
super(EpollPoller, self).close()
self._epoll.close()
def _control(self, fd):
mitogen.core._vv and IOLOG.debug('%r._control(%r)', self, fd)
mask = (((fd in self._rfds) and select.EPOLLIN) |
((fd in self._wfds) and select.EPOLLOUT))
if mask:
if fd in self._registered_fds:
self._epoll.modify(fd, mask)
else:
self._epoll.register(fd, mask)
self._registered_fds.add(fd)
elif fd in self._registered_fds:
self._epoll.unregister(fd)
self._registered_fds.remove(fd)
def start_receive(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_receive(%r, %r)',
self, fd, data)
self._rfds[fd] = (data or fd, self._generation)
self._control(fd)
def stop_receive(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_receive(%r)', self, fd)
self._rfds.pop(fd, None)
self._control(fd)
def start_transmit(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_transmit(%r, %r)',
self, fd, data)
self._wfds[fd] = (data or fd, self._generation)
self._control(fd)
def stop_transmit(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_transmit(%r)', self, fd)
self._wfds.pop(fd, None)
self._control(fd)
_inmask = (getattr(select, 'EPOLLIN', 0) |
getattr(select, 'EPOLLHUP', 0))
def _poll(self, timeout):
the_timeout = -1
if timeout is not None:
the_timeout = timeout
events, _ = mitogen.core.io_op(self._epoll.poll, the_timeout, 32)
for fd, event in events:
if event & self._inmask:
data, gen = self._rfds.get(fd, (None, None))
if gen and gen < self._generation:
# Events can still be read for an already-discarded fd.
mitogen.core._vv and IOLOG.debug('%r: POLLIN: %r', self, fd)
yield data
if event & select.EPOLLOUT:
data, gen = self._wfds.get(fd, (None, None))
if gen and gen < self._generation:
mitogen.core._vv and IOLOG.debug('%r: POLLOUT: %r', self, fd)
yield data
# 2.4 and 2.5 only had select.select() and select.poll().
for _klass in mitogen.core.Poller, PollPoller, KqueuePoller, EpollPoller:
if _klass.SUPPORTED:
PREFERRED_POLLER = _klass
# For processes that start many threads or connections, it's possible Latch
# will also get high-numbered FDs, and so select() becomes useless there too.
# So swap in our favourite poller.
if PollPoller.SUPPORTED:
mitogen.core.Latch.poller_class = PollPoller
else:
mitogen.core.Latch.poller_class = PREFERRED_POLLER
class LineLoggingProtocolMixin(object):
def __init__(self, **kwargs):
super(LineLoggingProtocolMixin, self).__init__(**kwargs)
self.logged_lines = []
self.logged_partial = None
def on_line_received(self, line):
self.logged_partial = None
self.logged_lines.append((mitogen.core.now(), line))
self.logged_lines[:] = self.logged_lines[-100:]
return super(LineLoggingProtocolMixin, self).on_line_received(line)
def on_partial_line_received(self, line):
self.logged_partial = line
return super(LineLoggingProtocolMixin, self).on_partial_line_received(line)
def on_disconnect(self, broker):
if self.logged_partial:
self.logged_lines.append((mitogen.core.now(), self.logged_partial))
self.logged_partial = None
super(LineLoggingProtocolMixin, self).on_disconnect(broker)
def get_history(streams):
history = []
for stream in streams:
if stream:
history.extend(getattr(stream.protocol, 'logged_lines', []))
history.sort()
s = b('\n').join(h[1] for h in history)
return mitogen.core.to_text(s)
class RegexProtocol(LineLoggingProtocolMixin, mitogen.core.DelimitedProtocol):
"""
Implement a delimited protocol where messages matching a set of regular
expressions are dispatched to individual handler methods. Input is
dispatches using :attr:`PATTERNS` and :attr:`PARTIAL_PATTERNS`, before
falling back to :meth:`on_unrecognized_line_received` and
:meth:`on_unrecognized_partial_line_received`.
"""
#: A sequence of 2-tuples of the form `(compiled pattern, method)` for
#: patterns that should be matched against complete (delimited) messages,
#: i.e. full lines.
PATTERNS = []
#: Like :attr:`PATTERNS`, but patterns that are matched against incomplete
#: lines.
PARTIAL_PATTERNS = []
def on_line_received(self, line):
super(RegexProtocol, self).on_line_received(line)
for pattern, func in self.PATTERNS:
match = pattern.search(line)
if match is not None:
return func(self, line, match)
return self.on_unrecognized_line_received(line)
def on_unrecognized_line_received(self, line):
LOG.debug('%s: (unrecognized): %s',
self.stream.name, line.decode('utf-8', 'replace'))
def on_partial_line_received(self, line):
super(RegexProtocol, self).on_partial_line_received(line)
LOG.debug('%s: (partial): %s',
self.stream.name, line.decode('utf-8', 'replace'))
for pattern, func in self.PARTIAL_PATTERNS:
match = pattern.search(line)
if match is not None:
return func(self, line, match)
return self.on_unrecognized_partial_line_received(line)
def on_unrecognized_partial_line_received(self, line):
LOG.debug('%s: (unrecognized partial): %s',
self.stream.name, line.decode('utf-8', 'replace'))
class BootstrapProtocol(RegexProtocol):
"""
Respond to stdout of a child during bootstrap. Wait for :attr:`EC0_MARKER`
to be written by the first stage to indicate it can receive the bootstrap,
then await :attr:`EC1_MARKER` to indicate success, and
:class:`MitogenProtocol` can be enabled.
"""
#: Sentinel value emitted by the first stage to indicate it is ready to
#: receive the compressed bootstrap. For :mod:`mitogen.ssh` this must have
#: length of at least `max(len('password'), len('debug1:'))`
EC0_MARKER = b('MITO000')
EC1_MARKER = b('MITO001')
EC2_MARKER = b('MITO002')
def __init__(self, broker):
super(BootstrapProtocol, self).__init__()
self._writer = mitogen.core.BufferedWriter(broker, self)
def on_transmit(self, broker):
self._writer.on_transmit(broker)
def _on_ec0_received(self, line, match):
LOG.debug('%r: first stage started succcessfully', self)
self._writer.write(self.stream.conn.get_preamble())
def _on_ec1_received(self, line, match):
LOG.debug('%r: first stage received mitogen.core source', self)
def _on_ec2_received(self, line, match):
LOG.debug('%r: new child booted successfully', self)
self.stream.conn._complete_connection()
return False
def on_unrecognized_line_received(self, line):
LOG.debug('%s: stdout: %s', self.stream.name,
line.decode('utf-8', 'replace'))
PATTERNS = [
(re.compile(EC0_MARKER), _on_ec0_received),
(re.compile(EC1_MARKER), _on_ec1_received),
(re.compile(EC2_MARKER), _on_ec2_received),
]
class LogProtocol(LineLoggingProtocolMixin, mitogen.core.DelimitedProtocol):
"""
For "hybrid TTY/socketpair" mode, after connection setup a spare TTY master
FD exists that cannot be closed, and to which SSH or sudo may continue
writing log messages.
The descriptor cannot be closed since the UNIX TTY layer sends SIGHUP to
processes whose controlling TTY is the slave whose master side was closed.
LogProtocol takes over this FD and creates log messages for anything
written to it.
"""
def on_line_received(self, line):
"""
Read a line, decode it as UTF-8, and log it.
"""
super(LogProtocol, self).on_line_received(line)
LOG.info(u'%s: %s', self.stream.name, line.decode('utf-8', 'replace'))
class MitogenProtocol(mitogen.core.MitogenProtocol):
"""
Extend core.MitogenProtocol to cause SHUTDOWN to be sent to the child
during graceful shutdown.
"""
def on_shutdown(self, broker):
"""
Respond to the broker's request for the stream to shut down by sending
SHUTDOWN to the child.
"""
LOG.debug('%r: requesting child shutdown', self)
self._send(
mitogen.core.Message(
src_id=mitogen.context_id,
dst_id=self.remote_id,
handle=mitogen.core.SHUTDOWN,
)
)
class Options(object):
name = None
#: The path to the remote Python interpreter.
python_path = get_sys_executable()
#: Maximum time to wait for a connection attempt.
connect_timeout = 30.0
#: True to cause context to write verbose /tmp/mitogen.<pid>.log.
debug = False
#: True to cause context to write /tmp/mitogen.stats.<pid>.<thread>.log.
profiling = False
#: True if unidirectional routing is enabled in the new child.
unidirectional = False
#: Passed via Router wrapper methods, must eventually be passed to
#: ExternalContext.main().
max_message_size = None
#: Remote name.
remote_name = None
#: Derived from :py:attr:`connect_timeout`; absolute floating point
#: UNIX timestamp after which the connection attempt should be abandoned.
connect_deadline = None
def __init__(self, max_message_size, name=None, remote_name=None,
python_path=None, debug=False, connect_timeout=None,
profiling=False, unidirectional=False, old_router=None):
self.name = name
self.max_message_size = max_message_size
if python_path:
self.python_path = python_path
if connect_timeout:
self.connect_timeout = connect_timeout
if remote_name is None:
remote_name = get_default_remote_name()
if '/' in remote_name or '\\' in remote_name:
raise ValueError('remote_name= cannot contain slashes')
if remote_name:
self.remote_name = mitogen.core.to_text(remote_name)
self.debug = debug
self.profiling = profiling
self.unidirectional = unidirectional
self.max_message_size = max_message_size
self.connect_deadline = mitogen.core.now() + self.connect_timeout
class Connection(object):
"""
Manage the lifetime of a set of :class:`Streams <Stream>` connecting to a
remote Python interpreter, including bootstrap, disconnection, and external
tool integration.
Base for streams capable of starting children.
"""
options_class = Options
#: The protocol attached to stdio of the child.
stream_protocol_class = BootstrapProtocol
#: The protocol attached to stderr of the child.
diag_protocol_class = LogProtocol
#: :class:`Process`
proc = None
#: :class:`mitogen.core.Stream` with sides connected to stdin/stdout.
stdio_stream = None
#: If `proc.stderr` is set, referencing either a plain pipe or the
#: controlling TTY, this references the corresponding
#: :class:`LogProtocol`'s stream, allowing it to be disconnected when this
#: stream is disconnected.
stderr_stream = None
#: Function with the semantics of :func:`create_child` used to create the
#: child process.
create_child = staticmethod(create_child)
#: Dictionary of extra kwargs passed to :attr:`create_child`.
create_child_args = {}
#: :data:`True` if the remote has indicated that it intends to detach, and
#: should not be killed on disconnect.
detached = False
#: If :data:`True`, indicates the child should not be killed during
#: graceful detachment, as it the actual process implementing the child
#: context. In all other cases, the subprocess is SSH, sudo, or a similar
#: tool that should be reminded to quit during disconnection.
child_is_immediate_subprocess = True
#: Prefix given to default names generated by :meth:`connect`.
name_prefix = u'local'
#: :class:`Timer` that runs :meth:`_on_timer_expired` when connection
#: timeout occurs.
_timer = None
#: When disconnection completes, instance of :class:`Reaper` used to wait
#: on the exit status of the subprocess.
_reaper = None
#: On failure, the exception object that should be propagated back to the
#: user.
exception = None
#: Extra text appended to :class:`EofError` if that exception is raised on
#: a failed connection attempt. May be used in subclasses to hint at common
#: problems with a particular connection method.
eof_error_hint = None
def __init__(self, options, router):
#: :class:`Options`
self.options = options
self._router = router
def __repr__(self):
return 'Connection(%r)' % (self.stdio_stream,)
# Minimised, gzipped, base64'd and passed to 'python -c'. It forks, dups
# file descriptor 0 as 100, creates a pipe, then execs a new interpreter
# with a custom argv.
# * Optimized for minimum byte count after minification & compression.
# * 'CONTEXT_NAME' and 'PREAMBLE_COMPRESSED_LEN' are substituted with
# their respective values.
# * CONTEXT_NAME must be prefixed with the name of the Python binary in
# order to allow virtualenvs to detect their install prefix.
# * For Darwin, OS X installs a craptacular argv0-introspecting Python
# version switcher as /usr/bin/python. Override attempts to call it
# with an explicit call to python2.7
#
# Locals:
# R: read side of interpreter stdin.
# W: write side of interpreter stdin.
# r: read side of core_src FD.
# w: write side of core_src FD.
# C: the decompressed core source.
# Final os.close(2) to avoid --py-debug build from corrupting stream with
# "[1234 refs]" during exit.
@staticmethod
def _first_stage():
R,W=os.pipe()
r,w=os.pipe()
if os.fork():
os.dup2(0,100)
os.dup2(R,0)
os.dup2(r,101)
os.close(R)
os.close(r)
os.close(W)
os.close(w)
if sys.platform == 'darwin' and sys.executable == '/usr/bin/python':
sys.executable += sys.version[:3]
os.environ['ARGV0']=sys.executable
os.execl(sys.executable,sys.executable+'(mitogen:CONTEXT_NAME)')
os.write(1,'MITO000\n'.encode())
C=_(os.fdopen(0,'rb').read(PREAMBLE_COMPRESSED_LEN),'zip')
fp=os.fdopen(W,'wb',0)
fp.write(C)
fp.close()
fp=os.fdopen(w,'wb',0)
fp.write(C)
fp.close()
os.write(1,'MITO001\n'.encode())
os.close(2)
def get_python_argv(self):
"""
Return the initial argument vector elements necessary to invoke Python,
by returning a 1-element list containing :attr:`python_path` if it is a
string, or simply returning it if it is already a list.
This allows emulation of existing tools where the Python invocation may
be set to e.g. `['/usr/bin/env', 'python']`.
"""
if isinstance(self.options.python_path, list):
return self.options.python_path
return [self.options.python_path]
def get_boot_command(self):
source = inspect.getsource(self._first_stage)
source = textwrap.dedent('\n'.join(source.strip().split('\n')[2:]))
source = source.replace(' ', '\t')
source = source.replace('CONTEXT_NAME', self.options.remote_name)
preamble_compressed = self.get_preamble()
source = source.replace('PREAMBLE_COMPRESSED_LEN',
str(len(preamble_compressed)))
compressed = zlib.compress(source.encode(), 9)
encoded = codecs.encode(compressed, 'base64').replace(b('\n'), b(''))
# We can't use bytes.decode() in 3.x since it was restricted to always
# return unicode, so codecs.decode() is used instead. In 3.x
# codecs.decode() requires a bytes object. Since we must be compatible
# with 2.4 (no bytes literal), an extra .encode() either returns the
# same str (2.x) or an equivalent bytes (3.x).
return self.get_python_argv() + [
'-c',
'import codecs,os,sys;_=codecs.decode;'
'exec(_(_("%s".encode(),"base64"),"zip"))' % (encoded.decode(),)
]
def get_econtext_config(self):
assert self.options.max_message_size is not None
parent_ids = mitogen.parent_ids[:]
parent_ids.insert(0, mitogen.context_id)
return {
'parent_ids': parent_ids,
'context_id': self.context.context_id,
'debug': self.options.debug,
'profiling': self.options.profiling,
'unidirectional': self.options.unidirectional,
'log_level': get_log_level(),
'whitelist': self._router.get_module_whitelist(),
'blacklist': self._router.get_module_blacklist(),
'max_message_size': self.options.max_message_size,
'version': mitogen.__version__,
}
def get_preamble(self):
suffix = (
'\nExternalContext(%r).main()\n' %\
(self.get_econtext_config(),)
)
partial = get_core_source_partial()
return partial.append(suffix.encode('utf-8'))
def _get_name(self):
"""
Called by :meth:`connect` after :attr:`pid` is known. Subclasses can
override it to specify a default stream name, or set
:attr:`name_prefix` to generate a default format.
"""
return u'%s.%s' % (self.name_prefix, self.proc.pid)
def start_child(self):
args = self.get_boot_command()
LOG.debug('command line for %r: %s', self, Argv(args))
try:
return self.create_child(args=args, **self.create_child_args)
except OSError:
e = sys.exc_info()[1]
msg = 'Child start failed: %s. Command was: %s' % (e, Argv(args))
raise mitogen.core.StreamError(msg)
def _adorn_eof_error(self, e):
"""
Subclasses may provide additional information in the case of a failed
connection.
"""
if self.eof_error_hint:
e.args = ('%s\n\n%s' % (e.args[0], self.eof_error_hint),)
def _complete_connection(self):
self._timer.cancel()
if not self.exception:
mitogen.core.unlisten(self._router.broker, 'shutdown',
self._on_broker_shutdown)
self._router.register(self.context, self.stdio_stream)
self.stdio_stream.set_protocol(
MitogenProtocol(
router=self._router,
remote_id=self.context.context_id,
)
)
self._router.route_monitor.notice_stream(self.stdio_stream)
self.latch.put()
def _fail_connection(self, exc):
"""
Fail the connection attempt.
"""
LOG.debug('failing connection %s due to %r',
self.stdio_stream and self.stdio_stream.name, exc)
if self.exception is None:
self._adorn_eof_error(exc)
self.exception = exc
mitogen.core.unlisten(self._router.broker, 'shutdown',
self._on_broker_shutdown)
for stream in self.stdio_stream, self.stderr_stream:
if stream and not stream.receive_side.closed:
stream.on_disconnect(self._router.broker)
self._complete_connection()
eof_error_msg = 'EOF on stream; last 100 lines received:\n'
def on_stdio_disconnect(self):
"""
Handle stdio stream disconnection by failing the Connection if the
stderr stream has already been closed. Otherwise, wait for it to close
(or timeout), to allow buffered diagnostic logs to be consumed.
It is normal that when a subprocess aborts, stdio has nothing buffered
when it is closed, thus signalling readability, causing an empty read
(interpreted as indicating disconnection) on the next loop iteration,
even if its stderr pipe has lots of diagnostic logs still buffered in
the kernel. Therefore we must wait for both pipes to indicate they are
empty before triggering connection failure.
"""
stderr = self.stderr_stream
if stderr is None or stderr.receive_side.closed:
self._on_streams_disconnected()
def on_stderr_disconnect(self):
"""
Inverse of :func:`on_stdio_disconnect`.
"""
if self.stdio_stream.receive_side.closed:
self._on_streams_disconnected()
def _on_streams_disconnected(self):
"""
When disconnection has been detected for both streams, cancel the
connection timer, mark the connection failed, and reap the child
process. Do nothing if the timer has already been cancelled, indicating
some existing failure has already been noticed.
"""
if self._timer.active:
self._timer.cancel()
self._fail_connection(EofError(
self.eof_error_msg + get_history(
[self.stdio_stream, self.stderr_stream]
)
))
if self._reaper:
return
self._reaper = Reaper(
broker=self._router.broker,
proc=self.proc,
kill=not (
(self.detached and self.child_is_immediate_subprocess) or
# Avoid killing so child has chance to write cProfile data
self._router.profiling
),
# Don't delay shutdown waiting for a detached child, since the
# detached child may expect to live indefinitely after its parent
# exited.
wait_on_shutdown=(not self.detached),
)
self._reaper.reap()
def _on_broker_shutdown(self):
"""
Respond to broker.shutdown() being called by failing the connection
attempt.
"""
self._fail_connection(CancelledError(BROKER_SHUTDOWN_MSG))
def stream_factory(self):
return self.stream_protocol_class.build_stream(
broker=self._router.broker,
)
def stderr_stream_factory(self):
return self.diag_protocol_class.build_stream()
def _setup_stdio_stream(self):
stream = self.stream_factory()
stream.conn = self
stream.name = self.options.name or self._get_name()
stream.accept(self.proc.stdout, self.proc.stdin)
mitogen.core.listen(stream, 'disconnect', self.on_stdio_disconnect)
self._router.broker.start_receive(stream)
return stream
def _setup_stderr_stream(self):
stream = self.stderr_stream_factory()
stream.conn = self
stream.name = self.options.name or self._get_name()
stream.accept(self.proc.stderr, self.proc.stderr)
mitogen.core.listen(stream, 'disconnect', self.on_stderr_disconnect)
self._router.broker.start_receive(stream)
return stream
def _on_timer_expired(self):
self._fail_connection(
mitogen.core.TimeoutError(
'Failed to setup connection after %.2f seconds',
self.options.connect_timeout,
)
)
def _async_connect(self):
LOG.debug('creating connection to context %d using %s',
self.context.context_id, self.__class__.__module__)
mitogen.core.listen(self._router.broker, 'shutdown',
self._on_broker_shutdown)
self._timer = self._router.broker.timers.schedule(
when=self.options.connect_deadline,
func=self._on_timer_expired,
)
try:
self.proc = self.start_child()
except Exception:
self._fail_connection(sys.exc_info()[1])
return
LOG.debug('child for %r started: pid:%r stdin:%r stdout:%r stderr:%r',
self, self.proc.pid,
self.proc.stdin.fileno(),
self.proc.stdout.fileno(),
self.proc.stderr and self.proc.stderr.fileno())
self.stdio_stream = self._setup_stdio_stream()
if self.context.name is None:
self.context.name = self.stdio_stream.name
self.proc.name = self.stdio_stream.name
if self.proc.stderr:
self.stderr_stream = self._setup_stderr_stream()
def connect(self, context):
self.context = context
self.latch = mitogen.core.Latch()
self._router.broker.defer(self._async_connect)
self.latch.get()
if self.exception:
raise self.exception
class ChildIdAllocator(object):
"""
Allocate new context IDs from a block of unique context IDs allocated by
the master process.
"""
def __init__(self, router):
self.router = router
self.lock = threading.Lock()
self.it = iter(xrange(0))
def allocate(self):
"""
Allocate an ID, requesting a fresh block from the master if the
existing block is exhausted.
:returns:
The new context ID.
.. warning::
This method is not safe to call from the :class:`Broker` thread, as
it may block on IO of its own.
"""
self.lock.acquire()
try:
for id_ in self.it:
return id_
master = self.router.context_by_id(0)
start, end = master.send_await(
mitogen.core.Message(dst_id=0, handle=mitogen.core.ALLOCATE_ID)
)
self.it = iter(xrange(start, end))
finally:
self.lock.release()
return self.allocate()
class CallChain(object):
"""
Deliver :data:`mitogen.core.CALL_FUNCTION` messages to a target context,
optionally threading related calls so an exception in an earlier call
cancels subsequent calls.
:param mitogen.core.Context context:
Target context.
:param bool pipelined:
Enable pipelining.
:meth:`call`, :meth:`call_no_reply` and :meth:`call_async`
normally issue calls and produce responses with no memory of prior
exceptions. If a call made with :meth:`call_no_reply` fails, the exception
is logged to the target context's logging framework.
**Pipelining**
When pipelining is enabled, if an exception occurs during a call,
subsequent calls made by the same :class:`CallChain` fail with the same
exception, including those already in-flight on the network, and no further
calls execute until :meth:`reset` is invoked.
No exception is logged for calls made with :meth:`call_no_reply`, instead
the exception is saved and reported as the result of subsequent
:meth:`call` or :meth:`call_async` calls.
Sequences of asynchronous calls can be made without wasting network
round-trips to discover if prior calls succeed, and chains originating from
multiple unrelated source contexts may overlap concurrently at a target
context without interference.
In this example, 4 calls complete in one round-trip::
chain = mitogen.parent.CallChain(context, pipelined=True)
chain.call_no_reply(os.mkdir, '/tmp/foo')
# If previous mkdir() failed, this never runs:
chain.call_no_reply(os.mkdir, '/tmp/foo/bar')
# If either mkdir() failed, this never runs, and the exception is
# asynchronously delivered to the receiver.
recv = chain.call_async(subprocess.check_output, '/tmp/foo')
# If anything so far failed, this never runs, and raises the exception.
chain.call(do_something)
# If this code was executed, the exception would also be raised.
if recv.get().unpickle() == 'baz':
pass
When pipelining is enabled, :meth:`reset` must be invoked to ensure any
exception is discarded, otherwise unbounded memory usage is possible in
long-running programs. The context manager protocol is supported to ensure
:meth:`reset` is always invoked::
with mitogen.parent.CallChain(context, pipelined=True) as chain:
chain.call_no_reply(...)
chain.call_no_reply(...)
chain.call_no_reply(...)
chain.call(...)
# chain.reset() automatically invoked.
"""
def __init__(self, context, pipelined=False):
self.context = context
if pipelined:
self.chain_id = self.make_chain_id()
else:
self.chain_id = None
@classmethod
def make_chain_id(cls):
return '%s-%s-%x-%x' % (
socket.gethostname(),
os.getpid(),
thread.get_ident(),
int(1e6 * mitogen.core.now()),
)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.context)
def __enter__(self):
return self
def __exit__(self, _1, _2, _3):
self.reset()
def reset(self):
"""
Instruct the target to forget any related exception.
"""
if not self.chain_id:
return
saved, self.chain_id = self.chain_id, None
try:
self.call_no_reply(mitogen.core.Dispatcher.forget_chain, saved)
finally:
self.chain_id = saved
closures_msg = (
'Mitogen cannot invoke closures, as doing so would require '
'serializing arbitrary program state, and no universal '
'method exists to recover a reference to them.'
)
lambda_msg = (
'Mitogen cannot invoke anonymous functions, as no universal method '
'exists to recover a reference to an anonymous function.'
)
method_msg = (
'Mitogen cannot invoke instance methods, as doing so would require '
'serializing arbitrary program state.'
)
def make_msg(self, fn, *args, **kwargs):
if getattr(fn, closure_attr, None) is not None:
raise TypeError(self.closures_msg)
if fn.__name__ == '<lambda>':
raise TypeError(self.lambda_msg)
if inspect.ismethod(fn):
im_self = getattr(fn, IM_SELF_ATTR)
if not inspect.isclass(im_self):
raise TypeError(self.method_msg)
klass = mitogen.core.to_text(im_self.__name__)
else:
klass = None
tup = (
self.chain_id,
mitogen.core.to_text(fn.__module__),
klass,
mitogen.core.to_text(fn.__name__),
args,
mitogen.core.Kwargs(kwargs)
)
return mitogen.core.Message.pickled(tup,
handle=mitogen.core.CALL_FUNCTION)
def call_no_reply(self, fn, *args, **kwargs):
"""
Like :meth:`call_async`, but do not wait for a return value, and inform
the target context no reply is expected. If the call fails and
pipelining is disabled, the exception will be logged to the target
context's logging framework.
"""
LOG.debug('starting no-reply function call to %r: %r',
self.context.name or self.context.context_id,
CallSpec(fn, args, kwargs))
self.context.send(self.make_msg(fn, *args, **kwargs))
def call_async(self, fn, *args, **kwargs):
"""
Arrange for `fn(*args, **kwargs)` to be invoked on the context's main
thread.
:param fn:
A free function in module scope or a class method of a class
directly reachable from module scope:
.. code-block:: python
# mymodule.py
def my_func():
'''A free function reachable as mymodule.my_func'''
class MyClass:
@classmethod
def my_classmethod(cls):
'''Reachable as mymodule.MyClass.my_classmethod'''
def my_instancemethod(self):
'''Unreachable: requires a class instance!'''
class MyEmbeddedClass:
@classmethod
def my_classmethod(cls):
'''Not directly reachable from module scope!'''
:param tuple args:
Function arguments, if any. See :ref:`serialization-rules` for
permitted types.
:param dict kwargs:
Function keyword arguments, if any. See :ref:`serialization-rules`
for permitted types.
:returns:
:class:`mitogen.core.Receiver` configured to receive the result of
the invocation:
.. code-block:: python
recv = context.call_async(os.check_output, 'ls /tmp/')
try:
# Prints output once it is received.
msg = recv.get()
print(msg.unpickle())
except mitogen.core.CallError, e:
print('Call failed:', str(e))
Asynchronous calls may be dispatched in parallel to multiple
contexts and consumed as they complete using
:class:`mitogen.select.Select`.
"""
LOG.debug('starting function call to %s: %r',
self.context.name or self.context.context_id,
CallSpec(fn, args, kwargs))
return self.context.send_async(self.make_msg(fn, *args, **kwargs))
def call(self, fn, *args, **kwargs):
"""
Like :meth:`call_async`, but block until the return value is available.
Equivalent to::
call_async(fn, *args, **kwargs).get().unpickle()
:returns:
The function's return value.
:raises mitogen.core.CallError:
An exception was raised in the remote context during execution.
"""
receiver = self.call_async(fn, *args, **kwargs)
return receiver.get().unpickle(throw_dead=False)
class Context(mitogen.core.Context):
"""
Extend :class:`mitogen.core.Context` with functionality useful to masters,
and child contexts who later become parents. Currently when this class is
required, the target context's router is upgraded at runtime.
"""
#: A :class:`CallChain` instance constructed by default, with pipelining
#: disabled. :meth:`call`, :meth:`call_async` and :meth:`call_no_reply` use
#: this instance.
call_chain_class = CallChain
via = None
def __init__(self, *args, **kwargs):
super(Context, self).__init__(*args, **kwargs)
self.default_call_chain = self.call_chain_class(self)
def __ne__(self, other):
return not (self == other)
def __eq__(self, other):
return (
isinstance(other, mitogen.core.Context) and
(other.context_id == self.context_id) and
(other.router == self.router)
)
def __hash__(self):
return hash((self.router, self.context_id))
def call_async(self, fn, *args, **kwargs):
"""
See :meth:`CallChain.call_async`.
"""
return self.default_call_chain.call_async(fn, *args, **kwargs)
def call(self, fn, *args, **kwargs):
"""
See :meth:`CallChain.call`.
"""
return self.default_call_chain.call(fn, *args, **kwargs)
def call_no_reply(self, fn, *args, **kwargs):
"""
See :meth:`CallChain.call_no_reply`.
"""
self.default_call_chain.call_no_reply(fn, *args, **kwargs)
def shutdown(self, wait=False):
"""
Arrange for the context to receive a ``SHUTDOWN`` message, triggering
graceful shutdown.
Due to a lack of support for timers, no attempt is made yet to force
terminate a hung context using this method. This will be fixed shortly.
:param bool wait:
If :data:`True`, block the calling thread until the context has
completely terminated.
:returns:
If `wait` is :data:`False`, returns a :class:`mitogen.core.Latch`
whose :meth:`get() <mitogen.core.Latch.get>` method returns
:data:`None` when shutdown completes. The `timeout` parameter may
be used to implement graceful timeouts.
"""
LOG.debug('%r.shutdown() sending SHUTDOWN', self)
latch = mitogen.core.Latch()
mitogen.core.listen(self, 'disconnect', lambda: latch.put(None))
self.send(
mitogen.core.Message(
handle=mitogen.core.SHUTDOWN,
)
)
if wait:
latch.get()
else:
return latch
class RouteMonitor(object):
"""
Generate and respond to :data:`mitogen.core.ADD_ROUTE` and
:data:`mitogen.core.DEL_ROUTE` messages sent to the local context by
maintaining a table of available routes, and propagating messages towards
parents and siblings as appropriate.
:class:`RouteMonitor` is responsible for generating routing messages for
directly attached children. It learns of new children via
:meth:`notice_stream` called by :class:`Router`, and subscribes to their
``disconnect`` event to learn when they disappear.
In children, constructing this class overwrites the stub
:data:`mitogen.core.DEL_ROUTE` handler installed by
:class:`mitogen.core.ExternalContext`, which is expected behaviour when a
child is beging upgraded in preparation to become a parent of children of
its own.
By virtue of only being active while responding to messages from a handler,
RouteMonitor lives entirely on the broker thread, so its data requires no
locking.
:param mitogen.master.Router router:
Router to install handlers on.
:param mitogen.core.Context parent:
:data:`None` in the master process, or reference to the parent context
we should propagate route updates towards.
"""
def __init__(self, router, parent=None):
self.router = router
self.parent = parent
self._log = logging.getLogger('mitogen.route_monitor')
#: Mapping of Stream instance to integer context IDs reachable via the
#: stream; used to cleanup routes during disconnection.
self._routes_by_stream = {}
self.router.add_handler(
fn=self._on_add_route,
handle=mitogen.core.ADD_ROUTE,
persist=True,
policy=is_immediate_child,
overwrite=True,
)
self.router.add_handler(
fn=self._on_del_route,
handle=mitogen.core.DEL_ROUTE,
persist=True,
policy=is_immediate_child,
overwrite=True,
)
def __repr__(self):
return 'RouteMonitor()'
def _send_one(self, stream, handle, target_id, name):
"""
Compose and send an update message on a stream.
:param mitogen.core.Stream stream:
Stream to send it on.
:param int handle:
:data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE`
:param int target_id:
ID of the connecting or disconnecting context.
:param str name:
Context name or :data:`None`.
"""
if not stream:
# We may not have a stream during shutdown.
return
data = str(target_id)
if name:
data = '%s:%s' % (target_id, name)
stream.protocol.send(
mitogen.core.Message(
handle=handle,
data=data.encode('utf-8'),
dst_id=stream.protocol.remote_id,
)
)
def _propagate_up(self, handle, target_id, name=None):
"""
In a non-master context, propagate an update towards the master.
:param int handle:
:data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE`
:param int target_id:
ID of the connecting or disconnecting context.
:param str name:
For :data:`mitogen.core.ADD_ROUTE`, the name of the new context
assigned by its parent. This is used by parents to assign the
:attr:`mitogen.core.Context.name` attribute.
"""
if self.parent:
stream = self.router.stream_by_id(self.parent.context_id)
self._send_one(stream, handle, target_id, name)
def _propagate_down(self, handle, target_id):
"""
For DEL_ROUTE, we additionally want to broadcast the message to any
stream that has ever communicated with the disconnecting ID, so
core.py's :meth:`mitogen.core.Router._on_del_route` can turn the
message into a disconnect event.
:param int handle:
:data:`mitogen.core.ADD_ROUTE` or :data:`mitogen.core.DEL_ROUTE`
:param int target_id:
ID of the connecting or disconnecting context.
"""
for stream in self.router.get_streams():
if target_id in stream.protocol.egress_ids and (
(self.parent is None) or
(self.parent.context_id != stream.protocol.remote_id)
):
self._send_one(stream, mitogen.core.DEL_ROUTE, target_id, None)
def notice_stream(self, stream):
"""
When this parent is responsible for a new directly connected child
stream, we're also responsible for broadcasting
:data:`mitogen.core.DEL_ROUTE` upstream when that child disconnects.
"""
self._routes_by_stream[stream] = set([stream.protocol.remote_id])
self._propagate_up(mitogen.core.ADD_ROUTE, stream.protocol.remote_id,
stream.name)
mitogen.core.listen(
obj=stream,
name='disconnect',
func=lambda: self._on_stream_disconnect(stream),
)
def get_routes(self, stream):
"""
Return the set of context IDs reachable on a stream.
:param mitogen.core.Stream stream:
:returns: set([int])
"""
return self._routes_by_stream.get(stream) or set()
def _on_stream_disconnect(self, stream):
"""
Respond to disconnection of a local stream by propagating DEL_ROUTE for
any contexts we know were attached to it.
"""
# During a stream crash it is possible for disconnect signal to fire
# twice, in which case ignore the second instance.
routes = self._routes_by_stream.pop(stream, None)
if routes is None:
return
self._log.debug('stream %s is gone; propagating DEL_ROUTE for %r',
stream.name, routes)
for target_id in routes:
self.router.del_route(target_id)
self._propagate_up(mitogen.core.DEL_ROUTE, target_id)
self._propagate_down(mitogen.core.DEL_ROUTE, target_id)
context = self.router.context_by_id(target_id, create=False)
if context:
mitogen.core.fire(context, 'disconnect')
def _on_add_route(self, msg):
"""
Respond to :data:`mitogen.core.ADD_ROUTE` by validating the source of
the message, updating the local table, and propagating the message
upwards.
"""
if msg.is_dead:
return
target_id_s, _, target_name = bytes_partition(msg.data, b(':'))
target_name = target_name.decode()
target_id = int(target_id_s)
self.router.context_by_id(target_id).name = target_name
stream = self.router.stream_by_id(msg.auth_id)
current = self.router.stream_by_id(target_id)
if current and current.protocol.remote_id != mitogen.parent_id:
self._log.error('Cannot add duplicate route to %r via %r, '
'already have existing route via %r',
target_id, stream, current)
return
self._log.debug('Adding route to %d via %r', target_id, stream)
self._routes_by_stream[stream].add(target_id)
self.router.add_route(target_id, stream)
self._propagate_up(mitogen.core.ADD_ROUTE, target_id, target_name)
def _on_del_route(self, msg):
"""
Respond to :data:`mitogen.core.DEL_ROUTE` by validating the source of
the message, updating the local table, propagating the message
upwards, and downwards towards any stream that every had a message
forwarded from it towards the disconnecting context.
"""
if msg.is_dead:
return
target_id = int(msg.data)
registered_stream = self.router.stream_by_id(target_id)
if registered_stream is None:
return
stream = self.router.stream_by_id(msg.auth_id)
if registered_stream != stream:
self._log.error('received DEL_ROUTE for %d from %r, expected %r',
target_id, stream, registered_stream)
return
context = self.router.context_by_id(target_id, create=False)
if context:
self._log.debug('firing local disconnect signal for %r', context)
mitogen.core.fire(context, 'disconnect')
self._log.debug('deleting route to %d via %r', target_id, stream)
routes = self._routes_by_stream.get(stream)
if routes:
routes.discard(target_id)
self.router.del_route(target_id)
if stream.protocol.remote_id != mitogen.parent_id:
self._propagate_up(mitogen.core.DEL_ROUTE, target_id)
self._propagate_down(mitogen.core.DEL_ROUTE, target_id)
class Router(mitogen.core.Router):
context_class = Context
debug = False
profiling = False
id_allocator = None
responder = None
log_forwarder = None
route_monitor = None
def upgrade(self, importer, parent):
LOG.debug('upgrading %r with capabilities to start new children', self)
self.id_allocator = ChildIdAllocator(router=self)
self.responder = ModuleForwarder(
router=self,
parent_context=parent,
importer=importer,
)
self.route_monitor = RouteMonitor(self, parent)
self.add_handler(
fn=self._on_detaching,
handle=mitogen.core.DETACHING,
persist=True,
)
def _on_detaching(self, msg):
if msg.is_dead:
return
stream = self.stream_by_id(msg.src_id)
if stream.protocol.remote_id != msg.src_id or stream.conn.detached:
LOG.warning('bad DETACHING received on %r: %r', stream, msg)
return
LOG.debug('%r: marking as detached', stream)
stream.conn.detached = True
msg.reply(None)
def get_streams(self):
"""
Return an atomic snapshot of all streams in existence at time of call.
This is safe to call from any thread.
"""
self._write_lock.acquire()
try:
return itervalues(self._stream_by_id)
finally:
self._write_lock.release()
def disconnect(self, context):
"""
Disconnect a context and forget its stream, assuming the context is
directly connected.
"""
stream = self.stream_by_id(context)
if stream is None or stream.protocol.remote_id != context.context_id:
return
l = mitogen.core.Latch()
mitogen.core.listen(stream, 'disconnect', l.put)
def disconnect():
LOG.debug('Starting disconnect of %r', stream)
stream.on_disconnect(self.broker)
self.broker.defer(disconnect)
l.get()
def add_route(self, target_id, stream):
"""
Arrange for messages whose `dst_id` is `target_id` to be forwarded on a
directly connected :class:`Stream`. Safe to call from any thread.
This is called automatically by :class:`RouteMonitor` in response to
:data:`mitogen.core.ADD_ROUTE` messages, but remains public while the
design has not yet settled, and situations may arise where routing is
not fully automatic.
:param int target_id:
Target context ID to add a route for.
:param mitogen.core.Stream stream:
Stream over which messages to the target should be routed.
"""
LOG.debug('%r: adding route to context %r via %r',
self, target_id, stream)
assert isinstance(target_id, int)
assert isinstance(stream, mitogen.core.Stream)
self._write_lock.acquire()
try:
self._stream_by_id[target_id] = stream
finally:
self._write_lock.release()
def del_route(self, target_id):
"""
Delete any route that exists for `target_id`. It is not an error to
delete a route that does not currently exist. Safe to call from any
thread.
This is called automatically by :class:`RouteMonitor` in response to
:data:`mitogen.core.DEL_ROUTE` messages, but remains public while the
design has not yet settled, and situations may arise where routing is
not fully automatic.
:param int target_id:
Target context ID to delete route for.
"""
LOG.debug('%r: deleting route to %r', self, target_id)
# DEL_ROUTE may be sent by a parent if it knows this context sent
# messages to a peer that has now disconnected, to let us raise
# 'disconnect' event on the appropriate Context instance. In that case,
# we won't a matching _stream_by_id entry for the disappearing route,
# so don't raise an error for a missing key here.
self._write_lock.acquire()
try:
self._stream_by_id.pop(target_id, None)
finally:
self._write_lock.release()
def get_module_blacklist(self):
if mitogen.context_id == 0:
return self.responder.blacklist
return self.importer.master_blacklist
def get_module_whitelist(self):
if mitogen.context_id == 0:
return self.responder.whitelist
return self.importer.master_whitelist
def allocate_id(self):
return self.id_allocator.allocate()
connection_timeout_msg = u"Connection timed out."
def _connect(self, klass, **kwargs):
context_id = self.allocate_id()
context = self.context_class(self, context_id)
context.name = kwargs.get('name')
kwargs['old_router'] = self
kwargs['max_message_size'] = self.max_message_size
conn = klass(klass.options_class(**kwargs), self)
try:
conn.connect(context=context)
except mitogen.core.TimeoutError:
raise mitogen.core.StreamError(self.connection_timeout_msg)
return context
def connect(self, method_name, name=None, **kwargs):
if name:
name = mitogen.core.to_text(name)
klass = get_connection_class(method_name)
kwargs.setdefault(u'debug', self.debug)
kwargs.setdefault(u'profiling', self.profiling)
kwargs.setdefault(u'unidirectional', self.unidirectional)
kwargs.setdefault(u'name', name)
via = kwargs.pop(u'via', None)
if via is not None:
return self.proxy_connect(via, method_name,
**mitogen.core.Kwargs(kwargs))
return self._connect(klass, **mitogen.core.Kwargs(kwargs))
def proxy_connect(self, via_context, method_name, name=None, **kwargs):
resp = via_context.call(_proxy_connect,
name=name,
method_name=method_name,
kwargs=mitogen.core.Kwargs(kwargs),
)
if resp['msg'] is not None:
raise mitogen.core.StreamError(resp['msg'])
name = u'%s.%s' % (via_context.name, resp['name'])
context = self.context_class(self, resp['id'], name=name)
context.via = via_context
self._write_lock.acquire()
try:
self._context_by_id[context.context_id] = context
finally:
self._write_lock.release()
return context
def buildah(self, **kwargs):
return self.connect(u'buildah', **kwargs)
def doas(self, **kwargs):
return self.connect(u'doas', **kwargs)
def docker(self, **kwargs):
return self.connect(u'docker', **kwargs)
def kubectl(self, **kwargs):
return self.connect(u'kubectl', **kwargs)
def fork(self, **kwargs):
return self.connect(u'fork', **kwargs)
def jail(self, **kwargs):
return self.connect(u'jail', **kwargs)
def local(self, **kwargs):
return self.connect(u'local', **kwargs)
def lxc(self, **kwargs):
return self.connect(u'lxc', **kwargs)
def lxd(self, **kwargs):
return self.connect(u'lxd', **kwargs)
def setns(self, **kwargs):
return self.connect(u'setns', **kwargs)
def su(self, **kwargs):
return self.connect(u'su', **kwargs)
def sudo(self, **kwargs):
return self.connect(u'sudo', **kwargs)
def ssh(self, **kwargs):
return self.connect(u'ssh', **kwargs)
class Reaper(object):
"""
Asynchronous logic for reaping :class:`Process` objects. This is necessary
to prevent uncontrolled buildup of zombie processes in long-lived parents
that will eventually reach an OS limit, preventing creation of new threads
and processes, and to log the exit status of the child in the case of an
error.
To avoid modifying process-global state such as with
:func:`signal.set_wakeup_fd` or installing a :data:`signal.SIGCHLD` handler
that might interfere with the user's ability to use those facilities,
Reaper polls for exit with backoff using timers installed on an associated
:class:`Broker`.
:param mitogen.core.Broker broker:
The :class:`Broker` on which to install timers
:param mitogen.parent.Process proc:
The process to reap.
:param bool kill:
If :data:`True`, send ``SIGTERM`` and ``SIGKILL`` to the process.
:param bool wait_on_shutdown:
If :data:`True`, delay :class:`Broker` shutdown if child has not yet
exited. If :data:`False` simply forget the child.
"""
#: :class:`Timer` that invokes :meth:`reap` after some polling delay.
_timer = None
def __init__(self, broker, proc, kill, wait_on_shutdown):
self.broker = broker
self.proc = proc
self.kill = kill
self.wait_on_shutdown = wait_on_shutdown
self._tries = 0
def _signal_child(self, signum):
# For processes like sudo we cannot actually send sudo a signal,
# because it is setuid, so this is best-effort only.
LOG.debug('%r: sending %s', self.proc, SIGNAL_BY_NUM[signum])
try:
os.kill(self.proc.pid, signum)
except OSError:
e = sys.exc_info()[1]
if e.args[0] != errno.EPERM:
raise
def _calc_delay(self, count):
"""
Calculate a poll delay given `count` attempts have already been made.
These constants have no principle, they just produce rapid but still
relatively conservative retries.
"""
delay = 0.05
for _ in xrange(count):
delay *= 1.72
return delay
def _on_broker_shutdown(self):
"""
Respond to :class:`Broker` shutdown by cancelling the reap timer if
:attr:`Router.await_children_at_shutdown` is disabled. Otherwise
shutdown is delayed for up to :attr:`Broker.shutdown_timeout` for
subprocesses may have no intention of exiting any time soon.
"""
if not self.wait_on_shutdown:
self._timer.cancel()
def _install_timer(self, delay):
new = self._timer is None
self._timer = self.broker.timers.schedule(
when=mitogen.core.now() + delay,
func=self.reap,
)
if new:
mitogen.core.listen(self.broker, 'shutdown',
self._on_broker_shutdown)
def _remove_timer(self):
if self._timer and self._timer.active:
self._timer.cancel()
mitogen.core.unlisten(self.broker, 'shutdown',
self._on_broker_shutdown)
def reap(self):
"""
Reap the child process during disconnection.
"""
status = self.proc.poll()
if status is not None:
LOG.debug('%r: %s', self.proc, returncode_to_str(status))
mitogen.core.fire(self.proc, 'exit')
self._remove_timer()
return
self._tries += 1
if self._tries > 20:
LOG.warning('%r: child will not exit, giving up', self)
self._remove_timer()
return
delay = self._calc_delay(self._tries - 1)
LOG.debug('%r still running after IO disconnect, recheck in %.03fs',
self.proc, delay)
self._install_timer(delay)
if not self.kill:
pass
elif self._tries == 2:
self._signal_child(signal.SIGTERM)
elif self._tries == 6: # roughly 4 seconds
self._signal_child(signal.SIGKILL)
class Process(object):
"""
Process objects provide a uniform interface to the :mod:`subprocess` and
:mod:`mitogen.fork`. This class is extended by :class:`PopenProcess` and
:class:`mitogen.fork.Process`.
:param int pid:
The process ID.
:param file stdin:
File object attached to standard input.
:param file stdout:
File object attached to standard output.
:param file stderr:
File object attached to standard error, or :data:`None`.
"""
#: Name of the process used in logs. Set to the stream/context name by
#: :class:`Connection`.
name = None
def __init__(self, pid, stdin, stdout, stderr=None):
#: The process ID.
self.pid = pid
#: File object attached to standard input.
self.stdin = stdin
#: File object attached to standard output.
self.stdout = stdout
#: File object attached to standard error.
self.stderr = stderr
def __repr__(self):
return '%s %s pid %d' % (
type(self).__name__,
self.name,
self.pid,
)
def poll(self):
"""
Fetch the child process exit status, or :data:`None` if it is still
running. This should be overridden by subclasses.
:returns:
Exit status in the style of the :attr:`subprocess.Popen.returncode`
attribute, i.e. with signals represented by a negative integer.
"""
raise NotImplementedError()
class PopenProcess(Process):
"""
:class:`Process` subclass wrapping a :class:`subprocess.Popen` object.
:param subprocess.Popen proc:
The subprocess.
"""
def __init__(self, proc, stdin, stdout, stderr=None):
super(PopenProcess, self).__init__(proc.pid, stdin, stdout, stderr)
#: The subprocess.
self.proc = proc
def poll(self):
return self.proc.poll()
class ModuleForwarder(object):
"""
Respond to :data:`mitogen.core.GET_MODULE` requests in a child by
forwarding the request to our parent context, or satisfying the request
from our local Importer cache.
"""
def __init__(self, router, parent_context, importer):
self.router = router
self.parent_context = parent_context
self.importer = importer
router.add_handler(
fn=self._on_forward_module,
handle=mitogen.core.FORWARD_MODULE,
persist=True,
policy=mitogen.core.has_parent_authority,
)
router.add_handler(
fn=self._on_get_module,
handle=mitogen.core.GET_MODULE,
persist=True,
policy=is_immediate_child,
)
def __repr__(self):
return 'ModuleForwarder'
def _on_forward_module(self, msg):
if msg.is_dead:
return
context_id_s, _, fullname = bytes_partition(msg.data, b('\x00'))
fullname = mitogen.core.to_text(fullname)
context_id = int(context_id_s)
stream = self.router.stream_by_id(context_id)
if stream.protocol.remote_id == mitogen.parent_id:
LOG.error('%r: dropping FORWARD_MODULE(%d, %r): no route to child',
self, context_id, fullname)
return
if fullname in stream.protocol.sent_modules:
return
LOG.debug('%r._on_forward_module() sending %r to %r via %r',
self, fullname, context_id, stream.protocol.remote_id)
self._send_module_and_related(stream, fullname)
if stream.protocol.remote_id != context_id:
stream.protocol._send(
mitogen.core.Message(
data=msg.data,
handle=mitogen.core.FORWARD_MODULE,
dst_id=stream.protocol.remote_id,
)
)
def _on_get_module(self, msg):
if msg.is_dead:
return
fullname = msg.data.decode('utf-8')
LOG.debug('%r: %s requested by context %d', self, fullname, msg.src_id)
callback = lambda: self._on_cache_callback(msg, fullname)
self.importer._request_module(fullname, callback)
def _on_cache_callback(self, msg, fullname):
stream = self.router.stream_by_id(msg.src_id)
LOG.debug('%r: sending %s to %r', self, fullname, stream)
self._send_module_and_related(stream, fullname)
def _send_module_and_related(self, stream, fullname):
tup = self.importer._cache[fullname]
for related in tup[4]:
rtup = self.importer._cache.get(related)
if rtup:
self._send_one_module(stream, rtup)
else:
LOG.debug('%r: %s not in cache (for %s)',
self, related, fullname)
self._send_one_module(stream, tup)
def _send_one_module(self, stream, tup):
if tup[0] not in stream.protocol.sent_modules:
stream.protocol.sent_modules.add(tup[0])
self.router._async_route(
mitogen.core.Message.pickled(
tup,
dst_id=stream.protocol.remote_id,
handle=mitogen.core.LOAD_MODULE,
)
)
| 35.06426 | 83 | 0.625309 |
import codecs
import errno
import fcntl
import getpass
import heapq
import inspect
import logging
import os
import re
import signal
import socket
import struct
import subprocess
import sys
import termios
import textwrap
import threading
import zlib
select = __import__('select')
try:
import thread
except ImportError:
import threading as thread
import mitogen.core
from mitogen.core import b
from mitogen.core import bytes_partition
from mitogen.core import IOLOG
LOG = logging.getLogger(__name__)
SELINUX_ENABLED = bool(int(fp.read()))
finally:
fp.close()
except IOError:
SELINUX_ENABLED = False
try:
next
except NameError:
from mitogen.core import next
itervalues = getattr(dict, 'itervalues', dict.values)
if mitogen.core.PY3:
xrange = range
closure_attr = '__closure__'
IM_SELF_ATTR = '__self__'
else:
closure_attr = 'func_closure'
IM_SELF_ATTR = 'im_self'
try:
SC_OPEN_MAX = os.sysconf('SC_OPEN_MAX')
except ValueError:
SC_OPEN_MAX = 1024
BROKER_SHUTDOWN_MSG = (
'Connection cancelled because the associated Broker began to shut down.'
)
OPENPTY_MSG = (
"Failed to create a PTY: %s. It is likely the maximum number of PTYs has "
"been reached. Consider increasing the 'kern.tty.ptmx_max' sysctl on OS "
"X, the 'kernel.pty.max' sysctl on Linux, or modifying your configuration "
"to avoid PTY use."
)
SYS_EXECUTABLE_MSG = (
"The Python sys.executable variable is unset, indicating Python was "
"unable to determine its original program name. Unless explicitly "
"configured otherwise, child contexts will be started using "
"'/usr/bin/python'"
)
_sys_executable_warning_logged = False
def _ioctl_cast(n):
if sys.version_info < (2, 5):
n, = struct.unpack('i', struct.pack('I', n))
return n
_preexec_hook = None
LINUX_TIOCGPTN = _ioctl_cast(2147767344)
LINUX_TIOCSPTLCK = _ioctl_cast(1074025521)
IS_LINUX = os.uname()[0] == 'Linux'
SIGNAL_BY_NUM = dict(
(getattr(signal, name), name)
for name in sorted(vars(signal), reverse=True)
if name.startswith('SIG') and not name.startswith('SIG_')
)
_core_source_lock = threading.Lock()
_core_source_partial = None
def get_log_level():
return (LOG.getEffectiveLevel() or logging.INFO)
def get_sys_executable():
if sys.executable:
return sys.executable
global _sys_executable_warning_logged
if not _sys_executable_warning_logged:
LOG.warn(SYS_EXECUTABLE_MSG)
_sys_executable_warning_logged = True
return '/usr/bin/python'
def _get_core_source():
return inspect.getsource(mitogen.core)
def get_core_source_partial():
global _core_source_partial
if _core_source_partial is None:
_core_source_lock.acquire()
try:
if _core_source_partial is None:
_core_source_partial = PartialZlib(
_get_core_source().encode('utf-8')
)
finally:
_core_source_lock.release()
return _core_source_partial
def get_default_remote_name():
s = u'%s@%s:%d'
s %= (getpass.getuser(), socket.gethostname(), os.getpid())
return s.translate({
ord(u'\\'): ord(u'_'),
ord(u'/'): ord(u'_')
})
def is_immediate_child(msg, stream):
return msg.src_id == stream.protocol.remote_id
def flags(names):
return sum(getattr(termios, name, 0)
for name in names.split())
def cfmakeraw(tflags):
iflag, oflag, cflag, lflag, ispeed, ospeed, cc = tflags
iflag &= ~flags('IMAXBEL IXOFF INPCK BRKINT PARMRK '
'ISTRIP INLCR ICRNL IXON IGNPAR')
iflag &= ~flags('IGNBRK BRKINT PARMRK')
oflag &= ~flags('OPOST')
lflag &= ~flags('ECHO ECHOE ECHOK ECHONL ICANON ISIG '
'IEXTEN NOFLSH TOSTOP PENDIN')
cflag &= ~flags('CSIZE PARENB')
cflag |= flags('CS8 CREAD')
return [iflag, oflag, cflag, lflag, ispeed, ospeed, cc]
def disable_echo(fd):
old = termios.tcgetattr(fd)
new = cfmakeraw(old)
flags = getattr(termios, 'TCSASOFT', 0)
if not mitogen.core.IS_WSL:
ttr(fd, flags, new)
def create_socketpair(size=None):
if size is None:
size = mitogen.core.CHUNK_SIZE
parentfp, childfp = socket.socketpair()
for fp in parentfp, childfp:
fp.setsockopt(socket.SOL_SOCKET, socket.SO_SNDBUF, size)
return parentfp, childfp
def create_best_pipe(escalates_privilege=False):
if (not escalates_privilege) or (not SELINUX_ENABLED):
parentfp, childfp = create_socketpair()
return parentfp, childfp, childfp, parentfp
parent_rfp, child_wfp = mitogen.core.pipe()
try:
child_rfp, parent_wfp = mitogen.core.pipe()
return parent_rfp, child_wfp, child_rfp, parent_wfp
except:
parent_rfp.close()
child_wfp.close()
raise
def popen(**kwargs):
real_preexec_fn = kwargs.pop('preexec_fn', None)
def preexec_fn():
if _preexec_hook:
_preexec_hook()
if real_preexec_fn:
real_preexec_fn()
return subprocess.Popen(preexec_fn=preexec_fn, **kwargs)
def create_child(args, merge_stdio=False, stderr_pipe=False,
escalates_privilege=False, preexec_fn=None):
parent_rfp, child_wfp, child_rfp, parent_wfp = create_best_pipe(
escalates_privilege=escalates_privilege
)
stderr = None
stderr_r = None
if merge_stdio:
stderr = child_wfp
elif stderr_pipe:
stderr_r, stderr = mitogen.core.pipe()
mitogen.core.set_cloexec(stderr_r.fileno())
try:
proc = popen(
args=args,
stdin=child_rfp,
stdout=child_wfp,
stderr=stderr,
close_fds=True,
preexec_fn=preexec_fn,
)
except:
child_rfp.close()
child_wfp.close()
parent_rfp.close()
parent_wfp.close()
if stderr_pipe:
stderr.close()
stderr_r.close()
raise
child_rfp.close()
child_wfp.close()
if stderr_pipe:
stderr.close()
return PopenProcess(
proc=proc,
stdin=parent_wfp,
stdout=parent_rfp,
stderr=stderr_r,
)
def _acquire_controlling_tty():
os.setsid()
if sys.platform in ('linux', 'linux2'):
os.close(os.open(os.ttyname(2), os.O_RDWR))
if hasattr(termios, 'TIOCSCTTY') and not mitogen.core.IS_WSL:
ios.TIOCSCTTY)
def _linux_broken_devpts_openpty():
master_fd = None
try:
master_fd = os.open('/dev/ptmx', os.O_RDWR)
fcntl.ioctl(master_fd, LINUX_TIOCSPTLCK, struct.pack('i', 0))
pty_num_s = fcntl.ioctl(master_fd, LINUX_TIOCGPTN,
struct.pack('i', 0))
pty_num, = struct.unpack('i', pty_num_s)
pty_name = '/dev/pts/%d' % (pty_num,)
# TTY. Otherwise when we close the FD we get killed by the kernel, and
# the child we spawn that should really attach to it will get EPERM
# during _acquire_controlling_tty().
slave_fd = os.open(pty_name, os.O_RDWR|os.O_NOCTTY)
return master_fd, slave_fd
except OSError:
if master_fd is not None:
os.close(master_fd)
e = sys.exc_info()[1]
raise mitogen.core.StreamError(OPENPTY_MSG, e)
def openpty():
try:
master_fd, slave_fd = os.openpty()
except OSError:
e = sys.exc_info()[1]
if not (IS_LINUX and e.args[0] == errno.EPERM):
raise mitogen.core.StreamError(OPENPTY_MSG, e)
master_fd, slave_fd = _linux_broken_devpts_openpty()
master_fp = os.fdopen(master_fd, 'r+b', 0)
slave_fp = os.fdopen(slave_fd, 'r+b', 0)
disable_echo(master_fd)
disable_echo(slave_fd)
mitogen.core.set_block(slave_fd)
return master_fp, slave_fp
def tty_create_child(args):
master_fp, slave_fp = openpty()
try:
proc = popen(
args=args,
stdin=slave_fp,
stdout=slave_fp,
stderr=slave_fp,
preexec_fn=_acquire_controlling_tty,
close_fds=True,
)
except:
master_fp.close()
slave_fp.close()
raise
slave_fp.close()
return PopenProcess(
proc=proc,
stdin=master_fp,
stdout=master_fp,
)
def hybrid_tty_create_child(args, escalates_privilege=False):
master_fp, slave_fp = openpty()
try:
parent_rfp, child_wfp, child_rfp, parent_wfp = create_best_pipe(
escalates_privilege=escalates_privilege,
)
try:
mitogen.core.set_block(child_rfp)
mitogen.core.set_block(child_wfp)
proc = popen(
args=args,
stdin=child_rfp,
stdout=child_wfp,
stderr=slave_fp,
preexec_fn=_acquire_controlling_tty,
close_fds=True,
)
except:
parent_rfp.close()
child_wfp.close()
parent_wfp.close()
child_rfp.close()
raise
except:
master_fp.close()
slave_fp.close()
raise
slave_fp.close()
child_rfp.close()
child_wfp.close()
return PopenProcess(
proc=proc,
stdin=parent_wfp,
stdout=parent_rfp,
stderr=master_fp,
)
class Timer(object):
#: Set to :data:`False` if :meth:`cancel` has been called, or immediately
#: prior to being executed by :meth:`TimerList.expire`.
active = True
def __init__(self, when, func):
self.when = when
self.func = func
def __repr__(self):
return 'Timer(%r, %r)' % (self.when, self.func)
def __eq__(self, other):
return self.when == other.when
def __lt__(self, other):
return self.when < other.when
def __le__(self, other):
return self.when <= other.when
def cancel(self):
self.active = False
class TimerList(object):
_now = mitogen.core.now
def __init__(self):
self._lst = []
def get_timeout(self):
while self._lst and not self._lst[0].active:
heapq.heappop(self._lst)
if self._lst:
return max(0, self._lst[0].when - self._now())
def schedule(self, when, func):
timer = Timer(when, func)
heapq.heappush(self._lst, timer)
return timer
def expire(self):
now = self._now()
while self._lst and self._lst[0].when <= now:
timer = heapq.heappop(self._lst)
if timer.active:
timer.active = False
timer.func()
class PartialZlib(object):
def __init__(self, s):
self.s = s
if sys.version_info > (2, 5):
self._compressor = zlib.compressobj(9)
self._out = self._compressor.compress(s)
self._out += self._compressor.flush(zlib.Z_SYNC_FLUSH)
else:
self._compressor = None
def append(self, s):
if self._compressor is None:
return zlib.compress(self.s + s, 9)
else:
compressor = self._compressor.copy()
out = self._out
out += compressor.compress(s)
return out + compressor.flush()
def _upgrade_broker(broker):
# This function is deadly! The act of calling start_receive() generates log
# messages which must be silenced as the upgrade progresses, otherwise the
# poller state will change as it is copied, resulting in write fds that are
# lost. (Due to LogHandler->Router->Stream->Protocol->Broker->Poller, where
# Stream only calls start_transmit() when transitioning from empty to
# non-empty buffer. If the start_transmit() is lost, writes from the child
# hang permanently).
root = logging.getLogger()
old_level = root.level
root.setLevel(logging.CRITICAL)
try:
old = broker.poller
new = PREFERRED_POLLER()
for fd, data in old.readers:
new.start_receive(fd, data)
for fd, data in old.writers:
new.start_transmit(fd, data)
old.close()
broker.poller = new
finally:
root.setLevel(old_level)
broker.timers = TimerList()
LOG.debug('upgraded %r with %r (new: %d readers, %d writers; '
'old: %d readers, %d writers)', old, new,
len(new.readers), len(new.writers),
len(old.readers), len(old.writers))
@mitogen.core.takes_econtext
def upgrade_router(econtext):
if not isinstance(econtext.router, Router): # TODO
econtext.broker.defer(_upgrade_broker, econtext.broker)
econtext.router.__class__ = Router # TODO
econtext.router.upgrade(
importer=econtext.importer,
parent=econtext.parent,
)
def get_connection_class(name):
if name == u'local':
name = u'parent'
module = mitogen.core.import_module(u'mitogen.' + name)
return module.Connection
@mitogen.core.takes_econtext
def _proxy_connect(name, method_name, kwargs, econtext):
upgrade_router(econtext)
try:
context = econtext.router._connect(
klass=get_connection_class(method_name),
name=name,
**kwargs
)
except mitogen.core.StreamError:
return {
u'id': None,
u'name': None,
u'msg': 'error occurred on host %s: %s' % (
socket.gethostname(),
sys.exc_info()[1],
),
}
return {
u'id': context.context_id,
u'name': context.name,
u'msg': None,
}
def returncode_to_str(n):
if n < 0:
return 'exited due to signal %d (%s)' % (-n, SIGNAL_BY_NUM.get(-n))
return 'exited with return code %d' % (n,)
class EofError(mitogen.core.StreamError):
# inherits from StreamError to maintain compatibility.
pass
class CancelledError(mitogen.core.StreamError):
pass
class Argv(object):
def __init__(self, argv):
self.argv = argv
must_escape = frozenset('\\$"`!')
must_escape_or_space = must_escape | frozenset(' ')
def escape(self, x):
if not self.must_escape_or_space.intersection(x):
return x
s = '"'
for c in x:
if c in self.must_escape:
s += '\\'
s += c
s += '"'
return s
def __str__(self):
return ' '.join(map(self.escape, self.argv))
class CallSpec(object):
def __init__(self, func, args, kwargs):
self.func = func
self.args = args
self.kwargs = kwargs
def _get_name(self):
bits = [self.func.__module__]
if inspect.ismethod(self.func):
im_self = getattr(self.func, IM_SELF_ATTR)
bits.append(getattr(im_self, '__name__', None) or
getattr(type(im_self), '__name__', None))
bits.append(self.func.__name__)
return u'.'.join(bits)
def _get_args(self):
return u', '.join(repr(a) for a in self.args)
def _get_kwargs(self):
s = u''
if self.kwargs:
s = u', '.join('%s=%r' % (k, v) for k, v in self.kwargs.items())
if self.args:
s = u', ' + s
return s
def __repr__(self):
return '%s(%s%s)' % (
self._get_name(),
self._get_args(),
self._get_kwargs(),
)
class PollPoller(mitogen.core.Poller):
SUPPORTED = hasattr(select, 'poll')
_repr = 'PollPoller()'
def __init__(self):
super(PollPoller, self).__init__()
self._pollobj = select.poll()
# TODO: no proof we dont need writemask too
_readmask = (
getattr(select, 'POLLIN', 0) |
getattr(select, 'POLLHUP', 0)
)
def _update(self, fd):
mask = (((fd in self._rfds) and self._readmask) |
((fd in self._wfds) and select.POLLOUT))
if mask:
self._pollobj.register(fd, mask)
else:
try:
self._pollobj.unregister(fd)
except KeyError:
pass
def _poll(self, timeout):
if timeout:
timeout *= 1000
events, _ = mitogen.core.io_op(self._pollobj.poll, timeout)
for fd, event in events:
if event & self._readmask:
IOLOG.debug('%r: POLLIN|POLLHUP for %r', self, fd)
data, gen = self._rfds.get(fd, (None, None))
if gen and gen < self._generation:
yield data
if event & select.POLLOUT:
IOLOG.debug('%r: POLLOUT for %r', self, fd)
data, gen = self._wfds.get(fd, (None, None))
if gen and gen < self._generation:
yield data
class KqueuePoller(mitogen.core.Poller):
SUPPORTED = hasattr(select, 'kqueue')
_repr = 'KqueuePoller()'
def __init__(self):
super(KqueuePoller, self).__init__()
self._kqueue = select.kqueue()
self._changelist = []
def close(self):
super(KqueuePoller, self).close()
self._kqueue.close()
def _control(self, fd, filters, flags):
mitogen.core._vv and IOLOG.debug(
'%r._control(%r, %r, %r)', self, fd, filters, flags)
# TODO: at shutdown it is currently possible for KQ_EV_ADD/KQ_EV_DEL
# pairs to be pending after the associated file descriptor has already
# been closed. Fixing this requires maintaining extra state, or perhaps
# making fd closure the poller's responsibility. In the meantime,
# simply apply changes immediately.
# self._changelist.append(select.kevent(fd, filters, flags))
changelist = [select.kevent(fd, filters, flags)]
events, _ = mitogen.core.io_op(self._kqueue.control, changelist, 0, 0)
assert not events
def start_receive(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_receive(%r, %r)',
self, fd, data)
if fd not in self._rfds:
self._control(fd, select.KQ_FILTER_READ, select.KQ_EV_ADD)
self._rfds[fd] = (data or fd, self._generation)
def stop_receive(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_receive(%r)', self, fd)
if fd in self._rfds:
self._control(fd, select.KQ_FILTER_READ, select.KQ_EV_DELETE)
del self._rfds[fd]
def start_transmit(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_transmit(%r, %r)',
self, fd, data)
if fd not in self._wfds:
self._control(fd, select.KQ_FILTER_WRITE, select.KQ_EV_ADD)
self._wfds[fd] = (data or fd, self._generation)
def stop_transmit(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_transmit(%r)', self, fd)
if fd in self._wfds:
self._control(fd, select.KQ_FILTER_WRITE, select.KQ_EV_DELETE)
del self._wfds[fd]
def _poll(self, timeout):
changelist = self._changelist
self._changelist = []
events, _ = mitogen.core.io_op(self._kqueue.control,
changelist, 32, timeout)
for event in events:
fd = event.ident
if event.flags & select.KQ_EV_ERROR:
LOG.debug('ignoring stale event for fd %r: errno=%d: %s',
fd, event.data, errno.errorcode.get(event.data))
elif event.filter == select.KQ_FILTER_READ:
data, gen = self._rfds.get(fd, (None, None))
# Events can still be read for an already-discarded fd.
if gen and gen < self._generation:
mitogen.core._vv and IOLOG.debug('%r: POLLIN: %r', self, fd)
yield data
elif event.filter == select.KQ_FILTER_WRITE and fd in self._wfds:
data, gen = self._wfds.get(fd, (None, None))
if gen and gen < self._generation:
mitogen.core._vv and IOLOG.debug('%r: POLLOUT: %r', self, fd)
yield data
class EpollPoller(mitogen.core.Poller):
SUPPORTED = hasattr(select, 'epoll')
_repr = 'EpollPoller()'
def __init__(self):
super(EpollPoller, self).__init__()
self._epoll = select.epoll(32)
self._registered_fds = set()
def close(self):
super(EpollPoller, self).close()
self._epoll.close()
def _control(self, fd):
mitogen.core._vv and IOLOG.debug('%r._control(%r)', self, fd)
mask = (((fd in self._rfds) and select.EPOLLIN) |
((fd in self._wfds) and select.EPOLLOUT))
if mask:
if fd in self._registered_fds:
self._epoll.modify(fd, mask)
else:
self._epoll.register(fd, mask)
self._registered_fds.add(fd)
elif fd in self._registered_fds:
self._epoll.unregister(fd)
self._registered_fds.remove(fd)
def start_receive(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_receive(%r, %r)',
self, fd, data)
self._rfds[fd] = (data or fd, self._generation)
self._control(fd)
def stop_receive(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_receive(%r)', self, fd)
self._rfds.pop(fd, None)
self._control(fd)
def start_transmit(self, fd, data=None):
mitogen.core._vv and IOLOG.debug('%r.start_transmit(%r, %r)',
self, fd, data)
self._wfds[fd] = (data or fd, self._generation)
self._control(fd)
def stop_transmit(self, fd):
mitogen.core._vv and IOLOG.debug('%r.stop_transmit(%r)', self, fd)
self._wfds.pop(fd, None)
self._control(fd)
_inmask = (getattr(select, 'EPOLLIN', 0) |
getattr(select, 'EPOLLHUP', 0))
def _poll(self, timeout):
the_timeout = -1
if timeout is not None:
the_timeout = timeout
events, _ = mitogen.core.io_op(self._epoll.poll, the_timeout, 32)
for fd, event in events:
if event & self._inmask:
data, gen = self._rfds.get(fd, (None, None))
if gen and gen < self._generation:
# Events can still be read for an already-discarded fd.
mitogen.core._vv and IOLOG.debug('%r: POLLIN: %r', self, fd)
yield data
if event & select.EPOLLOUT:
data, gen = self._wfds.get(fd, (None, None))
if gen and gen < self._generation:
mitogen.core._vv and IOLOG.debug('%r: POLLOUT: %r', self, fd)
yield data
# 2.4 and 2.5 only had select.select() and select.poll().
for _klass in mitogen.core.Poller, PollPoller, KqueuePoller, EpollPoller:
if _klass.SUPPORTED:
PREFERRED_POLLER = _klass
# For processes that start many threads or connections, it's possible Latch
# will also get high-numbered FDs, and so select() becomes useless there too.
# So swap in our favourite poller.
if PollPoller.SUPPORTED:
mitogen.core.Latch.poller_class = PollPoller
else:
mitogen.core.Latch.poller_class = PREFERRED_POLLER
class LineLoggingProtocolMixin(object):
def __init__(self, **kwargs):
super(LineLoggingProtocolMixin, self).__init__(**kwargs)
self.logged_lines = []
self.logged_partial = None
def on_line_received(self, line):
self.logged_partial = None
self.logged_lines.append((mitogen.core.now(), line))
self.logged_lines[:] = self.logged_lines[-100:]
return super(LineLoggingProtocolMixin, self).on_line_received(line)
def on_partial_line_received(self, line):
self.logged_partial = line
return super(LineLoggingProtocolMixin, self).on_partial_line_received(line)
def on_disconnect(self, broker):
if self.logged_partial:
self.logged_lines.append((mitogen.core.now(), self.logged_partial))
self.logged_partial = None
super(LineLoggingProtocolMixin, self).on_disconnect(broker)
def get_history(streams):
history = []
for stream in streams:
if stream:
history.extend(getattr(stream.protocol, 'logged_lines', []))
history.sort()
s = b('\n').join(h[1] for h in history)
return mitogen.core.to_text(s)
class RegexProtocol(LineLoggingProtocolMixin, mitogen.core.DelimitedProtocol):
#: A sequence of 2-tuples of the form `(compiled pattern, method)` for
#: patterns that should be matched against complete (delimited) messages,
#: i.e. full lines.
PATTERNS = []
#: Like :attr:`PATTERNS`, but patterns that are matched against incomplete
#: lines.
PARTIAL_PATTERNS = []
def on_line_received(self, line):
super(RegexProtocol, self).on_line_received(line)
for pattern, func in self.PATTERNS:
match = pattern.search(line)
if match is not None:
return func(self, line, match)
return self.on_unrecognized_line_received(line)
def on_unrecognized_line_received(self, line):
LOG.debug('%s: (unrecognized): %s',
self.stream.name, line.decode('utf-8', 'replace'))
def on_partial_line_received(self, line):
super(RegexProtocol, self).on_partial_line_received(line)
LOG.debug('%s: (partial): %s',
self.stream.name, line.decode('utf-8', 'replace'))
for pattern, func in self.PARTIAL_PATTERNS:
match = pattern.search(line)
if match is not None:
return func(self, line, match)
return self.on_unrecognized_partial_line_received(line)
def on_unrecognized_partial_line_received(self, line):
LOG.debug('%s: (unrecognized partial): %s',
self.stream.name, line.decode('utf-8', 'replace'))
class BootstrapProtocol(RegexProtocol):
#: Sentinel value emitted by the first stage to indicate it is ready to
#: receive the compressed bootstrap. For :mod:`mitogen.ssh` this must have
#: length of at least `max(len('password'), len('debug1:'))`
EC0_MARKER = b('MITO000')
EC1_MARKER = b('MITO001')
EC2_MARKER = b('MITO002')
def __init__(self, broker):
super(BootstrapProtocol, self).__init__()
self._writer = mitogen.core.BufferedWriter(broker, self)
def on_transmit(self, broker):
self._writer.on_transmit(broker)
def _on_ec0_received(self, line, match):
LOG.debug('%r: first stage started succcessfully', self)
self._writer.write(self.stream.conn.get_preamble())
def _on_ec1_received(self, line, match):
LOG.debug('%r: first stage received mitogen.core source', self)
def _on_ec2_received(self, line, match):
LOG.debug('%r: new child booted successfully', self)
self.stream.conn._complete_connection()
return False
def on_unrecognized_line_received(self, line):
LOG.debug('%s: stdout: %s', self.stream.name,
line.decode('utf-8', 'replace'))
PATTERNS = [
(re.compile(EC0_MARKER), _on_ec0_received),
(re.compile(EC1_MARKER), _on_ec1_received),
(re.compile(EC2_MARKER), _on_ec2_received),
]
class LogProtocol(LineLoggingProtocolMixin, mitogen.core.DelimitedProtocol):
def on_line_received(self, line):
super(LogProtocol, self).on_line_received(line)
LOG.info(u'%s: %s', self.stream.name, line.decode('utf-8', 'replace'))
class MitogenProtocol(mitogen.core.MitogenProtocol):
def on_shutdown(self, broker):
LOG.debug('%r: requesting child shutdown', self)
self._send(
mitogen.core.Message(
src_id=mitogen.context_id,
dst_id=self.remote_id,
handle=mitogen.core.SHUTDOWN,
)
)
class Options(object):
name = None
#: The path to the remote Python interpreter.
python_path = get_sys_executable()
#: Maximum time to wait for a connection attempt.
connect_timeout = 30.0
#: True to cause context to write verbose /tmp/mitogen.<pid>.log.
debug = False
#: True to cause context to write /tmp/mitogen.stats.<pid>.<thread>.log.
profiling = False
#: True if unidirectional routing is enabled in the new child.
unidirectional = False
#: Passed via Router wrapper methods, must eventually be passed to
#: ExternalContext.main().
max_message_size = None
#: Remote name.
remote_name = None
#: Derived from :py:attr:`connect_timeout`; absolute floating point
#: UNIX timestamp after which the connection attempt should be abandoned.
connect_deadline = None
def __init__(self, max_message_size, name=None, remote_name=None,
python_path=None, debug=False, connect_timeout=None,
profiling=False, unidirectional=False, old_router=None):
self.name = name
self.max_message_size = max_message_size
if python_path:
self.python_path = python_path
if connect_timeout:
self.connect_timeout = connect_timeout
if remote_name is None:
remote_name = get_default_remote_name()
if '/' in remote_name or '\\' in remote_name:
raise ValueError('remote_name= cannot contain slashes')
if remote_name:
self.remote_name = mitogen.core.to_text(remote_name)
self.debug = debug
self.profiling = profiling
self.unidirectional = unidirectional
self.max_message_size = max_message_size
self.connect_deadline = mitogen.core.now() + self.connect_timeout
class Connection(object):
options_class = Options
#: The protocol attached to stdio of the child.
stream_protocol_class = BootstrapProtocol
#: The protocol attached to stderr of the child.
diag_protocol_class = LogProtocol
#: :class:`Process`
proc = None
#: :class:`mitogen.core.Stream` with sides connected to stdin/stdout.
stdio_stream = None
#: If `proc.stderr` is set, referencing either a plain pipe or the
#: controlling TTY, this references the corresponding
#: :class:`LogProtocol`'s stream, allowing it to be disconnected when this
#: stream is disconnected.
stderr_stream = None
#: Function with the semantics of :func:`create_child` used to create the
#: child process.
create_child = staticmethod(create_child)
#: Dictionary of extra kwargs passed to :attr:`create_child`.
create_child_args = {}
#: :data:`True` if the remote has indicated that it intends to detach, and
#: should not be killed on disconnect.
detached = False
#: If :data:`True`, indicates the child should not be killed during
#: graceful detachment, as it the actual process implementing the child
#: context. In all other cases, the subprocess is SSH, sudo, or a similar
#: tool that should be reminded to quit during disconnection.
child_is_immediate_subprocess = True
#: Prefix given to default names generated by :meth:`connect`.
name_prefix = u'local'
#: :class:`Timer` that runs :meth:`_on_timer_expired` when connection
#: timeout occurs.
_timer = None
#: When disconnection completes, instance of :class:`Reaper` used to wait
#: on the exit status of the subprocess.
_reaper = None
#: On failure, the exception object that should be propagated back to the
#: user.
exception = None
#: Extra text appended to :class:`EofError` if that exception is raised on
#: a failed connection attempt. May be used in subclasses to hint at common
#: problems with a particular connection method.
eof_error_hint = None
def __init__(self, options, router):
#: :class:`Options`
self.options = options
self._router = router
def __repr__(self):
return 'Connection(%r)' % (self.stdio_stream,)
# Minimised, gzipped, base64'd and passed to 'python -c'. It forks, dups
# file descriptor 0 as 100, creates a pipe, then execs a new interpreter
# with a custom argv.
# * Optimized for minimum byte count after minification & compression.
# * 'CONTEXT_NAME' and 'PREAMBLE_COMPRESSED_LEN' are substituted with
# their respective values.
# * CONTEXT_NAME must be prefixed with the name of the Python binary in
# order to allow virtualenvs to detect their install prefix.
# * For Darwin, OS X installs a craptacular argv0-introspecting Python
# version switcher as /usr/bin/python. Override attempts to call it
# with an explicit call to python2.7
#
# Locals:
# R: read side of interpreter stdin.
# W: write side of interpreter stdin.
# r: read side of core_src FD.
# w: write side of core_src FD.
# C: the decompressed core source.
# Final os.close(2) to avoid --py-debug build from corrupting stream with
# "[1234 refs]" during exit.
@staticmethod
def _first_stage():
R,W=os.pipe()
r,w=os.pipe()
if os.fork():
os.dup2(0,100)
os.dup2(R,0)
os.dup2(r,101)
os.close(R)
os.close(r)
os.close(W)
os.close(w)
if sys.platform == 'darwin' and sys.executable == '/usr/bin/python':
sys.executable += sys.version[:3]
os.environ['ARGV0']=sys.executable
os.execl(sys.executable,sys.executable+'(mitogen:CONTEXT_NAME)')
os.write(1,'MITO000\n'.encode())
C=_(os.fdopen(0,'rb').read(PREAMBLE_COMPRESSED_LEN),'zip')
fp=os.fdopen(W,'wb',0)
fp.write(C)
fp.close()
fp=os.fdopen(w,'wb',0)
fp.write(C)
fp.close()
os.write(1,'MITO001\n'.encode())
os.close(2)
def get_python_argv(self):
if isinstance(self.options.python_path, list):
return self.options.python_path
return [self.options.python_path]
def get_boot_command(self):
source = inspect.getsource(self._first_stage)
source = textwrap.dedent('\n'.join(source.strip().split('\n')[2:]))
source = source.replace(' ', '\t')
source = source.replace('CONTEXT_NAME', self.options.remote_name)
preamble_compressed = self.get_preamble()
source = source.replace('PREAMBLE_COMPRESSED_LEN',
str(len(preamble_compressed)))
compressed = zlib.compress(source.encode(), 9)
encoded = codecs.encode(compressed, 'base64').replace(b('\n'), b(''))
# We can't use bytes.decode() in 3.x since it was restricted to always
# return unicode, so codecs.decode() is used instead. In 3.x
# codecs.decode() requires a bytes object. Since we must be compatible
# with 2.4 (no bytes literal), an extra .encode() either returns the
# same str (2.x) or an equivalent bytes (3.x).
return self.get_python_argv() + [
'-c',
'import codecs,os,sys;_=codecs.decode;'
'exec(_(_("%s".encode(),"base64"),"zip"))' % (encoded.decode(),)
]
def get_econtext_config(self):
assert self.options.max_message_size is not None
parent_ids = mitogen.parent_ids[:]
parent_ids.insert(0, mitogen.context_id)
return {
'parent_ids': parent_ids,
'context_id': self.context.context_id,
'debug': self.options.debug,
'profiling': self.options.profiling,
'unidirectional': self.options.unidirectional,
'log_level': get_log_level(),
'whitelist': self._router.get_module_whitelist(),
'blacklist': self._router.get_module_blacklist(),
'max_message_size': self.options.max_message_size,
'version': mitogen.__version__,
}
def get_preamble(self):
suffix = (
'\nExternalContext(%r).main()\n' %\
(self.get_econtext_config(),)
)
partial = get_core_source_partial()
return partial.append(suffix.encode('utf-8'))
def _get_name(self):
return u'%s.%s' % (self.name_prefix, self.proc.pid)
def start_child(self):
args = self.get_boot_command()
LOG.debug('command line for %r: %s', self, Argv(args))
try:
return self.create_child(args=args, **self.create_child_args)
except OSError:
e = sys.exc_info()[1]
msg = 'Child start failed: %s. Command was: %s' % (e, Argv(args))
raise mitogen.core.StreamError(msg)
def _adorn_eof_error(self, e):
if self.eof_error_hint:
e.args = ('%s\n\n%s' % (e.args[0], self.eof_error_hint),)
def _complete_connection(self):
self._timer.cancel()
if not self.exception:
mitogen.core.unlisten(self._router.broker, 'shutdown',
self._on_broker_shutdown)
self._router.register(self.context, self.stdio_stream)
self.stdio_stream.set_protocol(
MitogenProtocol(
router=self._router,
remote_id=self.context.context_id,
)
)
self._router.route_monitor.notice_stream(self.stdio_stream)
self.latch.put()
def _fail_connection(self, exc):
LOG.debug('failing connection %s due to %r',
self.stdio_stream and self.stdio_stream.name, exc)
if self.exception is None:
self._adorn_eof_error(exc)
self.exception = exc
mitogen.core.unlisten(self._router.broker, 'shutdown',
self._on_broker_shutdown)
for stream in self.stdio_stream, self.stderr_stream:
if stream and not stream.receive_side.closed:
stream.on_disconnect(self._router.broker)
self._complete_connection()
eof_error_msg = 'EOF on stream; last 100 lines received:\n'
def on_stdio_disconnect(self):
stderr = self.stderr_stream
if stderr is None or stderr.receive_side.closed:
self._on_streams_disconnected()
def on_stderr_disconnect(self):
if self.stdio_stream.receive_side.closed:
self._on_streams_disconnected()
def _on_streams_disconnected(self):
if self._timer.active:
self._timer.cancel()
self._fail_connection(EofError(
self.eof_error_msg + get_history(
[self.stdio_stream, self.stderr_stream]
)
))
if self._reaper:
return
self._reaper = Reaper(
broker=self._router.broker,
proc=self.proc,
kill=not (
(self.detached and self.child_is_immediate_subprocess) or
# Avoid killing so child has chance to write cProfile data
self._router.profiling
),
# Don't delay shutdown waiting for a detached child, since the
# detached child may expect to live indefinitely after its parent
# exited.
wait_on_shutdown=(not self.detached),
)
self._reaper.reap()
def _on_broker_shutdown(self):
self._fail_connection(CancelledError(BROKER_SHUTDOWN_MSG))
def stream_factory(self):
return self.stream_protocol_class.build_stream(
broker=self._router.broker,
)
def stderr_stream_factory(self):
return self.diag_protocol_class.build_stream()
def _setup_stdio_stream(self):
stream = self.stream_factory()
stream.conn = self
stream.name = self.options.name or self._get_name()
stream.accept(self.proc.stdout, self.proc.stdin)
mitogen.core.listen(stream, 'disconnect', self.on_stdio_disconnect)
self._router.broker.start_receive(stream)
return stream
def _setup_stderr_stream(self):
stream = self.stderr_stream_factory()
stream.conn = self
stream.name = self.options.name or self._get_name()
stream.accept(self.proc.stderr, self.proc.stderr)
mitogen.core.listen(stream, 'disconnect', self.on_stderr_disconnect)
self._router.broker.start_receive(stream)
return stream
def _on_timer_expired(self):
self._fail_connection(
mitogen.core.TimeoutError(
'Failed to setup connection after %.2f seconds',
self.options.connect_timeout,
)
)
def _async_connect(self):
LOG.debug('creating connection to context %d using %s',
self.context.context_id, self.__class__.__module__)
mitogen.core.listen(self._router.broker, 'shutdown',
self._on_broker_shutdown)
self._timer = self._router.broker.timers.schedule(
when=self.options.connect_deadline,
func=self._on_timer_expired,
)
try:
self.proc = self.start_child()
except Exception:
self._fail_connection(sys.exc_info()[1])
return
LOG.debug('child for %r started: pid:%r stdin:%r stdout:%r stderr:%r',
self, self.proc.pid,
self.proc.stdin.fileno(),
self.proc.stdout.fileno(),
self.proc.stderr and self.proc.stderr.fileno())
self.stdio_stream = self._setup_stdio_stream()
if self.context.name is None:
self.context.name = self.stdio_stream.name
self.proc.name = self.stdio_stream.name
if self.proc.stderr:
self.stderr_stream = self._setup_stderr_stream()
def connect(self, context):
self.context = context
self.latch = mitogen.core.Latch()
self._router.broker.defer(self._async_connect)
self.latch.get()
if self.exception:
raise self.exception
class ChildIdAllocator(object):
def __init__(self, router):
self.router = router
self.lock = threading.Lock()
self.it = iter(xrange(0))
def allocate(self):
self.lock.acquire()
try:
for id_ in self.it:
return id_
master = self.router.context_by_id(0)
start, end = master.send_await(
mitogen.core.Message(dst_id=0, handle=mitogen.core.ALLOCATE_ID)
)
self.it = iter(xrange(start, end))
finally:
self.lock.release()
return self.allocate()
class CallChain(object):
def __init__(self, context, pipelined=False):
self.context = context
if pipelined:
self.chain_id = self.make_chain_id()
else:
self.chain_id = None
@classmethod
def make_chain_id(cls):
return '%s-%s-%x-%x' % (
socket.gethostname(),
os.getpid(),
thread.get_ident(),
int(1e6 * mitogen.core.now()),
)
def __repr__(self):
return '%s(%s)' % (self.__class__.__name__, self.context)
def __enter__(self):
return self
def __exit__(self, _1, _2, _3):
self.reset()
def reset(self):
if not self.chain_id:
return
saved, self.chain_id = self.chain_id, None
try:
self.call_no_reply(mitogen.core.Dispatcher.forget_chain, saved)
finally:
self.chain_id = saved
closures_msg = (
'Mitogen cannot invoke closures, as doing so would require '
'serializing arbitrary program state, and no universal '
'method exists to recover a reference to them.'
)
lambda_msg = (
'Mitogen cannot invoke anonymous functions, as no universal method '
'exists to recover a reference to an anonymous function.'
)
method_msg = (
'Mitogen cannot invoke instance methods, as doing so would require '
'serializing arbitrary program state.'
)
def make_msg(self, fn, *args, **kwargs):
if getattr(fn, closure_attr, None) is not None:
raise TypeError(self.closures_msg)
if fn.__name__ == '<lambda>':
raise TypeError(self.lambda_msg)
if inspect.ismethod(fn):
im_self = getattr(fn, IM_SELF_ATTR)
if not inspect.isclass(im_self):
raise TypeError(self.method_msg)
klass = mitogen.core.to_text(im_self.__name__)
else:
klass = None
tup = (
self.chain_id,
mitogen.core.to_text(fn.__module__),
klass,
mitogen.core.to_text(fn.__name__),
args,
mitogen.core.Kwargs(kwargs)
)
return mitogen.core.Message.pickled(tup,
handle=mitogen.core.CALL_FUNCTION)
def call_no_reply(self, fn, *args, **kwargs):
LOG.debug('starting no-reply function call to %r: %r',
self.context.name or self.context.context_id,
CallSpec(fn, args, kwargs))
self.context.send(self.make_msg(fn, *args, **kwargs))
def call_async(self, fn, *args, **kwargs):
LOG.debug('starting function call to %s: %r',
self.context.name or self.context.context_id,
CallSpec(fn, args, kwargs))
return self.context.send_async(self.make_msg(fn, *args, **kwargs))
def call(self, fn, *args, **kwargs):
receiver = self.call_async(fn, *args, **kwargs)
return receiver.get().unpickle(throw_dead=False)
class Context(mitogen.core.Context):
#: A :class:`CallChain` instance constructed by default, with pipelining
#: disabled. :meth:`call`, :meth:`call_async` and :meth:`call_no_reply` use
#: this instance.
call_chain_class = CallChain
via = None
def __init__(self, *args, **kwargs):
super(Context, self).__init__(*args, **kwargs)
self.default_call_chain = self.call_chain_class(self)
def __ne__(self, other):
return not (self == other)
def __eq__(self, other):
return (
isinstance(other, mitogen.core.Context) and
(other.context_id == self.context_id) and
(other.router == self.router)
)
def __hash__(self):
return hash((self.router, self.context_id))
def call_async(self, fn, *args, **kwargs):
return self.default_call_chain.call_async(fn, *args, **kwargs)
def call(self, fn, *args, **kwargs):
return self.default_call_chain.call(fn, *args, **kwargs)
def call_no_reply(self, fn, *args, **kwargs):
self.default_call_chain.call_no_reply(fn, *args, **kwargs)
def shutdown(self, wait=False):
LOG.debug('%r.shutdown() sending SHUTDOWN', self)
latch = mitogen.core.Latch()
mitogen.core.listen(self, 'disconnect', lambda: latch.put(None))
self.send(
mitogen.core.Message(
handle=mitogen.core.SHUTDOWN,
)
)
if wait:
latch.get()
else:
return latch
class RouteMonitor(object):
def __init__(self, router, parent=None):
self.router = router
self.parent = parent
self._log = logging.getLogger('mitogen.route_monitor')
#: Mapping of Stream instance to integer context IDs reachable via the
#: stream; used to cleanup routes during disconnection.
self._routes_by_stream = {}
self.router.add_handler(
fn=self._on_add_route,
handle=mitogen.core.ADD_ROUTE,
persist=True,
policy=is_immediate_child,
overwrite=True,
)
self.router.add_handler(
fn=self._on_del_route,
handle=mitogen.core.DEL_ROUTE,
persist=True,
policy=is_immediate_child,
overwrite=True,
)
def __repr__(self):
return 'RouteMonitor()'
def _send_one(self, stream, handle, target_id, name):
if not stream:
# We may not have a stream during shutdown.
return
data = str(target_id)
if name:
data = '%s:%s' % (target_id, name)
stream.protocol.send(
mitogen.core.Message(
handle=handle,
data=data.encode('utf-8'),
dst_id=stream.protocol.remote_id,
)
)
def _propagate_up(self, handle, target_id, name=None):
if self.parent:
stream = self.router.stream_by_id(self.parent.context_id)
self._send_one(stream, handle, target_id, name)
def _propagate_down(self, handle, target_id):
for stream in self.router.get_streams():
if target_id in stream.protocol.egress_ids and (
(self.parent is None) or
(self.parent.context_id != stream.protocol.remote_id)
):
self._send_one(stream, mitogen.core.DEL_ROUTE, target_id, None)
def notice_stream(self, stream):
self._routes_by_stream[stream] = set([stream.protocol.remote_id])
self._propagate_up(mitogen.core.ADD_ROUTE, stream.protocol.remote_id,
stream.name)
mitogen.core.listen(
obj=stream,
name='disconnect',
func=lambda: self._on_stream_disconnect(stream),
)
def get_routes(self, stream):
return self._routes_by_stream.get(stream) or set()
def _on_stream_disconnect(self, stream):
# During a stream crash it is possible for disconnect signal to fire
# twice, in which case ignore the second instance.
routes = self._routes_by_stream.pop(stream, None)
if routes is None:
return
self._log.debug('stream %s is gone; propagating DEL_ROUTE for %r',
stream.name, routes)
for target_id in routes:
self.router.del_route(target_id)
self._propagate_up(mitogen.core.DEL_ROUTE, target_id)
self._propagate_down(mitogen.core.DEL_ROUTE, target_id)
context = self.router.context_by_id(target_id, create=False)
if context:
mitogen.core.fire(context, 'disconnect')
def _on_add_route(self, msg):
if msg.is_dead:
return
target_id_s, _, target_name = bytes_partition(msg.data, b(':'))
target_name = target_name.decode()
target_id = int(target_id_s)
self.router.context_by_id(target_id).name = target_name
stream = self.router.stream_by_id(msg.auth_id)
current = self.router.stream_by_id(target_id)
if current and current.protocol.remote_id != mitogen.parent_id:
self._log.error('Cannot add duplicate route to %r via %r, '
'already have existing route via %r',
target_id, stream, current)
return
self._log.debug('Adding route to %d via %r', target_id, stream)
self._routes_by_stream[stream].add(target_id)
self.router.add_route(target_id, stream)
self._propagate_up(mitogen.core.ADD_ROUTE, target_id, target_name)
def _on_del_route(self, msg):
if msg.is_dead:
return
target_id = int(msg.data)
registered_stream = self.router.stream_by_id(target_id)
if registered_stream is None:
return
stream = self.router.stream_by_id(msg.auth_id)
if registered_stream != stream:
self._log.error('received DEL_ROUTE for %d from %r, expected %r',
target_id, stream, registered_stream)
return
context = self.router.context_by_id(target_id, create=False)
if context:
self._log.debug('firing local disconnect signal for %r', context)
mitogen.core.fire(context, 'disconnect')
self._log.debug('deleting route to %d via %r', target_id, stream)
routes = self._routes_by_stream.get(stream)
if routes:
routes.discard(target_id)
self.router.del_route(target_id)
if stream.protocol.remote_id != mitogen.parent_id:
self._propagate_up(mitogen.core.DEL_ROUTE, target_id)
self._propagate_down(mitogen.core.DEL_ROUTE, target_id)
class Router(mitogen.core.Router):
context_class = Context
debug = False
profiling = False
id_allocator = None
responder = None
log_forwarder = None
route_monitor = None
def upgrade(self, importer, parent):
LOG.debug('upgrading %r with capabilities to start new children', self)
self.id_allocator = ChildIdAllocator(router=self)
self.responder = ModuleForwarder(
router=self,
parent_context=parent,
importer=importer,
)
self.route_monitor = RouteMonitor(self, parent)
self.add_handler(
fn=self._on_detaching,
handle=mitogen.core.DETACHING,
persist=True,
)
def _on_detaching(self, msg):
if msg.is_dead:
return
stream = self.stream_by_id(msg.src_id)
if stream.protocol.remote_id != msg.src_id or stream.conn.detached:
LOG.warning('bad DETACHING received on %r: %r', stream, msg)
return
LOG.debug('%r: marking as detached', stream)
stream.conn.detached = True
msg.reply(None)
def get_streams(self):
self._write_lock.acquire()
try:
return itervalues(self._stream_by_id)
finally:
self._write_lock.release()
def disconnect(self, context):
stream = self.stream_by_id(context)
if stream is None or stream.protocol.remote_id != context.context_id:
return
l = mitogen.core.Latch()
mitogen.core.listen(stream, 'disconnect', l.put)
def disconnect():
LOG.debug('Starting disconnect of %r', stream)
stream.on_disconnect(self.broker)
self.broker.defer(disconnect)
l.get()
def add_route(self, target_id, stream):
LOG.debug('%r: adding route to context %r via %r',
self, target_id, stream)
assert isinstance(target_id, int)
assert isinstance(stream, mitogen.core.Stream)
self._write_lock.acquire()
try:
self._stream_by_id[target_id] = stream
finally:
self._write_lock.release()
def del_route(self, target_id):
LOG.debug('%r: deleting route to %r', self, target_id)
# DEL_ROUTE may be sent by a parent if it knows this context sent
# messages to a peer that has now disconnected, to let us raise
# 'disconnect' event on the appropriate Context instance. In that case,
# we won't a matching _stream_by_id entry for the disappearing route,
# so don't raise an error for a missing key here.
self._write_lock.acquire()
try:
self._stream_by_id.pop(target_id, None)
finally:
self._write_lock.release()
def get_module_blacklist(self):
if mitogen.context_id == 0:
return self.responder.blacklist
return self.importer.master_blacklist
def get_module_whitelist(self):
if mitogen.context_id == 0:
return self.responder.whitelist
return self.importer.master_whitelist
def allocate_id(self):
return self.id_allocator.allocate()
connection_timeout_msg = u"Connection timed out."
def _connect(self, klass, **kwargs):
context_id = self.allocate_id()
context = self.context_class(self, context_id)
context.name = kwargs.get('name')
kwargs['old_router'] = self
kwargs['max_message_size'] = self.max_message_size
conn = klass(klass.options_class(**kwargs), self)
try:
conn.connect(context=context)
except mitogen.core.TimeoutError:
raise mitogen.core.StreamError(self.connection_timeout_msg)
return context
def connect(self, method_name, name=None, **kwargs):
if name:
name = mitogen.core.to_text(name)
klass = get_connection_class(method_name)
kwargs.setdefault(u'debug', self.debug)
kwargs.setdefault(u'profiling', self.profiling)
kwargs.setdefault(u'unidirectional', self.unidirectional)
kwargs.setdefault(u'name', name)
via = kwargs.pop(u'via', None)
if via is not None:
return self.proxy_connect(via, method_name,
**mitogen.core.Kwargs(kwargs))
return self._connect(klass, **mitogen.core.Kwargs(kwargs))
def proxy_connect(self, via_context, method_name, name=None, **kwargs):
resp = via_context.call(_proxy_connect,
name=name,
method_name=method_name,
kwargs=mitogen.core.Kwargs(kwargs),
)
if resp['msg'] is not None:
raise mitogen.core.StreamError(resp['msg'])
name = u'%s.%s' % (via_context.name, resp['name'])
context = self.context_class(self, resp['id'], name=name)
context.via = via_context
self._write_lock.acquire()
try:
self._context_by_id[context.context_id] = context
finally:
self._write_lock.release()
return context
def buildah(self, **kwargs):
return self.connect(u'buildah', **kwargs)
def doas(self, **kwargs):
return self.connect(u'doas', **kwargs)
def docker(self, **kwargs):
return self.connect(u'docker', **kwargs)
def kubectl(self, **kwargs):
return self.connect(u'kubectl', **kwargs)
def fork(self, **kwargs):
return self.connect(u'fork', **kwargs)
def jail(self, **kwargs):
return self.connect(u'jail', **kwargs)
def local(self, **kwargs):
return self.connect(u'local', **kwargs)
def lxc(self, **kwargs):
return self.connect(u'lxc', **kwargs)
def lxd(self, **kwargs):
return self.connect(u'lxd', **kwargs)
def setns(self, **kwargs):
return self.connect(u'setns', **kwargs)
def su(self, **kwargs):
return self.connect(u'su', **kwargs)
def sudo(self, **kwargs):
return self.connect(u'sudo', **kwargs)
def ssh(self, **kwargs):
return self.connect(u'ssh', **kwargs)
class Reaper(object):
#: :class:`Timer` that invokes :meth:`reap` after some polling delay.
_timer = None
def __init__(self, broker, proc, kill, wait_on_shutdown):
self.broker = broker
self.proc = proc
self.kill = kill
self.wait_on_shutdown = wait_on_shutdown
self._tries = 0
def _signal_child(self, signum):
# For processes like sudo we cannot actually send sudo a signal,
# because it is setuid, so this is best-effort only.
LOG.debug('%r: sending %s', self.proc, SIGNAL_BY_NUM[signum])
try:
os.kill(self.proc.pid, signum)
except OSError:
e = sys.exc_info()[1]
if e.args[0] != errno.EPERM:
raise
def _calc_delay(self, count):
delay = 0.05
for _ in xrange(count):
delay *= 1.72
return delay
def _on_broker_shutdown(self):
if not self.wait_on_shutdown:
self._timer.cancel()
def _install_timer(self, delay):
new = self._timer is None
self._timer = self.broker.timers.schedule(
when=mitogen.core.now() + delay,
func=self.reap,
)
if new:
mitogen.core.listen(self.broker, 'shutdown',
self._on_broker_shutdown)
def _remove_timer(self):
if self._timer and self._timer.active:
self._timer.cancel()
mitogen.core.unlisten(self.broker, 'shutdown',
self._on_broker_shutdown)
def reap(self):
status = self.proc.poll()
if status is not None:
LOG.debug('%r: %s', self.proc, returncode_to_str(status))
mitogen.core.fire(self.proc, 'exit')
self._remove_timer()
return
self._tries += 1
if self._tries > 20:
LOG.warning('%r: child will not exit, giving up', self)
self._remove_timer()
return
delay = self._calc_delay(self._tries - 1)
LOG.debug('%r still running after IO disconnect, recheck in %.03fs',
self.proc, delay)
self._install_timer(delay)
if not self.kill:
pass
elif self._tries == 2:
self._signal_child(signal.SIGTERM)
elif self._tries == 6: # roughly 4 seconds
self._signal_child(signal.SIGKILL)
class Process(object):
#: Name of the process used in logs. Set to the stream/context name by
#: :class:`Connection`.
name = None
def __init__(self, pid, stdin, stdout, stderr=None):
#: The process ID.
self.pid = pid
#: File object attached to standard input.
self.stdin = stdin
#: File object attached to standard output.
self.stdout = stdout
#: File object attached to standard error.
self.stderr = stderr
def __repr__(self):
return '%s %s pid %d' % (
type(self).__name__,
self.name,
self.pid,
)
def poll(self):
raise NotImplementedError()
class PopenProcess(Process):
def __init__(self, proc, stdin, stdout, stderr=None):
super(PopenProcess, self).__init__(proc.pid, stdin, stdout, stderr)
#: The subprocess.
self.proc = proc
def poll(self):
return self.proc.poll()
class ModuleForwarder(object):
def __init__(self, router, parent_context, importer):
self.router = router
self.parent_context = parent_context
self.importer = importer
router.add_handler(
fn=self._on_forward_module,
handle=mitogen.core.FORWARD_MODULE,
persist=True,
policy=mitogen.core.has_parent_authority,
)
router.add_handler(
fn=self._on_get_module,
handle=mitogen.core.GET_MODULE,
persist=True,
policy=is_immediate_child,
)
def __repr__(self):
return 'ModuleForwarder'
def _on_forward_module(self, msg):
if msg.is_dead:
return
context_id_s, _, fullname = bytes_partition(msg.data, b('\x00'))
fullname = mitogen.core.to_text(fullname)
context_id = int(context_id_s)
stream = self.router.stream_by_id(context_id)
if stream.protocol.remote_id == mitogen.parent_id:
LOG.error('%r: dropping FORWARD_MODULE(%d, %r): no route to child',
self, context_id, fullname)
return
if fullname in stream.protocol.sent_modules:
return
LOG.debug('%r._on_forward_module() sending %r to %r via %r',
self, fullname, context_id, stream.protocol.remote_id)
self._send_module_and_related(stream, fullname)
if stream.protocol.remote_id != context_id:
stream.protocol._send(
mitogen.core.Message(
data=msg.data,
handle=mitogen.core.FORWARD_MODULE,
dst_id=stream.protocol.remote_id,
)
)
def _on_get_module(self, msg):
if msg.is_dead:
return
fullname = msg.data.decode('utf-8')
LOG.debug('%r: %s requested by context %d', self, fullname, msg.src_id)
callback = lambda: self._on_cache_callback(msg, fullname)
self.importer._request_module(fullname, callback)
def _on_cache_callback(self, msg, fullname):
stream = self.router.stream_by_id(msg.src_id)
LOG.debug('%r: sending %s to %r', self, fullname, stream)
self._send_module_and_related(stream, fullname)
def _send_module_and_related(self, stream, fullname):
tup = self.importer._cache[fullname]
for related in tup[4]:
rtup = self.importer._cache.get(related)
if rtup:
self._send_one_module(stream, rtup)
else:
LOG.debug('%r: %s not in cache (for %s)',
self, related, fullname)
self._send_one_module(stream, tup)
def _send_one_module(self, stream, tup):
if tup[0] not in stream.protocol.sent_modules:
stream.protocol.sent_modules.add(tup[0])
self.router._async_route(
mitogen.core.Message.pickled(
tup,
dst_id=stream.protocol.remote_id,
handle=mitogen.core.LOAD_MODULE,
)
)
| true | true |
1c3e1ac1ffbcaae6a149c06bab5c2378e1b7ba27 | 5,010 | py | Python | bitflow-script/generated/python2/BitflowLexer.py | bitflow-stream/bitflow-script | b8427c02f65820108ca08356f9483e400fcbcaee | [
"Apache-2.0"
] | null | null | null | bitflow-script/generated/python2/BitflowLexer.py | bitflow-stream/bitflow-script | b8427c02f65820108ca08356f9483e400fcbcaee | [
"Apache-2.0"
] | null | null | null | bitflow-script/generated/python2/BitflowLexer.py | bitflow-stream/bitflow-script | b8427c02f65820108ca08356f9483e400fcbcaee | [
"Apache-2.0"
] | null | null | null | # Generated from Bitflow.g4 by ANTLR 4.7.1
# encoding: utf-8
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2")
buf.write(u"\23|\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write(u"\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t")
buf.write(u"\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22")
buf.write(u"\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\5\3\6\3\6\3\7\3\7")
buf.write(u"\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\f\3\f\3")
buf.write(u"\f\3\f\3\r\3\r\7\rC\n\r\f\r\16\rF\13\r\3\r\3\r\3\r\7")
buf.write(u"\rK\n\r\f\r\16\rN\13\r\3\r\3\r\3\r\7\rS\n\r\f\r\16\r")
buf.write(u"V\13\r\3\r\5\rY\n\r\3\16\6\16\\\n\16\r\16\16\16]\3\17")
buf.write(u"\3\17\7\17b\n\17\f\17\16\17e\13\17\3\17\3\17\3\17\3\17")
buf.write(u"\3\20\3\20\3\20\5\20n\n\20\3\20\3\20\3\21\3\21\3\21\5")
buf.write(u"\21u\n\21\3\21\3\21\3\22\3\22\3\22\3\22\5DLT\2\23\3\3")
buf.write(u"\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16")
buf.write(u"\33\17\35\20\37\21!\22#\23\3\2\4\n\2\'(,-/<AAC\\^^aa")
buf.write(u"c|\4\2\f\f\17\17\2\u0084\2\3\3\2\2\2\2\5\3\2\2\2\2\7")
buf.write(u"\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3")
buf.write(u"\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3")
buf.write(u"\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3")
buf.write(u"\2\2\2\2!\3\2\2\2\2#\3\2\2\2\3%\3\2\2\2\5\'\3\2\2\2\7")
buf.write(u")\3\2\2\2\t+\3\2\2\2\13.\3\2\2\2\r\60\3\2\2\2\17\62\3")
buf.write(u"\2\2\2\21\64\3\2\2\2\23\66\3\2\2\2\258\3\2\2\2\27:\3")
buf.write(u"\2\2\2\31X\3\2\2\2\33[\3\2\2\2\35_\3\2\2\2\37m\3\2\2")
buf.write(u"\2!t\3\2\2\2#x\3\2\2\2%&\7}\2\2&\4\3\2\2\2\'(\7\177\2")
buf.write(u"\2(\6\3\2\2\2)*\7=\2\2*\b\3\2\2\2+,\7/\2\2,-\7@\2\2-")
buf.write(u"\n\3\2\2\2./\7*\2\2/\f\3\2\2\2\60\61\7+\2\2\61\16\3\2")
buf.write(u"\2\2\62\63\7?\2\2\63\20\3\2\2\2\64\65\7.\2\2\65\22\3")
buf.write(u"\2\2\2\66\67\7]\2\2\67\24\3\2\2\289\7_\2\29\26\3\2\2")
buf.write(u"\2:;\7d\2\2;<\7c\2\2<=\7v\2\2=>\7e\2\2>?\7j\2\2?\30\3")
buf.write(u"\2\2\2@D\7$\2\2AC\13\2\2\2BA\3\2\2\2CF\3\2\2\2DE\3\2")
buf.write(u"\2\2DB\3\2\2\2EG\3\2\2\2FD\3\2\2\2GY\7$\2\2HL\7)\2\2")
buf.write(u"IK\13\2\2\2JI\3\2\2\2KN\3\2\2\2LM\3\2\2\2LJ\3\2\2\2M")
buf.write(u"O\3\2\2\2NL\3\2\2\2OY\7)\2\2PT\7b\2\2QS\13\2\2\2RQ\3")
buf.write(u"\2\2\2SV\3\2\2\2TU\3\2\2\2TR\3\2\2\2UW\3\2\2\2VT\3\2")
buf.write(u"\2\2WY\7b\2\2X@\3\2\2\2XH\3\2\2\2XP\3\2\2\2Y\32\3\2\2")
buf.write(u"\2Z\\\t\2\2\2[Z\3\2\2\2\\]\3\2\2\2][\3\2\2\2]^\3\2\2")
buf.write(u"\2^\34\3\2\2\2_c\7%\2\2`b\n\3\2\2a`\3\2\2\2be\3\2\2\2")
buf.write(u"ca\3\2\2\2cd\3\2\2\2df\3\2\2\2ec\3\2\2\2fg\5\37\20\2")
buf.write(u"gh\3\2\2\2hi\b\17\2\2i\36\3\2\2\2jn\t\3\2\2kl\7\17\2")
buf.write(u"\2ln\7\f\2\2mj\3\2\2\2mk\3\2\2\2no\3\2\2\2op\b\20\2\2")
buf.write(u"p \3\2\2\2qu\7\"\2\2rs\7^\2\2su\7u\2\2tq\3\2\2\2tr\3")
buf.write(u"\2\2\2uv\3\2\2\2vw\b\21\2\2w\"\3\2\2\2xy\7\13\2\2yz\3")
buf.write(u"\2\2\2z{\b\22\2\2{$\3\2\2\2\13\2DLTX]cmt\3\b\2\2")
return buf.getvalue()
class BitflowLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
OPEN = 1
CLOSE = 2
EOP = 3
NEXT = 4
OPEN_PARAMS = 5
CLOSE_PARAMS = 6
EQ = 7
SEP = 8
OPEN_HINTS = 9
CLOSE_HINTS = 10
BATCH = 11
STRING = 12
IDENTIFIER = 13
COMMENT = 14
NEWLINE = 15
WHITESPACE = 16
TAB = 17
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ u"DEFAULT_MODE" ]
literalNames = [ u"<INVALID>",
u"'{'", u"'}'", u"';'", u"'->'", u"'('", u"')'", u"'='", u"','",
u"'['", u"']'", u"'batch'", u"'\t'" ]
symbolicNames = [ u"<INVALID>",
u"OPEN", u"CLOSE", u"EOP", u"NEXT", u"OPEN_PARAMS", u"CLOSE_PARAMS",
u"EQ", u"SEP", u"OPEN_HINTS", u"CLOSE_HINTS", u"BATCH", u"STRING",
u"IDENTIFIER", u"COMMENT", u"NEWLINE", u"WHITESPACE", u"TAB" ]
ruleNames = [ u"OPEN", u"CLOSE", u"EOP", u"NEXT", u"OPEN_PARAMS", u"CLOSE_PARAMS",
u"EQ", u"SEP", u"OPEN_HINTS", u"CLOSE_HINTS", u"BATCH",
u"STRING", u"IDENTIFIER", u"COMMENT", u"NEWLINE", u"WHITESPACE",
u"TAB" ]
grammarFileName = u"Bitflow.g4"
def __init__(self, input=None, output=sys.stdout):
super(BitflowLexer, self).__init__(input, output=output)
self.checkVersion("4.7.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
| 46.388889 | 103 | 0.530539 |
from __future__ import print_function
from antlr4 import *
from io import StringIO
import sys
def serializedATN():
with StringIO() as buf:
buf.write(u"\3\u608b\ua72a\u8133\ub9ed\u417c\u3be7\u7786\u5964\2")
buf.write(u"\23|\b\1\4\2\t\2\4\3\t\3\4\4\t\4\4\5\t\5\4\6\t\6\4\7")
buf.write(u"\t\7\4\b\t\b\4\t\t\t\4\n\t\n\4\13\t\13\4\f\t\f\4\r\t")
buf.write(u"\r\4\16\t\16\4\17\t\17\4\20\t\20\4\21\t\21\4\22\t\22")
buf.write(u"\3\2\3\2\3\3\3\3\3\4\3\4\3\5\3\5\3\5\3\6\3\6\3\7\3\7")
buf.write(u"\3\b\3\b\3\t\3\t\3\n\3\n\3\13\3\13\3\f\3\f\3\f\3\f\3")
buf.write(u"\f\3\f\3\r\3\r\7\rC\n\r\f\r\16\rF\13\r\3\r\3\r\3\r\7")
buf.write(u"\rK\n\r\f\r\16\rN\13\r\3\r\3\r\3\r\7\rS\n\r\f\r\16\r")
buf.write(u"V\13\r\3\r\5\rY\n\r\3\16\6\16\\\n\16\r\16\16\16]\3\17")
buf.write(u"\3\17\7\17b\n\17\f\17\16\17e\13\17\3\17\3\17\3\17\3\17")
buf.write(u"\3\20\3\20\3\20\5\20n\n\20\3\20\3\20\3\21\3\21\3\21\5")
buf.write(u"\21u\n\21\3\21\3\21\3\22\3\22\3\22\3\22\5DLT\2\23\3\3")
buf.write(u"\5\4\7\5\t\6\13\7\r\b\17\t\21\n\23\13\25\f\27\r\31\16")
buf.write(u"\33\17\35\20\37\21!\22#\23\3\2\4\n\2\'(,-/<AAC\\^^aa")
buf.write(u"c|\4\2\f\f\17\17\2\u0084\2\3\3\2\2\2\2\5\3\2\2\2\2\7")
buf.write(u"\3\2\2\2\2\t\3\2\2\2\2\13\3\2\2\2\2\r\3\2\2\2\2\17\3")
buf.write(u"\2\2\2\2\21\3\2\2\2\2\23\3\2\2\2\2\25\3\2\2\2\2\27\3")
buf.write(u"\2\2\2\2\31\3\2\2\2\2\33\3\2\2\2\2\35\3\2\2\2\2\37\3")
buf.write(u"\2\2\2\2!\3\2\2\2\2#\3\2\2\2\3%\3\2\2\2\5\'\3\2\2\2\7")
buf.write(u")\3\2\2\2\t+\3\2\2\2\13.\3\2\2\2\r\60\3\2\2\2\17\62\3")
buf.write(u"\2\2\2\21\64\3\2\2\2\23\66\3\2\2\2\258\3\2\2\2\27:\3")
buf.write(u"\2\2\2\31X\3\2\2\2\33[\3\2\2\2\35_\3\2\2\2\37m\3\2\2")
buf.write(u"\2!t\3\2\2\2#x\3\2\2\2%&\7}\2\2&\4\3\2\2\2\'(\7\177\2")
buf.write(u"\2(\6\3\2\2\2)*\7=\2\2*\b\3\2\2\2+,\7/\2\2,-\7@\2\2-")
buf.write(u"\n\3\2\2\2./\7*\2\2/\f\3\2\2\2\60\61\7+\2\2\61\16\3\2")
buf.write(u"\2\2\62\63\7?\2\2\63\20\3\2\2\2\64\65\7.\2\2\65\22\3")
buf.write(u"\2\2\2\66\67\7]\2\2\67\24\3\2\2\289\7_\2\29\26\3\2\2")
buf.write(u"\2:;\7d\2\2;<\7c\2\2<=\7v\2\2=>\7e\2\2>?\7j\2\2?\30\3")
buf.write(u"\2\2\2@D\7$\2\2AC\13\2\2\2BA\3\2\2\2CF\3\2\2\2DE\3\2")
buf.write(u"\2\2DB\3\2\2\2EG\3\2\2\2FD\3\2\2\2GY\7$\2\2HL\7)\2\2")
buf.write(u"IK\13\2\2\2JI\3\2\2\2KN\3\2\2\2LM\3\2\2\2LJ\3\2\2\2M")
buf.write(u"O\3\2\2\2NL\3\2\2\2OY\7)\2\2PT\7b\2\2QS\13\2\2\2RQ\3")
buf.write(u"\2\2\2SV\3\2\2\2TU\3\2\2\2TR\3\2\2\2UW\3\2\2\2VT\3\2")
buf.write(u"\2\2WY\7b\2\2X@\3\2\2\2XH\3\2\2\2XP\3\2\2\2Y\32\3\2\2")
buf.write(u"\2Z\\\t\2\2\2[Z\3\2\2\2\\]\3\2\2\2][\3\2\2\2]^\3\2\2")
buf.write(u"\2^\34\3\2\2\2_c\7%\2\2`b\n\3\2\2a`\3\2\2\2be\3\2\2\2")
buf.write(u"ca\3\2\2\2cd\3\2\2\2df\3\2\2\2ec\3\2\2\2fg\5\37\20\2")
buf.write(u"gh\3\2\2\2hi\b\17\2\2i\36\3\2\2\2jn\t\3\2\2kl\7\17\2")
buf.write(u"\2ln\7\f\2\2mj\3\2\2\2mk\3\2\2\2no\3\2\2\2op\b\20\2\2")
buf.write(u"p \3\2\2\2qu\7\"\2\2rs\7^\2\2su\7u\2\2tq\3\2\2\2tr\3")
buf.write(u"\2\2\2uv\3\2\2\2vw\b\21\2\2w\"\3\2\2\2xy\7\13\2\2yz\3")
buf.write(u"\2\2\2z{\b\22\2\2{$\3\2\2\2\13\2DLTX]cmt\3\b\2\2")
return buf.getvalue()
class BitflowLexer(Lexer):
atn = ATNDeserializer().deserialize(serializedATN())
decisionsToDFA = [ DFA(ds, i) for i, ds in enumerate(atn.decisionToState) ]
OPEN = 1
CLOSE = 2
EOP = 3
NEXT = 4
OPEN_PARAMS = 5
CLOSE_PARAMS = 6
EQ = 7
SEP = 8
OPEN_HINTS = 9
CLOSE_HINTS = 10
BATCH = 11
STRING = 12
IDENTIFIER = 13
COMMENT = 14
NEWLINE = 15
WHITESPACE = 16
TAB = 17
channelNames = [ u"DEFAULT_TOKEN_CHANNEL", u"HIDDEN" ]
modeNames = [ u"DEFAULT_MODE" ]
literalNames = [ u"<INVALID>",
u"'{'", u"'}'", u"';'", u"'->'", u"'('", u"')'", u"'='", u"','",
u"'['", u"']'", u"'batch'", u"'\t'" ]
symbolicNames = [ u"<INVALID>",
u"OPEN", u"CLOSE", u"EOP", u"NEXT", u"OPEN_PARAMS", u"CLOSE_PARAMS",
u"EQ", u"SEP", u"OPEN_HINTS", u"CLOSE_HINTS", u"BATCH", u"STRING",
u"IDENTIFIER", u"COMMENT", u"NEWLINE", u"WHITESPACE", u"TAB" ]
ruleNames = [ u"OPEN", u"CLOSE", u"EOP", u"NEXT", u"OPEN_PARAMS", u"CLOSE_PARAMS",
u"EQ", u"SEP", u"OPEN_HINTS", u"CLOSE_HINTS", u"BATCH",
u"STRING", u"IDENTIFIER", u"COMMENT", u"NEWLINE", u"WHITESPACE",
u"TAB" ]
grammarFileName = u"Bitflow.g4"
def __init__(self, input=None, output=sys.stdout):
super(BitflowLexer, self).__init__(input, output=output)
self.checkVersion("4.7.1")
self._interp = LexerATNSimulator(self, self.atn, self.decisionsToDFA, PredictionContextCache())
self._actions = None
self._predicates = None
| true | true |
1c3e1b0e4c49dc316f529abeabc20b804d687524 | 3,823 | py | Python | python/plugins/MetaSearch/plugin.py | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | python/plugins/MetaSearch/plugin.py | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | null | null | null | python/plugins/MetaSearch/plugin.py | dyna-mis/Hilabeling | cb7d5d4be29624a20c8a367162dbc6fd779b2b52 | [
"MIT"
] | 1 | 2021-12-25T08:40:30.000Z | 2021-12-25T08:40:30.000Z | from builtins import object
# -*- coding: utf-8 -*-
###############################################################################
#
# Copyright (C) 2010 NextGIS (http://nextgis.org),
# Alexander Bruy (alexander.bruy@gmail.com),
# Maxim Dubinin (sim@gis-lab.info),
#
# Copyright (C) 2014 Tom Kralidis (tomkralidis@gmail.com)
#
# This source 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 2 of the License, or (at your option)
# any later version.
#
# This code 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, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
###############################################################################
import logging
from qgis.PyQt.QtCore import QCoreApplication
from qgis.PyQt.QtWidgets import QAction
from qgis.PyQt.QtGui import QIcon
from qgis.core import QgsApplication
from MetaSearch.dialogs.maindialog import MetaSearchDialog
from MetaSearch.util import get_help_url, open_url, StaticContext
LOGGER = logging.getLogger('MetaSearch')
class MetaSearchPlugin(object):
"""base plugin"""
def __init__(self, iface):
"""init"""
self.iface = iface
self.context = StaticContext()
self.action_run = None
self.action_help = None
self.dialog = None
self.web_menu = '&MetaSearch'
def initGui(self):
"""startup"""
# run
run_icon = QIcon('%s/%s' % (self.context.ppath,
'images/MetaSearch.svg'))
self.action_run = QAction(run_icon, 'MetaSearch',
self.iface.mainWindow())
self.action_run.setWhatsThis(QCoreApplication.translate('MetaSearch',
'MetaSearch plugin'))
self.action_run.setStatusTip(QCoreApplication.translate('MetaSearch',
'Search Metadata Catalogs'))
self.action_run.triggered.connect(self.run)
self.iface.addWebToolBarIcon(self.action_run)
self.iface.addPluginToWebMenu(self.web_menu, self.action_run)
# help
help_icon = QgsApplication.getThemeIcon('/mActionHelpContents.svg')
self.action_help = QAction(help_icon, 'Help', self.iface.mainWindow())
self.action_help.setWhatsThis(QCoreApplication.translate('MetaSearch',
'MetaSearch plugin help'))
self.action_help.setStatusTip(QCoreApplication.translate('MetaSearch',
'Get Help on MetaSearch'))
self.action_help.triggered.connect(self.help)
self.iface.addPluginToWebMenu(self.web_menu, self.action_help)
# prefab the dialog but not open it yet
self.dialog = MetaSearchDialog(self.iface)
def unload(self):
"""teardown"""
# remove the plugin menu item and icon
self.iface.removePluginWebMenu(self.web_menu, self.action_run)
self.iface.removePluginWebMenu(self.web_menu, self.action_help)
self.iface.removeWebToolBarIcon(self.action_run)
def run(self):
"""open MetaSearch"""
self.dialog.exec_()
def help(self):
"""open help in user's default web browser"""
open_url(get_help_url())
| 37.116505 | 92 | 0.610777 | from builtins import object
| true | true |
1c3e1b338819a66c4564a56099067a4c84d04ee3 | 1,520 | py | Python | rpi/sensors/APCUPS.py | brettonw/rpi_sensor | adb13e9b5c508fb31297cde2bc4d2c9fb156ce35 | [
"MIT"
] | null | null | null | rpi/sensors/APCUPS.py | brettonw/rpi_sensor | adb13e9b5c508fb31297cde2bc4d2c9fb156ce35 | [
"MIT"
] | null | null | null | rpi/sensors/APCUPS.py | brettonw/rpi_sensor | adb13e9b5c508fb31297cde2bc4d2c9fb156ce35 | [
"MIT"
] | null | null | null | #! /usr/bin/env python3
import subprocess
# helper to print each field we care about
separator = ""
def printKeyValuePair (key, value):
global separator
print ("{}\"{}\":{}".format (separator, key, value), end='')
separator = ","
# the key names we want to report with
reportNames = {
"LINEV" : "line/ Volts",
"LOADPCT" : "load/ Percent",
"BCHARGE" : "battery/ Percent",
"TIMELEFT" : "remaining/ Minutes"
}
# format a key value pair from the non-flag section of the report
def printWantedKeyValuePair (key, value):
if (key in reportNames):
reportName = reportNames[key]
key, unit = reportName.split ("/",1)
value = "{:3.1f}".format (float (value.replace(unit, "")))
printKeyValuePair(key, value)
# yes no array
yesno = ["\"no\"", "\"yes\""]
# from apcupsd cource, statflag values we care about are:
UPS_online = 0x00000008
UPS_replacebatt = 0x00000080
# get the apcups status and report the values we want
for line in subprocess.run(['/usr/sbin/apcaccess'], capture_output=True, text=True).stdout.splitlines():
kv = [items.rstrip () for items in line.split (": ", 1)]
if (kv[0] == "STATFLAG"):
# flags are reported as a hexadecimal number string. we make that into an int
flags = int (kv[1], 16)
printKeyValuePair ("online", yesno[int ((flags & UPS_online) > 0)])
printKeyValuePair ("replace", yesno[int ((flags & UPS_replacebatt) > 0)])
else:
printWantedKeyValuePair (kv[0], kv[1])
print ()
| 33.043478 | 104 | 0.640789 |
import subprocess
separator = ""
def printKeyValuePair (key, value):
global separator
print ("{}\"{}\":{}".format (separator, key, value), end='')
separator = ","
reportNames = {
"LINEV" : "line/ Volts",
"LOADPCT" : "load/ Percent",
"BCHARGE" : "battery/ Percent",
"TIMELEFT" : "remaining/ Minutes"
}
def printWantedKeyValuePair (key, value):
if (key in reportNames):
reportName = reportNames[key]
key, unit = reportName.split ("/",1)
value = "{:3.1f}".format (float (value.replace(unit, "")))
printKeyValuePair(key, value)
yesno = ["\"no\"", "\"yes\""]
UPS_online = 0x00000008
UPS_replacebatt = 0x00000080
for line in subprocess.run(['/usr/sbin/apcaccess'], capture_output=True, text=True).stdout.splitlines():
kv = [items.rstrip () for items in line.split (": ", 1)]
if (kv[0] == "STATFLAG"):
flags = int (kv[1], 16)
printKeyValuePair ("online", yesno[int ((flags & UPS_online) > 0)])
printKeyValuePair ("replace", yesno[int ((flags & UPS_replacebatt) > 0)])
else:
printWantedKeyValuePair (kv[0], kv[1])
print ()
| true | true |
1c3e1b3965b8a20c4961feaf13b451c9a0104ae2 | 1,150 | py | Python | arp.py | victorpegoraro/net_scan_finder | b775f45f711c767c8447b9536cbb6aeaae68aede | [
"MIT"
] | 1 | 2020-05-02T21:11:26.000Z | 2020-05-02T21:11:26.000Z | arp.py | victorpegoraro/net_scan_finder | b775f45f711c767c8447b9536cbb6aeaae68aede | [
"MIT"
] | null | null | null | arp.py | victorpegoraro/net_scan_finder | b775f45f711c767c8447b9536cbb6aeaae68aede | [
"MIT"
] | null | null | null | #!/usr/bin/env python
import scapy.all as scapy
import optparse
def get_args():
parser = optparse.OptionParser()
parser.add_option("-t", "--target", dest="ipaddr", help="Enter IP address or IP range EX: 192.168.0.1/24")
options, args = parser.parse_args()
if not options.ipaddr:
parser.error("[-] Please enter an ip address, --help for more info.")
return options.ipaddr
def scan(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
clients = []
for item in answered:
client = {"ip": item[0].pdst, "mac": item[1].src}
clients.append(client)
return clients
def print_results(clients):
print("IP\t\t\tMac Address\t\n---------------------------------------------")
for cl in clients:
print(cl["ip"] + "\t\t" + cl["mac"])
if __name__ == '__main__':
options = get_args()
results = scan(options)
print_results(results) | 20.175439 | 111 | 0.58087 |
import scapy.all as scapy
import optparse
def get_args():
parser = optparse.OptionParser()
parser.add_option("-t", "--target", dest="ipaddr", help="Enter IP address or IP range EX: 192.168.0.1/24")
options, args = parser.parse_args()
if not options.ipaddr:
parser.error("[-] Please enter an ip address, --help for more info.")
return options.ipaddr
def scan(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered = scapy.srp(arp_request_broadcast, timeout=1, verbose=False)[0]
clients = []
for item in answered:
client = {"ip": item[0].pdst, "mac": item[1].src}
clients.append(client)
return clients
def print_results(clients):
print("IP\t\t\tMac Address\t\n---------------------------------------------")
for cl in clients:
print(cl["ip"] + "\t\t" + cl["mac"])
if __name__ == '__main__':
options = get_args()
results = scan(options)
print_results(results) | true | true |
1c3e1bfd1ad36aeccf38bcff09387002aaceb2d4 | 3,011 | py | Python | ilpyt/nets/base_net.py | mitre/ilpyt | 6aecbe414f0032514ffb4206200596b8c3860b58 | [
"Apache-2.0"
] | 6 | 2021-09-20T20:25:11.000Z | 2022-01-05T16:04:04.000Z | ilpyt/nets/base_net.py | mitre/ilpyt | 6aecbe414f0032514ffb4206200596b8c3860b58 | [
"Apache-2.0"
] | null | null | null | ilpyt/nets/base_net.py | mitre/ilpyt | 6aecbe414f0032514ffb4206200596b8c3860b58 | [
"Apache-2.0"
] | null | null | null | """
`BaseNetwork` is the abstract class for a network. Networks parameterize
important functions during learning - most often, the agent policy.
To create a custom network, simply extend `BaseNetwork`. The `BaseNetwork` API
requires you to override the `initialize`, `get_action`, and `forward` methods.
- `initalize` sets `network` class variables, such as the network layers
- `get_action` draws from a torch distribution to perform an action
- `forward` computes a forward pass of the network
"""
from abc import abstractmethod
from typing import Any, Tuple
import torch
from torch.distributions import Distribution
class BaseNetwork(torch.nn.Module):
def __init__(self, **kwargs: Any) -> None:
"""
Parameters
----------
**kwargs:
arbitrary keyword arguments. Will be passed to the `initialize` and
`setup_experiment` functions
"""
super(BaseNetwork, self).__init__()
self.initialize(**kwargs)
@abstractmethod
def initialize(self, input_shape: tuple, output_shape: int) -> None:
"""
Perform network initialization. Build the network layers here.
Override this method when extending the `BaseNetwork` class.
Parameters
----------
input_shape: tuple
shape of input to network
output_shape: int
shape of output of network
"""
pass
@abstractmethod
def get_action(self, x: torch.Tensor) -> Tuple[Distribution, torch.Tensor]:
"""
Some algorithms will require us to draw from a distribution to perform
an action. Override this method when extending the `BaseNetwork` class.
Parameters
----------
x: torch.Tensor
input tensor to network
Returns
-------
torch.distributions.Distribution:
distribution to sample actions from
torch.Tensor:
action tensor, sampled from distribution
"""
pass
@abstractmethod
def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass of the network. Override this method when extending the
`BaseNetwork` class.
Parameters
----------
x: torch.Tensor
input tensor to network
Returns
-------
torch.Tensor:
output of network
"""
pass
def get_activation_layer(name: str) -> torch.nn.Module:
"""
Get an activation layer with the given name.
Parameters
-----------
name: str
activation layer name, choose from 'relu' or 'tanh'
Returns
-------
torch.nn.Module:
activation layer
Raises
------
ValueError:
if an unsupported activation layer is specified
"""
if name == 'relu':
return torch.nn.ReLU()
elif name == 'tanh':
return torch.nn.Tanh()
else:
raise ValueError('Unsupported activation layer chosen.')
| 27.126126 | 80 | 0.608436 |
from abc import abstractmethod
from typing import Any, Tuple
import torch
from torch.distributions import Distribution
class BaseNetwork(torch.nn.Module):
def __init__(self, **kwargs: Any) -> None:
super(BaseNetwork, self).__init__()
self.initialize(**kwargs)
@abstractmethod
def initialize(self, input_shape: tuple, output_shape: int) -> None:
pass
@abstractmethod
def get_action(self, x: torch.Tensor) -> Tuple[Distribution, torch.Tensor]:
pass
@abstractmethod
def forward(self, x: torch.Tensor) -> torch.Tensor:
pass
def get_activation_layer(name: str) -> torch.nn.Module:
if name == 'relu':
return torch.nn.ReLU()
elif name == 'tanh':
return torch.nn.Tanh()
else:
raise ValueError('Unsupported activation layer chosen.')
| true | true |
1c3e1c869cdf07b28cae0a81ca5128160b7caace | 3,983 | py | Python | appweb/website/auth.py | francescofranzese004/fitness_progetto | fc9d2816b397348a7337e307e489ec8132827a8e | [
"Apache-2.0"
] | null | null | null | appweb/website/auth.py | francescofranzese004/fitness_progetto | fc9d2816b397348a7337e307e489ec8132827a8e | [
"Apache-2.0"
] | null | null | null | appweb/website/auth.py | francescofranzese004/fitness_progetto | fc9d2816b397348a7337e307e489ec8132827a8e | [
"Apache-2.0"
] | null | null | null | from flask import Blueprint, render_template, request, flash, redirect, url_for
from . import db
from .models import User, Prenotazione
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, current_user
from datetime import datetime
#Il seguente file esegue quelle che sono le funzioni principali della pagina web.
#Contiene i vari routing e redirect a /login - /prenotazione - /signup implementando in ognuno di esse
#i vari form di login, signup e inserimento della prenotazione.
auth = Blueprint('auth', __name__) #Specifico che auth è una collezione di routings appartenente al main
@auth.route('/login', methods=['GET','POST']) #Metodi get e post per l'acquisizione dei dati dalla pagina
def login():
if request.method == 'POST':
email = request.form.get('email') #Prelevo informazioni email dal form
password = request.form.get('password') #Prelevo informazioni password dal form
user = User.query.filter_by(email=email).first() #Controllo che l'email esista nella query
if user: #Se esiste
if check_password_hash(user.password, password): #Se combaciano le password
flash('Bentornato!', category='success')
login_user(user, remember=True)
return redirect(url_for('auth.prenotazione')) #Login effettuato, redirect alla pagina di prenotazione
else:
flash('Password errata, riprovare.', category='error')
else:
flash('Email non esistente', category='error')
return render_template("login.html") #Le condizoni non si verificano. Si rimane nella pagina di login.
@auth.route('/prenotazione', methods=['GET','POST'])
def prenotazione():
if request.method=='POST':
DataOra= datetime.fromisoformat(request.form.get('data') + 'T' + request.form.get('ora')) #Concatenazione. Preleva la data e preleva l'ora dal form
prenotazione = Prenotazione(DataEOra=DataOra, user_id=current_user.id) #I parametri prenotazione saranno ('Data e ora', 'identificativo utente')
db.session.add(prenotazione) #Si aggiunge al database
db.session.commit() #Si aggiorna il database
flash('Prenotazione effettuata con successo!', category='success')
print(DataOra)
return render_template("prenotazione.html")
@auth.route('/sign-up', methods=['GET','POST'])
def signup():
if request.method == 'POST':
email = request.form.get('email') #^
password1 = request.form.get('password1') #| Raccolta dei dati per
password2 = request.form.get('password2') #| la registrazione dell'account
nome = request.form.get('nome') #v
user = User.query.filter_by(email=email).first() #Controlla se esiste già l'email in query
if user:
flash('Email già esistente.', category='error')
elif len(email) < 4:
flash('L email deve essere maggiore di 4 caratteri.', category='error')
elif len(nome) < 2:
flash('Il nome deve essere maggiore di 2 caratteri.', category='error')
elif password1!=password2:
flash('Le due password non coincidono', category='error')
elif len(password1) < 7:
flash('La password deve essere almeno di 7 caratteri.', category='error')
else:
new_user=User(email=email, nome=nome, password=generate_password_hash(password1, method='sha256')) #Parametri di user. La crittografia sha256 fa parte della libreria werkzeug
db.session.add(new_user) #Aggiunge l'utente creato
db.session.commit() #Aggiorna il database
login_user(new_user) #Login
flash('Utente creato.', category='success')
return redirect(url_for('auth.prenotazione'))
return render_template("signup.html") | 51.727273 | 187 | 0.657796 | from flask import Blueprint, render_template, request, flash, redirect, url_for
from . import db
from .models import User, Prenotazione
from werkzeug.security import generate_password_hash, check_password_hash
from flask_login import login_user, current_user
from datetime import datetime
auth = Blueprint('auth', __name__)
@auth.route('/login', methods=['GET','POST'])
def login():
if request.method == 'POST':
email = request.form.get('email') #Prelevo informazioni email dal form
password = request.form.get('password') #Prelevo informazioni password dal form
user = User.query.filter_by(email=email).first() #Controllo che l'email esista nella query
if user:
if check_password_hash(user.password, password):
flash('Bentornato!', category='success')
login_user(user, remember=True)
return redirect(url_for('auth.prenotazione'))
else:
flash('Password errata, riprovare.', category='error')
else:
flash('Email non esistente', category='error')
return render_template("login.html")
@auth.route('/prenotazione', methods=['GET','POST'])
def prenotazione():
if request.method=='POST':
DataOra= datetime.fromisoformat(request.form.get('data') + 'T' + request.form.get('ora'))
prenotazione = Prenotazione(DataEOra=DataOra, user_id=current_user.id) #I parametri prenotazione saranno ('Data e ora', 'identificativo utente')
db.session.add(prenotazione) #Si aggiunge al database
db.session.commit() #Si aggiorna il database
flash('Prenotazione effettuata con successo!', category='success')
print(DataOra)
return render_template("prenotazione.html")
@auth.route('/sign-up', methods=['GET','POST'])
def signup():
if request.method == 'POST':
email = request.form.get('email') #^
password1 = request.form.get('password1') #| Raccolta dei dati per
password2 = request.form.get('password2') #| la registrazione dell'account
nome = request.form.get('nome')
user = User.query.filter_by(email=email).first()
if user:
flash('Email già esistente.', category='error')
elif len(email) < 4:
flash('L email deve essere maggiore di 4 caratteri.', category='error')
elif len(nome) < 2:
flash('Il nome deve essere maggiore di 2 caratteri.', category='error')
elif password1!=password2:
flash('Le due password non coincidono', category='error')
elif len(password1) < 7:
flash('La password deve essere almeno di 7 caratteri.', category='error')
else:
new_user=User(email=email, nome=nome, password=generate_password_hash(password1, method='sha256')) #Parametri di user. La crittografia sha256 fa parte della libreria werkzeug
db.session.add(new_user) #Aggiunge l'utente creato
db.session.commit()
login_user(new_user)
flash('Utente creato.', category='success')
return redirect(url_for('auth.prenotazione'))
return render_template("signup.html") | true | true |
1c3e1cc3b9ce9d896e34e0783065966ba48012ce | 1,494 | py | Python | controllers/pwm_dimmer.py | stas-demydiuk/domoticz-h801-tasmota-plugin | f982d1a7a9aaec88b24d6537af1198e870564d65 | [
"MIT"
] | 8 | 2018-05-26T00:00:02.000Z | 2019-11-17T06:23:18.000Z | controllers/pwm_dimmer.py | stas-demydiuk/domoticz-h801-tasmota-plugin | f982d1a7a9aaec88b24d6537af1198e870564d65 | [
"MIT"
] | 4 | 2018-10-22T14:44:35.000Z | 2021-05-05T17:31:46.000Z | controllers/pwm_dimmer.py | stas-demydiuk/domoticz-h801-tasmota-plugin | f982d1a7a9aaec88b24d6537af1198e870564d65 | [
"MIT"
] | 2 | 2018-12-27T19:54:27.000Z | 2019-09-28T09:05:16.000Z | import Domoticz
from devices_manager import DevicesManager
class PwmDimmer:
def __init__(self, devices_manager, mode):
self.mode = mode
self.devices_manager = devices_manager
def checkDevices(self):
for unit in range(1, 6):
if not self.devices_manager.has_device(unit):
Domoticz.Debug("Create Dimmer Device #" + str(unit))
self.devices_manager.create_device(name="Channel #" + str(unit), unit=unit, type=244, sub_type=73, switch_type=7)
def onMqttMessage(self, topic, payload):
for unit in range(1, 6):
power_key = "POWER" + str(unit)
level_key = "Channel" + str(unit)
if (power_key) not in payload:
continue
device = self.devices_manager.get_device_by_unit(unit)
n_value = 1 if payload[power_key] == "ON" else 0
s_value = str(payload[level_key]) if level_key in payload else device.sValue
if device.nValue != n_value or device.sValue != s_value:
device.Update(nValue=n_value, sValue=s_value)
def onCommand(self, mqttClient, unit, command, level, color):
cmd = command.upper()
if cmd == 'ON' or cmd == 'OFF':
topic = "cmnd/" + self.mode + "/Power" + str(unit)
mqttClient.publish(topic, cmd)
if cmd == 'SET LEVEL':
topic = "cmnd/" + self.mode + "/Channel" + str(unit)
mqttClient.publish(topic, str(level)) | 37.35 | 129 | 0.599063 | import Domoticz
from devices_manager import DevicesManager
class PwmDimmer:
def __init__(self, devices_manager, mode):
self.mode = mode
self.devices_manager = devices_manager
def checkDevices(self):
for unit in range(1, 6):
if not self.devices_manager.has_device(unit):
Domoticz.Debug("Create Dimmer Device #" + str(unit))
self.devices_manager.create_device(name="Channel #" + str(unit), unit=unit, type=244, sub_type=73, switch_type=7)
def onMqttMessage(self, topic, payload):
for unit in range(1, 6):
power_key = "POWER" + str(unit)
level_key = "Channel" + str(unit)
if (power_key) not in payload:
continue
device = self.devices_manager.get_device_by_unit(unit)
n_value = 1 if payload[power_key] == "ON" else 0
s_value = str(payload[level_key]) if level_key in payload else device.sValue
if device.nValue != n_value or device.sValue != s_value:
device.Update(nValue=n_value, sValue=s_value)
def onCommand(self, mqttClient, unit, command, level, color):
cmd = command.upper()
if cmd == 'ON' or cmd == 'OFF':
topic = "cmnd/" + self.mode + "/Power" + str(unit)
mqttClient.publish(topic, cmd)
if cmd == 'SET LEVEL':
topic = "cmnd/" + self.mode + "/Channel" + str(unit)
mqttClient.publish(topic, str(level)) | true | true |
1c3e1d15c02db0b45bd299c37ca123d2d5d9b146 | 839 | py | Python | model_vision/src/test.py | diffunity/kpmg-corona-blue | 93c063933981009af8d661b9b91dda5e2ebf68ab | [
"MIT"
] | 3 | 2021-10-05T07:47:03.000Z | 2021-10-05T10:32:40.000Z | model_vision/src/test.py | diffunity/kpmg-corona-blue | 93c063933981009af8d661b9b91dda5e2ebf68ab | [
"MIT"
] | 6 | 2021-02-07T14:56:57.000Z | 2021-02-20T05:07:35.000Z | model_vision/src/test.py | diffunity/kpmg-corona-blue | 93c063933981009af8d661b9b91dda5e2ebf68ab | [
"MIT"
] | 1 | 2021-02-20T05:59:27.000Z | 2021-02-20T05:59:27.000Z | import sys
import yaml
import unittest
import numpy as np
from model import model
class Test(unittest.TestCase):
def setUp(self):
configs = yaml.load(open("./conf/config.yml").read(), Loader=yaml.Loader)
self.test_configs = configs["unittest_settings"]
self.model = model()
def test_case1(self):
if self.test_configs["input_type"] == "text":
r = {"input": "안녕 세계"}
else:
dim = self.test_configs["input_dimension"]
r = {"input": np.ndarray(dim).tolist()}
# mock message from backend
r["input"] = "https://raw.githubusercontent.com/diffunity/kpmg-corona-blue/vision/vision_model/images/image_UML.jpg"
output = self.model.inference(r)
print("Unittest output: ", output)
if __name__ == '__main__':
unittest.main()
| 26.21875 | 124 | 0.628129 | import sys
import yaml
import unittest
import numpy as np
from model import model
class Test(unittest.TestCase):
def setUp(self):
configs = yaml.load(open("./conf/config.yml").read(), Loader=yaml.Loader)
self.test_configs = configs["unittest_settings"]
self.model = model()
def test_case1(self):
if self.test_configs["input_type"] == "text":
r = {"input": "안녕 세계"}
else:
dim = self.test_configs["input_dimension"]
r = {"input": np.ndarray(dim).tolist()}
r["input"] = "https://raw.githubusercontent.com/diffunity/kpmg-corona-blue/vision/vision_model/images/image_UML.jpg"
output = self.model.inference(r)
print("Unittest output: ", output)
if __name__ == '__main__':
unittest.main()
| true | true |
1c3e1d3cb4937a0f1594aea801006e01a1c0cd0e | 11,882 | py | Python | gui/host_manager/remote_file_dialog.py | anglebinbin/Barista-tool | 2d51507fb3566881923f0b273127f59d23ed317f | [
"MIT"
] | 1 | 2020-02-11T19:05:17.000Z | 2020-02-11T19:05:17.000Z | gui/host_manager/remote_file_dialog.py | anglebinbin/Barista-tool | 2d51507fb3566881923f0b273127f59d23ed317f | [
"MIT"
] | null | null | null | gui/host_manager/remote_file_dialog.py | anglebinbin/Barista-tool | 2d51507fb3566881923f0b273127f59d23ed317f | [
"MIT"
] | null | null | null | from os.path import normpath
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex, pyqtSignal
from PyQt5.QtGui import QColor, QIcon
from PyQt5.QtWidgets import QDialog, QGridLayout, QTableView, QAbstractItemView, QComboBox, QPushButton, QLineEdit, \
QStyle, qApp, QFileIconProvider, QLabel
from backend.networking.net_util import sendMsgToHost
from backend.networking.protocol import Protocol
class RemoteFileDialog(QDialog):
def __init__(self, host, port, title="", fileFilter="All (*)", dirSelect=False, parent=None):
QDialog.__init__(self, parent)
self.fileFilter = fileFilter
# Set the window Title
if (title == ""):
title = "Remote"
windowtitle = title + " @ " + host + ":" + str(port)
self.setWindowTitle(windowtitle)
self.dirselect = dirSelect
self.returnvalue = ""
# Build the GUI
self.layout = QGridLayout(self)
self.tabview = self.KeyEventTableView()
self.tabview.verticalHeader().hide()
self.tabview.setSelectionMode(QAbstractItemView.SingleSelection)
self.tabview.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tabview.setFocus()
self.layout.addWidget(self.tabview, 1, 0, 1, 4)
# Import Model
self.model = self.RemoteFileItemModel(host, port, self.dirselect)
self.tabview.setModel(self.model)
# Parent Button
pix_parentdir = qApp.style().standardPixmap(QStyle.SP_FileDialogToParent)
ico_parentdir = QIcon(pix_parentdir)
self.pb_parentdir = QPushButton(ico_parentdir, "")
self.pb_parentdir.setFixedSize(35, 35)
self.pb_parentdir.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_parentdir, 0, 0)
# Refresh Button
pix_reload = qApp.style().standardPixmap(QStyle.SP_BrowserReload)
ico_reload = QIcon(pix_reload)
self.pb_refresh = QPushButton(ico_reload, "")
self.pb_refresh.setFixedSize(35, 35)
self.pb_refresh.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_refresh, 0, 1)
# Current Dir
self.le_path = QLineEdit()
self.le_path.setEnabled(False)
self.le_path.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.le_path, 0, 2, 1, 2)
# File Filter
self.cb_filter = QComboBox()
self.cb_filter.addItems([fi.split()[0] for fi in fileFilter.split(";;")])
if len(fileFilter.split(";;")) == 1:
self.cb_filter.setEnabled(False)
self.layout.addWidget(self.cb_filter, 2, 3, 1, 1)
# Status Label
self.lbl_status = QLabel("")
self.layout.addWidget(self.lbl_status, 2, 0, 1, 3)
# Confirm Button
self.pb_select = QPushButton("Select")
self.pb_select.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_select, 3, 2, 1, 1)
# Cancel Button
self.pb_cancel = QPushButton("Cancel")
self.pb_cancel.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_cancel, 3, 3, 1, 1)
# Resize Tabel
self.tabview.setColumnWidth(0, 400)
self.tabview.hideColumn(1)
self.tabview.setColumnWidth(2, 100)
self.tabview.setColumnWidth(3, 200)
self.tabview.setMinimumWidth(715)
self.tabview.setMinimumHeight(400)
self.adjustSize()
# Connect Signals
self.tabview.doubleClicked.connect(self._processInput) # Confirm on doubleclick
self.tabview.enterKey.connect(self._processInput) # Confirm on enter/return
self.tabview.backKey.connect(self._goToParentDir) # ParentDir on Backspace
self.tabview.selectionModel().currentChanged.connect(self._updateLineEdit) # update current dir
self.model.updateStatus.connect(self._setStatus) # update Host connection status
self.cb_filter.currentIndexChanged.connect(self._updateFilter) # update FileFilter
self.pb_parentdir.clicked.connect(self._goToParentDir) # Button ParentDir
self.pb_refresh.clicked.connect(self._updateCurrentDir) # Button Refresh
self.pb_cancel.clicked.connect(self._cancel) # Button Cancel
self.pb_select.clicked.connect(self._processInputButton) # Button Confirm / Select
# Fill Model with /home
self.model.updateModel("/home/", self._createFilter())
self._updateLineEdit()
self._updateSelection()
def _processInput(self):
"""update path or accept selection on double click, enter/return key or button """
if (self._getCurrentItemType()):
self.model.updateModel(self._getCurrentItemPath(), self._createFilter())
self._updateLineEdit()
self.tabview.scrollToTop()
self._updateSelection()
else:
self._accept()
def _processInputButton(self):
if self.dirselect:
self.returnvalue = self.le_path.text()
self.close()
else:
self._processInput()
def _createFilter(self):
"""create the filter from the Qt-syntax based on the current selection"""
current_filter = self.fileFilter.split(";;")[self.cb_filter.currentIndex()]
current_filter = current_filter.split(" ", 1)[1]
current_filter = current_filter[1:len(current_filter) - 1]
current_filter = current_filter.split()
return current_filter
def _updateFilter(self):
"""update the model with the current filter"""
self.model.updateModel(self.model.currentPath, self._createFilter())
self._updateSelection()
def _updateLineEdit(self):
"""set the current dir in the line edit"""
self.le_path.setText(normpath(self.model.currentPath))
def _getCurrentItemType(self):
"""check if selection is dir"""
row = self.tabview.currentIndex().row()
index = self.model.createIndex(row, 1)
return self.model.data(index, Qt.UserRole)
def _getCurrentItemPath(self):
"""get the path of the current selection"""
row = self.tabview.currentIndex().row()
index = self.model.createIndex(row, 1)
item = self.model.itemData(index)
if len(item) == 0:
return ""
return item[Qt.DisplayRole]
def _updateSelection(self):
"""change the selection to the first item"""
self.tabview.scrollToTop()
self.tabview.setCurrentIndex(self.model.createIndex(0, 0, ))
def _goToParentDir(self):
"""go to the parent directory"""
path = self.model.currentPath + "/.."
self.model.updateModel(path, self._createFilter())
self._updateLineEdit()
self._updateSelection()
def _updateCurrentDir(self):
"""refresh current directory"""
self.model.updateModel(self.model.currentPath, self._createFilter())
self._updateLineEdit()
self._updateSelection()
def _cancel(self):
"""close this dialog"""
self.close()
def _accept(self):
"""close this dialog and write the returnvalue"""
self.returnvalue = self._getCurrentItemPath()
self.close()
def _setStatus(self, status):
"""set the host connection status in the status label"""
if status:
self.lbl_status.setText("")
else:
self.lbl_status.setText("Host unreachable!")
class KeyEventTableView(QTableView):
"""A small helper class to catch the Keys on the TableView"""
enterKey = pyqtSignal()
backKey = pyqtSignal()
def __init__(self):
QTableView.__init__(self)
def keyPressEvent(self, keyEvent):
"""Detect the key presses and fire signals"""
if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
self.enterKey.emit()
return
if keyEvent.key() == Qt.Key_Backspace:
self.backKey.emit()
return
super(self.__class__, self).keyPressEvent(keyEvent)
class RemoteFileItemModel(QAbstractTableModel):
"""Model to convert the file dictionary into a table"""
updateStatus = pyqtSignal(bool)
def __init__(self, host, port, dirselect):
QAbstractTableModel.__init__(self)
self.host = host
self.port = port
self.dirselect = dirselect
self.currentPath = ""
self.fileList = list()
def rowCount(self, QModelIndex_parent=None, *args, **kwargs):
"""return the current row count"""
return len(self.fileList)
def columnCount(self, QModelIndex_parent=None, *args, **kwargs):
"""reuturn the current column count"""
return 4
def data(self, index, role=None):
"""return the data of the table for different roles"""
row = index.row()
if (row < 0 or row >= len(self.fileList)):
return
col = index.column()
file = self.fileList[row]
if role == Qt.UserRole: # use the UserRole to check if item is dir
if file["isDir"]:
return True
return False
if role == Qt.DisplayRole: # the text that is shown
if col == 0:
return file["name"]
if col == 1:
return file["path"]
if col == 2:
return file["fileSize"]
if col == 3:
return file["lastChange"]
if role == Qt.DecorationRole: # the icon in the first column
if col == 0:
fip = QFileIconProvider()
if file["isDir"]:
ico = fip.icon(QFileIconProvider.Folder) # type: QIcon
return ico.pixmap(20, 20)
ico = fip.icon(QFileIconProvider.File) # type: QIcon
return ico.pixmap(20, 20)
if role == Qt.BackgroundColorRole: # make stripes
if row % 2 == 0:
return QColor(Qt.white)
return QColor(Qt.lightGray).lighter(120)
def headerData(self, p_int, orient, int_role=None):
"""Change the column names in the header"""
if int_role == Qt.DisplayRole and orient == Qt.Horizontal:
return ["Name", "Path", "FileSize", "Last Changed"][p_int]
def updateModel(self, path="/home/", fileFilter=["*"]):
"""update the model by connecting to the host and asking for a new dir dictionary"""
msg = {"key": Protocol.GETDIR, "path": path, "filter": fileFilter, "dirSelect": False}
if self.dirselect:
msg["dirSelect"] = True
res = sendMsgToHost(self.host, self.port, msg)
if res:
self.currentPath = res["path"]
oldlen = len(self.fileList)
newlen = len(res["data"])
diff = oldlen - newlen
if diff > 0:
self.beginRemoveRows(QModelIndex(), newlen, oldlen - 1)
self.fileList = res["data"] # has to be done here to prevent invalid index exception
self.endRemoveRows()
if diff < 0:
self.beginInsertRows(QModelIndex(), oldlen, newlen - 1)
self.fileList = res["data"] # has to be done here to prevent invalid index exception
self.endInsertRows()
if diff == 0:
self.fileList = res["data"]
self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(newlen, 2))
self.updateStatus.emit(True)
return
self.updateStatus.emit(False)
| 39.214521 | 117 | 0.602087 | from os.path import normpath
from PyQt5.QtCore import QAbstractTableModel, Qt, QModelIndex, pyqtSignal
from PyQt5.QtGui import QColor, QIcon
from PyQt5.QtWidgets import QDialog, QGridLayout, QTableView, QAbstractItemView, QComboBox, QPushButton, QLineEdit, \
QStyle, qApp, QFileIconProvider, QLabel
from backend.networking.net_util import sendMsgToHost
from backend.networking.protocol import Protocol
class RemoteFileDialog(QDialog):
def __init__(self, host, port, title="", fileFilter="All (*)", dirSelect=False, parent=None):
QDialog.__init__(self, parent)
self.fileFilter = fileFilter
if (title == ""):
title = "Remote"
windowtitle = title + " @ " + host + ":" + str(port)
self.setWindowTitle(windowtitle)
self.dirselect = dirSelect
self.returnvalue = ""
self.layout = QGridLayout(self)
self.tabview = self.KeyEventTableView()
self.tabview.verticalHeader().hide()
self.tabview.setSelectionMode(QAbstractItemView.SingleSelection)
self.tabview.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tabview.setFocus()
self.layout.addWidget(self.tabview, 1, 0, 1, 4)
self.model = self.RemoteFileItemModel(host, port, self.dirselect)
self.tabview.setModel(self.model)
pix_parentdir = qApp.style().standardPixmap(QStyle.SP_FileDialogToParent)
ico_parentdir = QIcon(pix_parentdir)
self.pb_parentdir = QPushButton(ico_parentdir, "")
self.pb_parentdir.setFixedSize(35, 35)
self.pb_parentdir.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_parentdir, 0, 0)
pix_reload = qApp.style().standardPixmap(QStyle.SP_BrowserReload)
ico_reload = QIcon(pix_reload)
self.pb_refresh = QPushButton(ico_reload, "")
self.pb_refresh.setFixedSize(35, 35)
self.pb_refresh.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_refresh, 0, 1)
self.le_path = QLineEdit()
self.le_path.setEnabled(False)
self.le_path.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.le_path, 0, 2, 1, 2)
self.cb_filter = QComboBox()
self.cb_filter.addItems([fi.split()[0] for fi in fileFilter.split(";;")])
if len(fileFilter.split(";;")) == 1:
self.cb_filter.setEnabled(False)
self.layout.addWidget(self.cb_filter, 2, 3, 1, 1)
self.lbl_status = QLabel("")
self.layout.addWidget(self.lbl_status, 2, 0, 1, 3)
self.pb_select = QPushButton("Select")
self.pb_select.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_select, 3, 2, 1, 1)
self.pb_cancel = QPushButton("Cancel")
self.pb_cancel.setFocusPolicy(Qt.NoFocus)
self.layout.addWidget(self.pb_cancel, 3, 3, 1, 1)
self.tabview.setColumnWidth(0, 400)
self.tabview.hideColumn(1)
self.tabview.setColumnWidth(2, 100)
self.tabview.setColumnWidth(3, 200)
self.tabview.setMinimumWidth(715)
self.tabview.setMinimumHeight(400)
self.adjustSize()
self.tabview.doubleClicked.connect(self._processInput)
self.tabview.enterKey.connect(self._processInput)
self.tabview.backKey.connect(self._goToParentDir)
self.tabview.selectionModel().currentChanged.connect(self._updateLineEdit)
self.model.updateStatus.connect(self._setStatus)
self.cb_filter.currentIndexChanged.connect(self._updateFilter)
self.pb_parentdir.clicked.connect(self._goToParentDir)
self.pb_refresh.clicked.connect(self._updateCurrentDir)
self.pb_cancel.clicked.connect(self._cancel)
self.pb_select.clicked.connect(self._processInputButton)
self.model.updateModel("/home/", self._createFilter())
self._updateLineEdit()
self._updateSelection()
def _processInput(self):
if (self._getCurrentItemType()):
self.model.updateModel(self._getCurrentItemPath(), self._createFilter())
self._updateLineEdit()
self.tabview.scrollToTop()
self._updateSelection()
else:
self._accept()
def _processInputButton(self):
if self.dirselect:
self.returnvalue = self.le_path.text()
self.close()
else:
self._processInput()
def _createFilter(self):
current_filter = self.fileFilter.split(";;")[self.cb_filter.currentIndex()]
current_filter = current_filter.split(" ", 1)[1]
current_filter = current_filter[1:len(current_filter) - 1]
current_filter = current_filter.split()
return current_filter
def _updateFilter(self):
self.model.updateModel(self.model.currentPath, self._createFilter())
self._updateSelection()
def _updateLineEdit(self):
self.le_path.setText(normpath(self.model.currentPath))
def _getCurrentItemType(self):
row = self.tabview.currentIndex().row()
index = self.model.createIndex(row, 1)
return self.model.data(index, Qt.UserRole)
def _getCurrentItemPath(self):
row = self.tabview.currentIndex().row()
index = self.model.createIndex(row, 1)
item = self.model.itemData(index)
if len(item) == 0:
return ""
return item[Qt.DisplayRole]
def _updateSelection(self):
self.tabview.scrollToTop()
self.tabview.setCurrentIndex(self.model.createIndex(0, 0, ))
def _goToParentDir(self):
path = self.model.currentPath + "/.."
self.model.updateModel(path, self._createFilter())
self._updateLineEdit()
self._updateSelection()
def _updateCurrentDir(self):
self.model.updateModel(self.model.currentPath, self._createFilter())
self._updateLineEdit()
self._updateSelection()
def _cancel(self):
self.close()
def _accept(self):
self.returnvalue = self._getCurrentItemPath()
self.close()
def _setStatus(self, status):
if status:
self.lbl_status.setText("")
else:
self.lbl_status.setText("Host unreachable!")
class KeyEventTableView(QTableView):
enterKey = pyqtSignal()
backKey = pyqtSignal()
def __init__(self):
QTableView.__init__(self)
def keyPressEvent(self, keyEvent):
if keyEvent.key() == Qt.Key_Enter or keyEvent.key() == Qt.Key_Return:
self.enterKey.emit()
return
if keyEvent.key() == Qt.Key_Backspace:
self.backKey.emit()
return
super(self.__class__, self).keyPressEvent(keyEvent)
class RemoteFileItemModel(QAbstractTableModel):
updateStatus = pyqtSignal(bool)
def __init__(self, host, port, dirselect):
QAbstractTableModel.__init__(self)
self.host = host
self.port = port
self.dirselect = dirselect
self.currentPath = ""
self.fileList = list()
def rowCount(self, QModelIndex_parent=None, *args, **kwargs):
return len(self.fileList)
def columnCount(self, QModelIndex_parent=None, *args, **kwargs):
return 4
def data(self, index, role=None):
row = index.row()
if (row < 0 or row >= len(self.fileList)):
return
col = index.column()
file = self.fileList[row]
if role == Qt.UserRole:
if file["isDir"]:
return True
return False
if role == Qt.DisplayRole:
if col == 0:
return file["name"]
if col == 1:
return file["path"]
if col == 2:
return file["fileSize"]
if col == 3:
return file["lastChange"]
if role == Qt.DecorationRole:
if col == 0:
fip = QFileIconProvider()
if file["isDir"]:
ico = fip.icon(QFileIconProvider.Folder)
return ico.pixmap(20, 20)
ico = fip.icon(QFileIconProvider.File)
return ico.pixmap(20, 20)
if role == Qt.BackgroundColorRole:
if row % 2 == 0:
return QColor(Qt.white)
return QColor(Qt.lightGray).lighter(120)
def headerData(self, p_int, orient, int_role=None):
if int_role == Qt.DisplayRole and orient == Qt.Horizontal:
return ["Name", "Path", "FileSize", "Last Changed"][p_int]
def updateModel(self, path="/home/", fileFilter=["*"]):
msg = {"key": Protocol.GETDIR, "path": path, "filter": fileFilter, "dirSelect": False}
if self.dirselect:
msg["dirSelect"] = True
res = sendMsgToHost(self.host, self.port, msg)
if res:
self.currentPath = res["path"]
oldlen = len(self.fileList)
newlen = len(res["data"])
diff = oldlen - newlen
if diff > 0:
self.beginRemoveRows(QModelIndex(), newlen, oldlen - 1)
self.fileList = res["data"]
self.endRemoveRows()
if diff < 0:
self.beginInsertRows(QModelIndex(), oldlen, newlen - 1)
self.fileList = res["data"]
self.endInsertRows()
if diff == 0:
self.fileList = res["data"]
self.dataChanged.emit(self.createIndex(0, 0), self.createIndex(newlen, 2))
self.updateStatus.emit(True)
return
self.updateStatus.emit(False)
| true | true |
1c3e1d8084f6cdd2fd41504684374440dda47dc1 | 595 | py | Python | Basics/Loops.py | spirulinax/PyHub | ae92c249224013f86c06b4d6cec3c6caa2e18c4d | [
"MIT"
] | 1 | 2020-11-09T14:13:45.000Z | 2020-11-09T14:13:45.000Z | Basics/Loops.py | spirulinax/PyHub | ae92c249224013f86c06b4d6cec3c6caa2e18c4d | [
"MIT"
] | null | null | null | Basics/Loops.py | spirulinax/PyHub | ae92c249224013f86c06b4d6cec3c6caa2e18c4d | [
"MIT"
] | null | null | null | # While Loops :
i = 1
while i<11:
print(i)
i += 1
print()
# For Loops :
#Looping through lists:
greetings = ["Hello","World","!!!"]
for x in greetings: #Loops through elements of the list.
print(x)
print()
#Looping through a string:
for x in "hello": #Loops through characters in the string.
print(x)
print()
#Range Function:
for x in range(6): #0-5
print(x)
print()
for x in range(1, 6): #1-5
print(x)
print()
for x in range(0, 20, 2): #0-20, skips 2 -> 2,4,6....18,20
print(x)
print()
input("Press Enter key to exit ") | 18.030303 | 68 | 0.571429 |
i = 1
while i<11:
print(i)
i += 1
print()
greetings = ["Hello","World","!!!"]
for x in greetings:
print(x)
print()
for x in "hello":
print(x)
print()
for x in range(6):
print(x)
print()
for x in range(1, 6):
print(x)
print()
for x in range(0, 20, 2):
print(x)
print()
input("Press Enter key to exit ") | true | true |
1c3e1dd507d94b1adb0eb7905ef870b84330df89 | 4,943 | py | Python | elephantblog/models.py | sbaechler/feincms-elephantblog | d3d1824d1781cfa0f81d6cf16577f8e540fc1441 | [
"BSD-3-Clause"
] | null | null | null | elephantblog/models.py | sbaechler/feincms-elephantblog | d3d1824d1781cfa0f81d6cf16577f8e540fc1441 | [
"BSD-3-Clause"
] | null | null | null | elephantblog/models.py | sbaechler/feincms-elephantblog | d3d1824d1781cfa0f81d6cf16577f8e540fc1441 | [
"BSD-3-Clause"
] | null | null | null | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.template.defaultfilters import slugify
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _, ugettext
from feincms import translations
from feincms.models import Base
from feincms.module.mixins import ContentModelMixin
from feincms.utils.managers import ActiveAwareContentManagerMixin
from feincms.utils.queryset_transform import TransformManager
@python_2_unicode_compatible
class Category(models.Model, translations.TranslatedObjectMixin):
"""
Category is language-aware and connected to the Entry model via
a many to many relationship.
"""
ordering = models.SmallIntegerField(_('ordering'), default=0)
objects = translations.TranslatedObjectManager()
class Meta:
verbose_name = _('category')
verbose_name_plural = _('categories')
ordering = ['ordering']
def __str__(self):
try:
translation = self.translation
except models.ObjectDoesNotExist:
return ugettext('Unnamed category')
if translation:
return '%s' % translation
return ugettext('Unnamed category')
@python_2_unicode_compatible
class CategoryTranslation(translations.Translation(Category)):
title = models.CharField(_('category title'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
description = models.CharField(
_('description'), max_length=250, blank=True)
class Meta:
verbose_name = _('category translation')
verbose_name_plural = _('category translations')
ordering = ['title']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('elephantblog_category_detail', kwargs={
'slug': self.slug,
})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(CategoryTranslation, self).save(*args, **kwargs)
class EntryManager(ActiveAwareContentManagerMixin, TransformManager):
def featured(self):
return self.active().filter(is_featured=True)
EntryManager.add_to_active_filters(
Q(is_active=True),
key='cleared')
EntryManager.add_to_active_filters(
lambda queryset: queryset.filter(published_on__lte=timezone.now()),
key='published_on_past')
@python_2_unicode_compatible
class Entry(Base, ContentModelMixin):
is_active = models.BooleanField(
_('is active'), default=True, db_index=True)
is_featured = models.BooleanField(
_('is featured'), default=False, db_index=True)
title = models.CharField(_('title'), max_length=100)
slug = models.SlugField(
_('slug'), max_length=100,
unique_for_date='published_on')
author = models.ForeignKey(
getattr(settings, 'AUTH_USER_MODEL', 'auth.User'),
related_name='blogentries',
limit_choices_to={'is_staff': True}, verbose_name=_('author'))
published_on = models.DateTimeField(
_('published on'),
blank=True, null=True, default=timezone.now, db_index=True,
help_text=_(
'Will be filled in automatically when entry gets published.'))
last_changed = models.DateTimeField(
_('last change'), auto_now=True, editable=False)
categories = models.ManyToManyField(
Category, verbose_name=_('categories'),
related_name='blogentries', null=True, blank=True)
objects = EntryManager()
class Meta:
get_latest_by = 'published_on'
ordering = ['-published_on']
verbose_name = _('entry')
verbose_name_plural = _('entries')
def __str__(self):
return self.title
def __init__(self, *args, **kwargs):
super(Entry, self).__init__(*args, **kwargs)
self._old_is_active = self.is_active
def save(self, *args, **kwargs):
if self.is_active and not self.published_on:
self.published_on = timezone.now()
super(Entry, self).save(*args, **kwargs)
save.alters_data = True
def get_absolute_url(self):
# We use naive date using UTC for conversion for permalink
if getattr(settings, 'USE_TZ', False):
pub_date = timezone.make_naive(self.published_on, timezone.utc)
else:
pub_date = self.published_on
return reverse('elephantblog_entry_detail', kwargs={
'year': pub_date.strftime('%Y'),
'month': pub_date.strftime('%m'),
'day': pub_date.strftime('%d'),
'slug': self.slug,
})
@classmethod
def register_extension(cls, register_fn):
from .modeladmins import EntryAdmin
register_fn(cls, EntryAdmin)
| 32.097403 | 75 | 0.680963 | from __future__ import absolute_import, unicode_literals
from django.conf import settings
from django.core.urlresolvers import reverse
from django.db import models
from django.db.models import Q
from django.template.defaultfilters import slugify
from django.utils import timezone
from django.utils.encoding import python_2_unicode_compatible
from django.utils.translation import ugettext_lazy as _, ugettext
from feincms import translations
from feincms.models import Base
from feincms.module.mixins import ContentModelMixin
from feincms.utils.managers import ActiveAwareContentManagerMixin
from feincms.utils.queryset_transform import TransformManager
@python_2_unicode_compatible
class Category(models.Model, translations.TranslatedObjectMixin):
ordering = models.SmallIntegerField(_('ordering'), default=0)
objects = translations.TranslatedObjectManager()
class Meta:
verbose_name = _('category')
verbose_name_plural = _('categories')
ordering = ['ordering']
def __str__(self):
try:
translation = self.translation
except models.ObjectDoesNotExist:
return ugettext('Unnamed category')
if translation:
return '%s' % translation
return ugettext('Unnamed category')
@python_2_unicode_compatible
class CategoryTranslation(translations.Translation(Category)):
title = models.CharField(_('category title'), max_length=100)
slug = models.SlugField(_('slug'), unique=True)
description = models.CharField(
_('description'), max_length=250, blank=True)
class Meta:
verbose_name = _('category translation')
verbose_name_plural = _('category translations')
ordering = ['title']
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('elephantblog_category_detail', kwargs={
'slug': self.slug,
})
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.title)
super(CategoryTranslation, self).save(*args, **kwargs)
class EntryManager(ActiveAwareContentManagerMixin, TransformManager):
def featured(self):
return self.active().filter(is_featured=True)
EntryManager.add_to_active_filters(
Q(is_active=True),
key='cleared')
EntryManager.add_to_active_filters(
lambda queryset: queryset.filter(published_on__lte=timezone.now()),
key='published_on_past')
@python_2_unicode_compatible
class Entry(Base, ContentModelMixin):
is_active = models.BooleanField(
_('is active'), default=True, db_index=True)
is_featured = models.BooleanField(
_('is featured'), default=False, db_index=True)
title = models.CharField(_('title'), max_length=100)
slug = models.SlugField(
_('slug'), max_length=100,
unique_for_date='published_on')
author = models.ForeignKey(
getattr(settings, 'AUTH_USER_MODEL', 'auth.User'),
related_name='blogentries',
limit_choices_to={'is_staff': True}, verbose_name=_('author'))
published_on = models.DateTimeField(
_('published on'),
blank=True, null=True, default=timezone.now, db_index=True,
help_text=_(
'Will be filled in automatically when entry gets published.'))
last_changed = models.DateTimeField(
_('last change'), auto_now=True, editable=False)
categories = models.ManyToManyField(
Category, verbose_name=_('categories'),
related_name='blogentries', null=True, blank=True)
objects = EntryManager()
class Meta:
get_latest_by = 'published_on'
ordering = ['-published_on']
verbose_name = _('entry')
verbose_name_plural = _('entries')
def __str__(self):
return self.title
def __init__(self, *args, **kwargs):
super(Entry, self).__init__(*args, **kwargs)
self._old_is_active = self.is_active
def save(self, *args, **kwargs):
if self.is_active and not self.published_on:
self.published_on = timezone.now()
super(Entry, self).save(*args, **kwargs)
save.alters_data = True
def get_absolute_url(self):
if getattr(settings, 'USE_TZ', False):
pub_date = timezone.make_naive(self.published_on, timezone.utc)
else:
pub_date = self.published_on
return reverse('elephantblog_entry_detail', kwargs={
'year': pub_date.strftime('%Y'),
'month': pub_date.strftime('%m'),
'day': pub_date.strftime('%d'),
'slug': self.slug,
})
@classmethod
def register_extension(cls, register_fn):
from .modeladmins import EntryAdmin
register_fn(cls, EntryAdmin)
| true | true |
1c3e1e8e68d04871f96f80f4048970726b75f266 | 2,202 | py | Python | unified_mem_benchmark.py | tcapelle/tf-metal-experiments | d296ba2656dd352947ed8f6f80bdb349c1ab9617 | [
"MIT"
] | 96 | 2021-10-29T20:43:03.000Z | 2022-03-30T06:37:04.000Z | unified_mem_benchmark.py | tcapelle/tf-metal-experiments | d296ba2656dd352947ed8f6f80bdb349c1ab9617 | [
"MIT"
] | 10 | 2021-11-01T20:40:29.000Z | 2022-03-08T19:32:30.000Z | unified_mem_benchmark.py | tcapelle/tf-metal-experiments | d296ba2656dd352947ed8f6f80bdb349c1ab9617 | [
"MIT"
] | 10 | 2021-10-30T10:38:33.000Z | 2022-02-01T16:51:04.000Z | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--iterations", default=30, type=int,
help="Number of iterations to run within each benchmark")
parser.add_argument("--device1", default="/CPU:0", type=str)
parser.add_argument("--device2", default="/GPU:0", type=str)
args = parser.parse_args()
import os
import time
from tqdm import tqdm
import tensorflow as tf
@tf.function(experimental_autograph_options=tf.autograph.experimental.Feature.ALL)
def do_op(a, b):
with tf.device(args.device1):
x = a * b + b
with tf.device(args.device2):
x = tf.linalg.matmul(a, x)
with tf.device(args.device1):
x = a * x + b
with tf.device(args.device2):
x = tf.linalg.matmul(b, x)
with tf.device(args.device1):
x = a * b + x
with tf.device(args.device2):
x = tf.linalg.matmul(a, x)
with tf.device(args.device1):
x = a * b + x
with tf.device(args.device2):
x = tf.linalg.matmul(b, x)
return x
def benchmark_matmul(M, dtype=tf.float32, iterations=30):
# generate data and warm-up iteration
A = tf.random.normal([M, M], mean=0, stddev=1, dtype=dtype)
B = tf.random.normal([M, M], mean=0, stddev=1, dtype=dtype)
C = do_op(A, B)
C.numpy()
C = do_op(A, B)
C.numpy()
# run benchmark
st = time.time()
for _ in range(iterations+1):
C = do_op(A, B)
C.numpy()
et = time.time()
duration = (et-st)
return iterations/duration
fp16_matmul, fp32_matmul, fp64_matmul = [], [], []
fp16_tflops, fp32_tflops, fp64_tflops = [], [], []
M_list = [2048] * 30
print("\nStarting burn...\n")
burn_start = time.time()
for M in tqdm(M_list):
print("FP32", M, end=" : ")
ret = benchmark_matmul(M, dtype=tf.float32, iterations=args.iterations)
tflops = 4 * (ret * 2 * M**3 + 2*M*M)/ 1e12
fp32_matmul.append(ret)
fp32_tflops.append(tflops)
print(tflops)
#time.sleep(1)
burn_end = time.time()
print("\nFinished in", int(burn_end-burn_start), "seconds\n")
title = "Max TFLOPS achieved"
print("")
print(title)
print("="*len(title))
print("* FP32:", round(max(fp32_tflops),1), "TFLOPS")
print("")
| 27.525 | 82 | 0.624432 | import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--iterations", default=30, type=int,
help="Number of iterations to run within each benchmark")
parser.add_argument("--device1", default="/CPU:0", type=str)
parser.add_argument("--device2", default="/GPU:0", type=str)
args = parser.parse_args()
import os
import time
from tqdm import tqdm
import tensorflow as tf
@tf.function(experimental_autograph_options=tf.autograph.experimental.Feature.ALL)
def do_op(a, b):
with tf.device(args.device1):
x = a * b + b
with tf.device(args.device2):
x = tf.linalg.matmul(a, x)
with tf.device(args.device1):
x = a * x + b
with tf.device(args.device2):
x = tf.linalg.matmul(b, x)
with tf.device(args.device1):
x = a * b + x
with tf.device(args.device2):
x = tf.linalg.matmul(a, x)
with tf.device(args.device1):
x = a * b + x
with tf.device(args.device2):
x = tf.linalg.matmul(b, x)
return x
def benchmark_matmul(M, dtype=tf.float32, iterations=30):
A = tf.random.normal([M, M], mean=0, stddev=1, dtype=dtype)
B = tf.random.normal([M, M], mean=0, stddev=1, dtype=dtype)
C = do_op(A, B)
C.numpy()
C = do_op(A, B)
C.numpy()
st = time.time()
for _ in range(iterations+1):
C = do_op(A, B)
C.numpy()
et = time.time()
duration = (et-st)
return iterations/duration
fp16_matmul, fp32_matmul, fp64_matmul = [], [], []
fp16_tflops, fp32_tflops, fp64_tflops = [], [], []
M_list = [2048] * 30
print("\nStarting burn...\n")
burn_start = time.time()
for M in tqdm(M_list):
print("FP32", M, end=" : ")
ret = benchmark_matmul(M, dtype=tf.float32, iterations=args.iterations)
tflops = 4 * (ret * 2 * M**3 + 2*M*M)/ 1e12
fp32_matmul.append(ret)
fp32_tflops.append(tflops)
print(tflops)
burn_end = time.time()
print("\nFinished in", int(burn_end-burn_start), "seconds\n")
title = "Max TFLOPS achieved"
print("")
print(title)
print("="*len(title))
print("* FP32:", round(max(fp32_tflops),1), "TFLOPS")
print("")
| true | true |
1c3e1ef481efd0b6d4af937e7c92fac238269f9d | 409 | py | Python | tob-api/api_v2/models/Name.py | andrewwhitehead/TheOrgBook | 5a3dcd27cdcda0a3e19a68597a49997c68143ddc | [
"Apache-2.0"
] | null | null | null | tob-api/api_v2/models/Name.py | andrewwhitehead/TheOrgBook | 5a3dcd27cdcda0a3e19a68597a49997c68143ddc | [
"Apache-2.0"
] | 37 | 2019-03-12T20:10:57.000Z | 2020-11-26T18:39:51.000Z | tob-api/api_v2/models/Name.py | andrewwhitehead/TheOrgBook | 5a3dcd27cdcda0a3e19a68597a49997c68143ddc | [
"Apache-2.0"
] | 5 | 2019-02-26T17:38:37.000Z | 2020-11-26T14:48:03.000Z | from django.db import models
from .Auditable import Auditable
from .Credential import Credential
class Name(Auditable):
reindex_related = ['credential']
credential = models.ForeignKey(Credential, related_name="names", on_delete=models.CASCADE)
text = models.TextField(null=True)
language = models.TextField(null=True)
class Meta:
db_table = "name"
ordering = ('id',)
| 22.722222 | 94 | 0.706601 | from django.db import models
from .Auditable import Auditable
from .Credential import Credential
class Name(Auditable):
reindex_related = ['credential']
credential = models.ForeignKey(Credential, related_name="names", on_delete=models.CASCADE)
text = models.TextField(null=True)
language = models.TextField(null=True)
class Meta:
db_table = "name"
ordering = ('id',)
| true | true |
1c3e1f3af038eae1a91fa09018acf8d869c54d78 | 98 | py | Python | 32.operacoes_com_tuplas/13.update.py | robinson-1985/python-zero-dnc | df510d67e453611fcd320df1397cdb9ca47fecb8 | [
"MIT"
] | null | null | null | 32.operacoes_com_tuplas/13.update.py | robinson-1985/python-zero-dnc | df510d67e453611fcd320df1397cdb9ca47fecb8 | [
"MIT"
] | null | null | null | 32.operacoes_com_tuplas/13.update.py | robinson-1985/python-zero-dnc | df510d67e453611fcd320df1397cdb9ca47fecb8 | [
"MIT"
] | null | null | null | set_5={1,2,3,4,5}
set_3={1,2,3,4,7,0,9}
print(set_5)
print(set_3)
set_5.update(set_3)
print(set_5) | 16.333333 | 21 | 0.693878 | set_5={1,2,3,4,5}
set_3={1,2,3,4,7,0,9}
print(set_5)
print(set_3)
set_5.update(set_3)
print(set_5) | true | true |
1c3e1f48043047ffba0468863f386bf3937fe9a6 | 4,984 | py | Python | example_ticker_and_miniticker.py | esquire900/unicorn-binance-websocket-api | 0b519561cde4ed49a4aac039a996b188bfb4f521 | [
"MIT"
] | 404 | 2019-11-13T02:22:39.000Z | 2021-12-31T08:48:10.000Z | example_ticker_and_miniticker.py | gladiopeace/unicorn-binance-websocket-api | 5bddc943343766210e8635d551084e566ffe0c21 | [
"MIT"
] | 181 | 2019-11-02T21:10:17.000Z | 2021-12-31T12:55:51.000Z | example_ticker_and_miniticker.py | gladiopeace/unicorn-binance-websocket-api | 5bddc943343766210e8635d551084e566ffe0c21 | [
"MIT"
] | 103 | 2019-11-16T23:39:24.000Z | 2021-12-28T05:15:05.000Z | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# File: example_ticker_and_miniticker.py
#
# Part of ‘UNICORN Binance WebSocket API’
# Project website: https://github.com/oliver-zehentleitner/unicorn-binance-websocket-api
# Documentation: https://oliver-zehentleitner.github.io/unicorn-binance-websocket-api
# PyPI: https://pypi.org/project/unicorn-binance-websocket-api/
#
# Author: Oliver Zehentleitner
# https://about.me/oliver-zehentleitner
#
# Copyright (c) 2019-2021, Oliver Zehentleitner
# All rights reserved.
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing 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 MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR 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.
from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
import os
import time
import threading
import logging
# import class to process stream data
from example_process_streams import BinanceWebSocketApiProcessStreams
# https://docs.python.org/3/library/logging.html#logging-levels
logging.basicConfig(level=logging.DEBUG,
filename=os.path.basename(__file__) + '.log',
format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
style="{")
# create instance of BinanceWebSocketApiManager and provide the function for stream processing
binance_websocket_api_manager = BinanceWebSocketApiManager(BinanceWebSocketApiProcessStreams.process_stream_data)
# binance_websocket_api_manager = BinanceWebSocketApiManager(exchange="binance.com")
def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
while True:
if binance_websocket_api_manager.is_manager_stopping():
exit(0)
oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
if oldest_stream_data_from_stream_buffer is False:
time.sleep(0.01)
else:
#pass
print(oldest_stream_data_from_stream_buffer)
# start a worker process to move the received stream_data from the stream_buffer to a print function
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_websocket_api_manager,))
worker_thread.start()
# create streams
print("\r\n========================================== Starting ticker all ========================================\r\n")
ticker_arr_stream_id = binance_websocket_api_manager.create_stream("arr", "!ticker")
time.sleep(7)
binance_websocket_api_manager.stop_stream(ticker_arr_stream_id)
time.sleep(2)
print("\r\n=========================================== Stopp ticker all ==========================================\r\n")
print("\r\n============================================ Starting ticker ==========================================\r\n")
ticker_stream_id = binance_websocket_api_manager.create_stream("ticker", ['bnbbtc', 'ethbtc'])
time.sleep(7)
binance_websocket_api_manager.stop_stream(ticker_stream_id)
time.sleep(2)
print("\r\n============================================== Stop ticker ===========================================\r\n")
print("\r\n======================================== Starting !miniTicker arr =====================================\r\n")
miniTicker_arr_stream_id = binance_websocket_api_manager.create_stream("arr", "!miniTicker")
time.sleep(7)
binance_websocket_api_manager.stop_stream(miniTicker_arr_stream_id)
time.sleep(2)
print("\r\n========================================== Stop !miniTicker arr =======================================\r\n")
print("\r\n========================================== Starting miniTicker ========================================\r\n")
miniTicker_stream_id = binance_websocket_api_manager.create_stream("miniTicker", ['bnbbtc', 'ethbtc'])
time.sleep(7)
binance_websocket_api_manager.stop_stream(miniTicker_stream_id)
time.sleep(2)
print("\r\n============================================ Stop miniTicker==========================================\r\n")
binance_websocket_api_manager.print_summary()
binance_websocket_api_manager.stop_manager_with_all_streams() | 48.38835 | 120 | 0.675161 |
from unicorn_binance_websocket_api.unicorn_binance_websocket_api_manager import BinanceWebSocketApiManager
import os
import time
import threading
import logging
from example_process_streams import BinanceWebSocketApiProcessStreams
onfig(level=logging.DEBUG,
filename=os.path.basename(__file__) + '.log',
format="{asctime} [{levelname:8}] {process} {thread} {module}: {message}",
style="{")
binance_websocket_api_manager = BinanceWebSocketApiManager(BinanceWebSocketApiProcessStreams.process_stream_data)
def print_stream_data_from_stream_buffer(binance_websocket_api_manager):
while True:
if binance_websocket_api_manager.is_manager_stopping():
exit(0)
oldest_stream_data_from_stream_buffer = binance_websocket_api_manager.pop_stream_data_from_stream_buffer()
if oldest_stream_data_from_stream_buffer is False:
time.sleep(0.01)
else:
print(oldest_stream_data_from_stream_buffer)
worker_thread = threading.Thread(target=print_stream_data_from_stream_buffer, args=(binance_websocket_api_manager,))
worker_thread.start()
print("\r\n========================================== Starting ticker all ========================================\r\n")
ticker_arr_stream_id = binance_websocket_api_manager.create_stream("arr", "!ticker")
time.sleep(7)
binance_websocket_api_manager.stop_stream(ticker_arr_stream_id)
time.sleep(2)
print("\r\n=========================================== Stopp ticker all ==========================================\r\n")
print("\r\n============================================ Starting ticker ==========================================\r\n")
ticker_stream_id = binance_websocket_api_manager.create_stream("ticker", ['bnbbtc', 'ethbtc'])
time.sleep(7)
binance_websocket_api_manager.stop_stream(ticker_stream_id)
time.sleep(2)
print("\r\n============================================== Stop ticker ===========================================\r\n")
print("\r\n======================================== Starting !miniTicker arr =====================================\r\n")
miniTicker_arr_stream_id = binance_websocket_api_manager.create_stream("arr", "!miniTicker")
time.sleep(7)
binance_websocket_api_manager.stop_stream(miniTicker_arr_stream_id)
time.sleep(2)
print("\r\n========================================== Stop !miniTicker arr =======================================\r\n")
print("\r\n========================================== Starting miniTicker ========================================\r\n")
miniTicker_stream_id = binance_websocket_api_manager.create_stream("miniTicker", ['bnbbtc', 'ethbtc'])
time.sleep(7)
binance_websocket_api_manager.stop_stream(miniTicker_stream_id)
time.sleep(2)
print("\r\n============================================ Stop miniTicker==========================================\r\n")
binance_websocket_api_manager.print_summary()
binance_websocket_api_manager.stop_manager_with_all_streams() | true | true |
1c3e1fc2ba319da7c82d26f480a4424902c460fc | 24 | py | Python | web/db/__init__.py | ArturSamvelyan/fastapi-sqlalchemy-postgresql-template | c6ed650bd3ffeda98ecc4cd4a0d44b3cae5c1bfb | [
"MIT"
] | null | null | null | web/db/__init__.py | ArturSamvelyan/fastapi-sqlalchemy-postgresql-template | c6ed650bd3ffeda98ecc4cd4a0d44b3cae5c1bfb | [
"MIT"
] | null | null | null | web/db/__init__.py | ArturSamvelyan/fastapi-sqlalchemy-postgresql-template | c6ed650bd3ffeda98ecc4cd4a0d44b3cae5c1bfb | [
"MIT"
] | null | null | null | from .users import users | 24 | 24 | 0.833333 | from .users import users | true | true |
1c3e20b56db40a4968e01553fd867337cdcf67c5 | 25,818 | py | Python | examples/identity-app/images/agents/agent.py | fabio97U/bevel | 02909fec93b3256253279e43ebf0395f38c8eb7e | [
"Apache-2.0"
] | null | null | null | examples/identity-app/images/agents/agent.py | fabio97U/bevel | 02909fec93b3256253279e43ebf0395f38c8eb7e | [
"Apache-2.0"
] | null | null | null | examples/identity-app/images/agents/agent.py | fabio97U/bevel | 02909fec93b3256253279e43ebf0395f38c8eb7e | [
"Apache-2.0"
] | null | null | null | import asyncio
import asyncpg
import functools
import json
import logging
import os
import random
import subprocess
import hashlib
import base58
from timeit import default_timer
from aiohttp import (
web,
ClientSession,
ClientRequest,
ClientResponse,
ClientError,
ClientTimeout,
)
from .utils import flatten, log_json, log_msg, log_timer, output_reader
LOGGER = logging.getLogger(__name__)
event_stream_handler = logging.StreamHandler()
event_stream_handler.setFormatter(logging.Formatter("\nEVENT: %(message)s"))
DEBUG_EVENTS = os.getenv("EVENTS")
EVENT_LOGGER = logging.getLogger("event")
EVENT_LOGGER.setLevel(logging.DEBUG if DEBUG_EVENTS else logging.NOTSET)
EVENT_LOGGER.addHandler(event_stream_handler)
EVENT_LOGGER.propagate = False
TRACE_TARGET = os.getenv("TRACE_TARGET")
TRACE_TAG = os.getenv("TRACE_TAG")
TRACE_ENABLED = os.getenv("TRACE_ENABLED")
DEFAULT_POSTGRES = bool(os.getenv("POSTGRES"))
DEFAULT_INTERNAL_HOST = "127.0.0.1"
DEFAULT_EXTERNAL_HOST = "localhost"
DEFAULT_BIN_PATH = "../bin"
DEFAULT_PYTHON_PATH = ".."
START_TIMEOUT = float(os.getenv("START_TIMEOUT", 30.0))
RUN_MODE = os.getenv("RUNMODE")
GENESIS_URL = os.getenv("GENESIS_URL")
LEDGER_URL = os.getenv("LEDGER_URL")
GENESIS_FILE = os.getenv("GENESIS_FILE")
if RUN_MODE == "docker":
DEFAULT_INTERNAL_HOST = os.getenv("DOCKERHOST") or "host.docker.internal"
DEFAULT_EXTERNAL_HOST = DEFAULT_INTERNAL_HOST
DEFAULT_BIN_PATH = "./bin"
DEFAULT_PYTHON_PATH = "."
elif RUN_MODE == "pwd":
# DEFAULT_INTERNAL_HOST =
DEFAULT_EXTERNAL_HOST = os.getenv("DOCKERHOST") or "host.docker.internal"
DEFAULT_BIN_PATH = "./bin"
DEFAULT_PYTHON_PATH = "."
class repr_json:
def __init__(self, val):
self.val = val
def __repr__(self) -> str:
if isinstance(self.val, str):
return self.val
return json.dumps(self.val, indent=4)
async def default_genesis_txns():
genesis = None
try:
if GENESIS_URL:
async with ClientSession() as session:
async with session.get(GENESIS_URL) as resp:
genesis = await resp.text()
elif RUN_MODE == "docker":
async with ClientSession() as session:
async with session.get(
f"http://{DEFAULT_EXTERNAL_HOST}:9000/genesis"
) as resp:
genesis = await resp.text()
elif GENESIS_FILE:
with open(GENESIS_FILE, "r") as genesis_file:
genesis = genesis_file.read()
else:
with open("local-genesis.txt", "r") as genesis_file:
genesis = genesis_file.read()
except Exception:
LOGGER.exception("Error loading genesis transactions:")
return genesis
class DemoAgent:
def __init__(
self,
ident: str,
http_port: int,
admin_port: int,
internal_host: str = None,
external_host: str = None,
genesis_data: str = None,
seed: str = "random",
label: str = None,
color: str = None,
prefix: str = None,
timing: bool = False,
timing_log: str = None,
postgres: bool = None,
extra_args=None,
**params,
):
self.ident = ident
self.http_port = http_port
self.admin_port = admin_port
self.internal_host = internal_host or DEFAULT_INTERNAL_HOST
self.external_host = external_host or DEFAULT_EXTERNAL_HOST
self.genesis_data = genesis_data
self.label = label or ident
self.color = color
self.prefix = prefix
self.timing = timing
self.timing_log = timing_log
self.postgres = DEFAULT_POSTGRES if postgres is None else postgres
self.extra_args = extra_args
self.trace_enabled = TRACE_ENABLED
self.trace_target = TRACE_TARGET
self.trace_tag = TRACE_TAG
self.admin_url = f"http://{self.internal_host}:{admin_port}"
if RUN_MODE == "pwd":
self.endpoint = f"http://{self.external_host}".replace(
"{PORT}", str(http_port)
)
else:
self.endpoint = f"http://{self.external_host}:{http_port}"
if os.getenv("PUBLIC_TAILS_URL"):
self.public_tails_url = os.getenv("PUBLIC_TAILS_URL")
elif RUN_MODE == "pwd":
self.public_tails_url = f"http://{self.external_host}".replace(
"{PORT}", str(admin_port)
)
else:
self.public_tails_url = self.admin_url
self.webhook_port = None
self.webhook_url = None
self.webhook_site = None
self.params = params
self.proc = None
self.client_session: ClientSession = ClientSession()
rand_name = str(random.randint(100_000, 999_999))
self.seed = (
("my_seed_000000000000000000000000" + rand_name)[-32:]
if seed == "random"
else seed
)
self.storage_type = params.get("storage_type")
self.wallet_type = params.get("wallet_type", "indy")
self.wallet_name = (
params.get("wallet_name") or self.ident.lower().replace(" ", "") + rand_name
)
self.wallet_key = params.get("wallet_key") or self.ident + rand_name
self.did = None
self.wallet_stats = []
async def register_schema_and_creddef(
self, schema_name, version, schema_attrs, support_revocation: bool = False
):
# Create a schema
schema_body = {
"schema_name": schema_name,
"schema_version": version,
"attributes": schema_attrs,
}
schema_response = await self.admin_POST("/schemas", schema_body)
# log_json(json.dumps(schema_response), label="Schema:")
schema_id = schema_response["schema_id"]
log_msg("Schema ID:", schema_id)
# Create a cred def for the schema
credential_definition_body = {
"schema_id": schema_id,
"support_revocation": support_revocation,
}
credential_definition_response = await self.admin_POST(
"/credential-definitions", credential_definition_body
)
credential_definition_id = credential_definition_response[
"credential_definition_id"
]
log_msg("Cred def ID:", credential_definition_id)
return schema_id, credential_definition_id
async def create_and_publish_revocation_registry(
self, credential_def_id, max_cred_num
):
revoc_response = await self.admin_POST(
"/revocation/create-registry",
{
"credential_definition_id": credential_def_id,
"max_cred_num": max_cred_num,
},
)
revocation_registry_id = revoc_response["result"]["revoc_reg_id"]
tails_hash = revoc_response["result"]["tails_hash"]
# get the tails file from "GET /revocation/registry/{id}/tails-file"
tails_file = await self.admin_GET_FILE(
f"/revocation/registry/{revocation_registry_id}/tails-file"
)
hasher = hashlib.sha256()
hasher.update(tails_file)
my_tails_hash = base58.b58encode(hasher.digest()).decode("utf-8")
log_msg(f"Revocation Registry ID: {revocation_registry_id}")
assert tails_hash == my_tails_hash
# Real app should publish tails file somewhere and update the revocation registry with the URI.
# But for the demo, assume the agent's admin end-points are accessible to the other agents
# Update the revocation registry with the public URL to the tails file
tails_file_admin_url = (
f"{self.admin_url}/revocation/registry/{revocation_registry_id}/tails-file"
)
tails_file_url = f"{self.public_tails_url}/revocation/registry/{revocation_registry_id}/tails-file"
if RUN_MODE == "pwd":
tails_file_external_url = f"http://{self.external_host}".replace(
"{PORT}", str(self.admin_port)
)
else:
tails_file_external_url = f"http://127.0.0.1:{self.admin_port}"
tails_file_external_url += (
f"/revocation/registry/{revocation_registry_id}/tails-file"
)
revoc_updated_response = await self.admin_PATCH(
f"/revocation/registry/{revocation_registry_id}",
{"tails_public_uri": tails_file_url},
)
tails_public_uri = revoc_updated_response["result"]["tails_public_uri"]
assert tails_public_uri == tails_file_url
# if PUBLIC_TAILS_URL is specified, tell user how to get tails file from agent
if os.getenv("PUBLIC_TAILS_URL"):
log_msg(f"================")
log_msg(f"Revocation Registry Tails File Admin URL: {tails_file_admin_url}")
log_msg(f"Revocation Registry Tails File URL: {tails_public_uri}")
log_msg(f"External host Tails File URL: {tails_file_external_url}")
log_msg(f"================")
log_msg(f"mkdir -p ./revocation/registry/{revocation_registry_id}/")
log_msg(
f'curl -X GET "{tails_file_external_url}" --output ./revocation/registry/{revocation_registry_id}/tails-file.bin'
)
log_msg(
f"base64 revocation/registry/{revocation_registry_id}/tails-file.bin >revocation/registry/{revocation_registry_id}/tails-file"
)
log_msg(f"================")
revoc_publish_response = await self.admin_POST(
f"/revocation/registry/{revocation_registry_id}/publish"
)
return revoc_publish_response["result"]["revoc_reg_id"]
def get_agent_args(self):
result = [
("--endpoint", self.endpoint),
("--label", self.label),
"--auto-ping-connection",
"--auto-respond-messages",
("--inbound-transport", "http", "0.0.0.0", str(self.http_port)),
("--outbound-transport", "http"),
("--admin", "0.0.0.0", str(self.admin_port)),
"--admin-insecure-mode",
("--wallet-type", self.wallet_type),
("--wallet-name", self.wallet_name),
("--wallet-key", self.wallet_key),
"--preserve-exchange-records",
]
if self.genesis_data:
result.append(("--genesis-transactions", self.genesis_data))
if self.seed:
result.append(("--seed", self.seed))
if self.storage_type:
result.append(("--storage-type", self.storage_type))
if self.timing:
result.append("--timing")
if self.timing_log:
result.append(("--timing-log", self.timing_log))
if self.postgres:
result.extend(
[
("--wallet-storage-type", "postgres_storage"),
("--wallet-storage-config", json.dumps(self.postgres_config)),
("--wallet-storage-creds", json.dumps(self.postgres_creds)),
]
)
if self.webhook_url:
result.append(("--webhook-url", self.webhook_url))
if self.trace_enabled:
result.extend(
[
("--trace",),
("--trace-target", self.trace_target),
("--trace-tag", self.trace_tag),
("--trace-label", self.label + ".trace"),
]
)
else:
# set the tracing parameters but don't enable tracing
result.extend(
[
(
"--trace-target",
self.trace_target if self.trace_target else "log",
),
(
"--trace-tag",
self.trace_tag if self.trace_tag else "acapy.events",
),
("--trace-label", self.label + ".trace"),
]
)
if self.extra_args:
result.extend(self.extra_args)
return result
@property
def prefix_str(self):
if self.prefix:
return f"{self.prefix:10s} |"
async def register_did(self, ledger_url: str = None, alias: str = None):
self.log(f"Registering {self.ident} with seed {self.seed}")
if not ledger_url:
ledger_url = LEDGER_URL
if not ledger_url:
ledger_url = f"http://{self.external_host}:9000"
data = {"alias": alias or self.ident, "seed": self.seed, "role": "TRUST_ANCHOR"}
print('data: alias: {}, seed: {}, role: {}'.format(data["alias"], data["seed"], data["role"]))
async with self.client_session.post(
ledger_url + "/register", json=data
) as resp:
if resp.status != 200:
raise Exception(f"Error registering DID, response code {resp.status}")
nym_info = await resp.json()
self.did = nym_info["did"]
self.log(f"Got DID: {self.did}")
def handle_output(self, *output, source: str = None, **kwargs):
end = "" if source else "\n"
if source == "stderr":
color = "fg:ansired"
elif not source:
color = self.color or "fg:ansiblue"
else:
color = None
log_msg(*output, color=color, prefix=self.prefix_str, end=end, **kwargs)
def log(self, *msg, **kwargs):
self.handle_output(*msg, **kwargs)
def log_json(self, data, label: str = None, **kwargs):
log_json(data, label=label, prefix=self.prefix_str, **kwargs)
def log_timer(self, label: str, show: bool = True, **kwargs):
return log_timer(label, show, logger=self.log, **kwargs)
def _process(self, args, env, loop):
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
encoding="utf-8",
)
loop.run_in_executor(
None,
output_reader,
proc.stdout,
functools.partial(self.handle_output, source="stdout"),
)
loop.run_in_executor(
None,
output_reader,
proc.stderr,
functools.partial(self.handle_output, source="stderr"),
)
return proc
def get_process_args(self, bin_path: str = None):
cmd_path = "aca-py"
if bin_path is None:
bin_path = DEFAULT_BIN_PATH
if bin_path:
cmd_path = os.path.join(bin_path, cmd_path)
return list(flatten((["python3", cmd_path, "start"], self.get_agent_args())))
async def start_process(
self, python_path: str = None, bin_path: str = None, wait: bool = True
):
my_env = os.environ.copy()
python_path = DEFAULT_PYTHON_PATH if python_path is None else python_path
if python_path:
my_env["PYTHONPATH"] = python_path
agent_args = self.get_process_args(bin_path)
# start agent sub-process
loop = asyncio.get_event_loop()
self.proc = await loop.run_in_executor(
None, self._process, agent_args, my_env, loop
)
if wait:
await asyncio.sleep(1.0)
await self.detect_process()
def _terminate(self):
if self.proc and self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=0.5)
self.log(f"Exited with return code {self.proc.returncode}")
except subprocess.TimeoutExpired:
msg = "Process did not terminate in time"
self.log(msg)
raise Exception(msg)
async def terminate(self):
loop = asyncio.get_event_loop()
if self.proc:
await loop.run_in_executor(None, self._terminate)
await self.client_session.close()
if self.webhook_site:
await self.webhook_site.stop()
async def listen_webhooks(self, webhook_port):
self.webhook_port = webhook_port
self.webhook_url = f"http://localhost:{str(webhook_port)}/webhooks"
app = web.Application()
app.add_routes([web.post("/webhooks/topic/{topic}/", self._receive_webhook)])
runner = web.AppRunner(app)
await runner.setup()
self.webhook_site = web.TCPSite(runner, "0.0.0.0", webhook_port)
await self.webhook_site.start()
async def _receive_webhook(self, request: ClientRequest):
topic = request.match_info["topic"]
payload = await request.json()
await self.handle_webhook(topic, payload)
return web.Response(status=200)
async def handle_webhook(self, topic: str, payload):
if topic != "webhook": # would recurse
handler = f"handle_{topic}"
method = getattr(self, handler, None)
if method:
EVENT_LOGGER.debug(
"Agent called controller webhook: %s%s",
handler,
(f" with payload: \n{repr_json(payload)}" if payload else ""),
)
asyncio.get_event_loop().create_task(method(payload))
else:
log_msg(
f"Error: agent {self.ident} "
f"has no method {handler} "
f"to handle webhook on topic {topic}"
)
async def admin_request(
self, method, path, data=None, text=False, params=None
) -> ClientResponse:
params = {k: v for (k, v) in (params or {}).items() if v is not None}
async with self.client_session.request(
method, self.admin_url + path, json=data, params=params
) as resp:
resp.raise_for_status()
resp_text = await resp.text()
if not resp_text and not text:
return None
if not text:
try:
return json.loads(resp_text)
except json.JSONDecodeError as e:
raise Exception(f"Error decoding JSON: {resp_text}") from e
return resp_text
async def admin_GET(self, path, text=False, params=None) -> ClientResponse:
try:
EVENT_LOGGER.debug("Controller GET %s request to Agent", path)
response = await self.admin_request("GET", path, None, text, params)
EVENT_LOGGER.debug(
"Response from GET %s received: \n%s", path, repr_json(response),
)
return response
except ClientError as e:
self.log(f"Error during GET {path}: {str(e)}")
raise
async def admin_POST(
self, path, data=None, text=False, params=None
) -> ClientResponse:
try:
EVENT_LOGGER.debug(
"Controller POST %s request to Agent%s",
path,
(" with data: \n{}".format(repr_json(data)) if data else ""),
)
response = await self.admin_request("POST", path, data, text, params)
EVENT_LOGGER.debug(
"Response from POST %s received: \n%s", path, repr_json(response),
)
return response
except ClientError as e:
self.log(f"Error during POST {path}: {str(e)}")
raise
async def admin_PATCH(
self, path, data=None, text=False, params=None
) -> ClientResponse:
try:
return await self.admin_request("PATCH", path, data, text, params)
except ClientError as e:
self.log(f"Error during PATCH {path}: {str(e)}")
raise
async def admin_GET_FILE(self, path, params=None) -> bytes:
try:
params = {k: v for (k, v) in (params or {}).items() if v is not None}
resp = await self.client_session.request(
"GET", self.admin_url + path, params=params
)
resp.raise_for_status()
return await resp.read()
except ClientError as e:
self.log(f"Error during GET FILE {path}: {str(e)}")
raise
async def detect_process(self):
async def fetch_status(url: str, timeout: float):
text = None
start = default_timer()
async with ClientSession(timeout=ClientTimeout(total=3.0)) as session:
while default_timer() - start < timeout:
try:
async with session.get(url) as resp:
if resp.status == 200:
text = await resp.text()
break
except (ClientError, asyncio.TimeoutError):
pass
await asyncio.sleep(0.5)
return text
status_url = self.admin_url + "/status"
status_text = await fetch_status(status_url, START_TIMEOUT)
if not status_text:
raise Exception(
"Timed out waiting for agent process to start. "
+ f"Admin URL: {status_url}"
)
ok = False
try:
status = json.loads(status_text)
ok = isinstance(status, dict) and "version" in status
except json.JSONDecodeError:
pass
if not ok:
raise Exception(
f"Unexpected response from agent process. Admin URL: {status_url}"
)
async def fetch_timing(self):
status = await self.admin_GET("/status")
return status.get("timing")
def format_timing(self, timing: dict) -> dict:
result = []
for name, count in timing["count"].items():
result.append(
(
name[:35],
count,
timing["total"][name],
timing["avg"][name],
timing["min"][name],
timing["max"][name],
)
)
result.sort(key=lambda row: row[2], reverse=True)
yield "{:35} | {:>12} {:>12} {:>10} {:>10} {:>10}".format(
"", "count", "total", "avg", "min", "max"
)
yield "=" * 96
yield from (
"{:35} | {:12d} {:12.3f} {:10.3f} {:10.3f} {:10.3f}".format(*row)
for row in result
)
yield ""
async def reset_timing(self):
await self.admin_POST("/status/reset", text=True)
@property
def postgres_config(self):
return {
"url": f"{self.internal_host}:5432",
"tls": "None",
"max_connections": 5,
"min_idle_time": 0,
"connection_timeout": 10,
}
@property
def postgres_creds(self):
return {
"account": "postgres",
"password": "mysecretpassword",
"admin_account": "postgres",
"admin_password": "mysecretpassword",
}
async def collect_postgres_stats(self, ident: str, vacuum_full: bool = True):
creds = self.postgres_creds
conn = await asyncpg.connect(
host=self.internal_host,
port="5432",
user=creds["admin_account"],
password=creds["admin_password"],
database=self.wallet_name,
)
tables = ("items", "tags_encrypted", "tags_plaintext")
for t in tables:
await conn.execute(f"VACUUM FULL {t}" if vacuum_full else f"VACUUM {t}")
sizes = await conn.fetch(
"""
SELECT relname AS "relation",
pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size"
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname = 'public'
ORDER BY pg_total_relation_size(C.oid) DESC;
"""
)
results = {k: [0, "0B"] for k in tables}
for row in sizes:
if row["relation"] in results:
results[row["relation"]][1] = row["total_size"].replace(" ", "")
for t in tables:
row = await conn.fetchrow(f"""SELECT COUNT(*) AS "count" FROM {t}""")
results[t][0] = row["count"]
self.wallet_stats.append((ident, results))
await conn.close()
def format_postgres_stats(self):
if not self.wallet_stats:
return
yield "{:30} | {:>17} | {:>17} | {:>17}".format(
f"{self.wallet_name} DB", "items", "tags_encrypted", "tags_plaintext"
)
yield "=" * 90
for ident, stats in self.wallet_stats:
yield "{:30} | {:8d} {:>8} | {:8d} {:>8} | {:8d} {:>8}".format(
ident,
stats["items"][0],
stats["items"][1],
stats["tags_encrypted"][0],
stats["tags_encrypted"][1],
stats["tags_plaintext"][0],
stats["tags_plaintext"][1],
)
yield ""
def reset_postgres_stats(self):
self.wallet_stats.clear()
| 37.580786 | 143 | 0.548609 | import asyncio
import asyncpg
import functools
import json
import logging
import os
import random
import subprocess
import hashlib
import base58
from timeit import default_timer
from aiohttp import (
web,
ClientSession,
ClientRequest,
ClientResponse,
ClientError,
ClientTimeout,
)
from .utils import flatten, log_json, log_msg, log_timer, output_reader
LOGGER = logging.getLogger(__name__)
event_stream_handler = logging.StreamHandler()
event_stream_handler.setFormatter(logging.Formatter("\nEVENT: %(message)s"))
DEBUG_EVENTS = os.getenv("EVENTS")
EVENT_LOGGER = logging.getLogger("event")
EVENT_LOGGER.setLevel(logging.DEBUG if DEBUG_EVENTS else logging.NOTSET)
EVENT_LOGGER.addHandler(event_stream_handler)
EVENT_LOGGER.propagate = False
TRACE_TARGET = os.getenv("TRACE_TARGET")
TRACE_TAG = os.getenv("TRACE_TAG")
TRACE_ENABLED = os.getenv("TRACE_ENABLED")
DEFAULT_POSTGRES = bool(os.getenv("POSTGRES"))
DEFAULT_INTERNAL_HOST = "127.0.0.1"
DEFAULT_EXTERNAL_HOST = "localhost"
DEFAULT_BIN_PATH = "../bin"
DEFAULT_PYTHON_PATH = ".."
START_TIMEOUT = float(os.getenv("START_TIMEOUT", 30.0))
RUN_MODE = os.getenv("RUNMODE")
GENESIS_URL = os.getenv("GENESIS_URL")
LEDGER_URL = os.getenv("LEDGER_URL")
GENESIS_FILE = os.getenv("GENESIS_FILE")
if RUN_MODE == "docker":
DEFAULT_INTERNAL_HOST = os.getenv("DOCKERHOST") or "host.docker.internal"
DEFAULT_EXTERNAL_HOST = DEFAULT_INTERNAL_HOST
DEFAULT_BIN_PATH = "./bin"
DEFAULT_PYTHON_PATH = "."
elif RUN_MODE == "pwd":
DEFAULT_EXTERNAL_HOST = os.getenv("DOCKERHOST") or "host.docker.internal"
DEFAULT_BIN_PATH = "./bin"
DEFAULT_PYTHON_PATH = "."
class repr_json:
def __init__(self, val):
self.val = val
def __repr__(self) -> str:
if isinstance(self.val, str):
return self.val
return json.dumps(self.val, indent=4)
async def default_genesis_txns():
genesis = None
try:
if GENESIS_URL:
async with ClientSession() as session:
async with session.get(GENESIS_URL) as resp:
genesis = await resp.text()
elif RUN_MODE == "docker":
async with ClientSession() as session:
async with session.get(
f"http://{DEFAULT_EXTERNAL_HOST}:9000/genesis"
) as resp:
genesis = await resp.text()
elif GENESIS_FILE:
with open(GENESIS_FILE, "r") as genesis_file:
genesis = genesis_file.read()
else:
with open("local-genesis.txt", "r") as genesis_file:
genesis = genesis_file.read()
except Exception:
LOGGER.exception("Error loading genesis transactions:")
return genesis
class DemoAgent:
def __init__(
self,
ident: str,
http_port: int,
admin_port: int,
internal_host: str = None,
external_host: str = None,
genesis_data: str = None,
seed: str = "random",
label: str = None,
color: str = None,
prefix: str = None,
timing: bool = False,
timing_log: str = None,
postgres: bool = None,
extra_args=None,
**params,
):
self.ident = ident
self.http_port = http_port
self.admin_port = admin_port
self.internal_host = internal_host or DEFAULT_INTERNAL_HOST
self.external_host = external_host or DEFAULT_EXTERNAL_HOST
self.genesis_data = genesis_data
self.label = label or ident
self.color = color
self.prefix = prefix
self.timing = timing
self.timing_log = timing_log
self.postgres = DEFAULT_POSTGRES if postgres is None else postgres
self.extra_args = extra_args
self.trace_enabled = TRACE_ENABLED
self.trace_target = TRACE_TARGET
self.trace_tag = TRACE_TAG
self.admin_url = f"http://{self.internal_host}:{admin_port}"
if RUN_MODE == "pwd":
self.endpoint = f"http://{self.external_host}".replace(
"{PORT}", str(http_port)
)
else:
self.endpoint = f"http://{self.external_host}:{http_port}"
if os.getenv("PUBLIC_TAILS_URL"):
self.public_tails_url = os.getenv("PUBLIC_TAILS_URL")
elif RUN_MODE == "pwd":
self.public_tails_url = f"http://{self.external_host}".replace(
"{PORT}", str(admin_port)
)
else:
self.public_tails_url = self.admin_url
self.webhook_port = None
self.webhook_url = None
self.webhook_site = None
self.params = params
self.proc = None
self.client_session: ClientSession = ClientSession()
rand_name = str(random.randint(100_000, 999_999))
self.seed = (
("my_seed_000000000000000000000000" + rand_name)[-32:]
if seed == "random"
else seed
)
self.storage_type = params.get("storage_type")
self.wallet_type = params.get("wallet_type", "indy")
self.wallet_name = (
params.get("wallet_name") or self.ident.lower().replace(" ", "") + rand_name
)
self.wallet_key = params.get("wallet_key") or self.ident + rand_name
self.did = None
self.wallet_stats = []
async def register_schema_and_creddef(
self, schema_name, version, schema_attrs, support_revocation: bool = False
):
schema_body = {
"schema_name": schema_name,
"schema_version": version,
"attributes": schema_attrs,
}
schema_response = await self.admin_POST("/schemas", schema_body)
schema_id = schema_response["schema_id"]
log_msg("Schema ID:", schema_id)
credential_definition_body = {
"schema_id": schema_id,
"support_revocation": support_revocation,
}
credential_definition_response = await self.admin_POST(
"/credential-definitions", credential_definition_body
)
credential_definition_id = credential_definition_response[
"credential_definition_id"
]
log_msg("Cred def ID:", credential_definition_id)
return schema_id, credential_definition_id
async def create_and_publish_revocation_registry(
self, credential_def_id, max_cred_num
):
revoc_response = await self.admin_POST(
"/revocation/create-registry",
{
"credential_definition_id": credential_def_id,
"max_cred_num": max_cred_num,
},
)
revocation_registry_id = revoc_response["result"]["revoc_reg_id"]
tails_hash = revoc_response["result"]["tails_hash"]
tails_file = await self.admin_GET_FILE(
f"/revocation/registry/{revocation_registry_id}/tails-file"
)
hasher = hashlib.sha256()
hasher.update(tails_file)
my_tails_hash = base58.b58encode(hasher.digest()).decode("utf-8")
log_msg(f"Revocation Registry ID: {revocation_registry_id}")
assert tails_hash == my_tails_hash
# Update the revocation registry with the public URL to the tails file
tails_file_admin_url = (
f"{self.admin_url}/revocation/registry/{revocation_registry_id}/tails-file"
)
tails_file_url = f"{self.public_tails_url}/revocation/registry/{revocation_registry_id}/tails-file"
if RUN_MODE == "pwd":
tails_file_external_url = f"http://{self.external_host}".replace(
"{PORT}", str(self.admin_port)
)
else:
tails_file_external_url = f"http://127.0.0.1:{self.admin_port}"
tails_file_external_url += (
f"/revocation/registry/{revocation_registry_id}/tails-file"
)
revoc_updated_response = await self.admin_PATCH(
f"/revocation/registry/{revocation_registry_id}",
{"tails_public_uri": tails_file_url},
)
tails_public_uri = revoc_updated_response["result"]["tails_public_uri"]
assert tails_public_uri == tails_file_url
# if PUBLIC_TAILS_URL is specified, tell user how to get tails file from agent
if os.getenv("PUBLIC_TAILS_URL"):
log_msg(f"================")
log_msg(f"Revocation Registry Tails File Admin URL: {tails_file_admin_url}")
log_msg(f"Revocation Registry Tails File URL: {tails_public_uri}")
log_msg(f"External host Tails File URL: {tails_file_external_url}")
log_msg(f"================")
log_msg(f"mkdir -p ./revocation/registry/{revocation_registry_id}/")
log_msg(
f'curl -X GET "{tails_file_external_url}" --output ./revocation/registry/{revocation_registry_id}/tails-file.bin'
)
log_msg(
f"base64 revocation/registry/{revocation_registry_id}/tails-file.bin >revocation/registry/{revocation_registry_id}/tails-file"
)
log_msg(f"================")
revoc_publish_response = await self.admin_POST(
f"/revocation/registry/{revocation_registry_id}/publish"
)
return revoc_publish_response["result"]["revoc_reg_id"]
def get_agent_args(self):
result = [
("--endpoint", self.endpoint),
("--label", self.label),
"--auto-ping-connection",
"--auto-respond-messages",
("--inbound-transport", "http", "0.0.0.0", str(self.http_port)),
("--outbound-transport", "http"),
("--admin", "0.0.0.0", str(self.admin_port)),
"--admin-insecure-mode",
("--wallet-type", self.wallet_type),
("--wallet-name", self.wallet_name),
("--wallet-key", self.wallet_key),
"--preserve-exchange-records",
]
if self.genesis_data:
result.append(("--genesis-transactions", self.genesis_data))
if self.seed:
result.append(("--seed", self.seed))
if self.storage_type:
result.append(("--storage-type", self.storage_type))
if self.timing:
result.append("--timing")
if self.timing_log:
result.append(("--timing-log", self.timing_log))
if self.postgres:
result.extend(
[
("--wallet-storage-type", "postgres_storage"),
("--wallet-storage-config", json.dumps(self.postgres_config)),
("--wallet-storage-creds", json.dumps(self.postgres_creds)),
]
)
if self.webhook_url:
result.append(("--webhook-url", self.webhook_url))
if self.trace_enabled:
result.extend(
[
("--trace",),
("--trace-target", self.trace_target),
("--trace-tag", self.trace_tag),
("--trace-label", self.label + ".trace"),
]
)
else:
# set the tracing parameters but don't enable tracing
result.extend(
[
(
"--trace-target",
self.trace_target if self.trace_target else "log",
),
(
"--trace-tag",
self.trace_tag if self.trace_tag else "acapy.events",
),
("--trace-label", self.label + ".trace"),
]
)
if self.extra_args:
result.extend(self.extra_args)
return result
@property
def prefix_str(self):
if self.prefix:
return f"{self.prefix:10s} |"
async def register_did(self, ledger_url: str = None, alias: str = None):
self.log(f"Registering {self.ident} with seed {self.seed}")
if not ledger_url:
ledger_url = LEDGER_URL
if not ledger_url:
ledger_url = f"http://{self.external_host}:9000"
data = {"alias": alias or self.ident, "seed": self.seed, "role": "TRUST_ANCHOR"}
print('data: alias: {}, seed: {}, role: {}'.format(data["alias"], data["seed"], data["role"]))
async with self.client_session.post(
ledger_url + "/register", json=data
) as resp:
if resp.status != 200:
raise Exception(f"Error registering DID, response code {resp.status}")
nym_info = await resp.json()
self.did = nym_info["did"]
self.log(f"Got DID: {self.did}")
def handle_output(self, *output, source: str = None, **kwargs):
end = "" if source else "\n"
if source == "stderr":
color = "fg:ansired"
elif not source:
color = self.color or "fg:ansiblue"
else:
color = None
log_msg(*output, color=color, prefix=self.prefix_str, end=end, **kwargs)
def log(self, *msg, **kwargs):
self.handle_output(*msg, **kwargs)
def log_json(self, data, label: str = None, **kwargs):
log_json(data, label=label, prefix=self.prefix_str, **kwargs)
def log_timer(self, label: str, show: bool = True, **kwargs):
return log_timer(label, show, logger=self.log, **kwargs)
def _process(self, args, env, loop):
proc = subprocess.Popen(
args,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
env=env,
encoding="utf-8",
)
loop.run_in_executor(
None,
output_reader,
proc.stdout,
functools.partial(self.handle_output, source="stdout"),
)
loop.run_in_executor(
None,
output_reader,
proc.stderr,
functools.partial(self.handle_output, source="stderr"),
)
return proc
def get_process_args(self, bin_path: str = None):
cmd_path = "aca-py"
if bin_path is None:
bin_path = DEFAULT_BIN_PATH
if bin_path:
cmd_path = os.path.join(bin_path, cmd_path)
return list(flatten((["python3", cmd_path, "start"], self.get_agent_args())))
async def start_process(
self, python_path: str = None, bin_path: str = None, wait: bool = True
):
my_env = os.environ.copy()
python_path = DEFAULT_PYTHON_PATH if python_path is None else python_path
if python_path:
my_env["PYTHONPATH"] = python_path
agent_args = self.get_process_args(bin_path)
loop = asyncio.get_event_loop()
self.proc = await loop.run_in_executor(
None, self._process, agent_args, my_env, loop
)
if wait:
await asyncio.sleep(1.0)
await self.detect_process()
def _terminate(self):
if self.proc and self.proc.poll() is None:
self.proc.terminate()
try:
self.proc.wait(timeout=0.5)
self.log(f"Exited with return code {self.proc.returncode}")
except subprocess.TimeoutExpired:
msg = "Process did not terminate in time"
self.log(msg)
raise Exception(msg)
async def terminate(self):
loop = asyncio.get_event_loop()
if self.proc:
await loop.run_in_executor(None, self._terminate)
await self.client_session.close()
if self.webhook_site:
await self.webhook_site.stop()
async def listen_webhooks(self, webhook_port):
self.webhook_port = webhook_port
self.webhook_url = f"http://localhost:{str(webhook_port)}/webhooks"
app = web.Application()
app.add_routes([web.post("/webhooks/topic/{topic}/", self._receive_webhook)])
runner = web.AppRunner(app)
await runner.setup()
self.webhook_site = web.TCPSite(runner, "0.0.0.0", webhook_port)
await self.webhook_site.start()
async def _receive_webhook(self, request: ClientRequest):
topic = request.match_info["topic"]
payload = await request.json()
await self.handle_webhook(topic, payload)
return web.Response(status=200)
async def handle_webhook(self, topic: str, payload):
if topic != "webhook":
handler = f"handle_{topic}"
method = getattr(self, handler, None)
if method:
EVENT_LOGGER.debug(
"Agent called controller webhook: %s%s",
handler,
(f" with payload: \n{repr_json(payload)}" if payload else ""),
)
asyncio.get_event_loop().create_task(method(payload))
else:
log_msg(
f"Error: agent {self.ident} "
f"has no method {handler} "
f"to handle webhook on topic {topic}"
)
async def admin_request(
self, method, path, data=None, text=False, params=None
) -> ClientResponse:
params = {k: v for (k, v) in (params or {}).items() if v is not None}
async with self.client_session.request(
method, self.admin_url + path, json=data, params=params
) as resp:
resp.raise_for_status()
resp_text = await resp.text()
if not resp_text and not text:
return None
if not text:
try:
return json.loads(resp_text)
except json.JSONDecodeError as e:
raise Exception(f"Error decoding JSON: {resp_text}") from e
return resp_text
async def admin_GET(self, path, text=False, params=None) -> ClientResponse:
try:
EVENT_LOGGER.debug("Controller GET %s request to Agent", path)
response = await self.admin_request("GET", path, None, text, params)
EVENT_LOGGER.debug(
"Response from GET %s received: \n%s", path, repr_json(response),
)
return response
except ClientError as e:
self.log(f"Error during GET {path}: {str(e)}")
raise
async def admin_POST(
self, path, data=None, text=False, params=None
) -> ClientResponse:
try:
EVENT_LOGGER.debug(
"Controller POST %s request to Agent%s",
path,
(" with data: \n{}".format(repr_json(data)) if data else ""),
)
response = await self.admin_request("POST", path, data, text, params)
EVENT_LOGGER.debug(
"Response from POST %s received: \n%s", path, repr_json(response),
)
return response
except ClientError as e:
self.log(f"Error during POST {path}: {str(e)}")
raise
async def admin_PATCH(
self, path, data=None, text=False, params=None
) -> ClientResponse:
try:
return await self.admin_request("PATCH", path, data, text, params)
except ClientError as e:
self.log(f"Error during PATCH {path}: {str(e)}")
raise
async def admin_GET_FILE(self, path, params=None) -> bytes:
try:
params = {k: v for (k, v) in (params or {}).items() if v is not None}
resp = await self.client_session.request(
"GET", self.admin_url + path, params=params
)
resp.raise_for_status()
return await resp.read()
except ClientError as e:
self.log(f"Error during GET FILE {path}: {str(e)}")
raise
async def detect_process(self):
async def fetch_status(url: str, timeout: float):
text = None
start = default_timer()
async with ClientSession(timeout=ClientTimeout(total=3.0)) as session:
while default_timer() - start < timeout:
try:
async with session.get(url) as resp:
if resp.status == 200:
text = await resp.text()
break
except (ClientError, asyncio.TimeoutError):
pass
await asyncio.sleep(0.5)
return text
status_url = self.admin_url + "/status"
status_text = await fetch_status(status_url, START_TIMEOUT)
if not status_text:
raise Exception(
"Timed out waiting for agent process to start. "
+ f"Admin URL: {status_url}"
)
ok = False
try:
status = json.loads(status_text)
ok = isinstance(status, dict) and "version" in status
except json.JSONDecodeError:
pass
if not ok:
raise Exception(
f"Unexpected response from agent process. Admin URL: {status_url}"
)
async def fetch_timing(self):
status = await self.admin_GET("/status")
return status.get("timing")
def format_timing(self, timing: dict) -> dict:
result = []
for name, count in timing["count"].items():
result.append(
(
name[:35],
count,
timing["total"][name],
timing["avg"][name],
timing["min"][name],
timing["max"][name],
)
)
result.sort(key=lambda row: row[2], reverse=True)
yield "{:35} | {:>12} {:>12} {:>10} {:>10} {:>10}".format(
"", "count", "total", "avg", "min", "max"
)
yield "=" * 96
yield from (
"{:35} | {:12d} {:12.3f} {:10.3f} {:10.3f} {:10.3f}".format(*row)
for row in result
)
yield ""
async def reset_timing(self):
await self.admin_POST("/status/reset", text=True)
@property
def postgres_config(self):
return {
"url": f"{self.internal_host}:5432",
"tls": "None",
"max_connections": 5,
"min_idle_time": 0,
"connection_timeout": 10,
}
@property
def postgres_creds(self):
return {
"account": "postgres",
"password": "mysecretpassword",
"admin_account": "postgres",
"admin_password": "mysecretpassword",
}
async def collect_postgres_stats(self, ident: str, vacuum_full: bool = True):
creds = self.postgres_creds
conn = await asyncpg.connect(
host=self.internal_host,
port="5432",
user=creds["admin_account"],
password=creds["admin_password"],
database=self.wallet_name,
)
tables = ("items", "tags_encrypted", "tags_plaintext")
for t in tables:
await conn.execute(f"VACUUM FULL {t}" if vacuum_full else f"VACUUM {t}")
sizes = await conn.fetch(
"""
SELECT relname AS "relation",
pg_size_pretty(pg_total_relation_size(C.oid)) AS "total_size"
FROM pg_class C
LEFT JOIN pg_namespace N ON (N.oid = C.relnamespace)
WHERE nspname = 'public'
ORDER BY pg_total_relation_size(C.oid) DESC;
"""
)
results = {k: [0, "0B"] for k in tables}
for row in sizes:
if row["relation"] in results:
results[row["relation"]][1] = row["total_size"].replace(" ", "")
for t in tables:
row = await conn.fetchrow(f"""SELECT COUNT(*) AS "count" FROM {t}""")
results[t][0] = row["count"]
self.wallet_stats.append((ident, results))
await conn.close()
def format_postgres_stats(self):
if not self.wallet_stats:
return
yield "{:30} | {:>17} | {:>17} | {:>17}".format(
f"{self.wallet_name} DB", "items", "tags_encrypted", "tags_plaintext"
)
yield "=" * 90
for ident, stats in self.wallet_stats:
yield "{:30} | {:8d} {:>8} | {:8d} {:>8} | {:8d} {:>8}".format(
ident,
stats["items"][0],
stats["items"][1],
stats["tags_encrypted"][0],
stats["tags_encrypted"][1],
stats["tags_plaintext"][0],
stats["tags_plaintext"][1],
)
yield ""
def reset_postgres_stats(self):
self.wallet_stats.clear()
| true | true |
1c3e2159a603800c25810e4e53b4fd9f5f1e7568 | 1,323 | py | Python | tools/src/blogs/api/interface.py | Symthy/blog-index-manager | d0c2e0b265b35be7cdb5aead1f1543f4b0306bdf | [
"MIT"
] | null | null | null | tools/src/blogs/api/interface.py | Symthy/blog-index-manager | d0c2e0b265b35be7cdb5aead1f1543f4b0306bdf | [
"MIT"
] | 1 | 2022-01-29T08:28:36.000Z | 2022-01-29T08:28:36.000Z | tools/src/blogs/api/interface.py | Symthy/blog-index-manager | d0c2e0b265b35be7cdb5aead1f1543f4b0306bdf | [
"MIT"
] | null | null | null | from abc import ABC, abstractmethod
from typing import Optional
from domain.blog.blog_entry import BlogEntry, BlogEntries
from domain.blog.photo_entry import PhotoEntry
class IBlogApiExecutor(ABC):
@abstractmethod
def execute_get_blog_entry_api(self, entry_id: str) -> Optional[BlogEntry]:
pass
@abstractmethod
def execute_get_all_blog_entries_api(self) -> BlogEntries:
pass
@abstractmethod
def execute_register_blog_entry_api(self, title: str, category: str, content: str,
is_draft: bool) -> Optional[BlogEntry]:
pass
@abstractmethod
def execute_update_blog_summary_page(self, content: str) -> bool:
pass
@abstractmethod
def execute_update_blog_entry_api(self, entry_id: str, title: str, category: str,
content: str, is_draft: bool) -> Optional[BlogEntry]:
pass
@abstractmethod
def execute_get_photo_entry_api(self, entry_id: str) -> Optional[PhotoEntry]:
pass
@abstractmethod
def execute_register_photo_entry_api(self, image_file_path: str) -> Optional[PhotoEntry]:
pass
@abstractmethod
def execute_update_photo_entry_api(self, image_file_path: str, photo_entry: PhotoEntry) -> Optional[PhotoEntry]:
pass
| 31.5 | 116 | 0.687831 | from abc import ABC, abstractmethod
from typing import Optional
from domain.blog.blog_entry import BlogEntry, BlogEntries
from domain.blog.photo_entry import PhotoEntry
class IBlogApiExecutor(ABC):
@abstractmethod
def execute_get_blog_entry_api(self, entry_id: str) -> Optional[BlogEntry]:
pass
@abstractmethod
def execute_get_all_blog_entries_api(self) -> BlogEntries:
pass
@abstractmethod
def execute_register_blog_entry_api(self, title: str, category: str, content: str,
is_draft: bool) -> Optional[BlogEntry]:
pass
@abstractmethod
def execute_update_blog_summary_page(self, content: str) -> bool:
pass
@abstractmethod
def execute_update_blog_entry_api(self, entry_id: str, title: str, category: str,
content: str, is_draft: bool) -> Optional[BlogEntry]:
pass
@abstractmethod
def execute_get_photo_entry_api(self, entry_id: str) -> Optional[PhotoEntry]:
pass
@abstractmethod
def execute_register_photo_entry_api(self, image_file_path: str) -> Optional[PhotoEntry]:
pass
@abstractmethod
def execute_update_photo_entry_api(self, image_file_path: str, photo_entry: PhotoEntry) -> Optional[PhotoEntry]:
pass
| true | true |
1c3e221f4953258252911fd3d67bb0c47fea6d65 | 5,420 | py | Python | torchvision/datasets/sbd.py | MeepoAII/vision | 6e10e3f88158f12b7a304d3c2f803d2bbdde0823 | [
"BSD-3-Clause"
] | 2 | 2021-05-06T16:13:00.000Z | 2021-11-17T11:25:12.000Z | torchvision/datasets/sbd.py | MeepoAII/vision | 6e10e3f88158f12b7a304d3c2f803d2bbdde0823 | [
"BSD-3-Clause"
] | 3 | 2021-11-20T09:20:18.000Z | 2021-12-13T09:19:25.000Z | torchvision/datasets/sbd.py | MeepoAII/vision | 6e10e3f88158f12b7a304d3c2f803d2bbdde0823 | [
"BSD-3-Clause"
] | 3 | 2020-12-17T22:32:06.000Z | 2022-03-23T01:43:42.000Z | import os
import shutil
from .vision import VisionDataset
from typing import Any, Callable, Optional, Tuple
import numpy as np
from PIL import Image
from .utils import download_url, verify_str_arg
from .voc import download_extract
class SBDataset(VisionDataset):
"""`Semantic Boundaries Dataset <http://home.bharathh.info/pubs/codes/SBD/download.html>`_
The SBD currently contains annotations from 11355 images taken from the PASCAL VOC 2011 dataset.
.. note ::
Please note that the train and val splits included with this dataset are different from
the splits in the PASCAL VOC dataset. In particular some "train" images might be part of
VOC2012 val.
If you are interested in testing on VOC 2012 val, then use `image_set='train_noval'`,
which excludes all val images.
.. warning::
This class needs `scipy <https://docs.scipy.org/doc/>`_ to load target files from `.mat` format.
Args:
root (string): Root directory of the Semantic Boundaries Dataset
image_set (string, optional): Select the image_set to use, ``train``, ``val`` or ``train_noval``.
Image set ``train_noval`` excludes VOC 2012 val images.
mode (string, optional): Select target type. Possible values 'boundaries' or 'segmentation'.
In case of 'boundaries', the target is an array of shape `[num_classes, H, W]`,
where `num_classes=20`.
download (bool, optional): If true, downloads the dataset from the internet and
puts it in root directory. If dataset is already downloaded, it is not
downloaded again.
transforms (callable, optional): A function/transform that takes input sample and its target as entry
and returns a transformed version. Input sample is PIL image and target is a numpy array
if `mode='boundaries'` or PIL image if `mode='segmentation'`.
"""
url = "http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz"
md5 = "82b4d87ceb2ed10f6038a1cba92111cb"
filename = "benchmark.tgz"
voc_train_url = "http://home.bharathh.info/pubs/codes/SBD/train_noval.txt"
voc_split_filename = "train_noval.txt"
voc_split_md5 = "79bff800c5f0b1ec6b21080a3c066722"
def __init__(
self,
root: str,
image_set: str = "train",
mode: str = "boundaries",
download: bool = False,
transforms: Optional[Callable] = None,
) -> None:
try:
from scipy.io import loadmat
self._loadmat = loadmat
except ImportError:
raise RuntimeError("Scipy is not found. This dataset needs to have scipy installed: "
"pip install scipy")
super(SBDataset, self).__init__(root, transforms)
self.image_set = verify_str_arg(image_set, "image_set",
("train", "val", "train_noval"))
self.mode = verify_str_arg(mode, "mode", ("segmentation", "boundaries"))
self.num_classes = 20
sbd_root = self.root
image_dir = os.path.join(sbd_root, 'img')
mask_dir = os.path.join(sbd_root, 'cls')
if download:
download_extract(self.url, self.root, self.filename, self.md5)
extracted_ds_root = os.path.join(self.root, "benchmark_RELEASE", "dataset")
for f in ["cls", "img", "inst", "train.txt", "val.txt"]:
old_path = os.path.join(extracted_ds_root, f)
shutil.move(old_path, sbd_root)
download_url(self.voc_train_url, sbd_root, self.voc_split_filename,
self.voc_split_md5)
if not os.path.isdir(sbd_root):
raise RuntimeError('Dataset not found or corrupted.' +
' You can use download=True to download it')
split_f = os.path.join(sbd_root, image_set.rstrip('\n') + '.txt')
with open(os.path.join(split_f), "r") as fh:
file_names = [x.strip() for x in fh.readlines()]
self.images = [os.path.join(image_dir, x + ".jpg") for x in file_names]
self.masks = [os.path.join(mask_dir, x + ".mat") for x in file_names]
assert (len(self.images) == len(self.masks))
self._get_target = self._get_segmentation_target \
if self.mode == "segmentation" else self._get_boundaries_target
def _get_segmentation_target(self, filepath: str) -> Image.Image:
mat = self._loadmat(filepath)
return Image.fromarray(mat['GTcls'][0]['Segmentation'][0])
def _get_boundaries_target(self, filepath: str) -> np.ndarray:
mat = self._loadmat(filepath)
return np.concatenate([np.expand_dims(mat['GTcls'][0]['Boundaries'][0][i][0].toarray(), axis=0)
for i in range(self.num_classes)], axis=0)
def __getitem__(self, index: int) -> Tuple[Any, Any]:
img = Image.open(self.images[index]).convert('RGB')
target = self._get_target(self.masks[index])
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self) -> int:
return len(self.images)
def extra_repr(self) -> str:
lines = ["Image set: {image_set}", "Mode: {mode}"]
return '\n'.join(lines).format(**self.__dict__)
| 42.34375 | 109 | 0.631365 | import os
import shutil
from .vision import VisionDataset
from typing import Any, Callable, Optional, Tuple
import numpy as np
from PIL import Image
from .utils import download_url, verify_str_arg
from .voc import download_extract
class SBDataset(VisionDataset):
url = "http://www.eecs.berkeley.edu/Research/Projects/CS/vision/grouping/semantic_contours/benchmark.tgz"
md5 = "82b4d87ceb2ed10f6038a1cba92111cb"
filename = "benchmark.tgz"
voc_train_url = "http://home.bharathh.info/pubs/codes/SBD/train_noval.txt"
voc_split_filename = "train_noval.txt"
voc_split_md5 = "79bff800c5f0b1ec6b21080a3c066722"
def __init__(
self,
root: str,
image_set: str = "train",
mode: str = "boundaries",
download: bool = False,
transforms: Optional[Callable] = None,
) -> None:
try:
from scipy.io import loadmat
self._loadmat = loadmat
except ImportError:
raise RuntimeError("Scipy is not found. This dataset needs to have scipy installed: "
"pip install scipy")
super(SBDataset, self).__init__(root, transforms)
self.image_set = verify_str_arg(image_set, "image_set",
("train", "val", "train_noval"))
self.mode = verify_str_arg(mode, "mode", ("segmentation", "boundaries"))
self.num_classes = 20
sbd_root = self.root
image_dir = os.path.join(sbd_root, 'img')
mask_dir = os.path.join(sbd_root, 'cls')
if download:
download_extract(self.url, self.root, self.filename, self.md5)
extracted_ds_root = os.path.join(self.root, "benchmark_RELEASE", "dataset")
for f in ["cls", "img", "inst", "train.txt", "val.txt"]:
old_path = os.path.join(extracted_ds_root, f)
shutil.move(old_path, sbd_root)
download_url(self.voc_train_url, sbd_root, self.voc_split_filename,
self.voc_split_md5)
if not os.path.isdir(sbd_root):
raise RuntimeError('Dataset not found or corrupted.' +
' You can use download=True to download it')
split_f = os.path.join(sbd_root, image_set.rstrip('\n') + '.txt')
with open(os.path.join(split_f), "r") as fh:
file_names = [x.strip() for x in fh.readlines()]
self.images = [os.path.join(image_dir, x + ".jpg") for x in file_names]
self.masks = [os.path.join(mask_dir, x + ".mat") for x in file_names]
assert (len(self.images) == len(self.masks))
self._get_target = self._get_segmentation_target \
if self.mode == "segmentation" else self._get_boundaries_target
def _get_segmentation_target(self, filepath: str) -> Image.Image:
mat = self._loadmat(filepath)
return Image.fromarray(mat['GTcls'][0]['Segmentation'][0])
def _get_boundaries_target(self, filepath: str) -> np.ndarray:
mat = self._loadmat(filepath)
return np.concatenate([np.expand_dims(mat['GTcls'][0]['Boundaries'][0][i][0].toarray(), axis=0)
for i in range(self.num_classes)], axis=0)
def __getitem__(self, index: int) -> Tuple[Any, Any]:
img = Image.open(self.images[index]).convert('RGB')
target = self._get_target(self.masks[index])
if self.transforms is not None:
img, target = self.transforms(img, target)
return img, target
def __len__(self) -> int:
return len(self.images)
def extra_repr(self) -> str:
lines = ["Image set: {image_set}", "Mode: {mode}"]
return '\n'.join(lines).format(**self.__dict__)
| true | true |
1c3e22847b16126dac089d6b163792fd9ed564a1 | 1,008 | py | Python | src/ralph/deployment/management/commands/nexthostname.py | quamilek/ralph | bf7231ea096924332b874718b33cd1f43f9c783b | [
"Apache-2.0"
] | null | null | null | src/ralph/deployment/management/commands/nexthostname.py | quamilek/ralph | bf7231ea096924332b874718b33cd1f43f9c783b | [
"Apache-2.0"
] | null | null | null | src/ralph/deployment/management/commands/nexthostname.py | quamilek/ralph | bf7231ea096924332b874718b33cd1f43f9c783b | [
"Apache-2.0"
] | null | null | null | #!/usr/bin/env python
# -*- coding: utf-8 -*-
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.core.management.base import BaseCommand, CommandError
from ralph.deployment.util import get_next_free_hostname
from ralph.discovery.models import DataCenter
class Command(BaseCommand):
args = '<dc name>'
help = 'Return next host name for specified data center.'
def handle(self, dc_name=None, *args, **options):
if not dc_name:
raise CommandError('Please specify the DC name.')
try:
dc = DataCenter.objects.get(name=dc_name)
except DataCenter.DoesNotExist:
raise CommandError("Specified data center doesn't exists.")
hostname = get_next_free_hostname(dc)
if not hostname:
raise CommandError("Couldn't determine the next host name.")
self.stdout.write("Next host name: %s\n" % hostname)
| 32.516129 | 72 | 0.705357 |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
from django.core.management.base import BaseCommand, CommandError
from ralph.deployment.util import get_next_free_hostname
from ralph.discovery.models import DataCenter
class Command(BaseCommand):
args = '<dc name>'
help = 'Return next host name for specified data center.'
def handle(self, dc_name=None, *args, **options):
if not dc_name:
raise CommandError('Please specify the DC name.')
try:
dc = DataCenter.objects.get(name=dc_name)
except DataCenter.DoesNotExist:
raise CommandError("Specified data center doesn't exists.")
hostname = get_next_free_hostname(dc)
if not hostname:
raise CommandError("Couldn't determine the next host name.")
self.stdout.write("Next host name: %s\n" % hostname)
| true | true |
1c3e2365392a03bd6d8df514d57874b8d06fce21 | 6,090 | py | Python | packages/core/minos-microservice-common/tests/test_common/test_model/test_serializers/test_avro/test_schema/test_decoder.py | sorasful/minos-python | 1189330eebf6444627a2af6b29f347670f95a4dd | [
"MIT"
] | 247 | 2022-01-24T14:55:30.000Z | 2022-03-25T12:06:17.000Z | packages/core/minos-microservice-common/tests/test_common/test_model/test_serializers/test_avro/test_schema/test_decoder.py | sorasful/minos-python | 1189330eebf6444627a2af6b29f347670f95a4dd | [
"MIT"
] | 400 | 2021-04-03T08:51:40.000Z | 2022-01-28T11:51:22.000Z | packages/core/minos-microservice-common/tests/test_common/test_model/test_serializers/test_avro/test_schema/test_decoder.py | sorasful/minos-python | 1189330eebf6444627a2af6b29f347670f95a4dd | [
"MIT"
] | 21 | 2022-02-06T17:25:58.000Z | 2022-03-27T04:50:29.000Z | import unittest
from datetime import (
date,
datetime,
time,
timedelta,
)
from typing import (
Any,
Union,
)
from unittest.mock import (
patch,
)
from uuid import (
UUID,
)
from minos.common import (
AvroSchemaDecoder,
MinosMalformedAttributeException,
ModelType,
classname,
)
from tests.model_classes import (
ShoppingList,
Status,
)
class TestAvroSchemaDecoder(unittest.TestCase):
def test_model_type(self):
expected = ModelType.build("User", {"username": str}, namespace_="path.to")
field_schema = {
"fields": [{"name": "username", "type": "string"}],
"name": "User",
"namespace": "path.to.class",
"type": "record",
}
observed = AvroSchemaDecoder(field_schema).build()
self.assertEqual(expected, observed)
def test_model_type_single_module(self):
expected = ModelType.build("User", {"username": str}, namespace_="example")
field_schema = {
"fields": [{"name": "username", "type": "string"}],
"name": "User",
"namespace": "example",
"type": "record",
}
observed = AvroSchemaDecoder(field_schema).build()
self.assertEqual(expected, observed)
def test_int(self):
expected = int
observed = AvroSchemaDecoder({"name": "id", "type": "int"}).build()
self.assertEqual(expected, observed)
def test_bool(self):
expected = bool
observed = AvroSchemaDecoder({"name": "id", "type": "boolean"}).build()
self.assertEqual(expected, observed)
def test_float(self):
expected = float
observed = AvroSchemaDecoder({"name": "id", "type": "float"}).build()
self.assertEqual(expected, observed)
def test_double(self):
expected = float
observed = AvroSchemaDecoder({"name": "id", "type": "double"}).build()
self.assertEqual(expected, observed)
def test_bytes(self):
expected = bytes
observed = AvroSchemaDecoder({"name": "id", "type": "bytes"}).build()
self.assertEqual(expected, observed)
def test_date(self):
expected = date
observed = AvroSchemaDecoder({"name": "id", "type": "int", "logicalType": "date"}).build()
self.assertEqual(expected, observed)
def test_time(self):
expected = time
observed = AvroSchemaDecoder({"name": "id", "type": "int", "logicalType": "time-micros"}).build()
self.assertEqual(expected, observed)
def test_datetime(self):
expected = datetime
observed = AvroSchemaDecoder({"name": "id", "type": "long", "logicalType": "timestamp-micros"}).build()
self.assertEqual(expected, observed)
def test_timedelta(self):
expected = timedelta
observed = AvroSchemaDecoder({"name": "id", "type": "long", "logicalType": "timedelta-micros"}).build()
self.assertEqual(expected, observed)
def test_uuid(self):
expected = UUID
observed = AvroSchemaDecoder({"name": "id", "type": "string", "logicalType": "uuid"}).build()
self.assertEqual(expected, observed)
def test_list(self):
expected = list[str]
observed = AvroSchemaDecoder({"name": "example", "type": "array", "items": "string"}).build()
self.assertEqual(expected, observed)
def test_list_any(self):
expected = list[Any]
observed = AvroSchemaDecoder({"name": "example", "type": "array", "items": "null"}).build()
self.assertEqual(expected, observed)
def test_set(self):
expected = set[str]
schema = {"name": "example", "type": "array", "items": "string", "logicalType": "set"}
observed = AvroSchemaDecoder(schema).build()
self.assertEqual(expected, observed)
def test_set_any(self):
expected = set[Any]
schema = {"name": "example", "type": "array", "items": "null", "logicalType": "set"}
observed = AvroSchemaDecoder(schema).build()
self.assertEqual(expected, observed)
def test_dict(self):
expected = dict[str, int]
observed = AvroSchemaDecoder({"name": "example", "type": "map", "values": "int"}).build()
self.assertEqual(expected, observed)
def test_dict_any(self):
expected = dict[str, Any]
observed = AvroSchemaDecoder({"name": "example", "type": "map", "values": "null"}).build()
self.assertEqual(expected, observed)
def test_nested_arrays(self):
expected = list[list[str]]
observed = AvroSchemaDecoder(
{"name": "example", "type": "array", "items": {"type": {"type": "array", "items": "string"}}},
).build()
self.assertEqual(expected, observed)
def test_none(self):
expected = type(None)
observed = AvroSchemaDecoder({"name": "example", "type": "null"}).build()
self.assertEqual(expected, observed)
def test_union(self):
expected = list[Union[int, str]]
observed = AvroSchemaDecoder({"name": "example", "type": "array", "items": ["int", "string"]}).build()
self.assertEqual(expected, observed)
def test_raises(self):
with self.assertRaises(MinosMalformedAttributeException):
AvroSchemaDecoder({"name": "id", "type": "foo"}).build()
def test_logical_type(self):
expected = Status
observed = AvroSchemaDecoder({"type": "string", "logicalType": classname(Status)}).build()
self.assertEqual(expected, observed)
def test_logical_type_unknown(self):
expected = str
observed = AvroSchemaDecoder({"name": "id", "type": "string", "logicalType": "foo"}).build()
self.assertEqual(expected, observed)
def test_logical_type_model(self):
with patch.object(ShoppingList, "decode_schema", return_value=ShoppingList):
observed = AvroSchemaDecoder({"type": "string", "logicalType": classname(ShoppingList)}).build()
self.assertEqual(ShoppingList, observed)
if __name__ == "__main__":
unittest.main()
| 34.40678 | 111 | 0.611823 | import unittest
from datetime import (
date,
datetime,
time,
timedelta,
)
from typing import (
Any,
Union,
)
from unittest.mock import (
patch,
)
from uuid import (
UUID,
)
from minos.common import (
AvroSchemaDecoder,
MinosMalformedAttributeException,
ModelType,
classname,
)
from tests.model_classes import (
ShoppingList,
Status,
)
class TestAvroSchemaDecoder(unittest.TestCase):
def test_model_type(self):
expected = ModelType.build("User", {"username": str}, namespace_="path.to")
field_schema = {
"fields": [{"name": "username", "type": "string"}],
"name": "User",
"namespace": "path.to.class",
"type": "record",
}
observed = AvroSchemaDecoder(field_schema).build()
self.assertEqual(expected, observed)
def test_model_type_single_module(self):
expected = ModelType.build("User", {"username": str}, namespace_="example")
field_schema = {
"fields": [{"name": "username", "type": "string"}],
"name": "User",
"namespace": "example",
"type": "record",
}
observed = AvroSchemaDecoder(field_schema).build()
self.assertEqual(expected, observed)
def test_int(self):
expected = int
observed = AvroSchemaDecoder({"name": "id", "type": "int"}).build()
self.assertEqual(expected, observed)
def test_bool(self):
expected = bool
observed = AvroSchemaDecoder({"name": "id", "type": "boolean"}).build()
self.assertEqual(expected, observed)
def test_float(self):
expected = float
observed = AvroSchemaDecoder({"name": "id", "type": "float"}).build()
self.assertEqual(expected, observed)
def test_double(self):
expected = float
observed = AvroSchemaDecoder({"name": "id", "type": "double"}).build()
self.assertEqual(expected, observed)
def test_bytes(self):
expected = bytes
observed = AvroSchemaDecoder({"name": "id", "type": "bytes"}).build()
self.assertEqual(expected, observed)
def test_date(self):
expected = date
observed = AvroSchemaDecoder({"name": "id", "type": "int", "logicalType": "date"}).build()
self.assertEqual(expected, observed)
def test_time(self):
expected = time
observed = AvroSchemaDecoder({"name": "id", "type": "int", "logicalType": "time-micros"}).build()
self.assertEqual(expected, observed)
def test_datetime(self):
expected = datetime
observed = AvroSchemaDecoder({"name": "id", "type": "long", "logicalType": "timestamp-micros"}).build()
self.assertEqual(expected, observed)
def test_timedelta(self):
expected = timedelta
observed = AvroSchemaDecoder({"name": "id", "type": "long", "logicalType": "timedelta-micros"}).build()
self.assertEqual(expected, observed)
def test_uuid(self):
expected = UUID
observed = AvroSchemaDecoder({"name": "id", "type": "string", "logicalType": "uuid"}).build()
self.assertEqual(expected, observed)
def test_list(self):
expected = list[str]
observed = AvroSchemaDecoder({"name": "example", "type": "array", "items": "string"}).build()
self.assertEqual(expected, observed)
def test_list_any(self):
expected = list[Any]
observed = AvroSchemaDecoder({"name": "example", "type": "array", "items": "null"}).build()
self.assertEqual(expected, observed)
def test_set(self):
expected = set[str]
schema = {"name": "example", "type": "array", "items": "string", "logicalType": "set"}
observed = AvroSchemaDecoder(schema).build()
self.assertEqual(expected, observed)
def test_set_any(self):
expected = set[Any]
schema = {"name": "example", "type": "array", "items": "null", "logicalType": "set"}
observed = AvroSchemaDecoder(schema).build()
self.assertEqual(expected, observed)
def test_dict(self):
expected = dict[str, int]
observed = AvroSchemaDecoder({"name": "example", "type": "map", "values": "int"}).build()
self.assertEqual(expected, observed)
def test_dict_any(self):
expected = dict[str, Any]
observed = AvroSchemaDecoder({"name": "example", "type": "map", "values": "null"}).build()
self.assertEqual(expected, observed)
def test_nested_arrays(self):
expected = list[list[str]]
observed = AvroSchemaDecoder(
{"name": "example", "type": "array", "items": {"type": {"type": "array", "items": "string"}}},
).build()
self.assertEqual(expected, observed)
def test_none(self):
expected = type(None)
observed = AvroSchemaDecoder({"name": "example", "type": "null"}).build()
self.assertEqual(expected, observed)
def test_union(self):
expected = list[Union[int, str]]
observed = AvroSchemaDecoder({"name": "example", "type": "array", "items": ["int", "string"]}).build()
self.assertEqual(expected, observed)
def test_raises(self):
with self.assertRaises(MinosMalformedAttributeException):
AvroSchemaDecoder({"name": "id", "type": "foo"}).build()
def test_logical_type(self):
expected = Status
observed = AvroSchemaDecoder({"type": "string", "logicalType": classname(Status)}).build()
self.assertEqual(expected, observed)
def test_logical_type_unknown(self):
expected = str
observed = AvroSchemaDecoder({"name": "id", "type": "string", "logicalType": "foo"}).build()
self.assertEqual(expected, observed)
def test_logical_type_model(self):
with patch.object(ShoppingList, "decode_schema", return_value=ShoppingList):
observed = AvroSchemaDecoder({"type": "string", "logicalType": classname(ShoppingList)}).build()
self.assertEqual(ShoppingList, observed)
if __name__ == "__main__":
unittest.main()
| true | true |
1c3e236cbc8726fe2c849a5d7ff474a88063800c | 14,070 | py | Python | models.py | AliengirlLiv/dreamer-pytorch-1 | 33979d7c61d0406d27ea46b9dcbbd823f765a518 | [
"MIT"
] | null | null | null | models.py | AliengirlLiv/dreamer-pytorch-1 | 33979d7c61d0406d27ea46b9dcbbd823f765a518 | [
"MIT"
] | null | null | null | models.py | AliengirlLiv/dreamer-pytorch-1 | 33979d7c61d0406d27ea46b9dcbbd823f765a518 | [
"MIT"
] | null | null | null | from typing import Optional, List
import torch
from torch import jit, nn
from torch.nn import functional as F
import torch.distributions
from torch.distributions.normal import Normal
from torch.distributions.transforms import Transform, TanhTransform
from torch.distributions.transformed_distribution import TransformedDistribution
import numpy as np
# Wraps the input tuple for a function to process a time x batch x features sequence in batch x features (assumes one output)
def bottle(f, x_tuple):
x_sizes = tuple(map(lambda x: x.size(), x_tuple))
y = f(*map(lambda x: x[0].view(x[1][0] * x[1][1], *x[1][2:]), zip(x_tuple, x_sizes)))
y_size = y.size()
output = y.view(x_sizes[0][0], x_sizes[0][1], *y_size[1:])
return output
class TransitionModel(jit.ScriptModule):
__constants__ = ['min_std_dev']
def __init__(self, belief_size, state_size, action_size, hidden_size, embedding_size, activation_function='relu', min_std_dev=0.1):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.min_std_dev = min_std_dev
self.fc_embed_state_action = nn.Linear(state_size + action_size, belief_size)
self.rnn = nn.GRUCell(belief_size, belief_size)
self.fc_embed_belief_prior = nn.Linear(belief_size, hidden_size)
self.fc_state_prior = nn.Linear(hidden_size, 2 * state_size)
self.fc_embed_belief_posterior = nn.Linear(belief_size + embedding_size, hidden_size)
self.fc_state_posterior = nn.Linear(hidden_size, 2 * state_size)
self.modules = [self.fc_embed_state_action, self.fc_embed_belief_prior, self.fc_state_prior, self.fc_embed_belief_posterior, self.fc_state_posterior]
# Operates over (previous) state, (previous) actions, (previous) belief, (previous) nonterminals (mask), and (current) observations
# Diagram of expected inputs and outputs for T = 5 (-x- signifying beginning of output belief/state that gets sliced off):
# t : 0 1 2 3 4 5
# o : -X--X--X--X--X-
# a : -X--X--X--X--X-
# n : -X--X--X--X--X-
# pb: -X-
# ps: -X-
# b : -x--X--X--X--X--X-
# s : -x--X--X--X--X--X-
@jit.script_method
def forward(self, prev_state:torch.Tensor, actions:torch.Tensor, prev_belief:torch.Tensor, observations:Optional[torch.Tensor]=None, nonterminals:Optional[torch.Tensor]=None) -> List[torch.Tensor]:
'''
Input: init_belief, init_state: torch.Size([50, 200]) torch.Size([50, 30])
Output: beliefs, prior_states, prior_means, prior_std_devs, posterior_states, posterior_means, posterior_std_devs
torch.Size([49, 50, 200]) torch.Size([49, 50, 30]) torch.Size([49, 50, 30]) torch.Size([49, 50, 30]) torch.Size([49, 50, 30]) torch.Size([49, 50, 30]) torch.Size([49, 50, 30])
'''
# Create lists for hidden states (cannot use single tensor as buffer because autograd won't work with inplace writes)
T = actions.size(0) + 1
beliefs, prior_states, prior_means, prior_std_devs, posterior_states, posterior_means, posterior_std_devs = [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T
beliefs[0], prior_states[0], posterior_states[0] = prev_belief, prev_state, prev_state
# Loop over time sequence
for t in range(T - 1):
_state = prior_states[t] if observations is None else posterior_states[t] # Select appropriate previous state
_state = _state if nonterminals is None else _state * nonterminals[t] # Mask if previous transition was terminal
# Compute belief (deterministic hidden state)
hidden = self.act_fn(self.fc_embed_state_action(torch.cat([_state, actions[t]], dim=1)))
beliefs[t + 1] = self.rnn(hidden, beliefs[t])
# Compute state prior by applying transition dynamics
hidden = self.act_fn(self.fc_embed_belief_prior(beliefs[t + 1]))
prior_means[t + 1], _prior_std_dev = torch.chunk(self.fc_state_prior(hidden), 2, dim=1)
prior_std_devs[t + 1] = F.softplus(_prior_std_dev) + self.min_std_dev
prior_states[t + 1] = prior_means[t + 1] + prior_std_devs[t + 1] * torch.randn_like(prior_means[t + 1])
if observations is not None:
# Compute state posterior by applying transition dynamics and using current observation
t_ = t - 1 # Use t_ to deal with different time indexing for observations
hidden = self.act_fn(self.fc_embed_belief_posterior(torch.cat([beliefs[t + 1], observations[t_ + 1]], dim=1)))
posterior_means[t + 1], _posterior_std_dev = torch.chunk(self.fc_state_posterior(hidden), 2, dim=1)
posterior_std_devs[t + 1] = F.softplus(_posterior_std_dev) + self.min_std_dev
posterior_states[t + 1] = posterior_means[t + 1] + posterior_std_devs[t + 1] * torch.randn_like(posterior_means[t + 1])
# Return new hidden states
hidden = [torch.stack(beliefs[1:], dim=0), torch.stack(prior_states[1:], dim=0), torch.stack(prior_means[1:], dim=0), torch.stack(prior_std_devs[1:], dim=0)]
if observations is not None:
hidden += [torch.stack(posterior_states[1:], dim=0), torch.stack(posterior_means[1:], dim=0), torch.stack(posterior_std_devs[1:], dim=0)]
return hidden
class SymbolicObservationModel(jit.ScriptModule):
def __init__(self, observation_size, belief_size, state_size, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, embedding_size)
self.fc2 = nn.Linear(embedding_size, embedding_size)
self.fc3 = nn.Linear(embedding_size, observation_size)
self.modules = [self.fc1, self.fc2, self.fc3]
@jit.script_method
def forward(self, belief, state):
hidden = self.act_fn(self.fc1(torch.cat([belief, state], dim=1)))
hidden = self.act_fn(self.fc2(hidden))
observation = self.fc3(hidden)
return observation
class VisualObservationModel(jit.ScriptModule):
__constants__ = ['embedding_size']
def __init__(self, belief_size, state_size, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.embedding_size = embedding_size
self.fc1 = nn.Linear(belief_size + state_size, embedding_size)
self.conv1 = nn.ConvTranspose2d(embedding_size, 128, 5, stride=2)
self.conv2 = nn.ConvTranspose2d(128, 64, 5, stride=2)
self.conv3 = nn.ConvTranspose2d(64, 32, 6, stride=2)
self.conv4 = nn.ConvTranspose2d(32, 3, 6, stride=2)
self.modules = [self.fc1, self.conv1, self.conv2, self.conv3, self.conv4]
@jit.script_method
def forward(self, belief, state):
hidden = self.fc1(torch.cat([belief, state], dim=1)) # No nonlinearity here
hidden = hidden.view(-1, self.embedding_size, 1, 1)
hidden = self.act_fn(self.conv1(hidden))
hidden = self.act_fn(self.conv2(hidden))
hidden = self.act_fn(self.conv3(hidden))
observation = self.conv4(hidden)
return observation
def ObservationModel(symbolic, observation_size, belief_size, state_size, embedding_size, activation_function='relu'):
if symbolic:
return SymbolicObservationModel(observation_size, belief_size, state_size, embedding_size, activation_function)
else:
return VisualObservationModel(belief_size, state_size, embedding_size, activation_function)
class RewardModel(jit.ScriptModule):
def __init__(self, belief_size, state_size, hidden_size, activation_function='relu'):
# [--belief-size: 200, --hidden-size: 200, --state-size: 30]
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, 1)
self.modules = [self.fc1, self.fc2, self.fc3]
@jit.script_method
def forward(self, belief, state):
x = torch.cat([belief, state],dim=1)
hidden = self.act_fn(self.fc1(x))
hidden = self.act_fn(self.fc2(hidden))
reward = self.fc3(hidden).squeeze(dim=1)
return reward
class ValueModel(jit.ScriptModule):
def __init__(self, belief_size, state_size, hidden_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, hidden_size)
self.fc4 = nn.Linear(hidden_size, 1)
self.modules = [self.fc1, self.fc2, self.fc3, self.fc4]
@jit.script_method
def forward(self, belief, state):
x = torch.cat([belief, state],dim=1)
hidden = self.act_fn(self.fc1(x))
hidden = self.act_fn(self.fc2(hidden))
hidden = self.act_fn(self.fc3(hidden))
reward = self.fc4(hidden).squeeze(dim=1)
return reward
class ActorModel(jit.ScriptModule):
def __init__(self, belief_size, state_size, hidden_size, action_size, dist='tanh_normal',
activation_function='elu', min_std=1e-4, init_std=5, mean_scale=5):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, hidden_size)
self.fc4 = nn.Linear(hidden_size, hidden_size)
self.fc5 = nn.Linear(hidden_size, 2*action_size)
self.modules = [self.fc1, self.fc2, self.fc3, self.fc4, self.fc5]
self._dist = dist
self._min_std = min_std
self._init_std = init_std
self._mean_scale = mean_scale
@jit.script_method
def forward(self, belief, state):
raw_init_std = torch.log(torch.exp(self._init_std) - 1)
x = torch.cat([belief, state],dim=1)
hidden = self.act_fn(self.fc1(x))
hidden = self.act_fn(self.fc2(hidden))
hidden = self.act_fn(self.fc3(hidden))
hidden = self.act_fn(self.fc4(hidden))
action = self.fc5(hidden).squeeze(dim=1)
action_mean, action_std_dev = torch.chunk(action, 2, dim=1)
action_mean = self._mean_scale * torch.tanh(action_mean / self._mean_scale)
action_std = F.softplus(action_std_dev + raw_init_std) + self._min_std
return action_mean, action_std
def get_action(self, belief, state, det=False):
action_mean, action_std = self.forward(belief, state)
dist = Normal(action_mean, action_std)
dist = TransformedDistribution(dist, TanhBijector())
dist = torch.distributions.Independent(dist,1)
dist = SampleDist(dist)
if det: return dist.mode()
else: return dist.rsample()
class SymbolicEncoder(jit.ScriptModule):
def __init__(self, observation_size, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(observation_size, embedding_size)
self.fc2 = nn.Linear(embedding_size, embedding_size)
self.fc3 = nn.Linear(embedding_size, embedding_size)
self.modules = [self.fc1, self.fc2, self.fc3]
@jit.script_method
def forward(self, observation):
hidden = self.act_fn(self.fc1(observation))
hidden = self.act_fn(self.fc2(hidden))
hidden = self.fc3(hidden)
return hidden
class VisualEncoder(jit.ScriptModule):
__constants__ = ['embedding_size']
def __init__(self, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.embedding_size = embedding_size
self.conv1 = nn.Conv2d(3, 32, 4, stride=2)
self.conv2 = nn.Conv2d(32, 64, 4, stride=2)
self.conv3 = nn.Conv2d(64, 128, 4, stride=2)
self.conv4 = nn.Conv2d(128, 256, 4, stride=2)
self.fc = nn.Identity() if embedding_size == 1024 else nn.Linear(1024, embedding_size)
self.modules = [self.conv1, self.conv2, self.conv3, self.conv4]
@jit.script_method
def forward(self, observation, state):
hidden = self.act_fn(self.conv1(observation))
hidden = self.act_fn(self.conv2(hidden))
hidden = self.act_fn(self.conv3(hidden))
hidden = self.act_fn(self.conv4(hidden))
hidden = hidden.view(-1, 1024)
hidden = self.fc(hidden) # Identity if embedding size is 1024 else linear projection
hidden = torch.cat([hidden, state.float()], dim=-1)
return hidden
def Encoder(symbolic, observation_size, embedding_size, state_concat_size=0, activation_function='relu'):
if symbolic:
return SymbolicEncoder(observation_size, embedding_size, state_concat_size)
else:
return VisualEncoder(embedding_size, state_concat_size)
# "atanh", "TanhBijector" and "SampleDist" are from the following repo
# https://github.com/juliusfrost/dreamer-pytorch
def atanh(x):
return 0.5 * torch.log((1 + x) / (1 - x))
class TanhBijector(torch.distributions.Transform):
def __init__(self):
super().__init__()
self.bijective = True
@property
def sign(self): return 1.
def _call(self, x): return torch.tanh(x)
def _inverse(self, y: torch.Tensor):
y = torch.where(
(torch.abs(y) <= 1.),
torch.clamp(y, -0.99999997, 0.99999997),
y)
y = atanh(y)
return y
def log_abs_det_jacobian(self, x, y):
return 2. * (np.log(2) - x - F.softplus(-2. * x))
class SampleDist:
def __init__(self, dist, samples=100):
self._dist = dist
self._samples = samples
@property
def name(self):
return 'SampleDist'
def __getattr__(self, name):
return getattr(self._dist, name)
def mean(self):
sample = dist.rsample()
return torch.mean(sample, 0)
def mode(self):
dist = self._dist.expand((self._samples, *self._dist.batch_shape))
sample = dist.rsample()
logprob = dist.log_prob(sample)
batch_size = sample.size(1)
feature_size = sample.size(2)
indices = torch.argmax(logprob, dim=0).reshape(1, batch_size, 1).expand(1, batch_size, feature_size)
return torch.gather(sample, 0, indices).squeeze(0)
def entropy(self):
dist = self._dist.expand((self._samples, *self._dist.batch_shape))
sample = dist.rsample()
logprob = dist.log_prob(sample)
return -torch.mean(logprob, 0)
def sample(self):
return self._dist.sample()
| 43.831776 | 264 | 0.703625 | from typing import Optional, List
import torch
from torch import jit, nn
from torch.nn import functional as F
import torch.distributions
from torch.distributions.normal import Normal
from torch.distributions.transforms import Transform, TanhTransform
from torch.distributions.transformed_distribution import TransformedDistribution
import numpy as np
def bottle(f, x_tuple):
x_sizes = tuple(map(lambda x: x.size(), x_tuple))
y = f(*map(lambda x: x[0].view(x[1][0] * x[1][1], *x[1][2:]), zip(x_tuple, x_sizes)))
y_size = y.size()
output = y.view(x_sizes[0][0], x_sizes[0][1], *y_size[1:])
return output
class TransitionModel(jit.ScriptModule):
__constants__ = ['min_std_dev']
def __init__(self, belief_size, state_size, action_size, hidden_size, embedding_size, activation_function='relu', min_std_dev=0.1):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.min_std_dev = min_std_dev
self.fc_embed_state_action = nn.Linear(state_size + action_size, belief_size)
self.rnn = nn.GRUCell(belief_size, belief_size)
self.fc_embed_belief_prior = nn.Linear(belief_size, hidden_size)
self.fc_state_prior = nn.Linear(hidden_size, 2 * state_size)
self.fc_embed_belief_posterior = nn.Linear(belief_size + embedding_size, hidden_size)
self.fc_state_posterior = nn.Linear(hidden_size, 2 * state_size)
self.modules = [self.fc_embed_state_action, self.fc_embed_belief_prior, self.fc_state_prior, self.fc_embed_belief_posterior, self.fc_state_posterior]
@jit.script_method
def forward(self, prev_state:torch.Tensor, actions:torch.Tensor, prev_belief:torch.Tensor, observations:Optional[torch.Tensor]=None, nonterminals:Optional[torch.Tensor]=None) -> List[torch.Tensor]:
T = actions.size(0) + 1
beliefs, prior_states, prior_means, prior_std_devs, posterior_states, posterior_means, posterior_std_devs = [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T, [torch.empty(0)] * T
beliefs[0], prior_states[0], posterior_states[0] = prev_belief, prev_state, prev_state
# Loop over time sequence
for t in range(T - 1):
_state = prior_states[t] if observations is None else posterior_states[t] # Select appropriate previous state
_state = _state if nonterminals is None else _state * nonterminals[t] # Mask if previous transition was terminal
# Compute belief (deterministic hidden state)
hidden = self.act_fn(self.fc_embed_state_action(torch.cat([_state, actions[t]], dim=1)))
beliefs[t + 1] = self.rnn(hidden, beliefs[t])
# Compute state prior by applying transition dynamics
hidden = self.act_fn(self.fc_embed_belief_prior(beliefs[t + 1]))
prior_means[t + 1], _prior_std_dev = torch.chunk(self.fc_state_prior(hidden), 2, dim=1)
prior_std_devs[t + 1] = F.softplus(_prior_std_dev) + self.min_std_dev
prior_states[t + 1] = prior_means[t + 1] + prior_std_devs[t + 1] * torch.randn_like(prior_means[t + 1])
if observations is not None:
# Compute state posterior by applying transition dynamics and using current observation
t_ = t - 1 # Use t_ to deal with different time indexing for observations
hidden = self.act_fn(self.fc_embed_belief_posterior(torch.cat([beliefs[t + 1], observations[t_ + 1]], dim=1)))
posterior_means[t + 1], _posterior_std_dev = torch.chunk(self.fc_state_posterior(hidden), 2, dim=1)
posterior_std_devs[t + 1] = F.softplus(_posterior_std_dev) + self.min_std_dev
posterior_states[t + 1] = posterior_means[t + 1] + posterior_std_devs[t + 1] * torch.randn_like(posterior_means[t + 1])
# Return new hidden states
hidden = [torch.stack(beliefs[1:], dim=0), torch.stack(prior_states[1:], dim=0), torch.stack(prior_means[1:], dim=0), torch.stack(prior_std_devs[1:], dim=0)]
if observations is not None:
hidden += [torch.stack(posterior_states[1:], dim=0), torch.stack(posterior_means[1:], dim=0), torch.stack(posterior_std_devs[1:], dim=0)]
return hidden
class SymbolicObservationModel(jit.ScriptModule):
def __init__(self, observation_size, belief_size, state_size, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, embedding_size)
self.fc2 = nn.Linear(embedding_size, embedding_size)
self.fc3 = nn.Linear(embedding_size, observation_size)
self.modules = [self.fc1, self.fc2, self.fc3]
@jit.script_method
def forward(self, belief, state):
hidden = self.act_fn(self.fc1(torch.cat([belief, state], dim=1)))
hidden = self.act_fn(self.fc2(hidden))
observation = self.fc3(hidden)
return observation
class VisualObservationModel(jit.ScriptModule):
__constants__ = ['embedding_size']
def __init__(self, belief_size, state_size, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.embedding_size = embedding_size
self.fc1 = nn.Linear(belief_size + state_size, embedding_size)
self.conv1 = nn.ConvTranspose2d(embedding_size, 128, 5, stride=2)
self.conv2 = nn.ConvTranspose2d(128, 64, 5, stride=2)
self.conv3 = nn.ConvTranspose2d(64, 32, 6, stride=2)
self.conv4 = nn.ConvTranspose2d(32, 3, 6, stride=2)
self.modules = [self.fc1, self.conv1, self.conv2, self.conv3, self.conv4]
@jit.script_method
def forward(self, belief, state):
hidden = self.fc1(torch.cat([belief, state], dim=1)) # No nonlinearity here
hidden = hidden.view(-1, self.embedding_size, 1, 1)
hidden = self.act_fn(self.conv1(hidden))
hidden = self.act_fn(self.conv2(hidden))
hidden = self.act_fn(self.conv3(hidden))
observation = self.conv4(hidden)
return observation
def ObservationModel(symbolic, observation_size, belief_size, state_size, embedding_size, activation_function='relu'):
if symbolic:
return SymbolicObservationModel(observation_size, belief_size, state_size, embedding_size, activation_function)
else:
return VisualObservationModel(belief_size, state_size, embedding_size, activation_function)
class RewardModel(jit.ScriptModule):
def __init__(self, belief_size, state_size, hidden_size, activation_function='relu'):
# [--belief-size: 200, --hidden-size: 200, --state-size: 30]
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, 1)
self.modules = [self.fc1, self.fc2, self.fc3]
@jit.script_method
def forward(self, belief, state):
x = torch.cat([belief, state],dim=1)
hidden = self.act_fn(self.fc1(x))
hidden = self.act_fn(self.fc2(hidden))
reward = self.fc3(hidden).squeeze(dim=1)
return reward
class ValueModel(jit.ScriptModule):
def __init__(self, belief_size, state_size, hidden_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, hidden_size)
self.fc4 = nn.Linear(hidden_size, 1)
self.modules = [self.fc1, self.fc2, self.fc3, self.fc4]
@jit.script_method
def forward(self, belief, state):
x = torch.cat([belief, state],dim=1)
hidden = self.act_fn(self.fc1(x))
hidden = self.act_fn(self.fc2(hidden))
hidden = self.act_fn(self.fc3(hidden))
reward = self.fc4(hidden).squeeze(dim=1)
return reward
class ActorModel(jit.ScriptModule):
def __init__(self, belief_size, state_size, hidden_size, action_size, dist='tanh_normal',
activation_function='elu', min_std=1e-4, init_std=5, mean_scale=5):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(belief_size + state_size, hidden_size)
self.fc2 = nn.Linear(hidden_size, hidden_size)
self.fc3 = nn.Linear(hidden_size, hidden_size)
self.fc4 = nn.Linear(hidden_size, hidden_size)
self.fc5 = nn.Linear(hidden_size, 2*action_size)
self.modules = [self.fc1, self.fc2, self.fc3, self.fc4, self.fc5]
self._dist = dist
self._min_std = min_std
self._init_std = init_std
self._mean_scale = mean_scale
@jit.script_method
def forward(self, belief, state):
raw_init_std = torch.log(torch.exp(self._init_std) - 1)
x = torch.cat([belief, state],dim=1)
hidden = self.act_fn(self.fc1(x))
hidden = self.act_fn(self.fc2(hidden))
hidden = self.act_fn(self.fc3(hidden))
hidden = self.act_fn(self.fc4(hidden))
action = self.fc5(hidden).squeeze(dim=1)
action_mean, action_std_dev = torch.chunk(action, 2, dim=1)
action_mean = self._mean_scale * torch.tanh(action_mean / self._mean_scale)
action_std = F.softplus(action_std_dev + raw_init_std) + self._min_std
return action_mean, action_std
def get_action(self, belief, state, det=False):
action_mean, action_std = self.forward(belief, state)
dist = Normal(action_mean, action_std)
dist = TransformedDistribution(dist, TanhBijector())
dist = torch.distributions.Independent(dist,1)
dist = SampleDist(dist)
if det: return dist.mode()
else: return dist.rsample()
class SymbolicEncoder(jit.ScriptModule):
def __init__(self, observation_size, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.fc1 = nn.Linear(observation_size, embedding_size)
self.fc2 = nn.Linear(embedding_size, embedding_size)
self.fc3 = nn.Linear(embedding_size, embedding_size)
self.modules = [self.fc1, self.fc2, self.fc3]
@jit.script_method
def forward(self, observation):
hidden = self.act_fn(self.fc1(observation))
hidden = self.act_fn(self.fc2(hidden))
hidden = self.fc3(hidden)
return hidden
class VisualEncoder(jit.ScriptModule):
__constants__ = ['embedding_size']
def __init__(self, embedding_size, activation_function='relu'):
super().__init__()
self.act_fn = getattr(F, activation_function)
self.embedding_size = embedding_size
self.conv1 = nn.Conv2d(3, 32, 4, stride=2)
self.conv2 = nn.Conv2d(32, 64, 4, stride=2)
self.conv3 = nn.Conv2d(64, 128, 4, stride=2)
self.conv4 = nn.Conv2d(128, 256, 4, stride=2)
self.fc = nn.Identity() if embedding_size == 1024 else nn.Linear(1024, embedding_size)
self.modules = [self.conv1, self.conv2, self.conv3, self.conv4]
@jit.script_method
def forward(self, observation, state):
hidden = self.act_fn(self.conv1(observation))
hidden = self.act_fn(self.conv2(hidden))
hidden = self.act_fn(self.conv3(hidden))
hidden = self.act_fn(self.conv4(hidden))
hidden = hidden.view(-1, 1024)
hidden = self.fc(hidden) # Identity if embedding size is 1024 else linear projection
hidden = torch.cat([hidden, state.float()], dim=-1)
return hidden
def Encoder(symbolic, observation_size, embedding_size, state_concat_size=0, activation_function='relu'):
if symbolic:
return SymbolicEncoder(observation_size, embedding_size, state_concat_size)
else:
return VisualEncoder(embedding_size, state_concat_size)
# "atanh", "TanhBijector" and "SampleDist" are from the following repo
# https://github.com/juliusfrost/dreamer-pytorch
def atanh(x):
return 0.5 * torch.log((1 + x) / (1 - x))
class TanhBijector(torch.distributions.Transform):
def __init__(self):
super().__init__()
self.bijective = True
@property
def sign(self): return 1.
def _call(self, x): return torch.tanh(x)
def _inverse(self, y: torch.Tensor):
y = torch.where(
(torch.abs(y) <= 1.),
torch.clamp(y, -0.99999997, 0.99999997),
y)
y = atanh(y)
return y
def log_abs_det_jacobian(self, x, y):
return 2. * (np.log(2) - x - F.softplus(-2. * x))
class SampleDist:
def __init__(self, dist, samples=100):
self._dist = dist
self._samples = samples
@property
def name(self):
return 'SampleDist'
def __getattr__(self, name):
return getattr(self._dist, name)
def mean(self):
sample = dist.rsample()
return torch.mean(sample, 0)
def mode(self):
dist = self._dist.expand((self._samples, *self._dist.batch_shape))
sample = dist.rsample()
logprob = dist.log_prob(sample)
batch_size = sample.size(1)
feature_size = sample.size(2)
indices = torch.argmax(logprob, dim=0).reshape(1, batch_size, 1).expand(1, batch_size, feature_size)
return torch.gather(sample, 0, indices).squeeze(0)
def entropy(self):
dist = self._dist.expand((self._samples, *self._dist.batch_shape))
sample = dist.rsample()
logprob = dist.log_prob(sample)
return -torch.mean(logprob, 0)
def sample(self):
return self._dist.sample()
| true | true |
1c3e23a077709ee776901018e5e918adc3753882 | 5,253 | py | Python | essmc2/hooks/checkpoint.py | huang-ziyuan/EssentialMC2 | 87141df94c1ac8e426ceec071720b97f5b9d3b88 | [
"MIT"
] | null | null | null | essmc2/hooks/checkpoint.py | huang-ziyuan/EssentialMC2 | 87141df94c1ac8e426ceec071720b97f5b9d3b88 | [
"MIT"
] | null | null | null | essmc2/hooks/checkpoint.py | huang-ziyuan/EssentialMC2 | 87141df94c1ac8e426ceec071720b97f5b9d3b88 | [
"MIT"
] | null | null | null | # Copyright 2021 Alibaba Group Holding Limited. All Rights Reserved.
import os.path as osp
import sys
import warnings
import torch
import torch.distributed as du
from essmc2.utils.file_systems import FS
from .hook import Hook
from .registry import HOOKS
_DEFAULT_CHECKPOINT_PRIORITY = 300
@HOOKS.register_class()
class CheckpointHook(Hook):
""" Checkpoint resume or save hook.
Args:
interval (int): Save interval, by epoch.
save_best (bool): Save the best checkpoint by a metric key, default is False.
save_best_by (str): How to get the best the checkpoint by the metric key, default is ''.
+ means the higher the best (default).
- means the lower the best.
E.g. +acc@1, -err@1, acc@5(same as +acc@5)
"""
def __init__(self,
interval=1,
save_best=False,
save_best_by="",
**kwargs):
priority = kwargs.pop("priority") if "priority" in kwargs else _DEFAULT_CHECKPOINT_PRIORITY
super(CheckpointHook, self).__init__(priority=priority)
self.interval = interval
self.save_best = save_best
self.save_best_by = save_best_by
if self.save_best and not self.save_best_by:
warnings.warn("CheckpointHook: Parameter 'save_best_by' is not set, turn off save_best function.")
self.save_best = False
self.higher_the_best = True
if self.save_best:
if self.save_best_by.startswith("+"):
self.save_best_by = self.save_best_by[1:]
elif self.save_best_by.startswith("-"):
self.save_best_by = self.save_best_by[1:]
self.higher_the_best = False
if self.save_best and not self.save_best_by:
warnings.warn("CheckpointHook: Parameter 'save_best_by' is not valid, turn off save_best function.")
self.save_best = False
self._last_best = None if not self.save_best else (
sys.float_info.min if self.higher_the_best else sys.float_info.max
)
def before_solve(self, solver):
if solver.resume_from is None:
return
with FS.get_fs_client(solver.resume_from) as client:
if not client.exists(solver.resume_from):
solver.logger.error(f"File not exists {solver.resume_from}")
return
solver.logger.info(f"Loading checkpoint from {solver.resume_from}")
local_file = client.get_object_to_local_file(solver.resume_from)
checkpoint = torch.load(local_file)
solver.load_checkpoint(checkpoint)
if self.save_best and "_CheckpointHook_best" in checkpoint:
self._last_best = checkpoint["_CheckpointHook_best"]
def after_epoch(self, solver):
if du.is_available() and du.is_initialized() and du.get_rank() != 0:
return
if (solver.epoch + 1) % self.interval == 0:
solver.logger.info(f'Saving checkpoint after {solver.epoch + solver.num_folds} epochs')
checkpoint = solver.save_checkpoint()
if checkpoint is None or len(checkpoint) == 0:
return
cur_is_best = False
if self.save_best:
# Try to get current state from epoch_outputs["eval"]
cur_state = None \
if self.save_best_by not in solver.epoch_outputs["eval"] \
else solver.epoch_outputs["eval"][self.save_best_by]
# Try to get current state from agg_iter_outputs["eval"] if do_final_eval is False
if cur_state is None:
cur_state = None \
if self.save_best_by not in solver.agg_iter_outputs["eval"] \
else solver.agg_iter_outputs["eval"][self.save_best_by]
# Try to get current state from agg_iter_outputs["train"] if no evaluation
if cur_state is None:
cur_state = None \
if self.save_best_by not in solver.agg_iter_outputs["train"] \
else solver.agg_iter_outputs["train"][self.save_best_by]
if cur_state is not None:
if self.higher_the_best and cur_state > self._last_best:
self._last_best = cur_state
cur_is_best = True
elif not self.higher_the_best and cur_state < self._last_best:
self._last_best = cur_state
cur_is_best = True
checkpoint["_CheckpointHook_best"] = self._last_best
# minus 1, means index
save_path = osp.join(solver.work_dir, "epoch-{:05d}.pth".format(solver.epoch + solver.num_folds))
with FS.get_fs_client(save_path) as client:
local_file = client.convert_to_local_path(save_path)
with open(local_file, "wb") as f:
torch.save(checkpoint, f)
client.put_object_from_local_file(local_file, save_path)
if cur_is_best:
best_path = osp.join(solver.work_dir, f"best.pth")
client.make_link(best_path, save_path)
| 46.078947 | 112 | 0.605559 |
import os.path as osp
import sys
import warnings
import torch
import torch.distributed as du
from essmc2.utils.file_systems import FS
from .hook import Hook
from .registry import HOOKS
_DEFAULT_CHECKPOINT_PRIORITY = 300
@HOOKS.register_class()
class CheckpointHook(Hook):
def __init__(self,
interval=1,
save_best=False,
save_best_by="",
**kwargs):
priority = kwargs.pop("priority") if "priority" in kwargs else _DEFAULT_CHECKPOINT_PRIORITY
super(CheckpointHook, self).__init__(priority=priority)
self.interval = interval
self.save_best = save_best
self.save_best_by = save_best_by
if self.save_best and not self.save_best_by:
warnings.warn("CheckpointHook: Parameter 'save_best_by' is not set, turn off save_best function.")
self.save_best = False
self.higher_the_best = True
if self.save_best:
if self.save_best_by.startswith("+"):
self.save_best_by = self.save_best_by[1:]
elif self.save_best_by.startswith("-"):
self.save_best_by = self.save_best_by[1:]
self.higher_the_best = False
if self.save_best and not self.save_best_by:
warnings.warn("CheckpointHook: Parameter 'save_best_by' is not valid, turn off save_best function.")
self.save_best = False
self._last_best = None if not self.save_best else (
sys.float_info.min if self.higher_the_best else sys.float_info.max
)
def before_solve(self, solver):
if solver.resume_from is None:
return
with FS.get_fs_client(solver.resume_from) as client:
if not client.exists(solver.resume_from):
solver.logger.error(f"File not exists {solver.resume_from}")
return
solver.logger.info(f"Loading checkpoint from {solver.resume_from}")
local_file = client.get_object_to_local_file(solver.resume_from)
checkpoint = torch.load(local_file)
solver.load_checkpoint(checkpoint)
if self.save_best and "_CheckpointHook_best" in checkpoint:
self._last_best = checkpoint["_CheckpointHook_best"]
def after_epoch(self, solver):
if du.is_available() and du.is_initialized() and du.get_rank() != 0:
return
if (solver.epoch + 1) % self.interval == 0:
solver.logger.info(f'Saving checkpoint after {solver.epoch + solver.num_folds} epochs')
checkpoint = solver.save_checkpoint()
if checkpoint is None or len(checkpoint) == 0:
return
cur_is_best = False
if self.save_best:
cur_state = None \
if self.save_best_by not in solver.epoch_outputs["eval"] \
else solver.epoch_outputs["eval"][self.save_best_by]
if cur_state is None:
cur_state = None \
if self.save_best_by not in solver.agg_iter_outputs["eval"] \
else solver.agg_iter_outputs["eval"][self.save_best_by]
if cur_state is None:
cur_state = None \
if self.save_best_by not in solver.agg_iter_outputs["train"] \
else solver.agg_iter_outputs["train"][self.save_best_by]
if cur_state is not None:
if self.higher_the_best and cur_state > self._last_best:
self._last_best = cur_state
cur_is_best = True
elif not self.higher_the_best and cur_state < self._last_best:
self._last_best = cur_state
cur_is_best = True
checkpoint["_CheckpointHook_best"] = self._last_best
save_path = osp.join(solver.work_dir, "epoch-{:05d}.pth".format(solver.epoch + solver.num_folds))
with FS.get_fs_client(save_path) as client:
local_file = client.convert_to_local_path(save_path)
with open(local_file, "wb") as f:
torch.save(checkpoint, f)
client.put_object_from_local_file(local_file, save_path)
if cur_is_best:
best_path = osp.join(solver.work_dir, f"best.pth")
client.make_link(best_path, save_path)
| true | true |
1c3e24b64b12c99d3c2a85aa3935636a6cba247d | 1,799 | py | Python | scripts/run_experiment_from_doodad.py | richardrl/rlkit | 088dae169a8d5ba1430094eee66f27b2cb7c4998 | [
"MIT"
] | null | null | null | scripts/run_experiment_from_doodad.py | richardrl/rlkit | 088dae169a8d5ba1430094eee66f27b2cb7c4998 | [
"MIT"
] | null | null | null | scripts/run_experiment_from_doodad.py | richardrl/rlkit | 088dae169a8d5ba1430094eee66f27b2cb7c4998 | [
"MIT"
] | null | null | null | import doodad as dd
from rlkit.launchers.launcher_util import run_experiment_here
import torch.multiprocessing as mp
import faulthandler
if __name__ == "__main__":
faulthandler.enable()
import matplotlib
matplotlib.use('agg')
print("set fork")
mp.set_start_method('forkserver')
args_dict = dd.get_args()
method_call = args_dict['method_call']
run_experiment_kwargs = args_dict['run_experiment_kwargs']
output_dir = args_dict['output_dir']
run_mode = args_dict.get('mode', None)
if run_mode and run_mode in ['slurm_singularity', 'sss']:
import os
run_experiment_kwargs['variant']['slurm-job-id'] = os.environ.get(
'SLURM_JOB_ID', None
)
if run_mode and run_mode == 'ec2':
try:
import urllib.request
instance_id = urllib.request.urlopen(
'http://169.254.169.254/latest/meta-data/instance-id'
).read().decode()
run_experiment_kwargs['variant']['EC2_instance_id'] = instance_id
except Exception as e:
print("Could not get instance ID. Error was...")
print(e)
if run_mode and (run_mode == 'ec2' or run_mode == 'gcp'):
# Do this in case base_log_dir was already set
run_experiment_kwargs['base_log_dir'] = output_dir
run_experiment_here(
method_call,
include_exp_prefix_sub_dir=False,
**run_experiment_kwargs
)
else:
# print("re kwargs")
# print(run_experiment_kwargs)
# print('run experiment from doodad / import mujoco')
# import mujoco_py
# print("import success")
run_experiment_here(
method_call,
log_dir=output_dir,
**run_experiment_kwargs
) | 35.27451 | 77 | 0.625347 | import doodad as dd
from rlkit.launchers.launcher_util import run_experiment_here
import torch.multiprocessing as mp
import faulthandler
if __name__ == "__main__":
faulthandler.enable()
import matplotlib
matplotlib.use('agg')
print("set fork")
mp.set_start_method('forkserver')
args_dict = dd.get_args()
method_call = args_dict['method_call']
run_experiment_kwargs = args_dict['run_experiment_kwargs']
output_dir = args_dict['output_dir']
run_mode = args_dict.get('mode', None)
if run_mode and run_mode in ['slurm_singularity', 'sss']:
import os
run_experiment_kwargs['variant']['slurm-job-id'] = os.environ.get(
'SLURM_JOB_ID', None
)
if run_mode and run_mode == 'ec2':
try:
import urllib.request
instance_id = urllib.request.urlopen(
'http://169.254.169.254/latest/meta-data/instance-id'
).read().decode()
run_experiment_kwargs['variant']['EC2_instance_id'] = instance_id
except Exception as e:
print("Could not get instance ID. Error was...")
print(e)
if run_mode and (run_mode == 'ec2' or run_mode == 'gcp'):
run_experiment_kwargs['base_log_dir'] = output_dir
run_experiment_here(
method_call,
include_exp_prefix_sub_dir=False,
**run_experiment_kwargs
)
else:
run_experiment_here(
method_call,
log_dir=output_dir,
**run_experiment_kwargs
) | true | true |
1c3e252741d2610fad7636ac06b808e2e1d03668 | 108 | py | Python | resume/views.py | AkinWilderman/myPort | 3ddeea04ccffe3ed7b66d6dba2c1f2dc00c9eb6c | [
"Apache-2.0"
] | null | null | null | resume/views.py | AkinWilderman/myPort | 3ddeea04ccffe3ed7b66d6dba2c1f2dc00c9eb6c | [
"Apache-2.0"
] | null | null | null | resume/views.py | AkinWilderman/myPort | 3ddeea04ccffe3ed7b66d6dba2c1f2dc00c9eb6c | [
"Apache-2.0"
] | null | null | null | from django.shortcuts import render
def resume(request):
return render(request, 'resume/resume.html')
| 18 | 48 | 0.759259 | from django.shortcuts import render
def resume(request):
return render(request, 'resume/resume.html')
| true | true |
1c3e264641306fb838bde0f6cd3792460c73a77c | 16,387 | py | Python | main.py | chiro2001/cumcm-a | 6e8c11166c98b6683433423a595f346198cc4790 | [
"MIT"
] | null | null | null | main.py | chiro2001/cumcm-a | 6e8c11166c98b6683433423a595f346198cc4790 | [
"MIT"
] | null | null | null | main.py | chiro2001/cumcm-a | 6e8c11166c98b6683433423a595f346198cc4790 | [
"MIT"
] | null | null | null | import os
import argparse
import pandas as pd
import time
import matplotlib.pyplot as plt
import traceback
import torch.optim as optim
from tqdm import trange
import threading
from utils import *
import cv2
from base_logger import logger
from fast import FAST
# 是否使用多线程显示图像
draw_threaded: bool = False
# 一些全局变量
g_fig = None
g_frame: np.ndarray = None
g_draw_kwargs: dict = None
g_exit: bool = False
# 绘制当前图像
def draw(model: FAST, **kwargs):
global g_frame, g_draw_kwargs
if draw_threaded:
g_frame = model.expands.clone().cpu().detach().numpy()
g_draw_kwargs = kwargs
else:
g_draw_kwargs = kwargs
draw_thread(source=model.expands.clone().cpu().detach().numpy())
# 使用 opencv 绘制图像以便观察
# import cv2
# frame = model.expands.clone().cpu().detach().numpy()
# position = model.update_position(expand_source=frame)
# size = (int(position.transpose(0, 1)[0].max() - position.transpose(0, 1)[0].min() + 1),
# int(position.transpose(0, 1)[1].max() - position.transpose(0, 1)[1].min() + 1))
# im = np.zeros(size, dtype=np.uint8)
# for p in position:
# pos = (int((p[0] - position.transpose(0, 1)[0].min())), int((p[1] - position.transpose(0, 1)[1].min())))
# cv2.circle(im, center=pos, radius=5, color=(0xFF - int(0xFF * (p[2] - position.transpose(0, 1)[2].min()) / (
# position.transpose(0, 1)[2].max() - position.transpose(0, 1)[2].min()))), thickness=-1)
# cv2.imshow('now', im)
# cv2.waitKey(1)
# 绘图函数
def draw_thread(source: torch.Tensor = None):
global g_frame, g_fig
while True:
wait_time: int = g_draw_kwargs.get('wait_time', 0)
enlarge: float = g_draw_kwargs.get('enlarge', 500)
alpha: float = g_draw_kwargs.get('alpha', 0)
beta: float = g_draw_kwargs.get('beta', 0)
if source is None:
if g_exit:
return
if g_frame is None or model_ is None:
time.sleep(0.05)
continue
if wait_time < 0:
if g_fig is not None:
try:
plt.close(g_fig)
except Exception as e:
print(e)
# if g_fig is None:
# g_fig = plt.figure(1, figsize=(4, 4), dpi=80)
# fig1 = plt.figure(1, figsize=(4, 4), dpi=80)
# plt.clf()
fig1 = plt.figure(dpi=360, figsize=(10, 10))
plt.xlim(-300, 300)
plt.ylim(-300, 300)
# ax = plt.subplot(2, 2, 2, projection='3d')
# plt.sca(ax)
ax = plt.axes(projection='3d')
ax.view_init(elev=10., azim=11)
# ax.view_init(elev=90., azim=0)
ax.set_zlim(-400, -100)
# ax2 = plt.axes(projection='3d')
# ax2.view_init(elev=10., azim=11)
# # ax2.view_init(elev=90., azim=0)
# ax2.set_zlim(-400, -100)
if source is None:
# expands = g_frame * enlarge
expands_raw = g_frame
g_frame = None
else:
# expands = source * enlarge
expands_raw = source
def draw_it(expands_, c='g', enlarge_: float = 1):
# 直接使用未经变换的向量从而取得原来的视角
position: torch.Tensor = model_.update_position(expand_source=expands_, enlarge=enlarge_,
position_raw_source=model_.position_fixed,
unit_vector_source=model_.unit_vectors_fixed)
points = position.clone().detach().cpu().numpy()
ax.scatter3D(points.T[0], points.T[1], points.T[2], c=c, marker='.')
# 绘制不放大的图
# expands_real_raw = torch.zeros(expands_raw.shape, dtype=torch.float64, device=model_.device)
# print('expands', expands_raw)
# draw_it(expands_real_raw, c='m', enlarge_=1)
draw_it(expands_raw, c='g', enlarge_=enlarge)
# draw_it(expands_raw, 'm')
fig2 = plt.figure(dpi=120)
ax2 = plt.axes()
# ax2 = plt.subplot(2, 2, 1)
plt.sca(ax2)
# 画 expands
plt.plot([i for i in range(len(expands_raw))], expands_raw)
if source is None:
# if wait_time == 0:
# plt.show()
if 0 > wait_time:
plt.show()
time.sleep(wait_time)
if 0 == wait_time:
plt.draw()
t = wait_time + 0.5
plt.pause(t)
time.sleep(t)
# plt.close(g_fig)
elif wait_time < 0:
plt.draw()
plt.clf()
else:
# fig = plt.figure(1)
# plt.draw()
# 保存图像
if g_draw_kwargs.get('save_image', True):
problem = 'p1' if alpha == 0 else 'p2'
filename1, filename2 = f"pics/{problem}/{model_.mode}_x{int(enlarge)}_fixed.png", \
f"pics/{problem}/{model_.mode}_expands.png"
logger.warning(f'saving images to {filename1}, {filename2}')
fig1.savefig(filename1)
fig2.savefig(filename2)
plt.pause(wait_time if wait_time != 0 else 3)
plt.close(fig1)
plt.close(fig2)
plt.clf()
break
# 基于第 2 问的反射面调节方案,计算调节后馈源舱的接收比,即馈源舱有效区域接收到
# 的反射信号与 300 米口径内反射面的反射信号之比,并与基准反射球面的接收比作比较。
def calc(model: FAST):
with torch.no_grad():
# 计算内反射面的反射信号
s_inner_reflex = np.pi * FAST.R_SURFACE ** 2
# 总之先推理一遍试试
loss_total = model()
raw_square = model.get_light_loss(get_raw_surface=True)
# 求基准反射球面的反射面积
# 取另一个新的模型,其中的伸缩量就是 0
model2 = FAST()
raw_ball_square = model2.get_light_loss(get_raw_square=True)
# 将第三题结果写入文件
text1 = f"调节后馈源舱的接收比: {raw_square / s_inner_reflex}"
text2 = f"基准反射球面的接收比: {raw_ball_square / (np.pi * (FAST.D / 2) ** 2)}"
print(text1)
print(text2)
with open('data/p3.txt', 'w', encoding='utf-8') as f:
f.write(f"{text1}\r\n{text2}")
logger.warning(f"Saving p3.txt...")
# 运行主函数
def main(alpha: float = 0, beta: float = 0, learning_rate: float = 1e-4, show: bool = True, wait_time: int = 0,
out: str = 'data/附件4.xlsx', module_path: str = None, load_path: str = None, enlarge: float = 500,
mode: str = 'ring', save_image: bool = True, save_only: bool = False, calc_only: bool = False, **kwargs):
global model_, g_exit
model_ = FAST(**kwargs)
model = model_
if load_path is not None:
try:
if mode == FAST.MODE_SINGLE:
path = os.path.join(os.path.dirname(load_path),
f"{os.path.basename(load_path).split('.')[0]}_"
f"{mode}.{load_path.split('.')[-1]}")
else:
path = load_path
try:
if os.path.exists(path):
model.mode = mode
model.init_data()
model.load_state_dict(torch.load(path))
except FileNotFoundError:
logger.warning(f'No single module path: {path}, use ring module.')
model.load_state_dict(torch.load(load_path))
except FileNotFoundError:
logger.error(f"No module path: {load_path}")
if draw_threaded:
thread_draw = threading.Thread(target=draw_thread)
thread_draw.setDaemon(True)
thread_draw.start()
model.mode = mode
model.init_data()
# 旋转模型
# test_rotation(model)
model.rotate(alpha, beta, unit_degree=True)
# 亿些测试
# test_triangle_order(model)
# test_r2(model)
# exit()
# 仅仅计算第三题
if calc_only:
calc(model)
return
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
try:
for i in trange(1000):
optimizer.zero_grad()
loss = model()
logger.info(f'epoch {i} loss: {loss.item()}')
logger.warning(f"vertex: {model.vertex.clone().cpu().detach().item()}")
if not model.is_expands_legal():
logger.warning(f'不满足伸缩限制!共{model.count_illegal_expands()}')
if not model.is_padding_legal():
logger.warning(f'不满足间隔变化限制!')
loss.backward()
optimizer.step()
print(model.expands)
alpha_, beta_ = map(lambda x: x / 360 * 2 * np.pi, [alpha, beta])
if show:
# draw(model, wait_time=wait_time, enlarge=100)
# draw(model, wait_time=wait_time, enlarge=enlarge, alpha=(-alpha_), beta=(beta_ - np.pi / 2))
draw(model, wait_time=wait_time, enlarge=enlarge, alpha=alpha_, beta=beta_, save_image=save_image)
if save_only:
raise KeyboardInterrupt("Save Only Mode")
except KeyboardInterrupt:
logger.warning(f'trying to save data...')
g_exit = True
# 进行一个文件的保存
try:
logger.info(f'Saving expands data to: {out}')
writer = pd.ExcelWriter(out, engine='xlsxwriter')
if os.path.exists('data/vertex.txt'):
with open('data/vertex.txt', 'r', encoding='utf-8') as f:
vertex = float(f.read())
logger.warning('vertex loaded from data/vertex.txt.')
else:
with open('data/vertex.txt', 'w', encoding='utf-8') as f:
vertex = model.vertex.clone().cpu().detach().item()
f.write(str(vertex))
logger.warning('vertex saved to data/vertex.txt.')
pd.DataFrame({
'X坐标(米)': [0, ],
'Y坐标(米)': [0, ],
'Z坐标(米)': [vertex, ],
'': ['', ],
' ': ['', ],
'注:至少保留3位小数': ['', ]
}).to_excel(writer, sheet_name='理想抛物面顶点坐标', index=False)
worksheet = writer.sheets['理想抛物面顶点坐标']
worksheet.set_column("A:F", 10.36)
points_fixed: torch.Tensor = model_.update_position(expand_source=model.expands.clone().cpu().detach().numpy(),
position_raw_source=model_.position_fixed,
unit_vector_source=model_.unit_vectors_fixed) \
.clone().detach().cpu().numpy()
points_fixed = np.array([points_fixed[model.index_fixed[name]] for name in model.name_list_fixed])
pd.DataFrame({
'节点编号': model.name_list_fixed,
'X坐标(米)': points_fixed.T[0],
'Y坐标(米)': points_fixed.T[1],
'Z坐标(米)': points_fixed.T[2],
'': ['' for _ in range(model.count_nodes)],
' ': ['' for _ in range(model.count_nodes)],
'注:至少保留3位小数': ['' for _ in range(model.count_nodes)]
}).to_excel(writer, sheet_name='调整后主索节点编号及坐标', index=False)
worksheet = writer.sheets['调整后主索节点编号及坐标']
worksheet.set_column("A:G", 10.36)
expand_filled = model.get_expand_filled(expand_source=model.expands.cpu().detach()).detach().numpy()
expand_filled_fixed = np.array([expand_filled[model.index_fixed[name]] for name in model.name_list_fixed])
pd.DataFrame({
'对应主索节点编号': model.name_list_fixed,
'伸缩量(米)': expand_filled_fixed,
'': ['' for _ in range(model.count_nodes)],
'注:至少保留3位小数': ['' for _ in range(model.count_nodes)]
}).to_excel(writer, sheet_name='促动器顶端伸缩量', index=False)
worksheet = writer.sheets['促动器顶端伸缩量']
worksheet.set_column("A:A", 16.82)
worksheet.set_column("B:B", 13.82)
worksheet.set_column("C:C", 10.36)
worksheet.set_column("D:D", 10.36)
writer.close()
except Exception as e:
logger.error('保存数据文件出错: %s' % str(e))
traceback.print_exc()
# 进行一个模型的保存
try:
if module_path is not None:
if model.mode == FAST.MODE_SINGLE:
path = os.path.join(os.path.dirname(module_path),
f"{os.path.basename(module_path).split('.')[0]}_"
f"{model.mode}.{module_path.split('.')[-1]}")
else:
path = module_path
logger.info(f'Saving module weights to: {path}')
torch.save(model.state_dict(), path)
except Exception as e:
logger.error('保存模型文件出错: %s' % str(e))
traceback.print_exc()
# 测试:整体旋转模型
def test_rotation(model: FAST):
for beta in range(45, 90, 5):
model.rotate(0, beta, unit_degree=True)
draw_thread(model.expands.clone().cpu().detach().numpy())
# time.sleep(1)
model.read_data()
exit()
# 测试:测试原来三角形数据顺序
def test_triangle_order(model: FAST):
im = np.zeros((500, 500), dtype=np.uint8)
for i in range(model.count_triangles):
triangle = model.triangles_data[i]
board = model.get_board(triangle).cpu().clone().detach().numpy()
points = np.array((board.T[:2]).T, dtype=np.int32) + 250
cv2.fillPoly(im, [points], int(200 - i / model.count_triangles * 200) + 50)
cv2.imshow('triangles', im)
cv2.waitKey(1)
cv2.waitKey(0)
# 测试:z 坐标对于同一高度的点的汇集程度
def test_r2(model: FAST):
position_raw = model.position_raw.clone().cpu().detach().numpy()
step = 1
pos = 5
pos_last = 0
splits = []
fig = plt.figure(dpi=80)
while pos < len(position_raw):
# print(f'[{pos_last} : {pos}]')
position_selected = position_raw[pos_last:pos]
# print(len(position_selected))
# r2 = np.array([np.sum((i - [0, 0, -300.4]) ** 2) for i in position_selected])
r2 = np.array([i[2] for i in position_selected])
splits.append(r2.copy())
plt.plot([i for i in range(pos_last, pos, 1)], r2)
pos_last = pos
pos += step
step += 5
print('num[r] =', len(splits))
# r2 = np.array([np.sum((position_raw[i] - [0, 0, -300.4]) ** 2) / (30 * i) for i in range(len(position_raw))])
# r2 = np.array([(i + 10) / 500 + position_raw[i][2] / (((i + 1))) for i in range(len(position_raw))])
# plt.plot([i for i in range(len(r2))], r2)
# plt.plot([i for i in range(len(position_raw))], r2)
plt.show()
model_: FAST = None
if __name__ == '__main__':
# 以下为命令行参数配置,使用 python main.py -h 以得知具体使用方法
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--alpha', type=float, default=0, help='设置 alpha 角(单位:度)')
parser.add_argument('-b', '--beta', type=float, default=90, help='设置 beta 角(单位:度)')
parser.add_argument('-l', '--learning-rate', type=float, default=1e-2, help='设置学习率')
parser.add_argument('-r', '--randomly-init', type=bool, default=False, help='设置是否随机初始化参数')
parser.add_argument('-p', '--optim', type=str, default='Adam', help='设置梯度下降函数')
parser.add_argument('-d', '--device', type=str, default=None, help='设置 Tensor 计算设备')
parser.add_argument('-s', '--show', type=bool, default=False, help='设置是否显示训练中图像')
parser.add_argument('-g', '--save-image', type=bool, default=True, help='设置是否保存图像数据')
parser.add_argument('-y', '--save-only', type=bool, default=False, help='设置只保存数据不训练')
parser.add_argument('-w', '--wait-time', type=float, default=0, help='设置图像显示等待时间(单位:秒)')
parser.add_argument('-o', '--out', type=str, default='data/result.xlsx', help='设置完成后数据导出文件')
parser.add_argument('-m', '--module-path', type=str, default='data/module.pth', help='设置模型保存路径')
# parser.add_argument('-t', '--load-path', type=str, default='data/module.pth', help='设置模型加载路径')
parser.add_argument('-t', '--load-path', type=str, default=None, help='设置模型加载路径')
weight_default = [5, 2e3, 1e-4]
parser.add_argument('-w1', '--w1', type=float, default=weight_default[0], help='设置权值1')
parser.add_argument('-w2', '--w2', type=float, default=weight_default[1], help='设置权值2')
parser.add_argument('-w3', '--w3', type=float, default=weight_default[2], help='设置权值3')
parser.add_argument('-e', '--enlarge', type=float, default=500, help='设置图像伸缩放大倍数')
parser.add_argument('-i', '--mode', type=str, default='ring', help='设置训练模式["ring", "single"]')
parser.add_argument('-c', '--calc-only', type=bool, default=False, help='设置计算第 (3) 问后退出')
args = parser.parse_args()
logger.info(f'参数: {args}')
main(**args.__dict__)
logger.info('=== [ALL DONE] ===')
| 39.968293 | 119 | 0.564045 | import os
import argparse
import pandas as pd
import time
import matplotlib.pyplot as plt
import traceback
import torch.optim as optim
from tqdm import trange
import threading
from utils import *
import cv2
from base_logger import logger
from fast import FAST
draw_threaded: bool = False
g_fig = None
g_frame: np.ndarray = None
g_draw_kwargs: dict = None
g_exit: bool = False
def draw(model: FAST, **kwargs):
global g_frame, g_draw_kwargs
if draw_threaded:
g_frame = model.expands.clone().cpu().detach().numpy()
g_draw_kwargs = kwargs
else:
g_draw_kwargs = kwargs
draw_thread(source=model.expands.clone().cpu().detach().numpy())
def draw_thread(source: torch.Tensor = None):
global g_frame, g_fig
while True:
wait_time: int = g_draw_kwargs.get('wait_time', 0)
enlarge: float = g_draw_kwargs.get('enlarge', 500)
alpha: float = g_draw_kwargs.get('alpha', 0)
beta: float = g_draw_kwargs.get('beta', 0)
if source is None:
if g_exit:
return
if g_frame is None or model_ is None:
time.sleep(0.05)
continue
if wait_time < 0:
if g_fig is not None:
try:
plt.close(g_fig)
except Exception as e:
print(e)
fig1 = plt.figure(dpi=360, figsize=(10, 10))
plt.xlim(-300, 300)
plt.ylim(-300, 300)
ax = plt.axes(projection='3d')
ax.view_init(elev=10., azim=11)
ax.set_zlim(-400, -100)
one:
expands_raw = g_frame
g_frame = None
else:
expands_raw = source
def draw_it(expands_, c='g', enlarge_: float = 1):
position: torch.Tensor = model_.update_position(expand_source=expands_, enlarge=enlarge_,
position_raw_source=model_.position_fixed,
unit_vector_source=model_.unit_vectors_fixed)
points = position.clone().detach().cpu().numpy()
ax.scatter3D(points.T[0], points.T[1], points.T[2], c=c, marker='.')
draw_it(expands_raw, c='g', enlarge_=enlarge)
fig2 = plt.figure(dpi=120)
ax2 = plt.axes()
plt.sca(ax2)
plt.plot([i for i in range(len(expands_raw))], expands_raw)
if source is None:
if 0 > wait_time:
plt.show()
time.sleep(wait_time)
if 0 == wait_time:
plt.draw()
t = wait_time + 0.5
plt.pause(t)
time.sleep(t)
elif wait_time < 0:
plt.draw()
plt.clf()
else:
if g_draw_kwargs.get('save_image', True):
problem = 'p1' if alpha == 0 else 'p2'
filename1, filename2 = f"pics/{problem}/{model_.mode}_x{int(enlarge)}_fixed.png", \
f"pics/{problem}/{model_.mode}_expands.png"
logger.warning(f'saving images to {filename1}, {filename2}')
fig1.savefig(filename1)
fig2.savefig(filename2)
plt.pause(wait_time if wait_time != 0 else 3)
plt.close(fig1)
plt.close(fig2)
plt.clf()
break
def calc(model: FAST):
with torch.no_grad():
s_inner_reflex = np.pi * FAST.R_SURFACE ** 2
loss_total = model()
raw_square = model.get_light_loss(get_raw_surface=True)
model2 = FAST()
raw_ball_square = model2.get_light_loss(get_raw_square=True)
text1 = f"调节后馈源舱的接收比: {raw_square / s_inner_reflex}"
text2 = f"基准反射球面的接收比: {raw_ball_square / (np.pi * (FAST.D / 2) ** 2)}"
print(text1)
print(text2)
with open('data/p3.txt', 'w', encoding='utf-8') as f:
f.write(f"{text1}\r\n{text2}")
logger.warning(f"Saving p3.txt...")
def main(alpha: float = 0, beta: float = 0, learning_rate: float = 1e-4, show: bool = True, wait_time: int = 0,
out: str = 'data/附件4.xlsx', module_path: str = None, load_path: str = None, enlarge: float = 500,
mode: str = 'ring', save_image: bool = True, save_only: bool = False, calc_only: bool = False, **kwargs):
global model_, g_exit
model_ = FAST(**kwargs)
model = model_
if load_path is not None:
try:
if mode == FAST.MODE_SINGLE:
path = os.path.join(os.path.dirname(load_path),
f"{os.path.basename(load_path).split('.')[0]}_"
f"{mode}.{load_path.split('.')[-1]}")
else:
path = load_path
try:
if os.path.exists(path):
model.mode = mode
model.init_data()
model.load_state_dict(torch.load(path))
except FileNotFoundError:
logger.warning(f'No single module path: {path}, use ring module.')
model.load_state_dict(torch.load(load_path))
except FileNotFoundError:
logger.error(f"No module path: {load_path}")
if draw_threaded:
thread_draw = threading.Thread(target=draw_thread)
thread_draw.setDaemon(True)
thread_draw.start()
model.mode = mode
model.init_data()
model.rotate(alpha, beta, unit_degree=True)
if calc_only:
calc(model)
return
optimizer = optim.Adam(model.parameters(), lr=learning_rate)
try:
for i in trange(1000):
optimizer.zero_grad()
loss = model()
logger.info(f'epoch {i} loss: {loss.item()}')
logger.warning(f"vertex: {model.vertex.clone().cpu().detach().item()}")
if not model.is_expands_legal():
logger.warning(f'不满足伸缩限制!共{model.count_illegal_expands()}')
if not model.is_padding_legal():
logger.warning(f'不满足间隔变化限制!')
loss.backward()
optimizer.step()
print(model.expands)
alpha_, beta_ = map(lambda x: x / 360 * 2 * np.pi, [alpha, beta])
if show:
draw(model, wait_time=wait_time, enlarge=enlarge, alpha=alpha_, beta=beta_, save_image=save_image)
if save_only:
raise KeyboardInterrupt("Save Only Mode")
except KeyboardInterrupt:
logger.warning(f'trying to save data...')
g_exit = True
try:
logger.info(f'Saving expands data to: {out}')
writer = pd.ExcelWriter(out, engine='xlsxwriter')
if os.path.exists('data/vertex.txt'):
with open('data/vertex.txt', 'r', encoding='utf-8') as f:
vertex = float(f.read())
logger.warning('vertex loaded from data/vertex.txt.')
else:
with open('data/vertex.txt', 'w', encoding='utf-8') as f:
vertex = model.vertex.clone().cpu().detach().item()
f.write(str(vertex))
logger.warning('vertex saved to data/vertex.txt.')
pd.DataFrame({
'X坐标(米)': [0, ],
'Y坐标(米)': [0, ],
'Z坐标(米)': [vertex, ],
'': ['', ],
' ': ['', ],
'注:至少保留3位小数': ['', ]
}).to_excel(writer, sheet_name='理想抛物面顶点坐标', index=False)
worksheet = writer.sheets['理想抛物面顶点坐标']
worksheet.set_column("A:F", 10.36)
points_fixed: torch.Tensor = model_.update_position(expand_source=model.expands.clone().cpu().detach().numpy(),
position_raw_source=model_.position_fixed,
unit_vector_source=model_.unit_vectors_fixed) \
.clone().detach().cpu().numpy()
points_fixed = np.array([points_fixed[model.index_fixed[name]] for name in model.name_list_fixed])
pd.DataFrame({
'节点编号': model.name_list_fixed,
'X坐标(米)': points_fixed.T[0],
'Y坐标(米)': points_fixed.T[1],
'Z坐标(米)': points_fixed.T[2],
'': ['' for _ in range(model.count_nodes)],
' ': ['' for _ in range(model.count_nodes)],
'注:至少保留3位小数': ['' for _ in range(model.count_nodes)]
}).to_excel(writer, sheet_name='调整后主索节点编号及坐标', index=False)
worksheet = writer.sheets['调整后主索节点编号及坐标']
worksheet.set_column("A:G", 10.36)
expand_filled = model.get_expand_filled(expand_source=model.expands.cpu().detach()).detach().numpy()
expand_filled_fixed = np.array([expand_filled[model.index_fixed[name]] for name in model.name_list_fixed])
pd.DataFrame({
'对应主索节点编号': model.name_list_fixed,
'伸缩量(米)': expand_filled_fixed,
'': ['' for _ in range(model.count_nodes)],
'注:至少保留3位小数': ['' for _ in range(model.count_nodes)]
}).to_excel(writer, sheet_name='促动器顶端伸缩量', index=False)
worksheet = writer.sheets['促动器顶端伸缩量']
worksheet.set_column("A:A", 16.82)
worksheet.set_column("B:B", 13.82)
worksheet.set_column("C:C", 10.36)
worksheet.set_column("D:D", 10.36)
writer.close()
except Exception as e:
logger.error('保存数据文件出错: %s' % str(e))
traceback.print_exc()
try:
if module_path is not None:
if model.mode == FAST.MODE_SINGLE:
path = os.path.join(os.path.dirname(module_path),
f"{os.path.basename(module_path).split('.')[0]}_"
f"{model.mode}.{module_path.split('.')[-1]}")
else:
path = module_path
logger.info(f'Saving module weights to: {path}')
torch.save(model.state_dict(), path)
except Exception as e:
logger.error('保存模型文件出错: %s' % str(e))
traceback.print_exc()
def test_rotation(model: FAST):
for beta in range(45, 90, 5):
model.rotate(0, beta, unit_degree=True)
draw_thread(model.expands.clone().cpu().detach().numpy())
model.read_data()
exit()
def test_triangle_order(model: FAST):
im = np.zeros((500, 500), dtype=np.uint8)
for i in range(model.count_triangles):
triangle = model.triangles_data[i]
board = model.get_board(triangle).cpu().clone().detach().numpy()
points = np.array((board.T[:2]).T, dtype=np.int32) + 250
cv2.fillPoly(im, [points], int(200 - i / model.count_triangles * 200) + 50)
cv2.imshow('triangles', im)
cv2.waitKey(1)
cv2.waitKey(0)
def test_r2(model: FAST):
position_raw = model.position_raw.clone().cpu().detach().numpy()
step = 1
pos = 5
pos_last = 0
splits = []
fig = plt.figure(dpi=80)
while pos < len(position_raw):
position_selected = position_raw[pos_last:pos]
r2 = np.array([i[2] for i in position_selected])
splits.append(r2.copy())
plt.plot([i for i in range(pos_last, pos, 1)], r2)
pos_last = pos
pos += step
step += 5
print('num[r] =', len(splits))
plt.show()
model_: FAST = None
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('-a', '--alpha', type=float, default=0, help='设置 alpha 角(单位:度)')
parser.add_argument('-b', '--beta', type=float, default=90, help='设置 beta 角(单位:度)')
parser.add_argument('-l', '--learning-rate', type=float, default=1e-2, help='设置学习率')
parser.add_argument('-r', '--randomly-init', type=bool, default=False, help='设置是否随机初始化参数')
parser.add_argument('-p', '--optim', type=str, default='Adam', help='设置梯度下降函数')
parser.add_argument('-d', '--device', type=str, default=None, help='设置 Tensor 计算设备')
parser.add_argument('-s', '--show', type=bool, default=False, help='设置是否显示训练中图像')
parser.add_argument('-g', '--save-image', type=bool, default=True, help='设置是否保存图像数据')
parser.add_argument('-y', '--save-only', type=bool, default=False, help='设置只保存数据不训练')
parser.add_argument('-w', '--wait-time', type=float, default=0, help='设置图像显示等待时间(单位:秒)')
parser.add_argument('-o', '--out', type=str, default='data/result.xlsx', help='设置完成后数据导出文件')
parser.add_argument('-m', '--module-path', type=str, default='data/module.pth', help='设置模型保存路径')
parser.add_argument('-t', '--load-path', type=str, default=None, help='设置模型加载路径')
weight_default = [5, 2e3, 1e-4]
parser.add_argument('-w1', '--w1', type=float, default=weight_default[0], help='设置权值1')
parser.add_argument('-w2', '--w2', type=float, default=weight_default[1], help='设置权值2')
parser.add_argument('-w3', '--w3', type=float, default=weight_default[2], help='设置权值3')
parser.add_argument('-e', '--enlarge', type=float, default=500, help='设置图像伸缩放大倍数')
parser.add_argument('-i', '--mode', type=str, default='ring', help='设置训练模式["ring", "single"]')
parser.add_argument('-c', '--calc-only', type=bool, default=False, help='设置计算第 (3) 问后退出')
args = parser.parse_args()
logger.info(f'参数: {args}')
main(**args.__dict__)
logger.info('=== [ALL DONE] ===')
| true | true |
1c3e2743ad3dfe6322f1b8f5dbbb80cc79502c6d | 851 | py | Python | dbupgrade/apply.py | srittau/dbupgrade | 53472599c175768e2269d84ca7aed670d55c202b | [
"MIT"
] | 1 | 2020-10-26T13:28:47.000Z | 2020-10-26T13:28:47.000Z | dbupgrade/apply.py | srittau/dbupgrade | 53472599c175768e2269d84ca7aed670d55c202b | [
"MIT"
] | 83 | 2020-06-02T09:38:02.000Z | 2022-02-01T07:56:05.000Z | dbupgrade/apply.py | srittau/dbupgrade | 53472599c175768e2269d84ca7aed670d55c202b | [
"MIT"
] | null | null | null | import logging
from typing import Sequence
from sqlalchemy.exc import SQLAlchemyError
from dbupgrade.db import update_sql
from dbupgrade.files import FileInfo
def apply_files(db_url: str, files: Sequence[FileInfo]) -> None:
for file_info in files:
try:
apply_file(db_url, file_info)
except SQLAlchemyError as exc:
logging.error(str(exc))
return
def apply_file(db_url: str, file_info: FileInfo) -> None:
logging.info(
"applying #{0.version} (API level {0.api_level})".format(file_info)
)
with open(file_info.filename, "r") as stream:
sql = stream.read()
update_sql(
db_url,
sql,
file_info.schema,
file_info.version,
file_info.api_level,
transaction=file_info.transaction,
)
| 25.787879 | 75 | 0.625147 | import logging
from typing import Sequence
from sqlalchemy.exc import SQLAlchemyError
from dbupgrade.db import update_sql
from dbupgrade.files import FileInfo
def apply_files(db_url: str, files: Sequence[FileInfo]) -> None:
for file_info in files:
try:
apply_file(db_url, file_info)
except SQLAlchemyError as exc:
logging.error(str(exc))
return
def apply_file(db_url: str, file_info: FileInfo) -> None:
logging.info(
"applying #{0.version} (API level {0.api_level})".format(file_info)
)
with open(file_info.filename, "r") as stream:
sql = stream.read()
update_sql(
db_url,
sql,
file_info.schema,
file_info.version,
file_info.api_level,
transaction=file_info.transaction,
)
| true | true |
1c3e2799e1257b8489558f2dbcfe4857fb38cb9b | 1,507 | py | Python | cci-book/ed6/stacks_and_queues.py | topliceanu/learn | 6f4bb19fffb7b2baa88f047409075d5765ee6308 | [
"MIT"
] | 24 | 2016-03-21T07:53:54.000Z | 2020-06-29T12:16:36.000Z | cci-book/ed6/stacks_and_queues.py | topliceanu/learn | 6f4bb19fffb7b2baa88f047409075d5765ee6308 | [
"MIT"
] | 5 | 2015-09-29T17:12:36.000Z | 2020-03-26T20:51:56.000Z | cci-book/ed6/stacks_and_queues.py | topliceanu/learn | 6f4bb19fffb7b2baa88f047409075d5765ee6308 | [
"MIT"
] | 12 | 2016-05-24T16:48:32.000Z | 2020-10-02T12:22:09.000Z | # -*- coding: utf-8 -*-
class ThreeStacks(object):
""" 3.1 Three in One: Describe how you could use a
single array to implement three stacks.
"""
def __init__(self, size):
self.arr = [None] * size
self.stack1_ptr = 0
self.stack2_ptr = 1
self.stack3_ptr = 2
def pop(self, stack_no):
pass
def push(self, stack_no, item):
if stack_no == 1:
self.stack1_ptr = self.stack1_ptr + 3
self.arr[self.stack1_ptr] = item
elif stack_no == 2:
self.stack2_ptr = self.stack2_ptr + 3
self.arr[self.stack2_ptr] = item
elif stack_no == 3:
self.stack3_ptr = self.stack3_ptr + 3
self.arr[self.stack3_ptr] = item
else:
raise Exception('stack no {} does not exist'.format(stack_no))
def peek(self, stack_no):
if stack_no == 1:
return self.arr[self.stack1_ptr]
elif stack_no == 2:
return self.arr[self.stack2_ptr]
elif stack_no == 3:
return self.arr[self.stack3_ptr]
else:
raise Exception('stack no {} does not exist'.format(stack_no))
def is_empty(self, stack_no):
if stack_no == 1:
return self.stack1_ptr == 0
elif stack_no == 2:
return self.stack2_ptr == 1
elif stack_no == 3:
return self.stack3_ptr == 2
else:
raise Exception('stack no {} does not exist'.format(stack_no))
| 30.14 | 74 | 0.554745 |
class ThreeStacks(object):
def __init__(self, size):
self.arr = [None] * size
self.stack1_ptr = 0
self.stack2_ptr = 1
self.stack3_ptr = 2
def pop(self, stack_no):
pass
def push(self, stack_no, item):
if stack_no == 1:
self.stack1_ptr = self.stack1_ptr + 3
self.arr[self.stack1_ptr] = item
elif stack_no == 2:
self.stack2_ptr = self.stack2_ptr + 3
self.arr[self.stack2_ptr] = item
elif stack_no == 3:
self.stack3_ptr = self.stack3_ptr + 3
self.arr[self.stack3_ptr] = item
else:
raise Exception('stack no {} does not exist'.format(stack_no))
def peek(self, stack_no):
if stack_no == 1:
return self.arr[self.stack1_ptr]
elif stack_no == 2:
return self.arr[self.stack2_ptr]
elif stack_no == 3:
return self.arr[self.stack3_ptr]
else:
raise Exception('stack no {} does not exist'.format(stack_no))
def is_empty(self, stack_no):
if stack_no == 1:
return self.stack1_ptr == 0
elif stack_no == 2:
return self.stack2_ptr == 1
elif stack_no == 3:
return self.stack3_ptr == 2
else:
raise Exception('stack no {} does not exist'.format(stack_no))
| true | true |
1c3e27cf69c44694f8da63091c8cb9bdb2fde621 | 1,008 | py | Python | lib/django-1.4/django/__init__.py | MiCHiLU/google_appengine_sdk | 3da9f20d7e65e26c4938d2c4054bc4f39cbc5522 | [
"Apache-2.0"
] | 26 | 2015-01-20T08:02:38.000Z | 2020-06-10T04:57:41.000Z | lib/django-1.4/django/__init__.py | MiCHiLU/google_appengine_sdk | 3da9f20d7e65e26c4938d2c4054bc4f39cbc5522 | [
"Apache-2.0"
] | 4 | 2016-02-28T05:53:54.000Z | 2017-01-03T07:39:50.000Z | lib/django-1.4/django/__init__.py | MiCHiLU/google_appengine_sdk | 3da9f20d7e65e26c4938d2c4054bc4f39cbc5522 | [
"Apache-2.0"
] | 13 | 2016-02-28T00:14:23.000Z | 2021-05-03T15:47:36.000Z | VERSION = (1, 4, 13, 'final', 0)
def get_version(version=None):
"""Derives a PEP386-compliant version number from VERSION."""
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
# Now build the two parts of the version number:
# main = X.Y[.Z]
# sub = .devN - for pre-alpha releases
# | {a|b|c}N - for alpha, beta and rc releases
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
# At the toplevel, this would cause an import loop.
from django.utils.version import get_svn_revision
svn_revision = get_svn_revision()[4:]
if svn_revision != 'unknown':
sub = '.dev%s' % svn_revision
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
| 32.516129 | 65 | 0.575397 | VERSION = (1, 4, 13, 'final', 0)
def get_version(version=None):
if version is None:
version = VERSION
assert len(version) == 5
assert version[3] in ('alpha', 'beta', 'rc', 'final')
parts = 2 if version[2] == 0 else 3
main = '.'.join(str(x) for x in version[:parts])
sub = ''
if version[3] == 'alpha' and version[4] == 0:
from django.utils.version import get_svn_revision
svn_revision = get_svn_revision()[4:]
if svn_revision != 'unknown':
sub = '.dev%s' % svn_revision
elif version[3] != 'final':
mapping = {'alpha': 'a', 'beta': 'b', 'rc': 'c'}
sub = mapping[version[3]] + str(version[4])
return main + sub
| true | true |
1c3e283ff6e40fcdc1cc634891aebc01bad33f95 | 10,106 | py | Python | contrib/spendfrom/spendfrom.py | IngenuityCoin/Ingenuity | 475289926e435a9939358c695f4f10d1503bfa0c | [
"MIT"
] | 4 | 2018-12-06T23:56:18.000Z | 2021-03-06T10:15:33.000Z | contrib/spendfrom/spendfrom.py | IngenuityCoin/Ingenuity | 475289926e435a9939358c695f4f10d1503bfa0c | [
"MIT"
] | null | null | null | contrib/spendfrom/spendfrom.py | IngenuityCoin/Ingenuity | 475289926e435a9939358c695f4f10d1503bfa0c | [
"MIT"
] | 5 | 2018-12-06T23:56:41.000Z | 2021-05-10T06:35:51.000Z | #!/usr/bin/env python
#
# Use the raw transactions API to spend INGYs received on particular addresses,
# and send any change back to that same address.
#
# Example usage:
# spendfrom.py # Lists available funds
# spendfrom.py --from=ADDRESS --to=ADDRESS --amount=11.00
#
# Assumes it will talk to a ingenuityd or ingenuity-Qt running
# on localhost.
#
# Depends on jsonrpc
#
from decimal import *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
"""Make sure json library being used does not lose precision converting BTC values"""
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
"""Return the default location of the ingenuity data directory"""
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Ingenuity/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Ingenuity")
return os.path.expanduser("~/.ingenuity")
def read_bitcoin_config(dbdir):
"""Read the ingenuity.conf file from dbdir, returns dictionary of settings"""
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
if s.find('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "ingenuity.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
"""Connect to a ingenuity JSON-RPC server"""
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0) # 0/1 in config file, convert to True/False
if not 'rpcport' in config:
config['rpcport'] = 51475 if testnet else 3117
connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport'])
try:
result = ServiceProxy(connect)
# ServiceProxy is lazy-connect, so send an RPC command mostly to catch connection errors,
# but also make sure the ingenuityd we're talking to is/isn't testnet:
if result.getmininginfo()['testnet'] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(ingenuityd):
info = ingenuityd.getinfo()
if 'unlocked_until' not in info:
return True # wallet is not encrypted
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
ingenuityd.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = ingenuityd.getinfo()
return int(info['unlocked_until']) > time.time()
def list_available(ingenuityd):
address_summary = dict()
address_to_account = dict()
for info in ingenuityd.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = ingenuityd.listunspent(0)
for output in unspent:
# listunspent doesn't give addresses, so:
rawtx = ingenuityd.getrawtransaction(output['txid'], 1)
vout = rawtx["vout"][output['vout']]
pk = vout["scriptPubKey"]
# This code only deals with ordinary pay-to-ingenuity-address
# or pay-to-script-hash outputs right now; anything exotic is ignored.
if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
continue
address = pk["addresses"][0]
if address in address_summary:
address_summary[address]["total"] += vout["value"]
address_summary[address]["outputs"].append(output)
else:
address_summary[address] = {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(ingenuityd, fromaddresses, toaddress, amount, fee):
all_coins = list_available(ingenuityd)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed));
sys.exit(1)
#
# Note:
# Python's json/jsonrpc modules have inconsistent support for Decimal numbers.
# Instead of wrestling with getting json.dumps() (used by jsonrpc) to encode
# Decimals, I'm casting amounts to float before sending them to ingenuityd.
#
outputs = { toaddress : float(amount) }
(inputs, change_amount) = select_coins(needed, potential_inputs)
if change_amount > BASE_FEE: # don't bother with zero or tiny change
change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount)
rawtx = ingenuityd.createrawtransaction(inputs, outputs)
signed_rawtx = ingenuityd.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(ingenuityd, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = ingenuityd.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(ingenuityd, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = ingenuityd.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(ingenuityd, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000 # integer division rounds down
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
# Exercise for the reader: compute transaction priority, and
# warn if this is a very-low-priority transaction
except FeeError as err:
sys.stderr.write((str(err)+"\n"))
sys.exit(1)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get INGYs from")
parser.add_option("--to", dest="to", default=None,
help="address to get send INGYs to")
parser.add_option("--amount", dest="amount", default=None,
help="amount to send")
parser.add_option("--fee", dest="fee", default="0.0",
help="fee to include")
parser.add_option("--datadir", dest="datadir", default=determine_db_dir(),
help="location of ingenuity.conf file with RPC username/password (default: %default)")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true",
help="Use the test network")
parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true",
help="Don't broadcast the transaction, just create and print the transaction data")
(options, args) = parser.parse_args()
check_json_precision()
config = read_bitcoin_config(options.datadir)
if options.testnet: config['testnet'] = True
ingenuityd = connect_JSON(config)
if options.amount is None:
address_summary = list_available(ingenuityd)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1:
print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_wallet(ingenuityd) == False:
pass # Keep asking for passphrase until they get it right
txdata = create_tx(ingenuityd, options.fromaddresses.split(","), options.to, amount, fee)
sanity_test_fee(ingenuityd, txdata, amount*Decimal("0.01"))
if options.dry_run:
print(txdata)
else:
txid = ingenuityd.sendrawtransaction(txdata)
print(txid)
if __name__ == '__main__':
main()
| 37.708955 | 111 | 0.635167 |
mport *
import getpass
import math
import os
import os.path
import platform
import sys
import time
from jsonrpc import ServiceProxy, json
BASE_FEE=Decimal("0.001")
def check_json_precision():
n = Decimal("20000000.00000003")
satoshis = int(json.loads(json.dumps(float(n)))*1.0e8)
if satoshis != 2000000000000003:
raise RuntimeError("JSON encode/decode loses precision")
def determine_db_dir():
if platform.system() == "Darwin":
return os.path.expanduser("~/Library/Application Support/Ingenuity/")
elif platform.system() == "Windows":
return os.path.join(os.environ['APPDATA'], "Ingenuity")
return os.path.expanduser("~/.ingenuity")
def read_bitcoin_config(dbdir):
from ConfigParser import SafeConfigParser
class FakeSecHead(object):
def __init__(self, fp):
self.fp = fp
self.sechead = '[all]\n'
def readline(self):
if self.sechead:
try: return self.sechead
finally: self.sechead = None
else:
s = self.fp.readline()
if s.find('#') != -1:
s = s[0:s.find('#')].strip() +"\n"
return s
config_parser = SafeConfigParser()
config_parser.readfp(FakeSecHead(open(os.path.join(dbdir, "ingenuity.conf"))))
return dict(config_parser.items("all"))
def connect_JSON(config):
testnet = config.get('testnet', '0')
testnet = (int(testnet) > 0)
if not 'rpcport' in config:
config['rpcport'] = 51475 if testnet else 3117
connect = "http://%s:%s@127.0.0.1:%s"%(config['rpcuser'], config['rpcpassword'], config['rpcport'])
try:
result = ServiceProxy(connect)
if result.getmininginfo()['testnet'] != testnet:
sys.stderr.write("RPC server at "+connect+" testnet setting mismatch\n")
sys.exit(1)
return result
except:
sys.stderr.write("Error connecting to RPC server at "+connect+"\n")
sys.exit(1)
def unlock_wallet(ingenuityd):
info = ingenuityd.getinfo()
if 'unlocked_until' not in info:
return True
t = int(info['unlocked_until'])
if t <= time.time():
try:
passphrase = getpass.getpass("Wallet is locked; enter passphrase: ")
ingenuityd.walletpassphrase(passphrase, 5)
except:
sys.stderr.write("Wrong passphrase\n")
info = ingenuityd.getinfo()
return int(info['unlocked_until']) > time.time()
def list_available(ingenuityd):
address_summary = dict()
address_to_account = dict()
for info in ingenuityd.listreceivedbyaddress(0):
address_to_account[info["address"]] = info["account"]
unspent = ingenuityd.listunspent(0)
for output in unspent:
rawtx = ingenuityd.getrawtransaction(output['txid'], 1)
vout = rawtx["vout"][output['vout']]
pk = vout["scriptPubKey"]
# This code only deals with ordinary pay-to-ingenuity-address
# or pay-to-script-hash outputs right now; anything exotic is ignored.
if pk["type"] != "pubkeyhash" and pk["type"] != "scripthash":
continue
address = pk["addresses"][0]
if address in address_summary:
address_summary[address]["total"] += vout["value"]
address_summary[address]["outputs"].append(output)
else:
address_summary[address] = {
"total" : vout["value"],
"outputs" : [output],
"account" : address_to_account.get(address, "")
}
return address_summary
def select_coins(needed, inputs):
# Feel free to improve this, this is good enough for my simple needs:
outputs = []
have = Decimal("0.0")
n = 0
while have < needed and n < len(inputs):
outputs.append({ "txid":inputs[n]["txid"], "vout":inputs[n]["vout"]})
have += inputs[n]["amount"]
n += 1
return (outputs, have-needed)
def create_tx(ingenuityd, fromaddresses, toaddress, amount, fee):
all_coins = list_available(ingenuityd)
total_available = Decimal("0.0")
needed = amount+fee
potential_inputs = []
for addr in fromaddresses:
if addr not in all_coins:
continue
potential_inputs.extend(all_coins[addr]["outputs"])
total_available += all_coins[addr]["total"]
if total_available < needed:
sys.stderr.write("Error, only %f BTC available, need %f\n"%(total_available, needed));
sys.exit(1)
#
# Note:
# Python's json/jsonrpc modules have inconsistent support for Decimal numbers.
#
outputs = { toaddress : float(amount) }
(inputs, change_amount) = select_coins(needed, potential_inputs)
if change_amount > BASE_FEE: # don't bother with zero or tiny change
change_address = fromaddresses[-1]
if change_address in outputs:
outputs[change_address] += float(change_amount)
else:
outputs[change_address] = float(change_amount)
rawtx = ingenuityd.createrawtransaction(inputs, outputs)
signed_rawtx = ingenuityd.signrawtransaction(rawtx)
if not signed_rawtx["complete"]:
sys.stderr.write("signrawtransaction failed\n")
sys.exit(1)
txdata = signed_rawtx["hex"]
return txdata
def compute_amount_in(ingenuityd, txinfo):
result = Decimal("0.0")
for vin in txinfo['vin']:
in_info = ingenuityd.getrawtransaction(vin['txid'], 1)
vout = in_info['vout'][vin['vout']]
result = result + vout['value']
return result
def compute_amount_out(txinfo):
result = Decimal("0.0")
for vout in txinfo['vout']:
result = result + vout['value']
return result
def sanity_test_fee(ingenuityd, txdata_hex, max_fee):
class FeeError(RuntimeError):
pass
try:
txinfo = ingenuityd.decoderawtransaction(txdata_hex)
total_in = compute_amount_in(ingenuityd, txinfo)
total_out = compute_amount_out(txinfo)
if total_in-total_out > max_fee:
raise FeeError("Rejecting transaction, unreasonable fee of "+str(total_in-total_out))
tx_size = len(txdata_hex)/2
kb = tx_size/1000
if kb > 1 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee transaction, larger than 1000 bytes")
if total_in < 0.01 and fee < BASE_FEE:
raise FeeError("Rejecting no-fee, tiny-amount transaction")
except FeeError as err:
sys.stderr.write((str(err)+"\n"))
sys.exit(1)
def main():
import optparse
parser = optparse.OptionParser(usage="%prog [options]")
parser.add_option("--from", dest="fromaddresses", default=None,
help="addresses to get INGYs from")
parser.add_option("--to", dest="to", default=None,
help="address to get send INGYs to")
parser.add_option("--amount", dest="amount", default=None,
help="amount to send")
parser.add_option("--fee", dest="fee", default="0.0",
help="fee to include")
parser.add_option("--datadir", dest="datadir", default=determine_db_dir(),
help="location of ingenuity.conf file with RPC username/password (default: %default)")
parser.add_option("--testnet", dest="testnet", default=False, action="store_true",
help="Use the test network")
parser.add_option("--dry_run", dest="dry_run", default=False, action="store_true",
help="Don't broadcast the transaction, just create and print the transaction data")
(options, args) = parser.parse_args()
check_json_precision()
config = read_bitcoin_config(options.datadir)
if options.testnet: config['testnet'] = True
ingenuityd = connect_JSON(config)
if options.amount is None:
address_summary = list_available(ingenuityd)
for address,info in address_summary.iteritems():
n_transactions = len(info['outputs'])
if n_transactions > 1:
print("%s %.8f %s (%d transactions)"%(address, info['total'], info['account'], n_transactions))
else:
print("%s %.8f %s"%(address, info['total'], info['account']))
else:
fee = Decimal(options.fee)
amount = Decimal(options.amount)
while unlock_wallet(ingenuityd) == False:
pass # Keep asking for passphrase until they get it right
txdata = create_tx(ingenuityd, options.fromaddresses.split(","), options.to, amount, fee)
sanity_test_fee(ingenuityd, txdata, amount*Decimal("0.01"))
if options.dry_run:
print(txdata)
else:
txid = ingenuityd.sendrawtransaction(txdata)
print(txid)
if __name__ == '__main__':
main()
| true | true |
1c3e285315e8e1bf8ff79b5fe6dafb98ae8c51fa | 9,590 | py | Python | mykits/gallery-dl-wrap.py | fakegit/mo-han-toolbox | 9d5bbc1fe7f12040715d3a0d3f320a1ad617aed8 | [
"MIT"
] | null | null | null | mykits/gallery-dl-wrap.py | fakegit/mo-han-toolbox | 9d5bbc1fe7f12040715d3a0d3f320a1ad617aed8 | [
"MIT"
] | null | null | null | mykits/gallery-dl-wrap.py | fakegit/mo-han-toolbox | 9d5bbc1fe7f12040715d3a0d3f320a1ad617aed8 | [
"MIT"
] | null | null | null | #!/usr/bin/env python3
import os
import webbrowser
from mylib.ext.console_app import *
# if os.name != 'nt':
# raise NotImplementedError('launch new console window')
env_var = os.environ
conf_path = fstk.make_path(env_var['gallery_dl_conf']).strip('"')
base_dir = fstk.make_path(env_var['gallery_dl_base_directory']).strip('"')
pause_on_error = os.environ.get('PAUSEONERROR', 'yes').lower() in {'yes', 'true', '1'}
def _console_pause_nt():
os.system('pause')
def _console_pause():
os.system('read -p "press any key to continue . . ." -srn1')
def _console_new_run_nt(cmd):
os.system(f'start /min {cmd}')
def _console_new_run(cmd):
os.system(f'xterm -iconic -e {cmd}')
if os.name == 'nt':
console_new_run = _console_new_run_nt
console_pause = _console_pause_nt
else:
console_new_run = _console_new_run
console_pause = _console_pause
class GLDLCLIArgs(CLIArgumentsList):
merge_option_nargs = False
def make_options_list(options_dict: dict):
r = []
for k, v in options_dict.items():
if isinstance(v, str):
r.append(f'{k}={v}')
elif isinstance(v, T.Iterable):
il = []
for i in v:
if isinstance(i, str):
il.append(f'"{i}"')
r.append(f'{k}=[{", ".join(il)}]')
return r
def new_gallery_dl_cmd(*args, **kwargs):
cmd = GLDLCLIArgs('gallery-dl', R=3, c=conf_path,
o=f'base-directory={base_dir}', )
return cmd
def get_cookies_path(middle_name):
return fstk.make_path(env_var['cookies_dir'], f'cookies.{middle_name}.txt')
def per_site(args: T.List[str]):
url = args2url(args)
if 'pixiv.net' in url:
args = [*GLDLCLIArgs(ugoira_conv=True,
o=['cookies-update=true',
'filename="{category}.{id}_p{num}.{date:%Y-%m-%d}.{title}.{extension}"',
'directory=["{category} {user[name]} {user[id]}"]']),
*args, url]
elif 'fanbox.cc' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('fanbox'),
o=['cookies-update=true', 'videos=true',
'filename="{category}.{id}_p{num}.{date!S:.10}.{filename}.@{creatorId}.{extension}"',
'directory=["pixiv {user[name]} {user[userId]} {category} {creatorId}"]']),
*args, url]
elif 'twitter.com' in url:
args = [*GLDLCLIArgs(o=['videos=true', 'retweets=false', 'content=true',
'filename="twitter.{tweet_id}_p{num}.{date:%Y-%m-%d}.{filename}.{extension}"',
'directory=["{category} {author[nick]} @{author[name]}"]']),
*args, url]
elif 'danbooru.donmai.us' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('danbooru'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{created_at:.10}.{md5}.'
'{tag_string_character!S:L80/(various)/}.{tag_string_artist!S:L80/(various)/}.'
'{extension}"', ]),
*args, url]
elif 'gelbooru.com' in url:
args = [*GLDLCLIArgs(
cookies=get_cookies_path('gelbooru'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
'{tags_character!S:L80/(various)/}.{tags_artist!S:L80/(various)/}.{extension}"', ]
),
*args, url]
elif 'realbooru.com' in url:
args = [*GLDLCLIArgs(
# cookies=get_cookies_path('realbooru'),
o=[
'cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
# '{tags_character!S:L80/(various)/}.{tags_artist!S:L80/(various)/}.{extension}"',
'{search_tags!S:.80}.{extension}"'
]
),
*args, url]
elif 'rule34.xxx' in url:
args = [*GLDLCLIArgs(
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
'{tags_character!S:L80/(various)/}.{tags_artist!S:L80/(various)/}.{extension}"', ]
),
*args, url]
elif 'chan.sankakucomplex.com' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('sankaku'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
'{tag_string_character!S:L64/(various)/}.{tag_string_artist!S:L80/(various)/}.'
'{extension}"', ]),
*args, url]
elif 'idol.sankakucomplex.com' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('sankaku.idol'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{created_at!S:.10}.{md5}.'
'{tags_idol!S:L80/(various)/}.{extension}"', ]),
*args, url]
elif 'newgrounds.com' in url:
args = [*GLDLCLIArgs(o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["[{user}] {category}"]',
'filename="{category}.{index}.{date!S:.10}.'
'{title}.{artist!S:L80/(various)/}.{extension}"', ]),
*args, url]
elif 'kemono.party' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('kemonoparty'), write_metadata=True,
o=['cookies-update=true', 'videos=true', 'tags=true', 'metadata=true',
'directory=["{category} {service} {username} {user}"]',
'filename="{category}.{service}.{user}.{id}_p{num}.{date!S:.10}.{filename}.'
'{title}.{extension}"', ]),
*args, url]
elif 'nhentai' in url:
args = [*GLDLCLIArgs(o=make_options_list(dict(
directory=['{title} [{category} {gallery_id}]'],
filename='{filename}.{extension}'
))), *args, url]
else:
raise NotImplementedError(url)
return args
def pop_tag_from_args(args):
return fstk.sanitize_xu(re.sub(r'[\[\]]', '', args.pop(0)), reverse=True,
unescape_html=False, decode_url=False, unify_white_space=False)
def args2url(args):
first = args.pop(0)
if first.startswith('/users/') or first.startswith('/artworks/'):
url = 'https://www.pixiv.net' + first
elif first == 'fanbox':
url = f'https://{args.pop(0)}.fanbox.cc'
elif first == 'twitter':
url = f'https://twitter.com/{args.pop(0).lstrip("@")}/media'
elif first == 'danbooru':
url = f'https://danbooru.donmai.us/posts?tags={pop_tag_from_args(args)}'
elif first == 'gelbooru':
url = f'https://gelbooru.com/index.php?page=post&s=list&tags={pop_tag_from_args(args)}'
elif first == 'realbooru':
url = f'https://realbooru.com/index.php?page=post&s=list&tags={pop_tag_from_args(args)}'
elif first == 'sankaku':
x = pop_tag_from_args(args)
if x.isdigit():
url = f'https://chan.sankakucomplex.com/post/show/{x}'
else:
url = f'https://chan.sankakucomplex.com/?tags={x}'
elif first in ('idol', 'idolcomplex'):
x = pop_tag_from_args(args)
if x.isdigit():
url = f'https://idol.sankakucomplex.com/post/show/{x}'
else:
url = f'https://idol.sankakucomplex.com/?tags={x}'
elif first in ('ng', 'newgrounds'):
url = f'https://{pop_tag_from_args(args)}.newgrounds.com/art'
elif first in ('kemono', 'kemonoparty', 'kemono.party'):
url = f'https://kemono.party/{pop_tag_from_args(args)}'
else:
url = first
if url.startswith('https://twitter.com/') and not url.endswith('/media'):
url += '/media'
url = url.replace('chan.sankakucomplex.com/cn/', 'chan.sankakucomplex.com/')
return url
def loop():
cp = ConsolePrinter()
cp.ll()
while 1:
try:
line = input()
if not line.strip():
continue
if line == 'q':
sys.exit(0)
console_new_run(f'{__file__} {line}')
except KeyboardInterrupt:
sys.exit(2)
def main():
args = sys.argv[1:]
ostk.set_console_title(f'{path_basename(__file__)} - {args}')
if not args:
loop()
else:
if args[0] == 'o':
args.pop(0)
url = args2url(args)
return webbrowser.open_new_tab(url)
cmd = new_gallery_dl_cmd() + per_site(args)
try:
p = subprocess.Popen(cmd)
print(p.args)
if p.wait() and pause_on_error:
console_pause()
except KeyboardInterrupt:
sys.exit(2)
if __name__ == '__main__':
main()
| 39.303279 | 117 | 0.525339 |
import os
import webbrowser
from mylib.ext.console_app import *
env_var = os.environ
conf_path = fstk.make_path(env_var['gallery_dl_conf']).strip('"')
base_dir = fstk.make_path(env_var['gallery_dl_base_directory']).strip('"')
pause_on_error = os.environ.get('PAUSEONERROR', 'yes').lower() in {'yes', 'true', '1'}
def _console_pause_nt():
os.system('pause')
def _console_pause():
os.system('read -p "press any key to continue . . ." -srn1')
def _console_new_run_nt(cmd):
os.system(f'start /min {cmd}')
def _console_new_run(cmd):
os.system(f'xterm -iconic -e {cmd}')
if os.name == 'nt':
console_new_run = _console_new_run_nt
console_pause = _console_pause_nt
else:
console_new_run = _console_new_run
console_pause = _console_pause
class GLDLCLIArgs(CLIArgumentsList):
merge_option_nargs = False
def make_options_list(options_dict: dict):
r = []
for k, v in options_dict.items():
if isinstance(v, str):
r.append(f'{k}={v}')
elif isinstance(v, T.Iterable):
il = []
for i in v:
if isinstance(i, str):
il.append(f'"{i}"')
r.append(f'{k}=[{", ".join(il)}]')
return r
def new_gallery_dl_cmd(*args, **kwargs):
cmd = GLDLCLIArgs('gallery-dl', R=3, c=conf_path,
o=f'base-directory={base_dir}', )
return cmd
def get_cookies_path(middle_name):
return fstk.make_path(env_var['cookies_dir'], f'cookies.{middle_name}.txt')
def per_site(args: T.List[str]):
url = args2url(args)
if 'pixiv.net' in url:
args = [*GLDLCLIArgs(ugoira_conv=True,
o=['cookies-update=true',
'filename="{category}.{id}_p{num}.{date:%Y-%m-%d}.{title}.{extension}"',
'directory=["{category} {user[name]} {user[id]}"]']),
*args, url]
elif 'fanbox.cc' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('fanbox'),
o=['cookies-update=true', 'videos=true',
'filename="{category}.{id}_p{num}.{date!S:.10}.{filename}.@{creatorId}.{extension}"',
'directory=["pixiv {user[name]} {user[userId]} {category} {creatorId}"]']),
*args, url]
elif 'twitter.com' in url:
args = [*GLDLCLIArgs(o=['videos=true', 'retweets=false', 'content=true',
'filename="twitter.{tweet_id}_p{num}.{date:%Y-%m-%d}.{filename}.{extension}"',
'directory=["{category} {author[nick]} @{author[name]}"]']),
*args, url]
elif 'danbooru.donmai.us' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('danbooru'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{created_at:.10}.{md5}.'
'{tag_string_character!S:L80/(various)/}.{tag_string_artist!S:L80/(various)/}.'
'{extension}"', ]),
*args, url]
elif 'gelbooru.com' in url:
args = [*GLDLCLIArgs(
cookies=get_cookies_path('gelbooru'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
'{tags_character!S:L80/(various)/}.{tags_artist!S:L80/(various)/}.{extension}"', ]
),
*args, url]
elif 'realbooru.com' in url:
args = [*GLDLCLIArgs(
o=[
'cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
# '{tags_character!S:L80/(various)/}.{tags_artist!S:L80/(various)/}.{extension}"',
'{search_tags!S:.80}.{extension}"'
]
),
*args, url]
elif 'rule34.xxx' in url:
args = [*GLDLCLIArgs(
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
'{tags_character!S:L80/(various)/}.{tags_artist!S:L80/(various)/}.{extension}"', ]
),
*args, url]
elif 'chan.sankakucomplex.com' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('sankaku'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{date!S:.10}.{md5}.'
'{tag_string_character!S:L64/(various)/}.{tag_string_artist!S:L80/(various)/}.'
'{extension}"', ]),
*args, url]
elif 'idol.sankakucomplex.com' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('sankaku.idol'),
o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["{category} {search_tags}"]',
'filename="{category}.{id}.{created_at!S:.10}.{md5}.'
'{tags_idol!S:L80/(various)/}.{extension}"', ]),
*args, url]
elif 'newgrounds.com' in url:
args = [*GLDLCLIArgs(o=['cookies-update=true', 'videos=true', 'tags=true',
'directory=["[{user}] {category}"]',
'filename="{category}.{index}.{date!S:.10}.'
'{title}.{artist!S:L80/(various)/}.{extension}"', ]),
*args, url]
elif 'kemono.party' in url:
args = [*GLDLCLIArgs(cookies=get_cookies_path('kemonoparty'), write_metadata=True,
o=['cookies-update=true', 'videos=true', 'tags=true', 'metadata=true',
'directory=["{category} {service} {username} {user}"]',
'filename="{category}.{service}.{user}.{id}_p{num}.{date!S:.10}.{filename}.'
'{title}.{extension}"', ]),
*args, url]
elif 'nhentai' in url:
args = [*GLDLCLIArgs(o=make_options_list(dict(
directory=['{title} [{category} {gallery_id}]'],
filename='{filename}.{extension}'
))), *args, url]
else:
raise NotImplementedError(url)
return args
def pop_tag_from_args(args):
return fstk.sanitize_xu(re.sub(r'[\[\]]', '', args.pop(0)), reverse=True,
unescape_html=False, decode_url=False, unify_white_space=False)
def args2url(args):
first = args.pop(0)
if first.startswith('/users/') or first.startswith('/artworks/'):
url = 'https://www.pixiv.net' + first
elif first == 'fanbox':
url = f'https://{args.pop(0)}.fanbox.cc'
elif first == 'twitter':
url = f'https://twitter.com/{args.pop(0).lstrip("@")}/media'
elif first == 'danbooru':
url = f'https://danbooru.donmai.us/posts?tags={pop_tag_from_args(args)}'
elif first == 'gelbooru':
url = f'https://gelbooru.com/index.php?page=post&s=list&tags={pop_tag_from_args(args)}'
elif first == 'realbooru':
url = f'https://realbooru.com/index.php?page=post&s=list&tags={pop_tag_from_args(args)}'
elif first == 'sankaku':
x = pop_tag_from_args(args)
if x.isdigit():
url = f'https://chan.sankakucomplex.com/post/show/{x}'
else:
url = f'https://chan.sankakucomplex.com/?tags={x}'
elif first in ('idol', 'idolcomplex'):
x = pop_tag_from_args(args)
if x.isdigit():
url = f'https://idol.sankakucomplex.com/post/show/{x}'
else:
url = f'https://idol.sankakucomplex.com/?tags={x}'
elif first in ('ng', 'newgrounds'):
url = f'https://{pop_tag_from_args(args)}.newgrounds.com/art'
elif first in ('kemono', 'kemonoparty', 'kemono.party'):
url = f'https://kemono.party/{pop_tag_from_args(args)}'
else:
url = first
if url.startswith('https://twitter.com/') and not url.endswith('/media'):
url += '/media'
url = url.replace('chan.sankakucomplex.com/cn/', 'chan.sankakucomplex.com/')
return url
def loop():
cp = ConsolePrinter()
cp.ll()
while 1:
try:
line = input()
if not line.strip():
continue
if line == 'q':
sys.exit(0)
console_new_run(f'{__file__} {line}')
except KeyboardInterrupt:
sys.exit(2)
def main():
args = sys.argv[1:]
ostk.set_console_title(f'{path_basename(__file__)} - {args}')
if not args:
loop()
else:
if args[0] == 'o':
args.pop(0)
url = args2url(args)
return webbrowser.open_new_tab(url)
cmd = new_gallery_dl_cmd() + per_site(args)
try:
p = subprocess.Popen(cmd)
print(p.args)
if p.wait() and pause_on_error:
console_pause()
except KeyboardInterrupt:
sys.exit(2)
if __name__ == '__main__':
main()
| true | true |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.