code
stringlengths 4
1.01M
| language
stringclasses 2
values |
|---|---|
# pylint:disable=line-too-long
import logging
from ...sim_type import SimTypeFunction, SimTypeShort, SimTypeInt, SimTypeLong, SimTypeLongLong, SimTypeDouble, SimTypeFloat, SimTypePointer, SimTypeChar, SimStruct, SimTypeFixedSizeArray, SimTypeBottom, SimUnion, SimTypeBool
from ...calling_conventions import SimCCStdcall, SimCCMicrosoftAMD64
from .. import SIM_PROCEDURES as P
from . import SimLibrary
_l = logging.getLogger(name=__name__)
lib = SimLibrary()
lib.set_default_cc('X86', SimCCStdcall)
lib.set_default_cc('AMD64', SimCCMicrosoftAMD64)
lib.set_library_names("aclui.dll")
prototypes = \
{
#
'CreateSecurityPage': SimTypeFunction([SimTypeBottom(label="ISecurityInformation")], SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), arg_names=["psi"]),
#
'EditSecurity': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi"]),
#
'EditSecurityAdvanced': SimTypeFunction([SimTypePointer(SimTypeInt(signed=True, label="Int"), label="IntPtr", offset=0), SimTypeBottom(label="ISecurityInformation"), SimTypeInt(signed=False, label="SI_PAGE_TYPE")], SimTypeInt(signed=True, label="Int32"), arg_names=["hwndOwner", "psi", "uSIPage"]),
}
lib.set_prototypes(prototypes)
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>RMedia.GetOffset</title>
<link href="css/style.css" rel="stylesheet" type="text/css">
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
</head>
<body bgcolor="#ffffff">
<table border="0" width="100%" bgcolor="#F0F0FF">
<tr>
<td>Concept Framework 2.2 documentation</td>
<td align="right"><a href="index.html">Contents</a> | <a href="index_fun.html">Index</a></td>
</tr>
</table>
<h2><a href="RMedia.html">RMedia</a>.GetOffset</h2>
<table border="0" cellspacing="0" cellpadding="0" width="500" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr bgcolor="#f0f0f0">
<td><i>Name</i></td>
<td><i>Type</i></td>
<td><i>Access</i></td>
<td><i>Version</i></td>
<td><i>Deprecated</i></td>
</tr>
<tr bgcolor="#fafafa">
<td><b>GetOffset</b></td>
<td>function</td>
<td>public</td>
<td>version 1</td>
<td>no</td>
</tr>
</table>
<br />
<b>Prototype:</b><br />
<table bgcolor="#F0F0F0" width="100%" style="border-style:solid;border-width:1px;border-color:#D0D0D0;"><tr><td><b>public function GetOffset()</b></td></tr></table>
<br />
<br />
<b>Description:</b><br />
<table width="100%" bgcolor="#FAFAFF" style="border-style:solid;border-width:1px;border-color:#D0D0D0;">
<tr><td>
TODO: Document this
</td></tr>
</table>
<br />
<b>Returns:</b><br />
// TO DO
<br />
<br />
<!--
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-html40"
alt="Valid HTML 4.0 Transitional" height="31" width="88" border="0"></a>
<a href="http://jigsaw.w3.org/css-validator/">
<img style="border:0;width:88px;height:31px"
src="http://jigsaw.w3.org/css-validator/images/vcss"
alt="Valid CSS!" border="0"/>
</a>
</p>
-->
<table bgcolor="#F0F0F0" width="100%"><tr><td>Documented by Devronium Autodocumenter Alpha, generation time: Sun Jan 27 18:15:28 2013
GMT</td><td align="right">(c)2013 <a href="http://www.devronium.com">Devronium Applications</a></td></tr></table>
</body>
</html>
|
Java
|
require_relative 'model'
Record.where(version: 10606).delete_all
|
Java
|
# -*- coding: utf-8 -*-
"""
femagtools.plot
~~~~~~~~~~~~~~~
Creating plots
"""
import numpy as np
import scipy.interpolate as ip
import logging
try:
import matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
from mpl_toolkits.mplot3d import Axes3D
matplotlibversion = matplotlib.__version__
except ImportError: # ModuleNotFoundError:
matplotlibversion = 0
logger = logging.getLogger("femagtools.plot")
def _create_3d_axis():
"""creates a subplot with 3d projection if one does not already exist"""
from matplotlib.projections import get_projection_class
from matplotlib import _pylab_helpers
create_axis = True
if _pylab_helpers.Gcf.get_active() is not None:
if isinstance(plt.gca(), get_projection_class('3d')):
create_axis = False
if create_axis:
plt.figure()
plt.subplot(111, projection='3d')
def _plot_surface(ax, x, y, z, labels, azim=None):
"""helper function for surface plots"""
# ax.tick_params(axis='both', which='major', pad=-3)
assert np.size(x) > 1 and np.size(y) > 1 and np.size(z) > 1
if azim is not None:
ax.azim = azim
X, Y = np.meshgrid(x, y)
Z = np.ma.masked_invalid(z)
ax.plot_surface(X, Y, Z,
rstride=1, cstride=1,
cmap=cm.viridis, alpha=0.85,
vmin=np.nanmin(z), vmax=np.nanmax(z),
linewidth=0, antialiased=True)
# edgecolor=(0, 0, 0, 0))
# ax.set_xticks(xticks)
# ax.set_yticks(yticks)
# ax.set_zticks(zticks)
ax.set_xlabel(labels[0])
ax.set_ylabel(labels[1])
ax.set_title(labels[2])
# plt.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
def __phasor_plot(ax, up, idq, uxdq):
uref = max(up, uxdq[0])
uxd = uxdq[0]/uref
uxq = uxdq[1]/uref
u1d, u1q = (uxd, 1+uxq)
u1 = np.sqrt(u1d**2 + u1q**2)*uref
i1 = np.linalg.norm(idq)
i1d, i1q = (idq[0]/i1, idq[1]/i1)
qhw = 6 # width arrow head
qhl = 15 # length arrow head
qlw = 2 # line width
qts = 10 # textsize
# Length of the Current adjust to Ud: Initally 0.9, Maier(Oswald) = 0.5
curfac = max(0.9, 1.5*i1q/up)
def label_line(ax, X, Y, U, V, label, color='k', size=8):
"""Add a label to a line, at the proper angle.
Arguments
---------
line : matplotlib.lines.Line2D object,
label : str
x : float
x-position to place center of text (in data coordinated
y : float
y-position to place center of text (in data coordinates)
color : str
size : float
"""
x1, x2 = X, X + U
y1, y2 = Y, Y + V
if y2 == 0:
y2 = y1
if x2 == 0:
x2 = x1
x = (x1 + x2) / 2
y = (y1 + y2) / 2
slope_degrees = np.rad2deg(np.angle(U + V * 1j))
if slope_degrees < 0:
slope_degrees += 180
if 90 < slope_degrees <= 270:
slope_degrees += 180
x_offset = np.sin(np.deg2rad(slope_degrees))
y_offset = np.cos(np.deg2rad(slope_degrees))
bbox_props = dict(boxstyle="Round4, pad=0.1", fc="white", lw=0)
text = ax.annotate(label, xy=(x, y), xytext=(x_offset * 10, y_offset * 8),
textcoords='offset points',
size=size, color=color,
horizontalalignment='center',
verticalalignment='center',
fontfamily='monospace', fontweight='bold', bbox=bbox_props)
text.set_rotation(slope_degrees)
return text
if ax == 0:
ax = plt.gca()
ax.axes.xaxis.set_ticklabels([])
ax.axes.yaxis.set_ticklabels([])
# ax.set_aspect('equal')
ax.set_title(
r'$U_1$={0} V, $I_1$={1} A, $U_p$={2} V'.format(
round(u1, 1), round(i1, 1), round(up, 1)), fontsize=14)
up /= uref
ax.quiver(0, 0, 0, up, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw/2, headlength=qhl/2, headaxislength=qhl/2, width=qlw*2, color='k')
label_line(ax, 0, 0, 0, up, '$U_p$', 'k', qts)
ax.quiver(0, 0, u1d, u1q, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='r')
label_line(ax, 0, 0, u1d, u1q, '$U_1$', 'r', qts)
ax.quiver(0, 1, uxd, 0, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g')
label_line(ax, 0, 1, uxd, 0, '$U_d$', 'g', qts)
ax.quiver(uxd, 1, 0, uxq, angles='xy', scale_units='xy', scale=1, units='dots',
headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='g')
label_line(ax, uxd, 1, 0, uxq, '$U_q$', 'g', qts)
ax.quiver(0, 0, curfac*i1d, curfac*i1q, angles='xy', scale_units='xy', scale=1,
units='dots', headwidth=qhw, headlength=qhl, headaxislength=qhl, width=qlw, color='b')
label_line(ax, 0, 0, curfac*i1d, curfac*i1q, '$I_1$', 'b', qts)
xmin, xmax = (min(0, uxd, i1d), max(0, i1d, uxd))
ymin, ymax = (min(0, i1q, 1-uxq), max(1, i1q, 1+uxq))
ax.set_xlim([xmin-0.1, xmax+0.1])
ax.set_ylim([ymin-0.1, ymax+0.1])
ax.grid(True)
def i1beta_phasor(up, i1, beta, r1, xd, xq, ax=0):
"""creates a phasor plot
up: internal voltage
i1: current
beta: angle i1 vs up [deg]
r1: resistance
xd: reactance in direct axis
xq: reactance in quadrature axis"""
i1d, i1q = (i1*np.sin(beta/180*np.pi), i1*np.cos(beta/180*np.pi))
uxdq = ((r1*i1d - xq*i1q), (r1*i1q + xd*i1d))
__phasor_plot(ax, up, (i1d, i1q), uxdq)
def iqd_phasor(up, iqd, uqd, ax=0):
"""creates a phasor plot
up: internal voltage
iqd: current
uqd: terminal voltage"""
uxdq = (uqd[1]/np.sqrt(2), (uqd[0]/np.sqrt(2)-up))
__phasor_plot(ax, up, (iqd[1]/np.sqrt(2), iqd[0]/np.sqrt(2)), uxdq)
def phasor(bch, ax=0):
"""create phasor plot from bch"""
f1 = bch.machine['p']*bch.dqPar['speed']
w1 = 2*np.pi*f1
xd = w1*bch.dqPar['ld'][-1]
xq = w1*bch.dqPar['lq'][-1]
r1 = bch.machine['r1']
i1beta_phasor(bch.dqPar['up'][-1],
bch.dqPar['i1'][-1], bch.dqPar['beta'][-1],
r1, xd, xq, ax)
def airgap(airgap, ax=0):
"""creates plot of flux density in airgap"""
if ax == 0:
ax = plt.gca()
ax.set_title('Airgap Flux Density [T]')
ax.plot(airgap['pos'], airgap['B'],
label='Max {:4.2f} T'.format(max(airgap['B'])))
ax.plot(airgap['pos'], airgap['B_fft'],
label='Base Ampl {:4.2f} T'.format(airgap['Bamp']))
ax.set_xlabel('Position/°')
ax.legend()
ax.grid(True)
def airgap_fft(airgap, bmin=1e-2, ax=0):
"""plot airgap harmonics"""
unit = 'T'
if ax == 0:
ax = plt.gca()
ax.set_title('Airgap Flux Density Harmonics / {}'.format(unit))
ax.grid(True)
order, fluxdens = np.array([(n, b) for n, b in zip(airgap['nue'],
airgap['B_nue']) if b > bmin]).T
try:
markerline1, stemlines1, _ = ax.stem(order, fluxdens, '-.', basefmt=" ",
use_line_collection=True)
ax.set_xticks(order)
except ValueError: # empty sequence
pass
def torque(pos, torque, ax=0):
"""creates plot from torque vs position"""
k = 20
alpha = np.linspace(pos[0], pos[-1],
k*len(torque))
f = ip.interp1d(pos, torque, kind='quadratic')
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
if ax == 0:
ax = plt.gca()
ax.set_title('Torque / {}'.format(unit))
ax.grid(True)
ax.plot(pos, [scale*t for t in torque], 'go')
ax.plot(alpha, scale*f(alpha))
if np.min(torque) > 0 and np.max(torque) > 0:
ax.set_ylim(bottom=0)
elif np.min(torque) < 0 and np.max(torque) < 0:
ax.set_ylim(top=0)
def torque_fft(order, torque, ax=0):
"""plot torque harmonics"""
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
if ax == 0:
ax = plt.gca()
ax.set_title('Torque Harmonics / {}'.format(unit))
ax.grid(True)
try:
bw = 2.5E-2*max(order)
ax.bar(order, [scale*t for t in torque], width=bw, align='center')
ax.set_xlim(left=-bw/2)
except ValueError: # empty sequence
pass
def force(title, pos, force, xlabel='', ax=0):
"""plot force vs position"""
unit = 'N'
scale = 1
if min(force) < -9.9e3 or max(force) > 9.9e3:
scale = 1e-3
unit = 'kN'
if ax == 0:
ax = plt.gca()
ax.set_title('{} / {}'.format(title, unit))
ax.grid(True)
ax.plot(pos, [scale*f for f in force])
if xlabel:
ax.set_xlabel(xlabel)
if min(force) > 0:
ax.set_ylim(bottom=0)
def force_fft(order, force, ax=0):
"""plot force harmonics"""
unit = 'N'
scale = 1
if min(force) < -9.9e3 or max(force) > 9.9e3:
scale = 1e-3
unit = 'kN'
if ax == 0:
ax = plt.gca()
ax.set_title('Force Harmonics / {}'.format(unit))
ax.grid(True)
try:
bw = 2.5E-2*max(order)
ax.bar(order, [scale*t for t in force], width=bw, align='center')
ax.set_xlim(left=-bw/2)
except ValueError: # empty sequence
pass
def forcedens(title, pos, fdens, ax=0):
"""plot force densities"""
if ax == 0:
ax = plt.gca()
ax.set_title(title)
ax.grid(True)
ax.plot(pos, [1e-3*ft for ft in fdens[0]], label='F tang')
ax.plot(pos, [1e-3*fn for fn in fdens[1]], label='F norm')
ax.legend()
ax.set_xlabel('Pos / deg')
ax.set_ylabel('Force Density / kN/m²')
def forcedens_surface(fdens, ax=0):
if ax == 0:
_create_3d_axis()
ax = plt.gca()
xpos = [p for p in fdens.positions[0]['X']]
ypos = [p['position'] for p in fdens.positions]
z = 1e-3*np.array([p['FN']
for p in fdens.positions])
_plot_surface(ax, xpos, ypos, z,
(u'Rotor pos/°', u'Pos/°', u'F N / kN/m²'))
def forcedens_fft(title, fdens, ax=0):
"""plot force densities FFT
Args:
title: plot title
fdens: force density object
"""
if ax == 0:
ax = plt.axes(projection="3d")
F = 1e-3*fdens.fft()
fmin = 0.2
num_bars = F.shape[0] + 1
_xx, _yy = np.meshgrid(np.arange(1, num_bars),
np.arange(1, num_bars))
z_size = F[F > fmin]
x_pos, y_pos = _xx[F > fmin], _yy[F > fmin]
z_pos = np.zeros_like(z_size)
x_size = 2
y_size = 2
ax.bar3d(x_pos, y_pos, z_pos, x_size, y_size, z_size)
ax.view_init(azim=120)
ax.set_xlim(0, num_bars+1)
ax.set_ylim(0, num_bars+1)
ax.set_title(title)
ax.set_xlabel('M')
ax.set_ylabel('N')
ax.set_zlabel('kN/m²')
def winding_flux(pos, flux, ax=0):
"""plot flux vs position"""
if ax == 0:
ax = plt.gca()
ax.set_title('Winding Flux / Vs')
ax.grid(True)
for p, f in zip(pos, flux):
ax.plot(p, f)
def winding_current(pos, current, ax=0):
"""plot winding currents"""
if ax == 0:
ax = plt.gca()
ax.set_title('Winding Currents / A')
ax.grid(True)
for p, i in zip(pos, current):
ax.plot(p, i)
def voltage(title, pos, voltage, ax=0):
"""plot voltage vs. position"""
if ax == 0:
ax = plt.gca()
ax.set_title('{} / V'.format(title))
ax.grid(True)
ax.plot(pos, voltage)
def voltage_fft(title, order, voltage, ax=0):
"""plot FFT harmonics of voltage"""
if ax == 0:
ax = plt.gca()
ax.set_title('{} / V'.format(title))
ax.grid(True)
if max(order) < 5:
order += [5]
voltage += [0]
try:
bw = 2.5E-2*max(order)
ax.bar(order, voltage, width=bw, align='center')
except ValueError: # empty sequence
pass
def mcv_hbj(mcv, log=True, ax=0):
"""plot H, B, J of mcv dict"""
import femagtools.mcv
MUE0 = 4e-7*np.pi
ji = []
csiz = len(mcv['curve'])
if ax == 0:
ax = plt.gca()
ax.set_title(mcv['name'])
for k, c in enumerate(mcv['curve']):
bh = [(bi, hi*1e-3)
for bi, hi in zip(c['bi'],
c['hi'])]
try:
if csiz == 1 and mcv['ctype'] in (femagtools.mcv.MAGCRV,
femagtools.mcv.ORIENT_CRV):
ji = [b-MUE0*h*1e3 for b, h in bh]
except Exception:
pass
bi, hi = zip(*bh)
label = 'Flux Density'
if csiz > 1:
label = 'Flux Density ({0}°)'.format(mcv.mc1_angle[k])
if log:
ax.semilogx(hi, bi, label=label)
if ji:
ax.semilogx(hi, ji, label='Polarisation')
else:
ax.plot(hi, bi, label=label)
if ji:
ax.plot(hi, ji, label='Polarisation')
ax.set_xlabel('H / kA/m')
ax.set_ylabel('T')
if ji or csiz > 1:
ax.legend(loc='lower right')
ax.grid()
def mcv_muer(mcv, ax=0):
"""plot rel. permeability vs. B of mcv dict"""
MUE0 = 4e-7*np.pi
bi, ur = zip(*[(bx, bx/hx/MUE0)
for bx, hx in zip(mcv['curve'][0]['bi'],
mcv['curve'][0]['hi']) if not hx == 0])
if ax == 0:
ax = plt.gca()
ax.plot(bi, ur)
ax.set_xlabel('B / T')
ax.set_title('rel. Permeability')
ax.grid()
def mtpa(pmrel, i1max, title='', projection='', ax=0):
"""create a line or surface plot with torque and mtpa curve"""
nsamples = 10
i1 = np.linspace(0, i1max, nsamples)
iopt = np.array([pmrel.mtpa(x) for x in i1]).T
iqmax, idmax = pmrel.iqdmax(i1max)
iqmin, idmin = pmrel.iqdmin(i1max)
if projection == '3d':
nsamples = 50
else:
if iqmin == 0:
iqmin = 0.1*iqmax
id = np.linspace(idmin, idmax, nsamples)
iq = np.linspace(iqmin, iqmax, nsamples)
torque_iqd = np.array(
[[pmrel.torque_iqd(x, y)
for y in id] for x in iq])
if projection == '3d':
ax = idq_torque(id, iq, torque_iqd, ax)
ax.plot(iopt[1], iopt[0], iopt[2],
color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format(
np.max(iopt[2][-1])))
else:
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
x, y = np.meshgrid(id, iq)
CS = ax.contour(x, y, torque_iqd, 6, colors='k')
ax.clabel(CS, fmt='%d', inline=1)
ax.set_xlabel('Id/A')
ax.set_ylabel('Iq/A')
ax.plot(iopt[1], iopt[0],
color='red', linewidth=2, label='MTPA: {0:5.0f} Nm'.format(
np.max(iopt[2][-1])))
ax.grid()
if title:
ax.set_title(title)
ax.legend()
def mtpv(pmrel, u1max, i1max, title='', projection='', ax=0):
"""create a line or surface plot with voltage and mtpv curve"""
w1 = pmrel.w2_imax_umax(i1max, u1max)
nsamples = 20
if projection == '3d':
nsamples = 50
iqmax, idmax = pmrel.iqdmax(i1max)
iqmin, idmin = pmrel.iqdmin(i1max)
id = np.linspace(idmin, idmax, nsamples)
iq = np.linspace(iqmin, iqmax, nsamples)
u1_iqd = np.array(
[[np.linalg.norm(pmrel.uqd(w1, iqx, idx))/np.sqrt(2)
for idx in id] for iqx in iq])
u1 = np.mean(u1_iqd)
imtpv = np.array([pmrel.mtpv(wx, u1, i1max)
for wx in np.linspace(w1, 20*w1, nsamples)]).T
if projection == '3d':
torque_iqd = np.array(
[[pmrel.torque_iqd(x, y)
for y in id] for x in iq])
ax = idq_torque(id, iq, torque_iqd, ax)
ax.plot(imtpv[1], imtpv[0], imtpv[2],
color='red', linewidth=2)
else:
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
x, y = np.meshgrid(id, iq)
CS = ax.contour(x, y, u1_iqd, 4, colors='b') # linestyles='dashed')
ax.clabel(CS, fmt='%d', inline=1)
ax.plot(imtpv[1], imtpv[0],
color='red', linewidth=2,
label='MTPV: {0:5.0f} Nm'.format(np.max(imtpv[2])))
# beta = np.arctan2(imtpv[1][0], imtpv[0][0])
# b = np.linspace(beta, 0)
# ax.plot(np.sqrt(2)*i1max*np.sin(b), np.sqrt(2)*i1max*np.cos(b), 'r-')
ax.grid()
ax.legend()
ax.set_xlabel('Id/A')
ax.set_ylabel('Iq/A')
if title:
ax.set_title(title)
def __get_linearForce_title_keys(lf):
if 'force_r' in lf:
return ['Force r', 'Force z'], ['force_r', 'force_z']
return ['Force x', 'Force y'], ['force_x', 'force_y']
def pmrelsim(bch, title=''):
"""creates a plot of a PM/Rel motor simulation"""
cols = 2
rows = 4
if len(bch.flux['1']) > 1:
rows += 1
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[-1]['angle'], bch.torque[-1]['torque'])
plt.subplot(rows, cols, row+1)
tq = list(bch.torque_fft[-1]['torque'])
order = list(bch.torque_fft[-1]['order'])
if order and max(order) < 5:
order += [15]
tq += [0]
torque_fft(order, tq)
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[-1]['angle'], bch.torque[-1]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[-1]['angle'], bch.torque[-1]['force_y'])
row += 3
elif bch.linearForce:
title, keys = __get_linearForce_title_keys(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
flux = [bch.flux[k][-1] for k in bch.flux]
pos = [f['displ'] for f in flux]
winding_flux(pos,
[f['flux_k'] for f in flux])
plt.subplot(rows, cols, row+2)
winding_current(pos,
[f['current_k'] for f in flux])
plt.subplot(rows, cols, row+3)
voltage('Internal Voltage',
bch.flux['1'][-1]['displ'],
bch.flux['1'][-1]['voltage_dpsi'])
plt.subplot(rows, cols, row+4)
try:
voltage_fft('Internal Voltage Harmonics',
bch.flux_fft['1'][-1]['order'],
bch.flux_fft['1'][-1]['voltage'])
except:
pass
if len(bch.flux['1']) > 1:
plt.subplot(rows, cols, row+5)
voltage('No Load Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+6)
try:
voltage_fft('No Load Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
except:
pass
fig.tight_layout(h_pad=3.5)
if title:
fig.subplots_adjust(top=0.92)
def multcal(bch, title=''):
"""creates a plot of a MULT CAL simulation"""
cols = 2
rows = 4
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[-1]['angle'], bch.torque[-1]['torque'])
plt.subplot(rows, cols, row+1)
tq = list(bch.torque_fft[-1]['torque'])
order = list(bch.torque_fft[-1]['order'])
if order and max(order) < 5:
order += [15]
tq += [0]
torque_fft(order, tq)
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[-1]['angle'], bch.torque[-1]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[-1]['angle'], bch.torque[-1]['force_y'])
row += 3
elif bch.linearForce:
title, keys = __get_linearForce_title_keys(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
flux = [bch.flux[k][-1] for k in bch.flux]
pos = [f['displ'] for f in flux]
winding_flux(pos,
[f['flux_k'] for f in flux])
plt.subplot(rows, cols, row+2)
winding_current(pos,
[f['current_k'] for f in flux])
plt.subplot(rows, cols, row+3)
voltage('Internal Voltage',
bch.flux['1'][-1]['displ'],
bch.flux['1'][-1]['voltage_dpsi'])
plt.subplot(rows, cols, row+4)
try:
voltage_fft('Internal Voltage Harmonics',
bch.flux_fft['1'][-1]['order'],
bch.flux_fft['1'][-1]['voltage'])
except:
pass
if len(bch.flux['1']) > 1:
plt.subplot(rows, cols, row+5)
voltage('No Load Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+6)
try:
voltage_fft('No Load Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
except:
pass
fig.tight_layout(h_pad=3.5)
if title:
fig.subplots_adjust(top=0.92)
def fasttorque(bch, title=''):
"""creates a plot of a Fast Torque simulation"""
cols = 2
rows = 4
if len(bch.flux['1']) > 1:
rows += 1
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[-1]['angle'], bch.torque[-1]['torque'])
plt.subplot(rows, cols, row+1)
torque_fft(bch.torque_fft[-1]['order'], bch.torque_fft[-1]['torque'])
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[-1]['angle'], bch.torque[-1]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[-1]['angle'], bch.torque[-1]['force_y'])
row += 3
elif bch.linearForce:
title, keys = __get_linearForce_title_keys(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
flux = [bch.flux[k][-1] for k in bch.flux]
pos = [f['displ'] for f in flux]
winding_flux(pos, [f['flux_k'] for f in flux])
plt.subplot(rows, cols, row+2)
winding_current(pos, [f['current_k'] for f in flux])
plt.subplot(rows, cols, row+3)
voltage('Internal Voltage',
bch.flux['1'][-1]['displ'],
bch.flux['1'][-1]['voltage_dpsi'])
plt.subplot(rows, cols, row+4)
try:
voltage_fft('Internal Voltage Harmonics',
bch.flux_fft['1'][-1]['order'],
bch.flux_fft['1'][-1]['voltage'])
except:
pass
if len(bch.flux['1']) > 1:
plt.subplot(rows, cols, row+5)
voltage('No Load Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+6)
try:
voltage_fft('No Load Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
except:
pass
fig.tight_layout(h_pad=3.5)
if title:
fig.subplots_adjust(top=0.92)
def cogging(bch, title=''):
"""creates a cogging plot"""
cols = 2
rows = 3
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
if bch.torque:
torque(bch.torque[0]['angle'], bch.torque[0]['torque'])
plt.subplot(rows, cols, row+1)
if bch.torque_fft:
torque_fft(bch.torque_fft[0]['order'], bch.torque_fft[0]['torque'])
plt.subplot(rows, cols, row+2)
force('Force Fx',
bch.torque[0]['angle'], bch.torque[0]['force_x'])
plt.subplot(rows, cols, row+3)
force('Force Fy',
bch.torque[0]['angle'], bch.torque[0]['force_y'])
row += 3
elif bch.linearForce:
title, keys = __get_linearForce_title_keys(bch.linearForce[-1])
force(title[0], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[0]], 'Displt. / mm')
plt.subplot(rows, cols, row+1)
force_fft(bch.linearForce_fft[-2]['order'],
bch.linearForce_fft[-2]['force'])
plt.subplot(rows, cols, row+2)
force(title[1], bch.linearForce[-1]['displ'],
bch.linearForce[-1][keys[1]], 'Displt. / mm')
plt.subplot(rows, cols, row+3)
force_fft(bch.linearForce_fft[-1]['order'],
bch.linearForce_fft[-1]['force'])
row += 3
plt.subplot(rows, cols, row+1)
voltage('Voltage',
bch.flux['1'][0]['displ'],
bch.flux['1'][0]['voltage_dpsi'])
plt.subplot(rows, cols, row+2)
voltage_fft('Voltage Harmonics',
bch.flux_fft['1'][0]['order'],
bch.flux_fft['1'][0]['voltage'])
fig.tight_layout(h_pad=2)
if title:
fig.subplots_adjust(top=0.92)
def transientsc(bch, title=''):
"""creates a transient short circuit plot"""
cols = 1
rows = 2
htitle = 1.5 if title else 0
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 3*rows + htitle))
if title:
fig.suptitle(title, fontsize=16)
row = 1
plt.subplot(rows, cols, row)
ax = plt.gca()
ax.set_title('Currents / A')
ax.grid(True)
for i in ('ia', 'ib', 'ic'):
ax.plot(bch.scData['time'], bch.scData[i], label=i)
ax.set_xlabel('Time / s')
ax.legend()
row = 2
plt.subplot(rows, cols, row)
ax = plt.gca()
ax.set_title('Torque / Nm')
ax.grid(True)
ax.plot(bch.scData['time'], bch.scData['torque'])
ax.set_xlabel('Time / s')
fig.tight_layout(h_pad=2)
if title:
fig.subplots_adjust(top=0.92)
def i1beta_torque(i1, beta, torque, title='', ax=0):
"""creates a surface plot of torque vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = 210
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = -60
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
if title:
_plot_surface(ax, i1, beta, scale*np.asarray(torque),
(u'I1/A', u'Beta/°', title),
azim=azim)
else:
_plot_surface(ax, i1, beta, scale*np.asarray(torque),
(u'I1/A', u'Beta/°', u'Torque/{}'.format(unit)),
azim=azim)
def i1beta_ld(i1, beta, ld, ax=0):
"""creates a surface plot of ld vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, i1, beta, np.asarray(ld)*1e3,
(u'I1/A', u'Beta/°', u'Ld/mH'),
azim=60)
def i1beta_lq(i1, beta, lq, ax=0):
"""creates a surface plot of ld vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = 60
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = -120
_plot_surface(ax, i1, beta, np.asarray(lq)*1e3,
(u'I1/A', u'Beta/°', u'Lq/mH'),
azim=azim)
def i1beta_psim(i1, beta, psim, ax=0):
"""creates a surface plot of psim vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, i1, beta, psim,
(u'I1/A', u'Beta/°', u'Psi m/Vs'),
azim=60)
def i1beta_up(i1, beta, up, ax=0):
"""creates a surface plot of up vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, i1, beta, up,
(u'I1/A', u'Beta/°', u'Up/V'),
azim=60)
def i1beta_psid(i1, beta, psid, ax=0):
"""creates a surface plot of psid vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = -60
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = 60
_plot_surface(ax, i1, beta, psid,
(u'I1/A', u'Beta/°', u'Psi d/Vs'),
azim=azim)
def i1beta_psiq(i1, beta, psiq, ax=0):
"""creates a surface plot of psiq vs i1, beta"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
azim = 210
if 0 < np.mean(beta) or -90 > np.mean(beta):
azim = -60
_plot_surface(ax, i1, beta, psiq,
(u'I1/A', u'Beta/°', u'Psi q/Vs'),
azim=azim)
def idq_torque(id, iq, torque, ax=0):
"""creates a surface plot of torque vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
unit = 'Nm'
scale = 1
if np.min(torque) < -9.9e3 or np.max(torque) > 9.9e3:
scale = 1e-3
unit = 'kNm'
_plot_surface(ax, id, iq, scale*np.asarray(torque),
(u'Id/A', u'Iq/A', u'Torque/{}'.format(unit)),
azim=-60)
return ax
def idq_psid(id, iq, psid, ax=0):
"""creates a surface plot of psid vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, psid,
(u'Id/A', u'Iq/A', u'Psi d/Vs'),
azim=210)
def idq_psiq(id, iq, psiq, ax=0):
"""creates a surface plot of psiq vs id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, psiq,
(u'Id/A', u'Iq/A', u'Psi q/Vs'),
azim=210)
def idq_psim(id, iq, psim, ax=0):
"""creates a surface plot of psim vs. id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, psim,
(u'Id/A', u'Iq/A', u'Psi m [Vs]'),
azim=120)
def idq_ld(id, iq, ld, ax=0):
"""creates a surface plot of ld vs. id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, np.asarray(ld)*1e3,
(u'Id/A', u'Iq/A', u'L d/mH'),
azim=120)
def idq_lq(id, iq, lq, ax=0):
"""creates a surface plot of lq vs. id, iq"""
if ax == 0:
_create_3d_axis()
ax = plt.gca()
_plot_surface(ax, id, iq, np.asarray(lq)*1e3,
(u'Id/A', u'Iq/A', u'L q/mH'),
azim=120)
def ldlq(bch):
"""creates the surface plots of a BCH reader object
with a ld-lq identification"""
beta = bch.ldq['beta']
i1 = bch.ldq['i1']
torque = bch.ldq['torque']
ld = np.array(bch.ldq['ld'])
lq = np.array(bch.ldq['lq'])
psid = bch.ldq['psid']
psiq = bch.ldq['psiq']
rows = 3
fig = plt.figure(figsize=(10, 4*rows))
fig.suptitle('Ld-Lq Identification {}'.format(bch.filename), fontsize=16)
fig.add_subplot(rows, 2, 1, projection='3d')
i1beta_torque(i1, beta, torque)
fig.add_subplot(rows, 2, 2, projection='3d')
i1beta_psid(i1, beta, psid)
fig.add_subplot(rows, 2, 3, projection='3d')
i1beta_psiq(i1, beta, psiq)
fig.add_subplot(rows, 2, 4, projection='3d')
try:
i1beta_psim(i1, beta, bch.ldq['psim'])
except:
i1beta_up(i1, beta, bch.ldq['up'])
fig.add_subplot(rows, 2, 5, projection='3d')
i1beta_ld(i1, beta, ld)
fig.add_subplot(rows, 2, 6, projection='3d')
i1beta_lq(i1, beta, lq)
def psidq(bch):
"""creates the surface plots of a BCH reader object
with a psid-psiq identification"""
id = bch.psidq['id']
iq = bch.psidq['iq']
torque = bch.psidq['torque']
ld = np.array(bch.psidq_ldq['ld'])
lq = np.array(bch.psidq_ldq['lq'])
psim = bch.psidq_ldq['psim']
psid = bch.psidq['psid']
psiq = bch.psidq['psiq']
rows = 3
fig = plt.figure(figsize=(10, 4*rows))
fig.suptitle('Psid-Psiq Identification {}'.format(
bch.filename), fontsize=16)
fig.add_subplot(rows, 2, 1, projection='3d')
idq_torque(id, iq, torque)
fig.add_subplot(rows, 2, 2, projection='3d')
idq_psid(id, iq, psid)
fig.add_subplot(rows, 2, 3, projection='3d')
idq_psiq(id, iq, psiq)
fig.add_subplot(rows, 2, 4, projection='3d')
idq_psim(id, iq, psim)
fig.add_subplot(rows, 2, 5, projection='3d')
idq_ld(id, iq, ld)
fig.add_subplot(rows, 2, 6, projection='3d')
idq_lq(id, iq, lq)
def felosses(losses, coeffs, title='', log=True, ax=0):
"""plot iron losses with steinmetz or jordan approximation
Args:
losses: dict with f, B, pfe values
coeffs: list with steinmetz (cw, alpha, beta) or
jordan (cw, alpha, ch, beta, gamma) coeffs
title: title string
log: log scale for x and y axes if True
"""
import femagtools.losscoeffs as lc
if ax == 0:
ax = plt.gca()
fo = losses['fo']
Bo = losses['Bo']
B = plt.np.linspace(0.9*np.min(losses['B']),
1.1*0.9*np.max(losses['B']))
for i, f in enumerate(losses['f']):
pfe = [p for p in np.array(losses['pfe'])[i] if p]
if f > 0:
if len(coeffs) == 5:
ax.plot(B, lc.pfe_jordan(f, B, *coeffs, fo=fo, Bo=Bo))
elif len(coeffs) == 3:
ax.plot(B, lc.pfe_steinmetz(f, B, *coeffs, fo=fo, Bo=Bo))
plt.plot(losses['B'][:len(pfe)], pfe,
marker='o', label="{} Hz".format(f))
ax.set_title("Fe Losses/(W/kg) " + title)
if log:
ax.set_yscale('log')
ax.set_xscale('log')
ax.set_xlabel("Flux Density [T]")
# plt.ylabel("Pfe [W/kg]")
ax.legend()
ax.grid(True)
def spel(isa, with_axis=False, ax=0):
"""plot super elements of I7/ISA7 model
Args:
isa: Isa7 object
"""
from matplotlib.patches import Polygon
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
for se in isa.superelements:
ax.add_patch(Polygon([n.xy
for nc in se.nodechains
for n in nc.nodes],
color=isa.color[se.color], lw=0))
ax.autoscale(enable=True)
if not with_axis:
ax.axis('off')
def mesh(isa, with_axis=False, ax=0):
"""plot mesh of I7/ISA7 model
Args:
isa: Isa7 object
"""
from matplotlib.lines import Line2D
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
for el in isa.elements:
pts = [list(i) for i in zip(*[v.xy for v in el.vertices])]
ax.add_line(Line2D(pts[0], pts[1], color='b', ls='-', lw=0.25))
# for nc in isa.nodechains:
# pts = [list(i) for i in zip(*[(n.x, n.y) for n in nc.nodes])]
# ax.add_line(Line2D(pts[0], pts[1], color="b", ls="-", lw=0.25,
# marker=".", ms="2", mec="None"))
# for nc in isa.nodechains:
# if nc.nodemid is not None:
# plt.plot(*nc.nodemid.xy, "rx")
ax.autoscale(enable=True)
if not with_axis:
ax.axis('off')
def _contour(ax, title, elements, values, label='', isa=None):
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
if ax == 0:
ax = plt.gca()
ax.set_aspect('equal')
ax.set_title(title, fontsize=18)
if isa:
for se in isa.superelements:
ax.add_patch(Polygon([n.xy
for nc in se.nodechains
for n in nc.nodes],
color='gray', alpha=0.1, lw=0))
valid_values = np.logical_not(np.isnan(values))
patches = np.array([Polygon([v.xy for v in e.vertices])
for e in elements])[valid_values]
# , cmap=matplotlib.cm.jet, alpha=0.4)
p = PatchCollection(patches, alpha=1.0, match_original=False)
p.set_array(np.asarray(values)[valid_values])
ax.add_collection(p)
cb = plt.colorbar(p)
for patch in np.array([Polygon([v.xy for v in e.vertices],
fc='white', alpha=1.0)
for e in elements])[np.isnan(values)]:
ax.add_patch(patch)
if label:
cb.set_label(label=label, fontsize=18)
ax.autoscale(enable=True)
ax.axis('off')
def demag(isa, ax=0):
"""plot demag of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
emag = [e for e in isa.elements if e.is_magnet()]
demag = np.array([e.demagnetization(isa.MAGN_TEMPERATURE) for e in emag])
_contour(ax, f'Demagnetization at {isa.MAGN_TEMPERATURE} °C',
emag, demag, '-H / kA/m', isa)
logger.info("Max demagnetization %f", np.max(demag))
def demag_pos(isa, pos, icur=-1, ibeta=-1, ax=0):
"""plot demag of NC/I7/ISA7 model at rotor position
Args:
isa: Isa7/NC object
pos: rotor position in degree
icur: cur amplitude index or last index if -1
ibeta: beta angle index or last index if -1
"""
emag = [e for e in isa.elements if e.is_magnet()]
demag = np.array([isa.demagnetization(e, icur, ibeta)[1]
for e in emag])
for i, x in enumerate(isa.pos_el_fe_induction):
if x >= pos/180*np.pi:
break
hpol = demag[:, i]
hpol[hpol == 0] = np.nan
_contour(ax, f'Demagnetization at Pos. {round(x/np.pi*180)}° ({isa.MAGN_TEMPERATURE} °C)',
emag, hpol, '-H / kA/m', isa)
logger.info("Max demagnetization %f kA/m", np.nanmax(hpol))
def flux_density(isa, subreg=[], ax=0):
"""plot flux density of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
if subreg:
if isinstance(subreg, list):
sr = subreg
else:
sr = [subreg]
elements = [e for s in sr for se in isa.get_subregion(s).elements()
for e in se]
else:
elements = [e for e in isa.elements]
fluxd = np.array([np.linalg.norm(e.flux_density()) for e in elements])
_contour(ax, f'Flux Density T', elements, fluxd)
logger.info("Max flux dens %f", np.max(fluxd))
def loss_density(isa, subreg=[], ax=0):
"""plot loss density of NC/I7/ISA7 model
Args:
isa: Isa7/NC object
"""
if subreg:
if isinstance(subreg, list):
sr = subreg
else:
sr = [subreg]
elements = [e for s in sr for sre in isa.get_subregion(s).elements()
for e in sre]
else:
elements = [e for e in isa.elements]
lossd = np.array([e.loss_density*1e-3 for e in elements])
_contour(ax, 'Loss Density kW/m³', elements, lossd)
def mmf(f, title='', ax=0):
"""plot magnetomotive force (mmf) of winding"""
if ax == 0:
ax = plt.gca()
if title:
ax.set_title(title)
ax.plot(np.array(f['pos'])/np.pi*180, f['mmf'])
ax.plot(np.array(f['pos_fft'])/np.pi*180, f['mmf_fft'])
ax.set_xlabel('Position / Deg')
phi = [f['alfa0']/np.pi*180, f['alfa0']/np.pi*180]
y = [min(f['mmf_fft']), 1.1*max(f['mmf_fft'])]
ax.plot(phi, y, '--')
alfa0 = round(f['alfa0']/np.pi*180, 3)
ax.text(phi[0]/2, y[0]+0.05, f"{alfa0}°",
ha="center", va="bottom")
ax.annotate(f"", xy=(phi[0], y[0]),
xytext=(0, y[0]), arrowprops=dict(arrowstyle="->"))
ax.grid()
def mmf_fft(f, title='', mmfmin=1e-2, ax=0):
"""plot winding mmf harmonics"""
if ax == 0:
ax = plt.gca()
if title:
ax.set_title(title)
else:
ax.set_title('MMF Harmonics')
ax.grid(True)
order, mmf = np.array([(n, m) for n, m in zip(f['nue'],
f['mmf_nue']) if m > mmfmin]).T
try:
markerline1, stemlines1, _ = ax.stem(order, mmf, '-.', basefmt=" ",
use_line_collection=True)
ax.set_xticks(order)
except ValueError: # empty sequence
pass
def zoneplan(wdg, ax=0):
"""plot zone plan of winding wdg"""
from matplotlib.patches import Rectangle
upper, lower = wdg.zoneplan()
Qb = len([n for l in upper for n in l])
from femagtools.windings import coil_color
rh = 0.5
if lower:
yl = rh
ymax = 2*rh + 0.2
else:
yl = 0
ymax = rh + 0.2
if ax == 0:
ax = plt.gca()
ax.axis('off')
ax.set_xlim([-0.5, Qb-0.5])
ax.set_ylim([0, ymax])
ax.set_aspect(Qb/6+0.3)
for i, p in enumerate(upper):
for x in p:
ax.add_patch(Rectangle((abs(x)-1.5, yl), 1, rh,
facecolor=coil_color[i],
edgecolor='white', fill=True))
s = f'+{i+1}' if x > 0 else f'-{i+1}'
ax.text(abs(x)-1, yl+rh/2, s, color='black',
ha="center", va="center")
for i, p in enumerate(lower):
for x in p:
ax.add_patch(Rectangle((abs(x)-1.5, yl-rh), 1, rh,
facecolor=coil_color[i],
edgecolor='white', fill=True))
s = f'+{i+1}' if x > 0 else f'-{i+1}'
ax.text(abs(x)-1, yl-rh/2, s, color='black',
ha="center", va="center")
yu = yl+rh
step = 1 if Qb < 25 else 2
if lower:
yl -= rh
margin = 0.05
ax.text(-0.5, yu+margin, f'Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}',
ha='left', va='bottom', size=15)
for i in range(0, Qb, step):
ax.text(i, yl-margin, f'{i+1}', ha="center", va="top")
def winding_factors(wdg, n=8, ax=0):
"""plot winding factors"""
ax = plt.gca()
ax.set_title(f'Winding factors Q={wdg.Q}, p={wdg.p}, q={round(wdg.q,4)}')
ax.grid(True)
order, kwp, kwd, kw = np.array([(n, k1, k2, k3)
for n, k1, k2, k3 in zip(wdg.kw_order(n),
wdg.kwp(n),
wdg.kwd(n),
wdg.kw(n))]).T
try:
markerline1, stemlines1, _ = ax.stem(order-1, kwp, 'C1:', basefmt=" ",
markerfmt='C1.',
use_line_collection=True, label='Pitch')
markerline2, stemlines2, _ = ax.stem(order+1, kwd, 'C2:', basefmt=" ",
markerfmt='C2.',
use_line_collection=True, label='Distribution')
markerline3, stemlines3, _ = ax.stem(order, kw, 'C0-', basefmt=" ",
markerfmt='C0o',
use_line_collection=True, label='Total')
ax.set_xticks(order)
ax.legend()
except ValueError: # empty sequence
pass
def winding(wdg, ax=0):
"""plot coils of windings wdg"""
from matplotlib.patches import Rectangle
from matplotlib.lines import Line2D
from femagtools.windings import coil_color
coil_len = 25
coil_height = 4
dslot = 8
arrow_head_length = 2
arrow_head_width = 2
if ax == 0:
ax = plt.gca()
z = wdg.zoneplan()
xoff = 0
if z[-1]:
xoff = 0.75
yd = dslot*wdg.yd
mh = 2*coil_height/yd
slots = sorted([abs(n) for m in z[0] for n in m])
smax = slots[-1]*dslot
for n in slots:
x = n*dslot
ax.add_patch(Rectangle((x + dslot/4, 1), dslot /
2, coil_len - 2, fc="lightblue"))
ax.text(x, coil_len / 2,
str(n),
horizontalalignment="center",
verticalalignment="center",
backgroundcolor="white",
bbox=dict(boxstyle='circle,pad=0', fc="white", lw=0))
line_thickness = [0.6, 1.2]
for i, layer in enumerate(z):
b = -xoff if i else xoff
lw = line_thickness[i]
for m, mslots in enumerate(layer):
for k in mslots:
x = abs(k) * dslot + b
xpoints = []
ypoints = []
if (i == 0 and (k > 0 or (k < 0 and wdg.l > 1))):
# first layer, positive dir or neg. dir and 2-layers:
# from right bottom
if x + yd > smax+b:
dx = dslot if yd > dslot else yd/4
xpoints = [x + yd//2 + dx - xoff]
ypoints = [-coil_height + mh*dx]
xpoints += [x + yd//2 - xoff, x, x, x + yd//2-xoff]
ypoints += [-coil_height, 0, coil_len,
coil_len+coil_height]
if x + yd > smax+b:
xpoints += [x + yd//2 + dx - xoff]
ypoints += [coil_len+coil_height - mh*dx]
else:
# from left bottom
if x - yd < 0: # and x - yd/2 > -3*dslot:
dx = dslot if yd > dslot else yd/4
xpoints = [x - yd//2 - dx + xoff]
ypoints = [- coil_height + mh*dx]
xpoints += [x - yd//2+xoff, x, x, x - yd/2+xoff]
ypoints += [-coil_height, 0, coil_len,
coil_len+coil_height]
if x - yd < 0: # and x - yd > -3*dslot:
xpoints += [x - yd//2 - dx + xoff]
ypoints += [coil_len + coil_height - mh*dx]
ax.add_line(Line2D(xpoints, ypoints,
color=coil_color[m], lw=lw))
if k > 0:
h = arrow_head_length
y = coil_len * 0.8
else:
h = -arrow_head_length
y = coil_len * 0.2
ax.arrow(x, y, 0, h,
length_includes_head=True,
head_starts_at_zero=False,
head_length=arrow_head_length,
head_width=arrow_head_width,
fc=coil_color[m], lw=0)
if False: # TODO show winding connections
m = 0
for k in [n*wdg.Q/wdg.p/wdg.m + 1 for n in range(wdg.m)]:
if k < len(slots):
x = k * dslot + b + yd/2 - xoff
ax.add_line(Line2D([x, x],
[-2*coil_height, -coil_height],
color=coil_color[m], lw=lw))
ax.text(x, -2*coil_height+0.5, str(m+1), color=coil_color[m])
m += 1
ax.autoscale(enable=True)
ax.set_axis_off()
def main():
import io
import sys
import argparse
from .__init__ import __version__
from femagtools.bch import Reader
argparser = argparse.ArgumentParser(
description='Read BCH/BATCH/PLT file and create a plot')
argparser.add_argument('filename',
help='name of BCH/BATCH/PLT file')
argparser.add_argument(
"--version",
"-v",
action="version",
version="%(prog)s {}, Python {}".format(__version__, sys.version),
help="display version information",
)
args = argparser.parse_args()
if not matplotlibversion:
sys.exit(0)
if not args.filename:
sys.exit(0)
ext = args.filename.split('.')[-1].upper()
if ext.startswith('MC'):
import femagtools.mcv
mcv = femagtools.mcv.read(sys.argv[1])
if mcv['mc1_type'] in (femagtools.mcv.MAGCRV, femagtools.mcv.ORIENT_CRV):
ncols = 2
else: # Permanent Magnet
ncols = 1
fig, ax = plt.subplots(nrows=1, ncols=ncols, figsize=(10, 6))
if ncols > 1:
plt.subplot(1, 2, 1)
mcv_hbj(mcv)
plt.subplot(1, 2, 2)
mcv_muer(mcv)
else:
mcv_hbj(mcv, log=False)
fig.tight_layout()
fig.subplots_adjust(top=0.94)
plt.show()
return
if ext.startswith('PLT'):
import femagtools.forcedens
fdens = femagtools.forcedens.read(args.filename)
cols = 1
rows = 2
fig, ax = plt.subplots(nrows=rows, ncols=cols,
figsize=(10, 10*rows))
title = '{}, Rotor position {}'.format(
fdens.title, fdens.positions[0]['position'])
pos = fdens.positions[0]['X']
FT_FN = (fdens.positions[0]['FT'],
fdens.positions[0]['FN'])
plt.subplot(rows, cols, 1)
forcedens(title, pos, FT_FN)
title = 'Force Density Harmonics'
plt.subplot(rows, cols, 2)
forcedens_fft(title, fdens)
# fig.tight_layout(h_pad=3.5)
# if title:
# fig.subplots_adjust(top=0.92)
plt.show()
return
bchresults = Reader()
with io.open(args.filename, encoding='latin1', errors='ignore') as f:
bchresults.read(f.readlines())
if (bchresults.type.lower().find(
'pm-synchronous-motor simulation') >= 0 or
bchresults.type.lower().find(
'permanet-magnet-synchronous-motor') >= 0 or
bchresults.type.lower().find(
'simulation pm/universal-motor') >= 0):
pmrelsim(bchresults, bchresults.filename)
elif bchresults.type.lower().find(
'multiple calculation of forces and flux') >= 0:
multcal(bchresults, bchresults.filename)
elif bchresults.type.lower().find('cogging calculation') >= 0:
cogging(bchresults, bchresults.filename)
elif bchresults.type.lower().find('ld-lq-identification') >= 0:
ldlq(bchresults)
elif bchresults.type.lower().find('psid-psiq-identification') >= 0:
psidq(bchresults)
elif bchresults.type.lower().find('fast_torque calculation') >= 0:
fasttorque(bchresults)
elif bchresults.type.lower().find('transient sc') >= 0:
transientsc(bchresults, bchresults.filename)
else:
raise ValueError("BCH type {} not yet supported".format(
bchresults.type))
plt.show()
def characteristics(char, title=''):
fig, axs = plt.subplots(2, 2, figsize=(10, 8), sharex=True)
if title:
fig.suptitle(title)
n = np.array(char['n'])*60
pmech = np.array(char['pmech'])*1e-3
axs[0, 0].plot(n, np.array(char['T']), 'C0-', label='Torque')
axs[0, 0].set_ylabel("Torque / Nm")
axs[0, 0].grid()
axs[0, 0].legend(loc='center left')
ax1 = axs[0, 0].twinx()
ax1.plot(n, pmech, 'C1-', label='P mech')
ax1.set_ylabel("Power / kW")
ax1.legend(loc='lower center')
axs[0, 1].plot(n[1:], np.array(char['u1'][1:]), 'C0-', label='Voltage')
axs[0, 1].set_ylabel("Voltage / V",)
axs[0, 1].grid()
axs[0, 1].legend(loc='center left')
ax2 = axs[0, 1].twinx()
ax2.plot(n[1:], char['cosphi'][1:], 'C1-', label='Cos Phi')
ax2.set_ylabel("Cos Phi")
ax2.legend(loc='lower right')
if 'id' in char:
axs[1, 0].plot(n, np.array(char['id']), label='Id')
if 'iq' in char:
axs[1, 0].plot(n, np.array(char['iq']), label='Iq')
axs[1, 0].plot(n, np.array(char['i1']), label='I1')
axs[1, 0].set_xlabel("Speed / rpm")
axs[1, 0].set_ylabel("Current / A")
axs[1, 0].legend(loc='center left')
if 'beta' in char:
ax3 = axs[1, 0].twinx()
ax3.plot(n, char['beta'], 'C3-', label='Beta')
ax3.set_ylabel("Beta / °")
ax3.legend(loc='center right')
axs[1, 0].grid()
plfe = np.array(char['plfe'])*1e-3
plcu = np.array(char['plcu'])*1e-3
pl = np.array(char['losses'])*1e-3
axs[1, 1].plot(n, plcu, 'C0-', label='Cu Losses')
axs[1, 1].plot(n, plfe, 'C1-', label='Fe Losses')
axs[1, 1].set_ylabel("Losses / kW")
axs[1, 1].legend(loc='center left')
axs[1, 1].grid()
axs[1, 1].set_xlabel("Speed / rpm")
ax4 = axs[1, 1].twinx()
ax4.plot(n[1:-1], char['eta'][1:-1], 'C3-', label="Eta")
ax4.legend(loc='upper center')
ax4.set_ylabel("Efficiency")
fig.tight_layout()
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO,
format='%(asctime)s %(message)s')
main()
|
Java
|
import {Component, NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
@Component({
selector: 'application',
template: `<div>Hello!</div>`
})
export class BasicInlineComponent {}
@NgModule({
imports: [BrowserModule],
declarations: [BasicInlineComponent],
bootstrap: [BasicInlineComponent],
})
export class BasicInlineModule {}
|
Java
|
# -*- coding: utf-8 -*-
from __future__ import (absolute_import, division, print_function)
from . import _wrap_numbers, Symbol, Number, Matrix
def symbols(s):
""" mimics sympy.symbols """
tup = tuple(map(Symbol, s.replace(',', ' ').split()))
if len(tup) == 1:
return tup[0]
else:
return tup
def symarray(prefix, shape):
import numpy as np
arr = np.empty(shape, dtype=object)
for index in np.ndindex(shape):
arr[index] = Symbol('%s_%s' % (
prefix, '_'.join(map(str, index))))
return arr
def lambdify(args, exprs):
"""
lambdify mimics sympy.lambdify
"""
try:
nargs = len(args)
except TypeError:
args = (args,)
nargs = 1
try:
nexprs = len(exprs)
except TypeError:
exprs = (exprs,)
nexprs = 1
@_wrap_numbers
def f(*inp):
if len(inp) != nargs:
raise TypeError("Incorrect number of arguments")
try:
len(inp)
except TypeError:
inp = (inp,)
subsd = dict(zip(args, inp))
return [expr.subs(subsd).evalf() for expr in exprs][
0 if nexprs == 1 else slice(None)]
return f
class Lambdify(object):
"""
Lambdify mimics symengine.Lambdify
"""
def __init__(self, syms, exprs):
self.syms = syms
self.exprs = exprs
def __call__(self, inp, out=None):
inp = tuple(map(Number.make, inp))
subsd = dict(zip(self.syms, inp))
def _eval(expr_iter):
return [expr.subs(subsd).evalf() for expr in expr_iter]
exprs = self.exprs
if out is not None:
try:
out.flat = _eval(exprs.flatten())
except AttributeError:
out.flat = _eval(exprs)
elif isinstance(exprs, Matrix):
import numpy as np
nr, nc = exprs.nrows, exprs.ncols
out = np.empty((nr, nc))
for ri in range(nr):
for ci in range(nc):
out[ri, ci] = exprs._get_element(
ri*nc + ci).subs(subsd).evalf()
return out
# return Matrix(nr, nc, _eval(exprs._get_element(i) for
# i in range(nr*nc)))
elif hasattr(exprs, 'reshape'):
# NumPy like container:
container = exprs.__class__(exprs.shape, dtype=float, order='C')
container.flat = _eval(exprs.flatten())
return container
else:
return _eval(exprs)
|
Java
|
const maps = require('source-map-support');
maps.install({environment: 'node'});
|
Java
|
// Copyright (C) 2015 the V8 project authors. All rights reserved.
// This code is governed by the BSD license found in the LICENSE file.
/*---
esid: sec-array.from
es6id: 22.1.2.1
description: Value returned by mapping function (traversed via iterator)
info: |
[...]
2. If mapfn is undefined, let mapping be false.
3. else
a. If IsCallable(mapfn) is false, throw a TypeError exception.
b. If thisArg was supplied, let T be thisArg; else let T be undefined.
c. Let mapping be true
[...]
6. If usingIterator is not undefined, then
[...]
g. Repeat
[...]
vii. If mapping is true, then
1. Let mappedValue be Call(mapfn, T, «nextValue, k»).
2. If mappedValue is an abrupt completion, return
IteratorClose(iterator, mappedValue).
3. Let mappedValue be mappedValue.[[value]].
features: [Symbol.iterator]
---*/
var thisVals = [];
var nextResult = {
done: false,
value: {}
};
var nextNextResult = {
done: false,
value: {}
};
var firstReturnVal = {};
var secondReturnVal = {};
var mapFn = function(value, idx) {
var returnVal = nextReturnVal;
nextReturnVal = nextNextReturnVal;
nextNextReturnVal = null;
return returnVal;
};
var nextReturnVal = firstReturnVal;
var nextNextReturnVal = secondReturnVal;
var items = {};
var result;
items[Symbol.iterator] = function() {
return {
next: function() {
var result = nextResult;
nextResult = nextNextResult;
nextNextResult = {
done: true
};
return result;
}
};
};
result = Array.from(items, mapFn);
assert.sameValue(result.length, 2);
assert.sameValue(result[0], firstReturnVal);
assert.sameValue(result[1], secondReturnVal);
|
Java
|
package com.mithos.bfg.loop;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelEvent;
/**
* This class is an adapter for {@link OnEvent}. All methods do
* nothing and return true, so you need only implement the methods
* that you need to.
* @author James McMahon
*
*/
public class OnEventAdapter implements OnEvent {
@Override
public boolean keyPressed(KeyEvent e) {
return true;
}
@Override
public boolean keyReleased(KeyEvent e) {
return true;
}
@Override
public boolean mousePressed(MouseEvent e) {
return true;
}
@Override
public boolean mouseMoved(MouseEvent e) {
return true;
}
@Override
public boolean mouseReleased(MouseEvent e) {
return true;
}
@Override
public boolean mouseWheel(MouseWheelEvent e) {
return true;
}
}
|
Java
|
using Esprima.Ast;
namespace Jint.Runtime.Interpreter
{
/// <summary>
/// Per Engine.Evalute() call context.
/// </summary>
internal sealed class EvaluationContext
{
public EvaluationContext(Engine engine, in Completion? resumedCompletion = null)
{
Engine = engine;
DebugMode = engine._isDebugMode;
ResumedCompletion = resumedCompletion ?? default; // TODO later
OperatorOverloadingAllowed = engine.Options.Interop.AllowOperatorOverloading;
}
public Engine Engine { get; }
public Completion ResumedCompletion { get; }
public bool DebugMode { get; }
public Node LastSyntaxNode { get; set; }
public bool OperatorOverloadingAllowed { get; }
}
}
|
Java
|
log.enableAll();
(function(){
function animate() {
requestAnimationFrame(animate);
TWEEN.update();
}
animate();
})();
var transform = getStyleProperty('transform');
var getStyle = ( function() {
var getStyleFn = getComputedStyle ?
function( elem ) {
return getComputedStyle( elem, null );
} :
function( elem ) {
return elem.currentStyle;
};
return function getStyle( elem ) {
var style = getStyleFn( elem );
if ( !style ) {
log.error( 'Style returned ' + style +
'. Are you running this code in a hidden iframe on Firefox? ' +
'See http://bit.ly/getsizebug1' );
}
return style;
};
})();
var cache = {
imgW: 5100,
imgH: 852,
panOffsetX: 0,
ring: 0,
deg: 0,
runDeg: 0,
minOffsetDeg: 8,
rotationOffsetDeg: 0,
onceRotationOffsetDeg: 0,
nowOffset: 0,
len: 0,
touchLock: false,
timer: null
};
var tween1, tween2;
var util = {
setTranslateX: function setTranslateX(el, num) {
el.style[transform] = "translate3d(" + num + "px,0,0)";
}
};
var initPanoramaBox = function initPanoramaBox($el, opts) {
var elH = $el.height();
var elW = $el.width();
var $panoramaBox = $('<div class="panorama-box">' +
'<div class="panorama-item"></div>' +
'<div class="panorama-item"></div>' +
'</div>');
var $panoramaItem = $('.panorama-item', $panoramaBox);
var scal = elH / opts.height;
$panoramaItem.css({
width: opts.width,
height: opts.height
});
$panoramaBox.css({
width: elW / scal,
height: opts.height,
transform: 'scale3d(' + scal + ',' + scal + ',' + scal + ')',
'transform-origin': '0 0'
});
util.setTranslateX($panoramaItem.get(0), 0);
util.setTranslateX($panoramaItem.get(1), -opts.width);
$el.append($panoramaBox);
var offset = function offset(num) {
var width = opts.width;
var num1 = num % opts.width;
var num2;
if (num1 < -width / 2) {
num2 = width + num1 - 2;
} else {
num2 = -width + num1 + 2;
}
util.setTranslateX($panoramaItem.get(0), num1);
util.setTranslateX($panoramaItem.get(1), num2);
};
var run = function (subBox1, subBox2, width) {
return function offset(num) {
num = parseInt(num);
cache.len = num;
var num1 = num % width;
var num2;
if (num1 < -width / 2) {
num2 = width + num1 - 1;
} else {
num2 = -width + num1 + 2;
}
util.setTranslateX(subBox1, num1);
util.setTranslateX(subBox2, num2);
};
};
return run($panoramaItem.get(0), $panoramaItem.get(1), opts.width);
};
var $el = {};
$el.main = $('.wrapper');
var offset = initPanoramaBox($el.main, {
width: cache.imgW,
height: cache.imgH
});
var animOffset = function animOffset(length){
if(tween1){
tween1.stop();
}
tween1 = new TWEEN.Tween({x: cache.len});
tween1.to({x: length}, 600);
tween1.onUpdate(function(){
offset(this.x);
});
tween1.start();
};
var animPanEnd = function animPanEnd(velocityX){
if(tween2){
tween2.stop();
}
var oldLen = cache.len;
var offsetLen ;
tween2 = new TWEEN.Tween({x: cache.len});
tween2.to({x: cache.len - 200 * velocityX}, 600);
tween2.easing(TWEEN.Easing.Cubic.Out);
tween2.onUpdate(function(){
offset(this.x);
offsetLen =oldLen - this.x;
cache.nowOffset += + offsetLen;
cache.panOffsetX += + offsetLen;
});
tween2.start();
};
var initOrientationControl = function () {
FULLTILT.getDeviceOrientation({'type': 'world'})
.then(function (orientationControl) {
var orientationFunc = function orientationFunc() {
var screenAdjustedEvent = orientationControl.getScreenAdjustedEuler();
cache.navDeg = 360 - screenAdjustedEvent.alpha;
if (cache.navDeg > 270 && cache.navOldDeg < 90) {
cache.ring -= 1;
} else if (cache.navDeg < 90 && cache.navOldDeg > 270) {
cache.ring += 1;
}
cache.navOldDeg = cache.navDeg;
cache.oldDeg = cache.deg;
cache.deg = cache.ring * 360 + cache.navDeg;
var offsetDeg = cache.deg - cache.runDeg;
if (!cache.touchLock &&
(Math.abs(offsetDeg) > cache.minOffsetDeg)) {
var length = cache.imgW / 360 * -(cache.deg - cache.rotationOffsetDeg) + cache.panOffsetX;
cache.runDeg = cache.deg;
cache.nowOffset = length;
animOffset(length);
}
};
orientationControl.listen(orientationFunc);
})
.catch(function(e){
log.error(e);
});
};
var initTouch = function(){
var mc = new Hammer.Manager($el.main.get(0));
var pan = new Hammer.Pan();
$el.main.on('touchstart', function (evt) {
if (cache.timer) {
clearTimeout(cache.timer);
cache.timer = null;
}
cache.touchLock = true;
if(tween1){
tween1.stop();
}
if(tween2){
tween2.stop();
}
cache.nowOffset = cache.len;
});
$el.main.on('touchend', function (evt) {
cache.timer = setTimeout(function () {
cache.onceRotationOffsetDeg = cache.deg - cache.runDeg;
cache.runDeg = cache.deg + cache.onceRotationOffsetDeg;
cache.rotationOffsetDeg = cache.rotationOffsetDeg + cache.onceRotationOffsetDeg;
cache.touchLock = false;
}, 1000);
});
mc.add(pan);
mc.on('pan', function (evt) {
offset(cache.nowOffset + evt.deltaX);
});
mc.on('panend', function (evt) {
cache.nowOffset += + evt.deltaX;
cache.panOffsetX += + evt.deltaX;
//animPanEnd(evt.velocityX);
});
};
initTouch();
initOrientationControl();
|
Java
|
// Copyright (c) 2022, WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "WNNetworking/inc/WNReliableNetworkTransportSocket.h"
#include "WNNetworking/inc/WNReliableNetworkListenSocket.h"
#include <netdb.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/uio.h>
namespace wn {
namespace networking {
network_error WNReliableNetworkTransportSocket::connect_to(logging::log* _log,
const containers::string_view& target, uint32_t _connection_type,
uint16_t _port) {
char port_array[11] = {0};
memory::writeuint32(port_array, _port, 10);
addrinfo* result;
addrinfo* ptr;
if (0 != getaddrinfo(target.to_string(m_allocator).c_str(), port_array,
nullptr, &result)) {
_log->log_error("Could not resolve local port ", port_array);
return network_error::could_not_resolve;
}
ptr = result;
for (ptr = result; ptr != nullptr; ptr = ptr->ai_next) {
if ((_connection_type == 0xFFFFFFFF &&
(ptr->ai_family == AF_INET || ptr->ai_family == AF_INET6)) ||
ptr->ai_family == static_cast<int>(_connection_type)) {
m_sock_fd = socket(ptr->ai_family, SOCK_STREAM, IPPROTO_TCP);
if (m_sock_fd == -1) {
continue;
}
if (0 != connect(m_sock_fd, ptr->ai_addr, ptr->ai_addrlen)) {
::close(m_sock_fd);
m_sock_fd = -1;
continue;
}
break;
}
}
freeaddrinfo(result);
if (ptr == nullptr) {
_log->log_error("Could not resolve target ", target, ":", port_array);
return network_error::could_not_resolve;
}
return network_error::ok;
}
network_error WNReliableNetworkTransportSocket::do_send(
const send_ranges& _buffers) {
iovec* send_buffers =
static_cast<iovec*>(WN_STACK_ALLOC(sizeof(iovec) * _buffers.size()));
size_t total_bytes = 0;
for (size_t i = 0; i < _buffers.size(); ++i) {
total_bytes += _buffers[i].size();
send_buffers[i].iov_base =
const_cast<void*>(static_cast<const void*>(_buffers[i].data()));
send_buffers[i].iov_len = _buffers[i].size();
}
using iovlen_type = decltype(msghdr().msg_iovlen);
msghdr header = {nullptr, // msg_name
0, // msg_namelen
send_buffers, // msg_iov
static_cast<iovlen_type>(_buffers.size()), // msg_iovlen
nullptr, // msg_control
0, // msg_controllen
0};
ssize_t num_sent = 0;
if (0 > (num_sent = sendmsg(m_sock_fd, &header, 0))) {
return network_error::could_not_send;
}
if (num_sent != static_cast<ssize_t>(total_bytes)) {
return network_error::could_not_send;
::close(m_sock_fd);
m_sock_fd = -1;
}
return network_error::ok;
}
WNReceiveBuffer WNReliableNetworkTransportSocket::recv_sync() {
WNReceiveBuffer buffer(m_manager->acquire_buffer());
ssize_t received = 0;
if (0 >=
(received = recv(m_sock_fd, buffer.data.data(), buffer.data.size(), 0))) {
return WNReceiveBuffer(network_error::could_not_receive);
}
buffer.data =
containers::contiguous_range<char>(buffer.data.data(), received);
return buffer;
}
} // namespace networking
} // namespace wn
|
Java
|
// Copyright 2010-2014 UT-Battelle, LLC. See LICENSE.txt for more information.
#ifndef EAVL_SCENE_RENDERER_RT_H
#define EAVL_SCENE_RENDERER_RT_H
#include "eavlDataSet.h"
#include "eavlCellSet.h"
#include "eavlColor.h"
#include "eavlColorTable.h"
#include "eavlSceneRenderer.h"
#include "eavlRayTracerMutator.h"
#include "eavlTimer.h"
// ****************************************************************************
// Class: eavlSceneRendererRT
//
// Purpose:
///
///
//
// Programmer: Matt Larsen
// Creation: July 17, 2014
//
// Modifications:
//
// ****************************************************************************
class eavlSceneRendererRT : public eavlSceneRenderer
{
private:
eavlRayTracerMutator* tracer;
bool canRender;
bool setLight;
string ctName;
float pointRadius;
float lineWidth;
public:
eavlSceneRendererRT()
{
tracer = new eavlRayTracerMutator();
tracer->setDepth(1);
// /tracer->setVerbose(true);
tracer->setAOMax(5);
tracer->setOccSamples(4);
tracer->setAO(true);
tracer->setBVHCache(false); // don't use cache
tracer->setCompactOp(false);
tracer->setShadowsOn(true);
setLight = true;
ctName = "";
tracer->setDefaultMaterial(Ka,Kd,Ks);
pointRadius = .1f;
lineWidth = .05f;
}
~eavlSceneRendererRT()
{
delete tracer;
}
void SetPointRadius(float r)
{
if(r > 0) pointRadius = r;
}
void SetBackGroundColor(float r, float g, float b)
{
tracer->setBackgroundColor(r,g,b);
}
virtual void SetActiveColor(eavlColor c)
{
glColor3fv(c.c);
glDisable(GL_TEXTURE_1D);
//cout<<"Setting Active Color"<<endl;
}
virtual void SetActiveColorTable(eavlColorTable ct)
{
eavlSceneRenderer::SetActiveColorTable(ct);
if(ct.GetName()!=ctName)
{
ctName=ct.GetName();
tracer->setColorMap3f(colors,ncolors);
//cout<<"Setting Active Color Table"<<endl;
}
}
virtual void StartScene()
{
//cout<<"Calling Start scene"<<endl;
//tracer->startScene();
}
// ------------------------------------------------------------------------
virtual void StartTriangles()
{
//cout<<"Calling Start Tris"<<endl;
tracer->startScene();
}
virtual void EndTriangles()
{
//cout<<"Calling End Tris"<<endl;
}
virtual void AddTriangleVnVs(double x0, double y0, double z0,
double x1, double y1, double z1,
double x2, double y2, double z2,
double u0, double v0, double w0,
double u1, double v1, double w1,
double u2, double v2, double w2,
double s0, double s1, double s2)
{
tracer->scene->addTriangle(eavlVector3(x0,y0,z0) , eavlVector3(x1,y1,z1), eavlVector3(x2,y2,z2),
eavlVector3(u0,v0,w0) , eavlVector3(u1,v1,w1), eavlVector3(u2,v2,w2),
s0,s1,s2, "default");
}
// ------------------------------------------------------------------------
virtual void StartPoints()
{
tracer->startScene();
}
virtual void EndPoints()
{
//glEnd();
}
virtual void AddPointVs(double x, double y, double z, double r, double s)
{
tracer->scene->addSphere(pointRadius,x,y,z,s,"default");
}
// ------------------------------------------------------------------------
virtual void StartLines()
{
tracer->startScene();
}
virtual void EndLines()
{
//glEnd();
}
virtual void AddLineVs(double x0, double y0, double z0,
double x1, double y1, double z1,
double s0, double s1)
{
//cout<<"ADDING LINE"<<endl;
tracer->scene->addLine(lineWidth, eavlVector3(x0,y0,z0),s0, eavlVector3(x1,y1,z1),s1 );
}
// ------------------------------------------------------------------------
virtual void Render()
{
int tframe = eavlTimer::Start();
tracer->setDefaultMaterial(Ka,Kd,Ks);
tracer->setResolution(view.h,view.w);
float magnitude=tracer->scene->getSceneExtentMagnitude();
tracer->setAOMax(magnitude*.2f);
/*Set up field of view: tracer takes the half FOV in degrees*/
float fovx= 2.f*atan(tan(view.view3d.fov/2.f)*view.w/view.h);
fovx*=180.f/M_PI;
tracer->setFOVy((view.view3d.fov*(180.f/M_PI))/2.f);
tracer->setFOVx( fovx/2.f );
tracer->setZoom(view.view3d.zoom);
eavlVector3 lookdir = (view.view3d.at - view.view3d.from).normalized();
eavlVector3 right = (lookdir % view.view3d.up).normalized();
/* Tracer is a lefty, so this is flip so down is not up */
eavlVector3 up = ( lookdir % right).normalized();
tracer->lookAtPos(view.view3d.at.x,view.view3d.at.y,view.view3d.at.z);
tracer->setCameraPos(view.view3d.from.x,view.view3d.from.y,view.view3d.from.z);
tracer->setUp(up.x,up.y,up.z);
/*Otherwise the light will move with the camera*/
if(eyeLight)//setLight)
{
eavlVector3 minersLight(view.view3d.from.x,view.view3d.from.y,view.view3d.from.z);
minersLight = minersLight+ up*magnitude*.3f;
tracer->setLightParams(minersLight.x,minersLight.y,minersLight.z, 1.f, 1.f, 0.f, 0.f); /*Light params: intensity, constant, linear and exponential coefficeints*/
}
else
{
tracer->setLightParams(Lx, Ly, Lz, 1.f, 1.f , 0.f , 0.f);
}
tracer->Execute();
cerr<<"\nTotal Frame Time : "<<eavlTimer::Stop(tframe,"")<<endl;
}
virtual unsigned char *GetRGBAPixels()
{
return (unsigned char *) tracer->getFrameBuffer()->GetHostArray();
}
virtual float *GetDepthPixels()
{
float proj22=view.P(2,2);
float proj23=view.P(2,3);
float proj32=view.P(3,2);
return (float *) tracer->getDepthBuffer(proj22,proj23,proj32)->GetHostArray();
}
};
#endif
|
Java
|
module WavefrontOBJs
export loadOBJ, loadMTL, load_obj_mtl, numVertices, numFaces
include("geotypes.jl")
include("types.jl")
include("utils.jl")
include("obj.jl")
include("material.jl")
# convenience for loading OBJ and MTL simultaneously
function load_obj_mtl(fpath::ASCIIString)
objpath=string(fpath,".obj")
mtlpath=string(fpath,".mtl")
if !isfile(objpath)
error("OBJ file $objpath not found")
end
if !isfile(mtlpath)
error("MTL file $mtlpath not found")
end
loadOBJ(objpath), loadMTL(mtlpath)
end
end # module
|
Java
|
var _ = require('lodash');
var requireAll = require('require-all');
function load(router, options) {
if (_.isString(options))
options = {dirname: options};
return requireAll(_.defaults(options, {
filter: /(.*Controller)\.js$/,
recursive: true,
resolve: function (Controller) {
var c = new (Controller.__esModule ? Controller.default : Controller)();
c.register && c.register(router);
return c;
}
}));
}
module.exports = load;
|
Java
|
/*
* Copyright (c) 2012, JInterval Project.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
*
* 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.
*/
package net.java.jinterval.ir;
import com.cflex.util.lpSolve.LpConstant;
import com.cflex.util.lpSolve.LpModel;
import com.cflex.util.lpSolve.LpSolver;
import java.util.ArrayList;
//import org.apache.commons.math3.exception.MathIllegalArgumentException;
//TODO: Add exceptions and throws
public class IRPredictor {
private double[][] X;
private double[] Y;
private double[] E;
private boolean dataAreGiven;
// Number of observations
private int ObsNumber;
// Number of variables
private int VarNumber;
// Storage for predictions
private double PredictionMin;
private double PredictionMax;
private double[] PredictionMins;
private double[] PredictionMaxs;
// Last error
int ExitCode;
public IRPredictor(){
ObsNumber = 0;
VarNumber = 0;
dataAreGiven = false;
}
public IRPredictor(double[][] X, double[] Y, double[] E){
setData(X,Y,E);
}
public final void setData(double[][] X, double[] Y, double[] E)
// throws IllegalDimensionException
{
// if(X.length != Y.length || X.length != E.length)
// throw IllegalDimensionException;
this.X=X;
this.Y=Y;
this.E=E;
ObsNumber = X.length;
VarNumber = X[0].length;
dataAreGiven = true;
}
public int getExitCode() {
return ExitCode;
}
private boolean solveLpp(double[] Objective)
// throws IllegalDimensionException
{
if (Objective.length != VarNumber){
// throw IllegalDimensionException;
ExitCode = -1;
return false;
}
try {
// Init LP Solver
LpModel Lpp = new LpModel(0, VarNumber);
// Define LPP
double[] zObjective = new double[VarNumber+1];
System.arraycopy(Objective, 0, zObjective, 1, VarNumber);
Lpp.setObjFn(zObjective);
double[] zX=new double[VarNumber+1];
for (int i=0; i<ObsNumber; i++) {
System.arraycopy(X[i], 0, zX, 1, VarNumber);
Lpp.addConstraint(zX, LpConstant.LE, Y[i]+E[i]);
Lpp.addConstraint(zX, LpConstant.GE, Y[i]-E[i]);
// Solver.add_constraint(Lpp, zX, constant.LE, Y[i]+E[i]);
// Solver.add_constraint(Lpp, zX, constant.GE, Y[i]-E[i]);
}
//Solver.set_minim(Lpp);
//Lpp.setMinimum();
LpSolver Solver = new LpSolver(Lpp);
ExitCode = Solver.solve();
// ExitCode = Solver.solve(Lpp);
switch ( ExitCode ) {
case LpConstant.OPTIMAL:
PredictionMin = Lpp.getBestSolution(0);
break;
case LpConstant.INFEASIBLE:
//throw InfeasibleException
case LpConstant.UNBOUNDED:
//throw UnboundedException
}
// Solver.set_maxim(Lpp);
Lpp.setMaximum();
ExitCode = Solver.solve();
switch ( ExitCode ) {
case LpConstant.OPTIMAL:
PredictionMax = Lpp.getBestSolution(0);
break;
case LpConstant.INFEASIBLE:
//throw InfeasibleException
case LpConstant.UNBOUNDED:
//throw UnboundedException
}
} catch (Exception e){
//e.printStackTrace();
}
return ExitCode == LpConstant.OPTIMAL;
}
public boolean isDataConsistent(){
return solveLpp(X[0]);
}
public void compressData(){
}
public boolean predictAt(double[] x){
return solveLpp(x);
}
public boolean predictAtEveryDataPoint(){
PredictionMins = new double[ObsNumber];
PredictionMaxs = new double[ObsNumber];
boolean Solved = true;
for (int i=0; i<ObsNumber; i++){
Solved = Solved && predictAt(X[i]);
if(!Solved) {
break;
}
PredictionMins[i] = getMin();
PredictionMaxs[i] = getMax();
}
return Solved;
}
public double getMin(){
return PredictionMin;
}
public double getMax(){
return PredictionMax;
}
public double getMin(int i) {
return PredictionMins[i];
}
public double getMax(int i) {
return PredictionMaxs[i];
}
public double[] getMins() {
return PredictionMins;
}
public double[] getMaxs() {
return PredictionMaxs;
}
public double[] getResiduals(){
//Residuals=(y-(vmax+vmin)/2)/beta
double v;
double[] residuals = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
v = (PredictionMins[i]+PredictionMaxs[i])/2;
residuals[i] = (Y[i]-v)/E[i];
}
return residuals;
}
public double[] getLeverages(){
//Leverage=((vmax-vmin)/2)/beta
double v;
double[] leverages = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
v = (PredictionMaxs[i]-PredictionMins[i])/2;
leverages[i] = v/E[i];
}
return leverages;
}
public int[] getBoundary(){
final double EPSILON = 1.0e-6;
ArrayList<Integer> boundary = new ArrayList<Integer>();
double yp, ym, vp, vm;
for (int i=0; i<ObsNumber; i++){
yp = Y[i]+E[i];
vp = PredictionMaxs[i];
ym = Y[i]-E[i];
vm = PredictionMins[i];
if ( Math.abs(yp - vp) < EPSILON || Math.abs(ym - vm) < EPSILON ) {
boundary.add(1);
}
else {
boundary.add(0);
}
}
int[] a_boundary = new int[boundary.size()];
for (int i=0; i<a_boundary.length; i++){
a_boundary[i] = boundary.get(i).intValue();
}
return a_boundary;
}
public int[] getBoundaryNumbers(){
int Count = 0;
int[] boundary = getBoundary();
for (int i=0; i<boundary.length; i++){
if(boundary[i] == 1) {
Count++;
}
}
int j = 0;
int[] numbers = new int[Count];
for (int i=0; i<boundary.length; i++){
if(boundary[i] == 1) {
numbers[j++] = i;
}
}
return numbers;
}
//TODO: Implement getOutliers()
// public int[] getOutliers(){
//
// }
//TODO: Implement getOutliersNumbers()
// public int[] getOutliersNumbers(){
//
// }
public double[] getOutliersWeights(){
double[] outliers = new double[ObsNumber];
for(int i=0; i<ObsNumber; i++) {
outliers[i]=0;
}
try {
LpModel Lpp = new LpModel(0, ObsNumber+VarNumber);
// Build and set objective of LPP
double[] zObjective = new double[ObsNumber+VarNumber+1];
for(int i=1;i<=VarNumber; i++) {
zObjective[i] = 0;
}
for(int i=1;i<=ObsNumber; i++) {
zObjective[VarNumber+i] = 1;
}
Lpp.setObjFn(zObjective);
//Solver.set_minim(Lpp);
// Build and set constraints of LPP
double[] Row = new double[ObsNumber+VarNumber+1];
for (int i=0; i<ObsNumber; i++) {
for (int j=1; j<=VarNumber; j++) {
Row[j]=X[i][j-1];
}
for(int j=1; j<=ObsNumber; j++) {
Row[VarNumber+j] = 0;
}
Row[VarNumber+i+1] = -E[i];
// Solver.add_constraint(Lpp, Row, constant.LE, Y[i]);
Lpp.addConstraint(Row, LpConstant.LE, Y[i]);
Row[VarNumber+i+1] = E[i];
// Solver.add_constraint(Lpp, Row, constant.GE, Y[i]);
Lpp.addConstraint(Row, LpConstant.GE, Y[i]);
for (int j=1; j<=ObsNumber+VarNumber; j++) {
Row[j] = 0;
}
Row[VarNumber+i+1] = 1;
// Solver.add_constraint(Lpp, Row, constant.GE, 1);
Lpp.addConstraint(Row, LpConstant.GE, 1);
}
// Solve LPP and get outliers' weights
LpSolver Solver = new LpSolver(Lpp);
ExitCode = Solver.solve();
for(int i = 0; i < ObsNumber; i++) {
outliers[i] = Lpp.getBestSolution(Lpp.getRows()+VarNumber+i+1);
}
} catch(Exception e){
//e.printStackTrace();
}
return outliers;
}
}
|
Java
|
/*
* Copyright (c) 2016-2016, Roland Bock
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * 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.
*
* 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.
*/
#include "compare.h"
#include "Sample.h"
#include <sqlpp11/sqlpp11.h>
#include <iostream>
namespace
{
auto getTrue() -> std::string
{
MockDb::_serializer_context_t printer = {};
return serialize(sqlpp::value(true), printer).str();
}
auto getFalse() -> std::string
{
MockDb::_serializer_context_t printer = {};
return serialize(sqlpp::value(false), printer).str();
}
} // namespace
int Where(int, char*[])
{
const auto foo = test::TabFoo{};
const auto bar = test::TabBar{};
// Unconditionally
compare(__LINE__, select(foo.omega).from(foo).unconditionally(), "SELECT tab_foo.omega FROM tab_foo");
compare(__LINE__, remove_from(foo).unconditionally(), "DELETE FROM tab_foo");
compare(__LINE__, update(foo).set(foo.omega = 42).unconditionally(), "UPDATE tab_foo SET omega=42");
compare(__LINE__, update(foo).set(foo.omega = foo.omega - -1).unconditionally(),
"UPDATE tab_foo SET omega=(tab_foo.omega - -1)");
compare(__LINE__, where(sqlpp::value(true)), " WHERE " + getTrue());
// Never
compare(__LINE__, where(sqlpp::value(false)), " WHERE " + getFalse());
// Sometimes
compare(__LINE__, where(bar.gamma), " WHERE tab_bar.gamma");
compare(__LINE__, where(bar.gamma == false), " WHERE (tab_bar.gamma=" + getFalse() + ")");
compare(__LINE__, where(bar.beta.is_null()), " WHERE (tab_bar.beta IS NULL)");
compare(__LINE__, where(bar.beta == "SQL"), " WHERE (tab_bar.beta='SQL')");
compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null("SQL"))), " WHERE (tab_bar.beta='SQL')");
compare(__LINE__, where(is_equal_to_or_null(bar.beta, ::sqlpp::value_or_null<sqlpp::text>(::sqlpp::null))),
" WHERE (tab_bar.beta IS NULL)");
#if __cplusplus >= 201703L
// string_view argument
std::string_view sqlString = "SQL";
compare(__LINE__, where(bar.beta == sqlString), " WHERE (tab_bar.beta='SQL')");
#endif
return 0;
}
|
Java
|
#include <iostream>
#include <string>
#include <map>
#include <unistd.h>
#include <utility>
#include <sstream>
#include "./patricia-tree.hpp"
int main(void) {
std::cout << "Add new command!\n";
PatriciaTree<Node<std::string, StringKeySpec>> pt;
std::string command = "command";
std::string key;
while(command != "exit") {
getline(std::cin, key);
pt.insertNode(key, command);
std::cout << pt << "\n";
}
return 0;
}
|
Java
|
# urlwatch
A Puppet module for managing urlwatch and urlwatch cronjobs. This module also supports urlwatch's
built-in filtering features (hooks.py).
# Module usage
Example using Hiera: monitor Trac WikiStart and RecentChanges pages for edits:
classes:
- urlwatch
urlwatch::userconfigs:
john:
hour: '*'
minute: '20'
urls:
trac_wikistart:
url: 'https://trac.example.org/openvpn/wiki/WikiStart'
filter: '[0-9]* (year|month|week|day|hour|minute|second)s{0,1} ago'
trac_recentchanges:
url: 'https://trac.example.org/openvpn/wiki/RecentChanges'
filter: '[0-9]* (year|month|week|day|hour|minute|second)s{0,1} ago'
If you want the email to user 'john' to go to a public address, you can use the
puppetfinland/postfix module:
classes:
- postfix
postfix::mailaliases:
john:
recipient: 'john@example.org'
For details please refer to [init.pp](manifests/init.pp) and [userconfig.pp](manifests/userconfig.pp).
If you want to use the cron functionality in this module you probably want to
set up some mail aliases. One way to do this is to use ::postfix::mailaliases
hash parameter in the Puppet-Finland [postfix module](https://github.com/Puppet-Finland/postfix).
|
Java
|
# Add your own choices here!
fruit = ["apples", "oranges", "pears", "grapes", "blueberries"]
lunch = ["pho", "timmies", "thai", "burgers", "buffet!", "indian", "montanas"]
situations = {"fruit":fruit, "lunch":lunch}
|
Java
|
/***** includes *****/
#include "lfds720_stack_np_internal.h"
/***** private prototypes *****/
static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss,
struct lfds720_misc_validation_info *vi,
enum lfds720_misc_validity *lfds720_stack_np_validity );
/****************************************************************************/
void lfds720_stack_np_query( struct lfds720_stack_np_state *ss,
enum lfds720_stack_np_query query_type,
void *query_input,
void *query_output )
{
LFDS720_PAL_ASSERT( ss != NULL );
// TRD : query_type can be any value in its range
LFDS720_MISC_BARRIER_LOAD;
switch( query_type )
{
case LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT:
{
ptrdiff_t
se;
LFDS720_PAL_ASSERT( query_input == NULL );
LFDS720_PAL_ASSERT( query_output != NULL );
*(lfds720_pal_uint_t *) query_output = 0;
// TRD : count the elements on the stack_np
se = ss->top[LFDS720_MISC_OFFSET];
while( se != 0 )
{
( *(lfds720_pal_uint_t *) query_output )++;
se = LFDS720_MISC_OFFSET_TO_POINTER( ss, se, struct lfds720_stack_np_element )->next;
}
}
break;
case LFDS720_STACK_NP_QUERY_SINGLETHREADED_VALIDATE:
// TRD : query_input can be NULL
LFDS720_PAL_ASSERT( query_output != NULL );
lfds720_stack_np_internal_stack_np_validate( ss, (struct lfds720_misc_validation_info *) query_input, (enum lfds720_misc_validity *) query_output );
break;
}
return;
}
/****************************************************************************/
static void lfds720_stack_np_internal_stack_np_validate( struct lfds720_stack_np_state *ss,
struct lfds720_misc_validation_info *vi,
enum lfds720_misc_validity *lfds720_stack_np_validity )
{
lfds720_pal_uint_t
number_elements = 0;
ptrdiff_t
se_slow,
se_fast;
LFDS720_PAL_ASSERT( ss != NULL );
// TRD : vi can be NULL
LFDS720_PAL_ASSERT( lfds720_stack_np_validity != NULL );
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_VALID;
se_slow = se_fast = ss->top[LFDS720_MISC_OFFSET];
/* TRD : first, check for a loop
we have two pointers
both of which start at the top of the stack_np
we enter a loop
and on each iteration
we advance one pointer by one element
and the other by two
we exit the loop when both pointers are NULL
(have reached the end of the stack_np)
or
if we fast pointer 'sees' the slow pointer
which means we have a loop
*/
if( se_slow != 0 )
do
{
// se_slow = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_slow ) )->next;
se_slow = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_slow, struct lfds720_stack_np_element )->next;
if( se_fast != 0 )
// se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next;
se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next;
if( se_fast != 0 )
// se_fast = ( (struct lfds720_stack_np_element *) ( (void *) ss + se_fast ) )->next;
se_fast = LFDS720_MISC_OFFSET_TO_POINTER( ss, se_fast, struct lfds720_stack_np_element )->next;
}
while( se_slow != 0 and se_fast != se_slow );
if( se_fast != 0 and se_slow != 0 and se_fast == se_slow )
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_LOOP;
/* TRD : now check for expected number of elements
vi can be NULL, in which case we do not check
we know we don't have a loop from our earlier check
*/
if( *lfds720_stack_np_validity == LFDS720_MISC_VALIDITY_VALID and vi != NULL )
{
lfds720_stack_np_query( ss, LFDS720_STACK_NP_QUERY_SINGLETHREADED_GET_COUNT, NULL, (void *) &number_elements );
if( number_elements < vi->min_elements )
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_MISSING_ELEMENTS;
if( number_elements > vi->max_elements )
*lfds720_stack_np_validity = LFDS720_MISC_VALIDITY_INVALID_ADDITIONAL_ELEMENTS;
}
return;
}
|
Java
|
/*
* Copyright (c) 2009-2010 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * 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.
*
* * Neither the name of 'jMonkeyEngine' 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 OWNER 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.
*/
package com.jme3.gde.core.properties;
import com.jme3.gde.core.scene.SceneApplication;
import com.jme3.scene.Spatial;
import java.beans.PropertyEditor;
import java.lang.reflect.InvocationTargetException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.openide.nodes.PropertySupport;
import org.openide.util.Exceptions;
/**
*
* @author normenhansen
*/
public class UserDataProperty extends PropertySupport.ReadWrite<String> {
private Spatial spatial;
private String name = "null";
private int type = 0;
private List<ScenePropertyChangeListener> listeners = new LinkedList<ScenePropertyChangeListener>();
public UserDataProperty(Spatial node, String name) {
super(name, String.class, name, "");
this.spatial = node;
this.name = name;
this.type = getObjectType(node.getUserData(name));
}
public static int getObjectType(Object type) {
if (type instanceof Integer) {
return 0;
} else if (type instanceof Float) {
return 1;
} else if (type instanceof Boolean) {
return 2;
} else if (type instanceof String) {
return 3;
} else if (type instanceof Long) {
return 4;
} else {
Logger.getLogger(UserDataProperty.class.getName()).log(Level.WARNING, "UserData not editable" + (type == null ? "null" : type.getClass()));
return -1;
}
}
@Override
public String getValue() throws IllegalAccessException, InvocationTargetException {
return spatial.getUserData(name) + "";
}
@Override
public void setValue(final String val) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
if (spatial == null) {
return;
}
try {
SceneApplication.getApplication().enqueue(new Callable<Void>() {
public Void call() throws Exception {
switch (type) {
case 0:
spatial.setUserData(name, Integer.parseInt(val));
break;
case 1:
spatial.setUserData(name, Float.parseFloat(val));
break;
case 2:
spatial.setUserData(name, Boolean.parseBoolean(val));
break;
case 3:
spatial.setUserData(name, val);
break;
case 4:
spatial.setUserData(name, Long.parseLong(val));
break;
default:
// throw new UnsupportedOperationException();
}
return null;
}
}).get();
notifyListeners(null, val);
} catch (InterruptedException ex) {
Exceptions.printStackTrace(ex);
} catch (ExecutionException ex) {
Exceptions.printStackTrace(ex);
}
}
@Override
public PropertyEditor getPropertyEditor() {
return null;
// return new AnimationPropertyEditor(control);
}
public void addPropertyChangeListener(ScenePropertyChangeListener listener) {
listeners.add(listener);
}
public void removePropertyChangeListener(ScenePropertyChangeListener listener) {
listeners.remove(listener);
}
private void notifyListeners(Object before, Object after) {
for (Iterator<ScenePropertyChangeListener> it = listeners.iterator(); it.hasNext();) {
ScenePropertyChangeListener propertyChangeListener = it.next();
propertyChangeListener.propertyChange(getName(), before, after);
}
}
}
|
Java
|
#ifndef FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
#define FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
#include "aos/common/controls/polytope.h"
#ifdef INCLUDE_971_INFRASTRUCTURE
#include "frc971/control_loops/drivetrain/drivetrain.q.h"
#endif //INCLUDE_971_INFRASTRUCTURE
#include "frc971/control_loops/state_feedback_loop.h"
#include "frc971/control_loops/drivetrain/drivetrain_config.h"
namespace frc971 {
namespace control_loops {
namespace drivetrain {
class PolyDrivetrain {
public:
enum Gear { HIGH, LOW, SHIFTING_UP, SHIFTING_DOWN };
PolyDrivetrain(const DrivetrainConfig &dt_config);
int controller_index() const { return loop_->controller_index(); }
bool IsInGear(Gear gear) { return gear == LOW || gear == HIGH; }
// Computes the speed of the motor given the hall effect position and the
// speed of the robot.
double MotorSpeed(const constants::ShifterHallEffect &hall_effect,
double shifter_position, double velocity);
// Computes the states of the shifters for the left and right drivetrain sides
// given a requested state.
void UpdateGears(Gear requested_gear);
// Computes the next state of a shifter given the current state and the
// requested state.
Gear UpdateSingleGear(Gear requested_gear, Gear current_gear);
void SetGoal(double wheel, double throttle, bool quickturn, bool highgear);
#ifdef INCLUDE_971_INFRASTRUCTURE
void SetPosition(
const ::frc971::control_loops::DrivetrainQueue::Position *position);
#else //INCLUDE_971_INFRASTRUCTURE
void SetPosition(
const DrivetrainPosition *position);
#endif //INCLUDE_971_INFRASTRUCTURE
double FilterVelocity(double throttle);
double MaxVelocity();
void Update();
#ifdef INCLUDE_971_INFRASTRUCTURE
void SendMotors(::frc971::control_loops::DrivetrainQueue::Output *output);
#else //INCLUDE_971_INFRASTRUCTURE
void SendMotors(DrivetrainOutput *output);
#endif //INCLUDE_971_INFRASTRUCTURE
private:
StateFeedbackLoop<7, 2, 3> kf_;
const ::aos::controls::HPolytope<2> U_Poly_;
::std::unique_ptr<StateFeedbackLoop<2, 2, 2>> loop_;
const double ttrust_;
double wheel_;
double throttle_;
bool quickturn_;
int stale_count_;
double position_time_delta_;
Gear left_gear_;
Gear right_gear_;
#ifdef INCLUDE_971_INFRASTRUCTURE
::frc971::control_loops::DrivetrainQueue::Position last_position_;
::frc971::control_loops::DrivetrainQueue::Position position_;
#else //INCLUDE_971_INFRASTRUCTURE
DrivetrainPosition last_position_;
DrivetrainPosition position_;
#endif //INCLUDE_971_INFRASTRUCTURE
int counter_;
DrivetrainConfig dt_config_;
};
} // namespace drivetrain
} // namespace control_loops
} // namespace frc971
#endif // FRC971_CONTROL_LOOPS_DRIVETRAIN_POLYDRIVETRAIN_H_
|
Java
|
// Copyright (c) 2017 ASMlover. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list ofconditions and the following disclaimer.
//
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materialsprovided with the
// distribution.
//
// 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.
#include "minipy.h"
#include <iostream>
#include <string>
int main(int argc, char* argv[]) {
(void)argc, (void)argv;
const char* prompt = ">>> ";
std::cout << "********** MiniPy 0.1 **********" << std::endl;
std::cout << prompt;
std::string command;
while (std::getline(std::cin, command)) {
if (command.empty())
;
else if (command == "exit")
break;
else
Py_Execute(command);
std::cout << prompt;
}
return 0;
}
|
Java
|
# OCaml does not preserve binary compatibility across compiler releases,
# so when updating it you should ensure that all dependent packages are
# also updated by incrementing their revisions.
#
# Specific packages to pay attention to include:
# - camlp5
# - lablgtk
#
# Applications that really shouldn't break on a compiler update are:
# - coq
# - coccinelle
# - unison
class Ocaml < Formula
desc "General purpose programming language in the ML family"
homepage "https://ocaml.org/"
url "https://caml.inria.fr/pub/distrib/ocaml-4.12/ocaml-4.12.0.tar.xz"
sha256 "39ee9db8dc1e3eb65473dd81a71fabab7cc253dbd7b85e9f9b5b28271319bec3"
license "LGPL-2.1-only" => { with: "OCaml-LGPL-linking-exception" }
head "https://github.com/ocaml/ocaml.git", branch: "trunk"
livecheck do
url "https://ocaml.org/releases/"
regex(/href=.*?v?(\d+(?:\.\d+)+)\.html/i)
end
bottle do
sha256 cellar: :any, arm64_big_sur: "23d4a0ea99bad00b29387d05eef233fb1ce44a71e9031644f984850820f7b1fc"
sha256 cellar: :any, big_sur: "98ee5c246e559e6d494ce7e2927a8a4c11ff3c47c26d7a2da19053ba97aa6158"
sha256 cellar: :any, catalina: "f1f72000415627bc8ea540dffc7fd29c2d7ebc41c70e76b03a994c7e6e746284"
sha256 cellar: :any, mojave: "9badb226c3d92ae196c9a2922c73075eaa45ee90f3c9b06180e29706e95f2f0b"
sha256 cellar: :any_skip_relocation, x86_64_linux: "779e6f230c29dd6ef71ec70e83fea42168c097c720c0a4d4b1ae34ab6e58be74"
end
pour_bottle? do
# The ocaml compilers embed prefix information in weird ways that the default
# brew detection doesn't find, and so needs to be explicitly blacklisted.
reason "The bottle needs to be installed into #{Homebrew::DEFAULT_PREFIX}."
satisfy { HOMEBREW_PREFIX.to_s == Homebrew::DEFAULT_PREFIX }
end
def install
ENV.deparallelize # Builds are not parallel-safe, esp. with many cores
# the ./configure in this package is NOT a GNU autoconf script!
args = %W[
--prefix=#{HOMEBREW_PREFIX}
--enable-debug-runtime
--mandir=#{man}
]
system "./configure", *args
system "make", "world.opt"
system "make", "prefix=#{prefix}", "install"
end
test do
output = shell_output("echo 'let x = 1 ;;' | #{bin}/ocaml 2>&1")
assert_match "val x : int = 1", output
assert_match HOMEBREW_PREFIX.to_s, shell_output("#{bin}/ocamlc -where")
end
end
|
Java
|
class Xonsh < Formula
include Language::Python::Virtualenv
desc "Python-ish, BASHwards-compatible shell language and command prompt"
homepage "https://xon.sh/"
url "https://github.com/xonsh/xonsh/archive/0.8.12.tar.gz"
sha256 "7c51ce752f86e9eaae786a4886a6328ba66e16d91d2b7ba696baa6560a4de4ec"
head "https://github.com/xonsh/xonsh.git"
bottle do
cellar :any_skip_relocation
sha256 "0946b4172b6c6f927f17d9bd12ecb2fdf18f8f086abe0e7841c9dcb3b4c634dc" => :mojave
sha256 "19efaf5ee095bdbfd58e8b32b3629e3f5bd58f3dc3d310e382520554873bfaf6" => :high_sierra
sha256 "188f0659e92c741173d0d9fd14ecfd050abdbc7d82a350cb5e38faf931a65d35" => :sierra
end
depends_on "python"
# Resources based on `pip3 install xonsh[ptk,pygments,proctitle]`
# See https://xon.sh/osx.html#dependencies
resource "prompt_toolkit" do
url "https://files.pythonhosted.org/packages/d9/a5/4b2dd1a05403e34c3ba0d9c00f237c01967c0a4f59a427c9b241129cdfe4/prompt_toolkit-2.0.7.tar.gz"
sha256 "fd17048d8335c1e6d5ee403c3569953ba3eb8555d710bfc548faf0712666ea39"
end
resource "Pygments" do
url "https://files.pythonhosted.org/packages/64/69/413708eaf3a64a6abb8972644e0f20891a55e621c6759e2c3f3891e05d63/Pygments-2.3.1.tar.gz"
sha256 "5ffada19f6203563680669ee7f53b64dabbeb100eb51b61996085e99c03b284a"
end
resource "setproctitle" do
url "https://files.pythonhosted.org/packages/5a/0d/dc0d2234aacba6cf1a729964383e3452c52096dc695581248b548786f2b3/setproctitle-1.1.10.tar.gz"
sha256 "6283b7a58477dd8478fbb9e76defb37968ee4ba47b05ec1c053cb39638bd7398"
end
resource "six" do
url "https://files.pythonhosted.org/packages/dd/bf/4138e7bfb757de47d1f4b6994648ec67a51efe58fa907c1e11e350cddfca/six-1.12.0.tar.gz"
sha256 "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73"
end
resource "wcwidth" do
url "https://files.pythonhosted.org/packages/55/11/e4a2bb08bb450fdbd42cc709dd40de4ed2c472cf0ccb9e64af22279c5495/wcwidth-0.1.7.tar.gz"
sha256 "3df37372226d6e63e1b1e1eda15c594bca98a22d33a23832a90998faa96bc65e"
end
def install
virtualenv_install_with_resources
end
test do
assert_match "4", shell_output("#{bin}/xonsh -c 2+2")
end
end
|
Java
|
/*
* cuda_common.h
*
* Created on: Jul 14, 2014
* Author: shu
*/
#pragma once
#include <cstdio>
#include <stdint.h>
#define CUDA_CHECK_RETURN(value) { \
cudaError_t _m_cudaStat = value; \
if (_m_cudaStat != cudaSuccess) { \
fprintf(stderr, "Error %s at line %d in file %s\n", \
cudaGetErrorString(_m_cudaStat), __LINE__, __FILE__); \
exit(1); \
} }
namespace cuda_common {
typedef struct {
uint32_t query_position;
uint32_t database_position;
} Coordinate;
enum Direction {
kFoward, kReverse,
};
static const size_t kMaxLoadLength = 4;
}
|
Java
|
<?php
namespace Bacharu\Models;
use \Prajna\Objects\VIFMetrics as PrajnaVIFMetrics;
class VIFMetrics extends PrajnaVIFMetrics
{
public function __construct(){}
}
|
Java
|
# Copyright (c) 2015-2018 by the parties listed in the AUTHORS file.
# All rights reserved. Use of this source code is governed by
# a BSD-style license that can be found in the LICENSE file.
"""
sim_det_noise.py implements the noise simulation operator, OpSimNoise.
"""
import numpy as np
from ..op import Operator
from ..ctoast import sim_noise_sim_noise_timestream as sim_noise_timestream
from .. import timing as timing
class OpSimNoise(Operator):
"""
Operator which generates noise timestreams.
This passes through each observation and every process generates data
for its assigned samples. The dictionary for each observation should
include a unique 'ID' used in the random number generation. The
observation dictionary can optionally include a 'global_offset' member
that might be useful if you are splitting observations and want to
enforce reproducibility of a given sample, even when using
different-sized observations.
Args:
out (str): accumulate data to the cache with name <out>_<detector>.
If the named cache objects do not exist, then they are created.
realization (int): if simulating multiple realizations, the realization
index.
component (int): the component index to use for this noise simulation.
noise (str): PSD key in the observation dictionary.
"""
def __init__(self, out='noise', realization=0, component=0, noise='noise',
rate=None, altFFT=False):
# We call the parent class constructor, which currently does nothing
super().__init__()
self._out = out
self._oversample = 2
self._realization = realization
self._component = component
self._noisekey = noise
self._rate = rate
self._altfft = altFFT
def exec(self, data):
"""
Generate noise timestreams.
This iterates over all observations and detectors and generates
the noise timestreams based on the noise object for the current
observation.
Args:
data (toast.Data): The distributed data.
Raises:
KeyError: If an observation in data does not have noise
object defined under given key.
RuntimeError: If observations are not split into chunks.
"""
autotimer = timing.auto_timer(type(self).__name__)
for obs in data.obs:
obsindx = 0
if 'id' in obs:
obsindx = obs['id']
else:
print("Warning: observation ID is not set, using zero!")
telescope = 0
if 'telescope' in obs:
telescope = obs['telescope_id']
global_offset = 0
if 'global_offset' in obs:
global_offset = obs['global_offset']
tod = obs['tod']
if self._noisekey in obs:
nse = obs[self._noisekey]
else:
raise KeyError('Observation does not contain noise under '
'"{}"'.format(self._noisekey))
if tod.local_chunks is None:
raise RuntimeError('noise simulation for uniform distributed '
'samples not implemented')
# eventually we'll redistribute, to allow long correlations...
if self._rate is None:
times = tod.local_times()
else:
times = None
# Iterate over each chunk.
chunk_first = tod.local_samples[0]
for curchunk in range(tod.local_chunks[1]):
chunk_first += self.simulate_chunk(
tod=tod, nse=nse,
curchunk=curchunk, chunk_first=chunk_first,
obsindx=obsindx, times=times,
telescope=telescope, global_offset=global_offset)
return
def simulate_chunk(self, *, tod, nse, curchunk, chunk_first,
obsindx, times, telescope, global_offset):
"""
Simulate one chunk of noise for all detectors.
Args:
tod (toast.tod.TOD): TOD object for the observation.
nse (toast.tod.Noise): Noise object for the observation.
curchunk (int): The local index of the chunk to simulate.
chunk_first (int): First global sample index of the chunk.
obsindx (int): Observation index for random number stream.
times (int): Timestamps for effective sample rate.
telescope (int): Telescope index for random number stream.
global_offset (int): Global offset for random number stream.
Returns:
chunk_samp (int): Number of simulated samples
"""
autotimer = timing.auto_timer(type(self).__name__)
chunk_samp = tod.total_chunks[tod.local_chunks[0] + curchunk]
local_offset = chunk_first - tod.local_samples[0]
if self._rate is None:
# compute effective sample rate
rate = 1 / np.median(np.diff(
times[local_offset : local_offset+chunk_samp]))
else:
rate = self._rate
for key in nse.keys:
# Check if noise matching this PSD key is needed
weight = 0.
for det in tod.local_dets:
weight += np.abs(nse.weight(det, key))
if weight == 0:
continue
# Simulate the noise matching this key
#nsedata = sim_noise_timestream(
# self._realization, telescope, self._component, obsindx,
# nse.index(key), rate, chunk_first+global_offset, chunk_samp,
# self._oversample, nse.freq(key), nse.psd(key),
# self._altfft)[0]
nsedata = sim_noise_timestream(
self._realization, telescope, self._component, obsindx,
nse.index(key), rate, chunk_first+global_offset, chunk_samp,
self._oversample, nse.freq(key), nse.psd(key))
# Add the noise to all detectors that have nonzero weights
for det in tod.local_dets:
weight = nse.weight(det, key)
if weight == 0:
continue
cachename = '{}_{}'.format(self._out, det)
if tod.cache.exists(cachename):
ref = tod.cache.reference(cachename)
else:
ref = tod.cache.create(cachename, np.float64,
(tod.local_samples[1], ))
ref[local_offset : local_offset+chunk_samp] += weight*nsedata
del ref
return chunk_samp
|
Java
|
(function(){
var slides = [
{title: 'Работы для отдела Клиентского сервиса и сапорта ФС\nТикетная админка, админка массовых сбоев',
works: [
{img: 'i/works/ticket-admin.png', description:
'<div class="presentation_mb10"><strong>Тикетная админка</strong></div>' +
'<div class="presentation_mb10">Через эту админку сотрудники сапорта работают с обращениями пользователей соц. сети. Мною была реализована вся верстка раздела и код на js.</div>' +
'<div class="presentation_mb10">Особенности:</div>' +
'<ul class="presentation-list">' +
'<li>Интерфейс занимают всю высоту экрана монитора - резиновый по вертикали (На странице могут быть три внутреннии области со скролом );</li>' +
'<li>Автоподгрузка новых тикетов;</li>' +
'<li>Большое число кастомных элементов управления.</li>' +
'</ul>'
},
{img: 'i/works/ticket-admin2.png', description:
'<div class="presentation_mb10"><strong>Админка массовых сбоев</strong></div>' +
'<div class="presentation_mb10">Инструмент взаимодействия сотрудников сапорта и тестеровщиков. При наличие однотипных обращений пользователей, их тикеты групируются в массовый сбой. Который попадает к тестировщикам в виде таска в редмайн для исследования.</div>'
},
{img: 'i/works/ticket-admin3.png', description: 'Диалог просмотра массового сбоя.'},
{img: 'i/works/ticket-admin4.png', description: 'Пример реализации кастомного выпадающего списка.'},
]
},{title: 'Отдел модерации \nПопапы жалоб, страница заблокированного пользователя',
works: [
{img: 'i/works/complaint_popup.png', description:
'<div class="presentation_mb10"><strong>Попап подачи жалоб на пользователя</strong></div>' +
'<div class="">Мною была реализована вся frontend часть - верстка и код на js.</div>'
},{img: 'i/works/abusePopups.jpg', description:
'<div class="">Реализовано несколько кейсов с последовательной навигацией.</div>'
},{img: 'i/works/complaint_popup1.png', description:
'<div class="">Содержимое попапа - вопросник с готовыми ответами и возможностью отправить расширенное описание.</div>'
},
{img: 'i/works/abuse_form.jpg', description:
'Различные варианты попапов жалоб на нарушения со стороны пользователей. Попапы показываются на странице пользователя.'},
{img: 'i/works/abuse_page.jpg', description:
'Страница заблокированного пользователя. Реализована в нескольких вариантах для удаленного пользователя и расширенной для сотрудников Фотостраны. Мною была реализована верстка (html/php).'},
]
},{title: 'Раздел помощи (FAQ)',
works: [
{img: 'i/works/faq1.png', description:
'<div class="presentation_mb10">В разделе помощи я занимался поддержкой старого кода, правил баги. Поэтому там моя верстка присутствует только фрагментами. К примеру этот опросник сверстан мной. Весь hover эффект при выборе количества звезд реализован только на css.</div>' +
'<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/support/feedback/ask/" target="_blank">http://fotostrana.ru/support/feedback/ask/</a></div>'},
]
},{title: 'Раздел "Мои финансы"',
works: [
{img: 'i/works/finroom.png', description:
'<div class="presentation_mb10"><strong>Раздел "Мои финансы" страницы пользователя</strong></div>' +
'<div class="presentation_mb10">Мною была реализована верстка и необходимый код на js.</div>' +
'<div class="presentation_mb10">Раздел располагается по ссылке <a href="http://fotostrana.ru/finance/index/" target="_blank">http://fotostrana.ru/finance/index/</a></div>'
},
{img: 'i/works/finroom2.png', description:
'<div class="presentation_mb10">Для страницы было реализовано много различных блоков показываемые разным сегментам пользовательской аудитории.</div>'},
{img: 'i/works/finroom3.png', description: 'Так же мною были сверстаны различные попапы сопутсвующих премиальных услуг, доступные из этого раздела.'},
{img: 'i/works/autopay1.png', description: 'Попап услуги «Автоплатеж»'},
{img: 'i/works/fotocheck.png', description: 'СМС информирование'},
{img: 'i/works/finroom4.png', description: ''},
]
},{title: 'Финансовый попап \nПопап пополнения счета пользователя',
works: [
{img: 'i/works/finpopup1.png', description:
'<div class="presentation_mb10">Попап с большим количеством переходов и кастомными элементами управления.</div>' +
'<div class="presentation_mb10">Мною была сделана необходимая верстка и js код.</div>'
},
{img: 'i/works/finpopup2.png', description:
'<div class="presentation_mb10">Из сложных деталей интерфейса:</div>' +
'<ul class="presentation-list">' +
'<li>"резиновые" кнопки ввода необходимой суммы Фотомани, с возможностью указать произвольную сумму;</li>' +
'<li>контроль за вводом и валидация пользовательских данных.</li>' +
'</ul>'
},
{img: 'i/works/finpopup3.png', description: ''},
]
},{title: 'Сервис "Я модератор"',
works: [
{img: 'i/works/imoderator1.jpg', description:
'<div class="presentation_mb10"><strong>Сервис "Я модератор"</strong> - пользователям за вознаграждение передается часть модерируемого контента.</div>' +
'<div class="">Мною была выполнена вся верстка и весь js код. Из сложных деталей интерфеса - флип часы, реализованные с использованием css3 animation.</div>'
},
{img: 'i/works/imoderator2.jpg', description:
'<div class="presentation_mb10">В приложении реализовано несколько режимов модерации, в том числе и полно экранный режим (резиновый, скрывающий стандартный лэйаут страниц соц. сети).</div>' +
'<div class="">Так же в приложении реализованы инструменты для мотивации "качественной" оценки фотографий пользователями. Используются тестовые проверочные изображения, принудительная отправка в режим обучения и поиск дубликатов изображений в Google/Yandex.</div>'
},
]
},{title: 'Сервис "Голосование"',
works: [
{img: 'i/works/contest.jpg', description:
'<div class="presentation_mb10"><strong>Сервис "Голосование"</strong> - один из основных по доходности сервисов Фотостраны с большой аудиторией</div>' +
'<div class="presentation_mb10">В этом сервисе, я занимался поддержкой старого кода и версткой скидочных акций и сезонных мероприятий по активизации пользовательской активности приуроченные к праздникам, мероприятиям (Новый год, Олимпийские игры, 8-е марта, день всех влюбленных, 23 февраля, 12 апреля и др.)</div>' +
'<div class="presentation_mb10">Так же мною был переделан механизм рендеринга фотостены.</div>' +
'<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/" target="_blank">www.fotostrana.ru/contest/</a></div>'
},
{img: 'i/works/contest1.jpg', description:
''},
]
},{title: 'Игровой сервис "Битва кланов"',
works: [
{img: 'i/works/clan1.jpg', description:
'<div class="presentation_mb10"><strong>Игровой сервис "Битва Кланов"</strong> - игровой под сервис голосования. Игра в форме квеста.</div>' +
'<div>В этом сервисе я делал верстку и js код. Много кейсов, много попапов, много backbon-а. Используется sass, require.js, backbone.</div>'
},
{img: 'i/works/clan2.jpg', description: '<div class="">В сервис можно перейти по ссылке <a href="http://www.fotostrana.ru/contest/clan2/" target="_blank">www.fotostrana.ru/contest/clan2/</a></div>'},
{img: 'i/works/clan4.jpg', description: 'В сервисе много сложных интерфейсных решений, как на пример поле ввода сообщения в чат. Реализовано ограничение на длину вводимого сообщения и авторесайз высоты textarea.'},
{img: 'i/works/clan3.jpg', description: ''},
]
},{title: 'Сервис "Элитное голосование"',
works: [
{img: 'i/works/elite1.jpg', description: '<div class="presentation_mb10"><strong>Игровой сервис "Элитное голосование"</strong> - игровой под сервис голосования, доступный несколько дней в месяце для активных участников основного голосования.</div>' +
'<div>В этом сервисе я делал верстку и js код. Внешнее оформление переделывалось мною к каждому запуску сервиса.</div>'},
{img: 'i/works/elite2.jpg', description: ''},
]
},{title: 'Сервис "Люди"\nДейтинговый сервис Фотостраны',
works: [
{img: 'i/works/people1.jpg', description:
'<div class="presentation_mb10"><strong>Дейтинговый сервис "Люди"</strong> - на протяжении полу года поддерживал фронтенд сервиса - исправлял баги, верстал рекламные банеры и попапы.</div>' +
'<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/people/" target="_blank">fotostrana.ru/people/</a></div>'},
{img: 'i/works/people2.jpg', description: ''},
]
},{title: 'Сообщества и пиновый интерфейс',
works: [
{img: 'i/works/community1.jpg', description:
'<div class="presentation_mb10">Некоторое время работал над версткой сообществ и пиновым интерфейсом. Концепция пинов была позаимствована у другого сервиса Pinterest. Занимался проектом начиная с первого прототипа и до предрелизной подготовкой.</div>' +
'<div class="">В сервис можно перейти по ссылке <a href="http://fotostrana.ru/public/" target="_blank">fotostrana.ru/public/</a></div>'},
]
},{title: 'Сайт http://www.blik-cleaning.ru/',
works: [
{img: 'i/works/cleaning.jpg', description:
'<div class="presentation_mb10"><strong>Разработка сайта клининговой компании</strong></div>' +
'<div>Сайт сделан на CMS WordPress с оригинальной темой. </div>'},
{img: 'i/works/cleaning1.jpg', description: ''},
]
},{title: 'Сайт http://www.promalp.name/',
works: [
{img: 'i/works/promalp1.jpg', description:
'<div class="presentation_mb10"><strong>Сайт компании занимающейся промышленным альпинизмом.</strong></div>' +
'<div>Сайт сделан на node.js (express). Полностью реализован мною.</div>'},
{img: 'i/works/promalp2.jpg', description: 'Страница с портфолио.'},
{img: 'i/works/promalp3.jpg', description: 'Форма заявки.'},
]
},{title: 'Расширение для браузера chrome Netmarks',
works: [
{img: 'i/works/netmarks.jpg', description:
'<div class="presentation_mb10"><strong>Chrome extension "NetMarks"</strong></div>' +
'<div class="presentation_mb10">Расширение для удобной работы с браузерными закладками в виде выпадающего меню.</div>' +
'<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/netmarks/boepmphdpbdnficfifejnkejlljcefjb" target="_blank">Chrome store</a></div>'
},
]
},{title: 'Приложение для браузера chrome Deposit.calc',
works: [
{img: 'i/works/depcalc1.jpg', description:
'<div class="presentation_mb10"><strong>Deposit.calc</strong></div>' +
'<div class="presentation_mb10">Приложение позволяющее расчитать доход по вкладу с пополнениями. Используется собственный оригинальный алгоритм расчета.</div>' +
'<div class="">Доступно по ссылке в <a href="https://chrome.google.com/webstore/detail/депозитный-калькулятор/cibblnjekngmoeiehohbkmcbfijpcjdj" target="_blank">Chrome store</a></div>'},
{img: 'i/works/depcalc2.jpg', description: 'Для вывода графиков был использован highcharts.'},
]
},
];
var View = m3toolkit.View,
CollectionView = m3toolkit.CollectionView,
BlockView = m3toolkit.BlockView,
_base = {
// @param {Int} Index
// @return {Model} model from collection by index
getAnother: function(index){
return this.slideCollection.at(index);
}
};
var SlideModel = Backbone.Model.extend({
defaults: {
title: '',
works: [],
index: undefined,
next: undefined,
prev: undefined
}
});
var SlidesCollection = Backbone.Collection.extend({
model: SlideModel,
initialize: function(list){
var i = 0,
len = list.length
indexedList = list.map(function(item){
item.index = i;
if(i > 0){
item.prev = i - 1;
}
if(i < len - 1){
item.next = i + 1;
}
if(Array.isArray(item.works)){
item.frontImage = item.works[0].img;
}
i++;
return item;
});
Backbone.Collection.prototype.initialize.call(this, indexedList);
}
});
var WorkItemModel = Backbone.Model.extend({
defaults: {
img: '',
description: ''
}
});
var WorkItemsCollections = Backbone.Collection.extend({
model: WorkItemModel
});
var WorkItemPreview = View.extend({
className: 'presentation_work-item clearfix',
template: _.template(
'<img src="<%=img%>" class="Stretch m3-vertical "/>' +
'<% if(obj.description){ %>' +
'<div class="presentation_work-item_description"><%=obj.description%></div>' +
'<% }%>'
)
});
var SlideView = View.extend({
className: 'presentation_slide-wrap',
template: _.template(
'<div style="background-image: url(<%=obj.frontImage%>)" class="presentation_front-image"></div>' +
'<div class="presentation_front-image_hover"></div>'
),
events: {
click: function(e){
_base.openFullScreenPresentation(this.model);
}
},
});
var FullscreenSlideView = BlockView.extend({
className: 'presentation_fullscreen-slide',
template:
'<div class="presentation_fullscreen-slide_back"></div>' +
'<div class="presentation_fullscreen-slide_close" data-bind="close"></div>' +
'<div class="presentation_fullscreen-slide_wrap">' +
'<div class="presentation_fullscreen-slide_next" data-co="next">' +
'<div class="presentation_fullscreen-slide_nav-btn presentation_fullscreen-slide_nav-btn_next "></div>' +
'</div>' +
'<div class="presentation_fullscreen-slide_prev" data-co="prev">' +
'<div class="presentation_fullscreen-slide_nav-btn"></div>'+
'</div>' +
'<pre class="presentation_fullscreen-slide_title" data-co="title"></pre>' +
'<div class="" data-co="works" style=""></div>' +
'</div>',
events: {
'click [data-bind=close]': function(){
_base.hideFullScreenPresentation();
},
'click [data-co=next]': function(){
var nextIndex = this.model.get('next');
nextIndex != undefined && this._navigateTo(nextIndex);
},
'click [data-co=prev]': function(){
var prevIndex = this.model.get('prev');
prevIndex != undefined && this._navigateTo(prevIndex);
},
},
_navigateTo: function(index){
var prevModel =_base.getAnother(index);
if(prevModel){
var data = prevModel.toJSON();
this.model.set(prevModel.toJSON());
}
},
initialize: function(){
BlockView.prototype.initialize.call(this);
this.controls.prev[this.model.get('prev') != undefined ? 'show': 'hide']();
this.controls.next[this.model.get('next') ? 'show': 'hide']();
var workItemsCollection = new WorkItemsCollections(this.model.get('works'));
this.children.workCollection = new CollectionView({
collection: workItemsCollection,
el: this.controls.works
}, WorkItemPreview);
this.listenTo(this.model, 'change:works', function(model){
console.log('Works Changed');
workItemsCollection.reset(model.get('works'));
});
},
defineBindings: function(){
this._addComputed('works', 'works', function(control, model){
console.log('Refresh works');
var worksList = model.get('works');
console.dir(worksList);
});
this._addTransform('title', function(control, model, value){
console.log('Set new Title: `%s`', value);
control.text(value);
});
this._addTransform('next', function(control, model, value){
control[value ? 'show': 'hide']();
});
this._addTransform('prev', function(control, model, value){
control[value != undefined ? 'show': 'hide']();
});
}
});
var PresentationApp = View.extend({
className: 'presentation-wrap',
template:
'<div class="presentation-wrap_header">' +
'<div class="presentation-wrap_header-container">' +
'<div class="presentation-wrap_header-title clearfix">' +
/*'<div class="presentation-wrap_header-contacts">' +
'<div class="">Контакты для связи:</div>' +
'<div class="">8 (960) 243 14 03</div>' +
'<div class="">nsmalcev@bk.ru</div>' +
'</div>' +*/
'<h2 class="presentation_header1">Портфолио презентация</h2>' +
'<div class="presentation_liter1">Фронтенд разработчика Николая Мальцева</div>' +
'<div class="presentation_liter1">8 (960) 243 14 03, nsmalcev@bk.ru</div>' +
'<div class="presentation_liter1"><a href="http://matraska231.herokuapp.com/?portfolio=1#cv" target="_blank">Резюме</a></div>' +
'</div>' +
'</div>' +
'</div>' +
'<div class="presentation-wrap_body" data-bind="body">' +
'<div class="presentation-wrap_slide clearfix" data-bind="slides">' +
'</div>' +
'</div>' +
'<div data-bind="fullscreen" class="presentation_fullscreen-slide" style="display: none;"></div>',
initialize: function(){
View.prototype.initialize.call(this);
var $slides = this.$('[data-bind=slides]'),
$body = this.$('[data-bind=body]'),
slideCollection = new SlidesCollection(slides);
_base.app = this;
_base.slideCollection = slideCollection;
this.children['slides'] = new CollectionView({
collection: slideCollection,
el: $slides
}, SlideView);
this.children['fullscreen'] = new FullscreenSlideView({
el: this.$('[data-bind=fullscreen]'),
model: new SlideModel()
});
_base.openFullScreenPresentation = function(model){
$body.addClass('presentation-fix-body');
this.children['fullscreen'].$el.show();
this.children['fullscreen'].model.set(model.toJSON());
// TODO store vertical position
}.bind(this);
_base.hideFullScreenPresentation = function(){
this.children['fullscreen'].$el.hide();
$body.removeClass('presentation-fix-body');
}.bind(this);
}
});
var app = new PresentationApp({
el: '#app'
});
}());
|
Java
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (c) 2013 ASMlover. All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list ofconditions and the following disclaimer.
#
# * Redistributions in binary form must reproduce the above copyright
# notice, this list of conditions and the following disclaimer in
# the documentation and/or other materialsprovided with the
# distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
# FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
# COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
# ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
import zmq
import time
if __name__ == '__main__':
ctx = zmq.Context()
worker = ctx.socket(zmq.PULL)
worker.connect('tcp://localhost:5555')
sinker = ctx.socket(zmq.PUSH)
sinker.connect('tcp://localhost:6666')
print 'all workers are ready ...'
while True:
try:
msg = worker.recv()
print 'begin to work on task use `%s ms`' % msg
time.sleep(int(msg) * 0.001)
print '\tfinished this task'
sinker.send('finished task which used `%s ms`' % msg)
except KeyboardInterrupt:
break
sinker.close()
worker.close()
|
Java
|
class WireguardGo < Formula
desc "Userspace Go implementation of WireGuard"
homepage "https://www.wireguard.com/"
url "https://git.zx2c4.com/wireguard-go/snapshot/wireguard-go-0.0.20200320.tar.xz"
sha256 "c8262da949043976d092859843d3c0cdffe225ec6f1398ba119858b6c1b3552f"
license "MIT"
head "https://git.zx2c4.com/wireguard-go", using: :git
livecheck do
url :head
regex(/href=.*?wireguard-go[._-]v?(\d+(?:\.\d+)+)\.t/i)
end
bottle do
cellar :any_skip_relocation
sha256 "783b1eeb0aba2c336e91fe59ef9e8d5d449e51ef3a5ed313f96666c7d055fb02" => :catalina
sha256 "baf1cc2e7f0795747bcaed6856ce3a4075083356cc557497adf06ceaf28e0514" => :mojave
sha256 "23d0d338dddebcecc58aa5f1e651fbde03494b0d49071937c4cff0b4d19961c2" => :high_sierra
sha256 "168b97cf56b028ecf953768dcd06bd894aa1fc2daedb63a5074bfb5b60df99e5" => :x86_64_linux
end
depends_on "go" => :build
def install
ENV["GOPATH"] = HOMEBREW_CACHE/"go_cache"
system "make", "PREFIX=#{prefix}", "install"
end
test do
# ERROR: (notrealutun) Failed to create TUN device: no such file or directory
return if ENV["CI"]
assert_match "be utun", pipe_output("WG_PROCESS_FOREGROUND=1 #{bin}/wireguard-go notrealutun")
end
end
|
Java
|
# Writing your docs
How to write and layout your markdown source files.
---
## Configure Pages and Navigation
The [pages configuration](/user-guide/configuration/#pages) in your `mkdocs.yml` defines which pages are built by MkDocs and how they appear in the documentation navigation. If not provided, the pages configuration will be automatically created by discovering all the Markdown files in the [documentation directory](/user-guide/configuration/#docs_dir).
A simple pages configuration looks like this:
pages:
- 'index.md'
- 'about.md'
With this example we will build two pages at the top level and they will automatically have their titles inferred from the filename. Assuming `docs_dir` has the default value, `docs`, the source files for this documentation would be `docs/index.md` and `docs/about.md`. To provide a custom name for these pages, they can be added before the filename.
pages:
- Home: 'index.md'
- About: 'about.md'
### Multilevel documentation
Subsections can be created by listing related pages together under a section title. For example:
pages:
- Home: 'index.md'
- User Guide:
- 'Writing your docs': 'user-guide/writing-your-docs.md'
- 'Styling your docs': 'user-guide/styling-your-docs.md'
- About:
- 'License': 'about/license.md'
- 'Release Notes': 'about/release-notes.md'
With the above configuration we have three top level sections: Home, User Guide and About. Then under User Guide we have two pages, Writing your docs and Styling your docs. Under the About section we also have two pages, License and Release Notes.
*Note:* At present MkDocs only supports a second level of navigation.
## File layout
Your documentation source should be written as regular Markdown files, and placed in a directory somewhere in your project. Normally this directory will be named `docs` and will exist at the top level of your project, alongside the `mkdocs.yml` configuration file.
The simplest project you can create will look something like this:
mkdocs.yml
docs/
index.md
By convention your project homepage should always be named `index`. Any of the following extensions may be used for your Markdown source files: `markdown`, `mdown`, `mkdn`, `mkd`, `md`.
You can also create multi-page documentation, by creating several markdown files:
mkdocs.yml
docs/
index.md
about.md
license.md
The file layout you use determines the URLs that are used for the generated pages.
Given the above layout, pages would be generated for the following URLs:
/
/about/
/license/
You can also include your Markdown files in nested directories if that better suits your documentation layout.
docs/
index.md
user-guide/getting-started.md
user-guide/configuration-options.md
license.md
Source files inside nested directories will cause pages to be generated with nested URLs, like so:
/
/user-guide/getting-started/
/user-guide/configuration-options/
/license/
## Linking documents
MkDocs allows you to interlink your documentation by using regular Markdown hyperlinks.
#### Internal hyperlinks
When linking between pages in the documentation you can simply use the regular Markdown hyperlinking syntax, including the relative path to the Markdown document you wish to link to.
Please see the [project license](license.md) for further details.
When the MkDocs build runs, these hyperlinks will automatically be transformed into a hyperlink to the appropriate HTML page.
When working on your documentation you should be able to open the linked Markdown document in a new editor window simply by clicking on the link.
If the target documentation file is in another directory you'll need to make sure to include any relative directory path in the hyperlink.
Please see the [project license](../about/license.md) for further details.
You can also link to a section within a target documentation page by using an anchor link. The generated HTML will correctly transform the path portion of the hyperlink, and leave the anchor portion intact.
Please see the [project license](about.md#license) for further details.
## Images and media
As well as the Markdown source files, you can also include other file types in your documentation, which will be copied across when generating your documentation site. These might include images and other media.
For example, if your project documentation needed to include a [GitHub pages CNAME file](https://help.github.com/articles/setting-up-a-custom-domain-with-pages#setting-the-domain-in-your-repo) and a PNG formatted screenshot image then your file layout might look as follows:
mkdocs.yml
docs/
CNAME
index.md
about.md
license.md
img/
screenshot.png
To include images in your documentation source files, simply use any of the regular Markdown image syntaxes:
Cupcake indexer is a snazzy new project for indexing small cakes.

*Above: Cupcake indexer in progress*
You image will now be embedded when you build the documentation, and should also be previewed if you're working on the documentation with a Markdown editor.
## Markdown extensions
MkDocs supports the following Markdown extensions.
#### Tables
A simple table looks like this:
```text
First Header | Second Header | Third Header
------------ | ------------- | ------------
Content Cell | Content Cell | Content Cell
Content Cell | Content Cell | Content Cell
```
If you wish, you can add a leading and tailing pipe to each line of the table:
```text
| First Header | Second Header | Third Header |
| ------------ | ------------- | ------------ |
| Content Cell | Content Cell | Content Cell |
| Content Cell | Content Cell | Content Cell |
```
Specify alignment for each column by adding colons to separator lines:
```text
First Header | Second Header | Third Header
:----------- | :-----------: | -----------:
Left | Center | Right
Left | Center | Right
```
#### Fenced code blocks
Start with a line containing 3 or more backtick \` characters, and ends with the first line with the same number of backticks \`:
```
Fenced code blocks are like Stardard
Markdown’s regular code blocks, except that
they’re not indented and instead rely on a
start and end fence lines to delimit the code
block.
```
With the approach, the language can be specified on the first line after the backticks:
```python
def fn():
pass
```
|
Java
|
/* @LICENSE(MUSLC_MIT) */
#include "pthread_impl.h"
int pthread_detach(pthread_t t)
{
/* Cannot detach a thread that's already exiting */
if (a_swap(t->exitlock, 1))
return pthread_join(t, 0);
t->detached = 2;
__unlock(t->exitlock);
return 0;
}
|
Java
|
#!/bin/bash -e
# erik reed
# runs EM algorithm on hadoop streaming
if [ $# -ne 5 ]; then
echo Usage: $0 \"dir with net,tab,fg,em\" EM_FLAGS MAPPERS REDUCERS POP
echo "2 choices for EM_FLAGS: -u and -alem"
echo " -u corresponds to update; standard EM with fixed population size"
echo " e.g. a simple random restart with $POP BNs"
echo " -alem corresponds to Age-Layered EM with dynamic population size"
exit 1
fi
DAT_DIR=$1
EM_FLAGS=$2
MAPPERS=$3
REDUCERS=$4
# set to min_runs[0] if using ALEM
POP=$5
HADOOP_JAR=`echo $HADOOP_PREFIX/contrib/streaming/*.jar`
if [ -n "$HADOOP_PREFIX" ]; then
HADOOP_HOME=$HADOOP_PREFIX
elif [ -n "$HADOOP_HOME" ]; then
echo Hadoop env vars not proeprly set!
exit 1
else
HADOOP_PREFIX=$HADOOP_HOME
fi
# max MapReduce job iterations, not max EM iters, which
# is defined in dai_mapreduce.h
MAX_ITERS=1
# (disabled) save previous run if it exists (just in case)
#rm -rf out.prev
#mv -f out out.prev || true
rm -rf dat/out out
mkdir -p dat/out out
LOG="tee -a dat/out/log.txt"
echo $0 started at `date` | $LOG
echo -- Using parameters -- | $LOG
echo Directory: $DAT_DIR | $LOG
echo Max number of MapReduce iterations: $MAX_ITERS | $LOG
echo Reducers: $REDUCERS | $LOG
echo Mappers: $MAPPERS | $LOG
echo Population size: $POP | $LOG
echo EM flags: $EM_FLAGS
echo Max MR iterations: $MAX_ITERS
echo ---------------------- | $LOG
./scripts/make_input.sh $DAT_DIR
echo $POP > in/pop
# create random initial population
./utils in/fg $POP
# copy 0th iteration (i.e. initial values)
mkdir -p dat/out/iter.0
cp dat/in/dat dat/out/iter.0
cp dat/in/dat in
echo Clearing previous input from HDFS
hadoop fs -rmr -skipTrash out in &> /dev/null || true
echo Adding input to HDFS
hadoop fs -D dfs.replication=1 -put in in
for i in $(seq 1 1 $MAX_ITERS); do
echo starting MapReduce job iteration: $i
$HADOOP_PREFIX/bin/hadoop jar $HADOOP_JAR \
-files "dai_map,dai_reduce,in" \
-D 'stream.map.output.field.separator=:' \
-D 'stream.reduce.output.field.separator=:' \
-D mapred.tasktracker.tasks.maximum=$MAPPERS \
-D mapred.map.tasks=$MAPPERS \
-D mapred.output.compress=false \
-input in/tab_content \
-output out \
-mapper ./dai_map \
-reducer ./dai_reduce \
-numReduceTasks $REDUCERS
hadoop fs -cat out/part-* > dat/out/tmp
hadoop fs -rmr -skipTrash out in/dat
cat dat/out/tmp | ./utils $EM_FLAGS
rm dat/out/tmp in/dat # remove previous iteration
mkdir -p dat/out/iter.$i
mv out/* dat/out/iter.$i
if [ $i != $MAX_ITERS ]; then
cp out/dat in
echo Adding next iteration input to HDFS
hadoop fs -D dfs.replication=1 -put out/dat in
fi
if [ -n "$start_time" -a -n "$time_duration" ]; then
dur=$((`date +%s` - $start_time))
if [ $dur -ge $time_duration ]; then
echo $time_duration seconds reached! Quitting...
break
fi
fi
converged=`cat dat/out/iter.$i/converged`
if [ "$converged" = 1 ]; then
echo EM converged at iteration $i
break
fi
done
|
Java
|
#ifndef SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_
#define SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_
// Copyright (c) 2014, Ruslan Baratov
// All rights reserved.
#include <functional> // std::function
namespace sober {
namespace network {
namespace http {
using ExtraSuccessHandler = std::function<void()>;
} // namespace http
} // namespace network
} // namespace sober
#endif // SOBER_NETWORK_HTTP_EXTRA_SUCCESS_HANDLER_HPP_
|
Java
|
##大纲
* DevOps基础
* DevOps是什么
* DevOps解决什么问题
* DevOps都做什么
* Vagrant基础
* init
* box管理
* up
* ssh
* reload
* destroy
* port forward
* multi-machines
##目标
* 基本理解DevOps以及DevOps要做的事情
* 可以使用Vagrant创建虚拟机并使用虚拟机工作
##详细内容
#### DevOps是啥?
```
DevOps顾名思义, 就是Developer + Operatior,开发 + 运维。
当然,其实这里面还得加上QA。如图所示,三不像。
难道DevOps仅仅就是干三个角色的事儿么?
必然不是
DevOps是互相紧扣的一个过程。
通过Dev看QA,通过Ops看Dev等等
以上的概念太大,说个例子:
现在BOSS要你把所有javaEE的API拆成单独的jar包或者war包
然后每个包都部署到一个或者多个机器上。
真的你会去启动N个机器手动去部署么?
QA怎么去验证各个java实例的运行?
开发以后还怎么开发?
DevOps就会cover到上面的事儿
比如引入gradle自动拆成api包,然后要引入一个CI工具,比如jenkins或者go
当然构建出artifact是远远不够的,引入CD,我们要通过一系列的脚本来达到快速部署
还有在这个PIPELINE上的QA流程,是否通过job
最后,还能把虚拟化引入,比如vagrant、docker来部署单个java进程。
以上cover的就是devops的事儿
```
#### DevOps都干些啥?
```
如图,这些工具DevOps或多或少都会用
当然,我们普遍在LINUX下玩这件事儿,所以中间的BASH和SHELL SCRIPT是必须要求的
这里可以看到
有各种语言平台
有各种配置管理
有各种CI工具
有各种虚拟化产品
这些都会穿插在我们整个开发周期,所以,DevOps会一直跟这些工具打交到
```
#### DevOps解决什么问题
```
在提DevOps定义的时候举了一个例子,
实际上,DevOps就是解决整个开发过程中的协调问题
如何快速的给DEV和QA配置环境,开发的产出如何快速的到QA手里
QA反馈如何能及时到Dev手上
最重要的:CD
仅修改一行代码,要多久才能部署到产品环境,个人认为这就是DevOps。
```
#### SESSION课程和范围
```
一共会有5节课,这次是ITERATOR 0
目标是做一套完整的PIPELINE,达到快速部署的目的
会涉及到 java、jenkins、vagrant、tomcat、git等软件
通过是MAC作为宿主机,LINUX作为虚拟机进行整个课程的练习
```
|
Java
|
/*
* Copyright (c) 2012 Tom Denley
* This file incorporates work covered by the following copyright and
* permission notice:
*
* Copyright (c) 2003-2008, Franz-Josef Elmer, All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
*
* 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 OWNER 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.
*/
package org.netmelody.neoclassycle.renderer;
import org.netmelody.neoclassycle.graph.StrongComponent;
/**
* Interface for rendering a {@link StrongComponent}.
*
* @author Franz-Josef Elmer
*/
public interface StrongComponentRenderer {
/** Renderes the specified {@link StrongComponent}. */
public String render(StrongComponent component);
}
|
Java
|
from unittest import TestCase
import pkg_resources
from mock import patch
from click import UsageError
from click.testing import CliRunner
class TestCli(TestCase):
@patch('molo.core.cookiecutter.cookiecutter')
def test_scaffold(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'foo',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': (),
'include': (),
}
})
@patch('molo.core.cookiecutter.cookiecutter')
def test_scaffold_with_custom_dir(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo', 'bar'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'bar',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': (),
'include': (),
}
})
@patch('molo.core.cookiecutter.cookiecutter')
def test_scaffold_with_requirements(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo', '--require', 'bar'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'foo',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': ('bar',),
'include': (),
}
})
@patch('molo.core.cookiecutter.cookiecutter')
def test_scaffold_with_includes(self, mock_cookiecutter):
from molo.core.scripts import cli
package = pkg_resources.get_distribution('molo.core')
runner = CliRunner()
runner.invoke(cli.scaffold, ['foo', '--include', 'bar', 'baz'])
[call] = mock_cookiecutter.call_args_list
args, kwargs = call
self.assertTrue(kwargs['extra_context'].pop('secret_key'))
self.assertEqual(kwargs, {
'no_input': True,
'extra_context': {
'app_name': 'foo',
'directory': 'foo',
'author': 'Praekelt Foundation',
'author_email': 'dev@praekelt.com',
'url': None,
'license': 'BSD',
'molo_version': package.version,
'require': (),
'include': (('bar', 'baz'),),
}
})
@patch('molo.core.scripts.cli.get_package')
@patch('molo.core.scripts.cli.get_template_dirs')
@patch('shutil.copytree')
def test_unpack(self, mock_copytree, mock_get_template_dirs,
mock_get_package):
package = pkg_resources.get_distribution('molo.core')
mock_get_package.return_value = package
mock_get_template_dirs.return_value = ['foo']
mock_copytree.return_value = True
from molo.core.scripts import cli
runner = CliRunner()
runner.invoke(cli.unpack_templates, ['app1', 'app2'])
mock_copytree.assert_called_with(
pkg_resources.resource_filename('molo.core', 'templates/foo'),
pkg_resources.resource_filename('molo.core', 'templates/foo'))
def test_get_package(self):
from molo.core.scripts.cli import get_package
self.assertRaisesRegexp(
UsageError, 'molo.foo is not installed.', get_package, 'molo.foo')
|
Java
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ItzWarty.RAF
{
public class RAFFileListEntry
{
private byte[] directoryFileContent = null;
private UInt32 offsetEntry = 0;
private RAF raf = null;
public RAFFileListEntry(RAF raf, byte[] directoryFileContent, UInt32 offsetEntry)
{
this.raf = raf;
this.directoryFileContent = directoryFileContent;
this.offsetEntry = offsetEntry;
}
/// <summary>
/// Hash of the string name
/// </summary>
public UInt32 StringNameHash
{
get
{
return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry);
}
}
/// <summary>
/// Offset to the start of the archived file in the data file
/// </summary>
public UInt32 FileOffset
{
get
{
return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+4);
}
}
/// <summary>
/// Size of this archived file
/// </summary>
public UInt32 FileSize
{
get
{
return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+8);
}
}
/// <summary>
/// Index of the name of the archvied file in the string table
/// </summary>
public UInt32 FileNameStringTableIndex
{
get
{
return BitConverter.ToUInt32(directoryFileContent, (int)offsetEntry+12);
}
}
public String GetFileName
{
get
{
return this.raf.GetDirectoryFile().GetStringTable()[this.FileNameStringTableIndex];
}
}
}
}
|
Java
|
// Copyright (c) 2020 WNProject Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Intentionally left empty so that we can build a lib target for this library
#include "hashing/inc/hash.h"
|
Java
|
//
// Copyright (c) 2015 CNRS
//
// This file is part of Pinocchio
// Pinocchio is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// Pinocchio 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 Lesser Public License for more details. You should have
// received a copy of the GNU Lesser General Public License along with
// Pinocchio If not, see
// <http://www.gnu.org/licenses/>.
#ifndef __se3_se3_hpp__
#define __se3_se3_hpp__
#include <Eigen/Geometry>
#include "pinocchio/spatial/fwd.hpp"
#include "pinocchio/spatial/skew.hpp"
namespace se3
{
/* Type returned by the "se3Action" and "se3ActionInverse" functions. */
namespace internal
{
template<typename D>
struct ActionReturn { typedef D Type; };
}
/** The rigid transform aMb can be seen in two ways:
*
* - given a point p expressed in frame B by its coordinate vector Bp, aMb
* computes its coordinates in frame A by Ap = aMb Bp.
* - aMb displaces a solid S centered at frame A into the solid centered in
* B. In particular, the origin of A is displaced at the origin of B: $^aM_b
* ^aA = ^aB$.
* The rigid displacement is stored as a rotation matrix and translation vector by:
* aMb (x) = aRb*x + aAB
* where aAB is the vector from origin A to origin B expressed in coordinates A.
*/
template< class Derived>
class SE3Base
{
protected:
typedef Derived Derived_t;
SPATIAL_TYPEDEF_TEMPLATE(Derived_t);
public:
Derived_t & derived() { return *static_cast<Derived_t*>(this); }
const Derived_t& derived() const { return *static_cast<const Derived_t*>(this); }
const Angular_t & rotation() const { return derived().rotation_impl(); }
const Linear_t & translation() const { return derived().translation_impl(); }
Angular_t & rotation() { return derived().rotation_impl(); }
Linear_t & translation() { return derived().translation_impl(); }
void rotation(const Angular_t & R) { derived().rotation_impl(R); }
void translation(const Linear_t & R) { derived().translation_impl(R); }
Matrix4 toHomogeneousMatrix() const
{
return derived().toHomogeneousMatrix_impl();
}
operator Matrix4() const { return toHomogeneousMatrix(); }
Matrix6 toActionMatrix() const
{
return derived().toActionMatrix_impl();
}
operator Matrix6() const { return toActionMatrix(); }
void disp(std::ostream & os) const
{
static_cast<const Derived_t*>(this)->disp_impl(os);
}
Derived_t operator*(const Derived_t & m2) const { return derived().__mult__(m2); }
/// ay = aXb.act(by)
template<typename D>
typename internal::ActionReturn<D>::Type act (const D & d) const
{
return derived().act_impl(d);
}
/// by = aXb.actInv(ay)
template<typename D> typename internal::ActionReturn<D>::Type actInv(const D & d) const
{
return derived().actInv_impl(d);
}
Derived_t act (const Derived_t& m2) const { return derived().act_impl(m2); }
Derived_t actInv(const Derived_t& m2) const { return derived().actInv_impl(m2); }
bool operator == (const Derived_t & other) const
{
return derived().__equal__(other);
}
bool isApprox (const Derived_t & other) const
{
return derived().isApprox_impl(other);
}
friend std::ostream & operator << (std::ostream & os,const SE3Base<Derived> & X)
{
X.disp(os);
return os;
}
}; // class SE3Base
template<typename T, int U>
struct traits< SE3Tpl<T, U> >
{
typedef T Scalar_t;
typedef Eigen::Matrix<T,3,1,U> Vector3;
typedef Eigen::Matrix<T,4,1,U> Vector4;
typedef Eigen::Matrix<T,6,1,U> Vector6;
typedef Eigen::Matrix<T,3,3,U> Matrix3;
typedef Eigen::Matrix<T,4,4,U> Matrix4;
typedef Eigen::Matrix<T,6,6,U> Matrix6;
typedef Matrix3 Angular_t;
typedef Vector3 Linear_t;
typedef Matrix6 ActionMatrix_t;
typedef Eigen::Quaternion<T,U> Quaternion_t;
typedef SE3Tpl<T,U> SE3;
typedef ForceTpl<T,U> Force;
typedef MotionTpl<T,U> Motion;
typedef Symmetric3Tpl<T,U> Symmetric3;
enum {
LINEAR = 0,
ANGULAR = 3
};
}; // traits SE3Tpl
template<typename _Scalar, int _Options>
class SE3Tpl : public SE3Base< SE3Tpl< _Scalar, _Options > >
{
public:
friend class SE3Base< SE3Tpl< _Scalar, _Options > >;
SPATIAL_TYPEDEF_TEMPLATE(SE3Tpl);
SE3Tpl(): rot(), trans() {};
template<typename M3,typename v3>
SE3Tpl(const Eigen::MatrixBase<M3> & R, const Eigen::MatrixBase<v3> & p)
: rot(R), trans(p)
{
}
template<typename M4>
SE3Tpl(const Eigen::MatrixBase<M4> & m)
: rot(m.template block<3,3>(LINEAR,LINEAR)), trans(m.template block<3,1>(LINEAR,ANGULAR))
{
}
SE3Tpl(int) : rot(Matrix3::Identity()), trans(Vector3::Zero()) {}
template<typename S2, int O2>
SE3Tpl( const SE3Tpl<S2,O2> & clone )
: rot(clone.rotation()),trans(clone.translation()) {}
template<typename S2, int O2>
SE3Tpl & operator= (const SE3Tpl<S2,O2> & other)
{
rot = other.rotation ();
trans = other.translation ();
return *this;
}
static SE3Tpl Identity()
{
return SE3Tpl(1);
}
SE3Tpl & setIdentity () { rot.setIdentity (); trans.setZero (); return *this;}
/// aXb = bXa.inverse()
SE3Tpl inverse() const
{
return SE3Tpl(rot.transpose(), -rot.transpose()*trans);
}
static SE3Tpl Random()
{
Quaternion_t q(Vector4::Random());
q.normalize();
return SE3Tpl(q.matrix(),Vector3::Random());
}
SE3Tpl & setRandom ()
{
Quaternion_t q(Vector4::Random());
q.normalize ();
rot = q.matrix ();
trans.setRandom ();
return *this;
}
public:
Matrix4 toHomogeneousMatrix_impl() const
{
Matrix4 M;
M.template block<3,3>(LINEAR,LINEAR) = rot;
M.template block<3,1>(LINEAR,ANGULAR) = trans;
M.template block<1,3>(ANGULAR,LINEAR).setZero();
M(3,3) = 1;
return M;
}
/// Vb.toVector() = bXa.toMatrix() * Va.toVector()
Matrix6 toActionMatrix_impl() const
{
Matrix6 M;
M.template block<3,3>(ANGULAR,ANGULAR)
= M.template block<3,3>(LINEAR,LINEAR) = rot;
M.template block<3,3>(ANGULAR,LINEAR).setZero();
M.template block<3,3>(LINEAR,ANGULAR)
= skew(trans) * M.template block<3,3>(ANGULAR,ANGULAR);
return M;
}
void disp_impl(std::ostream & os) const
{
os << " R =\n" << rot << std::endl
<< " p = " << trans.transpose() << std::endl;
}
/// --- GROUP ACTIONS ON M6, F6 and I6 ---
/// ay = aXb.act(by)
template<typename D>
typename internal::ActionReturn<D>::Type act_impl (const D & d) const
{
return d.se3Action(*this);
}
/// by = aXb.actInv(ay)
template<typename D> typename internal::ActionReturn<D>::Type actInv_impl(const D & d) const
{
return d.se3ActionInverse(*this);
}
Vector3 act_impl (const Vector3& p) const { return (rot*p+trans).eval(); }
Vector3 actInv_impl(const Vector3& p) const { return (rot.transpose()*(p-trans)).eval(); }
SE3Tpl act_impl (const SE3Tpl& m2) const { return SE3Tpl( rot*m2.rot,trans+rot*m2.trans);}
SE3Tpl actInv_impl (const SE3Tpl& m2) const { return SE3Tpl( rot.transpose()*m2.rot, rot.transpose()*(m2.trans-trans));}
SE3Tpl __mult__(const SE3Tpl & m2) const { return this->act(m2);}
bool __equal__( const SE3Tpl & m2 ) const
{
return (rotation_impl() == m2.rotation() && translation_impl() == m2.translation());
}
bool isApprox_impl( const SE3Tpl & m2 ) const
{
Matrix4 diff( toHomogeneousMatrix_impl() -
m2.toHomogeneousMatrix_impl());
return (diff.isMuchSmallerThan(toHomogeneousMatrix_impl(), 1e-14)
&& diff.isMuchSmallerThan(m2.toHomogeneousMatrix_impl(), 1e-14) );
}
public:
const Angular_t & rotation_impl() const { return rot; }
Angular_t & rotation_impl() { return rot; }
void rotation_impl(const Angular_t & R) { rot = R; }
const Linear_t & translation_impl() const { return trans;}
Linear_t & translation_impl() { return trans;}
void translation_impl(const Linear_t & p) { trans=p; }
protected:
Angular_t rot;
Linear_t trans;
}; // class SE3Tpl
typedef SE3Tpl<double,0> SE3;
} // namespace se3
#endif // ifndef __se3_se3_hpp__
|
Java
|
/*
Copyright (c) 2012-2013, Politecnico di Milano. All rights reserved.
Andrea Zoppi <texzk@email.it>
Martino Migliavacca <martino.migliavacca@gmail.com>
http://airlab.elet.polimi.it/
http://www.openrobots.com/
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.
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 OWNER 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.
*/
/**
* @file urosNode.c
* @author Andrea Zoppi <texzk@email.it>
*
* @brief Node features of the middleware.
*/
/*===========================================================================*/
/* HEADER FILES */
/*===========================================================================*/
#include "../include/urosBase.h"
#include "../include/urosUser.h"
#include "../include/urosNode.h"
#include "../include/urosRpcCall.h"
#include "../include/urosRpcParser.h"
#include <string.h>
#define DEBUG 0
/*===========================================================================*/
/* LOCAL TYPES & MACROS */
/*===========================================================================*/
#if UROS_NODE_C_USE_ASSERT == UROS_FALSE && !defined(__DOXYGEN__)
#undef urosAssert
#define urosAssert(expr)
#endif
#if UROS_NODE_C_USE_ERROR_MSG == UROS_FALSE && !defined(__DOXYGEN__)
#undef urosError
#define urosError(when, action, msgargs) { if (when) { action; } }
#endif
/*===========================================================================*/
/* LOCAL VARIABLES */
/*===========================================================================*/
/** @brief Node thread stack.*/
static UROS_STACK(urosNodeThreadStack, UROS_NODE_THREAD_STKSIZE);
/** @brief XMLRPC Listener thread stack.*/
static UROS_STACK(xmlrpcListenerStack, UROS_XMLRPC_LISTENER_STKSIZE);
/** @brief TCPROS Listener thread stack.*/
static UROS_STACK(tcprosListenerStack, UROS_TCPROS_LISTENER_STKSIZE);
/** @brief XMLRPC Slave server worker thread stacks.*/
static UROS_STACKPOOL(slaveMemPoolChunk, UROS_XMLRPC_SLAVE_STKSIZE,
UROS_XMLRPC_SLAVE_POOLSIZE);
/** @brief TCPROS Client worker thread stacks.*/
static UROS_STACKPOOL(tcpcliMemPoolChunk, UROS_TCPROS_CLIENT_STKSIZE,
UROS_TCPROS_CLIENT_POOLSIZE);
/** @brief TCPROS Server worker thread stacks.*/
static UROS_STACKPOOL(tcpsvrMemPoolChunk, UROS_TCPROS_SERVER_STKSIZE,
UROS_TCPROS_SERVER_POOLSIZE);
/*===========================================================================*/
/* GLOBAL VARIABLES */
/*===========================================================================*/
/**
* @brief Node singleton.
*/
UrosNode urosNode;
/*===========================================================================*/
/* LOCAL FUNCTIONS */
/*===========================================================================*/
void uros_node_createthreads(void) {
static UrosNodeStatus *const stp = &urosNode.status;
uros_err_t err;
(void)err;
urosAssert(stp->xmlrpcListenerId == UROS_NULL_THREADID);
urosAssert(stp->tcprosListenerId == UROS_NULL_THREADID);
/* Fill the worker thread pools.*/
#if DEBUG
sleep(1);
printf("%s\n", stp->tcpcliThdPool.namep);
#endif
/* Subscribe thread */
printf("Subscribe Thread ID\n");
err = urosThreadPoolCreateAll(&stp->tcpcliThdPool);
urosAssert(err == UROS_OK);
/* Publish thread */
printf("Publish Thread ID\n");
err = urosThreadPoolCreateAll(&stp->tcpsvrThdPool);
urosAssert(err == UROS_OK);
printf("Servece? Thread ID\n");
err = urosThreadPoolCreateAll(&stp->slaveThdPool);
urosAssert(err == UROS_OK);
/* Spawn the XMLRPC Slave listener threads.*/
err = urosThreadCreateStatic(&stp->xmlrpcListenerId,
"RpcSlaveLis",
UROS_XMLRPC_LISTENER_PRIO,
(uros_proc_f)urosRpcSlaveListenerThread, NULL,
xmlrpcListenerStack,
UROS_XMLRPC_LISTENER_STKSIZE);
urosAssert(err == UROS_OK);
/* Spawn the TCPROS listener thread.*/
err = urosThreadCreateStatic(&stp->tcprosListenerId,
"TcpRosLis",
UROS_TCPROS_LISTENER_PRIO,
(uros_proc_f)urosTcpRosListenerThread, NULL,
tcprosListenerStack,
UROS_TCPROS_LISTENER_STKSIZE);
urosAssert(err == UROS_OK);
}
void uros_node_jointhreads(void) {
static const UrosNodeConfig *const cfgp = &urosNode.config;
static UrosNodeStatus *const stp = &urosNode.status;
UrosConn conn;
uros_err_t err;
(void)err;
urosAssert(stp->xmlrpcListenerId != UROS_NULL_THREADID);
urosAssert(stp->tcprosListenerId != UROS_NULL_THREADID);
/* Join the XMLRPC Slave listener threads.*/
urosConnObjectInit(&conn);
urosConnCreate(&conn, UROS_PROTO_TCP);
urosConnConnect(&conn, &cfgp->xmlrpcAddr);
urosConnClose(&conn);
err = urosThreadJoin(stp->xmlrpcListenerId);
urosAssert(err == UROS_OK);
stp->xmlrpcListenerId = UROS_NULL_THREADID;
/* Join the TCPROS listener thread.*/
urosConnObjectInit(&conn);
urosConnCreate(&conn, UROS_PROTO_TCP);
urosConnConnect(&conn, &cfgp->tcprosAddr);
urosConnClose(&conn);
err = urosThreadJoin(stp->tcprosListenerId);
urosAssert(err == UROS_OK);
stp->tcprosListenerId = UROS_NULL_THREADID;
/* Join the worker thread pools.*/
err = urosThreadPoolJoinAll(&stp->tcpcliThdPool);
urosAssert(err == UROS_OK);
err = urosThreadPoolJoinAll(&stp->tcpsvrThdPool);
urosAssert(err == UROS_OK);
err = urosThreadPoolJoinAll(&stp->slaveThdPool);
urosAssert(err == UROS_OK);
}
uros_err_t uros_node_pollmaster(void) {
static const UrosNodeConfig *const cfgp = &urosNode.config;
UrosRpcResponse res;
uros_err_t err;
/* Check if the Master can reply to a getPid() request.*/
urosRpcResponseObjectInit(&res);
err = urosRpcCallGetPid(
&cfgp->masterAddr,
&cfgp->xmlrpcUri,
&res
);
urosRpcResponseClean(&res);
return err;
}
void uros_node_registerall(void) {
/* Register topics.*/
urosUserPublishTopics();
urosUserSubscribeTopics();
/* Register services.*/
urosUserPublishServices();
/* Register parameters.*/
urosUserSubscribeParams();
}
void uros_node_unregisterall(void) {
static UrosNodeStatus *const stp = &urosNode.status;
UrosListNode *np;
UrosString exitMsg;
/* Get the exit message.*/
urosMutexLock(&stp->stateLock);
exitMsg = stp->exitMsg;
stp->exitMsg = urosStringAssignZ(NULL);
urosMutexUnlock(&stp->stateLock);
/* Exit from all the registered TCPROS worker threads.*/
urosMutexLock(&stp->pubTcpListLock);
for (np = stp->pubTcpList.headp; np != NULL; np = np->nextp) {
urosTcpRosStatusIssueExit((UrosTcpRosStatus*)np->datap);
}
urosMutexUnlock(&stp->pubTcpListLock);
urosMutexLock(&stp->subTcpListLock);
for (np = stp->subTcpList.headp; np != NULL; np = np->nextp) {
urosTcpRosStatusIssueExit((UrosTcpRosStatus*)np->datap);
}
urosMutexUnlock(&stp->subTcpListLock);
/* Call the shutdown function provided by the user.*/
urosUserShutdown(&exitMsg);
urosStringClean(&exitMsg);
/* Unregister topics.*/
urosUserUnpublishTopics();
urosUserUnsubscribeTopics();
/* Unregister services.*/
urosUserUnpublishServices();
/* Unregister parameters.*/
urosUserUnsubscribeParams();
}
/*===========================================================================*/
/* GLOBAL FUNCTIONS */
/*===========================================================================*/
/** @addtogroup node_funcs */
/** @{ */
/**
* @brief Initializes a node object.
* @details This procedure:
* - loads a nullified configuration
* - initializes the status lists
* - initializes the status locks
* - initializes and allocates memory pools
* - initializes thread pools
*
* @pre The node has not been initialized yet.
*
* @param[in,out] np
* Pointer to the @p UrosNode to be initialized.
*/
void urosNodeObjectInit(UrosNode *np) {
UrosNodeStatus *stp;
urosAssert(np != NULL);
/* Invalidate configuration variables.*/
memset((void*)&np->config, 0, sizeof(UrosNodeConfig));
/* Initialize status variables.*/
stp = &np->status;
stp->state = UROS_NODE_UNINIT;
stp->xmlrpcPid = ~0;
urosListObjectInit(&stp->subTopicList);
urosListObjectInit(&stp->pubTopicList);
urosListObjectInit(&stp->pubServiceList);
urosListObjectInit(&stp->subParamList);
urosListObjectInit(&stp->subTcpList);
urosListObjectInit(&stp->pubTcpList);
stp->xmlrpcListenerId = UROS_NULL_THREADID;
stp->tcprosListenerId = UROS_NULL_THREADID;
urosMutexObjectInit(&stp->stateLock);
urosMutexObjectInit(&stp->xmlrpcPidLock);
urosMutexObjectInit(&stp->subTopicListLock);
urosMutexObjectInit(&stp->pubTopicListLock);
urosMutexObjectInit(&stp->pubServiceListLock);
urosMutexObjectInit(&stp->subParamListLock);
urosMutexObjectInit(&stp->subTcpListLock);
urosMutexObjectInit(&stp->pubTcpListLock);
stp->exitFlag = UROS_FALSE;
/* Initialize mempools with their description.*/
urosMemPoolObjectInit(&stp->slaveMemPool,
UROS_STACKPOOL_BLKSIZE(UROS_XMLRPC_SLAVE_STKSIZE),
NULL);
urosMemPoolObjectInit(&stp->tcpcliMemPool,
UROS_STACKPOOL_BLKSIZE(UROS_TCPROS_CLIENT_STKSIZE),
NULL);
urosMemPoolObjectInit(&stp->tcpsvrMemPool,
UROS_STACKPOOL_BLKSIZE(UROS_TCPROS_SERVER_STKSIZE),
NULL);
/* Load the actual memory chunks for worker thread stacks.*/
urosMemPoolLoadArray(&stp->slaveMemPool, slaveMemPoolChunk,
UROS_XMLRPC_SLAVE_POOLSIZE);
urosMemPoolLoadArray(&stp->tcpcliMemPool, tcpcliMemPoolChunk,
UROS_TCPROS_CLIENT_POOLSIZE);
urosMemPoolLoadArray(&stp->tcpsvrMemPool, tcpsvrMemPoolChunk,
UROS_TCPROS_SERVER_POOLSIZE);
/* Initialize thread pools.*/
urosThreadPoolObjectInit(&stp->tcpcliThdPool, &stp->tcpcliMemPool,
(uros_proc_f)urosTcpRosClientThread,
"TcpRosCli",
UROS_TCPROS_CLIENT_PRIO);
urosThreadPoolObjectInit(&stp->tcpsvrThdPool, &stp->tcpsvrMemPool,
(uros_proc_f)urosTcpRosServerThread,
"TcpRosSvr",
UROS_TCPROS_SERVER_PRIO);
urosThreadPoolObjectInit(&stp->slaveThdPool, &stp->slaveMemPool,
(uros_proc_f)urosRpcSlaveServerThread,
"RpcSlaveSvr",
UROS_XMLRPC_SLAVE_PRIO);
/* The node is initialized and stopped.*/
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_IDLE;
urosMutexUnlock(&stp->stateLock);
}
/**
* @brief Creates the main Node thread.
* @note Should be called at system startup, after @p urosInit().
*
* @return
* Error code.
*/
uros_err_t urosNodeCreateThread(void) {
urosAssert(urosNode.status.exitFlag == UROS_FALSE);
urosNode.status.exitFlag = UROS_FALSE;
return urosThreadCreateStatic(
&urosNode.status.nodeThreadId, "urosNode",
UROS_NODE_THREAD_PRIO,
(uros_proc_f)urosNodeThread, NULL,
urosNodeThreadStack, UROS_NODE_THREAD_STKSIZE
);
}
/**
* @brief Node thread.
* @details This thread handles the whole life of the local node, including
* (un)registration (from)to the Master, thread pool magnagement,
* node shutdown, and so on.
*
* @param[in] argp
* Ignored.
* @return
* Error code.
*/
uros_err_t urosNodeThread(void *argp) {
static UrosNodeStatus *const stp = &urosNode.status;
uros_bool_t exitFlag;
(void)argp;
#if UROS_NODE_C_USE_ASSERT
urosMutexLock(&stp->stateLock);
urosAssert(stp->state == UROS_NODE_IDLE);
urosMutexUnlock(&stp->stateLock);
#endif
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_STARTUP;
urosMutexUnlock(&stp->stateLock);
/* Create the listener and pool threads.*/
uros_node_createthreads();
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
while (!exitFlag) {
/* Check if the Master is alive.*/
if (uros_node_pollmaster() != UROS_OK) {
/* Add a delay not to flood in case of short timeouts.*/
urosThreadSleepSec(3);
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
continue;
}
/* Register to the Master.*/
uros_node_registerall();
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_RUNNING;
urosMutexUnlock(&stp->stateLock);
/* Check if the Master is alive every 3 seconds.*/
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
while (!exitFlag) {
#if UROS_NODE_POLL_MASTER
urosError(uros_node_pollmaster() != UROS_OK, break,
("Master node "UROS_IPFMT" lost\n",
UROS_IPARG(&urosNode.config.masterAddr.ip)));
#endif
urosThreadSleepMsec(UROS_NODE_POLL_PERIOD);
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
urosMutexUnlock(&stp->stateLock);
}
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_SHUTDOWN;
urosMutexUnlock(&stp->stateLock);
/* Unregister from the Master*/
uros_node_unregisterall();
urosMutexLock(&stp->stateLock);
exitFlag = stp->exitFlag;
if (!exitFlag) {
/* The node has simply lost sight of the Master, restart.*/
stp->state = UROS_NODE_STARTUP;
}
urosMutexUnlock(&stp->stateLock);
}
/* Join listener and pool threads.*/
uros_node_jointhreads();
/* The node has shut down.*/
urosMutexLock(&stp->stateLock);
stp->state = UROS_NODE_IDLE;
urosMutexUnlock(&stp->stateLock);
return UROS_OK;
}
/**
* @brief Loads the default node configuration.
* @details Any previously allocated data is freed, then the default node
* configuration is loaded.
*
* @pre The related @p UrosNode is initialized.
*
* @param[in,out] cfgp
* Pointer to the target configuration descriptor.
*/
void urosNodeConfigLoadDefaults(UrosNodeConfig *cfgp) {
urosAssert(cfgp != NULL);
urosAssert(UROS_XMLRPC_LISTENER_PORT != UROS_TCPROS_LISTENER_PORT);
/* Deallocate any previously allocated data.*/
urosStringClean(&cfgp->nodeName);
urosStringClean(&cfgp->xmlrpcUri);
urosStringClean(&cfgp->tcprosUri);
urosStringClean(&cfgp->masterUri);
/* Load default values.*/
cfgp->nodeName = urosStringCloneZ(UROS_NODE_NAME);
cfgp->xmlrpcAddr.ip.dword = UROS_XMLRPC_LISTENER_IP;
cfgp->xmlrpcAddr.port = UROS_XMLRPC_LISTENER_PORT;
cfgp->xmlrpcUri = urosStringCloneZ(
"http://"UROS_XMLRPC_LISTENER_IP_SZ
":"UROS_STRINGIFY2(UROS_XMLRPC_LISTENER_PORT));
cfgp->tcprosAddr.ip.dword = UROS_TCPROS_LISTENER_IP;
cfgp->tcprosAddr.port = UROS_TCPROS_LISTENER_PORT;
cfgp->tcprosUri = urosStringCloneZ(
"rosrpc://"UROS_TCPROS_LISTENER_IP_SZ
":"UROS_STRINGIFY2(UROS_TCPROS_LISTENER_PORT));
cfgp->masterAddr.ip.dword = UROS_XMLRPC_MASTER_IP;
cfgp->masterAddr.port = UROS_XMLRPC_MASTER_PORT;
cfgp->masterUri = urosStringCloneZ(
"http://"UROS_XMLRPC_MASTER_IP_SZ
":"UROS_STRINGIFY2(UROS_XMLRPC_MASTER_PORT));
}
/**
* @brief Publishes a topic.
* @details Issues a @p publishTopic() call to the XMLRPC Master.
* @see urosRpcCallRegisterPublisher()
* @see urosNodePublishTopicByDesc()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is not published.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name string.
* @param[in] typep
* Pointer to the topic message type name string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t urosNodePublishTopic(const UrosString *namep,
const UrosString *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
static UrosNode *const np = &urosNode;
UrosTopic *topicp;
const UrosMsgType *statictypep;
UrosListNode *topicnodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(procf != NULL);
urosAssert(!flags.service);
/* Get the registered message type.*/
statictypep = urosFindStaticMsgType(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown message type [%.*s]\n", UROS_STRARG(typep)));
/* Check if the topic already exists.*/
urosMutexLock(&np->status.pubTopicListLock);
topicnodep = urosTopicListFindByName(&np->status.pubTopicList, namep);
urosMutexUnlock(&np->status.pubTopicListLock);
urosError(topicnodep != NULL, return UROS_ERR_BADPARAM,
("Topic [%.*s] already published\n", UROS_STRARG(namep)));
/* Create a new topic descriptor.*/
topicp = urosNew(NULL, UrosTopic);
if (topicp == NULL) { return UROS_ERR_NOMEM; }
urosTopicObjectInit(topicp);
topicp->name = urosStringClone(namep);
topicp->typep = statictypep;
topicp->procf = procf;
topicp->flags = flags;
/* Publish the topic.*/
err = urosNodePublishTopicByDesc(topicp);
if (err != UROS_OK) { urosTopicDelete(topicp); }
return err;
}
/**
* @brief Publishes a topic.
* @details Issues a @p publishTopic() call to the XMLRPC Master.
* @see urosRpcCallRegisterPublisher()
* @see urosNodePublishTopicByDesc()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is not published.
* @pre The TPCROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name null-terminated string.
* @param[in] typep
* Pointer to the topic message type name null-terminated string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t urosNodePublishTopicSZ(const char *namep,
const char *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
UrosString namestr, typestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(procf != NULL);
urosAssert(!flags.service);
namestr = urosStringAssignZ(namep);
typestr = urosStringAssignZ(typep);
return urosNodePublishTopic(&namestr, &typestr, procf, flags);
}
/**
* @brief Publishes a topic by its descriptor.
* @details Issues a @p publishTopic() call to the XMLRPC Master.
* @see urosRpcCallRegisterPublisher()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is not published.
* @pre The topic descriptor must have the @p service flag set to @p 0.
* @post The topic descriptor is used the following way:
* - If successful, the topic descriptor is referenced by the topic
* registry, and is no longer modifiable by the caller function.
* - If unsuccessful, the topic descriptor can be deallocated by the
* caller function.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] topicp
* Pointer to the topic descriptor to be published and registered.
* @return
* Error code.
*/
uros_err_t urosNodePublishTopicByDesc(UrosTopic *topicp) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosListNode *nodep;
urosAssert(topicp != NULL);
urosAssert(urosStringNotEmpty(&topicp->name));
urosAssert(topicp->typep != NULL);
urosAssert(urosStringNotEmpty(&topicp->typep->name));
urosAssert(topicp->procf != NULL);
urosAssert(!topicp->flags.service);
urosAssert(topicp->refcnt == 0);
urosAssert(topicp->refcnt == 0);
urosRpcResponseObjectInit(&res);
urosMutexLock(&np->status.pubTopicListLock);
/* Master XMLRPC registerPublisher() */
err = urosRpcCallRegisterPublisher(
&np->config.masterAddr,
&np->config.nodeName,
&topicp->name,
&topicp->typep->name,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Error %s while registering as publisher of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(&topicp->name)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Add to the published topics list.*/
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; }
urosListNodeObjectInit(nodep);
nodep->datap = (void*)topicp;
urosListAdd(&np->status.pubTopicList, nodep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.pubTopicListLock);
urosRpcResponseClean(&res);
return err;
}
/**
* @brief Unpublishes a topic.
* @details Issues an @p unpublishTopic() call to the XMLRPC Master.
* @see urosRpcCallUnregisterPublisher()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a string which names the topic.
* @return
* Error code.
*/
uros_err_t urosNodeUnpublishTopic(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosListNode *tcprosnodep, *topicnodep;
UrosTopic *topicp;
uros_err_t err;
UrosRpcResponse res;
urosAssert(urosStringNotEmpty(namep));
/* Find the topic descriptor.*/
urosMutexLock(&np->status.pubTopicListLock);
topicnodep = urosTopicListFindByName(&np->status.pubTopicList, namep);
if (topicnodep == NULL) {
urosError(topicnodep == NULL,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Topic [%.*s] not published\n", UROS_STRARG(namep)));
}
topicp = (UrosTopic*)topicnodep->datap;
/* Unregister the topic on the Master node.*/
err = urosRpcCallUnregisterPublisher(
&np->config.masterAddr,
&np->config.nodeName,
namep,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, UROS_NOP,
("Error %s while unregistering as publisher of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Unregister the topic locally.*/
topicp->flags.deleted = UROS_TRUE;
tcprosnodep = urosListRemove(&np->status.pubTopicList, topicnodep);
urosAssert(tcprosnodep == topicnodep);
if (topicp->refcnt > 0) {
/* Tell each publishing TCPROS thread to exit.*/
urosMutexLock(&np->status.pubTcpListLock);
for (tcprosnodep = np->status.pubTcpList.headp;
tcprosnodep != NULL;
tcprosnodep = tcprosnodep->nextp) {
UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap;
if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) {
urosMutexLock(&tcpstp->threadExitMtx);
tcpstp->threadExit = UROS_TRUE;
urosMutexUnlock(&tcpstp->threadExitMtx);
}
}
urosMutexUnlock(&np->status.pubTcpListLock);
/* NOTE: The last exiting thread freeds the topic descriptor.*/
} else {
/* No TCPROS connections, just free the descriptor immediately.*/
urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete);
}
_finally:
urosMutexUnlock(&np->status.pubTopicListLock);
return err;
}
/**
* @brief Unpublishes a topic.
* @details Issues an @p unpublishTopic() call to the XMLRPC Master.
* @see urosRpcCallUnregisterPublisher()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a null-terminated string which names the topic.
* @return
* Error code.
*/
uros_err_t urosNodeUnpublishTopicSZ(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return urosNodeUnpublishTopic(&namestr);
}
/**
* @brief Subscribes to a topic.
* @details Issues a @p registerSubscriber() call to the XMLRPC Master, and
* connects to known publishers.
* @see urosNodeSubscribeTopicByDesc()
* @see urosRpcCallRegisterSubscriber()
* @see urosNodeFindNewPublishers()
* @see urosRpcSlaveConnectToPublishers()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* subscribe/unsubscribe to any topics.
*
* @pre The topic is not subscribed.
* @post Connects to known publishers listed by a successful response.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name string.
* @param[in] typep
* Pointer to the topic message type name string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t urosNodeSubscribeTopic(const UrosString *namep,
const UrosString *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
static UrosNode *const np = &urosNode;
UrosTopic *topicp;
const UrosMsgType *statictypep;
UrosListNode *topicnodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(procf != NULL);
urosAssert(!flags.service);
/* Get the registered message type.*/
statictypep = urosFindStaticMsgType(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown message type [%.*s]\n", UROS_STRARG(typep)));
/* Check if the topic already exists.*/
urosMutexLock(&np->status.subTopicListLock);
topicnodep = urosTopicListFindByName(&np->status.subTopicList, namep);
urosMutexUnlock(&np->status.subTopicListLock);
urosError(topicnodep != NULL, return UROS_ERR_BADPARAM,
("Topic [%.*s] already subscribed\n", UROS_STRARG(namep)));
/* Create a new topic descriptor.*/
topicp = urosNew(NULL, UrosTopic);
if (topicp == NULL) { return UROS_ERR_NOMEM; }
urosTopicObjectInit(topicp);
topicp->name = urosStringClone(namep);
topicp->typep = statictypep;
topicp->procf = procf;
topicp->flags = flags;
/* Subscribe to the topic.*/
err = urosNodeSubscribeTopicByDesc(topicp);
if (err != UROS_OK) { urosTopicDelete(topicp); }
return err;
}
/**
* @brief Subscribes to a topic.
* @details Issues a @p registerSubscriber() call to the XMLRPC Master, and
* connects to known publishers.
* @see urosNodeSubscribeTopicByDesc()
* @see urosRpcCallRegisterSubscriber()
* @see urosNodeFindNewPublishers()
* @see urosRpcSlaveConnectToPublishers()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* subscribe/unsubscribe to any topics.
*
* @pre The topic is not subscribed.
* @post Connects to known publishers listed by a successful response.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] namep
* Pointer to the topic name null-terminated string.
* @param[in] typep
* Pointer to the topic message type name null-terminated string.
* @param[in] procf
* Topic handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t urosNodeSubscribeTopicSZ(const char *namep,
const char *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
UrosString namestr, typestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(procf != NULL);
urosAssert(!flags.service);
namestr = urosStringAssignZ(namep);
typestr = urosStringAssignZ(typep);
return urosNodeSubscribeTopic(&namestr, &typestr, procf, flags);
}
/**
* @brief Subscribes to a topic by its descriptor.
* @details Issues a @p registerSubscriber() call to the XMLRPC Master, and
* connects to known publishers.
* @see urosRpcCallRegisterSubscriber()
* @see urosNodeFindNewPublishers()
* @see urosRpcSlaveConnectToPublishers()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* subscribe/unsubscribe to any topics.
*
* @pre The topic is not subscribed.
* @pre The topic descriptor must have the @p service flag set to @p 0.
* @post The topic descriptor is used the following way:
* - If successful, the topic descriptor is referenced by the topic
* registry, and is no longer modifiable by the caller function.
* - If unsuccessful, the topic descriptor can be deallocated by the
* caller function.
* @post Connects to known publishers listed by a successful response.
* @pre The TCPROS @p service flag must be clear.
*
* @param[in] topicp
* Pointer to the topic descriptor to be subscribed to and registered.
* @return
* Error code.
*/
uros_err_t urosNodeSubscribeTopicByDesc(UrosTopic *topicp) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosList newpubs;
UrosListNode *nodep;
urosAssert(topicp != NULL);
urosAssert(urosStringNotEmpty(&topicp->name));
urosAssert(topicp->typep != NULL);
urosAssert(urosStringNotEmpty(&topicp->typep->name));
urosAssert(topicp->procf != NULL);
urosAssert(!topicp->flags.service);
urosAssert(topicp->refcnt == 0);
urosRpcResponseObjectInit(&res);
urosListObjectInit(&newpubs);
urosMutexLock(&np->status.subTopicListLock);
/* Master XMLRPC registerSubscriber() */
err = urosRpcCallRegisterSubscriber(
&np->config.masterAddr,
&np->config.nodeName,
&topicp->name,
&topicp->typep->name,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Cannot register as subscriber of topic [%.*s]\n",
UROS_STRARG(&topicp->name)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Connect to registered publishers.*/
err = urosNodeFindNewTopicPublishers(&topicp->name, res.valuep, &newpubs);
urosError(err != UROS_OK, goto _finally,
("Error %s while finding new publishers of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(&topicp->name)));
urosRpcResponseClean(&res);
err = urosRpcSlaveConnectToPublishers(&topicp->name, &newpubs);
urosError(err != UROS_OK, goto _finally,
("Error %s while connecting to new publishers of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(&topicp->name)));
/* Add to the subscribed topics list.*/
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; }
urosListNodeObjectInit(nodep);
nodep->datap = (void*)topicp;
urosListAdd(&np->status.subTopicList, nodep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.subTopicListLock);
urosListClean(&newpubs, (uros_delete_f)urosFree);
urosRpcResponseClean(&res);
return err;
}
/**
* @brief Unsubscribes to a topic.
* @details Issues an @p unregisterSubscriber() call to the XMLRPC Master.
* @see urosRpcCallUnregisterSubscriber()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no subscribing TCPROS threads, or
* - by the last subscribing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a string which names the topic.
* @return
* Error code.
*/
uros_err_t urosNodeUnsubscribeTopic(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosListNode *tcprosnodep, *topicnodep;
UrosTopic *topicp;
UrosTcpRosStatus *tcpstp;
uros_err_t err;
UrosRpcResponse res;
urosAssert(urosStringNotEmpty(namep));
/* Find the topic descriptor.*/
urosMutexLock(&np->status.subTopicListLock);
topicnodep = urosTopicListFindByName(&np->status.subTopicList, namep);
if (topicnodep == NULL) {
urosError(topicnodep == NULL,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Topic [%.*s] not subscribed\n", UROS_STRARG(namep)));
}
topicp = (UrosTopic*)topicnodep->datap;
/* Unregister the topic on the Master node.*/
err = urosRpcCallUnregisterSubscriber(
&np->config.masterAddr,
&np->config.nodeName,
namep,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, UROS_NOP,
("Error %s while unregistering as subscriber of topic [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Unregister the topic locally.*/
topicp->flags.deleted = UROS_TRUE;
tcprosnodep = urosListRemove(&np->status.subTopicList, topicnodep);
urosAssert(tcprosnodep == topicnodep);
if (topicp->refcnt > 0) {
/* Tell each subscribing TCPROS thread to exit.*/
urosMutexLock(&np->status.subTcpListLock);
for (tcprosnodep = np->status.subTcpList.headp;
tcprosnodep != NULL;
tcprosnodep = tcprosnodep->nextp) {
tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap;
if (tcpstp->topicp == topicp && !tcpstp->topicp->flags.service) {
urosMutexLock(&tcpstp->threadExitMtx);
tcpstp->threadExit = UROS_TRUE;
urosMutexUnlock(&tcpstp->threadExitMtx);
}
}
urosMutexUnlock(&np->status.subTcpListLock);
/* NOTE: The last exiting thread freeds the topic descriptor.*/
} else {
/* No TCPROS connections, just free the descriptor immediately.*/
urosListNodeDelete(topicnodep, (uros_delete_f)urosTopicDelete);
}
_finally:
urosMutexUnlock(&np->status.subTopicListLock);
return err;
}
/**
* @brief Unsubscribes to a topic.
* @details Issues an @p unregisterSubscriber() call to the XMLRPC Master.
* @see urosRpcCallUnregisterSubscriber()
* @warning The access to the topic registry is thread-safe, but delays of the
* XMLRPC communication will delay also any other threads trying to
* publish/unpublish any topics.
*
* @pre The topic is published.
* @post If successful, the topic descriptor is dereferenced by the topic
* registry, and will be freed:
* - by this function, if there are no subscribing TCPROS threads, or
* - by the last subscribing TCPROS thread which references the topic.
*
* @param[in] namep
* Pointer to a null-terminated string which names the topic.
* @return
* Error code.
*/
uros_err_t urosNodeUnsubscribeTopicSZ(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return urosNodeUnsubscribeTopic(&namestr);
}
/**
* @brief Executes a service call.
* @details Gets the service URI from the Master node. If found, it executes
* the service call once, and the result is returned.
* @note Only a @e single call will be executed. Persistent TCPROS service
* connections need custom handlers.
*
* @pre The TCPROS @p service flag must be set, @p persistent clear.
*
* @param[in] namep
* Pointer to the service name string.
* @param[in] typep
* Pointer to the service type name string.
* @param[in] callf
* Service call handler.
* @param[in] flags
* TCPROS flags. The @p service flag must be set, and @p persistent
* must be clear.
* @param[out] resobjp
* Pointer to the allocated response object. The service result will
* be written there only if the call is successful.
* @return
* Error code.
*/
uros_err_t urosNodeCallService(const UrosString *namep,
const UrosString *typep,
uros_tcpsrvcall_t callf,
uros_topicflags_t flags,
void *resobjp) {
UrosTopic service;
UrosAddr pubaddr;
const UrosMsgType *statictypep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(callf != NULL);
urosAssert(flags.service);
urosAssert(!flags.persistent);
urosAssert(resobjp != NULL);
/* Get the registered message type.*/
statictypep = urosFindStaticSrvType(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown service type [%.*s]\n", UROS_STRARG(typep)));
/* Resolve the service provider.*/
err = urosNodeResolveServicePublisher(namep, &pubaddr);
if (err != UROS_OK) { return err; }
/* Call the client service handler.*/
urosTopicObjectInit(&service);
service.name = *namep;
service.typep = statictypep;
service.procf = (uros_proc_f)callf;
service.flags = flags;
return urosTcpRosCallService(&pubaddr, &service, resobjp);
}
/**
* @brief Executes a service call.
* @details Gets the service URI from the Master node. If found, it executes
* the service call once, and the result is returned.
* @note Only a @e single call will be executed. Persistent TCPROS service
* connections need custom handlers.
*
* @pre The TCPROS @p service flag must be set, @p persistent clear.
*
* @param[in] namep
* Pointer to the service name null-terminated string.
* @param[in] typep
* Pointer to the service type name null-terminated string.
* @param[in] callf
* Service call handler.
* @param[in] flags
* TCPROS flags. The @p service flag must be set, and @p persistent
* must be clear.
* @param[out] resobjp
* Pointer to the allocated response object. The service result will
* be written there only if the call is successful.
* @return
* Error code.
*/
uros_err_t urosNodeCallServiceSZ(const char *namep,
const char *typep,
uros_tcpsrvcall_t callf,
uros_topicflags_t flags,
void *resobjp) {
UrosTopic service;
UrosAddr pubaddr;
const UrosMsgType *statictypep;
uros_err_t err;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(callf != NULL);
urosAssert(flags.service);
urosAssert(!flags.persistent);
urosAssert(resobjp != NULL);
/* Get the registered message type.*/
statictypep = urosFindStaticSrvTypeSZ(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown service type [%s]\n", typep));
/* Resolve the service provider.*/
urosTopicObjectInit(&service);
service.name = urosStringAssignZ(namep);
err = urosNodeResolveServicePublisher(&service.name, &pubaddr);
if (err != UROS_OK) { return err; }
/* Call the client service handler.*/
service.typep = statictypep;
service.procf = (uros_proc_f)callf;
service.flags = flags;
return urosTcpRosCallService(&pubaddr, &service, resobjp);
}
/**
* @brief Executes a service call.
* @details Gets the service URI from the Master node. If found, it executes
* the service call once, and the result is returned.
* @note Only a @e single call will be executed. Persistent TCPROS service
* connections need custom handlers.
*
* @pre @p servicep->procf must address a @p uros_tcpsrvcall_t function.
* @pre The TCPROS @p service flag must be set, @p persistent clear.
*
* @param[in] servicep
* Pointer to the service descriptor.
* @param[out] resobjp
* Pointer to the allocated response object. The service result will
* be written there only if the call is successful.
* @return
* Error code.
*/
uros_err_t urosNodeCallServiceByDesc(const UrosTopic *servicep,
void *resobjp) {
UrosAddr pubaddr;
uros_err_t err;
urosAssert(servicep != NULL);
urosAssert(urosStringNotEmpty(&servicep->name));
urosAssert(servicep->typep != NULL);
urosAssert(urosStringNotEmpty(&servicep->typep->name));
urosAssert(servicep->procf != NULL);
urosAssert(servicep->flags.service);
urosAssert(!servicep->flags.persistent);
urosAssert(resobjp != NULL);
/* Resolve the service provider.*/
err = urosNodeResolveServicePublisher(&servicep->name, &pubaddr);
if (err != UROS_OK) { return err; }
/* Call the client service handler.*/
return urosTcpRosCallService(&pubaddr, servicep, resobjp);
}
/**
* @brief Publishes a service.
* @details Issues a @p registerService() call to the XMLRPC Master.
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
* @see urosNodePublishServiceByDesc()
* @see urosRpcCallRegisterService()
*
* @pre The service is not published.
* @pre The TCPROS @p service flag must be set.
*
* @param[in] namep
* Pointer to the service name string.
* @param[in] typep
* Pointer to the service type name string.
* @param[in] procf
* Service handler function.
* @param[in] flags
* Topic flags.
* @return
* Error code.
*/
uros_err_t urosNodePublishService(const UrosString *namep,
const UrosString *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
static UrosNode *const np = &urosNode;
UrosTopic *servicep;
const UrosMsgType *statictypep;
UrosListNode *servicenodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(urosStringNotEmpty(typep));
urosAssert(procf != NULL);
urosAssert(flags.service);
/* Get the registered service type.*/
statictypep = urosFindStaticSrvType(typep);
urosError(statictypep == NULL, return UROS_ERR_BADPARAM,
("Unknown message type [%.*s]\n", UROS_STRARG(typep)));
/* Check if the service already exists.*/
urosMutexLock(&np->status.pubServiceListLock);
servicenodep = urosTopicListFindByName(&np->status.pubServiceList,
namep);
urosMutexUnlock(&np->status.pubServiceListLock);
urosError(servicenodep != NULL, return UROS_ERR_BADPARAM,
("Service [%.*s] already published\n", UROS_STRARG(namep)));
/* Create a new topic descriptor.*/
servicep = urosNew(NULL, UrosTopic);
if (servicep == NULL) { return UROS_ERR_NOMEM; }
urosTopicObjectInit(servicep);
servicep->name = urosStringClone(namep);
servicep->typep = statictypep;
servicep->procf = procf;
servicep->flags = flags;
/* Try to register the topic.*/
err = urosNodePublishServiceByDesc(servicep);
if (err != UROS_OK) { urosTopicDelete(servicep); }
return err;
}
/**
* @brief Publishes a service.
* @details Issues a @p registerService() call to the XMLRPC Master.
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
* @see urosNodePublishServiceByDesc()
* @see urosRpcCallRegisterService()
*
* @pre The service is not published.
* @pre The TCPROS @p service flag must be set.
*
* @param[in] namep
* Pointer to the service name null-terminated string.
* @param[in] typep
* Pointer to the service type name null-terminated string.
* @param[in] procf
* Service handler function.
* @param[in] flags
* Service flags.
* @return
* Error code.
*/
uros_err_t urosNodePublishServiceSZ(const char *namep,
const char *typep,
uros_proc_f procf,
uros_topicflags_t flags) {
UrosString namestr, typestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
urosAssert(typep != NULL);
urosAssert(typep[0] != 0);
urosAssert(procf != NULL);
namestr = urosStringAssignZ(namep);
typestr = urosStringAssignZ(typep);
return urosNodePublishService(&namestr, &typestr, procf, flags);
}
/**
* @brief Publishes a service by its descriptor.
* @details Issues a @p registerService() call to the XMLRPC Master.
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
* @see urosRpcCallRegisterService()
*
* @pre The TCPROS @p service flag must be set.
*
* @pre The service is not published.
* @pre The service descriptor must have the @p service flag set to @p 1.
* @post - If successful, the service descriptor is referenced by the
* service registry, and is no longer modifiable by the caller
* function.
* - If unsuccessful, the service descriptor can be deallocated by the
* caller function.
*
* @param[in] servicep
* Pointer to the service descriptor to be published and registered.
* @return
* Error code.
*/
uros_err_t urosNodePublishServiceByDesc(const UrosTopic *servicep) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosListNode *nodep;
urosAssert(servicep != NULL);
urosAssert(urosStringNotEmpty(&servicep->name));
urosAssert(servicep->typep != NULL);
urosAssert(urosStringNotEmpty(&servicep->typep->name));
urosAssert(servicep->procf != NULL);
urosAssert(servicep->flags.service);
urosRpcResponseObjectInit(&res);
urosMutexLock(&np->status.pubServiceListLock);
/* Master XMLRPC registerPublisher() */
err = urosRpcCallRegisterService(
&np->config.masterAddr,
&np->config.nodeName,
&servicep->name,
&np->config.tcprosUri,
&np->config.xmlrpcUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Cannot register service [%.*s]\n",
UROS_STRARG(&servicep->name)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Add to the published topics list.*/
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) { err = UROS_ERR_NOMEM; goto _finally; }
urosListNodeObjectInit(nodep);
nodep->datap = (void*)servicep;
urosListAdd(&np->status.pubServiceList, nodep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.pubServiceListLock);
urosRpcResponseClean(&res);
return err;
}
/**
* @brief Unpublishes a service.
* @details Issues an @p unregisterService() call to the XMLRPC Master.
* @see urosRpcCallUnregisterService()
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
*
* @pre The service is published.
* @post If successful, the service descriptor is dereferenced by the
* service registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the
* service.
*
* @param[in] namep
* Pointer to a string which names the service.
* @return
* Error code.
*/
uros_err_t urosNodeUnpublishService(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosListNode *tcprosnodep, *servicenodep;
UrosTopic *servicep;
uros_err_t err;
UrosRpcResponse res;
urosAssert(urosStringNotEmpty(namep));
/* Find the service descriptor.*/
urosMutexLock(&np->status.pubServiceListLock);
servicenodep = urosTopicListFindByName(&np->status.pubServiceList,
namep);
urosError(servicenodep == NULL,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Service [%.*s] not published\n", UROS_STRARG(namep)));
servicep = (UrosTopic*)servicenodep->datap;
/* Unregister the service on the Master node.*/
err = urosRpcCallUnregisterService(
&np->config.masterAddr,
&np->config.nodeName,
namep,
&np->config.tcprosUri,
&res
);
urosError(err != UROS_OK, goto _finally,
("Error %s while unregistering as publisher of service [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Unregister the service locally.*/
servicep->flags.deleted = UROS_TRUE;
tcprosnodep = urosListRemove(&np->status.pubServiceList, servicenodep);
urosAssert(tcprosnodep == servicenodep);
if (np->status.pubTcpList.length > 0) {
/* Tell each publishing TCPROS thread to exit.*/
urosMutexLock(&np->status.pubTcpListLock);
for (tcprosnodep = np->status.pubTcpList.headp;
tcprosnodep != NULL;
tcprosnodep = tcprosnodep->nextp) {
UrosTcpRosStatus *tcpstp = (UrosTcpRosStatus*)tcprosnodep->datap;
if (tcpstp->topicp == servicep && tcpstp->topicp->flags.service) {
urosMutexLock(&tcpstp->threadExitMtx);
tcpstp->threadExit = UROS_TRUE;
urosMutexUnlock(&tcpstp->threadExitMtx);
}
}
urosMutexUnlock(&np->status.pubTcpListLock);
/* NOTE: The last exiting thread freeds the service descriptor.*/
} else {
/* No TCPROS connections, just free the descriptor immediately.*/
urosListNodeDelete(servicenodep, (uros_delete_f)urosTopicDelete);
}
_finally:
urosMutexUnlock(&np->status.pubServiceListLock);
return err;
}
/**
* @brief Unpublishes a service.
* @details Issues an @p unregisterService() call to the XMLRPC Master.
* @see urosRpcCallUnregisterService()
* @warning The access to the service registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to publish/unpublish any services.
*
* @pre The service is published.
* @post If successful, the service descriptor is dereferenced by the
* service registry, and will be freed:
* - by this function, if there are no publishing TCPROS threads, or
* - by the last publishing TCPROS thread which references the
* service.
*
* @param[in] namep
* Pointer to a null-terminated string which names the service.
* @return
* Error code.
*/
uros_err_t urosNodeUnpublishServiceSZ(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return urosNodeUnpublishService(&namestr);
}
/**
* @brief Subscribes to a parameter by its descriptor.
* @details Issues a @p subscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see urosRpcCallSubscribeParam()
* @see urosNodeSubscribeParamByDesc()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has not been registered yet.
*
* @param[in] namep
* Pointer to the parameter name string.
* @return
* Error code.
*/
uros_err_t urosNodeSubscribeParam(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosString *clonednamep;
UrosListNode *paramnodep;
UrosRpcResponse res;
UrosListNode *nodep;
uros_err_t err;
urosAssert(urosStringNotEmpty(namep));
/* Check if the parameter already exists.*/
urosMutexLock(&np->status.subParamListLock);
paramnodep = urosStringListFindByName(&np->status.subParamList, namep);
urosMutexUnlock(&np->status.subParamListLock);
urosError(paramnodep != NULL, return UROS_ERR_BADPARAM,
("Parameter [%.*s] already subscribed\n", UROS_STRARG(namep)));
/* Create the storage data in advance.*/
clonednamep = urosNew(NULL, UrosString);
if (clonednamep == NULL) { return UROS_ERR_NOMEM; }
*clonednamep = urosStringClone(namep);
nodep = urosNew(NULL, UrosListNode);
if (clonednamep->datap == NULL || nodep == NULL) {
urosStringDelete(clonednamep); urosFree(nodep);
return UROS_ERR_NOMEM;
}
/* Subscribe to the topic.*/
urosRpcResponseObjectInit(&res);
urosMutexLock(&np->status.subParamListLock);
/* Master XMLRPC registerSubscriber() */
err = urosRpcCallSubscribeParam(
&np->config.masterAddr,
&np->config.nodeName,
&np->config.xmlrpcUri,
namep,
&res
);
urosError(err != UROS_OK, goto _finally,
("Error %s while subscribing to parameter [%.*s]\n",
urosErrorText(err), UROS_STRARG(namep)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %d, expected %d\n",
res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %d, expected 200\n", res.httpcode));
/* Add to the subscribed parameter list.*/
urosListNodeObjectInit(nodep);
nodep->datap = (void*)clonednamep;
urosListAdd(&np->status.subParamList, nodep);
/* Update to the current value.*/
urosUserParamUpdate(namep, res.valuep);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.subParamListLock);
urosRpcResponseClean(&res);
return err;
}
/**
* @brief Subscribes to a parameter.
* @details Issues a @p subscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see urosRpcCallSubscribeParam()
* @see urosNodeSubscribeParamByDesc()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has not been registered yet.
*
* @param[in] namep
* Pointer to the parameter name null-terminated string.
* @return
* Error code.
*/
uros_err_t urosNodeSubscribeParamSZ(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return urosNodeSubscribeParam(&namestr);
}
/**
* @brief Subscribes to a parameter.
* @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see urosRpcCallUnubscribeParam()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has been registered.
* @post If successful, the parameter descriptor is unreferenced and deleted
* by the parameter registry.
*
* @param[in] namep
* Pointer to a string which names the parameter to be unregistered.
* @return
* Error code.
*/
uros_err_t urosNodeUnsubscribeParam(const UrosString *namep) {
static UrosNode *const np = &urosNode;
UrosRpcResponse res;
uros_err_t err;
UrosListNode *nodep;
urosAssert(urosStringNotEmpty(namep));
urosRpcResponseObjectInit(&res);
urosMutexLock(&np->status.subParamListLock);
/* Check if the parameter was actually subscribed.*/
nodep = urosStringListFindByName(&np->status.subParamList, namep);
urosError(nodep == NULL, { err = UROS_ERR_BADPARAM; goto _finally; },
("Parameter [%.*s] not found\n", UROS_STRARG(namep)));
/* Master XMLRPC registerSubscriber() */
err = urosRpcCallUnsubscribeParam(
&np->config.masterAddr,
&np->config.nodeName,
&np->config.xmlrpcUri,
namep,
&res
);
urosError(err != UROS_OK, goto _finally,
("Cannot unsubscribe from param [%.*s]\n",
UROS_STRARG(namep)));
/* Check for valid codes.*/
urosError(res.code != UROS_RPCC_SUCCESS,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response code %ld, expected %d\n",
(long int)res.code, UROS_RPCC_SUCCESS));
urosError(res.httpcode != 200,
{ err = UROS_ERR_BADPARAM; goto _finally; },
("Response HTTP code %ld, expected 200\n",
(long int)res.httpcode));
/* Remove from the subscribed parameter list and delete.*/
nodep = urosListRemove(&np->status.subParamList, nodep);
urosAssert(nodep != NULL);
urosListNodeDelete(nodep, (uros_delete_f)urosStringDelete);
err = UROS_OK;
_finally:
/* Cleanup and return.*/
urosMutexUnlock(&np->status.subParamListLock);
urosRpcResponseClean(&res);
return err;
}
/**
* @brief Subscribes to a parameter.
* @details Issues an @p unsubscribeParam() call to the XMLRPC Master, and
* connects to known publishers.
* @see urosRpcCallUnubscribeParam()
* @warning The access to the parameter registry is thread-safe, but delays of
* the XMLRPC communication will delay also any other threads trying
* to subscribe/unsubscribe to any parameters.
*
* @pre The parameter has been registered.
* @post If successful, the parameter descriptor is unreferenced and deleted
* by the parameter registry.
*
* @param[in] namep
* Pointer to a null-terminated string which names the parameter to be
* unregistered.
* @return
* Error code.
*/
uros_err_t urosNodeUnsubscribeParamSZ(const char *namep) {
UrosString namestr;
urosAssert(namep != NULL);
urosAssert(namep[0] != 0);
namestr = urosStringAssignZ(namep);
return urosNodeUnsubscribeParam(&namestr);
}
/**
* @brief Find new publishers for a given topic.
* @details Scans through the provided publishers list to look for any new
* publishers.
*
* @param[in] namep
* Pointer to a non-empty string which names the targeted topic.
* @param[in] publishersp
* Pointer to an @p UrosRpcParam with @p UROS_RPCP_ARRAY pclass.
* It contains the list of current publishers, received for example
* through a XMLRPC call to @p subscribeTopic(). Each publisher is
* addressed by its URI.
* @param[out] newpubsp
* Pointer to an empty list which will be populated by the newly
* discovered publishers, if any.
* @return
* Error code.
*/
uros_err_t urosNodeFindNewTopicPublishers(const UrosString *namep,
const UrosRpcParam *publishersp,
UrosList *newpubsp) {
static UrosNode *const np = &urosNode;
uros_err_t err;
const UrosListNode *tcpnodep;
const UrosRpcParamNode *paramnodep;
const UrosTcpRosStatus *tcpstp, *tcpfoundp;
const UrosString *urip;
UrosAddr pubaddr;
(void)err;
urosAssert(urosStringNotEmpty(namep));
urosAssert(publishersp != NULL);
urosAssert(publishersp->pclass == UROS_RPCP_ARRAY);
urosAssert(publishersp->value.listp != NULL);
urosAssert(urosListIsValid(newpubsp));
urosAssert(newpubsp->length == 0);
/* Build a list of newly discovered publishers.*/
urosMutexLock(&np->status.subTcpListLock);
for (paramnodep = publishersp->value.listp->headp;
paramnodep != NULL;
paramnodep = paramnodep->nextp) {
urip = ¶mnodep->param.value.string;
err = urosUriToAddr(urip, &pubaddr);
urosAssert(err == UROS_OK);
tcpfoundp = NULL;
for (tcpnodep = np->status.subTcpList.headp;
tcpnodep != NULL;
tcpnodep = tcpnodep->nextp) {
tcpstp = (const UrosTcpRosStatus *)tcpnodep->datap;
if (tcpstp->topicp->flags.service == UROS_FALSE) {
urosAssert(tcpstp->topicp != NULL);
if (0 == urosStringCmp(&tcpstp->topicp->name, namep)) {
urosAssert(tcpstp->csp != NULL);
if (tcpstp->csp->remaddr.ip.dword == pubaddr.ip.dword &&
tcpstp->csp->remaddr.port == pubaddr.port) {
tcpfoundp = tcpstp;
}
}
}
}
if (tcpfoundp == NULL) {
UrosAddr *addrp;
UrosListNode *nodep;
/* New publisher.*/
addrp = urosNew(NULL, UrosAddr);
if (addrp == NULL) {
urosMutexUnlock(&np->status.subTcpListLock);
return UROS_ERR_NOMEM;
}
nodep = urosNew(NULL, UrosListNode);
if (nodep == NULL) {
urosFree(addrp);
urosMutexUnlock(&np->status.subTcpListLock);
return UROS_ERR_NOMEM;
}
*addrp = pubaddr;
nodep->datap = addrp;
nodep->nextp = NULL;
urosListAdd(newpubsp, nodep);
}
}
urosMutexUnlock(&np->status.subTcpListLock);
return UROS_OK;
}
/**
* @brief Gets the TCPROS URI of a topic publisher.
* @details Requests the TCPROS URI of a topic published by a node.
*
* @param[in] apiaddrp
* XMLRPC API address of the target node.
* @param[in] namep
* Pointer to the topic name string.
* @param[out] tcprosaddrp
* Pointer to an allocated @p UrosAddr descriptor, which will hold the
* TCPROS API address of the requested topic provider.
* @return
* Error code.
*/
uros_err_t urosNodeResolveTopicPublisher(const UrosAddr *apiaddrp,
const UrosString *namep,
UrosAddr *tcprosaddrp) {
static const UrosRpcParamNode tcprosnode = {
{ UROS_RPCP_STRING, {{ 6, "TCPROS" }} }, NULL
};
static const UrosRpcParamList tcproslist = {
(UrosRpcParamNode*)&tcprosnode, (UrosRpcParamNode*)&tcprosnode, 1
};
static const UrosRpcParamNode protonode = {
{ UROS_RPCP_ARRAY, {{ (size_t)&tcproslist, NULL }} }, NULL
};
static const UrosRpcParamList protolist = {
(UrosRpcParamNode*)&protonode, (UrosRpcParamNode*)&protonode, 1
};
uros_err_t err;
UrosRpcParamNode *nodep;
UrosRpcParam *paramp;
UrosRpcResponse res;
urosAssert(apiaddrp != NULL);
urosAssert(urosStringNotEmpty(namep));
urosAssert(tcprosaddrp != NULL);
#define _ERR { err = UROS_ERR_BADPARAM; goto _finally; }
/* Request the topic to the publisher.*/
urosRpcResponseObjectInit(&res);
err = urosRpcCallRequestTopic(
apiaddrp,
&urosNode.config.nodeName,
namep,
&protolist,
&res
);
/* Check for valid values.*/
if (err != UROS_OK) { goto _finally; }
urosError(res.httpcode != 200, _ERR,
("The HTTP response code is %lu, expected 200\n",
(long unsigned int)res.httpcode));
if (res.code != UROS_RPCC_SUCCESS) { _ERR }
urosError(res.valuep->pclass != UROS_RPCP_ARRAY, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_ARRAY)\n",
(int)res.valuep->pclass, (int)UROS_RPCP_ARRAY));
urosAssert(res.valuep->value.listp != NULL);
urosError(res.valuep->value.listp->length != 3, _ERR,
("Response value array length %lu, expected 3",
(long unsigned int)res.valuep->value.listp->length));
nodep = res.valuep->value.listp->headp;
/* Check the protocol string.*/
paramp = &nodep->param; nodep = nodep->nextp;
urosError(paramp->pclass != UROS_RPCP_STRING, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n",
(int)paramp->pclass, (int)UROS_RPCP_STRING));
urosError(0 != urosStringCmp(&tcprosnode.param.value.string,
¶mp->value.string), _ERR,
("Response protocol is [%.*s], expected [TCPROS]\n",
UROS_STRARG(&tcprosnode.param.value.string)));
/* Check the node hostname string.*/
paramp = &nodep->param; nodep = nodep->nextp;
urosError(paramp->pclass != UROS_RPCP_STRING, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n",
(int)paramp->pclass, (int)UROS_RPCP_STRING));
err = urosHostnameToIp(¶mp->value.string, &tcprosaddrp->ip);
urosError(err != UROS_OK, goto _finally,
("Cannot resolve hostname [%.*s]",
UROS_STRARG(¶mp->value.string)));
/* Check the node port number.*/
paramp = &nodep->param;
urosError(paramp->pclass != UROS_RPCP_INT, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_INT)\n",
(int)paramp->pclass, (int)UROS_RPCP_INT));
urosError(paramp->value.int32 < 0 || paramp->value.int32 > 65535, _ERR,
("Port number %ld outside range\n",
(long int)paramp->value.int32));
tcprosaddrp->port = (uint16_t)paramp->value.int32;
err = UROS_OK;
_finally:
urosRpcResponseClean(&res);
return err;
#undef _ERR
}
/**
* @brief Gets the TCPROS URI of a service publisher.
* @details Requests the TCPROS URI of a service published by a node.
*
* @param[in] namep
* Pointer to the topic name string.
* @param[out] pubaddrp
* Pointer to an allocated @p UrosAddr descriptor, which will hold the
* TCPROS API address of the requested service provider.
* @return
* Error code.
*/
uros_err_t urosNodeResolveServicePublisher(const UrosString *namep,
UrosAddr *pubaddrp) {
static const UrosNodeConfig *const cfgp = &urosNode.config;
uros_err_t err;
UrosRpcResponse res;
UrosString *uristrp;
urosAssert(urosStringNotEmpty(namep));
urosAssert(pubaddrp != NULL);
#define _ERR { err = UROS_ERR_BADPARAM; goto _finally; }
/* Lookup the service URI.*/
urosRpcResponseObjectInit(&res);
err = urosRpcCallLookupService(
&cfgp->masterAddr,
&cfgp->nodeName,
namep,
&res
);
/* Check for valid values.*/
if (err != UROS_OK) { goto _finally; }
urosError(res.httpcode != 200, _ERR,
("The HTTP response code is %lu, expected 200\n",
(long unsigned int)res.httpcode));
urosError(res.code != UROS_RPCC_SUCCESS, _ERR,
("Cannot find a provider for service [%.*s]\n",
UROS_STRARG(namep)));
urosError(res.valuep->pclass != UROS_RPCP_STRING, _ERR,
("Response value pclass is %d, expected %d (UROS_RPCP_STRING)\n",
(int)res.valuep->pclass, (int)UROS_RPCP_STRING));
uristrp = &res.valuep->value.string;
res.valuep->value.string = urosStringAssignZ(NULL);
urosRpcResponseClean(&res);
urosAssert(urosStringIsValid(uristrp));
urosError(uristrp->length == 0, _ERR, ("Service URI string is empty\n"));
/* Resolve the service address.*/
err = urosUriToAddr(uristrp, pubaddrp);
_finally:
urosRpcResponseClean(&res);
return err;
#undef _ERR
}
/** @} */
|
Java
|
import numpy as np
from scipy.sparse import csr_matrix
class AliasArray(np.ndarray):
"""An ndarray with a mapping of values to user-friendly names -- see example
This ndarray subclass enables comparing sub_id and hop_id arrays directly with
their friendly string identifiers. The mapping parameter translates sublattice
or hopping names into their number IDs.
Only the `==` and `!=` operators are overloaded to handle the aliases.
Examples
--------
>>> a = AliasArray([0, 1, 0], mapping={"A": 0, "B": 1})
>>> list(a == 0)
[True, False, True]
>>> list(a == "A")
[True, False, True]
>>> list(a != "A")
[False, True, False]
>>> a = AliasArray([0, 1, 0, 2], mapping={"A|1": 0, "B": 1, "A|2": 2})
>>> list(a == "A")
[True, False, True, True]
>>> list(a != "A")
[False, True, False, False]
"""
def __new__(cls, array, mapping):
obj = np.asarray(array).view(cls)
obj.mapping = {SplitName(k): v for k, v in mapping.items()}
return obj
def __array_finalize__(self, obj):
if obj is None:
return
self.mapping = getattr(obj, "mapping", None)
def _mapped_eq(self, other):
if other in self.mapping:
return super().__eq__(self.mapping[other])
else:
result = np.zeros(len(self), dtype=np.bool)
for k, v in self.mapping.items():
if k == other:
result = np.logical_or(result, super().__eq__(v))
return result
def __eq__(self, other):
if isinstance(other, str):
return self._mapped_eq(other)
else:
return super().__eq__(other)
def __ne__(self, other):
if isinstance(other, str):
return np.logical_not(self._mapped_eq(other))
else:
return super().__ne__(other)
# noinspection PyAbstractClass
class AliasCSRMatrix(csr_matrix):
"""Same as :class:`AliasArray` but for a CSR matrix
Examples
--------
>>> from scipy.sparse import spdiags
>>> m = AliasCSRMatrix(spdiags([1, 2, 1], [0], 3, 3), mapping={'A': 1, 'B': 2})
>>> list(m.data == 'A')
[True, False, True]
>>> list(m.tocoo().data == 'A')
[True, False, True]
>>> list(m[:2].data == 'A')
[True, False]
"""
def __init__(self, *args, **kwargs):
mapping = kwargs.pop('mapping', {})
if not mapping:
mapping = getattr(args[0], 'mapping', {})
super().__init__(*args, **kwargs)
self.data = AliasArray(self.data, mapping)
@property
def format(self):
return 'csr'
@format.setter
def format(self, _):
pass
@property
def mapping(self):
return self.data.mapping
def tocoo(self, *args, **kwargs):
coo = super().tocoo(*args, **kwargs)
coo.data = AliasArray(coo.data, mapping=self.mapping)
return coo
def __getitem__(self, item):
result = super().__getitem__(item)
if getattr(result, 'format', '') == 'csr':
return AliasCSRMatrix(result, mapping=self.mapping)
else:
return result
class AliasIndex:
"""An all-or-nothing array index based on equality with a specific value
The `==` and `!=` operators are overloaded to return a lazy array which is either
all `True` or all `False`. See the examples below. This is useful for modifiers
where the each call gets arrays with the same sub_id/hop_id for all elements.
Instead of passing an `AliasArray` with `.size` identical element, `AliasIndex`
does the same all-or-nothing indexing.
Examples
--------
>>> l = np.array([1, 2, 3])
>>> ai = AliasIndex("A", len(l))
>>> list(l[ai == "A"])
[1, 2, 3]
>>> list(l[ai == "B"])
[]
>>> list(l[ai != "A"])
[]
>>> list(l[ai != "B"])
[1, 2, 3]
>>> np.logical_and([True, False, True], ai == "A")
array([ True, False, True], dtype=bool)
>>> np.logical_and([True, False, True], ai != "A")
array([False, False, False], dtype=bool)
>>> bool(ai == "A")
True
>>> bool(ai != "A")
False
>>> str(ai)
'A'
>>> hash(ai) == hash("A")
True
>>> int(ai.eye)
1
>>> np.allclose(AliasIndex("A", 1, (2, 2)).eye, np.eye(2))
True
"""
class LazyArray:
def __init__(self, value, shape):
self.value = value
self.shape = shape
def __bool__(self):
return bool(self.value)
def __array__(self):
return np.full(self.shape, self.value)
def __init__(self, name, shape, orbs=(1, 1)):
self.name = name
self.shape = shape
self.orbs = orbs
def __str__(self):
return self.name
def __eq__(self, other):
return self.LazyArray(self.name == other, self.shape)
def __ne__(self, other):
return self.LazyArray(self.name != other, self.shape)
def __hash__(self):
return hash(self.name)
@property
def eye(self):
return np.eye(*self.orbs)
class SplitName(str):
"""String subclass with special support for strings of the form "first|second"
Operators `==` and `!=` are overloaded to return `True` even if only the first part matches.
Examples
--------
>>> s = SplitName("first|second")
>>> s == "first|second"
True
>>> s != "first|second"
False
>>> s == "first"
True
>>> s != "first"
False
>>> s == "second"
False
>>> s != "second"
True
"""
@property
def first(self):
return self.split("|")[0]
def __eq__(self, other):
return super().__eq__(other) or self.first == other
def __ne__(self, other):
return super().__ne__(other) and self.first != other
def __hash__(self):
return super().__hash__()
|
Java
|
package org.mastodon.tracking.mamut.trackmate.wizard;
import org.mastodon.mamut.model.Link;
import org.mastodon.mamut.model.Model;
import org.mastodon.mamut.model.Spot;
import org.mastodon.model.AbstractModelImporter;
public class CreateLargeModelExample
{
private static final int N_STARTING_CELLS = 6;
private static final int N_DIVISIONS = 17;
private static final int N_FRAMES_PER_DIVISION = 5;
private static final double VELOCITY = 5;
private static final double RADIUS = 3;
private final Model model;
public CreateLargeModelExample()
{
this.model = new Model();
}
public Model run()
{
return run( N_STARTING_CELLS, N_DIVISIONS, N_FRAMES_PER_DIVISION );
}
public Model run( final int nStartingCells, final int nDivisions, final int nFramesPerDivision )
{
new AbstractModelImporter< Model >( model ){{ startImport(); }};
final Spot tmp = model.getGraph().vertexRef();
for ( int ic = 0; ic < nStartingCells; ic++ )
{
final double angle = 2d * ic * Math.PI / N_STARTING_CELLS;
final double vx = VELOCITY * Math.cos( angle );
final double vy = VELOCITY * Math.sin( angle );
// final int nframes = N_DIVISIONS * N_FRAMES_PER_DIVISION;
final double x = 0.; // nframes * VELOCITY + vx;
final double y = 0.; // nframes * VELOCITY + vy;
final double z = N_DIVISIONS * VELOCITY;
final double[] pos = new double[] { x, y, z };
final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } };
final Spot mother = model.getGraph().addVertex( tmp ).init( 0, pos, cov );
addBranch( mother, vx, vy, 1, nDivisions, nFramesPerDivision );
}
model.getGraph().releaseRef( tmp );
new AbstractModelImporter< Model >( model ){{ finishImport(); }};
return model;
}
private void addBranch( final Spot start, final double vx, final double vy, final int iteration, final int nDivisions, final int nFramesPerDivision )
{
if ( iteration >= nDivisions ) { return; }
final Spot previousSpot = model.getGraph().vertexRef();
final Spot spot = model.getGraph().vertexRef();
final Spot daughter = model.getGraph().vertexRef();
final Link link = model.getGraph().edgeRef();
final double[] pos = new double[ 3 ];
final double[][] cov = new double[][] { { RADIUS, 0, 0 }, { 0, RADIUS, 0 }, { 0, 0, RADIUS } };
// Extend
previousSpot.refTo( start );
for ( int it = 0; it < nFramesPerDivision; it++ )
{
pos[ 0 ] = previousSpot.getDoublePosition( 0 ) + vx;
pos[ 1 ] = previousSpot.getDoublePosition( 1 ) + vy;
pos[ 2 ] = previousSpot.getDoublePosition( 2 );
final int frame = previousSpot.getTimepoint() + 1;
model.getGraph().addVertex( spot ).init( frame, pos, cov );
model.getGraph().addEdge( previousSpot, spot, link ).init();
previousSpot.refTo( spot );
}
// Divide
for ( int id = 0; id < 2; id++ )
{
final double sign = id == 0 ? 1 : -1;
final double x;
final double y;
final double z;
if ( iteration % 2 == 0 )
{
x = previousSpot.getDoublePosition( 0 );
y = previousSpot.getDoublePosition( 1 );
z = previousSpot.getDoublePosition( 2 ) + sign * VELOCITY * ( 1 - 0.5d * iteration / nDivisions ) * 2;
}
else
{
x = previousSpot.getDoublePosition( 0 ) - sign * vy * ( 1 - 0.5d * iteration / nDivisions ) * 2;
y = previousSpot.getDoublePosition( 1 ) + sign * vx * ( 1 - 0.5d * iteration / nDivisions ) * 2;
z = previousSpot.getDoublePosition( 2 );
}
final int frame = previousSpot.getTimepoint() + 1;
pos[ 0 ] = x;
pos[ 1 ] = y;
pos[ 2 ] = z;
model.getGraph().addVertex( daughter ).init( frame, pos, cov );
model.getGraph().addEdge( previousSpot, daughter, link ).init();
addBranch( daughter, vx, vy, iteration + 1, nDivisions, nFramesPerDivision );
}
model.getGraph().releaseRef( previousSpot );
model.getGraph().releaseRef( spot );
model.getGraph().releaseRef( daughter );
model.getGraph().releaseRef( link );
}
public static void main( final String[] args )
{
final CreateLargeModelExample clme = new CreateLargeModelExample();
final long start = System.currentTimeMillis();
final Model model = clme.run();
final long end = System.currentTimeMillis();
System.out.println( "Model created in " + ( end - start ) + " ms." );
System.out.println( "Total number of spots: " + model.getGraph().vertices().size() );
System.out.println( String.format( "Total memory used by the model: %.1f MB", ( Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory() ) / 1e6d ) );
}
}
|
Java
|
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at progrium@gmail.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
|
Java
|
/* Copyright (c) 2016-2017, Artem Kashkanov
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* 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.
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.*/
#ifndef IMAGE_H_
#define IMAGE_H_
#include <cstdlib>
#include <vector>
#include <fstream>
#include <iostream>
#include "bfutils.h"
#include "cmd.h"
#include <string.h>
class Section{
public:
Section(std::vector<Cmd> &SectionCmd, uint16_t MemoryBase, uint16_t MemorySize);
Section(std::vector<uint16_t> &SectionData,
uint16_t MemoryBase, uint16_t MemorySize);
Section(std::fstream &File);
~Section();
uint8_t GetType(){return Hdr.type;};
uint16_t GetFileBase(){return Hdr.FileBase;};
uint16_t GetMemoryBase(){return Hdr.MemoryBase;};
uint16_t GetFileSize(){return Hdr.FileSize;};
uint16_t GetMemorySize(){return Hdr.MemorySize;};
void WriteHeader(std::fstream &File);
void WriteData(std::fstream &File);
uint16_t *GetData(){return Data;};
bool Error(){return err;};
private:
bool err;
BfSection_t Hdr;
uint16_t *Data;
};
class Image{
public:
Image(std::fstream &File, bool hex);
Image(uint8_t _machine);
~Image();
void AddSection(Section §ion);
uint8_t GetSectionNum(void){return Hdr.SectionNum;};
Section &GetSection(uint8_t section){return Sections[section];};
void SetIpEntry(ADDRESS_TYPE Ptr){Hdr.IpEntry = Ptr;};
void SetApEntry(ADDRESS_TYPE Ptr){Hdr.ApEntry = Ptr;};
ADDRESS_TYPE GetIpEntry(){return Hdr.IpEntry;};
ADDRESS_TYPE GetApEntry(){return Hdr.ApEntry;};
bool ReadHex(std::fstream &File);
void Write(std::fstream &File);
bool Error(){return err;};
private:
bool m_hex;
bool err;
BfHeader_t Hdr;
std::vector<Section> Sections;
};
#endif //IMAGE_H_
|
Java
|
#{extends 'main.html' /} #{set title:'FAQ' /}
#{set faq:'active'/}
#{set title:'FAQ'/}
<div class="page-header">
<h1>Frequently Asked Questions
<a class="btn btn-primary login pull-right" href="@{Login.auth()}">Login with Dropbox</a>
<a class="btn btn-primary login pull-right" href="@{Login.boxAuth()}">Login with Box</a>
</h1>
</div>
<div class="well faq">
<h3>What is SortMyBox?</h3>
<p>SortMyBox is a magic folder inside your cloud storage folder.
Save new files there and we will move them based on rules you create.
Like e-mail filters, for your Dropbox.</p>
<h3>How does SortMyBox work?</h3>
<p>We check the contents of your SortMyBox folder every 15 minutes. If there are any files that match any of your
rules, we will move them to their correct location. We also log all file moves so you never lose a file.</p>
<h3>Is SortMyBox for me?</h3>
<p>Yes! Whether you're keeping your photos and videos organized or sharing documents with other people, SortMyBox will keep your files organized.</p>
<h3>How do I begin?</h3>
<p>Login using your <a href="@{Login.login()}">Dropbox</a> or <a href="@{Login.boxAuth()}">Box</a> account and
we will create a SortMyBox folder and some sample rules for you.
Save your files in this folder and you're good to go.</p>
<h3>Why do I have to provide access for my Dropbox/Box account?</h3>
<p>SortMyBox needs permission to move files around and put them in the appropriate folders. SortMyBox will never use your access for any other purposes.</p>
<h3>What sorting options do I have?</h3>
<p>We have 3 kinds of rules: </p>
<dl class="dl-horizontal">
<dt>Name Contains:</dt>
<dd>Move similarly named files to an appropriate folder.</dd>
<dd>A rule with the pattern <code>venice 2011</code> matches files named
<code>jen birthday venice 2011.jpg</code> or
<code>gondola venice 2011.jpg</code>.</dd>
<dt>Extension equals:</dt>
<dd>Files with a matching extension will be moved to an appropriate folder.</dd>
<dd>A rule with the extension <code>doc</code> matches files named
<code>science report final.doc</code> or
<code>resume.doc</code>, <strong>but not</strong>
<code>doc brown with marty.jpg</code>.</dd>
<dt>Name Pattern:</dt>
<dd>Use wildcards like <code>?</code> and <code>*</code> to move files to an appropriate folder. <code>?</code> matches a single letter/number/symbol/character whereas <code>*</code> can match any number of them.</dd>
<dd>The pattern <code>Prince*.mp3</code> matches <code>Prince - Purple rain.mp3</code> or <code>Prince.mp3</code>,
<strong>but not</strong> <code>Prince.doc</code> or <code>Best of Prince.mp3</code>.</dd>
<dd>The pattern <code>error?.txt</code> matches <code>error.txt</code> or <code>errors.txt</code>,
<strong>but not</strong> <code>errorss.txt</code> or <code>new error.txt</code>.</dd>
</dl>
<h3>Is SortMyBox free?</h3>
<p>Yes.</p>
<h3>Open source?</h3>
<p>SortMyBox is open source and BSD licensed, you can find it on <a href ="https://github.com/mustpax/sortmybox"> GitHub.</a></p>
<p>You can even run it on your own Google AppEngine instance. Instructions forthcoming!</p>
<h3>How do I contact you?</h3>
<p>You can <a href = "mailto: ${play.configuration.getProperty("sortbox.email")}" >email us</a>
or find us on <a href = "http://twitter.com/sortmybox">Twitter</a>.</p>
<h3>Anything else?</h3>
<p>Yes, please help us spread the word and share SortMyBox with other Dropbox & Box users! </p>
</div>
|
Java
|
<?php
/**
* Class for XML output
*
* PHP versions 5 and 7
*
* @category PEAR
* @package PEAR_PackageFileManager
* @author Greg Beaver <cellog@php.net>
* @copyright 2003-2015 The PEAR Group
* @license New BSD, Revised
* @link http://pear.php.net/package/PEAR_PackageFileManager
* @since File available since Release 1.2.0
*/
/**
* Class for XML output
*
* @category PEAR
* @package PEAR_PackageFileManager
* @author Greg Beaver <cellog@php.net>
* @copyright 2003-2015 The PEAR Group
* @license New BSD, Revised
* @version Release: @PEAR-VER@
* @link http://pear.php.net/package/PEAR_PackageFileManager
* @since Class available since Release 1.2.0
*/
class PEAR_PackageFileManager_XMLOutput extends PEAR_Common
{
/**
* Generate part of an XML description with release information.
*
* @param array $pkginfo array with release information
* @param bool $changelog whether the result will be in a changelog element
*
* @return string XML data
* @access private
*/
function _makeReleaseXml($pkginfo, $changelog = false)
{
$indent = $changelog ? " " : "";
$ret = "$indent <release>\n";
if (!empty($pkginfo['version'])) {
$ret .= "$indent <version>$pkginfo[version]</version>\n";
}
if (!empty($pkginfo['release_date'])) {
$ret .= "$indent <date>$pkginfo[release_date]</date>\n";
}
if (!empty($pkginfo['release_license'])) {
$ret .= "$indent <license>$pkginfo[release_license]</license>\n";
}
if (!empty($pkginfo['release_state'])) {
$ret .= "$indent <state>$pkginfo[release_state]</state>\n";
}
if (!empty($pkginfo['release_notes'])) {
$ret .= "$indent <notes>".htmlspecialchars($pkginfo['release_notes'])."</notes>\n";
}
if (!empty($pkginfo['release_warnings'])) {
$ret .= "$indent <warnings>".htmlspecialchars($pkginfo['release_warnings'])."</warnings>\n";
}
if (isset($pkginfo['release_deps']) && sizeof($pkginfo['release_deps']) > 0) {
$ret .= "$indent <deps>\n";
foreach ($pkginfo['release_deps'] as $dep) {
$ret .= "$indent <dep type=\"$dep[type]\" rel=\"$dep[rel]\"";
if (isset($dep['version'])) {
$ret .= " version=\"$dep[version]\"";
}
if (isset($dep['optional'])) {
$ret .= " optional=\"$dep[optional]\"";
}
if (isset($dep['name'])) {
$ret .= ">$dep[name]</dep>\n";
} else {
$ret .= "/>\n";
}
}
$ret .= "$indent </deps>\n";
}
if (isset($pkginfo['configure_options'])) {
$ret .= "$indent <configureoptions>\n";
foreach ($pkginfo['configure_options'] as $c) {
$ret .= "$indent <configureoption name=\"".
htmlspecialchars($c['name']) . "\"";
if (isset($c['default'])) {
$ret .= " default=\"" . htmlspecialchars($c['default']) . "\"";
}
$ret .= " prompt=\"" . htmlspecialchars($c['prompt']) . "\"";
$ret .= "/>\n";
}
$ret .= "$indent </configureoptions>\n";
}
if (isset($pkginfo['provides'])) {
foreach ($pkginfo['provides'] as $key => $what) {
$ret .= "$indent <provides type=\"$what[type]\" ";
$ret .= "name=\"$what[name]\" ";
if (isset($what['extends'])) {
$ret .= "extends=\"$what[extends]\" ";
}
$ret .= "/>\n";
}
}
if (isset($pkginfo['filelist'])) {
$ret .= "$indent <filelist>\n";
$ret .= $this->_doFileList($indent, $pkginfo['filelist'], '/');
$ret .= "$indent </filelist>\n";
}
$ret .= "$indent </release>\n";
return $ret;
}
/**
* Generate the <filelist> tag
*
* @param string $indent string to indent xml tag
* @param array $filelist list of files included in release
* @param string $curdir
*
* @access private
* @return string XML data
*/
function _doFileList($indent, $filelist, $curdir)
{
$ret = '';
foreach ($filelist as $file => $fa) {
if (isset($fa['##files'])) {
$ret .= "$indent <dir";
} else {
$ret .= "$indent <file";
}
if (isset($fa['role'])) {
$ret .= " role=\"$fa[role]\"";
}
if (isset($fa['baseinstalldir'])) {
$ret .= ' baseinstalldir="' .
htmlspecialchars($fa['baseinstalldir']) . '"';
}
if (isset($fa['md5sum'])) {
$ret .= " md5sum=\"$fa[md5sum]\"";
}
if (isset($fa['platform'])) {
$ret .= " platform=\"$fa[platform]\"";
}
if (!empty($fa['install-as'])) {
$ret .= ' install-as="' .
htmlspecialchars($fa['install-as']) . '"';
}
$ret .= ' name="' . htmlspecialchars($file) . '"';
if (isset($fa['##files'])) {
$ret .= ">\n";
$recurdir = $curdir;
if ($recurdir == '///') {
$recurdir = '';
}
$ret .= $this->_doFileList("$indent ", $fa['##files'], $recurdir . $file . '/');
$displaydir = $curdir;
if ($displaydir == '///' || $displaydir == '/') {
$displaydir = '';
}
$ret .= "$indent </dir> <!-- $displaydir$file -->\n";
} else {
if (empty($fa['replacements'])) {
$ret .= "/>\n";
} else {
$ret .= ">\n";
foreach ($fa['replacements'] as $r) {
$ret .= "$indent <replace";
foreach ($r as $k => $v) {
$ret .= " $k=\"" . htmlspecialchars($v) .'"';
}
$ret .= "/>\n";
}
$ret .= "$indent </file>\n";
}
}
}
return $ret;
}
}
|
Java
|
// Copyright (c) 2013-2017 Anton Kozhevnikov, Thomas Schulthess
// All rights reserved.
//
// 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.
//
// 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.
/** \file spline.h
*
* \brief Contains definition and partial implementaiton of sirius::Spline class.
*/
#ifndef __SPLINE_H__
#define __SPLINE_H__
// TODO: add back() method like in std::vector
// TODO: [?] store radial grid, not the pointer to the grid.
namespace sirius {
/// Cubic spline with a not-a-knot boundary conditions.
/** The following convention for spline coefficients is used: between points
* \f$ x_i \f$ and \f$ x_{i+1} \f$ the value of the spline is equal to
* \f$ a_i + b_i(x_{i+1} - x_i) + c_i(x_{i+1}-x_i)^2 + d_i(x_{i+1}-x_i)^3 \f$.
*/
template <typename T, typename U = double>
class Spline
{
private:
/// Radial grid.
Radial_grid<U> const* radial_grid_{nullptr};
mdarray<T, 2> coeffs_;
/* forbid copy constructor */
Spline(Spline<T, U> const& src__) = delete;
/* forbid assigment operator */
Spline<T, U>& operator=(Spline<T, U> const& src__) = delete;
/// Solver tridiagonal system of linear equaitons.
int solve(T* dl, T* d, T* du, T* b, int n)
{
for (int i = 0; i < n - 1; i++) {
if (std::abs(dl[i]) == 0) {
if (std::abs(d[i]) == 0) {
return i + 1;
}
} else if (std::abs(d[i]) >= std::abs(dl[i])) {
T mult = dl[i] / d[i];
d[i + 1] -= mult * du[i];
b[i + 1] -= mult * b[i];
if (i < n - 2) {
dl[i] = 0;
}
} else {
T mult = d[i] / dl[i];
d[i] = dl[i];
T tmp = d[i + 1];
d[i + 1] = du[i] - mult * tmp;
if (i < n - 2) {
dl[i] = du[i + 1];
du[i + 1] = -mult * dl[i];
}
du[i] = tmp;
tmp = b[i];
b[i] = b[i + 1];
b[i + 1] = tmp - mult * b[i + 1];
}
}
if (std::abs(d[n - 1]) == 0) {
return n;
}
b[n - 1] /= d[n - 1];
if (n > 1) {
b[n - 2] = (b[n - 2] - du[n - 2] * b[n - 1]) / d[n - 2];
}
for (int i = n - 3; i >= 0; i--) {
b[i] = (b[i] - du[i] * b[i + 1] - dl[i] * b[i + 2]) / d[i];
}
return 0;
}
public:
/// Default constructor.
Spline()
{
}
/// Constructor of a new empty spline.
Spline(Radial_grid<U> const& radial_grid__) : radial_grid_(&radial_grid__)
{
coeffs_ = mdarray<T, 2>(num_points(), 4);
coeffs_.zero();
}
/// Constructor of a spline from a function.
Spline(Radial_grid<U> const& radial_grid__, std::function<T(U)> f__) : radial_grid_(&radial_grid__)
{
coeffs_ = mdarray<T, 2>(num_points(), 4);
for (int i = 0; i < num_points(); i++) {
U x = (*radial_grid_)[i];
coeffs_(i, 0) = f__(x);
}
interpolate();
}
/// Constructor of a spline from a list of values.
Spline(Radial_grid<U> const& radial_grid__, std::vector<T> const& y__) : radial_grid_(&radial_grid__)
{
assert(radial_grid_->num_points() == (int)y__.size());
coeffs_ = mdarray<T, 2>(num_points(), 4);
for (int i = 0; i < num_points(); i++) {
coeffs_(i, 0) = y__[i];
}
interpolate();
}
/// Move constructor.
Spline(Spline<T, U>&& src__)
{
radial_grid_ = src__.radial_grid_;
coeffs_ = std::move(src__.coeffs_);
}
/// Move assigment operator.
Spline<T, U>& operator=(Spline<T, U>&& src__)
{
if (this != &src__) {
radial_grid_ = src__.radial_grid_;
coeffs_ = std::move(src__.coeffs_);
}
return *this;
}
Spline<T, U>& operator=(std::function<T(U)> f__)
{
for (int ir = 0; ir < radial_grid_->num_points(); ir++) {
U x = (*radial_grid_)[ir];
coeffs_(ir, 0) = f__(x);
}
return this->interpolate();
}
/// Integrate with r^m weight.
T integrate(int m__) const
{
std::vector<T> g(num_points());
return integrate(g, m__);
}
inline std::vector<T> values() const
{
std::vector<T> a(num_points());
for (int i = 0; i < num_points(); i++) {
a[i] = coeffs_(i, 0);
}
return std::move(a);
}
/// Return number of spline points.
inline int num_points() const
{
return radial_grid_->num_points();
}
inline std::array<T, 4> coeffs(int i__) const
{
return {coeffs_(i__, 0), coeffs_(i__, 1), coeffs_(i__, 2), coeffs_(i__, 3)};
}
inline mdarray<T, 2> const& coeffs() const
{
return coeffs_;
}
inline double x(int i__) const
{
return (*radial_grid_)[i__];
}
inline double dx(int i__) const
{
return radial_grid_->dx(i__);
}
inline T operator()(U x) const
{
int j = radial_grid_->index_of(x);
if (j == -1) {
TERMINATE("point not found");
}
U dx = x - (*radial_grid_)[j];
return (*this)(j, dx);
}
/// Return value at \f$ x_i \f$.
inline T& operator[](const int i)
{
return coeffs_(i, 0);
}
inline T operator[](const int i) const
{
return coeffs_(i, 0);
}
inline T operator()(const int i, U dx) const
{
assert(i >= 0);
assert(i < num_points() - 1);
assert(dx >= 0);
return coeffs_(i, 0) + dx * (coeffs_(i, 1) + dx * (coeffs_(i, 2) + dx * coeffs_(i, 3)));
}
inline T deriv(const int dm, const int i, const U dx) const
{
assert(i >= 0);
assert(i < num_points() - 1);
assert(dx >= 0);
T result = 0;
switch (dm) {
case 0: {
result = coeffs_(i, 0) + dx * (coeffs_(i, 1) + dx * (coeffs_(i, 2) + dx * coeffs_(i, 3)));
break;
}
case 1: {
result = coeffs_(i, 1) + (coeffs_(i, 2) * 2.0 + coeffs_(i, 3) * dx * 3.0) * dx;
break;
}
case 2: {
result = coeffs_(i, 2) * 2.0 + coeffs_(i, 3) * dx * 6.0;
break;
}
case 3: {
result = coeffs_(i, 3) * 6.0;
break;
}
default: {
TERMINATE("wrong order of derivative");
break;
}
}
return result;
}
inline T deriv(int dm, int i) const
{
assert(i >= 0);
assert(i < num_points());
assert(radial_grid_ != nullptr);
if (i == num_points() - 1) {
return deriv(dm, i - 1, radial_grid_->dx(i - 1));
} else {
return deriv(dm, i, 0);
}
}
inline Radial_grid<U> const& radial_grid() const
{
return *radial_grid_;
}
Spline<T, U>& interpolate()
{
int np = num_points();
/* lower diagonal */
std::vector<T> dl(np - 1);
/* main diagonal */
std::vector<T> d(np);
/* upper diagonal */
std::vector<T> du(np - 1);
std::vector<T> x(np);
std::vector<T> dy(np - 1);
/* derivative of y */
for (int i = 0; i < np - 1; i++) {
dy[i] = (coeffs_(i + 1, 0) - coeffs_(i, 0)) / radial_grid_->dx(i);
}
/* setup "B" vector of AX=B equation */
for (int i = 0; i < np - 2; i++) {
x[i + 1] = (dy[i + 1] - dy[i]) * 6.0;
}
x[0] = -x[1];
x[np - 1] = -x[np - 2];
/* main diagonal of "A" matrix */
for (int i = 0; i < np - 2; i++) {
d[i + 1] = static_cast<T>(2) * (static_cast<T>(radial_grid_->dx(i)) + static_cast<T>(radial_grid_->dx(i + 1)));
}
U h0 = radial_grid_->dx(0);
U h1 = radial_grid_->dx(1);
U h2 = radial_grid_->dx(np - 2);
U h3 = radial_grid_->dx(np - 3);
d[0] = (h1 / h0) * h1 - h0;
d[np - 1] = (h3 / h2) * h3 - h2;
/* subdiagonals of "A" matrix */
for (int i = 0; i < np - 1; i++) {
du[i] = static_cast<T>(radial_grid_->dx(i));
dl[i] = static_cast<T>(radial_grid_->dx(i));
}
du[0] = -(h1 * (1.0 + h1 / h0) + d[1]);
dl[np - 2] = -(h3 * (1.0 + h3 / h2) + d[np - 2]);
/* solve tridiagonal system */
//solve(a.data(), b.data(), c.data(), d.data(), np);
//auto& x = d;
//int info = linalg<CPU>::gtsv(np, 1, &a[0], &b[0], &c[0], &d[0], np);
int info = solve(&dl[0], &d[0], &du[0], &x[0], np);
if (info) {
std::stringstream s;
s << "error in tridiagonal solver: " << info;
TERMINATE(s);
}
for (int i = 0; i < np - 1; i++) {
coeffs_(i, 2) = x[i] / 2.0;
T t = (x[i + 1] - x[i]) / 6.0;
coeffs_(i, 1) = dy[i] - (coeffs_(i, 2) + t) * radial_grid_->dx(i);
coeffs_(i, 3) = t / radial_grid_->dx(i);
}
coeffs_(np - 1, 1) = 0;
coeffs_(np - 1, 2) = 0;
coeffs_(np - 1, 3) = 0;
return *this;
}
inline void scale(double a__)
{
for (int i = 0; i < num_points(); i++) {
coeffs_(i, 0) *= a__;
coeffs_(i, 1) *= a__;
coeffs_(i, 2) *= a__;
coeffs_(i, 3) *= a__;
}
}
T integrate_simpson() const
{
std::vector<U> w(num_points(), 0);
for (int i = 0; i < num_points() - 2; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U x2 = (*radial_grid_)[i + 2];
w[i] += (2 * x0 + x1 - 3 * x2) * (x1 - x0) / (x0 - x2) / 6;
w[i + 1] += (x0 - x1) * (x0 + 2 * x1 - 3 * x2) / 6 / (x2 - x1);
w[i + 2] += std::pow(x0 - x1, 3) / 6 / (x2 - x0) / (x2 - x1);
}
//for (int i = 1; i < num_points() - 1; i++) {
// w[i] *= 0.5;
//}
T res{0};
for (int i = 0; i < num_points(); i++) {
res += w[i] * coeffs_(i, 0);
}
return res;
}
T integrate_simple() const
{
T res{0};
for (int i = 0; i < num_points() - 1; i++) {
U dx = radial_grid_->dx(i);
res += 0.5 * (coeffs_(i, 0) + coeffs_(i + 1, 0)) * dx;
}
return res;
}
T integrate(std::vector<T>& g__, int m__) const
{
g__ = std::vector<T>(num_points());
g__[0] = 0.0;
switch (m__) {
case 0: {
T t = 1.0 / 3.0;
for (int i = 0; i < num_points() - 1; i++) {
U dx = radial_grid_->dx(i);
g__[i + 1] = g__[i] + (((coeffs_(i, 3) * dx * 0.25 + coeffs_(i, 2) * t) * dx + coeffs_(i, 1) * 0.5) * dx + coeffs_(i, 0)) * dx;
}
break;
}
case 2: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
U x0_2 = x0 * x0;
U x0_3 = x0_2 * x0;
U x1_2 = x1 * x1;
U x1_3 = x1_2 * x1;
g__[i + 1] = g__[i] + (20.0 * a0 * (x1_3 - x0_3) + 5.0 * a1 * (x0 * x0_3 + x1_3 * (3.0 * dx - x0)) -
dx * dx * dx * (-2.0 * a2 * (x0_2 + 3.0 * x0 * x1 + 6.0 * x1_2) -
a3 * dx * (x0_2 + 4.0 * x0 * x1 + 10.0 * x1_2))) / 60.0;
}
break;
}
case -1: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-1)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
g__[i + 1] = g__[i] + (dx / 6.0) * (6.0 * a1 + x0 * (-9.0 * a2 + 11.0 * a3 * x0) + x1 * (3.0 * a2 - 7.0 * a3 * x0 + 2.0 * a3 * x1)) +
(-a0 + x0 * (a1 + x0 * (-a2 + a3 * x0))) * std::log(x0 / x1);
}
break;
}
case -2: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-2)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
//g__[i + 1] = g__[i] + (((x0 - x1) * (-2.0 * a0 + x0 * (2.0 * a1 - 2.0 * a2 * (x0 + x1) +
// a3 * (2.0 * std::pow(x0, 2) + 5.0 * x0 * x1 - std::pow(x1, 2)))) +
// 2.0 * x0 * (a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * x1 * std::log(x1 / x0)) /
// (2.0 * x0 * x1));
g__[i + 1] = g__[i] + (a2 * dx - 5.0 * a3 * x0 * dx / 2.0 - a1 * (dx / x1) + a0 * (dx / x0 / x1) +
(x0 / x1) * dx * (a2 - a3 * x0) + a3 * x1 * dx / 2.0) +
(a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * std::log(x1 / x0);
}
break;
}
case -3: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-3)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
//g__[i + 1] = g__[i] + (-((x0 - x1) * (a0 * (x0 + x1) + x0 * (a1 * (-x0 + x1) +
// x0 * (a2 * x0 - a3 * std::pow(x0, 2) - 3.0 * a2 * x1 + 5.0 * a3 * x0 * x1 +
// 2.0 * a3 * std::pow(x1, 2)))) + 2.0 * std::pow(x0, 2) * (a2 - 3.0 * a3 * x0) * std::pow(x1, 2) *
// std::log(x0 / x1)) / (2.0 * std::pow(x0, 2) * std::pow(x1, 2)));
g__[i + 1] = g__[i] + dx * (a0 * (x0 + x1) + x0 * (a1 * dx +
x0 * (a2 * x0 - a3 * std::pow(x0, 2) - 3.0 * a2 * x1 + 5.0 * a3 * x0 * x1 +
2.0 * a3 * std::pow(x1, 2)))) / std::pow(x0 * x1, 2) / 2.0 +
(-a2 + 3.0 * a3 * x0) * std::log(x0 / x1);
}
break;
}
case -4: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
U dx = radial_grid_->dx(i);
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(-4)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
//g__[i + 1] = g__[i] + ((2.0 * a0 * (-std::pow(x0, 3) + std::pow(x1, 3)) +
// x0 * (x0 - x1) * (a1 * (x0 - x1) * (2.0 * x0 + x1) +
// x0 * (-2.0 * a2 * std::pow(x0 - x1, 2) + a3 * x0 * (2.0 * std::pow(x0, 2) - 7.0 * x0 * x1 +
// 11.0 * std::pow(x1, 2)))) + 6.0 * a3 * std::pow(x0 * x1, 3) * std::log(x1 / x0)) /
// (6.0 * std::pow(x0 * x1, 3)));
g__[i + 1] = g__[i] + (2.0 * a0 * (-std::pow(x0, 3) + std::pow(x1, 3)) -
x0 * dx * (-a1 * dx * (2.0 * x0 + x1) +
x0 * (-2.0 * a2 * std::pow(dx, 2) + a3 * x0 * (2.0 * std::pow(x0, 2) - 7.0 * x0 * x1 +
11.0 * std::pow(x1, 2))))) / std::pow(x0 * x1, 3) / 6.0 +
a3 * std::log(x1 / x0);
}
break;
}
default: {
for (int i = 0; i < num_points() - 1; i++) {
U x0 = (*radial_grid_)[i];
U x1 = (*radial_grid_)[i + 1];
T a0 = coeffs_(i, 0);
T a1 = coeffs_(i, 1);
T a2 = coeffs_(i, 2);
T a3 = coeffs_(i, 3);
// obtained with the following Mathematica code:
// FullSimplify[Integrate[x^(m)*(a0+a1*(x-x0)+a2*(x-x0)^2+a3*(x-x0)^3),{x,x0,x1}],
// Assumptions->{Element[{x0,x1},Reals],x1>x0>0}]
g__[i + 1] = g__[i] + (std::pow(x0, 1 + m__) * (-(a0 * double((2 + m__) * (3 + m__) * (4 + m__))) +
x0 * (a1 * double((3 + m__) * (4 + m__)) - 2.0 * a2 * double(4 + m__) * x0 +
6.0 * a3 * std::pow(x0, 2)))) / double((1 + m__) * (2 + m__) * (3 + m__) * (4 + m__)) +
std::pow(x1, 1 + m__) * ((a0 - x0 * (a1 + x0 * (-a2 + a3 * x0))) / double(1 + m__) +
((a1 + x0 * (-2.0 * a2 + 3.0 * a3 * x0)) * x1) / double(2 + m__) +
((a2 - 3.0 * a3 * x0) * std::pow(x1, 2)) / double(3 + m__) +
(a3 * std::pow(x1, 3)) / double(4 + m__));
}
break;
}
}
return g__[num_points() - 1];
}
uint64_t hash() const
{
return coeffs_.hash();
}
#ifdef __GPU
void copy_to_device()
{
coeffs_.allocate_on_device();
coeffs_.copy_to_device();
}
void async_copy_to_device(int thread_id__)
{
coeffs_.allocate_on_device();
coeffs_.async_copy_to_device(thread_id__);
}
#endif
};
template <typename T>
inline Spline<T> operator*(Spline<T> const& a__, Spline<T> const& b__)
{
//assert(a__.radial_grid().hash() == b__.radial_grid().hash());
Spline<double> s12(a__.radial_grid());
auto& coeffs_a = a__.coeffs();
auto& coeffs_b = b__.coeffs();
auto& coeffs = const_cast<mdarray<double, 2>&>(s12.coeffs());
for (int ir = 0; ir < a__.radial_grid().num_points(); ir++) {
coeffs(ir, 0) = coeffs_a(ir, 0) * coeffs_b(ir, 0);
coeffs(ir, 1) = coeffs_a(ir, 1) * coeffs_b(ir, 0) + coeffs_a(ir, 0) * coeffs_b(ir, 1);
coeffs(ir, 2) = coeffs_a(ir, 2) * coeffs_b(ir, 0) + coeffs_a(ir, 1) * coeffs_b(ir, 1) + coeffs_a(ir, 0) * coeffs_b(ir, 2);
coeffs(ir, 3) = coeffs_a(ir, 3) * coeffs_b(ir, 0) + coeffs_a(ir, 2) * coeffs_b(ir, 1) + coeffs_a(ir, 1) * coeffs_b(ir, 2) + coeffs_a(ir, 0) * coeffs_b(ir, 3);
}
return std::move(s12);
}
#ifdef __GPU
extern "C" double spline_inner_product_gpu_v2(int size__,
double const* x__,
double const* dx__,
double const* f__,
double const* g__,
double* d_buf__,
double* h_buf__,
int stream_id__);
extern "C" void spline_inner_product_gpu_v3(int const* idx_ri__,
int num_ri__,
int num_points__,
double const* x__,
double const* dx__,
double const* f__,
double const* g__,
double* result__);
#endif
template<typename T>
T inner(Spline<T> const& f__, Spline<T> const& g__, int m__, int num_points__)
{
//assert(f__.radial_grid().hash() == g__.radial_grid().hash());
T result = 0;
switch (m__)
{
case 0:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double dx = f__.dx(i);
auto f = f__.coeffs(i);
auto g = g__.coeffs(i);
T faga = f[0] * g[0];
T fdgd = f[3] * g[3];
T k1 = f[0] * g[1] + f[1] * g[0];
T k2 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k3 = f[0] * g[3] + f[1] * g[2] + f[2] * g[1] + f[3] * g[0];
T k4 = f[1] * g[3] + f[2] * g[2] + f[3] * g[1];
T k5 = f[2] * g[3] + f[3] * g[2];
result += dx * (faga +
dx * (k1 / 2.0 +
dx * (k2 / 3.0 +
dx * (k3 / 4.0 +
dx * (k4 / 5.0 +
dx * (k5 / 6.0 +
dx * fdgd / 7.0))))));
}
break;
}
case 1:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double x0 = f__.x(i);
double dx = f__.dx(i);
auto f = f__.coeffs(i);
auto g = g__.coeffs(i);
T faga = f[0] * g[0];
T fdgd = f[3] * g[3];
T k1 = f[0] * g[1] + f[1] * g[0];
T k2 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k3 = f[0] * g[3] + f[1] * g[2] + f[2] * g[1] + f[3] * g[0];
T k4 = f[1] * g[3] + f[2] * g[2] + f[3] * g[1];
T k5 = f[2] * g[3] + f[3] * g[2];
result += dx * ((faga * x0) +
dx * ((faga + k1 * x0) / 2.0 +
dx * ((k1 + k2 * x0) / 3.0 +
dx * ((k2 + k3 * x0) / 4.0 +
dx * ((k3 + k4 * x0) / 5.0 +
dx * ((k4 + k5 * x0) / 6.0 +
dx * ((k5 + fdgd * x0) / 7.0 +
dx * fdgd / 8.0)))))));
}
break;
}
case 2:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double x0 = f__.x(i);
double dx = f__.dx(i);
auto f = f__.coeffs(i);
auto g = g__.coeffs(i);
T k0 = f[0] * g[0];
T k1 = f[3] * g[1] + f[2] * g[2] + f[1] * g[3];
T k2 = f[3] * g[0] + f[2] * g[1] + f[1] * g[2] + f[0] * g[3];
T k3 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k4 = f[3] * g[2] + f[2] * g[3];
T k5 = f[1] * g[0] + f[0] * g[1];
T k6 = f[3] * g[3]; // 25 OPS
T r1 = k4 * 0.125 + k6 * x0 * 0.25;
T r2 = (k1 + x0 * (2.0 * k4 + k6 * x0)) * 0.14285714285714285714;
T r3 = (k2 + x0 * (2.0 * k1 + k4 * x0)) * 0.16666666666666666667;
T r4 = (k3 + x0 * (2.0 * k2 + k1 * x0)) * 0.2;
T r5 = (k5 + x0 * (2.0 * k3 + k2 * x0)) * 0.25;
T r6 = (k0 + x0 * (2.0 * k5 + k3 * x0)) * 0.33333333333333333333;
T r7 = (x0 * (2.0 * k0 + x0 * k5)) * 0.5;
T v = dx * k6 * 0.11111111111111111111;
v = dx * (r1 + v);
v = dx * (r2 + v);
v = dx * (r3 + v);
v = dx * (r4 + v);
v = dx * (r5 + v);
v = dx * (r6 + v);
v = dx * (r7 + v);
result += dx * (k0 * x0 * x0 + v);
}
break;
}
/* canonical formula derived with Mathematica */
/*case 2:
{
for (int i = 0; i < num_points__ - 1; i++)
{
double x0 = f__.x(i);
double dx = f__.dx(i);
auto f = f__.coefs(i);
auto g = g__.coefs(i);
T k0 = f[0] * g[0];
T k1 = f[3] * g[1] + f[2] * g[2] + f[1] * g[3];
T k2 = f[3] * g[0] + f[2] * g[1] + f[1] * g[2] + f[0] * g[3];
T k3 = f[2] * g[0] + f[1] * g[1] + f[0] * g[2];
T k4 = f[3] * g[2] + f[2] * g[3];
T k5 = f[1] * g[0] + f[0] * g[1];
T k6 = f[3] * g[3]; // 25 OPS
result += dx * (k0 * x0 * x0 +
dx * ((x0 * (2.0 * k0 + x0 * k5)) / 2.0 +
dx * ((k0 + x0 * (2.0 * k5 + k3 * x0)) / 3.0 +
dx * ((k5 + x0 * (2.0 * k3 + k2 * x0)) / 4.0 +
dx * ((k3 + x0 * (2.0 * k2 + k1 * x0)) / 5.0 +
dx * ((k2 + x0 * (2.0 * k1 + k4 * x0)) / 6.0 +
dx * ((k1 + x0 * (2.0 * k4 + k6 * x0)) / 7.0 +
dx * ((k4 + 2.0 * k6 * x0) / 8.0 +
dx * k6 / 9.0))))))));
}
break;
}*/
default:
{
TERMINATE("wrong r^m prefactor");
}
}
return result;
}
template<typename T>
T inner(Spline<T> const& f__, Spline<T> const& g__, int m__)
{
return inner(f__, g__, m__, f__.num_points());
}
};
#endif // __SPLINE_H__
|
Java
|
// Set color based on frequency and brightness
void setColor(int peak_index, int brightness) {
if (peak_index == 0) {
// signal was weak, turn lights off
red = 0;
green = 0;
blue = 0;
} else if (peak_index > 30) {
red = current_palette[29].red;
green = current_palette[29].green;
blue = current_palette[29].blue;
} else {
red = current_palette[peak_index - 1].red;
green = current_palette[peak_index - 1].green;
blue = current_palette[peak_index - 1].blue;
}
strip_color = strip.Color(
round((red / 100.0) * brightness),
round((green / 100.0) * brightness),
round((blue / 100.0) * brightness)
);
if (DEBUG) {
Serial.print((red / 100.0) * brightness);
Serial.print("\t");
Serial.print((green / 100.0) * brightness);
Serial.print("\t");
Serial.println((blue / 100.0) * brightness);
}
for (int i=0; i < strip.numPixels(); i++) {
strip.setPixelColor(i, strip_color);
}
strip.show();
}
void changeColorPalette() {
// re-populate colors for color_palette from new palette choice
if (palette_choice != new_palette_choice - 1) {
palette_choice = new_palette_choice - 1;
for (int i = 0; i < 30; i++) {
current_palette[i].red = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].red)
);
current_palette[i].green = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].green)
);
current_palette[i].blue = pgm_read_byte(
&(palettes[i + (palette_color_count * palette_choice)].blue)
);
}
}
}
|
Java
|
/*******
*
* FILE INFO:
* project: RTP_lib
* file: Types.h
* started on: 03/26/03
* started by: Cedric Lacroix <lacroix_cedric@yahoo.com>
*
*
* TODO:
*
* BUGS:
*
* UPDATE INFO:
* updated on: 05/13/03
* updated by: Cedric Lacroix <lacroix_cedric@yahoo.com>
*
*******/
#ifndef TYPES_H
#define TYPES_H
#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif
typedef unsigned char u_int8;
typedef unsigned short u_int16;
typedef unsigned long u_int32;
typedef unsigned int context;
/**
** Declaration for unix
**/
#ifdef UNIX
#ifndef _WIN32
typedef int SOCKET;
#endif
typedef struct sockaddr SOCKADDR;
typedef struct sockaddr_in SOCKADDR_IN;
#endif /* UNIX */
#endif /* TYPES_H */
|
Java
|
/**
* PatentPriority_type0.java
*
* This file was auto-generated from WSDL
* by the Apache Axis2 version: 1.6.2 Built on : Apr 17, 2012 (05:34:40 IST)
*/
package gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene;
/**
* PatentPriority_type0 bean class
*/
@SuppressWarnings({"unchecked","unused"})
public class PatentPriority_type0
implements org.apache.axis2.databinding.ADBBean{
/* This type was generated from the piece of schema that had
name = Patent-priority_type0
Namespace URI = http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene
Namespace Prefix = ns1
*/
/**
* field for PatentPriority_country
*/
protected java.lang.String localPatentPriority_country ;
/**
* Auto generated getter method
* @return java.lang.String
*/
public java.lang.String getPatentPriority_country(){
return localPatentPriority_country;
}
/**
* Auto generated setter method
* @param param PatentPriority_country
*/
public void setPatentPriority_country(java.lang.String param){
this.localPatentPriority_country=param;
}
/**
* field for PatentPriority_number
*/
protected java.lang.String localPatentPriority_number ;
/**
* Auto generated getter method
* @return java.lang.String
*/
public java.lang.String getPatentPriority_number(){
return localPatentPriority_number;
}
/**
* Auto generated setter method
* @param param PatentPriority_number
*/
public void setPatentPriority_number(java.lang.String param){
this.localPatentPriority_number=param;
}
/**
* field for PatentPriority_date
*/
protected gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0 localPatentPriority_date ;
/**
* Auto generated getter method
* @return gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0
*/
public gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0 getPatentPriority_date(){
return localPatentPriority_date;
}
/**
* Auto generated setter method
* @param param PatentPriority_date
*/
public void setPatentPriority_date(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0 param){
this.localPatentPriority_date=param;
}
/**
*
* @param parentQName
* @param factory
* @return org.apache.axiom.om.OMElement
*/
public org.apache.axiom.om.OMElement getOMElement (
final javax.xml.namespace.QName parentQName,
final org.apache.axiom.om.OMFactory factory) throws org.apache.axis2.databinding.ADBException{
org.apache.axiom.om.OMDataSource dataSource =
new org.apache.axis2.databinding.ADBDataSource(this,parentQName);
return factory.createOMElement(dataSource,parentQName);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
serialize(parentQName,xmlWriter,false);
}
public void serialize(final javax.xml.namespace.QName parentQName,
javax.xml.stream.XMLStreamWriter xmlWriter,
boolean serializeType)
throws javax.xml.stream.XMLStreamException, org.apache.axis2.databinding.ADBException{
java.lang.String prefix = null;
java.lang.String namespace = null;
prefix = parentQName.getPrefix();
namespace = parentQName.getNamespaceURI();
writeStartElement(prefix, namespace, parentQName.getLocalPart(), xmlWriter);
if (serializeType){
java.lang.String namespacePrefix = registerPrefix(xmlWriter,"http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene");
if ((namespacePrefix != null) && (namespacePrefix.trim().length() > 0)){
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
namespacePrefix+":Patent-priority_type0",
xmlWriter);
} else {
writeAttribute("xsi","http://www.w3.org/2001/XMLSchema-instance","type",
"Patent-priority_type0",
xmlWriter);
}
}
namespace = "http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene";
writeStartElement(null, namespace, "Patent-priority_country", xmlWriter);
if (localPatentPriority_country==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("Patent-priority_country cannot be null!!");
}else{
xmlWriter.writeCharacters(localPatentPriority_country);
}
xmlWriter.writeEndElement();
namespace = "http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene";
writeStartElement(null, namespace, "Patent-priority_number", xmlWriter);
if (localPatentPriority_number==null){
// write the nil attribute
throw new org.apache.axis2.databinding.ADBException("Patent-priority_number cannot be null!!");
}else{
xmlWriter.writeCharacters(localPatentPriority_number);
}
xmlWriter.writeEndElement();
if (localPatentPriority_date==null){
throw new org.apache.axis2.databinding.ADBException("Patent-priority_date cannot be null!!");
}
localPatentPriority_date.serialize(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_date"),
xmlWriter);
xmlWriter.writeEndElement();
}
private static java.lang.String generatePrefix(java.lang.String namespace) {
if(namespace.equals("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene")){
return "ns1";
}
return org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
/**
* Utility method to write an element start tag.
*/
private void writeStartElement(java.lang.String prefix, java.lang.String namespace, java.lang.String localPart,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String writerPrefix = xmlWriter.getPrefix(namespace);
if (writerPrefix != null) {
xmlWriter.writeStartElement(namespace, localPart);
} else {
if (namespace.length() == 0) {
prefix = "";
} else if (prefix == null) {
prefix = generatePrefix(namespace);
}
xmlWriter.writeStartElement(prefix, localPart, namespace);
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
}
/**
* Util method to write an attribute with the ns prefix
*/
private void writeAttribute(java.lang.String prefix,java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (xmlWriter.getPrefix(namespace) == null) {
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
xmlWriter.writeAttribute(namespace,attName,attValue);
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeAttribute(java.lang.String namespace,java.lang.String attName,
java.lang.String attValue,javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException{
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName,attValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace,attName,attValue);
}
}
/**
* Util method to write an attribute without the ns prefix
*/
private void writeQNameAttribute(java.lang.String namespace, java.lang.String attName,
javax.xml.namespace.QName qname, javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String attributeNamespace = qname.getNamespaceURI();
java.lang.String attributePrefix = xmlWriter.getPrefix(attributeNamespace);
if (attributePrefix == null) {
attributePrefix = registerPrefix(xmlWriter, attributeNamespace);
}
java.lang.String attributeValue;
if (attributePrefix.trim().length() > 0) {
attributeValue = attributePrefix + ":" + qname.getLocalPart();
} else {
attributeValue = qname.getLocalPart();
}
if (namespace.equals("")) {
xmlWriter.writeAttribute(attName, attributeValue);
} else {
registerPrefix(xmlWriter, namespace);
xmlWriter.writeAttribute(namespace, attName, attributeValue);
}
}
/**
* method to handle Qnames
*/
private void writeQName(javax.xml.namespace.QName qname,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
java.lang.String namespaceURI = qname.getNamespaceURI();
if (namespaceURI != null) {
java.lang.String prefix = xmlWriter.getPrefix(namespaceURI);
if (prefix == null) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
xmlWriter.writeCharacters(prefix + ":" + org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
} else {
// i.e this is the default namespace
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
} else {
xmlWriter.writeCharacters(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qname));
}
}
private void writeQNames(javax.xml.namespace.QName[] qnames,
javax.xml.stream.XMLStreamWriter xmlWriter) throws javax.xml.stream.XMLStreamException {
if (qnames != null) {
// we have to store this data until last moment since it is not possible to write any
// namespace data after writing the charactor data
java.lang.StringBuffer stringToWrite = new java.lang.StringBuffer();
java.lang.String namespaceURI = null;
java.lang.String prefix = null;
for (int i = 0; i < qnames.length; i++) {
if (i > 0) {
stringToWrite.append(" ");
}
namespaceURI = qnames[i].getNamespaceURI();
if (namespaceURI != null) {
prefix = xmlWriter.getPrefix(namespaceURI);
if ((prefix == null) || (prefix.length() == 0)) {
prefix = generatePrefix(namespaceURI);
xmlWriter.writeNamespace(prefix, namespaceURI);
xmlWriter.setPrefix(prefix,namespaceURI);
}
if (prefix.trim().length() > 0){
stringToWrite.append(prefix).append(":").append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
} else {
stringToWrite.append(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(qnames[i]));
}
}
xmlWriter.writeCharacters(stringToWrite.toString());
}
}
/**
* Register a namespace prefix
*/
private java.lang.String registerPrefix(javax.xml.stream.XMLStreamWriter xmlWriter, java.lang.String namespace) throws javax.xml.stream.XMLStreamException {
java.lang.String prefix = xmlWriter.getPrefix(namespace);
if (prefix == null) {
prefix = generatePrefix(namespace);
javax.xml.namespace.NamespaceContext nsContext = xmlWriter.getNamespaceContext();
while (true) {
java.lang.String uri = nsContext.getNamespaceURI(prefix);
if (uri == null || uri.length() == 0) {
break;
}
prefix = org.apache.axis2.databinding.utils.BeanUtil.getUniquePrefix();
}
xmlWriter.writeNamespace(prefix, namespace);
xmlWriter.setPrefix(prefix, namespace);
}
return prefix;
}
/**
* databinding method to get an XML representation of this object
*
*/
public javax.xml.stream.XMLStreamReader getPullParser(javax.xml.namespace.QName qName)
throws org.apache.axis2.databinding.ADBException{
java.util.ArrayList elementList = new java.util.ArrayList();
java.util.ArrayList attribList = new java.util.ArrayList();
elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene",
"Patent-priority_country"));
if (localPatentPriority_country != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localPatentPriority_country));
} else {
throw new org.apache.axis2.databinding.ADBException("Patent-priority_country cannot be null!!");
}
elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene",
"Patent-priority_number"));
if (localPatentPriority_number != null){
elementList.add(org.apache.axis2.databinding.utils.ConverterUtil.convertToString(localPatentPriority_number));
} else {
throw new org.apache.axis2.databinding.ADBException("Patent-priority_number cannot be null!!");
}
elementList.add(new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene",
"Patent-priority_date"));
if (localPatentPriority_date==null){
throw new org.apache.axis2.databinding.ADBException("Patent-priority_date cannot be null!!");
}
elementList.add(localPatentPriority_date);
return new org.apache.axis2.databinding.utils.reader.ADBXMLStreamReaderImpl(qName, elementList.toArray(), attribList.toArray());
}
/**
* Factory class that keeps the parse method
*/
public static class Factory{
/**
* static method to create the object
* Precondition: If this object is an element, the current or next start element starts this object and any intervening reader events are ignorable
* If this object is not an element, it is a complex type and the reader is at the event just after the outer start element
* Postcondition: If this object is an element, the reader is positioned at its end element
* If this object is a complex type, the reader is positioned at the end element of its outer element
*/
public static PatentPriority_type0 parse(javax.xml.stream.XMLStreamReader reader) throws java.lang.Exception{
PatentPriority_type0 object =
new PatentPriority_type0();
int event;
java.lang.String nillableValue = null;
java.lang.String prefix ="";
java.lang.String namespaceuri ="";
try {
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","type")!=null){
java.lang.String fullTypeName = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance",
"type");
if (fullTypeName!=null){
java.lang.String nsPrefix = null;
if (fullTypeName.indexOf(":") > -1){
nsPrefix = fullTypeName.substring(0,fullTypeName.indexOf(":"));
}
nsPrefix = nsPrefix==null?"":nsPrefix;
java.lang.String type = fullTypeName.substring(fullTypeName.indexOf(":")+1);
if (!"Patent-priority_type0".equals(type)){
//find namespace for the prefix
java.lang.String nsUri = reader.getNamespaceContext().getNamespaceURI(nsPrefix);
return (PatentPriority_type0)gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.ExtensionMapper.getTypeObject(
nsUri,type,reader);
}
}
}
// Note all attributes that were handled. Used to differ normal attributes
// from anyAttributes.
java.util.Vector handledAttributes = new java.util.Vector();
reader.next();
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_country").equals(reader.getName())){
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)){
throw new org.apache.axis2.databinding.ADBException("The element: "+"Patent-priority_country" +" cannot be null");
}
java.lang.String content = reader.getElementText();
object.setPatentPriority_country(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_number").equals(reader.getName())){
nillableValue = reader.getAttributeValue("http://www.w3.org/2001/XMLSchema-instance","nil");
if ("true".equals(nillableValue) || "1".equals(nillableValue)){
throw new org.apache.axis2.databinding.ADBException("The element: "+"Patent-priority_number" +" cannot be null");
}
java.lang.String content = reader.getElementText();
object.setPatentPriority_number(
org.apache.axis2.databinding.utils.ConverterUtil.convertToString(content));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement()) reader.next();
if (reader.isStartElement() && new javax.xml.namespace.QName("http://www.ncbi.nlm.nih.gov/soap/eutils/efetch_gene","Patent-priority_date").equals(reader.getName())){
object.setPatentPriority_date(gov.nih.nlm.ncbi.www.soap.eutils.efetch_gene.PatentPriority_date_type0.Factory.parse(reader));
reader.next();
} // End of if for expected property start element
else{
// A start element we are not expecting indicates an invalid parameter was passed
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
}
while (!reader.isStartElement() && !reader.isEndElement())
reader.next();
if (reader.isStartElement())
// A start element we are not expecting indicates a trailing invalid property
throw new org.apache.axis2.databinding.ADBException("Unexpected subelement " + reader.getName());
} catch (javax.xml.stream.XMLStreamException e) {
throw new java.lang.Exception(e);
}
return object;
}
}//end of factory class
}
|
Java
|
/* Copyright (c) 2013, Anthony Cornehl
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* - 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.
*
* 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.
*/
#include "check/twinshadow.h"
#include "twinshadow/string.h"
char *buf_strstrip;
START_TEST(strstrip_removes_preceding_and_trailing_whitespace)
{
ts_strstrip(buf_strstrip);
ck_assert_str_eq(buf_strstrip, "one two three");
}
END_TEST
void
setup_strstrip_test(void) {
buf_strstrip = strdup(" one two three ");
}
void
teardown_strstrip_test(void) {
free(buf_strstrip);
}
TCase *
tcase_strstrip(void) {
TCase *tc = tcase_create("strstrip");
tcase_add_checked_fixture(tc, setup_strstrip_test, teardown_strstrip_test);
tcase_add_test(tc, strstrip_removes_preceding_and_trailing_whitespace);
return tc;
}
CHECK_MAIN_STANDALONE(strstrip);
|
Java
|
//
// ooSocket.c WJ112
//
/*
* Copyright (c) 2014, Walter de Jong
* All rights reserved.
*
* 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.
*
* 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 OWNER 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.
*
*/
#include "oo/Sock.h"
#include "oo/print.h"
#include <cerrno>
#include <cstring>
#include <netdb.h>
#include <sys/types.h>
namespace oo {
int Sock::getprotobyname(const char *name) {
if (name == nullptr) {
name = "tcp";
}
struct protoent *proto = ::getprotobyname(name);
if (proto == nullptr) {
return -1;
}
return proto->p_proto;
}
int Sock::getservbyname(const char *name, const char *proto) {
if (name == nullptr) {
throw ReferenceError();
}
if (proto == nullptr) {
proto = "tcp";
}
struct servent *serv = ::getservbyname(name, proto);
if (!serv) {
// maybe it's just a numeric string
int port;
try {
port = convert<int>(name);
} catch(ValueError err) {
return -1;
}
if (port <= 0) { // invalid port number
return -1; // should we throw ValueError instead?
}
return port;
}
return ntohs(serv->s_port);
}
String Sock::getservbyport(int port, const char *proto) {
if (proto == nullptr) {
proto = "tcp";
}
struct servent *serv = ::getservbyport(htons(port), proto);
if (!serv) {
return String("");
}
return String(serv->s_proto);
}
bool Sock::listen(const char *serv) {
int sock = ::socket(AF_INET, SOCK_STREAM, 0);
if (sock == -1) {
throw IOError("failed to create socket");
}
// set option reuse bind address
int on = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#ifdef SO_REUSEPORT
int on2 = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#endif
struct sockaddr_in sa;
std::memset(&sa, 0, sizeof(struct sockaddr_in));
sa.sin_family = AF_INET;
sa.sin_addr.s_addr = INADDR_ANY;
int port = this->getservbyname(serv);
if (port == -1) {
::close(sock);
throw IOError("failed to listen, service unknown");
}
sa.sin_port = htons(port);
socklen_t sa_len = sizeof(struct sockaddr_in);
if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) {
::close(sock);
throw IOError("failed to bind socket");
}
if (::listen(sock, SOMAXCONN) == -1) {
::close(sock);
throw IOError("failed to listen on socket");
}
if (!f_.open(sock, "rw")) {
::close(sock);
throw IOError("failed to tie socket to a stream");
}
return true;
}
bool Sock::listen6(const char *serv) {
int sock = ::socket(AF_INET6, SOCK_STREAM, 0);
if (sock == -1) {
throw IOError("failed to create socket");
}
// set option reuse bind address
int on = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#ifdef SO_REUSEPORT
int on2 = 1;
if (::setsockopt(sock, SOL_SOCKET, SO_REUSEPORT, &on2, sizeof(int)) == -1) {
::close(sock);
throw IOError("failed to set socket option");
}
#endif
struct sockaddr_in6 sa;
std::memset(&sa, 0, sizeof(struct sockaddr_in6));
sa.sin6_family = AF_INET6;
sa.sin6_addr = in6addr_any;
int port = this->getservbyname(serv);
if (port == -1) {
::close(sock);
throw IOError("failed to listen, service unknown");
}
sa.sin6_port = htons(port);
socklen_t sa_len = sizeof(struct sockaddr_in6);
if (::bind(sock, (struct sockaddr *)&sa, sa_len) == -1) {
::close(sock);
throw IOError("failed to bind socket");
}
if (::listen(sock, SOMAXCONN) == -1) {
::close(sock);
throw IOError("failed to listen on socket");
}
if (!f_.open(sock, "rw")) {
::close(sock);
throw IOError("failed to tie socket to a stream");
}
return true;
}
bool Sock::connect(const char *ipaddr, const char *serv) {
if (ipaddr == nullptr) {
throw ReferenceError();
}
if (serv == nullptr) {
throw ReferenceError();
}
if (!this->isclosed()) {
throw IOError("socket is already in use");
}
struct addrinfo hints, *res;
std::memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC; // IPv4, IPv6, or any other protocol
hints.ai_socktype = SOCK_STREAM;
if (::getaddrinfo(ipaddr, serv, &hints, &res) != 0) {
throw IOError("failed to get address info");
}
int sock = -1;
// try connecting, try out all protocols
for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) {
if ((sock = ::socket(r->ai_family, r->ai_socktype, r->ai_protocol)) == -1) {
continue;
}
if (::connect(sock, r->ai_addr, r->ai_addrlen) == -1) {
::close(sock);
sock = -1;
continue;
}
break; // successful connect
}
freeaddrinfo(res);
if (sock == -1) {
throw IOError("failed to connect to remote host");
}
// tie it to a stream
if (!f_.open(sock, "w+")) {
::close(sock);
sock = -1;
throw IOError("failed to open socket as a stream");
}
return true;
}
Sock Sock::accept(void) const {
if (this->isclosed()) {
throw IOError("accept() called on a non-listening socket");
}
Sock sock;
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(struct sockaddr_storage);
int sockfd;
for(;;) {
sockfd = ::accept(f_.fileno(), (struct sockaddr *)&addr, &addr_len);
if (sockfd == -1) {
if (errno == EINTR) {
continue;
}
return Sock();
}
break;
}
if (!sock.f_.open(sockfd, "w+")) {
return Sock();
}
return sock;
}
String Sock::remoteaddr(void) const {
if (this->isclosed()) {
throw IOError("can not get remote address of an unconnected socket");
}
struct sockaddr_storage addr;
socklen_t addr_len = sizeof(struct sockaddr_storage);
if (::getpeername(f_.fileno(), (struct sockaddr *)&addr, &addr_len) == -1) {
throw IOError("failed to get remote address of socket");
}
char host[NI_MAXHOST];
if (::getnameinfo((struct sockaddr *)&addr, addr_len, host, sizeof(host),
nullptr, 0, NI_NUMERICHOST|NI_NUMERICSERV) == -1) {
throw IOError("failed to get numeric address of remote host");
}
return String(host);
}
Sock listen(const char *serv) {
Sock sock;
if (!sock.listen(serv)) {
return Sock();
}
return sock;
}
Sock listen6(const char *serv) {
Sock sock;
if (!sock.listen6(serv)) {
return Sock();
}
return sock;
}
Sock connect(const char *ipaddr, const char *serv) {
Sock sock;
if (!sock.connect(ipaddr, serv)) {
return Sock();
}
return sock;
}
String resolv(const String& ipaddr) {
if (ipaddr.empty()) {
throw ValueError();
}
struct addrinfo *res;
if (::getaddrinfo(ipaddr.c_str(), nullptr, nullptr, &res) != 0) {
// probably invalid IP address
return ipaddr;
}
char host[NI_MAXHOST];
for(struct addrinfo *r = res; r != nullptr; r = r->ai_next) {
if (::getnameinfo(r->ai_addr, r->ai_addrlen, host, sizeof(host), nullptr, 0, 0) == 0) {
freeaddrinfo(res);
return String(host);
}
}
// some kind of error
// print("TD error: %s", ::gai_strerror(err));
freeaddrinfo(res);
return ipaddr;
}
void fprint(Sock& sock, const char *fmt, ...) {
if (fmt == nullptr) {
throw ReferenceError();
}
if (!*fmt) {
return;
}
std::va_list ap;
va_start(ap, fmt);
vfprint(sock, fmt, ap);
va_end(ap);
}
void vfprint(Sock& sock, const char *fmt, std::va_list ap) {
if (fmt == nullptr) {
throw ReferenceError();
}
std::stringstream ss;
vssprint(ss, fmt, ap);
sock.write(ss.str());
}
} // namespace
// EOB
|
Java
|
// Copyright 2013 Yangqing Jia
#include <algorithm>
#include <cmath>
#include <cfloat>
#include <vector>
#include "caffe/layer.hpp"
#include "caffe/vision_layers.hpp"
#include "caffe/util/math_functions.hpp"
#include "caffe/util/io.hpp"
#define C_ 1
using std::max;
namespace caffe {
const float kLOG_THRESHOLD = 1e-20;
template <typename Dtype>
void MultinomialLogisticLossLayer<Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Loss Layer takes no output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[1]->channels(), 1);
CHECK_EQ(bottom[1]->height(), 1);
CHECK_EQ(bottom[1]->width(), 1);
}
template <typename Dtype>
Dtype MultinomialLogisticLossLayer<Dtype>::Backward_cpu(
const vector<Blob<Dtype>*>& top, const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
const Dtype* bottom_data = (*bottom)[0]->cpu_data();
const Dtype* bottom_label = (*bottom)[1]->cpu_data();
Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
int num = (*bottom)[0]->num();
int dim = (*bottom)[0]->count() / (*bottom)[0]->num();
memset(bottom_diff, 0, sizeof(Dtype) * (*bottom)[0]->count());
Dtype loss = 0;
for (int i = 0; i < num; ++i) {
int label = static_cast<int>(bottom_label[i]);
Dtype prob = max(bottom_data[i * dim + label], Dtype(kLOG_THRESHOLD));
loss -= log(prob);
bottom_diff[i * dim + label] = - 1. / prob / num;
}
return loss / num;
}
// TODO: implement the GPU version for multinomial loss
template <typename Dtype>
void InfogainLossLayer<Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Loss Layer takes no output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[1]->channels(), 1);
CHECK_EQ(bottom[1]->height(), 1);
CHECK_EQ(bottom[1]->width(), 1);
BlobProto blob_proto;
ReadProtoFromBinaryFile(this->layer_param_.source(), &blob_proto);
infogain_.FromProto(blob_proto);
CHECK_EQ(infogain_.num(), 1);
CHECK_EQ(infogain_.channels(), 1);
CHECK_EQ(infogain_.height(), infogain_.width());
}
template <typename Dtype>
Dtype InfogainLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down,
vector<Blob<Dtype>*>* bottom) {
const Dtype* bottom_data = (*bottom)[0]->cpu_data();
const Dtype* bottom_label = (*bottom)[1]->cpu_data();
const Dtype* infogain_mat = infogain_.cpu_data();
Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
int num = (*bottom)[0]->num();
int dim = (*bottom)[0]->count() / (*bottom)[0]->num();
CHECK_EQ(infogain_.height(), dim);
Dtype loss = 0;
for (int i = 0; i < num; ++i) {
int label = static_cast<int>(bottom_label[i]);
for (int j = 0; j < dim; ++j) {
Dtype prob = max(bottom_data[i * dim + j], Dtype(kLOG_THRESHOLD));
loss -= infogain_mat[label * dim + j] * log(prob);
bottom_diff[i * dim + j] = - infogain_mat[label * dim + j] / prob / num;
}
}
return loss / num;
}
template <typename Dtype>
void EuclideanLossLayer<Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Loss Layer takes no as output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[0]->channels(), bottom[1]->channels());
CHECK_EQ(bottom[0]->height(), bottom[1]->height());
CHECK_EQ(bottom[0]->width(), bottom[1]->width());
difference_.Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
}
template <typename Dtype>
Dtype EuclideanLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
int count = (*bottom)[0]->count();
int num = (*bottom)[0]->num();
caffe_sub(count, (*bottom)[0]->cpu_data(), (*bottom)[1]->cpu_data(),
difference_.mutable_cpu_data());
Dtype loss = caffe_cpu_dot(
count, difference_.cpu_data(), difference_.cpu_data()) / num / Dtype(2);
// Compute the gradient
caffe_axpby(count, Dtype(1) / num, difference_.cpu_data(), Dtype(0),
(*bottom)[0]->mutable_cpu_diff());
return loss;
}
template <typename Dtype>
void AccuracyLayer<Dtype>::SetUp(
const vector<Blob<Dtype>*>& bottom, vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Accuracy Layer takes two blobs as input.";
CHECK_EQ(top->size(), 1) << "Accuracy Layer takes 1 output.";
CHECK_EQ(bottom[0]->num(), bottom[1]->num())
<< "The data and label should have the same number.";
CHECK_EQ(bottom[1]->channels(), 1);
CHECK_EQ(bottom[1]->height(), 1);
CHECK_EQ(bottom[1]->width(), 1);
(*top)[0]->Reshape(1, 2, 1, 1);
}
template <typename Dtype>
void AccuracyLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
Dtype accuracy = 0;
Dtype logprob = 0;
const Dtype* bottom_data = bottom[0]->cpu_data();
const Dtype* bottom_label = bottom[1]->cpu_data();
int num = bottom[0]->num();
int dim = bottom[0]->count() / bottom[0]->num();
for (int i = 0; i < num; ++i) {
// Accuracy
Dtype maxval = -FLT_MAX;
int max_id = 0;
for (int j = 0; j < dim; ++j) {
if (bottom_data[i * dim + j] > maxval) {
maxval = bottom_data[i * dim + j];
max_id = j;
}
}
//LOG(INFO) << " max_id: " << max_id << " label: " << static_cast<int>(bottom_label[i]);
if (max_id == static_cast<int>(bottom_label[i])) {
++accuracy;
}
Dtype prob = max(bottom_data[i * dim + static_cast<int>(bottom_label[i])],
Dtype(kLOG_THRESHOLD));
logprob -= log(prob);
}
// LOG(INFO) << "classes: " << num;
(*top)[0]->mutable_cpu_data()[0] = accuracy / num;
(*top)[0]->mutable_cpu_data()[1] = logprob / num;
}
template <typename Dtype>
void HingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Hinge Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Hinge Loss Layer takes no output.";
}
template <typename Dtype>
void HingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
const Dtype* label = bottom[1]->cpu_data();
int num = bottom[0]->num();
int count = bottom[0]->count();
int dim = count / num;
caffe_copy(count, bottom_data, bottom_diff);
if(0) {
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j)
LOG(INFO) << bottom_data[i * dim + j];
LOG(INFO) << "*************ONE PASS*****************";
}
for (int i = 0; i < num; ++i) {
bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
//LOG(INFO) << bottom_diff[i * dim + static_cast<int>(label[i])];
}
for (int i = 0; i < num; ++i) {
for (int j = 0; j < dim; ++j) {
//LOG(INFO) << bottom_diff[i * dim + j];
bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]);
//if(bottom_diff[i*dim+j] != 1)
//LOG(INFO) << bottom_diff[i*dim+j];
}
}
}
template <typename Dtype>
Dtype HingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
const Dtype* label = (*bottom)[1]->cpu_data();
int num = (*bottom)[0]->num();
int count = (*bottom)[0]->count();
int dim = count / num;
Dtype loss = caffe_cpu_asum(count, bottom_diff) / num;
caffe_cpu_sign(count, bottom_diff, bottom_diff);
for (int i = 0; i < num; ++i) {
bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
}
caffe_scal(count, Dtype(1. / num), bottom_diff);
//LOG(INFO) << "loss" << loss;
return loss;
}
//**********************SquaredHingeLoss**********************
template <typename Dtype>
void SquaredHingeLossLayer<Dtype>::SetUp(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
CHECK_EQ(bottom.size(), 2) << "Squared Hinge Loss Layer takes two blobs as input.";
CHECK_EQ(top->size(), 0) << "Squared Hinge Loss Layer takes no output.";
}
template <typename Dtype>
void SquaredHingeLossLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
vector<Blob<Dtype>*>* top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
const Dtype* label = bottom[1]->cpu_data();
int num = bottom[0]->num();
int count = bottom[0]->count();
int dim = count / num;
caffe_copy(count, bottom_data, bottom_diff);
//Debug
if(0) {
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3; ++j) {
LOG(INFO) << bottom_data[i * dim + j];
}
LOG(INFO) << "*************ONE PASS*****************";
}
for (int i = 0; i < num; ++i) {
bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
//LOG(INFO) << static_cast<int>(label[i]);
}
for (int i = 0; i < num; ++i) {
for (int j = 0; j < dim; ++j) {
//LOG(INFO) << bottom_diff[i * dim + j];
bottom_diff[i * dim + j] = max(Dtype(0), 1 + bottom_diff[i * dim + j]);
//if(bottom_diff[i*dim+j] != 1)
//LOG(INFO) << bottom_diff[i*dim+j];
}
}
}
template <typename Dtype>
Dtype SquaredHingeLossLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const bool propagate_down, vector<Blob<Dtype>*>* bottom) {
Dtype* bottom_diff = (*bottom)[0]->mutable_cpu_diff();
const Dtype* label = (*bottom)[1]->cpu_data();
int num = (*bottom)[0]->num();
int count = (*bottom)[0]->count();
int dim = count / num;
Dtype loss = caffe_cpu_dot(count, bottom_diff, bottom_diff) / num;
for (int i = 0; i < num; ++i) {
bottom_diff[i * dim + static_cast<int>(label[i])] *= -1;
}
caffe_scal(count, Dtype(2.* C_ / num), bottom_diff);
//LOG(INFO) << "loss" << loss;
return loss;
}
INSTANTIATE_CLASS(MultinomialLogisticLossLayer);
INSTANTIATE_CLASS(InfogainLossLayer);
INSTANTIATE_CLASS(EuclideanLossLayer);
INSTANTIATE_CLASS(AccuracyLayer);
INSTANTIATE_CLASS(HingeLossLayer);
INSTANTIATE_CLASS(SquaredHingeLossLayer);
} // namespace caffe
|
Java
|
#ifndef _CONVOUTPUT_SPH_H_
#define _CONVOUTPUT_SPH_H_
/*
###################################################################################
#
# CDMlib - Cartesian Data Management library
#
# Copyright (c) 2013-2017 Advanced Institute for Computational Science (AICS), RIKEN.
# All rights reserved.
#
# Copyright (c) 2016-2017 Research Institute for Information Technology (RIIT), Kyushu University.
# All rights reserved.
#
###################################################################################
*/
/**
* @file convOutput_SPH.h
* @brief convOutput_SPH Class Header
* @author aics
* @date 2013/11/7
*/
#include "convOutput.h"
class convOutput_SPH : public convOutput {
public:
/** コンストラクタ */
convOutput_SPH();
/** デストラクタ */
~convOutput_SPH();
public:
/**
* @brief 出力ファイルをオープンする
* @param [in] prefix ファイル接頭文字
* @param [in] step ステップ数
* @param [in] id ランク番号
* @param [in] mio 出力時の分割指定 true = local / false = gather(default)
*/
cdm_FILE* OutputFile_Open(
const std::string prefix,
const unsigned step,
const int id,
const bool mio);
/**
* @brief sphファイルのheaderの書き込み
* @param[in] step ステップ数
* @param[in] dim 変数の個数
* @param[in] d_type データ型タイプ
* @param[in] imax x方向ボクセルサイズ
* @param[in] jmax y方向ボクセルサイズ
* @param[in] kmax z方向ボクセルサイズ
* @param[in] time 時間
* @param[in] org 原点座標
* @param[in] pit ピッチ
* @param[in] prefix ファイル接頭文字
* @param[in] pFile 出力ファイルポインタ
*/
bool
WriteHeaderRecord(int step,
int dim,
CDM::E_CDM_DTYPE d_type,
int imax,
int jmax,
int kmax,
double time,
double* org,
double* pit,
const std::string prefix,
cdm_FILE *pFile);
/**
* @brief マーカーの書き込み
* @param[in] dmy マーカー
* @param[in] pFile 出力ファイルポインタ
* @param[in] out plot3d用
*/
bool
WriteDataMarker(int dmy, cdm_FILE* pFile, bool out);
protected:
};
#endif // _CONVOUTPUT_SPH_H_
|
Java
|
#ifndef CRYPTOPP_CONFIG_H
#define CRYPTOPP_CONFIG_H
#ifdef __GNUC__
#define VC_INLINE static inline __attribute__((always_inline))
#elif defined (_MSC_VER)
#define VC_INLINE __forceinline
#else
#define VC_INLINE static inline
#endif
#ifdef __GNUC__
#define CRYPTOPP_GCC_VERSION (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__)
#endif
// Apple and LLVM's Clang. Apple Clang version 7.0 roughly equals LLVM Clang version 3.7
#if defined(__clang__ ) && !defined(__apple_build_version__)
#define CRYPTOPP_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#elif defined(__clang__ ) && defined(__apple_build_version__)
#define CRYPTOPP_APPLE_CLANG_VERSION (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__)
#endif
// Clang due to "Inline assembly operands don't work with .intel_syntax", http://llvm.org/bugs/show_bug.cgi?id=24232
// TODO: supply the upper version when LLVM fixes it. We set it to 20.0 for compilation purposes.
#if (defined(CRYPTOPP_CLANG_VERSION) && CRYPTOPP_CLANG_VERSION <= 200000) || (defined(CRYPTOPP_APPLE_CLANG_VERSION) && CRYPTOPP_APPLE_CLANG_VERSION <= 200000)
#define CRYPTOPP_DISABLE_INTEL_ASM 1
#endif
#ifndef CRYPTOPP_L1_CACHE_LINE_SIZE
// This should be a lower bound on the L1 cache line size. It's used for defense against timing attacks.
// Also see http://stackoverflow.com/questions/794632/programmatically-get-the-cache-line-size.
#if defined(_M_X64) || defined(__x86_64__) || (__ILP32__ >= 1)
#define CRYPTOPP_L1_CACHE_LINE_SIZE 64
#else
// L1 cache line size is 32 on Pentium III and earlier
#define CRYPTOPP_L1_CACHE_LINE_SIZE 32
#endif
#endif
#if defined(_MSC_VER) && (_MSC_VER > 1200)
#define CRYPTOPP_MSVC6PP_OR_LATER
#endif
#ifndef CRYPTOPP_ALIGN_DATA
#if defined(_MSC_VER)
#define CRYPTOPP_ALIGN_DATA(x) __declspec(align(x))
#elif defined(__GNUC__)
#define CRYPTOPP_ALIGN_DATA(x) __attribute__((aligned(x)))
#else
#define CRYPTOPP_ALIGN_DATA(x)
#endif
#endif
#ifndef CRYPTOPP_SECTION_ALIGN16
#if defined(__GNUC__) && !defined(__APPLE__)
// the alignment attribute doesn't seem to work without this section attribute when -fdata-sections is turned on
#define CRYPTOPP_SECTION_ALIGN16 __attribute__((section ("CryptoPP_Align16")))
#else
#define CRYPTOPP_SECTION_ALIGN16
#endif
#endif
#if defined(_MSC_VER) || defined(__fastcall)
#define CRYPTOPP_FASTCALL __fastcall
#else
#define CRYPTOPP_FASTCALL
#endif
#ifdef CRYPTOPP_DISABLE_X86ASM // for backwards compatibility: this macro had both meanings
#define CRYPTOPP_DISABLE_ASM
#define CRYPTOPP_DISABLE_SSE2
#endif
// Apple's Clang prior to 5.0 cannot handle SSE2 (and Apple does not use LLVM Clang numbering...)
#if defined(CRYPTOPP_APPLE_CLANG_VERSION) && (CRYPTOPP_APPLE_CLANG_VERSION < 50000)
# define CRYPTOPP_DISABLE_ASM
#endif
#if !defined(CRYPTOPP_DISABLE_ASM) && ((defined(_MSC_VER) && defined(_M_IX86)) || (defined(__GNUC__) && (defined(__i386__) || defined(__x86_64__))))
// C++Builder 2010 does not allow "call label" where label is defined within inline assembly
#define CRYPTOPP_X86_ASM_AVAILABLE
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || CRYPTOPP_GCC_VERSION >= 30300 || defined(__SSE2__))
#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE 0
#endif
// SSE3 was actually introduced in GNU as 2.17, which was released 6/23/2006, but we can't tell what version of binutils is installed.
// GCC 4.1.2 was released on 2/13/2007, so we'll use that as a proxy for the binutils version. Also see the output of
// `gcc -dM -E -march=native - < /dev/null | grep -i SSE` for preprocessor defines available.
#if !defined(CRYPTOPP_DISABLE_SSSE3) && (_MSC_VER >= 1400 || CRYPTOPP_GCC_VERSION >= 40102 || defined(__SSSE3__) || defined(__SSE3__))
#define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSSE3_ASM_AVAILABLE 0
#endif
#endif
#if !defined(CRYPTOPP_DISABLE_ASM) && defined(_MSC_VER) && defined(_M_X64)
#define CRYPTOPP_X64_MASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_DISABLE_ASM) && defined(__GNUC__) && defined(__x86_64__)
#define CRYPTOPP_X64_ASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_DISABLE_SSE2) && (defined(CRYPTOPP_MSVC6PP_OR_LATER) || defined(__SSE2__)) && !defined(_M_ARM)
#define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE 0
#endif
#if !defined(CRYPTOPP_DISABLE_SSSE3) && !defined(CRYPTOPP_DISABLE_AESNI) && CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE && (CRYPTOPP_GCC_VERSION >= 40400 || _MSC_FULL_VER >= 150030729 || __INTEL_COMPILER >= 1110 || defined(__AES__))
#define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE 0
#endif
#if CRYPTOPP_BOOL_SSE2_INTRINSICS_AVAILABLE || CRYPTOPP_BOOL_SSE2_ASM_AVAILABLE || defined(CRYPTOPP_X64_MASM_AVAILABLE)
#define CRYPTOPP_BOOL_ALIGN16 1
#else
#define CRYPTOPP_BOOL_ALIGN16 0
#endif
#if CRYPTOPP_BOOL_AESNI_INTRINSICS_AVAILABLE && (defined(__SSE4_1__) || defined(__INTEL_COMPILER) || defined(_MSC_VER))
#define CRYPTOPP_BOOL_SSE41_INTRINSICS_AVAILABLE 1
#else
#define CRYPTOPP_BOOL_SSE41_INTRINSICS_AVAILABLE 0
#endif
// how to allocate 16-byte aligned memory (for SSE2)
#if defined(_MSC_VER)
#define CRYPTOPP_MM_MALLOC_AVAILABLE
#elif defined(__FreeBSD__) || defined(__NetBSD__) || defined(__OpenBSD__)
#define CRYPTOPP_MALLOC_ALIGNMENT_IS_16
#elif defined(__linux__) || defined(__sun__) || defined(__CYGWIN__)
#define CRYPTOPP_MEMALIGN_AVAILABLE
#else
#define CRYPTOPP_NO_ALIGNED_ALLOC
#endif
// how to declare class constants
#if (defined(_MSC_VER) && _MSC_VER <= 1300) || defined(__INTEL_COMPILER)
# define CRYPTOPP_CONSTANT(x) enum {x};
#else
# define CRYPTOPP_CONSTANT(x) static const int x;
#endif
// Linux provides X32, which is 32-bit integers, longs and pointers on x86_64 using the full x86_64 register set.
// Detect via __ILP32__ (http://wiki.debian.org/X32Port). However, __ILP32__ shows up in more places than
// the System V ABI specs calls out, like on just about any 32-bit system with Clang.
#if ((__ILP32__ >= 1) || (_ILP32 >= 1)) && defined(__x86_64__)
#define CRYPTOPP_BOOL_X32 1
#else
#define CRYPTOPP_BOOL_X32 0
#endif
// see http://predef.sourceforge.net/prearch.html
#if (defined(_M_IX86) || defined(__i386__) || defined(__i386) || defined(_X86_) || defined(__I86__) || defined(__INTEL__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X86 1
#else
#define CRYPTOPP_BOOL_X86 0
#endif
#if (defined(_M_X64) || defined(__x86_64__)) && !CRYPTOPP_BOOL_X32
#define CRYPTOPP_BOOL_X64 1
#else
#define CRYPTOPP_BOOL_X64 0
#endif
// Undo the ASM and Intrinsic related defines due to X32.
#if CRYPTOPP_BOOL_X32
# undef CRYPTOPP_BOOL_X64
# undef CRYPTOPP_X64_ASM_AVAILABLE
# undef CRYPTOPP_X64_MASM_AVAILABLE
#endif
#if !defined(CRYPTOPP_NO_UNALIGNED_DATA_ACCESS) && !defined(CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS)
#if (CRYPTOPP_BOOL_X64 || CRYPTOPP_BOOL_X86 || CRYPTOPP_BOOL_X32 || defined(__powerpc__) || (__ARM_FEATURE_UNALIGNED >= 1))
#define CRYPTOPP_ALLOW_UNALIGNED_DATA_ACCESS
#endif
#endif
// this version of the macro is fastest on Pentium 3 and Pentium 4 with MSVC 6 SP5 w/ Processor Pack
#define GETBYTE(x, y) (unsigned int)((unsigned char)((x)>>(8*(y))))
// these may be faster on other CPUs/compilers
// #define GETBYTE(x, y) (unsigned int)(((x)>>(8*(y)))&255)
// #define GETBYTE(x, y) (((byte *)&(x))[y])
#define CRYPTOPP_GET_BYTE_AS_BYTE(x, y) ((byte)((x)>>(8*(y))))
#endif
|
Java
|
####################################################################################
#.Synopsis
# Creates and deletes sinkhole domains in Windows DNS servers.
#
#.Description
# Script takes fully-qualified domain names (FQDNs) and/or simple domain
# names, then uses them to create primary zones (not Active Directory
# integrated) in a Windows DNS server, setting all zones to resolve to a
# single chosen IP address. The IP address might be "0.0.0.0" or the IP
# of an internal server configured for logging. The intention is to
# prevent clients from resolving the correct IP address of unwanted FQDNs
# and domain names, such as for malware and phishing sites. Such names
# are said to be "sinkholed" or "blackholed" since they often resolve
# to 0.0.0.0, which is an inaccessible IP address.
#
#.Parameter InputFile
# Path to a file which contains the FQDNs and domain names to sinkhole.
# File can have blank lines, comment lines (# or ;), multiple FQDNs or
# domains per line (space- or comma-delimited), and can be a hosts file
# with IP addresses too (addresses and localhost entires will be ignored).
# You can also include wildcards to input multiple files, e.g.,
# "*bad*.txt", or pass in an array of file objects instead of a string.
#
#.Parameter Domain
# One or more FQDNs or domains to sinkhole, separated by spaces or commas.
#
#.Parameter SinkHoleIP
# The IP address to which all sinkholed names will resolve. The
# default is "0.0.0.0", but perhaps is better set to an internal server.
# Remember, there is only one IP for ALL the sinkholed domains.
#
#.Parameter DnsServerName
# FQDN of the Windows DNS server. Defaults to localhost. If specified,
# please always use a fully-qualified domain name (FQDN), especially if
# the DNS server is a stand-alone or in a different domain.
#
#.Parameter IncludeWildCard
# Will add a wildcard host record (*) to every sinkhole domain, which
# will match all possible hostnames within that domain. Keep in mind
# that sinkholing "www.sans.org" will treat the "www" as a domain
# name, so a wildcard is not needed to match it; but sinkholing just
# "sans.org" will not match "www.sans.org" or "ftp.sans.org" without
# the wildcard. If you only want to sinkhole the exact FQDN or domain
# name supplied to the script, then don't include a wildcard record.
# If you are certain that you do not want to resolve anything whatsoever
# under the sinkholed domains, then include the wildcard DNS record.
#
#.Parameter ReloadSinkHoleDomains
# Will cause every sinkholed domain in your DNS server to re-read the
# one shared zone file they all use. This is the zone file for the
# 000-sinkholed-domain.local domain. Keep in mind that the DNS
# graphical management tool shows you what is cached in memory, not
# what is in the zone file. Reload the sinkhole domains if you,
# for example, change the sinkhole IP address. Using this switch
# causes any other parameters to be ignored.
#
#.Parameter DeleteSinkHoleDomains
# Will delete all sinkhole domains, but will not delete any regular
# non-sinkhole domains. Strictly speaking, this deletes any domain
# which uses a zone file named "000-sinkholed-domain.local.dns".
# The zone file itself is not deleted, but it only 1KB in size.
# Using this switch causes any other parameters to be ignored.
#
#.Parameter RemoveLeadingWWW
# Some lists of sinkhole names are simple domain names, while other
# lists might prepend "www." to the beginning of many of the names.
# Use this switch to remove the "www." from the beginning of any
# name to be sinkholed, then consider using -IncludeWildCard too.
# Note that "www.", "www1.", "www2." ... "www9." will be cut too,
# but only for a single digit after the "www" part (1-9 only).
#
#.Parameter Credential
# An "authority\username" string to explicitly authenticate to the
# DNS server instead of using single sign-on with the current
# identity. The authority is either a server name or a domain name.
# You will be prompted for the passphrase. You can also pass in
# a variable with a credential object from Get-Credential.
#
#.Example
# .\Sinkhole-DNS.ps1 -Domain "www.sans.org"
#
# This will create a primary DNS domain named "www.sans.org"
# which will resolve to "0.0.0.0". DNS server is local.
#
#.Example
# .\Sinkhole-DNS.ps1 -Domain "www.sans.org" -SinkHoleIP "10.1.1.1"
#
# This will create a primary DNS domain named "www.sans.org"
# which will resolve to "10.1.1.1". DNS server is local.
#
#.Example
# .\Sinkhole-DNS.ps1 -InputFile file.txt -IncludeWildCard
#
# This will create DNS domains out of all the FQDNs and domain
# names listed in file.txt, plus add a wildcard (*) record.
#
#.Example
# .\Sinkhole-DNS.ps1 -ReloadSinkHoleDomains
#
# Perhaps after changing the sinkhole IP address, this will cause
# all sinkholed domains to re-read their shared zone file.
#
#.Example
# .\Sinkhole-DNS.ps1 -DeleteSinkHoleDomains
#
# This will delete all sinkholed domains, but will not delete
# any other domains. This does not delete the sinkhole zone file.
#
#.Example
# .\Sinkhole-DNS.ps1 -InputFile file.txt -DnsServerName `
# "server7.sans.org" -Credential "server7\administrator"
#
# This will create sinkholed domains from file.txt on a remote
# DNS server named "server7.sans.org" with explicit credentials.
# You will be prompted for the passphrase.
#
#.Example
# $Cred = Get-Credential -Credential "server7\administrator"
#
# .\Sinkhole-DNS.ps1 -InputFile *evil*.txt `
# -DnsServerName "server7.sans.org" -Credential $Cred
#
# This will create sinkholed domains from *evil*.txt on a remote
# DNS server named "server7.sans.org" with explicit credentials
# supplied in a credential object ($Cred) which can be reused again.
# Multiple input files may match "*evil*.txt".
#
#
####################################################################################
Param ($InputFile, [String] $Domain, [String] $SinkHoleIP = "0.0.0.0", [String] $DnsServerName = ".", [Switch] $IncludeWildCard,
[Switch] $ReloadSinkHoleDomains, [Switch] $DeleteSinkHoleDomains, [Switch] $RemoveLeadingWWW, $Credential)
# Check for common help switches.
if (($InputFile -ne $Null) -and ($InputFile.GetType().Name -eq "String") -and ($InputFile -match "/\?|-help|--h|--help"))
{
If ($Host.Version.Major -ge 2) { get-help -full .\sinkhole-dns.ps1 }
Else {"`nPlease read this script's header in Notepad for the help information."}
Exit
}
# Confirm PowerShell 2.0 or later.
If ($Host.Version.Major -lt 2) { "This script requires PowerShell 2.0 or later.`nDownload the latest version from http://www.microsoft.com/powershell`n" ; Exit }
# If necessary, prompt user for domain\username and a passphrase.
If ($Credential) { $Cred = Get-Credential -Credential $Credential }
Function Main
{
# Test access to WMI at target server ($ZoneClass is used later too).
$ZoneClass = GetWMI -Query "SELECT * FROM META_CLASS WHERE __CLASS = 'MicrosoftDNS_Zone'"
If (-not $? -or $ZoneClass.Name -ne "MicrosoftDNS_Zone") { Throw("Failed to connect to WMI service or the WMI DNS_Zone namespace!") ; Exit }
##### Parse input domains, but exclude the following: localhost, any IP addresses, blank lines.
#Process any -Domain args.
[Object[]] $Domains = @($Domain -Split "[\s\;\,]")
#Process any -InputFile arguments and expand any wildcards.
If (($InputFile -ne $Null) -and ($InputFile.GetType().Name -eq "String")) { $InputFile = dir $InputFile }
If ($InputFile -ne $Null) { $InputFile | ForEach { $Domains += Get-Content $_ | Where { $_ -notmatch "^[\#\;\<]" } | ForEach { $_ -Split "[\s\;\,]" } } }
#If -RemoveLeadingWWW was used, edit out those "www." strings.
If ($RemoveLeadingWWW) { 0..$([Int] $Domains.Count - 1) | ForEach { $Domains[$_] = $Domains[$_] -Replace "^www[1-9]{0,1}\.","" } }
#Convert to lowercase, remove redundants, exclude blank lines, exclude IPs, exclude anything with a colon in it, e.g., IPv6.
$Domains = $Domains | ForEach { $_.Trim().ToLower() } | Sort -Unique | Where { $_.Length -ne 0 -and $_ -notmatch "^localhost$|^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}|\:" }
If ($Domains.Count -le 0) { "No domains specified!" ; exit } Else { "`n" + [String] $Domains.Count + " domain(s) to sinkhole to $SinkHoleIP." }
#####
##### Get or create the master sinkhole zone: 000-sinkholed-domain.local.
$WmiPath = "Root\MicrosoftDNS:MicrosoftDNS_Zone.ContainerName='000-sinkholed-domain.local',DnsServerName='" + $DnsServerName + "',Name='000-sinkholed-domain.local'"
If (InvokeWmiMethod -ObjectPath $WmiPath -MethodName GetDistinguishedName) #Zone exists.
{
"`nThe 000-sinkholed-domain.local zone already exists, deleting its existing DNS records."
$ExistingRecords = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_AType WHERE ContainerName = '000-sinkholed-domain.local'")
If (-not $?) { Throw("Failed to query the A records of the 000-sinkholed-domain.local domain!") ; exit }
If ($ExistingRecords.Count -gt 0) { $ExistingRecords | ForEach { $_.Delete() } }
}
Else #Zone does not exist.
{
"`nCreating the 000-sinkholed-domain.local zone and its zone file."
$RR = $ZoneClass.CreateZone("000-sinkholed-domain.local",0,$false,$null,$null,"only-edit.000-sinkholed-domain.local.")
If (-not $? -or $RR.__CLASS -ne "__PARAMETERS")
{
If ($Credential -And ($DnsServerName.Length -ne 0) -And ($DnsServerName -NotLike "*.*")) { "Did you forget to use a FQDN for the DNS server name?" }
Throw("Failed to create the 000-sinkholed-domain.local domain!")
Exit
}
}
#####
##### Create DNS records in master sinkhole zone.
# Create the default A record with the sinkhole IP address.
$RecordClass = $Null # Defaults to "IN" class of record.
$TTL = 120 # Seconds. Defaults to zone default if you set this to $null.
$ATypeRecords = GetWMI -Query "SELECT * FROM META_CLASS WHERE __CLASS = 'MicrosoftDNS_AType'"
If (-not $? -or $ATypeRecords.Name -ne "MicrosoftDNS_AType") { "`nFailed to query A type records, but continuing..." }
$ARecord = $ATypeRecords.CreateInstanceFromPropertyData($DnsServerName,"000-sinkholed-domain.local","000-sinkholed-domain.local",$RecordClass,$TTL,$SinkHoleIP)
If ($?) { "Created default DNS record for the 000-sinkholed-domain.local zone ($SinkHoleIP)." }
Else { "Failed to create default A record for the 000-sinkholed-domain.local zone, but continuing..." }
# Create the wildcard A record if the -IncludeWildCard switch was used.
If ($IncludeWildCard)
{
$ARecord = $ATypeRecords.CreateInstanceFromPropertyData($DnsServerName,"000-sinkholed-domain.local","*.000-sinkholed-domain.local",$RecordClass,$TTL,$SinkHoleIP)
If ($?) { "Created the wildcard (*) record for the 000-sinkholed-domain.local zone ($SinkHoleIP)." }
Else { "Failed to create the wildcard (*) record for the 000-sinkholed-domain.local zone, but continuing..." }
}
# Update zone data file on disk after adding the A record(s).
If (InvokeWmiMethod -ObjectPath $WmiPath -MethodName WriteBackZone)
{ "Updated the zone file for 000-sinkholed-domain.local." }
Else
{
Start-Sleep -Seconds 2 #Just seems to help...
$ItWorked = InvokeWmiMethod -ObjectPath $WmiPath -MethodName WriteBackZone
If ($ItWorked) { "Updated the zone file for 000-sinkholed-domain.local." }
Else {"`nFailed to update the server data file for the 000-sinkholed-domain.local zone, but continuing..." }
}
#####
##### Create the sinkholed domains using the 000-sinkholed-domain.local.dns zone file.
$Created = $NotCreated = 0
$CurrentErrorActionPreference = $ErrorActionPreference
$ErrorActionPreference = "SilentlyContinue"
$Domains | ForEach `
{
$ZoneClass.CreateZone($_,0,$false,"000-sinkholed-domain.local.dns",$null,"only-edit.000-sinkholed-domain.local.") | Out-Null
If ($?) { $Created++ } Else { $NotCreated++ }
}
$ErrorActionPreference = $CurrentErrorActionPreference
"`nSinkhole domains created at the DNS server: $Created"
"`nDomains NOT created (maybe already existed): $NotCreated`n"
} #End of Main
Function GetWMI ([String] $Query)
{
# This is a helper function for the sake of -Credential.
If ($Credential) { Get-WmiObject -Query $Query -Namespace "Root/MicrosoftDNS" -ComputerName $DnsServerName -Credential $Cred }
Else { Get-WmiObject -Query $Query -Namespace "Root/MicrosoftDNS" -ComputerName $DnsServerName }
}
Function InvokeWmiMethod ([String] $ObjectPath, [String] $MethodName)
{
# This is a helper function for the sake of -Credential.
$ErrorActionPreference = "SilentlyContinue"
If ($Credential) { Invoke-WmiMethod -Path $ObjectPath -Name $MethodName -ComputerName $DnsServerName -Credential $Cred }
Else { Invoke-WmiMethod -Path $ObjectPath -Name $MethodName -ComputerName $DnsServerName }
$? #Returns
}
Function Reload-SinkHoledDomains
{
# Function causes sinkholed domains to be reloaded from the shared master zone file, perhaps after a -SinkHoleIP change.
# You may get errors if zone is temporarily locked for updates, but the DNS server's default lock is only two minutes.
"`nReloading sinkholed domains from the 000-sinkholed-domain.local.dns zone file, `nwhich may take a few minutes if you have 10K+ domains..."
$BHDomains = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_Zone WHERE DataFile = '000-sinkholed-domain.local.dns'")
If (-not $?) { Throw("Failed to connect to WMI service!") ; exit }
"`nSinkholed domains to be reloaded from the zone file: " + [String] $BHDomains.Count
$Locked = @() #Index numbers of zones which are temporarily locked and cannot be reloaded yet.
$i = 0
$ErrorActionPreference = "SilentlyContinue"
If ($BHDomains.Count -gt 0) { $BHDomains | ForEach { $_.ReloadZone() ; If (-not $?) { $Locked += $i } ; $i++ } }
If ($Locked.Count -gt 0)
{
"`n" + [String] $Locked.Count + " zone(s) are still temporarily locked, will try those again in two minutes.`nPlease wait two minutes or hit Ctrl-C to cancel..."
Start-Sleep -Seconds 60
"Just one more minute... Thank you for holding, your function call is appreciated."
Start-Sleep -Seconds 30
"Just 30 more seconds... Your patience is admirable, and you're good looking too!"
Start-Sleep -Seconds 35
$Locked | ForEach { $BHDomains[$_].ReloadZone() ; if (-not $?) { "`n" + [String] $BHDomains[$_].ContainerName + " is still locked and has not reloaded yet." } }
}
"`nThe other sinkholed domains were successfully reloaded.`n"
} #End
Function Delete-SinkHoledDomains
{
# Delete all sinkholed zones, including 000-sinkholed-domain.local, but
# note that this does not delete the (tiny) zone file on the drive.
"`nDeleting all sinkholed domains, which may take a few minutes if you have 10K+ domains..."
$BHDomains = @(GetWMI -Query "SELECT * FROM MicrosoftDNS_Zone WHERE DataFile = '000-sinkholed-domain.local.dns'")
If (-not $?) { Throw("Failed to connect to WMI service!") ; exit }
"`nSinkhole domains to be deleted: " + [String] $BHDomains.Count
$i = 0
If ($BHDomains.Count -gt 0) { $BHDomains | ForEach { $_.Delete() ; If ($?){$i++} } }
"Sinkhole domains deleted count: $i`n"
} #End
########################
# MAIN #
########################
If ($ReloadSinkHoleDomains) { Reload-SinkHoledDomains ; Exit }
If ($DeleteSinkHoleDomains) { Delete-SinkHoledDomains ; Exit }
Main
|
Java
|
var searchData=
[
['lettersonly',['lettersOnly',['../class_able_polecat___data___primitive___scalar___string.html#ab2a7acaf93e00fbbd75ea51e56bbf47e',1,'AblePolecat_Data_Primitive_Scalar_String']]],
['list_5fdelimiter',['LIST_DELIMITER',['../interface_able_polecat___query_language___statement_interface.html#a7a10020800f80146451f24fbd57744f1',1,'AblePolecat_QueryLanguage_StatementInterface']]],
['load',['load',['../interface_able_polecat___service___dtx_interface.html#a4dcaa8f72c8423d4de25a9e87fa6f3e4',1,'AblePolecat_Service_DtxInterface']]],
['loadclass',['loadClass',['../class_able_polecat___registry___class.html#af58c5b3a44f9688f9e90dd35abbdefa2',1,'AblePolecat_Registry_Class']]],
['loadmore',['loadMore',['../interface_able_polecat___service___dtx_interface.html#ab5a46d6d7f1795a26153dc59a28b9881',1,'AblePolecat_Service_DtxInterface']]],
['loadtemplatefragment',['loadTemplateFragment',['../class_able_polecat___dom.html#af8f857ffafb0c1e59d752b7b430a95a0',1,'AblePolecat_Dom']]],
['loadtoken',['loadToken',['../interface_able_polecat___access_control___role___user___authenticated___o_auth2_interface.html#a5126349c471fcaff1a74b9d117b979b1',1,'AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Interface\loadToken()'],['../class_able_polecat___access_control___role___user___authenticated___o_auth2_abstract.html#a5126349c471fcaff1a74b9d117b979b1',1,'AblePolecat_AccessControl_Role_User_Authenticated_OAuth2Abstract\loadToken()']]],
['log_2ephp',['Log.php',['../_command_2_log_8php.html',1,'']]],
['log_5fname_5fbootseq',['LOG_NAME_BOOTSEQ',['../class_able_polecat___log___boot.html#a645cd359836227fd9f770339a3147e7b',1,'AblePolecat_Log_Boot']]],
['logbootmessage',['logBootMessage',['../class_able_polecat___mode___server.html#a049626e8b9364098553ee05897b55111',1,'AblePolecat_Mode_Server']]],
['logerrorinfo',['logErrorInfo',['../class_able_polecat___database___pdo.html#a3fdddf6c2c95a4b45cf1a8468f07477d',1,'AblePolecat_Database_Pdo']]],
['logerrormessage',['logErrorMessage',['../class_able_polecat___log_abstract.html#aab8bf90eb60199535dca4c1a6a7742c6',1,'AblePolecat_LogAbstract']]],
['logstatusmessage',['logStatusMessage',['../class_able_polecat___log_abstract.html#af7ba4439ae852b1deed142b4c80f4453',1,'AblePolecat_LogAbstract']]],
['logwarningmessage',['logWarningMessage',['../class_able_polecat___log_abstract.html#a56bda277fc4e215249cfb9ed967204cc',1,'AblePolecat_LogAbstract']]],
['lookupconstraint',['lookupConstraint',['../class_able_polecat___resource___restricted_abstract.html#a46d5b25cc8f9b1ad658b5c6617536824',1,'AblePolecat_Resource_RestrictedAbstract']]],
['lvalue',['lvalue',['../interface_able_polecat___query_language___expression___binary_interface.html#a3441a080c58bdf934f6f24e8c0aea673',1,'AblePolecat_QueryLanguage_Expression_BinaryInterface\lvalue()'],['../class_able_polecat___query_language___expression___binary_abstract.html#a3441a080c58bdf934f6f24e8c0aea673',1,'AblePolecat_QueryLanguage_Expression_BinaryAbstract\lvalue()']]]
];
|
Java
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_GFX_IMAGE_IMAGE_UTIL_H_
#define UI_GFX_IMAGE_IMAGE_UTIL_H_
#include <vector>
#include "base/basictypes.h"
#include "ui/gfx/gfx_export.h"
namespace gfx {
class Image;
}
namespace gfx {
// Creates an image from the given JPEG-encoded input. If there was an error
// creating the image, returns an IsEmpty() Image.
UI_EXPORT Image ImageFrom1xJPEGEncodedData(const unsigned char* input,
size_t input_size);
// Fills the |dst| vector with JPEG-encoded bytes of the 1x representation of
// the given image.
// Returns true if the image has a 1x representation and the 1x representation
// was encoded successfully.
// |quality| determines the compression level, 0 == lowest, 100 == highest.
// Returns true if the Image was encoded successfully.
UI_EXPORT bool JPEG1xEncodedDataFromImage(const Image& image,
int quality,
std::vector<unsigned char>* dst);
} // namespace gfx
#endif // UI_GFX_IMAGE_IMAGE_UTIL_H_
|
Java
|
// Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/profiles/profile.h"
#include <string>
#include "base/command_line.h"
#include "base/compiler_specific.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/browser/background_contents_service_factory.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/content_settings/host_content_settings_map.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/extensions/extension_message_service.h"
#include "chrome/browser/extensions/extension_pref_store.h"
#include "chrome/browser/extensions/extension_process_manager.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/extension_special_storage_policy.h"
#include "chrome/browser/net/pref_proxy_config_service.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/browser/profiles/off_the_record_profile_io_data.h"
#include "chrome/browser/profiles/profile_dependency_manager.h"
#include "chrome/browser/ssl/ssl_host_state.h"
#include "chrome/browser/sync/profile_sync_service.h"
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/transport_security_persister.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/find_bar/find_bar_state.h"
#include "chrome/browser/ui/webui/chrome_url_data_manager.h"
#include "chrome/browser/ui/webui/extension_icon_source.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/extensions/extension.h"
#include "chrome/common/json_pref_store.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/render_messages.h"
#include "content/browser/appcache/chrome_appcache_service.h"
#include "content/browser/browser_thread.h"
#include "content/browser/chrome_blob_storage_context.h"
#include "content/browser/file_system/browser_file_system_helper.h"
#include "content/browser/host_zoom_map.h"
#include "content/browser/in_process_webkit/webkit_context.h"
#include "content/common/notification_service.h"
#include "grit/locale_settings.h"
#include "net/base/transport_security_state.h"
#include "ui/base/resource/resource_bundle.h"
#include "webkit/database/database_tracker.h"
#include "webkit/quota/quota_manager.h"
#if defined(TOOLKIT_USES_GTK)
#include "chrome/browser/ui/gtk/gtk_theme_service.h"
#endif
#if defined(OS_WIN)
#include "chrome/browser/password_manager/password_store_win.h"
#elif defined(OS_MACOSX)
#include "chrome/browser/keychain_mac.h"
#include "chrome/browser/password_manager/password_store_mac.h"
#elif defined(OS_POSIX) && !defined(OS_CHROMEOS)
#include "chrome/browser/password_manager/native_backend_gnome_x.h"
#include "chrome/browser/password_manager/native_backend_kwallet_x.h"
#include "chrome/browser/password_manager/password_store_x.h"
#elif defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/preferences.h"
#endif
using base::Time;
using base::TimeDelta;
// A pointer to the request context for the default profile. See comments on
// Profile::GetDefaultRequestContext.
net::URLRequestContextGetter* Profile::default_request_context_;
namespace {
} // namespace
Profile::Profile()
: restored_last_session_(false),
accessibility_pause_level_(0) {
}
// static
const char* Profile::kProfileKey = "__PROFILE__";
// static
const ProfileId Profile::kInvalidProfileId = static_cast<ProfileId>(0);
// static
void Profile::RegisterUserPrefs(PrefService* prefs) {
prefs->RegisterBooleanPref(prefs::kSearchSuggestEnabled, true);
prefs->RegisterBooleanPref(prefs::kSessionExitedCleanly, true);
prefs->RegisterBooleanPref(prefs::kSafeBrowsingEnabled, true);
prefs->RegisterBooleanPref(prefs::kSafeBrowsingReportingEnabled, false);
// TODO(estade): IDS_SPELLCHECK_DICTIONARY should be an ASCII string.
prefs->RegisterLocalizedStringPref(prefs::kSpellCheckDictionary,
IDS_SPELLCHECK_DICTIONARY);
prefs->RegisterBooleanPref(prefs::kEnableSpellCheck, true);
prefs->RegisterBooleanPref(prefs::kEnableAutoSpellCorrect, true);
#if defined(TOOLKIT_USES_GTK)
prefs->RegisterBooleanPref(prefs::kUsesSystemTheme,
GtkThemeService::DefaultUsesSystemTheme());
#endif
prefs->RegisterFilePathPref(prefs::kCurrentThemePackFilename, FilePath());
prefs->RegisterStringPref(prefs::kCurrentThemeID,
ThemeService::kDefaultThemeID);
prefs->RegisterDictionaryPref(prefs::kCurrentThemeImages);
prefs->RegisterDictionaryPref(prefs::kCurrentThemeColors);
prefs->RegisterDictionaryPref(prefs::kCurrentThemeTints);
prefs->RegisterDictionaryPref(prefs::kCurrentThemeDisplayProperties);
prefs->RegisterBooleanPref(prefs::kDisableExtensions, false);
prefs->RegisterStringPref(prefs::kSelectFileLastDirectory, "");
#if defined(OS_CHROMEOS)
// TODO(dilmah): For OS_CHROMEOS we maintain kApplicationLocale in both
// local state and user's profile. For other platforms we maintain
// kApplicationLocale only in local state.
// In the future we may want to maintain kApplicationLocale
// in user's profile for other platforms as well.
prefs->RegisterStringPref(prefs::kApplicationLocale, "");
prefs->RegisterStringPref(prefs::kApplicationLocaleBackup, "");
prefs->RegisterStringPref(prefs::kApplicationLocaleAccepted, "");
#endif
}
// static
net::URLRequestContextGetter* Profile::GetDefaultRequestContext() {
return default_request_context_;
}
bool Profile::IsGuestSession() {
#if defined(OS_CHROMEOS)
static bool is_guest_session =
CommandLine::ForCurrentProcess()->HasSwitch(switches::kGuestSession);
return is_guest_session;
#else
return false;
#endif
}
bool Profile::IsSyncAccessible() {
ProfileSyncService* syncService = GetProfileSyncService();
return syncService && !syncService->IsManaged();
}
////////////////////////////////////////////////////////////////////////////////
//
// OffTheRecordProfileImpl is a profile subclass that wraps an existing profile
// to make it suitable for the incognito mode.
//
////////////////////////////////////////////////////////////////////////////////
class OffTheRecordProfileImpl : public Profile,
public BrowserList::Observer {
public:
explicit OffTheRecordProfileImpl(Profile* real_profile)
: profile_(real_profile),
prefs_(real_profile->GetOffTheRecordPrefs()),
ALLOW_THIS_IN_INITIALIZER_LIST(io_data_(this)),
start_time_(Time::Now()) {
extension_process_manager_.reset(ExtensionProcessManager::Create(this));
BrowserList::AddObserver(this);
BackgroundContentsServiceFactory::GetForProfile(this);
DCHECK(real_profile->GetPrefs()->GetBoolean(prefs::kIncognitoEnabled));
// TODO(oshima): Remove the need to eagerly initialize the request context
// getter. chromeos::OnlineAttempt is illegally trying to access this
// Profile member from a thread other than the UI thread, so we need to
// prevent a race.
#if defined(OS_CHROMEOS)
GetRequestContext();
#endif // defined(OS_CHROMEOS)
// Make the chrome//extension-icon/ resource available.
ExtensionIconSource* icon_source = new ExtensionIconSource(real_profile);
GetChromeURLDataManager()->AddDataSource(icon_source);
}
virtual ~OffTheRecordProfileImpl() {
NotificationService::current()->Notify(NotificationType::PROFILE_DESTROYED,
Source<Profile>(this),
NotificationService::NoDetails());
ProfileDependencyManager::GetInstance()->DestroyProfileServices(this);
// Clean up all DB files/directories
if (db_tracker_)
BrowserThread::PostTask(
BrowserThread::FILE, FROM_HERE,
NewRunnableMethod(
db_tracker_.get(),
&webkit_database::DatabaseTracker::DeleteIncognitoDBDirectory));
BrowserList::RemoveObserver(this);
if (pref_proxy_config_tracker_)
pref_proxy_config_tracker_->DetachFromPrefService();
}
virtual ProfileId GetRuntimeId() {
return reinterpret_cast<ProfileId>(this);
}
virtual std::string GetProfileName() {
// Incognito profile should not return the profile name.
return std::string();
}
virtual FilePath GetPath() { return profile_->GetPath(); }
virtual bool IsOffTheRecord() {
return true;
}
virtual Profile* GetOffTheRecordProfile() {
return this;
}
virtual void DestroyOffTheRecordProfile() {
// Suicide is bad!
NOTREACHED();
}
virtual bool HasOffTheRecordProfile() {
return true;
}
virtual Profile* GetOriginalProfile() {
return profile_;
}
virtual ChromeAppCacheService* GetAppCacheService() {
if (!appcache_service_) {
appcache_service_ = new ChromeAppCacheService;
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(
appcache_service_.get(),
&ChromeAppCacheService::InitializeOnIOThread,
IsOffTheRecord()
? FilePath() : GetPath().Append(chrome::kAppCacheDirname),
make_scoped_refptr(GetHostContentSettingsMap()),
make_scoped_refptr(GetExtensionSpecialStoragePolicy()),
false));
}
return appcache_service_;
}
virtual webkit_database::DatabaseTracker* GetDatabaseTracker() {
if (!db_tracker_.get()) {
db_tracker_ = new webkit_database::DatabaseTracker(
GetPath(), IsOffTheRecord(), GetExtensionSpecialStoragePolicy());
}
return db_tracker_;
}
virtual VisitedLinkMaster* GetVisitedLinkMaster() {
// We don't provide access to the VisitedLinkMaster when we're OffTheRecord
// because we don't want to leak the sites that the user has visited before.
return NULL;
}
virtual ExtensionService* GetExtensionService() {
return GetOriginalProfile()->GetExtensionService();
}
virtual StatusTray* GetStatusTray() {
return GetOriginalProfile()->GetStatusTray();
}
virtual UserScriptMaster* GetUserScriptMaster() {
return GetOriginalProfile()->GetUserScriptMaster();
}
virtual ExtensionDevToolsManager* GetExtensionDevToolsManager() {
// TODO(mpcomplete): figure out whether we should return the original
// profile's version.
return NULL;
}
virtual ExtensionProcessManager* GetExtensionProcessManager() {
return extension_process_manager_.get();
}
virtual ExtensionMessageService* GetExtensionMessageService() {
return GetOriginalProfile()->GetExtensionMessageService();
}
virtual ExtensionEventRouter* GetExtensionEventRouter() {
return GetOriginalProfile()->GetExtensionEventRouter();
}
virtual ExtensionSpecialStoragePolicy* GetExtensionSpecialStoragePolicy() {
return GetOriginalProfile()->GetExtensionSpecialStoragePolicy();
}
virtual SSLHostState* GetSSLHostState() {
if (!ssl_host_state_.get())
ssl_host_state_.reset(new SSLHostState());
DCHECK(ssl_host_state_->CalledOnValidThread());
return ssl_host_state_.get();
}
virtual net::TransportSecurityState* GetTransportSecurityState() {
if (!transport_security_state_.get()) {
transport_security_state_ = new net::TransportSecurityState(
CommandLine::ForCurrentProcess()->GetSwitchValueASCII(
switches::kHstsHosts));
transport_security_loader_ =
new TransportSecurityPersister(true /* readonly */);
transport_security_loader_->Initialize(transport_security_state_.get(),
GetOriginalProfile()->GetPath());
}
return transport_security_state_.get();
}
virtual HistoryService* GetHistoryService(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetHistoryService(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual HistoryService* GetHistoryServiceWithoutCreating() {
return profile_->GetHistoryServiceWithoutCreating();
}
virtual FaviconService* GetFaviconService(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetFaviconService(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual AutocompleteClassifier* GetAutocompleteClassifier() {
return profile_->GetAutocompleteClassifier();
}
virtual WebDataService* GetWebDataService(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetWebDataService(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual WebDataService* GetWebDataServiceWithoutCreating() {
return profile_->GetWebDataServiceWithoutCreating();
}
virtual PasswordStore* GetPasswordStore(ServiceAccessType sat) {
if (sat == EXPLICIT_ACCESS)
return profile_->GetPasswordStore(sat);
NOTREACHED() << "This profile is OffTheRecord";
return NULL;
}
virtual PrefService* GetPrefs() {
return prefs_;
}
virtual PrefService* GetOffTheRecordPrefs() {
return prefs_;
}
virtual TemplateURLModel* GetTemplateURLModel() {
return profile_->GetTemplateURLModel();
}
virtual TemplateURLFetcher* GetTemplateURLFetcher() {
return profile_->GetTemplateURLFetcher();
}
virtual DownloadManager* GetDownloadManager() {
if (!download_manager_.get()) {
scoped_refptr<DownloadManager> dlm(
new DownloadManager(g_browser_process->download_status_updater()));
dlm->Init(this);
download_manager_.swap(dlm);
}
return download_manager_.get();
}
virtual bool HasCreatedDownloadManager() const {
return (download_manager_.get() != NULL);
}
virtual PersonalDataManager* GetPersonalDataManager() {
return NULL;
}
virtual fileapi::FileSystemContext* GetFileSystemContext() {
if (!file_system_context_)
file_system_context_ = CreateFileSystemContext(
GetPath(), IsOffTheRecord(), GetExtensionSpecialStoragePolicy());
DCHECK(file_system_context_.get());
return file_system_context_.get();
}
virtual net::URLRequestContextGetter* GetRequestContext() {
return io_data_.GetMainRequestContextGetter();
}
virtual quota::QuotaManager* GetQuotaManager() {
if (!quota_manager_.get()) {
quota_manager_ = new quota::QuotaManager(
IsOffTheRecord(),
GetPath(),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO),
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::DB));
}
return quota_manager_.get();
}
virtual net::URLRequestContextGetter* GetRequestContextForRenderProcess(
int renderer_child_id) {
if (CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalAppManifests)) {
const Extension* installed_app = GetExtensionService()->
GetInstalledAppForRenderer(renderer_child_id);
if (installed_app != NULL && installed_app->is_storage_isolated())
return GetRequestContextForIsolatedApp(installed_app->id());
}
return GetRequestContext();
}
virtual net::URLRequestContextGetter* GetRequestContextForMedia() {
// In OTR mode, media request context is the same as the original one.
return io_data_.GetMainRequestContextGetter();
}
virtual net::URLRequestContextGetter* GetRequestContextForExtensions() {
return io_data_.GetExtensionsRequestContextGetter();
}
virtual net::URLRequestContextGetter* GetRequestContextForIsolatedApp(
const std::string& app_id) {
return io_data_.GetIsolatedAppRequestContextGetter(app_id);
}
virtual const content::ResourceContext& GetResourceContext() {
return io_data_.GetResourceContext();
}
virtual net::SSLConfigService* GetSSLConfigService() {
return profile_->GetSSLConfigService();
}
virtual HostContentSettingsMap* GetHostContentSettingsMap() {
// Retrieve the host content settings map of the parent profile in order to
// ensure the preferences have been migrated.
profile_->GetHostContentSettingsMap();
if (!host_content_settings_map_.get())
host_content_settings_map_ = new HostContentSettingsMap(this);
return host_content_settings_map_.get();
}
virtual HostZoomMap* GetHostZoomMap() {
if (!host_zoom_map_)
host_zoom_map_ = new HostZoomMap(this);
return host_zoom_map_.get();
}
virtual GeolocationContentSettingsMap* GetGeolocationContentSettingsMap() {
return profile_->GetGeolocationContentSettingsMap();
}
virtual GeolocationPermissionContext* GetGeolocationPermissionContext() {
return profile_->GetGeolocationPermissionContext();
}
virtual UserStyleSheetWatcher* GetUserStyleSheetWatcher() {
return profile_->GetUserStyleSheetWatcher();
}
virtual FindBarState* GetFindBarState() {
if (!find_bar_state_.get())
find_bar_state_.reset(new FindBarState());
return find_bar_state_.get();
}
virtual bool HasProfileSyncService() const {
// We never have a profile sync service.
return false;
}
virtual bool DidLastSessionExitCleanly() {
return profile_->DidLastSessionExitCleanly();
}
virtual BookmarkModel* GetBookmarkModel() {
return profile_->GetBookmarkModel();
}
virtual ProtocolHandlerRegistry* GetProtocolHandlerRegistry() {
return profile_->GetProtocolHandlerRegistry();
}
virtual TokenService* GetTokenService() {
return NULL;
}
virtual ProfileSyncService* GetProfileSyncService() {
return NULL;
}
virtual ProfileSyncService* GetProfileSyncService(
const std::string& cros_user) {
return NULL;
}
virtual BrowserSignin* GetBrowserSignin() {
return profile_->GetBrowserSignin();
}
virtual CloudPrintProxyService* GetCloudPrintProxyService() {
return NULL;
}
virtual bool IsSameProfile(Profile* profile) {
return (profile == this) || (profile == profile_);
}
virtual Time GetStartTime() const {
return start_time_;
}
virtual SpellCheckHost* GetSpellCheckHost() {
return profile_->GetSpellCheckHost();
}
virtual void ReinitializeSpellCheckHost(bool force) {
profile_->ReinitializeSpellCheckHost(force);
}
virtual WebKitContext* GetWebKitContext() {
if (!webkit_context_.get()) {
webkit_context_ = new WebKitContext(
IsOffTheRecord(), GetPath(), GetExtensionSpecialStoragePolicy(),
false);
}
return webkit_context_.get();
}
virtual history::TopSites* GetTopSitesWithoutCreating() {
return NULL;
}
virtual history::TopSites* GetTopSites() {
return NULL;
}
virtual void MarkAsCleanShutdown() {
}
virtual void InitExtensions(bool extensions_enabled) {
NOTREACHED();
}
virtual void InitPromoResources() {
NOTREACHED();
}
virtual void InitRegisteredProtocolHandlers() {
NOTREACHED();
}
virtual NTPResourceCache* GetNTPResourceCache() {
// Just return the real profile resource cache.
return profile_->GetNTPResourceCache();
}
virtual FilePath last_selected_directory() {
const FilePath& directory = last_selected_directory_;
if (directory.empty()) {
return profile_->last_selected_directory();
}
return directory;
}
virtual void set_last_selected_directory(const FilePath& path) {
last_selected_directory_ = path;
}
#if defined(OS_CHROMEOS)
virtual void SetupChromeOSEnterpriseExtensionObserver() {
profile_->SetupChromeOSEnterpriseExtensionObserver();
}
virtual void InitChromeOSPreferences() {
// The incognito profile shouldn't have Chrome OS's preferences.
// The preferences are associated with the regular user profile.
}
#endif // defined(OS_CHROMEOS)
virtual void ExitedOffTheRecordMode() {
// DownloadManager is lazily created, so check before accessing it.
if (download_manager_.get()) {
// Drop our download manager so we forget about all the downloads made
// in incognito mode.
download_manager_->Shutdown();
download_manager_ = NULL;
}
}
virtual void OnBrowserAdded(const Browser* browser) {
}
virtual void OnBrowserRemoved(const Browser* browser) {
if (BrowserList::GetBrowserCount(this) == 0)
ExitedOffTheRecordMode();
}
virtual ChromeBlobStorageContext* GetBlobStorageContext() {
if (!blob_storage_context_) {
blob_storage_context_ = new ChromeBlobStorageContext();
BrowserThread::PostTask(
BrowserThread::IO, FROM_HERE,
NewRunnableMethod(
blob_storage_context_.get(),
&ChromeBlobStorageContext::InitializeOnIOThread));
}
return blob_storage_context_;
}
virtual ExtensionInfoMap* GetExtensionInfoMap() {
return profile_->GetExtensionInfoMap();
}
virtual ChromeURLDataManager* GetChromeURLDataManager() {
if (!chrome_url_data_manager_.get())
chrome_url_data_manager_.reset(new ChromeURLDataManager(this));
return chrome_url_data_manager_.get();
}
virtual PromoCounter* GetInstantPromoCounter() {
return NULL;
}
#if defined(OS_CHROMEOS)
virtual void ChangeAppLocale(const std::string& locale, AppLocaleChangedVia) {
}
virtual void OnLogin() {
}
#endif // defined(OS_CHROMEOS)
virtual PrefProxyConfigTracker* GetProxyConfigTracker() {
if (!pref_proxy_config_tracker_)
pref_proxy_config_tracker_ = new PrefProxyConfigTracker(GetPrefs());
return pref_proxy_config_tracker_;
}
virtual prerender::PrerenderManager* GetPrerenderManager() {
// We do not allow prerendering in OTR profiles at this point.
// TODO(tburkard): Figure out if we want to support this, and how, at some
// point in the future.
return NULL;
}
private:
NotificationRegistrar registrar_;
// The real underlying profile.
Profile* profile_;
// Weak pointer owned by |profile_|.
PrefService* prefs_;
scoped_ptr<ExtensionProcessManager> extension_process_manager_;
OffTheRecordProfileIOData::Handle io_data_;
// The download manager that only stores downloaded items in memory.
scoped_refptr<DownloadManager> download_manager_;
// We use a non-writable content settings map for OTR.
scoped_refptr<HostContentSettingsMap> host_content_settings_map_;
// Use a separate zoom map for OTR.
scoped_refptr<HostZoomMap> host_zoom_map_;
// Use a special WebKit context for OTR browsing.
scoped_refptr<WebKitContext> webkit_context_;
// We don't want SSLHostState from the OTR profile to leak back to the main
// profile because then the main profile would learn some of the host names
// the user visited while OTR.
scoped_ptr<SSLHostState> ssl_host_state_;
// Use a separate FindBarState so search terms do not leak back to the main
// profile.
scoped_ptr<FindBarState> find_bar_state_;
// The TransportSecurityState that only stores enabled sites in memory.
scoped_refptr<net::TransportSecurityState>
transport_security_state_;
// Time we were started.
Time start_time_;
scoped_refptr<ChromeAppCacheService> appcache_service_;
// The main database tracker for this profile.
// Should be used only on the file thread.
scoped_refptr<webkit_database::DatabaseTracker> db_tracker_;
FilePath last_selected_directory_;
scoped_refptr<ChromeBlobStorageContext> blob_storage_context_;
// The file_system context for this profile.
scoped_refptr<fileapi::FileSystemContext> file_system_context_;
scoped_refptr<PrefProxyConfigTracker> pref_proxy_config_tracker_;
scoped_ptr<ChromeURLDataManager> chrome_url_data_manager_;
scoped_refptr<quota::QuotaManager> quota_manager_;
// Used read-only.
scoped_refptr<TransportSecurityPersister> transport_security_loader_;
DISALLOW_COPY_AND_ASSIGN(OffTheRecordProfileImpl);
};
#if defined(OS_CHROMEOS)
// Special case of the OffTheRecordProfileImpl which is used while Guest
// session in CrOS.
class GuestSessionProfile : public OffTheRecordProfileImpl {
public:
explicit GuestSessionProfile(Profile* real_profile)
: OffTheRecordProfileImpl(real_profile) {
}
virtual PersonalDataManager* GetPersonalDataManager() {
return GetOriginalProfile()->GetPersonalDataManager();
}
virtual void InitChromeOSPreferences() {
chromeos_preferences_.reset(new chromeos::Preferences());
chromeos_preferences_->Init(GetPrefs());
}
private:
// The guest user should be able to customize Chrome OS preferences.
scoped_ptr<chromeos::Preferences> chromeos_preferences_;
};
#endif
Profile* Profile::CreateOffTheRecordProfile() {
#if defined(OS_CHROMEOS)
if (Profile::IsGuestSession())
return new GuestSessionProfile(this);
#endif
return new OffTheRecordProfileImpl(this);
}
|
Java
|
/*
* Copyright (c) 2006, 2006, Oracle and/or its affiliates. All rights reserved.
* ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
/*
* wrapper pow(x,y) return x**y
*/
#include "fdlibm.h"
#ifdef __STDC__
double pow(double x, double y) /* wrapper pow */
#else
double pow(x,y) /* wrapper pow */
double x,y;
#endif
{
#ifdef _IEEE_LIBM
return __ieee754_pow(x,y);
#else
double z;
z=__ieee754_pow(x,y);
if(_LIB_VERSION == _IEEE_|| isnan(y)) return z;
if(isnan(x)) {
if(y==0.0)
return __kernel_standard(x,y,42); /* pow(NaN,0.0) */
else
return z;
}
if(x==0.0){
if(y==0.0)
return __kernel_standard(x,y,20); /* pow(0.0,0.0) */
if(finite(y)&&y<0.0)
return __kernel_standard(x,y,23); /* pow(0.0,negative) */
return z;
}
if(!finite(z)) {
if(finite(x)&&finite(y)) {
if(isnan(z))
return __kernel_standard(x,y,24); /* pow neg**non-int */
else
return __kernel_standard(x,y,21); /* pow overflow */
}
}
if(z==0.0&&finite(x)&&finite(y))
return __kernel_standard(x,y,22); /* pow underflow */
return z;
#endif
}
|
Java
|
{% from 'macros/misc.html' import render_tag %}
{% macro render_flag_hidden(hidden_by) -%}
{{ render_tag(_('hidden'), class='user-comment-hidden', icon='hidden', title='%s (%s %s)'|format(_('hidden'), _('by'), hidden_by.screen_name)) }}
{%- endmacro %}
{% macro render_flag_new() -%}
{{ render_tag(_('new')) }}
{%- endmacro %}
|
Java
|
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef NET_HTTP_HTTP_STREAM_PARSER_H_
#define NET_HTTP_HTTP_STREAM_PARSER_H_
#include <string>
#include "base/basictypes.h"
#include "net/base/io_buffer.h"
#include "net/base/load_log.h"
#include "net/base/upload_data_stream.h"
#include "net/http/http_chunked_decoder.h"
#include "net/http/http_response_info.h"
#include "net/socket/client_socket_handle.h"
namespace net {
class ClientSocketHandle;
class HttpRequestInfo;
class HttpStreamParser {
public:
// Any data in |read_buffer| will be used before reading from the socket
// and any data left over after parsing the stream will be put into
// |read_buffer|. The left over data will start at offset 0 and the
// buffer's offset will be set to the first free byte. |read_buffer| may
// have its capacity changed.
HttpStreamParser(ClientSocketHandle* connection,
GrowableIOBuffer* read_buffer,
LoadLog* load_log);
~HttpStreamParser() {}
// These functions implement the interface described in HttpStream with
// some additional functionality
int SendRequest(const HttpRequestInfo* request, const std::string& headers,
UploadDataStream* request_body, HttpResponseInfo* response,
CompletionCallback* callback);
int ReadResponseHeaders(CompletionCallback* callback);
int ReadResponseBody(IOBuffer* buf, int buf_len,
CompletionCallback* callback);
uint64 GetUploadProgress() const;
HttpResponseInfo* GetResponseInfo();
bool IsResponseBodyComplete() const;
bool CanFindEndOfResponse() const;
bool IsMoreDataBuffered() const;
private:
// FOO_COMPLETE states implement the second half of potentially asynchronous
// operations and don't necessarily mean that FOO is complete.
enum State {
STATE_NONE,
STATE_SENDING_HEADERS,
STATE_SENDING_BODY,
STATE_REQUEST_SENT,
STATE_READ_HEADERS,
STATE_READ_HEADERS_COMPLETE,
STATE_BODY_PENDING,
STATE_READ_BODY,
STATE_READ_BODY_COMPLETE,
STATE_DONE
};
// The number of bytes by which the header buffer is grown when it reaches
// capacity.
enum { kHeaderBufInitialSize = 4096 };
// |kMaxHeaderBufSize| is the number of bytes that the response headers can
// grow to. If the body start is not found within this range of the
// response, the transaction will fail with ERR_RESPONSE_HEADERS_TOO_BIG.
// Note: |kMaxHeaderBufSize| should be a multiple of |kHeaderBufInitialSize|.
enum { kMaxHeaderBufSize = 256 * 1024 }; // 256 kilobytes.
// The maximum sane buffer size.
enum { kMaxBufSize = 2 * 1024 * 1024 }; // 2 megabytes.
// Handle callbacks.
void OnIOComplete(int result);
// Try to make progress sending/receiving the request/response.
int DoLoop(int result);
// The implementations of each state of the state machine.
int DoSendHeaders(int result);
int DoSendBody(int result);
int DoReadHeaders();
int DoReadHeadersComplete(int result);
int DoReadBody();
int DoReadBodyComplete(int result);
// Examines |read_buf_| to find the start and end of the headers. Return
// the offset for the end of the headers, or -1 if the complete headers
// were not found. If they are are found, parse them with
// DoParseResponseHeaders().
int ParseResponseHeaders();
// Parse the headers into response_.
void DoParseResponseHeaders(int end_of_header_offset);
// Examine the parsed headers to try to determine the response body size.
void CalculateResponseBodySize();
// Current state of the request.
State io_state_;
// The request to send.
const HttpRequestInfo* request_;
// The request header data.
scoped_refptr<DrainableIOBuffer> request_headers_;
// The request body data.
scoped_ptr<UploadDataStream> request_body_;
// Temporary buffer for reading.
scoped_refptr<GrowableIOBuffer> read_buf_;
// Offset of the first unused byte in |read_buf_|. May be nonzero due to
// a 1xx header, or body data in the same packet as header data.
int read_buf_unused_offset_;
// The amount beyond |read_buf_unused_offset_| where the status line starts;
// -1 if not found yet.
int response_header_start_offset_;
// The parsed response headers. Owned by the caller.
HttpResponseInfo* response_;
// Indicates the content length. If this value is less than zero
// (and chunked_decoder_ is null), then we must read until the server
// closes the connection.
int64 response_body_length_;
// Keep track of the number of response body bytes read so far.
int64 response_body_read_;
// Helper if the data is chunked.
scoped_ptr<HttpChunkedDecoder> chunked_decoder_;
// Where the caller wants the body data.
scoped_refptr<IOBuffer> user_read_buf_;
int user_read_buf_len_;
// The callback to notify a user that their request or response is
// complete or there was an error
CompletionCallback* user_callback_;
// In the client callback, the client can do anything, including
// destroying this class, so any pending callback must be issued
// after everything else is done. When it is time to issue the client
// callback, move it from |user_callback_| to |scheduled_callback_|.
CompletionCallback* scheduled_callback_;
// The underlying socket.
ClientSocketHandle* const connection_;
scoped_refptr<LoadLog> load_log_;
// Callback to be used when doing IO.
CompletionCallbackImpl<HttpStreamParser> io_callback_;
DISALLOW_COPY_AND_ASSIGN(HttpStreamParser);
};
} // namespace net
#endif // NET_HTTP_HTTP_STREAM_PARSER_H_
|
Java
|
# Goga – examples
## Summary
0. Simple functions
1. Constrained one-objective problems
2. Unconstrained two-objective problems
3. Constrained two-objective problems
4. Constrained and unconstrained three-objective problems
5. Unconstrained many-objectives problems
6. Truss shape and topology optimisation
7. Economic emission load dispatch
# 0 Simple functions
Goga can use two types of objective functions:
(A) the higher-level one: MinProb\_t which takes the vector of random variables x and returns
the objectives values in f. It may also return the inequality constraints in g and the
equality constraints in h. It also accepts integer random variables in y
(B) the lower-level one: ObjFunc\_t which takes the pointer to a candidate solution object
(Solution) and fills the Ova array in this object with the objective values. In this method
the vector of random variables x is stored as Flt
Both functions take the cpu number as input if that's necessary (rarely)
The functions definitions of each case are shown below
ObjFunc\_t defines the objective fuction
`type ObjFunc_t func(sol *Solution, cpu int)`
MinProb\_t defines objective functon for specialised minimisation problem
`type MinProb_t func(f, g, h, x []float64, y []int, cpu int)`
## Curve 1
```go
// case A: finding the minimum of 2.0 + (1+x)²
func fcnA(f, g, h, x []float64, y []int, cpu int) {
f[0] = 2.0 + (1.0+x[0])*(1.0+x[0])
}
// case B: finding the minimum of
func fcnB(sol *goga.Solution, cpu int) {
x := sol.Flt
sol.Ova[0] = 2.0 + (1.0+x[0])*(1.0+x[0])
}
// main function
func main() {
// problem definition
nf := 1 // number of objective functions
ng := 0 // number of inequality constraints
nh := 0 // number of equality constraints
// the solver (optimiser)
var opt goga.Optimiser
opt.Default() // must call this to set default constants
opt.FltMin = []float64{-2} // must set minimum
opt.FltMax = []float64{2} // must set maximum
// initialise the solver
useMethodA := false
if useMethodA {
opt.Init(goga.GenTrialSolutions, nil, fcnA, nf, ng, nh)
} else {
opt.Init(goga.GenTrialSolutions, fcnB, nil, nf, ng, nh)
}
// solve problem
opt.Solve()
// print results
xBest := opt.Solutions[0].Flt[0]
fBest := 2.0 + (1.0+xBest)*(1.0+xBest)
io.Pf("xBest = %v\n", xBest)
io.Pf("f(xBest) = %v\n", fBest)
// plotting
fvec := []float64{0} // temporary vector to use with fcnA
xvec := []float64{0} // temporary vector to use with fcnA
X := utl.LinSpace(-2, 2, 101)
F := utl.GetMapped(X, func(x float64) float64 {
xvec[0] = x
fcnA(fvec, nil, nil, xvec, nil, 0)
return fvec[0]
})
plt.Reset(true, nil)
plt.PlotOne(xBest, fBest, &plt.A{C: "r", M: "o", Ms: 20, NoClip: true})
plt.Plot(X, F, nil)
plt.Gll("$x$", "$f$", nil)
plt.Save("/tmp/goga", "simple01")
}
```
Source code: <a href="simple/simple01.go">simple/simple01.go</a>
<div id="container">
<p><img src="simple/figs/simple01.png" width="450"></p>
Output of simple01.go
</div>
## Curve 2
```go
// objective function
func fcn(f, g, h, x []float64, y []int, cpu int) {
f[0] = Cos(8*x[0]*Pi) * Exp(Cos(x[0]*Pi)-1)
}
// main function
func main() {
// problem definition
nf := 1 // number of objective functions
ng := 0 // number of inequality constraints
nh := 0 // number of equality constraints
// the solver (optimiser)
var opt goga.Optimiser
opt.Default() // must call this to set default constants
opt.FltMin = []float64{0} // must set minimum
opt.FltMax = []float64{2} // must set maximum
// initialise the solver
opt.Init(goga.GenTrialSolutions, nil, fcn, nf, ng, nh)
// solve problem
opt.Solve()
// auxiliary
fvec := []float64{0} // temporary vector to use with fcn
xvec := []float64{0} // temporary vector to use with fcn
// print results
xBest := opt.Solutions[0].Flt[0]
xvec[0] = xBest
fcn(fvec, nil, nil, xvec, nil, 0)
fBest := fvec[0]
io.Pf("xBest = %v\n", xBest)
io.Pf("f(xBest) = %v\n", fBest)
// generate f(x) curve
X := utl.LinSpace(opt.FltMin[0], opt.FltMax[0], 1001)
F := utl.GetMapped(X, func(x float64) float64 {
xvec[0] = x
fcn(fvec, nil, nil, xvec, nil, 0)
return fvec[0]
})
// plotting
plt.Reset(true, nil)
plt.PlotOne(xBest, fBest, &plt.A{L: "best", C: "#bf2e64", M: ".", Ms: 15, NoClip: true})
opt.PlotAddFltOva(0, 0, opt.Solutions, 1, &plt.A{L: "all", C: "g", Ls: "none", M: ".", NoClip: true})
plt.Plot(X, F, &plt.A{L: "f(x)", C: "#0077d2"})
plt.Gll("$x$", "$f$", nil)
plt.Save("/tmp/goga", "simple02")
}
```
Source code: <a href="simple/simple02.go">simple/simple02.go</a>
<div id="container">
<p><img src="simple/figs/simple02.png" width="450"></p>
Output of simple02.go
</div>
## Cross-in-tray function
See [cross-in-tray function on wikipedia](https://en.wikipedia.org/wiki/Test_functions_for_optimization)
```go
// objective function
func fcn(f, g, h, x []float64, y []int, cpu int) {
f[0] = -0.0001 * Pow(Abs(Sin(x[0])*Sin(x[1])*Exp(Abs(100-Sqrt(Pow(x[0], 2)+Pow(x[1], 2))/Pi)))+1, 0.1)
}
// main function
func main() {
// problem definition
nf := 1 // number of objective functions
ng := 0 // number of inequality constraints
nh := 0 // number of equality constraints
// the solver (optimiser)
var opt goga.Optimiser
opt.Default() // must call this to set default constants
opt.FltMin = []float64{-10, -10} // must set minimum
opt.FltMax = []float64{+10, +10} // must set maximum
opt.Nsol = 80
// initialise the solver
opt.Init(goga.GenTrialSolutions, nil, fcn, nf, ng, nh)
// solve problem
tstart := time.Now()
opt.Solve()
cputime := time.Now().Sub(tstart)
// print results
fvec := []float64{0} // temporary vector to use with fcn
xbest := opt.Solutions[0].Flt
fcn(fvec, nil, nil, xbest, nil, 0)
io.Pf("xBest = %v\n", xbest)
io.Pf("f(xBest) = %v\n", fvec)
// plotting
pp := goga.NewPlotParams(false)
pp.Npts = 101
pp.ArgsF.NoLines = true
pp.ArgsF.CmapIdx = 4
plt.Reset(true, nil)
plt.Title(io.Sf("Nsol(pop.size)=%d Tmax(generations)=%d CpuTime=%v", opt.Nsol, opt.Tmax, io.RoundDuration(cputime, 1e3)), &plt.A{Fsz: 8})
opt.PlotContour(0, 1, 0, pp)
plt.PlotOne(xbest[0], xbest[1], &plt.A{C: "r", Mec: "r", M: "*"})
plt.Gll("$x_0$", "$x_1$", nil)
plt.Save("/tmp/goga", "cross-in-tray")
}
```
Source code: <a href="simple/cross-in-tray.go">simple/cross-in-tray.go</a>
<div id="container">
<p><img src="simple/figs/cross-in-tray.png" width="450"></p>
Output of cross-in-tray.go
</div>
To check the **repeatability** of the code, the optimisation loop can be called several times. This
can be done with the `RunMany` function. For example, replace `opt.Solve()` with
```go
// solve problem
opt.RunMany("", "", false)
// stat
opt.PrintStatF(0)
```
Which will produce something similar to:
```
fmin = -2.0626118708227428
fave = -2.062611870822731
fmax = -2.0626118708217605
fdev = 9.817431965542015e-14
[-2.11,-2.10) | 0
[-2.10,-2.08) | 0
[-2.08,-2.07) | 0
[-2.07,-2.06) | 100 #####################
[-2.06,-2.04) | 0
[-2.04,-2.03) | 0
[-2.03,-2.01) | 0
count = 100
```
Source code: <a href="simple/cross-in-tray-stat.go">simple/cross-in-tray-stat.go</a>
# 1 Constrained one-objective problems
Source code: <a href="01-one-obj/one-obj.go">one-obj.go</a>
# 2 Unconstrained two-objective problems
Source code: <a href="02-two-obj/two-obj.go">two-obj.go</a>
# 3 Constrained two-objective problems
Source code: <a href="03-two-obj-ct/two-obj-ct.go">two-obj-ct.go</a>
# 4 Constrained and unconstrained three-objective problems
Source code: <a href="04-three-obj/three-obj.go">three-obj.go</a>
# 5 Unconstrained many-objectives problems
Source code: <a href="05-many-obj/many-obj.go">many-obj.go</a>
# 6 Truss shape and topology optimisation
Source code: <a href="06-truss/topology.go">topology.go</a>
and <a href="06-truss/femsim.go">femsim.go</a>
# 7 Economic emission load dispatch
Source code: <a href="07-eed/ecoemission.go">ecoemission.go</a>
and <a href="07-eed/generators.go">generators.go</a>
|
Java
|
/**
* Layout Select UI
*
* @package zork
* @subpackage form
* @author Kristof Matos <kristof.matos@megaweb.hu>
*/
( function ( global, $, js )
{
"use strict";
if ( typeof js.layoutSelect !== "undefined" )
{
return;
}
js.require( "jQuery.fn.vslider");
/**
* Generates layout select user interface from radio inputs
*
* @memberOf Zork.Form.Element
*/
global.Zork.prototype.layoutSelect = function ( element )
{
js.style('/styles/scripts/layoutselect.css');
element = $( element );
var defaultKey = element.data( "jsLayoutselectDefaultkey")
|| "paragraph.form.content.layout.default",
descriptionKeyPattern = element.data( "jsLayoutselectDescriptionkey")
|| "paragraph.form.content.layout.default-description",
imageSrcPattern = element.data( "jsLayoutselectImagesrc") || "",
selectType = element.data( "jsLayoutselectType") || "locale",
itemsPerRow = parseInt(element.data("jsLayoutselectItemsperrow"))>0
? parseInt(element.data("jsLayoutselectItemsperrow"))
: ( selectType == "local" ? 6 : 3 );
element.addClass( "layout-select "+selectType);
element.find( "label" ).each( function(idx,eleRadioItem) {
var input = $(eleRadioItem).find( ":radio" ),
inner = $('<div class="inner"/>').append(input),
title = $('<div class="title"/>').html( $(eleRadioItem).html() || js.core.translate(defaultKey) ),
overlay = $('<div class="overlay"/>'),
innerButtons = $('<div class="buttons"/>').appendTo(inner),
innerDescription = $('<p class="description"/>').appendTo(inner),
innerButtonsSelect = $('<span class="select"/>')
.html(
js.core.translate("default.select"
,js.core.userLocale)
)
.appendTo(innerButtons),
dateCreated = input.data("created") || '-',
dateModified = input.data("lastModified") || '-';
$(eleRadioItem).html('')
.append(inner)
.append(title)
.append(overlay);
if( selectType == 'import' )
{
innerDescription.html(
js.core.translate(
descriptionKeyPattern.replace("[value]",
input.attr( "value"))
,js.core.userLocale));
var imageSrc = imageSrcPattern
.replace("[value]",input.attr( "value"));
inner.prepend( $( "<img alt='icon' />" ).attr( "src", imageSrc ));
}
else//selectType == 'locale'
{
if( input.attr( "value") )
{
innerDescription
.append(
$('<div/>')
.append( $('<span/>').html(
js.core.translate("default.lastmodified",
js.core.userLocale)
+': ') )
.append( $('<span/>').html(dateModified) )
)
.append(
$('<div/>')
.append( $('<span/>').html(
js.core.translate("default.created",
js.core.userLocale)
+': ') )
.append( $('<span/>').html(dateCreated) )
);
js.core.translate("default.created",js.core.userLocale)
innerButtons.prepend(
$('<a class="preview"/>')
.html(
js.core.translate("default.preview"
,js.core.userLocale)
)
.attr('href','/app/'+js.core.userLocale
+'/paragraph/render/'+input.attr( "value"))
.attr('target','_blank')
);
}
}
innerButtonsSelect.on( "click", function(evt) {
element.find( "label" ).removeClass("selected");
$(evt.target.parentNode.parentNode.parentNode).addClass("selected");
} );
} );
var eleRow,
eleRowsContainer = $('<div/>').appendTo(element);
element.find( "label" ).each( function(idxItem,eleItem) {
if( idxItem%itemsPerRow==0 )
{
eleRow = $('<div />').appendTo(eleRowsContainer);
}
eleRow.append(eleItem);
} );
$(eleRowsContainer).vslider({"items":"div", "itemheight":( selectType == 'local' ? 300 : 255 )});
{
setTimeout( function(){ $('.ui-vslider').vslider('refresh') },100 );
}
};
global.Zork.prototype.layoutSelect.isElementConstructor = true;
} ( window, jQuery, zork ) );
|
Java
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author Bill
*/
public class BackRightAutonomous extends CommandBase {
public BackRightAutonomous() {
// Use requires() here to declare subsystem dependencies
// eg. requires(chassis);
}
// Called just before this Command runs the first time
protected void initialize() {
}
// Called repeatedly when this Command is scheduled to run
protected void execute() {
}
// Make this return true when this Command no longer needs to run execute()
protected boolean isFinished() {
return false;
}
// Called once after isFinished returns true
protected void end() {
}
// Called when another command which requires one or more of the same
// subsystems is scheduled to run
protected void interrupted() {
}
}
|
Java
|
/**
* Dialog to add a new visualization from any of your
* existing tables.
*
*/
cdb.admin.NewVisualizationDialogTableItem = cdb.core.View.extend({
events: {
"click .remove" : "_onRemove"
},
tagName: "li",
className: "table",
initialize: function() {
_.bindAll(this, "_onRemove");
this.template = this.getTemplate('dashboard/views/new_visualization_dialog_table_item');
},
render: function() {
this.$el.html(this.template(this.model.toJSON()));
return this.$el;
},
show: function() {
this.$el.show();
},
_onRemove: function(e) {
this.killEvent(e);
this.clear();
this.trigger("remove", this);
},
clear: function() {
this.$el.hide();
}
});
cdb.admin.NewVisualizationDialog = cdb.admin.BaseDialog.extend({
_MAX_LAYERS: 3,
_TEXTS: {
title: _t('Create visualization'),
loading_data: _t('Loading data…'),
description: _t('Select the layers you will use on this visualization (you will be able to add more later)'),
new_vis_title: _t("Give a name to your visualization"),
no_tables: _t("Looks like you don’t have any imported data in your account. To create your first \
visualization you will need to import at least a dataset.")
},
events: cdb.core.View.extendEvents({ // do not remove
"click .add" : "_onAddTableItem",
}),
initialize: function() {
if (!this.options.user) {
new Throw("No user specified when it is needed")
}
this.user = this.options.user;
// Dialog options
_.extend(this.options, {
title: this._TEXTS.title,
template_name: 'common/views/dialog_base',
clean_on_hide: true,
ok_button_classes: "button green hidden",
ok_title: this._TEXTS.title,
modal_type: "creation",
modal_class: 'new_visualization_dialog',
width: this.user.isInsideOrg() ? 502 : 464
});
// Set max layers if user has this parameter
var max_user_layers = this.options.user.get('max_layers');
if (!isNaN(max_user_layers) && this._MAX_LAYERS != max_user_layers) {
this._MAX_LAYERS = max_user_layers;
}
this.ok = this.options.ok;
this.model = new cdb.core.Model();
this.model.bind("change:disabled", this._onToggleDisabled, this);
// Collection to manage the tables
this.table_items = new Backbone.Collection();
this.table_items.bind("add", this._addTableItem, this);
this.table_items.bind("remove", this._onRemove, this);
this.constructor.__super__.initialize.apply(this);
this.setWizard(this.options.wizard_option);
this.visualizations = new cdb.admin.Visualizations({ type: "derived" });
},
render_content: function() {
this.$content = $("<div>");
var temp_content = this.getTemplate('dashboard/views/new_visualization_dialog');
this.$content.append(temp_content({ description: this._TEXTS.loading }));
// Tables combo
this.tableCombo = new cdb.ui.common.VisualizationsSelector({
model: this.visualizations,
user: this.options.user
});
this.$content.find('.tableListCombo').append(this.tableCombo.render().el);
this.addView(this.tableCombo);
this.disableOkButton();
this._loadTables();
return this.$content;
},
_onToggleDisabled: function() {
this.tableCombo[ this.model.get("disabled") ? "disable" : "enable" ]()
this.$(".combo_wrapper")[( this.model.get("disabled") ? "addClass" : "removeClass" )]('disabled');
},
_loadTables: function() {
this.visualizations.bind('reset', this._onReset, this);
this.visualizations.options.set({ type: "table", per_page: 100000 });
var order = { data: { o: { updated_at: "desc" }, exclude_raster: true }};
this.visualizations.fetch(order);
},
_onReset: function() {
this.visualizations.unbind(null, null, this); // do this one time and one time only
if (this.visualizations.size() == 0) {
this.emptyState = true;
this._showEmpyState();
} else {
this.emptyState = false;
this._showControls();
}
},
_showEmpyState: function() {
var self = this;
this.$el.find(".loader").fadeOut(250, function() {
$(this).addClass("hidden");
self.$el.find("p").html(self._TEXTS.no_tables);
self.$el.find(".ok.button").removeClass("green").addClass("grey");
self.$el.find(".ok.button").html("Ok, let's import some data");
self.$el.find(".ok.button").fadeIn(250, function() {
self.enableOkButton();
});
});
},
_showControls: function() {
var self = this;
this.$el.find(".loader").fadeOut(250, function() {
$(this).addClass("hidden");
self.$el.find("p").html(self._TEXTS.description);
self.$el.find(".combo_wrapper").addClass('active');
self.$el.find(".ok.button").fadeIn(250, function() { $(this).removeClass("hidden"); });
self.$el.find(".cancel").fadeIn(250);
});
this._setupScroll();
},
_setupScroll: function() {
this.$scrollPane = this.$el.find(".scrollpane");
this.$scrollPane.jScrollPane({ showArrows: true, animateScroll: true, animateDuration: 150 });
this.api = this.$scrollPane.data('jsp');
},
_cleanString: function(s, n) {
if (s) {
s = s.replace(/<(?:.|\n)*?>/gm, ''); // strip HTML tags
s = s.substr(0, n-1) + (s.length > n ? '…' : ''); // truncate string
}
return s;
},
_onAddTableItem: function(e) {
this.killEvent(e);
if (this.model.get("disabled")) return;
var table = this.tableCombo.getSelected();
if (table) {
var model = new cdb.core.Model(table);
this.table_items.add(model);
}
},
_afterAddItem: function() {
if (this.table_items.length >= this._MAX_LAYERS) {
this.model.set("disabled", true);
}
},
_afterRemoveItem: function() {
if (this.table_items.length < this._MAX_LAYERS) {
this.model.set("disabled", false);
}
},
_addTableItem: function(model) {
this.enableOkButton();
this._afterAddItem();
var view = new cdb.admin.NewVisualizationDialogTableItem({ model: model });
this.$(".tables").append(view.render());
view.bind("remove", this._onRemoveItem, this);
view.show();
this._refreshScrollPane();
},
_onRemoveItem: function(item) {
this.table_items.remove(item.model);
this._refreshScrollPane();
this._afterRemoveItem();
},
_onRemove: function() {
if (this.table_items.length == 0) this.disableOkButton();
},
_refreshScrollPane: function() {
var self = this;
this.$(".scrollpane").animate({
height: this.$(".tables").height() + 5 }, { duration: 150, complete: function() {
self.api && self.api.reinitialise();
}});
},
_ok: function(ev) {
this.killEvent(ev);
if (this.emptyState) {
this.hide();
this.trigger("navigate_tables", this);
} else {
if (this.table_items.length === 0) return;
this.hide();
this._openNameVisualizationDialog();
}
},
_openNameVisualizationDialog: function() {
var selected_tables = this.table_items.pluck("vis_id");
var tables = _.compact(
this.visualizations.map(function(m) {
if (_.contains(selected_tables, m.get('id'))) {
return m.get('table').name
}
return false;
})
);
var dlg = new cdb.admin.NameVisualization({
msg: this._TEXTS.new_vis_title,
onResponse: function(name) {
var vis = new cdb.admin.Visualization();
vis.save({ name: name, tables: tables }).success(function() {
window.location.href = vis.viewUrl();
});
}
});
dlg.bind("will_open", function() {
$("body").css({ overflow: "hidden" });
}, this);
dlg.bind("was_removed", function() {
$("body").css({ overflow: "auto" });
}, this);
dlg.appendToBody().open();
},
clean: function() {
$(".select2-drop.select2-drop-active").hide();
cdb.admin.BaseDialog.prototype.clean.call(this);
}
});
|
Java
|
/******************************************************************************
This source file is part of the Avogadro project.
Copyright 2013 Kitware, Inc.
This source code is released under the New BSD License, (the "License").
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.
******************************************************************************/
#include <utilities/vtktesting/imageregressiontest.h>
#include <avogadro/qtopengl/glwidget.h>
#include <avogadro/rendering/geometrynode.h>
#include <avogadro/rendering/spheregeometry.h>
#include <avogadro/rendering/textlabel2d.h>
#include <avogadro/rendering/textlabel3d.h>
#include <avogadro/rendering/textproperties.h>
#include <avogadro/core/vector.h>
#include <QtOpenGL/QGLFormat>
#include <QtWidgets/QApplication>
#include <QtGui/QImage>
#include <QtCore/QTimer>
#include <iostream>
using Avogadro::Vector2f;
using Avogadro::Vector3f;
using Avogadro::Vector2i;
using Avogadro::Vector3ub;
using Avogadro::Rendering::GeometryNode;
using Avogadro::Rendering::TextLabel2D;
using Avogadro::Rendering::TextLabel3D;
using Avogadro::Rendering::TextProperties;
using Avogadro::Rendering::SphereGeometry;
using Avogadro::QtOpenGL::GLWidget;
using Avogadro::VtkTesting::ImageRegressionTest;
int qttextlabeltest(int argc, char *argv[])
{
// Set up the default format for our GL contexts.
QGLFormat defaultFormat = QGLFormat::defaultFormat();
defaultFormat.setSampleBuffers(true);
QGLFormat::setDefaultFormat(defaultFormat);
// Create and show widget
QApplication app(argc, argv);
GLWidget widget;
widget.setGeometry(10, 10, 500, 500);
widget.show();
// Create scene
GeometryNode *geometry = new GeometryNode;
widget.renderer().scene().rootNode().addChild(geometry);
// Add a small sphere at the origin for reference:
SphereGeometry *spheres = new SphereGeometry;
spheres->addSphere(Vector3f::Zero(), Vector3ub(128, 128, 128), 0.1f);
geometry->addDrawable(spheres);
// Default text property:
TextProperties tprop;
// Test alignment:
TextLabel3D *l3 = NULL;
TextLabel2D *l2 = NULL;
// 3D:
tprop.setColorRgb(255, 0, 0);
tprop.setAlign(TextProperties::HLeft, TextProperties::VTop);
l3 = new TextLabel3D;
l3->setText("Upper Left Anchor");
l3->setAnchor(Vector3f::Zero());
l3->setTextProperties(tprop);
geometry->addDrawable(l3);
tprop.setColorRgb(0, 255, 0);
tprop.setAlign(TextProperties::HLeft, TextProperties::VBottom);
l3 = new TextLabel3D;
l3->setText("Bottom Left Anchor");
l3->setAnchor(Vector3f::Zero());
l3->setTextProperties(tprop);
geometry->addDrawable(l3);
tprop.setColorRgb(0, 0, 255);
tprop.setAlign(TextProperties::HRight, TextProperties::VTop);
l3 = new TextLabel3D;
l3->setText("Upper Right Anchor");
l3->setAnchor(Vector3f::Zero());
l3->setTextProperties(tprop);
geometry->addDrawable(l3);
tprop.setColorRgb(255, 255, 0);
tprop.setAlign(TextProperties::HRight, TextProperties::VBottom);
l3 = new TextLabel3D;
l3->setText("Bottom Right Anchor");
l3->setAnchor(Vector3f::Zero());
l3->setTextProperties(tprop);
geometry->addDrawable(l3);
tprop.setColorRgba(255, 255, 255, 220);
tprop.setRotationDegreesCW(90.f);
tprop.setAlign(TextProperties::HCenter, TextProperties::VCenter);
l3 = new TextLabel3D;
l3->setText("Centered Anchor (3D)");
l3->setAnchor(Vector3f::Zero());
l3->setTextProperties(tprop);
l3->setRenderPass(Avogadro::Rendering::TranslucentPass);
geometry->addDrawable(l3);
tprop.setRotationDegreesCW(0.f);
tprop.setAlpha(255);
// 2D:
tprop.setColorRgb(255, 0, 0);
tprop.setAlign(TextProperties::HLeft, TextProperties::VTop);
l2 = new TextLabel2D;
l2->setText("Upper Left Corner");
l2->setAnchor(Vector2i(0, widget.height()));
l2->setTextProperties(tprop);
geometry->addDrawable(l2);
tprop.setColorRgb(0, 255, 0);
tprop.setAlign(TextProperties::HLeft, TextProperties::VBottom);
l2 = new TextLabel2D;
l2->setText("Bottom Left Corner");
l2->setAnchor(Vector2i(0, 0));
l2->setTextProperties(tprop);
geometry->addDrawable(l2);
tprop.setColorRgb(0, 0, 255);
tprop.setAlign(TextProperties::HRight, TextProperties::VTop);
l2 = new TextLabel2D;
l2->setText("Upper Right Corner");
l2->setAnchor(Vector2i(widget.width(), widget.height()));
l2->setTextProperties(tprop);
geometry->addDrawable(l2);
tprop.setColorRgb(255, 255, 0);
tprop.setAlign(TextProperties::HRight, TextProperties::VBottom);
l2 = new TextLabel2D;
l2->setText("Bottom Right Corner");
l2->setAnchor(Vector2i(widget.width(), 0));
l2->setTextProperties(tprop);
geometry->addDrawable(l2);
tprop.setColorRgba(255, 255, 255, 220);
tprop.setAlign(TextProperties::HCenter, TextProperties::VCenter);
l2 = new TextLabel2D;
l2->setText("Centered Anchor (2D)");
l2->setAnchor(Vector2i(widget.width() / 2, widget.height() / 2));
l2->setTextProperties(tprop);
geometry->addDrawable(l2);
// Test the TextLabel3D's radius feature:
spheres->addSphere(Vector3f(0.f, 6.f, 0.f), Vector3ub(255, 255, 255), 1.f);
tprop.setColorRgba(255, 128, 64, 255);
tprop.setRotationDegreesCW(90.f);
l3 = new TextLabel3D;
l3->setText("Clipped");
l3->setAnchor(Vector3f(0.f, 6.f, 0.f));
l3->setTextProperties(tprop);
geometry->addDrawable(l3);
tprop.setColorRgba(64, 128, 255, 255);
tprop.setRotationDegreesCW(45.f);
l3 = new TextLabel3D;
l3->setText("Projected");
l3->setAnchor(Vector3f(0.f, 6.f, 0.f));
l3->setTextProperties(tprop);
l3->setRadius(1.f);
geometry->addDrawable(l3);
// Make sure the widget renders the scene, and store it in a QImage.
widget.raise();
widget.repaint();
// Run the application for a while, and then quit so we can save an image.
QTimer timer;
timer.setSingleShot(true);
app.connect(&timer, SIGNAL(timeout()), SLOT(quit()));
timer.start(200);
app.exec();
// Grab the frame buffer of the GLWidget and save it to a QImage.
QImage image = widget.grabFrameBuffer(false);
// Set up the image regression test.
ImageRegressionTest test(argc, argv);
// Do the image threshold test, printing output to the std::cout for ctest.
return test.imageThresholdTest(image, std::cout);
}
|
Java
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!--NewPage-->
<HTML>
<HEAD>
<!-- Generated by javadoc (build 1.6.0) on Wed May 09 10:30:52 EDT 2007 -->
<TITLE>
B-Index
</TITLE>
<META NAME="date" CONTENT="2007-05-09">
<LINK REL ="stylesheet" TYPE="text/css" HREF="../stylesheet.css" TITLE="Style">
<SCRIPT type="text/javascript">
function windowTitle()
{
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="B-Index";
}
}
</SCRIPT>
<NOSCRIPT>
</NOSCRIPT>
</HEAD>
<BODY BGCOLOR="white" onload="windowTitle();">
<HR>
<!-- ========= START OF TOP NAVBAR ======= -->
<A NAME="navbar_top"><!-- --></A>
<A HREF="#skip-navbar_top" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_top_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-1.html"><B>PREV LETTER</B></A>
<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_top"></A>
<!-- ========= END OF TOP NAVBAR ========= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">L</A> <A HREF="index-11.html">M</A> <A HREF="index-12.html">P</A> <A HREF="index-13.html">R</A> <A HREF="index-14.html">S</A> <A HREF="index-15.html">T</A> <A HREF="index-16.html">U</A> <A HREF="index-17.html">W</A> <HR>
<A NAME="_B_"><!-- --></A><H2>
<B>B</B></H2>
<DL>
<DT><A HREF="../edu/umd/cs/mtc/TestFramework.html#buildTestSuite(java.lang.Class)"><B>buildTestSuite(Class<?>)</B></A> -
Static method in class edu.umd.cs.mtc.<A HREF="../edu/umd/cs/mtc/TestFramework.html" title="class in edu.umd.cs.mtc">TestFramework</A>
<DD>Scan through a given class <code>c</code> to find any inner classes
that implement <A HREF="http://junit.sourceforge.net/javadoc/junit/framework/Test.html?is-external=true" title="class or interface in junit.framework"><CODE>Test</CODE></A>.
<DT><A HREF="../edu/umd/cs/mtc/TestFramework.html#buildTestSuite(java.lang.Class, java.lang.String)"><B>buildTestSuite(Class<?>, String)</B></A> -
Static method in class edu.umd.cs.mtc.<A HREF="../edu/umd/cs/mtc/TestFramework.html" title="class in edu.umd.cs.mtc">TestFramework</A>
<DD>Scan through a given class <code>c</code> to find any inner classes
that implement <A HREF="http://junit.sourceforge.net/javadoc/junit/framework/Test.html?is-external=true" title="class or interface in junit.framework"><CODE>Test</CODE></A>.
</DL>
<HR>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<A NAME="navbar_bottom"><!-- --></A>
<A HREF="#skip-navbar_bottom" title="Skip navigation links"></A>
<TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY="">
<TR>
<TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1">
<A NAME="navbar_bottom_firstrow"><!-- --></A>
<TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY="">
<TR ALIGN="center" VALIGN="top">
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../edu/umd/cs/mtc/package-tree.html"><FONT CLASS="NavBarFont1"><B>Tree</B></FONT></A> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A> </TD>
<TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> <FONT CLASS="NavBarFont1Rev"><B>Index</B></FONT> </TD>
<TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A> </TD>
</TR>
</TABLE>
</TD>
<TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM>
</EM>
</TD>
</TR>
<TR>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="index-1.html"><B>PREV LETTER</B></A>
<A HREF="index-3.html"><B>NEXT LETTER</B></A></FONT></TD>
<TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2">
<A HREF="../index.html?index-filesindex-2.html" target="_top"><B>FRAMES</B></A>
<A HREF="index-2.html" target="_top"><B>NO FRAMES</B></A>
<SCRIPT type="text/javascript">
<!--
if(window==top) {
document.writeln('<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>');
}
//-->
</SCRIPT>
<NOSCRIPT>
<A HREF="../allclasses-noframe.html"><B>All Classes</B></A>
</NOSCRIPT>
</FONT></TD>
</TR>
</TABLE>
<A NAME="skip-navbar_bottom"></A>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<A HREF="index-1.html">A</A> <A HREF="index-2.html">B</A> <A HREF="index-3.html">C</A> <A HREF="index-4.html">D</A> <A HREF="index-5.html">E</A> <A HREF="index-6.html">F</A> <A HREF="index-7.html">G</A> <A HREF="index-8.html">H</A> <A HREF="index-9.html">I</A> <A HREF="index-10.html">L</A> <A HREF="index-11.html">M</A> <A HREF="index-12.html">P</A> <A HREF="index-13.html">R</A> <A HREF="index-14.html">S</A> <A HREF="index-15.html">T</A> <A HREF="index-16.html">U</A> <A HREF="index-17.html">W</A> <HR>
</BODY>
</HTML>
|
Java
|
# Copyright 2020 The Cobalt Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# NOTE:
# libdav1d's build process will generate this file and populate it with defines
# that configure the project appropriately and set compilation flags. These
# flags are migrated into Cobalt's gyp and ninja build process which makes this
# file superfluous. However, we keep |config.asm| since the file is referenced
# in the includes for several source files and to keep the overall code changes
# low for ease of rebasing upstream changes from libdav1d.
|
Java
|
/****************************************************************************
**
** BSD 3-Clause License
**
** Copyright (c) 2017, bitdewy
** All rights reserved.
**
****************************************************************************/
#pragma once
#include <QtCore/QMap>
#include <QtGui/QIcon>
class Property;
class BoolPropertyManager;
class BoolPropertyManagerPrivate
{
BoolPropertyManager* boolPropertyManagerPtr_;
friend class BoolPropertyManager;
public:
BoolPropertyManagerPrivate();
BoolPropertyManagerPrivate(const BoolPropertyManagerPrivate&) = delete;
BoolPropertyManagerPrivate& operator=(const BoolPropertyManagerPrivate&) = delete;
QMap<const Property*, bool> values_;
const QIcon checkedIcon_;
const QIcon uncheckedIcon_;
};
|
Java
|
# The purpose of these tests are to ensure that calling ufuncs with quantities
# returns quantities with the right units, or raises exceptions.
import warnings
import pytest
import numpy as np
from numpy.testing.utils import assert_allclose
from ... import units as u
from ...tests.helper import raises
from ...extern.six.moves import zip
from ...utils.compat import NUMPY_LT_1_13
class TestUfuncCoverage(object):
"""Test that we cover all ufunc's"""
def test_coverage(self):
all_np_ufuncs = set([ufunc for ufunc in np.core.umath.__dict__.values()
if type(ufunc) == np.ufunc])
from .. import quantity_helper as qh
all_q_ufuncs = (qh.UNSUPPORTED_UFUNCS |
set(qh.UFUNC_HELPERS.keys()))
assert all_np_ufuncs - all_q_ufuncs == set([])
assert all_q_ufuncs - all_np_ufuncs == set([])
class TestQuantityTrigonometricFuncs(object):
"""
Test trigonometric functions
"""
def test_sin_scalar(self):
q = np.sin(30. * u.degree)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value, 0.5)
def test_sin_array(self):
q = np.sin(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value,
np.array([0., 1. / np.sqrt(2.), 1.]), atol=1.e-15)
def test_arcsin_scalar(self):
q1 = 30. * u.degree
q2 = np.arcsin(np.sin(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def test_arcsin_array(self):
q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian
q2 = np.arcsin(np.sin(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def test_sin_invalid_units(self):
with pytest.raises(TypeError) as exc:
np.sin(3. * u.m)
assert exc.value.args[0] == ("Can only apply 'sin' function "
"to quantities with angle units")
def test_arcsin_invalid_units(self):
with pytest.raises(TypeError) as exc:
np.arcsin(3. * u.m)
assert exc.value.args[0] == ("Can only apply 'arcsin' function to "
"dimensionless quantities")
def test_arcsin_no_warning_on_unscaled_quantity(self):
a = 15 * u.kpc
b = 27 * u.pc
with warnings.catch_warnings():
warnings.filterwarnings('error')
np.arcsin(b/a)
def test_cos_scalar(self):
q = np.cos(np.pi / 3. * u.radian)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value, 0.5)
def test_cos_array(self):
q = np.cos(np.array([0., np.pi / 4., np.pi / 2.]) * u.radian)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value,
np.array([1., 1. / np.sqrt(2.), 0.]), atol=1.e-15)
def test_arccos_scalar(self):
q1 = np.pi / 3. * u.radian
q2 = np.arccos(np.cos(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def test_arccos_array(self):
q1 = np.array([0., np.pi / 4., np.pi / 2.]) * u.radian
q2 = np.arccos(np.cos(q1)).to(q1.unit)
assert_allclose(q1.value, q2.value)
def test_cos_invalid_units(self):
with pytest.raises(TypeError) as exc:
np.cos(3. * u.s)
assert exc.value.args[0] == ("Can only apply 'cos' function "
"to quantities with angle units")
def test_arccos_invalid_units(self):
with pytest.raises(TypeError) as exc:
np.arccos(3. * u.s)
assert exc.value.args[0] == ("Can only apply 'arccos' function to "
"dimensionless quantities")
def test_tan_scalar(self):
q = np.tan(np.pi / 3. * u.radian)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value, np.sqrt(3.))
def test_tan_array(self):
q = np.tan(np.array([0., 45., 135., 180.]) * u.degree)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value,
np.array([0., 1., -1., 0.]), atol=1.e-15)
def test_arctan_scalar(self):
q = np.pi / 3. * u.radian
assert np.arctan(np.tan(q))
def test_arctan_array(self):
q = np.array([10., 30., 70., 80.]) * u.degree
assert_allclose(np.arctan(np.tan(q)).to_value(q.unit), q.value)
def test_tan_invalid_units(self):
with pytest.raises(TypeError) as exc:
np.tan(np.array([1, 2, 3]) * u.N)
assert exc.value.args[0] == ("Can only apply 'tan' function "
"to quantities with angle units")
def test_arctan_invalid_units(self):
with pytest.raises(TypeError) as exc:
np.arctan(np.array([1, 2, 3]) * u.N)
assert exc.value.args[0] == ("Can only apply 'arctan' function to "
"dimensionless quantities")
def test_arctan2_valid(self):
q1 = np.array([10., 30., 70., 80.]) * u.m
q2 = 2.0 * u.km
assert np.arctan2(q1, q2).unit == u.radian
assert_allclose(np.arctan2(q1, q2).value,
np.arctan2(q1.value, q2.to_value(q1.unit)))
q3 = q1 / q2
q4 = 1.
at2 = np.arctan2(q3, q4)
assert_allclose(at2.value, np.arctan2(q3.to_value(1), q4))
def test_arctan2_invalid(self):
with pytest.raises(u.UnitsError) as exc:
np.arctan2(np.array([1, 2, 3]) * u.N, 1. * u.s)
assert "compatible dimensions" in exc.value.args[0]
with pytest.raises(u.UnitsError) as exc:
np.arctan2(np.array([1, 2, 3]) * u.N, 1.)
assert "dimensionless quantities when other arg" in exc.value.args[0]
def test_radians(self):
q1 = np.deg2rad(180. * u.degree)
assert_allclose(q1.value, np.pi)
assert q1.unit == u.radian
q2 = np.radians(180. * u.degree)
assert_allclose(q2.value, np.pi)
assert q2.unit == u.radian
# the following doesn't make much sense in terms of the name of the
# routine, but we check it gives the correct result.
q3 = np.deg2rad(3. * u.radian)
assert_allclose(q3.value, 3.)
assert q3.unit == u.radian
q4 = np.radians(3. * u.radian)
assert_allclose(q4.value, 3.)
assert q4.unit == u.radian
with pytest.raises(TypeError):
np.deg2rad(3. * u.m)
with pytest.raises(TypeError):
np.radians(3. * u.m)
def test_degrees(self):
# the following doesn't make much sense in terms of the name of the
# routine, but we check it gives the correct result.
q1 = np.rad2deg(60. * u.degree)
assert_allclose(q1.value, 60.)
assert q1.unit == u.degree
q2 = np.degrees(60. * u.degree)
assert_allclose(q2.value, 60.)
assert q2.unit == u.degree
q3 = np.rad2deg(np.pi * u.radian)
assert_allclose(q3.value, 180.)
assert q3.unit == u.degree
q4 = np.degrees(np.pi * u.radian)
assert_allclose(q4.value, 180.)
assert q4.unit == u.degree
with pytest.raises(TypeError):
np.rad2deg(3. * u.m)
with pytest.raises(TypeError):
np.degrees(3. * u.m)
class TestQuantityMathFuncs(object):
"""
Test other mathematical functions
"""
def test_multiply_scalar(self):
assert np.multiply(4. * u.m, 2. / u.s) == 8. * u.m / u.s
assert np.multiply(4. * u.m, 2.) == 8. * u.m
assert np.multiply(4., 2. / u.s) == 8. / u.s
def test_multiply_array(self):
assert np.all(np.multiply(np.arange(3.) * u.m, 2. / u.s) ==
np.arange(0, 6., 2.) * u.m / u.s)
@pytest.mark.parametrize('function', (np.divide, np.true_divide))
def test_divide_scalar(self, function):
assert function(4. * u.m, 2. * u.s) == function(4., 2.) * u.m / u.s
assert function(4. * u.m, 2.) == function(4., 2.) * u.m
assert function(4., 2. * u.s) == function(4., 2.) / u.s
@pytest.mark.parametrize('function', (np.divide, np.true_divide))
def test_divide_array(self, function):
assert np.all(function(np.arange(3.) * u.m, 2. * u.s) ==
function(np.arange(3.), 2.) * u.m / u.s)
def test_floor_divide_remainder_and_divmod(self):
inch = u.Unit(0.0254 * u.m)
dividend = np.array([1., 2., 3.]) * u.m
divisor = np.array([3., 4., 5.]) * inch
quotient = dividend // divisor
remainder = dividend % divisor
assert_allclose(quotient.value, [13., 19., 23.])
assert quotient.unit == u.dimensionless_unscaled
assert_allclose(remainder.value, [0.0094, 0.0696, 0.079])
assert remainder.unit == dividend.unit
quotient2 = np.floor_divide(dividend, divisor)
remainder2 = np.remainder(dividend, divisor)
assert np.all(quotient2 == quotient)
assert np.all(remainder2 == remainder)
quotient3, remainder3 = divmod(dividend, divisor)
assert np.all(quotient3 == quotient)
assert np.all(remainder3 == remainder)
with pytest.raises(TypeError):
divmod(dividend, u.km)
with pytest.raises(TypeError):
dividend // u.km
with pytest.raises(TypeError):
dividend % u.km
if hasattr(np, 'divmod'): # not NUMPY_LT_1_13
quotient4, remainder4 = np.divmod(dividend, divisor)
assert np.all(quotient4 == quotient)
assert np.all(remainder4 == remainder)
with pytest.raises(TypeError):
np.divmod(dividend, u.km)
def test_sqrt_scalar(self):
assert np.sqrt(4. * u.m) == 2. * u.m ** 0.5
def test_sqrt_array(self):
assert np.all(np.sqrt(np.array([1., 4., 9.]) * u.m)
== np.array([1., 2., 3.]) * u.m ** 0.5)
def test_square_scalar(self):
assert np.square(4. * u.m) == 16. * u.m ** 2
def test_square_array(self):
assert np.all(np.square(np.array([1., 2., 3.]) * u.m)
== np.array([1., 4., 9.]) * u.m ** 2)
def test_reciprocal_scalar(self):
assert np.reciprocal(4. * u.m) == 0.25 / u.m
def test_reciprocal_array(self):
assert np.all(np.reciprocal(np.array([1., 2., 4.]) * u.m)
== np.array([1., 0.5, 0.25]) / u.m)
# cbrt only introduced in numpy 1.10
# heaviside only introduced in numpy 1.13
@pytest.mark.skipif("not hasattr(np, 'heaviside')")
def test_heaviside_scalar(self):
assert np.heaviside(0. * u.m, 0.5) == 0.5 * u.dimensionless_unscaled
assert np.heaviside(0. * u.s,
25 * u.percent) == 0.25 * u.dimensionless_unscaled
assert np.heaviside(2. * u.J, 0.25) == 1. * u.dimensionless_unscaled
@pytest.mark.skipif("not hasattr(np, 'heaviside')")
def test_heaviside_array(self):
values = np.array([-1., 0., 0., +1.])
halfway = np.array([0.75, 0.25, 0.75, 0.25]) * u.dimensionless_unscaled
assert np.all(np.heaviside(values * u.m,
halfway * u.dimensionless_unscaled) ==
[0, 0.25, 0.75, +1.] * u.dimensionless_unscaled)
@pytest.mark.skipif("not hasattr(np, 'cbrt')")
def test_cbrt_scalar(self):
assert np.cbrt(8. * u.m**3) == 2. * u.m
@pytest.mark.skipif("not hasattr(np, 'cbrt')")
def test_cbrt_array(self):
# Calculate cbrt on both sides since on Windows the cube root of 64
# does not exactly equal 4. See 4388.
values = np.array([1., 8., 64.])
assert np.all(np.cbrt(values * u.m**3) ==
np.cbrt(values) * u.m)
def test_power_scalar(self):
assert np.power(4. * u.m, 2.) == 16. * u.m ** 2
assert np.power(4., 200. * u.cm / u.m) == \
u.Quantity(16., u.dimensionless_unscaled)
# regression check on #1696
assert np.power(4. * u.m, 0.) == 1. * u.dimensionless_unscaled
def test_power_array(self):
assert np.all(np.power(np.array([1., 2., 3.]) * u.m, 3.)
== np.array([1., 8., 27.]) * u.m ** 3)
# regression check on #1696
assert np.all(np.power(np.arange(4.) * u.m, 0.) ==
1. * u.dimensionless_unscaled)
# float_power only introduced in numpy 1.12
@pytest.mark.skipif("not hasattr(np, 'float_power')")
def test_float_power_array(self):
assert np.all(np.float_power(np.array([1., 2., 3.]) * u.m, 3.)
== np.array([1., 8., 27.]) * u.m ** 3)
# regression check on #1696
assert np.all(np.float_power(np.arange(4.) * u.m, 0.) ==
1. * u.dimensionless_unscaled)
@raises(ValueError)
def test_power_array_array(self):
np.power(4. * u.m, [2., 4.])
@raises(ValueError)
def test_power_array_array2(self):
np.power([2., 4.] * u.m, [2., 4.])
def test_power_array_array3(self):
# Identical unit fractions are converted automatically to dimensionless
# and should be allowed as base for np.power: #4764
q = [2., 4.] * u.m / u.m
powers = [2., 4.]
res = np.power(q, powers)
assert np.all(res.value == q.value ** powers)
assert res.unit == u.dimensionless_unscaled
# The same holds for unit fractions that are scaled dimensionless.
q2 = [2., 4.] * u.m / u.cm
# Test also against different types of exponent
for cls in (list, tuple, np.array, np.ma.array, u.Quantity):
res2 = np.power(q2, cls(powers))
assert np.all(res2.value == q2.to_value(1) ** powers)
assert res2.unit == u.dimensionless_unscaled
# Though for single powers, we keep the composite unit.
res3 = q2 ** 2
assert np.all(res3.value == q2.value ** 2)
assert res3.unit == q2.unit ** 2
assert np.all(res3 == q2 ** [2, 2])
def test_power_invalid(self):
with pytest.raises(TypeError) as exc:
np.power(3., 4. * u.m)
assert "raise something to a dimensionless" in exc.value.args[0]
def test_copysign_scalar(self):
assert np.copysign(3 * u.m, 1.) == 3. * u.m
assert np.copysign(3 * u.m, 1. * u.s) == 3. * u.m
assert np.copysign(3 * u.m, -1.) == -3. * u.m
assert np.copysign(3 * u.m, -1. * u.s) == -3. * u.m
def test_copysign_array(self):
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1.) == -np.array([1., 2., 3.]) * u.s)
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, -1. * u.m) == -np.array([1., 2., 3.]) * u.s)
assert np.all(np.copysign(np.array([1., 2., 3.]) * u.s, np.array([-2., 2., -4.]) * u.m) == np.array([-1., 2., -3.]) * u.s)
q = np.copysign(np.array([1., 2., 3.]), -3 * u.m)
assert np.all(q == np.array([-1., -2., -3.]))
assert not isinstance(q, u.Quantity)
def test_ldexp_scalar(self):
assert np.ldexp(4. * u.m, 2) == 16. * u.m
def test_ldexp_array(self):
assert np.all(np.ldexp(np.array([1., 2., 3.]) * u.m, [3, 2, 1])
== np.array([8., 8., 6.]) * u.m)
def test_ldexp_invalid(self):
with pytest.raises(TypeError):
np.ldexp(3. * u.m, 4.)
with pytest.raises(TypeError):
np.ldexp(3., u.Quantity(4, u.m, dtype=int))
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_scalar(self, function):
q = function(3. * u.m / (6. * u.m))
assert q.unit == u.dimensionless_unscaled
assert q.value == function(0.5)
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_array(self, function):
q = function(np.array([2., 3., 6.]) * u.m / (6. * u.m))
assert q.unit == u.dimensionless_unscaled
assert np.all(q.value
== function(np.array([1. / 3., 1. / 2., 1.])))
# should also work on quantities that can be made dimensionless
q2 = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm))
assert q2.unit == u.dimensionless_unscaled
assert_allclose(q2.value,
function(np.array([100. / 3., 100. / 2., 100.])))
@pytest.mark.parametrize('function', (np.exp, np.expm1, np.exp2,
np.log, np.log2, np.log10, np.log1p))
def test_exp_invalid_units(self, function):
# Can't use exp() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
function(3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply '{0}' function to "
"dimensionless quantities"
.format(function.__name__))
def test_modf_scalar(self):
q = np.modf(9. * u.m / (600. * u.cm))
assert q == (0.5 * u.dimensionless_unscaled,
1. * u.dimensionless_unscaled)
def test_modf_array(self):
v = np.arange(10.) * u.m / (500. * u.cm)
q = np.modf(v)
n = np.modf(v.to_value(u.dimensionless_unscaled))
assert q[0].unit == u.dimensionless_unscaled
assert q[1].unit == u.dimensionless_unscaled
assert all(q[0].value == n[0])
assert all(q[1].value == n[1])
def test_frexp_scalar(self):
q = np.frexp(3. * u.m / (6. * u.m))
assert q == (np.array(0.5), np.array(0.0))
def test_frexp_array(self):
q = np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.m))
assert all((_q0, _q1) == np.frexp(_d) for _q0, _q1, _d
in zip(q[0], q[1], [1. / 3., 1. / 2., 1.]))
def test_frexp_invalid_units(self):
# Can't use prod() with non-dimensionless quantities
with pytest.raises(TypeError) as exc:
np.frexp(3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply 'frexp' function to "
"unscaled dimensionless quantities")
# also does not work on quantities that can be made dimensionless
with pytest.raises(TypeError) as exc:
np.frexp(np.array([2., 3., 6.]) * u.m / (6. * u.cm))
assert exc.value.args[0] == ("Can only apply 'frexp' function to "
"unscaled dimensionless quantities")
@pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2))
def test_dimensionless_twoarg_array(self, function):
q = function(np.array([2., 3., 6.]) * u.m / (6. * u.cm), 1.)
assert q.unit == u.dimensionless_unscaled
assert_allclose(q.value,
function(np.array([100. / 3., 100. / 2., 100.]), 1.))
@pytest.mark.parametrize('function', (np.logaddexp, np.logaddexp2))
def test_dimensionless_twoarg_invalid_units(self, function):
with pytest.raises(TypeError) as exc:
function(1. * u.km / u.s, 3. * u.m / u.s)
assert exc.value.args[0] == ("Can only apply '{0}' function to "
"dimensionless quantities"
.format(function.__name__))
class TestInvariantUfuncs(object):
# np.positive was only added in numpy 1.13.
@pytest.mark.parametrize(('ufunc'), [np.absolute, np.fabs,
np.conj, np.conjugate,
np.negative, np.spacing, np.rint,
np.floor, np.ceil] +
[np.positive] if hasattr(np, 'positive') else [])
def test_invariant_scalar(self, ufunc):
q_i = 4.7 * u.m
q_o = ufunc(q_i)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i.unit
assert q_o.value == ufunc(q_i.value)
@pytest.mark.parametrize(('ufunc'), [np.absolute, np.conjugate,
np.negative, np.rint,
np.floor, np.ceil])
def test_invariant_array(self, ufunc):
q_i = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_o = ufunc(q_i)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i.unit
assert np.all(q_o.value == ufunc(q_i.value))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_scalar(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.km
q_o = ufunc(q_i1, q_i2)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_array(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_i2 = np.array([10., -5., 1.e6]) * u.g / u.us
q_o = ufunc(q_i1, q_i2)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_one_arbitrary(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
arbitrary_unit_value = np.array([0.])
q_o = ufunc(q_i1, arbitrary_unit_value)
assert isinstance(q_o, u.Quantity)
assert q_o.unit == q_i1.unit
assert_allclose(q_o.value, ufunc(q_i1.value, arbitrary_unit_value))
@pytest.mark.parametrize(('ufunc'), [np.add, np.subtract, np.hypot,
np.maximum, np.minimum, np.nextafter,
np.remainder, np.mod, np.fmod])
def test_invariant_twoarg_invalid_units(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.s
with pytest.raises(u.UnitsError) as exc:
ufunc(q_i1, q_i2)
assert "compatible dimensions" in exc.value.args[0]
class TestComparisonUfuncs(object):
@pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal,
np.less, np.less_equal,
np.not_equal, np.equal])
def test_comparison_valid_units(self, ufunc):
q_i1 = np.array([-3.3, 2.1, 10.2]) * u.kg / u.s
q_i2 = np.array([10., -5., 1.e6]) * u.g / u.Ms
q_o = ufunc(q_i1, q_i2)
assert not isinstance(q_o, u.Quantity)
assert q_o.dtype == np.bool
assert np.all(q_o == ufunc(q_i1.value, q_i2.to_value(q_i1.unit)))
q_o2 = ufunc(q_i1 / q_i2, 2.)
assert not isinstance(q_o2, u.Quantity)
assert q_o2.dtype == np.bool
assert np.all(q_o2 == ufunc((q_i1 / q_i2)
.to_value(u.dimensionless_unscaled), 2.))
# comparison with 0., inf, nan is OK even for dimensional quantities
for arbitrary_unit_value in (0., np.inf, np.nan):
ufunc(q_i1, arbitrary_unit_value)
ufunc(q_i1, arbitrary_unit_value*np.ones(len(q_i1)))
# and just for completeness
ufunc(q_i1, np.array([0., np.inf, np.nan]))
@pytest.mark.parametrize(('ufunc'), [np.greater, np.greater_equal,
np.less, np.less_equal,
np.not_equal, np.equal])
def test_comparison_invalid_units(self, ufunc):
q_i1 = 4.7 * u.m
q_i2 = 9.4 * u.s
with pytest.raises(u.UnitsError) as exc:
ufunc(q_i1, q_i2)
assert "compatible dimensions" in exc.value.args[0]
class TestInplaceUfuncs(object):
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_one_argument_ufunc_inplace(self, value):
# without scaling
s = value * u.rad
check = s
np.sin(s, out=s)
assert check is s
assert check.unit == u.dimensionless_unscaled
# with scaling
s2 = (value * u.rad).to(u.deg)
check2 = s2
np.sin(s2, out=s2)
assert check2 is s2
assert check2.unit == u.dimensionless_unscaled
assert_allclose(s.value, s2.value)
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_one_argument_ufunc_inplace_2(self, value):
"""Check inplace works with non-quantity input and quantity output"""
s = value * u.m
check = s
np.absolute(value, out=s)
assert check is s
assert np.all(check.value == np.absolute(value))
assert check.unit is u.dimensionless_unscaled
np.sqrt(value, out=s)
assert check is s
assert np.all(check.value == np.sqrt(value))
assert check.unit is u.dimensionless_unscaled
np.exp(value, out=s)
assert check is s
assert np.all(check.value == np.exp(value))
assert check.unit is u.dimensionless_unscaled
np.arcsin(value/10., out=s)
assert check is s
assert np.all(check.value == np.arcsin(value/10.))
assert check.unit is u.radian
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_one_argument_two_output_ufunc_inplace(self, value):
v = 100. * value * u.cm / u.m
v_copy = v.copy()
tmp = v.copy()
check = v
np.modf(v, tmp, v) # cannot use out1,out2 keywords with numpy 1.7
assert check is v
assert check.unit == u.dimensionless_unscaled
v2 = v_copy.to(u.dimensionless_unscaled)
check2 = v2
np.modf(v2, tmp, v2)
assert check2 is v2
assert check2.unit == u.dimensionless_unscaled
# can also replace in last position if no scaling is needed
v3 = v_copy.to(u.dimensionless_unscaled)
check3 = v3
np.modf(v3, v3, tmp)
assert check3 is v3
assert check3.unit == u.dimensionless_unscaled
# in np<1.13, without __array_ufunc__, one cannot replace input with
# first output when scaling
v4 = v_copy.copy()
if NUMPY_LT_1_13:
with pytest.raises(TypeError):
np.modf(v4, v4, tmp)
else:
check4 = v4
np.modf(v4, v4, tmp)
assert check4 is v4
assert check4.unit == u.dimensionless_unscaled
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_two_argument_ufunc_inplace_1(self, value):
s = value * u.cycle
check = s
s /= 2.
assert check is s
assert np.all(check.value == value / 2.)
s /= u.s
assert check is s
assert check.unit == u.cycle / u.s
s *= 2. * u.s
assert check is s
assert np.all(check == value * u.cycle)
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_two_argument_ufunc_inplace_2(self, value):
s = value * u.cycle
check = s
np.arctan2(s, s, out=s)
assert check is s
assert check.unit == u.radian
with pytest.raises(u.UnitsError):
s += 1. * u.m
assert check is s
assert check.unit == u.radian
np.arctan2(1. * u.deg, s, out=s)
assert check is s
assert check.unit == u.radian
np.add(1. * u.deg, s, out=s)
assert check is s
assert check.unit == u.deg
np.multiply(2. / u.s, s, out=s)
assert check is s
assert check.unit == u.deg / u.s
def test_two_argument_ufunc_inplace_3(self):
s = np.array([1., 2., 3.]) * u.dimensionless_unscaled
np.add(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s)
assert np.all(s.value == np.array([3., 6., 9.]))
assert s.unit is u.dimensionless_unscaled
np.arctan2(np.array([1., 2., 3.]), np.array([1., 2., 3.]) * 2., out=s)
assert_allclose(s.value, np.arctan2(1., 2.))
assert s.unit is u.radian
@pytest.mark.skipif(NUMPY_LT_1_13, reason="numpy >=1.13 required.")
@pytest.mark.parametrize(('value'), [1., np.arange(10.)])
def test_two_argument_two_output_ufunc_inplace(self, value):
v = value * u.m
divisor = 70.*u.cm
v1 = v.copy()
tmp = v.copy()
check = np.divmod(v1, divisor, out=(tmp, v1))
assert check[0] is tmp and check[1] is v1
assert tmp.unit == u.dimensionless_unscaled
assert v1.unit == v.unit
v2 = v.copy()
check2 = np.divmod(v2, divisor, out=(v2, tmp))
assert check2[0] is v2 and check2[1] is tmp
assert v2.unit == u.dimensionless_unscaled
assert tmp.unit == v.unit
v3a = v.copy()
v3b = v.copy()
check3 = np.divmod(v3a, divisor, out=(v3a, v3b))
assert check3[0] is v3a and check3[1] is v3b
assert v3a.unit == u.dimensionless_unscaled
assert v3b.unit == v.unit
def test_ufunc_inplace_non_contiguous_data(self):
# ensure inplace works also for non-contiguous data (closes #1834)
s = np.arange(10.) * u.m
s_copy = s.copy()
s2 = s[::2]
s2 += 1. * u.cm
assert np.all(s[::2] > s_copy[::2])
assert np.all(s[1::2] == s_copy[1::2])
def test_ufunc_inplace_non_standard_dtype(self):
"""Check that inplace operations check properly for casting.
First two tests that check that float32 is kept close #3976.
"""
a1 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32)
a1 *= np.float32(10)
assert a1.unit is u.m
assert a1.dtype == np.float32
a2 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.float32)
a2 += (20.*u.km)
assert a2.unit is u.m
assert a2.dtype == np.float32
# For integer, in-place only works if no conversion is done.
a3 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32)
a3 += u.Quantity(10, u.m, dtype=np.int64)
assert a3.unit is u.m
assert a3.dtype == np.int32
a4 = u.Quantity([1, 2, 3, 4], u.m, dtype=np.int32)
with pytest.raises(TypeError):
a4 += u.Quantity(10, u.mm, dtype=np.int64)
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncAt(object):
"""Test that 'at' method for ufuncs (calculates in-place at given indices)
For Quantities, since calculations are in-place, it makes sense only
if the result is still a quantity, and if the unit does not have to change
"""
def test_one_argument_ufunc_at(self):
q = np.arange(10.) * u.m
i = np.array([1, 2])
qv = q.value.copy()
np.negative.at(q, i)
np.negative.at(qv, i)
assert np.all(q.value == qv)
assert q.unit is u.m
# cannot change from quantity to bool array
with pytest.raises(TypeError):
np.isfinite.at(q, i)
# for selective in-place, cannot change the unit
with pytest.raises(u.UnitsError):
np.square.at(q, i)
# except if the unit does not change (i.e., dimensionless)
d = np.arange(10.) * u.dimensionless_unscaled
dv = d.value.copy()
np.square.at(d, i)
np.square.at(dv, i)
assert np.all(d.value == dv)
assert d.unit is u.dimensionless_unscaled
d = np.arange(10.) * u.dimensionless_unscaled
dv = d.value.copy()
np.log.at(d, i)
np.log.at(dv, i)
assert np.all(d.value == dv)
assert d.unit is u.dimensionless_unscaled
# also for sine it doesn't work, even if given an angle
a = np.arange(10.) * u.radian
with pytest.raises(u.UnitsError):
np.sin.at(a, i)
# except, for consistency, if we have made radian equivalent to
# dimensionless (though hopefully it will never be needed)
av = a.value.copy()
with u.add_enabled_equivalencies(u.dimensionless_angles()):
np.sin.at(a, i)
np.sin.at(av, i)
assert_allclose(a.value, av)
# but we won't do double conversion
ad = np.arange(10.) * u.degree
with pytest.raises(u.UnitsError):
np.sin.at(ad, i)
def test_two_argument_ufunc_at(self):
s = np.arange(10.) * u.m
i = np.array([1, 2])
check = s.value.copy()
np.add.at(s, i, 1.*u.km)
np.add.at(check, i, 1000.)
assert np.all(s.value == check)
assert s.unit is u.m
with pytest.raises(u.UnitsError):
np.add.at(s, i, 1.*u.s)
# also raise UnitsError if unit would have to be changed
with pytest.raises(u.UnitsError):
np.multiply.at(s, i, 1*u.s)
# but be fine if it does not
s = np.arange(10.) * u.m
check = s.value.copy()
np.multiply.at(s, i, 2.*u.dimensionless_unscaled)
np.multiply.at(check, i, 2)
assert np.all(s.value == check)
s = np.arange(10.) * u.m
np.multiply.at(s, i, 2.)
assert np.all(s.value == check)
# of course cannot change class of data either
with pytest.raises(TypeError):
np.greater.at(s, i, 1.*u.km)
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncReduceReduceatAccumulate(object):
"""Test 'reduce', 'reduceat' and 'accumulate' methods for ufuncs
For Quantities, it makes sense only if the unit does not have to change
"""
def test_one_argument_ufunc_reduce_accumulate(self):
# one argument cannot be used
s = np.arange(10.) * u.radian
i = np.array([0, 5, 1, 6])
with pytest.raises(ValueError):
np.sin.reduce(s)
with pytest.raises(ValueError):
np.sin.accumulate(s)
with pytest.raises(ValueError):
np.sin.reduceat(s, i)
def test_two_argument_ufunc_reduce_accumulate(self):
s = np.arange(10.) * u.m
i = np.array([0, 5, 1, 6])
check = s.value.copy()
s_add_reduce = np.add.reduce(s)
check_add_reduce = np.add.reduce(check)
assert s_add_reduce.value == check_add_reduce
assert s_add_reduce.unit is u.m
s_add_accumulate = np.add.accumulate(s)
check_add_accumulate = np.add.accumulate(check)
assert np.all(s_add_accumulate.value == check_add_accumulate)
assert s_add_accumulate.unit is u.m
s_add_reduceat = np.add.reduceat(s, i)
check_add_reduceat = np.add.reduceat(check, i)
assert np.all(s_add_reduceat.value == check_add_reduceat)
assert s_add_reduceat.unit is u.m
# reduce(at) or accumulate on comparisons makes no sense,
# as intermediate result is not even a Quantity
with pytest.raises(TypeError):
np.greater.reduce(s)
with pytest.raises(TypeError):
np.greater.accumulate(s)
with pytest.raises(TypeError):
np.greater.reduceat(s, i)
# raise UnitsError if unit would have to be changed
with pytest.raises(u.UnitsError):
np.multiply.reduce(s)
with pytest.raises(u.UnitsError):
np.multiply.accumulate(s)
with pytest.raises(u.UnitsError):
np.multiply.reduceat(s, i)
# but be fine if it does not
s = np.arange(10.) * u.dimensionless_unscaled
check = s.value.copy()
s_multiply_reduce = np.multiply.reduce(s)
check_multiply_reduce = np.multiply.reduce(check)
assert s_multiply_reduce.value == check_multiply_reduce
assert s_multiply_reduce.unit is u.dimensionless_unscaled
s_multiply_accumulate = np.multiply.accumulate(s)
check_multiply_accumulate = np.multiply.accumulate(check)
assert np.all(s_multiply_accumulate.value == check_multiply_accumulate)
assert s_multiply_accumulate.unit is u.dimensionless_unscaled
s_multiply_reduceat = np.multiply.reduceat(s, i)
check_multiply_reduceat = np.multiply.reduceat(check, i)
assert np.all(s_multiply_reduceat.value == check_multiply_reduceat)
assert s_multiply_reduceat.unit is u.dimensionless_unscaled
@pytest.mark.xfail("NUMPY_LT_1_13")
class TestUfuncOuter(object):
"""Test 'outer' methods for ufuncs
Just a few spot checks, since it uses the same code as the regular
ufunc call
"""
def test_one_argument_ufunc_outer(self):
# one argument cannot be used
s = np.arange(10.) * u.radian
with pytest.raises(ValueError):
np.sin.outer(s)
def test_two_argument_ufunc_outer(self):
s1 = np.arange(10.) * u.m
s2 = np.arange(2.) * u.s
check1 = s1.value
check2 = s2.value
s12_multiply_outer = np.multiply.outer(s1, s2)
check12_multiply_outer = np.multiply.outer(check1, check2)
assert np.all(s12_multiply_outer.value == check12_multiply_outer)
assert s12_multiply_outer.unit == s1.unit * s2.unit
# raise UnitsError if appropriate
with pytest.raises(u.UnitsError):
np.add.outer(s1, s2)
# but be fine if it does not
s3 = np.arange(2.) * s1.unit
check3 = s3.value
s13_add_outer = np.add.outer(s1, s3)
check13_add_outer = np.add.outer(check1, check3)
assert np.all(s13_add_outer.value == check13_add_outer)
assert s13_add_outer.unit is s1.unit
s13_greater_outer = np.greater.outer(s1, s3)
check13_greater_outer = np.greater.outer(check1, check3)
assert type(s13_greater_outer) is np.ndarray
assert np.all(s13_greater_outer == check13_greater_outer)
|
Java
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>messageStream property - TorrentClientManager class - hetimatorrent library - Dart API</title>
<!-- required because all the links are pseudo-absolute -->
<base href="../..">
<link href='https://fonts.googleapis.com/css?family=Source+Code+Pro|Roboto:500,400italic,300,400' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="static-assets/prettify.css">
<link rel="stylesheet" href="static-assets/css/bootstrap.min.css">
<link rel="stylesheet" href="static-assets/styles.css">
<meta name="description" content="API docs for the messageStream property from the TorrentClientManager class, for the Dart programming language.">
<link rel="icon" href="static-assets/favicon.png">
<!-- Do not remove placeholder -->
<!-- Header Placeholder -->
</head>
<body>
<div id="overlay-under-drawer"></div>
<header class="container-fluid" id="title">
<nav class="navbar navbar-fixed-top">
<div class="container">
<button id="sidenav-left-toggle" type="button"> </button>
<ol class="breadcrumbs gt-separated hidden-xs">
<li><a href="index.html">hetimatorrent</a></li>
<li><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></li>
<li><a href="hetimatorrent/TorrentClientManager-class.html">TorrentClientManager</a></li>
<li class="self-crumb">messageStream</li>
</ol>
<div class="self-name">messageStream</div>
</div>
</nav>
<div class="container masthead">
<ol class="breadcrumbs gt-separated visible-xs">
<li><a href="index.html">hetimatorrent</a></li>
<li><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></li>
<li><a href="hetimatorrent/TorrentClientManager-class.html">TorrentClientManager</a></li>
<li class="self-crumb">messageStream</li>
</ol>
<div class="title-description">
<h1 class="title">
<div class="kind">property</div> messageStream
</h1>
<!-- p class="subtitle">
</p -->
</div>
<ul class="subnav">
</ul>
</div>
</header>
<div class="container body">
<div class="col-xs-6 col-sm-3 sidebar sidebar-offcanvas-left">
<h5><a href="index.html">hetimatorrent</a></h5>
<h5><a href="hetimatorrent/hetimatorrent-library.html">hetimatorrent</a></h5>
<h5><a href="hetimatorrent/TorrentClientManager-class.html">TorrentClientManager</a></h5>
<ol>
<li class="section-title"><a href="hetimatorrent/TorrentClientManager-class.html#instance-properties">Properties</a></li>
<li><a href="hetimatorrent/TorrentClientManager/globalIp.html">globalIp</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/globalPort.html">globalPort</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/isStart.html">isStart</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/localIp.html">localIp</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/localPort.html">localPort</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/messageStream.html">messageStream</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/onReceiveEvent.html">onReceiveEvent</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/onReceiveSignal.html">onReceiveSignal</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/rawclients.html">rawclients</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/verbose.html">verbose</a>
</li>
<li class="section-title"><a href="hetimatorrent/TorrentClientManager-class.html#constructors">Constructors</a></li>
<li><a href="hetimatorrent/TorrentClientManager/TorrentClientManager.html">TorrentClientManager</a></li>
<li class="section-title"><a href="hetimatorrent/TorrentClientManager-class.html#methods">Methods</a></li>
<li><a href="hetimatorrent/TorrentClientManager/addTorrentClientWithDelegationToAccept.html">addTorrentClientWithDelegationToAccept</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/getTorrentClientFromInfoHash.html">getTorrentClientFromInfoHash</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/log.html">log</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/start.html">start</a>
</li>
<li><a href="hetimatorrent/TorrentClientManager/stop.html">stop</a>
</li>
</ol>
</div><!--/.sidebar-offcanvas-->
<div class="col-xs-12 col-sm-9 col-md-6 main-content">
<section class="multi-line-signature">
<span class="returntype">StreamController<<a href="hetimatorrent.torrent.client.message/TorrentClientMessage-class.html">TorrentClientMessage</a>></span>
<span class="name ">messageStream</span>
<div class="readable-writable">
read / write
</div>
</section>
<section class="desc markdown">
<p class="no-docs">Not documented.</p>
</section>
</div> <!-- /.main-content -->
</div> <!-- container -->
<footer>
<div class="container-fluid">
<div class="container">
<p class="text-center">
<span class="no-break">
hetimatorrent 0.0.1 api docs
</span>
•
<span class="copyright no-break">
<a href="https://www.dartlang.org">
<img src="static-assets/favicon.png" alt="Dart" title="Dart"width="16" height="16">
</a>
</span>
•
<span class="copyright no-break">
<a href="http://creativecommons.org/licenses/by-sa/4.0/">cc license</a>
</span>
</p>
</div>
</div>
</footer>
<script src="static-assets/prettify.js"></script>
<script src="static-assets/script.js"></script>
<!-- Do not remove placeholder -->
<!-- Footer Placeholder -->
</body>
</html>
|
Java
|
// Copyright 2019 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "third_party/blink/public/common/page/content_to_visible_time_reporter.h"
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/debug/dump_without_crashing.h"
#include "base/feature_list.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/histogram_macros.h"
#include "base/strings/strcat.h"
#include "base/trace_event/trace_event.h"
#include "third_party/blink/public/common/features.h"
#include "third_party/blink/public/mojom/widget/record_content_to_visible_time_request.mojom.h"
#include "ui/gfx/presentation_feedback.h"
namespace blink {
namespace {
// Used to generate unique "TabSwitching::Latency" event ids. Note: The address
// of ContentToVisibleTimeReporter can't be used as an id because a single
// ContentToVisibleTimeReporter can generate multiple overlapping events.
int g_num_trace_events_in_process = 0;
const char* GetHistogramSuffix(
bool has_saved_frames,
const mojom::RecordContentToVisibleTimeRequest& start_state) {
if (has_saved_frames)
return "WithSavedFrames";
if (start_state.destination_is_loaded) {
return "NoSavedFrames_Loaded";
} else {
return "NoSavedFrames_NotLoaded";
}
}
void ReportUnOccludedMetric(const base::TimeTicks requested_time,
const gfx::PresentationFeedback& feedback) {
const base::TimeDelta delta = feedback.timestamp - requested_time;
UMA_HISTOGRAM_TIMES("Aura.WebContentsWindowUnOccludedTime", delta);
}
void RecordBackForwardCacheRestoreMetric(
const base::TimeTicks requested_time,
const gfx::PresentationFeedback& feedback) {
const base::TimeDelta delta = feedback.timestamp - requested_time;
// Histogram to record the content to visible duration after restoring a page
// from back-forward cache. Here min, max bucket size are same as the
// "PageLoad.PaintTiming.NavigationToFirstContentfulPaint" metric.
base::UmaHistogramCustomTimes(
"BackForwardCache.Restore.NavigationToFirstPaint", delta,
base::Milliseconds(10), base::Minutes(10), 100);
}
} // namespace
void UpdateRecordContentToVisibleTimeRequest(
mojom::RecordContentToVisibleTimeRequest const& from,
mojom::RecordContentToVisibleTimeRequest& to) {
to.event_start_time = std::min(to.event_start_time, from.event_start_time);
to.destination_is_loaded |= from.destination_is_loaded;
to.show_reason_tab_switching |= from.show_reason_tab_switching;
to.show_reason_unoccluded |= from.show_reason_unoccluded;
to.show_reason_bfcache_restore |= from.show_reason_bfcache_restore;
}
ContentToVisibleTimeReporter::ContentToVisibleTimeReporter()
: is_tab_switch_metric2_feature_enabled_(
base::FeatureList::IsEnabled(blink::features::kTabSwitchMetrics2)) {}
ContentToVisibleTimeReporter::~ContentToVisibleTimeReporter() = default;
base::OnceCallback<void(const gfx::PresentationFeedback&)>
ContentToVisibleTimeReporter::TabWasShown(
bool has_saved_frames,
mojom::RecordContentToVisibleTimeRequestPtr start_state,
base::TimeTicks widget_visibility_request_timestamp) {
DCHECK(!start_state->event_start_time.is_null());
DCHECK(!widget_visibility_request_timestamp.is_null());
DCHECK(!tab_switch_start_state_);
DCHECK(widget_visibility_request_timestamp_.is_null());
// Invalidate previously issued callbacks, to avoid accessing a null
// |tab_switch_start_state_|.
//
// TODO(https://crbug.com/1121339): Make sure that TabWasShown() is never
// called twice without a call to TabWasHidden() in-between, and remove this
// mitigation.
weak_ptr_factory_.InvalidateWeakPtrs();
has_saved_frames_ = has_saved_frames;
tab_switch_start_state_ = std::move(start_state);
widget_visibility_request_timestamp_ = widget_visibility_request_timestamp;
// |tab_switch_start_state_| is only reset by RecordHistogramsAndTraceEvents
// once the metrics have been emitted.
return base::BindOnce(
&ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents,
weak_ptr_factory_.GetWeakPtr(), false /* is_incomplete */,
tab_switch_start_state_->show_reason_tab_switching,
tab_switch_start_state_->show_reason_unoccluded,
tab_switch_start_state_->show_reason_bfcache_restore);
}
base::OnceCallback<void(const gfx::PresentationFeedback&)>
ContentToVisibleTimeReporter::TabWasShown(
bool has_saved_frames,
base::TimeTicks event_start_time,
bool destination_is_loaded,
bool show_reason_tab_switching,
bool show_reason_unoccluded,
bool show_reason_bfcache_restore,
base::TimeTicks widget_visibility_request_timestamp) {
return TabWasShown(
has_saved_frames,
mojom::RecordContentToVisibleTimeRequest::New(
event_start_time, destination_is_loaded, show_reason_tab_switching,
show_reason_unoccluded, show_reason_bfcache_restore),
widget_visibility_request_timestamp);
}
void ContentToVisibleTimeReporter::TabWasHidden() {
if (tab_switch_start_state_) {
RecordHistogramsAndTraceEvents(true /* is_incomplete */,
true /* show_reason_tab_switching */,
false /* show_reason_unoccluded */,
false /* show_reason_bfcache_restore */,
gfx::PresentationFeedback::Failure());
weak_ptr_factory_.InvalidateWeakPtrs();
}
}
void ContentToVisibleTimeReporter::RecordHistogramsAndTraceEvents(
bool is_incomplete,
bool show_reason_tab_switching,
bool show_reason_unoccluded,
bool show_reason_bfcache_restore,
const gfx::PresentationFeedback& feedback) {
DCHECK(tab_switch_start_state_);
DCHECK(!widget_visibility_request_timestamp_.is_null());
// If the DCHECK fail, make sure RenderWidgetHostImpl::WasShown was triggered
// for recording the event.
DCHECK(show_reason_bfcache_restore || show_reason_unoccluded ||
show_reason_tab_switching);
if (show_reason_bfcache_restore) {
RecordBackForwardCacheRestoreMetric(
tab_switch_start_state_->event_start_time, feedback);
}
if (show_reason_unoccluded) {
ReportUnOccludedMetric(tab_switch_start_state_->event_start_time, feedback);
}
if (!show_reason_tab_switching)
return;
// Tab switching has occurred.
auto tab_switch_result = TabSwitchResult::kSuccess;
if (is_incomplete)
tab_switch_result = TabSwitchResult::kIncomplete;
else if (feedback.flags & gfx::PresentationFeedback::kFailure)
tab_switch_result = TabSwitchResult::kPresentationFailure;
const auto tab_switch_duration =
feedback.timestamp - tab_switch_start_state_->event_start_time;
// Record trace events.
TRACE_EVENT_NESTABLE_ASYNC_BEGIN_WITH_TIMESTAMP0(
"latency", "TabSwitching::Latency",
TRACE_ID_LOCAL(g_num_trace_events_in_process),
tab_switch_start_state_->event_start_time);
TRACE_EVENT_NESTABLE_ASYNC_END_WITH_TIMESTAMP2(
"latency", "TabSwitching::Latency",
TRACE_ID_LOCAL(g_num_trace_events_in_process), feedback.timestamp,
"result", tab_switch_result, "latency",
tab_switch_duration.InMillisecondsF());
++g_num_trace_events_in_process;
const char* suffix =
GetHistogramSuffix(has_saved_frames_, *tab_switch_start_state_);
// Record result histogram.
if (is_tab_switch_metric2_feature_enabled_) {
base::UmaHistogramEnumeration(
base::StrCat({"Browser.Tabs.TabSwitchResult2.", suffix}),
tab_switch_result);
} else {
base::UmaHistogramEnumeration(
base::StrCat({"Browser.Tabs.TabSwitchResult.", suffix}),
tab_switch_result);
}
// Record latency histogram.
switch (tab_switch_result) {
case TabSwitchResult::kSuccess: {
if (is_tab_switch_metric2_feature_enabled_) {
base::UmaHistogramTimes(
base::StrCat({"Browser.Tabs.TotalSwitchDuration2.", suffix}),
tab_switch_duration);
} else {
base::UmaHistogramTimes(
base::StrCat({"Browser.Tabs.TotalSwitchDuration.", suffix}),
tab_switch_duration);
}
break;
}
case TabSwitchResult::kIncomplete: {
if (is_tab_switch_metric2_feature_enabled_) {
base::UmaHistogramTimes(
base::StrCat(
{"Browser.Tabs.TotalIncompleteSwitchDuration2.", suffix}),
tab_switch_duration);
} else {
base::UmaHistogramTimes(
base::StrCat(
{"Browser.Tabs.TotalIncompleteSwitchDuration.", suffix}),
tab_switch_duration);
}
break;
}
case TabSwitchResult::kPresentationFailure: {
break;
}
}
// Record legacy latency histogram.
UMA_HISTOGRAM_TIMES(
"MPArch.RWH_TabSwitchPaintDuration",
feedback.timestamp - widget_visibility_request_timestamp_);
// Reset tab switch information.
has_saved_frames_ = false;
tab_switch_start_state_.reset();
widget_visibility_request_timestamp_ = base::TimeTicks();
}
} // namespace blink
|
Java
|
#!/usr/bin/env python
"""
# Software License Agreement (BSD License)
#
# Copyright (c) 2012, University of California, Berkeley
# All rights reserved.
# Authors: Cameron Lee (cameronlee@berkeley.edu) and Dmitry Berenson (
berenson@eecs.berkeley.edu)
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# * Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
# * 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.
# * Neither the name of University of California, Berkeley 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 OWNER 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.
"""
"""
This node advertises an action which is used by the main lightning node
(see run_lightning.py) to run the Retrieve and Repair portion of LightningROS.
This node relies on a planner_stoppable type node to repair the paths, the
PathTools library to retrieve paths from the library (this is not a separate
node; just a python library that it calls), and the PathTools python library
which calls the collision_checker service and advertises a topic for displaying
stuff in RViz.
"""
import roslib
import rospy
import actionlib
import threading
from tools.PathTools import PlanTrajectoryWrapper, InvalidSectionWrapper, DrawPointsWrapper
from pathlib.PathLibrary import *
from lightning.msg import Float64Array, RRAction, RRResult
from lightning.msg import StopPlanning, RRStats
from lightning.srv import ManagePathLibrary, ManagePathLibraryResponse
import sys
import pickle
import time
# Name of this node.
RR_NODE_NAME = "rr_node"
# Name to use for stopping the repair planner. Published from this node.
STOP_PLANNER_NAME = "stop_rr_planning"
# Topic to subscribe to for stopping the whole node in the middle of processing.
STOP_RR_NAME = "stop_all_rr"
# Name of library managing service run from this node.
MANAGE_LIBRARY = "manage_path_library"
STATE_RETRIEVE, STATE_REPAIR, STATE_RETURN_PATH, STATE_FINISHED, STATE_FINISHED = (0, 1, 2, 3, 4)
class RRNode:
def __init__(self):
# Retrieve ROS parameters and configuration and cosntruct various objects.
self.robot_name = rospy.get_param("robot_name")
self.planner_config_name = rospy.get_param("planner_config_name")
self.current_joint_names = []
self.current_group_name = ""
self.plan_trajectory_wrapper = PlanTrajectoryWrapper("rr", int(rospy.get_param("~num_rr_planners")))
self.invalid_section_wrapper = InvalidSectionWrapper()
self.path_library = PathLibrary(rospy.get_param("~path_library_dir"), rospy.get_param("step_size"), node_size=int(rospy.get_param("~path_library_path_node_size")), sg_node_size=int(rospy.get_param("~path_library_sg_node_size")), dtw_dist=float(rospy.get_param("~dtw_distance")))
self.num_paths_checked = int(rospy.get_param("~num_paths_to_collision_check"))
self.stop_lock = threading.Lock()
self.stop = True
self.rr_server = actionlib.SimpleActionServer(RR_NODE_NAME, RRAction, execute_cb=self._retrieve_repair, auto_start=False)
self.rr_server.start()
self.stop_rr_subscriber = rospy.Subscriber(STOP_RR_NAME, StopPlanning, self._stop_rr_planner)
self.stop_rr_planner_publisher = rospy.Publisher(STOP_PLANNER_NAME, StopPlanning, queue_size=10)
self.manage_library_service = rospy.Service(MANAGE_LIBRARY, ManagePathLibrary, self._do_manage_action)
self.stats_pub = rospy.Publisher("rr_stats", RRStats, queue_size=10)
self.repaired_sections_lock = threading.Lock()
self.repaired_sections = []
self.working_lock = threading.Lock() #to ensure that node is not doing RR and doing a library management action at the same time
#if draw_points is True, then display points in rviz
self.draw_points = rospy.get_param("draw_points")
if self.draw_points:
self.draw_points_wrapper = DrawPointsWrapper()
def _set_repaired_section(self, index, section):
"""
After you have done the path planning to repair a section, store
the repaired path section.
Args:
index (int): the index corresponding to the section being repaired.
section (path, list of list of float): A path to store.
"""
self.repaired_sections_lock.acquire()
self.repaired_sections[index] = section
self.repaired_sections_lock.release()
def _call_planner(self, start, goal, planning_time):
"""
Calls a standard planner to plan between two points with an allowed
planning time.
Args:
start (list of float): A joint configuration corresponding to the
start position of the path.
goal (list of float): The jount configuration corresponding to the
goal position for the path.
Returns:
path: A list of joint configurations corresponding to the planned
path.
"""
ret = None
planner_number = self.plan_trajectory_wrapper.acquire_planner()
if not self._need_to_stop():
ret = self.plan_trajectory_wrapper.plan_trajectory(start, goal, planner_number, self.current_joint_names, self.current_group_name, planning_time, self.planner_config_name)
self.plan_trajectory_wrapper.release_planner(planner_number)
return ret
def _repair_thread(self, index, start, goal, start_index, goal_index, planning_time):
"""
Handles repairing a portion of the path.
All that this function really does is to plan from scratch between
the start and goal configurations and then store the planned path
in the appropriate places and draws either the repaired path or, if
the repair fails, the start and goal.
Args:
index (int): The index to pass to _set_repaired_section(),
corresponding to which of the invalid sections of the path we are
repairing.
start (list of float): The start joint configuration to use.
goal (list of float): The goal joint configuration to use.
start_index (int): The index in the overall path corresponding to
start. Only used for debugging info.
goal_index (int): The index in the overall path corresponding to
goal. Only used for debugging info.
planning_time (float): Maximum allowed time to spend planning, in
seconds.
"""
repaired_path = self._call_planner(start, goal, planning_time)
if self.draw_points:
if repaired_path is not None and len(repaired_path) > 0:
rospy.loginfo("RR action server: got repaired section with start = %s, goal = %s" % (repaired_path[0], repaired_path[-1]))
self.draw_points_wrapper.draw_points(repaired_path, self.current_group_name, "repaired"+str(start_index)+"_"+str(goal_index), DrawPointsWrapper.ANGLES, DrawPointsWrapper.GREENBLUE, 1.0, 0.01)
else:
if self.draw_points:
rospy.loginfo("RR action server: path repair for section (%i, %i) failed, start = %s, goal = %s" % (start_index, goal_index, start, goal))
self.draw_points_wrapper.draw_points([start, goal], self.current_group_name, "failed_repair"+str(start_index)+"_"+str(goal_index), DrawPointsWrapper.ANGLES, DrawPointsWrapper.GREENBLUE, 1.0)
if self._need_to_stop():
self._set_repaired_section(index, None)
else:
self._set_repaired_section(index, repaired_path)
def _need_to_stop(self):
self.stop_lock.acquire();
ret = self.stop;
self.stop_lock.release();
return ret;
def _set_stop_value(self, val):
self.stop_lock.acquire();
self.stop = val;
self.stop_lock.release();
def do_retrieved_path_drawing(self, projected, retrieved, invalid):
"""
Draws the points from the various paths involved in the planning
in different colors in different namespaces.
All of the arguments are lists of joint configurations, where each
joint configuration is a list of joint angles.
The only distinction between the different arguments being passed in
are which color the points in question are being drawn in.
Uses the DrawPointsWrapper to draw the points.
Args:
projected (list of list of float): List of points to draw as
projected between the library path and the actual start/goal
position. Will be drawn in blue.
retrieved (list of list of float): The path retrieved straight
from the path library. Will be drawn in white.
invalid (list of list of float): List of points which were invalid.
Will be drawn in red.
"""
if len(projected) > 0:
if self.draw_points:
self.draw_points_wrapper.draw_points(retrieved, self.current_group_name, "retrieved", DrawPointsWrapper.ANGLES, DrawPointsWrapper.WHITE, 0.1)
projectionDisplay = projected[:projected.index(retrieved[0])]+projected[projected.index(retrieved[-1])+1:]
self.draw_points_wrapper.draw_points(projectionDisplay, self.current_group_name, "projection", DrawPointsWrapper.ANGLES, DrawPointsWrapper.BLUE, 0.2)
invalidDisplay = []
for invSec in invalid:
invalidDisplay += projected[invSec[0]+1:invSec[-1]]
self.draw_points_wrapper.draw_points(invalidDisplay, self.current_group_name, "invalid", DrawPointsWrapper.ANGLES, DrawPointsWrapper.RED, 0.2)
def _retrieve_repair(self, action_goal):
"""
Callback which performs the full Retrieve and Repair for the path.
"""
self.working_lock.acquire()
self.start_time = time.time()
self.stats_msg = RRStats()
self._set_stop_value(False)
if self.draw_points:
self.draw_points_wrapper.clear_points()
rospy.loginfo("RR action server: RR got an action goal")
s, g = action_goal.start, action_goal.goal
res = RRResult()
res.status.status = res.status.FAILURE
self.current_joint_names = action_goal.joint_names
self.current_group_name = action_goal.group_name
projected, retrieved, invalid = [], [], []
repair_state = STATE_RETRIEVE
self.stats_msg.init_time = time.time() - self.start_time
# Go through the retrieve, repair, and return stages of the planning.
# The while loop should only ever go through 3 iterations, one for each
# stage.
while not self._need_to_stop() and repair_state != STATE_FINISHED:
if repair_state == STATE_RETRIEVE:
start_retrieve = time.time()
projected, retrieved, invalid = self.path_library.retrieve_path(s, g, self.num_paths_checked, self.robot_name, self.current_group_name, self.current_joint_names)
self.stats_msg.retrieve_time.append(time.time() - start_retrieve)
if len(projected) == 0:
rospy.loginfo("RR action server: got an empty path for retrieve state")
repair_state = STATE_FINISHED
else:
start_draw = time.time()
if self.draw_points:
self.do_retrieved_path_drawing(projected, retrieved, invalid)
self.stats_msg.draw_time.append(time.time() - start_draw)
repair_state = STATE_REPAIR
elif repair_state == STATE_REPAIR:
start_repair = time.time()
repaired = self._path_repair(projected, action_goal.allowed_planning_time.to_sec(), invalid_sections=invalid)
self.stats_msg.repair_time.append(time.time() - start_repair)
if repaired is None:
rospy.loginfo("RR action server: path repair didn't finish")
repair_state = STATE_FINISHED
else:
repair_state = STATE_RETURN_PATH
elif repair_state == STATE_RETURN_PATH:
start_return = time.time()
res.status.status = res.status.SUCCESS
res.retrieved_path = [Float64Array(p) for p in retrieved]
res.repaired_path = [Float64Array(p) for p in repaired]
rospy.loginfo("RR action server: returning a path")
repair_state = STATE_FINISHED
self.stats_msg.return_time = time.time() - start_return
if repair_state == STATE_RETRIEVE:
rospy.loginfo("RR action server: stopped before it retrieved a path")
elif repair_state == STATE_REPAIR:
rospy.loginfo("RR action server: stopped before it could repair a retrieved path")
elif repair_state == STATE_RETURN_PATH:
rospy.loginfo("RR action server: stopped before it could return a repaired path")
self.rr_server.set_succeeded(res)
self.stats_msg.total_time = time.time() - self.start_time
self.stats_pub.publish(self.stats_msg)
self.working_lock.release()
def _path_repair(self, original_path, planning_time, invalid_sections=None, use_parallel_repairing=True):
"""
Goes through each invalid section in a path and calls a planner to
repair it, with the potential for multi-threading. Returns the
repaired path.
Args:
original_path (path): The original path which needs repairing.
planning_time (float): The maximum allowed planning time for
each repair, in seconds.
invalid_sections (list of pairs of indicies): The pairs of indicies
describing the invalid sections. If None, then the invalid
sections will be computed by this function.
use_parallel_repairing (bool): Whether or not to use multi-threading.
Returns:
path: The repaired path.
"""
zeros_tuple = tuple([0 for i in xrange(len(self.current_joint_names))])
rospy.loginfo("RR action server: got path with %d points" % len(original_path))
if invalid_sections is None:
invalid_sections = self.invalid_section_wrapper.getInvalidSectionsForPath(original_path, self.current_group_name)
rospy.loginfo("RR action server: invalid sections: %s" % (str(invalid_sections)))
if len(invalid_sections) > 0:
if invalid_sections[0][0] == -1:
rospy.loginfo("RR action server: Start is not a valid state...nothing can be done")
return None
if invalid_sections[-1][1] == len(original_path):
rospy.loginfo("RR action server: Goal is not a valid state...nothing can be done")
return None
if use_parallel_repairing:
#multi-threaded repairing
self.repaired_sections = [None for i in xrange(len(invalid_sections))]
#each thread replans an invalid section
threadList = []
for i, sec in enumerate(invalid_sections):
th = threading.Thread(target=self._repair_thread, args=(i, original_path[sec[0]], original_path[sec[-1]], sec[0], sec[-1], planning_time))
threadList.append(th)
th.start()
for th in threadList:
th.join()
#once all threads return, then the repaired sections can be combined
for item in self.repaired_sections:
if item is None:
rospy.loginfo("RR action server: RR node was stopped during repair or repair failed")
return None
#replace invalid sections with replanned sections
new_path = original_path[0:invalid_sections[0][0]]
for i in xrange(len(invalid_sections)):
new_path += self.repaired_sections[i]
if i+1 < len(invalid_sections):
new_path += original_path[invalid_sections[i][1]+1:invalid_sections[i+1][0]]
new_path += original_path[invalid_sections[-1][1]+1:]
self.repaired_sections = [] #reset repaired_sections
else:
#single-threaded repairing
rospy.loginfo("RR action server: Got invalid sections: %s" % str(invalid_sections))
new_path = original_path[0:invalid_sections[0][0]]
for i in xrange(len(invalid_sections)):
if not self._need_to_stop():
#start_invalid and end_invalid must correspond to valid states when passed to the planner
start_invalid, end_invalid = invalid_sections[i]
rospy.loginfo("RR action server: Requesting path to replace from %d to %d" % (start_invalid, end_invalid))
repairedSection = self._call_planner(original_path[start_invalid], original_path[end_invalid])
if repairedSection is None:
rospy.loginfo("RR action server: RR section repair was stopped or failed")
return None
rospy.loginfo("RR action server: Planner returned a trajectory of %d points for %d to %d" % (len(repairedSection), start_invalid, end_invalid))
new_path += repairedSection
if i+1 < len(invalid_sections):
new_path += original_path[end_invalid+1:invalid_sections[i+1][0]]
else:
rospy.loginfo("RR action server: RR was stopped while it was repairing the retrieved path")
return None
new_path += original_path[invalid_sections[-1][1]+1:]
rospy.loginfo("RR action server: Trajectory after replan has %d points" % len(new_path))
else:
new_path = original_path
rospy.loginfo("RR action server: new trajectory has %i points" % (len(new_path)))
return new_path
def _stop_rr_planner(self, msg):
self._set_stop_value(True)
rospy.loginfo("RR action server: RR node got a stop message")
self.stop_rr_planner_publisher.publish(msg)
def _do_manage_action(self, request):
"""
Processes a ManagePathLibraryRequest as part of the ManagePathLibrary
service. Basically, either stores a path in the library or deletes it.
"""
response = ManagePathLibraryResponse()
response.result = response.FAILURE
if request.robot_name == "" or len(request.joint_names) == 0:
rospy.logerr("RR action server: robot name or joint names were not provided")
return response
self.working_lock.acquire()
if request.action == request.ACTION_STORE:
rospy.loginfo("RR action server: got a path to store in path library")
if len(request.path_to_store) > 0:
new_path = [p.positions for p in request.path_to_store]
if len(request.retrieved_path) == 0:
#PFS won so just store the path
store_path_result = self.path_library.store_path(new_path, request.robot_name, request.joint_names)
else:
store_path_result = self.path_library.store_path(new_path, request.robot_name, request.joint_names, [p.positions for p in request.retrieved_path])
response.result = response.SUCCESS
response.path_stored, response.num_library_paths = store_path_result
else:
response.message = "Path to store had no points"
elif request.action == request.ACTION_DELETE_PATH:
rospy.loginfo("RR action server: got a request to delete path %i in the path library" % (request.delete_id))
if self.path_library.delete_path_by_id(request.delete_id, request.robot_name, request.joint_names):
response.result = response.SUCCESS
else:
response.message = "No path in the library had id %i" % (request.delete_id)
elif request.action == request.ACTION_DELETE_LIBRARY:
rospy.loginfo("RR action server: got a request to delete library corresponding to robot %s and joints %s" % (request.robot_name, request.joint_names))
if self.path_library.delete_library(request.robot_name, request.joint_names):
response.result = response.SUCCESS
else:
response.message = "No library corresponding to robot %s and joint names %s exists"
else:
rospy.logerr("RR action server: manage path library request did not have a valid action set")
self.working_lock.release()
return response
if __name__ == "__main__":
try:
rospy.init_node("rr_node")
RRNode()
rospy.loginfo("Retrieve-repair: ready")
rospy.spin()
except rospy.ROSInterruptException:
pass
|
Java
|
package de.uni.freiburg.iig.telematik.sewol.accesscontrol.rbac.lattice.graphic;
import org.apache.commons.collections15.Factory;
import edu.uci.ics.jung.graph.Graph;
import edu.uci.ics.jung.graph.SparseMultigraph;
public class RoleGraphViewer {
Graph<Integer, String> g;
int nodeCount, edgeCount;
Factory<Integer> vertexFactory;
Factory<String> edgeFactory;
/** Creates a new instance of SimpleGraphView */
public RoleGraphViewer() {
// Graph<V, E> where V is the type of the vertices and E is the type of
// the edges
g = new SparseMultigraph<Integer, String>();
nodeCount = 0;
edgeCount = 0;
vertexFactory = new Factory<Integer>() { // My vertex factory
public Integer create() {
return nodeCount++;
}
};
edgeFactory = new Factory<String>() { // My edge factory
public String create() {
return "E" + edgeCount++;
}
};
}
}
|
Java
|
/**
* @author
*/
imports("Controls.Composite.Carousel");
using("System.Fx.Marquee");
var Carousel = Control.extend({
onChange: function (e) {
var ul = this.find('.x-carousel-header'), t;
if (t = ul.first(e.from))
t.removeClass('x-carousel-header-selected');
if(t = ul.first(e.to))
t.addClass('x-carousel-header-selected');
},
init: function (options) {
var me = this;
me.marquee = new Marquee(me, options.direction, options.loop, options.deferUpdate);
if (options.duration != null)
me.marquee.duration = options.duration;
if (options.delay != null)
me.marquee.delay = options.delay;
me.marquee.on('changing', me.onChange, me);
me.query('.x-carousel-header > li').setWidth(me.getWidth() / me.marquee.length).on(options.event || 'mouseover', function (e) {
me.marquee.moveTo(this.index());
});
me.onChange({to: 0});
me.marquee.start();
}
}).defineMethods("marquee", "moveTo moveBy start stop");
|
Java
|
#include <lib.h>
#include <string.h>
/* lsearch(3) and lfind(3)
*
* Author: Terrence W. Holm Sep. 1988
*/
#include <stddef.h>
char *lsearch(key, base, count, width, keycmp)
char *key;
char *base;
unsigned *count;
unsigned width;
_PROTOTYPE( int (*keycmp), (const void *, const void *));
{
char *entry;
char *last = base + *count * width;
for (entry = base; entry < last; entry += width)
if (keycmp(key, entry) == 0) return(entry);
bcopy(key, last, width);
*count += 1;
return(last);
}
char *lfind(key, base, count, width, keycmp)
char *key;
char *base;
unsigned *count;
unsigned width;
_PROTOTYPE( int (*keycmp), (const void *, const void *));
{
char *entry;
char *last = base + *count * width;
for (entry = base; entry < last; entry += width)
if (keycmp(key, entry) == 0) return(entry);
return((char *)NULL);
}
|
Java
|
#!/usr/bin/env python
from django.core.management import setup_environ
import settings
setup_environ(settings)
import socket
from trivia.models import *
irc = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
irc.connect((settings.IRC_SERVER, settings.IRC_PORT))
def send(msg):
irc.send(msg + "\r\n")
print "{SENT} " + msg
return
def msg(user, msg):
send("PRIVMSG " + user + " :" + msg)
return
def processline(line):
parts = line.split(' :',1)
args = parts[0].split(' ')
if (len(parts) > 1):
args.append(parts[1])
if args[0] == "PING":
send("PONG :" + args[1])
return
try:
if args[3] == "!questions":
questions = str(Question.objects.all())
msg(args[2], questions)
return
except IndexError:
return
# When we're done, remember to return.
return
send("USER " + (settings.IRC_NICKNAME + " ")*4)
send("NICK " + settings.IRC_NICKNAME)
for channel in settings.IRC_CHANNELS:
send("JOIN " + channel)
while True:
# EXIST
line = irc.recv(1024).rstrip()
if "\r\n" in line:
linesep = line.split()
for l in linesep:
processline(l)
continue
processline(line)
|
Java
|
/// <reference path="../../src/CaseModel.ts" />
/// <reference path="../../src/CaseViewer.ts" />
/// <reference path="../../src/PlugInManager.ts" />
class AnnotationPlugIn extends AssureIt.PlugInSet {
constructor(public plugInManager: AssureIt.PlugInManager) {
super(plugInManager);
this.HTMLRenderPlugIn = new AnnotationHTMLRenderPlugIn(plugInManager);
}
}
class AnnotationHTMLRenderPlugIn extends AssureIt.HTMLRenderPlugIn {
IsEnabled(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel) : boolean {
return true;
}
Delegate(caseViewer: AssureIt.CaseViewer, caseModel: AssureIt.NodeModel, element: JQuery) : boolean {
if(caseModel.Annotations.length == 0) return;
var text : string = "";
var p : {top: number; left: number} = element.position();
for(var i : number = 0; i < caseModel.Annotations.length; i++) {
text += "@" + caseModel.Annotations[i].Name + "<br>";
}
$('<div class="anno">' +
'<p>' + text + '</p>' +
'</div>')
.css({position: 'absolute', 'font-size': 25, color: 'gray', top: p.top - 20, left: p.left + 80}).appendTo(element);
return true;
}
}
|
Java
|
import React from "react";
import { expect } from "chai";
import { mount } from "enzyme";
import { Provider } from "react-redux";
import Editor from "../../../src/notebook/providers/editor";
import { dummyStore } from "../../utils";
import {
UPDATE_CELL_SOURCE,
FOCUS_CELL_EDITOR
} from "../../../src/notebook/constants";
describe("EditorProvider", () => {
const store = dummyStore();
const setup = (id, cellFocused = true) =>
mount(
<Provider store={store}>
<Editor id={id} cellFocused={cellFocused} />
</Provider>
);
it("can be constructed", () => {
const component = setup("test");
expect(component).to.not.be.null;
});
it("onChange updates cell source", () =>
new Promise(resolve => {
const dispatch = action => {
expect(action.id).to.equal("test");
expect(action.source).to.equal("i love nteract");
expect(action.type).to.equal(UPDATE_CELL_SOURCE);
resolve();
};
store.dispatch = dispatch;
const wrapper = setup("test");
const onChange = wrapper
.findWhere(n => n.prop("onChange") !== undefined)
.first()
.prop("onChange");
onChange("i love nteract");
}));
it("onFocusChange can update editor focus", () =>
new Promise(resolve => {
const dispatch = action => {
expect(action.id).to.equal("test");
expect(action.type).to.equal(FOCUS_CELL_EDITOR);
resolve();
};
store.dispatch = dispatch;
const wrapper = setup("test");
const onFocusChange = wrapper
.findWhere(n => n.prop("onFocusChange") !== undefined)
.first()
.prop("onFocusChange");
onFocusChange(true);
}));
});
|
Java
|
/*
* Copyright (c) 2014, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in
* the LICENSE file in the root directory of this source tree. An
* additional grant of patent rights can be found in the PATENTS file
* in the same directory.
*
*/
#include <errno.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/wait.h>
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdint.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <sys/types.h>
#include <assert.h>
#include <limits.h>
#include "child.h"
#include "net.h"
extern char** environ;
struct internal_child_info {
int flags;
const struct child_start_info* csi;
int* childfd;
int pty_slave;
};
__attribute__((noreturn))
static void
child_child_1(void* arg)
{
struct internal_child_info* ci = arg;
/* Resets O_CLOEXEC */
for (int i = 0; i < 3; ++i)
xdup3nc(ci->childfd[i], i, 0);
if (ci->csi->child_chdir && chdir(ci->csi->child_chdir) == -1)
die_errno("chdir");
if (ci->flags & CHILD_SETSID)
if (setsid() == (pid_t) -1)
die_errno("setsid");
if (ci->pty_slave != -1) {
if (ioctl(ci->pty_slave, TIOCSCTTY, 0) == -1)
die_errno("TIOCSCTTY");
if (tcsetpgrp(ci->pty_slave, getpid()) == -1)
die_errno("tcsetpgrp");
}
for (int i = 0; i < NSIG; ++i)
signal(i, SIG_DFL);
sigset_t no_signals;
VERIFY(sigemptyset(&no_signals) == 0);
VERIFY(sigprocmask(SIG_SETMASK, &no_signals, NULL) == 0);
if (ci->csi->pre_exec)
ci->csi->pre_exec(ci->csi->pre_exec_data);
xexecvpe(ci->csi->exename,
ci->csi->argv,
ci->csi->environ ?: (const char* const*) environ);
}
__attribute__((noreturn))
static void
child_child(struct internal_child_info* ci)
{
struct errinfo ei = { 0 };
ei.want_msg = true;
if (!catch_error(child_child_1, ci, &ei))
abort();
fprintf(stderr, "%s: %s\n", ei.prgname, ei.msg);
fflush(stderr);
_exit(127); // Do not allow errors to propagate further
}
static void
child_cleanup(void* arg)
{
struct child* child = arg;
if (!child->dead) {
if (child->pty_master == NULL) {
int sig = child->deathsig ?: SIGTERM;
pid_t child_pid = child->pid;
if (sig < 0) {
/* Send to process group instead */
sig = -sig;
child_pid = -child_pid;
}
(void) kill(child_pid, sig);
} else {
/* In the pty case, the system's automatic SIGHUP should
* take care of the killing. */
fdh_destroy(child->pty_master);
}
if (!child->skip_cleanup_wait && !signal_quit_in_progress)
child_wait(child);
}
}
struct child*
child_start(const struct child_start_info* csi)
{
struct child* child = xcalloc(sizeof (*child));
struct cleanup* cl_waiter = cleanup_allocate();
SCOPED_RESLIST(rl);
int flags = csi->flags;
int pty_master = -1;
int pty_slave = -1;
if (flags & (CHILD_PTY_STDIN |
CHILD_PTY_STDOUT |
CHILD_PTY_STDERR |
CHILD_CTTY))
{
flags |= (CHILD_CTTY | CHILD_SETSID);
}
if (flags & CHILD_CTTY) {
pty_master = xopen("/dev/ptmx", O_RDWR | O_NOCTTY | O_CLOEXEC, 0);
if (grantpt(pty_master) || unlockpt(pty_master))
die_errno("grantpt/unlockpt");
#ifdef HAVE_PTSNAME
// Yes, yes, ptsname is not thread-safe. We're
// single-threaded.
char* pty_slave_name = xstrdup(ptsname(pty_master));
#else
int pty_slave_num;
if (ioctl(pty_master, TIOCGPTN, &pty_slave_num) != 0)
die_errno("TIOCGPTN");
char* pty_slave_name = xaprintf("/dev/pts/%d", pty_slave_num);
#endif
pty_slave = xopen(pty_slave_name, O_RDWR | O_NOCTTY | O_CLOEXEC, 0);
if (csi->pty_setup)
csi->pty_setup(pty_master, pty_slave, csi->pty_setup_data);
}
int childfd[3];
int parentfd[3];
if (flags & CHILD_SOCKETPAIR_STDIO) {
flags &= ~(CHILD_PTY_STDIN | CHILD_PTY_STDOUT);
xsocketpair(AF_UNIX, SOCK_STREAM, 0, &childfd[0], &parentfd[0]);
childfd[1] = xdup(childfd[0]);
parentfd[1] = xdup(parentfd[0]);
} else {
if (flags & CHILD_PTY_STDIN) {
childfd[0] = xdup(pty_slave);
parentfd[0] = xdup(pty_master);
} else if (flags & CHILD_NULL_STDIN) {
childfd[0] = xopen("/dev/null", O_RDONLY, 0);
parentfd[0] = xopen("/dev/null", O_WRONLY, 0);
} else {
xpipe(&childfd[0], &parentfd[0]);
}
if (flags & CHILD_PTY_STDOUT) {
childfd[1] = xdup(pty_slave);
parentfd[1] = xdup(pty_master);
} else if (flags & CHILD_NULL_STDOUT) {
childfd[1] = xopen("/dev/null", O_WRONLY, 0);
parentfd[1] = xopen("/dev/null", O_RDONLY, 0);
} else {
xpipe(&parentfd[1], &childfd[1]);
}
}
// If child has a pty for both stdout and stderr, from our POV, it
// writes only to stdout.
if ((flags & CHILD_PTY_STDERR) && (flags & CHILD_PTY_STDOUT))
flags |= CHILD_MERGE_STDERR;
if (flags & CHILD_MERGE_STDERR) {
childfd[2] = xdup(childfd[1]);
parentfd[2] = xopen("/dev/null", O_RDONLY, 0);
} else if (flags & CHILD_PTY_STDERR) {
childfd[2] = xdup(pty_slave);
parentfd[2] = xdup(pty_master);
} else if (flags & CHILD_INHERIT_STDERR) {
childfd[2] = xdup(2);
} else if (flags & CHILD_NULL_STDERR) {
childfd[2] = xopen("/dev/null", O_WRONLY, 0);
parentfd[2] = xopen("/dev/null", O_RDONLY, 0);
} else {
xpipe(&parentfd[2], &childfd[2]);
}
WITH_CURRENT_RESLIST(rl->parent);
child->flags = flags;
child->deathsig = csi->deathsig;
if (pty_master != -1)
child->pty_master = fdh_dup(pty_master);
child->fd[0] = fdh_dup(parentfd[0]);
child->fd[1] = fdh_dup(parentfd[1]);
if ((flags & CHILD_INHERIT_STDERR) == 0)
child->fd[2] = fdh_dup(parentfd[2]);
// We need to block all signals until the child calls signal(2) to
// reset its signal handlers to the default. If we didn't, the
// child could run handlers we didn't expect.
sigset_t all_blocked;
sigset_t prev_blocked;
VERIFY(sigfillset(&all_blocked) == 0);
VERIFY(sigprocmask(SIG_SETMASK, &all_blocked, &prev_blocked) == 0);
pid_t child_pid = fork();
if (child_pid == 0) {
struct internal_child_info ci = {
.flags = flags,
.csi = csi,
.pty_slave = pty_slave,
.childfd = childfd,
};
child_child(&ci); // Never returns
}
VERIFY(sigprocmask(SIG_SETMASK, &prev_blocked, NULL) == 0);
if (child_pid == -1)
die_errno("fork");
child->pid = child_pid;
cleanup_commit(cl_waiter, child_cleanup, child);
return child;
}
bool
child_poll_death(struct child* child)
{
if (!child->dead) {
int ret = waitpid(child->pid, &child->status, WNOHANG);
if (ret < 0)
die_errno("waitpid");
if (ret > 0)
child->dead = true;
}
return child->dead;
}
int
child_wait(struct child* child)
{
int ret;
// N.B. THE COMMENTED CODE BELOW IS WRONG.
//
// do {
// WITH_IO_SIGNALS_ALLOWED();
// ret = waitpid(child->pid, &child->status, 0);
// } while (ret < 0 && errno == EINTR);
//
// It looks correct, doesn't it?
//
// Consider what happens if we get a fatal signal, say SIGINT,
// immediately after a successful return from waitpid() and
// before we restore the signal mask that blocks SIGINT.
// SIGINT runs the global cleanup handlers, one of which calls
// kill() on our subprocess's PID. (Normally, the assignment
// to child->dead below prevents our calling kill().) When
// waitpid() completes successfully, the kernel frees the
// process table entry for the process waited on. Between the
// waitpid() return and our call to kill(), another process
// can move into that process table slot, resulting in our
// subsequent kill() going to wrong process and killing an
// innocent program.
//
// Instead, we first block SIGCHLD (in addition to signals like
// SIGINT), then, _WITHOUT_ unblocking signals, call waitpid(...,
// WNOHANG). If that succeeds, our child is dead and we remember
// its status. If waitpid() indicates that our child is still
// running, we then wait for signals; when the child dies, we loop
// around and call waitpid() again. That waitpid() might fail if
// a different child died, or if we got a non-SIGCHLD signal, but
// eventually our child will die, waitpid() will succeed, and
// we'll exit the loop.
//
sigset_t block_during_poll;
if (!child->dead) {
sigemptyset(&block_during_poll);
for (int i = 1; i < NSIG; ++i)
if (!sigismember(&signals_unblock_for_io, i))
sigaddset(&block_during_poll, i);
sigdelset(&block_during_poll, SIGCHLD);
}
while (!child->dead) {
ret = waitpid(child->pid, &child->status, WNOHANG);
if (ret < 0) {
// waitpid will fail if child->pid isn't really our child;
// that means we have a bug somewhere, since it should be
// a zombie until we wait for it.
die_errno("waitpid(%u)", (unsigned) child->pid);
}
if (ret > 0) {
child->dead = true;
} else {
sigsuspend(&block_during_poll);
}
}
return child->status;
}
void
child_kill(struct child* child, int signo)
{
if (!child->dead && kill(child->pid, signo) == -1)
die_errno("kill");
}
static bool
any_poll_active_p(const struct pollfd* p, size_t n)
{
for (size_t i = 0; i < n; ++i)
if (p[i].fd != -1)
return true;
return false;
}
struct child_communication*
child_communicate(
struct child* child,
const void* data_for_child_in,
size_t data_for_child_size)
{
const uint8_t* data_for_child = data_for_child_in;
size_t bytes_consumed = 0;
size_t chunk_size = 512;
struct pollfd p[ARRAYSIZE(child->fd)];
memset(&p, 0, sizeof (p));
struct {
struct cleanup* cl;
uint8_t* buf;
size_t pos;
size_t sz;
} ob[ARRAYSIZE(child->fd)-1];
memset(&ob, 0, sizeof (ob));
for (int i = 0; i < ARRAYSIZE(p); ++i) {
int fd = child->fd[i]->fd;
fd_set_blocking_mode(fd, non_blocking);
p[i].fd = fd;
p[i].events = (i == 0) ? POLLIN : POLLOUT;
}
for (;;) {
if (p[0].fd != -1) {
size_t nr_to_write = data_for_child_size - bytes_consumed;
if (nr_to_write > 0) {
ssize_t nr_written =
write(p[0].fd,
data_for_child + bytes_consumed,
XMIN(nr_to_write, (size_t) SSIZE_MAX));
if (nr_written == -1 && !error_temporary_p(errno))
die_errno("write[child]");
bytes_consumed += XMAX(nr_written, 0);
}
if (bytes_consumed == data_for_child_size) {
fdh_destroy(child->fd[0]);
p[0].fd = -1;
}
}
for (size_t i = 0; i < ARRAYSIZE(ob); ++i) {
int fd = p[i+1].fd;
if (fd == -1)
continue;
if (ob[i].pos == ob[i].sz) {
struct cleanup* newcl = cleanup_allocate();
size_t newsz;
if (SATADD(&newsz, ob[i].sz, chunk_size))
die(ERANGE, "too many bytes from child");
void* newbuf = realloc(ob[i].buf, newsz);
if (newbuf == NULL)
die(ENOMEM, "could not allocate iobuf");
cleanup_commit(newcl, free, newbuf);
cleanup_forget(ob[i].cl);
ob[i].cl = newcl;
ob[i].buf = newbuf;
ob[i].sz = newsz;
}
size_t to_read = ob[i].sz - ob[i].pos;
ssize_t nr_read = read(fd, ob[i].buf + ob[i].pos, to_read);
if (nr_read == -1 && !error_temporary_p(errno))
die_errno("read[child:%d]", fd);
ob[i].pos += XMAX(0, nr_read);
if (nr_read == 0) {
fdh_destroy(child->fd[i+1]);
p[i+1].fd = -1;
}
}
if (!any_poll_active_p(p, ARRAYSIZE(p)))
break;
int rc;
{
WITH_IO_SIGNALS_ALLOWED();
rc = poll(p, ARRAYSIZE(p), -1);
}
if (rc == -1 && errno != EINTR)
die_errno("poll");
}
struct child_communication* com = xcalloc(sizeof (*com));
com->status = child_wait(child);
com->bytes_consumed = bytes_consumed;
for (size_t i = 0; i < ARRAYSIZE(ob); ++i) {
com->out[i].bytes = ob[i].buf;
com->out[i].nr = ob[i].pos;
}
return com;
}
bool
child_status_success_p(int status)
{
return WIFEXITED(status) && WEXITSTATUS(status) == 0;
}
|
Java
|
{-# LANGUAGE TemplateHaskell #-}
{-| Contains TemplateHaskell stuff I don't want to recompile every time I make
changes to other files, a pre-compiled header, so to say. Don't know if that
even works.
-}
module FeedGipeda.THGenerated
( benchmarkClosure
, stringDict
, __remoteTable
) where
import Control.Distributed.Process (Closure, Process, Static,
liftIO)
import Control.Distributed.Process.Closure (SerializableDict,
functionTDict, mkClosure,
remotable)
import FeedGipeda.GitShell (SHA)
import FeedGipeda.Repo (Repo)
import qualified FeedGipeda.Slave as Slave
import FeedGipeda.Types (Timeout)
benchmarkProcess :: (String, Repo, SHA, Rational) -> Process String
benchmarkProcess (benchmarkScript, repo, sha, timeout) =
liftIO (Slave.benchmark benchmarkScript repo sha (fromRational timeout))
remotable ['benchmarkProcess]
benchmarkClosure :: String -> Repo -> SHA -> Timeout -> Closure (Process String)
benchmarkClosure benchmarkScript repo commit timeout =
$(mkClosure 'benchmarkProcess) (benchmarkScript, repo, commit, toRational timeout)
stringDict :: Static (SerializableDict String)
stringDict =
$(functionTDict 'benchmarkProcess)
|
Java
|
<?php
namespace app\models;
use Yii;
/**
* This is the model class for table "record".
*
* @property string $todaydetail
* @property string $st_classmark
* @property string $startday
* @property string $endday
* @property integer $totalday
* @property string $country
* @property string $countryEN
* @property string $st_name
* @property string $st_nameEN
* @property string $gaokaohao
* @property string $idcard
* @property string $sex
* @property string $st_year
* @property string $st_class
* @property string $academy
* @property string $major
* @property string $status
* @property string $model
* @property string $today
*/
class Record extends \yii\db\ActiveRecord
{
private static $_instance;
public static function getinstance()
{
if(!(self::$_instance instanceof self))
{
self::$_instance =new self();
}
return self::$_instance;
}
/**
* @inheritdoc
*/
public static function tableName()
{
return 'record';
}
/**
* @inheritdoc
*/
public function rules()
{
return [
[['todaydetail', 'st_classmark'], 'required'],
[['idcard'],'string', 'length' =>18],
[['startday', 'endday'],'string', 'length' =>10],
[['totalday'], 'integer'],
[['todaydetail', 'model', 'today'], 'string', 'max' => 50],
[['st_classmark','refusereason','reason', 'country', 'countryEN', 'st_name', 'st_nameEN', 'gaokaohao', 'st_year', 'st_class', 'academy', 'major'], 'string', 'max' => 100],
[['sex', 'status'], 'string', 'max' => 20]
];
}
/**
* @inheritdoc
*/
public function attributeLabels()
{
return [
'todaydetail' => '时间编号',
'today' => '申请时间(点击可排序)',
'st_classmark' => '学号',
'refusereason' => '拒绝理由(若批审核不通过时填写)',
'reason' => '申请理由(必填 例具体缘由:医保证明)',
'startday' => '出发日期',
'endday' => '来校报到日期',
'totalday' => '出国总天数',
'country' => '目的国家(中文)',
'countryEN' => '目的国家(英文)',
'st_name' => '学生姓名',
'st_nameEN' => '英文名(中文姓名拼音)',
'gaokaohao' => '高考报名号(由学生处填写)',
'idcard' => '身份证',
'sex' => '性别(male/female)',
'st_year' => '入学年份',
'st_class' => '班级编号',
'academy' => '学院',
'major' => '专业',
'status' => '状态(点击可排序)',
'model' => '申请类型',
];
}
}
|
Java
|
package com.michaelbaranov.microba.gradient;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import com.michaelbaranov.microba.common.AbstractBoundedTableModel;
/**
* A very basic implementation of {@link AbstractBoundedTableModel} used by
* default by {@link GradientBar}. This implementation has bounds 0 - 100 and
* is mutable.
*
* @author Michael Baranov
*
*/
public class DefaultGradientModel extends AbstractBoundedTableModel {
protected static final int POSITION_COLUMN = 0;
protected static final int COLOR_COLUMN = 1;
protected List positionList = new ArrayList(32);
protected List colorList = new ArrayList(32);
/**
* Constructor.
*/
public DefaultGradientModel() {
super();
positionList.add(new Integer(0));
colorList.add(Color.YELLOW);
positionList.add(new Integer(50));
colorList.add(Color.RED);
positionList.add(new Integer(100));
colorList.add(Color.GREEN);
}
public int getLowerBound() {
return 0;
}
public int getUpperBound() {
return 100;
}
public int getRowCount() {
return positionList.size();
}
public int getColumnCount() {
return 2;
}
public Class getColumnClass(int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return Integer.class;
case COLOR_COLUMN:
return Color.class;
}
return super.getColumnClass(columnIndex);
}
public Object getValueAt(int rowIndex, int columnIndex) {
switch (columnIndex) {
case POSITION_COLUMN:
return positionList.get(rowIndex);
case COLOR_COLUMN:
return colorList.get(rowIndex);
}
return null;
}
/**
* Adds a color point.
*
* @param color
* @param position
*/
public void add(Color color, int position) {
colorList.add(color);
positionList.add(new Integer(position));
fireTableDataChanged();
}
/**
* Removes a color point at specified index.
*
* @param index
*/
public void remove(int index) {
colorList.remove(index);
positionList.remove(index);
fireTableDataChanged();
}
/**
* Removes all color points.
*/
public void clear() {
colorList.clear();
positionList.clear();
fireTableDataChanged();
}
}
|
Java
|
/* Scala.js runtime support
* Copyright 2013 LAMP/EPFL
* Author: Sébastien Doeraene
*/
/* ---------------------------------- *
* The top-level Scala.js environment *
* ---------------------------------- */
//!if outputMode == ECMAScript51Global
var ScalaJS = {};
//!endif
// Get the environment info
ScalaJS.env = (typeof __ScalaJSEnv === "object" && __ScalaJSEnv) ? __ScalaJSEnv : {};
// Global scope
ScalaJS.g =
(typeof ScalaJS.env["global"] === "object" && ScalaJS.env["global"])
? ScalaJS.env["global"]
: ((typeof global === "object" && global && global["Object"] === Object) ? global : this);
ScalaJS.env["global"] = ScalaJS.g;
// Where to send exports
//!if moduleKind == CommonJSModule
ScalaJS.e = exports;
//!else
ScalaJS.e =
(typeof ScalaJS.env["exportsNamespace"] === "object" && ScalaJS.env["exportsNamespace"])
? ScalaJS.env["exportsNamespace"] : ScalaJS.g;
//!endif
ScalaJS.env["exportsNamespace"] = ScalaJS.e;
// Freeze the environment info
ScalaJS.g["Object"]["freeze"](ScalaJS.env);
// Linking info - must be in sync with scala.scalajs.runtime.LinkingInfo
ScalaJS.linkingInfo = {
"envInfo": ScalaJS.env,
"semantics": {
//!if asInstanceOfs == Compliant
"asInstanceOfs": 0,
//!else
//!if asInstanceOfs == Fatal
"asInstanceOfs": 1,
//!else
"asInstanceOfs": 2,
//!endif
//!endif
//!if arrayIndexOutOfBounds == Compliant
"arrayIndexOutOfBounds": 0,
//!else
//!if arrayIndexOutOfBounds == Fatal
"arrayIndexOutOfBounds": 1,
//!else
"arrayIndexOutOfBounds": 2,
//!endif
//!endif
//!if moduleInit == Compliant
"moduleInit": 0,
//!else
//!if moduleInit == Fatal
"moduleInit": 1,
//!else
"moduleInit": 2,
//!endif
//!endif
//!if floats == Strict
"strictFloats": true,
//!else
"strictFloats": false,
//!endif
//!if productionMode == true
"productionMode": true
//!else
"productionMode": false
//!endif
},
//!if outputMode == ECMAScript6
"assumingES6": true,
//!else
"assumingES6": false,
//!endif
"linkerVersion": "{{LINKER_VERSION}}"
};
ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo);
ScalaJS.g["Object"]["freeze"](ScalaJS.linkingInfo["semantics"]);
// Snapshots of builtins and polyfills
//!if outputMode == ECMAScript6
ScalaJS.imul = ScalaJS.g["Math"]["imul"];
ScalaJS.fround = ScalaJS.g["Math"]["fround"];
ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"];
//!else
ScalaJS.imul = ScalaJS.g["Math"]["imul"] || (function(a, b) {
// See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/imul
const ah = (a >>> 16) & 0xffff;
const al = a & 0xffff;
const bh = (b >>> 16) & 0xffff;
const bl = b & 0xffff;
// the shift by 0 fixes the sign on the high part
// the final |0 converts the unsigned value into a signed value
return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
});
ScalaJS.fround = ScalaJS.g["Math"]["fround"] ||
//!if floats == Strict
(ScalaJS.g["Float32Array"] ? (function(v) {
const array = new ScalaJS.g["Float32Array"](1);
array[0] = v;
return array[0];
}) : (function(v) {
return ScalaJS.m.sjsr_package$().froundPolyfill__D__D(+v);
}));
//!else
(function(v) {
return +v;
});
//!endif
ScalaJS.clz32 = ScalaJS.g["Math"]["clz32"] || (function(i) {
// See Hacker's Delight, Section 5-3
if (i === 0) return 32;
let r = 1;
if ((i & 0xffff0000) === 0) { i <<= 16; r += 16; };
if ((i & 0xff000000) === 0) { i <<= 8; r += 8; };
if ((i & 0xf0000000) === 0) { i <<= 4; r += 4; };
if ((i & 0xc0000000) === 0) { i <<= 2; r += 2; };
return r + (i >> 31);
});
//!endif
// Other fields
//!if outputMode == ECMAScript51Global
ScalaJS.d = {}; // Data for types
ScalaJS.a = {}; // Scala.js-defined JS class value accessors
ScalaJS.b = {}; // Scala.js-defined JS class value fields
ScalaJS.c = {}; // Scala.js constructors
ScalaJS.h = {}; // Inheritable constructors (without initialization code)
ScalaJS.s = {}; // Static methods
ScalaJS.t = {}; // Static fields
ScalaJS.f = {}; // Default methods
ScalaJS.n = {}; // Module instances
ScalaJS.m = {}; // Module accessors
ScalaJS.is = {}; // isInstanceOf methods
ScalaJS.isArrayOf = {}; // isInstanceOfArrayOf methods
//!if asInstanceOfs != Unchecked
ScalaJS.as = {}; // asInstanceOf methods
ScalaJS.asArrayOf = {}; // asInstanceOfArrayOf methods
//!endif
ScalaJS.lastIDHash = 0; // last value attributed to an id hash code
ScalaJS.idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null;
//!else
let $lastIDHash = 0; // last value attributed to an id hash code
//!if outputMode == ECMAScript6
const $idHashCodeMap = new ScalaJS.g["WeakMap"]();
//!else
const $idHashCodeMap = ScalaJS.g["WeakMap"] ? new ScalaJS.g["WeakMap"]() : null;
//!endif
//!endif
// Core mechanism
ScalaJS.makeIsArrayOfPrimitive = function(primitiveData) {
return function(obj, depth) {
return !!(obj && obj.$classData &&
(obj.$classData.arrayDepth === depth) &&
(obj.$classData.arrayBase === primitiveData));
}
};
//!if asInstanceOfs != Unchecked
ScalaJS.makeAsArrayOfPrimitive = function(isInstanceOfFunction, arrayEncodedName) {
return function(obj, depth) {
if (isInstanceOfFunction(obj, depth) || (obj === null))
return obj;
else
ScalaJS.throwArrayCastException(obj, arrayEncodedName, depth);
}
};
//!endif
/** Encode a property name for runtime manipulation
* Usage:
* env.propertyName({someProp:0})
* Returns:
* "someProp"
* Useful when the property is renamed by a global optimizer (like Closure)
* but we must still get hold of a string of that name for runtime
* reflection.
*/
ScalaJS.propertyName = function(obj) {
for (const prop in obj)
return prop;
};
// Runtime functions
ScalaJS.isScalaJSObject = function(obj) {
return !!(obj && obj.$classData);
};
//!if asInstanceOfs != Unchecked
ScalaJS.throwClassCastException = function(instance, classFullName) {
//!if asInstanceOfs == Compliant
throw new ScalaJS.c.jl_ClassCastException().init___T(
instance + " is not an instance of " + classFullName);
//!else
throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable(
new ScalaJS.c.jl_ClassCastException().init___T(
instance + " is not an instance of " + classFullName));
//!endif
};
ScalaJS.throwArrayCastException = function(instance, classArrayEncodedName, depth) {
for (; depth; --depth)
classArrayEncodedName = "[" + classArrayEncodedName;
ScalaJS.throwClassCastException(instance, classArrayEncodedName);
};
//!endif
//!if arrayIndexOutOfBounds != Unchecked
ScalaJS.throwArrayIndexOutOfBoundsException = function(i) {
const msg = (i === null) ? null : ("" + i);
//!if arrayIndexOutOfBounds == Compliant
throw new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg);
//!else
throw new ScalaJS.c.sjsr_UndefinedBehaviorError().init___jl_Throwable(
new ScalaJS.c.jl_ArrayIndexOutOfBoundsException().init___T(msg));
//!endif
};
//!endif
ScalaJS.noIsInstance = function(instance) {
throw new ScalaJS.g["TypeError"](
"Cannot call isInstance() on a Class representing a raw JS trait/object");
};
ScalaJS.makeNativeArrayWrapper = function(arrayClassData, nativeArray) {
return new arrayClassData.constr(nativeArray);
};
ScalaJS.newArrayObject = function(arrayClassData, lengths) {
return ScalaJS.newArrayObjectInternal(arrayClassData, lengths, 0);
};
ScalaJS.newArrayObjectInternal = function(arrayClassData, lengths, lengthIndex) {
const result = new arrayClassData.constr(lengths[lengthIndex]);
if (lengthIndex < lengths.length-1) {
const subArrayClassData = arrayClassData.componentData;
const subLengthIndex = lengthIndex+1;
const underlying = result.u;
for (let i = 0; i < underlying.length; i++) {
underlying[i] = ScalaJS.newArrayObjectInternal(
subArrayClassData, lengths, subLengthIndex);
}
}
return result;
};
ScalaJS.objectToString = function(instance) {
if (instance === void 0)
return "undefined";
else
return instance.toString();
};
ScalaJS.objectGetClass = function(instance) {
switch (typeof instance) {
case "string":
return ScalaJS.d.T.getClassOf();
case "number": {
const v = instance | 0;
if (v === instance) { // is the value integral?
if (ScalaJS.isByte(v))
return ScalaJS.d.jl_Byte.getClassOf();
else if (ScalaJS.isShort(v))
return ScalaJS.d.jl_Short.getClassOf();
else
return ScalaJS.d.jl_Integer.getClassOf();
} else {
if (ScalaJS.isFloat(instance))
return ScalaJS.d.jl_Float.getClassOf();
else
return ScalaJS.d.jl_Double.getClassOf();
}
}
case "boolean":
return ScalaJS.d.jl_Boolean.getClassOf();
case "undefined":
return ScalaJS.d.sr_BoxedUnit.getClassOf();
default:
if (instance === null)
return instance.getClass__jl_Class();
else if (ScalaJS.is.sjsr_RuntimeLong(instance))
return ScalaJS.d.jl_Long.getClassOf();
else if (ScalaJS.isScalaJSObject(instance))
return instance.$classData.getClassOf();
else
return null; // Exception?
}
};
ScalaJS.objectClone = function(instance) {
if (ScalaJS.isScalaJSObject(instance) || (instance === null))
return instance.clone__O();
else
throw new ScalaJS.c.jl_CloneNotSupportedException().init___();
};
ScalaJS.objectNotify = function(instance) {
// final and no-op in java.lang.Object
if (instance === null)
instance.notify__V();
};
ScalaJS.objectNotifyAll = function(instance) {
// final and no-op in java.lang.Object
if (instance === null)
instance.notifyAll__V();
};
ScalaJS.objectFinalize = function(instance) {
if (ScalaJS.isScalaJSObject(instance) || (instance === null))
instance.finalize__V();
// else no-op
};
ScalaJS.objectEquals = function(instance, rhs) {
if (ScalaJS.isScalaJSObject(instance) || (instance === null))
return instance.equals__O__Z(rhs);
else if (typeof instance === "number")
return typeof rhs === "number" && ScalaJS.numberEquals(instance, rhs);
else
return instance === rhs;
};
ScalaJS.numberEquals = function(lhs, rhs) {
return (lhs === rhs) ? (
// 0.0.equals(-0.0) must be false
lhs !== 0 || 1/lhs === 1/rhs
) : (
// are they both NaN?
(lhs !== lhs) && (rhs !== rhs)
);
};
ScalaJS.objectHashCode = function(instance) {
switch (typeof instance) {
case "string":
return ScalaJS.m.sjsr_RuntimeString$().hashCode__T__I(instance);
case "number":
return ScalaJS.m.sjsr_Bits$().numberHashCode__D__I(instance);
case "boolean":
return instance ? 1231 : 1237;
case "undefined":
return 0;
default:
if (ScalaJS.isScalaJSObject(instance) || instance === null)
return instance.hashCode__I();
//!if outputMode != ECMAScript6
else if (ScalaJS.idHashCodeMap === null)
return 42;
//!endif
else
return ScalaJS.systemIdentityHashCode(instance);
}
};
ScalaJS.comparableCompareTo = function(instance, rhs) {
switch (typeof instance) {
case "string":
//!if asInstanceOfs != Unchecked
ScalaJS.as.T(rhs);
//!endif
return instance === rhs ? 0 : (instance < rhs ? -1 : 1);
case "number":
//!if asInstanceOfs != Unchecked
ScalaJS.as.jl_Number(rhs);
//!endif
return ScalaJS.m.jl_Double$().compare__D__D__I(instance, rhs);
case "boolean":
//!if asInstanceOfs != Unchecked
ScalaJS.asBoolean(rhs);
//!endif
return instance - rhs; // yes, this gives the right result
default:
return instance.compareTo__O__I(rhs);
}
};
ScalaJS.charSequenceLength = function(instance) {
if (typeof(instance) === "string")
//!if asInstanceOfs != Unchecked
return ScalaJS.uI(instance["length"]);
//!else
return instance["length"] | 0;
//!endif
else
return instance.length__I();
};
ScalaJS.charSequenceCharAt = function(instance, index) {
if (typeof(instance) === "string")
//!if asInstanceOfs != Unchecked
return ScalaJS.uI(instance["charCodeAt"](index)) & 0xffff;
//!else
return instance["charCodeAt"](index) & 0xffff;
//!endif
else
return instance.charAt__I__C(index);
};
ScalaJS.charSequenceSubSequence = function(instance, start, end) {
if (typeof(instance) === "string")
//!if asInstanceOfs != Unchecked
return ScalaJS.as.T(instance["substring"](start, end));
//!else
return instance["substring"](start, end);
//!endif
else
return instance.subSequence__I__I__jl_CharSequence(start, end);
};
ScalaJS.booleanBooleanValue = function(instance) {
if (typeof instance === "boolean") return instance;
else return instance.booleanValue__Z();
};
ScalaJS.numberByteValue = function(instance) {
if (typeof instance === "number") return (instance << 24) >> 24;
else return instance.byteValue__B();
};
ScalaJS.numberShortValue = function(instance) {
if (typeof instance === "number") return (instance << 16) >> 16;
else return instance.shortValue__S();
};
ScalaJS.numberIntValue = function(instance) {
if (typeof instance === "number") return instance | 0;
else return instance.intValue__I();
};
ScalaJS.numberLongValue = function(instance) {
if (typeof instance === "number")
return ScalaJS.m.sjsr_RuntimeLong$().fromDouble__D__sjsr_RuntimeLong(instance);
else
return instance.longValue__J();
};
ScalaJS.numberFloatValue = function(instance) {
if (typeof instance === "number") return ScalaJS.fround(instance);
else return instance.floatValue__F();
};
ScalaJS.numberDoubleValue = function(instance) {
if (typeof instance === "number") return instance;
else return instance.doubleValue__D();
};
ScalaJS.isNaN = function(instance) {
return instance !== instance;
};
ScalaJS.isInfinite = function(instance) {
return !ScalaJS.g["isFinite"](instance) && !ScalaJS.isNaN(instance);
};
ScalaJS.doubleToInt = function(x) {
return (x > 2147483647) ? (2147483647) : ((x < -2147483648) ? -2147483648 : (x | 0));
};
/** Instantiates a JS object with variadic arguments to the constructor. */
ScalaJS.newJSObjectWithVarargs = function(ctor, args) {
// This basically emulates the ECMAScript specification for 'new'.
const instance = ScalaJS.g["Object"]["create"](ctor.prototype);
const result = ctor["apply"](instance, args);
switch (typeof result) {
case "string": case "number": case "boolean": case "undefined": case "symbol":
return instance;
default:
return result === null ? instance : result;
}
};
ScalaJS.resolveSuperRef = function(initialProto, propName) {
const getPrototypeOf = ScalaJS.g["Object"]["getPrototypeOf"];
const getOwnPropertyDescriptor = ScalaJS.g["Object"]["getOwnPropertyDescriptor"];
let superProto = getPrototypeOf(initialProto);
while (superProto !== null) {
const desc = getOwnPropertyDescriptor(superProto, propName);
if (desc !== void 0)
return desc;
superProto = getPrototypeOf(superProto);
}
return void 0;
};
ScalaJS.superGet = function(initialProto, self, propName) {
const desc = ScalaJS.resolveSuperRef(initialProto, propName);
if (desc !== void 0) {
const getter = desc["get"];
if (getter !== void 0)
return getter["call"](self);
else
return desc["value"];
}
return void 0;
};
ScalaJS.superSet = function(initialProto, self, propName, value) {
const desc = ScalaJS.resolveSuperRef(initialProto, propName);
if (desc !== void 0) {
const setter = desc["set"];
if (setter !== void 0) {
setter["call"](self, value);
return void 0;
}
}
throw new ScalaJS.g["TypeError"]("super has no setter '" + propName + "'.");
};
//!if moduleKind == CommonJSModule
ScalaJS.moduleDefault = function(m) {
return (m && (typeof m === "object") && "default" in m) ? m["default"] : m;
};
//!endif
ScalaJS.propertiesOf = function(obj) {
const result = [];
for (const prop in obj)
result["push"](prop);
return result;
};
ScalaJS.systemArraycopy = function(src, srcPos, dest, destPos, length) {
const srcu = src.u;
const destu = dest.u;
//!if arrayIndexOutOfBounds != Unchecked
if (srcPos < 0 || destPos < 0 || length < 0 ||
(srcPos > ((srcu.length - length) | 0)) ||
(destPos > ((destu.length - length) | 0))) {
ScalaJS.throwArrayIndexOutOfBoundsException(null);
}
//!endif
if (srcu !== destu || destPos < srcPos || (((srcPos + length) | 0) < destPos)) {
for (let i = 0; i < length; i = (i + 1) | 0)
destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0];
} else {
for (let i = (length - 1) | 0; i >= 0; i = (i - 1) | 0)
destu[(destPos + i) | 0] = srcu[(srcPos + i) | 0];
}
};
ScalaJS.systemIdentityHashCode =
//!if outputMode != ECMAScript6
(ScalaJS.idHashCodeMap !== null) ?
//!endif
(function(obj) {
switch (typeof obj) {
case "string": case "number": case "boolean": case "undefined":
return ScalaJS.objectHashCode(obj);
default:
if (obj === null) {
return 0;
} else {
let hash = ScalaJS.idHashCodeMap["get"](obj);
if (hash === void 0) {
hash = (ScalaJS.lastIDHash + 1) | 0;
ScalaJS.lastIDHash = hash;
ScalaJS.idHashCodeMap["set"](obj, hash);
}
return hash;
}
}
//!if outputMode != ECMAScript6
}) :
(function(obj) {
if (ScalaJS.isScalaJSObject(obj)) {
let hash = obj["$idHashCode$0"];
if (hash !== void 0) {
return hash;
} else if (!ScalaJS.g["Object"]["isSealed"](obj)) {
hash = (ScalaJS.lastIDHash + 1) | 0;
ScalaJS.lastIDHash = hash;
obj["$idHashCode$0"] = hash;
return hash;
} else {
return 42;
}
} else if (obj === null) {
return 0;
} else {
return ScalaJS.objectHashCode(obj);
}
//!endif
});
// is/as for hijacked boxed classes (the non-trivial ones)
ScalaJS.isByte = function(v) {
return (v << 24 >> 24) === v && 1/v !== 1/-0;
};
ScalaJS.isShort = function(v) {
return (v << 16 >> 16) === v && 1/v !== 1/-0;
};
ScalaJS.isInt = function(v) {
return (v | 0) === v && 1/v !== 1/-0;
};
ScalaJS.isFloat = function(v) {
//!if floats == Strict
return v !== v || ScalaJS.fround(v) === v;
//!else
return typeof v === "number";
//!endif
};
//!if asInstanceOfs != Unchecked
ScalaJS.asUnit = function(v) {
if (v === void 0 || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "scala.runtime.BoxedUnit");
};
ScalaJS.asBoolean = function(v) {
if (typeof v === "boolean" || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Boolean");
};
ScalaJS.asByte = function(v) {
if (ScalaJS.isByte(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Byte");
};
ScalaJS.asShort = function(v) {
if (ScalaJS.isShort(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Short");
};
ScalaJS.asInt = function(v) {
if (ScalaJS.isInt(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Integer");
};
ScalaJS.asFloat = function(v) {
if (ScalaJS.isFloat(v) || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Float");
};
ScalaJS.asDouble = function(v) {
if (typeof v === "number" || v === null)
return v;
else
ScalaJS.throwClassCastException(v, "java.lang.Double");
};
//!endif
// Unboxes
//!if asInstanceOfs != Unchecked
ScalaJS.uZ = function(value) {
return !!ScalaJS.asBoolean(value);
};
ScalaJS.uB = function(value) {
return ScalaJS.asByte(value) | 0;
};
ScalaJS.uS = function(value) {
return ScalaJS.asShort(value) | 0;
};
ScalaJS.uI = function(value) {
return ScalaJS.asInt(value) | 0;
};
ScalaJS.uJ = function(value) {
return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1
: ScalaJS.as.sjsr_RuntimeLong(value);
};
ScalaJS.uF = function(value) {
/* Here, it is fine to use + instead of fround, because asFloat already
* ensures that the result is either null or a float.
*/
return +ScalaJS.asFloat(value);
};
ScalaJS.uD = function(value) {
return +ScalaJS.asDouble(value);
};
//!else
ScalaJS.uJ = function(value) {
return null === value ? ScalaJS.m.sjsr_RuntimeLong$().Zero$1 : value;
};
//!endif
// TypeArray conversions
ScalaJS.byteArray2TypedArray = function(value) { return new ScalaJS.g["Int8Array"](value.u); };
ScalaJS.shortArray2TypedArray = function(value) { return new ScalaJS.g["Int16Array"](value.u); };
ScalaJS.charArray2TypedArray = function(value) { return new ScalaJS.g["Uint16Array"](value.u); };
ScalaJS.intArray2TypedArray = function(value) { return new ScalaJS.g["Int32Array"](value.u); };
ScalaJS.floatArray2TypedArray = function(value) { return new ScalaJS.g["Float32Array"](value.u); };
ScalaJS.doubleArray2TypedArray = function(value) { return new ScalaJS.g["Float64Array"](value.u); };
ScalaJS.typedArray2ByteArray = function(value) {
const arrayClassData = ScalaJS.d.B.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Int8Array"](value));
};
ScalaJS.typedArray2ShortArray = function(value) {
const arrayClassData = ScalaJS.d.S.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Int16Array"](value));
};
ScalaJS.typedArray2CharArray = function(value) {
const arrayClassData = ScalaJS.d.C.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Uint16Array"](value));
};
ScalaJS.typedArray2IntArray = function(value) {
const arrayClassData = ScalaJS.d.I.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Int32Array"](value));
};
ScalaJS.typedArray2FloatArray = function(value) {
const arrayClassData = ScalaJS.d.F.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Float32Array"](value));
};
ScalaJS.typedArray2DoubleArray = function(value) {
const arrayClassData = ScalaJS.d.D.getArrayOf();
return new arrayClassData.constr(new ScalaJS.g["Float64Array"](value));
};
// TypeData class
//!if outputMode != ECMAScript6
/** @constructor */
ScalaJS.TypeData = function() {
//!else
class $TypeData {
constructor() {
//!endif
// Runtime support
this.constr = void 0;
this.parentData = void 0;
this.ancestors = null;
this.componentData = null;
this.arrayBase = null;
this.arrayDepth = 0;
this.zero = null;
this.arrayEncodedName = "";
this._classOf = void 0;
this._arrayOf = void 0;
this.isArrayOf = void 0;
// java.lang.Class support
this["name"] = "";
this["isPrimitive"] = false;
this["isInterface"] = false;
this["isArrayClass"] = false;
this["isRawJSType"] = false;
this["isInstance"] = void 0;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.initPrim = function(
//!else
initPrim(
//!endif
zero, arrayEncodedName, displayName) {
// Runtime support
this.ancestors = {};
this.componentData = null;
this.zero = zero;
this.arrayEncodedName = arrayEncodedName;
this.isArrayOf = function(obj, depth) { return false; };
// java.lang.Class support
this["name"] = displayName;
this["isPrimitive"] = true;
this["isInstance"] = function(obj) { return false; };
return this;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.initClass = function(
//!else
initClass(
//!endif
internalNameObj, isInterface, fullName,
ancestors, isRawJSType, parentData, isInstance, isArrayOf) {
const internalName = ScalaJS.propertyName(internalNameObj);
isInstance = isInstance || function(obj) {
return !!(obj && obj.$classData && obj.$classData.ancestors[internalName]);
};
isArrayOf = isArrayOf || function(obj, depth) {
return !!(obj && obj.$classData && (obj.$classData.arrayDepth === depth)
&& obj.$classData.arrayBase.ancestors[internalName])
};
// Runtime support
this.parentData = parentData;
this.ancestors = ancestors;
this.arrayEncodedName = "L"+fullName+";";
this.isArrayOf = isArrayOf;
// java.lang.Class support
this["name"] = fullName;
this["isInterface"] = isInterface;
this["isRawJSType"] = !!isRawJSType;
this["isInstance"] = isInstance;
return this;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.initArray = function(
//!else
initArray(
//!endif
componentData) {
// The constructor
const componentZero0 = componentData.zero;
// The zero for the Long runtime representation
// is a special case here, since the class has not
// been defined yet, when this file is read
const componentZero = (componentZero0 == "longZero")
? ScalaJS.m.sjsr_RuntimeLong$().Zero$1
: componentZero0;
//!if outputMode != ECMAScript6
/** @constructor */
const ArrayClass = function(arg) {
if (typeof(arg) === "number") {
// arg is the length of the array
this.u = new Array(arg);
for (let i = 0; i < arg; i++)
this.u[i] = componentZero;
} else {
// arg is a native array that we wrap
this.u = arg;
}
}
ArrayClass.prototype = new ScalaJS.h.O;
ArrayClass.prototype.constructor = ArrayClass;
//!if arrayIndexOutOfBounds != Unchecked
ArrayClass.prototype.get = function(i) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
return this.u[i];
};
ArrayClass.prototype.set = function(i, v) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
this.u[i] = v;
};
//!endif
ArrayClass.prototype.clone__O = function() {
if (this.u instanceof Array)
return new ArrayClass(this.u["slice"](0));
else
// The underlying Array is a TypedArray
return new ArrayClass(new this.u.constructor(this.u));
};
//!else
class ArrayClass extends ScalaJS.c.O {
constructor(arg) {
super();
if (typeof(arg) === "number") {
// arg is the length of the array
this.u = new Array(arg);
for (let i = 0; i < arg; i++)
this.u[i] = componentZero;
} else {
// arg is a native array that we wrap
this.u = arg;
}
};
//!if arrayIndexOutOfBounds != Unchecked
get(i) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
return this.u[i];
};
set(i, v) {
if (i < 0 || i >= this.u.length)
ScalaJS.throwArrayIndexOutOfBoundsException(i);
this.u[i] = v;
};
//!endif
clone__O() {
if (this.u instanceof Array)
return new ArrayClass(this.u["slice"](0));
else
// The underlying Array is a TypedArray
return new ArrayClass(new this.u.constructor(this.u));
};
};
//!endif
ArrayClass.prototype.$classData = this;
// Don't generate reflective call proxies. The compiler special cases
// reflective calls to methods on scala.Array
// The data
const encodedName = "[" + componentData.arrayEncodedName;
const componentBase = componentData.arrayBase || componentData;
const arrayDepth = componentData.arrayDepth + 1;
const isInstance = function(obj) {
return componentBase.isArrayOf(obj, arrayDepth);
}
// Runtime support
this.constr = ArrayClass;
this.parentData = ScalaJS.d.O;
this.ancestors = {O: 1, jl_Cloneable: 1, Ljava_io_Serializable: 1};
this.componentData = componentData;
this.arrayBase = componentBase;
this.arrayDepth = arrayDepth;
this.zero = null;
this.arrayEncodedName = encodedName;
this._classOf = undefined;
this._arrayOf = undefined;
this.isArrayOf = undefined;
// java.lang.Class support
this["name"] = encodedName;
this["isPrimitive"] = false;
this["isInterface"] = false;
this["isArrayClass"] = true;
this["isInstance"] = isInstance;
return this;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.getClassOf = function() {
//!else
getClassOf() {
//!endif
if (!this._classOf)
this._classOf = new ScalaJS.c.jl_Class().init___jl_ScalaJSClassData(this);
return this._classOf;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype.getArrayOf = function() {
//!else
getArrayOf() {
//!endif
if (!this._arrayOf)
this._arrayOf = new ScalaJS.TypeData().initArray(this);
return this._arrayOf;
};
// java.lang.Class support
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["getFakeInstance"] = function() {
//!else
"getFakeInstance"() {
//!endif
if (this === ScalaJS.d.T)
return "some string";
else if (this === ScalaJS.d.jl_Boolean)
return false;
else if (this === ScalaJS.d.jl_Byte ||
this === ScalaJS.d.jl_Short ||
this === ScalaJS.d.jl_Integer ||
this === ScalaJS.d.jl_Float ||
this === ScalaJS.d.jl_Double)
return 0;
else if (this === ScalaJS.d.jl_Long)
return ScalaJS.m.sjsr_RuntimeLong$().Zero$1;
else if (this === ScalaJS.d.sr_BoxedUnit)
return void 0;
else
return {$classData: this};
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["getSuperclass"] = function() {
//!else
"getSuperclass"() {
//!endif
return this.parentData ? this.parentData.getClassOf() : null;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["getComponentType"] = function() {
//!else
"getComponentType"() {
//!endif
return this.componentData ? this.componentData.getClassOf() : null;
};
//!if outputMode != ECMAScript6
ScalaJS.TypeData.prototype["newArrayOfThisClass"] = function(lengths) {
//!else
"newArrayOfThisClass"(lengths) {
//!endif
let arrayClassData = this;
for (let i = 0; i < lengths.length; i++)
arrayClassData = arrayClassData.getArrayOf();
return ScalaJS.newArrayObject(arrayClassData, lengths);
};
//!if outputMode == ECMAScript6
};
//!endif
// Create primitive types
ScalaJS.d.V = new ScalaJS.TypeData().initPrim(undefined, "V", "void");
ScalaJS.d.Z = new ScalaJS.TypeData().initPrim(false, "Z", "boolean");
ScalaJS.d.C = new ScalaJS.TypeData().initPrim(0, "C", "char");
ScalaJS.d.B = new ScalaJS.TypeData().initPrim(0, "B", "byte");
ScalaJS.d.S = new ScalaJS.TypeData().initPrim(0, "S", "short");
ScalaJS.d.I = new ScalaJS.TypeData().initPrim(0, "I", "int");
ScalaJS.d.J = new ScalaJS.TypeData().initPrim("longZero", "J", "long");
ScalaJS.d.F = new ScalaJS.TypeData().initPrim(0.0, "F", "float");
ScalaJS.d.D = new ScalaJS.TypeData().initPrim(0.0, "D", "double");
// Instance tests for array of primitives
ScalaJS.isArrayOf.Z = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.Z);
ScalaJS.d.Z.isArrayOf = ScalaJS.isArrayOf.Z;
ScalaJS.isArrayOf.C = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.C);
ScalaJS.d.C.isArrayOf = ScalaJS.isArrayOf.C;
ScalaJS.isArrayOf.B = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.B);
ScalaJS.d.B.isArrayOf = ScalaJS.isArrayOf.B;
ScalaJS.isArrayOf.S = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.S);
ScalaJS.d.S.isArrayOf = ScalaJS.isArrayOf.S;
ScalaJS.isArrayOf.I = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.I);
ScalaJS.d.I.isArrayOf = ScalaJS.isArrayOf.I;
ScalaJS.isArrayOf.J = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.J);
ScalaJS.d.J.isArrayOf = ScalaJS.isArrayOf.J;
ScalaJS.isArrayOf.F = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.F);
ScalaJS.d.F.isArrayOf = ScalaJS.isArrayOf.F;
ScalaJS.isArrayOf.D = ScalaJS.makeIsArrayOfPrimitive(ScalaJS.d.D);
ScalaJS.d.D.isArrayOf = ScalaJS.isArrayOf.D;
//!if asInstanceOfs != Unchecked
// asInstanceOfs for array of primitives
ScalaJS.asArrayOf.Z = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.Z, "Z");
ScalaJS.asArrayOf.C = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.C, "C");
ScalaJS.asArrayOf.B = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.B, "B");
ScalaJS.asArrayOf.S = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.S, "S");
ScalaJS.asArrayOf.I = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.I, "I");
ScalaJS.asArrayOf.J = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.J, "J");
ScalaJS.asArrayOf.F = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.F, "F");
ScalaJS.asArrayOf.D = ScalaJS.makeAsArrayOfPrimitive(ScalaJS.isArrayOf.D, "D");
//!endif
|
Java
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/panels/panel_resize_controller.h"
#include "base/logging.h"
#include "chrome/browser/ui/panels/panel.h"
#include "chrome/browser/ui/panels/panel_manager.h"
namespace {
static bool ResizingLeft(panel::ResizingSides sides) {
return sides == panel::RESIZE_TOP_LEFT ||
sides == panel::RESIZE_LEFT ||
sides == panel::RESIZE_BOTTOM_LEFT;
}
static bool ResizingRight(panel::ResizingSides sides) {
return sides == panel::RESIZE_TOP_RIGHT ||
sides == panel::RESIZE_RIGHT ||
sides == panel::RESIZE_BOTTOM_RIGHT;
}
static bool ResizingTop(panel::ResizingSides sides) {
return sides == panel::RESIZE_TOP_LEFT ||
sides == panel::RESIZE_TOP ||
sides == panel::RESIZE_TOP_RIGHT;
}
static bool ResizingBottom(panel::ResizingSides sides) {
return sides == panel::RESIZE_BOTTOM_RIGHT ||
sides == panel::RESIZE_BOTTOM ||
sides == panel::RESIZE_BOTTOM_LEFT;
}
}
PanelResizeController::PanelResizeController(PanelManager* panel_manager)
: panel_manager_(panel_manager),
resizing_panel_(NULL),
sides_resized_(panel::RESIZE_NONE) {
}
void PanelResizeController::StartResizing(Panel* panel,
const gfx::Point& mouse_location,
panel::ResizingSides sides) {
DCHECK(!IsResizing());
DCHECK_NE(panel::RESIZE_NONE, sides);
panel::Resizability resizability = panel->CanResizeByMouse();
DCHECK_NE(panel::NOT_RESIZABLE, resizability);
panel::Resizability resizability_to_test;
switch (sides) {
case panel::RESIZE_TOP_LEFT:
resizability_to_test = panel::RESIZABLE_TOP_LEFT;
break;
case panel::RESIZE_TOP:
resizability_to_test = panel::RESIZABLE_TOP;
break;
case panel::RESIZE_TOP_RIGHT:
resizability_to_test = panel::RESIZABLE_TOP_RIGHT;
break;
case panel::RESIZE_LEFT:
resizability_to_test = panel::RESIZABLE_LEFT;
break;
case panel::RESIZE_RIGHT:
resizability_to_test = panel::RESIZABLE_RIGHT;
break;
case panel::RESIZE_BOTTOM_LEFT:
resizability_to_test = panel::RESIZABLE_BOTTOM_LEFT;
break;
case panel::RESIZE_BOTTOM:
resizability_to_test = panel::RESIZABLE_BOTTOM;
break;
case panel::RESIZE_BOTTOM_RIGHT:
resizability_to_test = panel::RESIZABLE_BOTTOM_RIGHT;
break;
default:
resizability_to_test = panel::NOT_RESIZABLE;
break;
}
if ((resizability & resizability_to_test) == 0) {
DLOG(WARNING) << "Resizing not allowed. Is this a test?";
return;
}
mouse_location_at_start_ = mouse_location;
bounds_at_start_ = panel->GetBounds();
sides_resized_ = sides;
resizing_panel_ = panel;
resizing_panel_->OnPanelStartUserResizing();
}
void PanelResizeController::Resize(const gfx::Point& mouse_location) {
DCHECK(IsResizing());
panel::Resizability resizability = resizing_panel_->CanResizeByMouse();
if (panel::NOT_RESIZABLE == resizability) {
EndResizing(false);
return;
}
gfx::Rect bounds = resizing_panel_->GetBounds();
if (ResizingRight(sides_resized_)) {
bounds.set_width(std::max(bounds_at_start_.width() +
mouse_location.x() - mouse_location_at_start_.x(), 0));
}
if (ResizingBottom(sides_resized_)) {
bounds.set_height(std::max(bounds_at_start_.height() +
mouse_location.y() - mouse_location_at_start_.y(), 0));
}
if (ResizingLeft(sides_resized_)) {
bounds.set_width(std::max(bounds_at_start_.width() +
mouse_location_at_start_.x() - mouse_location.x(), 0));
}
if (ResizingTop(sides_resized_)) {
int new_height = std::max(bounds_at_start_.height() +
mouse_location_at_start_.y() - mouse_location.y(), 0);
int new_y = bounds_at_start_.bottom() - new_height;
// If the mouse is within the main screen area, make sure that the top
// border of panel cannot go outside the work area. This is to prevent
// panel's titlebar from being resized under the taskbar or OSX menu bar
// that is aligned to top screen edge.
int display_area_top_position = panel_manager_->display_area().y();
if (panel_manager_->display_settings_provider()->
GetPrimaryScreenArea().Contains(mouse_location) &&
new_y < display_area_top_position) {
new_height -= display_area_top_position - new_y;
}
bounds.set_height(new_height);
}
resizing_panel_->IncreaseMaxSize(bounds.size());
// This effectively only clamps using the min size, since the max_size was
// updated above.
bounds.set_size(resizing_panel_->ClampSize(bounds.size()));
if (ResizingLeft(sides_resized_))
bounds.set_x(bounds_at_start_.right() - bounds.width());
if (ResizingTop(sides_resized_))
bounds.set_y(bounds_at_start_.bottom() - bounds.height());
if (bounds != resizing_panel_->GetBounds())
resizing_panel_->OnWindowResizedByMouse(bounds);
}
Panel* PanelResizeController::EndResizing(bool cancelled) {
DCHECK(IsResizing());
if (cancelled)
resizing_panel_->OnWindowResizedByMouse(bounds_at_start_);
// Do a thorough cleanup.
resizing_panel_->OnPanelEndUserResizing();
Panel* resized_panel = resizing_panel_;
resizing_panel_ = NULL;
sides_resized_ = panel::RESIZE_NONE;
bounds_at_start_ = gfx::Rect();
mouse_location_at_start_ = gfx::Point();
return resized_panel;
}
void PanelResizeController::OnPanelClosed(Panel* panel) {
if (!resizing_panel_)
return;
// If the resizing panel is closed, abort the resize operation.
if (resizing_panel_ == panel)
EndResizing(false);
}
|
Java
|
/* $OpenBSD: limits.h,v 1.5 1998/03/22 21:15:24 millert Exp $ */
/* $NetBSD: limits.h,v 1.7 1996/01/05 18:10:57 pk Exp $ */
/*
* Copyright (c) 1988 The Regents of the University of California.
* All rights reserved.
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)limits.h 8.3 (Berkeley) 1/4/94
*/
#define CHAR_BIT 8 /* number of bits in a char */
#define MB_LEN_MAX 1 /* no multibyte characters */
#define SCHAR_MIN (-0x7f-1) /* max value for a signed char */
#define SCHAR_MAX 0x7f /* min value for a signed char */
#define UCHAR_MAX 0xffU /* max value for an unsigned char */
#define CHAR_MAX 0x7f /* max value for a char */
#define CHAR_MIN (-0x7f-1) /* min value for a char */
#define USHRT_MAX 0xffffU /* max value for an unsigned short */
#define SHRT_MAX 0x7fff /* max value for a short */
#define SHRT_MIN (-0x7fff-1) /* min value for a short */
#define UINT_MAX 0xffffffffU /* max value for an unsigned int */
#define INT_MAX 0x7fffffff /* max value for an int */
#define INT_MIN (-0x7fffffff-1) /* min value for an int */
#define ULONG_MAX 0xffffffffUL /* max value for an unsigned long */
#define LONG_MAX 0x7fffffffL /* max value for a long */
#define LONG_MIN (-0x7fffffffL-1) /* min value for a long */
#if !defined(_ANSI_SOURCE)
#define SSIZE_MAX INT_MAX /* max value for a ssize_t */
#if !defined(_POSIX_SOURCE) && !defined(_XOPEN_SOURCE)
#define SIZE_T_MAX UINT_MAX /* max value for a size_t */
#define UID_MAX UINT_MAX /* max value for a uid_t */
#define GID_MAX UINT_MAX /* max value for a gid_t */
/* GCC requires that quad constants be written as expressions. */
#define UQUAD_MAX ((u_quad_t)0-1) /* max value for a uquad_t */
/* max value for a quad_t */
#define QUAD_MAX ((quad_t)(UQUAD_MAX >> 1))
#define QUAD_MIN (-QUAD_MAX-1) /* min value for a quad_t */
#endif /* !_POSIX_SOURCE && !_XOPEN_SOURCE */
#endif /* !_ANSI_SOURCE */
#if (!defined(_ANSI_SOURCE)&&!defined(_POSIX_SOURCE)) || defined(_XOPEN_SOURCE)
#define LONG_BIT 32
#define WORD_BIT 32
#define DBL_DIG 15
#define DBL_MAX 1.7976931348623157E+308
#define DBL_MIN 2.2250738585072014E-308
#define FLT_DIG 6
#define FLT_MAX 3.40282347E+38F
#define FLT_MIN 1.17549435E-38F
#endif
|
Java
|
package com.percolate.sdk.dto;
import com.fasterxml.jackson.annotation.*;
import com.percolate.sdk.interfaces.HasExtraFields;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@SuppressWarnings("UnusedDeclaration")
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonInclude(JsonInclude.Include.NON_NULL)
public class FacebookConversationMessage implements Serializable, HasExtraFields {
private static final long serialVersionUID = -7978616001157824820L;
@JsonIgnore
public List<FacebookConversationMessage> extraMessages = new ArrayList<>(); // Set by client to group messages happening around the same time
@JsonIgnore
public String stickerUrl; //Set by client. If message is empty, ApiGetFacebookMessage is used to check for images/stickers.
@JsonIgnore
public List<FacebookMessageAttachment> attachments; //Set by client after calling ApiGetFacebookMessage.
@JsonIgnore
public Flag flag; //Set by client after calling ApiGetFlags
@JsonProperty("id")
protected String id;
@JsonProperty("conversation_id")
protected String conversationId;
@JsonProperty("from")
protected FacebookUser from;
// ApiGetFacebookConversations API returns "from"
// ApiGetFlag API returns "from_user"
// The setter method for this value sets <code>from</code> field.
@JsonProperty("from_user")
protected FacebookUser tempFromUser;
@JsonProperty("created_at")
protected String createdAt;
@JsonProperty("has_attachments")
protected Boolean hasAttachments;
@JsonProperty("message")
protected String message;
@JsonIgnore
protected Map<String, Object> extraFields = new HashMap<>();
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getConversationId() {
return conversationId;
}
public void setConversationId(String conversationId) {
this.conversationId = conversationId;
}
public FacebookUser getFrom() {
return from;
}
public void setFrom(FacebookUser from) {
this.from = from;
}
public void setTempFromUser(FacebookUser from) {
this.tempFromUser = from;
this.from = from;
}
public FacebookUser getTempFromUser() {
return tempFromUser;
}
public String getCreatedAt() {
return createdAt;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public Boolean getHasAttachments() {
return hasAttachments;
}
public void setHasAttachments(Boolean hasAttachments) {
this.hasAttachments = hasAttachments;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public Map<String, Object> getExtraFields() {
if(extraFields == null) {
extraFields = new HashMap<>();
}
return extraFields;
}
@Override
@JsonAnySetter
public void putExtraField(String key, Object value) {
getExtraFields().put(key, value);
}
}
|
Java
|
<?php
use yii\helpers\Html;
use kartik\grid\GridView;
use yii\helpers\ArrayHelper;
use backend\modules\qtn\models\Survey;
/* @var $this yii\web\View */
/* @var $searchModel backend\modules\qtn\Models\SurveySearch */
/* @var $dataProvider yii\data\ActiveDataProvider */
$this->title = 'Qtn Surveys';
$this->params['breadcrumbs'][] = $this->title;
?>
<div class="qtn-survey-index">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Qtn Survey', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?= GridView::widget([
'dataProvider' => $dataProvider,
// 'filterModel' => $searchModel,
'showPageSummary'=>true,
'pjax'=>true,
'striped'=>true,
'hover'=>true,
'panel'=>['type'=>'primary', 'heading'=>'Grid Grouping Example'],
'columns' => [
['class'=>'kartik\grid\SerialColumn'],
[
'attribute'=>'id',
'format' => 'raw',
'width'=>'310px',
'value'=>function ($model, $key, $index, $widget) {
$txt= $model->surveyTab->survey->name;
if($model->surveyTab->survey->status==0){
$txt .= ' '.Html::a('<span class=" glyphicon glyphicon-pencil"></span>',[ 'survey/update?id=' . $model->surveyTab->survey_id]);
}
$txt .= '___' .Html::a('<span class="glyphicon glyphicon-list-alt"></span>',[ 'survey/view?id=' .$model->surveyTab->survey_id]);
return $txt;
},
'filterInputOptions'=>['placeholder'=>'Any supplier'],
'group'=>true, // enable grouping,
'groupedRow'=>true, // move grouped column to a single grouped row
'groupOddCssClass'=>'kv-grouped-row', // configure odd group cell css class
'groupEvenCssClass'=>'kv-grouped-row', // configure even group cell css class
],
[
'attribute'=>'survey_tab_id',
'width'=>'310px',
'value'=>function ($model, $key, $index, $widget) {
return $model->surveyTab->name;
},
'group'=>true,
],
[
'attribute'=>'name',
'format' => 'raw',
'value'=>function ($data) {
$txt= $data->name;
if($data->surveyTab->survey->status==0){
$txt .= ' '.Html::a('คำถาม',[ 'survey/question?id=' . $data->surveyTab->survey_id]);
//$txt .=Html::a('table',[ 'survey/choice-title?id=' . $data->id]);
}
return $txt;
},
],
],
]); ?>
</div>
|
Java
|
@echo off
rem
rem Collective Knowledge
rem
rem See CK LICENSE.txt for licensing details.
rem See CK Copyright.txt for copyright details.
rem
rem Developer: Grigori Fursin
rem
rem CK entry point
rem Set default path by detecting the path to this script
set ck_path=%~dp0\..
rem Check if CK_ROOT is defined and used it, otherwise use auto-detected path
IF "%CK_ROOT%"=="" set CK_ROOT=%ck_path%
rem Load kernel module
IF EXIST %CK_ROOT%\ck\kernel.py (
python -W ignore::DeprecationWarning %CK_ROOT%\ck\kernel.py %*
) ELSE (
echo cK Error: kernel module not found!
)
|
Java
|
Bool_t SetGeneratedSmearingHistos = kFALSE;
Bool_t GetCentralityFromAlien = kFALSE;
std::string centralityFilename = "";
std::string centralityFilenameFromAlien = "/alice/cern.ch/user/a/acapon/.root";
const Int_t triggerNames = AliVEvent::kINT7;
const Int_t nMCSignal = 0;
const Int_t nCutsetting = 0;
const Double_t minGenPt = 0.05;
const Double_t maxGenPt = 20;
const Double_t minGenEta = -1.5;
const Double_t maxGenEta = 1.5;
const Double_t minPtCut = 0.2;
const Double_t maxPtCut = 15.0;
const Double_t minEtaCut = -0.8;
const Double_t maxEtaCut = 0.8;
// const Double_t minPtCut = 0.2;
// const Double_t maxPtCut = 8.0;
// const Double_t minEtaCut = -0.8;
// const Double_t maxEtaCut = 0.8;
// binning of single leg histograms
Bool_t usePtVector = kTRUE;
Double_t ptBins[] = {0.00,0.05,0.10,0.15,0.20,0.25,0.30,0.35,0.40,
0.45,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.85,
0.90,0.95,1.00,1.10,1.20,1.30,1.40,1.50,1.60,
1.70,1.80,1.90,2.00,2.10,2.30,2.50,3.00,3.50,
4.00,5.00,6.00,7.00,8.00,10.0,15.0};
const Int_t nBinsPt = ( sizeof(ptBins) / sizeof(ptBins[0]) )-1;
const Double_t minPtBin = 0;
const Double_t maxPtBin = 20;
const Int_t stepsPtBin = 800;
const Double_t minEtaBin = -1.0;
const Double_t maxEtaBin = 1.0;
const Int_t stepsEtaBin = 20;
const Double_t minPhiBin = 0;
const Double_t maxPhiBin = 6.3;
const Int_t stepsPhiBin = 20;
const Double_t minThetaBin = 0;
const Double_t maxThetaBin = TMath::TwoPi();
const Int_t stepsThetaBin = 60;
const Double_t minMassBin = 0;
const Double_t maxMassBin = 5;
const Int_t stepsMassBin = 500;
const Double_t minPairPtBin = 0;
const Double_t maxPairPtBin = 10;
const Int_t stepsPairPtBin = 100;
// Binning of resolution histograms
const Int_t NbinsDeltaMom = 2000;
const Double_t DeltaMomMin = -10.0;
const Double_t DeltaMomMax = 10.0;
const Int_t NbinsRelMom = 400;
const Double_t RelMomMin = 0.0;
const Double_t RelMomMax = 2.0;
const Int_t NbinsDeltaEta = 200;
const Double_t DeltaEtaMin = -0.4;
const Double_t DeltaEtaMax = 0.4;
const Int_t NbinsDeltaTheta = 200;
const Double_t DeltaThetaMin = -0.4;
const Double_t DeltaThetaMax = 0.4;
const Int_t NbinsDeltaPhi = 200;
const Double_t DeltaPhiMin = -0.4;
const Double_t DeltaPhiMax = 0.4;
void GetCentrality(const Int_t centrality, Double_t& CentMin, Double_t& CentMax){
std::cout << "GetCentrality with centrality " << centrality << std::endl;
if (centrality == 0){CentMin = 0; CentMax = 100;}
else if(centrality == 1){CentMin = 0; CentMax = 20;}
else if(centrality == 2){CentMin = 20; CentMax = 40;}
else if(centrality == 3){CentMin = 40; CentMax = 60;}
else if(centrality == 4){CentMin = 60; CentMax = 100;}
else if(centrality == 5){CentMin = 60; CentMax = 80;}
else if(centrality == 6){CentMin = 80; CentMax = 100;}
else if(centrality == 7){CentMin = 0; CentMax = 5;}
else if(centrality == 8){CentMin = -1; CentMax = -1;}
else {std::cout << "WARNING::Centrality range not found....." std::endl;}
return;
}
void ApplyPIDpostCalibration(AliAnalysisTaskElectronEfficiencyV2* task, Int_t whichDet, Bool_t wSDD){
std::cout << task << std::endl;
std::cout << "starting ApplyPIDpostCalibration()\n";
if(whichDet == 0 && wSDD){// ITS
std::cout << "Loading ITS correction" << std::endl;
TString localPath = "/home/aaron/Data/diElec_framework_output/PIDcalibration/";
TString fileName = "outputITS_MC.root";
TFile* inFile = TFile::Open(localPath+fileName);
if(!inFile){
gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" .");
std::cout << "Copy ITS correction from Alien" << std::endl;
inFile = TFile::Open(fileName);
}
else {
std::cout << "Correction loaded" << std::endl;
}
TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction"));
TH3D* width= dynamic_cast<TH3D*>(inFile->Get("sum_width_correction"));
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kITS, mean, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
task->SetWidthCorrFunction (AliAnalysisTaskElectronEfficiencyV2::kITS, width, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
}
if(whichDet == 1){// TOF
std::cout << "Loading TOF correction" << std::endl;
TString localPath = "/home/aaron/Data/diElec_framework_output/PIDcalibration/";
TString fileName = "outputTOF";
if(wSDD == kTRUE){
fileName.Append("_MC.root");
}else{
fileName.Append("_woSDD_MC.root");
}
TFile* inFile = TFile::Open(localPath+fileName);
if(!inFile){
gSystem->Exec("alien_cp alien:///alice/cern.ch/user/a/acapon/PIDcalibration/"+fileName+" .");
std::cout << "Copy TOF correction from Alien" << std::endl;
inFile = TFile::Open(fileName);
}
else {
std::cout << "Correction loaded" << std::endl;
}
TH3D* mean = dynamic_cast<TH3D*>(inFile->Get("sum_mean_correction"));
TH3D* width= dynamic_cast<TH3D*>(inFile->Get("sum_width_correction"));
task->SetCentroidCorrFunction(AliAnalysisTaskElectronEfficiencyV2::kTOF, mean, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
task->SetWidthCorrFunction (AliAnalysisTaskElectronEfficiencyV2::kTOF, width, AliDielectronVarManager::kP, AliDielectronVarManager::kEta, AliDielectronVarManager::kRefMultTPConly);
}
}
// #########################################################
// #########################################################
AliAnalysisFilter* SetupTrackCutsAndSettings(TString cutDefinition, Bool_t wSDD)
{
std::cout << "SetupTrackCutsAndSettings( cutInstance = " << cutDefinition << " )" <<std::endl;
AliAnalysisFilter *anaFilter = new AliAnalysisFilter("anaFilter","anaFilter"); // named constructor seems mandatory!
LMEECutLib* LMcutlib = new LMEECutLib(wSDD);
if(cutDefinition == "kResolutionCuts"){
std::cout << "Resolution Track Cuts being set" << std::endl;
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kResolutionTrackCuts, LMEECutLib::kResolutionTrackCuts));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutSet1"){ //TMVA
std::cout << "Setting up cut set 1" << std::endl;
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kCutSet1));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kTheoPID"){ // PID cut set from a Run 1 pPb analysis. Standard track cuts
std::cout << "Setting up Theo PID. Standard track cuts." << std::endl;
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kTheoPID));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kScheidCuts"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kScheidCuts, LMEECutLib::kScheidCuts));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
// ######## PID Cut variation settings #################
// These variations use the kCutSet1 track cuts and only vary PID
else if(cutDefinition == "kPIDcut1"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut1));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut2"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut2));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut3"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut3));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut4"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut4));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut5"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut5));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut6"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut6));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut7"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut7));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut8"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut8));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut9"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut9));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut10"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut10));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut11"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut11));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut12"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut12));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut13"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut13));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut14"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut14));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut15"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut15));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut16"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut16));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut17"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut17));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut18"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut18));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut19"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut19));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kPIDcut20"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutSet1, LMEECutLib::kPIDcut20));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
// ######## Track+ePID Cut variation settings #################
else if(cutDefinition == "kCutVar1"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar1, LMEECutLib::kCutVar1));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar2"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar2, LMEECutLib::kCutVar2));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar3"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar3, LMEECutLib::kCutVar3));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar4"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar4, LMEECutLib::kCutVar4));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar5"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar5, LMEECutLib::kCutVar5));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar6"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar6, LMEECutLib::kCutVar6));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar7"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar7, LMEECutLib::kCutVar7));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar8"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar8, LMEECutLib::kCutVar8));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar9"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar9, LMEECutLib::kCutVar9));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar10"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar10, LMEECutLib::kCutVar10));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar11"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar11, LMEECutLib::kCutVar11));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar12"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar12, LMEECutLib::kCutVar12));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar13"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar13, LMEECutLib::kCutVar13));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar14"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar14, LMEECutLib::kCutVar14));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar15"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar15, LMEECutLib::kCutVar15));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar16"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar16, LMEECutLib::kCutVar16));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar17"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar17, LMEECutLib::kCutVar17));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar18"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar18, LMEECutLib::kCutVar18));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar19"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar19, LMEECutLib::kCutVar19));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else if(cutDefinition == "kCutVar20"){
anaFilter->AddCuts(LMcutlib->GetTrackCuts(LMEECutLib::kCutVar20, LMEECutLib::kCutVar20));
anaFilter->SetName(cutDefinition);
anaFilter->Print();
}
else{
std::cout << "Undefined cut definition...." << std::endl;
return 0x0;
}
return anaFilter;
}
// #########################################################
// #########################################################
std::vector<Bool_t> AddSingleLegMCSignal(AliAnalysisTaskElectronEfficiencyV2* task){
// SetLegPDGs() requires two pdg codes. For single tracks a dummy value is
// passed, "1".
// All final state electrons (excluding conversion electrons)
AliDielectronSignalMC eleFinalState("eleFinalState","eleFinalState");
eleFinalState.SetLegPDGs(11,1);
eleFinalState.SetCheckBothChargesLegs(kTRUE,kTRUE);
eleFinalState.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
eleFinalState.SetMotherPDGs(22, 22, kTRUE, kTRUE); // Exclude conversion electrons
// Electrons from open charm mesons and baryons
AliDielectronSignalMC eleFinalStateFromD("eleFinalStateFromD","eleFinalStateFromD");
eleFinalStateFromD.SetLegPDGs(11,1);
eleFinalStateFromD.SetCheckBothChargesLegs(kTRUE,kTRUE);
eleFinalStateFromD.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
eleFinalStateFromD.SetMotherPDGs(402, 402);
eleFinalStateFromD.SetCheckBothChargesMothers(kTRUE,kTRUE);
// Electrons from open beauty mesons and baryons
AliDielectronSignalMC eleFinalStateFromB("eleFinalStateFromB","eleFinalStateFromB");
eleFinalStateFromB.SetLegPDGs(11,1);
eleFinalStateFromB.SetCheckBothChargesLegs(kTRUE,kTRUE);
eleFinalStateFromB.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
eleFinalStateFromB.SetMotherPDGs(502, 502);
eleFinalStateFromB.SetCheckBothChargesMothers(kTRUE,kTRUE);
// Add signals
task->AddSingleLegMCSignal(eleFinalState);
task->AddSingleLegMCSignal(eleFinalStateFromD);
task->AddSingleLegMCSignal(eleFinalStateFromB);
// This is used to get electrons not from same mother for pair efficiency.
// Needed to look at D and B meson electrons as functionality to pair those is
// not implemented in the framework. Instead, use all final start electrons
// from D or B decays for efficiency correction, for example.
// The ordering must match the ordering of the added signals above*.
std::vector<Bool_t> DielectronsPairNotFromSameMother;
DielectronsPairNotFromSameMother.push_back(kFALSE);
DielectronsPairNotFromSameMother.push_back(kTRUE);
DielectronsPairNotFromSameMother.push_back(kTRUE);
return DielectronsPairNotFromSameMother;
}
// #########################################################
// #########################################################
void AddPairMCSignal(AliAnalysisTaskElectronEfficiencyV2* task){
// Dielectron pairs from same mother (excluding conversions)
AliDielectronSignalMC pair_sameMother("sameMother","sameMother");
pair_sameMother.SetLegPDGs(11,-11);
pair_sameMother.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother.SetMotherPDGs(22,22,kTRUE,kTRUE); // Exclude conversion
//###################################################################
// Signals for specific dielectron decay channels
AliDielectronSignalMC pair_sameMother_pion("sameMother_pion","sameMother_pion");
pair_sameMother_pion.SetLegPDGs(11,-11);
pair_sameMother_pion.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_pion.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_pion.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_pion.SetMotherPDGs(111,111);
AliDielectronSignalMC pair_sameMother_eta("sameMother_eta","sameMother_eta");
pair_sameMother_eta.SetLegPDGs(11,-11);
pair_sameMother_eta.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_eta.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_eta.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_eta.SetMotherPDGs(221,221);
AliDielectronSignalMC pair_sameMother_etaP("sameMother_etaP","sameMother_etaP");
pair_sameMother_etaP.SetLegPDGs(11,-11);
pair_sameMother_etaP.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_etaP.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_etaP.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_etaP.SetMotherPDGs(331,331);
AliDielectronSignalMC pair_sameMother_rho("sameMother_rho","sameMother_rho");
pair_sameMother_rho.SetLegPDGs(11,-11);
pair_sameMother_rho.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_rho.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_rho.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_rho.SetMotherPDGs(113, 113);
AliDielectronSignalMC pair_sameMother_omega("sameMother_omega","sameMother_omega");
pair_sameMother_omega.SetLegPDGs(11,-11);
pair_sameMother_omega.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_omega.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_omega.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_omega.SetMotherPDGs(223, 223);
AliDielectronSignalMC pair_sameMother_phi("sameMother_phi","sameMother_phi");
pair_sameMother_phi.SetLegPDGs(11,-11);
pair_sameMother_phi.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_phi.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_phi.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_phi.SetMotherPDGs(333, 333);
AliDielectronSignalMC pair_sameMother_jpsi("sameMother_jpsi","sameMother_jpsi");
pair_sameMother_jpsi.SetLegPDGs(11,-11);
pair_sameMother_jpsi.SetCheckBothChargesLegs(kTRUE,kTRUE);
pair_sameMother_jpsi.SetLegSources(AliDielectronSignalMC::kFinalState, AliDielectronSignalMC::kFinalState);
// Set mother properties
pair_sameMother_jpsi.SetMothersRelation(AliDielectronSignalMC::kSame);
pair_sameMother_jpsi.SetMotherPDGs(443, 443);
task->AddPairMCSignal(pair_sameMother);
// task->AddPairMCSignal(pair_sameMother_pion);
// task->AddPairMCSignal(pair_sameMother_eta);
// task->AddPairMCSignal(pair_sameMother_etaP);
// task->AddPairMCSignal(pair_sameMother_rho);
// task->AddPairMCSignal(pair_sameMother_omega);
// task->AddPairMCSignal(pair_sameMother_phi);
// task->AddPairMCSignal(pair_sameMother_jpsi);
}
|
Java
|
<?php
/*
Copyright (c) 2007, Till Brehm, projektfarm Gmbh
All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
* 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.
* Neither the name of THConfig 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 OWNER 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.
*/
/******************************************
* Begin Form configuration
******************************************/
$list_def_file = "list/web_aliasdomain.list.php";
$tform_def_file = "form/web_aliasdomain.tform.php";
/******************************************
* End Form configuration
******************************************/
require_once('../../lib/config.inc.php');
require_once('../../lib/app.inc.php');
//* Check permissions for module
$app->auth->check_module_permissions('sites');
$app->uses("tform_actions");
$app->tform_actions->onDelete();
?>
|
Java
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/renderer_preferences_util.h"
#include <stdint.h>
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_util.h"
#include "build/build_config.h"
#include "build/chromeos_buildflags.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/net/convert_explicitly_allowed_network_ports_pref.h"
#if BUILDFLAG(IS_CHROMEOS_ASH)
#include "chrome/browser/ash/login/demo_mode/demo_session.h"
#endif
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/pref_names.h"
#include "components/language/core/browser/language_prefs.h"
#include "components/language/core/browser/pref_names.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/browser_accessibility_state.h"
#include "content/public/browser/renderer_preferences_util.h"
#include "media/media_buildflags.h"
#include "third_party/blink/public/common/peerconnection/webrtc_ip_handling_policy.h"
#include "third_party/blink/public/common/renderer_preferences/renderer_preferences.h"
#include "third_party/blink/public/public_buildflags.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/ui_base_features.h"
#if defined(TOOLKIT_VIEWS)
#include "ui/views/controls/textfield/textfield.h"
#endif
#if defined(OS_MAC)
#include "ui/base/cocoa/defaults_utils.h"
#endif
#if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
#include "chrome/browser/themes/theme_service.h"
#include "chrome/browser/themes/theme_service_factory.h"
#include "ui/views/linux_ui/linux_ui.h"
#endif
#include "content/nw/src/common/nw_content_common_hooks.h"
namespace {
// Parses a string |range| with a port range in the form "<min>-<max>".
// If |range| is not in the correct format or contains an invalid range, zero
// is written to |min_port| and |max_port|.
// TODO(guidou): Consider replacing with remoting/protocol/port_range.cc
void ParsePortRange(const std::string& range,
uint16_t* min_port,
uint16_t* max_port) {
*min_port = 0;
*max_port = 0;
if (range.empty())
return;
size_t separator_index = range.find('-');
if (separator_index == std::string::npos)
return;
std::string min_port_string, max_port_string;
base::TrimWhitespaceASCII(range.substr(0, separator_index), base::TRIM_ALL,
&min_port_string);
base::TrimWhitespaceASCII(range.substr(separator_index + 1), base::TRIM_ALL,
&max_port_string);
unsigned min_port_uint, max_port_uint;
if (!base::StringToUint(min_port_string, &min_port_uint) ||
!base::StringToUint(max_port_string, &max_port_uint)) {
return;
}
if (min_port_uint == 0 || min_port_uint > max_port_uint ||
max_port_uint > UINT16_MAX) {
return;
}
*min_port = static_cast<uint16_t>(min_port_uint);
*max_port = static_cast<uint16_t>(max_port_uint);
}
// Extracts the string representation of URLs allowed for local IP exposure.
std::vector<std::string> GetLocalIpsAllowedUrls(
const base::ListValue* allowed_urls) {
std::vector<std::string> ret;
if (allowed_urls) {
const auto& urls = allowed_urls->GetList();
for (const auto& url : urls)
ret.push_back(url.GetString());
}
return ret;
}
std::string GetLanguageListForProfile(Profile* profile,
const std::string& language_list) {
if (profile->IsOffTheRecord()) {
// In incognito mode return only the first language.
return language::GetFirstLanguage(language_list);
}
#if BUILDFLAG(IS_CHROMEOS_ASH)
// On Chrome OS, if in demo mode, add the demo mode private language list.
if (ash::DemoSession::IsDeviceInDemoMode()) {
return language_list + "," + ash::DemoSession::GetAdditionalLanguageList();
}
#endif
return language_list;
}
} // namespace
namespace renderer_preferences_util {
void UpdateFromSystemSettings(blink::RendererPreferences* prefs,
Profile* profile) {
const PrefService* pref_service = profile->GetPrefs();
prefs->accept_languages = GetLanguageListForProfile(
profile, pref_service->GetString(language::prefs::kAcceptLanguages));
prefs->enable_referrers = pref_service->GetBoolean(prefs::kEnableReferrers);
prefs->enable_do_not_track =
pref_service->GetBoolean(prefs::kEnableDoNotTrack);
prefs->enable_encrypted_media =
pref_service->GetBoolean(prefs::kEnableEncryptedMedia);
prefs->webrtc_ip_handling_policy = std::string();
#if !defined(OS_ANDROID)
prefs->caret_browsing_enabled =
pref_service->GetBoolean(prefs::kCaretBrowsingEnabled);
content::BrowserAccessibilityState::GetInstance()->SetCaretBrowsingState(
prefs->caret_browsing_enabled);
#endif
if (prefs->webrtc_ip_handling_policy.empty()) {
prefs->webrtc_ip_handling_policy =
pref_service->GetString(prefs::kWebRTCIPHandlingPolicy);
}
std::string webrtc_udp_port_range =
pref_service->GetString(prefs::kWebRTCUDPPortRange);
ParsePortRange(webrtc_udp_port_range, &prefs->webrtc_udp_min_port,
&prefs->webrtc_udp_max_port);
const base::ListValue* allowed_urls =
pref_service->GetList(prefs::kWebRtcLocalIpsAllowedUrls);
prefs->webrtc_local_ips_allowed_urls = GetLocalIpsAllowedUrls(allowed_urls);
prefs->webrtc_allow_legacy_tls_protocols =
pref_service->GetBoolean(prefs::kWebRTCAllowLegacyTLSProtocols);
#if defined(USE_AURA)
prefs->focus_ring_color = SkColorSetRGB(0x4D, 0x90, 0xFE);
#if BUILDFLAG(IS_CHROMEOS_ASH) || BUILDFLAG(IS_CHROMEOS_LACROS)
// This color is 0x544d90fe modulated with 0xffffff.
prefs->active_selection_bg_color = SkColorSetRGB(0xCB, 0xE4, 0xFA);
prefs->active_selection_fg_color = SK_ColorBLACK;
prefs->inactive_selection_bg_color = SkColorSetRGB(0xEA, 0xEA, 0xEA);
prefs->inactive_selection_fg_color = SK_ColorBLACK;
#endif
#endif
#if defined(TOOLKIT_VIEWS)
prefs->caret_blink_interval = views::Textfield::GetCaretBlinkInterval();
#endif
#if defined(OS_MAC)
base::TimeDelta interval;
if (ui::TextInsertionCaretBlinkPeriod(&interval))
prefs->caret_blink_interval = interval;
#endif
#if defined(USE_AURA) && (defined(OS_LINUX) || BUILDFLAG(IS_CHROMEOS_LACROS))
views::LinuxUI* linux_ui = views::LinuxUI::instance();
if (linux_ui) {
if (ThemeServiceFactory::GetForProfile(profile)->UsingSystemTheme()) {
prefs->focus_ring_color = linux_ui->GetFocusRingColor();
prefs->active_selection_bg_color = linux_ui->GetActiveSelectionBgColor();
prefs->active_selection_fg_color = linux_ui->GetActiveSelectionFgColor();
prefs->inactive_selection_bg_color =
linux_ui->GetInactiveSelectionBgColor();
prefs->inactive_selection_fg_color =
linux_ui->GetInactiveSelectionFgColor();
}
// If we have a linux_ui object, set the caret blink interval regardless of
// whether we're in native theme mode.
prefs->caret_blink_interval = linux_ui->GetCursorBlinkInterval();
}
#endif
#if defined(OS_LINUX) || defined(OS_CHROMEOS) || defined(OS_ANDROID) || \
defined(OS_WIN)
content::UpdateFontRendererPreferencesFromSystemSettings(prefs);
#endif
#if !defined(OS_MAC)
prefs->plugin_fullscreen_allowed =
pref_service->GetBoolean(prefs::kFullscreenAllowed);
#endif
PrefService* local_state = g_browser_process->local_state();
if (local_state) {
prefs->allow_cross_origin_auth_prompt =
local_state->GetBoolean(prefs::kAllowCrossOriginAuthPrompt);
prefs->explicitly_allowed_network_ports =
ConvertExplicitlyAllowedNetworkPortsPref(local_state);
}
#if defined(OS_MAC)
prefs->focus_ring_color = SkColorSetRGB(0x00, 0x5F, 0xCC);
#else
prefs->focus_ring_color = SkColorSetRGB(0x10, 0x10, 0x10);
#endif
std::string user_agent;
if (nw::GetUserAgentFromManifest(&user_agent))
prefs->user_agent_override.ua_string_override = user_agent;
}
} // namespace renderer_preferences_util
|
Java
|
package net.minidev.ovh.api.price.dedicatedcloud._2014v1.sbg1a.infrastructure.filer;
import com.fasterxml.jackson.annotation.JsonProperty;
/**
* Enum of Hourlys
*/
public enum OvhHourlyEnum {
@JsonProperty("iscsi-1200-GB")
iscsi_1200_GB("iscsi-1200-GB"),
@JsonProperty("iscsi-13200g-GB")
iscsi_13200g_GB("iscsi-13200g-GB"),
@JsonProperty("iscsi-3300-GB")
iscsi_3300_GB("iscsi-3300-GB"),
@JsonProperty("iscsi-6600-GB")
iscsi_6600_GB("iscsi-6600-GB"),
@JsonProperty("iscsi-800-GB")
iscsi_800_GB("iscsi-800-GB"),
@JsonProperty("nfs-100-GB")
nfs_100_GB("nfs-100-GB"),
@JsonProperty("nfs-1200-GB")
nfs_1200_GB("nfs-1200-GB"),
@JsonProperty("nfs-13200-GB")
nfs_13200_GB("nfs-13200-GB"),
@JsonProperty("nfs-1600-GB")
nfs_1600_GB("nfs-1600-GB"),
@JsonProperty("nfs-2400-GB")
nfs_2400_GB("nfs-2400-GB"),
@JsonProperty("nfs-3300-GB")
nfs_3300_GB("nfs-3300-GB"),
@JsonProperty("nfs-6600-GB")
nfs_6600_GB("nfs-6600-GB"),
@JsonProperty("nfs-800-GB")
nfs_800_GB("nfs-800-GB");
final String value;
OvhHourlyEnum(String s) {
this.value = s;
}
public String toString() {
return this.value;
}
}
|
Java
|
<?php
/**
* Rules_Whitespace_SuperfluousWhitespaceRule.
*
* Checks that no whitespace at the end of each line and no two empty lines in the content.
*
* @package SmartyLint
* @author Umakant Patil <me@umakantpatil.com>
* @copyright 2013-15 Umakant Patil
* @license https://github.com/umakantp/SmartyLint/blob/master/LICENSE BSD Licence
* @link https://github.com/umakantp/SmartyLint
*/
class Rules_Whitespace_SuperfluousWhitespaceRule implements SmartyLint_Rule {
/**
* Returns an array of tokens this test wants to listen for.
*
* @return array
*/
public function register() {
return array('NEW_LINE');
}
/**
* Processes this rule, when one of its tokens is encountered.
*
* @param SmartyLint_File $smartylFile The file being scanned.
* @param int $stackPtr The position of the current token in
* the stack passed in $tokens.
*
* @return void
*/
public function process(SmartyLint_File $smartylFile, $stackPtr) {
$tokens = $smartylFile->getTokens();
$beforeNewLine = false;
if (isset($tokens[($stackPtr - 1)])) {
$beforeNewLine = $tokens[($stackPtr - 1)]['type'];
if ($beforeNewLine == 'TAB' || $beforeNewLine == 'SPACE') {
$smartylFile->addError('Whitespace found at end of line', $stackPtr, 'EndFile');
}
}
$newLinesFound = 1;
for ($i = ($stackPtr-1); $i >= 0; $i--) {
if (isset($tokens[$i]) && $tokens[$i]['type'] == 'NEW_LINE') {
$newLinesFound++;
} else {
break;
}
}
if ($newLinesFound > 3) {
$error = 'Found %s empty lines in a row.';
$data = array($newLinesFound);
$smartylFile->addError($error, ($stackPtr - $newLinesFound), 'EmptyLines', $data);
}
}
}
|
Java
|
<?php
App::uses('CloggyAppModel', 'Cloggy.Model');
class CloggySearchFullText extends CloggyAppModel {
public $name = 'CloggySearchFullText';
public $useTable = 'search_fulltext';
public $actsAs = array('CloggySearchFullTexIndex','CloggySearchFullTextTerm');
public function getTotal() {
return $this->find('count');
}
/**
* Do search using MysqlFullTextSearch
*
* @link http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html NATURAL SEARCH
* @link http://dev.mysql.com/doc/refman/5.0/en/fulltext-boolean.html BOOLEAN MODE
* @param string $query
* @return array
*/
public function search($query) {
//default used mode
$usedMode = __d('cloggy','Natural Search');
/*
* first try to search with natural search
* NATURAL SEARCH
*/
$data = $this->find('all',array(
'contain' => false,
'fields' => array('*','MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\') AS rating'),
'conditions' => array('MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\')'),
'order' => array('rating' => 'desc')
));
/*
* if failed or empty results then
* reset search in BOOLEAN MODE
* with operator '*' that means search
* data which contain 'query' or 'queries', etc
*/
if (empty($data)) {
//format query string
$query = $this->buildTerm($query);
/*
* begin searching data
*/
$data = $this->find('all',array(
'contain' => false,
'fields' => array('*','MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE) AS rating'),
'conditions' => array('MATCH (CloggySearchFullText.source_sentences,CloggySearchFullText.source_text) AGAINST (\''.$query.'\' IN BOOLEAN MODE)'),
'order' => array('rating' => 'desc')
));
//switch search mode
$usedMode = __d('cloggy','Boolean Mode');
}
return array(
'mode' => $usedMode,
'results' => $data
);
}
}
|
Java
|
<!DOCTYPE html>
<html>
<head>
<title>{title} - Montage Docs</title>
<link rel="stylesheet" href="/mdl/material.min.css">
<link rel="stylesheet" href="/mdl/styles.css">
<script src="/mdl/material.min.js"></script>
<link rel="stylesheet" href="https://tools-static.wmflabs.org/fontcdn/css?family=Roboto:400,200,100">
</head>
<body class="mdl-montage mdl-color--grey-100 mdl-color-text--grey-700 mdl-base">
<header class="mdl-layout__header mdl-layout__header--scroll">
<div class="mdl-layout mdl-js-layout mdl-layout--fixed-header">
<div class="mdl-layout--large-screen-only mdl-layout__header-row">
<button class="mdl-button mdl-js-button mdl-button--icon" disabled="disabled">
<img alt="Montage Logo" src="/dist/images/logo_white_fat.svg">
</button>
<h1><a href="/docs/">Montage</a>: {title}</h1>
</div>
</div>
</header>
<main class="mdl-layout__content">
<section class="section--center mdl-grid mdl-grid--no-spacing mdl-shadow--2dp">
<div class="mdl-card mdl-cell mdl-cell--12-col">
<div class="mdl-card__supporting-text mdl-grid">
<p>
<p>{?body}{body|s}{:else}Nothing to see here!{/body}</p>
</p>
</div>
</div>
</section>
</main>
</body>
</html>
|
Java
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.