repo_name
stringlengths 5
100
| path
stringlengths 4
375
| copies
stringclasses 991
values | size
stringlengths 4
7
| content
stringlengths 666
1M
| license
stringclasses 15
values |
---|---|---|---|---|---|
njase/numpy
|
numpy/polynomial/hermite.py
|
10
|
57840
|
"""
Objects for dealing with Hermite series.
This module provides a number of objects (mostly functions) useful for
dealing with Hermite series, including a `Hermite` class that
encapsulates the usual arithmetic operations. (General information
on how this module represents and works with such polynomials is in the
docstring for its "parent" sub-package, `numpy.polynomial`).
Constants
---------
- `hermdomain` -- Hermite series default domain, [-1,1].
- `hermzero` -- Hermite series that evaluates identically to 0.
- `hermone` -- Hermite series that evaluates identically to 1.
- `hermx` -- Hermite series for the identity map, ``f(x) = x``.
Arithmetic
----------
- `hermmulx` -- multiply a Hermite series in ``P_i(x)`` by ``x``.
- `hermadd` -- add two Hermite series.
- `hermsub` -- subtract one Hermite series from another.
- `hermmul` -- multiply two Hermite series.
- `hermdiv` -- divide one Hermite series by another.
- `hermval` -- evaluate a Hermite series at given points.
- `hermval2d` -- evaluate a 2D Hermite series at given points.
- `hermval3d` -- evaluate a 3D Hermite series at given points.
- `hermgrid2d` -- evaluate a 2D Hermite series on a Cartesian product.
- `hermgrid3d` -- evaluate a 3D Hermite series on a Cartesian product.
Calculus
--------
- `hermder` -- differentiate a Hermite series.
- `hermint` -- integrate a Hermite series.
Misc Functions
--------------
- `hermfromroots` -- create a Hermite series with specified roots.
- `hermroots` -- find the roots of a Hermite series.
- `hermvander` -- Vandermonde-like matrix for Hermite polynomials.
- `hermvander2d` -- Vandermonde-like matrix for 2D power series.
- `hermvander3d` -- Vandermonde-like matrix for 3D power series.
- `hermgauss` -- Gauss-Hermite quadrature, points and weights.
- `hermweight` -- Hermite weight function.
- `hermcompanion` -- symmetrized companion matrix in Hermite form.
- `hermfit` -- least-squares fit returning a Hermite series.
- `hermtrim` -- trim leading coefficients from a Hermite series.
- `hermline` -- Hermite series of given straight line.
- `herm2poly` -- convert a Hermite series to a polynomial.
- `poly2herm` -- convert a polynomial to a Hermite series.
Classes
-------
- `Hermite` -- A Hermite series class.
See also
--------
`numpy.polynomial`
"""
from __future__ import division, absolute_import, print_function
import warnings
import numpy as np
import numpy.linalg as la
from . import polyutils as pu
from ._polybase import ABCPolyBase
__all__ = [
'hermzero', 'hermone', 'hermx', 'hermdomain', 'hermline', 'hermadd',
'hermsub', 'hermmulx', 'hermmul', 'hermdiv', 'hermpow', 'hermval',
'hermder', 'hermint', 'herm2poly', 'poly2herm', 'hermfromroots',
'hermvander', 'hermfit', 'hermtrim', 'hermroots', 'Hermite',
'hermval2d', 'hermval3d', 'hermgrid2d', 'hermgrid3d', 'hermvander2d',
'hermvander3d', 'hermcompanion', 'hermgauss', 'hermweight']
hermtrim = pu.trimcoef
def poly2herm(pol):
"""
poly2herm(pol)
Convert a polynomial to a Hermite series.
Convert an array representing the coefficients of a polynomial (relative
to the "standard" basis) ordered from lowest degree to highest, to an
array of the coefficients of the equivalent Hermite series, ordered
from lowest to highest degree.
Parameters
----------
pol : array_like
1-D array containing the polynomial coefficients
Returns
-------
c : ndarray
1-D array containing the coefficients of the equivalent Hermite
series.
See Also
--------
herm2poly
Notes
-----
The easy way to do conversions between polynomial basis sets
is to use the convert method of a class instance.
Examples
--------
>>> from numpy.polynomial.hermite import poly2herm
>>> poly2herm(np.arange(4))
array([ 1. , 2.75 , 0.5 , 0.375])
"""
[pol] = pu.as_series([pol])
deg = len(pol) - 1
res = 0
for i in range(deg, -1, -1):
res = hermadd(hermmulx(res), pol[i])
return res
def herm2poly(c):
"""
Convert a Hermite series to a polynomial.
Convert an array representing the coefficients of a Hermite series,
ordered from lowest degree to highest, to an array of the coefficients
of the equivalent polynomial (relative to the "standard" basis) ordered
from lowest to highest degree.
Parameters
----------
c : array_like
1-D array containing the Hermite series coefficients, ordered
from lowest order term to highest.
Returns
-------
pol : ndarray
1-D array containing the coefficients of the equivalent polynomial
(relative to the "standard" basis) ordered from lowest order term
to highest.
See Also
--------
poly2herm
Notes
-----
The easy way to do conversions between polynomial basis sets
is to use the convert method of a class instance.
Examples
--------
>>> from numpy.polynomial.hermite import herm2poly
>>> herm2poly([ 1. , 2.75 , 0.5 , 0.375])
array([ 0., 1., 2., 3.])
"""
from .polynomial import polyadd, polysub, polymulx
[c] = pu.as_series([c])
n = len(c)
if n == 1:
return c
if n == 2:
c[1] *= 2
return c
else:
c0 = c[-2]
c1 = c[-1]
# i is the current degree of c1
for i in range(n - 1, 1, -1):
tmp = c0
c0 = polysub(c[i - 2], c1*(2*(i - 1)))
c1 = polyadd(tmp, polymulx(c1)*2)
return polyadd(c0, polymulx(c1)*2)
#
# These are constant arrays are of integer type so as to be compatible
# with the widest range of other types, such as Decimal.
#
# Hermite
hermdomain = np.array([-1, 1])
# Hermite coefficients representing zero.
hermzero = np.array([0])
# Hermite coefficients representing one.
hermone = np.array([1])
# Hermite coefficients representing the identity x.
hermx = np.array([0, 1/2])
def hermline(off, scl):
"""
Hermite series whose graph is a straight line.
Parameters
----------
off, scl : scalars
The specified line is given by ``off + scl*x``.
Returns
-------
y : ndarray
This module's representation of the Hermite series for
``off + scl*x``.
See Also
--------
polyline, chebline
Examples
--------
>>> from numpy.polynomial.hermite import hermline, hermval
>>> hermval(0,hermline(3, 2))
3.0
>>> hermval(1,hermline(3, 2))
5.0
"""
if scl != 0:
return np.array([off, scl/2])
else:
return np.array([off])
def hermfromroots(roots):
"""
Generate a Hermite series with given roots.
The function returns the coefficients of the polynomial
.. math:: p(x) = (x - r_0) * (x - r_1) * ... * (x - r_n),
in Hermite form, where the `r_n` are the roots specified in `roots`.
If a zero has multiplicity n, then it must appear in `roots` n times.
For instance, if 2 is a root of multiplicity three and 3 is a root of
multiplicity 2, then `roots` looks something like [2, 2, 2, 3, 3]. The
roots can appear in any order.
If the returned coefficients are `c`, then
.. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x)
The coefficient of the last term is not generally 1 for monic
polynomials in Hermite form.
Parameters
----------
roots : array_like
Sequence containing the roots.
Returns
-------
out : ndarray
1-D array of coefficients. If all roots are real then `out` is a
real array, if some of the roots are complex, then `out` is complex
even if all the coefficients in the result are real (see Examples
below).
See Also
--------
polyfromroots, legfromroots, lagfromroots, chebfromroots,
hermefromroots.
Examples
--------
>>> from numpy.polynomial.hermite import hermfromroots, hermval
>>> coef = hermfromroots((-1, 0, 1))
>>> hermval((-1, 0, 1), coef)
array([ 0., 0., 0.])
>>> coef = hermfromroots((-1j, 1j))
>>> hermval((-1j, 1j), coef)
array([ 0.+0.j, 0.+0.j])
"""
if len(roots) == 0:
return np.ones(1)
else:
[roots] = pu.as_series([roots], trim=False)
roots.sort()
p = [hermline(-r, 1) for r in roots]
n = len(p)
while n > 1:
m, r = divmod(n, 2)
tmp = [hermmul(p[i], p[i+m]) for i in range(m)]
if r:
tmp[0] = hermmul(tmp[0], p[-1])
p = tmp
n = m
return p[0]
def hermadd(c1, c2):
"""
Add one Hermite series to another.
Returns the sum of two Hermite series `c1` + `c2`. The arguments
are sequences of coefficients ordered from lowest order term to
highest, i.e., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the Hermite series of their sum.
See Also
--------
hermsub, hermmul, hermdiv, hermpow
Notes
-----
Unlike multiplication, division, etc., the sum of two Hermite series
is a Hermite series (without having to "reproject" the result onto
the basis set) so addition, just like that of "standard" polynomials,
is simply "component-wise."
Examples
--------
>>> from numpy.polynomial.hermite import hermadd
>>> hermadd([1, 2, 3], [1, 2, 3, 4])
array([ 2., 4., 6., 4.])
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if len(c1) > len(c2):
c1[:c2.size] += c2
ret = c1
else:
c2[:c1.size] += c1
ret = c2
return pu.trimseq(ret)
def hermsub(c1, c2):
"""
Subtract one Hermite series from another.
Returns the difference of two Hermite series `c1` - `c2`. The
sequences of coefficients are from lowest order term to highest, i.e.,
[1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Of Hermite series coefficients representing their difference.
See Also
--------
hermadd, hermmul, hermdiv, hermpow
Notes
-----
Unlike multiplication, division, etc., the difference of two Hermite
series is a Hermite series (without having to "reproject" the result
onto the basis set) so subtraction, just like that of "standard"
polynomials, is simply "component-wise."
Examples
--------
>>> from numpy.polynomial.hermite import hermsub
>>> hermsub([1, 2, 3, 4], [1, 2, 3])
array([ 0., 0., 0., 4.])
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if len(c1) > len(c2):
c1[:c2.size] -= c2
ret = c1
else:
c2 = -c2
c2[:c1.size] += c1
ret = c2
return pu.trimseq(ret)
def hermmulx(c):
"""Multiply a Hermite series by x.
Multiply the Hermite series `c` by x, where x is the independent
variable.
Parameters
----------
c : array_like
1-D array of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Array representing the result of the multiplication.
Notes
-----
The multiplication uses the recursion relationship for Hermite
polynomials in the form
.. math::
xP_i(x) = (P_{i + 1}(x)/2 + i*P_{i - 1}(x))
Examples
--------
>>> from numpy.polynomial.hermite import hermmulx
>>> hermmulx([1, 2, 3])
array([ 2. , 6.5, 1. , 1.5])
"""
# c is a trimmed copy
[c] = pu.as_series([c])
# The zero series needs special treatment
if len(c) == 1 and c[0] == 0:
return c
prd = np.empty(len(c) + 1, dtype=c.dtype)
prd[0] = c[0]*0
prd[1] = c[0]/2
for i in range(1, len(c)):
prd[i + 1] = c[i]/2
prd[i - 1] += c[i]*i
return prd
def hermmul(c1, c2):
"""
Multiply one Hermite series by another.
Returns the product of two Hermite series `c1` * `c2`. The arguments
are sequences of coefficients, from lowest order "term" to highest,
e.g., [1,2,3] represents the series ``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
out : ndarray
Of Hermite series coefficients representing their product.
See Also
--------
hermadd, hermsub, hermdiv, hermpow
Notes
-----
In general, the (polynomial) product of two C-series results in terms
that are not in the Hermite polynomial basis set. Thus, to express
the product as a Hermite series, it is necessary to "reproject" the
product onto said basis set, which may produce "unintuitive" (but
correct) results; see Examples section below.
Examples
--------
>>> from numpy.polynomial.hermite import hermmul
>>> hermmul([1, 2, 3], [0, 1, 2])
array([ 52., 29., 52., 7., 6.])
"""
# s1, s2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if len(c1) > len(c2):
c = c2
xs = c1
else:
c = c1
xs = c2
if len(c) == 1:
c0 = c[0]*xs
c1 = 0
elif len(c) == 2:
c0 = c[0]*xs
c1 = c[1]*xs
else:
nd = len(c)
c0 = c[-2]*xs
c1 = c[-1]*xs
for i in range(3, len(c) + 1):
tmp = c0
nd = nd - 1
c0 = hermsub(c[-i]*xs, c1*(2*(nd - 1)))
c1 = hermadd(tmp, hermmulx(c1)*2)
return hermadd(c0, hermmulx(c1)*2)
def hermdiv(c1, c2):
"""
Divide one Hermite series by another.
Returns the quotient-with-remainder of two Hermite series
`c1` / `c2`. The arguments are sequences of coefficients from lowest
order "term" to highest, e.g., [1,2,3] represents the series
``P_0 + 2*P_1 + 3*P_2``.
Parameters
----------
c1, c2 : array_like
1-D arrays of Hermite series coefficients ordered from low to
high.
Returns
-------
[quo, rem] : ndarrays
Of Hermite series coefficients representing the quotient and
remainder.
See Also
--------
hermadd, hermsub, hermmul, hermpow
Notes
-----
In general, the (polynomial) division of one Hermite series by another
results in quotient and remainder terms that are not in the Hermite
polynomial basis set. Thus, to express these results as a Hermite
series, it is necessary to "reproject" the results onto the Hermite
basis set, which may produce "unintuitive" (but correct) results; see
Examples section below.
Examples
--------
>>> from numpy.polynomial.hermite import hermdiv
>>> hermdiv([ 52., 29., 52., 7., 6.], [0, 1, 2])
(array([ 1., 2., 3.]), array([ 0.]))
>>> hermdiv([ 54., 31., 52., 7., 6.], [0, 1, 2])
(array([ 1., 2., 3.]), array([ 2., 2.]))
>>> hermdiv([ 53., 30., 52., 7., 6.], [0, 1, 2])
(array([ 1., 2., 3.]), array([ 1., 1.]))
"""
# c1, c2 are trimmed copies
[c1, c2] = pu.as_series([c1, c2])
if c2[-1] == 0:
raise ZeroDivisionError()
lc1 = len(c1)
lc2 = len(c2)
if lc1 < lc2:
return c1[:1]*0, c1
elif lc2 == 1:
return c1/c2[-1], c1[:1]*0
else:
quo = np.empty(lc1 - lc2 + 1, dtype=c1.dtype)
rem = c1
for i in range(lc1 - lc2, - 1, -1):
p = hermmul([0]*i + [1], c2)
q = rem[-1]/p[-1]
rem = rem[:-1] - q*p[:-1]
quo[i] = q
return quo, pu.trimseq(rem)
def hermpow(c, pow, maxpower=16):
"""Raise a Hermite series to a power.
Returns the Hermite series `c` raised to the power `pow`. The
argument `c` is a sequence of coefficients ordered from low to high.
i.e., [1,2,3] is the series ``P_0 + 2*P_1 + 3*P_2.``
Parameters
----------
c : array_like
1-D array of Hermite series coefficients ordered from low to
high.
pow : integer
Power to which the series will be raised
maxpower : integer, optional
Maximum power allowed. This is mainly to limit growth of the series
to unmanageable size. Default is 16
Returns
-------
coef : ndarray
Hermite series of power.
See Also
--------
hermadd, hermsub, hermmul, hermdiv
Examples
--------
>>> from numpy.polynomial.hermite import hermpow
>>> hermpow([1, 2, 3], 2)
array([ 81., 52., 82., 12., 9.])
"""
# c is a trimmed copy
[c] = pu.as_series([c])
power = int(pow)
if power != pow or power < 0:
raise ValueError("Power must be a non-negative integer.")
elif maxpower is not None and power > maxpower:
raise ValueError("Power is too large")
elif power == 0:
return np.array([1], dtype=c.dtype)
elif power == 1:
return c
else:
# This can be made more efficient by using powers of two
# in the usual way.
prd = c
for i in range(2, power + 1):
prd = hermmul(prd, c)
return prd
def hermder(c, m=1, scl=1, axis=0):
"""
Differentiate a Hermite series.
Returns the Hermite series coefficients `c` differentiated `m` times
along `axis`. At each iteration the result is multiplied by `scl` (the
scaling factor is for use in a linear change of variable). The argument
`c` is an array of coefficients from low to high degree along each
axis, e.g., [1,2,3] represents the series ``1*H_0 + 2*H_1 + 3*H_2``
while [[1,2],[1,2]] represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) +
2*H_0(x)*H_1(y) + 2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is
``y``.
Parameters
----------
c : array_like
Array of Hermite series coefficients. If `c` is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Number of derivatives taken, must be non-negative. (Default: 1)
scl : scalar, optional
Each differentiation is multiplied by `scl`. The end result is
multiplication by ``scl**m``. This is for use in a linear change of
variable. (Default: 1)
axis : int, optional
Axis over which the derivative is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
der : ndarray
Hermite series of the derivative.
See Also
--------
hermint
Notes
-----
In general, the result of differentiating a Hermite series does not
resemble the same operation on a power series. Thus the result of this
function may be "unintuitive," albeit correct; see Examples section
below.
Examples
--------
>>> from numpy.polynomial.hermite import hermder
>>> hermder([ 1. , 0.5, 0.5, 0.5])
array([ 1., 2., 3.])
>>> hermder([-0.5, 1./2., 1./8., 1./12., 1./16.], m=2)
array([ 1., 2., 3.])
"""
c = np.array(c, ndmin=1, copy=1)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
cnt, iaxis = [int(t) for t in [m, axis]]
if cnt != m:
raise ValueError("The order of derivation must be integer")
if cnt < 0:
raise ValueError("The order of derivation must be non-negative")
if iaxis != axis:
raise ValueError("The axis must be integer")
if not -c.ndim <= iaxis < c.ndim:
raise ValueError("The axis is out of range")
if iaxis < 0:
iaxis += c.ndim
if cnt == 0:
return c
c = np.rollaxis(c, iaxis)
n = len(c)
if cnt >= n:
c = c[:1]*0
else:
for i in range(cnt):
n = n - 1
c *= scl
der = np.empty((n,) + c.shape[1:], dtype=c.dtype)
for j in range(n, 0, -1):
der[j - 1] = (2*j)*c[j]
c = der
c = np.rollaxis(c, 0, iaxis + 1)
return c
def hermint(c, m=1, k=[], lbnd=0, scl=1, axis=0):
"""
Integrate a Hermite series.
Returns the Hermite series coefficients `c` integrated `m` times from
`lbnd` along `axis`. At each iteration the resulting series is
**multiplied** by `scl` and an integration constant, `k`, is added.
The scaling factor is for use in a linear change of variable. ("Buyer
beware": note that, depending on what one is doing, one may want `scl`
to be the reciprocal of what one might expect; for more information,
see the Notes section below.) The argument `c` is an array of
coefficients from low to high degree along each axis, e.g., [1,2,3]
represents the series ``H_0 + 2*H_1 + 3*H_2`` while [[1,2],[1,2]]
represents ``1*H_0(x)*H_0(y) + 1*H_1(x)*H_0(y) + 2*H_0(x)*H_1(y) +
2*H_1(x)*H_1(y)`` if axis=0 is ``x`` and axis=1 is ``y``.
Parameters
----------
c : array_like
Array of Hermite series coefficients. If c is multidimensional the
different axis correspond to different variables with the degree in
each axis given by the corresponding index.
m : int, optional
Order of integration, must be positive. (Default: 1)
k : {[], list, scalar}, optional
Integration constant(s). The value of the first integral at
``lbnd`` is the first value in the list, the value of the second
integral at ``lbnd`` is the second value, etc. If ``k == []`` (the
default), all constants are set to zero. If ``m == 1``, a single
scalar can be given instead of a list.
lbnd : scalar, optional
The lower bound of the integral. (Default: 0)
scl : scalar, optional
Following each integration the result is *multiplied* by `scl`
before the integration constant is added. (Default: 1)
axis : int, optional
Axis over which the integral is taken. (Default: 0).
.. versionadded:: 1.7.0
Returns
-------
S : ndarray
Hermite series coefficients of the integral.
Raises
------
ValueError
If ``m < 0``, ``len(k) > m``, ``np.isscalar(lbnd) == False``, or
``np.isscalar(scl) == False``.
See Also
--------
hermder
Notes
-----
Note that the result of each integration is *multiplied* by `scl`.
Why is this important to note? Say one is making a linear change of
variable :math:`u = ax + b` in an integral relative to `x`. Then
.. math::`dx = du/a`, so one will need to set `scl` equal to
:math:`1/a` - perhaps not what one would have first thought.
Also note that, in general, the result of integrating a C-series needs
to be "reprojected" onto the C-series basis set. Thus, typically,
the result of this function is "unintuitive," albeit correct; see
Examples section below.
Examples
--------
>>> from numpy.polynomial.hermite import hermint
>>> hermint([1,2,3]) # integrate once, value 0 at 0.
array([ 1. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], m=2) # integrate twice, value & deriv 0 at 0
array([-0.5 , 0.5 , 0.125 , 0.08333333, 0.0625 ])
>>> hermint([1,2,3], k=1) # integrate once, value 1 at 0.
array([ 2. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], lbnd=-1) # integrate once, value 0 at -1
array([-2. , 0.5, 0.5, 0.5])
>>> hermint([1,2,3], m=2, k=[1,2], lbnd=-1)
array([ 1.66666667, -0.5 , 0.125 , 0.08333333, 0.0625 ])
"""
c = np.array(c, ndmin=1, copy=1)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if not np.iterable(k):
k = [k]
cnt, iaxis = [int(t) for t in [m, axis]]
if cnt != m:
raise ValueError("The order of integration must be integer")
if cnt < 0:
raise ValueError("The order of integration must be non-negative")
if len(k) > cnt:
raise ValueError("Too many integration constants")
if iaxis != axis:
raise ValueError("The axis must be integer")
if not -c.ndim <= iaxis < c.ndim:
raise ValueError("The axis is out of range")
if iaxis < 0:
iaxis += c.ndim
if cnt == 0:
return c
c = np.rollaxis(c, iaxis)
k = list(k) + [0]*(cnt - len(k))
for i in range(cnt):
n = len(c)
c *= scl
if n == 1 and np.all(c[0] == 0):
c[0] += k[i]
else:
tmp = np.empty((n + 1,) + c.shape[1:], dtype=c.dtype)
tmp[0] = c[0]*0
tmp[1] = c[0]/2
for j in range(1, n):
tmp[j + 1] = c[j]/(2*(j + 1))
tmp[0] += k[i] - hermval(lbnd, tmp)
c = tmp
c = np.rollaxis(c, 0, iaxis + 1)
return c
def hermval(x, c, tensor=True):
"""
Evaluate an Hermite series at points x.
If `c` is of length `n + 1`, this function returns the value:
.. math:: p(x) = c_0 * H_0(x) + c_1 * H_1(x) + ... + c_n * H_n(x)
The parameter `x` is converted to an array only if it is a tuple or a
list, otherwise it is treated as a scalar. In either case, either `x`
or its elements must support multiplication and addition both with
themselves and with the elements of `c`.
If `c` is a 1-D array, then `p(x)` will have the same shape as `x`. If
`c` is multidimensional, then the shape of the result depends on the
value of `tensor`. If `tensor` is true the shape will be c.shape[1:] +
x.shape. If `tensor` is false the shape will be c.shape[1:]. Note that
scalars have shape (,).
Trailing zeros in the coefficients will be used in the evaluation, so
they should be avoided if efficiency is a concern.
Parameters
----------
x : array_like, compatible object
If `x` is a list or tuple, it is converted to an ndarray, otherwise
it is left unchanged and treated as a scalar. In either case, `x`
or its elements must support addition and multiplication with
with themselves and with the elements of `c`.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree n are contained in c[n]. If `c` is multidimensional the
remaining indices enumerate multiple polynomials. In the two
dimensional case the coefficients may be thought of as stored in
the columns of `c`.
tensor : boolean, optional
If True, the shape of the coefficient array is extended with ones
on the right, one for each dimension of `x`. Scalars have dimension 0
for this action. The result is that every column of coefficients in
`c` is evaluated for every element of `x`. If False, `x` is broadcast
over the columns of `c` for the evaluation. This keyword is useful
when `c` is multidimensional. The default value is True.
.. versionadded:: 1.7.0
Returns
-------
values : ndarray, algebra_like
The shape of the return value is described above.
See Also
--------
hermval2d, hermgrid2d, hermval3d, hermgrid3d
Notes
-----
The evaluation uses Clenshaw recursion, aka synthetic division.
Examples
--------
>>> from numpy.polynomial.hermite import hermval
>>> coef = [1,2,3]
>>> hermval(1, coef)
11.0
>>> hermval([[1,2],[3,4]], coef)
array([[ 11., 51.],
[ 115., 203.]])
"""
c = np.array(c, ndmin=1, copy=0)
if c.dtype.char in '?bBhHiIlLqQpP':
c = c.astype(np.double)
if isinstance(x, (tuple, list)):
x = np.asarray(x)
if isinstance(x, np.ndarray) and tensor:
c = c.reshape(c.shape + (1,)*x.ndim)
x2 = x*2
if len(c) == 1:
c0 = c[0]
c1 = 0
elif len(c) == 2:
c0 = c[0]
c1 = c[1]
else:
nd = len(c)
c0 = c[-2]
c1 = c[-1]
for i in range(3, len(c) + 1):
tmp = c0
nd = nd - 1
c0 = c[-i] - c1*(2*(nd - 1))
c1 = tmp + c1*x2
return c0 + c1*x2
def hermval2d(x, y, c):
"""
Evaluate a 2-D Hermite series at points (x, y).
This function returns the values:
.. math:: p(x,y) = \\sum_{i,j} c_{i,j} * H_i(x) * H_j(y)
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars and they
must have the same shape after conversion. In either case, either `x`
and `y` or their elements must support multiplication and addition both
with themselves and with the elements of `c`.
If `c` is a 1-D array a one is implicitly appended to its shape to make
it 2-D. The shape of the result will be c.shape[2:] + x.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points `(x, y)`,
where `x` and `y` must have the same shape. If `x` or `y` is a list
or tuple, it is first converted to an ndarray, otherwise it is left
unchanged and if it isn't an ndarray it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term
of multi-degree i,j is contained in ``c[i,j]``. If `c` has
dimension greater than two the remaining indices enumerate multiple
sets of coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points formed with
pairs of corresponding values from `x` and `y`.
See Also
--------
hermval, hermgrid2d, hermval3d, hermgrid3d
Notes
-----
.. versionadded::1.7.0
"""
try:
x, y = np.array((x, y), copy=0)
except:
raise ValueError('x, y are incompatible')
c = hermval(x, c)
c = hermval(y, c, tensor=False)
return c
def hermgrid2d(x, y, c):
"""
Evaluate a 2-D Hermite series on the Cartesian product of x and y.
This function returns the values:
.. math:: p(a,b) = \sum_{i,j} c_{i,j} * H_i(a) * H_j(b)
where the points `(a, b)` consist of all pairs formed by taking
`a` from `x` and `b` from `y`. The resulting points form a grid with
`x` in the first dimension and `y` in the second.
The parameters `x` and `y` are converted to arrays only if they are
tuples or a lists, otherwise they are treated as a scalars. In either
case, either `x` and `y` or their elements must support multiplication
and addition both with themselves and with the elements of `c`.
If `c` has fewer than two dimensions, ones are implicitly appended to
its shape to make it 2-D. The shape of the result will be c.shape[2:] +
x.shape.
Parameters
----------
x, y : array_like, compatible objects
The two dimensional series is evaluated at the points in the
Cartesian product of `x` and `y`. If `x` or `y` is a list or
tuple, it is first converted to an ndarray, otherwise it is left
unchanged and, if it isn't an ndarray, it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree i,j are contained in ``c[i,j]``. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points in the Cartesian
product of `x` and `y`.
See Also
--------
hermval, hermval2d, hermval3d, hermgrid3d
Notes
-----
.. versionadded::1.7.0
"""
c = hermval(x, c)
c = hermval(y, c)
return c
def hermval3d(x, y, z, c):
"""
Evaluate a 3-D Hermite series at points (x, y, z).
This function returns the values:
.. math:: p(x,y,z) = \\sum_{i,j,k} c_{i,j,k} * H_i(x) * H_j(y) * H_k(z)
The parameters `x`, `y`, and `z` are converted to arrays only if
they are tuples or a lists, otherwise they are treated as a scalars and
they must have the same shape after conversion. In either case, either
`x`, `y`, and `z` or their elements must support multiplication and
addition both with themselves and with the elements of `c`.
If `c` has fewer than 3 dimensions, ones are implicitly appended to its
shape to make it 3-D. The shape of the result will be c.shape[3:] +
x.shape.
Parameters
----------
x, y, z : array_like, compatible object
The three dimensional series is evaluated at the points
`(x, y, z)`, where `x`, `y`, and `z` must have the same shape. If
any of `x`, `y`, or `z` is a list or tuple, it is first converted
to an ndarray, otherwise it is left unchanged and if it isn't an
ndarray it is treated as a scalar.
c : array_like
Array of coefficients ordered so that the coefficient of the term of
multi-degree i,j,k is contained in ``c[i,j,k]``. If `c` has dimension
greater than 3 the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the multidimensional polynomial on points formed with
triples of corresponding values from `x`, `y`, and `z`.
See Also
--------
hermval, hermval2d, hermgrid2d, hermgrid3d
Notes
-----
.. versionadded::1.7.0
"""
try:
x, y, z = np.array((x, y, z), copy=0)
except:
raise ValueError('x, y, z are incompatible')
c = hermval(x, c)
c = hermval(y, c, tensor=False)
c = hermval(z, c, tensor=False)
return c
def hermgrid3d(x, y, z, c):
"""
Evaluate a 3-D Hermite series on the Cartesian product of x, y, and z.
This function returns the values:
.. math:: p(a,b,c) = \\sum_{i,j,k} c_{i,j,k} * H_i(a) * H_j(b) * H_k(c)
where the points `(a, b, c)` consist of all triples formed by taking
`a` from `x`, `b` from `y`, and `c` from `z`. The resulting points form
a grid with `x` in the first dimension, `y` in the second, and `z` in
the third.
The parameters `x`, `y`, and `z` are converted to arrays only if they
are tuples or a lists, otherwise they are treated as a scalars. In
either case, either `x`, `y`, and `z` or their elements must support
multiplication and addition both with themselves and with the elements
of `c`.
If `c` has fewer than three dimensions, ones are implicitly appended to
its shape to make it 3-D. The shape of the result will be c.shape[3:] +
x.shape + y.shape + z.shape.
Parameters
----------
x, y, z : array_like, compatible objects
The three dimensional series is evaluated at the points in the
Cartesian product of `x`, `y`, and `z`. If `x`,`y`, or `z` is a
list or tuple, it is first converted to an ndarray, otherwise it is
left unchanged and, if it isn't an ndarray, it is treated as a
scalar.
c : array_like
Array of coefficients ordered so that the coefficients for terms of
degree i,j are contained in ``c[i,j]``. If `c` has dimension
greater than two the remaining indices enumerate multiple sets of
coefficients.
Returns
-------
values : ndarray, compatible object
The values of the two dimensional polynomial at points in the Cartesian
product of `x` and `y`.
See Also
--------
hermval, hermval2d, hermgrid2d, hermval3d
Notes
-----
.. versionadded::1.7.0
"""
c = hermval(x, c)
c = hermval(y, c)
c = hermval(z, c)
return c
def hermvander(x, deg):
"""Pseudo-Vandermonde matrix of given degree.
Returns the pseudo-Vandermonde matrix of degree `deg` and sample points
`x`. The pseudo-Vandermonde matrix is defined by
.. math:: V[..., i] = H_i(x),
where `0 <= i <= deg`. The leading indices of `V` index the elements of
`x` and the last index is the degree of the Hermite polynomial.
If `c` is a 1-D array of coefficients of length `n + 1` and `V` is the
array ``V = hermvander(x, n)``, then ``np.dot(V, c)`` and
``hermval(x, c)`` are the same up to roundoff. This equivalence is
useful both for least squares fitting and for the evaluation of a large
number of Hermite series of the same degree and sample points.
Parameters
----------
x : array_like
Array of points. The dtype is converted to float64 or complex128
depending on whether any of the elements are complex. If `x` is
scalar it is converted to a 1-D array.
deg : int
Degree of the resulting matrix.
Returns
-------
vander : ndarray
The pseudo-Vandermonde matrix. The shape of the returned matrix is
``x.shape + (deg + 1,)``, where The last index is the degree of the
corresponding Hermite polynomial. The dtype will be the same as
the converted `x`.
Examples
--------
>>> from numpy.polynomial.hermite import hermvander
>>> x = np.array([-1, 0, 1])
>>> hermvander(x, 3)
array([[ 1., -2., 2., 4.],
[ 1., 0., -2., -0.],
[ 1., 2., 2., -4.]])
"""
ideg = int(deg)
if ideg != deg:
raise ValueError("deg must be integer")
if ideg < 0:
raise ValueError("deg must be non-negative")
x = np.array(x, copy=0, ndmin=1) + 0.0
dims = (ideg + 1,) + x.shape
dtyp = x.dtype
v = np.empty(dims, dtype=dtyp)
v[0] = x*0 + 1
if ideg > 0:
x2 = x*2
v[1] = x2
for i in range(2, ideg + 1):
v[i] = (v[i-1]*x2 - v[i-2]*(2*(i - 1)))
return np.rollaxis(v, 0, v.ndim)
def hermvander2d(x, y, deg):
"""Pseudo-Vandermonde matrix of given degrees.
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
points `(x, y)`. The pseudo-Vandermonde matrix is defined by
.. math:: V[..., deg[1]*i + j] = H_i(x) * H_j(y),
where `0 <= i <= deg[0]` and `0 <= j <= deg[1]`. The leading indices of
`V` index the points `(x, y)` and the last index encodes the degrees of
the Hermite polynomials.
If ``V = hermvander2d(x, y, [xdeg, ydeg])``, then the columns of `V`
correspond to the elements of a 2-D coefficient array `c` of shape
(xdeg + 1, ydeg + 1) in the order
.. math:: c_{00}, c_{01}, c_{02} ... , c_{10}, c_{11}, c_{12} ...
and ``np.dot(V, c.flat)`` and ``hermval2d(x, y, c)`` will be the same
up to roundoff. This equivalence is useful both for least squares
fitting and for the evaluation of a large number of 2-D Hermite
series of the same degrees and sample points.
Parameters
----------
x, y : array_like
Arrays of point coordinates, all of the same shape. The dtypes
will be converted to either float64 or complex128 depending on
whether any of the elements are complex. Scalars are converted to 1-D
arrays.
deg : list of ints
List of maximum degrees of the form [x_deg, y_deg].
Returns
-------
vander2d : ndarray
The shape of the returned matrix is ``x.shape + (order,)``, where
:math:`order = (deg[0]+1)*(deg([1]+1)`. The dtype will be the same
as the converted `x` and `y`.
See Also
--------
hermvander, hermvander3d. hermval2d, hermval3d
Notes
-----
.. versionadded::1.7.0
"""
ideg = [int(d) for d in deg]
is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
if is_valid != [1, 1]:
raise ValueError("degrees must be non-negative integers")
degx, degy = ideg
x, y = np.array((x, y), copy=0) + 0.0
vx = hermvander(x, degx)
vy = hermvander(y, degy)
v = vx[..., None]*vy[..., None,:]
return v.reshape(v.shape[:-2] + (-1,))
def hermvander3d(x, y, z, deg):
"""Pseudo-Vandermonde matrix of given degrees.
Returns the pseudo-Vandermonde matrix of degrees `deg` and sample
points `(x, y, z)`. If `l, m, n` are the given degrees in `x, y, z`,
then The pseudo-Vandermonde matrix is defined by
.. math:: V[..., (m+1)(n+1)i + (n+1)j + k] = H_i(x)*H_j(y)*H_k(z),
where `0 <= i <= l`, `0 <= j <= m`, and `0 <= j <= n`. The leading
indices of `V` index the points `(x, y, z)` and the last index encodes
the degrees of the Hermite polynomials.
If ``V = hermvander3d(x, y, z, [xdeg, ydeg, zdeg])``, then the columns
of `V` correspond to the elements of a 3-D coefficient array `c` of
shape (xdeg + 1, ydeg + 1, zdeg + 1) in the order
.. math:: c_{000}, c_{001}, c_{002},... , c_{010}, c_{011}, c_{012},...
and ``np.dot(V, c.flat)`` and ``hermval3d(x, y, z, c)`` will be the
same up to roundoff. This equivalence is useful both for least squares
fitting and for the evaluation of a large number of 3-D Hermite
series of the same degrees and sample points.
Parameters
----------
x, y, z : array_like
Arrays of point coordinates, all of the same shape. The dtypes will
be converted to either float64 or complex128 depending on whether
any of the elements are complex. Scalars are converted to 1-D
arrays.
deg : list of ints
List of maximum degrees of the form [x_deg, y_deg, z_deg].
Returns
-------
vander3d : ndarray
The shape of the returned matrix is ``x.shape + (order,)``, where
:math:`order = (deg[0]+1)*(deg([1]+1)*(deg[2]+1)`. The dtype will
be the same as the converted `x`, `y`, and `z`.
See Also
--------
hermvander, hermvander3d. hermval2d, hermval3d
Notes
-----
.. versionadded::1.7.0
"""
ideg = [int(d) for d in deg]
is_valid = [id == d and id >= 0 for id, d in zip(ideg, deg)]
if is_valid != [1, 1, 1]:
raise ValueError("degrees must be non-negative integers")
degx, degy, degz = ideg
x, y, z = np.array((x, y, z), copy=0) + 0.0
vx = hermvander(x, degx)
vy = hermvander(y, degy)
vz = hermvander(z, degz)
v = vx[..., None, None]*vy[..., None,:, None]*vz[..., None, None,:]
return v.reshape(v.shape[:-3] + (-1,))
def hermfit(x, y, deg, rcond=None, full=False, w=None):
"""
Least squares fit of Hermite series to data.
Return the coefficients of a Hermite series of degree `deg` that is the
least squares fit to the data values `y` given at points `x`. If `y` is
1-D the returned coefficients will also be 1-D. If `y` is 2-D multiple
fits are done, one for each column of `y`, and the resulting
coefficients are stored in the corresponding columns of a 2-D return.
The fitted polynomial(s) are in the form
.. math:: p(x) = c_0 + c_1 * H_1(x) + ... + c_n * H_n(x),
where `n` is `deg`.
Parameters
----------
x : array_like, shape (M,)
x-coordinates of the M sample points ``(x[i], y[i])``.
y : array_like, shape (M,) or (M, K)
y-coordinates of the sample points. Several data sets of sample
points sharing the same x-coordinates can be fitted at once by
passing in a 2D-array that contains one dataset per column.
deg : int or 1-D array_like
Degree(s) of the fitting polynomials. If `deg` is a single integer
all terms up to and including the `deg`'th term are included in the
fit. For NumPy versions >= 1.11.0 a list of integers specifying the
degrees of the terms to include may be used instead.
rcond : float, optional
Relative condition number of the fit. Singular values smaller than
this relative to the largest singular value will be ignored. The
default value is len(x)*eps, where eps is the relative precision of
the float type, about 2e-16 in most cases.
full : bool, optional
Switch determining nature of return value. When it is False (the
default) just the coefficients are returned, when True diagnostic
information from the singular value decomposition is also returned.
w : array_like, shape (`M`,), optional
Weights. If not None, the contribution of each point
``(x[i],y[i])`` to the fit is weighted by `w[i]`. Ideally the
weights are chosen so that the errors of the products ``w[i]*y[i]``
all have the same variance. The default value is None.
Returns
-------
coef : ndarray, shape (M,) or (M, K)
Hermite coefficients ordered from low to high. If `y` was 2-D,
the coefficients for the data in column k of `y` are in column
`k`.
[residuals, rank, singular_values, rcond] : list
These values are only returned if `full` = True
resid -- sum of squared residuals of the least squares fit
rank -- the numerical rank of the scaled Vandermonde matrix
sv -- singular values of the scaled Vandermonde matrix
rcond -- value of `rcond`.
For more details, see `linalg.lstsq`.
Warns
-----
RankWarning
The rank of the coefficient matrix in the least-squares fit is
deficient. The warning is only raised if `full` = False. The
warnings can be turned off by
>>> import warnings
>>> warnings.simplefilter('ignore', RankWarning)
See Also
--------
chebfit, legfit, lagfit, polyfit, hermefit
hermval : Evaluates a Hermite series.
hermvander : Vandermonde matrix of Hermite series.
hermweight : Hermite weight function
linalg.lstsq : Computes a least-squares fit from the matrix.
scipy.interpolate.UnivariateSpline : Computes spline fits.
Notes
-----
The solution is the coefficients of the Hermite series `p` that
minimizes the sum of the weighted squared errors
.. math:: E = \\sum_j w_j^2 * |y_j - p(x_j)|^2,
where the :math:`w_j` are the weights. This problem is solved by
setting up the (typically) overdetermined matrix equation
.. math:: V(x) * c = w * y,
where `V` is the weighted pseudo Vandermonde matrix of `x`, `c` are the
coefficients to be solved for, `w` are the weights, `y` are the
observed values. This equation is then solved using the singular value
decomposition of `V`.
If some of the singular values of `V` are so small that they are
neglected, then a `RankWarning` will be issued. This means that the
coefficient values may be poorly determined. Using a lower order fit
will usually get rid of the warning. The `rcond` parameter can also be
set to a value smaller than its default, but the resulting fit may be
spurious and have large contributions from roundoff error.
Fits using Hermite series are probably most useful when the data can be
approximated by ``sqrt(w(x)) * p(x)``, where `w(x)` is the Hermite
weight. In that case the weight ``sqrt(w(x[i])`` should be used
together with data values ``y[i]/sqrt(w(x[i])``. The weight function is
available as `hermweight`.
References
----------
.. [1] Wikipedia, "Curve fitting",
http://en.wikipedia.org/wiki/Curve_fitting
Examples
--------
>>> from numpy.polynomial.hermite import hermfit, hermval
>>> x = np.linspace(-10, 10)
>>> err = np.random.randn(len(x))/10
>>> y = hermval(x, [1, 2, 3]) + err
>>> hermfit(x, y, 2)
array([ 0.97902637, 1.99849131, 3.00006 ])
"""
x = np.asarray(x) + 0.0
y = np.asarray(y) + 0.0
deg = np.asarray(deg)
# check arguments.
if deg.ndim > 1 or deg.dtype.kind not in 'iu' or deg.size == 0:
raise TypeError("deg must be an int or non-empty 1-D array of int")
if deg.min() < 0:
raise ValueError("expected deg >= 0")
if x.ndim != 1:
raise TypeError("expected 1D vector for x")
if x.size == 0:
raise TypeError("expected non-empty vector for x")
if y.ndim < 1 or y.ndim > 2:
raise TypeError("expected 1D or 2D array for y")
if len(x) != len(y):
raise TypeError("expected x and y to have same length")
if deg.ndim == 0:
lmax = deg
order = lmax + 1
van = hermvander(x, lmax)
else:
deg = np.sort(deg)
lmax = deg[-1]
order = len(deg)
van = hermvander(x, lmax)[:, deg]
# set up the least squares matrices in transposed form
lhs = van.T
rhs = y.T
if w is not None:
w = np.asarray(w) + 0.0
if w.ndim != 1:
raise TypeError("expected 1D vector for w")
if len(x) != len(w):
raise TypeError("expected x and w to have same length")
# apply weights. Don't use inplace operations as they
# can cause problems with NA.
lhs = lhs * w
rhs = rhs * w
# set rcond
if rcond is None:
rcond = len(x)*np.finfo(x.dtype).eps
# Determine the norms of the design matrix columns.
if issubclass(lhs.dtype.type, np.complexfloating):
scl = np.sqrt((np.square(lhs.real) + np.square(lhs.imag)).sum(1))
else:
scl = np.sqrt(np.square(lhs).sum(1))
scl[scl == 0] = 1
# Solve the least squares problem.
c, resids, rank, s = la.lstsq(lhs.T/scl, rhs.T, rcond)
c = (c.T/scl).T
# Expand c to include non-fitted coefficients which are set to zero
if deg.ndim > 0:
if c.ndim == 2:
cc = np.zeros((lmax+1, c.shape[1]), dtype=c.dtype)
else:
cc = np.zeros(lmax+1, dtype=c.dtype)
cc[deg] = c
c = cc
# warn on rank reduction
if rank != order and not full:
msg = "The fit may be poorly conditioned"
warnings.warn(msg, pu.RankWarning, stacklevel=2)
if full:
return c, [resids, rank, s, rcond]
else:
return c
def hermcompanion(c):
"""Return the scaled companion matrix of c.
The basis polynomials are scaled so that the companion matrix is
symmetric when `c` is an Hermite basis polynomial. This provides
better eigenvalue estimates than the unscaled case and for basis
polynomials the eigenvalues are guaranteed to be real if
`numpy.linalg.eigvalsh` is used to obtain them.
Parameters
----------
c : array_like
1-D array of Hermite series coefficients ordered from low to high
degree.
Returns
-------
mat : ndarray
Scaled companion matrix of dimensions (deg, deg).
Notes
-----
.. versionadded::1.7.0
"""
# c is a trimmed copy
[c] = pu.as_series([c])
if len(c) < 2:
raise ValueError('Series must have maximum degree of at least 1.')
if len(c) == 2:
return np.array([[-.5*c[0]/c[1]]])
n = len(c) - 1
mat = np.zeros((n, n), dtype=c.dtype)
scl = np.hstack((1., 1./np.sqrt(2.*np.arange(n - 1, 0, -1))))
scl = np.multiply.accumulate(scl)[::-1]
top = mat.reshape(-1)[1::n+1]
bot = mat.reshape(-1)[n::n+1]
top[...] = np.sqrt(.5*np.arange(1, n))
bot[...] = top
mat[:, -1] -= scl*c[:-1]/(2.0*c[-1])
return mat
def hermroots(c):
"""
Compute the roots of a Hermite series.
Return the roots (a.k.a. "zeros") of the polynomial
.. math:: p(x) = \\sum_i c[i] * H_i(x).
Parameters
----------
c : 1-D array_like
1-D array of coefficients.
Returns
-------
out : ndarray
Array of the roots of the series. If all the roots are real,
then `out` is also real, otherwise it is complex.
See Also
--------
polyroots, legroots, lagroots, chebroots, hermeroots
Notes
-----
The root estimates are obtained as the eigenvalues of the companion
matrix, Roots far from the origin of the complex plane may have large
errors due to the numerical instability of the series for such
values. Roots with multiplicity greater than 1 will also show larger
errors as the value of the series near such points is relatively
insensitive to errors in the roots. Isolated roots near the origin can
be improved by a few iterations of Newton's method.
The Hermite series basis polynomials aren't powers of `x` so the
results of this function may seem unintuitive.
Examples
--------
>>> from numpy.polynomial.hermite import hermroots, hermfromroots
>>> coef = hermfromroots([-1, 0, 1])
>>> coef
array([ 0. , 0.25 , 0. , 0.125])
>>> hermroots(coef)
array([ -1.00000000e+00, -1.38777878e-17, 1.00000000e+00])
"""
# c is a trimmed copy
[c] = pu.as_series([c])
if len(c) <= 1:
return np.array([], dtype=c.dtype)
if len(c) == 2:
return np.array([-.5*c[0]/c[1]])
m = hermcompanion(c)
r = la.eigvals(m)
r.sort()
return r
def _normed_hermite_n(x, n):
"""
Evaluate a normalized Hermite polynomial.
Compute the value of the normalized Hermite polynomial of degree ``n``
at the points ``x``.
Parameters
----------
x : ndarray of double.
Points at which to evaluate the function
n : int
Degree of the normalized Hermite function to be evaluated.
Returns
-------
values : ndarray
The shape of the return value is described above.
Notes
-----
.. versionadded:: 1.10.0
This function is needed for finding the Gauss points and integration
weights for high degrees. The values of the standard Hermite functions
overflow when n >= 207.
"""
if n == 0:
return np.ones(x.shape)/np.sqrt(np.sqrt(np.pi))
c0 = 0.
c1 = 1./np.sqrt(np.sqrt(np.pi))
nd = float(n)
for i in range(n - 1):
tmp = c0
c0 = -c1*np.sqrt((nd - 1.)/nd)
c1 = tmp + c1*x*np.sqrt(2./nd)
nd = nd - 1.0
return c0 + c1*x*np.sqrt(2)
def hermgauss(deg):
"""
Gauss-Hermite quadrature.
Computes the sample points and weights for Gauss-Hermite quadrature.
These sample points and weights will correctly integrate polynomials of
degree :math:`2*deg - 1` or less over the interval :math:`[-\inf, \inf]`
with the weight function :math:`f(x) = \exp(-x^2)`.
Parameters
----------
deg : int
Number of sample points and weights. It must be >= 1.
Returns
-------
x : ndarray
1-D ndarray containing the sample points.
y : ndarray
1-D ndarray containing the weights.
Notes
-----
.. versionadded::1.7.0
The results have only been tested up to degree 100, higher degrees may
be problematic. The weights are determined by using the fact that
.. math:: w_k = c / (H'_n(x_k) * H_{n-1}(x_k))
where :math:`c` is a constant independent of :math:`k` and :math:`x_k`
is the k'th root of :math:`H_n`, and then scaling the results to get
the right value when integrating 1.
"""
ideg = int(deg)
if ideg != deg or ideg < 1:
raise ValueError("deg must be a non-negative integer")
# first approximation of roots. We use the fact that the companion
# matrix is symmetric in this case in order to obtain better zeros.
c = np.array([0]*deg + [1], dtype=np.float64)
m = hermcompanion(c)
x = la.eigvalsh(m)
# improve roots by one application of Newton
dy = _normed_hermite_n(x, ideg)
df = _normed_hermite_n(x, ideg - 1) * np.sqrt(2*ideg)
x -= dy/df
# compute the weights. We scale the factor to avoid possible numerical
# overflow.
fm = _normed_hermite_n(x, ideg - 1)
fm /= np.abs(fm).max()
w = 1/(fm * fm)
# for Hermite we can also symmetrize
w = (w + w[::-1])/2
x = (x - x[::-1])/2
# scale w to get the right value
w *= np.sqrt(np.pi) / w.sum()
return x, w
def hermweight(x):
"""
Weight function of the Hermite polynomials.
The weight function is :math:`\exp(-x^2)` and the interval of
integration is :math:`[-\inf, \inf]`. the Hermite polynomials are
orthogonal, but not normalized, with respect to this weight function.
Parameters
----------
x : array_like
Values at which the weight function will be computed.
Returns
-------
w : ndarray
The weight function at `x`.
Notes
-----
.. versionadded::1.7.0
"""
w = np.exp(-x**2)
return w
#
# Hermite series class
#
class Hermite(ABCPolyBase):
"""An Hermite series class.
The Hermite class provides the standard Python numerical methods
'+', '-', '*', '//', '%', 'divmod', '**', and '()' as well as the
attributes and methods listed in the `ABCPolyBase` documentation.
Parameters
----------
coef : array_like
Hermite coefficients in order of increasing degree, i.e,
``(1, 2, 3)`` gives ``1*H_0(x) + 2*H_1(X) + 3*H_2(x)``.
domain : (2,) array_like, optional
Domain to use. The interval ``[domain[0], domain[1]]`` is mapped
to the interval ``[window[0], window[1]]`` by shifting and scaling.
The default value is [-1, 1].
window : (2,) array_like, optional
Window, see `domain` for its use. The default value is [-1, 1].
.. versionadded:: 1.6.0
"""
# Virtual Functions
_add = staticmethod(hermadd)
_sub = staticmethod(hermsub)
_mul = staticmethod(hermmul)
_div = staticmethod(hermdiv)
_pow = staticmethod(hermpow)
_val = staticmethod(hermval)
_int = staticmethod(hermint)
_der = staticmethod(hermder)
_fit = staticmethod(hermfit)
_line = staticmethod(hermline)
_roots = staticmethod(hermroots)
_fromroots = staticmethod(hermfromroots)
# Virtual properties
nickname = 'herm'
domain = np.array(hermdomain)
window = np.array(hermdomain)
|
bsd-3-clause
|
RamonGuiuGou/l10n-spain
|
l10n_es_payment_order/wizard/csb58.py
|
13
|
15269
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (c) 2006 ACYSOS S.L. (http://acysos.com) All Rights Reserved.
# Pedro Tarrafeta <[email protected]>
# Ignacio Ibeas <[email protected]>
# Copyright (c) 2008 Pablo Rocandio. All Rights Reserved.
# Copyright (c) 2009 Zikzakmedia S.L. (http://zikzakmedia.com) All Rights
# Reserved.
# Jordi Esteve <[email protected]>
# Copyright (c) 2013 Serv. Tecnol. Avanzados (http://www.serviciosbaeza.com)
# Pedro M. Baeza <[email protected]>
# $Id$
#
# Corregido para instalación TinyERP estándar 4.2.0: Zikzakmedia S.L. 2008
# Jordi Esteve <[email protected]>
#
# Añadidas cuentas de remesas y tipos de pago. 2008
# Pablo Rocandio <[email protected]>
#
# Rehecho de nuevo para instalación OpenERP 5.0.0 sobre
# account_payment_extension: Zikzakmedia S.L. 2009
# Jordi Esteve <[email protected]>
#
# Refactorización. Acysos S.L. (http://www.acysos.com) 2012
# Ignacio Ibeas <[email protected]>
#
# Migración Odoo 8.0. Acysos S.L. (http://www.acysos.com) 2015
# Ignacio Ibeas <[email protected]>
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as published
# by the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp import _
from datetime import datetime
from .log import Log
from .converter import PaymentConverterSpain
class Csb58(object):
def __init__(self, env):
self.env = env
def _cabecera_presentador_58(self):
converter = PaymentConverterSpain()
texto = '5170'
texto += (self.order.mode.bank_id.partner_id.vat[2:] +
self.order.mode.csb_suffix).zfill(12)
texto += datetime.today().strftime('%d%m%y')
texto += 6*' '
texto += converter.to_ascii(
self.order.mode.bank_id.partner_id.name).ljust(40)
texto += 20*' '
cc = converter.digits_only(self.order.mode.bank_id.acc_number)
texto += cc[0:8]
texto += 66*' '
texto += '\r\n'
if len(texto) != 164:
raise Log(_('Configuration error:\n\nThe line "%s" is not 162 '
'characters long:\n%s') % ('Cabecera presentador 58',
texto), True)
return texto
def _cabecera_ordenante_58(self):
converter = PaymentConverterSpain()
texto = '5370'
texto += (self.order.mode.bank_id.partner_id.vat[2:] +
self.order.mode.csb_suffix).zfill(12)
texto += datetime.today().strftime('%d%m%y')
texto += 6*' '
texto += converter.to_ascii(
self.order.mode.bank_id.partner_id.name).ljust(40)
cc = converter.digits_only(self.order.mode.bank_id.acc_number)
texto += cc[0:20]
texto += 8*' '
texto += '06'
texto += 52*' '
texto += self.order.mode.csb58_ine and converter.to_ascii(
self.order.mode.csb58_ine)[:9].zfill(9) or 9*' '
texto += 3*' '
texto += '\r\n'
if len(texto) != 164:
raise Log(_('Configuration error:\n\nThe line "%s" is not 162 '
'characters long:\n%s') % ('Cabecera ordenante 58',
texto), True)
return texto
def _individual_obligatorio_58(self, recibo):
converter = PaymentConverterSpain()
texto = '5670'
texto += (self.order.mode.bank_id.partner_id.vat[2:] +
self.order.mode.csb_suffix).zfill(12)
texto += str(recibo['name'])[-12:].zfill(12)
nombre = converter.to_ascii(recibo['partner_id'].name)
texto += nombre[0:40].ljust(40)
ccc = recibo['bank_id'] and recibo['bank_id'].acc_number or ''
ccc = converter.digits_only(ccc)
texto += str(ccc)[0:20].zfill(20)
importe = int(round(abs(recibo['amount'])*100, 0))
texto += str(importe).zfill(10)
# Referencia para devolución (sólo válida si no se agrupa) #
if len(recibo['ml_inv_ref']) == 1:
texto += str(recibo['ml_inv_ref'][0].id)[-16:].zfill(16)
else:
texto += 16*' '
######################################################################
concepto = ''
if recibo['communication']:
concepto = recibo['communication']
texto += converter.to_ascii(concepto)[0:40].ljust(40)
if recibo.get('date'):
date_cargo = datetime.strptime(recibo['date'], '%Y-%m-%d')
elif recibo.get('ml_maturity_date'):
date_cargo = datetime.strptime(recibo['ml_maturity_date'],
'%Y-%m-%d')
else:
date_cargo = datetime.today()
texto += date_cargo.strftime('%d%m%y')
texto += 2*' '
texto += '\r\n'
if len(texto) != 164:
raise Log(_('Configuration error:\n\nThe line "%s" is not 162 '
'characters long:\n%s') % ('Individual obligatorio 58',
texto), True)
return texto
def _individual_opcional_58(self, recibo):
"""Para poner el segundo texto de comunicación"""
converter = PaymentConverterSpain()
texto = '5671'
texto += (self.order.mode.bank_id.partner_id.vat[2:] +
self.order.mode.csb_suffix).zfill(12)
texto += str(recibo['name'])[-12:].zfill(12)
texto += converter.to_ascii(recibo['communication2'])[0:134].ljust(134)
texto += '\r\n'
if len(texto) != 164:
raise Log(_('Configuration error:\n\nThe line "%s" is not 162 '
'characters long:\n%s') % ('Individual opcional 58',
texto), True)
return texto
def _registro_obligatorio_domicilio_58(self, recibo):
"""
Registro obligatorio domicilio 58 para no domiciliados.
Formato:
ZONA DESCRIPCION POS LONGITUD TIPO
INICIAL REGISTRO
A: A1 Código de Registro: 56 1 2 Numérico
A2 Código de Dato: 76 3 2 Numérico
B: B1 Código del Cliente Ordenante 5 12 Alfanumérico
(NIF 9POS Y SUF 3POS)
B2 Código de Referencia 17 12 Alfanumérico
C: Domicilio del Deudor 29 40 Alfanumérico
D: D1 Plaza del Domicilio del Deudor 69 35 Alfanumérico
D2 Código Postal del Domicilio 104 5 Numérico
del Deudor
E: E1 Localidad del Ordenante al 109 38 Alfanumérico
que se anticipó el Crédito
E2 Código de la Provincia de 147 2 Numérico
esta Localidad
F: F1 Fecha de origen en que se 149 6 Numérico
formalizó el Cto.(DDMMAA)
F2 Libre 155 8 Alfanumérico
"""
converter = PaymentConverterSpain()
alt_format = self.order.mode.csb58_alt_address_format
#
# Obtenemos la dirección (por defecto) del partner, a imagen
# y semejanza de lo que hace info_partner
# del objeto payment.line (account_payment/payment.py),
# Pero si no encontramos ninguna dirección por defecto,
# tomamos la primera del partner.
#
st = ''
code_zip = ''
city = ''
if recibo['partner_id'].address:
ads = None
for item in recibo['partner_id'].address:
if item.type == 'default':
ads = item
break
if not ads and len(recibo['partner_id'].address) > 0:
ads = recibo['partner_id'].address[0]
st = ads.street and ads.street or ''
partner_zip = self.env['res.partner.zip']
if 'zip_id' in ads:
obj_zip_city = ads.zip_id and partner_zip.browse(
ads.zip_id.id, self.context) or ''
code_zip = obj_zip_city and obj_zip_city.name or ''
city = obj_zip_city and obj_zip_city.city or ''
else:
code_zip = ads.zip and ads.zip or ''
city = ads.city and ads.city or ''
#
# Comprobamos el código postal:
# "Cuando no se conozca el código
# completo, se cumplimentara, al menos, las dos primeras
# posiciones que identifican la provincia, dejando el resto de
# posiciones a cero."
#
if len(code_zip) < 2:
code_zip = ads.state_id and ads.state_id.code or ''
#
# Obtenemos la localidad y código de provincia del ordenante
#
ord_city = ''
ord_state_code = ''
if self.order.mode.partner_id.address:
ads = None
for item in self.order.mode.partner_id.address:
if item.type == 'default':
ads = item
break
if not ads and len(self.order.mode.partner_id.address) > 0:
ads = self.order.mode.partner_id.address[0]
ord_city = ads.state_id and ads.state_id.name or ''
ord_state_code = ads.state_id and ads.state_id.code or ''
#
# Calculamos la 'Fecha de origen en que se formalizo el crédito
# anticipado' esto es, la fecha de creación del recibo.
#
if recibo.get('create_date'):
date_ct = datetime.strptime(recibo['create_date'],
'%Y-%m-%d %H:%M:%S')
elif recibo.get('ml_date_created'):
date_ct = datetime.strptime(recibo['ml_date_created'], '%Y-%m-%d')
else:
date_ct = datetime.today()
#
# Componemos la línea formateada
#
texto = '5676'
texto += (self.order.mode.bank_id.partner_id.vat[2:] +
self.order.mode.csb_suffix).zfill(12)
texto += str(recibo['name'])[-12:].zfill(12)
texto += converter.to_ascii(st)[:40].ljust(40) # Domicilio
texto += converter.to_ascii(city)[:35].ljust(35) # Plaza (ciudad)
texto += converter.to_ascii(code_zip)[:5].zfill(5) # CP
# Localidad del ordenante (ciudad)
texto += converter.to_ascii(ord_city)[:38].ljust(38)
if alt_format:
#
# Si usamos el formato alternativo (basado en FacturaPlus)
# escribimos la fecha en la posición 147 y dejamos dos carácteres
# en blanco tras ella.
# Lo correcto, según la norma, es que en la posición 147 aparezca
# el código de provincia (2 dígitos) y la fecha empiece en
# la posición 149.
#
texto += date_ct.strftime('%d%m%y') # Fecha crédito
texto += 2*' '
else:
# Cod prov del ordenante
texto += converter.to_ascii(ord_state_code)[:2].zfill(2)
texto += date_ct.strftime('%d%m%y') # Fecha crédito
texto += 8*' ' # Libre
texto += '\r\n'
if len(texto) != 164:
raise Log(_('Configuration error:\n\nThe line "%s" is not 162 '
'characters long:\n%s') % ('Obligatorio domicilio 58',
texto), True)
return texto
def _total_ordenante_58(self):
texto = '5870'
texto += (self.order.mode.bank_id.partner_id.vat[2:] +
self.order.mode.csb_suffix).zfill(12)
texto += 72*' '
totalordenante = int(round(abs(self.order.total) * 100, 0))
texto += str(totalordenante).zfill(10)
texto += 6*' '
texto += str(self.num_recibos).zfill(10)
texto += str(self.num_recibos + self.num_lines_opc + 2).zfill(10)
texto += 38*' '
texto += '\r\n'
if len(texto) != 164:
raise Log(_('Configuration error:\n\nThe line "%s" is not 162 '
'characters long:\n%s') % ('Total ordenante 58',
texto), True)
return texto
def _total_general_58(self):
texto = '5970'
texto += (self.order.mode.bank_id.partner_id.vat[2:] +
self.order.mode.csb_suffix).zfill(12)
texto += 52*' '
texto += '0001'
texto += 16*' '
totalremesa = int(round(abs(self.order.total) * 100, 0))
texto += str(totalremesa).zfill(10)
texto += 6*' '
texto += str(self.num_recibos).zfill(10)
texto += str(self.num_recibos + self.num_lines_opc + 4).zfill(10)
texto += 38*' '
texto += '\r\n'
if len(texto) != 164:
raise Log(_('Configuration error:\n\nThe line "%s" is not 162 '
'characters long:\n%s') % ('Total general 58', texto),
True)
return texto
def create_file(self, order, lines):
self.order = order
txt_file = ''
self.num_recibos = 0
self.num_lines_opc = 0
txt_file += self._cabecera_presentador_58()
txt_file += self._cabecera_ordenante_58()
for recibo in lines:
txt_file += self._individual_obligatorio_58(recibo)
self.num_recibos = self.num_recibos + 1
# Sólo emitimos el registro individual si communication2 contiene
# texto
if (recibo['communication2'] and
len(recibo['communication2'].strip()) > 0):
txt_file += self._individual_opcional_58(recibo)
self.num_lines_opc = self.num_lines_opc + 1
# Para recibos no domiciliados, añadimos el registro obligatorio
# de domicilio (necesario con algunos bancos/cajas).
if self.order.mode.csb58_include_address:
txt_file += self._registro_obligatorio_domicilio_58(recibo)
self.num_lines_opc = self.num_lines_opc + 1
txt_file += self._total_ordenante_58()
txt_file += self._total_general_58()
return txt_file
|
agpl-3.0
|
robotican/ric
|
ric_board/scripts/RiCConfigurator/BAL/Devices/launchFile.py
|
1
|
3040
|
__author__ = 'tom'
from PyQt4.QtGui import *
from BAL.Interface.DeviceFrame import LAUNCH, EX_DEV, DeviceFrame
from lxml.etree import Element, SubElement, XML
import rospkg
class RosLaunch(DeviceFrame):
def __init__(self, frame, data):
DeviceFrame.__init__(self, EX_DEV, frame, data)
self._pkg = ''
self._file = ''
self._name = ''
def toDict(self):
data = dict()
data['type'] = LAUNCH
data['name'] = self._name
data['pkg'] = self._pkg
data['file'] = self._file
return data
def fromDict(self, data):
self._name = data['name']
self._pkg = data['pkg']
self._file = data['file']
def showDetails(self, items=None):
self.name = QLineEdit(self._name)
self.pkg = QLineEdit(self._pkg)
self.file = QPushButton('Browse')
self.file.clicked.connect(self.browse)
self._frame.layout().addRow(QLabel('Name:'), self.name)
self._frame.layout().addRow(QLabel('package:'), self.pkg)
self._frame.layout().addRow(QLabel('Launch file:'), self.file)
def browse(self):
if str(self.pkg.text()) == '':
QMessageBox.critical(self._frame, "Error", "You need to fill the package field before you browse for the file.")
return
try:
fullPath = rospkg.RosPack().get_path(str(self.pkg.text()))
except rospkg.ResourceNotFound:
QMessageBox.critical(self._frame, "Error", "Package not found.")
return
launchFile = str(QFileDialog.getOpenFileName(self._frame, 'Load file', fullPath, 'Launch file (*.launch)'))
if launchFile == '': return
index = launchFile.find(str(self.pkg.text()))
if index == -1:
QMessageBox.critical(self._frame, "Error", "launch is not from %s package." % str(self.pkg.text()))
return
self._file = launchFile[index + len(str(self.pkg.text())):]
self._pkg = str(self.pkg.text())
def saveToFile(self, parent):
SubElement(parent, 'include', {
'file': '$(find %s)%s' % (self._pkg, self._file)
})
def printDetails(self):
self._frame.layout().addRow(QLabel('Name:'), QLabel(self._name))
self._frame.layout().addRow(QLabel('package:'), QLabel(self._pkg))
self._frame.layout().addRow(QLabel('launch file:'), QLabel(self._file))
def getName(self):
return self._name
def add(self):
old = self._name
self._name = str(self.name.text())
if not self.nameIsValid():
error = QErrorMessage()
error.setWindowTitle("Same name error")
error.showMessage("Name already taken.")
error.exec_()
self._name = old
self._isValid = False
return
if self._file == '' or self._pkg == '':
QMessageBox.critical(self._frame, "Error", "one or more field are empty please fill theme.")
return
self._isValid = True
|
bsd-3-clause
|
carlgao/lenga
|
images/lenny64-peon/usr/share/python-support/python-boto/boto/mashups/iobject.py
|
1
|
3829
|
# Copyright (c) 2006,2007 Mitch Garnaat http://garnaat.org/
#
# Permission is hereby granted, free of charge, to any person obtaining a
# copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish, dis-
# tribute, sublicense, and/or sell copies of the Software, and to permit
# persons to whom the Software is furnished to do so, subject to the fol-
# lowing conditions:
#
# The above copyright notice and this permission notice shall be included
# in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABIL-
# ITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
# SHALL THE AUTHOR BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
# IN THE SOFTWARE.
import os
def int_val_fn(v):
try:
int(v)
return True
except:
return False
class IObject(object):
def choose_from_list(self, item_list, search_str='',
prompt='Enter Selection'):
choice = None
while not choice:
n = 1
choices = []
for item in item_list:
if isinstance(item, str):
print '[%d] %s' % (n, item)
choices.append(item)
n += 1
else:
obj, id, desc = item
if desc.find(search_str) >= 0:
print '[%d] %s - %s' % (n, id, desc)
choices.append(obj)
n += 1
if choices:
val = raw_input('%s[1-%d]: ' % (prompt, len(choices)))
if val.startswith('/'):
search_str = val[1:]
else:
try:
int_val = int(val)
if int_val == 0:
return None
choice = choices[int_val-1]
except ValueError:
print '%s is not a valid choice' % val
except IndexError:
print '%s is not within the range[1-%d]' % (val,
len(choices))
else:
print "No objects matched your pattern"
search_str = ''
return choice
def get_string(self, prompt, validation_fn=None):
okay = False
while not okay:
val = raw_input('%s: ' % prompt)
if validation_fn:
okay = validation_fn(val)
if not okay:
print 'Invalid value: %s' % val
else:
okay = True
return val
def get_filename(self, prompt):
okay = False
val = ''
while not okay:
val = raw_input('%s: %s' % (prompt, val))
val = os.path.expanduser(val)
if os.path.isfile(val):
okay = True
elif os.path.isdir(val):
path = val
val = self.choose_from_list(os.listdir(path))
if val:
val = os.path.join(path, val)
okay = True
else:
val = ''
else:
print 'Invalid value: %s' % val
val = ''
return val
def get_int(self, prompt):
s = self.get_string(prompt, int_val_fn)
return int(s)
|
mit
|
owlas/moma
|
googletest/scripts/release_docs.py
|
1167
|
6132
|
#!/usr/bin/env python
#
# Copyright 2013 Google Inc. 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 Google Inc. 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.
"""Script for branching Google Test/Mock wiki pages for a new version.
SYNOPSIS
release_docs.py NEW_RELEASE_VERSION
Google Test and Google Mock's external user documentation is in
interlinked wiki files. When we release a new version of
Google Test or Google Mock, we need to branch the wiki files
such that users of a specific version of Google Test/Mock can
look up documenation relevant for that version. This script
automates that process by:
- branching the current wiki pages (which document the
behavior of the SVN trunk head) to pages for the specified
version (e.g. branching FAQ.wiki to V2_6_FAQ.wiki when
NEW_RELEASE_VERSION is 2.6);
- updating the links in the branched files to point to the branched
version (e.g. a link in V2_6_FAQ.wiki that pointed to
Primer.wiki#Anchor will now point to V2_6_Primer.wiki#Anchor).
NOTE: NEW_RELEASE_VERSION must be a NEW version number for
which the wiki pages don't yet exist; otherwise you'll get SVN
errors like "svn: Path 'V1_7_PumpManual.wiki' is not a
directory" when running the script.
EXAMPLE
$ cd PATH/TO/GTEST_SVN_WORKSPACE/trunk
$ scripts/release_docs.py 2.6 # create wiki pages for v2.6
$ svn status # verify the file list
$ svn diff # verify the file contents
$ svn commit -m "release wiki pages for v2.6"
"""
__author__ = '[email protected] (Zhanyong Wan)'
import os
import re
import sys
import common
# Wiki pages that shouldn't be branched for every gtest/gmock release.
GTEST_UNVERSIONED_WIKIS = ['DevGuide.wiki']
GMOCK_UNVERSIONED_WIKIS = [
'DesignDoc.wiki',
'DevGuide.wiki',
'KnownIssues.wiki'
]
def DropWikiSuffix(wiki_filename):
"""Removes the .wiki suffix (if any) from the given filename."""
return (wiki_filename[:-len('.wiki')] if wiki_filename.endswith('.wiki')
else wiki_filename)
class WikiBrancher(object):
"""Branches ..."""
def __init__(self, dot_version):
self.project, svn_root_path = common.GetSvnInfo()
if self.project not in ('googletest', 'googlemock'):
sys.exit('This script must be run in a gtest or gmock SVN workspace.')
self.wiki_dir = svn_root_path + '/wiki'
# Turn '2.6' to 'V2_6_'.
self.version_prefix = 'V' + dot_version.replace('.', '_') + '_'
self.files_to_branch = self.GetFilesToBranch()
page_names = [DropWikiSuffix(f) for f in self.files_to_branch]
# A link to Foo.wiki is in one of the following forms:
# [Foo words]
# [Foo#Anchor words]
# [http://code.google.com/.../wiki/Foo words]
# [http://code.google.com/.../wiki/Foo#Anchor words]
# We want to replace 'Foo' with 'V2_6_Foo' in the above cases.
self.search_for_re = re.compile(
# This regex matches either
# [Foo
# or
# /wiki/Foo
# followed by a space or a #, where Foo is the name of an
# unversioned wiki page.
r'(\[|/wiki/)(%s)([ #])' % '|'.join(page_names))
self.replace_with = r'\1%s\2\3' % (self.version_prefix,)
def GetFilesToBranch(self):
"""Returns a list of .wiki file names that need to be branched."""
unversioned_wikis = (GTEST_UNVERSIONED_WIKIS if self.project == 'googletest'
else GMOCK_UNVERSIONED_WIKIS)
return [f for f in os.listdir(self.wiki_dir)
if (f.endswith('.wiki') and
not re.match(r'^V\d', f) and # Excluded versioned .wiki files.
f not in unversioned_wikis)]
def BranchFiles(self):
"""Branches the .wiki files needed to be branched."""
print 'Branching %d .wiki files:' % (len(self.files_to_branch),)
os.chdir(self.wiki_dir)
for f in self.files_to_branch:
command = 'svn cp %s %s%s' % (f, self.version_prefix, f)
print command
os.system(command)
def UpdateLinksInBranchedFiles(self):
for f in self.files_to_branch:
source_file = os.path.join(self.wiki_dir, f)
versioned_file = os.path.join(self.wiki_dir, self.version_prefix + f)
print 'Updating links in %s.' % (versioned_file,)
text = file(source_file, 'r').read()
new_text = self.search_for_re.sub(self.replace_with, text)
file(versioned_file, 'w').write(new_text)
def main():
if len(sys.argv) != 2:
sys.exit(__doc__)
brancher = WikiBrancher(sys.argv[1])
brancher.BranchFiles()
brancher.UpdateLinksInBranchedFiles()
if __name__ == '__main__':
main()
|
bsd-3-clause
|
Johnzero/OE7
|
openerp/tests/addons/test_exceptions/models.py
|
66
|
1289
|
# -*- coding: utf-8 -*-
import openerp
class m(openerp.osv.osv.Model):
""" This model exposes a few methods that will raise the different
exceptions that must be handled by the server (and its RPC layer)
and the clients.
"""
_name = 'test.exceptions.model'
def generate_except_osv(self, cr, uid, ids, context=None):
# title is ignored in the new (6.1) exceptions
raise openerp.osv.osv.except_osv('title', 'description')
def generate_except_orm(self, cr, uid, ids, context=None):
# title is ignored in the new (6.1) exceptions
raise openerp.osv.orm.except_orm('title', 'description')
def generate_warning(self, cr, uid, ids, context=None):
raise openerp.exceptions.Warning('description')
def generate_access_denied(self, cr, uid, ids, context=None):
raise openerp.exceptions.AccessDenied()
def generate_access_error(self, cr, uid, ids, context=None):
raise openerp.exceptions.AccessError('description')
def generate_exc_access_denied(self, cr, uid, ids, context=None):
raise Exception('AccessDenied')
def generate_undefined(self, cr, uid, ids, context=None):
self.surely_undefined_sumbol
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
PriceChild/ansible
|
lib/ansible/playbook/__init__.py
|
83
|
4214
|
# (c) 2012-2014, Michael DeHaan <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import os
from ansible import constants as C
from ansible.errors import AnsibleParserError
from ansible.module_utils._text import to_text
from ansible.playbook.play import Play
from ansible.playbook.playbook_include import PlaybookInclude
from ansible.plugins import get_all_plugin_loaders
try:
from __main__ import display
except ImportError:
from ansible.utils.display import Display
display = Display()
__all__ = ['Playbook']
class Playbook:
def __init__(self, loader):
# Entries in the datastructure of a playbook may
# be either a play or an include statement
self._entries = []
self._basedir = to_text(os.getcwd(), errors='surrogate_or_strict')
self._loader = loader
self._file_name = None
@staticmethod
def load(file_name, variable_manager=None, loader=None):
pb = Playbook(loader=loader)
pb._load_playbook_data(file_name=file_name, variable_manager=variable_manager)
return pb
def _load_playbook_data(self, file_name, variable_manager):
if os.path.isabs(file_name):
self._basedir = os.path.dirname(file_name)
else:
self._basedir = os.path.normpath(os.path.join(self._basedir, os.path.dirname(file_name)))
# set the loaders basedir
cur_basedir = self._loader.get_basedir()
self._loader.set_basedir(self._basedir)
self._file_name = file_name
# dynamically load any plugins from the playbook directory
for name, obj in get_all_plugin_loaders():
if obj.subdir:
plugin_path = os.path.join(self._basedir, obj.subdir)
if os.path.isdir(plugin_path):
obj.add_directory(plugin_path)
ds = self._loader.load_from_file(os.path.basename(file_name))
if not isinstance(ds, list):
# restore the basedir in case this error is caught and handled
self._loader.set_basedir(cur_basedir)
raise AnsibleParserError("playbooks must be a list of plays", obj=ds)
# Parse the playbook entries. For plays, we simply parse them
# using the Play() object, and includes are parsed using the
# PlaybookInclude() object
for entry in ds:
if not isinstance(entry, dict):
# restore the basedir in case this error is caught and handled
self._loader.set_basedir(cur_basedir)
raise AnsibleParserError("playbook entries must be either a valid play or an include statement", obj=entry)
if 'include' in entry:
pb = PlaybookInclude.load(entry, basedir=self._basedir, variable_manager=variable_manager, loader=self._loader)
if pb is not None:
self._entries.extend(pb._entries)
else:
display.display("skipping playbook include '%s' due to conditional test failure" % entry.get('include', entry), color=C.COLOR_SKIP)
else:
entry_obj = Play.load(entry, variable_manager=variable_manager, loader=self._loader)
self._entries.append(entry_obj)
# we're done, so restore the old basedir in the loader
self._loader.set_basedir(cur_basedir)
def get_loader(self):
return self._loader
def get_plays(self):
return self._entries[:]
|
gpl-3.0
|
hardikvasa/hadoop-mapreduce-examples-python
|
wikipedia-link-analysis-mapper.py
|
1
|
2412
|
#!/usr/bin/env python
import sys
#Finding 'Next Link' on a given web page
def get_next_link(s):
start_link = s.find("href=")
if start_link == -1: #If no links are found then give an error!
end_quote = 0
link = "no_links"
return link, end_quote
else:
start_quote = s.find('"', start_link)
end_quote = s.find('"',start_quote+1)
link = str(s[start_quote+1:end_quote])
return link, end_quote
#Getting all links with the help of 'get_next_links'
def get_all_links(page):
links = []
while True:
link, end_link = get_next_link(page)
if link == "no_links":
break
else:
links.append(link) #Append all the links in the list named 'Links'
#time.sleep(0.1)
page = page[end_link:]
return links
##Main Program
for line in sys.stdin:
line = line.strip() #remove white spaces
if 'wgArticleId' in line:
key = 'Articles'
value = 1
print( "%s\t%d" % (key, value) )
else:
links = get_all_links(line)
for j in links:
if 'href=' in line:
s = line.find('href')
if '.jpg' in line or '.png' in line or '.svg' in line or '.gif' in line or '.jpeg' in line or '.tiff' in line or '.xcf' in line:
key = 'Image Links'
value = 1
print( "%s\t%d" % (key, value) )
elif 'en.wikipedia.org' in line or '/w/' in line:
key = 'Internal but Irrelevant'
value = 1
print( "%s\t%d" % (key, value) )
elif '.wikipedia.org' in line:
key = 'Non-English Wikipedia Link'
value = 1
print( "%s\t%d" % (key, value) )
elif 'wikimedia.org' in line or 'wikimediafoundation.org' in line:
key = 'Organizational Link'
value = 1
print( "%s\t%d" % (key, value) )
elif '/wiki/' in line[s+6:s+15]:
key = 'Internal Link'
value = 1
print( "%s\t%d" % (key, value) )
else:
key = 'External Link'
value = 1
print( "%s\t%d" % (key, value) )
else:
pass
|
mit
|
nicholedwight/nichole-theme
|
node_modules/grunt-docker/node_modules/docker/node_modules/pygmentize-bundled/vendor/pygments/pygments/lexers/__init__.py
|
194
|
7698
|
# -*- coding: utf-8 -*-
"""
pygments.lexers
~~~~~~~~~~~~~~~
Pygments lexers.
:copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import sys
import types
import fnmatch
from os.path import basename
from pygments.lexers._mapping import LEXERS
from pygments.modeline import get_filetype_from_buffer
from pygments.plugin import find_plugin_lexers
from pygments.util import ClassNotFound, bytes
__all__ = ['get_lexer_by_name', 'get_lexer_for_filename', 'find_lexer_class',
'guess_lexer'] + LEXERS.keys()
_lexer_cache = {}
def _load_lexers(module_name):
"""
Load a lexer (and all others in the module too).
"""
mod = __import__(module_name, None, None, ['__all__'])
for lexer_name in mod.__all__:
cls = getattr(mod, lexer_name)
_lexer_cache[cls.name] = cls
def get_all_lexers():
"""
Return a generator of tuples in the form ``(name, aliases,
filenames, mimetypes)`` of all know lexers.
"""
for item in LEXERS.itervalues():
yield item[1:]
for lexer in find_plugin_lexers():
yield lexer.name, lexer.aliases, lexer.filenames, lexer.mimetypes
def find_lexer_class(name):
"""
Lookup a lexer class by name. Return None if not found.
"""
if name in _lexer_cache:
return _lexer_cache[name]
# lookup builtin lexers
for module_name, lname, aliases, _, _ in LEXERS.itervalues():
if name == lname:
_load_lexers(module_name)
return _lexer_cache[name]
# continue with lexers from setuptools entrypoints
for cls in find_plugin_lexers():
if cls.name == name:
return cls
def get_lexer_by_name(_alias, **options):
"""
Get a lexer by an alias.
"""
# lookup builtin lexers
for module_name, name, aliases, _, _ in LEXERS.itervalues():
if _alias in aliases:
if name not in _lexer_cache:
_load_lexers(module_name)
return _lexer_cache[name](**options)
# continue with lexers from setuptools entrypoints
for cls in find_plugin_lexers():
if _alias in cls.aliases:
return cls(**options)
raise ClassNotFound('no lexer for alias %r found' % _alias)
def get_lexer_for_filename(_fn, code=None, **options):
"""
Get a lexer for a filename. If multiple lexers match the filename
pattern, use ``analyze_text()`` to figure out which one is more
appropriate.
"""
matches = []
fn = basename(_fn)
for modname, name, _, filenames, _ in LEXERS.itervalues():
for filename in filenames:
if fnmatch.fnmatch(fn, filename):
if name not in _lexer_cache:
_load_lexers(modname)
matches.append((_lexer_cache[name], filename))
for cls in find_plugin_lexers():
for filename in cls.filenames:
if fnmatch.fnmatch(fn, filename):
matches.append((cls, filename))
if sys.version_info > (3,) and isinstance(code, bytes):
# decode it, since all analyse_text functions expect unicode
code = code.decode('latin1')
def get_rating(info):
cls, filename = info
# explicit patterns get a bonus
bonus = '*' not in filename and 0.5 or 0
# The class _always_ defines analyse_text because it's included in
# the Lexer class. The default implementation returns None which
# gets turned into 0.0. Run scripts/detect_missing_analyse_text.py
# to find lexers which need it overridden.
if code:
return cls.analyse_text(code) + bonus
return cls.priority + bonus
if matches:
matches.sort(key=get_rating)
#print "Possible lexers, after sort:", matches
return matches[-1][0](**options)
raise ClassNotFound('no lexer for filename %r found' % _fn)
def get_lexer_for_mimetype(_mime, **options):
"""
Get a lexer for a mimetype.
"""
for modname, name, _, _, mimetypes in LEXERS.itervalues():
if _mime in mimetypes:
if name not in _lexer_cache:
_load_lexers(modname)
return _lexer_cache[name](**options)
for cls in find_plugin_lexers():
if _mime in cls.mimetypes:
return cls(**options)
raise ClassNotFound('no lexer for mimetype %r found' % _mime)
def _iter_lexerclasses():
"""
Return an iterator over all lexer classes.
"""
for key in sorted(LEXERS):
module_name, name = LEXERS[key][:2]
if name not in _lexer_cache:
_load_lexers(module_name)
yield _lexer_cache[name]
for lexer in find_plugin_lexers():
yield lexer
def guess_lexer_for_filename(_fn, _text, **options):
"""
Lookup all lexers that handle those filenames primary (``filenames``)
or secondary (``alias_filenames``). Then run a text analysis for those
lexers and choose the best result.
usage::
>>> from pygments.lexers import guess_lexer_for_filename
>>> guess_lexer_for_filename('hello.html', '<%= @foo %>')
<pygments.lexers.templates.RhtmlLexer object at 0xb7d2f32c>
>>> guess_lexer_for_filename('hello.html', '<h1>{{ title|e }}</h1>')
<pygments.lexers.templates.HtmlDjangoLexer object at 0xb7d2f2ac>
>>> guess_lexer_for_filename('style.css', 'a { color: <?= $link ?> }')
<pygments.lexers.templates.CssPhpLexer object at 0xb7ba518c>
"""
fn = basename(_fn)
primary = None
matching_lexers = set()
for lexer in _iter_lexerclasses():
for filename in lexer.filenames:
if fnmatch.fnmatch(fn, filename):
matching_lexers.add(lexer)
primary = lexer
for filename in lexer.alias_filenames:
if fnmatch.fnmatch(fn, filename):
matching_lexers.add(lexer)
if not matching_lexers:
raise ClassNotFound('no lexer for filename %r found' % fn)
if len(matching_lexers) == 1:
return matching_lexers.pop()(**options)
result = []
for lexer in matching_lexers:
rv = lexer.analyse_text(_text)
if rv == 1.0:
return lexer(**options)
result.append((rv, lexer))
result.sort()
if not result[-1][0] and primary is not None:
return primary(**options)
return result[-1][1](**options)
def guess_lexer(_text, **options):
"""
Guess a lexer by strong distinctions in the text (eg, shebang).
"""
# try to get a vim modeline first
ft = get_filetype_from_buffer(_text)
if ft is not None:
try:
return get_lexer_by_name(ft, **options)
except ClassNotFound:
pass
best_lexer = [0.0, None]
for lexer in _iter_lexerclasses():
rv = lexer.analyse_text(_text)
if rv == 1.0:
return lexer(**options)
if rv > best_lexer[0]:
best_lexer[:] = (rv, lexer)
if not best_lexer[0] or best_lexer[1] is None:
raise ClassNotFound('no lexer matching the text found')
return best_lexer[1](**options)
class _automodule(types.ModuleType):
"""Automatically import lexers."""
def __getattr__(self, name):
info = LEXERS.get(name)
if info:
_load_lexers(info[0])
cls = _lexer_cache[info[1]]
setattr(self, name, cls)
return cls
raise AttributeError(name)
oldmod = sys.modules['pygments.lexers']
newmod = _automodule('pygments.lexers')
newmod.__dict__.update(oldmod.__dict__)
sys.modules['pygments.lexers'] = newmod
del newmod.newmod, newmod.oldmod, newmod.sys, newmod.types
|
mit
|
mancoast/CPythonPyc_test
|
fail/313_inspect_fodder2.py
|
179
|
1419
|
# line 1
def wrap(foo=None):
def wrapper(func):
return func
return wrapper
# line 7
def replace(func):
def insteadfunc():
print('hello')
return insteadfunc
# line 13
@wrap()
@wrap(wrap)
def wrapped():
pass
# line 19
@replace
def gone():
pass
# line 24
oll = lambda m: m
# line 27
tll = lambda g: g and \
g and \
g
# line 32
tlli = lambda d: d and \
d
# line 36
def onelinefunc(): pass
# line 39
def manyargs(arg1, arg2,
arg3, arg4): pass
# line 43
def twolinefunc(m): return m and \
m
# line 47
a = [None,
lambda x: x,
None]
# line 52
def setfunc(func):
globals()["anonymous"] = func
setfunc(lambda x, y: x*y)
# line 57
def with_comment(): # hello
world
# line 61
multiline_sig = [
lambda x, \
y: x+y,
None,
]
# line 68
def func69():
class cls70:
def func71():
pass
return cls70
extra74 = 74
# line 76
def func77(): pass
(extra78, stuff78) = 'xy'
extra79 = 'stop'
# line 81
class cls82:
def func83(): pass
(extra84, stuff84) = 'xy'
extra85 = 'stop'
# line 87
def func88():
# comment
return 90
# line 92
def f():
class X:
def g():
"doc"
return 42
return X
method_in_dynamic_class = f().g
#line 101
def keyworded(*arg1, arg2=1):
pass
#line 105
def annotated(arg1: list):
pass
#line 109
def keyword_only_arg(*, arg):
pass
|
gpl-3.0
|
GitAngel/django
|
django/db/models/signals.py
|
399
|
2734
|
from django.apps import apps
from django.dispatch import Signal
from django.utils import six
class_prepared = Signal(providing_args=["class"])
class ModelSignal(Signal):
"""
Signal subclass that allows the sender to be lazily specified as a string
of the `app_label.ModelName` form.
"""
def __init__(self, *args, **kwargs):
super(ModelSignal, self).__init__(*args, **kwargs)
self.unresolved_references = {}
class_prepared.connect(self._resolve_references)
def _resolve_references(self, sender, **kwargs):
opts = sender._meta
reference = (opts.app_label, opts.object_name)
try:
receivers = self.unresolved_references.pop(reference)
except KeyError:
pass
else:
for receiver, weak, dispatch_uid in receivers:
super(ModelSignal, self).connect(
receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid
)
def connect(self, receiver, sender=None, weak=True, dispatch_uid=None):
if isinstance(sender, six.string_types):
try:
app_label, model_name = sender.split('.')
except ValueError:
raise ValueError(
"Specified sender must either be a model or a "
"model name of the 'app_label.ModelName' form."
)
try:
sender = apps.get_registered_model(app_label, model_name)
except LookupError:
ref = (app_label, model_name)
refs = self.unresolved_references.setdefault(ref, [])
refs.append((receiver, weak, dispatch_uid))
return
super(ModelSignal, self).connect(
receiver, sender=sender, weak=weak, dispatch_uid=dispatch_uid
)
pre_init = ModelSignal(providing_args=["instance", "args", "kwargs"], use_caching=True)
post_init = ModelSignal(providing_args=["instance"], use_caching=True)
pre_save = ModelSignal(providing_args=["instance", "raw", "using", "update_fields"],
use_caching=True)
post_save = ModelSignal(providing_args=["instance", "raw", "created", "using", "update_fields"], use_caching=True)
pre_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)
post_delete = ModelSignal(providing_args=["instance", "using"], use_caching=True)
m2m_changed = ModelSignal(
providing_args=["action", "instance", "reverse", "model", "pk_set", "using"],
use_caching=True,
)
pre_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"])
post_migrate = Signal(providing_args=["app_config", "verbosity", "interactive", "using"])
|
bsd-3-clause
|
c0defreak/python-for-android
|
python3-alpha/python3-src/Lib/test/test_shelve.py
|
57
|
5834
|
import unittest
import shelve
import glob
from test import support
from collections import MutableMapping
from test.test_dbm import dbm_iterator
def L1(s):
return s.decode("latin-1")
class byteskeydict(MutableMapping):
"Mapping that supports bytes keys"
def __init__(self):
self.d = {}
def __getitem__(self, key):
return self.d[L1(key)]
def __setitem__(self, key, value):
self.d[L1(key)] = value
def __delitem__(self, key):
del self.d[L1(key)]
def __len__(self):
return len(self.d)
def iterkeys(self):
for k in self.d.keys():
yield k.encode("latin-1")
__iter__ = iterkeys
def keys(self):
return list(self.iterkeys())
def copy(self):
return byteskeydict(self.d)
class TestCase(unittest.TestCase):
fn = "shelftemp.db"
def tearDown(self):
for f in glob.glob(self.fn+"*"):
support.unlink(f)
def test_close(self):
d1 = {}
s = shelve.Shelf(d1, protocol=2, writeback=False)
s['key1'] = [1,2,3,4]
self.assertEqual(s['key1'], [1,2,3,4])
self.assertEqual(len(s), 1)
s.close()
self.assertRaises(ValueError, len, s)
try:
s['key1']
except ValueError:
pass
else:
self.fail('Closed shelf should not find a key')
def test_ascii_file_shelf(self):
s = shelve.open(self.fn, protocol=0)
try:
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
finally:
s.close()
def test_binary_file_shelf(self):
s = shelve.open(self.fn, protocol=1)
try:
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
finally:
s.close()
def test_proto2_file_shelf(self):
s = shelve.open(self.fn, protocol=2)
try:
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
finally:
s.close()
def test_in_memory_shelf(self):
d1 = byteskeydict()
s = shelve.Shelf(d1, protocol=0)
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
s.close()
d2 = byteskeydict()
s = shelve.Shelf(d2, protocol=1)
s['key1'] = (1,2,3,4)
self.assertEqual(s['key1'], (1,2,3,4))
s.close()
self.assertEqual(len(d1), 1)
self.assertEqual(len(d2), 1)
self.assertNotEqual(d1.items(), d2.items())
def test_mutable_entry(self):
d1 = byteskeydict()
s = shelve.Shelf(d1, protocol=2, writeback=False)
s['key1'] = [1,2,3,4]
self.assertEqual(s['key1'], [1,2,3,4])
s['key1'].append(5)
self.assertEqual(s['key1'], [1,2,3,4])
s.close()
d2 = byteskeydict()
s = shelve.Shelf(d2, protocol=2, writeback=True)
s['key1'] = [1,2,3,4]
self.assertEqual(s['key1'], [1,2,3,4])
s['key1'].append(5)
self.assertEqual(s['key1'], [1,2,3,4,5])
s.close()
self.assertEqual(len(d1), 1)
self.assertEqual(len(d2), 1)
def test_keyencoding(self):
d = {}
key = 'Pöp'
# the default keyencoding is utf-8
shelve.Shelf(d)[key] = [1]
self.assertIn(key.encode('utf-8'), d)
# but a different one can be given
shelve.Shelf(d, keyencoding='latin1')[key] = [1]
self.assertIn(key.encode('latin1'), d)
# with all consequences
s = shelve.Shelf(d, keyencoding='ascii')
self.assertRaises(UnicodeEncodeError, s.__setitem__, key, [1])
def test_writeback_also_writes_immediately(self):
# Issue 5754
d = {}
key = 'key'
encodedkey = key.encode('utf-8')
s = shelve.Shelf(d, writeback=True)
s[key] = [1]
p1 = d[encodedkey] # Will give a KeyError if backing store not updated
s['key'].append(2)
s.close()
p2 = d[encodedkey]
self.assertNotEqual(p1, p2) # Write creates new object in store
from test import mapping_tests
class TestShelveBase(mapping_tests.BasicTestMappingProtocol):
fn = "shelftemp.db"
counter = 0
def __init__(self, *args, **kw):
self._db = []
mapping_tests.BasicTestMappingProtocol.__init__(self, *args, **kw)
type2test = shelve.Shelf
def _reference(self):
return {"key1":"value1", "key2":2, "key3":(1,2,3)}
def _empty_mapping(self):
if self._in_mem:
x= shelve.Shelf(byteskeydict(), **self._args)
else:
self.counter+=1
x= shelve.open(self.fn+str(self.counter), **self._args)
self._db.append(x)
return x
def tearDown(self):
for db in self._db:
db.close()
self._db = []
if not self._in_mem:
for f in glob.glob(self.fn+"*"):
support.unlink(f)
class TestAsciiFileShelve(TestShelveBase):
_args={'protocol':0}
_in_mem = False
class TestBinaryFileShelve(TestShelveBase):
_args={'protocol':1}
_in_mem = False
class TestProto2FileShelve(TestShelveBase):
_args={'protocol':2}
_in_mem = False
class TestAsciiMemShelve(TestShelveBase):
_args={'protocol':0}
_in_mem = True
class TestBinaryMemShelve(TestShelveBase):
_args={'protocol':1}
_in_mem = True
class TestProto2MemShelve(TestShelveBase):
_args={'protocol':2}
_in_mem = True
def test_main():
for module in dbm_iterator():
support.run_unittest(
TestAsciiFileShelve,
TestBinaryFileShelve,
TestProto2FileShelve,
TestAsciiMemShelve,
TestBinaryMemShelve,
TestProto2MemShelve,
TestCase
)
if __name__ == "__main__":
test_main()
|
apache-2.0
|
IronLanguages/ironpython2
|
Src/StdLib/Lib/encodings/mac_croatian.py
|
593
|
13889
|
""" Python Character Mapping Codec mac_croatian generated from 'MAPPINGS/VENDORS/APPLE/CROATIAN.TXT' with gencodec.py.
"""#"
import codecs
### Codec APIs
class Codec(codecs.Codec):
def encode(self,input,errors='strict'):
return codecs.charmap_encode(input,errors,encoding_table)
def decode(self,input,errors='strict'):
return codecs.charmap_decode(input,errors,decoding_table)
class IncrementalEncoder(codecs.IncrementalEncoder):
def encode(self, input, final=False):
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
class IncrementalDecoder(codecs.IncrementalDecoder):
def decode(self, input, final=False):
return codecs.charmap_decode(input,self.errors,decoding_table)[0]
class StreamWriter(Codec,codecs.StreamWriter):
pass
class StreamReader(Codec,codecs.StreamReader):
pass
### encodings module API
def getregentry():
return codecs.CodecInfo(
name='mac-croatian',
encode=Codec().encode,
decode=Codec().decode,
incrementalencoder=IncrementalEncoder,
incrementaldecoder=IncrementalDecoder,
streamreader=StreamReader,
streamwriter=StreamWriter,
)
### Decoding Table
decoding_table = (
u'\x00' # 0x00 -> CONTROL CHARACTER
u'\x01' # 0x01 -> CONTROL CHARACTER
u'\x02' # 0x02 -> CONTROL CHARACTER
u'\x03' # 0x03 -> CONTROL CHARACTER
u'\x04' # 0x04 -> CONTROL CHARACTER
u'\x05' # 0x05 -> CONTROL CHARACTER
u'\x06' # 0x06 -> CONTROL CHARACTER
u'\x07' # 0x07 -> CONTROL CHARACTER
u'\x08' # 0x08 -> CONTROL CHARACTER
u'\t' # 0x09 -> CONTROL CHARACTER
u'\n' # 0x0A -> CONTROL CHARACTER
u'\x0b' # 0x0B -> CONTROL CHARACTER
u'\x0c' # 0x0C -> CONTROL CHARACTER
u'\r' # 0x0D -> CONTROL CHARACTER
u'\x0e' # 0x0E -> CONTROL CHARACTER
u'\x0f' # 0x0F -> CONTROL CHARACTER
u'\x10' # 0x10 -> CONTROL CHARACTER
u'\x11' # 0x11 -> CONTROL CHARACTER
u'\x12' # 0x12 -> CONTROL CHARACTER
u'\x13' # 0x13 -> CONTROL CHARACTER
u'\x14' # 0x14 -> CONTROL CHARACTER
u'\x15' # 0x15 -> CONTROL CHARACTER
u'\x16' # 0x16 -> CONTROL CHARACTER
u'\x17' # 0x17 -> CONTROL CHARACTER
u'\x18' # 0x18 -> CONTROL CHARACTER
u'\x19' # 0x19 -> CONTROL CHARACTER
u'\x1a' # 0x1A -> CONTROL CHARACTER
u'\x1b' # 0x1B -> CONTROL CHARACTER
u'\x1c' # 0x1C -> CONTROL CHARACTER
u'\x1d' # 0x1D -> CONTROL CHARACTER
u'\x1e' # 0x1E -> CONTROL CHARACTER
u'\x1f' # 0x1F -> CONTROL CHARACTER
u' ' # 0x20 -> SPACE
u'!' # 0x21 -> EXCLAMATION MARK
u'"' # 0x22 -> QUOTATION MARK
u'#' # 0x23 -> NUMBER SIGN
u'$' # 0x24 -> DOLLAR SIGN
u'%' # 0x25 -> PERCENT SIGN
u'&' # 0x26 -> AMPERSAND
u"'" # 0x27 -> APOSTROPHE
u'(' # 0x28 -> LEFT PARENTHESIS
u')' # 0x29 -> RIGHT PARENTHESIS
u'*' # 0x2A -> ASTERISK
u'+' # 0x2B -> PLUS SIGN
u',' # 0x2C -> COMMA
u'-' # 0x2D -> HYPHEN-MINUS
u'.' # 0x2E -> FULL STOP
u'/' # 0x2F -> SOLIDUS
u'0' # 0x30 -> DIGIT ZERO
u'1' # 0x31 -> DIGIT ONE
u'2' # 0x32 -> DIGIT TWO
u'3' # 0x33 -> DIGIT THREE
u'4' # 0x34 -> DIGIT FOUR
u'5' # 0x35 -> DIGIT FIVE
u'6' # 0x36 -> DIGIT SIX
u'7' # 0x37 -> DIGIT SEVEN
u'8' # 0x38 -> DIGIT EIGHT
u'9' # 0x39 -> DIGIT NINE
u':' # 0x3A -> COLON
u';' # 0x3B -> SEMICOLON
u'<' # 0x3C -> LESS-THAN SIGN
u'=' # 0x3D -> EQUALS SIGN
u'>' # 0x3E -> GREATER-THAN SIGN
u'?' # 0x3F -> QUESTION MARK
u'@' # 0x40 -> COMMERCIAL AT
u'A' # 0x41 -> LATIN CAPITAL LETTER A
u'B' # 0x42 -> LATIN CAPITAL LETTER B
u'C' # 0x43 -> LATIN CAPITAL LETTER C
u'D' # 0x44 -> LATIN CAPITAL LETTER D
u'E' # 0x45 -> LATIN CAPITAL LETTER E
u'F' # 0x46 -> LATIN CAPITAL LETTER F
u'G' # 0x47 -> LATIN CAPITAL LETTER G
u'H' # 0x48 -> LATIN CAPITAL LETTER H
u'I' # 0x49 -> LATIN CAPITAL LETTER I
u'J' # 0x4A -> LATIN CAPITAL LETTER J
u'K' # 0x4B -> LATIN CAPITAL LETTER K
u'L' # 0x4C -> LATIN CAPITAL LETTER L
u'M' # 0x4D -> LATIN CAPITAL LETTER M
u'N' # 0x4E -> LATIN CAPITAL LETTER N
u'O' # 0x4F -> LATIN CAPITAL LETTER O
u'P' # 0x50 -> LATIN CAPITAL LETTER P
u'Q' # 0x51 -> LATIN CAPITAL LETTER Q
u'R' # 0x52 -> LATIN CAPITAL LETTER R
u'S' # 0x53 -> LATIN CAPITAL LETTER S
u'T' # 0x54 -> LATIN CAPITAL LETTER T
u'U' # 0x55 -> LATIN CAPITAL LETTER U
u'V' # 0x56 -> LATIN CAPITAL LETTER V
u'W' # 0x57 -> LATIN CAPITAL LETTER W
u'X' # 0x58 -> LATIN CAPITAL LETTER X
u'Y' # 0x59 -> LATIN CAPITAL LETTER Y
u'Z' # 0x5A -> LATIN CAPITAL LETTER Z
u'[' # 0x5B -> LEFT SQUARE BRACKET
u'\\' # 0x5C -> REVERSE SOLIDUS
u']' # 0x5D -> RIGHT SQUARE BRACKET
u'^' # 0x5E -> CIRCUMFLEX ACCENT
u'_' # 0x5F -> LOW LINE
u'`' # 0x60 -> GRAVE ACCENT
u'a' # 0x61 -> LATIN SMALL LETTER A
u'b' # 0x62 -> LATIN SMALL LETTER B
u'c' # 0x63 -> LATIN SMALL LETTER C
u'd' # 0x64 -> LATIN SMALL LETTER D
u'e' # 0x65 -> LATIN SMALL LETTER E
u'f' # 0x66 -> LATIN SMALL LETTER F
u'g' # 0x67 -> LATIN SMALL LETTER G
u'h' # 0x68 -> LATIN SMALL LETTER H
u'i' # 0x69 -> LATIN SMALL LETTER I
u'j' # 0x6A -> LATIN SMALL LETTER J
u'k' # 0x6B -> LATIN SMALL LETTER K
u'l' # 0x6C -> LATIN SMALL LETTER L
u'm' # 0x6D -> LATIN SMALL LETTER M
u'n' # 0x6E -> LATIN SMALL LETTER N
u'o' # 0x6F -> LATIN SMALL LETTER O
u'p' # 0x70 -> LATIN SMALL LETTER P
u'q' # 0x71 -> LATIN SMALL LETTER Q
u'r' # 0x72 -> LATIN SMALL LETTER R
u's' # 0x73 -> LATIN SMALL LETTER S
u't' # 0x74 -> LATIN SMALL LETTER T
u'u' # 0x75 -> LATIN SMALL LETTER U
u'v' # 0x76 -> LATIN SMALL LETTER V
u'w' # 0x77 -> LATIN SMALL LETTER W
u'x' # 0x78 -> LATIN SMALL LETTER X
u'y' # 0x79 -> LATIN SMALL LETTER Y
u'z' # 0x7A -> LATIN SMALL LETTER Z
u'{' # 0x7B -> LEFT CURLY BRACKET
u'|' # 0x7C -> VERTICAL LINE
u'}' # 0x7D -> RIGHT CURLY BRACKET
u'~' # 0x7E -> TILDE
u'\x7f' # 0x7F -> CONTROL CHARACTER
u'\xc4' # 0x80 -> LATIN CAPITAL LETTER A WITH DIAERESIS
u'\xc5' # 0x81 -> LATIN CAPITAL LETTER A WITH RING ABOVE
u'\xc7' # 0x82 -> LATIN CAPITAL LETTER C WITH CEDILLA
u'\xc9' # 0x83 -> LATIN CAPITAL LETTER E WITH ACUTE
u'\xd1' # 0x84 -> LATIN CAPITAL LETTER N WITH TILDE
u'\xd6' # 0x85 -> LATIN CAPITAL LETTER O WITH DIAERESIS
u'\xdc' # 0x86 -> LATIN CAPITAL LETTER U WITH DIAERESIS
u'\xe1' # 0x87 -> LATIN SMALL LETTER A WITH ACUTE
u'\xe0' # 0x88 -> LATIN SMALL LETTER A WITH GRAVE
u'\xe2' # 0x89 -> LATIN SMALL LETTER A WITH CIRCUMFLEX
u'\xe4' # 0x8A -> LATIN SMALL LETTER A WITH DIAERESIS
u'\xe3' # 0x8B -> LATIN SMALL LETTER A WITH TILDE
u'\xe5' # 0x8C -> LATIN SMALL LETTER A WITH RING ABOVE
u'\xe7' # 0x8D -> LATIN SMALL LETTER C WITH CEDILLA
u'\xe9' # 0x8E -> LATIN SMALL LETTER E WITH ACUTE
u'\xe8' # 0x8F -> LATIN SMALL LETTER E WITH GRAVE
u'\xea' # 0x90 -> LATIN SMALL LETTER E WITH CIRCUMFLEX
u'\xeb' # 0x91 -> LATIN SMALL LETTER E WITH DIAERESIS
u'\xed' # 0x92 -> LATIN SMALL LETTER I WITH ACUTE
u'\xec' # 0x93 -> LATIN SMALL LETTER I WITH GRAVE
u'\xee' # 0x94 -> LATIN SMALL LETTER I WITH CIRCUMFLEX
u'\xef' # 0x95 -> LATIN SMALL LETTER I WITH DIAERESIS
u'\xf1' # 0x96 -> LATIN SMALL LETTER N WITH TILDE
u'\xf3' # 0x97 -> LATIN SMALL LETTER O WITH ACUTE
u'\xf2' # 0x98 -> LATIN SMALL LETTER O WITH GRAVE
u'\xf4' # 0x99 -> LATIN SMALL LETTER O WITH CIRCUMFLEX
u'\xf6' # 0x9A -> LATIN SMALL LETTER O WITH DIAERESIS
u'\xf5' # 0x9B -> LATIN SMALL LETTER O WITH TILDE
u'\xfa' # 0x9C -> LATIN SMALL LETTER U WITH ACUTE
u'\xf9' # 0x9D -> LATIN SMALL LETTER U WITH GRAVE
u'\xfb' # 0x9E -> LATIN SMALL LETTER U WITH CIRCUMFLEX
u'\xfc' # 0x9F -> LATIN SMALL LETTER U WITH DIAERESIS
u'\u2020' # 0xA0 -> DAGGER
u'\xb0' # 0xA1 -> DEGREE SIGN
u'\xa2' # 0xA2 -> CENT SIGN
u'\xa3' # 0xA3 -> POUND SIGN
u'\xa7' # 0xA4 -> SECTION SIGN
u'\u2022' # 0xA5 -> BULLET
u'\xb6' # 0xA6 -> PILCROW SIGN
u'\xdf' # 0xA7 -> LATIN SMALL LETTER SHARP S
u'\xae' # 0xA8 -> REGISTERED SIGN
u'\u0160' # 0xA9 -> LATIN CAPITAL LETTER S WITH CARON
u'\u2122' # 0xAA -> TRADE MARK SIGN
u'\xb4' # 0xAB -> ACUTE ACCENT
u'\xa8' # 0xAC -> DIAERESIS
u'\u2260' # 0xAD -> NOT EQUAL TO
u'\u017d' # 0xAE -> LATIN CAPITAL LETTER Z WITH CARON
u'\xd8' # 0xAF -> LATIN CAPITAL LETTER O WITH STROKE
u'\u221e' # 0xB0 -> INFINITY
u'\xb1' # 0xB1 -> PLUS-MINUS SIGN
u'\u2264' # 0xB2 -> LESS-THAN OR EQUAL TO
u'\u2265' # 0xB3 -> GREATER-THAN OR EQUAL TO
u'\u2206' # 0xB4 -> INCREMENT
u'\xb5' # 0xB5 -> MICRO SIGN
u'\u2202' # 0xB6 -> PARTIAL DIFFERENTIAL
u'\u2211' # 0xB7 -> N-ARY SUMMATION
u'\u220f' # 0xB8 -> N-ARY PRODUCT
u'\u0161' # 0xB9 -> LATIN SMALL LETTER S WITH CARON
u'\u222b' # 0xBA -> INTEGRAL
u'\xaa' # 0xBB -> FEMININE ORDINAL INDICATOR
u'\xba' # 0xBC -> MASCULINE ORDINAL INDICATOR
u'\u03a9' # 0xBD -> GREEK CAPITAL LETTER OMEGA
u'\u017e' # 0xBE -> LATIN SMALL LETTER Z WITH CARON
u'\xf8' # 0xBF -> LATIN SMALL LETTER O WITH STROKE
u'\xbf' # 0xC0 -> INVERTED QUESTION MARK
u'\xa1' # 0xC1 -> INVERTED EXCLAMATION MARK
u'\xac' # 0xC2 -> NOT SIGN
u'\u221a' # 0xC3 -> SQUARE ROOT
u'\u0192' # 0xC4 -> LATIN SMALL LETTER F WITH HOOK
u'\u2248' # 0xC5 -> ALMOST EQUAL TO
u'\u0106' # 0xC6 -> LATIN CAPITAL LETTER C WITH ACUTE
u'\xab' # 0xC7 -> LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u010c' # 0xC8 -> LATIN CAPITAL LETTER C WITH CARON
u'\u2026' # 0xC9 -> HORIZONTAL ELLIPSIS
u'\xa0' # 0xCA -> NO-BREAK SPACE
u'\xc0' # 0xCB -> LATIN CAPITAL LETTER A WITH GRAVE
u'\xc3' # 0xCC -> LATIN CAPITAL LETTER A WITH TILDE
u'\xd5' # 0xCD -> LATIN CAPITAL LETTER O WITH TILDE
u'\u0152' # 0xCE -> LATIN CAPITAL LIGATURE OE
u'\u0153' # 0xCF -> LATIN SMALL LIGATURE OE
u'\u0110' # 0xD0 -> LATIN CAPITAL LETTER D WITH STROKE
u'\u2014' # 0xD1 -> EM DASH
u'\u201c' # 0xD2 -> LEFT DOUBLE QUOTATION MARK
u'\u201d' # 0xD3 -> RIGHT DOUBLE QUOTATION MARK
u'\u2018' # 0xD4 -> LEFT SINGLE QUOTATION MARK
u'\u2019' # 0xD5 -> RIGHT SINGLE QUOTATION MARK
u'\xf7' # 0xD6 -> DIVISION SIGN
u'\u25ca' # 0xD7 -> LOZENGE
u'\uf8ff' # 0xD8 -> Apple logo
u'\xa9' # 0xD9 -> COPYRIGHT SIGN
u'\u2044' # 0xDA -> FRACTION SLASH
u'\u20ac' # 0xDB -> EURO SIGN
u'\u2039' # 0xDC -> SINGLE LEFT-POINTING ANGLE QUOTATION MARK
u'\u203a' # 0xDD -> SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
u'\xc6' # 0xDE -> LATIN CAPITAL LETTER AE
u'\xbb' # 0xDF -> RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
u'\u2013' # 0xE0 -> EN DASH
u'\xb7' # 0xE1 -> MIDDLE DOT
u'\u201a' # 0xE2 -> SINGLE LOW-9 QUOTATION MARK
u'\u201e' # 0xE3 -> DOUBLE LOW-9 QUOTATION MARK
u'\u2030' # 0xE4 -> PER MILLE SIGN
u'\xc2' # 0xE5 -> LATIN CAPITAL LETTER A WITH CIRCUMFLEX
u'\u0107' # 0xE6 -> LATIN SMALL LETTER C WITH ACUTE
u'\xc1' # 0xE7 -> LATIN CAPITAL LETTER A WITH ACUTE
u'\u010d' # 0xE8 -> LATIN SMALL LETTER C WITH CARON
u'\xc8' # 0xE9 -> LATIN CAPITAL LETTER E WITH GRAVE
u'\xcd' # 0xEA -> LATIN CAPITAL LETTER I WITH ACUTE
u'\xce' # 0xEB -> LATIN CAPITAL LETTER I WITH CIRCUMFLEX
u'\xcf' # 0xEC -> LATIN CAPITAL LETTER I WITH DIAERESIS
u'\xcc' # 0xED -> LATIN CAPITAL LETTER I WITH GRAVE
u'\xd3' # 0xEE -> LATIN CAPITAL LETTER O WITH ACUTE
u'\xd4' # 0xEF -> LATIN CAPITAL LETTER O WITH CIRCUMFLEX
u'\u0111' # 0xF0 -> LATIN SMALL LETTER D WITH STROKE
u'\xd2' # 0xF1 -> LATIN CAPITAL LETTER O WITH GRAVE
u'\xda' # 0xF2 -> LATIN CAPITAL LETTER U WITH ACUTE
u'\xdb' # 0xF3 -> LATIN CAPITAL LETTER U WITH CIRCUMFLEX
u'\xd9' # 0xF4 -> LATIN CAPITAL LETTER U WITH GRAVE
u'\u0131' # 0xF5 -> LATIN SMALL LETTER DOTLESS I
u'\u02c6' # 0xF6 -> MODIFIER LETTER CIRCUMFLEX ACCENT
u'\u02dc' # 0xF7 -> SMALL TILDE
u'\xaf' # 0xF8 -> MACRON
u'\u03c0' # 0xF9 -> GREEK SMALL LETTER PI
u'\xcb' # 0xFA -> LATIN CAPITAL LETTER E WITH DIAERESIS
u'\u02da' # 0xFB -> RING ABOVE
u'\xb8' # 0xFC -> CEDILLA
u'\xca' # 0xFD -> LATIN CAPITAL LETTER E WITH CIRCUMFLEX
u'\xe6' # 0xFE -> LATIN SMALL LETTER AE
u'\u02c7' # 0xFF -> CARON
)
### Encoding table
encoding_table=codecs.charmap_build(decoding_table)
|
apache-2.0
|
CydarLtd/ansible
|
lib/ansible/modules/network/f5/bigip_facts.py
|
72
|
62015
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# (c) 2013, Matt Hite <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: bigip_facts
short_description: Collect facts from F5 BIG-IP devices
description:
- Collect facts from F5 BIG-IP devices via iControl SOAP API
version_added: "1.6"
author:
- Matt Hite (@mhite)
- Tim Rupp (@caphrim007)
notes:
- Requires BIG-IP software version >= 11.4
- F5 developed module 'bigsuds' required (see http://devcentral.f5.com)
- Best run as a local_action in your playbook
- Tested with manager and above account privilege level
- C(provision) facts were added in 2.2
requirements:
- bigsuds
options:
session:
description:
- BIG-IP session support; may be useful to avoid concurrency
issues in certain circumstances.
required: false
default: true
choices: []
aliases: []
include:
description:
- Fact category or list of categories to collect
required: true
default: null
choices:
- address_class
- certificate
- client_ssl_profile
- device
- device_group
- interface
- key
- node
- pool
- provision
- rule
- self_ip
- software
- system_info
- traffic_group
- trunk
- virtual_address
- virtual_server
- vlan
aliases: []
filter:
description:
- Shell-style glob matching string used to filter fact keys. Not
applicable for software, provision, and system_info fact categories.
required: false
default: null
choices: []
aliases: []
extends_documentation_fragment: f5
'''
EXAMPLES = '''
- name: Collect BIG-IP facts
bigip_facts:
server: "lb.mydomain.com"
user: "admin"
password: "secret"
include: "interface,vlan"
delegate_to: localhost
'''
try:
from suds import MethodNotFound, WebFault
except ImportError:
bigsuds_found = False
else:
bigsuds_found = True
import fnmatch
import re
import traceback
class F5(object):
"""F5 iControl class.
F5 BIG-IP iControl API class.
Attributes:
api: iControl API instance.
"""
def __init__(self, host, user, password, session=False, validate_certs=True, port=443):
self.api = bigip_api(host, user, password, validate_certs, port)
if session:
self.start_session()
def start_session(self):
self.api = self.api.with_session_id()
def get_api(self):
return self.api
def set_recursive_query_state(self, state):
self.api.System.Session.set_recursive_query_state(state)
def get_recursive_query_state(self):
return self.api.System.Session.get_recursive_query_state()
def enable_recursive_query_state(self):
self.set_recursive_query_state('STATE_ENABLED')
def disable_recursive_query_state(self):
self.set_recursive_query_state('STATE_DISABLED')
def set_active_folder(self, folder):
self.api.System.Session.set_active_folder(folder=folder)
def get_active_folder(self):
return self.api.System.Session.get_active_folder()
class Interfaces(object):
"""Interfaces class.
F5 BIG-IP interfaces class.
Attributes:
api: iControl API instance.
interfaces: A list of BIG-IP interface names.
"""
def __init__(self, api, regex=None):
self.api = api
self.interfaces = api.Networking.Interfaces.get_list()
if regex:
re_filter = re.compile(regex)
self.interfaces = filter(re_filter.search, self.interfaces)
def get_list(self):
return self.interfaces
def get_active_media(self):
return self.api.Networking.Interfaces.get_active_media(self.interfaces)
def get_actual_flow_control(self):
return self.api.Networking.Interfaces.get_actual_flow_control(self.interfaces)
def get_bundle_state(self):
return self.api.Networking.Interfaces.get_bundle_state(self.interfaces)
def get_description(self):
return self.api.Networking.Interfaces.get_description(self.interfaces)
def get_dual_media_state(self):
return self.api.Networking.Interfaces.get_dual_media_state(self.interfaces)
def get_enabled_state(self):
return self.api.Networking.Interfaces.get_enabled_state(self.interfaces)
def get_if_index(self):
return self.api.Networking.Interfaces.get_if_index(self.interfaces)
def get_learning_mode(self):
return self.api.Networking.Interfaces.get_learning_mode(self.interfaces)
def get_lldp_admin_status(self):
return self.api.Networking.Interfaces.get_lldp_admin_status(self.interfaces)
def get_lldp_tlvmap(self):
return self.api.Networking.Interfaces.get_lldp_tlvmap(self.interfaces)
def get_mac_address(self):
return self.api.Networking.Interfaces.get_mac_address(self.interfaces)
def get_media(self):
return self.api.Networking.Interfaces.get_media(self.interfaces)
def get_media_option(self):
return self.api.Networking.Interfaces.get_media_option(self.interfaces)
def get_media_option_sfp(self):
return self.api.Networking.Interfaces.get_media_option_sfp(self.interfaces)
def get_media_sfp(self):
return self.api.Networking.Interfaces.get_media_sfp(self.interfaces)
def get_media_speed(self):
return self.api.Networking.Interfaces.get_media_speed(self.interfaces)
def get_media_status(self):
return self.api.Networking.Interfaces.get_media_status(self.interfaces)
def get_mtu(self):
return self.api.Networking.Interfaces.get_mtu(self.interfaces)
def get_phy_master_slave_mode(self):
return self.api.Networking.Interfaces.get_phy_master_slave_mode(self.interfaces)
def get_prefer_sfp_state(self):
return self.api.Networking.Interfaces.get_prefer_sfp_state(self.interfaces)
def get_flow_control(self):
return self.api.Networking.Interfaces.get_requested_flow_control(self.interfaces)
def get_sflow_poll_interval(self):
return self.api.Networking.Interfaces.get_sflow_poll_interval(self.interfaces)
def get_sflow_poll_interval_global(self):
return self.api.Networking.Interfaces.get_sflow_poll_interval_global(self.interfaces)
def get_sfp_media_state(self):
return self.api.Networking.Interfaces.get_sfp_media_state(self.interfaces)
def get_stp_active_edge_port_state(self):
return self.api.Networking.Interfaces.get_stp_active_edge_port_state(self.interfaces)
def get_stp_enabled_state(self):
return self.api.Networking.Interfaces.get_stp_enabled_state(self.interfaces)
def get_stp_link_type(self):
return self.api.Networking.Interfaces.get_stp_link_type(self.interfaces)
def get_stp_protocol_detection_reset_state(self):
return self.api.Networking.Interfaces.get_stp_protocol_detection_reset_state(self.interfaces)
class SelfIPs(object):
"""Self IPs class.
F5 BIG-IP Self IPs class.
Attributes:
api: iControl API instance.
self_ips: List of self IPs.
"""
def __init__(self, api, regex=None):
self.api = api
self.self_ips = api.Networking.SelfIPV2.get_list()
if regex:
re_filter = re.compile(regex)
self.self_ips = filter(re_filter.search, self.self_ips)
def get_list(self):
return self.self_ips
def get_address(self):
return self.api.Networking.SelfIPV2.get_address(self.self_ips)
def get_allow_access_list(self):
return self.api.Networking.SelfIPV2.get_allow_access_list(self.self_ips)
def get_description(self):
return self.api.Networking.SelfIPV2.get_description(self.self_ips)
def get_enforced_firewall_policy(self):
return self.api.Networking.SelfIPV2.get_enforced_firewall_policy(self.self_ips)
def get_floating_state(self):
return self.api.Networking.SelfIPV2.get_floating_state(self.self_ips)
def get_fw_rule(self):
return self.api.Networking.SelfIPV2.get_fw_rule(self.self_ips)
def get_netmask(self):
return self.api.Networking.SelfIPV2.get_netmask(self.self_ips)
def get_staged_firewall_policy(self):
return self.api.Networking.SelfIPV2.get_staged_firewall_policy(self.self_ips)
def get_traffic_group(self):
return self.api.Networking.SelfIPV2.get_traffic_group(self.self_ips)
def get_vlan(self):
return self.api.Networking.SelfIPV2.get_vlan(self.self_ips)
def get_is_traffic_group_inherited(self):
return self.api.Networking.SelfIPV2.is_traffic_group_inherited(self.self_ips)
class Trunks(object):
"""Trunks class.
F5 BIG-IP trunks class.
Attributes:
api: iControl API instance.
trunks: List of trunks.
"""
def __init__(self, api, regex=None):
self.api = api
self.trunks = api.Networking.Trunk.get_list()
if regex:
re_filter = re.compile(regex)
self.trunks = filter(re_filter.search, self.trunks)
def get_list(self):
return self.trunks
def get_active_lacp_state(self):
return self.api.Networking.Trunk.get_active_lacp_state(self.trunks)
def get_configured_member_count(self):
return self.api.Networking.Trunk.get_configured_member_count(self.trunks)
def get_description(self):
return self.api.Networking.Trunk.get_description(self.trunks)
def get_distribution_hash_option(self):
return self.api.Networking.Trunk.get_distribution_hash_option(self.trunks)
def get_interface(self):
return self.api.Networking.Trunk.get_interface(self.trunks)
def get_lacp_enabled_state(self):
return self.api.Networking.Trunk.get_lacp_enabled_state(self.trunks)
def get_lacp_timeout_option(self):
return self.api.Networking.Trunk.get_lacp_timeout_option(self.trunks)
def get_link_selection_policy(self):
return self.api.Networking.Trunk.get_link_selection_policy(self.trunks)
def get_media_speed(self):
return self.api.Networking.Trunk.get_media_speed(self.trunks)
def get_media_status(self):
return self.api.Networking.Trunk.get_media_status(self.trunks)
def get_operational_member_count(self):
return self.api.Networking.Trunk.get_operational_member_count(self.trunks)
def get_stp_enabled_state(self):
return self.api.Networking.Trunk.get_stp_enabled_state(self.trunks)
def get_stp_protocol_detection_reset_state(self):
return self.api.Networking.Trunk.get_stp_protocol_detection_reset_state(self.trunks)
class Vlans(object):
"""Vlans class.
F5 BIG-IP Vlans class.
Attributes:
api: iControl API instance.
vlans: List of VLANs.
"""
def __init__(self, api, regex=None):
self.api = api
self.vlans = api.Networking.VLAN.get_list()
if regex:
re_filter = re.compile(regex)
self.vlans = filter(re_filter.search, self.vlans)
def get_list(self):
return self.vlans
def get_auto_lasthop(self):
return self.api.Networking.VLAN.get_auto_lasthop(self.vlans)
def get_cmp_hash_algorithm(self):
return self.api.Networking.VLAN.get_cmp_hash_algorithm(self.vlans)
def get_description(self):
return self.api.Networking.VLAN.get_description(self.vlans)
def get_dynamic_forwarding(self):
return self.api.Networking.VLAN.get_dynamic_forwarding(self.vlans)
def get_failsafe_action(self):
return self.api.Networking.VLAN.get_failsafe_action(self.vlans)
def get_failsafe_state(self):
return self.api.Networking.VLAN.get_failsafe_state(self.vlans)
def get_failsafe_timeout(self):
return self.api.Networking.VLAN.get_failsafe_timeout(self.vlans)
def get_if_index(self):
return self.api.Networking.VLAN.get_if_index(self.vlans)
def get_learning_mode(self):
return self.api.Networking.VLAN.get_learning_mode(self.vlans)
def get_mac_masquerade_address(self):
return self.api.Networking.VLAN.get_mac_masquerade_address(self.vlans)
def get_member(self):
return self.api.Networking.VLAN.get_member(self.vlans)
def get_mtu(self):
return self.api.Networking.VLAN.get_mtu(self.vlans)
def get_sflow_poll_interval(self):
return self.api.Networking.VLAN.get_sflow_poll_interval(self.vlans)
def get_sflow_poll_interval_global(self):
return self.api.Networking.VLAN.get_sflow_poll_interval_global(self.vlans)
def get_sflow_sampling_rate(self):
return self.api.Networking.VLAN.get_sflow_sampling_rate(self.vlans)
def get_sflow_sampling_rate_global(self):
return self.api.Networking.VLAN.get_sflow_sampling_rate_global(self.vlans)
def get_source_check_state(self):
return self.api.Networking.VLAN.get_source_check_state(self.vlans)
def get_true_mac_address(self):
return self.api.Networking.VLAN.get_true_mac_address(self.vlans)
def get_vlan_id(self):
return self.api.Networking.VLAN.get_vlan_id(self.vlans)
class Software(object):
"""Software class.
F5 BIG-IP software class.
Attributes:
api: iControl API instance.
"""
def __init__(self, api):
self.api = api
def get_all_software_status(self):
return self.api.System.SoftwareManagement.get_all_software_status()
class VirtualServers(object):
"""Virtual servers class.
F5 BIG-IP virtual servers class.
Attributes:
api: iControl API instance.
virtual_servers: List of virtual servers.
"""
def __init__(self, api, regex=None):
self.api = api
self.virtual_servers = api.LocalLB.VirtualServer.get_list()
if regex:
re_filter = re.compile(regex)
self.virtual_servers = filter(re_filter.search, self.virtual_servers)
def get_list(self):
return self.virtual_servers
def get_actual_hardware_acceleration(self):
return self.api.LocalLB.VirtualServer.get_actual_hardware_acceleration(self.virtual_servers)
def get_authentication_profile(self):
return self.api.LocalLB.VirtualServer.get_authentication_profile(self.virtual_servers)
def get_auto_lasthop(self):
return self.api.LocalLB.VirtualServer.get_auto_lasthop(self.virtual_servers)
def get_bw_controller_policy(self):
return self.api.LocalLB.VirtualServer.get_bw_controller_policy(self.virtual_servers)
def get_clone_pool(self):
return self.api.LocalLB.VirtualServer.get_clone_pool(self.virtual_servers)
def get_cmp_enable_mode(self):
return self.api.LocalLB.VirtualServer.get_cmp_enable_mode(self.virtual_servers)
def get_connection_limit(self):
return self.api.LocalLB.VirtualServer.get_connection_limit(self.virtual_servers)
def get_connection_mirror_state(self):
return self.api.LocalLB.VirtualServer.get_connection_mirror_state(self.virtual_servers)
def get_default_pool_name(self):
return self.api.LocalLB.VirtualServer.get_default_pool_name(self.virtual_servers)
def get_description(self):
return self.api.LocalLB.VirtualServer.get_description(self.virtual_servers)
def get_destination(self):
return self.api.LocalLB.VirtualServer.get_destination_v2(self.virtual_servers)
def get_enabled_state(self):
return self.api.LocalLB.VirtualServer.get_enabled_state(self.virtual_servers)
def get_enforced_firewall_policy(self):
return self.api.LocalLB.VirtualServer.get_enforced_firewall_policy(self.virtual_servers)
def get_fallback_persistence_profile(self):
return self.api.LocalLB.VirtualServer.get_fallback_persistence_profile(self.virtual_servers)
def get_fw_rule(self):
return self.api.LocalLB.VirtualServer.get_fw_rule(self.virtual_servers)
def get_gtm_score(self):
return self.api.LocalLB.VirtualServer.get_gtm_score(self.virtual_servers)
def get_last_hop_pool(self):
return self.api.LocalLB.VirtualServer.get_last_hop_pool(self.virtual_servers)
def get_nat64_state(self):
return self.api.LocalLB.VirtualServer.get_nat64_state(self.virtual_servers)
def get_object_status(self):
return self.api.LocalLB.VirtualServer.get_object_status(self.virtual_servers)
def get_persistence_profile(self):
return self.api.LocalLB.VirtualServer.get_persistence_profile(self.virtual_servers)
def get_profile(self):
return self.api.LocalLB.VirtualServer.get_profile(self.virtual_servers)
def get_protocol(self):
return self.api.LocalLB.VirtualServer.get_protocol(self.virtual_servers)
def get_rate_class(self):
return self.api.LocalLB.VirtualServer.get_rate_class(self.virtual_servers)
def get_rate_limit(self):
return self.api.LocalLB.VirtualServer.get_rate_limit(self.virtual_servers)
def get_rate_limit_destination_mask(self):
return self.api.LocalLB.VirtualServer.get_rate_limit_destination_mask(self.virtual_servers)
def get_rate_limit_mode(self):
return self.api.LocalLB.VirtualServer.get_rate_limit_mode(self.virtual_servers)
def get_rate_limit_source_mask(self):
return self.api.LocalLB.VirtualServer.get_rate_limit_source_mask(self.virtual_servers)
def get_related_rule(self):
return self.api.LocalLB.VirtualServer.get_related_rule(self.virtual_servers)
def get_rule(self):
return self.api.LocalLB.VirtualServer.get_rule(self.virtual_servers)
def get_security_log_profile(self):
return self.api.LocalLB.VirtualServer.get_security_log_profile(self.virtual_servers)
def get_snat_pool(self):
return self.api.LocalLB.VirtualServer.get_snat_pool(self.virtual_servers)
def get_snat_type(self):
return self.api.LocalLB.VirtualServer.get_snat_type(self.virtual_servers)
def get_source_address(self):
return self.api.LocalLB.VirtualServer.get_source_address(self.virtual_servers)
def get_source_address_translation_lsn_pool(self):
return self.api.LocalLB.VirtualServer.get_source_address_translation_lsn_pool(self.virtual_servers)
def get_source_address_translation_snat_pool(self):
return self.api.LocalLB.VirtualServer.get_source_address_translation_snat_pool(self.virtual_servers)
def get_source_address_translation_type(self):
return self.api.LocalLB.VirtualServer.get_source_address_translation_type(self.virtual_servers)
def get_source_port_behavior(self):
return self.api.LocalLB.VirtualServer.get_source_port_behavior(self.virtual_servers)
def get_staged_firewall_policy(self):
return self.api.LocalLB.VirtualServer.get_staged_firewall_policy(self.virtual_servers)
def get_translate_address_state(self):
return self.api.LocalLB.VirtualServer.get_translate_address_state(self.virtual_servers)
def get_translate_port_state(self):
return self.api.LocalLB.VirtualServer.get_translate_port_state(self.virtual_servers)
def get_type(self):
return self.api.LocalLB.VirtualServer.get_type(self.virtual_servers)
def get_vlan(self):
return self.api.LocalLB.VirtualServer.get_vlan(self.virtual_servers)
def get_wildmask(self):
return self.api.LocalLB.VirtualServer.get_wildmask(self.virtual_servers)
class Pools(object):
"""Pools class.
F5 BIG-IP pools class.
Attributes:
api: iControl API instance.
pool_names: List of pool names.
"""
def __init__(self, api, regex=None):
self.api = api
self.pool_names = api.LocalLB.Pool.get_list()
if regex:
re_filter = re.compile(regex)
self.pool_names = filter(re_filter.search, self.pool_names)
def get_list(self):
return self.pool_names
def get_action_on_service_down(self):
return self.api.LocalLB.Pool.get_action_on_service_down(self.pool_names)
def get_active_member_count(self):
return self.api.LocalLB.Pool.get_active_member_count(self.pool_names)
def get_aggregate_dynamic_ratio(self):
return self.api.LocalLB.Pool.get_aggregate_dynamic_ratio(self.pool_names)
def get_allow_nat_state(self):
return self.api.LocalLB.Pool.get_allow_nat_state(self.pool_names)
def get_allow_snat_state(self):
return self.api.LocalLB.Pool.get_allow_snat_state(self.pool_names)
def get_client_ip_tos(self):
return self.api.LocalLB.Pool.get_client_ip_tos(self.pool_names)
def get_client_link_qos(self):
return self.api.LocalLB.Pool.get_client_link_qos(self.pool_names)
def get_description(self):
return self.api.LocalLB.Pool.get_description(self.pool_names)
def get_gateway_failsafe_device(self):
return self.api.LocalLB.Pool.get_gateway_failsafe_device(self.pool_names)
def get_ignore_persisted_weight_state(self):
return self.api.LocalLB.Pool.get_ignore_persisted_weight_state(self.pool_names)
def get_lb_method(self):
return self.api.LocalLB.Pool.get_lb_method(self.pool_names)
def get_member(self):
return self.api.LocalLB.Pool.get_member_v2(self.pool_names)
def get_minimum_active_member(self):
return self.api.LocalLB.Pool.get_minimum_active_member(self.pool_names)
def get_minimum_up_member(self):
return self.api.LocalLB.Pool.get_minimum_up_member(self.pool_names)
def get_minimum_up_member_action(self):
return self.api.LocalLB.Pool.get_minimum_up_member_action(self.pool_names)
def get_minimum_up_member_enabled_state(self):
return self.api.LocalLB.Pool.get_minimum_up_member_enabled_state(self.pool_names)
def get_monitor_association(self):
return self.api.LocalLB.Pool.get_monitor_association(self.pool_names)
def get_monitor_instance(self):
return self.api.LocalLB.Pool.get_monitor_instance(self.pool_names)
def get_object_status(self):
return self.api.LocalLB.Pool.get_object_status(self.pool_names)
def get_profile(self):
return self.api.LocalLB.Pool.get_profile(self.pool_names)
def get_queue_depth_limit(self):
return self.api.LocalLB.Pool.get_queue_depth_limit(self.pool_names)
def get_queue_on_connection_limit_state(self):
return self.api.LocalLB.Pool.get_queue_on_connection_limit_state(self.pool_names)
def get_queue_time_limit(self):
return self.api.LocalLB.Pool.get_queue_time_limit(self.pool_names)
def get_reselect_tries(self):
return self.api.LocalLB.Pool.get_reselect_tries(self.pool_names)
def get_server_ip_tos(self):
return self.api.LocalLB.Pool.get_server_ip_tos(self.pool_names)
def get_server_link_qos(self):
return self.api.LocalLB.Pool.get_server_link_qos(self.pool_names)
def get_simple_timeout(self):
return self.api.LocalLB.Pool.get_simple_timeout(self.pool_names)
def get_slow_ramp_time(self):
return self.api.LocalLB.Pool.get_slow_ramp_time(self.pool_names)
class Devices(object):
"""Devices class.
F5 BIG-IP devices class.
Attributes:
api: iControl API instance.
devices: List of devices.
"""
def __init__(self, api, regex=None):
self.api = api
self.devices = api.Management.Device.get_list()
if regex:
re_filter = re.compile(regex)
self.devices = filter(re_filter.search, self.devices)
def get_list(self):
return self.devices
def get_active_modules(self):
return self.api.Management.Device.get_active_modules(self.devices)
def get_base_mac_address(self):
return self.api.Management.Device.get_base_mac_address(self.devices)
def get_blade_addresses(self):
return self.api.Management.Device.get_blade_addresses(self.devices)
def get_build(self):
return self.api.Management.Device.get_build(self.devices)
def get_chassis_id(self):
return self.api.Management.Device.get_chassis_id(self.devices)
def get_chassis_type(self):
return self.api.Management.Device.get_chassis_type(self.devices)
def get_comment(self):
return self.api.Management.Device.get_comment(self.devices)
def get_configsync_address(self):
return self.api.Management.Device.get_configsync_address(self.devices)
def get_contact(self):
return self.api.Management.Device.get_contact(self.devices)
def get_description(self):
return self.api.Management.Device.get_description(self.devices)
def get_edition(self):
return self.api.Management.Device.get_edition(self.devices)
def get_failover_state(self):
return self.api.Management.Device.get_failover_state(self.devices)
def get_local_device(self):
return self.api.Management.Device.get_local_device()
def get_hostname(self):
return self.api.Management.Device.get_hostname(self.devices)
def get_inactive_modules(self):
return self.api.Management.Device.get_inactive_modules(self.devices)
def get_location(self):
return self.api.Management.Device.get_location(self.devices)
def get_management_address(self):
return self.api.Management.Device.get_management_address(self.devices)
def get_marketing_name(self):
return self.api.Management.Device.get_marketing_name(self.devices)
def get_multicast_address(self):
return self.api.Management.Device.get_multicast_address(self.devices)
def get_optional_modules(self):
return self.api.Management.Device.get_optional_modules(self.devices)
def get_platform_id(self):
return self.api.Management.Device.get_platform_id(self.devices)
def get_primary_mirror_address(self):
return self.api.Management.Device.get_primary_mirror_address(self.devices)
def get_product(self):
return self.api.Management.Device.get_product(self.devices)
def get_secondary_mirror_address(self):
return self.api.Management.Device.get_secondary_mirror_address(self.devices)
def get_software_version(self):
return self.api.Management.Device.get_software_version(self.devices)
def get_timelimited_modules(self):
return self.api.Management.Device.get_timelimited_modules(self.devices)
def get_timezone(self):
return self.api.Management.Device.get_timezone(self.devices)
def get_unicast_addresses(self):
return self.api.Management.Device.get_unicast_addresses(self.devices)
class DeviceGroups(object):
"""Device groups class.
F5 BIG-IP device groups class.
Attributes:
api: iControl API instance.
device_groups: List of device groups.
"""
def __init__(self, api, regex=None):
self.api = api
self.device_groups = api.Management.DeviceGroup.get_list()
if regex:
re_filter = re.compile(regex)
self.device_groups = filter(re_filter.search, self.device_groups)
def get_list(self):
return self.device_groups
def get_all_preferred_active(self):
return self.api.Management.DeviceGroup.get_all_preferred_active(self.device_groups)
def get_autosync_enabled_state(self):
return self.api.Management.DeviceGroup.get_autosync_enabled_state(self.device_groups)
def get_description(self):
return self.api.Management.DeviceGroup.get_description(self.device_groups)
def get_device(self):
return self.api.Management.DeviceGroup.get_device(self.device_groups)
def get_full_load_on_sync_state(self):
return self.api.Management.DeviceGroup.get_full_load_on_sync_state(self.device_groups)
def get_incremental_config_sync_size_maximum(self):
return self.api.Management.DeviceGroup.get_incremental_config_sync_size_maximum(self.device_groups)
def get_network_failover_enabled_state(self):
return self.api.Management.DeviceGroup.get_network_failover_enabled_state(self.device_groups)
def get_sync_status(self):
return self.api.Management.DeviceGroup.get_sync_status(self.device_groups)
def get_type(self):
return self.api.Management.DeviceGroup.get_type(self.device_groups)
class TrafficGroups(object):
"""Traffic groups class.
F5 BIG-IP traffic groups class.
Attributes:
api: iControl API instance.
traffic_groups: List of traffic groups.
"""
def __init__(self, api, regex=None):
self.api = api
self.traffic_groups = api.Management.TrafficGroup.get_list()
if regex:
re_filter = re.compile(regex)
self.traffic_groups = filter(re_filter.search, self.traffic_groups)
def get_list(self):
return self.traffic_groups
def get_auto_failback_enabled_state(self):
return self.api.Management.TrafficGroup.get_auto_failback_enabled_state(self.traffic_groups)
def get_auto_failback_time(self):
return self.api.Management.TrafficGroup.get_auto_failback_time(self.traffic_groups)
def get_default_device(self):
return self.api.Management.TrafficGroup.get_default_device(self.traffic_groups)
def get_description(self):
return self.api.Management.TrafficGroup.get_description(self.traffic_groups)
def get_ha_load_factor(self):
return self.api.Management.TrafficGroup.get_ha_load_factor(self.traffic_groups)
def get_ha_order(self):
return self.api.Management.TrafficGroup.get_ha_order(self.traffic_groups)
def get_is_floating(self):
return self.api.Management.TrafficGroup.get_is_floating(self.traffic_groups)
def get_mac_masquerade_address(self):
return self.api.Management.TrafficGroup.get_mac_masquerade_address(self.traffic_groups)
def get_unit_id(self):
return self.api.Management.TrafficGroup.get_unit_id(self.traffic_groups)
class Rules(object):
"""Rules class.
F5 BIG-IP iRules class.
Attributes:
api: iControl API instance.
rules: List of iRules.
"""
def __init__(self, api, regex=None):
self.api = api
self.rules = api.LocalLB.Rule.get_list()
if regex:
re_filter = re.compile(regex)
self.traffic_groups = filter(re_filter.search, self.rules)
def get_list(self):
return self.rules
def get_description(self):
return self.api.LocalLB.Rule.get_description(rule_names=self.rules)
def get_ignore_vertification(self):
return self.api.LocalLB.Rule.get_ignore_vertification(rule_names=self.rules)
def get_verification_status(self):
return self.api.LocalLB.Rule.get_verification_status_v2(rule_names=self.rules)
def get_definition(self):
return [x['rule_definition'] for x in self.api.LocalLB.Rule.query_rule(rule_names=self.rules)]
class Nodes(object):
"""Nodes class.
F5 BIG-IP nodes class.
Attributes:
api: iControl API instance.
nodes: List of nodes.
"""
def __init__(self, api, regex=None):
self.api = api
self.nodes = api.LocalLB.NodeAddressV2.get_list()
if regex:
re_filter = re.compile(regex)
self.nodes = filter(re_filter.search, self.nodes)
def get_list(self):
return self.nodes
def get_address(self):
return self.api.LocalLB.NodeAddressV2.get_address(nodes=self.nodes)
def get_connection_limit(self):
return self.api.LocalLB.NodeAddressV2.get_connection_limit(nodes=self.nodes)
def get_description(self):
return self.api.LocalLB.NodeAddressV2.get_description(nodes=self.nodes)
def get_dynamic_ratio(self):
return self.api.LocalLB.NodeAddressV2.get_dynamic_ratio_v2(nodes=self.nodes)
def get_monitor_instance(self):
return self.api.LocalLB.NodeAddressV2.get_monitor_instance(nodes=self.nodes)
def get_monitor_rule(self):
return self.api.LocalLB.NodeAddressV2.get_monitor_rule(nodes=self.nodes)
def get_monitor_status(self):
return self.api.LocalLB.NodeAddressV2.get_monitor_status(nodes=self.nodes)
def get_object_status(self):
return self.api.LocalLB.NodeAddressV2.get_object_status(nodes=self.nodes)
def get_rate_limit(self):
return self.api.LocalLB.NodeAddressV2.get_rate_limit(nodes=self.nodes)
def get_ratio(self):
return self.api.LocalLB.NodeAddressV2.get_ratio(nodes=self.nodes)
def get_session_status(self):
return self.api.LocalLB.NodeAddressV2.get_session_status(nodes=self.nodes)
class VirtualAddresses(object):
"""Virtual addresses class.
F5 BIG-IP virtual addresses class.
Attributes:
api: iControl API instance.
virtual_addresses: List of virtual addresses.
"""
def __init__(self, api, regex=None):
self.api = api
self.virtual_addresses = api.LocalLB.VirtualAddressV2.get_list()
if regex:
re_filter = re.compile(regex)
self.virtual_addresses = filter(re_filter.search, self.virtual_addresses)
def get_list(self):
return self.virtual_addresses
def get_address(self):
return self.api.LocalLB.VirtualAddressV2.get_address(self.virtual_addresses)
def get_arp_state(self):
return self.api.LocalLB.VirtualAddressV2.get_arp_state(self.virtual_addresses)
def get_auto_delete_state(self):
return self.api.LocalLB.VirtualAddressV2.get_auto_delete_state(self.virtual_addresses)
def get_connection_limit(self):
return self.api.LocalLB.VirtualAddressV2.get_connection_limit(self.virtual_addresses)
def get_description(self):
return self.api.LocalLB.VirtualAddressV2.get_description(self.virtual_addresses)
def get_enabled_state(self):
return self.api.LocalLB.VirtualAddressV2.get_enabled_state(self.virtual_addresses)
def get_icmp_echo_state(self):
return self.api.LocalLB.VirtualAddressV2.get_icmp_echo_state(self.virtual_addresses)
def get_is_floating_state(self):
return self.api.LocalLB.VirtualAddressV2.get_is_floating_state(self.virtual_addresses)
def get_netmask(self):
return self.api.LocalLB.VirtualAddressV2.get_netmask(self.virtual_addresses)
def get_object_status(self):
return self.api.LocalLB.VirtualAddressV2.get_object_status(self.virtual_addresses)
def get_route_advertisement_state(self):
return self.api.LocalLB.VirtualAddressV2.get_route_advertisement_state(self.virtual_addresses)
def get_traffic_group(self):
return self.api.LocalLB.VirtualAddressV2.get_traffic_group(self.virtual_addresses)
class AddressClasses(object):
"""Address group/class class.
F5 BIG-IP address group/class class.
Attributes:
api: iControl API instance.
address_classes: List of address classes.
"""
def __init__(self, api, regex=None):
self.api = api
self.address_classes = api.LocalLB.Class.get_address_class_list()
if regex:
re_filter = re.compile(regex)
self.address_classes = filter(re_filter.search, self.address_classes)
def get_list(self):
return self.address_classes
def get_address_class(self):
key = self.api.LocalLB.Class.get_address_class(self.address_classes)
value = self.api.LocalLB.Class.get_address_class_member_data_value(key)
result = list(map(zip, [x['members'] for x in key], value))
return result
def get_description(self):
return self.api.LocalLB.Class.get_description(self.address_classes)
class Certificates(object):
"""Certificates class.
F5 BIG-IP certificates class.
Attributes:
api: iControl API instance.
certificates: List of certificate identifiers.
certificate_list: List of certificate information structures.
"""
def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"):
self.api = api
self.certificate_list = api.Management.KeyCertificate.get_certificate_list(mode=mode)
self.certificates = [x['certificate']['cert_info']['id'] for x in self.certificate_list]
if regex:
re_filter = re.compile(regex)
self.certificates = filter(re_filter.search, self.certificates)
self.certificate_list = [x for x in self.certificate_list if x['certificate']['cert_info']['id'] in self.certificates]
def get_list(self):
return self.certificates
def get_certificate_list(self):
return self.certificate_list
class Keys(object):
"""Keys class.
F5 BIG-IP keys class.
Attributes:
api: iControl API instance.
keys: List of key identifiers.
key_list: List of key information structures.
"""
def __init__(self, api, regex=None, mode="MANAGEMENT_MODE_DEFAULT"):
self.api = api
self.key_list = api.Management.KeyCertificate.get_key_list(mode=mode)
self.keys = [x['key_info']['id'] for x in self.key_list]
if regex:
re_filter = re.compile(regex)
self.keys = filter(re_filter.search, self.keys)
self.key_list = [x for x in self.key_list if x['key_info']['id'] in self.keys]
def get_list(self):
return self.keys
def get_key_list(self):
return self.key_list
class ProfileClientSSL(object):
"""Client SSL profiles class.
F5 BIG-IP client SSL profiles class.
Attributes:
api: iControl API instance.
profiles: List of client SSL profiles.
"""
def __init__(self, api, regex=None):
self.api = api
self.profiles = api.LocalLB.ProfileClientSSL.get_list()
if regex:
re_filter = re.compile(regex)
self.profiles = filter(re_filter.search, self.profiles)
def get_list(self):
return self.profiles
def get_alert_timeout(self):
return self.api.LocalLB.ProfileClientSSL.get_alert_timeout(self.profiles)
def get_allow_nonssl_state(self):
return self.api.LocalLB.ProfileClientSSL.get_allow_nonssl_state(self.profiles)
def get_authenticate_depth(self):
return self.api.LocalLB.ProfileClientSSL.get_authenticate_depth(self.profiles)
def get_authenticate_once_state(self):
return self.api.LocalLB.ProfileClientSSL.get_authenticate_once_state(self.profiles)
def get_ca_file(self):
return self.api.LocalLB.ProfileClientSSL.get_ca_file_v2(self.profiles)
def get_cache_size(self):
return self.api.LocalLB.ProfileClientSSL.get_cache_size(self.profiles)
def get_cache_timeout(self):
return self.api.LocalLB.ProfileClientSSL.get_cache_timeout(self.profiles)
def get_certificate_file(self):
return self.api.LocalLB.ProfileClientSSL.get_certificate_file_v2(self.profiles)
def get_chain_file(self):
return self.api.LocalLB.ProfileClientSSL.get_chain_file_v2(self.profiles)
def get_cipher_list(self):
return self.api.LocalLB.ProfileClientSSL.get_cipher_list(self.profiles)
def get_client_certificate_ca_file(self):
return self.api.LocalLB.ProfileClientSSL.get_client_certificate_ca_file_v2(self.profiles)
def get_crl_file(self):
return self.api.LocalLB.ProfileClientSSL.get_crl_file_v2(self.profiles)
def get_default_profile(self):
return self.api.LocalLB.ProfileClientSSL.get_default_profile(self.profiles)
def get_description(self):
return self.api.LocalLB.ProfileClientSSL.get_description(self.profiles)
def get_forward_proxy_ca_certificate_file(self):
return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_certificate_file(self.profiles)
def get_forward_proxy_ca_key_file(self):
return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_key_file(self.profiles)
def get_forward_proxy_ca_passphrase(self):
return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_ca_passphrase(self.profiles)
def get_forward_proxy_certificate_extension_include(self):
return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_extension_include(self.profiles)
def get_forward_proxy_certificate_lifespan(self):
return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_certificate_lifespan(self.profiles)
def get_forward_proxy_enabled_state(self):
return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_enabled_state(self.profiles)
def get_forward_proxy_lookup_by_ipaddr_port_state(self):
return self.api.LocalLB.ProfileClientSSL.get_forward_proxy_lookup_by_ipaddr_port_state(self.profiles)
def get_handshake_timeout(self):
return self.api.LocalLB.ProfileClientSSL.get_handshake_timeout(self.profiles)
def get_key_file(self):
return self.api.LocalLB.ProfileClientSSL.get_key_file_v2(self.profiles)
def get_modssl_emulation_state(self):
return self.api.LocalLB.ProfileClientSSL.get_modssl_emulation_state(self.profiles)
def get_passphrase(self):
return self.api.LocalLB.ProfileClientSSL.get_passphrase(self.profiles)
def get_peer_certification_mode(self):
return self.api.LocalLB.ProfileClientSSL.get_peer_certification_mode(self.profiles)
def get_profile_mode(self):
return self.api.LocalLB.ProfileClientSSL.get_profile_mode(self.profiles)
def get_renegotiation_maximum_record_delay(self):
return self.api.LocalLB.ProfileClientSSL.get_renegotiation_maximum_record_delay(self.profiles)
def get_renegotiation_period(self):
return self.api.LocalLB.ProfileClientSSL.get_renegotiation_period(self.profiles)
def get_renegotiation_state(self):
return self.api.LocalLB.ProfileClientSSL.get_renegotiation_state(self.profiles)
def get_renegotiation_throughput(self):
return self.api.LocalLB.ProfileClientSSL.get_renegotiation_throughput(self.profiles)
def get_retain_certificate_state(self):
return self.api.LocalLB.ProfileClientSSL.get_retain_certificate_state(self.profiles)
def get_secure_renegotiation_mode(self):
return self.api.LocalLB.ProfileClientSSL.get_secure_renegotiation_mode(self.profiles)
def get_server_name(self):
return self.api.LocalLB.ProfileClientSSL.get_server_name(self.profiles)
def get_session_ticket_state(self):
return self.api.LocalLB.ProfileClientSSL.get_session_ticket_state(self.profiles)
def get_sni_default_state(self):
return self.api.LocalLB.ProfileClientSSL.get_sni_default_state(self.profiles)
def get_sni_require_state(self):
return self.api.LocalLB.ProfileClientSSL.get_sni_require_state(self.profiles)
def get_ssl_option(self):
return self.api.LocalLB.ProfileClientSSL.get_ssl_option(self.profiles)
def get_strict_resume_state(self):
return self.api.LocalLB.ProfileClientSSL.get_strict_resume_state(self.profiles)
def get_unclean_shutdown_state(self):
return self.api.LocalLB.ProfileClientSSL.get_unclean_shutdown_state(self.profiles)
def get_is_base_profile(self):
return self.api.LocalLB.ProfileClientSSL.is_base_profile(self.profiles)
def get_is_system_profile(self):
return self.api.LocalLB.ProfileClientSSL.is_system_profile(self.profiles)
class SystemInfo(object):
"""System information class.
F5 BIG-IP system information class.
Attributes:
api: iControl API instance.
"""
def __init__(self, api):
self.api = api
def get_base_mac_address(self):
return self.api.System.SystemInfo.get_base_mac_address()
def get_blade_temperature(self):
return self.api.System.SystemInfo.get_blade_temperature()
def get_chassis_slot_information(self):
return self.api.System.SystemInfo.get_chassis_slot_information()
def get_globally_unique_identifier(self):
return self.api.System.SystemInfo.get_globally_unique_identifier()
def get_group_id(self):
return self.api.System.SystemInfo.get_group_id()
def get_hardware_information(self):
return self.api.System.SystemInfo.get_hardware_information()
def get_marketing_name(self):
return self.api.System.SystemInfo.get_marketing_name()
def get_product_information(self):
return self.api.System.SystemInfo.get_product_information()
def get_pva_version(self):
return self.api.System.SystemInfo.get_pva_version()
def get_system_id(self):
return self.api.System.SystemInfo.get_system_id()
def get_system_information(self):
return self.api.System.SystemInfo.get_system_information()
def get_time(self):
return self.api.System.SystemInfo.get_time()
def get_time_zone(self):
return self.api.System.SystemInfo.get_time_zone()
def get_uptime(self):
return self.api.System.SystemInfo.get_uptime()
class ProvisionInfo(object):
"""Provision information class.
F5 BIG-IP provision information class.
Attributes:
api: iControl API instance.
"""
def __init__(self, api):
self.api = api
def get_list(self):
result = []
list = self.api.Management.Provision.get_list()
for item in list:
item = item.lower().replace('tmos_module_', '')
result.append(item)
return result
def get_provisioned_list(self):
result = []
list = self.api.Management.Provision.get_provisioned_list()
for item in list:
item = item.lower().replace('tmos_module_', '')
result.append(item)
return result
def generate_dict(api_obj, fields):
result_dict = {}
lists = []
supported_fields = []
if api_obj.get_list():
for field in fields:
try:
api_response = getattr(api_obj, "get_" + field)()
except (MethodNotFound, WebFault):
pass
else:
lists.append(api_response)
supported_fields.append(field)
for i, j in enumerate(api_obj.get_list()):
temp = {}
temp.update([(item[0], item[1][i]) for item in zip(supported_fields, lists)])
result_dict[j] = temp
return result_dict
def generate_simple_dict(api_obj, fields):
result_dict = {}
for field in fields:
try:
api_response = getattr(api_obj, "get_" + field)()
except (MethodNotFound, WebFault):
pass
else:
result_dict[field] = api_response
return result_dict
def generate_interface_dict(f5, regex):
interfaces = Interfaces(f5.get_api(), regex)
fields = ['active_media', 'actual_flow_control', 'bundle_state',
'description', 'dual_media_state', 'enabled_state', 'if_index',
'learning_mode', 'lldp_admin_status', 'lldp_tlvmap',
'mac_address', 'media', 'media_option', 'media_option_sfp',
'media_sfp', 'media_speed', 'media_status', 'mtu',
'phy_master_slave_mode', 'prefer_sfp_state', 'flow_control',
'sflow_poll_interval', 'sflow_poll_interval_global',
'sfp_media_state', 'stp_active_edge_port_state',
'stp_enabled_state', 'stp_link_type',
'stp_protocol_detection_reset_state']
return generate_dict(interfaces, fields)
def generate_self_ip_dict(f5, regex):
self_ips = SelfIPs(f5.get_api(), regex)
fields = ['address', 'allow_access_list', 'description',
'enforced_firewall_policy', 'floating_state', 'fw_rule',
'netmask', 'staged_firewall_policy', 'traffic_group',
'vlan', 'is_traffic_group_inherited']
return generate_dict(self_ips, fields)
def generate_trunk_dict(f5, regex):
trunks = Trunks(f5.get_api(), regex)
fields = ['active_lacp_state', 'configured_member_count', 'description',
'distribution_hash_option', 'interface', 'lacp_enabled_state',
'lacp_timeout_option', 'link_selection_policy', 'media_speed',
'media_status', 'operational_member_count', 'stp_enabled_state',
'stp_protocol_detection_reset_state']
return generate_dict(trunks, fields)
def generate_vlan_dict(f5, regex):
vlans = Vlans(f5.get_api(), regex)
fields = ['auto_lasthop', 'cmp_hash_algorithm', 'description',
'dynamic_forwarding', 'failsafe_action', 'failsafe_state',
'failsafe_timeout', 'if_index', 'learning_mode',
'mac_masquerade_address', 'member', 'mtu',
'sflow_poll_interval', 'sflow_poll_interval_global',
'sflow_sampling_rate', 'sflow_sampling_rate_global',
'source_check_state', 'true_mac_address', 'vlan_id']
return generate_dict(vlans, fields)
def generate_vs_dict(f5, regex):
virtual_servers = VirtualServers(f5.get_api(), regex)
fields = ['actual_hardware_acceleration', 'authentication_profile',
'auto_lasthop', 'bw_controller_policy', 'clone_pool',
'cmp_enable_mode', 'connection_limit', 'connection_mirror_state',
'default_pool_name', 'description', 'destination',
'enabled_state', 'enforced_firewall_policy',
'fallback_persistence_profile', 'fw_rule', 'gtm_score',
'last_hop_pool', 'nat64_state', 'object_status',
'persistence_profile', 'profile', 'protocol',
'rate_class', 'rate_limit', 'rate_limit_destination_mask',
'rate_limit_mode', 'rate_limit_source_mask', 'related_rule',
'rule', 'security_log_profile', 'snat_pool', 'snat_type',
'source_address', 'source_address_translation_lsn_pool',
'source_address_translation_snat_pool',
'source_address_translation_type', 'source_port_behavior',
'staged_firewall_policy', 'translate_address_state',
'translate_port_state', 'type', 'vlan', 'wildmask']
return generate_dict(virtual_servers, fields)
def generate_pool_dict(f5, regex):
pools = Pools(f5.get_api(), regex)
fields = ['action_on_service_down', 'active_member_count',
'aggregate_dynamic_ratio', 'allow_nat_state',
'allow_snat_state', 'client_ip_tos', 'client_link_qos',
'description', 'gateway_failsafe_device',
'ignore_persisted_weight_state', 'lb_method', 'member',
'minimum_active_member', 'minimum_up_member',
'minimum_up_member_action', 'minimum_up_member_enabled_state',
'monitor_association', 'monitor_instance', 'object_status',
'profile', 'queue_depth_limit',
'queue_on_connection_limit_state', 'queue_time_limit',
'reselect_tries', 'server_ip_tos', 'server_link_qos',
'simple_timeout', 'slow_ramp_time']
return generate_dict(pools, fields)
def generate_device_dict(f5, regex):
devices = Devices(f5.get_api(), regex)
fields = ['active_modules', 'base_mac_address', 'blade_addresses',
'build', 'chassis_id', 'chassis_type', 'comment',
'configsync_address', 'contact', 'description', 'edition',
'failover_state', 'hostname', 'inactive_modules', 'location',
'management_address', 'marketing_name', 'multicast_address',
'optional_modules', 'platform_id', 'primary_mirror_address',
'product', 'secondary_mirror_address', 'software_version',
'timelimited_modules', 'timezone', 'unicast_addresses']
return generate_dict(devices, fields)
def generate_device_group_dict(f5, regex):
device_groups = DeviceGroups(f5.get_api(), regex)
fields = ['all_preferred_active', 'autosync_enabled_state', 'description',
'device', 'full_load_on_sync_state',
'incremental_config_sync_size_maximum',
'network_failover_enabled_state', 'sync_status', 'type']
return generate_dict(device_groups, fields)
def generate_traffic_group_dict(f5, regex):
traffic_groups = TrafficGroups(f5.get_api(), regex)
fields = ['auto_failback_enabled_state', 'auto_failback_time',
'default_device', 'description', 'ha_load_factor',
'ha_order', 'is_floating', 'mac_masquerade_address',
'unit_id']
return generate_dict(traffic_groups, fields)
def generate_rule_dict(f5, regex):
rules = Rules(f5.get_api(), regex)
fields = ['definition', 'description', 'ignore_vertification',
'verification_status']
return generate_dict(rules, fields)
def generate_node_dict(f5, regex):
nodes = Nodes(f5.get_api(), regex)
fields = ['address', 'connection_limit', 'description', 'dynamic_ratio',
'monitor_instance', 'monitor_rule', 'monitor_status',
'object_status', 'rate_limit', 'ratio', 'session_status']
return generate_dict(nodes, fields)
def generate_virtual_address_dict(f5, regex):
virtual_addresses = VirtualAddresses(f5.get_api(), regex)
fields = ['address', 'arp_state', 'auto_delete_state', 'connection_limit',
'description', 'enabled_state', 'icmp_echo_state',
'is_floating_state', 'netmask', 'object_status',
'route_advertisement_state', 'traffic_group']
return generate_dict(virtual_addresses, fields)
def generate_address_class_dict(f5, regex):
address_classes = AddressClasses(f5.get_api(), regex)
fields = ['address_class', 'description']
return generate_dict(address_classes, fields)
def generate_certificate_dict(f5, regex):
certificates = Certificates(f5.get_api(), regex)
return dict(zip(certificates.get_list(), certificates.get_certificate_list()))
def generate_key_dict(f5, regex):
keys = Keys(f5.get_api(), regex)
return dict(zip(keys.get_list(), keys.get_key_list()))
def generate_client_ssl_profile_dict(f5, regex):
profiles = ProfileClientSSL(f5.get_api(), regex)
fields = ['alert_timeout', 'allow_nonssl_state', 'authenticate_depth',
'authenticate_once_state', 'ca_file', 'cache_size',
'cache_timeout', 'certificate_file', 'chain_file',
'cipher_list', 'client_certificate_ca_file', 'crl_file',
'default_profile', 'description',
'forward_proxy_ca_certificate_file', 'forward_proxy_ca_key_file',
'forward_proxy_ca_passphrase',
'forward_proxy_certificate_extension_include',
'forward_proxy_certificate_lifespan',
'forward_proxy_enabled_state',
'forward_proxy_lookup_by_ipaddr_port_state', 'handshake_timeout',
'key_file', 'modssl_emulation_state', 'passphrase',
'peer_certification_mode', 'profile_mode',
'renegotiation_maximum_record_delay', 'renegotiation_period',
'renegotiation_state', 'renegotiation_throughput',
'retain_certificate_state', 'secure_renegotiation_mode',
'server_name', 'session_ticket_state', 'sni_default_state',
'sni_require_state', 'ssl_option', 'strict_resume_state',
'unclean_shutdown_state', 'is_base_profile', 'is_system_profile']
return generate_dict(profiles, fields)
def generate_system_info_dict(f5):
system_info = SystemInfo(f5.get_api())
fields = ['base_mac_address',
'blade_temperature', 'chassis_slot_information',
'globally_unique_identifier', 'group_id',
'hardware_information',
'marketing_name',
'product_information', 'pva_version', 'system_id',
'system_information', 'time',
'time_zone', 'uptime']
return generate_simple_dict(system_info, fields)
def generate_software_list(f5):
software = Software(f5.get_api())
software_list = software.get_all_software_status()
return software_list
def generate_provision_dict(f5):
provisioned = ProvisionInfo(f5.get_api())
fields = ['list', 'provisioned_list']
return generate_simple_dict(provisioned, fields)
def main():
argument_spec = f5_argument_spec()
meta_args = dict(
session=dict(type='bool', default=False),
include=dict(type='list', required=True),
filter=dict(type='str', required=False),
)
argument_spec.update(meta_args)
module = AnsibleModule(
argument_spec=argument_spec
)
if not bigsuds_found:
module.fail_json(msg="the python suds and bigsuds modules are required")
server = module.params['server']
server_port = module.params['server_port']
user = module.params['user']
password = module.params['password']
validate_certs = module.params['validate_certs']
session = module.params['session']
fact_filter = module.params['filter']
if validate_certs:
import ssl
if not hasattr(ssl, 'SSLContext'):
module.fail_json(
msg='bigsuds does not support verifying certificates with python < 2.7.9. Either update python or set validate_certs=False on the task'
)
if fact_filter:
regex = fnmatch.translate(fact_filter)
else:
regex = None
include = [x.lower() for x in module.params['include']]
valid_includes = ('address_class', 'certificate', 'client_ssl_profile',
'device', 'device_group', 'interface', 'key', 'node',
'pool', 'provision', 'rule', 'self_ip', 'software',
'system_info', 'traffic_group', 'trunk',
'virtual_address', 'virtual_server', 'vlan')
include_test = map(lambda x: x in valid_includes, include)
if not all(include_test):
module.fail_json(msg="value of include must be one or more of: %s, got: %s" % (",".join(valid_includes), ",".join(include)))
try:
facts = {}
if len(include) > 0:
f5 = F5(server, user, password, session, validate_certs, server_port)
saved_active_folder = f5.get_active_folder()
saved_recursive_query_state = f5.get_recursive_query_state()
if saved_active_folder != "/":
f5.set_active_folder("/")
if saved_recursive_query_state != "STATE_ENABLED":
f5.enable_recursive_query_state()
if 'interface' in include:
facts['interface'] = generate_interface_dict(f5, regex)
if 'self_ip' in include:
facts['self_ip'] = generate_self_ip_dict(f5, regex)
if 'trunk' in include:
facts['trunk'] = generate_trunk_dict(f5, regex)
if 'vlan' in include:
facts['vlan'] = generate_vlan_dict(f5, regex)
if 'virtual_server' in include:
facts['virtual_server'] = generate_vs_dict(f5, regex)
if 'pool' in include:
facts['pool'] = generate_pool_dict(f5, regex)
if 'provision' in include:
facts['provision'] = generate_provision_dict(f5)
if 'device' in include:
facts['device'] = generate_device_dict(f5, regex)
if 'device_group' in include:
facts['device_group'] = generate_device_group_dict(f5, regex)
if 'traffic_group' in include:
facts['traffic_group'] = generate_traffic_group_dict(f5, regex)
if 'rule' in include:
facts['rule'] = generate_rule_dict(f5, regex)
if 'node' in include:
facts['node'] = generate_node_dict(f5, regex)
if 'virtual_address' in include:
facts['virtual_address'] = generate_virtual_address_dict(f5, regex)
if 'address_class' in include:
facts['address_class'] = generate_address_class_dict(f5, regex)
if 'software' in include:
facts['software'] = generate_software_list(f5)
if 'certificate' in include:
facts['certificate'] = generate_certificate_dict(f5, regex)
if 'key' in include:
facts['key'] = generate_key_dict(f5, regex)
if 'client_ssl_profile' in include:
facts['client_ssl_profile'] = generate_client_ssl_profile_dict(f5, regex)
if 'system_info' in include:
facts['system_info'] = generate_system_info_dict(f5)
# restore saved state
if saved_active_folder and saved_active_folder != "/":
f5.set_active_folder(saved_active_folder)
if saved_recursive_query_state and \
saved_recursive_query_state != "STATE_ENABLED":
f5.set_recursive_query_state(saved_recursive_query_state)
result = {'ansible_facts': facts}
except Exception as e:
module.fail_json(msg="received exception: %s\ntraceback: %s" % (e, traceback.format_exc()))
module.exit_json(**result)
# include magic from lib/ansible/module_common.py
from ansible.module_utils.basic import *
from ansible.module_utils.f5_utils import *
if __name__ == '__main__':
main()
|
gpl-3.0
|
Endika/odoo
|
addons/pos_restaurant/__openerp__.py
|
311
|
2001
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
{
'name': 'Restaurant',
'version': '1.0',
'category': 'Point of Sale',
'sequence': 6,
'summary': 'Restaurant extensions for the Point of Sale ',
'description': """
=======================
This module adds several restaurant features to the Point of Sale:
- Bill Printing: Allows you to print a receipt before the order is paid
- Bill Splitting: Allows you to split an order into different orders
- Kitchen Order Printing: allows you to print orders updates to kitchen or bar printers
""",
'author': 'OpenERP SA',
'depends': ['point_of_sale'],
'website': 'https://www.odoo.com/page/point-of-sale',
'data': [
'restaurant_view.xml',
'security/ir.model.access.csv',
'views/templates.xml',
],
'qweb':[
'static/src/xml/multiprint.xml',
'static/src/xml/splitbill.xml',
'static/src/xml/printbill.xml',
],
'installable': True,
'auto_install': False,
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
foursquare/commons-old
|
src/python/twitter/common/process/process_handle.py
|
1
|
3405
|
from twitter.common.string import ScanfParser
try:
from twitter.common import log
except ImportError:
log = None
class ProcessHandle(object):
"""
ProcessHandle interface. Methods that must be exposed by whatever process
monitoring mechanism you use.
"""
def cpu_time(self):
"""
Total cpu time of this process.
"""
raise NotImplementedError
def wall_time(self):
"""
Total wall time this process has been up.
"""
raise NotImplementedError
def pid(self):
"""
PID of the process.
"""
raise NotImplementedError
def ppid(self):
"""
Parent PID of the process.
"""
raise NotImplementedError
def user(self):
"""
The owner of the process.
"""
raise NotImplementedError
def cwd(self):
"""
The current working directory of the process.
"""
raise NotImplementedError
class ProcessHandleParser(ScanfParser):
"""
Given:
attrs: list of attribute names
type_map: map of attribute name to attribute type (%d/%u/etc format converter)
handlers: optional set of postprocessing callbacks that take (attribute, value)
Process a line from one of the process information sources (e.g. ps, procfs.)
"""
def parse(self, line):
d = {}
try:
so = ScanfParser.parse(self, ' '.join(line.split()), True)
for attr, value in zip(self._attrs, so.ungrouped()):
d[attr] = self._handlers[attr](attr, value) if attr in self._handlers else value
except ScanfParser.ParseError as e:
if log: log.error('ProcessHandleParser failed: %s' % e)
return {}
return d
def __init__(self, attrs, type_map, handlers = {}):
self._attrs = attrs
self._handlers = handlers
attr_list = map(type_map.get, attrs)
ScanfParser.__init__(self, ' '.join(attr_list))
class ProcessHandleParserBase(object):
"""
Given a provider of process lines, parse them into bundles of attributes that can be
translated into ProcessHandles.
"""
def _produce(self):
raise NotImplementedError
def _realize(self):
return self._realize_from_line(self._produce())
def _realize_from_line(self, line):
self._exists = False
if line is None:
self._attrs = {}
else:
self._attrs = self.PARSER.parse(line)
if self._attrs:
self._pid = self._attrs['pid']
self._exists = True
@classmethod
def from_line(cls, line):
proc = cls()
proc._realize_from_line(line)
return proc
@classmethod
def init_class(cls):
if not hasattr(cls, 'PARSER'):
assert hasattr(cls, 'ATTRS')
assert hasattr(cls, 'TYPE_MAP')
assert hasattr(cls, 'HANDLERS')
setattr(cls, 'PARSER', ProcessHandleParser(cls.ATTRS, cls.TYPE_MAP, cls.HANDLERS))
if not hasattr(cls, 'ALIASES'):
cls.ALIASES = {}
def __init__(self, pid=-1):
self.init_class()
self._exists = False
self._pid = pid
self._attrs = None
if pid != -1:
self._realize()
def exists(self):
return self._exists
def get(self, key):
probe_key = self.ALIASES[key] if key in self.ALIASES else key
if probe_key in self._attrs:
return self._attrs.get(probe_key)
else:
raise AttributeError("%s not in ProcessHandle" % probe_key)
def refresh(self, line=None):
return self._realize() if line is None else self._realize_from_line(self, line)
|
apache-2.0
|
3nids/QGIS
|
tests/src/python/test_qgsvirtuallayertask.py
|
45
|
2761
|
# -*- coding: utf-8 -*-
"""QGIS Unit tests for QgsVirtualLayerTask.
.. note:: This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
"""
__author__ = 'Paul Blottiere'
__date__ = '28/02/2018'
__copyright__ = 'Copyright 2018, The QGIS Project'
import qgis # NOQA
import os
from qgis.core import (
QgsProject,
QgsVectorLayer,
QgsApplication,
QgsVirtualLayerDefinition,
QgsVirtualLayerTask
)
from qgis.PyQt.QtCore import QCoreApplication
from qgis.testing import start_app, unittest
from utilities import unitTestDataPath
start_app()
class TestQgsVirtualLayerTask(unittest.TestCase):
def setUp(self):
self.testDataDir = unitTestDataPath()
self._success = False
self._fail = False
self.ids = None
self.task = None
def onSuccess(self):
self._success = True
self.ids = [f.id() for f in self.task.layer().getFeatures()]
def onFail(self):
self._fail = True
self._exceptionText = self.task.exceptionText()
def test(self):
l1 = QgsVectorLayer(os.path.join(self.testDataDir, "france_parts.shp"), "françéà", "ogr", QgsVectorLayer.LayerOptions(False))
self.assertEqual(l1.isValid(), True)
QgsProject.instance().addMapLayer(l1)
df = QgsVirtualLayerDefinition()
df.setQuery('select * from "françéà"')
self.task = QgsVirtualLayerTask(df)
ids = [f.id() for f in self.task.layer().getFeatures()]
self.assertEqual(len(ids), 0)
self.task.taskCompleted.connect(self.onSuccess)
self.task.taskTerminated.connect(self.onFail)
QgsApplication.taskManager().addTask(self.task)
while not self._success and not self._fail:
QCoreApplication.processEvents()
self.assertTrue(self._success)
self.assertFalse(self._fail)
self.assertEqual(len(self.ids), 4)
# Test exception
self._success = False
self._fail = False
df.setQuery('select *')
self.task = QgsVirtualLayerTask(df)
self.task.taskCompleted.connect(self.onSuccess)
self.task.taskTerminated.connect(self.onFail)
QgsApplication.taskManager().addTask(self.task)
while not self._success and not self._fail:
QCoreApplication.processEvents()
self.assertFalse(self._success)
self.assertTrue(self._fail)
self.assertEqual(self._exceptionText, 'Query preparation error on PRAGMA table_info(_tview): no tables specified', self._exceptionText)
if __name__ == '__main__':
unittest.main()
|
gpl-2.0
|
myyc/kleptes
|
kleptes/utils.py
|
1
|
1213
|
import re
import fnmatch
import pandas as pd
# three days
EXPIRE = 259200
def get_re(pattern):
if type(pattern) == str:
return re.compile(fnmatch.translate(pattern), flags=re.IGNORECASE)
elif type(pattern) == list:
return re.compile("|".join(fnmatch.translate(pattern)),
flags=re.IGNORECASE)
else:
raise ValueError("'pattern' must either be a string or a list "
"(or None)")
class SearchableDataFrame(pd.DataFrame):
"""A DataFrame that implements a search method via __call__"""
def __call__(self, pattern=None, cols=None):
if pattern is None:
return self
p = get_re(pattern)
if cols not in list(self.columns):
if cols is None:
_df = self.select_dtypes(["object"])
elif type(cols) == list:
_df = self[cols]
else:
raise ValueError("'cols' must be either a 'list', 'None' or "
"the name of a column.")
s = _df.apply(lambda x: x.str.match(p)).sum(axis=1).astype("bool")
else:
s = self[cols].str.match(p)
return self[s]
|
bsd-3-clause
|
poo12138/gem5-stable
|
tests/configs/memtest-ruby.py
|
9
|
4768
|
# Copyright (c) 2006-2007 The Regents of The University of Michigan
# Copyright (c) 2010 Advanced Micro Devices, Inc.
# 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 the copyright holders 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.
#
# Authors: Ron Dreslinski
import m5
from m5.objects import *
from m5.defines import buildEnv
from m5.util import addToPath
import os, optparse, sys
# Get paths we might need
config_path = os.path.dirname(os.path.abspath(__file__))
config_root = os.path.dirname(config_path)
m5_root = os.path.dirname(config_root)
addToPath(config_root+'/configs/common')
addToPath(config_root+'/configs/ruby')
addToPath(config_root+'/configs/topologies')
import Ruby
import Options
parser = optparse.OptionParser()
Options.addCommonOptions(parser)
# Add the ruby specific and protocol specific options
Ruby.define_options(parser)
(options, args) = parser.parse_args()
#
# Set the default cache size and associativity to be very small to encourage
# races between requests and writebacks.
#
options.l1d_size="256B"
options.l1i_size="256B"
options.l2_size="512B"
options.l3_size="1kB"
options.l1d_assoc=2
options.l1i_assoc=2
options.l2_assoc=2
options.l3_assoc=2
options.ports=32
#MAX CORES IS 8 with the fals sharing method
nb_cores = 8
# ruby does not support atomic, functional, or uncacheable accesses
cpus = [ MemTest(atomic=False, percent_functional=50,
percent_uncacheable=0, suppress_func_warnings=True) \
for i in xrange(nb_cores) ]
# overwrite options.num_cpus with the nb_cores value
options.num_cpus = nb_cores
# system simulated
system = System(cpu = cpus,
funcmem = SimpleMemory(in_addr_map = False),
physmem = SimpleMemory(null = True),
funcbus = NoncoherentXBar())
# Dummy voltage domain for all our clock domains
system.voltage_domain = VoltageDomain()
system.clk_domain = SrcClockDomain(clock = '1GHz',
voltage_domain = system.voltage_domain)
# Create a seperate clock domain for components that should run at
# CPUs frequency
system.cpu_clk_domain = SrcClockDomain(clock = '2GHz',
voltage_domain = system.voltage_domain)
# All cpus are associated with cpu_clk_domain
for cpu in cpus:
cpu.clk_domain = system.cpu_clk_domain
system.mem_ranges = AddrRange('256MB')
Ruby.create_system(options, system)
# Create a separate clock domain for Ruby
system.ruby.clk_domain = SrcClockDomain(clock = options.ruby_clock,
voltage_domain = system.voltage_domain)
assert(len(cpus) == len(system.ruby._cpu_ports))
for (i, ruby_port) in enumerate(system.ruby._cpu_ports):
#
# Tie the cpu test and functional ports to the ruby cpu ports and
# physmem, respectively
#
cpus[i].test = ruby_port.slave
cpus[i].functional = system.funcbus.slave
#
# Since the memtester is incredibly bursty, increase the deadlock
# threshold to 1 million cycles
#
ruby_port.deadlock_threshold = 1000000
# connect reference memory to funcbus
system.funcmem.port = system.funcbus.master
# -----------------------
# run simulation
# -----------------------
root = Root(full_system = False, system = system)
root.system.mem_mode = 'timing'
# Not much point in this being higher than the L1 latency
m5.ticks.setGlobalFrequency('1ns')
|
bsd-3-clause
|
safwanrahman/kitsune
|
kitsune/sumo/parser.py
|
3
|
13902
|
from os.path import basename
from urlparse import urlparse, parse_qs
from django.conf import settings
from django.template.loader import render_to_string
from django.utils.translation import ugettext_lazy as _lazy, ugettext as _
from wikimarkup.parser import Parser, ALLOWED_TAGS
from kitsune.gallery.models import Image, Video
from kitsune.sumo import email_utils
from kitsune.sumo.urlresolvers import reverse
ALLOWED_ATTRIBUTES = {
'a': ['href', 'title', 'class', 'rel', 'data-mozilla-ui-reset'],
'div': ['id', 'class', 'style', 'data-for', 'title', 'data-target',
'data-modal'],
'h1': ['id'],
'h2': ['id'],
'h3': ['id'],
'h4': ['id'],
'h5': ['id'],
'h6': ['id'],
'li': ['class'],
'span': ['class', 'data-for'],
'img': ['class', 'src', 'data-original-src', 'alt', 'title', 'height',
'width', 'style'],
'video': ['height', 'width', 'controls', 'data-fallback', 'poster',
'data-width', 'data-height'],
'source': ['src', 'type'],
}
ALLOWED_STYLES = ['vertical-align']
IMAGE_PARAMS = ['alt', 'align', 'caption', 'valign', 'frame', 'page', 'link',
'width', 'height']
IMAGE_PARAM_VALUES = {
'align': ('none', 'left', 'center', 'right'),
'valign': ('baseline', 'sub', 'super', 'top', 'text-top', 'middle',
'bottom', 'text-bottom'),
}
VIDEO_PARAMS = ['height', 'width', 'modal', 'title', 'placeholder']
YOUTUBE_PLACEHOLDER = 'YOUTUBE_EMBED_PLACEHOLDER_%s'
def wiki_to_html(wiki_markup, locale=settings.WIKI_DEFAULT_LANGUAGE,
nofollow=True, tags=None):
"""Wiki Markup -> HTML"""
return WikiParser().parse(wiki_markup, show_toc=False, locale=locale,
nofollow=nofollow, tags=tags)
def get_object_fallback(cls, title, locale, default=None, **kwargs):
"""Return an instance of cls matching title and locale, or fall
back to the default locale.
When falling back to the default locale, follow any wiki redirects
internally.
If the fallback fails, the return value is `default`.
You may pass in additional kwargs which go straight to the query.
"""
try:
return cls.objects.get(title=title, locale=locale, **kwargs)
except (cls.DoesNotExist, IOError):
pass
# Fallback
try:
default_lang_doc = cls.objects.get(
title=title, locale=settings.WIKI_DEFAULT_LANGUAGE, **kwargs)
# Return the translation of this English item:
if hasattr(default_lang_doc, 'translated_to'):
trans = default_lang_doc.translated_to(locale)
if trans and trans.current_revision:
return trans
# Follow redirects internally in an attempt to find a
# translation of the final redirect target in the requested
# locale. This happens a lot when an English article is
# renamed and a redirect is left in its wake: we wouldn't want
# the non-English user to be linked to the English redirect,
# which would happily redirect them to the English final
# article.
if hasattr(default_lang_doc, 'redirect_document'):
target = default_lang_doc.redirect_document()
if target:
trans = target.translated_to(locale)
if trans and trans.current_revision:
return trans
# Return the English item:
return default_lang_doc
# Okay, all else failed
except (cls.DoesNotExist, IOError):
return default
def _get_wiki_link(title, locale):
"""Checks the page exists, and returns its URL or the URL to create it.
Return value is a dict: {'found': boolean, 'url': string}.
found is False if the document does not exist.
"""
# Prevent circular import. sumo is conceptually a utils apps and
# shouldn't have import-time (or really, any, but that's not going
# to happen) dependencies on client apps.
from kitsune.wiki.models import Document
d = get_object_fallback(Document, locale=locale, title=title,
is_template=False)
if d:
# If the article redirects use its destination article
while d.redirect_document():
d = d.redirect_document()
# The locale in the link urls should always match the current
# document's locale even if the document/slug being linked to
# is in the default locale.
url = reverse('wiki.document', locale=locale, args=[d.slug])
return {'found': True, 'url': url, 'text': d.title}
# To avoid circular imports, wiki.models imports wiki_to_html
from kitsune.sumo.templatetags.jinja_helpers import urlparams
return {'found': False,
'text': title,
'url': urlparams(reverse('wiki.new_document', locale=locale),
title=title)}
def build_hook_params(string, locale, allowed_params=[],
allowed_param_values={}):
"""Parses a string of the form 'some-title|opt1|opt2=arg2|opt3...'
Builds a list of items and returns relevant parameters in a dict.
"""
if '|' not in string: # No params? Simple and easy.
string = string.strip()
return (string, {'alt': string})
items = [i.strip() for i in string.split('|')]
title = items.pop(0)
params = {}
last_item = ''
for item in items: # this splits by = or assigns the dict key to True
if '=' in item:
param, value = item.split('=', 1)
params[param] = value
else:
params[item] = True
last_item = item
if 'caption' in allowed_params:
params['caption'] = title
# Allowed parameters are not caption. All else is.
if last_item and last_item not in allowed_params:
params['caption'] = items.pop()
del params[last_item]
elif last_item == 'caption':
params['caption'] = last_item
# Validate params allowed
for p in params.keys():
if p not in allowed_params:
del params[p]
# Validate params with limited # of values
for p in allowed_param_values:
if p in params and params[p] not in allowed_param_values[p]:
del params[p]
# Handle page as a special case
if 'page' in params and params['page'] is not True:
link = _get_wiki_link(params['page'], locale)
params['link'] = link['url']
params['found'] = link['found']
return (title, params)
class WikiParser(Parser):
"""Wrapper for wikimarkup which adds Kitsune-specific callbacks
and setup.
"""
image_template = 'wikiparser/hook_image.html'
def __init__(self, base_url=None):
super(WikiParser, self).__init__(base_url)
# Register default hooks
self.registerInternalLinkHook(None, self._hook_internal_link)
self.registerInternalLinkHook('Image', self._hook_image_tag)
self.registerInternalLinkHook('Video', self._hook_video)
self.registerInternalLinkHook('V', self._hook_video)
self.registerInternalLinkHook('Button', self._hook_button)
self.youtube_videos = []
def parse(self, text, show_toc=None, tags=None, attributes=None,
styles=None, locale=settings.WIKI_DEFAULT_LANGUAGE,
nofollow=False, youtube_embeds=True, **kwargs):
"""Given wiki markup, return HTML.
Pass a locale to get all the hooks to look up Documents or
Media (Video, Image) for that locale. We key Documents by
title and locale, so both are required to identify it for a
e.g. link.
Since py-wikimarkup's hooks don't offer custom paramters for
callbacks, we're using self.locale to keep things simple.
:arg text: the text to parse
:arg show_toc: should we show a table of contents?
:arg tags: the allowed html tags
:arg attributes: the allowed html attributes
:arg styles: the allowed css styles
:arg locale: the locale to use
:arg nofollow: should links have nofollow set?
:arg youtube_embeds: should we replace the youtube placeholders
with the iframes? This is kind of a hack so that subclasses
can skip embedding here and do it on their own at the end
of parsing.
"""
self.locale = locale
@email_utils.safe_translation
def _parse(locale):
return super(WikiParser, self).parse(
text,
show_toc=show_toc,
tags=tags or ALLOWED_TAGS,
attributes=attributes or ALLOWED_ATTRIBUTES,
styles=styles or ALLOWED_STYLES,
nofollow=nofollow,
strip_comments=True,
**kwargs)
html = _parse(locale)
if youtube_embeds:
html = self.add_youtube_embeds(html)
return html
def add_youtube_embeds(self, html):
"""Insert youtube embeds.
We need to play this placeholder replacement game because we don't
allow iframes in the rendered content.
"""
for video_id in self.youtube_videos:
html = html.replace(YOUTUBE_PLACEHOLDER % video_id,
generate_youtube_embed(video_id))
return html
def _hook_internal_link(self, parser, space, name):
"""Parses text and returns internal link."""
text = False
title = name
# Split on pipe -- [[href|name]]
if '|' in name:
title, text = title.split('|', 1)
hash = ''
if '#' in title:
title, hash = title.split('#', 1)
# Sections use _, page names use +
if hash != '':
hash = '#' + hash.replace(' ', '_')
# Links to this page can just contain href="#hash"
if title == '' and hash != '':
if not text:
text = hash.replace('_', ' ')
return u'<a href="%s">%s</a>' % (hash, text)
link = _get_wiki_link(title, self.locale)
extra_a_attr = ''
if not link['found']:
extra_a_attr += (u' class="new" title="{tooltip}"'
.format(tooltip=_('Page does not exist.')))
if not text:
text = link['text']
return u'<a href="{url}{hash}"{extra}>{text}</a>'.format(
url=link['url'], hash=hash, extra=extra_a_attr, text=text)
def _hook_image_tag(self, parser, space, name):
"""Adds syntax for inserting images."""
title, params = build_hook_params(name, self.locale, IMAGE_PARAMS,
IMAGE_PARAM_VALUES)
message = _lazy(u'The image "%s" does not exist.') % title
image = get_object_fallback(Image, title, self.locale, message)
if isinstance(image, basestring):
return image
return render_to_string(self.image_template, {
'image': image,
'params': params,
'STATIC_URL': settings.STATIC_URL,
})
# Videos are objects that can have one or more files attached to them
#
# They are keyed by title in the syntax and the locale passed to the
# parser.
def _hook_video(self, parser, space, title):
"""Handles [[Video:video title]] with locale from parser."""
message = _lazy(u'The video "%s" does not exist.') % title
# params, only modal supported for now
title, params = build_hook_params(title, self.locale, VIDEO_PARAMS)
# If this is a youtube video, return the youtube embed
if _is_youtube_url(title):
parsed_url = urlparse(title)
netloc = parsed_url.netloc
if netloc == 'youtu.be':
# The video id is the path minus the leading /
video_id = parsed_url.path[1:]
else:
# The video id is in the v= query param
video_id = parse_qs(parsed_url.query)['v'][0]
self.youtube_videos.append(video_id)
return YOUTUBE_PLACEHOLDER % video_id
v = get_object_fallback(Video, title, self.locale, message)
if isinstance(v, basestring):
return v
return generate_video(v, params)
def _hook_button(self, parser, space, btn_type):
btn_type, params = build_hook_params(btn_type, self.locale)
if btn_type == 'refresh':
template = 'wikiparser/hook_refresh_button.html'
else:
return _lazy(u'Button of type "%s" does not exist.') % btn_type
return render_to_string(template, {'params': params})
def generate_video(v, params=[]):
"""Takes a video object and returns HTML markup for embedding it."""
sources = []
if v.webm:
sources.append({'src': _get_video_url(v.webm), 'type': 'webm'})
if v.ogv:
sources.append({'src': _get_video_url(v.ogv), 'type': 'ogg'})
data_fallback = ''
# Flash fallback
if v.flv:
data_fallback = _get_video_url(v.flv)
return render_to_string('wikiparser/hook_video.html', {
'fallback': data_fallback, 'sources': sources, 'params': params,
'video': v,
'height': settings.WIKI_VIDEO_HEIGHT,
'width': settings.WIKI_VIDEO_WIDTH
})
def generate_youtube_embed(video_id):
"""Takes a youtube video id and returns the embed markup."""
return render_to_string('wikiparser/hook_youtube_embed.html', {'video_id': video_id})
def _get_video_url(video_file):
if settings.GALLERY_VIDEO_URL:
return settings.GALLERY_VIDEO_URL + basename(video_file.name)
return video_file.url
def _is_youtube_url(url):
"""Returns true if the URL is to youtube."""
parsed_url = urlparse(url)
netloc = parsed_url.netloc
return netloc in ['youtu.be', 'youtube.com', 'www.youtube.com']
|
bsd-3-clause
|
jsirois/commons
|
src/python/twitter/common/http/server.py
|
14
|
9449
|
# ==================================================================================================
# Copyright 2011 Twitter, Inc.
# --------------------------------------------------------------------------------------------------
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this work except in compliance with the License.
# You may obtain a copy of the License in the LICENSE file, or at:
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==================================================================================================
import copy
import os
import threading
import types
import bottle
__all__ = (
'abort',
'HttpServer',
'mako_view',
'redirect',
'request',
'response',
'route',
'static_file',
'view',
)
class HttpServer(object):
"""
Wrapper around bottle to make class-bound servers a little easier
to write.
Three illustrative examples:
Basic encapsulated server:
from twitter.common.http import HttpServer, route
class MyServer(HttpServer):
@route("/hello")
@route("/hello/:first")
@route("/hello/:first/:last")
def hello(self, first='Zaphod', last='Beeblebrox'):
return 'Hello, %s %s!' % (first, last)
server = MyServer()
server.run('localhost', 8888)
Using a mixin pattern:
class HelloMixin(object):
@route("/hello")
def hello(self):
return 'Hello!'
class GoodbyeMixin(object):
@route("/goodbye")
def goodbye(self):
return 'Goodbye!'
# mixin directly by subclassing
class MyServerUno(HttpServer, HelloMixin, GoodbyeMixin):
pass
# or instead mixin dynamically
class MyServerDos(HttpServer):
pass
server = MyServerDos()
server.mount_routes(HelloMixin())
server.mount_routes(GoodbyeMixin())
Plugin handling:
Bottle supports plugins. You can manually specify the plugin for a route with the 'apply'
keyword argument:
class DiagnosticsEndpoints(object):
@route('/vars', apply=[TimerPlugin()])
def vars(self):
return self.metrics.sample()
but if you'd like to have a plugin apply to all methods routed within a particular class,
you can set the class attribute 'plugins':
class DiagnosticsEndpoints(object):
plugins = [TimerPlugin()]
skip_plugins = []
@route('/vars')
def vars(self):
return self.metrics.sample()
@route('/ping', apply=[BasicAuth(require_group='mesos')])
def ping(self):
return 'pong'
@route('/health', skip=['TimerPlugin'])
return 'ok'
This attribute will be mixed-in after plugins specified on a per route basis. You may also
specify 'skip_plugins' at the class-level or 'skip' at the route-level which is a list of
plugins/plugin names to not apply to the routes.
This also makes it possible to mix-in authentication classes, e.g.
class AuthenticateEverything(object):
plugins = [BasicAuth()]
class MyApplication(AuthenticateEverything):
@route('/list/:name')
def list_by_name(self, name):
...
"""
ROUTES_ATTRIBUTE = '__routes__'
VIEW_ATTRIBUTE = '__view__'
ERROR_ATTRIBUTE = '__errors__'
abort = staticmethod(bottle.abort)
request = Request = bottle.request
response = Response = bottle.response
redirect = staticmethod(bottle.redirect)
static_file = staticmethod(bottle.static_file)
@classmethod
def route(cls, *args, **kwargs):
"""Route a request to a callback. For the route format, see:
http://bottlepy.org/docs/dev/tutorial.html#request-routing"""
# Annotates the callback function with a set of applicable routes rather than registering
# the route with the global application. This allows us to mount routes at instantiation
# time rather than at route declaration time.
def annotated(function):
if not hasattr(function, cls.ROUTES_ATTRIBUTE):
setattr(function, cls.ROUTES_ATTRIBUTE, [])
getattr(function, cls.ROUTES_ATTRIBUTE).append((args, kwargs))
return function
return annotated
@classmethod
def view(cls, *args, **kwargs):
"""Postprocess the output of this method with a view. For more information see:
http://bottlepy.org/docs/dev/tutorial.html#templates"""
# Annotates the callback function with a set of applicable views a la HttpServer.route above.
def annotated(function):
setattr(function, cls.VIEW_ATTRIBUTE, (args, kwargs))
return function
return annotated
@classmethod
def error(cls, error_code):
def annotated(function):
if not hasattr(function, cls.ERROR_ATTRIBUTE):
setattr(function, cls.ERROR_ATTRIBUTE, [])
getattr(function, cls.ERROR_ATTRIBUTE).append(error_code)
return function
return annotated
@classmethod
def mako_view(cls, *args, **kwargs):
"""Helper function for annotating mako-specific views."""
kwargs.update(template_adapter=bottle.MakoTemplate)
return cls.view(*args, **kwargs)
@classmethod
def set_content_type(cls, header_value):
cls.response.content_type = header_value
def __init__(self):
self._app = bottle.Bottle()
self._hostname = None
self._port = None
self._mounts = set()
self.mount_routes(self)
# Delegate to the underlying Bottle application
def __getattr__(self, attr):
return getattr(self._app, attr)
@classmethod
def source_name(cls, class_or_instance):
return getattr(class_or_instance, '__name__', class_or_instance.__class__.__name__)
def _bind_method(self, class_instance, method_name):
"""
Delegate class_instance.method_name to self.method_name
"""
if not hasattr(class_instance, method_name):
raise ValueError('No method %s.%s exists for bind_method!' % (
self.source_name(class_instance), method_name))
if isinstance(getattr(class_instance, method_name), types.MethodType):
method_self = getattr(class_instance, method_name).im_self
if method_self is None:
# I attempted to allow for an unbound class pattern but failed. The Python interpreter
# allows for types.MethodType(cls.f, cls(), cls) to bind properly, but (cls.f, self, cls)
# cannot unless self is in the cls MRO chain which is not guaranteed if cls just derives
# from a vanilla object.
raise TypeError('Cannot mount methods from an unbound class.')
self._mounts.add(method_self)
setattr(self, method_name, getattr(class_instance, method_name))
@classmethod
def _apply_plugins(cls, class_instance, kw):
plugins = kw.get('apply', [])
skiplist = kw.get('skip', [])
class_plugins = getattr(class_instance, 'plugins', [])
class_skiplist = getattr(class_instance, 'skiplist', [])
kw.update(apply=plugins + class_plugins, skip=skiplist + class_skiplist)
return kw
def mount_routes(self, class_instance):
"""
Mount the routes from another class instance.
The routes must be added to the class via the HttpServer.route annotation and not directly
from the bottle.route decorator.
"""
for callback_name in dir(class_instance):
callback = getattr(class_instance, callback_name)
if hasattr(callback, self.ROUTES_ATTRIBUTE) or hasattr(callback, self.ERROR_ATTRIBUTE):
# Bind the un-annotated callback to this class
self._bind_method(class_instance, callback_name)
# Apply view annotations
if hasattr(callback, self.VIEW_ATTRIBUTE):
args, kw = getattr(callback, self.VIEW_ATTRIBUTE)
callback = bottle.view(*args, **kw)(callback)
setattr(self, callback_name, callback)
# Apply route annotations
for args, kw in getattr(callback, self.ROUTES_ATTRIBUTE, ()):
kw = self._apply_plugins(class_instance, copy.deepcopy(kw))
kw.update(callback=callback)
self._app.route(*args, **kw)
for error_code in getattr(callback, self.ERROR_ATTRIBUTE, ()):
self._app.error(error_code)(callback)
@property
def app(self):
"""
Return the bottle app object associated with this HttpServer instance.
"""
return self._app
@property
def hostname(self):
return self._hostname
@property
def port(self):
return self._port
def run(self, hostname, port, server='wsgiref'):
"""
Start a webserver on hostname & port.
"""
self._hostname = hostname
self._port = port
self._app.run(host=hostname, port=port, server=server)
def __str__(self):
return 'HttpServer(%s, mixins: %s)' % (
'%s:%s' (self.hostname, self.port) if self.hostname else 'unbound',
', '.join(self.source_name(instance) for instance in self._mounts))
abort = HttpServer.abort
mako_view = HttpServer.mako_view
redirect = HttpServer.redirect
request = HttpServer.request
response = HttpServer.response
route = HttpServer.route
static_file = HttpServer.static_file
view = HttpServer.view
|
apache-2.0
|
JioCloud/python-cinderclient
|
cinderclient/v2/volume_backups.py
|
3
|
3500
|
# Copyright (C) 2013 Hewlett-Packard Development Company, L.P.
# 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.
"""
Volume Backups interface (1.1 extension).
"""
from cinderclient import base
class VolumeBackup(base.Resource):
"""A volume backup is a block level backup of a volume."""
def __repr__(self):
return "<VolumeBackup: %s>" % self.id
def delete(self):
"""Delete this volume backup."""
return self.manager.delete(self)
class VolumeBackupManager(base.ManagerWithFind):
"""Manage :class:`VolumeBackup` resources."""
resource_class = VolumeBackup
def create(self, volume_id, container=None,
name=None, description=None):
"""Creates a volume backup.
:param volume_id: The ID of the volume to backup.
:param container: The name of the backup service container.
:param name: The name of the backup.
:param description: The description of the backup.
:rtype: :class:`VolumeBackup`
"""
body = {'backup': {'volume_id': volume_id,
'container': container,
'name': name,
'description': description}}
return self._create('/backups', body, 'backup')
def get(self, backup_id):
"""Show volume backup details.
:param backup_id: The ID of the backup to display.
:rtype: :class:`VolumeBackup`
"""
return self._get("/backups/%s" % backup_id, "backup")
def list(self, detailed=True):
"""Get a list of all volume backups.
:rtype: list of :class:`VolumeBackup`
"""
if detailed is True:
return self._list("/backups/detail", "backups")
else:
return self._list("/backups", "backups")
def delete(self, backup):
"""Delete a volume backup.
:param backup: The :class:`VolumeBackup` to delete.
"""
self._delete("/backups/%s" % base.getid(backup))
def export_record(self, backup_id):
"""Export volume backup metadata record.
:param backup_id: The ID of the backup to export.
:rtype: :class:`VolumeBackup`
"""
resp, body = \
self.api.client.get("/backups/%s/export_record" % backup_id)
return body['backup-record']
def import_record(self, backup_service, backup_url):
"""Export volume backup metadata record.
:param backup_service: Backup service to use for importing the backup
:param backup_urlBackup URL for importing the backup metadata
:rtype: :class:`VolumeBackup`
"""
body = {'backup-record': {'backup_service': backup_service,
'backup_url': backup_url}}
self.run_hooks('modify_body_for_update', body, 'backup-record')
resp, body = self.api.client.post("/backups/import_record", body=body)
return body['backup']
|
apache-2.0
|
danielpalomino/gem5
|
src/arch/x86/isa/insts/x87/arithmetic/round.py
|
91
|
2152
|
# Copyright (c) 2007 The Hewlett-Packard Development Company
# All rights reserved.
#
# The license below extends only to copyright in the software and shall
# not be construed as granting a license to any other intellectual
# property including but not limited to intellectual property relating
# to a hardware implementation of the functionality of the software
# licensed hereunder. You may use the software subject to the license
# terms below provided that you ensure that this notice is replicated
# unmodified and in its entirety in all distributions of the software,
# modified or unmodified, in source code or in binary form.
#
# 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 the copyright holders 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.
#
# Authors: Gabe Black
microcode = '''
# FRNDINT
'''
|
bsd-3-clause
|
jgao54/airflow
|
airflow/contrib/sensors/cassandra_record_sensor.py
|
10
|
2616
|
# -*- coding: utf-8 -*-
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
from airflow.contrib.hooks.cassandra_hook import CassandraHook
from airflow.sensors.base_sensor_operator import BaseSensorOperator
from airflow.utils.decorators import apply_defaults
class CassandraRecordSensor(BaseSensorOperator):
"""
Checks for the existence of a record in a Cassandra cluster.
For example, if you want to wait for a record that has values 'v1' and 'v2' for each
primary keys 'p1' and 'p2' to be populated in keyspace 'k' and table 't',
instantiate it as follows:
>>> cassandra_sensor = CassandraRecordSensor(table="k.t",
... keys={"p1": "v1", "p2": "v2"},
... cassandra_conn_id="cassandra_default",
... task_id="cassandra_sensor")
"""
template_fields = ('table', 'keys')
@apply_defaults
def __init__(self, table, keys, cassandra_conn_id, *args, **kwargs):
"""
Create a new CassandraRecordSensor
:param table: Target Cassandra table.
Use dot notation to target a specific keyspace.
:type table: str
:param keys: The keys and their values to be monitored
:type keys: dict
:param cassandra_conn_id: The connection ID to use
when connecting to Cassandra cluster
:type cassandra_conn_id: str
"""
super(CassandraRecordSensor, self).__init__(*args, **kwargs)
self.cassandra_conn_id = cassandra_conn_id
self.table = table
self.keys = keys
def poke(self, context):
self.log.info('Sensor check existence of record: %s', self.keys)
hook = CassandraHook(self.cassandra_conn_id)
return hook.record_exists(self.table, self.keys)
|
apache-2.0
|
sander76/home-assistant
|
tests/components/plant/test_init.py
|
5
|
7945
|
"""Unit tests for platform/plant.py."""
from datetime import datetime, timedelta
import pytest
from homeassistant.components import recorder
import homeassistant.components.plant as plant
from homeassistant.const import (
ATTR_UNIT_OF_MEASUREMENT,
CONDUCTIVITY,
LIGHT_LUX,
STATE_OK,
STATE_PROBLEM,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
)
from homeassistant.core import State
from homeassistant.setup import async_setup_component
from tests.common import init_recorder_component
GOOD_DATA = {
"moisture": 50,
"battery": 90,
"temperature": 23.4,
"conductivity": 777,
"brightness": 987,
}
BRIGHTNESS_ENTITY = "sensor.mqtt_plant_brightness"
MOISTURE_ENTITY = "sensor.mqtt_plant_moisture"
GOOD_CONFIG = {
"sensors": {
"moisture": MOISTURE_ENTITY,
"battery": "sensor.mqtt_plant_battery",
"temperature": "sensor.mqtt_plant_temperature",
"conductivity": "sensor.mqtt_plant_conductivity",
"brightness": BRIGHTNESS_ENTITY,
},
"min_moisture": 20,
"max_moisture": 60,
"min_battery": 17,
"min_conductivity": 500,
"min_temperature": 15,
"min_brightness": 500,
}
async def test_valid_data(hass):
"""Test processing valid data."""
sensor = plant.Plant("my plant", GOOD_CONFIG)
sensor.entity_id = "sensor.mqtt_plant_battery"
sensor.hass = hass
for reading, value in GOOD_DATA.items():
sensor.state_changed(
GOOD_CONFIG["sensors"][reading],
State(GOOD_CONFIG["sensors"][reading], value),
)
assert sensor.state == "ok"
attrib = sensor.extra_state_attributes
for reading, value in GOOD_DATA.items():
# battery level has a different name in
# the JSON format than in hass
assert attrib[reading] == value
async def test_low_battery(hass):
"""Test processing with low battery data and limit set."""
sensor = plant.Plant("other plant", GOOD_CONFIG)
sensor.entity_id = "sensor.mqtt_plant_battery"
sensor.hass = hass
assert sensor.extra_state_attributes["problem"] == "none"
sensor.state_changed(
"sensor.mqtt_plant_battery",
State("sensor.mqtt_plant_battery", 10),
)
assert sensor.state == "problem"
assert sensor.extra_state_attributes["problem"] == "battery low"
async def test_initial_states(hass):
"""Test plant initialises attributes if sensor already exists."""
hass.states.async_set(MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY})
plant_name = "some_plant"
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.attributes[plant.READING_MOISTURE] == 5
async def test_update_states(hass):
"""Test updating the state of a sensor.
Make sure that plant processes this correctly.
"""
plant_name = "some_plant"
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
hass.states.async_set(MOISTURE_ENTITY, 5, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_PROBLEM
assert state.attributes[plant.READING_MOISTURE] == 5
async def test_unavailable_state(hass):
"""Test updating the state with unavailable.
Make sure that plant processes this correctly.
"""
plant_name = "some_plant"
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
hass.states.async_set(
MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY}
)
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_PROBLEM
assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE
async def test_state_problem_if_unavailable(hass):
"""Test updating the state with unavailable after setting it to valid value.
Make sure that plant processes this correctly.
"""
plant_name = "some_plant"
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
hass.states.async_set(MOISTURE_ENTITY, 42, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_OK
assert state.attributes[plant.READING_MOISTURE] == 42
hass.states.async_set(
MOISTURE_ENTITY, STATE_UNAVAILABLE, {ATTR_UNIT_OF_MEASUREMENT: CONDUCTIVITY}
)
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_PROBLEM
assert state.attributes[plant.READING_MOISTURE] == STATE_UNAVAILABLE
@pytest.mark.skipif(
plant.ENABLE_LOAD_HISTORY is False,
reason="tests for loading from DB are unstable, thus"
"this feature is turned of until tests become"
"stable",
)
async def test_load_from_db(hass):
"""Test bootstrapping the brightness history from the database.
This test can should only be executed if the loading of the history
is enabled via plant.ENABLE_LOAD_HISTORY.
"""
init_recorder_component(hass)
plant_name = "wise_plant"
for value in [20, 30, 10]:
hass.states.async_set(
BRIGHTNESS_ENTITY, value, {ATTR_UNIT_OF_MEASUREMENT: "Lux"}
)
await hass.async_block_till_done()
# wait for the recorder to really store the data
hass.data[recorder.DATA_INSTANCE].block_till_done()
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_UNKNOWN
max_brightness = state.attributes.get(plant.ATTR_MAX_BRIGHTNESS_HISTORY)
assert max_brightness == 30
async def test_brightness_history(hass):
"""Test the min_brightness check."""
plant_name = "some_plant"
assert await async_setup_component(
hass, plant.DOMAIN, {plant.DOMAIN: {plant_name: GOOD_CONFIG}}
)
hass.states.async_set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: LIGHT_LUX})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_PROBLEM
hass.states.async_set(BRIGHTNESS_ENTITY, 600, {ATTR_UNIT_OF_MEASUREMENT: LIGHT_LUX})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_OK
hass.states.async_set(BRIGHTNESS_ENTITY, 100, {ATTR_UNIT_OF_MEASUREMENT: LIGHT_LUX})
await hass.async_block_till_done()
state = hass.states.get(f"plant.{plant_name}")
assert state.state == STATE_OK
def test_daily_history_no_data(hass):
"""Test with empty history."""
dh = plant.DailyHistory(3)
assert dh.max is None
def test_daily_history_one_day(hass):
"""Test storing data for the same day."""
dh = plant.DailyHistory(3)
values = [-2, 10, 0, 5, 20]
for i in range(len(values)):
dh.add_measurement(values[i])
max_value = max(values[0 : i + 1])
assert len(dh._days) == 1
assert dh.max == max_value
def test_daily_history_multiple_days(hass):
"""Test storing data for different days."""
dh = plant.DailyHistory(3)
today = datetime.now()
today_minus_1 = today - timedelta(days=1)
today_minus_2 = today_minus_1 - timedelta(days=1)
today_minus_3 = today_minus_2 - timedelta(days=1)
days = [today_minus_3, today_minus_2, today_minus_1, today]
values = [10, 1, 7, 3]
max_values = [10, 10, 10, 7]
for i in range(len(days)):
dh.add_measurement(values[i], days[i])
assert max_values[i] == dh.max
|
apache-2.0
|
MiltosD/CEF-ELRC
|
lib/python2.7/site-packages/dateutil/rrule.py
|
254
|
40402
|
"""
Copyright (c) 2003-2010 Gustavo Niemeyer <[email protected]>
This module offers extensions to the standard python 2.3+
datetime module.
"""
__author__ = "Gustavo Niemeyer <[email protected]>"
__license__ = "PSF License"
import itertools
import datetime
import calendar
import thread
import sys
__all__ = ["rrule", "rruleset", "rrulestr",
"YEARLY", "MONTHLY", "WEEKLY", "DAILY",
"HOURLY", "MINUTELY", "SECONDLY",
"MO", "TU", "WE", "TH", "FR", "SA", "SU"]
# Every mask is 7 days longer to handle cross-year weekly periods.
M366MASK = tuple([1]*31+[2]*29+[3]*31+[4]*30+[5]*31+[6]*30+
[7]*31+[8]*31+[9]*30+[10]*31+[11]*30+[12]*31+[1]*7)
M365MASK = list(M366MASK)
M29, M30, M31 = range(1,30), range(1,31), range(1,32)
MDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
MDAY365MASK = list(MDAY366MASK)
M29, M30, M31 = range(-29,0), range(-30,0), range(-31,0)
NMDAY366MASK = tuple(M31+M29+M31+M30+M31+M30+M31+M31+M30+M31+M30+M31+M31[:7])
NMDAY365MASK = list(NMDAY366MASK)
M366RANGE = (0,31,60,91,121,152,182,213,244,274,305,335,366)
M365RANGE = (0,31,59,90,120,151,181,212,243,273,304,334,365)
WDAYMASK = [0,1,2,3,4,5,6]*55
del M29, M30, M31, M365MASK[59], MDAY365MASK[59], NMDAY365MASK[31]
MDAY365MASK = tuple(MDAY365MASK)
M365MASK = tuple(M365MASK)
(YEARLY,
MONTHLY,
WEEKLY,
DAILY,
HOURLY,
MINUTELY,
SECONDLY) = range(7)
# Imported on demand.
easter = None
parser = None
class weekday(object):
__slots__ = ["weekday", "n"]
def __init__(self, weekday, n=None):
if n == 0:
raise ValueError, "Can't create weekday with n == 0"
self.weekday = weekday
self.n = n
def __call__(self, n):
if n == self.n:
return self
else:
return self.__class__(self.weekday, n)
def __eq__(self, other):
try:
if self.weekday != other.weekday or self.n != other.n:
return False
except AttributeError:
return False
return True
def __repr__(self):
s = ("MO", "TU", "WE", "TH", "FR", "SA", "SU")[self.weekday]
if not self.n:
return s
else:
return "%s(%+d)" % (s, self.n)
MO, TU, WE, TH, FR, SA, SU = weekdays = tuple([weekday(x) for x in range(7)])
class rrulebase:
def __init__(self, cache=False):
if cache:
self._cache = []
self._cache_lock = thread.allocate_lock()
self._cache_gen = self._iter()
self._cache_complete = False
else:
self._cache = None
self._cache_complete = False
self._len = None
def __iter__(self):
if self._cache_complete:
return iter(self._cache)
elif self._cache is None:
return self._iter()
else:
return self._iter_cached()
def _iter_cached(self):
i = 0
gen = self._cache_gen
cache = self._cache
acquire = self._cache_lock.acquire
release = self._cache_lock.release
while gen:
if i == len(cache):
acquire()
if self._cache_complete:
break
try:
for j in range(10):
cache.append(gen.next())
except StopIteration:
self._cache_gen = gen = None
self._cache_complete = True
break
release()
yield cache[i]
i += 1
while i < self._len:
yield cache[i]
i += 1
def __getitem__(self, item):
if self._cache_complete:
return self._cache[item]
elif isinstance(item, slice):
if item.step and item.step < 0:
return list(iter(self))[item]
else:
return list(itertools.islice(self,
item.start or 0,
item.stop or sys.maxint,
item.step or 1))
elif item >= 0:
gen = iter(self)
try:
for i in range(item+1):
res = gen.next()
except StopIteration:
raise IndexError
return res
else:
return list(iter(self))[item]
def __contains__(self, item):
if self._cache_complete:
return item in self._cache
else:
for i in self:
if i == item:
return True
elif i > item:
return False
return False
# __len__() introduces a large performance penality.
def count(self):
if self._len is None:
for x in self: pass
return self._len
def before(self, dt, inc=False):
if self._cache_complete:
gen = self._cache
else:
gen = self
last = None
if inc:
for i in gen:
if i > dt:
break
last = i
else:
for i in gen:
if i >= dt:
break
last = i
return last
def after(self, dt, inc=False):
if self._cache_complete:
gen = self._cache
else:
gen = self
if inc:
for i in gen:
if i >= dt:
return i
else:
for i in gen:
if i > dt:
return i
return None
def between(self, after, before, inc=False):
if self._cache_complete:
gen = self._cache
else:
gen = self
started = False
l = []
if inc:
for i in gen:
if i > before:
break
elif not started:
if i >= after:
started = True
l.append(i)
else:
l.append(i)
else:
for i in gen:
if i >= before:
break
elif not started:
if i > after:
started = True
l.append(i)
else:
l.append(i)
return l
class rrule(rrulebase):
def __init__(self, freq, dtstart=None,
interval=1, wkst=None, count=None, until=None, bysetpos=None,
bymonth=None, bymonthday=None, byyearday=None, byeaster=None,
byweekno=None, byweekday=None,
byhour=None, byminute=None, bysecond=None,
cache=False):
rrulebase.__init__(self, cache)
global easter
if not dtstart:
dtstart = datetime.datetime.now().replace(microsecond=0)
elif not isinstance(dtstart, datetime.datetime):
dtstart = datetime.datetime.fromordinal(dtstart.toordinal())
else:
dtstart = dtstart.replace(microsecond=0)
self._dtstart = dtstart
self._tzinfo = dtstart.tzinfo
self._freq = freq
self._interval = interval
self._count = count
if until and not isinstance(until, datetime.datetime):
until = datetime.datetime.fromordinal(until.toordinal())
self._until = until
if wkst is None:
self._wkst = calendar.firstweekday()
elif type(wkst) is int:
self._wkst = wkst
else:
self._wkst = wkst.weekday
if bysetpos is None:
self._bysetpos = None
elif type(bysetpos) is int:
if bysetpos == 0 or not (-366 <= bysetpos <= 366):
raise ValueError("bysetpos must be between 1 and 366, "
"or between -366 and -1")
self._bysetpos = (bysetpos,)
else:
self._bysetpos = tuple(bysetpos)
for pos in self._bysetpos:
if pos == 0 or not (-366 <= pos <= 366):
raise ValueError("bysetpos must be between 1 and 366, "
"or between -366 and -1")
if not (byweekno or byyearday or bymonthday or
byweekday is not None or byeaster is not None):
if freq == YEARLY:
if not bymonth:
bymonth = dtstart.month
bymonthday = dtstart.day
elif freq == MONTHLY:
bymonthday = dtstart.day
elif freq == WEEKLY:
byweekday = dtstart.weekday()
# bymonth
if not bymonth:
self._bymonth = None
elif type(bymonth) is int:
self._bymonth = (bymonth,)
else:
self._bymonth = tuple(bymonth)
# byyearday
if not byyearday:
self._byyearday = None
elif type(byyearday) is int:
self._byyearday = (byyearday,)
else:
self._byyearday = tuple(byyearday)
# byeaster
if byeaster is not None:
if not easter:
from dateutil import easter
if type(byeaster) is int:
self._byeaster = (byeaster,)
else:
self._byeaster = tuple(byeaster)
else:
self._byeaster = None
# bymonthay
if not bymonthday:
self._bymonthday = ()
self._bynmonthday = ()
elif type(bymonthday) is int:
if bymonthday < 0:
self._bynmonthday = (bymonthday,)
self._bymonthday = ()
else:
self._bymonthday = (bymonthday,)
self._bynmonthday = ()
else:
self._bymonthday = tuple([x for x in bymonthday if x > 0])
self._bynmonthday = tuple([x for x in bymonthday if x < 0])
# byweekno
if byweekno is None:
self._byweekno = None
elif type(byweekno) is int:
self._byweekno = (byweekno,)
else:
self._byweekno = tuple(byweekno)
# byweekday / bynweekday
if byweekday is None:
self._byweekday = None
self._bynweekday = None
elif type(byweekday) is int:
self._byweekday = (byweekday,)
self._bynweekday = None
elif hasattr(byweekday, "n"):
if not byweekday.n or freq > MONTHLY:
self._byweekday = (byweekday.weekday,)
self._bynweekday = None
else:
self._bynweekday = ((byweekday.weekday, byweekday.n),)
self._byweekday = None
else:
self._byweekday = []
self._bynweekday = []
for wday in byweekday:
if type(wday) is int:
self._byweekday.append(wday)
elif not wday.n or freq > MONTHLY:
self._byweekday.append(wday.weekday)
else:
self._bynweekday.append((wday.weekday, wday.n))
self._byweekday = tuple(self._byweekday)
self._bynweekday = tuple(self._bynweekday)
if not self._byweekday:
self._byweekday = None
elif not self._bynweekday:
self._bynweekday = None
# byhour
if byhour is None:
if freq < HOURLY:
self._byhour = (dtstart.hour,)
else:
self._byhour = None
elif type(byhour) is int:
self._byhour = (byhour,)
else:
self._byhour = tuple(byhour)
# byminute
if byminute is None:
if freq < MINUTELY:
self._byminute = (dtstart.minute,)
else:
self._byminute = None
elif type(byminute) is int:
self._byminute = (byminute,)
else:
self._byminute = tuple(byminute)
# bysecond
if bysecond is None:
if freq < SECONDLY:
self._bysecond = (dtstart.second,)
else:
self._bysecond = None
elif type(bysecond) is int:
self._bysecond = (bysecond,)
else:
self._bysecond = tuple(bysecond)
if self._freq >= HOURLY:
self._timeset = None
else:
self._timeset = []
for hour in self._byhour:
for minute in self._byminute:
for second in self._bysecond:
self._timeset.append(
datetime.time(hour, minute, second,
tzinfo=self._tzinfo))
self._timeset.sort()
self._timeset = tuple(self._timeset)
def _iter(self):
year, month, day, hour, minute, second, weekday, yearday, _ = \
self._dtstart.timetuple()
# Some local variables to speed things up a bit
freq = self._freq
interval = self._interval
wkst = self._wkst
until = self._until
bymonth = self._bymonth
byweekno = self._byweekno
byyearday = self._byyearday
byweekday = self._byweekday
byeaster = self._byeaster
bymonthday = self._bymonthday
bynmonthday = self._bynmonthday
bysetpos = self._bysetpos
byhour = self._byhour
byminute = self._byminute
bysecond = self._bysecond
ii = _iterinfo(self)
ii.rebuild(year, month)
getdayset = {YEARLY:ii.ydayset,
MONTHLY:ii.mdayset,
WEEKLY:ii.wdayset,
DAILY:ii.ddayset,
HOURLY:ii.ddayset,
MINUTELY:ii.ddayset,
SECONDLY:ii.ddayset}[freq]
if freq < HOURLY:
timeset = self._timeset
else:
gettimeset = {HOURLY:ii.htimeset,
MINUTELY:ii.mtimeset,
SECONDLY:ii.stimeset}[freq]
if ((freq >= HOURLY and
self._byhour and hour not in self._byhour) or
(freq >= MINUTELY and
self._byminute and minute not in self._byminute) or
(freq >= SECONDLY and
self._bysecond and second not in self._bysecond)):
timeset = ()
else:
timeset = gettimeset(hour, minute, second)
total = 0
count = self._count
while True:
# Get dayset with the right frequency
dayset, start, end = getdayset(year, month, day)
# Do the "hard" work ;-)
filtered = False
for i in dayset[start:end]:
if ((bymonth and ii.mmask[i] not in bymonth) or
(byweekno and not ii.wnomask[i]) or
(byweekday and ii.wdaymask[i] not in byweekday) or
(ii.nwdaymask and not ii.nwdaymask[i]) or
(byeaster and not ii.eastermask[i]) or
((bymonthday or bynmonthday) and
ii.mdaymask[i] not in bymonthday and
ii.nmdaymask[i] not in bynmonthday) or
(byyearday and
((i < ii.yearlen and i+1 not in byyearday
and -ii.yearlen+i not in byyearday) or
(i >= ii.yearlen and i+1-ii.yearlen not in byyearday
and -ii.nextyearlen+i-ii.yearlen
not in byyearday)))):
dayset[i] = None
filtered = True
# Output results
if bysetpos and timeset:
poslist = []
for pos in bysetpos:
if pos < 0:
daypos, timepos = divmod(pos, len(timeset))
else:
daypos, timepos = divmod(pos-1, len(timeset))
try:
i = [x for x in dayset[start:end]
if x is not None][daypos]
time = timeset[timepos]
except IndexError:
pass
else:
date = datetime.date.fromordinal(ii.yearordinal+i)
res = datetime.datetime.combine(date, time)
if res not in poslist:
poslist.append(res)
poslist.sort()
for res in poslist:
if until and res > until:
self._len = total
return
elif res >= self._dtstart:
total += 1
yield res
if count:
count -= 1
if not count:
self._len = total
return
else:
for i in dayset[start:end]:
if i is not None:
date = datetime.date.fromordinal(ii.yearordinal+i)
for time in timeset:
res = datetime.datetime.combine(date, time)
if until and res > until:
self._len = total
return
elif res >= self._dtstart:
total += 1
yield res
if count:
count -= 1
if not count:
self._len = total
return
# Handle frequency and interval
fixday = False
if freq == YEARLY:
year += interval
if year > datetime.MAXYEAR:
self._len = total
return
ii.rebuild(year, month)
elif freq == MONTHLY:
month += interval
if month > 12:
div, mod = divmod(month, 12)
month = mod
year += div
if month == 0:
month = 12
year -= 1
if year > datetime.MAXYEAR:
self._len = total
return
ii.rebuild(year, month)
elif freq == WEEKLY:
if wkst > weekday:
day += -(weekday+1+(6-wkst))+self._interval*7
else:
day += -(weekday-wkst)+self._interval*7
weekday = wkst
fixday = True
elif freq == DAILY:
day += interval
fixday = True
elif freq == HOURLY:
if filtered:
# Jump to one iteration before next day
hour += ((23-hour)//interval)*interval
while True:
hour += interval
div, mod = divmod(hour, 24)
if div:
hour = mod
day += div
fixday = True
if not byhour or hour in byhour:
break
timeset = gettimeset(hour, minute, second)
elif freq == MINUTELY:
if filtered:
# Jump to one iteration before next day
minute += ((1439-(hour*60+minute))//interval)*interval
while True:
minute += interval
div, mod = divmod(minute, 60)
if div:
minute = mod
hour += div
div, mod = divmod(hour, 24)
if div:
hour = mod
day += div
fixday = True
filtered = False
if ((not byhour or hour in byhour) and
(not byminute or minute in byminute)):
break
timeset = gettimeset(hour, minute, second)
elif freq == SECONDLY:
if filtered:
# Jump to one iteration before next day
second += (((86399-(hour*3600+minute*60+second))
//interval)*interval)
while True:
second += self._interval
div, mod = divmod(second, 60)
if div:
second = mod
minute += div
div, mod = divmod(minute, 60)
if div:
minute = mod
hour += div
div, mod = divmod(hour, 24)
if div:
hour = mod
day += div
fixday = True
if ((not byhour or hour in byhour) and
(not byminute or minute in byminute) and
(not bysecond or second in bysecond)):
break
timeset = gettimeset(hour, minute, second)
if fixday and day > 28:
daysinmonth = calendar.monthrange(year, month)[1]
if day > daysinmonth:
while day > daysinmonth:
day -= daysinmonth
month += 1
if month == 13:
month = 1
year += 1
if year > datetime.MAXYEAR:
self._len = total
return
daysinmonth = calendar.monthrange(year, month)[1]
ii.rebuild(year, month)
class _iterinfo(object):
__slots__ = ["rrule", "lastyear", "lastmonth",
"yearlen", "nextyearlen", "yearordinal", "yearweekday",
"mmask", "mrange", "mdaymask", "nmdaymask",
"wdaymask", "wnomask", "nwdaymask", "eastermask"]
def __init__(self, rrule):
for attr in self.__slots__:
setattr(self, attr, None)
self.rrule = rrule
def rebuild(self, year, month):
# Every mask is 7 days longer to handle cross-year weekly periods.
rr = self.rrule
if year != self.lastyear:
self.yearlen = 365+calendar.isleap(year)
self.nextyearlen = 365+calendar.isleap(year+1)
firstyday = datetime.date(year, 1, 1)
self.yearordinal = firstyday.toordinal()
self.yearweekday = firstyday.weekday()
wday = datetime.date(year, 1, 1).weekday()
if self.yearlen == 365:
self.mmask = M365MASK
self.mdaymask = MDAY365MASK
self.nmdaymask = NMDAY365MASK
self.wdaymask = WDAYMASK[wday:]
self.mrange = M365RANGE
else:
self.mmask = M366MASK
self.mdaymask = MDAY366MASK
self.nmdaymask = NMDAY366MASK
self.wdaymask = WDAYMASK[wday:]
self.mrange = M366RANGE
if not rr._byweekno:
self.wnomask = None
else:
self.wnomask = [0]*(self.yearlen+7)
#no1wkst = firstwkst = self.wdaymask.index(rr._wkst)
no1wkst = firstwkst = (7-self.yearweekday+rr._wkst)%7
if no1wkst >= 4:
no1wkst = 0
# Number of days in the year, plus the days we got
# from last year.
wyearlen = self.yearlen+(self.yearweekday-rr._wkst)%7
else:
# Number of days in the year, minus the days we
# left in last year.
wyearlen = self.yearlen-no1wkst
div, mod = divmod(wyearlen, 7)
numweeks = div+mod//4
for n in rr._byweekno:
if n < 0:
n += numweeks+1
if not (0 < n <= numweeks):
continue
if n > 1:
i = no1wkst+(n-1)*7
if no1wkst != firstwkst:
i -= 7-firstwkst
else:
i = no1wkst
for j in range(7):
self.wnomask[i] = 1
i += 1
if self.wdaymask[i] == rr._wkst:
break
if 1 in rr._byweekno:
# Check week number 1 of next year as well
# TODO: Check -numweeks for next year.
i = no1wkst+numweeks*7
if no1wkst != firstwkst:
i -= 7-firstwkst
if i < self.yearlen:
# If week starts in next year, we
# don't care about it.
for j in range(7):
self.wnomask[i] = 1
i += 1
if self.wdaymask[i] == rr._wkst:
break
if no1wkst:
# Check last week number of last year as
# well. If no1wkst is 0, either the year
# started on week start, or week number 1
# got days from last year, so there are no
# days from last year's last week number in
# this year.
if -1 not in rr._byweekno:
lyearweekday = datetime.date(year-1,1,1).weekday()
lno1wkst = (7-lyearweekday+rr._wkst)%7
lyearlen = 365+calendar.isleap(year-1)
if lno1wkst >= 4:
lno1wkst = 0
lnumweeks = 52+(lyearlen+
(lyearweekday-rr._wkst)%7)%7//4
else:
lnumweeks = 52+(self.yearlen-no1wkst)%7//4
else:
lnumweeks = -1
if lnumweeks in rr._byweekno:
for i in range(no1wkst):
self.wnomask[i] = 1
if (rr._bynweekday and
(month != self.lastmonth or year != self.lastyear)):
ranges = []
if rr._freq == YEARLY:
if rr._bymonth:
for month in rr._bymonth:
ranges.append(self.mrange[month-1:month+1])
else:
ranges = [(0, self.yearlen)]
elif rr._freq == MONTHLY:
ranges = [self.mrange[month-1:month+1]]
if ranges:
# Weekly frequency won't get here, so we may not
# care about cross-year weekly periods.
self.nwdaymask = [0]*self.yearlen
for first, last in ranges:
last -= 1
for wday, n in rr._bynweekday:
if n < 0:
i = last+(n+1)*7
i -= (self.wdaymask[i]-wday)%7
else:
i = first+(n-1)*7
i += (7-self.wdaymask[i]+wday)%7
if first <= i <= last:
self.nwdaymask[i] = 1
if rr._byeaster:
self.eastermask = [0]*(self.yearlen+7)
eyday = easter.easter(year).toordinal()-self.yearordinal
for offset in rr._byeaster:
self.eastermask[eyday+offset] = 1
self.lastyear = year
self.lastmonth = month
def ydayset(self, year, month, day):
return range(self.yearlen), 0, self.yearlen
def mdayset(self, year, month, day):
set = [None]*self.yearlen
start, end = self.mrange[month-1:month+1]
for i in range(start, end):
set[i] = i
return set, start, end
def wdayset(self, year, month, day):
# We need to handle cross-year weeks here.
set = [None]*(self.yearlen+7)
i = datetime.date(year, month, day).toordinal()-self.yearordinal
start = i
for j in range(7):
set[i] = i
i += 1
#if (not (0 <= i < self.yearlen) or
# self.wdaymask[i] == self.rrule._wkst):
# This will cross the year boundary, if necessary.
if self.wdaymask[i] == self.rrule._wkst:
break
return set, start, i
def ddayset(self, year, month, day):
set = [None]*self.yearlen
i = datetime.date(year, month, day).toordinal()-self.yearordinal
set[i] = i
return set, i, i+1
def htimeset(self, hour, minute, second):
set = []
rr = self.rrule
for minute in rr._byminute:
for second in rr._bysecond:
set.append(datetime.time(hour, minute, second,
tzinfo=rr._tzinfo))
set.sort()
return set
def mtimeset(self, hour, minute, second):
set = []
rr = self.rrule
for second in rr._bysecond:
set.append(datetime.time(hour, minute, second, tzinfo=rr._tzinfo))
set.sort()
return set
def stimeset(self, hour, minute, second):
return (datetime.time(hour, minute, second,
tzinfo=self.rrule._tzinfo),)
class rruleset(rrulebase):
class _genitem:
def __init__(self, genlist, gen):
try:
self.dt = gen()
genlist.append(self)
except StopIteration:
pass
self.genlist = genlist
self.gen = gen
def next(self):
try:
self.dt = self.gen()
except StopIteration:
self.genlist.remove(self)
def __cmp__(self, other):
return cmp(self.dt, other.dt)
def __init__(self, cache=False):
rrulebase.__init__(self, cache)
self._rrule = []
self._rdate = []
self._exrule = []
self._exdate = []
def rrule(self, rrule):
self._rrule.append(rrule)
def rdate(self, rdate):
self._rdate.append(rdate)
def exrule(self, exrule):
self._exrule.append(exrule)
def exdate(self, exdate):
self._exdate.append(exdate)
def _iter(self):
rlist = []
self._rdate.sort()
self._genitem(rlist, iter(self._rdate).next)
for gen in [iter(x).next for x in self._rrule]:
self._genitem(rlist, gen)
rlist.sort()
exlist = []
self._exdate.sort()
self._genitem(exlist, iter(self._exdate).next)
for gen in [iter(x).next for x in self._exrule]:
self._genitem(exlist, gen)
exlist.sort()
lastdt = None
total = 0
while rlist:
ritem = rlist[0]
if not lastdt or lastdt != ritem.dt:
while exlist and exlist[0] < ritem:
exlist[0].next()
exlist.sort()
if not exlist or ritem != exlist[0]:
total += 1
yield ritem.dt
lastdt = ritem.dt
ritem.next()
rlist.sort()
self._len = total
class _rrulestr:
_freq_map = {"YEARLY": YEARLY,
"MONTHLY": MONTHLY,
"WEEKLY": WEEKLY,
"DAILY": DAILY,
"HOURLY": HOURLY,
"MINUTELY": MINUTELY,
"SECONDLY": SECONDLY}
_weekday_map = {"MO":0,"TU":1,"WE":2,"TH":3,"FR":4,"SA":5,"SU":6}
def _handle_int(self, rrkwargs, name, value, **kwargs):
rrkwargs[name.lower()] = int(value)
def _handle_int_list(self, rrkwargs, name, value, **kwargs):
rrkwargs[name.lower()] = [int(x) for x in value.split(',')]
_handle_INTERVAL = _handle_int
_handle_COUNT = _handle_int
_handle_BYSETPOS = _handle_int_list
_handle_BYMONTH = _handle_int_list
_handle_BYMONTHDAY = _handle_int_list
_handle_BYYEARDAY = _handle_int_list
_handle_BYEASTER = _handle_int_list
_handle_BYWEEKNO = _handle_int_list
_handle_BYHOUR = _handle_int_list
_handle_BYMINUTE = _handle_int_list
_handle_BYSECOND = _handle_int_list
def _handle_FREQ(self, rrkwargs, name, value, **kwargs):
rrkwargs["freq"] = self._freq_map[value]
def _handle_UNTIL(self, rrkwargs, name, value, **kwargs):
global parser
if not parser:
from dateutil import parser
try:
rrkwargs["until"] = parser.parse(value,
ignoretz=kwargs.get("ignoretz"),
tzinfos=kwargs.get("tzinfos"))
except ValueError:
raise ValueError, "invalid until date"
def _handle_WKST(self, rrkwargs, name, value, **kwargs):
rrkwargs["wkst"] = self._weekday_map[value]
def _handle_BYWEEKDAY(self, rrkwargs, name, value, **kwarsg):
l = []
for wday in value.split(','):
for i in range(len(wday)):
if wday[i] not in '+-0123456789':
break
n = wday[:i] or None
w = wday[i:]
if n: n = int(n)
l.append(weekdays[self._weekday_map[w]](n))
rrkwargs["byweekday"] = l
_handle_BYDAY = _handle_BYWEEKDAY
def _parse_rfc_rrule(self, line,
dtstart=None,
cache=False,
ignoretz=False,
tzinfos=None):
if line.find(':') != -1:
name, value = line.split(':')
if name != "RRULE":
raise ValueError, "unknown parameter name"
else:
value = line
rrkwargs = {}
for pair in value.split(';'):
name, value = pair.split('=')
name = name.upper()
value = value.upper()
try:
getattr(self, "_handle_"+name)(rrkwargs, name, value,
ignoretz=ignoretz,
tzinfos=tzinfos)
except AttributeError:
raise ValueError, "unknown parameter '%s'" % name
except (KeyError, ValueError):
raise ValueError, "invalid '%s': %s" % (name, value)
return rrule(dtstart=dtstart, cache=cache, **rrkwargs)
def _parse_rfc(self, s,
dtstart=None,
cache=False,
unfold=False,
forceset=False,
compatible=False,
ignoretz=False,
tzinfos=None):
global parser
if compatible:
forceset = True
unfold = True
s = s.upper()
if not s.strip():
raise ValueError, "empty string"
if unfold:
lines = s.splitlines()
i = 0
while i < len(lines):
line = lines[i].rstrip()
if not line:
del lines[i]
elif i > 0 and line[0] == " ":
lines[i-1] += line[1:]
del lines[i]
else:
i += 1
else:
lines = s.split()
if (not forceset and len(lines) == 1 and
(s.find(':') == -1 or s.startswith('RRULE:'))):
return self._parse_rfc_rrule(lines[0], cache=cache,
dtstart=dtstart, ignoretz=ignoretz,
tzinfos=tzinfos)
else:
rrulevals = []
rdatevals = []
exrulevals = []
exdatevals = []
for line in lines:
if not line:
continue
if line.find(':') == -1:
name = "RRULE"
value = line
else:
name, value = line.split(':', 1)
parms = name.split(';')
if not parms:
raise ValueError, "empty property name"
name = parms[0]
parms = parms[1:]
if name == "RRULE":
for parm in parms:
raise ValueError, "unsupported RRULE parm: "+parm
rrulevals.append(value)
elif name == "RDATE":
for parm in parms:
if parm != "VALUE=DATE-TIME":
raise ValueError, "unsupported RDATE parm: "+parm
rdatevals.append(value)
elif name == "EXRULE":
for parm in parms:
raise ValueError, "unsupported EXRULE parm: "+parm
exrulevals.append(value)
elif name == "EXDATE":
for parm in parms:
if parm != "VALUE=DATE-TIME":
raise ValueError, "unsupported RDATE parm: "+parm
exdatevals.append(value)
elif name == "DTSTART":
for parm in parms:
raise ValueError, "unsupported DTSTART parm: "+parm
if not parser:
from dateutil import parser
dtstart = parser.parse(value, ignoretz=ignoretz,
tzinfos=tzinfos)
else:
raise ValueError, "unsupported property: "+name
if (forceset or len(rrulevals) > 1 or
rdatevals or exrulevals or exdatevals):
if not parser and (rdatevals or exdatevals):
from dateutil import parser
set = rruleset(cache=cache)
for value in rrulevals:
set.rrule(self._parse_rfc_rrule(value, dtstart=dtstart,
ignoretz=ignoretz,
tzinfos=tzinfos))
for value in rdatevals:
for datestr in value.split(','):
set.rdate(parser.parse(datestr,
ignoretz=ignoretz,
tzinfos=tzinfos))
for value in exrulevals:
set.exrule(self._parse_rfc_rrule(value, dtstart=dtstart,
ignoretz=ignoretz,
tzinfos=tzinfos))
for value in exdatevals:
for datestr in value.split(','):
set.exdate(parser.parse(datestr,
ignoretz=ignoretz,
tzinfos=tzinfos))
if compatible and dtstart:
set.rdate(dtstart)
return set
else:
return self._parse_rfc_rrule(rrulevals[0],
dtstart=dtstart,
cache=cache,
ignoretz=ignoretz,
tzinfos=tzinfos)
def __call__(self, s, **kwargs):
return self._parse_rfc(s, **kwargs)
rrulestr = _rrulestr()
# vim:ts=4:sw=4:et
|
bsd-3-clause
|
xybu/onedrived-dev
|
onedrived/od_models/webhook_notification.py
|
1
|
1902
|
"""
webhook_notification.py
Implementation of the datatypes used in OneDrive webhook notification, which is absent
from official OneDrive Python SDK.
:copyright: (c) Xiangyu Bu <[email protected]>
:license: MIT
"""
from .. import od_dateutils
class WebhookNotification:
""" https://dev.onedrive.com/resources/webhookNotifiation.htm """
def __init__(self, prop_dict):
self._prop_dict = prop_dict
@property
def context(self):
"""
:return str | None:
An optional string value that is passed back in the notification message for this subscription.
"""
try:
return self._prop_dict['context']
except KeyError:
return None
@property
def expiration_datetime(self):
"""
:return arrow.Arrow: The date and time when the subscription will expire if not updated or renewed.
"""
return od_dateutils.str_to_datetime(self._prop_dict['expirationDateTime'])
@property
def resource(self):
"""
:return str: URL to the item where the subscription is registered.
"""
return self._prop_dict['resource']
@property
def subscription_id(self):
"""
:return str: The unique identifier for the subscription resource.
"""
return self._prop_dict['subscriptionId']
@property
def tenant_id(self):
"""
:return str:
Unique identifier for the tenant which generated this notification.
This is only returned for OneDrive for Business and SharePoint.
"""
try:
return self._prop_dict['tenantId']
except KeyError:
return None
@property
def user_id(self):
"""
:return str: Unique identifier for the drive which generated this notification.
"""
return self._prop_dict['userId']
|
mit
|
pchauncey/ansible
|
lib/ansible/utils/shlex.py
|
267
|
1279
|
# (c) 2015, Marius Gedminas <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# alongwith Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import shlex
from ansible.module_utils.six import PY3
from ansible.module_utils._text import to_bytes, to_text
if PY3:
# shlex.split() wants Unicode (i.e. ``str``) input on Python 3
shlex_split = shlex.split
else:
# shlex.split() wants bytes (i.e. ``str``) input on Python 2
def shlex_split(s, comments=False, posix=True):
return map(to_text, shlex.split(to_bytes(s), comments, posix))
shlex_split.__doc__ = shlex.split.__doc__
|
gpl-3.0
|
littlstar/chromium.src
|
content/test/gpu/page_sets/pixel_tests.py
|
8
|
1531
|
# Copyright 2014 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.
from telemetry.page import page as page_module
from telemetry.page import page_set as page_set_module
class PixelTestsPage(page_module.Page):
def __init__(self, url, name, test_rect, revision, page_set):
super(PixelTestsPage, self).__init__(url=url, page_set=page_set, name=name)
self.user_agent_type = 'desktop'
self.test_rect = test_rect
self.revision = revision
def RunNavigateSteps(self, action_runner):
action_runner.NavigateToPage(self)
action_runner.WaitForJavaScriptCondition(
'domAutomationController._finished', timeout_in_seconds=30)
class PixelTestsPageSet(page_set_module.PageSet):
""" Some basic test cases for GPU. """
def __init__(self):
super(PixelTestsPageSet, self).__init__(
user_agent_type='desktop')
self.AddPage(PixelTestsPage(
url='file://../../data/gpu/pixel_canvas2d.html',
name='Pixel.Canvas2DRedBox',
test_rect=[0, 0, 300, 300],
revision=4,
page_set=self))
self.AddPage(PixelTestsPage(
url='file://../../data/gpu/pixel_css3d.html',
name='Pixel.CSS3DBlueBox',
test_rect=[0, 0, 300, 300],
revision=9,
page_set=self))
self.AddPage(PixelTestsPage(
url='file://../../data/gpu/pixel_webgl.html',
name='Pixel.WebGLGreenTriangle',
test_rect=[0, 0, 300, 300],
revision=8,
page_set=self))
|
bsd-3-clause
|
Acehaidrey/incubator-airflow
|
airflow/providers/google/cloud/hooks/spanner.py
|
8
|
16842
|
#
# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements. See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership. The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
"""This module contains a Google Cloud Spanner Hook."""
from typing import Callable, List, Optional, Sequence, Union
from google.api_core.exceptions import AlreadyExists, GoogleAPICallError
from google.cloud.spanner_v1.client import Client
from google.cloud.spanner_v1.database import Database
from google.cloud.spanner_v1.instance import Instance
from google.cloud.spanner_v1.transaction import Transaction
from google.longrunning.operations_grpc_pb2 import Operation # noqa: F401
from airflow.exceptions import AirflowException
from airflow.providers.google.common.hooks.base_google import GoogleBaseHook
class SpannerHook(GoogleBaseHook):
"""
Hook for Google Cloud Spanner APIs.
All the methods in the hook where project_id is used must be called with
keyword arguments rather than positional.
"""
def __init__(
self,
gcp_conn_id: str = "google_cloud_default",
delegate_to: Optional[str] = None,
impersonation_chain: Optional[Union[str, Sequence[str]]] = None,
) -> None:
super().__init__(
gcp_conn_id=gcp_conn_id,
delegate_to=delegate_to,
impersonation_chain=impersonation_chain,
)
self._client = None
def _get_client(self, project_id: str) -> Client:
"""
Provides a client for interacting with the Cloud Spanner API.
:param project_id: The ID of the Google Cloud project.
:type project_id: str
:return: Client
:rtype: google.cloud.spanner_v1.client.Client
"""
if not self._client:
self._client = Client(
project=project_id, credentials=self._get_credentials(), client_info=self.client_info
)
return self._client
@GoogleBaseHook.fallback_to_default_project_id
def get_instance(
self,
instance_id: str,
project_id: str,
) -> Instance:
"""
Gets information about a particular instance.
:param project_id: Optional, The ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:type project_id: str
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:return: Spanner instance
:rtype: google.cloud.spanner_v1.instance.Instance
"""
instance = self._get_client(project_id=project_id).instance(instance_id=instance_id)
if not instance.exists():
return None
return instance
def _apply_to_instance(
self,
project_id: str,
instance_id: str,
configuration_name: str,
node_count: int,
display_name: str,
func: Callable[[Instance], Operation],
) -> None:
"""
Invokes a method on a given instance by applying a specified Callable.
:param project_id: The ID of the Google Cloud project that owns the Cloud Spanner database.
:type project_id: str
:param instance_id: The ID of the instance.
:type instance_id: str
:param configuration_name: Name of the instance configuration defining how the
instance will be created. Required for instances which do not yet exist.
:type configuration_name: str
:param node_count: (Optional) Number of nodes allocated to the instance.
:type node_count: int
:param display_name: (Optional) The display name for the instance in the Cloud
Console UI. (Must be between 4 and 30 characters.) If this value is not set
in the constructor, will fall back to the instance ID.
:type display_name: str
:param func: Method of the instance to be called.
:type func: Callable[google.cloud.spanner_v1.instance.Instance]
"""
instance = self._get_client(project_id=project_id).instance(
instance_id=instance_id,
configuration_name=configuration_name,
node_count=node_count,
display_name=display_name,
)
try:
operation = func(instance) # type: Operation
except GoogleAPICallError as e:
self.log.error('An error occurred: %s. Exiting.', e.message)
raise e
if operation:
result = operation.result()
self.log.info(result)
@GoogleBaseHook.fallback_to_default_project_id
def create_instance(
self,
instance_id: str,
configuration_name: str,
node_count: int,
display_name: str,
project_id: str,
) -> None:
"""
Creates a new Cloud Spanner instance.
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param configuration_name: The name of the instance configuration defining how the
instance will be created. Possible configuration values can be retrieved via
https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instanceConfigs/list
:type configuration_name: str
:param node_count: (Optional) The number of nodes allocated to the Cloud Spanner
instance.
:type node_count: int
:param display_name: (Optional) The display name for the instance in the Google Cloud Console.
Must be between 4 and 30 characters. If this value is not passed, the name falls back
to the instance ID.
:type display_name: str
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:type project_id: str
:return: None
"""
self._apply_to_instance(
project_id, instance_id, configuration_name, node_count, display_name, lambda x: x.create()
)
@GoogleBaseHook.fallback_to_default_project_id
def update_instance(
self,
instance_id: str,
configuration_name: str,
node_count: int,
display_name: str,
project_id: str,
) -> None:
"""
Updates an existing Cloud Spanner instance.
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param configuration_name: The name of the instance configuration defining how the
instance will be created. Possible configuration values can be retrieved via
https://cloud.google.com/spanner/docs/reference/rest/v1/projects.instanceConfigs/list
:type configuration_name: str
:param node_count: (Optional) The number of nodes allocated to the Cloud Spanner
instance.
:type node_count: int
:param display_name: (Optional) The display name for the instance in the Google Cloud
Console. Must be between 4 and 30 characters. If this value is not set in
the constructor, the name falls back to the instance ID.
:type display_name: str
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:type project_id: str
:return: None
"""
self._apply_to_instance(
project_id, instance_id, configuration_name, node_count, display_name, lambda x: x.update()
)
@GoogleBaseHook.fallback_to_default_project_id
def delete_instance(self, instance_id: str, project_id: str) -> None:
"""
Deletes an existing Cloud Spanner instance.
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:type project_id: str
:return: None
"""
instance = self._get_client(project_id=project_id).instance(instance_id)
try:
instance.delete()
return
except GoogleAPICallError as e:
self.log.error('An error occurred: %s. Exiting.', e.message)
raise e
@GoogleBaseHook.fallback_to_default_project_id
def get_database(
self,
instance_id: str,
database_id: str,
project_id: str,
) -> Optional[Database]:
"""
Retrieves a database in Cloud Spanner. If the database does not exist
in the specified instance, it returns None.
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param database_id: The ID of the database in Cloud Spanner.
:type database_id: str
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:type project_id: str
:return: Database object or None if database does not exist
:rtype: google.cloud.spanner_v1.database.Database or None
"""
instance = self._get_client(project_id=project_id).instance(instance_id=instance_id)
if not instance.exists():
raise AirflowException(f"The instance {instance_id} does not exist in project {project_id} !")
database = instance.database(database_id=database_id)
if not database.exists():
return None
return database
@GoogleBaseHook.fallback_to_default_project_id
def create_database(
self,
instance_id: str,
database_id: str,
ddl_statements: List[str],
project_id: str,
) -> None:
"""
Creates a new database in Cloud Spanner.
:type project_id: str
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param database_id: The ID of the database to create in Cloud Spanner.
:type database_id: str
:param ddl_statements: The string list containing DDL for the new database.
:type ddl_statements: list[str]
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:return: None
"""
instance = self._get_client(project_id=project_id).instance(instance_id=instance_id)
if not instance.exists():
raise AirflowException(f"The instance {instance_id} does not exist in project {project_id} !")
database = instance.database(database_id=database_id, ddl_statements=ddl_statements)
try:
operation = database.create() # type: Operation
except GoogleAPICallError as e:
self.log.error('An error occurred: %s. Exiting.', e.message)
raise e
if operation:
result = operation.result()
self.log.info(result)
@GoogleBaseHook.fallback_to_default_project_id
def update_database(
self,
instance_id: str,
database_id: str,
ddl_statements: List[str],
project_id: str,
operation_id: Optional[str] = None,
) -> None:
"""
Updates DDL of a database in Cloud Spanner.
:type project_id: str
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param database_id: The ID of the database in Cloud Spanner.
:type database_id: str
:param ddl_statements: The string list containing DDL for the new database.
:type ddl_statements: list[str]
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:param operation_id: (Optional) The unique per database operation ID that can be
specified to implement idempotency check.
:type operation_id: str
:return: None
"""
instance = self._get_client(project_id=project_id).instance(instance_id=instance_id)
if not instance.exists():
raise AirflowException(f"The instance {instance_id} does not exist in project {project_id} !")
database = instance.database(database_id=database_id)
try:
operation = database.update_ddl(ddl_statements=ddl_statements, operation_id=operation_id)
if operation:
result = operation.result()
self.log.info(result)
return
except AlreadyExists as e:
if e.code == 409 and operation_id in e.message:
self.log.info(
"Replayed update_ddl message - the operation id %s " "was already done before.",
operation_id,
)
return
except GoogleAPICallError as e:
self.log.error('An error occurred: %s. Exiting.', e.message)
raise e
@GoogleBaseHook.fallback_to_default_project_id
def delete_database(self, instance_id: str, database_id, project_id: str) -> bool:
"""
Drops a database in Cloud Spanner.
:type project_id: str
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param database_id: The ID of the database in Cloud Spanner.
:type database_id: str
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:return: True if everything succeeded
:rtype: bool
"""
instance = self._get_client(project_id=project_id).instance(instance_id=instance_id)
if not instance.exists():
raise AirflowException(f"The instance {instance_id} does not exist in project {project_id} !")
database = instance.database(database_id=database_id)
if not database.exists():
self.log.info(
"The database %s is already deleted from instance %s. Exiting.", database_id, instance_id
)
return False
try:
database.drop() # pylint: disable=E1111
except GoogleAPICallError as e:
self.log.error('An error occurred: %s. Exiting.', e.message)
raise e
return True
@GoogleBaseHook.fallback_to_default_project_id
def execute_dml(
self,
instance_id: str,
database_id: str,
queries: List[str],
project_id: str,
) -> None:
"""
Executes an arbitrary DML query (INSERT, UPDATE, DELETE).
:param instance_id: The ID of the Cloud Spanner instance.
:type instance_id: str
:param database_id: The ID of the database in Cloud Spanner.
:type database_id: str
:param queries: The queries to execute.
:type queries: List[str]
:param project_id: Optional, the ID of the Google Cloud project that owns the Cloud Spanner
database. If set to None or missing, the default project_id from the Google Cloud connection
is used.
:type project_id: str
"""
self._get_client(project_id=project_id).instance(instance_id=instance_id).database(
database_id=database_id
).run_in_transaction(lambda transaction: self._execute_sql_in_transaction(transaction, queries))
@staticmethod
def _execute_sql_in_transaction(transaction: Transaction, queries: List[str]):
for sql in queries:
transaction.execute_update(sql)
|
apache-2.0
|
dhimmel/networkx
|
networkx/algorithms/tests/test_dominating.py
|
54
|
1348
|
from nose.tools import assert_equal, assert_true, assert_false, raises
import networkx as nx
def test_dominating_set():
G = nx.gnp_random_graph(100, 0.1)
D = nx.dominating_set(G)
assert_true(nx.is_dominating_set(G, D))
D = nx.dominating_set(G, start_with=0)
assert_true(nx.is_dominating_set(G, D))
def test_complete():
""" In complete graphs each node is a dominating set.
Thus the dominating set has to be of cardinality 1.
"""
K4 = nx.complete_graph(4)
assert_equal(len(nx.dominating_set(K4)), 1)
K5 = nx.complete_graph(5)
assert_equal(len(nx.dominating_set(K5)), 1)
@raises(nx.NetworkXError)
def test_dominating_set_error():
G = nx.path_graph(4)
D = nx.dominating_set(G, start_with=10)
def test_is_dominating_set():
G = nx.path_graph(4)
d = set([1, 3])
assert_true(nx.is_dominating_set(G, d))
d = set([0, 2])
assert_true(nx.is_dominating_set(G, d))
d = set([1])
assert_false(nx.is_dominating_set(G, d))
def test_wikipedia_is_dominating_set():
"""Example from http://en.wikipedia.org/wiki/Dominating_set
"""
G = nx.cycle_graph(4)
G.add_edges_from([(0, 4), (1, 4), (2,5)])
assert_true(nx.is_dominating_set(G, set([4, 3, 5])))
assert_true(nx.is_dominating_set(G, set([0, 2])))
assert_true(nx.is_dominating_set(G, set([1, 2])))
|
bsd-3-clause
|
mats116/ElasticBigQuery
|
boilerplate/external/wtforms/widgets/core.py
|
67
|
8340
|
from __future__ import unicode_literals
from cgi import escape
from wtforms.compat import text_type, string_types, iteritems
__all__ = (
'CheckboxInput', 'FileInput', 'HiddenInput', 'ListWidget', 'PasswordInput',
'RadioInput', 'Select', 'SubmitInput', 'TableWidget', 'TextArea',
'TextInput', 'Option'
)
def html_params(**kwargs):
"""
Generate HTML parameters from inputted keyword arguments.
The output value is sorted by the passed keys, to provide consistent output
each time this function is called with the same parameters. Because of the
frequent use of the normally reserved keywords `class` and `for`, suffixing
these with an underscore will allow them to be used.
>>> html_params(name='text1', id='f', class_='text') == 'class="text" id="f" name="text1"'
True
"""
params = []
for k,v in sorted(iteritems(kwargs)):
if k in ('class_', 'class__', 'for_'):
k = k[:-1]
if v is True:
params.append(k)
else:
params.append('%s="%s"' % (text_type(k), escape(text_type(v), quote=True)))
return ' '.join(params)
class HTMLString(text_type):
def __html__(self):
return self
class ListWidget(object):
"""
Renders a list of fields as a `ul` or `ol` list.
This is used for fields which encapsulate many inner fields as subfields.
The widget will try to iterate the field to get access to the subfields and
call them to render them.
If `prefix_label` is set, the subfield's label is printed before the field,
otherwise afterwards. The latter is useful for iterating radios or
checkboxes.
"""
def __init__(self, html_tag='ul', prefix_label=True):
assert html_tag in ('ol', 'ul')
self.html_tag = html_tag
self.prefix_label = prefix_label
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
html = ['<%s %s>' % (self.html_tag, html_params(**kwargs))]
for subfield in field:
if self.prefix_label:
html.append('<li>%s: %s</li>' % (subfield.label, subfield()))
else:
html.append('<li>%s %s</li>' % (subfield(), subfield.label))
html.append('</%s>' % self.html_tag)
return HTMLString(''.join(html))
class TableWidget(object):
"""
Renders a list of fields as a set of table rows with th/td pairs.
If `with_table_tag` is True, then an enclosing <table> is placed around the
rows.
Hidden fields will not be displayed with a row, instead the field will be
pushed into a subsequent table row to ensure XHTML validity. Hidden fields
at the end of the field list will appear outside the table.
"""
def __init__(self, with_table_tag=True):
self.with_table_tag = with_table_tag
def __call__(self, field, **kwargs):
html = []
if self.with_table_tag:
kwargs.setdefault('id', field.id)
html.append('<table %s>' % html_params(**kwargs))
hidden = ''
for subfield in field:
if subfield.type == 'HiddenField':
hidden += text_type(subfield)
else:
html.append('<tr><th>%s</th><td>%s%s</td></tr>' % (text_type(subfield.label), hidden, text_type(subfield)))
hidden = ''
if self.with_table_tag:
html.append('</table>')
if hidden:
html.append(hidden)
return HTMLString(''.join(html))
class Input(object):
"""
Render a basic ``<input>`` field.
This is used as the basis for most of the other input fields.
By default, the `_value()` method will be called upon the associated field
to provide the ``value=`` HTML attribute.
"""
html_params = staticmethod(html_params)
def __init__(self, input_type=None):
if input_type is not None:
self.input_type = input_type
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
kwargs.setdefault('type', self.input_type)
if 'value' not in kwargs:
kwargs['value'] = field._value()
return HTMLString('<input %s>' % self.html_params(name=field.name, **kwargs))
class TextInput(Input):
"""
Render a single-line text input.
"""
input_type = 'text'
class PasswordInput(Input):
"""
Render a password input.
For security purposes, this field will not reproduce the value on a form
submit by default. To have the value filled in, set `hide_value` to
`False`.
"""
input_type = 'password'
def __init__(self, hide_value=True):
self.hide_value = hide_value
def __call__(self, field, **kwargs):
if self.hide_value:
kwargs['value'] = ''
return super(PasswordInput, self).__call__(field, **kwargs)
class HiddenInput(Input):
"""
Render a hidden input.
"""
input_type = 'hidden'
class CheckboxInput(Input):
"""
Render a checkbox.
The ``checked`` HTML attribute is set if the field's data is a non-false value.
"""
input_type = 'checkbox'
def __call__(self, field, **kwargs):
if getattr(field, 'checked', field.data):
kwargs['checked'] = True
return super(CheckboxInput, self).__call__(field, **kwargs)
class RadioInput(Input):
"""
Render a single radio button.
This widget is most commonly used in conjunction with ListWidget or some
other listing, as singular radio buttons are not very useful.
"""
input_type = 'radio'
def __call__(self, field, **kwargs):
if field.checked:
kwargs['checked'] = True
return super(RadioInput, self).__call__(field, **kwargs)
class FileInput(object):
"""
Renders a file input chooser field.
"""
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
value = field._value()
if value:
kwargs.setdefault('value', value)
return HTMLString('<input %s>' % html_params(name=field.name, type='file', **kwargs))
class SubmitInput(Input):
"""
Renders a submit button.
The field's label is used as the text of the submit button instead of the
data on the field.
"""
input_type = 'submit'
def __call__(self, field, **kwargs):
kwargs.setdefault('value', field.label.text)
return super(SubmitInput, self).__call__(field, **kwargs)
class TextArea(object):
"""
Renders a multi-line text area.
`rows` and `cols` ought to be passed as keyword args when rendering.
"""
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
return HTMLString('<textarea %s>%s</textarea>' % (html_params(name=field.name, **kwargs), escape(text_type(field._value()))))
class Select(object):
"""
Renders a select field.
If `multiple` is True, then the `size` property should be specified on
rendering to make the field useful.
The field must provide an `iter_choices()` method which the widget will
call on rendering; this method must yield tuples of
`(value, label, selected)`.
"""
def __init__(self, multiple=False):
self.multiple = multiple
def __call__(self, field, **kwargs):
kwargs.setdefault('id', field.id)
if self.multiple:
kwargs['multiple'] = True
html = ['<select %s>' % html_params(name=field.name, **kwargs)]
for val, label, selected in field.iter_choices():
html.append(self.render_option(val, label, selected))
html.append('</select>')
return HTMLString(''.join(html))
@classmethod
def render_option(cls, value, label, selected, **kwargs):
options = dict(kwargs, value=value)
if selected:
options['selected'] = True
return HTMLString('<option %s>%s</option>' % (html_params(**options), escape(text_type(label))))
class Option(object):
"""
Renders the individual option from a select field.
This is just a convenience for various custom rendering situations, and an
option by itself does not constitute an entire field.
"""
def __call__(self, field, **kwargs):
return Select.render_option(field._value(), field.label.text, field.checked, **kwargs)
|
lgpl-3.0
|
oandrew/home-assistant
|
homeassistant/components/sensor/gpsd.py
|
17
|
3323
|
"""
Support for GPSD.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/sensor.gpsd/
"""
import logging
import voluptuous as vol
from homeassistant.components.sensor import PLATFORM_SCHEMA
from homeassistant.const import (
ATTR_LATITUDE, ATTR_LONGITUDE, STATE_UNKNOWN, CONF_HOST, CONF_PORT,
CONF_NAME)
from homeassistant.helpers.entity import Entity
import homeassistant.helpers.config_validation as cv
REQUIREMENTS = ['gps3==0.33.3']
_LOGGER = logging.getLogger(__name__)
ATTR_CLIMB = 'climb'
ATTR_ELEVATION = 'elevation'
ATTR_GPS_TIME = 'gps_time'
ATTR_MODE = 'mode'
ATTR_SPEED = 'speed'
DEFAULT_HOST = 'localhost'
DEFAULT_NAME = 'GPS'
DEFAULT_PORT = 2947
PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend({
vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
vol.Optional(CONF_HOST, default=DEFAULT_HOST): cv.string,
vol.Optional(CONF_PORT, default=DEFAULT_PORT): cv.port,
})
def setup_platform(hass, config, add_devices, discovery_info=None):
"""Setup the GPSD component."""
name = config.get(CONF_NAME)
host = config.get(CONF_HOST)
port = config.get(CONF_PORT)
# Will hopefully be possible with the next gps3 update
# https://github.com/wadda/gps3/issues/11
# from gps3 import gps3
# try:
# gpsd_socket = gps3.GPSDSocket()
# gpsd_socket.connect(host=host, port=port)
# except GPSError:
# _LOGGER.warning('Not able to connect to GPSD')
# return False
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect((host, port))
sock.shutdown(2)
_LOGGER.debug('Connection to GPSD possible')
except socket.error:
_LOGGER.error('Not able to connect to GPSD')
return False
add_devices([GpsdSensor(hass, name, host, port)])
class GpsdSensor(Entity):
"""Representation of a GPS receiver available via GPSD."""
def __init__(self, hass, name, host, port):
"""Initialize the GPSD sensor."""
from gps3.agps3threaded import AGPS3mechanism
self.hass = hass
self._name = name
self._host = host
self._port = port
self.agps_thread = AGPS3mechanism()
self.agps_thread.stream_data(host=self._host, port=self._port)
self.agps_thread.run_thread()
@property
def name(self):
"""Return the name."""
return self._name
# pylint: disable=no-member
@property
def state(self):
"""Return the state of GPSD."""
if self.agps_thread.data_stream.mode == 3:
return "3D Fix"
elif self.agps_thread.data_stream.mode == 2:
return "2D Fix"
else:
return STATE_UNKNOWN
@property
def state_attributes(self):
"""Return the state attributes of the GPS."""
return {
ATTR_LATITUDE: self.agps_thread.data_stream.lat,
ATTR_LONGITUDE: self.agps_thread.data_stream.lon,
ATTR_ELEVATION: self.agps_thread.data_stream.alt,
ATTR_GPS_TIME: self.agps_thread.data_stream.time,
ATTR_SPEED: self.agps_thread.data_stream.speed,
ATTR_CLIMB: self.agps_thread.data_stream.climb,
ATTR_MODE: self.agps_thread.data_stream.mode,
}
|
mit
|
satsumas/prop
|
qtree.py
|
1
|
1595
|
"""
A presentation layer for generating LaTeX Qtree output.
"""
import copy
class Qtree(object):
r"""
A qtree is rendered as a root with some branches:
ROOT
/ \
b1 b2 ...
"""
def __init__(self, root, branches=[]):
"""
@arg root: A string which is rendered as "ROOT" in the example above.
@arg branches: A list of Qtree objects.
"""
self._root = root
self._branches = branches
def addBranch(self, branch):
"""
Add a new branch.
@param branch: A Qtree.
"""
self._branches.append(branch)
def _escapedRoot(self):
"""
Converts newlines into double backslashes and wraps curly brackets around it.
"""
return "{%s}" % (self._root.replace("\n", r"\\"),)
def render(self, seen=None):
"""
Sibling branches are rendered inside qtree by simply concatenating
them.
"""
if seen is None:
seen = [self]
else:
seen.append(self)
results = []
def _debug(q):
print repr(q._root) + ":" + hex(id(q)), "branches:", [b._root + ":" + hex(id(b)) for b in q._branches]
_debug(self)
for branch in self._branches:
if branch not in seen:
seen.append(branch)
results.append(branch.render(seen=copy.copy(seen)))
else:
print "SEEN YOU BEFORE! ==="
_debug(branch)
print "===================="
return "[.%s %s ]" % (self._escapedRoot(), " ".join(results))
|
gpl-3.0
|
zstars/weblabdeusto
|
server/src/test/unit/voodoo/test_mapper.py
|
2
|
10712
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2005 onwards University of Deusto
# All rights reserved.
#
# This software is licensed as described in the file COPYING, which
# you should have received as part of this distribution.
#
# This software consists of contributions made by many individuals,
# listed below:
#
# Author: Pablo Orduña <[email protected]>
#
import unittest
import threading
import thread
import pickle
import datetime
import xmlrpclib
import urllib2
import xml.parsers.expat as expat_parser
import voodoo.mapper as mapper
class MyClass(object):
def __init__(self,first_field,second_field,third_field):
object.__init__(self)
self._first_field = first_field
self._second_field = second_field
self._third_field = third_field
self.sum_of_fields = first_field + second_field
self.another = threading.Lock()
self.yet_another = 5.5
def my_method(self):
self.another.acquire()
self.another.release()
class MyOtherClass:
def __init__(self,param):
self.param = param
self.param2 = open(__file__)
class JetAnotherClass:
def __init__(self,param):
self.otherReference = param
class MyClass2(object):
pass
class MyError(Exception): pass
class SimpleClass: pass
class MapperTestCase(unittest.TestCase):
def test_dto_generator(self):
mc = MyClass(1,2,(1,2))
mc.and_another = MyClass(1,3,(1,3))
moc = MyOtherClass(4+4j)
# Cyclic references
jac1 = JetAnotherClass(None)
jac2 = JetAnotherClass(jac1)
jac1.otherReference = jac2
# mc and moc can't be pickled
# pickle raises pickle.PicklingError in Python < 2.7 but TypeError in Python 2.7; we try both exceptions
try:
self.assertRaises(
pickle.PicklingError,
pickle.dumps,
mc
)
except:
first_assertion_failed = True
else:
first_assertion_failed = False
try:
self.assertRaises(
TypeError,
pickle.dumps,
mc
)
except:
if first_assertion_failed:
raise
self.assertRaises(
TypeError,
pickle.dumps,
moc
)
my_dto = mapper.dto_generator(mc)
self.assertEquals(
my_dto._first_field,
mc._first_field
)
self.assertEquals(
my_dto._second_field,
mc._second_field
)
self.assertEquals(
my_dto._third_field,
mc._third_field
)
self.assertEquals(
my_dto.sum_of_fields,
mc.sum_of_fields
)
self.assertNotEquals( #Lock not allowed
type(my_dto.another),
thread.LockType
)
self.assertEquals(
my_dto.yet_another,
mc.yet_another
)
# And inside and_another... so on
self.assertEquals(
my_dto.and_another._first_field,
mc.and_another._first_field
)
# What about moc?
my_other_dto = mapper.dto_generator(moc)
self.assertEquals(
my_other_dto.param,
moc.param
)
self.assertEquals(
hasattr(my_other_dto,'param2'),
False
)
# What about JetAnotherClass?
my_other_jac1 = mapper.dto_generator(jac1)
my_other_jac1.otherReference
# Go ahead! Pickle me! ;-D
pickled = pickle.dumps(my_dto)
my_dto2 = pickle.loads(pickled)
pickled = pickle.dumps(my_other_dto)
my_other_dto2 = pickle.loads(pickled)
# Let's try to unload them
my_dto2 = mapper.load_from_dto(my_dto2)
my_other_dto2 = mapper.load_from_dto(my_other_dto2)
# Let's check locks work
my_dto2.my_method() #Nothing happens :-)
def test_mapping_ignorable(self):
native_obj = expat_parser.ParserCreate()
self.assertRaises(
pickle.PicklingError,
pickle.dumps,
native_obj
)
class MyClass(object):
pass
my_class = MyClass()
my_class.native_obj = native_obj
dto = mapper.dto_generator(my_class)
my_class2 = mapper.load_from_dto(dto)
self.assertTrue(isinstance(my_class2.native_obj,str))
def test_dto_not_comparable_instances(self):
dt = xmlrpclib.DateTime()
# DateTime throws exception when doing:
# dt == {}
# for instance
dto = mapper.dto_generator({"foo" : dt})
dt2 = mapper.load_from_dto(dto)
self.assertEquals(["foo"], dt2.keys())
self.assertEquals(dt.value, dt2["foo"].value)
def test_dto_exception(self):
exception = MyError("foo")
dto = mapper.dto_generator(exception)
generated = mapper.load_from_dto(dto)
self.assertTrue(isinstance(generated,MyError))
self.assertEquals("foo", generated.args[0] )
def test_dto_builtin(self):
exception = AttributeError("foo")
dto = mapper.dto_generator(exception)
generated = mapper.load_from_dto(dto)
self.assertTrue(isinstance(generated,AttributeError))
self.assertEquals("foo", generated.args[0] )
def test_dto_datetime(self):
sc = SimpleClass()
sc.time = datetime.datetime(2007, 12, 31, 23, 55)
dto = mapper.dto_generator(sc)
sc2 = mapper.load_from_dto(dto)
self.assertEquals(2007, sc2.time.year)
self.assertEquals(12 , sc2.time.month)
self.assertEquals(31 , sc2.time.day)
self.assertEquals(23 , sc2.time.hour)
self.assertEquals(55 , sc2.time.minute)
def test_skip_recoverables(self):
a = SimpleClass()
a.l = threading.Lock()
dto = mapper.dto_generator(a)
a2 = mapper.load_from_dto(dto, skip_recoverables = True)
self.assertEquals(None, a2.l)
a3 = mapper.load_from_dto(dto, skip_recoverables = False)
self.assertTrue(isinstance(a3.l, thread.LockType))
def test_remove_unpickables_lock(self):
a = SimpleClass()
a.l = threading.Lock()
mapper.remove_unpickables(a)
self.assertEquals(None, a.l)
def test_remove_unpickables_not_comparable_instances(self):
dt = xmlrpclib.DateTime()
# DateTime throws exception when doing:
# dt == {}
# for instance
mapper.remove_unpickables({"foo" : dt})
def test_remove_unpickables_datetime(self):
sc = SimpleClass()
sc.time = datetime.datetime(2007, 12, 31, 23, 55)
mapper.remove_unpickables(sc)
self.assertEquals(2007, sc.time.year)
self.assertEquals(12 , sc.time.month)
self.assertEquals(31 , sc.time.day)
self.assertEquals(23 , sc.time.hour)
self.assertEquals(55 , sc.time.minute)
def test_remove_unpickables_ignorable(self):
parser = expat_parser.ParserCreate()
self.assertRaises(
pickle.PicklingError,
pickle.dumps,
parser
)
my_class = MyClass2()
my_class.parser = parser
mapper.remove_unpickables(my_class)
pickle.dumps(my_class) # No problem now
self.assertEqual(None, my_class.parser)
def test_remove_unpickables_general(self):
mc = MyClass(1,2,(1,2))
mc.and_another = MyClass(1,3,(1,3))
moc = MyOtherClass(4+4j)
# Cyclic references
jac1 = JetAnotherClass(None)
jac2 = JetAnotherClass(jac1)
jac1.otherReference = jac2
# mc and moc can't be pickled
# pickle raises pickle.PicklingError in Python < 2.7 but TypeError in Python 2.7; we try both exceptions
try:
self.assertRaises(
pickle.PicklingError,
pickle.dumps,
mc
)
except:
failed_first_time = True
else:
failed_first_time = False
try:
self.assertRaises(
TypeError,
pickle.dumps,
mc
)
except:
if failed_first_time:
raise
self.assertRaises(
TypeError,
pickle.dumps,
moc
)
mapper.remove_unpickables(mc)
self.assertEquals(
1,
mc._first_field
)
self.assertEquals(
2,
mc._second_field
)
self.assertEquals(
(1,2),
mc._third_field
)
self.assertEquals(
1 + 2,
mc.sum_of_fields
)
self.assertEquals( #Lock not allowed
None,
mc.another
)
self.assertEquals(
5.5,
mc.yet_another
)
# And inside and_another... so on
self.assertEquals(
1,
mc.and_another._first_field
)
# What about moc?
mapper.remove_unpickables(moc)
self.assertEquals(
4+4j,
moc.param
)
self.assertEquals(
None,
moc.param2
)
# What about JetAnotherClass?
mapper.remove_unpickables(jac1)
# Go ahead! Pickle me! ;-D
pickled = pickle.dumps(mc)
pickle.loads(pickled)
pickled = pickle.dumps(moc)
pickle.loads(pickled)
def test_remove_unpickables_http_exception(self):
try:
urllib2.urlopen("http://localhost/this.does.not.exist")
self.fail("exception expected")
except urllib2.URLError as e:
pass
except urllib2.HTTPError as e:
pass
removed = mapper.remove_unpickables(e)
pickled = pickle.dumps(removed)
pickle.loads(pickled)
def test_condition(self):
c1 = threading.Condition()
dto = mapper.dto_generator(c1)
c2 = mapper.load_from_dto(dto)
self.assertTrue(hasattr(c2, 'acquire'))
self.assertTrue(hasattr(c2, 'release'))
def suite():
return unittest.makeSuite(MapperTestCase)
if __name__ == '__main__':
unittest.main()
|
bsd-2-clause
|
clinton-hall/nzbToMedia
|
core/configuration.py
|
1
|
31372
|
# coding=utf-8
from __future__ import (
absolute_import,
division,
print_function,
unicode_literals,
)
import copy
import os
import shutil
from itertools import chain
import configobj
from six import iteritems
import core
from core import logger
class Section(configobj.Section, object):
def isenabled(self):
# checks if subsection enabled, returns true/false if subsection specified otherwise returns true/false in {}
if not self.sections:
try:
value = list(ConfigObj.find_key(self, 'enabled'))[0]
except Exception:
value = 0
if int(value) == 1:
return self
else:
to_return = copy.deepcopy(self)
for section_name, subsections in to_return.items():
for subsection in subsections:
try:
value = list(ConfigObj.find_key(subsections, 'enabled'))[0]
except Exception:
value = 0
if int(value) != 1:
del to_return[section_name][subsection]
# cleanout empty sections and subsections
for key in [k for (k, v) in to_return.items() if not v]:
del to_return[key]
return to_return
def findsection(self, key):
to_return = copy.deepcopy(self)
for subsection in to_return:
try:
value = list(ConfigObj.find_key(to_return[subsection], key))[0]
except Exception:
value = None
if not value:
del to_return[subsection]
else:
for category in to_return[subsection]:
if category != key:
del to_return[subsection][category]
# cleanout empty sections and subsections
for key in [k for (k, v) in to_return.items() if not v]:
del to_return[key]
return to_return
def __getitem__(self, key):
if key in self.keys():
return dict.__getitem__(self, key)
to_return = copy.deepcopy(self)
for section, subsections in to_return.items():
if section in key:
continue
if isinstance(subsections, Section) and subsections.sections:
for subsection, options in subsections.items():
if subsection in key:
continue
if key in options:
return options[key]
del subsections[subsection]
else:
if section not in key:
del to_return[section]
# cleanout empty sections and subsections
for key in [k for (k, v) in to_return.items() if not v]:
del to_return[key]
return to_return
class ConfigObj(configobj.ConfigObj, Section):
def __init__(self, *args, **kw):
if len(args) == 0:
args = (core.CONFIG_FILE,)
super(configobj.ConfigObj, self).__init__(*args, **kw)
self.interpolation = False
@staticmethod
def find_key(node, kv):
if isinstance(node, list):
for i in node:
for x in ConfigObj.find_key(i, kv):
yield x
elif isinstance(node, dict):
if kv in node:
yield node[kv]
for j in node.values():
for x in ConfigObj.find_key(j, kv):
yield x
@staticmethod
def migrate():
global CFG_NEW, CFG_OLD
CFG_NEW = None
CFG_OLD = None
try:
# check for autoProcessMedia.cfg and create if it does not exist
if not os.path.isfile(core.CONFIG_FILE):
shutil.copyfile(core.CONFIG_SPEC_FILE, core.CONFIG_FILE)
CFG_OLD = config(core.CONFIG_FILE)
except Exception as error:
logger.error('Error {msg} when copying to .cfg'.format(msg=error))
try:
# check for autoProcessMedia.cfg.spec and create if it does not exist
if not os.path.isfile(core.CONFIG_SPEC_FILE):
shutil.copyfile(core.CONFIG_FILE, core.CONFIG_SPEC_FILE)
CFG_NEW = config(core.CONFIG_SPEC_FILE)
except Exception as error:
logger.error('Error {msg} when copying to .spec'.format(msg=error))
# check for autoProcessMedia.cfg and autoProcessMedia.cfg.spec and if they don't exist return and fail
if CFG_NEW is None or CFG_OLD is None:
return False
subsections = {}
# gather all new-style and old-style sub-sections
for newsection in CFG_NEW:
if CFG_NEW[newsection].sections:
subsections.update({newsection: CFG_NEW[newsection].sections})
for section in CFG_OLD:
if CFG_OLD[section].sections:
subsections.update({section: CFG_OLD[section].sections})
for option, value in CFG_OLD[section].items():
if option in ['category', 'cpsCategory', 'sbCategory', 'hpCategory', 'mlCategory', 'gzCategory', 'raCategory', 'ndCategory', 'W3Category']:
if not isinstance(value, list):
value = [value]
# add subsection
subsections.update({section: value})
CFG_OLD[section].pop(option)
continue
def cleanup_values(values, section):
for option, value in iteritems(values):
if section in ['CouchPotato']:
if option == ['outputDirectory']:
CFG_NEW['Torrent'][option] = os.path.split(os.path.normpath(value))[0]
values.pop(option)
if section in ['CouchPotato', 'HeadPhones', 'Gamez', 'Mylar']:
if option in ['username', 'password']:
values.pop(option)
if section in ['SickBeard', 'Mylar']:
if option == 'wait_for': # remove old format
values.pop(option)
if section in ['SickBeard', 'NzbDrone']:
if option == 'failed_fork': # change this old format
values['failed'] = 'auto'
values.pop(option)
if option == 'outputDirectory': # move this to new location format
CFG_NEW['Torrent'][option] = os.path.split(os.path.normpath(value))[0]
values.pop(option)
if section in ['Torrent']:
if option in ['compressedExtensions', 'mediaExtensions', 'metaExtensions', 'minSampleSize']:
CFG_NEW['Extensions'][option] = value
values.pop(option)
if option == 'useLink': # Sym links supported now as well.
if value in ['1', 1]:
value = 'hard'
elif value in ['0', 0]:
value = 'no'
values[option] = value
if option == 'forceClean':
CFG_NEW['General']['force_clean'] = value
values.pop(option)
if option == 'qBittorrenHost': #We had a typo that is now fixed.
CFG_NEW['Torrent']['qBittorrentHost'] = value
values.pop(option)
if section in ['Transcoder']:
if option in ['niceness']:
CFG_NEW['Posix'][option] = value
values.pop(option)
if option == 'remote_path':
if value and value not in ['0', '1', 0, 1]:
value = 1
elif not value:
value = 0
values[option] = value
# remove any options that we no longer need so they don't migrate into our new config
if not list(ConfigObj.find_key(CFG_NEW, option)):
try:
values.pop(option)
except Exception:
pass
return values
def process_section(section, subsections=None):
if subsections:
for subsection in subsections:
if subsection in CFG_OLD.sections:
values = cleanup_values(CFG_OLD[subsection], section)
if subsection not in CFG_NEW[section].sections:
CFG_NEW[section][subsection] = {}
for option, value in values.items():
CFG_NEW[section][subsection][option] = value
elif subsection in CFG_OLD[section].sections:
values = cleanup_values(CFG_OLD[section][subsection], section)
if subsection not in CFG_NEW[section].sections:
CFG_NEW[section][subsection] = {}
for option, value in values.items():
CFG_NEW[section][subsection][option] = value
else:
values = cleanup_values(CFG_OLD[section], section)
if section not in CFG_NEW.sections:
CFG_NEW[section] = {}
for option, value in values.items():
CFG_NEW[section][option] = value
# convert old-style categories to new-style sub-sections
for section in CFG_OLD.keys():
subsection = None
if section in list(chain.from_iterable(subsections.values())):
subsection = section
section = ''.join([k for k, v in iteritems(subsections) if subsection in v])
process_section(section, subsection)
elif section in subsections.keys():
subsection = subsections[section]
process_section(section, subsection)
elif section in CFG_OLD.keys():
process_section(section, subsection)
# create a backup of our old config
CFG_OLD.filename = '{config}.old'.format(config=core.CONFIG_FILE)
CFG_OLD.write()
# write our new config to autoProcessMedia.cfg
CFG_NEW.filename = core.CONFIG_FILE
CFG_NEW.write()
return True
@staticmethod
def addnzbget():
# load configs into memory
cfg_new = config()
try:
if 'NZBPO_NDCATEGORY' in os.environ and 'NZBPO_SBCATEGORY' in os.environ:
if os.environ['NZBPO_NDCATEGORY'] == os.environ['NZBPO_SBCATEGORY']:
logger.warning('{x} category is set for SickBeard and Sonarr. '
'Please check your config in NZBGet'.format
(x=os.environ['NZBPO_NDCATEGORY']))
if 'NZBPO_RACATEGORY' in os.environ and 'NZBPO_CPSCATEGORY' in os.environ:
if os.environ['NZBPO_RACATEGORY'] == os.environ['NZBPO_CPSCATEGORY']:
logger.warning('{x} category is set for CouchPotato and Radarr. '
'Please check your config in NZBGet'.format
(x=os.environ['NZBPO_RACATEGORY']))
if 'NZBPO_RACATEGORY' in os.environ and 'NZBPO_W3CATEGORY' in os.environ:
if os.environ['NZBPO_RACATEGORY'] == os.environ['NZBPO_W3CATEGORY']:
logger.warning('{x} category is set for Watcher3 and Radarr. '
'Please check your config in NZBGet'.format
(x=os.environ['NZBPO_RACATEGORY']))
if 'NZBPO_W3CATEGORY' in os.environ and 'NZBPO_CPSCATEGORY' in os.environ:
if os.environ['NZBPO_W3CATEGORY'] == os.environ['NZBPO_CPSCATEGORY']:
logger.warning('{x} category is set for CouchPotato and Watcher3. '
'Please check your config in NZBGet'.format
(x=os.environ['NZBPO_W3CATEGORY']))
if 'NZBPO_LICATEGORY' in os.environ and 'NZBPO_HPCATEGORY' in os.environ:
if os.environ['NZBPO_LICATEGORY'] == os.environ['NZBPO_HPCATEGORY']:
logger.warning('{x} category is set for HeadPhones and Lidarr. '
'Please check your config in NZBGet'.format
(x=os.environ['NZBPO_LICATEGORY']))
section = 'Nzb'
key = 'NZBOP_DESTDIR'
if key in os.environ:
option = 'default_downloadDirectory'
value = os.environ[key]
cfg_new[section][option] = value
section = 'General'
env_keys = ['AUTO_UPDATE', 'CHECK_MEDIA', 'SAFE_MODE', 'NO_EXTRACT_FAILED']
cfg_keys = ['auto_update', 'check_media', 'safe_mode', 'no_extract_failed']
for index in range(len(env_keys)):
key = 'NZBPO_{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
cfg_new[section][option] = value
section = 'Network'
env_keys = ['MOUNTPOINTS']
cfg_keys = ['mount_points']
for index in range(len(env_keys)):
key = 'NZBPO_{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
cfg_new[section][option] = value
section = 'CouchPotato'
env_cat_key = 'NZBPO_CPSCATEGORY'
env_keys = ['ENABLED', 'APIKEY', 'HOST', 'PORT', 'SSL', 'WEB_ROOT', 'METHOD', 'DELETE_FAILED', 'REMOTE_PATH',
'WAIT_FOR', 'WATCH_DIR', 'OMDBAPIKEY']
cfg_keys = ['enabled', 'apikey', 'host', 'port', 'ssl', 'web_root', 'method', 'delete_failed', 'remote_path',
'wait_for', 'watch_dir', 'omdbapikey']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_CPS{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
if os.environ[env_cat_key] in cfg_new['Radarr'].sections:
cfg_new['Radarr'][env_cat_key]['enabled'] = 0
if os.environ[env_cat_key] in cfg_new['Watcher3'].sections:
cfg_new['Watcher3'][env_cat_key]['enabled'] = 0
section = 'Watcher3'
env_cat_key = 'NZBPO_W3CATEGORY'
env_keys = ['ENABLED', 'APIKEY', 'HOST', 'PORT', 'SSL', 'WEB_ROOT', 'METHOD', 'DELETE_FAILED', 'REMOTE_PATH',
'WAIT_FOR', 'WATCH_DIR', 'OMDBAPIKEY']
cfg_keys = ['enabled', 'apikey', 'host', 'port', 'ssl', 'web_root', 'method', 'delete_failed', 'remote_path',
'wait_for', 'watch_dir', 'omdbapikey']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_W3{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
if os.environ[env_cat_key] in cfg_new['Radarr'].sections:
cfg_new['Radarr'][env_cat_key]['enabled'] = 0
if os.environ[env_cat_key] in cfg_new['CouchPotato'].sections:
cfg_new['CouchPotato'][env_cat_key]['enabled'] = 0
section = 'SickBeard'
env_cat_key = 'NZBPO_SBCATEGORY'
env_keys = ['ENABLED', 'HOST', 'PORT', 'APIKEY', 'USERNAME', 'PASSWORD', 'SSL', 'WEB_ROOT', 'WATCH_DIR', 'FORK',
'DELETE_FAILED', 'TORRENT_NOLINK', 'NZBEXTRACTIONBY', 'REMOTE_PATH', 'PROCESS_METHOD']
cfg_keys = ['enabled', 'host', 'port', 'apikey', 'username', 'password', 'ssl', 'web_root', 'watch_dir', 'fork',
'delete_failed', 'Torrent_NoLink', 'nzbExtractionBy', 'remote_path', 'process_method']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_SB{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
if os.environ[env_cat_key] in cfg_new['NzbDrone'].sections:
cfg_new['NzbDrone'][env_cat_key]['enabled'] = 0
section = 'HeadPhones'
env_cat_key = 'NZBPO_HPCATEGORY'
env_keys = ['ENABLED', 'APIKEY', 'HOST', 'PORT', 'SSL', 'WEB_ROOT', 'WAIT_FOR', 'WATCH_DIR', 'REMOTE_PATH', 'DELETE_FAILED']
cfg_keys = ['enabled', 'apikey', 'host', 'port', 'ssl', 'web_root', 'wait_for', 'watch_dir', 'remote_path', 'delete_failed']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_HP{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
if os.environ[env_cat_key] in cfg_new['Lidarr'].sections:
cfg_new['Lidarr'][env_cat_key]['enabled'] = 0
section = 'Mylar'
env_cat_key = 'NZBPO_MYCATEGORY'
env_keys = ['ENABLED', 'HOST', 'PORT', 'USERNAME', 'PASSWORD', 'APIKEY', 'SSL', 'WEB_ROOT', 'WATCH_DIR',
'REMOTE_PATH']
cfg_keys = ['enabled', 'host', 'port', 'username', 'password', 'apikey', 'ssl', 'web_root', 'watch_dir',
'remote_path']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_MY{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
section = 'Gamez'
env_cat_key = 'NZBPO_GZCATEGORY'
env_keys = ['ENABLED', 'APIKEY', 'HOST', 'PORT', 'SSL', 'WEB_ROOT', 'WATCH_DIR', 'LIBRARY', 'REMOTE_PATH']
cfg_keys = ['enabled', 'apikey', 'host', 'port', 'ssl', 'web_root', 'watch_dir', 'library', 'remote_path']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_GZ{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
section = 'LazyLibrarian'
env_cat_key = 'NZBPO_LLCATEGORY'
env_keys = ['ENABLED', 'APIKEY', 'HOST', 'PORT', 'SSL', 'WEB_ROOT', 'WATCH_DIR', 'REMOTE_PATH']
cfg_keys = ['enabled', 'apikey', 'host', 'port', 'ssl', 'web_root', 'watch_dir', 'remote_path']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_LL{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
section = 'NzbDrone'
env_cat_key = 'NZBPO_NDCATEGORY'
env_keys = ['ENABLED', 'HOST', 'APIKEY', 'PORT', 'SSL', 'WEB_ROOT', 'WATCH_DIR', 'FORK', 'DELETE_FAILED',
'TORRENT_NOLINK', 'NZBEXTRACTIONBY', 'WAIT_FOR', 'DELETE_FAILED', 'REMOTE_PATH', 'IMPORTMODE']
# new cfgKey added for importMode
cfg_keys = ['enabled', 'host', 'apikey', 'port', 'ssl', 'web_root', 'watch_dir', 'fork', 'delete_failed',
'Torrent_NoLink', 'nzbExtractionBy', 'wait_for', 'delete_failed', 'remote_path', 'importMode']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_ND{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
if os.environ[env_cat_key] in cfg_new['SickBeard'].sections:
cfg_new['SickBeard'][env_cat_key]['enabled'] = 0
section = 'Radarr'
env_cat_key = 'NZBPO_RACATEGORY'
env_keys = ['ENABLED', 'HOST', 'APIKEY', 'PORT', 'SSL', 'WEB_ROOT', 'WATCH_DIR', 'FORK', 'DELETE_FAILED',
'TORRENT_NOLINK', 'NZBEXTRACTIONBY', 'WAIT_FOR', 'DELETE_FAILED', 'REMOTE_PATH', 'OMDBAPIKEY', 'IMPORTMODE']
# new cfgKey added for importMode
cfg_keys = ['enabled', 'host', 'apikey', 'port', 'ssl', 'web_root', 'watch_dir', 'fork', 'delete_failed',
'Torrent_NoLink', 'nzbExtractionBy', 'wait_for', 'delete_failed', 'remote_path', 'omdbapikey', 'importMode']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_RA{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
if os.environ[env_cat_key] in cfg_new['CouchPotato'].sections:
cfg_new['CouchPotato'][env_cat_key]['enabled'] = 0
if os.environ[env_cat_key] in cfg_new['Wacther3'].sections:
cfg_new['Watcher3'][env_cat_key]['enabled'] = 0
section = 'Lidarr'
env_cat_key = 'NZBPO_LICATEGORY'
env_keys = ['ENABLED', 'HOST', 'APIKEY', 'PORT', 'SSL', 'WEB_ROOT', 'WATCH_DIR', 'FORK', 'DELETE_FAILED',
'TORRENT_NOLINK', 'NZBEXTRACTIONBY', 'WAIT_FOR', 'DELETE_FAILED', 'REMOTE_PATH']
cfg_keys = ['enabled', 'host', 'apikey', 'port', 'ssl', 'web_root', 'watch_dir', 'fork', 'delete_failed',
'Torrent_NoLink', 'nzbExtractionBy', 'wait_for', 'delete_failed', 'remote_path']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_LI{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
if os.environ[env_cat_key] in cfg_new['HeadPhones'].sections:
cfg_new['HeadPhones'][env_cat_key]['enabled'] = 0
section = 'Extensions'
env_keys = ['COMPRESSEDEXTENSIONS', 'MEDIAEXTENSIONS', 'METAEXTENSIONS']
cfg_keys = ['compressedExtensions', 'mediaExtensions', 'metaExtensions']
for index in range(len(env_keys)):
key = 'NZBPO_{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
cfg_new[section][option] = value
section = 'Posix'
env_keys = ['NICENESS', 'IONICE_CLASS', 'IONICE_CLASSDATA']
cfg_keys = ['niceness', 'ionice_class', 'ionice_classdata']
for index in range(len(env_keys)):
key = 'NZBPO_{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
cfg_new[section][option] = value
section = 'Transcoder'
env_keys = ['TRANSCODE', 'DUPLICATE', 'IGNOREEXTENSIONS', 'OUTPUTFASTSTART', 'OUTPUTVIDEOPATH',
'PROCESSOUTPUT', 'AUDIOLANGUAGE', 'ALLAUDIOLANGUAGES', 'SUBLANGUAGES',
'ALLSUBLANGUAGES', 'EMBEDSUBS', 'BURNINSUBTITLE', 'EXTRACTSUBS', 'EXTERNALSUBDIR',
'OUTPUTDEFAULT', 'OUTPUTVIDEOEXTENSION', 'OUTPUTVIDEOCODEC', 'VIDEOCODECALLOW',
'OUTPUTVIDEOPRESET', 'OUTPUTVIDEOFRAMERATE', 'OUTPUTVIDEOBITRATE', 'OUTPUTAUDIOCODEC',
'AUDIOCODECALLOW', 'OUTPUTAUDIOBITRATE', 'OUTPUTQUALITYPERCENT', 'GETSUBS',
'OUTPUTAUDIOTRACK2CODEC', 'AUDIOCODEC2ALLOW', 'OUTPUTAUDIOTRACK2BITRATE',
'OUTPUTAUDIOOTHERCODEC', 'AUDIOOTHERCODECALLOW', 'OUTPUTAUDIOOTHERBITRATE',
'OUTPUTSUBTITLECODEC', 'OUTPUTAUDIOCHANNELS', 'OUTPUTAUDIOTRACK2CHANNELS',
'OUTPUTAUDIOOTHERCHANNELS', 'OUTPUTVIDEORESOLUTION']
cfg_keys = ['transcode', 'duplicate', 'ignoreExtensions', 'outputFastStart', 'outputVideoPath',
'processOutput', 'audioLanguage', 'allAudioLanguages', 'subLanguages',
'allSubLanguages', 'embedSubs', 'burnInSubtitle', 'extractSubs', 'externalSubDir',
'outputDefault', 'outputVideoExtension', 'outputVideoCodec', 'VideoCodecAllow',
'outputVideoPreset', 'outputVideoFramerate', 'outputVideoBitrate', 'outputAudioCodec',
'AudioCodecAllow', 'outputAudioBitrate', 'outputQualityPercent', 'getSubs',
'outputAudioTrack2Codec', 'AudioCodec2Allow', 'outputAudioTrack2Bitrate',
'outputAudioOtherCodec', 'AudioOtherCodecAllow', 'outputAudioOtherBitrate',
'outputSubtitleCodec', 'outputAudioChannels', 'outputAudioTrack2Channels',
'outputAudioOtherChannels', 'outputVideoResolution']
for index in range(len(env_keys)):
key = 'NZBPO_{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
cfg_new[section][option] = value
section = 'WakeOnLan'
env_keys = ['WAKE', 'HOST', 'PORT', 'MAC']
cfg_keys = ['wake', 'host', 'port', 'mac']
for index in range(len(env_keys)):
key = 'NZBPO_WOL{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
cfg_new[section][option] = value
section = 'UserScript'
env_cat_key = 'NZBPO_USCATEGORY'
env_keys = ['USER_SCRIPT_MEDIAEXTENSIONS', 'USER_SCRIPT_PATH', 'USER_SCRIPT_PARAM', 'USER_SCRIPT_RUNONCE',
'USER_SCRIPT_SUCCESSCODES', 'USER_SCRIPT_CLEAN', 'USDELAY', 'USREMOTE_PATH']
cfg_keys = ['user_script_mediaExtensions', 'user_script_path', 'user_script_param', 'user_script_runOnce',
'user_script_successCodes', 'user_script_clean', 'delay', 'remote_path']
if env_cat_key in os.environ:
for index in range(len(env_keys)):
key = 'NZBPO_{index}'.format(index=env_keys[index])
if key in os.environ:
option = cfg_keys[index]
value = os.environ[key]
if os.environ[env_cat_key] not in cfg_new[section].sections:
cfg_new[section][os.environ[env_cat_key]] = {}
cfg_new[section][os.environ[env_cat_key]][option] = value
cfg_new[section][os.environ[env_cat_key]]['enabled'] = 1
except Exception as error:
logger.debug('Error {msg} when applying NZBGet config'.format(msg=error))
try:
# write our new config to autoProcessMedia.cfg
cfg_new.filename = core.CONFIG_FILE
cfg_new.write()
except Exception as error:
logger.debug('Error {msg} when writing changes to .cfg'.format(msg=error))
return cfg_new
configobj.Section = Section
configobj.ConfigObj = ConfigObj
config = ConfigObj
|
gpl-3.0
|
kidaa/bttext
|
menu.py
|
2
|
1342
|
import curses
import textout
from textout import btText
import init
import sys
menuTitle = "/\\\\ Menue //\\"
MENU_W = 55
def btExit():
init.quit()
sys.exit()
def btContinue():
pass
menuList = [[str(btText("Continue")), btContinue],
[str(btText("Quit")), btExit]]
def drawMenu(menuWin, choice):
menuWin.erase()
menuWin.box()
h, w = menuWin.getmaxyx()
textout.textOut(menuTitle, (w - len(menuTitle)) / 2, 0, dst = menuWin)
for i in range(len(menuList)):
if choice == i:
textout.textOut(">", 2, i + 2, dst = menuWin)
textout.textOut(str(btText(menuList[i][0])), 4, i + 2, dst = menuWin)
def start():
dsth, dstw = init.stdscr.getmaxyx()
choice = 0
x = (dstw - MENU_W) / 2
y = (dsth - len(menuList)) / 2
w = MENU_W
h = len(menuList) + 4
menuWin = curses.newwin(h, w, y, x)
drawMenu(menuWin, choice)
menuWin.refresh()
while 1:
c = menuWin.getch()
if c == ord("j"):
choice = choice + 1
elif c == ord("k"):
choice = choice - 1
elif (c == ord("l")) | (c == ord(" ")):
if menuList[choice][1] == btContinue:
break
else:
menuList[choice][1]()
choice = choice % len(menuList)
drawMenu(menuWin, choice)
|
gpl-3.0
|
mancoast/CPythonPyc_test
|
cpython/220_test_rfc822.py
|
3
|
7109
|
import rfc822
import sys
import test_support
import unittest
try:
from cStringIO import StringIO
except ImportError:
from StringIO import StringIO
class MessageTestCase(unittest.TestCase):
def create_message(self, msg):
return rfc822.Message(StringIO(msg))
def test_get(self):
msg = self.create_message(
'To: "last, first" <[email protected]>\n\ntest\n')
self.assert_(msg.get("to") == '"last, first" <[email protected]>')
self.assert_(msg.get("TO") == '"last, first" <[email protected]>')
self.assert_(msg.get("No-Such-Header") == "")
self.assert_(msg.get("No-Such-Header", "No-Such-Value")
== "No-Such-Value")
def test_setdefault(self):
msg = self.create_message(
'To: "last, first" <[email protected]>\n\ntest\n')
self.assert_(not msg.has_key("New-Header"))
self.assert_(msg.setdefault("New-Header", "New-Value") == "New-Value")
self.assert_(msg.setdefault("New-Header", "Different-Value")
== "New-Value")
self.assert_(msg["new-header"] == "New-Value")
self.assert_(msg.setdefault("Another-Header") == "")
self.assert_(msg["another-header"] == "")
def check(self, msg, results):
"""Check addresses and the date."""
m = self.create_message(msg)
i = 0
for n, a in m.getaddrlist('to') + m.getaddrlist('cc'):
try:
mn, ma = results[i][0], results[i][1]
except IndexError:
print 'extra parsed address:', repr(n), repr(a)
continue
i = i + 1
if mn == n and ma == a:
pass
else:
print 'not found:', repr(n), repr(a)
out = m.getdate('date')
if out:
self.assertEqual(out,
(1999, 1, 13, 23, 57, 35, 0, 0, 0),
"date conversion failed")
# Note: all test cases must have the same date (in various formats),
# or no date!
def test_basic(self):
self.check(
'Date: Wed, 13 Jan 1999 23:57:35 -0500\n'
'From: Guido van Rossum <[email protected]>\n'
'To: "Guido van\n'
'\t : Rossum" <[email protected]>\n'
'Subject: test2\n'
'\n'
'test2\n',
[('Guido van\n\t : Rossum', '[email protected]')])
self.check(
'From: Barry <[email protected]\n'
'To: [email protected] (Guido: the Barbarian)\n'
'Subject: nonsense\n'
'Date: Wednesday, January 13 1999 23:57:35 -0500\n'
'\n'
'test',
[('Guido: the Barbarian', '[email protected]')])
self.check(
'From: Barry <[email protected]\n'
'To: [email protected] (Guido: the Barbarian)\n'
'Cc: "Guido: the Madman" <[email protected]>\n'
'Date: 13-Jan-1999 23:57:35 EST\n'
'\n'
'test',
[('Guido: the Barbarian', '[email protected]'),
('Guido: the Madman', '[email protected]')
])
self.check(
'To: "The monster with\n'
' the very long name: Guido" <[email protected]>\n'
'Date: Wed, 13 Jan 1999 23:57:35 -0500\n'
'\n'
'test',
[('The monster with\n the very long name: Guido',
'[email protected]')])
self.check(
'To: "Amit J. Patel" <[email protected]>\n'
'CC: Mike Fletcher <[email protected]>,\n'
' "\'[email protected]\'" <[email protected]>\n'
'Cc: [email protected], [email protected]\n'
'Cc: [email protected]\n'
'Date: Wed, 13 Jan 1999 23:57:35 -0500\n'
'\n'
'test',
[('Amit J. Patel', '[email protected]'),
('Mike Fletcher', '[email protected]'),
("'[email protected]'", '[email protected]'),
('', '[email protected]'),
('', '[email protected]'),
('', '[email protected]'),
])
self.check(
'To: Some One <[email protected]>\n'
'From: Anudder Persin <[email protected]>\n'
'Date:\n'
'\n'
'test',
[('Some One', '[email protected]')])
self.check(
'To: [email protected] (User J. Person)\n\n',
[('User J. Person', '[email protected]')])
def test_twisted(self):
# This one is just twisted. I don't know what the proper
# result should be, but it shouldn't be to infloop, which is
# what used to happen!
self.check(
'To: <[smtp:[email protected]][email protected]>\n'
'Date: Wed, 13 Jan 1999 23:57:35 -0500\n'
'\n'
'test',
[('', ''),
('', '[email protected]'),
('', '[email protected]'),
])
def test_commas_in_full_name(self):
# This exercises the old commas-in-a-full-name bug, which
# should be doing the right thing in recent versions of the
# module.
self.check(
'To: "last, first" <[email protected]>\n'
'\n'
'test',
[('last, first', '[email protected]')])
def test_quoted_name(self):
self.check(
'To: (Comment stuff) "Quoted name"@somewhere.com\n'
'\n'
'test',
[('Comment stuff', '"Quoted name"@somewhere.com')])
def test_bogus_to_header(self):
self.check(
'To: :\n'
'Cc: [email protected]\n'
'Date: Wed, 13 Jan 1999 23:57:35 -0500\n'
'\n'
'test',
[('', '[email protected]')])
def test_addr_ipquad(self):
self.check(
'To: guido@[132.151.1.21]\n'
'\n'
'foo',
[('', 'guido@[132.151.1.21]')])
def test_rfc2822_phrases(self):
# RFC 2822 (the update to RFC 822) specifies that dots in phrases are
# obsolete syntax, which conforming programs MUST recognize but NEVER
# generate (see $4.1 Miscellaneous obsolete tokens). This is a
# departure from RFC 822 which did not allow dots in non-quoted
# phrases.
self.check('To: User J. Person <[email protected]>\n\n',
[('User J. Person', '[email protected]')])
# This takes to long to add to the test suite
## def test_an_excrutiatingly_long_address_field(self):
## OBSCENELY_LONG_HEADER_MULTIPLIER = 10000
## oneaddr = ('Person' * 10) + '@' + ('.'.join(['dom']*10)) + '.com'
## addr = ', '.join([oneaddr] * OBSCENELY_LONG_HEADER_MULTIPLIER)
## lst = rfc822.AddrlistClass(addr).getaddrlist()
## self.assertEqual(len(lst), OBSCENELY_LONG_HEADER_MULTIPLIER)
def test_main():
test_support.run_unittest(MessageTestCase)
if __name__ == "__main__":
test_main()
|
gpl-3.0
|
kyleabeauchamp/fah-projects
|
code/setup_siegetank.py
|
1
|
1472
|
import base64
import os
import gzip
import siegetank
system_name = "src"
# Need a more secure way to store and load this.
my_token = os.environ["SIEGETANK_TOKEN"]
siegetank.login(my_token)
RUNS_PATH = "/home/kyleb/src/choderalab/FAHNVT/%s/RUNS_NPT/RUN0/" % system_name
opts = {'description': '%s NPT v2.0 In this project we are running simulations of the important cancer-related protein, src kinase, which will help to provide insight into how we might eventually develop more effective therapies for the various types of cancer.' % system_name,
'steps_per_frame': 125000}
target = siegetank.add_target(options=opts, engines=['openmm_601_opencl', 'openmm_601_cpu'])
system_filename = os.path.join(RUNS_PATH, "system.xml")
system_gz = gzip.compress(open(system_filename, 'rb').read())
encoded_system = base64.b64encode(system_gz).decode()
integrator_filename = os.path.join(RUNS_PATH, "integrator.xml")
integrator_gz = gzip.compress(open(integrator_filename, 'rb').read())
encoded_intg = base64.b64encode(integrator_gz).decode()
for i in range(500):
print(i)
state_filename = os.path.join(RUNS_PATH, "state%d.xml" % i)
state_gz = gzip.compress(open(state_filename, 'rb').read())
encoded_state = base64.b64encode(state_gz).decode()
data = {
'system.xml.gz.b64': encoded_system,
'state.xml.gz.b64': encoded_state,
'integrator.xml.gz.b64': encoded_intg
}
stream = target.add_stream(files=data, scv='vspg11')
|
gpl-2.0
|
zhoulingjun/django
|
tests/migrations/test_multidb.py
|
366
|
6909
|
import unittest
from django.db import connection, migrations, models
from django.db.migrations.state import ProjectState
from django.test import override_settings
from .test_operations import OperationTestBase
try:
import sqlparse
except ImportError:
sqlparse = None
class AgnosticRouter(object):
"""
A router that doesn't have an opinion regarding migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return None
class MigrateNothingRouter(object):
"""
A router that doesn't allow migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return False
class MigrateEverythingRouter(object):
"""
A router that always allows migrating.
"""
def allow_migrate(self, db, app_label, **hints):
return True
class MigrateWhenFooRouter(object):
"""
A router that allows migrating depending on a hint.
"""
def allow_migrate(self, db, app_label, **hints):
return hints.get('foo', False)
class MultiDBOperationTests(OperationTestBase):
multi_db = True
def _test_create_model(self, app_label, should_run):
"""
Tests that CreateModel honours multi-db settings.
"""
operation = migrations.CreateModel(
"Pony",
[("id", models.AutoField(primary_key=True))],
)
# Test the state alteration
project_state = ProjectState()
new_state = project_state.clone()
operation.state_forwards(app_label, new_state)
# Test the database alteration
self.assertTableNotExists("%s_pony" % app_label)
with connection.schema_editor() as editor:
operation.database_forwards(app_label, editor, project_state, new_state)
if should_run:
self.assertTableExists("%s_pony" % app_label)
else:
self.assertTableNotExists("%s_pony" % app_label)
# And test reversal
with connection.schema_editor() as editor:
operation.database_backwards(app_label, editor, new_state, project_state)
self.assertTableNotExists("%s_pony" % app_label)
@override_settings(DATABASE_ROUTERS=[AgnosticRouter()])
def test_create_model(self):
"""
Test when router doesn't have an opinion (i.e. CreateModel should run).
"""
self._test_create_model("test_mltdb_crmo", should_run=True)
@override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()])
def test_create_model2(self):
"""
Test when router returns False (i.e. CreateModel shouldn't run).
"""
self._test_create_model("test_mltdb_crmo2", should_run=False)
@override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()])
def test_create_model3(self):
"""
Test when router returns True (i.e. CreateModel should run).
"""
self._test_create_model("test_mltdb_crmo3", should_run=True)
def test_create_model4(self):
"""
Test multiple routers.
"""
with override_settings(DATABASE_ROUTERS=[AgnosticRouter(), AgnosticRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
with override_settings(DATABASE_ROUTERS=[MigrateNothingRouter(), MigrateEverythingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=False)
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter(), MigrateNothingRouter()]):
self._test_create_model("test_mltdb_crmo4", should_run=True)
def _test_run_sql(self, app_label, should_run, hints=None):
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]):
project_state = self.set_up_test_model(app_label)
sql = """
INSERT INTO {0}_pony (pink, weight) VALUES (1, 3.55);
INSERT INTO {0}_pony (pink, weight) VALUES (3, 5.0);
""".format(app_label)
operation = migrations.RunSQL(sql, hints=hints or {})
# Test the state alteration does nothing
new_state = project_state.clone()
operation.state_forwards(app_label, new_state)
self.assertEqual(new_state, project_state)
# Test the database alteration
self.assertEqual(project_state.apps.get_model(app_label, "Pony").objects.count(), 0)
with connection.schema_editor() as editor:
operation.database_forwards(app_label, editor, project_state, new_state)
Pony = project_state.apps.get_model(app_label, "Pony")
if should_run:
self.assertEqual(Pony.objects.count(), 2)
else:
self.assertEqual(Pony.objects.count(), 0)
@unittest.skipIf(sqlparse is None and connection.features.requires_sqlparse_for_splitting, "Missing sqlparse")
@override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()])
def test_run_sql(self):
self._test_run_sql("test_mltdb_runsql", should_run=False)
@unittest.skipIf(sqlparse is None and connection.features.requires_sqlparse_for_splitting, "Missing sqlparse")
@override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()])
def test_run_sql2(self):
self._test_run_sql("test_mltdb_runsql2", should_run=False)
self._test_run_sql("test_mltdb_runsql2", should_run=True, hints={'foo': True})
def _test_run_python(self, app_label, should_run, hints=None):
with override_settings(DATABASE_ROUTERS=[MigrateEverythingRouter()]):
project_state = self.set_up_test_model(app_label)
# Create the operation
def inner_method(models, schema_editor):
Pony = models.get_model(app_label, "Pony")
Pony.objects.create(pink=1, weight=3.55)
Pony.objects.create(weight=5)
operation = migrations.RunPython(inner_method, hints=hints or {})
# Test the state alteration does nothing
new_state = project_state.clone()
operation.state_forwards(app_label, new_state)
self.assertEqual(new_state, project_state)
# Test the database alteration
self.assertEqual(project_state.apps.get_model(app_label, "Pony").objects.count(), 0)
with connection.schema_editor() as editor:
operation.database_forwards(app_label, editor, project_state, new_state)
Pony = project_state.apps.get_model(app_label, "Pony")
if should_run:
self.assertEqual(Pony.objects.count(), 2)
else:
self.assertEqual(Pony.objects.count(), 0)
@override_settings(DATABASE_ROUTERS=[MigrateNothingRouter()])
def test_run_python(self):
self._test_run_python("test_mltdb_runpython", should_run=False)
@override_settings(DATABASE_ROUTERS=[MigrateWhenFooRouter()])
def test_run_python2(self):
self._test_run_python("test_mltdb_runpython2", should_run=False)
self._test_run_python("test_mltdb_runpython2", should_run=True, hints={'foo': True})
|
bsd-3-clause
|
CEG-FYP-OpenStack/scheduler
|
nova/tests/unit/objects/test_virt_cpu_topology.py
|
94
|
1397
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from nova import objects
from nova.tests.unit.objects import test_objects
_top_dict = {
'sockets': 2,
'cores': 4,
'threads': 8
}
class _TestVirtCPUTopologyObject(object):
def test_object_from_dict(self):
top_obj = objects.VirtCPUTopology.from_dict(_top_dict)
self.compare_obj(top_obj, _top_dict)
def test_object_to_dict(self):
top_obj = objects.VirtCPUTopology()
top_obj.sockets = 2
top_obj.cores = 4
top_obj.threads = 8
spec = top_obj.to_dict()
self.assertEqual(_top_dict, spec)
class TestVirtCPUTopologyObject(test_objects._LocalTest,
_TestVirtCPUTopologyObject):
pass
class TestRemoteVirtCPUTopologyObject(test_objects._RemoteTest,
_TestVirtCPUTopologyObject):
pass
|
apache-2.0
|
adityacs/ansible
|
lib/ansible/modules/network/ios/ios_vrf.py
|
12
|
11615
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {
'status': ['preview'],
'supported_by': 'core',
'version': '1.0'
}
DOCUMENTATION = """
---
module: ios_vrf
version_added: "2.3"
author: "Peter Sprygada (@privateip)"
short_description: Manage the collection of VRF definitions on IOS devices
description:
- This module provides declarative management of VRF definitions on
Cisco IOS devices. It allows playbooks to manage individual or
the entire VRF collection. It also supports purging VRF definitions from
the configuration that are not explicitly defined.
options:
vrfs:
description:
- The set of VRF definition objects to be configured on the remote
IOS device. Ths list entries can either be the VRF name or a hash
of VRF definitions and attributes. This argument is mutually
exclusive with the C(name) argument.
required: false
default: null
name:
description:
- The name of the VRF definition to be managed on the remote IOS
device. The VRF definition name is an ASCII string name used
to uniquely identify the VRF. This argument is mutually exclusive
with the C(vrfs) argument
required: false
default: null
description:
description:
- Provides a short description of the VRF definition in the
current active configuration. The VRF definition value accepts
alphanumberic characters used to provide additional information
about the VRF.
required: false
default: null
rd:
description:
- The router-distigusher value uniquely identifies the VRF to
routing processes on the remote IOS system. The RD value takes
the form of A:B where A and B are both numeric values.
required: false
default: null
interfaces:
description:
- The C(interfaces) argument identifies the set of interfaces that
should be configured in the VRF. Interfaces must be routed
interfaces in order to be placed into a VRF.
required: false
default: null
purge:
description:
- The C(purge) argument instructs the module to consider the
VRF definition absolute. It will remove any previously configured
VRFs on the device.
required: false
default: false
state:
description:
- The C(state) argument configures the state of the VRF definition
as it relates to the device operational configuration. When set
to I(present), the VRF should be configured in the device active
configuration and when set to I(absent) the VRF should not be
in the device active configuration
required: false
default: present
choices: ['present', 'absent']
"""
EXAMPLES = """
- name: configure a vrf named management
ios_vrf:
name: management
description: oob mgmt vrf
interfaces:
- Management1
- name: remove a vrf named test
ios_vrf:
name: test
state: absent
- name: configure set of VRFs and purge any others
ios_vrf:
vrfs:
- red
- blue
- green
purge: yes
"""
RETURN = """
commands:
description: The list of configuration mode commands to send to the device
returned: always
type: list
sample:
- vrf definition ansible
- description management vrf
- rd: 1:100
start:
description: The time the job started
returned: always
type: str
sample: "2016-11-16 10:38:15.126146"
end:
description: The time the job ended
returned: always
type: str
sample: "2016-11-16 10:38:25.595612"
delta:
description: The time elapsed to perform all operations
returned: always
type: str
sample: "0:00:10.469466"
"""
import re
from functools import partial
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.ios import load_config, get_config
from ansible.module_utils.ios import ios_argument_spec, check_args
from ansible.module_utils.netcfg import NetworkConfig
from ansible.module_utils.six import iteritems
def add_command_to_vrf(name, cmd, commands):
if 'vrf definition %s' % name not in commands:
commands.append('vrf definition %s' % name)
commands.append(cmd)
def map_obj_to_commands(updates, module):
commands = list()
state = module.params['state']
for update in updates:
want, have = update
needs_update = lambda x: want.get(x) and (want.get(x) != have.get(x))
if want['state'] == 'absent':
commands.append('no vrf definition %s' % want['name'])
continue
if not have.get('state'):
commands.append('vrf definition %s' % want['name'])
if needs_update('description'):
cmd = 'description %s' % want['description']
add_command_to_vrf(want['name'], cmd, commands)
if needs_update('rd'):
cmd = 'rd %s' % want['rd']
add_command_to_vrf(want['name'], cmd, commands)
if want['interfaces'] is not None:
# handle the deletes
for intf in set(have.get('interfaces', [])).difference(want['interfaces']):
commands.extend(['interface %s' % intf,
'no vrf forwarding %s' % want['name']])
# handle the adds
for intf in set(want['interfaces']).difference(have.get('interfaces', [])):
cfg = get_config(module)
configobj = NetworkConfig(indent=1, contents=cfg)
children = configobj['interface %s' % intf].children
intf_config = '\n'.join(children)
commands.extend(['interface %s' % intf,
'vrf forwarding %s' % want['name']])
match = re.search('ip address .+', intf_config, re.M)
if match:
commands.append(match.group())
return commands
def parse_description(configobj, name):
cfg = configobj['vrf definition %s' % name]
cfg = '\n'.join(cfg.children)
match = re.search(r'description (.+)$', cfg, re.M)
if match:
return match.group(1)
def parse_rd(configobj, name):
cfg = configobj['vrf definition %s' % name]
cfg = '\n'.join(cfg.children)
match = re.search(r'rd (.+)$', cfg, re.M)
if match:
return match.group(1)
def parse_interfaces(configobj, name):
vrf_cfg = 'vrf forwarding %s' % name
interfaces = list()
for intf in re.findall('^interface .+', str(configobj), re.M):
if vrf_cfg in '\n'.join(configobj[intf].children):
interfaces.append(intf.split(' ')[1])
return interfaces
def map_config_to_obj(module):
config = get_config(module)
configobj = NetworkConfig(indent=1, contents=config)
match = re.findall(r'^vrf definition (\S+)', config, re.M)
if not match:
return list()
instances = list()
for item in set(match):
obj = {
'name': item,
'state': 'present',
'description': parse_description(configobj, item),
'rd': parse_rd(configobj, item),
'interfaces': parse_interfaces(configobj, item)
}
instances.append(obj)
return instances
def get_param_value(key, item, module):
# if key doesn't exist in the item, get it from module.params
if not item.get(key):
value = module.params[key]
# if key does exist, do a type check on it to validate it
else:
value_type = module.argument_spec[key].get('type', 'str')
type_checker = module._CHECK_ARGUMENT_TYPES_DISPATCHER[value_type]
type_checker(item[key])
value = item[key]
# validate the param value (if validator func exists)
validator = globals().get('validate_%s' % key)
if validator:
validator(value, module)
return value
def map_params_to_obj(module):
vrfs = module.params.get('vrfs')
if not vrfs:
if not module.params['name'] and module.params['purge']:
return list()
elif not module.params['name']:
module.fail_json(msg='name is required')
collection = [{'name': module.params['name']}]
else:
collection = list()
for item in vrfs:
if not isinstance(item, dict):
collection.append({'name': item})
elif 'name' not in item:
module.fail_json(msg='name is required')
else:
collection.append(item)
objects = list()
for item in collection:
get_value = partial(get_param_value, item=item, module=module)
item['description'] = get_value('description')
item['rd'] = get_value('rd')
item['interfaces'] = get_value('interfaces')
item['state'] = get_value('state')
objects.append(item)
return objects
def update_objects(want, have):
updates = list()
for entry in want:
item = next((i for i in have if i['name'] == entry['name']), None)
if all((item is None, entry['state'] == 'present')):
updates.append((entry, {}))
else:
for key, value in iteritems(entry):
if value:
if isinstance(value, list):
if sorted(value) != sorted(item[key]):
if (entry, item) not in updates:
updates.append((entry, item))
elif value != item[key]:
if (entry, item) not in updates:
updates.append((entry, item))
return updates
def main():
""" main entry point for module execution
"""
argument_spec = dict(
vrfs=dict(type='list'),
name=dict(),
description=dict(),
rd=dict(),
interfaces=dict(type='list'),
purge=dict(type='bool', default=False),
state=dict(default='present', choices=['present', 'absent'])
)
argument_spec.update(ios_argument_spec)
mutually_exclusive = [('name', 'vrfs')]
module = AnsibleModule(argument_spec=argument_spec,
mutually_exclusive=mutually_exclusive,
supports_check_mode=True)
result = {'changed': False}
warnings = list()
check_args(module, warnings)
result['warnings'] = warnings
want = map_params_to_obj(module)
have = map_config_to_obj(module)
commands = map_obj_to_commands(update_objects(want,have), module)
if module.params['purge']:
want_vrfs = [x['name'] for x in want]
have_vrfs = [x['name'] for x in have]
for item in set(have_vrfs).difference(want_vrfs):
cmd = 'no vrf definition %s' % item
if cmd not in commands:
commands.append(cmd)
result['commands'] = commands
if commands:
if not module.check_mode:
load_config(module, commands)
result['changed'] = True
module.exit_json(**result)
if __name__ == '__main__':
main()
|
gpl-3.0
|
gregdek/ansible
|
lib/ansible/modules/network/f5/bigip_dns_zone.py
|
14
|
19409
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
#
# Copyright: (c) 2018, F5 Networks Inc.
# GNU General Public License v3.0 (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'certified'}
DOCUMENTATION = r'''
---
module: bigip_dns_zone
short_description: Manage DNS zones on BIG-IP
description:
- Manage DNS zones on BIG-IP. The zones managed here are primarily used
for configuring DNS Express on BIG-IP. This module does not configure
zones that are found in BIG-IP ZoneRunner.
version_added: 2.8
options:
name:
description:
- Specifies the name of the DNS zone.
- The name must begin with a letter and contain only letters, numbers,
and the underscore character.
required: True
dns_express:
description:
- DNS express related settings.
suboptions:
server:
description:
- Specifies the back-end authoritative DNS server from which the BIG-IP
system receives AXFR zone transfers for the DNS Express zone.
enabled:
description:
- Specifies the current status of the DNS Express zone.
type: bool
notify_action:
description:
- Specifies the action the system takes when a NOTIFY message is received
for this DNS Express zone.
- If a TSIG key is configured for the zone, the signature is only validated
for C(consume) and C(repeat) actions.
- When C(consume), the NOTIFY message is seen only by DNS Express.
- When C(bypass), the NOTIFY message does not go to DNS Express, but
instead goes to a back-end DNS server (subject to the value of the
Unhandled Query Action configured in the DNS profile applied to the
listener that handles the DNS request).
- When C(repeat), the NOTIFY message goes to both DNS Express and any
back-end DNS server.
choices:
- consume
- bypass
- repeat
allow_notify_from:
description:
- Specifies the IP addresses from which the system accepts NOTIFY messages
for this DNS Express zone.
verify_tsig:
description:
- Specifies whether the system verifies the identity of the authoritative
nameserver that sends updated information for this DNS Express zone.
type: bool
response_policy:
description:
- Specifies whether this DNS Express zone is a DNS response policy zone (RPZ).
type: bool
nameservers:
description:
- Specifies the DNS nameservers to which the system sends NOTIFY messages.
tsig_server_key:
description:
- Specifies the TSIG key the system uses to authenticate the back-end DNS
authoritative server that sends AXFR zone transfers to the BIG-IP system.
state:
description:
- When C(present), ensures that the resource exists.
- When C(absent), ensures the resource is removed.
default: present
choices:
- present
- absent
partition:
description:
- Device partition to manage resources on.
default: Common
extends_documentation_fragment: f5
author:
- Tim Rupp (@caphrim007)
'''
EXAMPLES = r'''
- name: Create a DNS zone for DNS express
bigip_dns_zone:
name: foo.bar.com
dns_express:
enabled: yes
server: dns-lab
allow_notify_from:
- 192.168.39.10
notify_action: consume
verify_tsig: no
response_policy: no
provider:
password: secret
server: lb.mydomain.com
user: admin
delegate_to: localhost
'''
RETURN = r'''
enabled:
description: Whether the zone is enabled or not.
returned: changed
type: bool
sample: yes
allow_notify_from:
description: The new DNS Express Allow NOTIFY From value.
returned: changed
type: list
sample: ['1.1.1.1', '2.2.2.2']
notify_action:
description: The new DNS Express Notify Action value.
returned: changed
type: str
sample: consume
verify_tsig:
description: The new DNS Express Verify Notify TSIG value.
returned: changed
type: bool
sample: yes
express_server:
description: The new DNS Express Server value.
returned: changed
type: str
sample: server1
response_policy:
description: The new DNS Express Response Policy value.
returned: changed
type: bool
sample: no
nameservers:
description: The new Zone Transfer Clients Nameservers value.
returned: changed
type: list
sample: ['/Common/server1', '/Common/server2']
tsig_server_key:
description: The new TSIG Server Key value.
returned: changed
type: str
sample: /Common/key1
'''
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.basic import env_fallback
try:
from library.module_utils.network.f5.bigip import F5RestClient
from library.module_utils.network.f5.common import F5ModuleError
from library.module_utils.network.f5.common import AnsibleF5Parameters
from library.module_utils.network.f5.common import cleanup_tokens
from library.module_utils.network.f5.common import fq_name
from library.module_utils.network.f5.common import f5_argument_spec
from library.module_utils.network.f5.common import exit_json
from library.module_utils.network.f5.common import fail_json
from library.module_utils.network.f5.common import transform_name
from library.module_utils.network.f5.common import flatten_boolean
from library.module_utils.network.f5.compare import cmp_simple_list
except ImportError:
from ansible.module_utils.network.f5.bigip import F5RestClient
from ansible.module_utils.network.f5.common import F5ModuleError
from ansible.module_utils.network.f5.common import AnsibleF5Parameters
from ansible.module_utils.network.f5.common import cleanup_tokens
from ansible.module_utils.network.f5.common import fq_name
from ansible.module_utils.network.f5.common import f5_argument_spec
from ansible.module_utils.network.f5.common import exit_json
from ansible.module_utils.network.f5.common import fail_json
from ansible.module_utils.network.f5.common import transform_name
from ansible.module_utils.network.f5.common import flatten_boolean
from ansible.module_utils.network.f5.compare import cmp_simple_list
class Parameters(AnsibleF5Parameters):
api_map = {
'dnsExpressEnabled': 'enabled',
'dnsExpressAllowNotify': 'allow_notify_from',
'dnsExpressNotifyAction': 'notify_action',
'dnsExpressNotifyTsigVerify': 'verify_tsig',
'dnsExpressServer': 'express_server',
'responsePolicy': 'response_policy',
'transferClients': 'nameservers',
'serverTsigKey': 'tsig_server_key',
}
api_attributes = [
'dnsExpressEnabled',
'dnsExpressAllowNotify',
'dnsExpressNotifyAction',
'dnsExpressNotifyTsigVerify',
'dnsExpressServer',
'responsePolicy',
'transferClients',
'serverTsigKey',
]
returnables = [
'enabled',
'allow_notify_from',
'notify_action',
'verify_tsig',
'express_server',
'response_policy',
'nameservers',
'tsig_server_key',
]
updatables = [
'enabled',
'allow_notify_from',
'notify_action',
'verify_tsig',
'express_server',
'response_policy',
'nameservers',
'tsig_server_key',
]
class ApiParameters(Parameters):
pass
class ModuleParameters(Parameters):
@property
def express_server(self):
try:
if self._values['dns_express']['server'] is None:
return None
if self._values['dns_express']['server'] in ['', 'none']:
return ''
return fq_name(self.partition, self._values['dns_express']['server'])
except (TypeError, KeyError):
return None
@property
def nameservers(self):
if self._values['nameservers'] is None:
return None
elif len(self._values['nameservers']) == 1 and self._values['nameservers'][0] in ['', 'none']:
return ''
return [fq_name(self.partition, x) for x in self._values['nameservers']]
@property
def tsig_server_key(self):
if self._values['tsig_server_key'] is None:
return None
if self._values['tsig_server_key'] in ['', 'none']:
return ''
return fq_name(self.partition, self._values['tsig_server_key'])
@property
def enabled(self):
try:
return flatten_boolean(self._values['dns_express']['enabled'])
except (TypeError, KeyError):
return None
@property
def verify_tsig(self):
try:
return flatten_boolean(self._values['dns_express']['verify_tsig'])
except (TypeError, KeyError):
return None
@property
def notify_action(self):
try:
return self._values['dns_express']['notify_action']
except (TypeError, KeyError):
return None
@property
def response_policy(self):
try:
return flatten_boolean(self._values['dns_express']['response_policy'])
except (TypeError, KeyError):
return None
@property
def allow_notify_from(self):
try:
v = self._values['dns_express']['allow_notify_from']
if v is None:
return None
elif len(v) == 1 and v[0] in ['', 'none']:
return ''
return v
except (TypeError, KeyError):
return None
class Changes(Parameters):
def to_return(self):
result = {}
try:
for returnable in self.returnables:
result[returnable] = getattr(self, returnable)
result = self._filter_params(result)
except Exception:
pass
return result
class UsableChanges(Changes):
pass
class ReportableChanges(Changes):
pass
class Difference(object):
def __init__(self, want, have=None):
self.want = want
self.have = have
def compare(self, param):
try:
result = getattr(self, param)
return result
except AttributeError:
return self.__default(param)
@property
def allow_notify_from(self):
return cmp_simple_list(self.want.allow_notify_from, self.have.allow_notify_from)
@property
def nameservers(self):
return cmp_simple_list(self.want.nameservers, self.have.nameservers)
@property
def express_server(self):
if self.want.express_server is None:
return None
if self.want.express_server == '' and self.have.express_server is None:
return None
if self.want.express_server != self.have.express_server:
return self.want.express_server
@property
def tsig_server_key(self):
if self.want.tsig_server_key is None:
return None
if self.want.tsig_server_key == '' and self.have.tsig_server_key is None:
return None
if self.want.tsig_server_key != self.have.tsig_server_key:
return self.want.tsig_server_key
def __default(self, param):
attr1 = getattr(self.want, param)
try:
attr2 = getattr(self.have, param)
if attr1 != attr2:
return attr1
except AttributeError:
return attr1
class ModuleManager(object):
def __init__(self, *args, **kwargs):
self.module = kwargs.get('module', None)
self.client = kwargs.get('client', None)
self.want = ModuleParameters(params=self.module.params)
self.have = ApiParameters()
self.changes = UsableChanges()
def _set_changed_options(self):
changed = {}
for key in Parameters.returnables:
if getattr(self.want, key) is not None:
changed[key] = getattr(self.want, key)
if changed:
self.changes = UsableChanges(params=changed)
def _update_changed_options(self):
diff = Difference(self.want, self.have)
updatables = Parameters.updatables
changed = dict()
for k in updatables:
change = diff.compare(k)
if change is None:
continue
else:
if isinstance(change, dict):
changed.update(change)
else:
changed[k] = change
if changed:
self.changes = UsableChanges(params=changed)
return True
return False
def should_update(self):
result = self._update_changed_options()
if result:
return True
return False
def exec_module(self):
changed = False
result = dict()
state = self.want.state
if state == "present":
changed = self.present()
elif state == "absent":
changed = self.absent()
reportable = ReportableChanges(params=self.changes.to_return())
changes = reportable.to_return()
result.update(**changes)
result.update(dict(changed=changed))
self._announce_deprecations(result)
return result
def _announce_deprecations(self, result):
warnings = result.pop('__warnings', [])
for warning in warnings:
self.client.module.deprecate(
msg=warning['msg'],
version=warning['version']
)
def present(self):
if self.exists():
return self.update()
else:
return self.create()
def exists(self):
uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError:
return False
if resp.status == 404 or 'code' in response and response['code'] == 404:
return False
return True
def update(self):
self.have = self.read_current_from_device()
if not self.should_update():
return False
if self.module.check_mode:
return True
self.update_on_device()
return True
def remove(self):
if self.module.check_mode:
return True
self.remove_from_device()
if self.exists():
raise F5ModuleError("Failed to delete the resource.")
return True
def create(self):
self._set_changed_options()
if self.module.check_mode:
return True
self.create_on_device()
return True
def create_on_device(self):
params = self.changes.api_params()
params['name'] = self.want.name
params['partition'] = self.want.partition
uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/".format(
self.client.provider['server'],
self.client.provider['server_port']
)
resp = self.client.api.post(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] in [400, 403]:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def update_on_device(self):
params = self.changes.api_params()
uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.patch(uri, json=params)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
def absent(self):
if self.exists():
return self.remove()
return False
def remove_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
response = self.client.api.delete(uri)
if response.status == 200:
return True
raise F5ModuleError(response.content)
def read_current_from_device(self):
uri = "https://{0}:{1}/mgmt/tm/ltm/dns/zone/{2}".format(
self.client.provider['server'],
self.client.provider['server_port'],
transform_name(self.want.partition, self.want.name)
)
resp = self.client.api.get(uri)
try:
response = resp.json()
except ValueError as ex:
raise F5ModuleError(str(ex))
if 'code' in response and response['code'] == 400:
if 'message' in response:
raise F5ModuleError(response['message'])
else:
raise F5ModuleError(resp.content)
return ApiParameters(params=response)
class ArgumentSpec(object):
def __init__(self):
self.supports_check_mode = True
argument_spec = dict(
name=dict(required=True),
dns_express=dict(
type='dict',
options=dict(
server=dict(),
enabled=dict(type='bool'),
notify_action=dict(
choices=['consume', 'bypass', 'repeat']
),
allow_notify_from=dict(type='list'),
verify_tsig=dict(type='bool'),
response_policy=dict(type='bool')
)
),
nameservers=dict(type='list'),
tsig_server_key=dict(),
partition=dict(
default='Common',
fallback=(env_fallback, ['F5_PARTITION'])
),
state=dict(
default='present',
choices=['present', 'absent']
)
)
self.argument_spec = {}
self.argument_spec.update(f5_argument_spec)
self.argument_spec.update(argument_spec)
def main():
spec = ArgumentSpec()
module = AnsibleModule(
argument_spec=spec.argument_spec,
supports_check_mode=spec.supports_check_mode,
)
client = F5RestClient(**module.params)
try:
mm = ModuleManager(module=module, client=client)
results = mm.exec_module()
cleanup_tokens(client)
exit_json(module, results, client)
except F5ModuleError as ex:
cleanup_tokens(client)
fail_json(module, ex, client)
if __name__ == '__main__':
main()
|
gpl-3.0
|
dhenrygithub/QGIS
|
python/plugins/processing/algs/qgis/RectanglesOvalsDiamondsFixed.py
|
2
|
8734
|
# -*- coding: utf-8 -*-
"""
***************************************************************************
RectanglesOvalsDiamondsFixed.py
---------------------
Date : April 2016
Copyright : (C) 2016 by Alexander Bruy
Email : alexander dot bruy at gmail dot com
***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************
"""
__author__ = 'Alexander Bruy'
__date__ = 'August 2012'
__copyright__ = '(C) 2012, Victor Olaya'
# This will get replaced with a git SHA1 when you do a git archive323
__revision__ = '$Format:%H$'
import os
import math
from qgis.PyQt.QtGui import QIcon
from qgis.core import QGis, QgsFeature, QgsGeometry, QgsPoint
from processing.core.GeoAlgorithm import GeoAlgorithm
from processing.core.ProcessingLog import ProcessingLog
from processing.core.GeoAlgorithmExecutionException import GeoAlgorithmExecutionException
from processing.core.parameters import ParameterVector
from processing.core.parameters import ParameterSelection
from processing.core.parameters import ParameterNumber
from processing.core.outputs import OutputVector
from processing.tools import dataobjects, vector
class RectanglesOvalsDiamondsFixed(GeoAlgorithm):
INPUT_LAYER = 'INPUT_LAYER'
SHAPE = 'SHAPE'
WIDTH = 'WIDTH'
HEIGHT = 'HEIGHT'
ROTATION = 'ROTATION'
SEGMENTS = 'SEGMENTS'
OUTPUT_LAYER = 'OUTPUT_LAYER'
def defineCharacteristics(self):
self.name, self.i18n_name = self.trAlgorithm('Rectangles, ovals, diamonds (fixed)')
self.group, self.i18n_group = self.trAlgorithm('Vector geometry tools')
self.shapes = [self.tr('Rectangles'), self.tr('Diamonds'), self.tr('Ovals')]
self.addParameter(ParameterVector(self.INPUT_LAYER,
self.tr('Input layer'),
[ParameterVector.VECTOR_TYPE_POINT]))
self.addParameter(ParameterSelection(self.SHAPE,
self.tr('Buffer shape'), self.shapes))
self.addParameter(ParameterNumber(self.WIDTH, self.tr('Width'),
0.0000001, 999999999.0, 1.0))
self.addParameter(ParameterNumber(self.HEIGHT, self.tr('Height'),
0.0000001, 999999999.0, 1.0))
self.addParameter(ParameterNumber(self.ROTATION, self.tr('Rotation'),
0.0, 360.0, optional=True))
self.addParameter(ParameterNumber(self.SEGMENTS,
self.tr('Number of segments'),
1,
999999999,
36))
self.addOutput(OutputVector(self.OUTPUT_LAYER,
self.tr('Output')))
def processAlgorithm(self, progress):
layer = dataobjects.getObjectFromUri(
self.getParameterValue(self.INPUT_LAYER))
shape = self.getParameterValue(self.SHAPE)
width = self.getParameterValue(self.WIDTH)
height = self.getParameterValue(self.HEIGHT)
rotation = self.getParameterValue(self.ROTATION)
segments = self.getParameterValue(self.SEGMENTS)
writer = self.getOutputFromName(
self.OUTPUT_LAYER).getVectorWriter(
layer.pendingFields().toList(),
QGis.WKBPolygon,
layer.crs())
outFeat = QgsFeature()
features = vector.features(layer)
total = 100.0 / len(features)
if shape == 0:
self.rectangles(writer, features, width, height, rotation)
elif shape == 1:
self.diamonds(writer, features, width, height, rotation)
else:
self.ovals(writer, features, width, height, rotation, segments)
del writer
def rectangles(self, writer, features, width, height, rotation):
ft = QgsFeature()
xOffset = width / 2.0
yOffset = height / 2.0
if rotation is not None:
phi = rotation * math.pi / 180
for current, feat in enumerate(features):
point = feat.constGeometry().asPoint()
x = point.x()
y = point.y()
points = [(-xOffset, -yOffset), (-xOffset, yOffset), (xOffset, yOffset), (xOffset, -yOffset)]
polygon = [[QgsPoint(i[0] * math.cos(phi) + i[1] * math.sin(phi) + x,
-i[0] * math.sin(phi) + i[1] * math.cos(phi) + y) for i in points]]
ft.setGeometry(QgsGeometry.fromPolygon(polygon))
ft.setAttributes(feat.attributes())
writer.addFeature(ft)
else:
for current, feat in enumerate(features):
point = feat.constGeometry().asPoint()
x = point.x()
y = point.y()
points = [(-xOffset, -yOffset), (-xOffset, yOffset), (xOffset, yOffset), (xOffset, -yOffset)]
polygon = [[QgsPoint(i[0] + x, i[1] + y) for i in points]]
ft.setGeometry(QgsGeometry.fromPolygon(polygon))
ft.setAttributes(feat.attributes())
writer.addFeature(ft)
def diamonds(self, writer, features, width, height, rotation):
ft = QgsFeature()
xOffset = width / 2.0
yOffset = height / 2.0
if rotation is not None:
phi = rotation * math.pi / 180
for current, feat in enumerate(features):
point = feat.constGeometry().asPoint()
x = point.x()
y = point.y()
points = [(0.0, -yOffset), (-xOffset, 0.0), (0.0, yOffset), (xOffset, 0.0)]
polygon = [[QgsPoint(i[0] * math.cos(phi) + i[1] * math.sin(phi) + x,
-i[0] * math.sin(phi) + i[1] * math.cos(phi) + y) for i in points]]
ft.setGeometry(QgsGeometry.fromPolygon(polygon))
ft.setAttributes(feat.attributes())
writer.addFeature(ft)
else:
for current, feat in enumerate(features):
point = feat.constGeometry().asPoint()
x = point.x()
y = point.y()
points = [(0.0, -yOffset), (-xOffset, 0.0), (0.0, yOffset), (xOffset, 0.0)]
polygon = [[QgsPoint(i[0] + x, i[1] + y) for i in points]]
ft.setGeometry(QgsGeometry.fromPolygon(polygon))
ft.setAttributes(feat.attributes())
writer.addFeature(ft)
def ovals(self, writer, features, width, height, rotation, segments):
ft = QgsFeature()
xOffset = width / 2.0
yOffset = height / 2.0
if rotation is not None:
phi = rotation * math.pi / 180
for current, feat in enumerate(features):
point = feat.constGeometry().asPoint()
x = point.x()
y = point.y()
points = []
for t in [(2 * math.pi) / segments * i for i in xrange(segments)]:
points.append((xOffset * math.cos(t), yOffset * math.sin(t)))
polygon = [[QgsPoint(i[0] * math.cos(phi) + i[1] * math.sin(phi) + x,
-i[0] * math.sin(phi) + i[1] * math.cos(phi) + y) for i in points]]
ft.setGeometry(QgsGeometry.fromPolygon(polygon))
ft.setAttributes(feat.attributes())
writer.addFeature(ft)
else:
for current, feat in enumerate(features):
point = feat.constGeometry().asPoint()
x = point.x()
y = point.y()
points = []
for t in [(2 * math.pi) / segments * i for i in xrange(segments)]:
points.append((xOffset * math.cos(t), yOffset * math.sin(t)))
polygon = [[QgsPoint(i[0] + x, i[1] + y) for i in points]]
ft.setGeometry(QgsGeometry.fromPolygon(polygon))
ft.setAttributes(feat.attributes())
writer.addFeature(ft)
|
gpl-2.0
|
aehernandez/HyperSpace
|
src/python/simple_server.py
|
1
|
4104
|
from asyncio import coroutine
from random import randint
from autobahn.asyncio.wamp import ApplicationSession, ApplicationRunner
from autobahn.wamp.types import PublishOptions
import asyncio
from threading import Thread as Process
# helpfer function to get the current time
import time
millis = lambda: int(round(time.time() * 1000))
app_uri = "com.hyperspace."
canvas_size = (800, 600)
def call_in_bg(target, *, loop=None, executor=None):
"""Schedules and starts target callable as a background task
If not given, *loop* defaults to the current thread's event loop
If not given, *executor* defaults to the loop's default executor
Returns the scheduled task.
"""
if loop is None:
loop = asyncio.get_event_loop()
if callable(target):
return loop.run_in_executor(executor, target)
raise TypeError("target must be a callable, "
"not {!r}".format(type(target)))
class Player():
def __init__(self, position, angle=0, velocity=(0, 0), session_id=None,
player_id=None):
self.position = position
self.angle = angle
self.velocity = velocity
self.last_beat = millis()
self.player_id = player_id
self.session_id = session_id
def __repr__(self):
return "<Player {p.session_id} {{{p.position}, {p.angle}, {p.velocity}}}>".format(p=self)
def update(self, x, y, angle=None, velocity=None):
self.position = (x, y)
if (angle != None):
self.angle = angle
if (velocity != None):
self.velocity = velocity
self.last_beat = millis()
def unwrap(self):
(x, y) = self.position
(vx, vy) = self.velocity
return (self.session_id, x, y, self.angle, vx, vy)
class SimpleServer(ApplicationSession):
@coroutine
def onJoin(self, details):
self.clients = {}
print("Server ready")
def register_client(session_id):
(x, y) = (randint(0, canvas_size[0]), randint(0, canvas_size[1]))
player = Player((x, y), player_id=1, session_id=session_id)
self.clients[session_id] = player
print("Registered Client {}".format(session_id))
return (session_id, x, y)
def deregister_client(session_id):
del self.clients[session_id]
def recv_player_updates(session_id, x, y, angle, vx, vy):
if session_id in self.clients:
self.clients[session_id].update(x, y, angle, (vx, vy))
yield from self.register(register_client, app_uri + "register_client")
yield from self.subscribe(recv_player_updates, app_uri + "player_update")
yield from self.subscribe(deregister_client, app_uri +
"deregister_client")
asyncio.async(self.send_all_player_updates())
asyncio.async(self.check_player_heartbeat())
@coroutine
def send_all_player_updates(self):
while True:
for client in self.clients.values():
unwrapped_players = [player.unwrap() for player in
self.clients.values() if player.session_id !=
client.session_id]
if len(unwrapped_players) > 0:
self.publish(app_uri + "player_positions", unwrapped_players,
options=PublishOptions(eligible=[client.session_id]))
yield from asyncio.sleep(0.01)
@coroutine
def check_player_heartbeat(self):
while True:
now = millis()
for client in self.clients.values():
if now - client.last_beat > 2000:
self.publish(app_uri + "deregister_client",
client.session_id,
options=PublishOptions(exclude_me=False))
print("Player {} has timed out".format(client.session_id))
yield from asyncio.sleep(2)
if __name__ == "__main__":
runner = ApplicationRunner(url="ws://localhost:8081/ws", realm="hyperspace")
runner.run(SimpleServer)
|
gpl-3.0
|
wanglongqi/sympy
|
sympy/polys/polyfuncs.py
|
45
|
7823
|
"""High-level polynomials manipulation functions. """
from __future__ import print_function, division
from sympy.polys.polytools import (
poly_from_expr, parallel_poly_from_expr, Poly)
from sympy.polys.polyoptions import allowed_flags
from sympy.polys.specialpolys import (
symmetric_poly, interpolating_poly)
from sympy.polys.polyerrors import (
PolificationFailed, ComputationFailed,
MultivariatePolynomialError)
from sympy.utilities import numbered_symbols, take, public
from sympy.core import S, Basic, Add, Mul
from sympy.core.compatibility import range
@public
def symmetrize(F, *gens, **args):
"""
Rewrite a polynomial in terms of elementary symmetric polynomials.
A symmetric polynomial is a multivariate polynomial that remains invariant
under any variable permutation, i.e., if ``f = f(x_1, x_2, ..., x_n)``,
then ``f = f(x_{i_1}, x_{i_2}, ..., x_{i_n})``, where
``(i_1, i_2, ..., i_n)`` is a permutation of ``(1, 2, ..., n)`` (an
element of the group ``S_n``).
Returns a tuple of symmetric polynomials ``(f1, f2, ..., fn)`` such that
``f = f1 + f2 + ... + fn``.
Examples
========
>>> from sympy.polys.polyfuncs import symmetrize
>>> from sympy.abc import x, y
>>> symmetrize(x**2 + y**2)
(-2*x*y + (x + y)**2, 0)
>>> symmetrize(x**2 + y**2, formal=True)
(s1**2 - 2*s2, 0, [(s1, x + y), (s2, x*y)])
>>> symmetrize(x**2 - y**2)
(-2*x*y + (x + y)**2, -2*y**2)
>>> symmetrize(x**2 - y**2, formal=True)
(s1**2 - 2*s2, -2*y**2, [(s1, x + y), (s2, x*y)])
"""
allowed_flags(args, ['formal', 'symbols'])
iterable = True
if not hasattr(F, '__iter__'):
iterable = False
F = [F]
try:
F, opt = parallel_poly_from_expr(F, *gens, **args)
except PolificationFailed as exc:
result = []
for expr in exc.exprs:
if expr.is_Number:
result.append((expr, S.Zero))
else:
raise ComputationFailed('symmetrize', len(F), exc)
else:
if not iterable:
result, = result
if not exc.opt.formal:
return result
else:
if iterable:
return result, []
else:
return result + ([],)
polys, symbols = [], opt.symbols
gens, dom = opt.gens, opt.domain
for i in range(0, len(gens)):
poly = symmetric_poly(i + 1, gens, polys=True)
polys.append((next(symbols), poly.set_domain(dom)))
indices = list(range(0, len(gens) - 1))
weights = list(range(len(gens), 0, -1))
result = []
for f in F:
symmetric = []
if not f.is_homogeneous:
symmetric.append(f.TC())
f -= f.TC()
while f:
_height, _monom, _coeff = -1, None, None
for i, (monom, coeff) in enumerate(f.terms()):
if all(monom[i] >= monom[i + 1] for i in indices):
height = max([ n*m for n, m in zip(weights, monom) ])
if height > _height:
_height, _monom, _coeff = height, monom, coeff
if _height != -1:
monom, coeff = _monom, _coeff
else:
break
exponents = []
for m1, m2 in zip(monom, monom[1:] + (0,)):
exponents.append(m1 - m2)
term = [ s**n for (s, _), n in zip(polys, exponents) ]
poly = [ p**n for (_, p), n in zip(polys, exponents) ]
symmetric.append(Mul(coeff, *term))
product = poly[0].mul(coeff)
for p in poly[1:]:
product = product.mul(p)
f -= product
result.append((Add(*symmetric), f.as_expr()))
polys = [ (s, p.as_expr()) for s, p in polys ]
if not opt.formal:
for i, (sym, non_sym) in enumerate(result):
result[i] = (sym.subs(polys), non_sym)
if not iterable:
result, = result
if not opt.formal:
return result
else:
if iterable:
return result, polys
else:
return result + (polys,)
@public
def horner(f, *gens, **args):
"""
Rewrite a polynomial in Horner form.
Among other applications, evaluation of a polynomial at a point is optimal
when it is applied using the Horner scheme ([1]).
Examples
========
>>> from sympy.polys.polyfuncs import horner
>>> from sympy.abc import x, y, a, b, c, d, e
>>> horner(9*x**4 + 8*x**3 + 7*x**2 + 6*x + 5)
x*(x*(x*(9*x + 8) + 7) + 6) + 5
>>> horner(a*x**4 + b*x**3 + c*x**2 + d*x + e)
e + x*(d + x*(c + x*(a*x + b)))
>>> f = 4*x**2*y**2 + 2*x**2*y + 2*x*y**2 + x*y
>>> horner(f, wrt=x)
x*(x*y*(4*y + 2) + y*(2*y + 1))
>>> horner(f, wrt=y)
y*(x*y*(4*x + 2) + x*(2*x + 1))
References
==========
[1] - http://en.wikipedia.org/wiki/Horner_scheme
"""
allowed_flags(args, [])
try:
F, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
return exc.expr
form, gen = S.Zero, F.gen
if F.is_univariate:
for coeff in F.all_coeffs():
form = form*gen + coeff
else:
F, gens = Poly(F, gen), gens[1:]
for coeff in F.all_coeffs():
form = form*gen + horner(coeff, *gens, **args)
return form
@public
def interpolate(data, x):
"""
Construct an interpolating polynomial for the data points.
Examples
========
>>> from sympy.polys.polyfuncs import interpolate
>>> from sympy.abc import x
A list is interpreted as though it were paired with a range starting
from 1:
>>> interpolate([1, 4, 9, 16], x)
x**2
This can be made explicit by giving a list of coordinates:
>>> interpolate([(1, 1), (2, 4), (3, 9)], x)
x**2
The (x, y) coordinates can also be given as keys and values of a
dictionary (and the points need not be equispaced):
>>> interpolate([(-1, 2), (1, 2), (2, 5)], x)
x**2 + 1
>>> interpolate({-1: 2, 1: 2, 2: 5}, x)
x**2 + 1
"""
n = len(data)
if isinstance(data, dict):
X, Y = list(zip(*data.items()))
else:
if isinstance(data[0], tuple):
X, Y = list(zip(*data))
else:
X = list(range(1, n + 1))
Y = list(data)
poly = interpolating_poly(n, x, X, Y)
return poly.expand()
@public
def viete(f, roots=None, *gens, **args):
"""
Generate Viete's formulas for ``f``.
Examples
========
>>> from sympy.polys.polyfuncs import viete
>>> from sympy import symbols
>>> x, a, b, c, r1, r2 = symbols('x,a:c,r1:3')
>>> viete(a*x**2 + b*x + c, [r1, r2], x)
[(r1 + r2, -b/a), (r1*r2, c/a)]
"""
allowed_flags(args, [])
if isinstance(roots, Basic):
gens, roots = (roots,) + gens, None
try:
f, opt = poly_from_expr(f, *gens, **args)
except PolificationFailed as exc:
raise ComputationFailed('viete', 1, exc)
if f.is_multivariate:
raise MultivariatePolynomialError(
"multivariate polynomials are not allowed")
n = f.degree()
if n < 1:
raise ValueError(
"can't derive Viete's formulas for a constant polynomial")
if roots is None:
roots = numbered_symbols('r', start=1)
roots = take(roots, n)
if n != len(roots):
raise ValueError("required %s roots, got %s" % (n, len(roots)))
lc, coeffs = f.LC(), f.all_coeffs()
result, sign = [], -1
for i, coeff in enumerate(coeffs[1:]):
poly = symmetric_poly(i + 1, roots)
coeff = sign*(coeff/lc)
result.append((poly, coeff))
sign = -sign
return result
|
bsd-3-clause
|
nuagenetworks/monolithe
|
monolithe/generators/lang/html/__init__.py
|
2
|
1817
|
# -*- coding: utf-8 -*-
#
# Copyright (c) 2015, Alcatel-Lucent Inc
# 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 the copyright holder nor the names of its contributors
# may be used to endorse or promote products derived from this software without
# specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
__all__ = ['PackageWriter', 'VanillaWriter', 'APIVersionWriter']
from .writers.packagewriter import PackageWriter
from .writers.vanillawriter import VanillaWriter
from .writers.apiversionwriter import APIVersionWriter
|
bsd-3-clause
|
tanmaykm/edx-platform
|
common/djangoapps/heartbeat/views.py
|
199
|
1440
|
from xmodule.modulestore.django import modulestore
from dogapi import dog_stats_api
from util.json_request import JsonResponse
from django.db import connection
from django.db.utils import DatabaseError
from xmodule.exceptions import HeartbeatFailure
@dog_stats_api.timed('edxapp.heartbeat')
def heartbeat(request):
"""
Simple view that a loadbalancer can check to verify that the app is up. Returns a json doc
of service id: status or message. If the status for any service is anything other than True,
it returns HTTP code 503 (Service Unavailable); otherwise, it returns 200.
"""
# This refactoring merely delegates to the default modulestore (which if it's mixed modulestore will
# delegate to all configured modulestores) and a quick test of sql. A later refactoring may allow
# any service to register itself as participating in the heartbeat. It's important that all implementation
# do as little as possible but give a sound determination that they are ready.
try:
output = modulestore().heartbeat()
except HeartbeatFailure as fail:
return JsonResponse({fail.service: unicode(fail)}, status=503)
cursor = connection.cursor()
try:
cursor.execute("SELECT CURRENT_DATE")
cursor.fetchone()
output['SQL'] = True
except DatabaseError as fail:
return JsonResponse({'SQL': unicode(fail)}, status=503)
return JsonResponse(output)
|
agpl-3.0
|
abhattad4/Digi-Menu
|
tests/generic_views/test_edit.py
|
7
|
19270
|
from __future__ import unicode_literals
import warnings
from django import forms
from django.core.exceptions import ImproperlyConfigured
from django.core.urlresolvers import reverse
from django.test import TestCase, ignore_warnings, override_settings
from django.test.client import RequestFactory
from django.utils.deprecation import RemovedInDjango20Warning
from django.views.generic.base import View
from django.views.generic.edit import CreateView, FormMixin, ModelFormMixin
from . import views
from .models import Artist, Author
from .test_forms import AuthorForm
class FormMixinTests(TestCase):
def test_initial_data(self):
""" Test instance independence of initial data dict (see #16138) """
initial_1 = FormMixin().get_initial()
initial_1['foo'] = 'bar'
initial_2 = FormMixin().get_initial()
self.assertNotEqual(initial_1, initial_2)
def test_get_prefix(self):
""" Test prefix can be set (see #18872) """
test_string = 'test'
rf = RequestFactory()
get_request = rf.get('/')
class TestFormMixin(FormMixin):
request = get_request
default_kwargs = TestFormMixin().get_form_kwargs()
self.assertIsNone(default_kwargs.get('prefix'))
set_mixin = TestFormMixin()
set_mixin.prefix = test_string
set_kwargs = set_mixin.get_form_kwargs()
self.assertEqual(test_string, set_kwargs.get('prefix'))
def test_get_form(self):
class TestFormMixin(FormMixin):
request = RequestFactory().get('/')
self.assertIsInstance(
TestFormMixin().get_form(forms.Form), forms.Form,
'get_form() should use provided form class.'
)
class FormClassTestFormMixin(TestFormMixin):
form_class = forms.Form
self.assertIsInstance(
FormClassTestFormMixin().get_form(), forms.Form,
'get_form() should fallback to get_form_class() if none is provided.'
)
def test_get_form_missing_form_class_default_value(self):
with warnings.catch_warnings(record=True) as w:
warnings.filterwarnings('always')
class MissingDefaultValue(FormMixin):
request = RequestFactory().get('/')
form_class = forms.Form
def get_form(self, form_class):
return form_class(**self.get_form_kwargs())
self.assertEqual(len(w), 1)
self.assertEqual(w[0].category, RemovedInDjango20Warning)
self.assertEqual(
str(w[0].message),
'`generic_views.test_edit.MissingDefaultValue.get_form` method '
'must define a default value for its `form_class` argument.'
)
self.assertIsInstance(
MissingDefaultValue().get_form(), forms.Form,
)
@override_settings(ROOT_URLCONF='generic_views.urls')
class BasicFormTests(TestCase):
def test_post_data(self):
res = self.client.post('/contact/', {'name': "Me", 'message': "Hello"})
self.assertRedirects(res, 'http://testserver/list/authors/')
class ModelFormMixinTests(TestCase):
def test_get_form(self):
form_class = views.AuthorGetQuerySetFormView().get_form_class()
self.assertEqual(form_class._meta.model, Author)
def test_get_form_checks_for_object(self):
mixin = ModelFormMixin()
mixin.request = RequestFactory().get('/')
self.assertEqual({'initial': {}, 'prefix': None},
mixin.get_form_kwargs())
@override_settings(ROOT_URLCONF='generic_views.urls')
class CreateViewTests(TestCase):
def test_create(self):
res = self.client.get('/edit/authors/create/')
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertIsInstance(res.context['view'], View)
self.assertNotIn('object', res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/author_form.html')
res = self.client.post('/edit/authors/create/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
def test_create_invalid(self):
res = self.client.post('/edit/authors/create/',
{'name': 'A' * 101, 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_form.html')
self.assertEqual(len(res.context['form'].errors), 1)
self.assertEqual(Author.objects.count(), 0)
def test_create_with_object_url(self):
res = self.client.post('/edit/artists/create/',
{'name': 'Rene Magritte'})
self.assertEqual(res.status_code, 302)
artist = Artist.objects.get(name='Rene Magritte')
self.assertRedirects(res, 'http://testserver/detail/artist/%d/' % artist.pk)
self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
def test_create_with_redirect(self):
res = self.client.post('/edit/authors/create/redirect/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/edit/authors/create/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
@ignore_warnings(category=RemovedInDjango20Warning)
def test_create_with_interpolated_redirect(self):
res = self.client.post(
'/edit/authors/create/interpolate_redirect/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'}
)
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
self.assertEqual(res.status_code, 302)
pk = Author.objects.first().pk
self.assertRedirects(res, 'http://testserver/edit/author/%d/update/' % pk)
# Also test with escaped chars in URL
res = self.client.post(
'/edit/authors/create/interpolate_redirect_nonascii/',
{'name': 'John Doe', 'slug': 'john-doe'}
)
self.assertEqual(res.status_code, 302)
pk = Author.objects.get(name='John Doe').pk
self.assertRedirects(res, 'http://testserver/%C3%A9dit/author/{}/update/'.format(pk))
def test_create_with_special_properties(self):
res = self.client.get('/edit/authors/create/special/')
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], views.AuthorForm)
self.assertNotIn('object', res.context)
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/authors/create/special/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
obj = Author.objects.get(slug='randall-munroe')
self.assertRedirects(res, reverse('author_detail', kwargs={'pk': obj.pk}))
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
def test_create_without_redirect(self):
try:
self.client.post('/edit/authors/create/naive/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.fail('Should raise exception -- No redirect URL provided, and no get_absolute_url provided')
except ImproperlyConfigured:
pass
def test_create_restricted(self):
res = self.client.post('/edit/authors/create/restricted/',
{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/accounts/login/?next=/edit/authors/create/restricted/')
def test_create_view_with_restricted_fields(self):
class MyCreateView(CreateView):
model = Author
fields = ['name']
self.assertEqual(list(MyCreateView().get_form_class().base_fields),
['name'])
def test_create_view_all_fields(self):
class MyCreateView(CreateView):
model = Author
fields = '__all__'
self.assertEqual(list(MyCreateView().get_form_class().base_fields),
['name', 'slug'])
def test_create_view_without_explicit_fields(self):
class MyCreateView(CreateView):
model = Author
message = (
"Using ModelFormMixin (base class of MyCreateView) without the "
"'fields' attribute is prohibited."
)
with self.assertRaisesMessage(ImproperlyConfigured, message):
MyCreateView().get_form_class()
def test_define_both_fields_and_form_class(self):
class MyCreateView(CreateView):
model = Author
form_class = AuthorForm
fields = ['name']
message = "Specifying both 'fields' and 'form_class' is not permitted."
with self.assertRaisesMessage(ImproperlyConfigured, message):
MyCreateView().get_form_class()
@override_settings(ROOT_URLCONF='generic_views.urls')
class UpdateViewTests(TestCase):
def test_update_post(self):
a = Author.objects.create(
name='Randall Munroe',
slug='randall-munroe',
)
res = self.client.get('/edit/author/%d/update/' % a.pk)
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
self.assertTemplateUsed(res, 'generic_views/author_form.html')
# Modification with both POST and PUT (browser compatible)
res = self.client.post('/edit/author/%d/update/' % a.pk,
{'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])
def test_update_invalid(self):
a = Author.objects.create(
name='Randall Munroe',
slug='randall-munroe',
)
res = self.client.post('/edit/author/%d/update/' % a.pk,
{'name': 'A' * 101, 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 200)
self.assertTemplateUsed(res, 'generic_views/author_form.html')
self.assertEqual(len(res.context['form'].errors), 1)
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe>'])
def test_update_with_object_url(self):
a = Artist.objects.create(name='Rene Magritte')
res = self.client.post('/edit/artists/%d/update/' % a.pk,
{'name': 'Rene Magritte'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/detail/artist/%d/' % a.pk)
self.assertQuerysetEqual(Artist.objects.all(), ['<Artist: Rene Magritte>'])
def test_update_with_redirect(self):
a = Author.objects.create(
name='Randall Munroe',
slug='randall-munroe',
)
res = self.client.post('/edit/author/%d/update/redirect/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/edit/authors/create/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
@ignore_warnings(category=RemovedInDjango20Warning)
def test_update_with_interpolated_redirect(self):
a = Author.objects.create(
name='Randall Munroe',
slug='randall-munroe',
)
res = self.client.post(
'/edit/author/%d/update/interpolate_redirect/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'}
)
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
self.assertEqual(res.status_code, 302)
pk = Author.objects.first().pk
self.assertRedirects(res, 'http://testserver/edit/author/%d/update/' % pk)
# Also test with escaped chars in URL
res = self.client.post(
'/edit/author/%d/update/interpolate_redirect_nonascii/' % a.pk,
{'name': 'John Doe', 'slug': 'john-doe'}
)
self.assertEqual(res.status_code, 302)
pk = Author.objects.get(name='John Doe').pk
self.assertRedirects(res, 'http://testserver/%C3%A9dit/author/{}/update/'.format(pk))
def test_update_with_special_properties(self):
a = Author.objects.create(
name='Randall Munroe',
slug='randall-munroe',
)
res = self.client.get('/edit/author/%d/update/special/' % a.pk)
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], views.AuthorForm)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/form.html')
res = self.client.post('/edit/author/%d/update/special/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/detail/author/%d/' % a.pk)
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (author of xkcd)>'])
def test_update_without_redirect(self):
a = Author.objects.create(
name='Randall Munroe',
slug='randall-munroe',
)
# Should raise exception -- No redirect URL provided, and no
# get_absolute_url provided
with self.assertRaises(ImproperlyConfigured):
self.client.post('/edit/author/%d/update/naive/' % a.pk,
{'name': 'Randall Munroe (author of xkcd)', 'slug': 'randall-munroe'})
def test_update_get_object(self):
a = Author.objects.create(
pk=1,
name='Randall Munroe',
slug='randall-munroe',
)
res = self.client.get('/edit/author/update/')
self.assertEqual(res.status_code, 200)
self.assertIsInstance(res.context['form'], forms.ModelForm)
self.assertIsInstance(res.context['view'], View)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
self.assertTemplateUsed(res, 'generic_views/author_form.html')
# Modification with both POST and PUT (browser compatible)
res = self.client.post('/edit/author/update/',
{'name': 'Randall Munroe (xkcd)', 'slug': 'randall-munroe'})
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), ['<Author: Randall Munroe (xkcd)>'])
@override_settings(ROOT_URLCONF='generic_views.urls')
class DeleteViewTests(TestCase):
def test_delete_by_post(self):
a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
res = self.client.get('/edit/author/%d/delete/' % a.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['author'], Author.objects.get(pk=a.pk))
self.assertTemplateUsed(res, 'generic_views/author_confirm_delete.html')
# Deletion with POST
res = self.client.post('/edit/author/%d/delete/' % a.pk)
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), [])
def test_delete_by_delete(self):
# Deletion with browser compatible DELETE method
a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
res = self.client.delete('/edit/author/%d/delete/' % a.pk)
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), [])
def test_delete_with_redirect(self):
a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
res = self.client.post('/edit/author/%d/delete/redirect/' % a.pk)
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/edit/authors/create/')
self.assertQuerysetEqual(Author.objects.all(), [])
@ignore_warnings(category=RemovedInDjango20Warning)
def test_delete_with_interpolated_redirect(self):
a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
res = self.client.post('/edit/author/%d/delete/interpolate_redirect/' % a.pk)
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/edit/authors/create/?deleted=%d' % a.pk)
self.assertQuerysetEqual(Author.objects.all(), [])
# Also test with escaped chars in URL
a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
res = self.client.post('/edit/author/{}/delete/interpolate_redirect_nonascii/'.format(a.pk))
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/%C3%A9dit/authors/create/?deleted={}'.format(a.pk))
def test_delete_with_special_properties(self):
a = Author.objects.create(**{'name': 'Randall Munroe', 'slug': 'randall-munroe'})
res = self.client.get('/edit/author/%d/delete/special/' % a.pk)
self.assertEqual(res.status_code, 200)
self.assertEqual(res.context['object'], Author.objects.get(pk=a.pk))
self.assertEqual(res.context['thingy'], Author.objects.get(pk=a.pk))
self.assertNotIn('author', res.context)
self.assertTemplateUsed(res, 'generic_views/confirm_delete.html')
res = self.client.post('/edit/author/%d/delete/special/' % a.pk)
self.assertEqual(res.status_code, 302)
self.assertRedirects(res, 'http://testserver/list/authors/')
self.assertQuerysetEqual(Author.objects.all(), [])
def test_delete_without_redirect(self):
a = Author.objects.create(
name='Randall Munroe',
slug='randall-munroe',
)
# Should raise exception -- No redirect URL provided, and no
# get_absolute_url provided
with self.assertRaises(ImproperlyConfigured):
self.client.post('/edit/author/%d/delete/naive/' % a.pk)
|
bsd-3-clause
|
ceb8/astroquery
|
astroquery/eso/tests/test_eso.py
|
2
|
3190
|
# Licensed under a 3-clause BSD style license - see LICENSE.rst
import os
from ...utils.testing_tools import MockResponse
from ...eso import Eso
DATA_DIR = os.path.join(os.path.dirname(__file__), 'data')
def data_path(filename):
return os.path.join(DATA_DIR, filename)
DATA_FILES = {'GET': {'http://archive.eso.org/wdb/wdb/eso/eso_archive_main/form':
'main_query_form.html',
'http://archive.eso.org/wdb/wdb/eso/amber/form':
'amber_query_form.html',
'http://archive.eso.org/wdb/wdb/adp/phase3_main/form':
'vvv_sgra_form.html',
},
'POST': {'http://archive.eso.org/wdb/wdb/eso/eso_archive_main/query':
'main_sgra_query.tbl',
'http://archive.eso.org/wdb/wdb/eso/amber/query':
'amber_sgra_query.tbl',
'http://archive.eso.org/wdb/wdb/adp/phase3_main/query':
'vvv_sgra_survey_response.tbl',
}
}
def eso_request(request_type, url, **kwargs):
with open(data_path(DATA_FILES[request_type][url]), 'rb') as f:
response = MockResponse(content=f.read(), url=url)
return response
# @pytest.fixture
# def patch_get(request):
# try:
# mp = request.getfixturevalue("monkeypatch")
# except AttributeError: # pytest < 3
# mp = request.getfuncargvalue("monkeypatch")
# mp.setattr(Eso, 'request', eso_request)
# return mp
# This test should attempt to access the internet and therefore should fail
# (_activate_form always connects to the internet)
# @pytest.mark.xfail
def test_amber_SgrAstar(monkeypatch):
# Local caching prevents a remote query here
eso = Eso()
# monkeypatch instructions from https://pytest.org/latest/monkeypatch.html
monkeypatch.setattr(eso, '_request', eso_request)
# set up local cache path to prevent remote query
eso.cache_location = DATA_DIR
# the failure should occur here
result = eso.query_instrument('amber', target='Sgr A*')
# test that max_results = 50
assert len(result) == 50
assert 'GC_IRS7' in result['Object']
def test_main_SgrAstar(monkeypatch):
# Local caching prevents a remote query here
eso = Eso()
# monkeypatch instructions from https://pytest.org/latest/monkeypatch.html
monkeypatch.setattr(eso, '_request', eso_request)
# set up local cache path to prevent remote query
eso.cache_location = DATA_DIR
# the failure should occur here
result = eso.query_main(target='Sgr A*')
# test that max_results = 50
assert len(result) == 50
assert 'GC_IRS7' in result['OBJECT']
def test_vvv(monkeypatch):
eso = Eso()
monkeypatch.setattr(eso, '_request', eso_request)
eso.cache_location = DATA_DIR
result_s = eso.query_surveys('VVV',
coord1=266.41681662, coord2=-29.00782497,
box='01 00 00',
)
assert result_s is not None
assert 'Object' in result_s.colnames
assert 'b333' in result_s['Object']
|
bsd-3-clause
|
heesub/linux
|
tools/perf/scripts/python/Perf-Trace-Util/lib/Perf/Trace/SchedGui.py
|
12980
|
5411
|
# SchedGui.py - Python extension for perf script, basic GUI code for
# traces drawing and overview.
#
# Copyright (C) 2010 by Frederic Weisbecker <[email protected]>
#
# This software is distributed under the terms of the GNU General
# Public License ("GPL") version 2 as published by the Free Software
# Foundation.
try:
import wx
except ImportError:
raise ImportError, "You need to install the wxpython lib for this script"
class RootFrame(wx.Frame):
Y_OFFSET = 100
RECT_HEIGHT = 100
RECT_SPACE = 50
EVENT_MARKING_WIDTH = 5
def __init__(self, sched_tracer, title, parent = None, id = -1):
wx.Frame.__init__(self, parent, id, title)
(self.screen_width, self.screen_height) = wx.GetDisplaySize()
self.screen_width -= 10
self.screen_height -= 10
self.zoom = 0.5
self.scroll_scale = 20
self.sched_tracer = sched_tracer
self.sched_tracer.set_root_win(self)
(self.ts_start, self.ts_end) = sched_tracer.interval()
self.update_width_virtual()
self.nr_rects = sched_tracer.nr_rectangles() + 1
self.height_virtual = RootFrame.Y_OFFSET + (self.nr_rects * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
# whole window panel
self.panel = wx.Panel(self, size=(self.screen_width, self.screen_height))
# scrollable container
self.scroll = wx.ScrolledWindow(self.panel)
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale)
self.scroll.EnableScrolling(True, True)
self.scroll.SetFocus()
# scrollable drawing area
self.scroll_panel = wx.Panel(self.scroll, size=(self.screen_width - 15, self.screen_height / 2))
self.scroll_panel.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll_panel.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll_panel.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Bind(wx.EVT_PAINT, self.on_paint)
self.scroll.Bind(wx.EVT_KEY_DOWN, self.on_key_press)
self.scroll.Bind(wx.EVT_LEFT_DOWN, self.on_mouse_down)
self.scroll.Fit()
self.Fit()
self.scroll_panel.SetDimensions(-1, -1, self.width_virtual, self.height_virtual, wx.SIZE_USE_EXISTING)
self.txt = None
self.Show(True)
def us_to_px(self, val):
return val / (10 ** 3) * self.zoom
def px_to_us(self, val):
return (val / self.zoom) * (10 ** 3)
def scroll_start(self):
(x, y) = self.scroll.GetViewStart()
return (x * self.scroll_scale, y * self.scroll_scale)
def scroll_start_us(self):
(x, y) = self.scroll_start()
return self.px_to_us(x)
def paint_rectangle_zone(self, nr, color, top_color, start, end):
offset_px = self.us_to_px(start - self.ts_start)
width_px = self.us_to_px(end - self.ts_start)
offset_py = RootFrame.Y_OFFSET + (nr * (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE))
width_py = RootFrame.RECT_HEIGHT
dc = self.dc
if top_color is not None:
(r, g, b) = top_color
top_color = wx.Colour(r, g, b)
brush = wx.Brush(top_color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, RootFrame.EVENT_MARKING_WIDTH)
width_py -= RootFrame.EVENT_MARKING_WIDTH
offset_py += RootFrame.EVENT_MARKING_WIDTH
(r ,g, b) = color
color = wx.Colour(r, g, b)
brush = wx.Brush(color, wx.SOLID)
dc.SetBrush(brush)
dc.DrawRectangle(offset_px, offset_py, width_px, width_py)
def update_rectangles(self, dc, start, end):
start += self.ts_start
end += self.ts_start
self.sched_tracer.fill_zone(start, end)
def on_paint(self, event):
dc = wx.PaintDC(self.scroll_panel)
self.dc = dc
width = min(self.width_virtual, self.screen_width)
(x, y) = self.scroll_start()
start = self.px_to_us(x)
end = self.px_to_us(x + width)
self.update_rectangles(dc, start, end)
def rect_from_ypixel(self, y):
y -= RootFrame.Y_OFFSET
rect = y / (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
height = y % (RootFrame.RECT_HEIGHT + RootFrame.RECT_SPACE)
if rect < 0 or rect > self.nr_rects - 1 or height > RootFrame.RECT_HEIGHT:
return -1
return rect
def update_summary(self, txt):
if self.txt:
self.txt.Destroy()
self.txt = wx.StaticText(self.panel, -1, txt, (0, (self.screen_height / 2) + 50))
def on_mouse_down(self, event):
(x, y) = event.GetPositionTuple()
rect = self.rect_from_ypixel(y)
if rect == -1:
return
t = self.px_to_us(x) + self.ts_start
self.sched_tracer.mouse_down(rect, t)
def update_width_virtual(self):
self.width_virtual = self.us_to_px(self.ts_end - self.ts_start)
def __zoom(self, x):
self.update_width_virtual()
(xpos, ypos) = self.scroll.GetViewStart()
xpos = self.us_to_px(x) / self.scroll_scale
self.scroll.SetScrollbars(self.scroll_scale, self.scroll_scale, self.width_virtual / self.scroll_scale, self.height_virtual / self.scroll_scale, xpos, ypos)
self.Refresh()
def zoom_in(self):
x = self.scroll_start_us()
self.zoom *= 2
self.__zoom(x)
def zoom_out(self):
x = self.scroll_start_us()
self.zoom /= 2
self.__zoom(x)
def on_key_press(self, event):
key = event.GetRawKeyCode()
if key == ord("+"):
self.zoom_in()
return
if key == ord("-"):
self.zoom_out()
return
key = event.GetKeyCode()
(x, y) = self.scroll.GetViewStart()
if key == wx.WXK_RIGHT:
self.scroll.Scroll(x + 1, y)
elif key == wx.WXK_LEFT:
self.scroll.Scroll(x - 1, y)
elif key == wx.WXK_DOWN:
self.scroll.Scroll(x, y + 1)
elif key == wx.WXK_UP:
self.scroll.Scroll(x, y - 1)
|
gpl-2.0
|
Jgarcia-IAS/SAT
|
openerp/addons/account_budget/wizard/account_budget_crossovered_report.py
|
375
|
2089
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
import time
from openerp.osv import fields, osv
class account_budget_crossvered_report(osv.osv_memory):
_name = "account.budget.crossvered.report"
_description = "Account Budget crossvered report"
_columns = {
'date_from': fields.date('Start of period', required=True),
'date_to': fields.date('End of period', required=True),
}
_defaults = {
'date_from': lambda *a: time.strftime('%Y-01-01'),
'date_to': lambda *a: time.strftime('%Y-%m-%d'),
}
def check_report(self, cr, uid, ids, context=None):
if context is None:
context = {}
data = self.read(cr, uid, ids, context=context)[0]
datas = {
'ids': context.get('active_ids', []),
'model': 'crossovered.budget',
'form': data
}
datas['form']['ids'] = datas['ids']
datas['form']['report'] = 'analytic-full'
return self.pool['report'].get_action(cr, uid, [], 'account_budget.report_crossoveredbudget', data=datas, context=context)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
douban/dpark
|
dpark/tracker.py
|
1
|
3549
|
from __future__ import absolute_import
import socket
import zmq
import time
from dpark.utils import spawn
from dpark.utils.log import get_logger
logger = get_logger(__name__)
class TrackerMessage(object):
pass
class StopTrackerMessage(TrackerMessage):
pass
class SetValueMessage(TrackerMessage):
def __init__(self, key, value):
self.key = key
self.value = value
class AddItemMessage(TrackerMessage):
def __init__(self, key, item):
self.key = key
self.item = item
class RemoveItemMessage(TrackerMessage):
def __init__(self, key, item):
self.key = key
self.item = item
class GetValueMessage(TrackerMessage):
def __init__(self, key):
self.key = key
class TrackerServer(object):
locs = {}
def __init__(self):
self.addr = None
self.thread = None
self.ctx = None
def start(self):
if self.ctx is None:
self.ctx = zmq.Context()
self.thread = spawn(self.run)
while self.addr is None:
time.sleep(0.01)
def stop(self):
sock = self.ctx.socket(zmq.REQ)
sock.connect(self.addr)
sock.send_pyobj(StopTrackerMessage())
confirm_msg = sock.recv_pyobj()
sock.close()
self.thread.join()
if self.ctx is not None:
self.ctx.destroy()
self.ctx = None
return confirm_msg
def get(self, key):
return self.locs.get(key, [])
def set(self, key, value):
if not isinstance(value, list):
value = [value]
self.locs[key] = value
def add(self, key, item):
if key not in self.locs:
self.locs[key] = []
self.locs[key].append(item)
def remove(self, key, item):
if item in self.locs[key]:
self.locs[key].remove(item)
def run(self):
sock = self.ctx.socket(zmq.REP)
port = sock.bind_to_random_port("tcp://0.0.0.0")
self.addr = "tcp://%s:%d" % (socket.gethostname(), port)
logger.debug("TrackerServer started at %s", self.addr)
def reply(msg_):
sock.send_pyobj(msg_)
while True:
msg = sock.recv_pyobj()
if isinstance(msg, SetValueMessage):
self.set(msg.key, msg.value)
reply('OK')
elif isinstance(msg, AddItemMessage):
self.add(msg.key, msg.item)
reply('OK')
elif isinstance(msg, RemoveItemMessage):
self.remove(msg.key, msg.item)
reply('OK')
elif isinstance(msg, GetValueMessage):
reply(self.get(msg.key))
elif isinstance(msg, StopTrackerMessage):
reply('OK')
break
else:
logger.error("unexpected msg %s %s", msg, type(msg))
reply('ERROR')
sock.close()
logger.debug("stop TrackerServer %s", self.addr)
class TrackerClient(object):
def __init__(self, addr):
self.addr = addr
self.ctx = None
def call(self, msg):
if self.ctx is None:
self.ctx = zmq.Context()
sock = None
try:
sock = self.ctx.socket(zmq.REQ)
sock.connect(self.addr)
sock.send_pyobj(msg)
return sock.recv_pyobj()
finally:
if sock:
sock.close()
def stop(self):
if self.ctx is not None:
self.ctx.destroy()
self.ctx = None
|
bsd-3-clause
|
jazztpt/edx-platform
|
common/djangoapps/cors_csrf/views.py
|
100
|
2533
|
"""Views for enabling cross-domain requests. """
import logging
import json
from django.conf import settings
from django.views.decorators.cache import cache_page
from django.http import HttpResponseNotFound
from edxmako.shortcuts import render_to_response
from cors_csrf.models import XDomainProxyConfiguration
log = logging.getLogger(__name__)
XDOMAIN_PROXY_CACHE_TIMEOUT = getattr(settings, 'XDOMAIN_PROXY_CACHE_TIMEOUT', 60 * 15)
@cache_page(XDOMAIN_PROXY_CACHE_TIMEOUT)
def xdomain_proxy(request): # pylint: disable=unused-argument
"""Serve the xdomain proxy page.
Internet Explorer 9 does not send cookie information with CORS,
which means we can't make cross-domain POST requests that
require authentication (for example, from the course details
page on the marketing site to the enrollment API
to auto-enroll a user in an "honor" track).
The XDomain library [https://github.com/jpillora/xdomain]
provides an alternative to using CORS.
The library works as follows:
1) A static HTML file ("xdomain_proxy.html") is served from courses.edx.org.
The file includes JavaScript and a domain whitelist.
2) The course details page (on edx.org) creates an invisible iframe
that loads the proxy HTML file.
3) A JS shim library on the course details page intercepts
AJAX requests and communicates with JavaScript on the iframed page.
The iframed page then proxies the request to the LMS.
Since the iframed page is served from courses.edx.org,
this is a same-domain request, so all cookies for the domain
are sent along with the request.
You can enable this feature and configure the domain whitelist
using Django admin.
"""
config = XDomainProxyConfiguration.current()
if not config.enabled:
return HttpResponseNotFound()
allowed_domains = []
for domain in config.whitelist.split("\n"): # pylint: disable=no-member
if domain.strip():
allowed_domains.append(domain.strip())
if not allowed_domains:
log.warning(
u"No whitelist configured for cross-domain proxy. "
u"You can configure the whitelist in Django Admin "
u"using the XDomainProxyConfiguration model."
)
return HttpResponseNotFound()
context = {
'xdomain_masters': json.dumps({
domain: '*'
for domain in allowed_domains
})
}
return render_to_response('cors_csrf/xdomain_proxy.html', context)
|
agpl-3.0
|
hzlf/openbroadcast.org
|
website/tools/crispy_forms_extra/layout.py
|
2
|
3726
|
import itertools
from django.conf import settings
from django.utils.html import conditional_escape
from crispy_forms.layout import LayoutObject, Div
from crispy_forms.utils import render_field
TEMPLATE_PACK = getattr(settings, "CRISPY_TEMPLATE_PACK", "bootstrap")
class Row(Div):
"""
Layout object. It wraps fields in a div whose default class is "formRow". Example::
Row('form_field_1', 'form_field_2', 'form_field_3')
"""
css_class = "form-row"
class Column(Div):
"""
Layout object. It wraps fields in a div whose default class is "formColumn". Example::
Column('form_field_1', 'form_field_2')
"""
css_class = "form-column"
class LookupField(LayoutObject):
"""
Layout object, It contains one field name, and you can add attributes to it easily.
For setting class attributes, you need to use `css_class`, as `class` is a Python keyword.
Example::
Field('field_name', style="color: #333;", css_class="whatever", id="field_name")
"""
template = "%s/lookup_field.html" % TEMPLATE_PACK
def __init__(self, *args, **kwargs):
self.fields = list(args)
if not hasattr(self, "attrs"):
self.attrs = {}
if kwargs.has_key("css_class"):
if "class" in self.attrs:
self.attrs["class"] += " %s" % kwargs.pop("css_class")
else:
self.attrs["class"] = kwargs.pop("css_class")
self.template = kwargs.pop("template", self.template)
# We use kwargs as HTML attributes, turning data_id='test' into data-id='test'
self.attrs.update(
dict(
[
(k.replace("_", "-"), conditional_escape(v))
for k, v in kwargs.items()
]
)
)
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
html = ""
for field in self.fields:
html += render_field(
field,
form,
form_style,
context,
template=self.template,
attrs=self.attrs,
)
return html
class LookupImageField(LayoutObject):
"""
Layout object, It contains one field name, and you can add attributes to it easily.
For setting class attributes, you need to use `css_class`, as `class` is a Python keyword.
Example::
Field('field_name', style="color: #333;", css_class="whatever", id="field_name")
"""
template = "%s/lookup_image_field.html" % TEMPLATE_PACK
def __init__(self, *args, **kwargs):
self.fields = list(args)
if not hasattr(self, "attrs"):
self.attrs = {}
if kwargs.has_key("css_class"):
if "class" in self.attrs:
self.attrs["class"] += " %s" % kwargs.pop("css_class")
else:
self.attrs["class"] = kwargs.pop("css_class")
self.template = kwargs.pop("template", self.template)
# We use kwargs as HTML attributes, turning data_id='test' into data-id='test'
self.attrs.update(
dict(
[
(k.replace("_", "-"), conditional_escape(v))
for k, v in kwargs.items()
]
)
)
def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs):
html = ""
for field in self.fields:
html += render_field(
field,
form,
form_style,
context,
template=self.template,
attrs=self.attrs,
)
return html
|
gpl-3.0
|
ulikoehler/Translatron
|
Translatron/DocumentImport/PMC.py
|
1
|
8545
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from ctypes import c_bool
import tarfile
import functools
import time
from bs4 import BeautifulSoup, Comment, NavigableString
from Translatron import DocumentDB
from ansicolor import black, red
from multiprocessing import Process, Queue
__author__ = "Uli Köhler"
__copyright__ = "Copyright 2015 Uli Köhler"
__license__ = "Apache License v2.0"
__version__ = "0.1"
__maintainer__ = "Uli Köhler"
__email__ = "[email protected]"
__status__ = "Development"
class DocumentUnparseableException(Exception):
pass
def extractTitle(front):
"Extract the PMC article title from a document"
try:
return front.find("article-meta").find("title-group").find("article-title").text
except:
raise DocumentUnparseableException("Can't extract title from document")
def extractArticleID(front, idType="doi"):
"Extract any article ID (e.g. DOI or PMC) from a document"
try:
return front.find("article-meta").find("article-id", {"pub-id-type": idType}).text
except: #Some articles have no DOI, e.g. PMC3671658
return None
def extractNLMTAJournal(front):
"Extract the PMC NLM-TA journal ID from a document"
try:
return front.find("journal-meta").find("journal-id", {"journal-id-type":"nlm-ta"}).text
except:
raise DocumentUnparseableException("Can't extract NLM-TA journal identified from document")
def extractPublicationDate(front):
"Extract the PMC publication date from a document. Print publication date is preferred over epub date"
articleMeta = front.find("article-meta")
try:
#Try ppub first
ppub = articleMeta.find("pub-date", {"pub-type": "ppub"})
#https://xkcd.com/1179/
return ppub.find("year").text + "-" + ppub.find("month").text
except:
#printed publication date fail -> fallback to epub date
try:
epub = articleMeta.find("pub-date", {"pub-type": "epub"})
return epub.find("year").text + "-" + epub.find("month").text
except: return "Unknown"
def extractAuthors(front):
"Extract the PMC NLM-TA journal ID from a document"
authors = []
contribGroup = front.find("article-meta").find("contrib-group")
if contribGroup is None: return []
for contrib in contribGroup.find_all("contrib", {"contrib-type": "author"}):
name = contrib.find("name")
if name is None: #Probably a collaboration
try: authors.append(contrib.collab.text)
except: raise DocumentUnparseableException("Collab unavailable: " + contrib)
else: #A natural person
try:
authors.append(name.find("given-names").text + " " + name.surname.text)
except: raise DocumentUnparseableException("Name illegal: " + contrib)
return authors
def processPMCFileContent(xml):
"Process a string representing a PMC XML file"
soup = BeautifulSoup(xml, "lxml")
try:
return processPMCDoc(soup)
except Exception as e:
print(red("Parser exception while processsing PMC:%s" % extractArticleID(soup, "pmc")))
print(e)
return None
class PMCProcessorWorker(Process):
"""
PMC processor with a dedicated YakDB connection that
is used to spread load of processing onto multiple cores
"""
def __init__(self, queue):
super(PMCProcessorWorker, self).__init__()
self.queue = queue
#Accumulates documents that will be written. Reduces number of PUT requests
self.writeQueue = []
def run(self):
db = DocumentDB.YakDBDocumentDatabase(mode="PUSH")
for data in iter( self.queue.get, None ):
#Convert XML string to document object
doc = processPMCFileContent(data)
if doc is None: continue #Parse error
self.writeQueue.append(doc)
#Write if write queue size has been reached
if len(self.writeQueue) >= 128:
db.writeDocuments(self.writeQueue)
self.writeQueue.clear()
#Flush remaining
if self.writeQueue:
db.writeDocuments(self.writeQueue)
class PMCTARParser(object):
def __init__(self, numWorkers=8):
"Initialize a new multithreaded PMC TAR parser"
#Worker queue
self.queue = Queue(maxsize=1024)
#Start worker processes
self.numWorkers = numWorkers
def iteratePMCTarGZ(self, infile, filterStr=""):
"Iterate XML files inside a PMC .tar.gz that pass the given prefix filter"
with tarfile.open(infile, 'r|gz') as tarIn:
for entry in tarIn:
if not entry.isfile():
if entry.name.startswith(filterStr):
print("Processing %s ..." % entry.name)
else:
print("Skipping %s ..." % entry.name)
continue
#Apply prefix fiter
if not entry.name.startswith(filterStr): continue
#Open entry as file-like object
fin = tarIn.extractfile(entry)
yield fin
def processPMCTarGZ(self, infile, filterStr="", contentFilterStr=None):
"Process a .tar.gz containing PMC XMLs, e.g. articles.A-B.tar.gz"
startTime = time.time()
docCount = 0
#Start worker processes
for i in range(self.numWorkers):
PMCProcessorWorker(self.queue).start()
#Process tar files
for filelike in self.iteratePMCTarGZ(infile, filterStr):
if filelike is not None:
#TARs are sequential streams, so we need to .read() NOW,
# even if a thread pool (as opposed to a process pool)
# would be used
content = filelike.read()
# Apply content filter (if any)
if contentFilterStr:
if contentFilterStr not in content.lower():
continue
# Process asynchronously
self.queue.put(content)
docCount += 1
#Terminate worker processes (asynchronously)
for i in range(self.numWorkers):
self.queue.put(None)
#Stats
endTime = time.time()
print("Imported %d documents in %.1f seconds" % (docCount, endTime - startTime))
def processPMCXML(self, infile):
"Process a single PMC XML file. Does not use separate worker processes."
#Read file content
with open(infile) as fin:
xml = fin.read()
#Convert to document object
doc = processPMCFileContent(xml)
#Safe in database
self.db.writeDocument(doc)
def processPMCDoc(soup):
"Process a soup of a PMC article"
article = soup.article
front = article.front
abstract = front.find("article-meta").abstract
pmcId = extractArticleID(front, "pmc")
doc = {
"id": "pmc:" + pmcId,
"pmid": extractArticleID(front, "pmid"),
"pmcid": "PMC" + pmcId,
"authors": extractAuthors(front),
"title": extractTitle(front),
"doi": extractArticleID(front, "doi"),
"journal": extractNLMTAJournal(front),
"pubdate": extractPublicationDate(front),
"source": "PMC",
}
#Collect a list of all (non-metadata) paragraphs
#TODO also collect tables, captions etc
paragraphTags = []
for tag in article.children:
#Skip comments and NavigableStrings
if isinstance(tag, Comment) or isinstance(tag, NavigableString):
continue
#Skip meta info
if tag.name == "front" or tag.name == "back":
continue
[paragraphTags.append(p) for p in tag.find_all("p")]
#Append all raw paragraphs (not section headers from the paragraphs)
[paragraphTags.append(p) for p in abstract.find_all("p")]
#Convert paragraphs to text
doc["paragraphs"] = [p.get_text(separator=u" ") for p in paragraphTags]
return doc
def runPMCImporterCLITool(args):
#Open tables with REQ/REP connection
DocumentDB.YakDBDocumentDatabase(mode="REQ")
#Worker threads will have individual DB connections
parser = PMCTARParser(numWorkers=args.workers)
for infile in args.infile:
if infile.endswith(".tar.gz"):
parser.processPMCTarGZ(infile, filterStr=args.filter, contentFilterStr=args.content_filter.lower().encode("utf-8"))
elif infile.endswith(".nxml") or infile.endswith(".xml"):
parser.processPMCXML(infile)
|
apache-2.0
|
soltanmm/grpc
|
tools/run_tests/package_targets.py
|
2
|
5961
|
#!/usr/bin/env python2.7
# Copyright 2016, Google Inc.
# 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 Google Inc. 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.
"""Definition of targets to build distribution packages."""
import jobset
def create_docker_jobspec(name, dockerfile_dir, shell_command, environ={},
flake_retries=0, timeout_retries=0):
"""Creates jobspec for a task running under docker."""
environ = environ.copy()
environ['RUN_COMMAND'] = shell_command
docker_args=[]
for k,v in environ.items():
docker_args += ['-e', '%s=%s' % (k, v)]
docker_env = {'DOCKERFILE_DIR': dockerfile_dir,
'DOCKER_RUN_SCRIPT': 'tools/run_tests/dockerize/docker_run.sh',
'OUTPUT_DIR': 'artifacts'}
jobspec = jobset.JobSpec(
cmdline=['tools/run_tests/dockerize/build_and_run_docker.sh'] + docker_args,
environ=docker_env,
shortname='build_package.%s' % (name),
timeout_seconds=30*60,
flake_retries=flake_retries,
timeout_retries=timeout_retries)
return jobspec
def create_jobspec(name, cmdline, environ=None, cwd=None, shell=False,
flake_retries=0, timeout_retries=0):
"""Creates jobspec."""
jobspec = jobset.JobSpec(
cmdline=cmdline,
environ=environ,
cwd=cwd,
shortname='build_package.%s' % (name),
timeout_seconds=10*60,
flake_retries=flake_retries,
timeout_retries=timeout_retries,
shell=shell)
return jobspec
class CSharpPackage:
"""Builds C# nuget packages."""
def __init__(self, use_coreclr=False):
self.use_coreclr = use_coreclr
self.name = 'csharp_package_coreclr' if use_coreclr else 'csharp_package'
self.labels = ['package', 'csharp']
if use_coreclr:
self.labels += ['linux']
else:
self.labels += ['windows']
def pre_build_jobspecs(self):
if 'windows' in self.labels:
return [create_jobspec('prebuild_%s' % self.name,
['tools\\run_tests\\pre_build_csharp.bat'],
shell=True,
flake_retries=5,
timeout_retries=2)]
else:
return []
def build_jobspec(self):
if self.use_coreclr:
return create_docker_jobspec(
self.name,
'tools/dockerfile/test/csharp_coreclr_x64',
'tools/run_tests/build_package_csharp_coreclr.sh')
else:
return create_jobspec(self.name,
['build_packages.bat'],
cwd='src\\csharp',
shell=True)
def __str__(self):
return self.name
class NodePackage:
"""Builds Node NPM package and collects precompiled binaries"""
def __init__(self):
self.name = 'node_package'
self.labels = ['package', 'node', 'linux']
def pre_build_jobspecs(self):
return []
def build_jobspec(self):
return create_docker_jobspec(
self.name,
'tools/dockerfile/grpc_artifact_linux_x64',
'tools/run_tests/build_package_node.sh')
class RubyPackage:
"""Collects ruby gems created in the artifact phase"""
def __init__(self):
self.name = 'ruby_package'
self.labels = ['package', 'ruby', 'linux']
def pre_build_jobspecs(self):
return []
def build_jobspec(self):
return create_docker_jobspec(
self.name,
'tools/dockerfile/grpc_artifact_linux_x64',
'tools/run_tests/build_package_ruby.sh')
class PythonPackage:
"""Collects python eggs and wheels created in the artifact phase"""
def __init__(self):
self.name = 'python_package'
self.labels = ['package', 'python', 'linux']
def pre_build_jobspecs(self):
return []
def build_jobspec(self):
return create_docker_jobspec(
self.name,
'tools/dockerfile/grpc_artifact_linux_x64',
'tools/run_tests/build_package_python.sh')
class PHPPackage:
"""Copy PHP PECL package artifact"""
def __init__(self):
self.name = 'php_package'
self.labels = ['package', 'php', 'linux']
def pre_build_jobspecs(self):
return []
def build_jobspec(self):
return create_docker_jobspec(
self.name,
'tools/dockerfile/grpc_artifact_linux_x64',
'tools/run_tests/build_package_php.sh')
def targets():
"""Gets list of supported targets"""
return [CSharpPackage(),
CSharpPackage(use_coreclr=True),
NodePackage(),
RubyPackage(),
PythonPackage(),
PHPPackage()]
|
bsd-3-clause
|
monetate/sqlalchemy
|
test/orm/test_assorted_eager.py
|
3
|
37238
|
"""Exercises for eager loading.
Derived from mailing list-reported problems and issue tracker issues.
These are generally very old 0.1-era tests and at some point should
be cleaned up and modernized.
"""
import datetime
import sqlalchemy as sa
from sqlalchemy import ForeignKey
from sqlalchemy import Integer
from sqlalchemy import String
from sqlalchemy import testing
from sqlalchemy import text
from sqlalchemy.orm import backref
from sqlalchemy.orm import mapper
from sqlalchemy.orm import relationship
from sqlalchemy.orm import Session
from sqlalchemy.testing import eq_
from sqlalchemy.testing import fixtures
from sqlalchemy.testing.fixtures import fixture_session
from sqlalchemy.testing.schema import Column
from sqlalchemy.testing.schema import Table
class EagerTest(fixtures.MappedTest):
run_deletes = None
run_inserts = "once"
run_setup_mappers = "once"
@classmethod
def define_tables(cls, metadata):
Table(
"owners",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(30)),
)
Table(
"categories",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", String(20)),
)
Table(
"tests",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"owner_id", Integer, ForeignKey("owners.id"), nullable=False
),
Column(
"category_id",
Integer,
ForeignKey("categories.id"),
nullable=False,
),
)
Table(
"options",
metadata,
Column(
"test_id", Integer, ForeignKey("tests.id"), primary_key=True
),
Column(
"owner_id", Integer, ForeignKey("owners.id"), primary_key=True
),
Column(
"someoption",
sa.Boolean,
server_default=sa.false(),
nullable=False,
),
)
@classmethod
def setup_classes(cls):
class Owner(cls.Basic):
pass
class Category(cls.Basic):
pass
class Thing(cls.Basic):
pass
class Option(cls.Basic):
pass
@classmethod
def setup_mappers(cls):
Category, owners, Option, tests, Thing, Owner, options, categories = (
cls.classes.Category,
cls.tables.owners,
cls.classes.Option,
cls.tables.tests,
cls.classes.Thing,
cls.classes.Owner,
cls.tables.options,
cls.tables.categories,
)
mapper(Owner, owners)
mapper(Category, categories)
mapper(
Option,
options,
properties=dict(
owner=relationship(Owner, viewonly=True),
test=relationship(Thing, viewonly=True),
),
)
mapper(
Thing,
tests,
properties=dict(
owner=relationship(Owner, backref="tests"),
category=relationship(Category),
owner_option=relationship(
Option,
primaryjoin=sa.and_(
tests.c.id == options.c.test_id,
tests.c.owner_id == options.c.owner_id,
),
foreign_keys=[options.c.test_id, options.c.owner_id],
uselist=False,
),
),
)
@classmethod
def insert_data(cls, connection):
Owner, Category, Option, Thing = (
cls.classes.Owner,
cls.classes.Category,
cls.classes.Option,
cls.classes.Thing,
)
session = Session(connection)
o = Owner()
c = Category(name="Some Category")
session.add_all(
(
Thing(owner=o, category=c),
Thing(
owner=o, category=c, owner_option=Option(someoption=True)
),
Thing(owner=o, category=c, owner_option=Option()),
)
)
session.flush()
def test_noorm(self, connection):
"""test the control case"""
tests, options, categories = (
self.tables.tests,
self.tables.options,
self.tables.categories,
)
# I want to display a list of tests owned by owner 1
# if someoption is false or they haven't specified it yet (null)
# but not if they set it to true (example someoption is for hiding)
# desired output for owner 1
# test_id, cat_name
# 1 'Some Category'
# 3 "
# not orm style correct query
print("Obtaining correct results without orm")
result = connection.execute(
sa.select(tests.c.id, categories.c.name)
.where(
sa.and_(
tests.c.owner_id == 1,
sa.or_(
options.c.someoption == None, # noqa
options.c.someoption == False,
),
)
)
.order_by(tests.c.id)
.select_from(
tests.join(categories).outerjoin(
options,
sa.and_(
tests.c.id == options.c.test_id,
tests.c.owner_id == options.c.owner_id,
),
)
)
).fetchall()
eq_(result, [(1, "Some Category"), (3, "Some Category")])
def test_withoutjoinedload(self):
Thing, tests, options = (
self.classes.Thing,
self.tables.tests,
self.tables.options,
)
s = fixture_session()
result = (
s.query(Thing)
.select_from(
tests.outerjoin(
options,
sa.and_(
tests.c.id == options.c.test_id,
tests.c.owner_id == options.c.owner_id,
),
)
)
.filter(
sa.and_(
tests.c.owner_id == 1,
sa.or_(
options.c.someoption == None, # noqa
options.c.someoption == False,
),
)
)
)
result_str = ["%d %s" % (t.id, t.category.name) for t in result]
eq_(result_str, ["1 Some Category", "3 Some Category"])
def test_withjoinedload(self):
"""
Test that an joinedload locates the correct "from" clause with which to
attach to, when presented with a query that already has a complicated
from clause.
"""
Thing, tests, options = (
self.classes.Thing,
self.tables.tests,
self.tables.options,
)
s = fixture_session()
q = s.query(Thing).options(sa.orm.joinedload("category"))
result = q.select_from(
tests.outerjoin(
options,
sa.and_(
tests.c.id == options.c.test_id,
tests.c.owner_id == options.c.owner_id,
),
)
).filter(
sa.and_(
tests.c.owner_id == 1,
sa.or_(
options.c.someoption == None,
options.c.someoption == False, # noqa
),
)
)
result_str = ["%d %s" % (t.id, t.category.name) for t in result]
eq_(result_str, ["1 Some Category", "3 Some Category"])
def test_dslish(self):
"""test the same as withjoinedload except using generative"""
Thing, tests, options = (
self.classes.Thing,
self.tables.tests,
self.tables.options,
)
s = fixture_session()
q = s.query(Thing).options(sa.orm.joinedload("category"))
result = q.filter(
sa.and_(
tests.c.owner_id == 1,
sa.or_(
options.c.someoption == None,
options.c.someoption == False, # noqa
),
)
).outerjoin("owner_option")
result_str = ["%d %s" % (t.id, t.category.name) for t in result]
eq_(result_str, ["1 Some Category", "3 Some Category"])
@testing.crashes("sybase", "FIXME: unknown, verify not fails_on")
def test_without_outerjoin_literal(self):
Thing, tests = (self.classes.Thing, self.tables.tests)
s = fixture_session()
q = s.query(Thing).options(sa.orm.joinedload("category"))
result = q.filter(
(tests.c.owner_id == 1)
& text(
"options.someoption is null or options.someoption=:opt"
).bindparams(opt=False)
).join("owner_option")
result_str = ["%d %s" % (t.id, t.category.name) for t in result]
eq_(result_str, ["3 Some Category"])
def test_withoutouterjoin(self):
Thing, tests, options = (
self.classes.Thing,
self.tables.tests,
self.tables.options,
)
s = fixture_session()
q = s.query(Thing).options(sa.orm.joinedload("category"))
result = q.filter(
(tests.c.owner_id == 1)
& (
(options.c.someoption == None)
| (options.c.someoption == False)
) # noqa
).join("owner_option")
result_str = ["%d %s" % (t.id, t.category.name) for t in result]
eq_(result_str, ["3 Some Category"])
class EagerTest2(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"left",
metadata,
Column("id", Integer, ForeignKey("middle.id"), primary_key=True),
Column("data", String(50), primary_key=True),
)
Table(
"middle",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data", String(50)),
)
Table(
"right",
metadata,
Column("id", Integer, ForeignKey("middle.id"), primary_key=True),
Column("data", String(50), primary_key=True),
)
@classmethod
def setup_classes(cls):
class Left(cls.Basic):
def __init__(self, data):
self.data = data
class Middle(cls.Basic):
def __init__(self, data):
self.data = data
class Right(cls.Basic):
def __init__(self, data):
self.data = data
@classmethod
def setup_mappers(cls):
Right, Middle, middle, right, left, Left = (
cls.classes.Right,
cls.classes.Middle,
cls.tables.middle,
cls.tables.right,
cls.tables.left,
cls.classes.Left,
)
# set up bi-directional eager loads
mapper(Left, left)
mapper(Right, right)
mapper(
Middle,
middle,
properties=dict(
left=relationship(
Left,
lazy="joined",
backref=backref("middle", lazy="joined"),
),
right=relationship(
Right,
lazy="joined",
backref=backref("middle", lazy="joined"),
),
),
),
def test_eager_terminate(self):
"""Eager query generation does not include the same mapper's table twice.
Or, that bi-directional eager loads don't include each other in eager
query generation.
"""
Middle, Right, Left = (
self.classes.Middle,
self.classes.Right,
self.classes.Left,
)
p = Middle("m1")
p.left.append(Left("l1"))
p.right.append(Right("r1"))
session = fixture_session()
session.add(p)
session.flush()
session.expunge_all()
session.query(Left).filter_by(data="l1").one()
class EagerTest3(fixtures.MappedTest):
"""Eager loading combined with nested SELECT statements, functions, and
aggregates."""
@classmethod
def define_tables(cls, metadata):
Table(
"datas",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("a", Integer, nullable=False),
)
Table(
"foo",
metadata,
Column(
"data_id", Integer, ForeignKey("datas.id"), primary_key=True
),
Column("bar", Integer),
)
Table(
"stats",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("data_id", Integer, ForeignKey("datas.id")),
Column("somedata", Integer, nullable=False),
)
@classmethod
def setup_classes(cls):
class Data(cls.Basic):
pass
class Foo(cls.Basic):
pass
class Stat(cls.Basic):
pass
def test_nesting_with_functions(self):
Stat, Foo, stats, foo, Data, datas = (
self.classes.Stat,
self.classes.Foo,
self.tables.stats,
self.tables.foo,
self.classes.Data,
self.tables.datas,
)
mapper(Data, datas)
mapper(
Foo,
foo,
properties={
"data": relationship(
Data, backref=backref("foo", uselist=False)
)
},
)
mapper(Stat, stats, properties={"data": relationship(Data)})
session = fixture_session()
data = [Data(a=x) for x in range(5)]
session.add_all(data)
session.add_all(
(
Stat(data=data[0], somedata=1),
Stat(data=data[1], somedata=2),
Stat(data=data[2], somedata=3),
Stat(data=data[3], somedata=4),
Stat(data=data[4], somedata=5),
Stat(data=data[0], somedata=6),
Stat(data=data[1], somedata=7),
Stat(data=data[2], somedata=8),
Stat(data=data[3], somedata=9),
Stat(data=data[4], somedata=10),
)
)
session.flush()
arb_data = (
sa.select(
stats.c.data_id, sa.func.max(stats.c.somedata).label("max")
)
.where(stats.c.data_id <= 5)
.group_by(stats.c.data_id)
)
arb_result = session.connection().execute(arb_data).fetchall()
# order the result list descending based on 'max'
arb_result.sort(key=lambda a: a._mapping["max"], reverse=True)
# extract just the "data_id" from it
arb_result = [row._mapping["data_id"] for row in arb_result]
arb_data = arb_data.alias("arb")
# now query for Data objects using that above select, adding the
# "order by max desc" separately
q = (
session.query(Data)
.options(sa.orm.joinedload("foo"))
.select_from(
datas.join(arb_data, arb_data.c.data_id == datas.c.id)
)
.order_by(sa.desc(arb_data.c.max))
.limit(10)
)
# extract "data_id" from the list of result objects
verify_result = [d.id for d in q]
eq_(verify_result, arb_result)
class EagerTest4(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"departments",
metadata,
Column(
"department_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(50)),
)
Table(
"employees",
metadata,
Column(
"person_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(50)),
Column(
"department_id",
Integer,
ForeignKey("departments.department_id"),
),
)
@classmethod
def setup_classes(cls):
class Department(cls.Basic):
pass
class Employee(cls.Basic):
pass
def test_basic(self):
Department, Employee, employees, departments = (
self.classes.Department,
self.classes.Employee,
self.tables.employees,
self.tables.departments,
)
mapper(Employee, employees)
mapper(
Department,
departments,
properties=dict(
employees=relationship(
Employee, lazy="joined", backref="department"
)
),
)
d1 = Department(name="One")
for e in "Jim", "Jack", "John", "Susan":
d1.employees.append(Employee(name=e))
d2 = Department(name="Two")
for e in "Joe", "Bob", "Mary", "Wally":
d2.employees.append(Employee(name=e))
sess = fixture_session()
sess.add_all((d1, d2))
sess.flush()
q = (
sess.query(Department)
.join("employees")
.filter(Employee.name.startswith("J"))
.distinct()
.order_by(sa.desc(Department.name))
)
eq_(q.count(), 2)
assert q[0] is d2
class EagerTest5(fixtures.MappedTest):
"""Construction of AliasedClauses for the same eager load property but
different parent mappers, due to inheritance."""
@classmethod
def define_tables(cls, metadata):
Table(
"base",
metadata,
Column("uid", String(30), primary_key=True),
Column("x", String(30)),
)
Table(
"derived",
metadata,
Column(
"uid", String(30), ForeignKey("base.uid"), primary_key=True
),
Column("y", String(30)),
)
Table(
"derivedII",
metadata,
Column(
"uid", String(30), ForeignKey("base.uid"), primary_key=True
),
Column("z", String(30)),
)
Table(
"comments",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("uid", String(30), ForeignKey("base.uid")),
Column("comment", String(30)),
)
@classmethod
def setup_classes(cls):
class Base(cls.Basic):
def __init__(self, uid, x):
self.uid = uid
self.x = x
class Derived(Base):
def __init__(self, uid, x, y):
self.uid = uid
self.x = x
self.y = y
class DerivedII(Base):
def __init__(self, uid, x, z):
self.uid = uid
self.x = x
self.z = z
class Comment(cls.Basic):
def __init__(self, uid, comment):
self.uid = uid
self.comment = comment
def test_basic(self):
(
Comment,
Derived,
derived,
comments,
DerivedII,
Base,
base,
derivedII,
) = (
self.classes.Comment,
self.classes.Derived,
self.tables.derived,
self.tables.comments,
self.classes.DerivedII,
self.classes.Base,
self.tables.base,
self.tables.derivedII,
)
mapper(Comment, comments)
baseMapper = mapper(
Base,
base,
properties=dict(
comments=relationship(
Comment, lazy="joined", cascade="all, delete-orphan"
)
),
)
mapper(Derived, derived, inherits=baseMapper)
mapper(DerivedII, derivedII, inherits=baseMapper)
sess = fixture_session()
d = Derived("uid1", "x", "y")
d.comments = [Comment("uid1", "comment")]
d2 = DerivedII("uid2", "xx", "z")
d2.comments = [Comment("uid2", "comment")]
sess.add_all((d, d2))
sess.flush()
sess.expunge_all()
# this eager load sets up an AliasedClauses for the "comment"
# relationship, then stores it in clauses_by_lead_mapper[mapper for
# Derived]
d = sess.query(Derived).get("uid1")
sess.expunge_all()
assert len([c for c in d.comments]) == 1
# this eager load sets up an AliasedClauses for the "comment"
# relationship, and should store it in clauses_by_lead_mapper[mapper
# for DerivedII]. the bug was that the previous AliasedClause create
# prevented this population from occurring.
d2 = sess.query(DerivedII).get("uid2")
sess.expunge_all()
# object is not in the session; therefore the lazy load cant trigger
# here, eager load had to succeed
assert len([c for c in d2.comments]) == 1
class EagerTest6(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"design_types",
metadata,
Column(
"design_type_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
)
Table(
"design",
metadata,
Column(
"design_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column(
"design_type_id",
Integer,
ForeignKey("design_types.design_type_id"),
),
)
Table(
"parts",
metadata,
Column(
"part_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("design_id", Integer, ForeignKey("design.design_id")),
Column(
"design_type_id",
Integer,
ForeignKey("design_types.design_type_id"),
),
)
Table(
"inherited_part",
metadata,
Column(
"ip_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("part_id", Integer, ForeignKey("parts.part_id")),
Column("design_id", Integer, ForeignKey("design.design_id")),
)
@classmethod
def setup_classes(cls):
class Part(cls.Basic):
pass
class Design(cls.Basic):
pass
class DesignType(cls.Basic):
pass
class InheritedPart(cls.Basic):
pass
def test_one(self):
(
Part,
inherited_part,
design_types,
DesignType,
parts,
design,
Design,
InheritedPart,
) = (
self.classes.Part,
self.tables.inherited_part,
self.tables.design_types,
self.classes.DesignType,
self.tables.parts,
self.tables.design,
self.classes.Design,
self.classes.InheritedPart,
)
p_m = mapper(Part, parts)
mapper(
InheritedPart,
inherited_part,
properties=dict(part=relationship(Part, lazy="joined")),
)
d_m = mapper(
Design,
design,
properties=dict(
inheritedParts=relationship(
InheritedPart,
cascade="all, delete-orphan",
backref="design",
)
),
)
mapper(DesignType, design_types)
d_m.add_property(
"type", relationship(DesignType, lazy="joined", backref="designs")
)
p_m.add_property(
"design",
relationship(
Design,
lazy="joined",
backref=backref("parts", cascade="all, delete-orphan"),
),
)
d = Design()
sess = fixture_session()
sess.add(d)
sess.flush()
sess.expunge_all()
x = sess.query(Design).get(1)
x.inheritedParts
class EagerTest7(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"companies",
metadata,
Column(
"company_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("company_name", String(40)),
)
Table(
"addresses",
metadata,
Column(
"address_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("company_id", Integer, ForeignKey("companies.company_id")),
Column("address", String(40)),
)
Table(
"phone_numbers",
metadata,
Column(
"phone_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("address_id", Integer, ForeignKey("addresses.address_id")),
Column("type", String(20)),
Column("number", String(10)),
)
Table(
"invoices",
metadata,
Column(
"invoice_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("company_id", Integer, ForeignKey("companies.company_id")),
Column("date", sa.DateTime),
)
@classmethod
def setup_classes(cls):
class Company(cls.Comparable):
pass
class Address(cls.Comparable):
pass
class Phone(cls.Comparable):
pass
class Invoice(cls.Comparable):
pass
def test_load_m2o_attached_to_o2(self):
"""
Tests eager load of a many-to-one attached to a one-to-many. this
testcase illustrated the bug, which is that when the single Company is
loaded, no further processing of the rows occurred in order to load
the Company's second Address object.
"""
addresses, invoices, Company, companies, Invoice, Address = (
self.tables.addresses,
self.tables.invoices,
self.classes.Company,
self.tables.companies,
self.classes.Invoice,
self.classes.Address,
)
mapper(Address, addresses)
mapper(
Company,
companies,
properties={"addresses": relationship(Address, lazy="joined")},
)
mapper(
Invoice,
invoices,
properties={"company": relationship(Company, lazy="joined")},
)
a1 = Address(address="a1 address")
a2 = Address(address="a2 address")
c1 = Company(company_name="company 1", addresses=[a1, a2])
i1 = Invoice(date=datetime.datetime.now(), company=c1)
session = fixture_session()
session.add(i1)
session.flush()
company_id = c1.company_id
invoice_id = i1.invoice_id
session.expunge_all()
c = session.query(Company).get(company_id)
session.expunge_all()
i = session.query(Invoice).get(invoice_id)
def go():
eq_(c, i.company)
eq_(c.addresses, i.company.addresses)
self.assert_sql_count(testing.db, go, 0)
class EagerTest8(fixtures.MappedTest):
@classmethod
def define_tables(cls, metadata):
Table(
"prj",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("created", sa.DateTime),
Column("title", sa.String(100)),
)
Table(
"task",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column(
"status_id",
Integer,
ForeignKey("task_status.id"),
nullable=False,
),
Column("title", sa.String(100)),
Column(
"task_type_id",
Integer,
ForeignKey("task_type.id"),
nullable=False,
),
Column("prj_id", Integer, ForeignKey("prj.id"), nullable=False),
)
Table(
"task_status",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
)
Table(
"task_type",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
)
Table(
"msg",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("posted", sa.DateTime, index=True),
Column("type_id", Integer, ForeignKey("msg_type.id")),
Column("task_id", Integer, ForeignKey("task.id")),
)
Table(
"msg_type",
metadata,
Column(
"id", Integer, primary_key=True, test_needs_autoincrement=True
),
Column("name", sa.String(20)),
Column("display_name", sa.String(20)),
)
@classmethod
def fixtures(cls):
return dict(
prj=(("id",), (1,)),
task_status=(("id",), (1,)),
task_type=(("id",), (1,)),
task=(
("title", "task_type_id", "status_id", "prj_id"),
("task 1", 1, 1, 1),
),
)
@classmethod
def setup_classes(cls):
class Task_Type(cls.Comparable):
pass
class Joined(cls.Comparable):
pass
def test_nested_joins(self):
task, Task_Type, Joined, task_type, msg = (
self.tables.task,
self.classes.Task_Type,
self.classes.Joined,
self.tables.task_type,
self.tables.msg,
)
# this is testing some subtle column resolution stuff,
# concerning corresponding_column() being extremely accurate
# as well as how mapper sets up its column properties
mapper(Task_Type, task_type)
j = sa.outerjoin(task, msg, task.c.id == msg.c.task_id)
jj = (
sa.select(
task.c.id.label("task_id"),
sa.func.count(msg.c.id).label("props_cnt"),
)
.select_from(j)
.group_by(task.c.id)
.alias("prop_c_s")
)
jjj = sa.join(task, jj, task.c.id == jj.c.task_id)
mapper(
Joined,
jjj,
properties=dict(type=relationship(Task_Type, lazy="joined")),
)
session = fixture_session()
eq_(
session.query(Joined)
.order_by(Joined.id)
.limit(10)
.offset(0)
.one(),
Joined(id=1, title="task 1", props_cnt=0),
)
class EagerTest9(fixtures.MappedTest):
"""Test the usage of query options to eagerly load specific paths.
This relies upon the 'path' construct used by PropertyOption to relate
LoaderStrategies to specific paths, as well as the path state maintained
throughout the query setup/mapper instances process.
"""
@classmethod
def define_tables(cls, metadata):
Table(
"accounts",
metadata,
Column(
"account_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(40)),
)
Table(
"transactions",
metadata,
Column(
"transaction_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(40)),
)
Table(
"entries",
metadata,
Column(
"entry_id",
Integer,
primary_key=True,
test_needs_autoincrement=True,
),
Column("name", String(40)),
Column("account_id", Integer, ForeignKey("accounts.account_id")),
Column(
"transaction_id",
Integer,
ForeignKey("transactions.transaction_id"),
),
)
@classmethod
def setup_classes(cls):
class Account(cls.Basic):
pass
class Transaction(cls.Basic):
pass
class Entry(cls.Basic):
pass
@classmethod
def setup_mappers(cls):
Account, Transaction, transactions, accounts, entries, Entry = (
cls.classes.Account,
cls.classes.Transaction,
cls.tables.transactions,
cls.tables.accounts,
cls.tables.entries,
cls.classes.Entry,
)
mapper(Account, accounts)
mapper(Transaction, transactions)
mapper(
Entry,
entries,
properties=dict(
account=relationship(
Account,
uselist=False,
backref=backref(
"entries", lazy="select", order_by=entries.c.entry_id
),
),
transaction=relationship(
Transaction,
uselist=False,
backref=backref(
"entries", lazy="joined", order_by=entries.c.entry_id
),
),
),
)
def test_joinedload_on_path(self):
Entry, Account, Transaction = (
self.classes.Entry,
self.classes.Account,
self.classes.Transaction,
)
session = fixture_session()
tx1 = Transaction(name="tx1")
tx2 = Transaction(name="tx2")
acc1 = Account(name="acc1")
Entry(name="ent11", account=acc1, transaction=tx1)
Entry(name="ent12", account=acc1, transaction=tx2)
acc2 = Account(name="acc2")
Entry(name="ent21", account=acc2, transaction=tx1)
Entry(name="ent22", account=acc2, transaction=tx2)
session.add(acc1)
session.flush()
session.expunge_all()
def go():
# load just the first Account. eager loading will actually load
# all objects saved thus far, but will not eagerly load the
# "accounts" off the immediate "entries"; only the "accounts" off
# the entries->transaction->entries
acc = (
session.query(Account)
.options(
sa.orm.joinedload("entries")
.joinedload("transaction")
.joinedload("entries")
.joinedload("account")
)
.order_by(Account.account_id)
).first()
# no sql occurs
eq_(acc.name, "acc1")
eq_(acc.entries[0].transaction.entries[0].account.name, "acc1")
eq_(acc.entries[0].transaction.entries[1].account.name, "acc2")
# lazyload triggers but no sql occurs because many-to-one uses
# cached query.get()
for e in acc.entries:
assert e.account is acc
self.assert_sql_count(testing.db, go, 1)
|
mit
|
Antiun/odoo
|
addons/report_webkit/ir_report.py
|
382
|
3807
|
# -*- coding: utf-8 -*-
##############################################################################
#
# Copyright (c) 2010 Camptocamp SA (http://www.camptocamp.com)
# All Right Reserved
#
# Author : Nicolas Bessi (Camptocamp)
#
# WARNING: This program as such is intended to be used by professional
# programmers who take the whole responsability of assessing all potential
# consequences resulting from its eventual inadequacies and bugs
# End users who are looking for a ready-to-use solution with commercial
# garantees and support are strongly adviced to contract a Free Software
# Service Company
#
# This program is Free Software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
##############################################################################
import openerp
from openerp.osv import fields, orm
from webkit_report import WebKitParser
class ir_actions_report_xml(orm.Model):
_inherit = 'ir.actions.report.xml'
_columns = {
'webkit_header': fields.property(
type='many2one', relation='ir.header_webkit',
string='Webkit Header', help="The header linked to the report",
required=True),
'webkit_debug': fields.boolean('Webkit debug',
help="Enable the webkit engine debugger"),
'report_webkit_data': fields.text('Webkit Template',
help="This template will be used if the main report file is not found"),
'precise_mode': fields.boolean('Precise Mode',
help="This mode allow more precise element position as each object"
" is printed on a separate HTML but memory and disk usage are wider.")
}
def _lookup_report(self, cr, name):
"""
Look up a report definition.
"""
import operator
import os
opj = os.path.join
# First lookup in the deprecated place, because if the report definition
# has not been updated, it is more likely the correct definition is there.
# Only reports with custom parser specified in Python are still there.
if 'report.' + name in openerp.report.interface.report_int._reports:
new_report = openerp.report.interface.report_int._reports['report.' + name]
if not isinstance(new_report, WebKitParser):
new_report = None
else:
cr.execute("SELECT * FROM ir_act_report_xml WHERE report_name=%s and report_type=%s", (name, 'webkit'))
r = cr.dictfetchone()
if r:
if r['parser']:
parser = operator.attrgetter(r['parser'])(openerp.addons)
kwargs = { 'parser': parser }
else:
kwargs = {}
new_report = WebKitParser('report.'+r['report_name'],
r['model'], opj('addons',r['report_rml'] or '/'),
header=r['header'], register=False, **kwargs)
else:
new_report = None
if new_report:
return new_report
else:
return super(ir_actions_report_xml, self)._lookup_report(cr, name)
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
agpl-3.0
|
Gillu13/scipy
|
scipy/integrate/tests/test_integrate.py
|
55
|
22040
|
# Authors: Nils Wagner, Ed Schofield, Pauli Virtanen, John Travers
"""
Tests for numerical integration.
"""
from __future__ import division, print_function, absolute_import
import numpy as np
from numpy import (arange, zeros, array, dot, sqrt, cos, sin, eye, pi, exp,
allclose)
from scipy._lib.six import xrange
from numpy.testing import (
assert_, TestCase, run_module_suite, assert_array_almost_equal,
assert_raises, assert_allclose, assert_array_equal, assert_equal)
from scipy.integrate import odeint, ode, complex_ode
#------------------------------------------------------------------------------
# Test ODE integrators
#------------------------------------------------------------------------------
class TestOdeint(TestCase):
# Check integrate.odeint
def _do_problem(self, problem):
t = arange(0.0, problem.stop_t, 0.05)
z, infodict = odeint(problem.f, problem.z0, t, full_output=True)
assert_(problem.verify(z, t))
def test_odeint(self):
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.cmplx:
continue
self._do_problem(problem)
class TestODEClass(TestCase):
ode_class = None # Set in subclass.
def _do_problem(self, problem, integrator, method='adams'):
# ode has callback arguments in different order than odeint
f = lambda t, z: problem.f(z, t)
jac = None
if hasattr(problem, 'jac'):
jac = lambda t, z: problem.jac(z, t)
integrator_params = {}
if problem.lband is not None or problem.uband is not None:
integrator_params['uband'] = problem.uband
integrator_params['lband'] = problem.lband
ig = self.ode_class(f, jac)
ig.set_integrator(integrator,
atol=problem.atol/10,
rtol=problem.rtol/10,
method=method,
**integrator_params)
ig.set_initial_value(problem.z0, t=0.0)
z = ig.integrate(problem.stop_t)
assert_array_equal(z, ig.y)
assert_(ig.successful(), (problem, method))
assert_(problem.verify(array([z]), problem.stop_t), (problem, method))
class TestOde(TestODEClass):
ode_class = ode
def test_vode(self):
# Check the vode solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.cmplx:
continue
if not problem.stiff:
self._do_problem(problem, 'vode', 'adams')
self._do_problem(problem, 'vode', 'bdf')
def test_zvode(self):
# Check the zvode solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if not problem.stiff:
self._do_problem(problem, 'zvode', 'adams')
self._do_problem(problem, 'zvode', 'bdf')
def test_lsoda(self):
# Check the lsoda solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.cmplx:
continue
self._do_problem(problem, 'lsoda')
def test_dopri5(self):
# Check the dopri5 solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.cmplx:
continue
if problem.stiff:
continue
if hasattr(problem, 'jac'):
continue
self._do_problem(problem, 'dopri5')
def test_dop853(self):
# Check the dop853 solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.cmplx:
continue
if problem.stiff:
continue
if hasattr(problem, 'jac'):
continue
self._do_problem(problem, 'dop853')
def test_concurrent_fail(self):
for sol in ('vode', 'zvode', 'lsoda'):
f = lambda t, y: 1.0
r = ode(f).set_integrator(sol)
r.set_initial_value(0, 0)
r2 = ode(f).set_integrator(sol)
r2.set_initial_value(0, 0)
r.integrate(r.t + 0.1)
r2.integrate(r2.t + 0.1)
assert_raises(RuntimeError, r.integrate, r.t + 0.1)
def test_concurrent_ok(self):
f = lambda t, y: 1.0
for k in xrange(3):
for sol in ('vode', 'zvode', 'lsoda', 'dopri5', 'dop853'):
r = ode(f).set_integrator(sol)
r.set_initial_value(0, 0)
r2 = ode(f).set_integrator(sol)
r2.set_initial_value(0, 0)
r.integrate(r.t + 0.1)
r2.integrate(r2.t + 0.1)
r2.integrate(r2.t + 0.1)
assert_allclose(r.y, 0.1)
assert_allclose(r2.y, 0.2)
for sol in ('dopri5', 'dop853'):
r = ode(f).set_integrator(sol)
r.set_initial_value(0, 0)
r2 = ode(f).set_integrator(sol)
r2.set_initial_value(0, 0)
r.integrate(r.t + 0.1)
r.integrate(r.t + 0.1)
r2.integrate(r2.t + 0.1)
r.integrate(r.t + 0.1)
r2.integrate(r2.t + 0.1)
assert_allclose(r.y, 0.3)
assert_allclose(r2.y, 0.2)
class TestComplexOde(TestODEClass):
ode_class = complex_ode
def test_vode(self):
# Check the vode solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if not problem.stiff:
self._do_problem(problem, 'vode', 'adams')
else:
self._do_problem(problem, 'vode', 'bdf')
def test_lsoda(self):
# Check the lsoda solver
for problem_cls in PROBLEMS:
problem = problem_cls()
self._do_problem(problem, 'lsoda')
def test_dopri5(self):
# Check the dopri5 solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.stiff:
continue
if hasattr(problem, 'jac'):
continue
self._do_problem(problem, 'dopri5')
def test_dop853(self):
# Check the dop853 solver
for problem_cls in PROBLEMS:
problem = problem_cls()
if problem.stiff:
continue
if hasattr(problem, 'jac'):
continue
self._do_problem(problem, 'dop853')
class TestSolout(TestCase):
# Check integrate.ode correctly handles solout for dopri5 and dop853
def _run_solout_test(self, integrator):
# Check correct usage of solout
ts = []
ys = []
t0 = 0.0
tend = 10.0
y0 = [1.0, 2.0]
def solout(t, y):
ts.append(t)
ys.append(y.copy())
def rhs(t, y):
return [y[0] + y[1], -y[1]**2]
ig = ode(rhs).set_integrator(integrator)
ig.set_solout(solout)
ig.set_initial_value(y0, t0)
ret = ig.integrate(tend)
assert_array_equal(ys[0], y0)
assert_array_equal(ys[-1], ret)
assert_equal(ts[0], t0)
assert_equal(ts[-1], tend)
def test_solout(self):
for integrator in ('dopri5', 'dop853'):
self._run_solout_test(integrator)
def _run_solout_after_initial_test(self, integrator):
# Check if solout works even if it is set after the initial value.
ts = []
ys = []
t0 = 0.0
tend = 10.0
y0 = [1.0, 2.0]
def solout(t, y):
ts.append(t)
ys.append(y.copy())
def rhs(t, y):
return [y[0] + y[1], -y[1]**2]
ig = ode(rhs).set_integrator(integrator)
ig.set_initial_value(y0, t0)
ig.set_solout(solout)
ret = ig.integrate(tend)
assert_array_equal(ys[0], y0)
assert_array_equal(ys[-1], ret)
assert_equal(ts[0], t0)
assert_equal(ts[-1], tend)
def test_solout_after_initial(self):
for integrator in ('dopri5', 'dop853'):
self._run_solout_after_initial_test(integrator)
def _run_solout_break_test(self, integrator):
# Check correct usage of stopping via solout
ts = []
ys = []
t0 = 0.0
tend = 10.0
y0 = [1.0, 2.0]
def solout(t, y):
ts.append(t)
ys.append(y.copy())
if t > tend/2.0:
return -1
def rhs(t, y):
return [y[0] + y[1], -y[1]**2]
ig = ode(rhs).set_integrator(integrator)
ig.set_solout(solout)
ig.set_initial_value(y0, t0)
ret = ig.integrate(tend)
assert_array_equal(ys[0], y0)
assert_array_equal(ys[-1], ret)
assert_equal(ts[0], t0)
assert_(ts[-1] > tend/2.0)
assert_(ts[-1] < tend)
def test_solout_break(self):
for integrator in ('dopri5', 'dop853'):
self._run_solout_break_test(integrator)
class TestComplexSolout(TestCase):
# Check integrate.ode correctly handles solout for dopri5 and dop853
def _run_solout_test(self, integrator):
# Check correct usage of solout
ts = []
ys = []
t0 = 0.0
tend = 20.0
y0 = [0.0]
def solout(t, y):
ts.append(t)
ys.append(y.copy())
def rhs(t, y):
return [1.0/(t - 10.0 - 1j)]
ig = complex_ode(rhs).set_integrator(integrator)
ig.set_solout(solout)
ig.set_initial_value(y0, t0)
ret = ig.integrate(tend)
assert_array_equal(ys[0], y0)
assert_array_equal(ys[-1], ret)
assert_equal(ts[0], t0)
assert_equal(ts[-1], tend)
def test_solout(self):
for integrator in ('dopri5', 'dop853'):
self._run_solout_test(integrator)
def _run_solout_break_test(self, integrator):
# Check correct usage of stopping via solout
ts = []
ys = []
t0 = 0.0
tend = 20.0
y0 = [0.0]
def solout(t, y):
ts.append(t)
ys.append(y.copy())
if t > tend/2.0:
return -1
def rhs(t, y):
return [1.0/(t - 10.0 - 1j)]
ig = complex_ode(rhs).set_integrator(integrator)
ig.set_solout(solout)
ig.set_initial_value(y0, t0)
ret = ig.integrate(tend)
assert_array_equal(ys[0], y0)
assert_array_equal(ys[-1], ret)
assert_equal(ts[0], t0)
assert_(ts[-1] > tend/2.0)
assert_(ts[-1] < tend)
def test_solout_break(self):
for integrator in ('dopri5', 'dop853'):
self._run_solout_break_test(integrator)
#------------------------------------------------------------------------------
# Test problems
#------------------------------------------------------------------------------
class ODE:
"""
ODE problem
"""
stiff = False
cmplx = False
stop_t = 1
z0 = []
lband = None
uband = None
atol = 1e-6
rtol = 1e-5
class SimpleOscillator(ODE):
r"""
Free vibration of a simple oscillator::
m \ddot{u} + k u = 0, u(0) = u_0 \dot{u}(0) \dot{u}_0
Solution::
u(t) = u_0*cos(sqrt(k/m)*t)+\dot{u}_0*sin(sqrt(k/m)*t)/sqrt(k/m)
"""
stop_t = 1 + 0.09
z0 = array([1.0, 0.1], float)
k = 4.0
m = 1.0
def f(self, z, t):
tmp = zeros((2, 2), float)
tmp[0, 1] = 1.0
tmp[1, 0] = -self.k / self.m
return dot(tmp, z)
def verify(self, zs, t):
omega = sqrt(self.k / self.m)
u = self.z0[0]*cos(omega*t) + self.z0[1]*sin(omega*t)/omega
return allclose(u, zs[:, 0], atol=self.atol, rtol=self.rtol)
class ComplexExp(ODE):
r"""The equation :lm:`\dot u = i u`"""
stop_t = 1.23*pi
z0 = exp([1j, 2j, 3j, 4j, 5j])
cmplx = True
def f(self, z, t):
return 1j*z
def jac(self, z, t):
return 1j*eye(5)
def verify(self, zs, t):
u = self.z0 * exp(1j*t)
return allclose(u, zs, atol=self.atol, rtol=self.rtol)
class Pi(ODE):
r"""Integrate 1/(t + 1j) from t=-10 to t=10"""
stop_t = 20
z0 = [0]
cmplx = True
def f(self, z, t):
return array([1./(t - 10 + 1j)])
def verify(self, zs, t):
u = -2j * np.arctan(10)
return allclose(u, zs[-1, :], atol=self.atol, rtol=self.rtol)
class CoupledDecay(ODE):
r"""
3 coupled decays suited for banded treatment
(banded mode makes it necessary when N>>3)
"""
stiff = True
stop_t = 0.5
z0 = [5.0, 7.0, 13.0]
lband = 1
uband = 0
lmbd = [0.17, 0.23, 0.29] # fictious decay constants
def f(self, z, t):
lmbd = self.lmbd
return np.array([-lmbd[0]*z[0],
-lmbd[1]*z[1] + lmbd[0]*z[0],
-lmbd[2]*z[2] + lmbd[1]*z[1]])
def jac(self, z, t):
# The full Jacobian is
#
# [-lmbd[0] 0 0 ]
# [ lmbd[0] -lmbd[1] 0 ]
# [ 0 lmbd[1] -lmbd[2]]
#
# The lower and upper bandwidths are lband=1 and uband=0, resp.
# The representation of this array in packed format is
#
# [-lmbd[0] -lmbd[1] -lmbd[2]]
# [ lmbd[0] lmbd[1] 0 ]
lmbd = self.lmbd
j = np.zeros((self.lband + self.uband + 1, 3), order='F')
def set_j(ri, ci, val):
j[self.uband + ri - ci, ci] = val
set_j(0, 0, -lmbd[0])
set_j(1, 0, lmbd[0])
set_j(1, 1, -lmbd[1])
set_j(2, 1, lmbd[1])
set_j(2, 2, -lmbd[2])
return j
def verify(self, zs, t):
# Formulae derived by hand
lmbd = np.array(self.lmbd)
d10 = lmbd[1] - lmbd[0]
d21 = lmbd[2] - lmbd[1]
d20 = lmbd[2] - lmbd[0]
e0 = np.exp(-lmbd[0] * t)
e1 = np.exp(-lmbd[1] * t)
e2 = np.exp(-lmbd[2] * t)
u = np.vstack((
self.z0[0] * e0,
self.z0[1] * e1 + self.z0[0] * lmbd[0] / d10 * (e0 - e1),
self.z0[2] * e2 + self.z0[1] * lmbd[1] / d21 * (e1 - e2) +
lmbd[1] * lmbd[0] * self.z0[0] / d10 *
(1 / d20 * (e0 - e2) - 1 / d21 * (e1 - e2)))).transpose()
return allclose(u, zs, atol=self.atol, rtol=self.rtol)
PROBLEMS = [SimpleOscillator, ComplexExp, Pi, CoupledDecay]
#------------------------------------------------------------------------------
def f(t, x):
dxdt = [x[1], -x[0]]
return dxdt
def jac(t, x):
j = array([[0.0, 1.0],
[-1.0, 0.0]])
return j
def f1(t, x, omega):
dxdt = [omega*x[1], -omega*x[0]]
return dxdt
def jac1(t, x, omega):
j = array([[0.0, omega],
[-omega, 0.0]])
return j
def f2(t, x, omega1, omega2):
dxdt = [omega1*x[1], -omega2*x[0]]
return dxdt
def jac2(t, x, omega1, omega2):
j = array([[0.0, omega1],
[-omega2, 0.0]])
return j
def fv(t, x, omega):
dxdt = [omega[0]*x[1], -omega[1]*x[0]]
return dxdt
def jacv(t, x, omega):
j = array([[0.0, omega[0]],
[-omega[1], 0.0]])
return j
class ODECheckParameterUse(object):
"""Call an ode-class solver with several cases of parameter use."""
# This class is intentionally not a TestCase subclass.
# solver_name must be set before tests can be run with this class.
# Set these in subclasses.
solver_name = ''
solver_uses_jac = False
def _get_solver(self, f, jac):
solver = ode(f, jac)
if self.solver_uses_jac:
solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7,
with_jacobian=self.solver_uses_jac)
else:
# XXX Shouldn't set_integrator *always* accept the keyword arg
# 'with_jacobian', and perhaps raise an exception if it is set
# to True if the solver can't actually use it?
solver.set_integrator(self.solver_name, atol=1e-9, rtol=1e-7)
return solver
def _check_solver(self, solver):
ic = [1.0, 0.0]
solver.set_initial_value(ic, 0.0)
solver.integrate(pi)
assert_array_almost_equal(solver.y, [-1.0, 0.0])
def test_no_params(self):
solver = self._get_solver(f, jac)
self._check_solver(solver)
def test_one_scalar_param(self):
solver = self._get_solver(f1, jac1)
omega = 1.0
solver.set_f_params(omega)
if self.solver_uses_jac:
solver.set_jac_params(omega)
self._check_solver(solver)
def test_two_scalar_params(self):
solver = self._get_solver(f2, jac2)
omega1 = 1.0
omega2 = 1.0
solver.set_f_params(omega1, omega2)
if self.solver_uses_jac:
solver.set_jac_params(omega1, omega2)
self._check_solver(solver)
def test_vector_param(self):
solver = self._get_solver(fv, jacv)
omega = [1.0, 1.0]
solver.set_f_params(omega)
if self.solver_uses_jac:
solver.set_jac_params(omega)
self._check_solver(solver)
class DOPRI5CheckParameterUse(ODECheckParameterUse, TestCase):
solver_name = 'dopri5'
solver_uses_jac = False
class DOP853CheckParameterUse(ODECheckParameterUse, TestCase):
solver_name = 'dop853'
solver_uses_jac = False
class VODECheckParameterUse(ODECheckParameterUse, TestCase):
solver_name = 'vode'
solver_uses_jac = True
class ZVODECheckParameterUse(ODECheckParameterUse, TestCase):
solver_name = 'zvode'
solver_uses_jac = True
class LSODACheckParameterUse(ODECheckParameterUse, TestCase):
solver_name = 'lsoda'
solver_uses_jac = True
def test_odeint_trivial_time():
# Test that odeint succeeds when given a single time point
# and full_output=True. This is a regression test for gh-4282.
y0 = 1
t = [0]
y, info = odeint(lambda y, t: -y, y0, t, full_output=True)
assert_array_equal(y, np.array([[y0]]))
def test_odeint_banded_jacobian():
# Test the use of the `Dfun`, `ml` and `mu` options of odeint.
def func(y, t, c):
return c.dot(y)
def jac(y, t, c):
return c
def jac_transpose(y, t, c):
return c.T.copy(order='C')
def bjac_rows(y, t, c):
jac = np.row_stack((np.r_[0, np.diag(c, 1)],
np.diag(c),
np.r_[np.diag(c, -1), 0],
np.r_[np.diag(c, -2), 0, 0]))
return jac
def bjac_cols(y, t, c):
return bjac_rows(y, t, c).T.copy(order='C')
c = array([[-205, 0.01, 0.00, 0.0],
[0.1, -2.50, 0.02, 0.0],
[1e-3, 0.01, -2.0, 0.01],
[0.00, 0.00, 0.1, -1.0]])
y0 = np.ones(4)
t = np.array([0, 5, 10, 100])
# Use the full Jacobian.
sol1, info1 = odeint(func, y0, t, args=(c,), full_output=True,
atol=1e-13, rtol=1e-11, mxstep=10000,
Dfun=jac)
# Use the transposed full Jacobian, with col_deriv=True.
sol2, info2 = odeint(func, y0, t, args=(c,), full_output=True,
atol=1e-13, rtol=1e-11, mxstep=10000,
Dfun=jac_transpose, col_deriv=True)
# Use the banded Jacobian.
sol3, info3 = odeint(func, y0, t, args=(c,), full_output=True,
atol=1e-13, rtol=1e-11, mxstep=10000,
Dfun=bjac_rows, ml=2, mu=1)
# Use the transposed banded Jacobian, with col_deriv=True.
sol4, info4 = odeint(func, y0, t, args=(c,), full_output=True,
atol=1e-13, rtol=1e-11, mxstep=10000,
Dfun=bjac_cols, ml=2, mu=1, col_deriv=True)
assert_allclose(sol1, sol2, err_msg="sol1 != sol2")
assert_allclose(sol1, sol3, atol=1e-12, err_msg="sol1 != sol3")
assert_allclose(sol3, sol4, err_msg="sol3 != sol4")
# Verify that the number of jacobian evaluations was the same for the
# calls of odeint with a full jacobian and with a banded jacobian. This is
# a regression test--there was a bug in the handling of banded jacobians
# that resulted in an incorrect jacobian matrix being passed to the LSODA
# code. That would cause errors or excessive jacobian evaluations.
assert_array_equal(info1['nje'], info2['nje'])
assert_array_equal(info3['nje'], info4['nje'])
def test_odeint_errors():
def sys1d(x, t):
return -100*x
def bad1(x, t):
return 1.0/0
def bad2(x, t):
return "foo"
def bad_jac1(x, t):
return 1.0/0
def bad_jac2(x, t):
return [["foo"]]
def sys2d(x, t):
return [-100*x[0], -0.1*x[1]]
def sys2d_bad_jac(x, t):
return [[1.0/0, 0], [0, -0.1]]
assert_raises(ZeroDivisionError, odeint, bad1, 1.0, [0, 1])
assert_raises(ValueError, odeint, bad2, 1.0, [0, 1])
assert_raises(ZeroDivisionError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac1)
assert_raises(ValueError, odeint, sys1d, 1.0, [0, 1], Dfun=bad_jac2)
assert_raises(ZeroDivisionError, odeint, sys2d, [1.0, 1.0], [0, 1],
Dfun=sys2d_bad_jac)
def test_odeint_bad_shapes():
# Tests of some errors that can occur with odeint.
def badrhs(x, t):
return [1, -1]
def sys1(x, t):
return -100*x
def badjac(x, t):
return [[0, 0, 0]]
# y0 must be at most 1-d.
bad_y0 = [[0, 0], [0, 0]]
assert_raises(ValueError, odeint, sys1, bad_y0, [0, 1])
# t must be at most 1-d.
bad_t = [[0, 1], [2, 3]]
assert_raises(ValueError, odeint, sys1, [10.0], bad_t)
# y0 is 10, but badrhs(x, t) returns [1, -1].
assert_raises(RuntimeError, odeint, badrhs, 10, [0, 1])
# shape of array returned by badjac(x, t) is not correct.
assert_raises(RuntimeError, odeint, sys1, [10, 10], [0, 1], Dfun=badjac)
if __name__ == "__main__":
run_module_suite()
|
bsd-3-clause
|
mlperf/training_results_v0.6
|
NVIDIA/benchmarks/minigo/implementations/tensorflow/minigo/go.py
|
3
|
19698
|
# Copyright 2018 Google LLC
#
# 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.
"""
A board is a NxN numpy array.
A Coordinate is a tuple index into the board.
A Move is a (Coordinate c | None).
A PlayerMove is a (Color, Move) tuple
(0, 0) is considered to be the upper left corner of the board, and (18, 0) is the lower left.
"""
from collections import namedtuple
import copy
import itertools
import numpy as np
import os
import coords
N = int(os.environ.get('BOARD_SIZE', 19))
# Represent a board as a numpy array, with 0 empty, 1 is black, -1 is white.
# This means that swapping colors is as simple as multiplying array by -1.
WHITE, EMPTY, BLACK, FILL, KO, UNKNOWN = range(-1, 5)
# Represents "group not found" in the LibertyTracker object
MISSING_GROUP_ID = -1
ALL_COORDS = [(i, j) for i in range(N) for j in range(N)]
EMPTY_BOARD = np.zeros([N, N], dtype=np.int8)
def _check_bounds(c):
return 0 <= c[0] < N and 0 <= c[1] < N
NEIGHBORS = {(x, y): list(filter(_check_bounds, [
(x+1, y), (x-1, y), (x, y+1), (x, y-1)])) for x, y in ALL_COORDS}
DIAGONALS = {(x, y): list(filter(_check_bounds, [
(x+1, y+1), (x+1, y-1), (x-1, y+1), (x-1, y-1)])) for x, y in ALL_COORDS}
class IllegalMove(Exception):
pass
class PlayerMove(namedtuple('PlayerMove', ['color', 'move'])):
pass
class PositionWithContext(namedtuple('SgfPosition', ['position', 'next_move', 'result'])):
pass
def place_stones(board, color, stones):
for s in stones:
board[s] = color
def replay_position(position, result):
"""
Wrapper for a go.Position which replays its history.
Assumes an empty start position! (i.e. no handicap, and history must be exhaustive.)
Result must be passed in, since a resign cannot be inferred from position
history alone.
for position_w_context in replay_position(position):
print(position_w_context.position)
"""
assert position.n == len(position.recent), "Position history is incomplete"
pos = Position(komi=position.komi)
for player_move in position.recent:
color, next_move = player_move
yield PositionWithContext(pos, next_move, result)
pos = pos.play_move(next_move, color=color)
def find_reached(board, c):
color = board[c]
chain = set([c])
reached = set()
frontier = [c]
while frontier:
current = frontier.pop()
chain.add(current)
for n in NEIGHBORS[current]:
if board[n] == color and n not in chain:
frontier.append(n)
elif board[n] != color:
reached.add(n)
return chain, reached
def is_koish(board, c):
'Check if c is surrounded on all sides by 1 color, and return that color'
if board[c] != EMPTY:
return None
neighbors = {board[n] for n in NEIGHBORS[c]}
if len(neighbors) == 1 and EMPTY not in neighbors:
return list(neighbors)[0]
else:
return None
def is_eyeish(board, c):
'Check if c is an eye, for the purpose of restricting MC rollouts.'
# pass is fine.
if c is None:
return
color = is_koish(board, c)
if color is None:
return None
diagonal_faults = 0
diagonals = DIAGONALS[c]
if len(diagonals) < 4:
diagonal_faults += 1
for d in diagonals:
if not board[d] in (color, EMPTY):
diagonal_faults += 1
if diagonal_faults > 1:
return None
else:
return color
class Group(namedtuple('Group', ['id', 'stones', 'liberties', 'color'])):
"""
stones: a frozenset of Coordinates belonging to this group
liberties: a frozenset of Coordinates that are empty and adjacent to this group.
color: color of this group
"""
def __eq__(self, other):
return self.stones == other.stones and self.liberties == other.liberties and self.color == other.color
class LibertyTracker():
@staticmethod
def from_board(board):
board = np.copy(board)
curr_group_id = 0
lib_tracker = LibertyTracker()
for color in (WHITE, BLACK):
while color in board:
curr_group_id += 1
found_color = np.where(board == color)
coord = found_color[0][0], found_color[1][0]
chain, reached = find_reached(board, coord)
liberties = frozenset(r for r in reached if board[r] == EMPTY)
new_group = Group(curr_group_id, frozenset(
chain), liberties, color)
lib_tracker.groups[curr_group_id] = new_group
for s in chain:
lib_tracker.group_index[s] = curr_group_id
place_stones(board, FILL, chain)
lib_tracker.max_group_id = curr_group_id
liberty_counts = np.zeros([N, N], dtype=np.uint8)
for group in lib_tracker.groups.values():
num_libs = len(group.liberties)
for s in group.stones:
liberty_counts[s] = num_libs
lib_tracker.liberty_cache = liberty_counts
return lib_tracker
def __init__(self, group_index=None, groups=None, liberty_cache=None, max_group_id=1):
# group_index: a NxN numpy array of group_ids. -1 means no group
# groups: a dict of group_id to groups
# liberty_cache: a NxN numpy array of liberty counts
self.group_index = group_index if group_index is not None else - \
np.ones([N, N], dtype=np.int32)
self.groups = groups or {}
self.liberty_cache = liberty_cache if liberty_cache is not None else np.zeros([
N, N], dtype=np.uint8)
self.max_group_id = max_group_id
def __deepcopy__(self, memodict={}):
new_group_index = np.copy(self.group_index)
new_lib_cache = np.copy(self.liberty_cache)
# shallow copy
new_groups = copy.copy(self.groups)
return LibertyTracker(new_group_index, new_groups, liberty_cache=new_lib_cache, max_group_id=self.max_group_id)
def add_stone(self, color, c):
assert self.group_index[c] == MISSING_GROUP_ID
captured_stones = set()
opponent_neighboring_group_ids = set()
friendly_neighboring_group_ids = set()
empty_neighbors = set()
for n in NEIGHBORS[c]:
neighbor_group_id = self.group_index[n]
if neighbor_group_id != MISSING_GROUP_ID:
neighbor_group = self.groups[neighbor_group_id]
if neighbor_group.color == color:
friendly_neighboring_group_ids.add(neighbor_group_id)
else:
opponent_neighboring_group_ids.add(neighbor_group_id)
else:
empty_neighbors.add(n)
new_group = self._merge_from_played(
color, c, empty_neighbors, friendly_neighboring_group_ids)
# new_group becomes stale as _update_liberties and
# _handle_captures are called; must refetch with self.groups[new_group.id]
for group_id in opponent_neighboring_group_ids:
neighbor_group = self.groups[group_id]
if len(neighbor_group.liberties) == 1:
captured = self._capture_group(group_id)
captured_stones.update(captured)
else:
self._update_liberties(group_id, remove={c})
self._handle_captures(captured_stones)
# suicide is illegal
if len(self.groups[new_group.id].liberties) == 0:
raise IllegalMove("Move at {} would commit suicide!\n".format(c))
return captured_stones
def _merge_from_played(self, color, played, libs, other_group_ids):
stones = {played}
liberties = set(libs)
for group_id in other_group_ids:
other = self.groups.pop(group_id)
stones.update(other.stones)
liberties.update(other.liberties)
if other_group_ids:
liberties.remove(played)
assert stones.isdisjoint(liberties)
self.max_group_id += 1
result = Group(
self.max_group_id,
frozenset(stones),
frozenset(liberties),
color)
self.groups[result.id] = result
for s in result.stones:
self.group_index[s] = result.id
self.liberty_cache[s] = len(result.liberties)
return result
def _capture_group(self, group_id):
dead_group = self.groups.pop(group_id)
for s in dead_group.stones:
self.group_index[s] = MISSING_GROUP_ID
self.liberty_cache[s] = 0
return dead_group.stones
def _update_liberties(self, group_id, add=set(), remove=set()):
group = self.groups[group_id]
new_libs = (group.liberties | add) - remove
self.groups[group_id] = Group(
group_id, group.stones, new_libs, group.color)
new_lib_count = len(new_libs)
for s in self.groups[group_id].stones:
self.liberty_cache[s] = new_lib_count
def _handle_captures(self, captured_stones):
for s in captured_stones:
for n in NEIGHBORS[s]:
group_id = self.group_index[n]
if group_id != MISSING_GROUP_ID:
self._update_liberties(group_id, add={s})
class Position():
def __init__(self, board=None, n=0, komi=7.5, caps=(0, 0),
lib_tracker=None, ko=None, recent=tuple(),
board_deltas=None, to_play=BLACK):
"""
board: a numpy array
n: an int representing moves played so far
komi: a float, representing points given to the second player.
caps: a (int, int) tuple of captures for B, W.
lib_tracker: a LibertyTracker object
ko: a Move
recent: a tuple of PlayerMoves, such that recent[-1] is the last move.
board_deltas: a np.array of shape (n, go.N, go.N) representing changes
made to the board at each move (played move and captures).
Should satisfy next_pos.board - next_pos.board_deltas[0] == pos.board
to_play: BLACK or WHITE
"""
assert type(recent) is tuple
self.board = board if board is not None else np.copy(EMPTY_BOARD)
# With a full history, self.n == len(self.recent) == num moves played
self.n = n
self.komi = komi
self.caps = caps
self.lib_tracker = lib_tracker or LibertyTracker.from_board(self.board)
self.ko = ko
self.recent = recent
self.board_deltas = board_deltas if board_deltas is not None else np.zeros([
0, N, N], dtype=np.int8)
self.to_play = to_play
def __deepcopy__(self, memodict={}):
new_board = np.copy(self.board)
new_lib_tracker = copy.deepcopy(self.lib_tracker)
return Position(new_board, self.n, self.komi, self.caps, new_lib_tracker, self.ko, self.recent, self.board_deltas, self.to_play)
def __str__(self, colors=True):
if colors:
pretty_print_map = {
WHITE: '\x1b[0;31;47mO',
EMPTY: '\x1b[0;31;43m.',
BLACK: '\x1b[0;31;40mX',
FILL: '#',
KO: '*',
}
else:
pretty_print_map = {
WHITE: 'O',
EMPTY: '.',
BLACK: 'X',
FILL: '#',
KO: '*',
}
board = np.copy(self.board)
captures = self.caps
if self.ko is not None:
place_stones(board, KO, [self.ko])
raw_board_contents = []
for i in range(N):
row = []
for j in range(N):
appended = '<' if (self.recent and (i, j) ==
self.recent[-1].move) else ' '
row.append(pretty_print_map[board[i, j]] + appended)
if colors:
row.append('\x1b[0m')
raw_board_contents.append(''.join(row))
row_labels = ['%2d ' % i for i in range(N, 0, -1)]
annotated_board_contents = [''.join(r) for r in zip(
row_labels, raw_board_contents, row_labels)]
header_footer_rows = [
' ' + ' '.join('ABCDEFGHJKLMNOPQRST'[:N]) + ' ']
annotated_board = '\n'.join(itertools.chain(
header_footer_rows, annotated_board_contents, header_footer_rows))
details = "\nMove: {}. Captures X: {} O: {}\n".format(
self.n, *captures)
return annotated_board + details
def is_move_suicidal(self, move):
potential_libs = set()
for n in NEIGHBORS[move]:
neighbor_group_id = self.lib_tracker.group_index[n]
if neighbor_group_id == MISSING_GROUP_ID:
# at least one liberty after playing here, so not a suicide
return False
neighbor_group = self.lib_tracker.groups[neighbor_group_id]
if neighbor_group.color == self.to_play:
potential_libs |= neighbor_group.liberties
elif len(neighbor_group.liberties) == 1:
# would capture an opponent group if they only had one lib.
return False
# it's possible to suicide by connecting several friendly groups
# each of which had one liberty.
potential_libs -= set([move])
return not potential_libs
def is_move_legal(self, move):
'Checks that a move is on an empty space, not on ko, and not suicide'
if move is None:
return True
if self.board[move] != EMPTY:
return False
if move == self.ko:
return False
if self.is_move_suicidal(move):
return False
return True
def all_legal_moves(self):
'Returns a np.array of size go.N**2 + 1, with 1 = legal, 0 = illegal'
# by default, every move is legal
legal_moves = np.ones([N, N], dtype=np.int8)
# ...unless there is already a stone there
legal_moves[self.board != EMPTY] = 0
# calculate which spots have 4 stones next to them
# padding is because the edge always counts as a lost liberty.
adjacent = np.ones([N + 2, N + 2], dtype=np.int8)
adjacent[1:-1, 1:-1] = np.abs(self.board)
num_adjacent_stones = (adjacent[:-2, 1:-1] + adjacent[1:-1, :-2] +
adjacent[2:, 1:-1] + adjacent[1:-1, 2:])
# Surrounded spots are those that are empty and have 4 adjacent stones.
surrounded_spots = np.multiply(
(self.board == EMPTY),
(num_adjacent_stones == 4))
# Such spots are possibly illegal, unless they are capturing something.
# Iterate over and manually check each spot.
for coord in np.transpose(np.nonzero(surrounded_spots)):
if self.is_move_suicidal(tuple(coord)):
legal_moves[tuple(coord)] = 0
# ...and retaking ko is always illegal
if self.ko is not None:
legal_moves[self.ko] = 0
# and pass is always legal
return np.concatenate([legal_moves.ravel(), [1]])
def pass_move(self, mutate=False):
pos = self if mutate else copy.deepcopy(self)
pos.n += 1
pos.recent += (PlayerMove(pos.to_play, None),)
pos.board_deltas = np.concatenate((
np.zeros([1, N, N], dtype=np.int8),
pos.board_deltas[:6]))
pos.to_play *= -1
pos.ko = None
return pos
def flip_playerturn(self, mutate=False):
pos = self if mutate else copy.deepcopy(self)
pos.ko = None
pos.to_play *= -1
return pos
def get_liberties(self):
return self.lib_tracker.liberty_cache
def play_move(self, c, color=None, mutate=False):
# Obeys CGOS Rules of Play. In short:
# No suicides
# Chinese/area scoring
# Positional superko (this is very crudely approximate at the moment.)
if color is None:
color = self.to_play
pos = self if mutate else copy.deepcopy(self)
if c is None:
pos = pos.pass_move(mutate=mutate)
return pos
if not self.is_move_legal(c):
raise IllegalMove("{} move at {} is illegal: \n{}".format(
"Black" if self.to_play == BLACK else "White",
coords.to_gtp(c), self))
potential_ko = is_koish(self.board, c)
place_stones(pos.board, color, [c])
captured_stones = pos.lib_tracker.add_stone(color, c)
place_stones(pos.board, EMPTY, captured_stones)
opp_color = color * -1
new_board_delta = np.zeros([N, N], dtype=np.int8)
new_board_delta[c] = color
place_stones(new_board_delta, color, captured_stones)
if len(captured_stones) == 1 and potential_ko == opp_color:
new_ko = list(captured_stones)[0]
else:
new_ko = None
if pos.to_play == BLACK:
new_caps = (pos.caps[0] + len(captured_stones), pos.caps[1])
else:
new_caps = (pos.caps[0], pos.caps[1] + len(captured_stones))
pos.n += 1
pos.caps = new_caps
pos.ko = new_ko
pos.recent += (PlayerMove(color, c),)
# keep a rolling history of last 7 deltas - that's all we'll need to
# extract the last 8 board states.
pos.board_deltas = np.concatenate((
new_board_delta.reshape(1, N, N),
pos.board_deltas[:6]))
pos.to_play *= -1
return pos
def is_game_over(self):
return (len(self.recent) >= 2 and
self.recent[-1].move is None and
self.recent[-2].move is None)
def score(self):
'Return score from B perspective. If W is winning, score is negative.'
working_board = np.copy(self.board)
while EMPTY in working_board:
unassigned_spaces = np.where(working_board == EMPTY)
c = unassigned_spaces[0][0], unassigned_spaces[1][0]
territory, borders = find_reached(working_board, c)
border_colors = set(working_board[b] for b in borders)
X_border = BLACK in border_colors
O_border = WHITE in border_colors
if X_border and not O_border:
territory_color = BLACK
elif O_border and not X_border:
territory_color = WHITE
else:
territory_color = UNKNOWN # dame, or seki
place_stones(working_board, territory_color, territory)
return np.count_nonzero(working_board == BLACK) - np.count_nonzero(working_board == WHITE) - self.komi
def result(self):
score = self.score()
if score > 0:
return 1
elif score < 0:
return -1
else:
return 0
def result_string(self):
score = self.score()
if score > 0:
return 'B+' + '%.1f' % score
elif score < 0:
return 'W+' + '%.1f' % abs(score)
else:
return 'DRAW'
|
apache-2.0
|
CryptopiaNZ/DOT
|
contrib/testgen/gen_base58_test_vectors.py
|
1000
|
4343
|
#!/usr/bin/env python
'''
Generate valid and invalid base58 address and private key test vectors.
Usage:
gen_base58_test_vectors.py valid 50 > ../../src/test/data/base58_keys_valid.json
gen_base58_test_vectors.py invalid 50 > ../../src/test/data/base58_keys_invalid.json
'''
# 2012 Wladimir J. van der Laan
# Released under MIT License
import os
from itertools import islice
from base58 import b58encode, b58decode, b58encode_chk, b58decode_chk, b58chars
import random
from binascii import b2a_hex
# key types
PUBKEY_ADDRESS = 0
SCRIPT_ADDRESS = 5
PUBKEY_ADDRESS_TEST = 111
SCRIPT_ADDRESS_TEST = 196
PRIVKEY = 128
PRIVKEY_TEST = 239
metadata_keys = ['isPrivkey', 'isTestnet', 'addrType', 'isCompressed']
# templates for valid sequences
templates = [
# prefix, payload_size, suffix, metadata
# None = N/A
((PUBKEY_ADDRESS,), 20, (), (False, False, 'pubkey', None)),
((SCRIPT_ADDRESS,), 20, (), (False, False, 'script', None)),
((PUBKEY_ADDRESS_TEST,), 20, (), (False, True, 'pubkey', None)),
((SCRIPT_ADDRESS_TEST,), 20, (), (False, True, 'script', None)),
((PRIVKEY,), 32, (), (True, False, None, False)),
((PRIVKEY,), 32, (1,), (True, False, None, True)),
((PRIVKEY_TEST,), 32, (), (True, True, None, False)),
((PRIVKEY_TEST,), 32, (1,), (True, True, None, True))
]
def is_valid(v):
'''Check vector v for validity'''
result = b58decode_chk(v)
if result is None:
return False
valid = False
for template in templates:
prefix = str(bytearray(template[0]))
suffix = str(bytearray(template[2]))
if result.startswith(prefix) and result.endswith(suffix):
if (len(result) - len(prefix) - len(suffix)) == template[1]:
return True
return False
def gen_valid_vectors():
'''Generate valid test vectors'''
while True:
for template in templates:
prefix = str(bytearray(template[0]))
payload = os.urandom(template[1])
suffix = str(bytearray(template[2]))
rv = b58encode_chk(prefix + payload + suffix)
assert is_valid(rv)
metadata = dict([(x,y) for (x,y) in zip(metadata_keys,template[3]) if y is not None])
yield (rv, b2a_hex(payload), metadata)
def gen_invalid_vector(template, corrupt_prefix, randomize_payload_size, corrupt_suffix):
'''Generate possibly invalid vector'''
if corrupt_prefix:
prefix = os.urandom(1)
else:
prefix = str(bytearray(template[0]))
if randomize_payload_size:
payload = os.urandom(max(int(random.expovariate(0.5)), 50))
else:
payload = os.urandom(template[1])
if corrupt_suffix:
suffix = os.urandom(len(template[2]))
else:
suffix = str(bytearray(template[2]))
return b58encode_chk(prefix + payload + suffix)
def randbool(p = 0.5):
'''Return True with P(p)'''
return random.random() < p
def gen_invalid_vectors():
'''Generate invalid test vectors'''
# start with some manual edge-cases
yield "",
yield "x",
while True:
# kinds of invalid vectors:
# invalid prefix
# invalid payload length
# invalid (randomized) suffix (add random data)
# corrupt checksum
for template in templates:
val = gen_invalid_vector(template, randbool(0.2), randbool(0.2), randbool(0.2))
if random.randint(0,10)<1: # line corruption
if randbool(): # add random character to end
val += random.choice(b58chars)
else: # replace random character in the middle
n = random.randint(0, len(val))
val = val[0:n] + random.choice(b58chars) + val[n+1:]
if not is_valid(val):
yield val,
if __name__ == '__main__':
import sys, json
iters = {'valid':gen_valid_vectors, 'invalid':gen_invalid_vectors}
try:
uiter = iters[sys.argv[1]]
except IndexError:
uiter = gen_valid_vectors
try:
count = int(sys.argv[2])
except IndexError:
count = 0
data = list(islice(uiter(), count))
json.dump(data, sys.stdout, sort_keys=True, indent=4)
sys.stdout.write('\n')
|
mit
|
SteveHNH/ansible
|
lib/ansible/modules/cloud/openstack/os_user_role.py
|
19
|
6456
|
#!/usr/bin/python
# Copyright (c) 2016 IBM
#
# This module is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This software is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this software. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: os_user_role
short_description: Associate OpenStack Identity users and roles
extends_documentation_fragment: openstack
author: "Monty Taylor (@emonty), David Shrewsbury (@Shrews)"
version_added: "2.1"
description:
- Grant and revoke roles in either project or domain context for
OpenStack Identity Users.
options:
role:
description:
- Name or ID for the role.
required: true
user:
description:
- Name or ID for the user. If I(user) is not specified, then
I(group) is required. Both may not be specified.
required: false
default: null
group:
description:
- Name or ID for the group. Valid only with keystone version 3.
If I(group) is not specified, then I(user) is required. Both
may not be specified.
required: false
default: null
project:
description:
- Name or ID of the project to scope the role association to.
If you are using keystone version 2, then this value is required.
required: false
default: null
domain:
description:
- ID of the domain to scope the role association to. Valid only with
keystone version 3, and required if I(project) is not specified.
required: false
default: null
state:
description:
- Should the roles be present or absent on the user.
choices: [present, absent]
default: present
availability_zone:
description:
- Ignored. Present for backwards compatibility
required: false
requirements:
- "python >= 2.6"
- "shade"
'''
EXAMPLES = '''
# Grant an admin role on the user admin in the project project1
- os_user_role:
cloud: mycloud
user: admin
role: admin
project: project1
# Revoke the admin role from the user barney in the newyork domain
- os_user_role:
cloud: mycloud
state: absent
user: barney
role: admin
domain: newyork
'''
RETURN = '''
#
'''
try:
import shade
HAS_SHADE = True
except ImportError:
HAS_SHADE = False
from distutils.version import StrictVersion
def _system_state_change(state, assignment):
if state == 'present' and not assignment:
return True
elif state == 'absent' and assignment:
return True
return False
def _build_kwargs(user, group, project, domain):
kwargs = {}
if user:
kwargs['user'] = user
if group:
kwargs['group'] = group
if project:
kwargs['project'] = project
if domain:
kwargs['domain'] = domain
return kwargs
def main():
argument_spec = openstack_full_argument_spec(
role=dict(required=True),
user=dict(required=False),
group=dict(required=False),
project=dict(required=False),
domain=dict(required=False),
state=dict(default='present', choices=['absent', 'present']),
)
module_kwargs = openstack_module_kwargs(
required_one_of=[
['user', 'group']
])
module = AnsibleModule(argument_spec,
supports_check_mode=True,
**module_kwargs)
# role grant/revoke API introduced in 1.5.0
if not HAS_SHADE or (StrictVersion(shade.__version__) < StrictVersion('1.5.0')):
module.fail_json(msg='shade 1.5.0 or higher is required for this module')
role = module.params.pop('role')
user = module.params.pop('user')
group = module.params.pop('group')
project = module.params.pop('project')
domain = module.params.pop('domain')
state = module.params.pop('state')
try:
cloud = shade.operator_cloud(**module.params)
filters = {}
r = cloud.get_role(role)
if r is None:
module.fail_json(msg="Role %s is not valid" % role)
filters['role'] = r['id']
if user:
u = cloud.get_user(user)
if u is None:
module.fail_json(msg="User %s is not valid" % user)
filters['user'] = u['id']
if group:
g = cloud.get_group(group)
if g is None:
module.fail_json(msg="Group %s is not valid" % group)
filters['group'] = g['id']
if domain:
d = cloud.get_domain(domain)
if d is None:
module.fail_json(msg="Domain %s is not valid" % domain)
filters['domain'] = d['id']
if project:
if domain:
p = cloud.get_project(project, domain_id=filters['domain'])
else:
p = cloud.get_project(project)
if p is None:
module.fail_json(msg="Project %s is not valid" % project)
filters['project'] = p['id']
assignment = cloud.list_role_assignments(filters=filters)
if module.check_mode:
module.exit_json(changed=_system_state_change(state, assignment))
changed = False
if state == 'present':
if not assignment:
kwargs = _build_kwargs(user, group, project, domain)
cloud.grant_role(role, **kwargs)
changed = True
elif state == 'absent':
if assignment:
kwargs = _build_kwargs(user, group, project, domain)
cloud.revoke_role(role, **kwargs)
changed=True
module.exit_json(changed=changed)
except shade.OpenStackCloudException as e:
module.fail_json(msg=str(e))
from ansible.module_utils.basic import *
from ansible.module_utils.openstack import *
if __name__ == '__main__':
main()
|
gpl-3.0
|
hanselke/erpnext-1
|
erpnext/controllers/trends.py
|
52
|
10972
|
# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
# License: GNU General Public License v3. See license.txt
from __future__ import unicode_literals
import frappe
from frappe.utils import getdate
from frappe import _
def get_columns(filters, trans):
validate_filters(filters)
# get conditions for based_on filter cond
based_on_details = based_wise_columns_query(filters.get("based_on"), trans)
# get conditions for periodic filter cond
period_cols, period_select = period_wise_columns_query(filters, trans)
# get conditions for grouping filter cond
group_by_cols = group_wise_column(filters.get("group_by"))
columns = based_on_details["based_on_cols"] + period_cols + [_("Total(Qty)") + ":Float:120", _("Total(Amt)") + ":Currency:120"]
if group_by_cols:
columns = based_on_details["based_on_cols"] + group_by_cols + period_cols + \
[_("Total(Qty)") + ":Float:120", _("Total(Amt)") + ":Currency:120"]
conditions = {"based_on_select": based_on_details["based_on_select"], "period_wise_select": period_select,
"columns": columns, "group_by": based_on_details["based_on_group_by"], "grbc": group_by_cols, "trans": trans,
"addl_tables": based_on_details["addl_tables"], "addl_tables_relational_cond": based_on_details.get("addl_tables_relational_cond", "")}
return conditions
def validate_filters(filters):
for f in ["Fiscal Year", "Based On", "Period", "Company"]:
if not filters.get(f.lower().replace(" ", "_")):
frappe.throw(_("{0} is mandatory").format(f))
if not frappe.db.exists("Fiscal Year", filters.get("fiscal_year")):
frappe.throw(_("Fiscal Year: {0} does not exists").format(filters.get("fiscal_year")))
if filters.get("based_on") == filters.get("group_by"):
frappe.throw(_("'Based On' and 'Group By' can not be same"))
def get_data(filters, conditions):
data = []
inc, cond= '',''
query_details = conditions["based_on_select"] + conditions["period_wise_select"]
if conditions["based_on_select"] in ["t1.project_name,", "t2.project_name,"]:
cond = 'and '+ conditions["based_on_select"][:-1] +' IS Not NULL'
if filters.get("group_by"):
sel_col = ''
ind = conditions["columns"].index(conditions["grbc"][0])
if filters.get("group_by") == 'Item':
sel_col = 't2.item_code'
elif filters.get("group_by") == 'Customer':
sel_col = 't1.customer'
elif filters.get("group_by") == 'Supplier':
sel_col = 't1.supplier'
if filters.get('based_on') in ['Item','Customer','Supplier']:
inc = 2
else :
inc = 1
data1 = frappe.db.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s and
t1.docstatus = 1 %s %s
group by %s
""" % (query_details, conditions["trans"], conditions["trans"], conditions["addl_tables"], "%s",
"%s", conditions.get("addl_tables_relational_cond"), cond, conditions["group_by"]), (filters.get("company"),
filters["fiscal_year"]),as_list=1)
for d in range(len(data1)):
#to add blanck column
dt = data1[d]
dt.insert(ind,'')
data.append(dt)
#to get distinct value of col specified by group_by in filter
row = frappe.db.sql("""select DISTINCT(%s) from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s
and t1.docstatus = 1 and %s = %s %s
""" %
(sel_col, conditions["trans"], conditions["trans"], conditions["addl_tables"],
"%s", "%s", conditions["group_by"], "%s", conditions.get("addl_tables_relational_cond")),
(filters.get("company"), filters.get("fiscal_year"), data1[d][0]), as_list=1)
for i in range(len(row)):
des = ['' for q in range(len(conditions["columns"]))]
#get data for group_by filter
row1 = frappe.db.sql(""" select %s , %s from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s
and t1.docstatus = 1 and %s = %s and %s = %s %s
""" %
(sel_col, conditions["period_wise_select"], conditions["trans"],
conditions["trans"], conditions["addl_tables"], "%s", "%s", sel_col,
"%s", conditions["group_by"], "%s", conditions.get("addl_tables_relational_cond")),
(filters.get("company"), filters.get("fiscal_year"), row[i][0],
data1[d][0]), as_list=1)
des[ind] = row[i]
for j in range(1,len(conditions["columns"])-inc):
des[j+inc] = row1[0][j]
data.append(des)
else:
data = frappe.db.sql(""" select %s from `tab%s` t1, `tab%s Item` t2 %s
where t2.parent = t1.name and t1.company = %s and t1.fiscal_year = %s and
t1.docstatus = 1 %s %s
group by %s
""" %
(query_details, conditions["trans"], conditions["trans"], conditions["addl_tables"],
"%s", "%s", cond, conditions.get("addl_tables_relational_cond", ""), conditions["group_by"]),
(filters.get("company"), filters.get("fiscal_year")), as_list=1)
return data
def get_mon(dt):
return getdate(dt).strftime("%b")
def period_wise_columns_query(filters, trans):
query_details = ''
pwc = []
bet_dates = get_period_date_ranges(filters.get("period"), filters.get("fiscal_year"))
if trans in ['Purchase Receipt', 'Delivery Note', 'Purchase Invoice', 'Sales Invoice']:
trans_date = 'posting_date'
else:
trans_date = 'transaction_date'
if filters.get("period") != 'Yearly':
for dt in bet_dates:
get_period_wise_columns(dt, filters.get("period"), pwc)
query_details = get_period_wise_query(dt, trans_date, query_details)
else:
pwc = [_(filters.get("fiscal_year")) + " ("+_("Qty") + "):Float:120",
_(filters.get("fiscal_year")) + " ("+ _("Amt") + "):Currency:120"]
query_details = " SUM(t2.qty), SUM(t2.base_net_amount),"
query_details += 'SUM(t2.qty), SUM(t2.base_net_amount)'
return pwc, query_details
def get_period_wise_columns(bet_dates, period, pwc):
if period == 'Monthly':
pwc += [_(get_mon(bet_dates[0])) + " (" + _("Qty") + "):Float:120",
_(get_mon(bet_dates[0])) + " (" + _("Amt") + "):Currency:120"]
else:
pwc += [_(get_mon(bet_dates[0])) + "-" + _(get_mon(bet_dates[1])) + " (" + _("Qty") + "):Float:120",
_(get_mon(bet_dates[0])) + "-" + _(get_mon(bet_dates[1])) + " (" + _("Amt") + "):Currency:120"]
def get_period_wise_query(bet_dates, trans_date, query_details):
query_details += """SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.qty, NULL)),
SUM(IF(t1.%(trans_date)s BETWEEN '%(sd)s' AND '%(ed)s', t2.base_net_amount, NULL)),
""" % {"trans_date": trans_date, "sd": bet_dates[0],"ed": bet_dates[1]}
return query_details
@frappe.whitelist(allow_guest=True)
def get_period_date_ranges(period, fiscal_year=None, year_start_date=None):
from dateutil.relativedelta import relativedelta
if not year_start_date:
year_start_date, year_end_date = frappe.db.get_value("Fiscal Year",
fiscal_year, ["year_start_date", "year_end_date"])
increment = {
"Monthly": 1,
"Quarterly": 3,
"Half-Yearly": 6,
"Yearly": 12
}.get(period)
period_date_ranges = []
for i in xrange(1, 13, increment):
period_end_date = getdate(year_start_date) + relativedelta(months=increment, days=-1)
if period_end_date > getdate(year_end_date):
period_end_date = year_end_date
period_date_ranges.append([year_start_date, period_end_date])
year_start_date = period_end_date + relativedelta(days=1)
if period_end_date == year_end_date:
break
return period_date_ranges
def get_period_month_ranges(period, fiscal_year):
from dateutil.relativedelta import relativedelta
period_month_ranges = []
for start_date, end_date in get_period_date_ranges(period, fiscal_year):
months_in_this_period = []
while start_date <= end_date:
months_in_this_period.append(start_date.strftime("%B"))
start_date += relativedelta(months=1)
period_month_ranges.append(months_in_this_period)
return period_month_ranges
def based_wise_columns_query(based_on, trans):
based_on_details = {}
# based_on_cols, based_on_select, based_on_group_by, addl_tables
if based_on == "Item":
based_on_details["based_on_cols"] = ["Item:Link/Item:120", "Item Name:Data:120"]
based_on_details["based_on_select"] = "t2.item_code, t2.item_name,"
based_on_details["based_on_group_by"] = 't2.item_code'
based_on_details["addl_tables"] = ''
elif based_on == "Item Group":
based_on_details["based_on_cols"] = ["Item Group:Link/Item Group:120"]
based_on_details["based_on_select"] = "t2.item_group,"
based_on_details["based_on_group_by"] = 't2.item_group'
based_on_details["addl_tables"] = ''
elif based_on == "Customer":
based_on_details["based_on_cols"] = ["Customer:Link/Customer:120", "Territory:Link/Territory:120"]
based_on_details["based_on_select"] = "t1.customer_name, t1.territory, "
based_on_details["based_on_group_by"] = 't1.customer_name'
based_on_details["addl_tables"] = ''
elif based_on == "Customer Group":
based_on_details["based_on_cols"] = ["Customer Group:Link/Customer Group"]
based_on_details["based_on_select"] = "t1.customer_group,"
based_on_details["based_on_group_by"] = 't1.customer_group'
based_on_details["addl_tables"] = ''
elif based_on == 'Supplier':
based_on_details["based_on_cols"] = ["Supplier:Link/Supplier:120", "Supplier Type:Link/Supplier Type:140"]
based_on_details["based_on_select"] = "t1.supplier, t3.supplier_type,"
based_on_details["based_on_group_by"] = 't1.supplier'
based_on_details["addl_tables"] = ',`tabSupplier` t3'
based_on_details["addl_tables_relational_cond"] = " and t1.supplier = t3.name"
elif based_on == 'Supplier Type':
based_on_details["based_on_cols"] = ["Supplier Type:Link/Supplier Type:140"]
based_on_details["based_on_select"] = "t3.supplier_type,"
based_on_details["based_on_group_by"] = 't3.supplier_type'
based_on_details["addl_tables"] = ',`tabSupplier` t3'
based_on_details["addl_tables_relational_cond"] = " and t1.supplier = t3.name"
elif based_on == "Territory":
based_on_details["based_on_cols"] = ["Territory:Link/Territory:120"]
based_on_details["based_on_select"] = "t1.territory,"
based_on_details["based_on_group_by"] = 't1.territory'
based_on_details["addl_tables"] = ''
elif based_on == "Project":
if trans in ['Sales Invoice', 'Delivery Note', 'Sales Order']:
based_on_details["based_on_cols"] = ["Project:Link/Project:120"]
based_on_details["based_on_select"] = "t1.project_name,"
based_on_details["based_on_group_by"] = 't1.project_name'
based_on_details["addl_tables"] = ''
elif trans in ['Purchase Order', 'Purchase Invoice', 'Purchase Receipt']:
based_on_details["based_on_cols"] = ["Project:Link/Project:120"]
based_on_details["based_on_select"] = "t2.project_name,"
based_on_details["based_on_group_by"] = 't2.project_name'
based_on_details["addl_tables"] = ''
else:
frappe.throw(_("Project-wise data is not available for Quotation"))
return based_on_details
def group_wise_column(group_by):
if group_by:
return [group_by+":Link/"+group_by+":120"]
else:
return []
|
agpl-3.0
|
j0nathan33/CouchPotatoServer
|
couchpotato/core/media/movie/providers/trailer/youtube_dl/extractor/noco.py
|
8
|
3451
|
# encoding: utf-8
from __future__ import unicode_literals
import re
from .common import InfoExtractor
from ..utils import (
ExtractorError,
unified_strdate,
compat_str,
)
class NocoIE(InfoExtractor):
_VALID_URL = r'http://(?:(?:www\.)?noco\.tv/emission/|player\.noco\.tv/\?idvideo=)(?P<id>\d+)'
_TEST = {
'url': 'http://noco.tv/emission/11538/nolife/ami-ami-idol-hello-france/',
'md5': '0a993f0058ddbcd902630b2047ef710e',
'info_dict': {
'id': '11538',
'ext': 'mp4',
'title': 'Ami Ami Idol - Hello! France',
'description': 'md5:4eaab46ab68fa4197a317a88a53d3b86',
'upload_date': '20140412',
'uploader': 'Nolife',
'uploader_id': 'NOL',
'duration': 2851.2,
},
'skip': 'Requires noco account',
}
def _real_extract(self, url):
mobj = re.match(self._VALID_URL, url)
video_id = mobj.group('id')
medias = self._download_json(
'https://api.noco.tv/1.0/video/medias/%s' % video_id, video_id, 'Downloading video JSON')
formats = []
for fmt in medias['fr']['video_list']['default']['quality_list']:
format_id = fmt['quality_key']
file = self._download_json(
'https://api.noco.tv/1.0/video/file/%s/fr/%s' % (format_id.lower(), video_id),
video_id, 'Downloading %s video JSON' % format_id)
file_url = file['file']
if not file_url:
continue
if file_url == 'forbidden':
raise ExtractorError(
'%s returned error: %s - %s' % (
self.IE_NAME, file['popmessage']['title'], file['popmessage']['message']),
expected=True)
formats.append({
'url': file_url,
'format_id': format_id,
'width': fmt['res_width'],
'height': fmt['res_lines'],
'abr': fmt['audiobitrate'],
'vbr': fmt['videobitrate'],
'filesize': fmt['filesize'],
'format_note': fmt['quality_name'],
'preference': fmt['priority'],
})
self._sort_formats(formats)
show = self._download_json(
'https://api.noco.tv/1.0/shows/show/%s' % video_id, video_id, 'Downloading show JSON')[0]
upload_date = unified_strdate(show['indexed'])
uploader = show['partner_name']
uploader_id = show['partner_key']
duration = show['duration_ms'] / 1000.0
thumbnail = show['screenshot']
episode = show.get('show_TT') or show.get('show_OT')
family = show.get('family_TT') or show.get('family_OT')
episode_number = show.get('episode_number')
title = ''
if family:
title += family
if episode_number:
title += ' #' + compat_str(episode_number)
if episode:
title += ' - ' + episode
description = show.get('show_resume') or show.get('family_resume')
return {
'id': video_id,
'title': title,
'description': description,
'thumbnail': thumbnail,
'upload_date': upload_date,
'uploader': uploader,
'uploader_id': uploader_id,
'duration': duration,
'formats': formats,
}
|
gpl-3.0
|
arjen75/ics-lge-kernel-msm7x27-chick
|
scripts/rt-tester/rt-tester.py
|
1094
|
5362
|
#!/usr/bin/python
#
# rt-mutex tester
#
# (C) 2006 Thomas Gleixner <[email protected]>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
import os
import sys
import getopt
import shutil
import string
# Globals
quiet = 0
test = 0
comments = 0
sysfsprefix = "/sys/devices/system/rttest/rttest"
statusfile = "/status"
commandfile = "/command"
# Command opcodes
cmd_opcodes = {
"schedother" : "1",
"schedfifo" : "2",
"lock" : "3",
"locknowait" : "4",
"lockint" : "5",
"lockintnowait" : "6",
"lockcont" : "7",
"unlock" : "8",
"lockbkl" : "9",
"unlockbkl" : "10",
"signal" : "11",
"resetevent" : "98",
"reset" : "99",
}
test_opcodes = {
"prioeq" : ["P" , "eq" , None],
"priolt" : ["P" , "lt" , None],
"priogt" : ["P" , "gt" , None],
"nprioeq" : ["N" , "eq" , None],
"npriolt" : ["N" , "lt" , None],
"npriogt" : ["N" , "gt" , None],
"unlocked" : ["M" , "eq" , 0],
"trylock" : ["M" , "eq" , 1],
"blocked" : ["M" , "eq" , 2],
"blockedwake" : ["M" , "eq" , 3],
"locked" : ["M" , "eq" , 4],
"opcodeeq" : ["O" , "eq" , None],
"opcodelt" : ["O" , "lt" , None],
"opcodegt" : ["O" , "gt" , None],
"eventeq" : ["E" , "eq" , None],
"eventlt" : ["E" , "lt" , None],
"eventgt" : ["E" , "gt" , None],
}
# Print usage information
def usage():
print "rt-tester.py <-c -h -q -t> <testfile>"
print " -c display comments after first command"
print " -h help"
print " -q quiet mode"
print " -t test mode (syntax check)"
print " testfile: read test specification from testfile"
print " otherwise from stdin"
return
# Print progress when not in quiet mode
def progress(str):
if not quiet:
print str
# Analyse a status value
def analyse(val, top, arg):
intval = int(val)
if top[0] == "M":
intval = intval / (10 ** int(arg))
intval = intval % 10
argval = top[2]
elif top[0] == "O":
argval = int(cmd_opcodes.get(arg, arg))
else:
argval = int(arg)
# progress("%d %s %d" %(intval, top[1], argval))
if top[1] == "eq" and intval == argval:
return 1
if top[1] == "lt" and intval < argval:
return 1
if top[1] == "gt" and intval > argval:
return 1
return 0
# Parse the commandline
try:
(options, arguments) = getopt.getopt(sys.argv[1:],'chqt')
except getopt.GetoptError, ex:
usage()
sys.exit(1)
# Parse commandline options
for option, value in options:
if option == "-c":
comments = 1
elif option == "-q":
quiet = 1
elif option == "-t":
test = 1
elif option == '-h':
usage()
sys.exit(0)
# Select the input source
if arguments:
try:
fd = open(arguments[0])
except Exception,ex:
sys.stderr.write("File not found %s\n" %(arguments[0]))
sys.exit(1)
else:
fd = sys.stdin
linenr = 0
# Read the test patterns
while 1:
linenr = linenr + 1
line = fd.readline()
if not len(line):
break
line = line.strip()
parts = line.split(":")
if not parts or len(parts) < 1:
continue
if len(parts[0]) == 0:
continue
if parts[0].startswith("#"):
if comments > 1:
progress(line)
continue
if comments == 1:
comments = 2
progress(line)
cmd = parts[0].strip().lower()
opc = parts[1].strip().lower()
tid = parts[2].strip()
dat = parts[3].strip()
try:
# Test or wait for a status value
if cmd == "t" or cmd == "w":
testop = test_opcodes[opc]
fname = "%s%s%s" %(sysfsprefix, tid, statusfile)
if test:
print fname
continue
while 1:
query = 1
fsta = open(fname, 'r')
status = fsta.readline().strip()
fsta.close()
stat = status.split(",")
for s in stat:
s = s.strip()
if s.startswith(testop[0]):
# Seperate status value
val = s[2:].strip()
query = analyse(val, testop, dat)
break
if query or cmd == "t":
break
progress(" " + status)
if not query:
sys.stderr.write("Test failed in line %d\n" %(linenr))
sys.exit(1)
# Issue a command to the tester
elif cmd == "c":
cmdnr = cmd_opcodes[opc]
# Build command string and sys filename
cmdstr = "%s:%s" %(cmdnr, dat)
fname = "%s%s%s" %(sysfsprefix, tid, commandfile)
if test:
print fname
continue
fcmd = open(fname, 'w')
fcmd.write(cmdstr)
fcmd.close()
except Exception,ex:
sys.stderr.write(str(ex))
sys.stderr.write("\nSyntax error in line %d\n" %(linenr))
if not test:
fd.close()
sys.exit(1)
# Normal exit pass
print "Pass"
sys.exit(0)
|
gpl-2.0
|
lmazuel/azure-sdk-for-python
|
azure-batch/azure/batch/models/pool_enable_auto_scale_parameter.py
|
1
|
2432
|
# coding=utf-8
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
from msrest.serialization import Model
class PoolEnableAutoScaleParameter(Model):
"""Options for enabling automatic scaling on a pool.
:param auto_scale_formula: The formula for the desired number of compute
nodes in the pool. The formula is checked for validity before it is
applied to the pool. If the formula is not valid, the Batch service
rejects the request with detailed error information. For more information
about specifying this formula, see Automatically scale compute nodes in an
Azure Batch pool
(https://azure.microsoft.com/en-us/documentation/articles/batch-automatic-scaling).
:type auto_scale_formula: str
:param auto_scale_evaluation_interval: The time interval at which to
automatically adjust the pool size according to the autoscale formula. The
default value is 15 minutes. The minimum and maximum value are 5 minutes
and 168 hours respectively. If you specify a value less than 5 minutes or
greater than 168 hours, the Batch service rejects the request with an
invalid property value error; if you are calling the REST API directly,
the HTTP status code is 400 (Bad Request). If you specify a new interval,
then the existing autoscale evaluation schedule will be stopped and a new
autoscale evaluation schedule will be started, with its starting time
being the time when this request was issued.
:type auto_scale_evaluation_interval: timedelta
"""
_attribute_map = {
'auto_scale_formula': {'key': 'autoScaleFormula', 'type': 'str'},
'auto_scale_evaluation_interval': {'key': 'autoScaleEvaluationInterval', 'type': 'duration'},
}
def __init__(self, auto_scale_formula=None, auto_scale_evaluation_interval=None):
super(PoolEnableAutoScaleParameter, self).__init__()
self.auto_scale_formula = auto_scale_formula
self.auto_scale_evaluation_interval = auto_scale_evaluation_interval
|
mit
|
biddisco/VTK
|
Examples/Modelling/Python/iceCream.py
|
42
|
3209
|
#!/usr/bin/env python
# This example demonstrates how to use boolean combinations of implicit
# functions to create a model of an ice cream cone.
import vtk
from vtk.util.colors import chocolate, mint
# Create implicit function primitives. These have been carefully
# placed to give the effect that we want. We are going to use various
# combinations of these functions to create the shape we want; for
# example, we use planes intersected with a cone (which is infinite in
# extent) to get a finite cone.
cone = vtk.vtkCone()
cone.SetAngle(20)
vertPlane = vtk.vtkPlane()
vertPlane.SetOrigin(.1, 0, 0)
vertPlane.SetNormal(-1, 0, 0)
basePlane = vtk.vtkPlane()
basePlane.SetOrigin(1.2, 0, 0)
basePlane.SetNormal(1, 0, 0)
iceCream = vtk.vtkSphere()
iceCream.SetCenter(1.333, 0, 0)
iceCream.SetRadius(0.5)
bite = vtk.vtkSphere()
bite.SetCenter(1.5, 0, 0.5)
bite.SetRadius(0.25)
# Combine primitives to build ice-cream cone. Clip the cone with planes.
theCone = vtk.vtkImplicitBoolean()
theCone.SetOperationTypeToIntersection()
theCone.AddFunction(cone)
theCone.AddFunction(vertPlane)
theCone.AddFunction(basePlane)
# Take a bite out of the ice cream.
theCream = vtk.vtkImplicitBoolean()
theCream.SetOperationTypeToDifference()
theCream.AddFunction(iceCream)
theCream.AddFunction(bite)
# The sample function generates a distance function from the implicit
# function (which in this case is the cone). This is then contoured to
# get a polygonal surface.
theConeSample = vtk.vtkSampleFunction()
theConeSample.SetImplicitFunction(theCone)
theConeSample.SetModelBounds(-1, 1.5, -1.25, 1.25, -1.25, 1.25)
theConeSample.SetSampleDimensions(60, 60, 60)
theConeSample.ComputeNormalsOff()
theConeSurface = vtk.vtkContourFilter()
theConeSurface.SetInputConnection(theConeSample.GetOutputPort())
theConeSurface.SetValue(0, 0.0)
coneMapper = vtk.vtkPolyDataMapper()
coneMapper.SetInputConnection(theConeSurface.GetOutputPort())
coneMapper.ScalarVisibilityOff()
coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMapper)
coneActor.GetProperty().SetColor(chocolate)
# The same here for the ice cream.
theCreamSample = vtk.vtkSampleFunction()
theCreamSample.SetImplicitFunction(theCream)
theCreamSample.SetModelBounds(0, 2.5, -1.25, 1.25, -1.25, 1.25)
theCreamSample.SetSampleDimensions(60, 60, 60)
theCreamSample.ComputeNormalsOff()
theCreamSurface = vtk.vtkContourFilter()
theCreamSurface.SetInputConnection(theCreamSample.GetOutputPort())
theCreamSurface.SetValue(0, 0.0)
creamMapper = vtk.vtkPolyDataMapper()
creamMapper.SetInputConnection(theCreamSurface.GetOutputPort())
creamMapper.ScalarVisibilityOff()
creamActor = vtk.vtkActor()
creamActor.SetMapper(creamMapper)
creamActor.GetProperty().SetColor(mint)
# Create the usual rendering stuff
ren = vtk.vtkRenderer()
renWin = vtk.vtkRenderWindow()
renWin.AddRenderer(ren)
iren = vtk.vtkRenderWindowInteractor()
iren.SetRenderWindow(renWin)
# Add the actors to the renderer, set the background and size
ren.AddActor(coneActor)
ren.AddActor(creamActor)
ren.SetBackground(1, 1, 1)
renWin.SetSize(250, 250)
ren.ResetCamera()
ren.GetActiveCamera().Roll(90)
ren.GetActiveCamera().Dolly(1.5)
ren.ResetCameraClippingRange()
iren.Initialize()
renWin.Render()
iren.Start()
|
bsd-3-clause
|
tlainevool/eatspection
|
data/test/sql/test_restaurant_storage.py
|
1
|
1208
|
import unittest
import sqlite3
from data.db_creation.sql.restaurant_table_creator import RestaurantTableCreator
from data.sql.restaurant_storage import RestaurantStorage
from model.restaurant import Restaurant
class TestRestaurantStorage(unittest.TestCase):
def test_insert(self):
conn = sqlite3.connect(':memory:')
creator = RestaurantTableCreator(conn)
creator.create_tables()
storage = RestaurantStorage(conn)
restaurant = Restaurant(
'test_123',
"Joe's Crabshack",
city="Los Angeles",
state='CA')
storage.insert(restaurant)
actual = storage.get_by_id(restaurant.rid)
self.assertEqual(actual.rid, restaurant.rid)
self.assertEqual(actual.name, restaurant.name)
self.assertEqual(actual.address, restaurant.address)
self.assertEqual(actual.city, restaurant.city)
self.assertEqual(actual.state, restaurant.state)
self.assertEqual(actual.zip_code, restaurant.zip_code)
self.assertEqual(actual.latitude, restaurant.latitude)
self.assertEqual(actual.longitude, restaurant.longitude)
if __name__ == '__main__':
unittest.main()
|
mit
|
abdesslem/CTF
|
models.py
|
2
|
1692
|
from flask_login import LoginManager, UserMixin, login_user, logout_user, current_user, login_required
from werkzeug.security import generate_password_hash, check_password_hash
import ctf
class User(UserMixin, ctf.db.Model):
__tablename__ = 'users'
id = ctf.db.Column(ctf.db.Integer, primary_key=True)
username = ctf.db.Column(ctf.db.String(80), unique=True)
email = ctf.db.Column(ctf.db.String(80))
password_hash = ctf.db.Column(ctf.db.String(120))
school = ctf.db.Column(ctf.db.String(120))
score = ctf.db.Column(ctf.db.String(20))
solved = ctf.db.Column(ctf.db.String(400))
lastSubmit = ctf.db.Column(ctf.db.DateTime)
confirmed = ctf.db.Column(ctf.db.Boolean, nullable=False, default=False)
#timestamp=datetime.datetime.utcnow()
#def __init__(self, **kwargs):
# super(User, self).__init__(**kwargs)
@property
def password(self):
raise AttributeError('password is not a readable attribute')
@password.setter
def password(self, password):
self.password_hash = generate_password_hash(password)
def verify_password(self, password):
return check_password_hash(self.password_hash, password)
def __repr__(self):
return '<User %r>' % self.username
class Challenges(ctf.db.Model):
__tablename__ = 'challenges'
id = ctf.db.Column(ctf.db.Integer, primary_key=True)
name = ctf.db.Column(ctf.db.String(80), unique=True)
category = ctf.db.Column(ctf.db.String(80))
info = ctf.db.Column(ctf.db.String(800))
score = ctf.db.Column(ctf.db.String(20))
flag = ctf.db.Column(ctf.db.String(40))
def __repr__(self):
return '<Challenges %r>' % self.name
|
mit
|
kennethgillen/ansible
|
lib/ansible/modules/system/pam_limits.py
|
27
|
9407
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# (c) 2014, Sebastien Rohaut <[email protected]>
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
ANSIBLE_METADATA = {'metadata_version': '1.0',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: pam_limits
version_added: "2.0"
author:
- "Sebastien Rohaut (@usawa)"
short_description: Modify Linux PAM limits
description:
- The C(pam_limits) module modify PAM limits, default in /etc/security/limits.conf.
For the full documentation, see man limits.conf(5).
options:
domain:
description:
- A username, @groupname, wildcard, uid/gid range.
required: true
limit_type:
description:
- Limit type, see C(man limits) for an explanation
required: true
choices: [ "hard", "soft", "-" ]
limit_item:
description:
- The limit to be set
required: true
choices:
- "core"
- "data"
- "fsize"
- "memlock"
- "nofile"
- "rss"
- "stack"
- "cpu"
- "nproc"
- "as"
- "maxlogins"
- "maxsyslogins"
- "priority"
- "locks"
- "sigpending"
- "msgqueue"
- "nice"
- "rtprio"
- "chroot"
value:
description:
- The value of the limit.
required: true
backup:
description:
- Create a backup file including the timestamp information so you can get
the original file back if you somehow clobbered it incorrectly.
required: false
choices: [ "yes", "no" ]
default: "no"
use_min:
description:
- If set to C(yes), the minimal value will be used or conserved.
If the specified value is inferior to the value in the file, file content is replaced with the new value,
else content is not modified.
required: false
choices: [ "yes", "no" ]
default: "no"
use_max:
description:
- If set to C(yes), the maximal value will be used or conserved.
If the specified value is superior to the value in the file, file content is replaced with the new value,
else content is not modified.
required: false
choices: [ "yes", "no" ]
default: "no"
dest:
description:
- Modify the limits.conf path.
required: false
default: "/etc/security/limits.conf"
comment:
description:
- Comment associated with the limit.
required: false
default: ''
'''
EXAMPLES = '''
# Add or modify nofile soft limit for the user joe
- pam_limits:
domain: joe
limit_type: soft
limit_item: nofile
value: 64000
# Add or modify fsize hard limit for the user smith. Keep or set the maximal value.
- pam_limits:
domain: smith
limit_type: hard
limit_item: fsize
value: 1000000
use_max: yes
# Add or modify memlock, both soft and hard, limit for the user james with a comment.
- pam_limits:
domain: james
limit_type: '-'
limit_item: memlock
value: unlimited
comment: unlimited memory lock for james
'''
import os
import os.path
import shutil
import re
def main():
pam_items = ['core', 'data', 'fsize', 'memlock', 'nofile', 'rss', 'stack', 'cpu', 'nproc', 'as', 'maxlogins', 'maxsyslogins', 'priority', 'locks',
'sigpending', 'msgqueue', 'nice', 'rtprio', 'chroot']
pam_types = [ 'soft', 'hard', '-' ]
limits_conf = '/etc/security/limits.conf'
module = AnsibleModule(
# not checking because of daisy chain to file module
argument_spec = dict(
domain = dict(required=True, type='str'),
limit_type = dict(required=True, type='str', choices=pam_types),
limit_item = dict(required=True, type='str', choices=pam_items),
value = dict(required=True, type='str'),
use_max = dict(default=False, type='bool'),
use_min = dict(default=False, type='bool'),
backup = dict(default=False, type='bool'),
dest = dict(default=limits_conf, type='str'),
comment = dict(required=False, default='', type='str')
)
)
domain = module.params['domain']
limit_type = module.params['limit_type']
limit_item = module.params['limit_item']
value = module.params['value']
use_max = module.params['use_max']
use_min = module.params['use_min']
backup = module.params['backup']
limits_conf = module.params['dest']
new_comment = module.params['comment']
changed = False
if os.path.isfile(limits_conf):
if not os.access(limits_conf, os.W_OK):
module.fail_json(msg="%s is not writable. Use sudo" % (limits_conf) )
else:
module.fail_json(msg="%s is not visible (check presence, access rights, use sudo)" % (limits_conf) )
if use_max and use_min:
module.fail_json(msg="Cannot use use_min and use_max at the same time." )
if not (value in ['unlimited', 'infinity', '-1'] or value.isdigit()):
module.fail_json(msg="Argument 'value' can be one of 'unlimited', 'infinity', '-1' or positive number. Refer to manual pages for more details.")
# Backup
if backup:
backup_file = module.backup_local(limits_conf)
space_pattern = re.compile(r'\s+')
message = ''
f = open (limits_conf, 'r')
# Tempfile
nf = tempfile.NamedTemporaryFile()
found = False
new_value = value
for line in f:
if line.startswith('#'):
nf.write(line)
continue
newline = re.sub(space_pattern, ' ', line).strip()
if not newline:
nf.write(line)
continue
# Remove comment in line
newline = newline.split('#',1)[0]
try:
old_comment = line.split('#',1)[1]
except:
old_comment = ''
newline = newline.rstrip()
if not new_comment:
new_comment = old_comment
if new_comment:
new_comment = "\t#"+new_comment
line_fields = newline.split(' ')
if len(line_fields) != 4:
nf.write(line)
continue
line_domain = line_fields[0]
line_type = line_fields[1]
line_item = line_fields[2]
actual_value = line_fields[3]
if not (actual_value in ['unlimited', 'infinity', '-1'] or actual_value.isdigit()):
module.fail_json(msg="Invalid configuration of '%s'. Current value of %s is unsupported." % (limits_conf, line_item))
# Found the line
if line_domain == domain and line_type == limit_type and line_item == limit_item:
found = True
if value == actual_value:
message = line
nf.write(line)
continue
actual_value_unlimited = actual_value in ['unlimited', 'infinity', '-1']
value_unlimited = value in ['unlimited', 'infinity', '-1']
if use_max:
if value.isdigit() and actual_value.isdigit():
new_value = str(max(int(value), int(actual_value)))
elif actual_value_unlimited:
new_value = actual_value
else:
new_value = value
if use_min:
if value.isdigit() and actual_value.isdigit():
new_value = str(min(int(value), int(actual_value)))
elif value_unlimited:
new_value = actual_value
else:
new_value = value
# Change line only if value has changed
if new_value != actual_value:
changed = True
new_limit = domain + "\t" + limit_type + "\t" + limit_item + "\t" + new_value + new_comment + "\n"
message = new_limit
nf.write(new_limit)
else:
message = line
nf.write(line)
else:
nf.write(line)
if not found:
changed = True
new_limit = domain + "\t" + limit_type + "\t" + limit_item + "\t" + new_value + new_comment + "\n"
message = new_limit
nf.write(new_limit)
f.close()
nf.flush()
# Copy tempfile to newfile
module.atomic_move(nf.name, f.name)
try:
nf.close()
except:
pass
res_args = dict(
changed = changed, msg = message
)
if backup:
res_args['backup_file'] = backup_file
module.exit_json(**res_args)
# import module snippets
from ansible.module_utils.basic import *
if __name__ == '__main__':
main()
|
gpl-3.0
|
qdubious/gitinspector
|
gitinspector/config.py
|
51
|
2939
|
# coding: utf-8
#
# Copyright © 2013 Ejwa Software. All rights reserved.
#
# This file is part of gitinspector.
#
# gitinspector is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# gitinspector is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with gitinspector. If not, see <http://www.gnu.org/licenses/>.
from __future__ import unicode_literals
import extensions
import filtering
import format
import interval
import optval
import os
import subprocess
def __read_git_config__(repo, variable):
previous_directory = os.getcwd()
os.chdir(repo)
setting = subprocess.Popen("git config inspector." + variable, shell=True, bufsize=1,
stdout=subprocess.PIPE).stdout
os.chdir(previous_directory)
try:
setting = setting.readlines()[0]
setting = setting.decode("utf-8", "replace").strip()
except IndexError:
setting = ""
return setting
def __read_git_config_bool__(repo, variable):
try:
variable = __read_git_config__(repo, variable)
return optval.get_boolean_argument(False if variable == "" else variable)
except optval.InvalidOptionArgument:
return False
def __read_git_config_string__(repo, variable):
string = __read_git_config__(repo, variable)
return (True, string) if len(string) > 0 else (False, None)
def init(run):
var = __read_git_config_string__(run.repo, "file-types")
if var[0]:
extensions.define(var[1])
var = __read_git_config_string__(run.repo, "exclude")
if var[0]:
filtering.add(var[1])
var = __read_git_config_string__(run.repo, "format")
if var[0] and not format.select(var[1]):
raise format.InvalidFormatError(_("specified output format not supported."))
run.hard = __read_git_config_bool__(run.repo, "hard")
run.list_file_types = __read_git_config_bool__(run.repo, "list-file-types")
run.localize_output = __read_git_config_bool__(run.repo, "localize-output")
run.metrics = __read_git_config_bool__(run.repo, "metrics")
run.responsibilities = __read_git_config_bool__(run.repo, "responsibilities")
run.useweeks = __read_git_config_bool__(run.repo, "weeks")
var = __read_git_config_string__(run.repo, "since")
if var[0]:
interval.set_since(var[1])
var = __read_git_config_string__(run.repo, "until")
if var[0]:
interval.set_until(var[1])
run.timeline = __read_git_config_bool__(run.repo, "timeline")
if __read_git_config_bool__(run.repo, "grading"):
run.hard = True
run.list_file_types = True
run.metrics = True
run.responsibilities = True
run.timeline = True
run.useweeks = True
|
gpl-3.0
|
benoit-pierre/mcomix
|
mcomix/run.py
|
1
|
10893
|
import os
import sys
import optparse
import signal
if __name__ == '__main__':
print >> sys.stderr, 'PROGRAM TERMINATED'
print >> sys.stderr, 'Please do not run this script directly! Use mcomixstarter.py instead.'
sys.exit(1)
# These modules must not depend on GTK, pkg_resources, PIL,
# or any other optional libraries.
from mcomix import (
constants,
log,
portability,
preferences,
)
def wait_and_exit():
""" Wait for the user pressing ENTER before closing. This should help
the user find possibly missing dependencies when starting, since the
Python window will not close down immediately after the error. """
if sys.platform == 'win32' and not sys.stdin.closed and not sys.stdout.closed:
print
raw_input("Press ENTER to continue...")
sys.exit(1)
def print_version(opt, value, parser, *args, **kwargs):
"""Print the version number and exit."""
print constants.APPNAME + ' ' + constants.VERSION
sys.exit(0)
def parse_arguments(argv):
""" Parse the command line passed in <argv>. Returns a tuple containing
(options, arguments). Errors parsing the command line are handled in
this function. """
parser = optparse.OptionParser(
usage="%%prog %s" % _('[OPTION...] [PATH]'),
description=_('View images and comic book archives.'),
add_help_option=False)
parser.add_option('--help', action='help',
help=_('Show this help and exit.'))
parser.add_option('-s', '--slideshow', dest='slideshow', action='store_true',
help=_('Start the application in slideshow mode.'))
parser.add_option('-l', '--library', dest='library', action='store_true',
help=_('Show the library on startup.'))
parser.add_option('-v', '--version', action='callback', callback=print_version,
help=_('Show the version number and exit.'))
if sys.platform == 'win32':
parser.add_option('--no-update-fontconfig-cache',
dest='update_fontconfig_cache',
default=True, action='store_false',
help=_('Don\'t update fontconfig cache at startup.'))
else:
parser.add_option('--update-fontconfig-cache',
dest='update_fontconfig_cache',
default=False, action='store_true',
help=_('Update fontconfig cache at startup.'))
viewmodes = optparse.OptionGroup(parser, _('View modes'))
viewmodes.add_option('-f', '--fullscreen', dest='fullscreen', action='store_true',
help=_('Start the application in fullscreen mode.'))
viewmodes.add_option('-m', '--manga', dest='manga', action='store_true',
help=_('Start the application in manga mode.'))
viewmodes.add_option('-d', '--double-page', dest='doublepage', action='store_true',
help=_('Start the application in double page mode.'))
parser.add_option_group(viewmodes)
fitmodes = optparse.OptionGroup(parser, _('Zoom modes'))
fitmodes.add_option('-b', '--zoom-best', dest='zoommode', action='store_const',
const=constants.ZOOM_MODE_BEST,
help=_('Start the application with zoom set to best fit mode.'))
fitmodes.add_option('-w', '--zoom-width', dest='zoommode', action='store_const',
const=constants.ZOOM_MODE_WIDTH,
help=_('Start the application with zoom set to fit width.'))
fitmodes.add_option('-h', '--zoom-height', dest='zoommode', action='store_const',
const=constants.ZOOM_MODE_HEIGHT,
help=_('Start the application with zoom set to fit height.'))
parser.add_option_group(fitmodes)
debugopts = optparse.OptionGroup(parser, _('Debug options'))
debugopts.add_option('-W', dest='loglevel', action='store',
choices=('all', 'debug', 'info', 'warn', 'error'), default='warn',
metavar='[ all | debug | info | warn | error ]',
help=_('Sets the desired output log level.'))
# This supresses an error when MComix is used with cProfile
debugopts.add_option('-o', dest='output', action='store',
default='', help=optparse.SUPPRESS_HELP)
parser.add_option_group(debugopts)
opts, args = parser.parse_args(argv)
# Fix up log level to use constants from log.
if opts.loglevel == 'all':
opts.loglevel = log.DEBUG
if opts.loglevel == 'debug':
opts.loglevel = log.DEBUG
if opts.loglevel == 'info':
opts.loglevel = log.INFO
elif opts.loglevel == 'warn':
opts.loglevel = log.WARNING
elif opts.loglevel == 'error':
opts.loglevel = log.ERROR
return opts, args
def run():
"""Run the program."""
try:
import pkg_resources
except ImportError:
# gettext isn't initialized yet, since pkg_resources is required to find translation files.
# Thus, localizing these messages is pointless.
log._print("The package 'pkg_resources' could not be found.")
log._print("You need to install the 'setuptools' package, which also includes pkg_resources.")
log._print("Note: On most distributions, 'distribute' supersedes 'setuptools'.")
wait_and_exit()
# Load configuration and setup localisation.
preferences.read_preferences_file()
from mcomix import i18n
i18n.install_gettext()
# Retrieve and parse command line arguments.
argv = portability.get_commandline_args()
opts, args = parse_arguments(argv)
# First things first: set the log level.
log.setLevel(opts.loglevel)
# On Windows, update the fontconfig cache manually, before MComix starts
# using Gtk, since the process may take several minutes, during which the
# main window will just be frozen if the work is left to Gtk itself...
if opts.update_fontconfig_cache:
# First, update fontconfig cache.
log.debug('starting fontconfig cache update')
try:
from mcomix.win32 import fc_cache
from mcomix import process
fc_cache.update()
log.debug('fontconfig cache updated')
except Exception as e:
log.error('during fontconfig cache update', exc_info=e)
# And then replace current MComix process with a fresh one
# (that will not try to update the cache again).
exe = sys.argv[0]
if sys.platform == 'win32' and exe.endswith('.py'):
# Find the interpreter.
exe = process.find_executable(('pythonw.exe', 'python.exe'))
args = [exe, sys.argv[0]]
else:
args = [exe]
if sys.platform == 'win32':
args.append('--no-update-fontconfig-cache')
args.extend(argv)
if '--update-fontconfig-cache' in args:
args.remove('--update-fontconfig-cache')
log.debug('restarting MComix from fresh: os.execv(%s, %s)', repr(exe), args)
try:
if sys.platform == 'win32':
# Of course we can't use os.execv on Windows because it will
# mangle arguments containing spaces or non-ascii characters...
process.Win32Popen(args)
sys.exit(0)
else:
os.execv(exe, args)
except Exception as e:
log.error('os.execv(%s, %s) failed', exe, str(args), exc_info=e)
wait_and_exit()
# Check for PyGTK and PIL dependencies.
try:
import pygtk
pygtk.require('2.0')
import gtk
assert gtk.gtk_version >= (2, 12, 0)
assert gtk.pygtk_version >= (2, 12, 0)
import gobject
gobject.threads_init()
except AssertionError:
log.error( _("You do not have the required versions of GTK+ and PyGTK installed.") )
log.error( _('Installed GTK+ version is: %s') % \
'.'.join([str(n) for n in gtk.gtk_version]) )
log.error( _('Required GTK+ version is: 2.12.0 or higher') )
log.error( _('Installed PyGTK version is: %s') % \
'.'.join([str(n) for n in gtk.pygtk_version]) )
log.error( _('Required PyGTK version is: 2.12.0 or higher') )
wait_and_exit()
except ImportError:
log.error( _('Required PyGTK version is: 2.12.0 or higher') )
log.error( _('No version of PyGTK was found on your system.') )
log.error( _('This error might be caused by missing GTK+ libraries.') )
wait_and_exit()
try:
import PIL.Image
assert PIL.Image.VERSION >= '1.1.5'
except AssertionError:
log.error( _("You don't have the required version of the Python Imaging"), end=' ')
log.error( _('Library (PIL) installed.') )
log.error( _('Installed PIL version is: %s') % Image.VERSION )
log.error( _('Required PIL version is: 1.1.5 or higher') )
wait_and_exit()
except ImportError:
log.error( _('Python Imaging Library (PIL) 1.1.5 or higher is required.') )
log.error( _('No version of the Python Imaging Library was found on your system.') )
wait_and_exit()
if not os.path.exists(constants.DATA_DIR):
os.makedirs(constants.DATA_DIR, 0700)
if not os.path.exists(constants.CONFIG_DIR):
os.makedirs(constants.CONFIG_DIR, 0700)
from mcomix import icons
icons.load_icons()
open_path = None
open_page = 1
if len(args) == 1:
open_path = args[0]
elif len(args) > 1:
open_path = args
elif preferences.prefs['auto load last file'] \
and preferences.prefs['path to last file'] \
and os.path.isfile(preferences.prefs['path to last file']):
open_path = preferences.prefs['path to last file']
open_page = preferences.prefs['page of last file']
# Some languages require a RTL layout
if preferences.prefs['language'] in ('he', 'fa'):
gtk.widget_set_default_direction(gtk.TEXT_DIR_RTL)
gtk.gdk.set_program_class(constants.APPNAME)
from mcomix import main
window = main.MainWindow(fullscreen = opts.fullscreen, is_slideshow = opts.slideshow,
show_library = opts.library, manga_mode = opts.manga,
double_page = opts.doublepage, zoom_mode = opts.zoommode,
open_path = open_path, open_page = open_page)
main.set_main_window(window)
if 'win32' != sys.platform:
# Add a SIGCHLD handler to reap zombie processes.
def on_sigchld(signum, frame):
try:
os.waitpid(-1, os.WNOHANG)
except OSError:
pass
signal.signal(signal.SIGCHLD, on_sigchld)
signal.signal(signal.SIGTERM, lambda: gobject.idle_add(window.terminate_program))
try:
gtk.main()
except KeyboardInterrupt: # Will not always work because of threading.
window.terminate_program()
# vim: expandtab:sw=4:ts=4
|
gpl-2.0
|
mahak/neutron
|
neutron/privileged/__init__.py
|
2
|
2057
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
from oslo_privsep import capabilities as caps
from oslo_privsep import priv_context
# It is expected that most (if not all) neutron operations can be
# executed with these privileges.
default = priv_context.PrivContext(
__name__,
cfg_section='privsep',
pypath=__name__ + '.default',
# TODO(gus): CAP_SYS_ADMIN is required (only?) for manipulating
# network namespaces. SYS_ADMIN is a lot of scary powers, so
# consider breaking this out into a separate minimal context.
capabilities=[caps.CAP_SYS_ADMIN,
caps.CAP_NET_ADMIN,
caps.CAP_DAC_OVERRIDE,
caps.CAP_DAC_READ_SEARCH,
caps.CAP_SYS_PTRACE],
)
dhcp_release_cmd = priv_context.PrivContext(
__name__,
cfg_section='privsep_dhcp_release',
pypath=__name__ + '.dhcp_release_cmd',
capabilities=[caps.CAP_SYS_ADMIN,
caps.CAP_NET_ADMIN]
)
ovs_vsctl_cmd = priv_context.PrivContext(
__name__,
cfg_section='privsep_ovs_vsctl',
pypath=__name__ + '.ovs_vsctl_cmd',
capabilities=[caps.CAP_SYS_ADMIN,
caps.CAP_NET_ADMIN]
)
namespace_cmd = priv_context.PrivContext(
__name__,
cfg_section='privsep_namespace',
pypath=__name__ + '.namespace_cmd',
capabilities=[caps.CAP_SYS_ADMIN]
)
conntrack_cmd = priv_context.PrivContext(
__name__,
cfg_section='privsep_conntrack',
pypath=__name__ + '.conntrack_cmd',
capabilities=[caps.CAP_NET_ADMIN]
)
|
apache-2.0
|
girving/tensorflow
|
tensorflow/compiler/xla/python_api/types.py
|
32
|
4874
|
# Copyright 2018 The TensorFlow 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.
# ======================================
"""Utilities for XLA-specific Python types."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import collections
import numpy as _np # Avoids becoming a part of public Tensorflow API.
from tensorflow.compiler.xla import xla_data_pb2
from tensorflow.python.framework import dtypes
# Records corresponsence between a XLA primitive type and Python/Numpy types.
#
# primitive_type: value of type xla_data_pb2.PrimitiveType
# numpy_dtype: corresponsing Numpy "dtype" (like np.float32)
# literal_field_name: name of the field in the LiteralProto message elements
# of this type go into.
# literal_field_type: type of the field named 'literal_field_name'.
#
# TODO(eliben): figure out how to avoid knowing the extra Python type and the
# astype cast when writing into Literals.
TypeConversionRecord = collections.namedtuple('TypeConversionRecord', [
'primitive_type', 'numpy_dtype', 'literal_field_name', 'literal_field_type'
])
# Maps from XLA primitive types to TypeConversionRecord.
MAP_XLA_TYPE_TO_RECORD = {
xla_data_pb2.BF16:
TypeConversionRecord(
primitive_type=xla_data_pb2.BF16,
numpy_dtype=dtypes.bfloat16.as_numpy_dtype,
literal_field_name='bf16s',
literal_field_type=float),
xla_data_pb2.F16:
TypeConversionRecord(
primitive_type=xla_data_pb2.F16,
numpy_dtype=_np.float16,
literal_field_name='f16s',
literal_field_type=float),
xla_data_pb2.F32:
TypeConversionRecord(
primitive_type=xla_data_pb2.F32,
numpy_dtype=_np.float32,
literal_field_name='f32s',
literal_field_type=float),
xla_data_pb2.F64:
TypeConversionRecord(
primitive_type=xla_data_pb2.F64,
numpy_dtype=_np.float64,
literal_field_name='f64s',
literal_field_type=float),
xla_data_pb2.S8:
TypeConversionRecord(
primitive_type=xla_data_pb2.S8,
numpy_dtype=_np.int8,
literal_field_name='s8s',
literal_field_type=int),
xla_data_pb2.S16:
TypeConversionRecord(
primitive_type=xla_data_pb2.S16,
numpy_dtype=_np.int16,
literal_field_name='s16s',
literal_field_type=int),
xla_data_pb2.S32:
TypeConversionRecord(
primitive_type=xla_data_pb2.S32,
numpy_dtype=_np.int32,
literal_field_name='s32s',
literal_field_type=int),
xla_data_pb2.S64:
TypeConversionRecord(
primitive_type=xla_data_pb2.S64,
numpy_dtype=_np.int64,
literal_field_name='s64s',
literal_field_type=int),
xla_data_pb2.U8:
TypeConversionRecord(
primitive_type=xla_data_pb2.U8,
numpy_dtype=_np.uint8,
literal_field_name='s8s',
literal_field_type=int),
xla_data_pb2.U16:
TypeConversionRecord(
primitive_type=xla_data_pb2.U16,
numpy_dtype=_np.uint16,
literal_field_name='s16s',
literal_field_type=int),
xla_data_pb2.U32:
TypeConversionRecord(
primitive_type=xla_data_pb2.U32,
numpy_dtype=_np.uint32,
literal_field_name='s32s',
literal_field_type=int),
xla_data_pb2.U64:
TypeConversionRecord(
primitive_type=xla_data_pb2.U64,
numpy_dtype=_np.uint64,
literal_field_name='s64s',
literal_field_type=int),
xla_data_pb2.PRED:
TypeConversionRecord(
primitive_type=xla_data_pb2.PRED,
numpy_dtype=_np.bool,
literal_field_name='preds',
literal_field_type=bool)
}
# Maps from Numpy dtypes to TypeConversionRecord.
# Note the conversion on the key. Numpy has a known issue wherein dtype hashing
# doesn't work as expected (https://github.com/numpy/numpy/issues/7242). Thus,
# when keying by dtype in this dict, we use the string form of dtypes.
MAP_DTYPE_TO_RECORD = {
str(_np.dtype(record.numpy_dtype)): record
for record in MAP_XLA_TYPE_TO_RECORD.values()
}
|
apache-2.0
|
x111ong/odoo
|
addons/mass_mailing/wizard/mail_compose_message.py
|
308
|
3066
|
# -*- coding: utf-8 -*-
from openerp.osv import osv, fields
class MailComposeMessage(osv.TransientModel):
"""Add concept of mass mailing campaign to the mail.compose.message wizard
"""
_inherit = 'mail.compose.message'
_columns = {
'mass_mailing_campaign_id': fields.many2one(
'mail.mass_mailing.campaign', 'Mass Mailing Campaign',
),
'mass_mailing_id': fields.many2one(
'mail.mass_mailing', 'Mass Mailing'
),
'mass_mailing_name': fields.char('Mass Mailing'),
'mailing_list_ids': fields.many2many(
'mail.mass_mailing.list', string='Mailing List'
),
}
def get_mail_values(self, cr, uid, wizard, res_ids, context=None):
""" Override method that generated the mail content by creating the
mail.mail.statistics values in the o2m of mail_mail, when doing pure
email mass mailing. """
res = super(MailComposeMessage, self).get_mail_values(cr, uid, wizard, res_ids, context=context)
# use only for allowed models in mass mailing
if wizard.composition_mode == 'mass_mail' and \
(wizard.mass_mailing_name or wizard.mass_mailing_id) and \
wizard.model in [item[0] for item in self.pool['mail.mass_mailing']._get_mailing_model(cr, uid, context=context)]:
mass_mailing = wizard.mass_mailing_id
if not mass_mailing:
reply_to_mode = wizard.no_auto_thread and 'email' or 'thread'
reply_to = wizard.no_auto_thread and wizard.reply_to or False
mass_mailing_id = self.pool['mail.mass_mailing'].create(
cr, uid, {
'mass_mailing_campaign_id': wizard.mass_mailing_campaign_id and wizard.mass_mailing_campaign_id.id or False,
'name': wizard.mass_mailing_name,
'template_id': wizard.template_id and wizard.template_id.id or False,
'state': 'done',
'reply_to_mode': reply_to_mode,
'reply_to': reply_to,
'sent_date': fields.datetime.now(),
'body_html': wizard.body,
'mailing_model': wizard.model,
'mailing_domain': wizard.active_domain,
}, context=context)
mass_mailing = self.pool['mail.mass_mailing'].browse(cr, uid, mass_mailing_id, context=context)
for res_id in res_ids:
res[res_id].update({
'mailing_id': mass_mailing.id,
'statistics_ids': [(0, 0, {
'model': wizard.model,
'res_id': res_id,
'mass_mailing_id': mass_mailing.id,
})],
# email-mode: keep original message for routing
'notification': mass_mailing.reply_to_mode == 'thread',
'auto_delete': True,
})
return res
|
agpl-3.0
|
nkgilley/home-assistant
|
homeassistant/components/point/binary_sensor.py
|
6
|
4199
|
"""Support for Minut Point binary sensors."""
import logging
from homeassistant.components.binary_sensor import DOMAIN, BinarySensorEntity
from homeassistant.core import callback
from homeassistant.helpers.dispatcher import async_dispatcher_connect
from . import MinutPointEntity
from .const import DOMAIN as POINT_DOMAIN, POINT_DISCOVERY_NEW, SIGNAL_WEBHOOK
_LOGGER = logging.getLogger(__name__)
EVENTS = {
"battery": ("battery_low", ""), # On means low, Off means normal
"button_press": ( # On means the button was pressed, Off means normal
"short_button_press",
"",
),
"cold": ( # On means cold, Off means normal
"temperature_low",
"temperature_risen_normal",
),
"connectivity": ( # On means connected, Off means disconnected
"device_online",
"device_offline",
),
"dry": ( # On means too dry, Off means normal
"humidity_low",
"humidity_risen_normal",
),
"heat": ( # On means hot, Off means normal
"temperature_high",
"temperature_dropped_normal",
),
"moisture": ( # On means wet, Off means dry
"humidity_high",
"humidity_dropped_normal",
),
"sound": ( # On means sound detected, Off means no sound (clear)
"avg_sound_high",
"sound_level_dropped_normal",
),
"tamper": ("tamper", ""), # On means the point was removed or attached
}
async def async_setup_entry(hass, config_entry, async_add_entities):
"""Set up a Point's binary sensors based on a config entry."""
async def async_discover_sensor(device_id):
"""Discover and add a discovered sensor."""
client = hass.data[POINT_DOMAIN][config_entry.entry_id]
async_add_entities(
(
MinutPointBinarySensor(client, device_id, device_class)
for device_class in EVENTS
),
True,
)
async_dispatcher_connect(
hass, POINT_DISCOVERY_NEW.format(DOMAIN, POINT_DOMAIN), async_discover_sensor
)
class MinutPointBinarySensor(MinutPointEntity, BinarySensorEntity):
"""The platform class required by Home Assistant."""
def __init__(self, point_client, device_id, device_class):
"""Initialize the binary sensor."""
super().__init__(point_client, device_id, device_class)
self._async_unsub_hook_dispatcher_connect = None
self._events = EVENTS[device_class]
self._is_on = None
async def async_added_to_hass(self):
"""Call when entity is added to HOme Assistant."""
await super().async_added_to_hass()
self._async_unsub_hook_dispatcher_connect = async_dispatcher_connect(
self.hass, SIGNAL_WEBHOOK, self._webhook_event
)
async def async_will_remove_from_hass(self):
"""Disconnect dispatcher listener when removed."""
await super().async_will_remove_from_hass()
if self._async_unsub_hook_dispatcher_connect:
self._async_unsub_hook_dispatcher_connect()
async def _update_callback(self):
"""Update the value of the sensor."""
if not self.is_updated:
return
if self._events[0] in self.device.ongoing_events:
self._is_on = True
else:
self._is_on = None
self.async_write_ha_state()
@callback
def _webhook_event(self, data, webhook):
"""Process new event from the webhook."""
if self.device.webhook != webhook:
return
_type = data.get("event", {}).get("type")
_device_id = data.get("event", {}).get("device_id")
if _type not in self._events or _device_id != self.device.device_id:
return
_LOGGER.debug("Received webhook: %s", _type)
if _type == self._events[0]:
self._is_on = True
if _type == self._events[1]:
self._is_on = None
self.async_write_ha_state()
@property
def is_on(self):
"""Return the state of the binary sensor."""
if self.device_class == "connectivity":
# connectivity is the other way around.
return not self._is_on
return self._is_on
|
apache-2.0
|
exploreodoo/datStruct
|
odoo/addons/delivery/partner.py
|
383
|
1404
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import fields, osv
class res_partner(osv.osv):
_inherit = 'res.partner'
_columns = {
'property_delivery_carrier': fields.property(
type='many2one',
relation='delivery.carrier',
string="Delivery Method",
help="This delivery method will be used when invoicing from picking."),
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
gpl-2.0
|
yfried/ansible
|
lib/ansible/modules/packaging/os/apt.py
|
5
|
41284
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2012, Flowroute LLC
# Written by Matthew Williams <[email protected]>
# Based on yum module written by Seth Vidal <skvidal at fedoraproject.org>
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['stableinterface'],
'supported_by': 'core'}
DOCUMENTATION = '''
---
module: apt
short_description: Manages apt-packages
description:
- Manages I(apt) packages (such as for Debian/Ubuntu).
version_added: "0.0.2"
options:
name:
description:
- A list of package names, like C(foo), or package specifier with version, like C(foo=1.0).
Name wildcards (fnmatch) like C(apt*) and version wildcards like C(foo=1.0*) are also supported.
aliases: [ package, pkg ]
state:
description:
- Indicates the desired package state. C(latest) ensures that the latest version is installed. C(build-dep) ensures the package build dependencies
are installed. C(fixed) attempt to correct a system with broken dependencies in place.
default: present
choices: [ absent, build-dep, latest, present, fixed ]
update_cache:
description:
- Run the equivalent of C(apt-get update) before the operation. Can be run as part of the package installation or as a separate step.
type: bool
default: 'no'
cache_valid_time:
description:
- Update the apt cache if its older than the I(cache_valid_time). This option is set in seconds.
As of Ansible 2.4, this sets I(update_cache=yes).
default: 0
purge:
description:
- Will force purging of configuration files if the module state is set to I(absent).
type: bool
default: 'no'
default_release:
description:
- Corresponds to the C(-t) option for I(apt) and sets pin priorities
install_recommends:
description:
- Corresponds to the C(--no-install-recommends) option for I(apt). C(yes) installs recommended packages. C(no) does not install
recommended packages. By default, Ansible will use the same defaults as the operating system. Suggested packages are never installed.
aliases: ['install-recommends']
type: bool
force:
description:
- 'Corresponds to the C(--force-yes) to I(apt-get) and implies C(allow_unauthenticated: yes)'
- "This option will disable checking both the packages' signatures and the certificates of the
web servers they are downloaded from."
- 'This option *is not* the equivalent of passing the C(-f) flag to I(apt-get) on the command line'
- '**This is a destructive operation with the potential to destroy your system, and it should almost never be used.**
Please also see C(man apt-get) for more information.'
type: bool
default: 'no'
allow_unauthenticated:
description:
- Ignore if packages cannot be authenticated. This is useful for bootstrapping environments that manage their own apt-key setup.
- 'C(allow_unauthenticated) is only supported with state: I(install)/I(present)'
type: bool
default: 'no'
version_added: "2.1"
upgrade:
description:
- If yes or safe, performs an aptitude safe-upgrade.
- If full, performs an aptitude full-upgrade.
- If dist, performs an apt-get dist-upgrade.
- 'Note: This does not upgrade a specific package, use state=latest for that.'
- 'Note: Since 2.4, apt-get is used as a fall-back if aptitude is not present.'
version_added: "1.1"
choices: [ dist, full, 'no', safe, 'yes' ]
default: 'no'
dpkg_options:
description:
- Add dpkg options to apt command. Defaults to '-o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold"'
- Options should be supplied as comma separated list
default: force-confdef,force-confold
deb:
description:
- Path to a .deb package on the remote machine.
- If :// in the path, ansible will attempt to download deb before installing. (Version added 2.1)
- Requires the C(xz-utils) package to extract the control file of the deb package to install.
required: false
version_added: "1.6"
autoremove:
description:
- If C(yes), remove unused dependency packages for all module states except I(build-dep). It can also be used as the only option.
- Previous to version 2.4, autoclean was also an alias for autoremove, now it is its own separate command. See documentation for further information.
type: bool
default: 'no'
version_added: "2.1"
autoclean:
description:
- If C(yes), cleans the local repository of retrieved package files that can no longer be downloaded.
type: bool
default: 'no'
version_added: "2.4"
only_upgrade:
description:
- Only upgrade a package if it is already installed.
type: bool
default: 'no'
version_added: "2.1"
force_apt_get:
description:
- Force usage of apt-get instead of aptitude
type: bool
default: 'no'
version_added: "2.4"
requirements:
- python-apt (python 2)
- python3-apt (python 3)
- aptitude (before 2.4)
author: "Matthew Williams (@mgwilliams)"
notes:
- Three of the upgrade modes (C(full), C(safe) and its alias C(yes)) required C(aptitude) up to 2.3, since 2.4 C(apt-get) is used as a fall-back.
- apt starts newly installed services by default, this is what the underlying tooling does,
to avoid this you can set the ``RUNLEVEL`` environment variable to 1.
- The apt-get commandline supports implicit regex matches here but we do not because it can let typos through easier
(If you typo C(foo) as C(fo) apt-get would install packages that have "fo" in their name with a warning and a prompt for the user.
Since we don't have warnings and prompts before installing we disallow this.Use an explicit fnmatch pattern if you want wildcarding)
- When used with a `loop:` each package will be processed individually, it is much more efficient to pass the list directly to the `name` option.
'''
EXAMPLES = '''
- name: Update repositories cache and install "foo" package
apt:
name: foo
update_cache: yes
- name: Install apache httpd but avoid starting it immediately (state=present is optional)
apt:
name: apache2
state: present
environment:
RUNLEVEL: 1
- name: Remove "foo" package
apt:
name: foo
state: absent
- name: Install the package "foo"
apt:
name: foo
- name: Install a list of packages
apt:
name: "{{ packages }}"
vars:
packages:
- foo
- foo-tools
- name: Install the version '1.00' of package "foo"
apt:
name: foo=1.00
- name: Update the repository cache and update package "nginx" to latest version using default release squeeze-backport
apt:
name: nginx
state: latest
default_release: squeeze-backports
update_cache: yes
- name: Install latest version of "openjdk-6-jdk" ignoring "install-recommends"
apt:
name: openjdk-6-jdk
state: latest
install_recommends: no
- name: Upgrade all packages to the latest version
apt:
name: "*"
state: latest
- name: Update all packages to the latest version
apt:
upgrade: dist
- name: Run the equivalent of "apt-get update" as a separate step
apt:
update_cache: yes
- name: Only run "update_cache=yes" if the last one is more than 3600 seconds ago
apt:
update_cache: yes
cache_valid_time: 3600
- name: Pass options to dpkg on run
apt:
upgrade: dist
update_cache: yes
dpkg_options: 'force-confold,force-confdef'
- name: Install a .deb package
apt:
deb: /tmp/mypackage.deb
- name: Install the build dependencies for package "foo"
apt:
pkg: foo
state: build-dep
- name: Install a .deb package from the internet.
apt:
deb: https://example.com/python-ppq_0.1-1_all.deb
- name: Remove useless packages from the cache
apt:
autoclean: yes
- name: Remove dependencies that are no longer required
apt:
autoremove: yes
'''
RETURN = '''
cache_updated:
description: if the cache was updated or not
returned: success, in some cases
type: boolean
sample: True
cache_update_time:
description: time of the last cache update (0 if unknown)
returned: success, in some cases
type: int
sample: 1425828348000
stdout:
description: output from apt
returned: success, when needed
type: string
sample: "Reading package lists...\nBuilding dependency tree...\nReading state information...\nThe following extra packages will be installed:\n apache2-bin ..."
stderr:
description: error output from apt
returned: success, when needed
type: string
sample: "AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 127.0.1.1. Set the 'ServerName' directive globally to ..."
''' # NOQA
# added to stave off future warnings about apt api
import warnings
warnings.filterwarnings('ignore', "apt API not stable yet", FutureWarning)
import datetime
import fnmatch
import itertools
import os
import re
import sys
import time
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils._text import to_bytes, to_native
from ansible.module_utils.urls import fetch_file
# APT related constants
APT_ENV_VARS = dict(
DEBIAN_FRONTEND='noninteractive',
DEBIAN_PRIORITY='critical',
# We screenscrape apt-get and aptitude output for information so we need
# to make sure we use the C locale when running commands
LANG='C',
LC_ALL='C',
LC_MESSAGES='C',
LC_CTYPE='C',
)
DPKG_OPTIONS = 'force-confdef,force-confold'
APT_GET_ZERO = "\n0 upgraded, 0 newly installed"
APTITUDE_ZERO = "\n0 packages upgraded, 0 newly installed"
APT_LISTS_PATH = "/var/lib/apt/lists"
APT_UPDATE_SUCCESS_STAMP_PATH = "/var/lib/apt/periodic/update-success-stamp"
APT_MARK_INVALID_OP = 'Invalid operation'
APT_MARK_INVALID_OP_DEB6 = 'Usage: apt-mark [options] {markauto|unmarkauto} packages'
CLEAN_OP_CHANGED_STR = dict(
autoremove='The following packages will be REMOVED',
# "Del python3-q 2.4-1 [24 kB]"
autoclean='Del ',
)
HAS_PYTHON_APT = True
try:
import apt
import apt.debfile
import apt_pkg
except ImportError:
HAS_PYTHON_APT = False
if sys.version_info[0] < 3:
PYTHON_APT = 'python-apt'
else:
PYTHON_APT = 'python3-apt'
def package_split(pkgspec):
parts = pkgspec.split('=', 1)
version = None
if len(parts) > 1:
version = parts[1]
return parts[0], version
def package_versions(pkgname, pkg, pkg_cache):
try:
versions = set(p.version for p in pkg.versions)
except AttributeError:
# assume older version of python-apt is installed
# apt.package.Package#versions require python-apt >= 0.7.9.
pkg_cache_list = (p for p in pkg_cache.Packages if p.Name == pkgname)
pkg_versions = (p.VersionList for p in pkg_cache_list)
versions = set(p.VerStr for p in itertools.chain(*pkg_versions))
return versions
def package_version_compare(version, other_version):
try:
return apt_pkg.version_compare(version, other_version)
except AttributeError:
return apt_pkg.VersionCompare(version, other_version)
def package_status(m, pkgname, version, cache, state):
try:
# get the package from the cache, as well as the
# low-level apt_pkg.Package object which contains
# state fields not directly accessible from the
# higher-level apt.package.Package object.
pkg = cache[pkgname]
ll_pkg = cache._cache[pkgname] # the low-level package object
except KeyError:
if state == 'install':
try:
provided_packages = cache.get_providing_packages(pkgname)
if provided_packages:
is_installed = False
upgradable = False
version_ok = False
# when virtual package providing only one package, look up status of target package
if cache.is_virtual_package(pkgname) and len(provided_packages) == 1:
package = provided_packages[0]
installed, version_ok, upgradable, has_files = package_status(m, package.name, version, cache, state='install')
if installed:
is_installed = True
return is_installed, version_ok, upgradable, False
m.fail_json(msg="No package matching '%s' is available" % pkgname)
except AttributeError:
# python-apt version too old to detect virtual packages
# mark as upgradable and let apt-get install deal with it
return False, False, True, False
else:
return False, False, False, False
try:
has_files = len(pkg.installed_files) > 0
except UnicodeDecodeError:
has_files = True
except AttributeError:
has_files = False # older python-apt cannot be used to determine non-purged
try:
package_is_installed = ll_pkg.current_state == apt_pkg.CURSTATE_INSTALLED
except AttributeError: # python-apt 0.7.X has very weak low-level object
try:
# might not be necessary as python-apt post-0.7.X should have current_state property
package_is_installed = pkg.is_installed
except AttributeError:
# assume older version of python-apt is installed
package_is_installed = pkg.isInstalled
version_is_installed = package_is_installed
if version:
versions = package_versions(pkgname, pkg, cache._cache)
avail_upgrades = fnmatch.filter(versions, version)
if package_is_installed:
try:
installed_version = pkg.installed.version
except AttributeError:
installed_version = pkg.installedVersion
# check if the version is matched as well
version_is_installed = fnmatch.fnmatch(installed_version, version)
# Only claim the package is upgradable if a candidate matches the version
package_is_upgradable = False
for candidate in avail_upgrades:
if package_version_compare(candidate, installed_version) > 0:
package_is_upgradable = True
break
else:
package_is_upgradable = bool(avail_upgrades)
else:
try:
package_is_upgradable = pkg.is_upgradable
except AttributeError:
# assume older version of python-apt is installed
package_is_upgradable = pkg.isUpgradable
return package_is_installed, version_is_installed, package_is_upgradable, has_files
def expand_dpkg_options(dpkg_options_compressed):
options_list = dpkg_options_compressed.split(',')
dpkg_options = ""
for dpkg_option in options_list:
dpkg_options = '%s -o "Dpkg::Options::=--%s"' \
% (dpkg_options, dpkg_option)
return dpkg_options.strip()
def expand_pkgspec_from_fnmatches(m, pkgspec, cache):
# Note: apt-get does implicit regex matching when an exact package name
# match is not found. Something like this:
# matches = [pkg.name for pkg in cache if re.match(pkgspec, pkg.name)]
# (Should also deal with the ':' for multiarch like the fnmatch code below)
#
# We have decided not to do similar implicit regex matching but might take
# a PR to add some sort of explicit regex matching:
# https://github.com/ansible/ansible-modules-core/issues/1258
new_pkgspec = []
if pkgspec:
for pkgspec_pattern in pkgspec:
pkgname_pattern, version = package_split(pkgspec_pattern)
# note that none of these chars is allowed in a (debian) pkgname
if frozenset('*?[]!').intersection(pkgname_pattern):
# handle multiarch pkgnames, the idea is that "apt*" should
# only select native packages. But "apt*:i386" should still work
if ":" not in pkgname_pattern:
# Filter the multiarch packages from the cache only once
try:
pkg_name_cache = _non_multiarch
except NameError:
pkg_name_cache = _non_multiarch = [pkg.name for pkg in cache if ':' not in pkg.name] # noqa: F841
else:
# Create a cache of pkg_names including multiarch only once
try:
pkg_name_cache = _all_pkg_names
except NameError:
pkg_name_cache = _all_pkg_names = [pkg.name for pkg in cache] # noqa: F841
matches = fnmatch.filter(pkg_name_cache, pkgname_pattern)
if not matches:
m.fail_json(msg="No package(s) matching '%s' available" % str(pkgname_pattern))
else:
new_pkgspec.extend(matches)
else:
# No wildcards in name
new_pkgspec.append(pkgspec_pattern)
return new_pkgspec
def parse_diff(output):
diff = to_native(output).splitlines()
try:
# check for start marker from aptitude
diff_start = diff.index('Resolving dependencies...')
except ValueError:
try:
# check for start marker from apt-get
diff_start = diff.index('Reading state information...')
except ValueError:
# show everything
diff_start = -1
try:
# check for end marker line from both apt-get and aptitude
diff_end = next(i for i, item in enumerate(diff) if re.match('[0-9]+ (packages )?upgraded', item))
except StopIteration:
diff_end = len(diff)
diff_start += 1
diff_end += 1
return {'prepared': '\n'.join(diff[diff_start:diff_end])}
def mark_installed_manually(m, packages):
if not packages:
return
apt_mark_cmd_path = m.get_bin_path("apt-mark")
# https://github.com/ansible/ansible/issues/40531
if apt_mark_cmd_path is None:
m.warn("Could not find apt-mark binary, not marking package(s) as manually installed.")
return
cmd = "%s manual %s" % (apt_mark_cmd_path, ' '.join(packages))
rc, out, err = m.run_command(cmd)
if APT_MARK_INVALID_OP in err or APT_MARK_INVALID_OP_DEB6 in err:
cmd = "%s unmarkauto %s" % (apt_mark_cmd_path, ' '.join(packages))
rc, out, err = m.run_command(cmd)
if rc != 0:
m.fail_json(msg="'%s' failed: %s" % (cmd, err), stdout=out, stderr=err, rc=rc)
def install(m, pkgspec, cache, upgrade=False, default_release=None,
install_recommends=None, force=False,
dpkg_options=expand_dpkg_options(DPKG_OPTIONS),
build_dep=False, fixed=False, autoremove=False, only_upgrade=False,
allow_unauthenticated=False):
pkg_list = []
packages = ""
pkgspec = expand_pkgspec_from_fnmatches(m, pkgspec, cache)
package_names = []
for package in pkgspec:
if build_dep:
# Let apt decide what to install
pkg_list.append("'%s'" % package)
continue
name, version = package_split(package)
package_names.append(name)
installed, installed_version, upgradable, has_files = package_status(m, name, version, cache, state='install')
if (not installed and not only_upgrade) or (installed and not installed_version) or (upgrade and upgradable):
pkg_list.append("'%s'" % package)
if installed_version and upgradable and version:
# This happens when the package is installed, a newer version is
# available, and the version is a wildcard that matches both
#
# We do not apply the upgrade flag because we cannot specify both
# a version and state=latest. (This behaviour mirrors how apt
# treats a version with wildcard in the package)
pkg_list.append("'%s'" % package)
packages = ' '.join(pkg_list)
if packages:
if force:
force_yes = '--force-yes'
else:
force_yes = ''
if m.check_mode:
check_arg = '--simulate'
else:
check_arg = ''
if autoremove:
autoremove = '--auto-remove'
else:
autoremove = ''
if only_upgrade:
only_upgrade = '--only-upgrade'
else:
only_upgrade = ''
if fixed:
fixed = '--fix-broken'
else:
fixed = ''
if build_dep:
cmd = "%s -y %s %s %s %s %s build-dep %s" % (APT_GET_CMD, dpkg_options, only_upgrade, fixed, force_yes, check_arg, packages)
else:
cmd = "%s -y %s %s %s %s %s %s install %s" % (APT_GET_CMD, dpkg_options, only_upgrade, fixed, force_yes, autoremove, check_arg, packages)
if default_release:
cmd += " -t '%s'" % (default_release,)
if install_recommends is False:
cmd += " -o APT::Install-Recommends=no"
elif install_recommends is True:
cmd += " -o APT::Install-Recommends=yes"
# install_recommends is None uses the OS default
if allow_unauthenticated:
cmd += " --allow-unauthenticated"
rc, out, err = m.run_command(cmd)
if m._diff:
diff = parse_diff(out)
else:
diff = {}
status = True
changed = True
if build_dep:
changed = APT_GET_ZERO not in out
data = dict(changed=changed, stdout=out, stderr=err, diff=diff)
if rc:
status = False
data = dict(msg="'%s' failed: %s" % (cmd, err), stdout=out, stderr=err, rc=rc)
else:
status = True
data = dict(changed=False)
if not build_dep:
mark_installed_manually(m, package_names)
return (status, data)
def get_field_of_deb(m, deb_file, field="Version"):
cmd_dpkg = m.get_bin_path("dpkg", True)
cmd = cmd_dpkg + " --field %s %s" % (deb_file, field)
rc, stdout, stderr = m.run_command(cmd)
if rc != 0:
m.fail_json(msg="%s failed" % cmd, stdout=stdout, stderr=stderr)
return to_native(stdout).strip('\n')
def install_deb(m, debs, cache, force, install_recommends, allow_unauthenticated, dpkg_options):
changed = False
deps_to_install = []
pkgs_to_install = []
for deb_file in debs.split(','):
try:
pkg = apt.debfile.DebPackage(deb_file)
pkg_name = get_field_of_deb(m, deb_file, "Package")
pkg_version = get_field_of_deb(m, deb_file, "Version")
if len(apt_pkg.get_architectures()) > 1:
pkg_arch = get_field_of_deb(m, deb_file, "Architecture")
pkg_key = "%s:%s" % (pkg_name, pkg_arch)
else:
pkg_key = pkg_name
try:
installed_pkg = apt.Cache()[pkg_key]
installed_version = installed_pkg.installed.version
if package_version_compare(pkg_version, installed_version) == 0:
# Does not need to down-/upgrade, move on to next package
continue
except Exception:
# Must not be installed, continue with installation
pass
# Check if package is installable
if not pkg.check() and not force:
m.fail_json(msg=pkg._failure_string)
# add any missing deps to the list of deps we need
# to install so they're all done in one shot
deps_to_install.extend(pkg.missing_deps)
except Exception as e:
m.fail_json(msg="Unable to install package: %s" % to_native(e))
# and add this deb to the list of packages to install
pkgs_to_install.append(deb_file)
# install the deps through apt
retvals = {}
if deps_to_install:
(success, retvals) = install(m=m, pkgspec=deps_to_install, cache=cache,
install_recommends=install_recommends,
dpkg_options=expand_dpkg_options(dpkg_options))
if not success:
m.fail_json(**retvals)
changed = retvals.get('changed', False)
if pkgs_to_install:
options = ' '.join(["--%s" % x for x in dpkg_options.split(",")])
if m.check_mode:
options += " --simulate"
if force:
options += " --force-all"
cmd = "dpkg %s -i %s" % (options, " ".join(pkgs_to_install))
rc, out, err = m.run_command(cmd)
if "stdout" in retvals:
stdout = retvals["stdout"] + out
else:
stdout = out
if "diff" in retvals:
diff = retvals["diff"]
if 'prepared' in diff:
diff['prepared'] += '\n\n' + out
else:
diff = parse_diff(out)
if "stderr" in retvals:
stderr = retvals["stderr"] + err
else:
stderr = err
if rc == 0:
m.exit_json(changed=True, stdout=stdout, stderr=stderr, diff=diff)
else:
m.fail_json(msg="%s failed" % cmd, stdout=stdout, stderr=stderr)
else:
m.exit_json(changed=changed, stdout=retvals.get('stdout', ''), stderr=retvals.get('stderr', ''), diff=retvals.get('diff', ''))
def remove(m, pkgspec, cache, purge=False, force=False,
dpkg_options=expand_dpkg_options(DPKG_OPTIONS), autoremove=False):
pkg_list = []
pkgspec = expand_pkgspec_from_fnmatches(m, pkgspec, cache)
for package in pkgspec:
name, version = package_split(package)
installed, installed_version, upgradable, has_files = package_status(m, name, version, cache, state='remove')
if installed_version or (has_files and purge):
pkg_list.append("'%s'" % package)
packages = ' '.join(pkg_list)
if not packages:
m.exit_json(changed=False)
else:
if force:
force_yes = '--force-yes'
else:
force_yes = ''
if purge:
purge = '--purge'
else:
purge = ''
if autoremove:
autoremove = '--auto-remove'
else:
autoremove = ''
if m.check_mode:
check_arg = '--simulate'
else:
check_arg = ''
cmd = "%s -q -y %s %s %s %s %s remove %s" % (APT_GET_CMD, dpkg_options, purge, force_yes, autoremove, check_arg, packages)
rc, out, err = m.run_command(cmd)
if m._diff:
diff = parse_diff(out)
else:
diff = {}
if rc:
m.fail_json(msg="'apt-get remove %s' failed: %s" % (packages, err), stdout=out, stderr=err, rc=rc)
m.exit_json(changed=True, stdout=out, stderr=err, diff=diff)
def cleanup(m, purge=False, force=False, operation=None,
dpkg_options=expand_dpkg_options(DPKG_OPTIONS)):
if operation not in frozenset(['autoremove', 'autoclean']):
raise AssertionError('Expected "autoremove" or "autoclean" cleanup operation, got %s' % operation)
if force:
force_yes = '--force-yes'
else:
force_yes = ''
if purge:
purge = '--purge'
else:
purge = ''
if m.check_mode:
check_arg = '--simulate'
else:
check_arg = ''
cmd = "%s -y %s %s %s %s %s" % (APT_GET_CMD, dpkg_options, purge, force_yes, operation, check_arg)
rc, out, err = m.run_command(cmd)
if m._diff:
diff = parse_diff(out)
else:
diff = {}
if rc:
m.fail_json(msg="'apt-get %s' failed: %s" % (operation, err), stdout=out, stderr=err, rc=rc)
changed = CLEAN_OP_CHANGED_STR[operation] in out
m.exit_json(changed=changed, stdout=out, stderr=err, diff=diff)
def upgrade(m, mode="yes", force=False, default_release=None,
use_apt_get=False,
dpkg_options=expand_dpkg_options(DPKG_OPTIONS), autoremove=False,
allow_unauthenticated=False,
):
if autoremove:
autoremove = '--auto-remove'
else:
autoremove = ''
if m.check_mode:
check_arg = '--simulate'
else:
check_arg = ''
apt_cmd = None
prompt_regex = None
if mode == "dist" or (mode == "full" and use_apt_get):
# apt-get dist-upgrade
apt_cmd = APT_GET_CMD
upgrade_command = "dist-upgrade %s" % (autoremove)
elif mode == "full" and not use_apt_get:
# aptitude full-upgrade
apt_cmd = APTITUDE_CMD
upgrade_command = "full-upgrade"
else:
if use_apt_get:
apt_cmd = APT_GET_CMD
upgrade_command = "upgrade --with-new-pkgs %s" % (autoremove)
else:
# aptitude safe-upgrade # mode=yes # default
apt_cmd = APTITUDE_CMD
upgrade_command = "safe-upgrade"
prompt_regex = r"(^Do you want to ignore this warning and proceed anyway\?|^\*\*\*.*\[default=.*\])"
if force:
if apt_cmd == APT_GET_CMD:
force_yes = '--force-yes'
else:
force_yes = '--assume-yes --allow-untrusted'
else:
force_yes = ''
allow_unauthenticated = '--allow-unauthenticated' if allow_unauthenticated else ''
if apt_cmd is None:
if use_apt_get:
apt_cmd = APT_GET_CMD
else:
m.fail_json(msg="Unable to find APTITUDE in path. Please make sure "
"to have APTITUDE in path or use 'force_apt_get=True'")
apt_cmd_path = m.get_bin_path(apt_cmd, required=True)
cmd = '%s -y %s %s %s %s %s' % (apt_cmd_path, dpkg_options, force_yes, allow_unauthenticated,
check_arg, upgrade_command)
if default_release:
cmd += " -t '%s'" % (default_release,)
rc, out, err = m.run_command(cmd, prompt_regex=prompt_regex)
if m._diff:
diff = parse_diff(out)
else:
diff = {}
if rc:
m.fail_json(msg="'%s %s' failed: %s" % (apt_cmd, upgrade_command, err), stdout=out, rc=rc)
if (apt_cmd == APT_GET_CMD and APT_GET_ZERO in out) or (apt_cmd == APTITUDE_CMD and APTITUDE_ZERO in out):
m.exit_json(changed=False, msg=out, stdout=out, stderr=err)
m.exit_json(changed=True, msg=out, stdout=out, stderr=err, diff=diff)
def get_cache_mtime():
"""Return mtime of a valid apt cache file.
Stat the apt cache file and if no cache file is found return 0
:returns: ``int``
"""
cache_time = 0
if os.path.exists(APT_UPDATE_SUCCESS_STAMP_PATH):
cache_time = os.stat(APT_UPDATE_SUCCESS_STAMP_PATH).st_mtime
elif os.path.exists(APT_LISTS_PATH):
cache_time = os.stat(APT_LISTS_PATH).st_mtime
return cache_time
def get_updated_cache_time():
"""Return the mtime time stamp and the updated cache time.
Always retrieve the mtime of the apt cache or set the `cache_mtime`
variable to 0
:returns: ``tuple``
"""
cache_mtime = get_cache_mtime()
mtimestamp = datetime.datetime.fromtimestamp(cache_mtime)
updated_cache_time = int(time.mktime(mtimestamp.timetuple()))
return mtimestamp, updated_cache_time
# https://github.com/ansible/ansible-modules-core/issues/2951
def get_cache(module):
'''Attempt to get the cache object and update till it works'''
cache = None
try:
cache = apt.Cache()
except SystemError as e:
if '/var/lib/apt/lists/' in to_native(e).lower():
# update cache until files are fixed or retries exceeded
retries = 0
while retries < 2:
(rc, so, se) = module.run_command(['apt-get', 'update', '-q'])
retries += 1
if rc == 0:
break
if rc != 0:
module.fail_json(msg='Updating the cache to correct corrupt package lists failed:\n%s\n%s' % (to_native(e), so + se), rc=rc)
# try again
cache = apt.Cache()
else:
module.fail_json(msg=to_native(e))
return cache
def main():
module = AnsibleModule(
argument_spec=dict(
state=dict(type='str', default='present', choices=['absent', 'build-dep', 'installed', 'latest', 'present', 'removed', 'present', 'fixed']),
update_cache=dict(type='bool', aliases=['update-cache']),
cache_valid_time=dict(type='int', default=0),
purge=dict(type='bool', default=False),
package=dict(type='list', aliases=['pkg', 'name']),
deb=dict(type='path'),
default_release=dict(type='str', aliases=['default-release']),
install_recommends=dict(type='bool', aliases=['install-recommends']),
force=dict(type='bool', default=False),
upgrade=dict(type='str', choices=['dist', 'full', 'no', 'safe', 'yes']),
dpkg_options=dict(type='str', default=DPKG_OPTIONS),
autoremove=dict(type='bool', default=False),
autoclean=dict(type='bool', default=False),
only_upgrade=dict(type='bool', default=False),
force_apt_get=dict(type='bool', default=False),
allow_unauthenticated=dict(type='bool', default=False, aliases=['allow-unauthenticated']),
),
mutually_exclusive=[['deb', 'package', 'upgrade']],
required_one_of=[['autoremove', 'deb', 'package', 'update_cache', 'upgrade']],
supports_check_mode=True,
)
module.run_command_environ_update = APT_ENV_VARS
if not HAS_PYTHON_APT:
if module.check_mode:
module.fail_json(msg="%s must be installed to use check mode. "
"If run normally this module can auto-install it." % PYTHON_APT)
try:
module.warn("Updating cache and auto-installing missing dependency: %s" % PYTHON_APT)
module.run_command(['apt-get', 'update'], check_rc=True)
module.run_command(['apt-get', 'install', '--no-install-recommends', PYTHON_APT, '-y', '-q'], check_rc=True)
global apt, apt_pkg
import apt
import apt.debfile
import apt_pkg
except ImportError:
module.fail_json(msg="Could not import python modules: apt, apt_pkg. "
"Please install %s package." % PYTHON_APT)
global APTITUDE_CMD
APTITUDE_CMD = module.get_bin_path("aptitude", False)
global APT_GET_CMD
APT_GET_CMD = module.get_bin_path("apt-get")
p = module.params
if p['upgrade'] == 'no':
p['upgrade'] = None
use_apt_get = p['force_apt_get']
if not use_apt_get and not APTITUDE_CMD and p.get('upgrade', None) in ['full', 'safe', 'yes']:
module.warn("Could not find aptitude. Using apt-get instead.")
use_apt_get = True
updated_cache = False
updated_cache_time = 0
install_recommends = p['install_recommends']
allow_unauthenticated = p['allow_unauthenticated']
dpkg_options = expand_dpkg_options(p['dpkg_options'])
autoremove = p['autoremove']
autoclean = p['autoclean']
# Deal with deprecated aliases
if p['state'] == 'installed':
module.deprecate("State 'installed' is deprecated. Using state 'present' instead.", version="2.9")
p['state'] = 'present'
if p['state'] == 'removed':
module.deprecate("State 'removed' is deprecated. Using state 'absent' instead.", version="2.9")
p['state'] = 'absent'
# Get the cache object
cache = get_cache(module)
try:
if p['default_release']:
try:
apt_pkg.config['APT::Default-Release'] = p['default_release']
except AttributeError:
apt_pkg.Config['APT::Default-Release'] = p['default_release']
# reopen cache w/ modified config
cache.open(progress=None)
mtimestamp, updated_cache_time = get_updated_cache_time()
# Cache valid time is default 0, which will update the cache if
# needed and `update_cache` was set to true
updated_cache = False
if p['update_cache'] or p['cache_valid_time']:
now = datetime.datetime.now()
tdelta = datetime.timedelta(seconds=p['cache_valid_time'])
if not mtimestamp + tdelta >= now:
# Retry to update the cache up to 3 times
err = ''
for retry in range(3):
try:
cache.update()
break
except apt.cache.FetchFailedException as e:
err = to_native(e)
else:
module.fail_json(msg='Failed to update apt cache: %s' % err)
cache.open(progress=None)
mtimestamp, post_cache_update_time = get_updated_cache_time()
if updated_cache_time != post_cache_update_time:
updated_cache = True
updated_cache_time = post_cache_update_time
# If there is nothing else to do exit. This will set state as
# changed based on if the cache was updated.
if not p['package'] and not p['upgrade'] and not p['deb']:
module.exit_json(
changed=updated_cache,
cache_updated=updated_cache,
cache_update_time=updated_cache_time
)
force_yes = p['force']
if p['upgrade']:
upgrade(module, p['upgrade'], force_yes, p['default_release'], use_apt_get, dpkg_options, autoremove, allow_unauthenticated)
if p['deb']:
if p['state'] != 'present':
module.fail_json(msg="deb only supports state=present")
if '://' in p['deb']:
p['deb'] = fetch_file(module, p['deb'])
install_deb(module, p['deb'], cache,
install_recommends=install_recommends,
allow_unauthenticated=allow_unauthenticated,
force=force_yes, dpkg_options=p['dpkg_options'])
unfiltered_packages = p['package'] or ()
packages = [package for package in unfiltered_packages if package != '*']
all_installed = '*' in unfiltered_packages
latest = p['state'] == 'latest'
if latest and all_installed:
if packages:
module.fail_json(msg='unable to install additional packages when upgrading all installed packages')
upgrade(module, 'yes', force_yes, p['default_release'], use_apt_get, dpkg_options, autoremove, allow_unauthenticated)
if packages:
for package in packages:
if package.count('=') > 1:
module.fail_json(msg="invalid package spec: %s" % package)
if latest and '=' in package:
module.fail_json(msg='version number inconsistent with state=latest: %s' % package)
if not packages:
if autoclean:
cleanup(module, p['purge'], force=force_yes, operation='autoclean', dpkg_options=dpkg_options)
if autoremove:
cleanup(module, p['purge'], force=force_yes, operation='autoremove', dpkg_options=dpkg_options)
if p['state'] in ('latest', 'present', 'build-dep', 'fixed'):
state_upgrade = False
state_builddep = False
state_fixed = False
if p['state'] == 'latest':
state_upgrade = True
if p['state'] == 'build-dep':
state_builddep = True
if p['state'] == 'fixed':
state_fixed = True
success, retvals = install(
module,
packages,
cache,
upgrade=state_upgrade,
default_release=p['default_release'],
install_recommends=install_recommends,
force=force_yes,
dpkg_options=dpkg_options,
build_dep=state_builddep,
fixed=state_fixed,
autoremove=autoremove,
only_upgrade=p['only_upgrade'],
allow_unauthenticated=allow_unauthenticated
)
# Store if the cache has been updated
retvals['cache_updated'] = updated_cache
# Store when the update time was last
retvals['cache_update_time'] = updated_cache_time
if success:
module.exit_json(**retvals)
else:
module.fail_json(**retvals)
elif p['state'] == 'absent':
remove(module, packages, cache, p['purge'], force=force_yes, dpkg_options=dpkg_options, autoremove=autoremove)
except apt.cache.LockFailedException:
module.fail_json(msg="Failed to lock apt for exclusive operation")
except apt.cache.FetchFailedException:
module.fail_json(msg="Could not fetch updated apt files")
if __name__ == "__main__":
main()
|
gpl-3.0
|
skulbrane/theHarvester
|
discovery/jigsaw.py
|
23
|
1810
|
import string
import httplib
import sys
import myparser
import re
# http://www.jigsaw.com/SearchAcrossCompanies.xhtml?opCode=refresh&rpage=4&mode=0&cnCountry=&order=0&orderby=0&cmName=accuvant&cnDead=false&cnExOwned=false&count=0&screenNameType=0&screenName=&omitScreenNameType=0&omitScreenName=&companyId=0&estimatedCount=277&rowsPerPage=50
class search_jigsaw:
def __init__(self, word, limit):
self.word = word.replace(' ', '%20')
self.results = ""
self.totalresults = ""
self.server = "www.jigsaw.com"
self.hostname = "www.jigsaw.com"
self.userAgent = "(Mozilla/5.0 (Windows; U; Windows NT 6.0;en-US; rv:1.9.2) Gecko/20100115 Firefox/3.6"
self.quantity = "100"
self.limit = int(limit)
self.counter = 0
def do_search(self):
h = httplib.HTTP(self.server)
h.putrequest(
'GET',
"/FreeTextSearch.xhtml?opCode=search&autoSuggested=True&freeText=" +
self.word)
h.putheader('User-agent', self.userAgent)
h.endheaders()
returncode, returnmsg, headers = h.getreply()
self.results = h.getfile().read()
self.totalresults += self.results
def check_next(self):
renext = re.compile('> Next <')
nextres = renext.findall(self.results)
if nextres != []:
nexty = "1"
else:
nexty = "0"
return nexty
def get_people(self):
rawres = myparser.parser(self.totalresults, self.word)
return rawres.people_jigsaw()
def process(self):
while (self.counter < self.limit):
self.do_search()
more = self.check_next()
if more == "1":
self.counter += 100
else:
break
|
gpl-2.0
|
tchernomax/ansible
|
lib/ansible/modules/network/cloudengine/ce_vxlan_arp.py
|
43
|
23695
|
#!/usr/bin/python
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
#
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = """
---
module: ce_vxlan_arp
version_added: "2.4"
short_description: Manages ARP attributes of VXLAN on HUAWEI CloudEngine devices.
description:
- Manages ARP attributes of VXLAN on HUAWEI CloudEngine devices.
author: QijunPan (@CloudEngine-Ansible)
options:
evn_bgp:
description:
- Enables EVN BGP.
choices: ['enable', 'disable']
evn_source_ip:
description:
- Specifies the source address of an EVN BGP peer.
The value is in dotted decimal notation.
evn_peer_ip:
description:
- Specifies the IP address of an EVN BGP peer.
The value is in dotted decimal notation.
evn_server:
description:
- Configures the local device as the router reflector (RR) on the EVN network.
choices: ['enable', 'disable']
evn_reflect_client:
description:
- Configures the local device as the route reflector (RR) and its peer as the client.
choices: ['enable', 'disable']
vbdif_name:
description:
- Full name of VBDIF interface, i.e. Vbdif100.
arp_collect_host:
description:
- Enables EVN BGP or BGP EVPN to collect host information.
choices: ['enable', 'disable']
host_collect_protocol:
description:
- Enables EVN BGP or BGP EVPN to advertise host information.
choices: ['bgp','none']
bridge_domain_id:
description:
- Specifies a BD(bridge domain) ID.
The value is an integer ranging from 1 to 16777215.
arp_suppress:
description:
- Enables ARP broadcast suppression in a BD.
choices: ['enable', 'disable']
state:
description:
- Determines whether the config should be present or not
on the device.
default: present
choices: ['present', 'absent']
"""
EXAMPLES = '''
- name: vxlan arp module test
hosts: ce128
connection: local
gather_facts: no
vars:
cli:
host: "{{ inventory_hostname }}"
port: "{{ ansible_ssh_port }}"
username: "{{ username }}"
password: "{{ password }}"
transport: cli
tasks:
- name: Configure EVN BGP on Layer 2 and Layer 3 VXLAN gateways to establish EVN BGP peer relationships.
ce_vxlan_arp:
evn_bgp: enable
evn_source_ip: 6.6.6.6
evn_peer_ip: 7.7.7.7
provider: "{{ cli }}"
- name: Configure a Layer 3 VXLAN gateway as a BGP RR.
ce_vxlan_arp:
evn_bgp: enable
evn_server: enable
provider: "{{ cli }}"
- name: Enable EVN BGP on a Layer 3 VXLAN gateway to collect host information.
ce_vxlan_arp:
vbdif_name: Vbdif100
arp_collect_host: enable
provider: "{{ cli }}"
- name: Enable Layer 2 and Layer 3 VXLAN gateways to use EVN BGP to advertise host information.
ce_vxlan_arp:
host_collect_protocol: bgp
provider: "{{ cli }}"
- name: Enable ARP broadcast suppression on a Layer 2 VXLAN gateway.
ce_vxlan_arp:
bridge_domain_id: 100
arp_suppress: enable
provider: "{{ cli }}"
'''
RETURN = '''
proposed:
description: k/v pairs of parameters passed into module
returned: verbose mode
type: dict
sample: {"evn_bgp": "enable", "evn_source_ip": "6.6.6.6", "evn_peer_ip":"7.7.7.7", state: "present"}
existing:
description: k/v pairs of existing configuration
returned: verbose mode
type: dict
sample: {"evn_bgp": "disable", "evn_source_ip": null, "evn_peer_ip": []}
end_state:
description: k/v pairs of configuration after module execution
returned: verbose mode
type: dict
sample: {"evn_bgp": "enable", "evn_source_ip": "6.6.6.6", "evn_peer_ip": ["7.7.7.7"]}
updates:
description: commands sent to the device
returned: always
type: list
sample: ["evn bgp",
"source-address 6.6.6.6",
"peer 7.7.7.7"]
changed:
description: check to see if a change was made on the device
returned: always
type: boolean
sample: true
'''
import re
from ansible.module_utils.basic import AnsibleModule
from ansible.module_utils.network.cloudengine.ce import get_config, load_config
from ansible.module_utils.network.cloudengine.ce import ce_argument_spec
def is_config_exist(cmp_cfg, test_cfg):
"""is configuration exist"""
if not cmp_cfg or not test_cfg:
return False
return bool(test_cfg in cmp_cfg)
def is_valid_v4addr(addr):
"""check is ipv4 addr is valid"""
if addr.count('.') == 3:
addr_list = addr.split('.')
if len(addr_list) != 4:
return False
for each_num in addr_list:
if not each_num.isdigit():
return False
if int(each_num) > 255:
return False
return True
return False
def get_evn_peers(config):
"""get evn peer ip list"""
get = re.findall(r"peer ([0-9]+.[0-9]+.[0-9]+.[0-9]+)", config)
if not get:
return None
else:
return list(set(get))
def get_evn_srouce(config):
"""get evn peer ip list"""
get = re.findall(
r"source-address ([0-9]+.[0-9]+.[0-9]+.[0-9]+)", config)
if not get:
return None
else:
return get[0]
def get_evn_reflect_client(config):
"""get evn reflect client list"""
get = re.findall(
r"peer ([0-9]+.[0-9]+.[0-9]+.[0-9]+)\s*reflect-client", config)
if not get:
return None
else:
return list(get)
class VxlanArp(object):
"""
Manages arp attributes of VXLAN.
"""
def __init__(self, argument_spec):
self.spec = argument_spec
self.module = None
self.init_module()
# module input info
self.evn_bgp = self.module.params['evn_bgp']
self.evn_source_ip = self.module.params['evn_source_ip']
self.evn_peer_ip = self.module.params['evn_peer_ip']
self.evn_server = self.module.params['evn_server']
self.evn_reflect_client = self.module.params['evn_reflect_client']
self.vbdif_name = self.module.params['vbdif_name']
self.arp_collect_host = self.module.params['arp_collect_host']
self.host_collect_protocol = self.module.params[
'host_collect_protocol']
self.bridge_domain_id = self.module.params['bridge_domain_id']
self.arp_suppress = self.module.params['arp_suppress']
self.state = self.module.params['state']
# host info
self.host = self.module.params['host']
self.username = self.module.params['username']
self.port = self.module.params['port']
# state
self.config = "" # current config
self.changed = False
self.updates_cmd = list()
self.commands = list()
self.results = dict()
self.proposed = dict()
self.existing = dict()
self.end_state = dict()
def init_module(self):
"""init module"""
required_together = [("vbdif_name", "arp_collect_host"), ("bridge_domain_id", "arp_suppress")]
self.module = AnsibleModule(argument_spec=self.spec,
required_together=required_together,
supports_check_mode=True)
def cli_load_config(self, commands):
"""load config by cli"""
if not self.module.check_mode:
load_config(self.module, commands)
def get_current_config(self):
"""get current configuration"""
flags = list()
exp = "| ignore-case section include evn bgp|host collect protocol bgp"
if self.vbdif_name:
exp += "|^interface %s$" % self.vbdif_name
if self.bridge_domain_id:
exp += "|^bridge-domain %s$" % self.bridge_domain_id
flags.append(exp)
config = get_config(self.module, flags)
return config
def cli_add_command(self, command, undo=False):
"""add command to self.update_cmd and self.commands"""
if undo and command.lower() not in ["quit", "return"]:
cmd = "undo " + command
else:
cmd = command
self.commands.append(cmd) # set to device
if command.lower() not in ["quit", "return"]:
self.updates_cmd.append(cmd) # show updates result
def config_bridge_domain(self):
"""manage bridge domain configuration"""
if not self.bridge_domain_id:
return
# bridge-domain bd-id
# [undo] arp broadcast-suppress enable
cmd = "bridge-domain %s" % self.bridge_domain_id
if not is_config_exist(self.config, cmd):
self.module.fail_json(msg="Error: Bridge domain %s is not exist." % self.bridge_domain_id)
cmd = "arp broadcast-suppress enable"
exist = is_config_exist(self.config, cmd)
if self.arp_suppress == "enable" and not exist:
self.cli_add_command("bridge-domain %s" % self.bridge_domain_id)
self.cli_add_command(cmd)
self.cli_add_command("quit")
elif self.arp_suppress == "disable" and exist:
self.cli_add_command("bridge-domain %s" % self.bridge_domain_id)
self.cli_add_command(cmd, undo=True)
self.cli_add_command("quit")
def config_evn_bgp(self):
"""enables EVN BGP and configure evn bgp command"""
evn_bgp_view = False
evn_bgp_enable = False
cmd = "evn bgp"
exist = is_config_exist(self.config, cmd)
if self.evn_bgp == "enable" or exist:
evn_bgp_enable = True
# [undo] evn bgp
if self.evn_bgp:
if self.evn_bgp == "enable" and not exist:
self.cli_add_command(cmd)
evn_bgp_view = True
elif self.evn_bgp == "disable" and exist:
self.cli_add_command(cmd, undo=True)
return
# [undo] source-address ip-address
if evn_bgp_enable and self.evn_source_ip:
cmd = "source-address %s" % self.evn_source_ip
exist = is_config_exist(self.config, cmd)
if self.state == "present" and not exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd)
elif self.state == "absent" and exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd, undo=True)
# [undo] peer ip-address
# [undo] peer ipv4-address reflect-client
if evn_bgp_enable and self.evn_peer_ip:
cmd = "peer %s" % self.evn_peer_ip
exist = is_config_exist(self.config, cmd)
if self.state == "present":
if not exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd)
if self.evn_reflect_client == "enable":
self.cli_add_command(
"peer %s reflect-client" % self.evn_peer_ip)
else:
if self.evn_reflect_client:
cmd = "peer %s reflect-client" % self.evn_peer_ip
exist = is_config_exist(self.config, cmd)
if self.evn_reflect_client == "enable" and not exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd)
elif self.evn_reflect_client == "disable" and exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd, undo=True)
else:
if exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd, undo=True)
# [undo] server enable
if evn_bgp_enable and self.evn_server:
cmd = "server enable"
exist = is_config_exist(self.config, cmd)
if self.evn_server == "enable" and not exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd)
elif self.evn_server == "disable" and exist:
if not evn_bgp_view:
self.cli_add_command("evn bgp")
evn_bgp_view = True
self.cli_add_command(cmd, undo=True)
if evn_bgp_view:
self.cli_add_command("quit")
def config_vbdif(self):
"""configure command at the VBDIF interface view"""
# interface vbdif bd-id
# [undo] arp collect host enable
cmd = "interface %s" % self.vbdif_name.lower().capitalize()
exist = is_config_exist(self.config, cmd)
if not exist:
self.module.fail_json(
msg="Error: Interface %s does not exist." % self.vbdif_name)
cmd = "arp collect host enable"
exist = is_config_exist(self.config, cmd)
if self.arp_collect_host == "enable" and not exist:
self.cli_add_command("interface %s" %
self.vbdif_name.lower().capitalize())
self.cli_add_command(cmd)
self.cli_add_command("quit")
elif self.arp_collect_host == "disable" and exist:
self.cli_add_command("interface %s" %
self.vbdif_name.lower().capitalize())
self.cli_add_command(cmd, undo=True)
self.cli_add_command("quit")
def config_host_collect_protocal(self):
"""Enable EVN BGP or BGP EVPN to advertise host information"""
# [undo] host collect protocol bgp
cmd = "host collect protocol bgp"
exist = is_config_exist(self.config, cmd)
if self.state == "present":
if self.host_collect_protocol == "bgp" and not exist:
self.cli_add_command(cmd)
elif self.host_collect_protocol == "none" and exist:
self.cli_add_command(cmd, undo=True)
else:
if self.host_collect_protocol == "bgp" and exist:
self.cli_add_command(cmd, undo=True)
def is_valid_vbdif(self, ifname):
"""check is interface vbdif is valid"""
if not ifname.upper().startswith('VBDIF'):
return False
bdid = self.vbdif_name.replace(" ", "").upper().replace("VBDIF", "")
if not bdid.isdigit():
return False
if int(bdid) < 1 or int(bdid) > 16777215:
return False
return True
def check_params(self):
"""Check all input params"""
# bridge domain id check
if self.bridge_domain_id:
if not self.bridge_domain_id.isdigit():
self.module.fail_json(
msg="Error: Bridge domain id is not digit.")
if int(self.bridge_domain_id) < 1 or int(self.bridge_domain_id) > 16777215:
self.module.fail_json(
msg="Error: Bridge domain id is not in the range from 1 to 16777215.")
# evn_source_ip check
if self.evn_source_ip:
if not is_valid_v4addr(self.evn_source_ip):
self.module.fail_json(msg="Error: evn_source_ip is invalid.")
# evn_peer_ip check
if self.evn_peer_ip:
if not is_valid_v4addr(self.evn_peer_ip):
self.module.fail_json(msg="Error: evn_peer_ip is invalid.")
# vbdif_name check
if self.vbdif_name:
self.vbdif_name = self.vbdif_name.replace(
" ", "").lower().capitalize()
if not self.is_valid_vbdif(self.vbdif_name):
self.module.fail_json(msg="Error: vbdif_name is invalid.")
# evn_reflect_client and evn_peer_ip must set at the same time
if self.evn_reflect_client and not self.evn_peer_ip:
self.module.fail_json(
msg="Error: evn_reflect_client and evn_peer_ip must set at the same time.")
# evn_server and evn_reflect_client can not set at the same time
if self.evn_server == "enable" and self.evn_reflect_client == "enable":
self.module.fail_json(
msg="Error: evn_server and evn_reflect_client can not set at the same time.")
def get_proposed(self):
"""get proposed info"""
if self.evn_bgp:
self.proposed["evn_bgp"] = self.evn_bgp
if self.evn_source_ip:
self.proposed["evn_source_ip"] = self.evn_source_ip
if self.evn_peer_ip:
self.proposed["evn_peer_ip"] = self.evn_peer_ip
if self.evn_server:
self.proposed["evn_server"] = self.evn_server
if self.evn_reflect_client:
self.proposed["evn_reflect_client"] = self.evn_reflect_client
if self.arp_collect_host:
self.proposed["arp_collect_host"] = self.arp_collect_host
if self.host_collect_protocol:
self.proposed["host_collect_protocol"] = self.host_collect_protocol
if self.arp_suppress:
self.proposed["arp_suppress"] = self.arp_suppress
if self.vbdif_name:
self.proposed["vbdif_name"] = self.evn_peer_ip
if self.bridge_domain_id:
self.proposed["bridge_domain_id"] = self.bridge_domain_id
self.proposed["state"] = self.state
def get_existing(self):
"""get existing info"""
evn_bgp_exist = is_config_exist(self.config, "evn bgp")
if evn_bgp_exist:
self.existing["evn_bgp"] = "enable"
else:
self.existing["evn_bgp"] = "disable"
if evn_bgp_exist:
if is_config_exist(self.config, "server enable"):
self.existing["evn_server"] = "enable"
else:
self.existing["evn_server"] = "disable"
self.existing["evn_source_ip"] = get_evn_srouce(self.config)
self.existing["evn_peer_ip"] = get_evn_peers(self.config)
self.existing["evn_reflect_client"] = get_evn_reflect_client(
self.config)
if is_config_exist(self.config, "arp collect host enable"):
self.existing["host_collect_protocol"] = "enable"
else:
self.existing["host_collect_protocol"] = "disable"
if is_config_exist(self.config, "host collect protocol bgp"):
self.existing["host_collect_protocol"] = "bgp"
else:
self.existing["host_collect_protocol"] = None
if is_config_exist(self.config, "arp broadcast-suppress enable"):
self.existing["arp_suppress"] = "enable"
else:
self.existing["arp_suppress"] = "disable"
def get_end_state(self):
"""get end state info"""
config = self.get_current_config()
evn_bgp_exist = is_config_exist(config, "evn bgp")
if evn_bgp_exist:
self.end_state["evn_bgp"] = "enable"
else:
self.end_state["evn_bgp"] = "disable"
if evn_bgp_exist:
if is_config_exist(config, "server enable"):
self.end_state["evn_server"] = "enable"
else:
self.end_state["evn_server"] = "disable"
self.end_state["evn_source_ip"] = get_evn_srouce(config)
self.end_state["evn_peer_ip"] = get_evn_peers(config)
self.end_state[
"evn_reflect_client"] = get_evn_reflect_client(config)
if is_config_exist(config, "arp collect host enable"):
self.end_state["host_collect_protocol"] = "enable"
else:
self.end_state["host_collect_protocol"] = "disable"
if is_config_exist(config, "host collect protocol bgp"):
self.end_state["host_collect_protocol"] = "bgp"
else:
self.end_state["host_collect_protocol"] = None
if is_config_exist(config, "arp broadcast-suppress enable"):
self.end_state["arp_suppress"] = "enable"
else:
self.end_state["arp_suppress"] = "disable"
def work(self):
"""worker"""
self.check_params()
self.config = self.get_current_config()
self.get_existing()
self.get_proposed()
# deal present or absent
if self.evn_bgp or self.evn_server or self.evn_peer_ip or self.evn_source_ip:
self.config_evn_bgp()
if self.vbdif_name and self.arp_collect_host:
self.config_vbdif()
if self.host_collect_protocol:
self.config_host_collect_protocal()
if self.bridge_domain_id and self.arp_suppress:
self.config_bridge_domain()
if self.commands:
self.cli_load_config(self.commands)
self.changed = True
self.get_end_state()
self.results['changed'] = self.changed
self.results['proposed'] = self.proposed
self.results['existing'] = self.existing
self.results['end_state'] = self.end_state
if self.changed:
self.results['updates'] = self.updates_cmd
else:
self.results['updates'] = list()
self.module.exit_json(**self.results)
def main():
"""Module main"""
argument_spec = dict(
evn_bgp=dict(required=False, type='str',
choices=['enable', 'disable']),
evn_source_ip=dict(required=False, type='str'),
evn_peer_ip=dict(required=False, type='str'),
evn_server=dict(required=False, type='str',
choices=['enable', 'disable']),
evn_reflect_client=dict(
required=False, type='str', choices=['enable', 'disable']),
vbdif_name=dict(required=False, type='str'),
arp_collect_host=dict(required=False, type='str',
choices=['enable', 'disable']),
host_collect_protocol=dict(
required=False, type='str', choices=['bgp', 'none']),
bridge_domain_id=dict(required=False, type='str'),
arp_suppress=dict(required=False, type='str',
choices=['enable', 'disable']),
state=dict(required=False, default='present',
choices=['present', 'absent'])
)
argument_spec.update(ce_argument_spec)
module = VxlanArp(argument_spec)
module.work()
if __name__ == '__main__':
main()
|
gpl-3.0
|
deschler/django-invitation
|
examples/invitation_project/settings.py
|
9
|
1139
|
import os
ROOT_PATH = os.path.dirname(__file__)
TEMPLATE_DEBUG = DEBUG = True
MANAGERS = ADMINS = ()
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = os.path.join(ROOT_PATH, 'testdb.sqlite')
TIME_ZONE = 'America/Chicago'
LANGUAGE_CODE = 'en-us'
SITE_ID = 1
USE_I18N = True
MEDIA_ROOT = ''
MEDIA_URL = ''
ADMIN_MEDIA_PREFIX = '/media/'
SECRET_KEY = '2+@4vnr#v8e273^+a)g$8%dre^dwcn#d&n#8+l6jk7r#$p&3zk'
TEMPLATE_LOADERS = (
'django.template.loaders.filesystem.load_template_source',
'django.template.loaders.app_directories.load_template_source',
)
MIDDLEWARE_CLASSES = (
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
)
ROOT_URLCONF = 'urls'
TEMPLATE_DIRS = (os.path.join(ROOT_PATH, 'templates'),)
INSTALLED_APPS = (
'invitation',
'registration',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.sites',
'django.contrib.admin',
)
INVITE_MODE = True
ACCOUNT_INVITATION_DAYS = 30
ACCOUNT_ACTIVATION_DAYS = 20
INVITATIONS_PER_USER = 5
|
bsd-3-clause
|
t794104/ansible
|
test/units/modules/network/cnos/test_cnos_vlan.py
|
34
|
7341
|
# (c) 2018 Red Hat Inc.
#
# This file is part of Ansible
#
# Ansible is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Ansible is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
# Make coding more python3-ish
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
import json
from units.compat.mock import patch
from ansible.modules.network.cnos import cnos_vlan
from ansible.modules.network.cnos.cnos_vlan import parse_vlan_brief
from units.modules.utils import set_module_args
from .cnos_module import TestCnosModule, load_fixture
class TestCnosVlanModule(TestCnosModule):
module = cnos_vlan
def setUp(self):
super(TestCnosVlanModule, self).setUp()
self.mock_run_commands = patch('ansible.modules.network.cnos.cnos_vlan.run_commands')
self.run_commands = self.mock_run_commands.start()
self.mock_load_config = patch('ansible.modules.network.cnos.cnos_vlan.load_config')
self.load_config = self.mock_load_config.start()
def tearDown(self):
super(TestCnosVlanModule, self).tearDown()
self.mock_run_commands.stop()
self.mock_load_config.stop()
def load_fixtures(self, commands=None, transport='cli'):
self.run_commands.return_value = [load_fixture('cnos_vlan_config.cfg')]
self.load_config.return_value = {'diff': None, 'session': 'session'}
def test_cnos_vlan_create(self):
set_module_args({'vlan_id': '3', 'name': 'test', 'state': 'present'})
result = self.execute_module(changed=True)
expected_commands = [
'vlan 3',
'name test',
]
self.assertEqual(result['commands'], expected_commands)
def test_cnos_vlan_id_startwith_9(self):
set_module_args({'vlan_id': '13', 'name': 'anil', 'state': 'present'})
result = self.execute_module(changed=False)
expected_commands = []
self.assertEqual(result['commands'], expected_commands)
def test_cnos_vlan_rename(self):
set_module_args({'vlan_id': '2', 'name': 'test', 'state': 'present'})
result = self.execute_module(changed=True)
expected_commands = [
'vlan 2',
'name test',
]
self.assertEqual(result['commands'], expected_commands)
def test_cnos_vlan_with_interfaces(self):
set_module_args({'vlan_id': '2', 'name': 'vlan2', 'state': 'present',
'interfaces': ['Ethernet1/33', 'Ethernet1/44']})
result = self.execute_module(changed=True)
expected_commands = [
'vlan 2',
'name vlan2',
'vlan 2',
'interface Ethernet1/33',
'switchport mode access',
'switchport access vlan 2',
'vlan 2',
'interface Ethernet1/44',
'switchport mode access',
'switchport access vlan 2',
]
self.assertEqual(result['commands'], expected_commands)
def test_cnos_vlan_with_interfaces_and_newvlan(self):
set_module_args({'vlan_id': '3',
'name': 'vlan3', 'state': 'present',
'interfaces': ['Ethernet1/33', 'Ethernet1/44']})
result = self.execute_module(changed=True)
expected_commands = [
'vlan 3',
'name vlan3',
'vlan 3',
'interface Ethernet1/33',
'switchport mode access',
'switchport access vlan 3',
'vlan 3',
'interface Ethernet1/44',
'switchport mode access',
'switchport access vlan 3',
]
self.assertEqual(result['commands'], expected_commands)
def test_parse_vlan_brief(self):
result = parse_vlan_brief(load_fixture('cnos_vlan_config.cfg'))
obj = [
{
'interfaces': [
'po1',
'po2',
'po11',
'po12',
'po13',
'po14',
'po15',
'po17',
'po20',
'po100',
'po1001',
'po1002',
'po1003',
'po1004',
'Ethernet1/2',
'Ethernet1/3',
'Ethernet1/4',
'Ethernet1/9',
'Ethernet1/10',
'Ethernet1/11',
'Ethernet1/14',
'Ethernet1/15',
'Ethernet1/16',
'Ethernet1/17',
'Ethernet1/18',
'Ethernet1/19',
'Ethernet1/20',
'Ethernet1/21',
'Ethernet1/22',
'Ethernet1/23',
'Ethernet1/24',
'Ethernet1/25',
'Ethernet1/26',
'Ethernet1/27',
'Ethernet1/28',
'Ethernet1/29',
'Ethernet1/30',
'Ethernet1/31',
'Ethernet1/32',
'Ethernet1/33',
'Ethernet1/34',
'Ethernet1/35',
'Ethernet1/36',
'Ethernet1/37',
'Ethernet1/38',
'Ethernet1/39',
'Ethernet1/40',
'Ethernet1/41',
'Ethernet1/42',
'Ethernet1/43',
'Ethernet1/44',
'Ethernet1/45',
'Ethernet1/46',
'Ethernet1/47',
'Ethernet1/48',
'Ethernet1/49',
'Ethernet1/50',
'Ethernet1/51',
'Ethernet1/52',
'Ethernet1/53',
'Ethernet1/54'],
'state': 'ACTIVE',
'name': 'default',
'vlan_id': '1'},
{
'interfaces': [],
'state': 'ACTIVE',
'name': 'VLAN0002',
'vlan_id': '2'},
{
'interfaces': [],
'state': 'ACTIVE',
'name': 'VLAN0003',
'vlan_id': '3'},
{
'interfaces': [],
'state': 'ACTIVE',
'name': 'VLAN0005',
'vlan_id': '5'},
{
'interfaces': [],
'state': 'ACTIVE',
'name': 'VLAN0012',
'vlan_id': '12'},
{
'interfaces': [],
'state': 'ACTIVE',
'name': 'anil',
'vlan_id': '13'}]
self.assertEqual(result, obj)
|
gpl-3.0
|
madecoste/swarming
|
appengine/components/third_party/webtest/forms.py
|
5
|
18091
|
# -*- coding: utf-8 -*-
"""Helpers to fill and submit forms."""
import re
from bs4 import BeautifulSoup
from webtest.compat import OrderedDict
from webtest import utils
class NoValue(object):
pass
class Upload(object):
"""
A file to upload::
>>> Upload('filename.txt', 'data', 'application/octet-stream')
<Upload "filename.txt">
>>> Upload('filename.txt', 'data')
<Upload "filename.txt">
>>> Upload("README.txt")
<Upload "README.txt">
:param filename: Name of the file to upload.
:param content: Contents of the file.
:param content_type: MIME type of the file.
"""
def __init__(self, filename, content=None, content_type=None):
self.filename = filename
self.content = content
self.content_type = content_type
def __iter__(self):
yield self.filename
if self.content:
yield self.content
yield self.content_type
# TODO: do we handle the case when we need to get
# contents ourselves?
def __repr__(self):
return '<Upload "%s">' % self.filename
class Field(object):
"""Base class for all Field objects.
.. attribute:: classes
Dictionary of field types (select, radio, etc)
.. attribute:: value
Set/get value of the field.
"""
classes = {}
def __init__(self, form, tag, name, pos,
value=None, id=None, **attrs):
self.form = form
self.tag = tag
self.name = name
self.pos = pos
self._value = value
self.id = id
self.attrs = attrs
def value__get(self):
if self._value is None:
return ''
else:
return self._value
def value__set(self, value):
self._value = value
value = property(value__get, value__set)
def force_value(self, value):
"""Like setting a value, except forces it (even for, say, hidden
fields).
"""
self._value = value
def __repr__(self):
value = '<%s name="%s"' % (self.__class__.__name__, self.name)
if self.id:
value += ' id="%s"' % self.id
return value + '>'
class Select(Field):
"""Field representing ``<select />`` form element."""
def __init__(self, *args, **attrs):
super(Select, self).__init__(*args, **attrs)
self.options = []
# Undetermined yet:
self.selectedIndex = None
# we have no forced value
self._forced_value = NoValue
def force_value(self, value):
"""Like setting a value, except forces it (even for, say, hidden
fields).
"""
self._forced_value = value
def value__set(self, value):
if self._forced_value is not NoValue:
self._forced_value = NoValue
for i, (option, checked) in enumerate(self.options):
if option == utils.stringify(value):
self.selectedIndex = i
break
else:
raise ValueError(
"Option %r not found (from %s)"
% (value, ', '.join(
[repr(o) for o, c in self.options])))
def value__get(self):
if self._forced_value is not NoValue:
return self._forced_value
elif self.selectedIndex is not None:
return self.options[self.selectedIndex][0]
else:
for option, checked in self.options:
if checked:
return option
else:
if self.options:
return self.options[0][0]
value = property(value__get, value__set)
class MultipleSelect(Field):
"""Field representing ``<select multiple="multiple">``"""
def __init__(self, *args, **attrs):
super(MultipleSelect, self).__init__(*args, **attrs)
self.options = []
# Undetermined yet:
self.selectedIndices = []
self._forced_values = []
def force_value(self, values):
"""Like setting a value, except forces it (even for, say, hidden
fields).
"""
self._forced_values = values
self.selectedIndices = []
def value__set(self, values):
str_values = [utils.stringify(value) for value in values]
self.selectedIndices = []
for i, (option, checked) in enumerate(self.options):
if option in str_values:
self.selectedIndices.append(i)
str_values.remove(option)
if str_values:
raise ValueError(
"Option(s) %r not found (from %s)"
% (', '.join(str_values),
', '.join([repr(o) for o, c in self.options])))
def value__get(self):
selected_values = []
if self.selectedIndices:
selected_values = [self.options[i][0]
for i in self.selectedIndices]
elif not self._forced_values:
selected_values = []
for option, checked in self.options:
if checked:
selected_values.append(option)
if self._forced_values:
selected_values += self._forced_values
if self.options and (not selected_values):
selected_values = None
return selected_values
value = property(value__get, value__set)
class Radio(Select):
"""Field representing ``<input type="radio">``"""
def value__get(self):
if self.selectedIndex is not None:
return self.options[self.selectedIndex][0]
else:
for option, checked in self.options:
if checked:
return option
else:
return None
value = property(value__get, Select.value__set)
class Checkbox(Field):
"""Field representing ``<input type="checkbox">``
.. attribute:: checked
Returns True if checkbox is checked.
"""
def __init__(self, *args, **attrs):
super(Checkbox, self).__init__(*args, **attrs)
self._checked = 'checked' in attrs
def value__set(self, value):
self._checked = not not value
def value__get(self):
if self._checked:
if self._value is None:
return 'on'
else:
return self._value
else:
return None
value = property(value__get, value__set)
def checked__get(self):
return bool(self._checked)
def checked__set(self, value):
self._checked = not not value
checked = property(checked__get, checked__set)
class Text(Field):
"""Field representing ``<input type="text">``"""
class File(Field):
"""Field representing ``<input type="file">``"""
# TODO: This doesn't actually handle file uploads and enctype
def value__get(self):
if self._value is None:
return ''
else:
return self._value
value = property(value__get, Field.value__set)
class Textarea(Text):
"""Field representing ``<textarea>``"""
class Hidden(Text):
"""Field representing ``<input type="hidden">``"""
class Submit(Field):
"""Field representing ``<input type="submit">`` and ``<button>``"""
def value__get(self):
return None
def value__set(self, value):
raise AttributeError(
"You cannot set the value of the <%s> field %r"
% (self.tag, self.name))
value = property(value__get, value__set)
def value_if_submitted(self):
# TODO: does this ever get set?
return self._value
Field.classes['submit'] = Submit
Field.classes['button'] = Submit
Field.classes['image'] = Submit
Field.classes['multiple_select'] = MultipleSelect
Field.classes['select'] = Select
Field.classes['hidden'] = Hidden
Field.classes['file'] = File
Field.classes['text'] = Text
Field.classes['password'] = Text
Field.classes['checkbox'] = Checkbox
Field.classes['textarea'] = Textarea
Field.classes['radio'] = Radio
class Form(object):
"""This object represents a form that has been found in a page.
:param response: `webob.response.TestResponse` instance
:param text: Unparsed html of the form
.. attribute:: text
the full HTML of the form.
.. attribute:: action
the relative URI of the action.
.. attribute:: method
the HTTP method (e.g., ``'GET'``).
.. attribute:: id
the id, or None if not given.
.. attribute:: enctype
encoding of the form submission
.. attribute:: fields
a dictionary of fields, each value is a list of fields by
that name. ``<input type=\"radio\">`` and ``<select>`` are
both represented as single fields with multiple options.
.. attribute:: field_order
Ordered list of field names as found in the html.
"""
# TODO: use BeautifulSoup4 for this
_tag_re = re.compile(r'<(/?)([a-z0-9_\-]*)([^>]*?)>', re.I)
_label_re = re.compile(
'''<label\s+(?:[^>]*)for=(?:"|')([a-z0-9_\-]+)(?:"|')(?:[^>]*)>''',
re.I)
FieldClass = Field
def __init__(self, response, text):
self.response = response
self.text = text
self.html = BeautifulSoup(self.text, "html.parser")
attrs = self.html('form')[0].attrs
self.action = attrs.get('action', '')
self.method = attrs.get('method', 'GET')
self.id = attrs.get('id')
self.enctype = attrs.get('enctype',
'application/x-www-form-urlencoded')
self._parse_fields()
def _parse_fields(self):
fields = OrderedDict()
field_order = []
tags = ('input', 'select', 'textarea', 'button')
for pos, node in enumerate(self.html.findAll(tags)):
attrs = dict(node.attrs)
tag = node.name
name = None
if 'name' in attrs:
name = attrs.pop('name')
if tag == 'textarea':
if node.text.startswith('\r\n'):
text = node.text[2:]
elif node.text.startswith('\n'):
text = node.text[1:]
else:
text = node.text
attrs['value'] = text
tag_type = attrs.get('type', 'text').lower()
if tag == 'select':
tag_type = 'select'
if tag_type == "select" and "multiple" in attrs:
tag_type = "multiple_select"
if tag == 'button':
tag_type = 'submit'
FieldClass = self.FieldClass.classes.get(tag_type,
self.FieldClass)
if tag == 'input':
if tag_type == 'radio':
field = fields.get(name)
if not field:
field = FieldClass(self, tag, name, pos, **attrs)
fields.setdefault(name, []).append(field)
field_order.append((name, field))
else:
field = field[0]
assert isinstance(field,
self.FieldClass.classes['radio'])
field.options.append((attrs.get('value'),
'checked' in attrs))
continue
field = FieldClass(self, tag, name, pos, **attrs)
fields.setdefault(name, []).append(field)
field_order.append((name, field))
if tag == 'select':
for option in node('option'):
field.options.append((option.attrs.get('value', option.text),
'selected' in option.attrs))
self.field_order = field_order
self.fields = fields
def __setitem__(self, name, value):
"""Set the value of the named field. If there is 0 or multiple fields
by that name, it is an error.
Multiple checkboxes of the same name are special-cased; a list may be
assigned to them to check the checkboxes whose value is present in the
list (and uncheck all others).
Setting the value of a ``<select>`` selects the given option (and
confirms it is an option). Setting radio fields does the same.
Checkboxes get boolean values. You cannot set hidden fields or buttons.
Use ``.set()`` if there is any ambiguity and you must provide an index.
"""
fields = self.fields.get(name)
assert fields is not None, (
"No field by the name %r found (fields: %s)"
% (name, ', '.join(map(repr, self.fields.keys()))))
all_checkboxes = all(isinstance(f, Checkbox) for f in fields)
if all_checkboxes and isinstance(value, list):
values = set(utils.stringify(v) for v in value)
for f in fields:
f.checked = f._value in values
else:
assert len(fields) == 1, (
"Multiple fields match %r: %s"
% (name, ', '.join(map(repr, fields))))
fields[0].value = value
def __getitem__(self, name):
"""Get the named field object (ambiguity is an error)."""
fields = self.fields.get(name)
assert fields is not None, (
"No field by the name %r found" % name)
assert len(fields) == 1, (
"Multiple fields match %r: %s"
% (name, ', '.join(map(repr, fields))))
return fields[0]
def lint(self):
"""
Check that the html is valid:
- each field must have an id
- each field must have a label
"""
labels = self._label_re.findall(self.text)
for name, fields in self.fields.items():
for field in fields:
if not isinstance(field, (Submit, Hidden)):
if not field.id:
raise AttributeError("%r as no id attribute" % field)
elif field.id not in labels:
raise AttributeError(
"%r as no associated label" % field)
def set(self, name, value, index=None):
"""Set the given name, using ``index`` to disambiguate."""
if index is None:
self[name] = value
else:
fields = self.fields.get(name)
assert fields is not None, (
"No fields found matching %r" % name)
field = fields[index]
field.value = value
def get(self, name, index=None, default=utils.NoDefault):
"""
Get the named/indexed field object, or ``default`` if no field is
found. Throws an AssertionError if no field is found and no ``default``
was given.
"""
fields = self.fields.get(name)
if fields is None:
if default is utils.NoDefault:
raise AssertionError(
"No fields found matching %r (and no default given)"
% name)
return default
if index is None:
return self[name]
return fields[index]
def select(self, name, value, index=None):
"""Like ``.set()``, except also confirms the target is a ``<select>``.
"""
field = self.get(name, index=index)
assert isinstance(field, Select)
field.value = value
def submit(self, name=None, index=None, **args):
"""Submits the form. If ``name`` is given, then also select that
button (using ``index`` to disambiguate)``.
Any extra keyword arguments are passed to the
:meth:`webtest.TestResponse.get` or
:meth:`webtest.TestResponse.post` method.
Returns a :class:`webtest.TestResponse` object.
"""
fields = self.submit_fields(name, index=index)
if self.method.upper() != "GET":
args.setdefault("content_type", self.enctype)
return self.response.goto(self.action, method=self.method,
params=fields, **args)
def upload_fields(self):
"""Return a list of file field tuples of the form::
(field name, file name)
or::
(field name, file name, file contents).
"""
uploads = []
for name, fields in self.fields.items():
for field in fields:
if isinstance(field, File) and field.value:
uploads.append([name] + list(field.value))
return uploads
def submit_fields(self, name=None, index=None):
"""Return a list of ``[(name, value), ...]`` for the current state of
the form.
:param name: Same as for :meth:`submit`
:param index: Same as for :meth:`submit`
"""
submit = []
# Use another name here so we can keep function param the same for BWC.
submit_name = name
if index is None:
index = 0
# This counts all fields with the submit name not just submit fields.
current_index = 0
for name, field in self.field_order:
if name is None: # pragma: no cover
continue
if submit_name is not None and name == submit_name:
if current_index == index:
submit.append((name, field.value_if_submitted()))
current_index += 1
else:
value = field.value
if value is None:
continue
if isinstance(field, File):
submit.append((name, field))
continue
if isinstance(value, list):
for item in value:
submit.append((name, item))
else:
submit.append((name, value))
return submit
def __repr__(self):
value = '<Form'
if self.id:
value += ' id=%r' % str(self.id)
return value + ' />'
|
apache-2.0
|
drewandersonnz/openshift-tools
|
openshift/installer/vendored/openshift-ansible-3.9.14-1/roles/openshift_health_checker/test/rpm_version_test.py
|
56
|
2120
|
import pytest
import rpm_version
expected_pkgs = {
"spam": {
"name": "spam",
"version": "3.2.1",
},
"eggs": {
"name": "eggs",
"version": "3.2.1",
},
}
@pytest.mark.parametrize('pkgs, expect_not_found', [
(
{},
["spam", "eggs"], # none found
),
(
{"spam": ["3.2.1", "4.5.1"]},
["eggs"], # completely missing
),
(
{
"spam": ["3.2.1", "4.5.1"],
"eggs": ["3.2.1"],
},
[], # all found
),
])
def test_check_pkg_found(pkgs, expect_not_found):
if expect_not_found:
with pytest.raises(rpm_version.RpmVersionException) as e:
rpm_version._check_pkg_versions(pkgs, expected_pkgs)
assert "not found to be installed" in str(e.value)
assert set(expect_not_found) == set(e.value.problem_pkgs)
else:
rpm_version._check_pkg_versions(pkgs, expected_pkgs)
@pytest.mark.parametrize('pkgs, expect_not_found', [
(
{
'spam': ['3.2.1'],
'eggs': ['3.3.2'],
},
{
"eggs": {
"required_versions": ["3.2"],
"found_versions": ["3.3"],
}
}, # not the right version
),
(
{
'spam': ['3.1.2', "3.3.2"],
'eggs': ['3.3.2', "1.2.3"],
},
{
"eggs": {
"required_versions": ["3.2"],
"found_versions": ["3.3", "1.2"],
},
"spam": {
"required_versions": ["3.2"],
"found_versions": ["3.1", "3.3"],
}
}, # not the right version
),
])
def test_check_pkg_version_found(pkgs, expect_not_found):
if expect_not_found:
with pytest.raises(rpm_version.RpmVersionException) as e:
rpm_version._check_pkg_versions(pkgs, expected_pkgs)
assert "found to be installed with an incorrect version" in str(e.value)
assert expect_not_found == e.value.problem_pkgs
else:
rpm_version._check_pkg_versions(pkgs, expected_pkgs)
|
apache-2.0
|
rsvip/Django
|
tests/defer_regress/models.py
|
104
|
2530
|
"""
Regression tests for defer() / only() behavior.
"""
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
@python_2_unicode_compatible
class Item(models.Model):
name = models.CharField(max_length=15)
text = models.TextField(default="xyzzy")
value = models.IntegerField()
other_value = models.IntegerField(default=0)
def __str__(self):
return self.name
class RelatedItem(models.Model):
item = models.ForeignKey(Item)
class ProxyRelated(RelatedItem):
class Meta:
proxy = True
class Child(models.Model):
name = models.CharField(max_length=10)
value = models.IntegerField()
@python_2_unicode_compatible
class Leaf(models.Model):
name = models.CharField(max_length=10)
child = models.ForeignKey(Child)
second_child = models.ForeignKey(Child, related_name="other", null=True)
value = models.IntegerField(default=42)
def __str__(self):
return self.name
class ResolveThis(models.Model):
num = models.FloatField()
name = models.CharField(max_length=16)
class Proxy(Item):
class Meta:
proxy = True
@python_2_unicode_compatible
class SimpleItem(models.Model):
name = models.CharField(max_length=15)
value = models.IntegerField()
def __str__(self):
return self.name
class Feature(models.Model):
item = models.ForeignKey(SimpleItem)
class SpecialFeature(models.Model):
feature = models.ForeignKey(Feature)
class OneToOneItem(models.Model):
item = models.OneToOneField(Item, related_name="one_to_one_item")
name = models.CharField(max_length=15)
class ItemAndSimpleItem(models.Model):
item = models.ForeignKey(Item)
simple = models.ForeignKey(SimpleItem)
class Profile(models.Model):
profile1 = models.CharField(max_length=1000, default='profile1')
class Location(models.Model):
location1 = models.CharField(max_length=1000, default='location1')
class Request(models.Model):
profile = models.ForeignKey(Profile, null=True, blank=True)
location = models.ForeignKey(Location)
items = models.ManyToManyField(Item)
request1 = models.CharField(default='request1', max_length=1000)
request2 = models.CharField(default='request2', max_length=1000)
request3 = models.CharField(default='request3', max_length=1000)
request4 = models.CharField(default='request4', max_length=1000)
class Base(models.Model):
text = models.TextField()
class Derived(Base):
other_text = models.TextField()
|
bsd-3-clause
|
lpatmo/actionify_the_news
|
open_connect/accounts/forms.py
|
1
|
8077
|
"""Forms for accounts app."""
# pylint: disable=no-init,no-self-use
from django import forms
from django.contrib.admin import widgets
from django.contrib.auth.models import Group as AuthGroup
from django.contrib.auth.models import Permission
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.utils.timezone import now
from email.utils import formataddr
from open_connect.accounts.models import User, Invite
from open_connect.mailer.utils import clean_addresses
from open_connect.media.models import Image
from open_connect.groups.models import Group
from open_connect.connectmessages.models import Thread
from open_connect.connect_core.utils.mixins import SanitizeHTMLMixin
YES_NO_CHOICES = (('no', 'No'), ('yes', 'Yes'))
class UserImageForm(forms.ModelForm):
"""Form for GroupImage model."""
image = forms.ImageField(required=False)
class Meta(object):
"""Meta options."""
model = Image
fields = ['image']
class UserForm(SanitizeHTMLMixin, forms.ModelForm):
"""Form for creating/editing a user."""
class Meta(object):
"""Meta options for UserForm."""
model = User
fields = [
'first_name', 'last_name', 'biography', 'timezone',
'facebook_url', 'twitter_handle', 'website_url',
'group_notification_period', 'show_groups_on_profile',
'receive_group_join_notifications'
]
def clean_biography(self):
"""Strip invalid html from biography field."""
return self.sanitize_html(self.cleaned_data['biography'])
class UserAdminForm(forms.ModelForm):
"""Form for administering a User in the Django admin"""
class Meta(object):
"""Meta options for the User Admin Form"""
model = User
exclude = []
def __init__(self, *args, **kwargs):
"""Initialize the User Admin Form"""
super(UserAdminForm, self).__init__(*args, **kwargs)
class TermsAndConductAcceptForm(forms.Form):
"""Form for accepting terms and conduct agreements."""
accept_tos = forms.BooleanField(
required=True,
widget=forms.HiddenInput(),
label=u'I agree to the Connect Terms of Service.'
)
accept_ucoc = forms.BooleanField(
required=True,
widget=forms.HiddenInput(),
label=u'I agree to the Connect User Code of Conduct.'
)
next = forms.CharField(widget=forms.HiddenInput())
def save(self, user_id):
"""Save the form."""
user = User.objects.get(pk=user_id)
user.tos_accepted_at = now()
user.ucoc_accepted_at = now()
user.save()
return user
class InviteForm(forms.Form):
"""Form for inviting a user."""
emails = forms.CharField(
widget=forms.Textarea(),
help_text='Use a comma to separate multiple addresses.'
)
is_staff = forms.BooleanField(required=False)
is_superuser = forms.BooleanField(required=False)
groups = forms.ModelMultipleChoiceField(
queryset=Group.objects.filter(),
required=False
)
def clean_emails(self):
"""Clean up email field to only include symantically valid addresses"""
emails = clean_addresses(self.data['emails'])
if not len(emails):
raise ValidationError('No Valid Addresses Found')
email_string = [formataddr(entry) for entry in emails]
return email_string
def save(self):
"""Save the form."""
is_staff = self.cleaned_data.get('is_staff', False)
is_superuser = self.cleaned_data.get('is_superuser', False)
groups = self.cleaned_data['groups']
created_by = self.created_by
invites = []
for email in self.cleaned_data['emails']:
invite, created = Invite.objects.get_or_create(
email=email,
defaults={
'is_staff': is_staff,
'is_superuser': is_superuser,
'created_by': created_by
}
)
invite.send_invite(sender_id=self.created_by.pk)
if created:
# pylint: disable=expression-not-assigned
[invite.groups.add(group) for group in groups]
invites.append(invite)
return invites
class BanUserForm(forms.Form):
"""Form for banning a user."""
user = forms.ModelChoiceField(
queryset=User.objects.all(),
widget=forms.HiddenInput()
)
confirm = forms.BooleanField(
label='Are you sure you want to ban this user?',
required=False
)
def save(self):
"""Save the form result."""
if not self.cleaned_data['confirm']:
return
user = self.cleaned_data['user']
most_recent_threads = Thread.objects.filter(
latest_message__sender=user,
).exclude(first_message__sender=user)
for thread in most_recent_threads:
try:
latest_message = thread.message_set.exclude(
sender=user).filter(status='approved').latest('created_at')
except ObjectDoesNotExist:
continue
thread.latest_message = latest_message
thread.save()
User.objects.filter(
pk=user.pk).update(is_banned=True)
class UnBanUserForm(forms.Form):
"""Form for unbanning a user."""
user = forms.ModelChoiceField(
queryset=User.objects.all(),
widget=forms.HiddenInput()
)
confirm = forms.BooleanField(
label='Are you sure you want to unban this user?',
required=False
)
def save(self):
"""Save the form result."""
if not self.cleaned_data['confirm']:
return
user = self.cleaned_data['user']
threads = Thread.objects.filter(
message__sender=user, message__status='approved'
)
for thread in threads:
latest_message = thread.message_set.latest('created_at')
if thread.latest_message != latest_message:
thread.latest_message = latest_message
thread.save()
User.objects.filter(
pk=user.pk).update(is_banned=False)
class BecomeUserForm(forms.Form):
"""Form to become another user."""
user_to_become = forms.ModelChoiceField(
queryset=User.objects.all(),
widget=forms.HiddenInput()
)
class InviteEntryForm(forms.Form):
"""Form for consuming an invite."""
invite_code = forms.CharField(max_length=32)
def clean_invite_code(self):
"""Verify the invite code and return the invite object."""
try:
invite = Invite.objects.get(
code=self.cleaned_data['invite_code'],
consumed_at__isnull=True
)
except Invite.DoesNotExist:
raise ValidationError('Invalid invite code')
return invite
def save(self):
"""Consume the invite and update the user."""
self.cleaned_data['invite_code'].use_invite(self.user_id)
class AssignToPermGroupForm(forms.Form):
"""Form for adding users to a permission group in admin."""
permission_group = forms.ModelChoiceField(
queryset=AuthGroup.objects.filter(group__isnull=True),
help_text='Select a permission group to assign users to'
)
users = forms.ModelMultipleChoiceField(
queryset=User.objects.all(),
widget=forms.MultipleHiddenInput()
)
def save(self):
"""Save the form."""
group = self.cleaned_data['permission_group']
for user in self.cleaned_data['users']:
group.user_set.add(user)
class UserPermissionForm(forms.ModelForm):
"""Form for modifying user permissions."""
user_permissions = forms.ModelMultipleChoiceField(
queryset=Permission.objects.all(),
required=False,
widget=widgets.FilteredSelectMultiple('Permission', False))
class Meta(object):
"""Meta options."""
model = User
fields = ['user_permissions']
|
mit
|
teamtuga4/teamtuga4ever.repository
|
plugin.video.pancas/resources/lib/resolvers/veehd.py
|
23
|
1650
|
# -*- coding: utf-8 -*-
'''
Specto Add-on
Copyright (C) 2015 lambda
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
'''
import re,urllib,urlparse
from resources.lib.libraries import client
def resolve(url):
try:
result = client.request(url, close=False)
result = result.replace('\n','')
url = re.compile('function\s*load_download.+?src\s*:\s*"(.+?)"').findall(result)[0]
url = urlparse.urljoin('http://veehd.com', url)
result = client.request(url, close=False)
i = client.parseDOM(result, 'iframe', ret='src')
if len(i) > 0:
i = urlparse.urljoin('http://veehd.com', i[0])
client.request(i, close=False)
result = client.request(url)
url = re.compile('href *= *"([^"]+(?:mkv|mp4|avi))"').findall(result)
url += re.compile('src *= *"([^"]+(?:divx|avi))"').findall(result)
url += re.compile('"url" *: *"(.+?)"').findall(result)
url = urllib.unquote(url[0])
return url
except:
return
|
gpl-2.0
|
Omicia/omicia_api_examples
|
python/ClinicalReportLaunchers/get_clinical_report.py
|
1
|
1764
|
"""Get a clinical report, either with extended information or not.
Example usages:
python get_clinical_report.py 1801
python get_clinical_report.py 1801 --e true
"""
import os
import requests
from requests.auth import HTTPBasicAuth
import sys
import simplejson as json
import argparse
# Load environment variables for request authentication parameters
if "FABRIC_API_PASSWORD" not in os.environ:
sys.exit("FABRIC_API_PASSWORD environment variable missing")
if "FABRIC_API_LOGIN" not in os.environ:
sys.exit("FABRIC_API_LOGIN environment variable missing")
FABRIC_API_LOGIN = os.environ['FABRIC_API_LOGIN']
FABRIC_API_PASSWORD = os.environ['FABRIC_API_PASSWORD']
FABRIC_API_URL = os.environ.get('FABRIC_API_URL', 'https://api.fabricgenomics.com')
auth = HTTPBasicAuth(FABRIC_API_LOGIN, FABRIC_API_PASSWORD)
def get_clinical_report(cr_id, extended=False):
"""Use the Omicia API to get a clinical report, either with or without
extended variant and fields information
"""
# Construct request
url = "{}/reports/{}/"
if extended:
url += "?extended=True"
url = url.format(FABRIC_API_URL, cr_id)
sys.stdout.flush()
result = requests.get(url, auth=auth)
return result.json()
def main():
"""Main function. Get a clinical report by ID.
"""
parser = argparse.ArgumentParser(description='Fetch a clinical report')
parser.add_argument('c', metavar='clinical_report_id', type=int)
parser.add_argument('--e', metavar='extended', type=bool, default=False)
args = parser.parse_args()
cr_id = args.c
extended = args.e
json_response = get_clinical_report(cr_id, extended=extended)
sys.stdout.write(json.dumps(json_response, indent=4))
if __name__ == "__main__":
main()
|
mit
|
EDUlib/edx-platform
|
common/lib/xmodule/xmodule/course_module.py
|
1
|
63430
|
"""
Django module container for classes and operations related to the "Course Module" content type
"""
import json
import logging
from datetime import datetime, timedelta
from io import BytesIO
import dateutil.parser
import requests
from django.conf import settings
from django.core.validators import validate_email
from lazy import lazy
from lxml import etree
from path import Path as path
from pytz import utc
from xblock.fields import Boolean, Dict, Float, Integer, List, Scope, String
from openedx.core.djangoapps.video_pipeline.models import VideoUploadsEnabledByDefault
from openedx.core.lib.license import LicenseMixin
from openedx.core.lib.teams_config import TeamsConfig # lint-amnesty, pylint: disable=unused-import
from xmodule import course_metadata_utils
from xmodule.course_metadata_utils import DEFAULT_GRADING_POLICY, DEFAULT_START_DATE
from xmodule.graders import grader_from_conf
from xmodule.seq_module import SequenceBlock
from xmodule.tabs import CourseTabList, InvalidTabsException
from .fields import Date
from .modulestore.exceptions import InvalidProctoringProvider
log = logging.getLogger(__name__)
# Make '_' a no-op so we can scrape strings. Using lambda instead of
# `django.utils.translation.ugettext_noop` because Django cannot be imported in this file
_ = lambda text: text
CATALOG_VISIBILITY_CATALOG_AND_ABOUT = "both"
CATALOG_VISIBILITY_ABOUT = "about"
CATALOG_VISIBILITY_NONE = "none"
DEFAULT_COURSE_VISIBILITY_IN_CATALOG = getattr(
settings,
'DEFAULT_COURSE_VISIBILITY_IN_CATALOG',
'both'
)
DEFAULT_MOBILE_AVAILABLE = getattr(settings, 'DEFAULT_MOBILE_AVAILABLE', False)
# Note: updating assets does not have settings defined, so using `getattr`.
EXAM_SETTINGS_HTML_VIEW_ENABLED = getattr(settings, 'FEATURES', {}).get('ENABLE_EXAM_SETTINGS_HTML_VIEW', False)
SPECIAL_EXAMS_ENABLED = getattr(settings, 'FEATURES', {}).get('ENABLE_SPECIAL_EXAMS', False)
COURSE_VISIBILITY_PRIVATE = 'private'
COURSE_VISIBILITY_PUBLIC_OUTLINE = 'public_outline'
COURSE_VISIBILITY_PUBLIC = 'public'
class StringOrDate(Date): # lint-amnesty, pylint: disable=missing-class-docstring
def from_json(self, value): # lint-amnesty, pylint: disable=arguments-differ
"""
Parse an optional metadata key containing a time or a string:
if present, assume it's a string if it doesn't parse.
"""
try:
result = super().from_json(value)
except ValueError:
return value
if result is None:
return value
else:
return result
def to_json(self, value):
"""
Convert a time struct or string to a string.
"""
try:
result = super().to_json(value)
except: # lint-amnesty, pylint: disable=bare-except
return value
if result is None:
return value
else:
return result
class EmailString(String):
"""
Parse String with email validation
"""
def from_json(self, value):
if value:
validate_email(value)
return value
else:
return None
edx_xml_parser = etree.XMLParser(dtd_validation=False, load_dtd=False,
remove_comments=True, remove_blank_text=True)
_cached_toc = {}
class Textbook: # lint-amnesty, pylint: disable=missing-class-docstring,eq-without-hash
def __init__(self, title, book_url):
self.title = title
self.book_url = book_url
@lazy
def start_page(self):
return int(self.table_of_contents[0].attrib['page'])
@lazy
def end_page(self): # lint-amnesty, pylint: disable=missing-function-docstring
# The last page should be the last element in the table of contents,
# but it may be nested. So recurse all the way down the last element
last_el = self.table_of_contents[-1]
while last_el.getchildren():
last_el = last_el[-1]
return int(last_el.attrib['page'])
@lazy
def table_of_contents(self):
"""
Accesses the textbook's table of contents (default name "toc.xml") at the URL self.book_url
Returns XML tree representation of the table of contents
"""
toc_url = self.book_url + 'toc.xml'
# cdodge: I've added this caching of TOC because in Mongo-backed instances (but not Filesystem stores)
# course modules have a very short lifespan and are constantly being created and torn down.
# Since this module in the __init__() method does a synchronous call to AWS to get the TOC
# this is causing a big performance problem. So let's be a bit smarter about this and cache
# each fetch and store in-mem for 10 minutes.
# NOTE: I have to get this onto sandbox ASAP as we're having runtime failures. I'd like to swing back and
# rewrite to use the traditional Django in-memory cache.
try:
# see if we already fetched this
if toc_url in _cached_toc:
(table_of_contents, timestamp) = _cached_toc[toc_url]
age = datetime.now(utc) - timestamp
# expire every 10 minutes
if age.seconds < 600:
return table_of_contents
except Exception as err: # lint-amnesty, pylint: disable=broad-except
pass
# Get the table of contents from S3
log.info("Retrieving textbook table of contents from %s", toc_url)
try:
r = requests.get(toc_url)
except Exception as err:
msg = f'Error {err}: Unable to retrieve textbook table of contents at {toc_url}'
log.error(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
# TOC is XML. Parse it
try:
table_of_contents = etree.fromstring(r.text)
except Exception as err:
msg = f'Error {err}: Unable to parse XML for textbook table of contents at {toc_url}'
log.error(msg)
raise Exception(msg) # lint-amnesty, pylint: disable=raise-missing-from
return table_of_contents
def __eq__(self, other):
return (self.title == other.title and
self.book_url == other.book_url)
def __ne__(self, other):
return not self == other
class TextbookList(List): # lint-amnesty, pylint: disable=missing-class-docstring
def from_json(self, values): # lint-amnesty, pylint: disable=arguments-differ
textbooks = []
for title, book_url in values:
try:
textbooks.append(Textbook(title, book_url))
except: # lint-amnesty, pylint: disable=bare-except
# If we can't get to S3 (e.g. on a train with no internet), don't break
# the rest of the courseware.
log.exception(f"Couldn't load textbook ({title}, {book_url})")
continue
return textbooks
def to_json(self, values): # lint-amnesty, pylint: disable=arguments-differ
json_data = []
for val in values:
if isinstance(val, Textbook):
json_data.append((val.title, val.book_url))
elif isinstance(val, tuple):
json_data.append(val)
else:
continue
return json_data
class ProctoringProvider(String):
"""
ProctoringProvider field, which includes validation of the provider
and default that pulls from edx platform settings.
"""
def from_json(self, value):
"""
Return ProctoringProvider as full featured Python type. Perform validation on the provider
and include any inherited values from the platform default.
"""
value = super().from_json(value)
self._validate_proctoring_provider(value)
value = self._get_proctoring_value(value)
return value
def _get_proctoring_value(self, value):
"""
Return a proctoring value that includes any inherited attributes from the platform defaults
for the provider.
"""
# if provider is missing from the value, return the default
if value is None:
return self.default
return value
def _validate_proctoring_provider(self, value):
"""
Validate the value for the proctoring provider. If the proctoring provider value is
specified, and it is not one of the providers configured at the platform level, return
a list of error messages to the caller.
"""
available_providers = get_available_providers()
if value is not None and value not in available_providers:
raise InvalidProctoringProvider(value, available_providers)
@property
def default(self):
"""
Return default value for ProctoringProvider.
"""
default = super().default
proctoring_backend_settings = getattr(settings, 'PROCTORING_BACKENDS', None)
if proctoring_backend_settings:
return proctoring_backend_settings.get('DEFAULT', None)
return default
def get_available_providers(): # lint-amnesty, pylint: disable=missing-function-docstring
proctoring_backend_settings = getattr(
settings,
'PROCTORING_BACKENDS',
{}
)
available_providers = [provider for provider in proctoring_backend_settings if provider != 'DEFAULT']
available_providers.sort()
return available_providers
class TeamsConfigField(Dict):
"""
XBlock field for teams configuration, including definitions for teamsets.
Serializes to JSON dictionary.
"""
_default = TeamsConfig({})
def from_json(self, value):
"""
Return a TeamsConfig instance from a dict.
"""
return TeamsConfig(value)
def to_json(self, value):
"""
Convert a TeamsConfig instance back to a dict.
If we have the data that was used to build the TeamsConfig instance,
return that instead of `value.cleaned_data`, thus preserving the
data in the form that the user entered it.
"""
if value.source_data is not None:
return value.source_data
return value.cleaned_data
class CourseFields: # lint-amnesty, pylint: disable=missing-class-docstring
lti_passports = List(
display_name=_("LTI Passports"),
help=_('Enter the passports for course LTI tools in the following format: "id:client_key:client_secret".'),
scope=Scope.settings
)
textbooks = TextbookList(
help=_("List of Textbook objects with (title, url) for textbooks used in this course"),
default=[],
scope=Scope.content
)
wiki_slug = String(help=_("Slug that points to the wiki for this course"), scope=Scope.content)
enrollment_start = Date(help=_("Date that enrollment for this class is opened"), scope=Scope.settings)
enrollment_end = Date(help=_("Date that enrollment for this class is closed"), scope=Scope.settings)
start = Date(
help=_("Start time when this module is visible"),
default=DEFAULT_START_DATE,
scope=Scope.settings
)
end = Date(help=_("Date that this class ends"), scope=Scope.settings)
certificate_available_date = Date(
help=_("Date that certificates become available to learners"),
scope=Scope.content
)
cosmetic_display_price = Integer(
display_name=_("Cosmetic Course Display Price"),
help=_(
"The cost displayed to students for enrolling in the course. If a paid course registration price is "
"set by an administrator in the database, that price will be displayed instead of this one."
),
default=0,
scope=Scope.settings,
)
advertised_start = String(
display_name=_("Course Advertised Start"),
help=_(
"Enter the text that you want to use as the advertised starting time frame for the course, "
"such as \"Winter 2018\". If you enter null for this value, the start date that you have set "
"for this course is used."
),
scope=Scope.settings
)
pre_requisite_courses = List(
display_name=_("Pre-Requisite Courses"),
help=_("Pre-Requisite Course key if this course has a pre-requisite course"),
scope=Scope.settings
)
grading_policy = Dict(
help=_("Grading policy definition for this class"),
default=DEFAULT_GRADING_POLICY,
scope=Scope.content
)
show_calculator = Boolean(
display_name=_("Show Calculator"),
help=_("Enter true or false. When true, students can see the calculator in the course."),
default=False,
scope=Scope.settings
)
display_name = String(
help=_("Enter the name of the course as it should appear in the course list."),
default="Empty",
display_name=_("Course Display Name"),
scope=Scope.settings,
)
course_edit_method = String(
display_name=_("Course Editor"),
help=_('Enter the method by which this course is edited ("XML" or "Studio").'),
default="Studio",
scope=Scope.settings,
deprecated=True # Deprecated because someone would not edit this value within Studio.
)
tabs = CourseTabList(help="List of tabs to enable in this course", scope=Scope.settings, default=[])
end_of_course_survey_url = String(
display_name=_("Course Survey URL"),
help=_("Enter the URL for the end-of-course survey. If your course does not have a survey, enter null."),
scope=Scope.settings,
deprecated=True # We wish to remove this entirely, TNL-3399
)
discussion_blackouts = List(
display_name=_("Discussion Blackout Dates"),
help=_(
'Enter pairs of dates between which students cannot post to discussion forums. Inside the provided '
'brackets, enter an additional set of square brackets surrounding each pair of dates you add. '
'Format each pair of dates as ["YYYY-MM-DD", "YYYY-MM-DD"]. To specify times as well as dates, '
'format each pair as ["YYYY-MM-DDTHH:MM", "YYYY-MM-DDTHH:MM"]. Be sure to include the "T" between '
'the date and time. For example, an entry defining two blackout periods looks like this, including '
'the outer pair of square brackets: [["2015-09-15", "2015-09-21"], ["2015-10-01", "2015-10-08"]] '
),
scope=Scope.settings
)
discussion_topics = Dict(
display_name=_("Discussion Topic Mapping"),
help=_(
'Enter discussion categories in the following format: "CategoryName": '
'{"id": "i4x-InstitutionName-CourseNumber-course-CourseRun"}. For example, one discussion '
'category may be "Lydian Mode": {"id": "i4x-UniversityX-MUS101-course-2015_T1"}. The "id" '
'value for each category must be unique. In "id" values, the only special characters that are '
'supported are underscore, hyphen, and period. You can also specify a category as the default '
'for new posts in the Discussion page by setting its "default" attribute to true. For example, '
'"Lydian Mode": {"id": "i4x-UniversityX-MUS101-course-2015_T1", "default": true}.'
),
scope=Scope.settings
)
discussion_sort_alpha = Boolean(
display_name=_("Discussion Sorting Alphabetical"),
scope=Scope.settings, default=False,
help=_(
"Enter true or false. If true, discussion categories and subcategories are sorted alphabetically. "
"If false, they are sorted chronologically by creation date and time."
)
)
announcement = Date(
display_name=_("Course Announcement Date"),
help=_("Enter the date to announce your course."),
scope=Scope.settings
)
cohort_config = Dict(
display_name=_("Cohort Configuration"),
help=_(
"Enter policy keys and values to enable the cohort feature, define automated student assignment to "
"groups, or identify any course-wide discussion topics as private to cohort members."
),
scope=Scope.settings
)
is_new = Boolean(
display_name=_("Course Is New"),
help=_(
"Enter true or false. If true, the course appears in the list of new courses, and a New! "
"badge temporarily appears next to the course image."
),
scope=Scope.settings
)
mobile_available = Boolean(
display_name=_("Mobile Course Available"),
help=_("Enter true or false. If true, the course will be available to mobile devices."),
default=DEFAULT_MOBILE_AVAILABLE,
scope=Scope.settings
)
video_upload_pipeline = Dict(
display_name=_("Video Upload Credentials"),
help=_("Enter the unique identifier for your course's video files provided by edX."),
scope=Scope.settings
)
no_grade = Boolean(
display_name=_("Course Not Graded"),
help=_("Enter true or false. If true, the course will not be graded."),
default=False,
scope=Scope.settings
)
disable_progress_graph = Boolean(
display_name=_("Disable Progress Graph"),
help=_("Enter true or false. If true, students cannot view the progress graph."),
default=False,
scope=Scope.settings
)
pdf_textbooks = List(
display_name=_("PDF Textbooks"),
help=_("List of dictionaries containing pdf_textbook configuration"), scope=Scope.settings
)
html_textbooks = List(
display_name=_("HTML Textbooks"),
help=_(
"For HTML textbooks that appear as separate tabs in the course, enter the name of the tab (usually "
"the title of the book) as well as the URLs and titles of each chapter in the book."
),
scope=Scope.settings
)
remote_gradebook = Dict(
display_name=_("Remote Gradebook"),
help=_(
"Enter the remote gradebook mapping. Only use this setting when "
"REMOTE_GRADEBOOK_URL has been specified."
),
scope=Scope.settings
)
enable_ccx = Boolean(
# Translators: Custom Courses for edX (CCX) is an edX feature for re-using course content. CCX Coach is
# a role created by a course Instructor to enable a person (the "Coach") to manage the custom course for
# his students.
display_name=_("Enable CCX"),
help=_(
# Translators: Custom Courses for edX (CCX) is an edX feature for re-using course content. CCX Coach is
# a role created by a course Instructor to enable a person (the "Coach") to manage the custom course for
# his students.
"Allow course instructors to assign CCX Coach roles, and allow coaches to manage Custom Courses on edX."
" When false, Custom Courses cannot be created, but existing Custom Courses will be preserved."
),
default=False,
scope=Scope.settings
)
ccx_connector = String(
# Translators: Custom Courses for edX (CCX) is an edX feature for re-using course content.
display_name=_("CCX Connector URL"),
# Translators: Custom Courses for edX (CCX) is an edX feature for re-using course content.
help=_(
"URL for CCX Connector application for managing creation of CCXs. (optional)."
" Ignored unless 'Enable CCX' is set to 'true'."
),
scope=Scope.settings, default=""
)
allow_anonymous = Boolean(
display_name=_("Allow Anonymous Discussion Posts"),
help=_("Enter true or false. If true, students can create discussion posts that are anonymous to all users."),
scope=Scope.settings, default=True
)
allow_anonymous_to_peers = Boolean(
display_name=_("Allow Anonymous Discussion Posts to Peers"),
help=_(
"Enter true or false. If true, students can create discussion posts that are anonymous to other "
"students. This setting does not make posts anonymous to course staff."
),
scope=Scope.settings, default=False
)
advanced_modules = List(
display_name=_("Advanced Module List"),
help=_("Enter the names of the advanced modules to use in your course."),
scope=Scope.settings
)
has_children = True
info_sidebar_name = String(
display_name=_("Course Home Sidebar Name"),
help=_(
"Enter the heading that you want students to see above your course handouts on the Course Home page. "
"Your course handouts appear in the right panel of the page."
),
deprecated=True,
scope=Scope.settings, default=_('Course Handouts'))
show_timezone = Boolean(
help=_(
"True if timezones should be shown on dates in the course. "
"Deprecated in favor of due_date_display_format."
),
scope=Scope.settings, default=True
)
due_date_display_format = String(
display_name=_("Due Date Display Format"),
help=_(
"Enter the format for due dates. The default is Mon DD, YYYY. Enter \"%m-%d-%Y\" for MM-DD-YYYY, "
"\"%d-%m-%Y\" for DD-MM-YYYY, \"%Y-%m-%d\" for YYYY-MM-DD, or \"%Y-%d-%m\" for YYYY-DD-MM."
),
scope=Scope.settings, default=None
)
enrollment_domain = String(
display_name=_("External Login Domain"),
help=_("Enter the external login method students can use for the course."),
scope=Scope.settings
)
certificates_show_before_end = Boolean(
display_name=_("Certificates Downloadable Before End"),
help=_(
"Enter true or false. If true, students can download certificates before the course ends, if they've "
"met certificate requirements."
),
scope=Scope.settings,
default=False,
deprecated=True
)
certificates_display_behavior = String(
display_name=_("Certificates Display Behavior"),
help=_(
"Enter end, early_with_info, or early_no_info. After certificate generation, students who passed see a "
"link to their certificates on the dashboard and students who did not pass see information about the "
"grading configuration. The default is end, which displays this certificate information to all students "
"after the course end date. To display this certificate information to all students as soon as "
"certificates are generated, enter early_with_info. To display only the links to passing students as "
"soon as certificates are generated, enter early_no_info."
),
scope=Scope.settings,
default="end"
)
course_image = String(
display_name=_("Course About Page Image"),
help=_(
"Edit the name of the course image file. You must upload this file on the Files & Uploads page. "
"You can also set the course image on the Settings & Details page."
),
scope=Scope.settings,
# Ensure that courses imported from XML keep their image
default="images_course_image.jpg",
hide_on_enabled_publisher=True
)
banner_image = String(
display_name=_("Course Banner Image"),
help=_(
"Edit the name of the banner image file. "
"You can set the banner image on the Settings & Details page."
),
scope=Scope.settings,
# Ensure that courses imported from XML keep their image
default="images_course_image.jpg"
)
video_thumbnail_image = String(
display_name=_("Course Video Thumbnail Image"),
help=_(
"Edit the name of the video thumbnail image file. "
"You can set the video thumbnail image on the Settings & Details page."
),
scope=Scope.settings,
# Ensure that courses imported from XML keep their image
default="images_course_image.jpg"
)
issue_badges = Boolean(
display_name=_("Issue Open Badges"),
help=_(
"Issue Open Badges badges for this course. Badges are generated when certificates are created."
),
scope=Scope.settings,
default=True
)
## Course level Certificate Name overrides.
cert_name_short = String(
help=_(
'Use this setting only when generating PDF certificates. '
'Between quotation marks, enter the short name of the type of certificate that '
'students receive when they complete the course. For instance, "Certificate".'
),
display_name=_("Certificate Name (Short)"),
scope=Scope.settings,
default=""
)
cert_name_long = String(
help=_(
'Use this setting only when generating PDF certificates. '
'Between quotation marks, enter the long name of the type of certificate that students '
'receive when they complete the course. For instance, "Certificate of Achievement".'
),
display_name=_("Certificate Name (Long)"),
scope=Scope.settings,
default=""
)
cert_html_view_enabled = Boolean(
display_name=_("Certificate Web/HTML View Enabled"),
help=_("If true, certificate Web/HTML views are enabled for the course."),
scope=Scope.settings,
default=True,
deprecated=True
)
cert_html_view_overrides = Dict(
# Translators: This field is the container for course-specific certificate configuration values
display_name=_("Certificate Web/HTML View Overrides"),
# Translators: These overrides allow for an alternative configuration of the certificate web view
help=_("Enter course-specific overrides for the Web/HTML template parameters here (JSON format)"),
scope=Scope.settings,
)
# Specific certificate information managed via Studio (should eventually fold other cert settings into this)
certificates = Dict(
# Translators: This field is the container for course-specific certificate configuration values
display_name=_("Certificate Configuration"),
# Translators: These overrides allow for an alternative configuration of the certificate web view
help=_("Enter course-specific configuration information here (JSON format)"),
scope=Scope.settings,
)
# An extra property is used rather than the wiki_slug/number because
# there are courses that change the number for different runs. This allows
# courses to share the same css_class across runs even if they have
# different numbers.
#
# TODO get rid of this as soon as possible or potentially build in a robust
# way to add in course-specific styling. There needs to be a discussion
# about the right way to do this, but arjun will address this ASAP. Also
# note that the courseware template needs to change when this is removed.
css_class = String(
display_name=_("CSS Class for Course Reruns"),
help=_("Allows courses to share the same css class across runs even if they have different numbers."),
scope=Scope.settings, default="",
deprecated=True
)
# TODO: This is a quick kludge to allow CS50 (and other courses) to
# specify their own discussion forums as external links by specifying a
# "discussion_link" in their policy JSON file. This should later get
# folded in with Syllabus, Course Info, and additional Custom tabs in a
# more sensible framework later.
discussion_link = String(
display_name=_("Discussion Forum External Link"),
help=_("Allows specification of an external link to replace discussion forums."),
scope=Scope.settings,
deprecated=True
)
# TODO: same as above, intended to let internal CS50 hide the progress tab
# until we get grade integration set up.
# Explicit comparison to True because we always want to return a bool.
hide_progress_tab = Boolean(
display_name=_("Hide Progress Tab"),
help=_("Allows hiding of the progress tab."),
scope=Scope.settings,
deprecated=True
)
display_organization = String(
display_name=_("Course Organization Display String"),
help=_(
"Enter the course organization that you want to appear in the course. This setting overrides the "
"organization that you entered when you created the course. To use the organization that you entered "
"when you created the course, enter null."
),
scope=Scope.settings
)
display_coursenumber = String(
display_name=_("Course Number Display String"),
help=_(
"Enter the course number that you want to appear in the course. This setting overrides the course "
"number that you entered when you created the course. To use the course number that you entered when "
"you created the course, enter null."
),
scope=Scope.settings,
default=""
)
max_student_enrollments_allowed = Integer(
display_name=_("Course Maximum Student Enrollment"),
help=_(
"Enter the maximum number of students that can enroll in the course. To allow an unlimited number of "
"students, enter null."
),
scope=Scope.settings
)
allow_public_wiki_access = Boolean(
display_name=_("Allow Public Wiki Access"),
help=_(
"Enter true or false. If true, students can view the course wiki even "
"if they're not enrolled in the course."
),
default=False,
scope=Scope.settings
)
invitation_only = Boolean(
display_name=_("Invitation Only"),
help=_("Whether to restrict enrollment to invitation by the course staff."),
default=False,
scope=Scope.settings
)
course_survey_name = String(
display_name=_("Pre-Course Survey Name"),
help=_("Name of SurveyForm to display as a pre-course survey to the user."),
default=None,
scope=Scope.settings,
deprecated=True
)
course_survey_required = Boolean(
display_name=_("Pre-Course Survey Required"),
help=_(
"Specify whether students must complete a survey before they can view your course content. If you "
"set this value to true, you must add a name for the survey to the Course Survey Name setting above."
),
default=False,
scope=Scope.settings,
deprecated=True
)
catalog_visibility = String(
display_name=_("Course Visibility In Catalog"),
help=_(
# Translators: the quoted words 'both', 'about', and 'none' must be
# left untranslated. Leave them as English words.
"Defines the access permissions for showing the course in the course catalog. This can be set to one "
"of three values: 'both' (show in catalog and allow access to about page), 'about' (only allow access "
"to about page), 'none' (do not show in catalog and do not allow access to an about page)."
),
default=DEFAULT_COURSE_VISIBILITY_IN_CATALOG,
scope=Scope.settings,
values=[
{"display_name": "Both", "value": CATALOG_VISIBILITY_CATALOG_AND_ABOUT},
{"display_name": "About", "value": CATALOG_VISIBILITY_ABOUT},
{"display_name": "None", "value": CATALOG_VISIBILITY_NONE},
],
)
entrance_exam_enabled = Boolean(
display_name=_("Entrance Exam Enabled"),
help=_(
"Specify whether students must complete an entrance exam before they can view your course content. "
"Note, you must enable Entrance Exams for this course setting to take effect."
),
default=False,
scope=Scope.settings,
)
# Note: Although users enter the entrance exam minimum score
# as a percentage value, it is internally converted and stored
# as a decimal value less than 1.
entrance_exam_minimum_score_pct = Float(
display_name=_("Entrance Exam Minimum Score (%)"),
help=_(
"Specify a minimum percentage score for an entrance exam before students can view your course content. "
"Note, you must enable Entrance Exams for this course setting to take effect."
),
default=65,
scope=Scope.settings,
)
entrance_exam_id = String(
display_name=_("Entrance Exam ID"),
help=_("Content module identifier (location) of entrance exam."),
default=None,
scope=Scope.settings,
)
social_sharing_url = String(
display_name=_("Social Media Sharing URL"),
help=_(
"If dashboard social sharing and custom course URLs are enabled, you can provide a URL "
"(such as the URL to a course About page) that social media sites can link to. URLs must "
"be fully qualified. For example: http://www.edx.org/course/Introduction-to-MOOCs-ITM001"
),
default=None,
scope=Scope.settings,
)
language = String(
display_name=_("Course Language"),
help=_("Specify the language of your course."),
default=None,
scope=Scope.settings
)
teams_configuration = TeamsConfigField(
display_name=_("Teams Configuration"),
# Translators: please don't translate "id".
help=_(
'Configure team sets, limit team sizes, and set visibility settings using JSON. See '
'<a target="_blank" href="https://edx.readthedocs.io/projects/edx-partner-course-staff/en/latest/'
'course_features/teams/teams_setup.html#enable-and-configure-teams">teams '
'configuration documentation</a> for help and examples.'
),
scope=Scope.settings,
)
enable_proctored_exams = Boolean(
display_name=_("Enable Proctored Exams"),
help=_(
"Enter true or false. If this value is true, proctored exams are enabled in your course. "
"Note that enabling proctored exams will also enable timed exams."
),
default=False,
scope=Scope.settings,
deprecated=EXAM_SETTINGS_HTML_VIEW_ENABLED
)
proctoring_provider = ProctoringProvider(
display_name=_("Proctoring Provider"),
help=_(
"Enter the proctoring provider you want to use for this course run. "
"Choose from the following options: {available_providers}."),
help_format_args=dict(
# Put the available providers into a format variable so that translators
# don't translate them.
available_providers=(
', '.join(get_available_providers())
),
),
scope=Scope.settings,
deprecated=EXAM_SETTINGS_HTML_VIEW_ENABLED
)
proctoring_escalation_email = EmailString(
display_name=_("Proctortrack Exam Escalation Contact"),
help=_(
"Required if 'proctortrack' is selected as your proctoring provider. "
"Enter an email address to be contacted by the support team whenever there are escalations "
"(e.g. appeals, delayed reviews, etc.)."
),
default=None,
scope=Scope.settings,
deprecated=EXAM_SETTINGS_HTML_VIEW_ENABLED
)
allow_proctoring_opt_out = Boolean(
display_name=_("Allow Opting Out of Proctored Exams"),
help=_(
"Enter true or false. If this value is true, learners can choose to take proctored exams "
"without proctoring. If this value is false, all learners must take the exam with proctoring. "
"This setting only applies if proctored exams are enabled for the course."
),
default=False,
scope=Scope.settings,
deprecated=EXAM_SETTINGS_HTML_VIEW_ENABLED
)
create_zendesk_tickets = Boolean(
display_name=_("Create Zendesk Tickets For Suspicious Proctored Exam Attempts"),
help=_(
"Enter true or false. If this value is true, a Zendesk ticket will be created for suspicious attempts."
),
default=True,
scope=Scope.settings,
deprecated=EXAM_SETTINGS_HTML_VIEW_ENABLED
)
enable_timed_exams = Boolean(
display_name=_("Enable Timed Exams"),
help=_(
"Enter true or false. If this value is true, timed exams are enabled in your course. "
"Regardless of this setting, timed exams are enabled if Enable Proctored Exams is set to true."
),
default=SPECIAL_EXAMS_ENABLED,
scope=Scope.settings,
deprecated=EXAM_SETTINGS_HTML_VIEW_ENABLED
)
minimum_grade_credit = Float(
display_name=_("Minimum Grade for Credit"),
help=_(
"The minimum grade that a learner must earn to receive credit in the course, "
"as a decimal between 0.0 and 1.0. For example, for 75%, enter 0.75."
),
default=0.8,
scope=Scope.settings,
)
self_paced = Boolean(
display_name=_("Self Paced"),
help=_(
"Set this to \"true\" to mark this course as self-paced. Self-paced courses do not have "
"due dates for assignments, and students can progress through the course at any rate before "
"the course ends."
),
default=False,
scope=Scope.settings
)
enable_subsection_gating = Boolean(
display_name=_("Enable Subsection Prerequisites"),
help=_(
"Enter true or false. If this value is true, you can hide a "
"subsection until learners earn a minimum score in another, "
"prerequisite subsection."
),
default=False,
scope=Scope.settings
)
learning_info = List(
display_name=_("Course Learning Information"),
help=_("Specify what student can learn from the course."),
default=[],
scope=Scope.settings
)
course_visibility = String(
display_name=_("Course Visibility For Unenrolled Learners"),
help=_(
# Translators: the quoted words 'private', 'public_outline', and 'public'
# must be left untranslated. Leave them as English words.
"Defines the access permissions for unenrolled learners. This can be set to one of three values: "
"'private' (default visibility, only allowed for enrolled students), 'public_outline' "
"(allow access to course outline) and 'public' (allow access to both outline and course content)."
),
default=COURSE_VISIBILITY_PRIVATE,
scope=Scope.settings,
values=[
{"display_name": "private", "value": COURSE_VISIBILITY_PRIVATE},
{"display_name": "public_outline", "value": COURSE_VISIBILITY_PUBLIC_OUTLINE},
{"display_name": "public", "value": COURSE_VISIBILITY_PUBLIC},
],
)
"""
instructor_info dict structure:
{
"instructors": [
{
"name": "",
"title": "",
"organization": "",
"image": "",
"bio": ""
}
]
}
"""
instructor_info = Dict(
display_name=_("Course Instructor"),
help=_("Enter the details for Course Instructor"),
default={
"instructors": []
},
scope=Scope.settings
)
allow_unsupported_xblocks = Boolean(
display_name=_("Add Unsupported Problems and Tools"),
help=_(
"Enter true or false. If true, you can add unsupported problems and tools to your course in Studio. "
"Unsupported problems and tools are not recommended for use in courses due to non-compliance with one or "
"more of the base requirements, such as testing, accessibility, internationalization, and documentation."
),
scope=Scope.settings, default=False
)
highlights_enabled_for_messaging = Boolean(
display_name=_("Highlights Enabled for Messaging"),
help=_(
"Enter true or false. If true, any highlights associated with content in the course will be messaged "
"to learners at their scheduled time."
),
scope=Scope.settings, default=False
)
other_course_settings = Dict(
display_name=_("Other Course Settings"),
help=_(
"Any additional information about the course that the platform needs or that allows integration with "
"external systems such as CRM software. Enter a dictionary of values in JSON format, such as "
"{ \"my_custom_setting\": \"value\", \"other_setting\": \"value\" }"
),
scope=Scope.settings
)
class CourseBlock(
CourseFields,
SequenceBlock,
LicenseMixin,
): # pylint: disable=abstract-method
"""
The Course XBlock.
"""
resources_dir = None
def __init__(self, *args, **kwargs):
"""
Expects the same arguments as XModuleDescriptor.__init__
"""
super().__init__(*args, **kwargs)
_ = self.runtime.service(self, "i18n").ugettext
self._gating_prerequisites = None
if self.wiki_slug is None:
self.wiki_slug = self.location.course
if self.due_date_display_format is None and self.show_timezone is False:
# For existing courses with show_timezone set to False (and no due_date_display_format specified),
# set the due_date_display_format to what would have been shown previously (with no timezone).
# Then remove show_timezone so that if the user clears out the due_date_display_format,
# they get the default date display.
self.due_date_display_format = "DATE_TIME"
del self.show_timezone
# NOTE: relies on the modulestore to call set_grading_policy() right after
# init. (Modulestore is in charge of figuring out where to load the policy from)
# NOTE (THK): This is a last-minute addition for Fall 2012 launch to dynamically
# disable the syllabus content for courses that do not provide a syllabus
if self.system.resources_fs is None:
self.syllabus_present = False
else:
self.syllabus_present = self.system.resources_fs.exists(path('syllabus'))
self._grading_policy = {}
self.set_grading_policy(self.grading_policy)
if self.discussion_topics == {}:
self.discussion_topics = {_('General'): {'id': self.location.html_id()}}
try:
if not getattr(self, "tabs", []):
CourseTabList.initialize_default(self)
except InvalidTabsException as err:
raise type(err)('{msg} For course: {course_id}'.format(msg=str(err), course_id=str(self.id))) # lint-amnesty, pylint: disable=line-too-long
self.set_default_certificate_available_date()
def set_grading_policy(self, course_policy):
"""
The JSON object can have the keys GRADER and GRADE_CUTOFFS. If either is
missing, it reverts to the default.
"""
if course_policy is None:
course_policy = {}
# Load the global settings as a dictionary
grading_policy = self.grading_policy
# BOY DO I HATE THIS grading_policy CODE ACROBATICS YET HERE I ADD MORE (dhm)--this fixes things persisted w/
# defective grading policy values (but not None)
if 'GRADER' not in grading_policy:
grading_policy['GRADER'] = CourseFields.grading_policy.default['GRADER']
if 'GRADE_CUTOFFS' not in grading_policy:
grading_policy['GRADE_CUTOFFS'] = CourseFields.grading_policy.default['GRADE_CUTOFFS']
# Override any global settings with the course settings
grading_policy.update(course_policy)
# Here is where we should parse any configurations, so that we can fail early
# Use setters so that side effecting to .definitions works
self.raw_grader = grading_policy['GRADER'] # used for cms access
self.grade_cutoffs = grading_policy['GRADE_CUTOFFS']
def set_default_certificate_available_date(self):
if (not self.certificate_available_date) and self.end:
self.certificate_available_date = self.end + timedelta(days=2)
@classmethod
def read_grading_policy(cls, paths, system):
"""Load a grading policy from the specified paths, in order, if it exists."""
# Default to a blank policy dict
policy_str = '{}'
for policy_path in paths:
if not system.resources_fs.exists(policy_path):
continue
log.debug(f"Loading grading policy from {policy_path}")
try:
with system.resources_fs.open(policy_path) as grading_policy_file:
policy_str = grading_policy_file.read()
# if we successfully read the file, stop looking at backups
break
except OSError:
msg = f"Unable to load course settings file from '{policy_path}'"
log.warning(msg)
return policy_str
@classmethod
def from_xml(cls, xml_data, system, id_generator):
instance = super().from_xml(xml_data, system, id_generator)
# bleh, have to parse the XML here to just pull out the url_name attribute
# I don't think it's stored anywhere in the instance.
if isinstance(xml_data, str):
xml_data = xml_data.encode('ascii', 'ignore')
course_file = BytesIO(xml_data)
xml_obj = etree.parse(course_file, parser=edx_xml_parser).getroot()
policy_dir = None
url_name = xml_obj.get('url_name', xml_obj.get('slug'))
if url_name:
policy_dir = 'policies/' + url_name
# Try to load grading policy
paths = ['grading_policy.json']
if policy_dir:
paths = [policy_dir + '/grading_policy.json'] + paths
try:
policy = json.loads(cls.read_grading_policy(paths, system))
except ValueError:
system.error_tracker("Unable to decode grading policy as json")
policy = {}
# now set the current instance. set_grading_policy() will apply some inheritance rules
instance.set_grading_policy(policy)
return instance
@classmethod
def definition_from_xml(cls, xml_object, system):
textbooks = []
for textbook in xml_object.findall("textbook"):
textbooks.append((textbook.get('title'), textbook.get('book_url')))
xml_object.remove(textbook)
# Load the wiki tag if it exists
wiki_slug = None
wiki_tag = xml_object.find("wiki")
if wiki_tag is not None:
wiki_slug = wiki_tag.attrib.get("slug", default=None)
xml_object.remove(wiki_tag)
definition, children = super().definition_from_xml(xml_object, system)
definition['textbooks'] = textbooks
definition['wiki_slug'] = wiki_slug
# load license if it exists
definition = LicenseMixin.parse_license_from_xml(definition, xml_object)
return definition, children
def definition_to_xml(self, resource_fs):
xml_object = super().definition_to_xml(resource_fs)
if self.textbooks:
textbook_xml_object = etree.Element('textbook')
for textbook in self.textbooks: # lint-amnesty, pylint: disable=not-an-iterable
textbook_xml_object.set('title', textbook.title)
textbook_xml_object.set('book_url', textbook.book_url)
xml_object.append(textbook_xml_object)
if self.wiki_slug is not None:
wiki_xml_object = etree.Element('wiki')
wiki_xml_object.set('slug', self.wiki_slug)
xml_object.append(wiki_xml_object)
# handle license specifically. Default the course to have a license
# of "All Rights Reserved", if a license is not explicitly set.
self.add_license_to_xml(xml_object, default="all-rights-reserved")
return xml_object
def has_ended(self):
"""
Returns True if the current time is after the specified course end date.
Returns False if there is no end date specified.
"""
return course_metadata_utils.has_course_ended(self.end)
def may_certify(self):
"""
Return whether it is acceptable to show the student a certificate download link.
"""
return course_metadata_utils.may_certify_for_course(
self.certificates_display_behavior,
self.certificates_show_before_end,
self.has_ended(),
self.certificate_available_date,
self.self_paced
)
def has_started(self):
return course_metadata_utils.has_course_started(self.start)
@property
def grader(self):
return grader_from_conf(self.raw_grader)
@property
def raw_grader(self): # lint-amnesty, pylint: disable=missing-function-docstring
# force the caching of the xblock value so that it can detect the change
# pylint: disable=pointless-statement
self.grading_policy['GRADER']
return self._grading_policy['RAW_GRADER']
@raw_grader.setter
def raw_grader(self, value):
# NOTE WELL: this change will not update the processed graders.
# If we need that, this needs to call grader_from_conf.
self._grading_policy['RAW_GRADER'] = value
self.grading_policy['GRADER'] = value
@property
def grade_cutoffs(self):
return self._grading_policy['GRADE_CUTOFFS']
@grade_cutoffs.setter
def grade_cutoffs(self, value):
self._grading_policy['GRADE_CUTOFFS'] = value
# XBlock fields don't update after mutation
policy = self.grading_policy
policy['GRADE_CUTOFFS'] = value
self.grading_policy = policy
@property
def lowest_passing_grade(self):
return min(self._grading_policy['GRADE_CUTOFFS'].values())
@property
def is_cohorted(self):
"""
Return whether the course is cohorted.
Note: No longer used. See openedx.core.djangoapps.course_groups.models.CourseCohortSettings.
"""
config = self.cohort_config
if config is None:
return False
return bool(config.get("cohorted"))
@property
def auto_cohort(self):
"""
Return whether the course is auto-cohorted.
Note: No longer used. See openedx.core.djangoapps.course_groups.models.CourseCohortSettings.
"""
if not self.is_cohorted:
return False
return bool(self.cohort_config.get(
"auto_cohort", False))
@property
def auto_cohort_groups(self):
"""
Return the list of groups to put students into. Returns [] if not
specified. Returns specified list even if is_cohorted and/or auto_cohort are
false.
Note: No longer used. See openedx.core.djangoapps.course_groups.models.CourseCohortSettings.
"""
if self.cohort_config is None:
return []
else:
return self.cohort_config.get("auto_cohort_groups", [])
@property
def top_level_discussion_topic_ids(self):
"""
Return list of topic ids defined in course policy.
"""
topics = self.discussion_topics
return [d["id"] for d in topics.values()]
@property
def cohorted_discussions(self):
"""
Return the set of discussions that is explicitly cohorted. It may be
the empty set. Note that all inline discussions are automatically
cohorted based on the course's is_cohorted setting.
Note: No longer used. See openedx.core.djangoapps.course_groups.models.CourseCohortSettings.
"""
config = self.cohort_config
if config is None:
return set()
return set(config.get("cohorted_discussions", []))
@property
def always_cohort_inline_discussions(self):
"""
This allow to change the default behavior of inline discussions cohorting. By
setting this to 'True', all inline discussions are cohorted. The default value is
now `False`, meaning that inline discussions are not cohorted unless their discussion IDs
are specifically listed as cohorted.
Note: No longer used except to get the initial value when cohorts are first enabled on a course
(and for migrating old courses). See openedx.core.djangoapps.course_groups.models.CourseCohortSettings.
"""
config = self.cohort_config
if config is None:
# This value sets the default for newly created courses.
return False
return bool(config.get("always_cohort_inline_discussions", False))
@property
def is_newish(self):
"""
Returns if the course has been flagged as new. If
there is no flag, return a heuristic value considering the
announcement and the start dates.
"""
flag = self.is_new
if flag is None:
# Use a heuristic if the course has not been flagged
announcement, start, now = course_metadata_utils.sorting_dates(
self.start, self.advertised_start, self.announcement
)
if announcement and (now - announcement).days < 30:
# The course has been announced for less that month
return True
elif (now - start).days < 1:
# The course has not started yet
return True
else:
return False
elif isinstance(flag, str):
return flag.lower() in ['true', 'yes', 'y']
else:
return bool(flag)
@property
def sorting_score(self):
"""
Returns a tuple that can be used to sort the courses according
the how "new" they are. The "newness" score is computed using a
heuristic that takes into account the announcement and
(advertised) start dates of the course if available.
The lower the number the "newer" the course.
"""
return course_metadata_utils.sorting_score(self.start, self.advertised_start, self.announcement)
@staticmethod
def make_id(org, course, url_name):
return '/'.join([org, course, url_name])
@property
def id(self):
"""Return the course_id for this course"""
return self.location.course_key
@property
def start_date_is_still_default(self):
"""
Checks if the start date set for the course is still default, i.e. .start has not been modified,
and .advertised_start has not been set.
"""
return course_metadata_utils.course_start_date_is_default(
self.start,
self.advertised_start
)
def get_discussion_blackout_datetimes(self):
"""
Get a list of dicts with start and end fields with datetime values from
the discussion_blackouts setting
"""
blackout_dates = self.discussion_blackouts
date_proxy = Date()
if blackout_dates and type(blackout_dates[0]) not in (list, tuple):
blackout_dates = [blackout_dates]
try:
ret = [
{"start": date_proxy.from_json(start), "end": date_proxy.from_json(end)}
for start, end
in [blackout_date for blackout_date in blackout_dates if blackout_date]
]
for blackout in ret:
if not blackout["start"] or not blackout["end"]:
raise ValueError
return ret
except (TypeError, ValueError):
log.info(
"Error parsing discussion_blackouts %s for course %s",
blackout_dates,
self.id
)
return []
@property
def forum_posts_allowed(self):
"""
Return whether forum posts are allowed by the discussion_blackouts
setting
"""
blackouts = self.get_discussion_blackout_datetimes()
now = datetime.now(utc)
for blackout in blackouts:
if blackout["start"] <= now <= blackout["end"]:
return False
return True
@property
def number(self):
"""
Returns this course's number.
This is a "number" in the sense of the "course numbers" that you see at
lots of universities. For example, given a course
"Intro to Computer Science" with the course key "edX/CS-101/2014", the
course number would be "CS-101"
"""
return course_metadata_utils.number_for_course_location(self.location)
@property
def display_number_with_default(self):
"""
Return a display course number if it has been specified, otherwise return the 'course' that is in the location
"""
if self.display_coursenumber:
return self.display_coursenumber
return self.number
@property
def org(self):
return self.location.org
@property
def display_org_with_default(self):
"""
Return a display organization if it has been specified, otherwise return the 'org' that is in the location
"""
if self.display_organization:
return self.display_organization
return self.org
@property
def video_pipeline_configured(self):
"""
Returns whether the video pipeline advanced setting is configured for this course.
"""
return VideoUploadsEnabledByDefault.feature_enabled(course_id=self.id) or (
self.video_upload_pipeline is not None and
'course_video_upload_token' in self.video_upload_pipeline
)
def clean_id(self, padding_char='='):
"""
Returns a unique deterministic base32-encoded ID for the course.
The optional padding_char parameter allows you to override the "=" character used for padding.
"""
return course_metadata_utils.clean_course_key(self.location.course_key, padding_char)
@property
def teams_enabled(self):
"""
Alias to `self.teams_configuration.is_enabled`, for convenience.
Returns bool.
"""
return self.teams_configuration.is_enabled # pylint: disable=no-member
@property
def teamsets(self):
"""
Alias to `self.teams_configuration.teamsets`, for convenience.
Returns list[TeamsetConfig].
"""
return self.teams_configuration.teamsets # pylint: disable=no-member
@property
def teamsets_by_id(self):
"""
Alias to `self.teams_configuration.teamsets_by_id`, for convenience.
Returns dict[str: TeamsetConfig].
"""
return self.teams_configuration.teamsets_by_id
def set_user_partitions_for_scheme(self, partitions, scheme):
"""
Set the user partitions for a particular scheme.
Preserves partitions associated with other schemes.
Arguments:
scheme (object): The user partition scheme.
Returns:
list of `UserPartition`
"""
other_partitions = [
p for p in self.user_partitions # pylint: disable=access-member-before-definition
if p.scheme != scheme
]
self.user_partitions = other_partitions + partitions # pylint: disable=attribute-defined-outside-init
@property
def can_toggle_course_pacing(self):
"""
Whether or not the course can be set to self-paced at this time.
Returns:
bool: False if the course has already started or no start date set, True otherwise.
"""
if not self.start:
return False
return datetime.now(utc) <= self.start
class CourseSummary:
"""
A lightweight course summary class, which constructs split/mongo course summary without loading
the course. It is used at cms for listing courses to global staff user.
"""
course_info_fields = ['display_name', 'display_coursenumber', 'display_organization', 'end']
def __init__(self, course_locator, display_name="Empty", display_coursenumber=None, display_organization=None,
end=None):
"""
Initialize and construct course summary
Arguments:
course_locator (CourseLocator): CourseLocator object of the course.
display_name (unicode): display name of the course. When you create a course from console, display_name
isn't set (course block has no key `display_name`). "Empty" name is returned when we load the course.
If `display_name` isn't present in the course block, use the `Empty` as default display name.
We can set None as a display_name in Course Advance Settings; Do not use "Empty" when display_name is
set to None.
display_coursenumber (unicode|None): Course number that is specified & appears in the courseware
display_organization (unicode|None): Course organization that is specified & appears in the courseware
end (unicode|None): Course end date. Must contain timezone.
"""
self.display_coursenumber = display_coursenumber
self.display_organization = display_organization
self.display_name = display_name
self.id = course_locator # pylint: disable=invalid-name
self.location = course_locator.make_usage_key('course', 'course')
self.end = end
if end is not None and not isinstance(end, datetime):
self.end = dateutil.parser.parse(end)
@property
def display_org_with_default(self):
"""
Return a display organization if it has been specified, otherwise return the 'org' that
is in the location
"""
if self.display_organization:
return self.display_organization
return self.location.org
@property
def display_number_with_default(self):
"""
Return a display course number if it has been specified, otherwise return the 'course' that
is in the location
"""
if self.display_coursenumber:
return self.display_coursenumber
return self.location.course
def has_ended(self):
"""
Returns whether the course has ended.
"""
try:
return course_metadata_utils.has_course_ended(self.end)
except TypeError as e:
log.warning(
"Course '{course_id}' has an improperly formatted end date '{end_date}'. Error: '{err}'.".format(
course_id=str(self.id), end_date=self.end, err=e
)
)
modified_end = self.end.replace(tzinfo=utc)
return course_metadata_utils.has_course_ended(modified_end)
|
agpl-3.0
|
rapidhere/open-hackathon
|
open-hackathon-client/src/client/user/__init__.py
|
24
|
1396
|
# -*- coding: utf-8 -*-
#
# -----------------------------------------------------------------------------------
# Copyright (c) Microsoft Open Technologies (Shanghai) Co. Ltd. All rights reserved.
#
# The MIT License (MIT)
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# -----------------------------------------------------------------------------------
__author__ = 'root'
|
mit
|
dev-burbrink/pydslice
|
pydslice/pydslice_debugger.py
|
1
|
1921
|
# pydslice_debugger.py
#
# Generic definitions for debuggers
#
# Copyright (C) 2016 Josh Burbrink <[email protected]>
#
# Debug level for printing
DEBUG_PRINT_LEVEL_ALWAYS = 0
DEBUG_PRINT_LEVEL_ERROR = 1
DEBUG_PRINT_LEVEL_WARNING = 2
DEBUG_PRINT_LEVEL_INFO = 3
DEBUG_PRINT_LEVEL_VERBOSE = 4
debug_print_level = DEBUG_PRINT_LEVEL_ALWAYS
# Debug level for symbols
DEBUG_SYMBOL_LEVEL_NONE = 0
DEBUG_SYMBOL_LEVEL_LINES = 1
DEBUG_SYMBOL_LEVEL_VARIABLES = 2
debug_symbol_level = DEBUG_SYMBOL_LEVEL_LINES
class Debugger():
# Initializes the debugger interface
def __init(self):
pass
# Prints string to debugger
def print_msg(self, level, str):
pass
# Gets the value of $pc
def get_pc(self):
pass
# Reverses execution of the debugged process by one step
def reverse_step(self):
pass
# Executes the debugged process by one step
def step(self):
pass
# Returns the architecture for the process
def get_architecture(self):
pass
# Retrieves a 1 byte value from memory of the debugged process
def read_byte(self,address):
pass
# Disassembles the instruction at pc
def disassemble(self, address, length):
pass
# Performs additional setup tasks for the debugger
def setup_slice(self, slice, init_callbacks):
pass
# Gets symbol information about the current line of code
def get_line_info(self):
pass
# Get symbol info for address
def get_addr_info(self, addr):
pass
# Determines if a given address is in executable memory
def is_address_executable(self, address):
pass
# Determines if pc is inside specified file
def inside_file(self, filename):
return False
# Determines if pc is inside specified function
def inside_function(self, functionname):
return False
|
lgpl-3.0
|
jkoelker/ryu
|
ryu/services/protocols/bgp/processor.py
|
10
|
17632
|
# Copyright (C) 2014 Nippon Telegraph and Telephone Corporation.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
Module related to processing bgp paths.
"""
import logging
from ryu.services.protocols.bgp.base import Activity
from ryu.services.protocols.bgp.base import add_bgp_error_metadata
from ryu.services.protocols.bgp.base import BGP_PROCESSOR_ERROR_CODE
from ryu.services.protocols.bgp.base import BGPSException
from ryu.services.protocols.bgp.utils import circlist
from ryu.services.protocols.bgp.utils.evtlet import EventletIOFactory
from ryu.lib.packet.bgp import RF_RTC_UC
from ryu.lib.packet.bgp import BGP_ATTR_TYPE_AS_PATH
from ryu.lib.packet.bgp import BGP_ATTR_TYPE_LOCAL_PREF
from ryu.lib.packet.bgp import BGP_ATTR_TYPE_MULTI_EXIT_DISC
from ryu.lib.packet.bgp import BGP_ATTR_TYPE_ORIGIN
from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_IGP
from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_EGP
from ryu.lib.packet.bgp import BGP_ATTR_ORIGIN_INCOMPLETE
LOG = logging.getLogger('bgpspeaker.processor')
@add_bgp_error_metadata(code=BGP_PROCESSOR_ERROR_CODE, sub_code=1,
def_desc='Error occurred when processing bgp '
'destination.')
class BgpProcessorError(BGPSException):
"""Base exception related to all destination path processing errors.
"""
pass
# Disabling known bug in pylint.
# pylint: disable=R0921
class BgpProcessor(Activity):
"""Worker that processes queued `Destination'.
`Destination` that have updates related to its paths need to be
(re)processed. Only one instance of this processor is enough for normal
cases. If you want more control on which destinations get processed faster
compared to other destinations, you can create several instance of this
works to achieve the desired work flow.
"""
# Max. number of destinations processed per cycle.
MAX_DEST_PROCESSED_PER_CYCLE = 100
#
# DestQueue
#
# A circular list type in which objects are linked to each
# other using the 'next_dest_to_process' and 'prev_dest_to_process'
# attributes.
#
_DestQueue = circlist.CircularListType(
next_attr_name='next_dest_to_process',
prev_attr_name='prev_dest_to_process')
def __init__(self, core_service, work_units_per_cycle=None):
Activity.__init__(self)
# Back pointer to core service instance that created this processor.
self._core_service = core_service
self._dest_queue = BgpProcessor._DestQueue()
self._rtdest_queue = BgpProcessor._DestQueue()
self.dest_que_evt = EventletIOFactory.create_custom_event()
self.work_units_per_cycle =\
work_units_per_cycle or BgpProcessor.MAX_DEST_PROCESSED_PER_CYCLE
def _run(self, *args, **kwargs):
# Sit in tight loop, getting destinations from the queue and processing
# one at a time.
while True:
LOG.debug('Starting new processing run...')
# We process all RT destination first so that we get a new RT
# filter that apply for each peer
self._process_rtdest()
# We then process a batch of other destinations (we do not process
# all destination here as we want to give change to other
# greenthread to run)
self._process_dest()
if self._dest_queue.is_empty():
# If we have no destinations queued for processing, we wait.
self.dest_que_evt.clear()
self.dest_que_evt.wait()
else:
self.pause(0)
def _process_dest(self):
dest_processed = 0
LOG.debug('Processing destination...')
while (dest_processed < self.work_units_per_cycle and
not self._dest_queue.is_empty()):
# We process the first destination in the queue.
next_dest = self._dest_queue.pop_first()
if next_dest:
next_dest.process()
dest_processed += 1
def _process_rtdest(self):
LOG.debug('Processing RT NLRI destination...')
if self._rtdest_queue.is_empty():
return
else:
processed_any = False
while not self._rtdest_queue.is_empty():
# We process the first destination in the queue.
next_dest = self._rtdest_queue.pop_first()
if next_dest:
next_dest.process()
processed_any = True
if processed_any:
# Since RT destination were updated we update RT filters
self._core_service.update_rtfilters()
def enqueue(self, destination):
"""Enqueues given destination for processing.
Given instance should be a valid destination.
"""
if not destination:
raise BgpProcessorError('Invalid destination %s.' % destination)
dest_queue = self._dest_queue
# RtDest are queued in a separate queue
if destination.route_family == RF_RTC_UC:
dest_queue = self._rtdest_queue
# We do not add given destination to the queue for processing if
# it is already on the queue.
if not dest_queue.is_on_list(destination):
dest_queue.append(destination)
# Wake-up processing thread if sleeping.
self.dest_que_evt.set()
# =============================================================================
# Best path computation related utilities.
# =============================================================================
# Various reasons a path is chosen as best path.
BPR_UNKNOWN = 'Unknown'
BPR_ONLY_PATH = 'Only Path'
BPR_REACHABLE_NEXT_HOP = 'Reachable Next Hop'
BPR_HIGHEST_WEIGHT = 'Highest Weight'
BPR_LOCAL_PREF = 'Local Pref'
BPR_LOCAL_ORIGIN = 'Local Origin'
BPR_ASPATH = 'AS Path'
BPR_ORIGIN = 'Origin'
BPR_MED = 'MED'
BPR_ASN = 'ASN'
BPR_IGP_COST = 'IGP Cost'
BPR_ROUTER_ID = 'Router ID'
def _compare_by_version(path1, path2):
"""Returns the current/latest learned path.
Checks if given paths are from same source/peer and then compares their
version number to determine which path is received later. If paths are from
different source/peer return None.
"""
if path1.source == path2.source:
if path1.source_version_num > path2.source_version_num:
return path1
else:
return path2
return None
def compute_best_path(local_asn, path1, path2):
"""Compares given paths and returns best path.
Parameters:
-`local_asn`: asn of local bgpspeaker
-`path1`: first path to compare
-`path2`: second path to compare
Best path processing will involve following steps:
1. Select a path with a reachable next hop.
2. Select the path with the highest weight.
3. If path weights are the same, select the path with the highest
local preference value.
4. Prefer locally originated routes (network routes, redistributed
routes, or aggregated routes) over received routes.
5. Select the route with the shortest AS-path length.
6. If all paths have the same AS-path length, select the path based
on origin: IGP is preferred over EGP; EGP is preferred over
Incomplete.
7. If the origins are the same, select the path with lowest MED
value.
8. If the paths have the same MED values, select the path learned
via EBGP over one learned via IBGP.
9. Select the route with the lowest IGP cost to the next hop.
10. Select the route received from the peer with the lowest BGP
router ID.
Returns None if best-path among given paths cannot be computed else best
path.
Assumes paths from NC has source equal to None.
"""
best_path = None
best_path_reason = BPR_UNKNOWN
# Follow best path calculation algorithm steps.
if best_path is None:
best_path = _cmp_by_reachable_nh(path1, path2)
best_path_reason = BPR_REACHABLE_NEXT_HOP
if best_path is None:
best_path = _cmp_by_higest_wg(path1, path2)
best_path_reason = BPR_HIGHEST_WEIGHT
if best_path is None:
best_path = _cmp_by_local_pref(path1, path2)
best_path_reason = BPR_LOCAL_PREF
if best_path is None:
best_path = _cmp_by_local_origin(path1, path2)
best_path_reason = BPR_LOCAL_ORIGIN
if best_path is None:
best_path = _cmp_by_aspath(path1, path2)
best_path_reason = BPR_ASPATH
if best_path is None:
best_path = _cmp_by_origin(path1, path2)
best_path_reason = BPR_ORIGIN
if best_path is None:
best_path = _cmp_by_med(path1, path2)
best_path_reason = BPR_MED
if best_path is None:
best_path = _cmp_by_asn(local_asn, path1, path2)
best_path_reason = BPR_ASN
if best_path is None:
best_path = _cmp_by_igp_cost(path1, path2)
best_path_reason = BPR_IGP_COST
if best_path is None:
best_path = _cmp_by_router_id(local_asn, path1, path2)
best_path_reason = BPR_ROUTER_ID
if best_path is None:
best_path_reason = BPR_UNKNOWN
return (best_path, best_path_reason)
def _cmp_by_reachable_nh(path1, path2):
"""Compares given paths and selects best path based on reachable next-hop.
If no path matches this criteria, return None.
"""
# TODO(PH): Currently we do not have a way to check if a IGP route to
# NEXT_HOP exists from BGPS.
return None
def _cmp_by_higest_wg(path1, path2):
"""Selects a path with highest weight.
Weight is BGPS specific parameter. It is local to the router on which it
is configured.
Return:
None if best path among given paths cannot be decided, else best path.
"""
# TODO(PH): Revisit this when BGPS has concept of policy to be applied to
# in-bound NLRIs.
return None
def _cmp_by_local_pref(path1, path2):
"""Selects a path with highest local-preference.
Unlike the weight attribute, which is only relevant to the local
router, local preference is an attribute that routers exchange in the
same AS. Highest local-pref is preferred. If we cannot decide,
we return None.
"""
# TODO(PH): Revisit this when BGPS has concept of policy to be applied to
# in-bound NLRIs.
# Default local-pref values is 100
lp1 = path1.get_pattr(BGP_ATTR_TYPE_LOCAL_PREF)
lp2 = path2.get_pattr(BGP_ATTR_TYPE_LOCAL_PREF)
if not (lp1 and lp2):
return None
# Highest local-preference value is preferred.
lp1 = lp1.value
lp2 = lp2.value
if lp1 > lp2:
return path1
elif lp2 > lp1:
return path2
else:
return None
def _cmp_by_local_origin(path1, path2):
"""Select locally originating path as best path.
Locally originating routes are network routes, redistributed routes,
or aggregated routes. For now we are going to prefer routes received
through a Flexinet-Peer as locally originating route compared to routes
received from a BGP peer.
Returns None if given paths have same source.
"""
# If both paths are from same sources we cannot compare them here.
if path1.source == path2.source:
return None
# Here we consider prefix from NC as locally originating static route.
# Hence it is preferred.
if path1.source is None:
return path1
if path2.source is None:
return path2
return None
def _cmp_by_aspath(path1, path2):
"""Calculated the best-paths by comparing as-path lengths.
Shortest as-path length is preferred. If both path have same lengths,
we return None.
"""
as_path1 = path1.get_pattr(BGP_ATTR_TYPE_AS_PATH)
as_path2 = path2.get_pattr(BGP_ATTR_TYPE_AS_PATH)
assert as_path1 and as_path2
l1 = as_path1.get_as_path_len()
l2 = as_path2.get_as_path_len()
assert l1 is not None and l2 is not None
if l1 > l2:
return path2
elif l2 > l1:
return path1
else:
return None
def _cmp_by_origin(path1, path2):
"""Select the best path based on origin attribute.
IGP is preferred over EGP; EGP is preferred over Incomplete.
If both paths have same origin, we return None.
"""
def get_origin_pref(origin):
if origin.value == BGP_ATTR_ORIGIN_IGP:
return 3
elif origin.value == BGP_ATTR_ORIGIN_EGP:
return 2
elif origin.value == BGP_ATTR_ORIGIN_INCOMPLETE:
return 1
else:
LOG.error('Invalid origin value encountered %s.' % origin)
return 0
origin1 = path1.get_pattr(BGP_ATTR_TYPE_ORIGIN)
origin2 = path2.get_pattr(BGP_ATTR_TYPE_ORIGIN)
assert origin1 is not None and origin2 is not None
# If both paths have same origins
if origin1.value == origin2.value:
return None
# Translate origin values to preference.
origin1 = get_origin_pref(origin1)
origin2 = get_origin_pref(origin2)
# Return preferred path.
if origin1 == origin2:
return None
elif origin1 > origin2:
return path1
return path2
def _cmp_by_med(path1, path2):
"""Select the path based with lowest MED value.
If both paths have same MED, return None.
By default, a route that arrives with no MED value is treated as if it
had a MED of 0, the most preferred value.
RFC says lower MED is preferred over higher MED value.
"""
def get_path_med(path):
med = path.get_pattr(BGP_ATTR_TYPE_MULTI_EXIT_DISC)
if not med:
return 0
return med.value
med1 = get_path_med(path1)
med2 = get_path_med(path2)
if med1 == med2:
return None
elif med1 < med2:
return path1
return path2
def _cmp_by_asn(local_asn, path1, path2):
"""Select the path based on source (iBGP/eBGP) peer.
eBGP path is preferred over iBGP. If both paths are from same kind of
peers, return None.
"""
def get_path_source_asn(path):
asn = None
if path.source is None:
asn = local_asn
else:
asn = path.source.remote_as
return asn
p1_asn = get_path_source_asn(path1)
p2_asn = get_path_source_asn(path2)
# If path1 is from ibgp peer and path2 is from ebgp peer.
if (p1_asn == local_asn) and (p2_asn != local_asn):
return path2
# If path2 is from ibgp peer and path1 is from ebgp peer,
if (p2_asn == local_asn) and (p1_asn != local_asn):
return path1
# If both paths are from ebgp or ibpg peers, we cannot decide.
return None
def _cmp_by_igp_cost(path1, path2):
"""Select the route with the lowest IGP cost to the next hop.
Return None if igp cost is same.
"""
# TODO(PH): Currently BGPS has no concept of IGP and IGP cost.
return None
def _cmp_by_router_id(local_asn, path1, path2):
"""Select the route received from the peer with the lowest BGP router ID.
If both paths are eBGP paths, then we do not do any tie breaking, i.e we do
not pick best-path based on this criteria.
RFC: http://tools.ietf.org/html/rfc5004
We pick best path between two iBGP paths as usual.
"""
def get_asn(path_source):
if path_source is None:
return local_asn
else:
return path_source.remote_as
def get_router_id(path_source, local_bgp_id):
if path_source is None:
return local_bgp_id
else:
return path_source.protocol.recv_open_msg.bgp_identifier
path_source1 = path1.source
path_source2 = path2.source
# If both paths are from NC we have same router Id, hence cannot compare.
if path_source1 is None and path_source2 is None:
return None
asn1 = get_asn(path_source1)
asn2 = get_asn(path_source2)
is_ebgp1 = asn1 != local_asn
is_ebgp2 = asn2 != local_asn
# If both paths are from eBGP peers, then according to RFC we need
# not tie break using router id.
if (is_ebgp1 and is_ebgp2):
return None
if ((is_ebgp1 is True and is_ebgp2 is False) or
(is_ebgp1 is False and is_ebgp2 is True)):
raise ValueError('This method does not support comparing ebgp with'
' ibgp path')
# At least one path is not coming from NC, so we get local bgp id.
if path_source1 is not None:
local_bgp_id = path_source1.protocol.sent_open_msg.bgp_identifier
else:
local_bgp_id = path_source2.protocol.sent_open_msg.bgp_identifier
# Get router ids.
router_id1 = get_router_id(path_source1, local_bgp_id)
router_id2 = get_router_id(path_source2, local_bgp_id)
# If both router ids are same/equal we cannot decide.
# This case is possible since router ids are arbitrary.
if router_id1 == router_id2:
return None
# Select the path with lowest router Id.
from ryu.services.protocols.bgp.utils.bgp import from_inet_ptoi
if (from_inet_ptoi(router_id1) < from_inet_ptoi(router_id2)):
return path1
else:
return path2
|
apache-2.0
|
felliott/waterbutler
|
waterbutler/providers/owncloud/metadata.py
|
6
|
2005
|
from waterbutler.core import metadata
class BaseOwnCloudMetadata(metadata.BaseMetadata):
def __init__(self, href, folder, attributes=None):
super(BaseOwnCloudMetadata, self).__init__(None)
self.attributes = attributes or {}
self._folder = folder
self._href = href
@property
def provider(self):
return 'owncloud'
@property
def name(self):
return self._href.strip('/').split('/')[-1]
@property
def path(self):
path = self._href[len(self._folder) - 1:]
return path
@property
def size(self):
if '{DAV:}getcontentlength' in self.attributes:
return str(int(self.attributes['{DAV:}getcontentlength']))
return None
@property
def etag(self):
return str(self.attributes['{DAV:}getetag'])
@property
def modified(self):
return self.attributes['{DAV:}getlastmodified']
@property
def created_utc(self):
return None
class OwnCloudFileMetadata(BaseOwnCloudMetadata, metadata.BaseFileMetadata):
@property
def content_type(self):
if '{DAV:}getcontenttype' in self.attributes:
return str(self.attributes['{DAV:}getcontenttype'])
return None
class OwnCloudFolderMetadata(BaseOwnCloudMetadata, metadata.BaseFolderMetadata):
@property
def content_type(self):
if '{DAV:}getcontenttype' in self.attributes:
return str(self.attributes['{DAV:}getcontenttype'])
return 'httpd/unix-directory'
class OwnCloudFileRevisionMetadata(metadata.BaseFileRevisionMetadata):
def __init__(self, modified):
self._modified = modified
@classmethod
def from_metadata(cls, metadata):
return OwnCloudFileRevisionMetadata(modified=metadata.modified)
@property
def version_identifier(self):
return 'revision'
@property
def version(self):
return 'latest'
@property
def modified(self):
return self._modified
|
apache-2.0
|
Greennut/ostproject
|
django/contrib/gis/gdal/geomtype.py
|
404
|
2967
|
from django.contrib.gis.gdal.error import OGRException
#### OGRGeomType ####
class OGRGeomType(object):
"Encapulates OGR Geometry Types."
wkb25bit = -2147483648
# Dictionary of acceptable OGRwkbGeometryType s and their string names.
_types = {0 : 'Unknown',
1 : 'Point',
2 : 'LineString',
3 : 'Polygon',
4 : 'MultiPoint',
5 : 'MultiLineString',
6 : 'MultiPolygon',
7 : 'GeometryCollection',
100 : 'None',
101 : 'LinearRing',
1 + wkb25bit: 'Point25D',
2 + wkb25bit: 'LineString25D',
3 + wkb25bit: 'Polygon25D',
4 + wkb25bit: 'MultiPoint25D',
5 + wkb25bit : 'MultiLineString25D',
6 + wkb25bit : 'MultiPolygon25D',
7 + wkb25bit : 'GeometryCollection25D',
}
# Reverse type dictionary, keyed by lower-case of the name.
_str_types = dict([(v.lower(), k) for k, v in _types.items()])
def __init__(self, type_input):
"Figures out the correct OGR Type based upon the input."
if isinstance(type_input, OGRGeomType):
num = type_input.num
elif isinstance(type_input, basestring):
type_input = type_input.lower()
if type_input == 'geometry': type_input='unknown'
num = self._str_types.get(type_input, None)
if num is None:
raise OGRException('Invalid OGR String Type "%s"' % type_input)
elif isinstance(type_input, int):
if not type_input in self._types:
raise OGRException('Invalid OGR Integer Type: %d' % type_input)
num = type_input
else:
raise TypeError('Invalid OGR input type given.')
# Setting the OGR geometry type number.
self.num = num
def __str__(self):
"Returns the value of the name property."
return self.name
def __eq__(self, other):
"""
Does an equivalence test on the OGR type with the given
other OGRGeomType, the short-hand string, or the integer.
"""
if isinstance(other, OGRGeomType):
return self.num == other.num
elif isinstance(other, basestring):
return self.name.lower() == other.lower()
elif isinstance(other, int):
return self.num == other
else:
return False
def __ne__(self, other):
return not (self == other)
@property
def name(self):
"Returns a short-hand string form of the OGR Geometry type."
return self._types[self.num]
@property
def django(self):
"Returns the Django GeometryField for this OGR Type."
s = self.name.replace('25D', '')
if s in ('LinearRing', 'None'):
return None
elif s == 'Unknown':
s = 'Geometry'
return s + 'Field'
|
bsd-3-clause
|
nguy/PyDisdrometer
|
pydsd/aux_readers/read_2ds.py
|
3
|
4909
|
# -*- coding: utf-8 -*-
import csv
import datetime
import itertools
import numpy as np
import numpy.ma as ma
import scipy.optimize
from pytmatrix.psd import GammaPSD
from ..DropSizeDistribution import DropSizeDistribution
from ..io import common
def read_2ds(filename, campaign="acapex"):
"""Read a airborne 2DS Cloud Probe File into a DropSizeDistribution Object.
Takes a filename pointing to a 2DS Horizontal G1 Aircraft file and returns a `DropSizeDistribution` object.
Parameters:
-----------
filename: string
2DS Cloud Probe Filename
campaign: optional, string
Optional campaign setting, currently does nothing. Defaults to acapex
Usage:
------
dsd = read_2ds_h(filename, campaign='acapex')
Current Options for campaign are:
'acapex'
Returns:
--------
dsd: `DropSizeDistribution`
`DropSizeDistribution` object
Note:
-----
No rain rate in the raw file.
"""
reader = TwoDSReader(filename, campaign)
if reader:
return DropSizeDistribution(reader)
else:
return None
del (reader)
class TwoDSReader(object):
""" TwoDSReader class for 2DS Cloud Probe Data.
This class reads and parses data from 2DS data files. Use the read_2ds() function to interface with this.
"""
def __init__(self, filename, campaign="acapex"):
""" Initializer for a 2DS Cloud Probe class.
Read and process a 2DS Cloud Probe data file. This should only be called by the read_2ds() function.
Parameters:
-----------
filename: string
filename pointing to a 2DS file.
campaign: optional, string
campaign name, currently only supports acapex. Defaults to 'acapex'
Returns:
--------
two_ds: TwoDSReader
TwoDSReader class
"""
self.fields = {}
time = []
bins = []
Nd = []
self.f = open(filename, "rU")
reader = csv.reader(self.f)
# Remove Header lines but save them to variables for use later
next(self.f)
next(self.f)
next(self.f)
header_l = next(self.f)
for row in reader:
time.append(float(row[0].split()[0]))
Nd.append(list(map(float, row[10:71])))
Nd = np.ma.array(Nd)
time = np.ma.array(time)
header = header_l.split(",")
bins = header[10:71]
# Loop over the bins, split them, remove the C, split again into bin edges
bin_edge_str = []
for i, sbin in enumerate(bins):
s = sbin.split(":")
bin_no_clist = s[1]
s1 = bin_no_clist.split("-")
bin_edge_str.append(s1)
# Loop over the list of strings containing bin edges, turn them into integers
bin_edge_int = []
bin_edge_int.append(float(bin_edge_str[0][0]))
for sbins in bin_edge_str:
bin_edge_int.append(float(sbins[1]))
bin_edge_int[-1] = 4000
bin_edges = np.array(bin_edge_int)
spread = np.diff(bin_edges)
# diameter
diameter = bin_edges[0:-1] + spread / 2.0
# NEED TO GRAB DATE FROM FILE
yyyy = os.path.basename(self.filename).split(".")[1][0:4]
mm = os.path.basename(self.filename).split(".")[1][4:6]
dd = os.path.basename(self.filename).split(".")[1][6:8]
t_units = "seconds since " + "-".join([yyyy, mm, dd]) + "T00:00:00"
# Return a common epoch time dictionary
self.time = _get_epoch_time(time, t_units)
self.bin_edges = common.var_to_dict(
"bin_edges", bin_edges / 1000., "mm", "Boundaries of bin sizes"
)
self.spread = common.var_to_dict(
"spread", spread / 1000., "mm", "Bin size spread of bins"
)
self.diameter = common.var_to_dict(
"diameter", diameter / 1000., "mm", "Particle diameter of bins"
)
# #/L/micrometer to #/m^3/mm
self.fields["Nd"] = common.var_to_dict(
"Nd",
np.ma.array(Nd * 1000. * 1000.),
"m^-3 mm^-1",
"Liquid water particle concentration",
)
def _get_epoch_time(sample_times, t_units):
"""Convert time to epoch time and return a dictionary."""
# Convert the time array into a datetime instance
dts = num2date(sample_times, t_units)
# Now convert this datetime instance into a number of seconds since Epoch
timesec = date2num(dts, common.EPOCH_UNITS)
# Now once again convert this data into a datetime instance
time_unaware = num2date(timesec, common.EPOCH_UNITS)
eptime = {
"data": time_unaware,
"units": common.EPOCH_UNITS,
"standard_name": "Time",
"long_name": "Time (UTC)",
}
|
lgpl-2.1
|
flingone/frameworks_base_cmds_remoted
|
libs/boost/tools/build/test/searched_lib.py
|
6
|
5114
|
#!/usr/bin/python
# Copyright 2003 Dave Abrahams
# Copyright 2003, 2004, 2005, 2006 Vladimir Prus
# Distributed under the Boost Software License, Version 1.0.
# (See accompanying file LICENSE_1_0.txt or http://www.boost.org/LICENSE_1_0.txt)
# Test usage of searched-libs: one which are found via -l
# switch to the linker/compiler.
import BoostBuild
import os
import string
t = BoostBuild.Tester(use_test_config=False)
# To start with, we have to prepare a library to link with.
t.write("lib/jamroot.jam", "")
t.write("lib/jamfile.jam", "lib test_lib : test_lib.cpp ;")
t.write("lib/test_lib.cpp", """\
#ifdef _WIN32
__declspec(dllexport)
#endif
void foo() {}
""");
t.run_build_system(subdir="lib")
t.expect_addition("lib/bin/$toolset/debug/test_lib.dll")
# Auto adjusting of suffixes does not work, since we need to
# change dll to lib.
if ( ( os.name == "nt" ) or os.uname()[0].lower().startswith("cygwin") ) and \
( BoostBuild.get_toolset() != "gcc" ):
t.copy("lib/bin/$toolset/debug/test_lib.implib", "lib/test_lib.implib")
t.copy("lib/bin/$toolset/debug/test_lib.dll", "lib/test_lib.dll")
else:
t.copy("lib/bin/$toolset/debug/test_lib.dll", "lib/test_lib.dll")
# Test that the simplest usage of searched library works.
t.write("jamroot.jam", "")
t.write("jamfile.jam", """\
import path ;
import project ;
exe main : main.cpp helper ;
lib helper : helper.cpp test_lib ;
lib test_lib : : <name>test_lib <search>lib ;
""")
t.write("main.cpp", """\
void helper();
int main() { helper(); }
""")
t.write("helper.cpp", """\
void foo();
void
#if defined(_WIN32)
__declspec(dllexport)
#endif
helper() { foo(); }
""")
t.run_build_system(["-d2"])
t.expect_addition("bin/$toolset/debug/main.exe")
t.rm("bin/$toolset/debug/main.exe")
# Test that 'unit-test' will correctly add runtime paths to searched libraries.
t.write("jamfile.jam", """\
import path ;
import project ;
import testing ;
project : requirements <hardcode-dll-paths>false ;
unit-test main : main.cpp helper ;
lib helper : helper.cpp test_lib ;
lib test_lib : : <name>test_lib <search>lib ;
""")
t.run_build_system()
t.expect_addition("bin/$toolset/debug/main.passed")
t.rm("bin/$toolset/debug/main.exe")
# Now try using searched lib from static lib. Request shared version of searched
# lib, since we do not have a static one handy.
t.write("jamfile.jam", """\
exe main : main.cpp helper ;
lib helper : helper.cpp test_lib/<link>shared : <link>static ;
lib test_lib : : <name>test_lib <search>lib ;
""")
t.run_build_system(stderr=None)
t.expect_addition("bin/$toolset/debug/main.exe")
t.expect_addition("bin/$toolset/debug/link-static/helper.lib")
t.rm("bin/$toolset/debug/main.exe")
# A regression test: <library>property referring to searched-lib was being
# mishandled. As the result, we were putting target name to the command line!
# Note that
# g++ ...... <.>z
# works nicely in some cases, sending output from compiler to file 'z'. This
# problem shows up when searched libs are in usage requirements.
t.write("jamfile.jam", "exe main : main.cpp d/d2//a ;")
t.write("main.cpp", """\
void foo();
int main() { foo(); }
""")
t.write("d/d2/jamfile.jam", """\
lib test_lib : : <name>test_lib <search>../../lib ;
lib a : a.cpp : : : <library>test_lib ;
""")
t.write("d/d2/a.cpp", """\
#ifdef _WIN32
__declspec(dllexport) int force_library_creation_for_a;
#endif
""")
t.run_build_system()
# A regression test. Searched targets were not associated with any properties.
# For that reason, if the same searched lib is generated with two different
# properties, we had an error saying they are actualized to the same Jam target
# name.
t.write("jamroot.jam", "")
t.write("a.cpp", "")
# The 'l' library will be built in two variants: 'debug' (directly requested)
# and 'release' (requested from 'a').
t.write("jamfile.jam", """\
exe a : a.cpp l/<variant>release ;
lib l : : <name>l_d <variant>debug ;
lib l : : <name>l_r <variant>release ;
""")
t.run_build_system(["-n"])
# A regression test. Two virtual target with the same properties were created
# for 'l' target, which caused and error to be reported when actualizing
# targets. The final error is correct, but we should not create two duplicated
# targets. Thanks to Andre Hentz for finding this bug.
t.write("jamroot.jam", "")
t.write("a.cpp", "")
t.write("jamfile.jam", """\
project a : requirements <runtime-link>static ;
static-lib a : a.cpp l ;
lib l : : <name>l_f ;
""")
t.run_build_system(["-n"])
# Make sure plain "lib foobar ; " works.
t.write("jamfile.jam", """\
exe a : a.cpp foobar ;
lib foobar ;
""")
t.run_build_system(["-n", "-d2"])
t.fail_test(string.find(t.stdout(), "foobar") == -1)
# Make sure plain "lib foo bar ; " works.
t.write("jamfile.jam", """\
exe a : a.cpp foo bar ;
lib foo bar ;
""")
t.run_build_system(["-n", "-d2"])
t.fail_test(string.find(t.stdout(), "foo") == -1)
t.fail_test(string.find(t.stdout(), "bar") == -1)
t.cleanup()
|
apache-2.0
|
magic0704/neutron
|
neutron/tests/unit/db/test_l3_ha_db.py
|
2
|
23196
|
# Copyright (C) 2014 eNovance SAS <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import mock
from oslo_config import cfg
from neutron.api.v2 import attributes
from neutron.common import constants
from neutron import context
from neutron.db import agents_db
from neutron.db import common_db_mixin
from neutron.db import l3_agentschedulers_db
from neutron.db import l3_hamode_db
from neutron.extensions import l3
from neutron.extensions import l3_ext_ha_mode
from neutron import manager
from neutron.openstack.common import uuidutils
from neutron.scheduler import l3_agent_scheduler
from neutron.tests.unit import testlib_api
_uuid = uuidutils.generate_uuid
class FakeL3PluginWithAgents(common_db_mixin.CommonDbMixin,
l3_hamode_db.L3_HA_NAT_db_mixin,
l3_agentschedulers_db.L3AgentSchedulerDbMixin,
agents_db.AgentDbMixin):
pass
class L3HATestFramework(testlib_api.SqlTestCase):
def setUp(self):
super(L3HATestFramework, self).setUp()
self.admin_ctx = context.get_admin_context()
self.setup_coreplugin('neutron.plugins.ml2.plugin.Ml2Plugin')
self.core_plugin = manager.NeutronManager.get_plugin()
notif_p = mock.patch.object(l3_hamode_db.L3_HA_NAT_db_mixin,
'_notify_ha_interfaces_updated')
self.notif_m = notif_p.start()
cfg.CONF.set_override('allow_overlapping_ips', True)
self.plugin = FakeL3PluginWithAgents()
self._register_agents()
def _register_agents(self):
agent_status = {
'agent_type': constants.AGENT_TYPE_L3,
'binary': 'neutron-l3-agent',
'host': 'l3host',
'topic': 'N/A',
'configurations': {'agent_mode': 'legacy'}
}
self.plugin.create_or_update_agent(self.admin_ctx, agent_status)
agent_status['host'] = 'l3host_2'
agent_status['configurations'] = {'agent_mode': 'dvr_snat'}
self.plugin.create_or_update_agent(self.admin_ctx, agent_status)
self.agent1, self.agent2 = self.plugin.get_agents(self.admin_ctx)
def _create_router(self, ha=True, tenant_id='tenant1', distributed=None,
ctx=None):
if ctx is None:
ctx = self.admin_ctx
ctx.tenant_id = tenant_id
router = {'name': 'router1', 'admin_state_up': True}
if ha is not None:
router['ha'] = ha
if distributed is not None:
router['distributed'] = distributed
return self.plugin.create_router(ctx, {'router': router})
def _update_router(self, router_id, ha=True, distributed=None, ctx=None):
if ctx is None:
ctx = self.admin_ctx
data = {'ha': ha} if ha is not None else {}
if distributed is not None:
data['distributed'] = distributed
return self.plugin._update_router_db(ctx, router_id,
data, None)
def _bind_router(self, router_id):
with self.admin_ctx.session.begin(subtransactions=True):
scheduler = l3_agent_scheduler.ChanceScheduler()
agents_db = self.plugin.get_agents_db(self.admin_ctx)
scheduler.bind_ha_router_to_agents(
self.plugin,
self.admin_ctx,
router_id,
agents_db)
def test_get_ha_router_port_bindings(self):
router = self._create_router()
self._bind_router(router['id'])
bindings = self.plugin.get_ha_router_port_bindings(
self.admin_ctx, [router['id']])
binding_dicts = [{'router_id': binding['router_id'],
'l3_agent_id': binding['l3_agent_id']}
for binding in bindings]
self.assertIn({'router_id': router['id'],
'l3_agent_id': self.agent1['id']}, binding_dicts)
self.assertIn({'router_id': router['id'],
'l3_agent_id': self.agent2['id']}, binding_dicts)
def test_get_l3_bindings_hosting_router_with_ha_states_ha_router(self):
router = self._create_router()
self._bind_router(router['id'])
self.plugin.update_routers_states(
self.admin_ctx, {router['id']: 'active'}, self.agent1['host'])
bindings = self.plugin.get_l3_bindings_hosting_router_with_ha_states(
self.admin_ctx, router['id'])
agent_ids = [(agent[0]['id'], agent[1]) for agent in bindings]
self.assertIn((self.agent1['id'], 'active'), agent_ids)
self.assertIn((self.agent2['id'], 'standby'), agent_ids)
def test_get_l3_bindings_hosting_router_with_ha_states_not_scheduled(self):
router = self._create_router(ha=False)
bindings = self.plugin.get_l3_bindings_hosting_router_with_ha_states(
self.admin_ctx, router['id'])
self.assertEqual([], bindings)
class L3HATestCase(L3HATestFramework):
def test_verify_configuration_succeed(self):
# Default configuration should pass
self.plugin._verify_configuration()
def test_verify_configuration_l3_ha_net_cidr_is_not_a_cidr(self):
cfg.CONF.set_override('l3_ha_net_cidr', 'not a cidr')
self.assertRaises(
l3_ext_ha_mode.HANetworkCIDRNotValid,
self.plugin._verify_configuration)
def test_verify_configuration_l3_ha_net_cidr_is_not_a_subnet(self):
cfg.CONF.set_override('l3_ha_net_cidr', '10.0.0.1/8')
self.assertRaises(
l3_ext_ha_mode.HANetworkCIDRNotValid,
self.plugin._verify_configuration)
def test_verify_configuration_min_l3_agents_per_router_below_minimum(self):
cfg.CONF.set_override('min_l3_agents_per_router', 0)
self.assertRaises(
l3_ext_ha_mode.HAMinimumAgentsNumberNotValid,
self.plugin._check_num_agents_per_router)
def test_verify_configuration_max_l3_agents_below_min_l3_agents(self):
cfg.CONF.set_override('max_l3_agents_per_router', 3)
cfg.CONF.set_override('min_l3_agents_per_router', 4)
self.assertRaises(
l3_ext_ha_mode.HAMaximumAgentsNumberNotValid,
self.plugin._check_num_agents_per_router)
def test_verify_configuration_max_l3_agents_unlimited(self):
cfg.CONF.set_override('max_l3_agents_per_router',
l3_hamode_db.UNLIMITED_AGENTS_PER_ROUTER)
self.plugin._check_num_agents_per_router()
def test_ha_router_create(self):
router = self._create_router()
self.assertTrue(router['ha'])
def test_ha_router_create_with_distributed(self):
self.assertRaises(l3_ext_ha_mode.DistributedHARouterNotSupported,
self._create_router,
distributed=True)
def test_no_ha_router_create(self):
router = self._create_router(ha=False)
self.assertFalse(router['ha'])
def test_router_create_with_ha_conf_enabled(self):
cfg.CONF.set_override('l3_ha', True)
router = self._create_router(ha=None)
self.assertTrue(router['ha'])
def test_migration_from_ha(self):
router = self._create_router()
self.assertTrue(router['ha'])
router = self._update_router(router['id'], ha=False)
self.assertFalse(router.extra_attributes['ha'])
self.assertIsNone(router.extra_attributes['ha_vr_id'])
def test_migration_to_ha(self):
router = self._create_router(ha=False)
self.assertFalse(router['ha'])
router = self._update_router(router['id'], ha=True)
self.assertTrue(router.extra_attributes['ha'])
self.assertIsNotNone(router.extra_attributes['ha_vr_id'])
def test_migrate_ha_router_to_distributed(self):
router = self._create_router()
self.assertTrue(router['ha'])
self.assertRaises(l3_ext_ha_mode.DistributedHARouterNotSupported,
self._update_router,
router['id'],
distributed=True)
def test_l3_agent_routers_query_interface(self):
router = self._create_router()
self._bind_router(router['id'])
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx,
self.agent1['host'])
self.assertEqual(1, len(routers))
router = routers[0]
self.assertIsNotNone(router.get('ha'))
interface = router.get(constants.HA_INTERFACE_KEY)
self.assertIsNotNone(interface)
self.assertEqual(constants.DEVICE_OWNER_ROUTER_HA_INTF,
interface['device_owner'])
subnets = interface['subnets']
self.assertEqual(1, len(subnets))
self.assertEqual(cfg.CONF.l3_ha_net_cidr, subnets[0]['cidr'])
def test_unique_ha_network_per_tenant(self):
tenant1 = _uuid()
tenant2 = _uuid()
self._create_router(tenant_id=tenant1)
self._create_router(tenant_id=tenant2)
ha_network1 = self.plugin.get_ha_network(self.admin_ctx, tenant1)
ha_network2 = self.plugin.get_ha_network(self.admin_ctx, tenant2)
self.assertNotEqual(
ha_network1['network_id'], ha_network2['network_id'])
def _deployed_router_change_ha_flag(self, to_ha):
self._create_router(ha=not to_ha)
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx)
router = routers[0]
interface = router.get(constants.HA_INTERFACE_KEY)
if to_ha:
self.assertIsNone(interface)
else:
self.assertIsNotNone(interface)
self._update_router(router['id'], to_ha)
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx)
router = routers[0]
interface = router.get(constants.HA_INTERFACE_KEY)
if to_ha:
self.assertIsNotNone(interface)
else:
self.assertIsNone(interface)
def test_deployed_router_can_have_ha_enabled(self):
self._deployed_router_change_ha_flag(to_ha=True)
def test_deployed_router_can_have_ha_disabled(self):
self._deployed_router_change_ha_flag(to_ha=False)
def test_create_ha_router_notifies_agent(self):
self._create_router()
self.assertTrue(self.notif_m.called)
def test_update_router_to_ha_notifies_agent(self):
router = self._create_router(ha=False)
self.notif_m.reset_mock()
self._update_router(router['id'], ha=True)
self.assertTrue(self.notif_m.called)
def test_unique_vr_id_between_routers(self):
self._create_router()
self._create_router()
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx)
self.assertEqual(2, len(routers))
self.assertNotEqual(routers[0]['ha_vr_id'], routers[1]['ha_vr_id'])
@mock.patch('neutron.db.l3_hamode_db.VR_ID_RANGE', new=set(range(1, 1)))
def test_vr_id_depleted(self):
self.assertRaises(l3_ext_ha_mode.NoVRIDAvailable, self._create_router)
@mock.patch('neutron.db.l3_hamode_db.VR_ID_RANGE', new=set(range(1, 2)))
def test_vr_id_unique_range_per_tenant(self):
self._create_router()
self._create_router(tenant_id=_uuid())
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx)
self.assertEqual(2, len(routers))
self.assertEqual(routers[0]['ha_vr_id'], routers[1]['ha_vr_id'])
@mock.patch('neutron.db.l3_hamode_db.MAX_ALLOCATION_TRIES', new=2)
def test_vr_id_allocation_contraint_conflict(self):
router = self._create_router()
network = self.plugin.get_ha_network(self.admin_ctx,
router['tenant_id'])
with mock.patch.object(self.plugin, '_get_allocated_vr_id',
return_value=set()) as alloc:
self.assertRaises(l3_ext_ha_mode.MaxVRIDAllocationTriesReached,
self.plugin._allocate_vr_id, self.admin_ctx,
network.network_id, router['id'])
self.assertEqual(2, len(alloc.mock_calls))
def test_vr_id_allocation_delete_router(self):
router = self._create_router()
network = self.plugin.get_ha_network(self.admin_ctx,
router['tenant_id'])
allocs_before = self.plugin._get_allocated_vr_id(self.admin_ctx,
network.network_id)
router = self._create_router()
allocs_current = self.plugin._get_allocated_vr_id(self.admin_ctx,
network.network_id)
self.assertNotEqual(allocs_before, allocs_current)
self.plugin.delete_router(self.admin_ctx, router['id'])
allocs_after = self.plugin._get_allocated_vr_id(self.admin_ctx,
network.network_id)
self.assertEqual(allocs_before, allocs_after)
def test_vr_id_allocation_router_migration(self):
router = self._create_router()
network = self.plugin.get_ha_network(self.admin_ctx,
router['tenant_id'])
allocs_before = self.plugin._get_allocated_vr_id(self.admin_ctx,
network.network_id)
router = self._create_router()
self._update_router(router['id'], ha=False)
allocs_after = self.plugin._get_allocated_vr_id(self.admin_ctx,
network.network_id)
self.assertEqual(allocs_before, allocs_after)
def test_one_ha_router_one_not(self):
self._create_router(ha=False)
self._create_router()
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx)
ha0 = routers[0]['ha']
ha1 = routers[1]['ha']
self.assertNotEqual(ha0, ha1)
def test_add_ha_port_binding_failure_rolls_back_port(self):
router = self._create_router()
device_filter = {'device_id': [router['id']]}
ports_before = self.core_plugin.get_ports(
self.admin_ctx, filters=device_filter)
network = self.plugin.get_ha_network(self.admin_ctx,
router['tenant_id'])
with mock.patch.object(self.plugin, '_create_ha_port_binding',
side_effect=ValueError):
self.assertRaises(ValueError, self.plugin.add_ha_port,
self.admin_ctx, router['id'], network.network_id,
router['tenant_id'])
ports_after = self.core_plugin.get_ports(
self.admin_ctx, filters=device_filter)
self.assertEqual(ports_before, ports_after)
def test_create_ha_network_binding_failure_rolls_back_network(self):
networks_before = self.core_plugin.get_networks(self.admin_ctx)
with mock.patch.object(self.plugin,
'_create_ha_network_tenant_binding',
side_effect=ValueError):
self.assertRaises(ValueError, self.plugin._create_ha_network,
self.admin_ctx, _uuid())
networks_after = self.core_plugin.get_networks(self.admin_ctx)
self.assertEqual(networks_before, networks_after)
def test_create_ha_network_subnet_failure_rolls_back_network(self):
networks_before = self.core_plugin.get_networks(self.admin_ctx)
with mock.patch.object(self.plugin, '_create_ha_subnet',
side_effect=ValueError):
self.assertRaises(ValueError, self.plugin._create_ha_network,
self.admin_ctx, _uuid())
networks_after = self.core_plugin.get_networks(self.admin_ctx)
self.assertEqual(networks_before, networks_after)
def test_create_ha_interfaces_binding_failure_rolls_back_ports(self):
router = self._create_router()
network = self.plugin.get_ha_network(self.admin_ctx,
router['tenant_id'])
device_filter = {'device_id': [router['id']]}
ports_before = self.core_plugin.get_ports(
self.admin_ctx, filters=device_filter)
router_db = self.plugin._get_router(self.admin_ctx, router['id'])
with mock.patch.object(self.plugin, '_create_ha_port_binding',
side_effect=ValueError):
self.assertRaises(ValueError, self.plugin._create_ha_interfaces,
self.admin_ctx, router_db, network)
ports_after = self.core_plugin.get_ports(
self.admin_ctx, filters=device_filter)
self.assertEqual(ports_before, ports_after)
def test_create_router_db_ha_attribute_failure_rolls_back_router(self):
routers_before = self.plugin.get_routers(self.admin_ctx)
for method in ('_set_vr_id',
'_create_ha_interfaces',
'_notify_ha_interfaces_updated'):
with mock.patch.object(self.plugin, method,
side_effect=ValueError):
self.assertRaises(ValueError, self._create_router)
routers_after = self.plugin.get_routers(self.admin_ctx)
self.assertEqual(routers_before, routers_after)
def test_update_routers_states(self):
router1 = self._create_router()
self._bind_router(router1['id'])
router2 = self._create_router()
self._bind_router(router2['id'])
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx,
self.agent1['host'])
for router in routers:
self.assertEqual('standby', router[constants.HA_ROUTER_STATE_KEY])
states = {router1['id']: 'active',
router2['id']: 'standby'}
self.plugin.update_routers_states(
self.admin_ctx, states, self.agent1['host'])
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx,
self.agent1['host'])
for router in routers:
self.assertEqual(states[router['id']],
router[constants.HA_ROUTER_STATE_KEY])
def test_set_router_states_handles_concurrently_deleted_router(self):
router1 = self._create_router()
self._bind_router(router1['id'])
router2 = self._create_router()
self._bind_router(router2['id'])
bindings = self.plugin.get_ha_router_port_bindings(
self.admin_ctx, [router1['id'], router2['id']])
self.plugin.delete_router(self.admin_ctx, router1['id'])
self.plugin._set_router_states(
self.admin_ctx, bindings, {router1['id']: 'active',
router2['id']: 'active'})
routers = self.plugin.get_ha_sync_data_for_host(self.admin_ctx,
self.agent1['host'])
self.assertEqual('active', routers[0][constants.HA_ROUTER_STATE_KEY])
def test_exclude_dvr_agents_for_ha_candidates(self):
"""Test dvr agents are not counted in the ha candidates.
This test case tests that when get_number_of_agents_for_scheduling
is called, it doesn't count dvr agents.
"""
# Test setup registers two l3 agents.
# Register another l3 agent with dvr mode and assert that
# get_number_of_ha_agent_candidates return 2.
dvr_agent_status = {
'agent_type': constants.AGENT_TYPE_L3,
'binary': 'neutron-l3-agent',
'host': 'l3host_3',
'topic': 'N/A',
'configurations': {'agent_mode': 'dvr'}
}
self.plugin.create_or_update_agent(self.admin_ctx, dvr_agent_status)
num_ha_candidates = self.plugin.get_number_of_agents_for_scheduling(
self.admin_ctx)
self.assertEqual(2, num_ha_candidates)
class L3HAModeDbTestCase(L3HATestFramework):
def _create_network(self, plugin, ctx, name='net',
tenant_id='tenant1'):
network = {'network': {'name': name,
'shared': False,
'admin_state_up': True,
'tenant_id': tenant_id}}
return plugin.create_network(ctx, network)['id']
def _create_subnet(self, plugin, ctx, network_id, cidr='10.0.0.0/8',
name='subnet', tenant_id='tenant1'):
subnet = {'subnet': {'name': name,
'ip_version': 4,
'network_id': network_id,
'cidr': cidr,
'gateway_ip': attributes.ATTR_NOT_SPECIFIED,
'allocation_pools': attributes.ATTR_NOT_SPECIFIED,
'dns_nameservers': attributes.ATTR_NOT_SPECIFIED,
'host_routes': attributes.ATTR_NOT_SPECIFIED,
'tenant_id': tenant_id,
'enable_dhcp': True,
'ipv6_ra_mode': attributes.ATTR_NOT_SPECIFIED}}
created_subnet = plugin.create_subnet(ctx, subnet)
return created_subnet
def test_remove_ha_in_use(self):
router = self._create_router(ctx=self.admin_ctx)
network_id = self._create_network(self.core_plugin, self.admin_ctx)
subnet = self._create_subnet(self.core_plugin, self.admin_ctx,
network_id)
interface_info = {'subnet_id': subnet['id']}
self.plugin.add_router_interface(self.admin_ctx,
router['id'],
interface_info)
self.assertRaises(l3.RouterInUse, self.plugin.delete_router,
self.admin_ctx, router['id'])
bindings = self.plugin.get_ha_router_port_bindings(
self.admin_ctx, [router['id']])
self.assertEqual(2, len(bindings))
class L3HAUserTestCase(L3HATestFramework):
def setUp(self):
super(L3HAUserTestCase, self).setUp()
self.user_ctx = context.Context('', _uuid())
def test_create_ha_router(self):
self._create_router(ctx=self.user_ctx)
def test_update_router(self):
router = self._create_router(ctx=self.user_ctx)
self._update_router(router['id'], ha=False, ctx=self.user_ctx)
def test_delete_router(self):
router = self._create_router(ctx=self.user_ctx)
self.plugin.delete_router(self.user_ctx, router['id'])
|
apache-2.0
|
jimsimon/sky_engine
|
tools/linux/dump-static-initializers.py
|
83
|
8354
|
#!/usr/bin/env python
# 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.
"""Dump functions called by static intializers in a Linux Release binary.
Usage example:
tools/linux/dump-static-intializers.py out/Release/chrome
A brief overview of static initialization:
1) the compiler writes out, per object file, a function that contains
the static intializers for that file.
2) the compiler also writes out a pointer to that function in a special
section.
3) at link time, the linker concatenates the function pointer sections
into a single list of all initializers.
4) at run time, on startup the binary runs all function pointers.
The functions in (1) all have mangled names of the form
_GLOBAL__I_foobar.cc
using objdump, we can disassemble those functions and dump all symbols that
they reference.
"""
import optparse
import re
import subprocess
import sys
# A map of symbol => informative text about it.
NOTES = {
'__cxa_atexit@plt': 'registers a dtor to run at exit',
'std::__ioinit': '#includes <iostream>, use <ostream> instead',
}
# Determine whether this is a git checkout (as opposed to e.g. svn).
IS_GIT_WORKSPACE = (subprocess.Popen(
['git', 'rev-parse'], stderr=subprocess.PIPE).wait() == 0)
class Demangler(object):
"""A wrapper around c++filt to provide a function to demangle symbols."""
def __init__(self):
self.cppfilt = subprocess.Popen(['c++filt'],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
def Demangle(self, sym):
"""Given mangled symbol |sym|, return its demangled form."""
self.cppfilt.stdin.write(sym + '\n')
return self.cppfilt.stdout.readline().strip()
# Matches for example: "cert_logger.pb.cc", capturing "cert_logger".
protobuf_filename_re = re.compile(r'(.*)\.pb\.cc$')
def QualifyFilenameAsProto(filename):
"""Attempt to qualify a bare |filename| with a src-relative path, assuming it
is a protoc-generated file. If a single match is found, it is returned.
Otherwise the original filename is returned."""
if not IS_GIT_WORKSPACE:
return filename
match = protobuf_filename_re.match(filename)
if not match:
return filename
basename = match.groups(0)
gitlsfiles = subprocess.Popen(
['git', 'ls-files', '--', '*/%s.proto' % basename],
stdout=subprocess.PIPE)
candidate = filename
for line in gitlsfiles.stdout:
if candidate != filename:
return filename # Multiple hits, can't help.
candidate = line.strip()
return candidate
# Regex matching the substring of a symbol's demangled text representation most
# likely to appear in a source file.
# Example: "v8::internal::Builtins::InitBuiltinFunctionTable()" becomes
# "InitBuiltinFunctionTable", since the first (optional & non-capturing) group
# picks up any ::-qualification and the last fragment picks up a suffix that
# starts with an opener.
symbol_code_name_re = re.compile(r'^(?:[^(<[]*::)?([^:(<[]*).*?$')
def QualifyFilename(filename, symbol):
"""Given a bare filename and a symbol that occurs in it, attempt to qualify
it with a src-relative path. If more than one file matches, return the
original filename."""
if not IS_GIT_WORKSPACE:
return filename
match = symbol_code_name_re.match(symbol)
if not match:
return filename
symbol = match.group(1)
gitgrep = subprocess.Popen(
['git', 'grep', '-l', symbol, '--', '*/%s' % filename],
stdout=subprocess.PIPE)
candidate = filename
for line in gitgrep.stdout:
if candidate != filename: # More than one candidate; return bare filename.
return filename
candidate = line.strip()
return candidate
# Regex matching nm output for the symbols we're interested in.
# See test_ParseNmLine for examples.
nm_re = re.compile(r'(\S+) (\S+) t (?:_ZN12)?_GLOBAL__(?:sub_)?I_(.*)')
def ParseNmLine(line):
"""Given a line of nm output, parse static initializers as a
(file, start, size) tuple."""
match = nm_re.match(line)
if match:
addr, size, filename = match.groups()
return (filename, int(addr, 16), int(size, 16))
def test_ParseNmLine():
"""Verify the nm_re regex matches some sample lines."""
parse = ParseNmLine(
'0000000001919920 0000000000000008 t '
'_ZN12_GLOBAL__I_safe_browsing_service.cc')
assert parse == ('safe_browsing_service.cc', 26319136, 8), parse
parse = ParseNmLine(
'00000000026b9eb0 0000000000000024 t '
'_GLOBAL__sub_I_extension_specifics.pb.cc')
assert parse == ('extension_specifics.pb.cc', 40607408, 36), parse
# Just always run the test; it is fast enough.
test_ParseNmLine()
def ParseNm(binary):
"""Given a binary, yield static initializers as (file, start, size) tuples."""
nm = subprocess.Popen(['nm', '-S', binary], stdout=subprocess.PIPE)
for line in nm.stdout:
parse = ParseNmLine(line)
if parse:
yield parse
# Regex matching objdump output for the symbols we're interested in.
# Example line:
# 12354ab: (disassembly, including <FunctionReference>)
disassembly_re = re.compile(r'^\s+[0-9a-f]+:.*<(\S+)>')
def ExtractSymbolReferences(binary, start, end):
"""Given a span of addresses, returns symbol references from disassembly."""
cmd = ['objdump', binary, '--disassemble',
'--start-address=0x%x' % start, '--stop-address=0x%x' % end]
objdump = subprocess.Popen(cmd, stdout=subprocess.PIPE)
refs = set()
for line in objdump.stdout:
if '__static_initialization_and_destruction' in line:
raise RuntimeError, ('code mentions '
'__static_initialization_and_destruction; '
'did you accidentally run this on a Debug binary?')
match = disassembly_re.search(line)
if match:
(ref,) = match.groups()
if ref.startswith('.LC') or ref.startswith('_DYNAMIC'):
# Ignore these, they are uninformative.
continue
if ref.startswith('_GLOBAL__I_'):
# Probably a relative jump within this function.
continue
refs.add(ref)
return sorted(refs)
def main():
parser = optparse.OptionParser(usage='%prog [option] filename')
parser.add_option('-d', '--diffable', dest='diffable',
action='store_true', default=False,
help='Prints the filename on each line, for more easily '
'diff-able output. (Used by sizes.py)')
opts, args = parser.parse_args()
if len(args) != 1:
parser.error('missing filename argument')
return 1
binary = args[0]
demangler = Demangler()
file_count = 0
initializer_count = 0
files = ParseNm(binary)
if opts.diffable:
files = sorted(files)
for filename, addr, size in files:
file_count += 1
ref_output = []
qualified_filename = QualifyFilenameAsProto(filename)
if size == 2:
# gcc generates a two-byte 'repz retq' initializer when there is a
# ctor even when the ctor is empty. This is fixed in gcc 4.6, but
# Android uses gcc 4.4.
ref_output.append('[empty ctor, but it still has cost on gcc <4.6]')
else:
for ref in ExtractSymbolReferences(binary, addr, addr+size):
initializer_count += 1
ref = demangler.Demangle(ref)
if qualified_filename == filename:
qualified_filename = QualifyFilename(filename, ref)
note = ''
if ref in NOTES:
note = NOTES[ref]
elif ref.endswith('_2eproto()'):
note = 'protocol compiler bug: crbug.com/105626'
if note:
ref_output.append('%s [%s]' % (ref, note))
else:
ref_output.append(ref)
if opts.diffable:
if ref_output:
print '\n'.join('# ' + qualified_filename + ' ' + r for r in ref_output)
else:
print '# %s: (empty initializer list)' % qualified_filename
else:
print '%s (initializer offset 0x%x size 0x%x)' % (qualified_filename,
addr, size)
print ''.join(' %s\n' % r for r in ref_output)
if opts.diffable:
print '#',
print 'Found %d static initializers in %d files.' % (initializer_count,
file_count)
return 0
if '__main__' == __name__:
sys.exit(main())
|
bsd-3-clause
|
TRESCLOUD/odoopub
|
addons/website_event/models/event.py
|
45
|
5258
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2013-Today OpenERP SA (<http://www.openerp.com>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
##############################################################################
from openerp.osv import osv, fields
from openerp import SUPERUSER_ID
from openerp.tools.translate import _
import re
from openerp.addons.website.models.website import slug
class event(osv.osv):
_name = 'event.event'
_inherit = ['event.event','website.seo.metadata']
def _get_new_menu_pages(self, cr, uid, event, context=None):
context = context or {}
todo = [
(_('Introduction'), 'website_event.template_intro'),
(_('Location'), 'website_event.template_location')
]
web = self.pool.get('website')
result = []
for name,path in todo:
name2 = name+' '+event.name
newpath = web.new_page(cr, uid, name2, path, ispage=False, context=context)
url = "/event/"+slug(event)+"/page/" + newpath
result.append((name, url))
return result
def _set_show_menu(self, cr, uid, ids, name, value, arg, context=None):
menuobj = self.pool.get('website.menu')
eventobj = self.pool.get('event.event')
for event in self.browse(cr, uid, [ids], context=context):
if event.menu_id and not value:
menuobj.unlink(cr, uid, [event.menu_id.id], context=context)
elif value and not event.menu_id:
root = menuobj.create(cr, uid, {
'name': event.name
}, context=context)
tocreate = self._get_new_menu_pages(cr, uid, event, context)
tocreate.append((_('Register'), '/event/%s/register' % slug(event)))
sequence = 0
for name,url in tocreate:
menuobj.create(cr, uid, {
'name': name,
'url': url,
'parent_id': root,
'sequence': sequence
}, context=context)
sequence += 1
eventobj.write(cr, uid, [event.id], {'menu_id': root}, context=context)
return True
def _get_show_menu(self, cr, uid, ids, field_name, arg, context=None):
res = dict.fromkeys(ids, '')
for event in self.browse(cr, uid, ids, context=context):
res[event.id] = bool(event.menu_id)
return res
def _website_url(self, cr, uid, ids, field_name, arg, context=None):
res = dict.fromkeys(ids, '')
for event in self.browse(cr, uid, ids, context=context):
res[event.id] = "/event/" + slug(event)
return res
def _default_hashtag(self, cr, uid, context={}):
name = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id.name
return re.sub("[- \\.\\(\\)\\@\\#\\&]+", "", name).lower()
_columns = {
'twitter_hashtag': fields.char('Twitter Hashtag'),
'website_published': fields.boolean('Visible in Website', copy=False),
# TDE TODO FIXME: when website_mail/mail_thread.py inheritance work -> this field won't be necessary
'website_message_ids': fields.one2many(
'mail.message', 'res_id',
domain=lambda self: [
'&', ('model', '=', self._name), ('type', '=', 'comment')
],
string='Website Messages',
help="Website communication history",
),
'website_url': fields.function(_website_url, string="Website url", type="char"),
'show_menu': fields.function(_get_show_menu, fnct_inv=_set_show_menu, type='boolean', string='Dedicated Menu'),
'menu_id': fields.many2one('website.menu', 'Event Menu'),
}
_defaults = {
'show_menu': False,
'twitter_hashtag': _default_hashtag
}
def google_map_img(self, cr, uid, ids, zoom=8, width=298, height=298, context=None):
event = self.browse(cr, uid, ids[0], context=context)
if event.address_id:
return self.browse(cr, SUPERUSER_ID, ids[0], context=context).address_id.google_map_img()
return None
def google_map_link(self, cr, uid, ids, zoom=8, context=None):
event = self.browse(cr, uid, ids[0], context=context)
if event.address_id:
return self.browse(cr, SUPERUSER_ID, ids[0], context=context).address_id.google_map_link()
return None
|
agpl-3.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.