repo_name
stringlengths 5
92
| path
stringlengths 4
221
| copies
stringclasses 19
values | size
stringlengths 4
6
| content
stringlengths 766
896k
| license
stringclasses 15
values | hash
int64 -9,223,277,421,539,062,000
9,223,102,107B
| line_mean
float64 6.51
99.9
| line_max
int64 32
997
| alpha_frac
float64 0.25
0.96
| autogenerated
bool 1
class | ratio
float64 1.5
13.6
| config_test
bool 2
classes | has_no_keywords
bool 2
classes | few_assignments
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
flacjacket/sympy
|
sympy/core/tests/test_expr.py
|
1
|
48018
|
from __future__ import division
from sympy import (Add, Basic, S, Symbol, Wild, Float, Integer, Rational, I,
sin, cos, tan, exp, log, nan, oo, sqrt, symbols, Integral, sympify,
WildFunction, Poly, Function, Derivative, Number, pi, NumberSymbol, zoo,
Piecewise, Mul, Pow, nsimplify, ratsimp, trigsimp, radsimp, powsimp,
simplify, together, collect, factorial, apart, combsimp, factor, refine,
cancel, Tuple, default_sort_key, DiracDelta, gamma, Dummy, Sum, E,
exp_polar, Lambda)
from sympy.core.function import AppliedUndef
from sympy.abc import a, b, c, d, e, n, t, u, x, y, z
from sympy.physics.secondquant import FockState
from sympy.physics.units import meter
from sympy.utilities.pytest import raises, XFAIL
class DummyNumber(object):
"""
Minimal implementation of a number that works with SymPy.
If one has a Number class (e.g. Sage Integer, or some other custom class)
that one wants to work well with SymPy, one has to implement at least the
methods of this class DummyNumber, resp. its subclasses I5 and F1_1.
Basically, one just needs to implement either __int__() or __float__() and
then one needs to make sure that the class works with Python integers and
with itself.
"""
def __radd__(self, a):
if isinstance(a, (int, float)):
return a + self.number
return NotImplemented
def __truediv__(a, b):
return a.__div__(b)
def __rtruediv__(a, b):
return a.__rdiv__(b)
def __add__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number + a
return NotImplemented
def __rsub__(self, a):
if isinstance(a, (int, float)):
return a - self.number
return NotImplemented
def __sub__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number - a
return NotImplemented
def __rmul__(self, a):
if isinstance(a, (int, float)):
return a * self.number
return NotImplemented
def __mul__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number * a
return NotImplemented
def __rdiv__(self, a):
if isinstance(a, (int, float)):
return a / self.number
return NotImplemented
def __div__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number / a
return NotImplemented
def __rpow__(self, a):
if isinstance(a, (int, float)):
return a ** self.number
return NotImplemented
def __pow__(self, a):
if isinstance(a, (int, float, DummyNumber)):
return self.number ** a
return NotImplemented
def __pos__(self):
return self.number
def __neg__(self):
return - self.number
class I5(DummyNumber):
number = 5
def __int__(self):
return self.number
class F1_1(DummyNumber):
number = 1.1
def __float__(self):
return self.number
i5 = I5()
f1_1 = F1_1()
# basic sympy objects
basic_objs = [
Rational(2),
Float("1.3"),
x,
y,
pow(x,y)*y,
]
# all supported objects
all_objs = basic_objs + [
5,
5.5,
i5,
f1_1
]
def dotest(s):
for x in all_objs:
for y in all_objs:
s(x,y)
return True
def test_basic():
def j(a,b):
x = a
x = +a
x = -a
x = a+b
x = a-b
x = a*b
x = a/b
x = a**b
assert dotest(j)
def test_ibasic():
def s(a,b):
x = a
x += b
x = a
x -= b
x = a
x *= b
x = a
x /= b
assert dotest(s)
def test_relational():
assert (pi < 3) == False
assert (pi <= 3) == False
assert (pi > 3) == True
assert (pi >= 3) == True
assert (-pi < 3) == True
assert (-pi <= 3) == True
assert (-pi > 3) == False
assert (-pi >= 3) == False
assert (x - 2 < x - 3) == False
def test_relational_noncommutative():
from sympy import Lt, Gt, Le, Ge
A, B = symbols('A,B', commutative=False)
assert (A < B) == Lt(A, B)
assert (A <= B) == Le(A, B)
assert (A > B) == Gt(A, B)
assert (A >= B) == Ge(A, B)
def test_basic_nostr():
for obj in basic_objs:
raises(TypeError, lambda: obj + '1')
raises(TypeError, lambda: obj - '1')
if obj == 2:
if hasattr(int, '__index__'): # Python 2.5+ (PEP 357)
assert obj * '1' == '11'
else:
raises(TypeError, lambda: obj * '1')
raises(TypeError, lambda: obj / '1')
raises(TypeError, lambda: obj ** '1')
def test_leadterm():
assert (3+2*x**(log(3)/log(2)-1)).leadterm(x) == (3,0)
assert (1/x**2+1+x+x**2).leadterm(x)[1] == -2
assert (1/x+1+x+x**2).leadterm(x)[1] == -1
assert (x**2+1/x).leadterm(x)[1] == -1
assert (1+x**2).leadterm(x)[1] == 0
assert (x+1).leadterm(x)[1] == 0
assert (x+x**2).leadterm(x)[1] == 1
assert (x**2).leadterm(x)[1] == 2
def test_as_leading_term():
assert (3+2*x**(log(3)/log(2)-1)).as_leading_term(x) == 3
assert (1/x**2+1+x+x**2).as_leading_term(x) == 1/x**2
assert (1/x+1+x+x**2).as_leading_term(x) == 1/x
assert (x**2+1/x).as_leading_term(x) == 1/x
assert (1+x**2).as_leading_term(x) == 1
assert (x+1).as_leading_term(x) == 1
assert (x+x**2).as_leading_term(x) == x
assert (x**2).as_leading_term(x) == x**2
assert (x + oo).as_leading_term(x) == oo
def test_leadterm2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).leadterm(x) == \
(sin(1 + sin(1)), 0)
def test_leadterm3():
assert (y+z+x).leadterm(x) == (y+z, 0)
def test_as_leading_term2():
assert (x*cos(1)*cos(1 + sin(1)) + sin(1 + sin(1))).as_leading_term(x) == \
sin(1 + sin(1))
def test_as_leading_term3():
assert (2+pi+x).as_leading_term(x) == 2 + pi
assert (2*x+pi*x+x**2).as_leading_term(x) == (2+pi)*x
def test_as_leading_term_stub():
class foo(Function):
pass
assert foo(1/x).as_leading_term(x) == foo(1/x)
assert foo(1).as_leading_term(x) == foo(1)
raises(NotImplementedError, lambda: foo(x).as_leading_term(x))
def test_atoms():
assert sorted(list(x.atoms())) == [x]
assert sorted(list((1+x).atoms())) == sorted([1, x])
assert sorted(list((1+2*cos(x)).atoms(Symbol))) == [x]
assert sorted(list((1+2*cos(x)).atoms(Symbol,Number))) == sorted([1, 2, x])
assert sorted(list((2*(x**(y**x))).atoms())) == sorted([2, x, y])
assert sorted(list(Rational(1,2).atoms())) == [S.Half]
assert sorted(list(Rational(1,2).atoms(Symbol))) == []
assert sorted(list(sin(oo).atoms(oo))) == [oo]
assert sorted(list(Poly(0, x).atoms())) == [S.Zero]
assert sorted(list(Poly(1, x).atoms())) == [S.One]
assert sorted(list(Poly(x, x).atoms())) == [x]
assert sorted(list(Poly(x, x, y).atoms())) == [x]
assert sorted(list(Poly(x + y, x, y).atoms())) == sorted([x, y])
assert sorted(list(Poly(x + y, x, y, z).atoms())) == sorted([x, y])
assert sorted(list(Poly(x + y*t, x, y, z).atoms())) == sorted([t, x, y])
assert list((I*pi).atoms(NumberSymbol)) == [pi]
assert sorted((I*pi).atoms(NumberSymbol, I)) == \
sorted((I*pi).atoms(I,NumberSymbol)) == [pi, I]
assert exp(exp(x)).atoms(exp) == set([exp(exp(x)), exp(x)])
assert (1 + x*(2 + y)+exp(3 + z)).atoms(Add) == set(
[1 + x*(2 + y)+exp(3 + z),
2 + y,
3 + z])
# issue 3033
f = Function('f')
e = (f(x) + sin(x) + 2)
assert e.atoms(AppliedUndef) == \
set([f(x)])
assert e.atoms(AppliedUndef, Function) == \
set([f(x), sin(x)])
assert e.atoms(Function) == \
set([f(x), sin(x)])
assert e.atoms(AppliedUndef, Number) == \
set([f(x), S(2)])
assert e.atoms(Function, Number) == \
set([S(2), sin(x), f(x)])
def test_is_polynomial():
k = Symbol('k', nonnegative=True, integer=True)
assert Rational(2).is_polynomial(x, y, z) == True
assert (S.Pi).is_polynomial(x, y, z) == True
assert x.is_polynomial(x) == True
assert x.is_polynomial(y) == True
assert (x**2).is_polynomial(x) == True
assert (x**2).is_polynomial(y) == True
assert (x**(-2)).is_polynomial(x) == False
assert (x**(-2)).is_polynomial(y) == True
assert (2**x).is_polynomial(x) == False
assert (2**x).is_polynomial(y) == True
assert (x**k).is_polynomial(x) == False
assert (x**k).is_polynomial(k) == False
assert (x**x).is_polynomial(x) == False
assert (k**k).is_polynomial(k) == False
assert (k**x).is_polynomial(k) == False
assert (x**(-k)).is_polynomial(x) == False
assert ((2*x)**k).is_polynomial(x) == False
assert (x**2 + 3*x - 8).is_polynomial(x) == True
assert (x**2 + 3*x - 8).is_polynomial(y) == True
assert (x**2 + 3*x - 8).is_polynomial() == True
assert sqrt(x).is_polynomial(x) == False
assert (sqrt(x)**3).is_polynomial(x) == False
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(x) == True
assert (x**2 + 3*x*sqrt(y) - 8).is_polynomial(y) == False
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial() == True
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial() == False
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(2)).is_polynomial(x, y) == True
assert ((x**2)*(y**2) + x*(y**2) + y*x + exp(x)).is_polynomial(x, y) == False
def test_is_rational_function():
assert Integer(1).is_rational_function() == True
assert Integer(1).is_rational_function(x) == True
assert Rational(17,54).is_rational_function() == True
assert Rational(17,54).is_rational_function(x) == True
assert (12/x).is_rational_function() == True
assert (12/x).is_rational_function(x) == True
assert (x/y).is_rational_function() == True
assert (x/y).is_rational_function(x) == True
assert (x/y).is_rational_function(x, y) == True
assert (x**2+1/x/y).is_rational_function() == True
assert (x**2+1/x/y).is_rational_function(x) == True
assert (x**2+1/x/y).is_rational_function(x, y) == True
assert (sin(y)/x).is_rational_function() == False
assert (sin(y)/x).is_rational_function(y) == False
assert (sin(y)/x).is_rational_function(x) == True
assert (sin(y)/x).is_rational_function(x, y) == False
def test_SAGE1():
#see http://code.google.com/p/sympy/issues/detail?id=247
class MyInt:
def _sympy_(self):
return Integer(5)
m = MyInt()
e = Rational(2)*m
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE2():
class MyInt(object):
def __int__(self):
return 5
assert sympify(MyInt()) == 5
e = Rational(2)*MyInt()
assert e == 10
raises(TypeError, lambda: Rational(2)*MyInt)
def test_SAGE3():
class MySymbol:
def __rmul__(self, other):
return ('mys', other, self)
o = MySymbol()
e = x*o
assert e == ('mys', x, o)
def test_len():
e = x*y
assert len(e.args) == 2
e = x+y+z
assert len(e.args) == 3
def test_doit():
a = Integral(x**2, x)
assert isinstance(a.doit(), Integral) == False
assert isinstance(a.doit(integrals=True), Integral) == False
assert isinstance(a.doit(integrals=False), Integral) == True
assert (2*Integral(x, x)).doit() == x**2
def test_attribute_error():
raises(AttributeError, lambda: x.cos())
raises(AttributeError, lambda: x.sin())
raises(AttributeError, lambda: x.exp())
def test_args():
assert (x*y).args in ((x, y), (y, x))
assert (x+y).args in ((x, y), (y, x))
assert (x*y+1).args in ((x*y, 1), (1, x*y))
assert sin(x*y).args == (x*y,)
assert sin(x*y).args[0] == x*y
assert (x**y).args == (x,y)
assert (x**y).args[0] == x
assert (x**y).args[1] == y
def test_iter_basic_args():
assert list(sin(x*y).iter_basic_args()) == [x*y]
assert list((x**y).iter_basic_args()) == [x, y]
def test_noncommutative_expand_issue658():
A, B, C = symbols('A,B,C', commutative=False)
assert A*B - B*A != 0
assert (A*(A+B)*B).expand() == A**2*B + A*B**2
assert (A*(A+B+C)*B).expand() == A**2*B + A*B**2 + A*C*B
def test_as_numer_denom():
a, b, c = symbols('a, b, c')
assert nan.as_numer_denom() == (nan, 1)
assert oo.as_numer_denom() == (oo, 1)
assert (-oo).as_numer_denom() == (-oo, 1)
assert zoo.as_numer_denom() == (zoo, 1)
assert (-zoo).as_numer_denom() == (zoo, 1)
assert x.as_numer_denom() == (x, 1)
assert (1/x).as_numer_denom() == (1, x)
assert (x/y).as_numer_denom() == (x, y)
assert (x/2).as_numer_denom() == (x, 2)
assert (x*y/z).as_numer_denom() == (x*y, z)
assert (x/(y*z)).as_numer_denom() == (x, y*z)
assert Rational(1, 2).as_numer_denom() == (1, 2)
assert (1/y**2).as_numer_denom() == (1, y**2)
assert (x/y**2).as_numer_denom() == (x, y**2)
assert ((x**2+1)/y).as_numer_denom() == (x**2+1, y)
assert (x*(y+1)/y**7).as_numer_denom() == (x*(y+1), y**7)
assert (x**-2).as_numer_denom() == (1, x**2)
assert (a/x + b/2/x + c/3/x).as_numer_denom() == \
(6*a + 3*b + 2*c, 6*x)
assert (a/x + b/2/x + c/3/y).as_numer_denom() == \
(2*c*x + y*(6*a + 3*b), 6*x*y)
assert (a/x + b/2/x + c/.5/x).as_numer_denom() == \
(2*a + b + 4.0*c, 2*x)
# this should take no more than a few seconds
assert int(log(Add(*[Dummy()/i/x for i in xrange(1, 705)]
).as_numer_denom()[1]/x).n(4)) == 705
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).as_numer_denom() == \
(x + i, 3)
assert (S.Infinity + x/3 + y/4).as_numer_denom() == \
(4*x + 3*y + S.Infinity, 12)
assert (oo*x + zoo*y).as_numer_denom() == \
(zoo*y + oo*x, 1)
A, B, C = symbols('A,B,C', commutative=False)
assert (A*B*C**-1).as_numer_denom() == (A*B*C**-1, 1)
assert (A*B*C**-1/x).as_numer_denom() == (A*B*C**-1, x)
assert (C**-1*A*B).as_numer_denom() == (C**-1*A*B, 1)
assert (C**-1*A*B/x).as_numer_denom() == (C**-1*A*B, x)
assert ((A*B*C)**-1).as_numer_denom() == ((A*B*C)**-1, 1)
assert ((A*B*C)**-1/x).as_numer_denom() == ((A*B*C)**-1, x)
def test_as_independent():
assert (2*x*sin(x)+y+x).as_independent(x) == (y, x + 2*x*sin(x))
assert (2*x*sin(x)+y+x).as_independent(y) == (x + 2*x*sin(x), y)
assert (2*x*sin(x)+y+x).as_independent(x, y) == (0, y + x + 2*x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(x) == (cos(y), x*sin(x))
assert (x*sin(x)*cos(y)).as_independent(y) == (x*sin(x), cos(y))
assert (x*sin(x)*cos(y)).as_independent(x, y) == (1, x*sin(x)*cos(y))
assert (sin(x)).as_independent(x) == (1, sin(x))
assert (sin(x)).as_independent(y) == (sin(x), 1)
assert (2*sin(x)).as_independent(x) == (2, sin(x))
assert (2*sin(x)).as_independent(y) == (2*sin(x), 1)
# issue 1804 = 1766b
n1, n2, n3 = symbols('n1 n2 n3', commutative=False)
assert (n1 + n1*n2).as_independent(n2) == (n1, n1*n2)
assert (n2*n1 + n1*n2).as_independent(n2) == (0, n1*n2 + n2*n1)
assert (n1*n2*n1).as_independent(n2) == (n1, n2*n1)
assert (n1*n2*n1).as_independent(n1) == (1, n1*n2*n1)
assert (3*x).as_independent(x, as_Add=True) == (0, 3*x)
assert (3*x).as_independent(x, as_Add=False) == (3, x)
assert (3+x).as_independent(x, as_Add=True) == (3, x)
assert (3+x).as_independent(x, as_Add=False) == (1, 3 + x)
# issue 2380
assert (3*x).as_independent(Symbol) == (3, x)
# issue 2549
assert (n1*x*y).as_independent(x) == (n1*y, x)
assert ((x + n1)*(x - y)).as_independent(x) == (1, (x + n1)*(x - y))
assert ((x + n1)*(x - y)).as_independent(y) == (x + n1, x - y)
assert (DiracDelta(x - n1)*DiracDelta(x - y)).as_independent(x) == (1, DiracDelta(x - n1)*DiracDelta(x - y))
assert (x*y*n1*n2*n3).as_independent(n2) == (x*y*n1, n2*n3)
assert (x*y*n1*n2*n3).as_independent(n1) == (x*y, n1*n2*n3)
assert (x*y*n1*n2*n3).as_independent(n3) == (x*y*n1*n2, n3)
assert (DiracDelta(x - n1)*DiracDelta(y - n1)*DiracDelta(x - n2)).as_independent(y) == \
(DiracDelta(x - n1), DiracDelta(y - n1)*DiracDelta(x - n2))
# issue 2685
assert (x + Integral(x, (x, 1, 2))).as_independent(x, strict=True) == \
(Integral(x, (x, 1, 2)), x)
def test_call():
# See the long history of this in issues 1927 and 2006.
# No effect as there are no callables
assert sin(x)(1) == sin(x)
assert (1+sin(x))(1) == 1+sin(x)
# Effect in the pressence of callables
l = Lambda(x, 2*x)
assert (l+x)(y) == 2*y+x
assert (x**l)(2) == x**4
# TODO UndefinedFunction does not subclass Expr
#f = Function('f')
#assert (2*f)(x) == 2*f(x)
def test_replace():
f = log(sin(x)) + tan(sin(x**2))
assert f.replace(sin, cos) == log(cos(x)) + tan(cos(x**2))
assert f.replace(sin, lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
a = Wild('a')
assert f.replace(sin(a), cos(a)) == log(cos(x)) + tan(cos(x**2))
assert f.replace(sin(a), lambda a: sin(2*a)) == log(sin(2*x)) + tan(sin(2*x**2))
g = 2*sin(x**3)
assert g.replace(lambda expr: expr.is_Number, lambda expr: expr**2) == 4*sin(x**9)
assert cos(x).replace(cos, sin, map=True) == (sin(x), {cos(x): sin(x)})
assert sin(x).replace(cos, sin) == sin(x)
assert (y*sin(x)).replace(sin, lambda expr: sin(expr)/y) == sin(x)
def test_find():
expr = (x + y + 2 + sin(3*x))
assert expr.find(lambda u: u.is_Integer) == set([S(2), S(3)])
assert expr.find(lambda u: u.is_Symbol) == set([x, y])
assert expr.find(lambda u: u.is_Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(lambda u: u.is_Symbol, group=True) == {x: 2, y: 1}
assert expr.find(Integer) == set([S(2), S(3)])
assert expr.find(Symbol) == set([x, y])
assert expr.find(Integer, group=True) == {S(2): 1, S(3): 1}
assert expr.find(Symbol, group=True) == {x: 2, y: 1}
a = Wild('a')
expr = sin(sin(x)) + sin(x) + cos(x) + x
assert expr.find(lambda u: type(u) is sin) == set([sin(x), sin(sin(x))])
assert expr.find(lambda u: type(u) is sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin(a)) == set([sin(x), sin(sin(x))])
assert expr.find(sin(a), group=True) == {sin(x): 2, sin(sin(x)): 1}
assert expr.find(sin) == set([sin(x), sin(sin(x))])
assert expr.find(sin, group=True) == {sin(x): 2, sin(sin(x)): 1}
def test_count():
expr = (x + y + 2 + sin(3*x))
assert expr.count(lambda u: u.is_Integer) == 2
assert expr.count(lambda u: u.is_Symbol) == 3
assert expr.count(Integer) == 2
assert expr.count(Symbol) == 3
assert expr.count(2) == 1
a = Wild('a')
assert expr.count(sin) == 1
assert expr.count(sin(a)) == 1
assert expr.count(lambda u: type(u) is sin) == 1
def test_has_basics():
f = Function('f')
g = Function('g')
p = Wild('p')
assert sin(x).has(x)
assert sin(x).has(sin)
assert not sin(x).has(y)
assert not sin(x).has(cos)
assert f(x).has(x)
assert f(x).has(f)
assert not f(x).has(y)
assert not f(x).has(g)
assert f(x).diff(x).has(x)
assert f(x).diff(x).has(f)
assert f(x).diff(x).has(Derivative)
assert not f(x).diff(x).has(y)
assert not f(x).diff(x).has(g)
assert not f(x).diff(x).has(sin)
assert (x**2).has(Symbol)
assert not (x**2).has(Wild)
assert (2*p).has(Wild)
assert not x.has()
def test_has_multiple():
f = x**2*y + sin(2**t + log(z))
assert f.has(x)
assert f.has(y)
assert f.has(z)
assert f.has(t)
assert not f.has(u)
assert f.has(x, y, z, t)
assert f.has(x, y, z, t, u)
i = Integer(4400)
assert not i.has(x)
assert (i*x**i).has(x)
assert not (i*y**i).has(x)
assert (i*y**i).has(x, y)
assert not (i*y**i).has(x, z)
def test_has_piecewise():
f = (x*y + 3/y)**(3 + 2)
g = Function('g')
h = Function('h')
p = Piecewise((g(x), x < -1), (1, x <= 1), (f, True))
assert p.has(x)
assert p.has(y)
assert not p.has(z)
assert p.has(1)
assert p.has(3)
assert not p.has(4)
assert p.has(f)
assert p.has(g)
assert not p.has(h)
def test_has_iterative():
A, B, C = symbols('A,B,C', commutative=False)
f = x*gamma(x)*sin(x)*exp(x*y)*A*B*C*cos(x*A*B)
assert f.has(x)
assert f.has(x*y)
assert f.has(x*sin(x))
assert not f.has(x*sin(y))
assert f.has(x*A)
assert f.has(x*A*B)
assert not f.has(x*A*C)
assert f.has(x*A*B*C)
assert not f.has(x*A*C*B)
assert f.has(x*sin(x)*A*B*C)
assert not f.has(x*sin(x)*A*C*B)
assert not f.has(x*sin(y)*A*B*C)
assert f.has(x*gamma(x))
assert not f.has(x + sin(x))
assert (x & y & z).has(x & z)
def test_has_integrals():
f = Integral(x**2 + sin(x*y*z), (x, 0, x + y + z))
assert f.has(x + y)
assert f.has(x + z)
assert f.has(y + z)
assert f.has(x*y)
assert f.has(x*z)
assert f.has(y*z)
assert not f.has(2*x + y)
assert not f.has(2*x*y)
def test_has_tuple():
f = Function('f')
g = Function('g')
h = Function('h')
assert Tuple(x, y).has(x)
assert not Tuple(x, y).has(z)
assert Tuple(f(x), g(x)).has(x)
assert not Tuple(f(x), g(x)).has(y)
assert Tuple(f(x), g(x)).has(f)
assert Tuple(f(x), g(x)).has(f(x))
assert not Tuple(f, g).has(x)
assert Tuple(f, g).has(f)
assert not Tuple(f, g).has(h)
assert Tuple(True).has(True) is True # .has(1) will also be True
def test_has_units():
from sympy.physics.units import m, s
assert (x*m/s).has(x)
assert (x*m/s).has(y, z) is False
def test_has_polys():
poly = Poly(x**2 + x*y*sin(z), x, y, t)
assert poly.has(x)
assert poly.has(x, y, z)
assert poly.has(x, y, z, t)
def test_has_physics():
assert FockState((x, y)).has(x)
def test_as_poly_as_expr():
f = x**2 + 2*x*y
assert f.as_poly().as_expr() == f
assert f.as_poly(x, y).as_expr() == f
assert (f + sin(x)).as_poly(x, y) is None
p = Poly(f, x, y)
assert p.as_poly() == p
def test_nonzero():
assert bool(S.Zero) == False
assert bool(S.One) == True
assert bool(x) == True
assert bool(x+y) == True
assert bool(x-x) == False
assert bool(x*y) == True
assert bool(x*1) == True
assert bool(x*0) == False
def test_is_number():
assert Float(3.14).is_number == True
assert Integer(737).is_number == True
assert Rational(3, 2).is_number == True
assert Rational(8).is_number == True
assert x.is_number == False
assert (2*x).is_number == False
assert (x + y).is_number == False
assert log(2).is_number == True
assert log(x).is_number == False
assert (2 + log(2)).is_number == True
assert (8+log(2)).is_number == True
assert (2 + log(x)).is_number == False
assert (8+log(2)+x).is_number == False
assert (1+x**2/x-x).is_number == True
assert Tuple(Integer(1)).is_number == False
assert Add(2, x).is_number == False
assert Mul(3, 4).is_number == True
assert Pow(log(2), 2).is_number == True
assert oo.is_number == True
g = WildFunction('g')
assert g.is_number == False
assert (2*g).is_number == False
assert (x**2).subs(x, 3).is_number == True
# test extensibility of .is_number
# on subinstances of Basic
class A(Basic):
pass
a = A()
assert a.is_number == False
def test_as_coeff_add():
assert S(2).as_coeff_add() == (2, ())
assert S(3.0).as_coeff_add() == (0, (S(3.0),))
assert S(-3.0).as_coeff_add() == (0, (S(-3.0),))
assert x .as_coeff_add() == ( 0, (x,))
assert (-1+x).as_coeff_add() == (-1, (x,))
assert ( 2+x).as_coeff_add() == ( 2, (x,))
assert ( 1+x).as_coeff_add() == ( 1, (x,))
assert (x + y).as_coeff_add(y) == (x, (y,))
assert (3*x).as_coeff_add(y) == (3*x, ())
# don't do expansion
e = (x + y)**2
assert e.as_coeff_add(y) == (0, (e,))
def test_as_coeff_mul():
assert S(2).as_coeff_mul() == (2, ())
assert S(3.0).as_coeff_mul() == (1, (S(3.0),))
assert S(-3.0).as_coeff_mul() == (-1, (S(3.0),))
assert x .as_coeff_mul() == ( 1, (x,))
assert (-x).as_coeff_mul() == (-1, (x,))
assert (2*x).as_coeff_mul() == (2, (x,))
assert (x*y).as_coeff_mul(y) == (x, (y,))
assert (3 + x).as_coeff_mul(y) == (3 + x, ())
# don't do expansion
e = exp(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
e = 2**(x + y)
assert e.as_coeff_mul(y) == (1, (e,))
def test_as_coeff_exponent():
assert (3*x**4).as_coeff_exponent(x) == (3, 4)
assert (2*x**3).as_coeff_exponent(x) == (2, 3)
assert (4*x**2).as_coeff_exponent(x) == (4, 2)
assert (6*x**1).as_coeff_exponent(x) == (6, 1)
assert (3*x**0).as_coeff_exponent(x) == (3, 0)
assert (2*x**0).as_coeff_exponent(x) == (2, 0)
assert (1*x**0).as_coeff_exponent(x) == (1, 0)
assert (0*x**0).as_coeff_exponent(x) == (0, 0)
assert (-1*x**0).as_coeff_exponent(x) == (-1, 0)
assert (-2*x**0).as_coeff_exponent(x) == (-2, 0)
assert (2*x**3+pi*x**3).as_coeff_exponent(x) == (2+pi, 3)
assert (x*log(2)/(2*x + pi*x)).as_coeff_exponent(x) == \
(log(2)/(2+pi), 0)
# 1685
D = Derivative
f = Function('f')
fx = D(f(x), x)
assert fx.as_coeff_exponent(f(x)) == (fx ,0)
def test_extractions():
assert ((x*y)**3).extract_multiplicatively(x**2 * y) == x*y**2
assert ((x*y)**3).extract_multiplicatively(x**4 * y) == None
assert (2*x).extract_multiplicatively(2) == x
assert (2*x).extract_multiplicatively(3) == None
assert (2*x).extract_multiplicatively(-1) == None
assert (Rational(1, 2)*x).extract_multiplicatively(3) == x/6
assert (sqrt(x)).extract_multiplicatively(x) == None
assert (sqrt(x)).extract_multiplicatively(1/x) == None
assert ((x*y)**3).extract_additively(1) == None
assert (x + 1).extract_additively(x) == 1
assert (x + 1).extract_additively(2*x) == None
assert (x + 1).extract_additively(-x) == None
assert (-x + 1).extract_additively(2*x) == None
assert (2*x + 3).extract_additively(x) == x + 3
assert (2*x + 3).extract_additively(2) == 2*x + 1
assert (2*x + 3).extract_additively(3) == 2*x
assert (2*x + 3).extract_additively(-2) == None
assert (2*x + 3).extract_additively(3*x) == None
assert (2*x + 3).extract_additively(2*x) == 3
assert x.extract_additively(0) == x
assert S(2).extract_additively(x) is None
assert S(2.).extract_additively(2) == S.Zero
assert S(2*x + 3).extract_additively(x + 1) == x + 2
assert S(2*x + 3).extract_additively(y + 1) is None
assert S(2*x - 3).extract_additively(x + 1) is None
assert S(2*x - 3).extract_additively(y + z) is None
assert ((a + 1)*x*4 + y).extract_additively(x).expand() == \
4*a*x + 3*x + y
assert ((a + 1)*x*4 + 3*y).extract_additively(x + 2*y).expand() == \
4*a*x + 3*x + y
assert (y*(x + 1)).extract_additively(x + 1) is None
assert ((y + 1)*(x + 1) + 3).extract_additively(x + 1) == \
y*(x + 1) + 3
assert ((x + y)*(x + 1) + x + y + 3).extract_additively(x + y) == \
x*(x + y) + 3
assert (x + y + 2*((x + y)*(x + 1)) + 3).extract_additively((x + y)*(x + 1)) == \
x + y + (x + 1)*(x + y) + 3
assert ((y + 1)*(x + 2*y + 1) + 3).extract_additively(y + 1) == \
(x + 2*y)*(y + 1) + 3
n = Symbol("n", integer=True)
assert (Integer(-3)).could_extract_minus_sign() == True
assert (-n*x+x).could_extract_minus_sign() != (n*x-x).could_extract_minus_sign()
assert (x-y).could_extract_minus_sign() != (-x+y).could_extract_minus_sign()
assert (1-x-y).could_extract_minus_sign() == True
assert (1-x+y).could_extract_minus_sign() == False
assert ((-x-x*y)/y).could_extract_minus_sign() == True
assert (-(x+x*y)/y).could_extract_minus_sign() == True
assert ((x+x*y)/(-y)).could_extract_minus_sign() == True
assert ((x+x*y)/y).could_extract_minus_sign() == False
assert (x*(-x-x**3)).could_extract_minus_sign() == True # used to give inf recurs
assert ((-x-y)/(x+y)).could_extract_minus_sign() == True # is_Mul odd case
# The results of each of these will vary on different machines, e.g.
# the first one might be False and the other (then) is true or vice versa,
# so both are included.
assert ((-x-y)/(x-y)).could_extract_minus_sign() == False or\
((-x-y)/(y-x)).could_extract_minus_sign() == False # is_Mul even case
assert ( x - y).could_extract_minus_sign() == False
assert (-x + y).could_extract_minus_sign() == True
def test_coeff():
assert (x+1).coeff(x+1) == 1
assert (3*x).coeff(0) == 0
assert (z*(1+x)*x**2).coeff(1+x) == z*x**2
assert (1+2*x*x**(1+x)).coeff(x*x**(1+x)) == 2
assert (1+2*x**(y+z)).coeff(x**(y+z)) == 2
assert (3+2*x+4*x**2).coeff(1) == 0
assert (3+2*x+4*x**2).coeff(-1) == 0
assert (3+2*x+4*x**2).coeff(x) == 2
assert (3+2*x+4*x**2).coeff(x**2) == 4
assert (3+2*x+4*x**2).coeff(x**3) == 0
assert (-x/8 + x*y).coeff(x) == -S(1)/8 + y
assert (-x/8 + x*y).coeff(-x) == S(1)/8
assert (4*x).coeff(2*x) == 0
assert (2*x).coeff(2*x) == 1
assert (-oo*x).coeff(x*oo) == -1
n1, n2 = symbols('n1 n2', commutative=False)
assert (n1*n2).coeff(n1) == 1
assert (n1*n2).coeff(n2) == n1
assert (n1*n2 + x*n1).coeff(n1) == 1 # 1*n1*(n2+x)
assert (n2*n1 + x*n1).coeff(n1) == n2 + x
assert (n2*n1 + x*n1**2).coeff(n1) == n2
assert (n1**x).coeff(n1) == 0
assert (n1*n2 + n2*n1).coeff(n1) == 0
assert (2*(n1+n2)*n2).coeff(n1+n2, right=1) == n2
assert (2*(n1+n2)*n2).coeff(n1+n2, right=0) == 2
f = Function('f')
assert (2*f(x) + 3*f(x).diff(x)).coeff(f(x)) == 2
expr = z*(x+y)**2
expr2 = z*(x+y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x+y)**2
assert expr.coeff(x+y) == 0
assert expr2.coeff(z) == (x+y)**2 + (2*x + 2*y)**2
assert (x + y + 3*z).coeff(1) == x + y
assert (-x + 2*y).coeff(-1) == x
assert (x - 2*y).coeff(-1) == 2*y
assert (3 + 2*x + 4*x**2).coeff(1) == 0
assert (-x - 2*y).coeff(2) == -y
assert (x + sqrt(2)*x).coeff(sqrt(2)) == x
assert (3 + 2*x + 4*x**2).coeff(x) == 2
assert (3 + 2*x + 4*x**2).coeff(x**2) == 4
assert (3 + 2*x + 4*x**2).coeff(x**3) == 0
assert (z*(x + y)**2).coeff((x + y)**2) == z
assert (z*(x + y)**2).coeff(x + y) == 0
assert (2 + 2*x + (x + 1)*y).coeff(x + 1) == y
assert (x + 2*y + 3).coeff(1) == x
assert (x + 2*y + 3).coeff(x, 0) == 2*y + 3
assert (x**2 + 2*y + 3*x).coeff(x**2, 0) == 2*y + 3*x
assert x.coeff(0, 0) == 0
assert x.coeff(x, 0) == 0
n, m, o, l = symbols('n m o l', commutative=False)
assert n.coeff(n) == 1
assert y.coeff(n) == 0
assert (3*n).coeff(n) == 3
assert (2 + n).coeff(x*m) == 0
assert (2*x*n*m).coeff(x) == 2*n*m
assert (2 + n).coeff(x*m*n + y) == 0
assert (2*x*n*m).coeff(3*n) == 0
assert (n*m + m*n*m).coeff(n) == 1 + m
assert (n*m + m*n*m).coeff(n, right=True) == m # = (1 + m)*n*m
assert (n*m + m*n).coeff(n) == 0
assert (n*m + o*m*n).coeff(m*n) == o
assert (n*m + o*m*n).coeff(m*n, right=1) == 1
assert (n*m + n*m*n).coeff(n*m, right=1) == 1 + n # = n*m*(n + 1)
def test_coeff2():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff((psi(r).diff(r))) == 2/r
def test_coeff2_0():
r, kappa = symbols('r, kappa')
psi = Function("psi")
g = 1/r**2 * (2*r*psi(r).diff(r, 1) + r**2 * psi(r).diff(r, 2))
g = g.expand()
assert g.coeff(psi(r).diff(r, 2)) == 1
def test_coeff_expand():
expr = z*(x+y)**2
expr2 = z*(x+y)**2 + z*(2*x + 2*y)**2
assert expr.coeff(z) == (x+y)**2
assert expr2.coeff(z) == (x+y)**2 + (2*x + 2*y)**2
def test_integrate():
assert x.integrate(x) == x**2/2
assert x.integrate((x, 0, 1)) == S(1)/2
def test_as_base_exp():
assert x.as_base_exp() == (x, S.One)
assert (x*y*z).as_base_exp() == (x*y*z, S.One)
assert (x+y+z).as_base_exp() == (x+y+z, S.One)
assert ((x+y)**z).as_base_exp() == (x+y, z)
def test_issue1864():
assert hasattr(Mul(x, y), "is_commutative")
assert hasattr(Mul(x, y, evaluate=False), "is_commutative")
assert hasattr(Pow(x, y), "is_commutative")
assert hasattr(Pow(x, y, evaluate=False), "is_commutative")
expr = Mul(Pow(2, 2, evaluate=False), 3, evaluate=False) + 1
assert hasattr(expr, "is_commutative")
def test_action_verbs():
assert nsimplify((1/(exp(3*pi*x/5)+1))) == (1/(exp(3*pi*x/5)+1)).nsimplify()
assert ratsimp(1/x + 1/y) == (1/x + 1/y).ratsimp()
assert trigsimp(log(x), deep=True) == (log(x)).trigsimp(deep = True)
assert radsimp(1/(2+sqrt(2))) == (1/(2+sqrt(2))).radsimp()
assert powsimp(x**y*x**z*y**z, combine='all') == (x**y*x**z*y**z).powsimp(combine='all')
assert simplify(x**y*x**z*y**z) == (x**y*x**z*y**z).simplify()
assert together(1/x + 1/y) == (1/x + 1/y).together()
# Not tested because it's deprecated
#assert separate((x*(y*z)**3)**2) == ((x*(y*z)**3)**2).separate()
assert collect(a*x**2 + b*x**2 + a*x - b*x + c, x) == (a*x**2 + b*x**2 + a*x - b*x + c).collect(x)
assert apart(y/(y+2)/(y+1), y) == (y/(y+2)/(y+1)).apart(y)
assert combsimp(y/(x+2)/(x+1)) == (y/(x+2)/(x+1)).combsimp()
assert factor(x**2+5*x+6) == (x**2+5*x+6).factor()
assert refine(sqrt(x**2)) == sqrt(x**2).refine()
assert cancel((x**2+5*x+6)/(x+2)) == ((x**2+5*x+6)/(x+2)).cancel()
def test_as_powers_dict():
assert x.as_powers_dict() == {x: 1}
assert (x**y*z).as_powers_dict() == {x: y, z: 1}
assert Mul(2, 2, **dict(evaluate=False)).as_powers_dict() == {S(2): S(2)}
def test_as_coefficients_dict():
check = [S(1), x, y, x*y, 1]
assert [Add(3*x, 2*x, y, 3).as_coefficients_dict()[i] for i in check] == \
[3, 5, 1, 0, 0]
assert [(3*x*y).as_coefficients_dict()[i] for i in check] == \
[0, 0, 0, 3, 0]
assert (3.0*x*y).as_coefficients_dict()[3.0*x*y] == 1
def test_args_cnc():
A = symbols('A', commutative=False)
assert (x+A).args_cnc() == \
[[], [x + A]]
assert (x+a).args_cnc() == \
[[a + x], []]
assert (x*a).args_cnc() == \
[[a, x], []]
assert (x*y*A*(A+1)).args_cnc(cset=True) == \
[set([x, y]), [A, 1 + A]]
assert Mul(x, x, evaluate=False).args_cnc(cset=True, warn=False) == \
[set([x]), []]
assert Mul(x, x**2, evaluate=False).args_cnc(cset=True, warn=False) == \
[set([x, x**2]), []]
raises(ValueError, lambda: Mul(x, x, evaluate=False).args_cnc(cset=True))
assert Mul(x, y, x, evaluate=False).args_cnc() == \
[[x, y, x], []]
def test_new_rawargs():
n = Symbol('n', commutative=False)
a = x + n
assert a.is_commutative is False
assert a._new_rawargs(x).is_commutative
assert a._new_rawargs(x, y).is_commutative
assert a._new_rawargs(x, n).is_commutative is False
assert a._new_rawargs(x, y, n).is_commutative is False
m = x*n
assert m.is_commutative is False
assert m._new_rawargs(x).is_commutative
assert m._new_rawargs(n).is_commutative is False
assert m._new_rawargs(x, y).is_commutative
assert m._new_rawargs(x, n).is_commutative is False
assert m._new_rawargs(x, y, n).is_commutative is False
assert m._new_rawargs(x, n, reeval=False).is_commutative is False
assert m._new_rawargs(S.One) is S.One
def test_2127():
assert Add(evaluate=False) == 0
assert Mul(evaluate=False) == 1
assert Mul(x+y, evaluate=False).is_Add
def test_free_symbols():
# free_symbols should return the free symbols of an object
assert S(1).free_symbols == set()
assert (x).free_symbols == set([x])
assert Integral(x, (x, 1, y)).free_symbols == set([y])
assert (-Integral(x, (x, 1, y))).free_symbols == set([y])
assert meter.free_symbols == set()
assert (meter**x).free_symbols == set([x])
def test_issue2201():
x = Symbol('x', commutative=False)
assert x*sqrt(2)/sqrt(6) == x*sqrt(3)/3
def test_issue_2061():
assert sqrt(-1.0*x) == 1.0*sqrt(-x)
assert sqrt(1.0*x) == 1.0*sqrt(x)
def test_as_coeff_Mul():
assert Integer(3).as_coeff_Mul() == (Integer(3), Integer(1))
assert Rational(3, 4).as_coeff_Mul() == (Rational(3, 4), Integer(1))
assert Float(5.0).as_coeff_Mul() == (Float(5.0), Integer(1))
assert (Integer(3)*x).as_coeff_Mul() == (Integer(3), x)
assert (Rational(3, 4)*x).as_coeff_Mul() == (Rational(3, 4), x)
assert (Float(5.0)*x).as_coeff_Mul() == (Float(5.0), x)
assert (Integer(3)*x*y).as_coeff_Mul() == (Integer(3), x*y)
assert (Rational(3, 4)*x*y).as_coeff_Mul() == (Rational(3, 4), x*y)
assert (Float(5.0)*x*y).as_coeff_Mul() == (Float(5.0), x*y)
assert (x).as_coeff_Mul() == (S.One, x)
assert (x*y).as_coeff_Mul() == (S.One, x*y)
def test_as_coeff_Add():
assert Integer(3).as_coeff_Add() == (Integer(3), Integer(0))
assert Rational(3, 4).as_coeff_Add() == (Rational(3, 4), Integer(0))
assert Float(5.0).as_coeff_Add() == (Float(5.0), Integer(0))
assert (Integer(3) + x).as_coeff_Add() == (Integer(3), x)
assert (Rational(3, 4) + x).as_coeff_Add() == (Rational(3, 4), x)
assert (Float(5.0) + x).as_coeff_Add() == (Float(5.0), x)
assert (Integer(3) + x + y).as_coeff_Add() == (Integer(3), x + y)
assert (Rational(3, 4) + x + y).as_coeff_Add() == (Rational(3, 4), x + y)
assert (Float(5.0) + x + y).as_coeff_Add() == (Float(5.0), x + y)
assert (x).as_coeff_Add() == (S.Zero, x)
assert (x*y).as_coeff_Add() == (S.Zero, x*y)
def test_expr_sorting():
f, g = symbols('f,g', cls=Function)
exprs = [1/x**2, 1/x, sqrt(sqrt(x)), sqrt(x), x, sqrt(x)**3, x**2]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x, 2*x, 2*x**2, 2*x**3, x**n, 2*x**n, sin(x), sin(x)**n, sin(x**2), cos(x), cos(x**2), tan(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [x + 1, x**2 + x + 1, x**3 + x**2 + x + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [S(4), x - 3*I/2, x + 3*I/2, x - 4*I + 1, x + 4*I + 1]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [f(x), g(x), exp(x), sin(x), cos(x), factorial(x)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [Tuple(x, y), Tuple(x, z), Tuple(x, y, z)]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[3], [1, 2]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [[1, 2], [1, 2, 3]]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [{x: -y}, {x: y}]
assert sorted(exprs, key=default_sort_key) == exprs
exprs = [set([1]), set([1, 2])]
assert sorted(exprs, key=default_sort_key) == exprs
def test_as_ordered_factors():
f, g = symbols('f,g', cls=Function)
assert x.as_ordered_factors() == [x]
assert (2*x*x**n*sin(x)*cos(x)).as_ordered_factors() == [Integer(2), x, x**n, sin(x), cos(x)]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Mul(*args)
assert expr.as_ordered_factors() == args
A, B = symbols('A,B', commutative=False)
assert (A*B).as_ordered_factors() == [A, B]
assert (B*A).as_ordered_factors() == [B, A]
def test_as_ordered_terms():
f, g = symbols('f,g', cls=Function)
assert x.as_ordered_terms() == [x]
assert (sin(x)**2*cos(x) + sin(x)*cos(x)**2 + 1).as_ordered_terms() == [sin(x)**2*cos(x), sin(x)*cos(x)**2, 1]
args = [f(1), f(2), f(3), f(1, 2, 3), g(1), g(2), g(3), g(1, 2, 3)]
expr = Add(*args)
assert expr.as_ordered_terms() == args
assert (1 + 4*sqrt(3)*pi*x).as_ordered_terms() == [4*pi*x*sqrt(3), 1]
assert ( 2 + 3*I).as_ordered_terms() == [ 2, 3*I]
assert (-2 + 3*I).as_ordered_terms() == [-2, 3*I]
assert ( 2 - 3*I).as_ordered_terms() == [ 2, -3*I]
assert (-2 - 3*I).as_ordered_terms() == [-2, -3*I]
assert ( 4 + 3*I).as_ordered_terms() == [ 4, 3*I]
assert (-4 + 3*I).as_ordered_terms() == [-4, 3*I]
assert ( 4 - 3*I).as_ordered_terms() == [ 4, -3*I]
assert (-4 - 3*I).as_ordered_terms() == [-4, -3*I]
f = x**2*y**2 + x*y**4 + y + 2
assert f.as_ordered_terms(order="lex") == [x**2*y**2, x*y**4, y, 2]
assert f.as_ordered_terms(order="grlex") == [x*y**4, x**2*y**2, y, 2]
assert f.as_ordered_terms(order="rev-lex") == [2, y, x*y**4, x**2*y**2]
assert f.as_ordered_terms(order="rev-grlex") == [2, y, x**2*y**2, x*y**4]
def test_sort_key_atomic_expr():
from sympy.physics.units import m, s
assert sorted([-m, s], key=lambda arg: arg.sort_key()) == [-m, s]
def test_issue_1100():
# first subs and limit gives NaN
a = x/y
assert a._eval_interval(x, 0, oo)._eval_interval(y, oo, 0) is S.NaN
# second subs and limit gives NaN
assert a._eval_interval(x, 0, oo)._eval_interval(y, 0, oo) is S.NaN
# difference gives S.NaN
a = x - y
assert a._eval_interval(x, 1, oo)._eval_interval(y, oo, 1) is S.NaN
raises(ValueError, lambda: x._eval_interval(x, None, None))
def test_primitive():
assert (3*(x + 1)**2).primitive() == (3, (x + 1)**2)
assert (6*x + 2).primitive() == (2, 3*x + 1)
assert (x/2 + 3).primitive() == (S(1)/2, x + 6)
eq = (6*x + 2)*(x/2 + 3)
assert eq.primitive()[0] == 1
eq = (2 + 2*x)**2
assert eq.primitive()[0] == 1
assert (4.0*x).primitive() == (1, 4.0*x)
assert (4.0*x + y/2).primitive() == (S.Half, 8.0*x + y)
assert (-2*x).primitive() == (2, -x)
assert Add(5*z/7, 0.5*x, 3*y/2, evaluate=False).primitive() == \
(S(1)/14, 7.0*x + 21*y + 10*z)
for i in [S.Infinity, S.NegativeInfinity, S.ComplexInfinity]:
assert (i + x/3).primitive() == \
(S(1)/3, i + x)
assert (S.Infinity + 2*x/3 + 4*y/7).primitive() == \
(S(1)/21, 14*x + 12*y + oo)
assert S.Zero.primitive() == (S.One, S.Zero)
def test_issue_2744():
a = 1 + x
assert (2*a).extract_multiplicatively(a) == 2
assert (4*a).extract_multiplicatively(2*a) == 2
assert ((3*a)*(2*a)).extract_multiplicatively(a) == 6*a
def test_is_constant():
from sympy.solvers.solvers import checksol
Sum(x, (x, 1, 10)).is_constant() == True
Sum(x, (x, 1, n)).is_constant() == False
Sum(x, (x, 1, n)).is_constant(y) == True
Sum(x, (x, 1, n)).is_constant(n) == False
Sum(x, (x, 1, n)).is_constant(x) == True
eq = a*cos(x)**2 + a*sin(x)**2 - a
eq.is_constant() == True
assert eq.subs({x:pi, a:2}) == eq.subs({x:pi, a:3}) == 0
assert x.is_constant() is False
assert x.is_constant(y) is True
assert checksol(x, x, Sum(x, (x, 1, n))) == False
assert checksol(x, x, Sum(x, (x, 1, n))) == False
f = Function('f')
assert checksol(x, x, f(x)) == False
p = symbols('p', positive=True)
assert Pow(x, S(0), evaluate=False).is_constant() == True # == 1
assert Pow(S(0), x, evaluate=False).is_constant() == False # == 0 or 1
assert Pow(S(0), p, evaluate=False).is_constant() == True # == 1
assert (2**x).is_constant() == False
assert Pow(S(2), S(3), evaluate=False).is_constant() == True
z1, z2 = symbols('z1 z2', zero=True)
assert (z1 + 2*z2).is_constant() is True
assert meter.is_constant() is True
assert (3*meter).is_constant() is True
assert (x*meter).is_constant() is False
def test_equals():
assert (-3 - sqrt(5) + (-sqrt(10)/2 - sqrt(2)/2)**2).equals(0)
assert (x**2 - 1).equals((x + 1)*(x - 1))
assert (cos(x)**2 + sin(x)**2).equals(1)
assert (a*cos(x)**2 + a*sin(x)**2).equals(a)
r = sqrt(2)
assert (-1/(r + r*x) + 1/r/(1 + x)).equals(0)
assert factorial(x + 1).equals((x + 1)*factorial(x))
assert sqrt(3).equals(2*sqrt(3)) is False
assert (sqrt(5)*sqrt(3)).equals(sqrt(3)) is False
assert (sqrt(5) + sqrt(3)).equals(0) is False
assert (sqrt(5) + pi).equals(0) is False
assert meter.equals(0) is False
assert (3*meter**2).equals(0) is False
# from integrate(x*sqrt(1+2*x), x);
# diff is zero only when assumptions allow
i = 2*sqrt(2)*x**(S(5)/2)*(1 + 1/(2*x))**(S(5)/2)/5 + \
2*sqrt(2)*x**(S(3)/2)*(1 + 1/(2*x))**(S(5)/2)/(-6 - 3/x)
ans = sqrt(2*x + 1)*(6*x**2 + x - 1)/15
diff = i - ans
assert diff.equals(0) is False
assert diff.subs(x, -S.Half/2) == 7*sqrt(2)/120
# there are regions for x for which the expression is True, for
# example, when x < -1/2 or x > 0 the expression is zero
p = Symbol('p', positive=True)
assert diff.subs(x, p).equals(0) is True
assert diff.subs(x, -1).equals(0) is True
def test_random():
from sympy import posify
assert posify(x)[0]._random() is not None
def test_round():
from sympy.abc import x
assert Float('0.1249999').round(2) == 0.12
d20 = 12345678901234567890
ans = S(d20).round(2)
assert ans.is_Float and ans == d20
ans = S(d20).round(-2)
assert ans.is_Float and ans == 12345678901234567900
assert S('1/7').round(4) == 0.1429
assert S('.[12345]').round(4) == 0.1235
assert S('.1349').round(2) == 0.13
n = S(12345)
ans = n.round()
assert ans.is_Float
assert ans == n
ans = n.round(1)
assert ans.is_Float
assert ans == n
ans = n.round(4)
assert ans.is_Float
assert ans == n
assert n.round(-1) == 12350
r = n.round(-4)
assert r == 10000
# in fact, it should equal many values since __eq__
# compares at equal precision
assert all(r == i for i in range(9984, 10049))
assert n.round(-5) == 0
assert (pi + sqrt(2)).round(2) == 4.56
assert (10*(pi + sqrt(2))).round(-1) == 50
raises(TypeError, lambda: round(x + 2, 2))
assert S(2.3).round(1) == 2.3
e = S(12.345).round(2)
assert e == round(12.345, 2)
assert type(e) is Float
assert (Float(.3, 3) + 2*pi).round() == 7
assert (Float(.3, 3) + 2*pi*100).round() == 629
assert (Float(.03, 3) + 2*pi/100).round(5) == 0.09283
assert (Float(.03, 3) + 2*pi/100).round(4) == 0.0928
assert (pi + 2*E*I).round() == 3 + 5*I
assert S.Zero.round() == 0
a = (Add(1, Float('1.'+'9'*27, ''), evaluate=0))
assert a.round(10) == Float('3.0000000000','')
assert a.round(25) == Float('3.0000000000000000000000000','')
assert a.round(26) == Float('3.00000000000000000000000000','')
assert a.round(27) == Float('2.999999999999999999999999999','')
assert a.round(30) == Float('2.999999999999999999999999999','')
raises(TypeError, lambda: x.round())
# exact magnitude of 10
assert str(S(1).round()) == '1.'
assert str(S(100).round()) == '100.'
# applied to real and imaginary portions
assert (2*pi + E*I).round() == 6 + 3*I
assert (2*pi + I/10).round() == 6
assert (pi/10 + 2*I).round() == 2*I
# the lhs re and im parts are Float with dps of 2
# and those on the right have dps of 15 so they won't compare
# equal unless we use string or compare components (which will
# then coerce the floats to the same precision) or re-create
# the floats
assert str((pi/10 + E*I).round(2)) == '0.31 + 2.72*I'
assert (pi/10 + E*I).round(2).as_real_imag() == (0.31, 2.72)
assert (pi/10 + E*I).round(2) == Float(0.31, 2) + I*Float(2.72, 3)
# issue 3815
assert (I**(I+3)).round(3) == Float('-0.208','')*I
def test_extract_branch_factor():
assert exp_polar(2.0*I*pi).extract_branch_factor() == (1, 1)
|
bsd-3-clause
| 625,356,421,304,624,600
| 33.645022
| 114
| 0.54313
| false
| 2.594586
| true
| false
| false
|
praekelt/vumi-go
|
go/apps/tests/view_helpers.py
|
1
|
2691
|
from django.core.urlresolvers import reverse
from zope.interface import implements
from vumi.tests.helpers import generate_proxies, IHelper
from go.base import utils as base_utils
from go.base.tests.helpers import DjangoVumiApiHelper
from go.vumitools.tests.helpers import GoMessageHelper
from .helpers import ApplicationHelper
class AppViewsHelper(object):
implements(IHelper)
def __init__(self, conversation_type):
self.conversation_type = conversation_type
self.vumi_helper = DjangoVumiApiHelper()
self._app_helper = ApplicationHelper(
conversation_type, self.vumi_helper)
# Proxy methods from our helpers.
generate_proxies(self, self._app_helper)
generate_proxies(self, self.vumi_helper)
def setup(self):
# Create the things we need to create
self.vumi_helper.setup()
self.vumi_helper.make_django_user()
def cleanup(self):
return self.vumi_helper.cleanup()
def get_new_view_url(self):
return reverse('conversations:new_conversation')
def get_conversation_helper(self, conversation):
return ConversationViewHelper(self, conversation.key)
def create_conversation_helper(self, *args, **kw):
conversation = self.create_conversation(*args, **kw)
return self.get_conversation_helper(conversation)
def get_api_commands_sent(self):
return base_utils.connection.get_commands()
class ConversationViewHelper(object):
def __init__(self, app_views_helper, conversation_key):
self.conversation_key = conversation_key
self.conversation_type = app_views_helper.conversation_type
self.app_helper = app_views_helper
def get_view_url(self, view):
view_def = base_utils.get_conversation_view_definition(
self.conversation_type)
return view_def.get_view_url(
view, conversation_key=self.conversation_key)
def get_action_view_url(self, action_name):
return reverse('conversations:conversation_action', kwargs={
'conversation_key': self.conversation_key,
'action_name': action_name,
})
def get_conversation(self):
return self.app_helper.get_conversation(self.conversation_key)
def add_stored_inbound(self, count, **kw):
msg_helper = GoMessageHelper(vumi_helper=self.app_helper)
conv = self.get_conversation()
return msg_helper.add_inbound_to_conv(conv, count, **kw)
def add_stored_replies(self, msgs):
msg_helper = GoMessageHelper(vumi_helper=self.app_helper)
conv = self.get_conversation()
return msg_helper.add_replies_to_conv(conv, msgs)
|
bsd-3-clause
| -5,930,899,879,608,765,000
| 33.5
| 70
| 0.687105
| false
| 3.666213
| false
| false
| false
|
palominodb/tableizer
|
tableizer/ttt_gui/rrd.py
|
1
|
5968
|
# rrd.py
# Copyright (C) 2009-2013 PalominoDB, Inc.
#
# You may contact the maintainers at eng@palominodb.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.
#
# 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 os
from django.conf import settings
import rrdtool
from utilities.utils import flatten, titleize, str_to_datetime, datetime_to_int
class Rrdtool(object):
def server_graph(self, servers, since, type_='full'):
msgs = []
ok = True
for srv in flatten([servers]):
path = settings.FORMATTER_OPTIONS.get('rrd', {}).get('path', '')
rrd_path = os.path.join(path, srv.name, 'server_%s.rrd' % (srv.name))
opts = self.__common_opts('server_%s' % (srv.name), since, type_, 'Server Aggregate - %s' % (srv.name))
opts.append(map(lambda ds: self.__common_ds_opts(ds, rrd_path), [
['data_length', ['AREA%s:STACK', '#00ff40']],
['index_length', ['AREA%s', '#0040ff']],
#['data_free', ['LINE2%s', '#0f00f0']],
]))
opts = flatten(opts)
opts = map(lambda x: str(x), opts)
try:
rrdtool.graph(opts)
except Exception, e:
msgs.append(e)
ok = False
return [ok, msgs]
def database_graph(self, databases, since, type_='full'):
msgs = []
ok = True
for db in flatten([databases]):
path = settings.FORMATTER_OPTIONS.get('rrd', {}).get('path', '')
rrd_path = os.path.join(path, db.server.name, 'database_%s.rrd' % (db.name))
opts = self.__common_opts('database_%s_%s' % (db.server.name, db.name), since,
type_, 'Database Aggregate - %s.%s' % (db.server.name, db.name))
opts.append(map(lambda ds: self.__common_ds_opts(ds, rrd_path), [
['data_length', ['AREA%s:STACK', '#00ff40']],
['index_length', ['AREA%s', '#0040ff']],
#['data_free', ['LINE2%s', '#0f00f0']],
]))
opts = flatten(opts)
opts = map(lambda x: str(x), opts)
try:
rrdtool.graph(opts)
except Exception, e:
msgs.append(e)
ok = False
return [ok, msgs]
def table_graph(self, tables, since, type_='full'):
msgs = []
ok = True
for tbl in flatten([tables]):
path = settings.FORMATTER_OPTIONS.get('rrd', {}).get('path', '')
rrd_path = os.path.join(path, tbl.schema.server.name, tbl.schema.name, '%s.rrd' % (tbl.name))
opts = self.__common_opts('table_%s_%s_%s' % (tbl.schema.server.name, tbl.schema.name, tbl.name),
since, type_, 'Table - %s.%s.%s' % (tbl.schema.server.name, tbl.schema.name, tbl.name))
opts.append(map(lambda ds: self.__common_ds_opts(ds, rrd_path), [
['data_length', ['AREA%s:STACK', '#00ff40']],
['index_length', ['AREA%s', '#0040ff']],
#['data_free', ['LINE2%s', '#0f00f0']],
]))
opts = flatten(opts)
opts = map(lambda x: str(x), opts)
try:
rrdtool.graph(opts)
except Exception, e:
msgs.append(e)
ok = False
return [ok, msgs]
def __common_opts(self, path_frag, since, type_, title):
filename = '%s.%s.%s.png' % (path_frag, since, type_)
since = str_to_datetime(since)
since = datetime_to_int(since)
if not os.path.isdir(os.path.join(settings.MEDIA_ROOT, 'graphs')):
os.makedirs(os.path.join(settings.MEDIA_ROOT, 'graphs'))
path = os.path.join(settings.MEDIA_ROOT, 'graphs', filename)
o = [path, '-s', str(since), '--width', '640' if type_ == 'full' else '128',
'-e', 'now', '--title', '%s' % (str(title))]
if type_ == 'thumb':
o.append('-j')
o.append('--height')
o.append('16')
return o
def __common_ds_opts(self, ds, rrd_path):
dsname = ds[0]
gitems = ds[1:]
ret = []
ret.append('DEF:avg_{0}={1}:{0}:AVERAGE'.format(dsname, rrd_path))
ret.append('DEF:min_{0}={1}:{0}:MIN'.format(dsname, rrd_path))
ret.append('DEF:max_{0}={1}:{0}:MAX'.format(dsname, rrd_path))
ret.append('VDEF:v_last_{0}=avg_{0},LAST'.format(dsname))
ret.append('VDEF:v_avg_{0}=avg_{0},AVERAGE'.format(dsname))
ret.append('VDEF:v_min_{0}=avg_{0},MINIMUM'.format(dsname))
ret.append('VDEF:v_max_{0}=avg_{0},MAXIMUM'.format(dsname))
for gi in gitems:
ret.append(gi[0] % ':avg_{0}{1}:"{2}"'.format(dsname, gi[1], titleize(dsname)))
ret.append('GPRINT:v_last_{0}:"Current\\: %0.2lf%s"'.format(dsname))
ret.append('GPRINT:v_avg_{0}:"Avg\\: %0.2lf%s"'.format(dsname))
ret.append('GPRINT:v_min_{0}:"Min\\: %0.2lf%s"'.format(dsname))
ret.append('GPRINT:v_max_{0}:"Max\\: %0.2lf%s"'.format(dsname))
ret.append('COMMENT:"\\s"')
ret.append('COMMENT:"\\s"')
return ret
|
gpl-2.0
| -9,085,685,221,464,438,000
| 42.562044
| 127
| 0.525637
| false
| 3.435809
| false
| false
| false
|
florian-wagner/gimli
|
python/pygimli/gui/vtk/wxVTKRenderWindowInteractor.py
|
1
|
24830
|
# -*- coding: utf-8 -*-
"""
A VTK RenderWindowInteractor widget for wxPython.
Find wxPython info at http://wxPython.org
Created by Prabhu Ramachandran, April 2002
Based on wxVTKRenderWindow.py
Fixes and updates by Charl P. Botha 2003-2008
Updated to new wx namespace and some cleaning up by Andrea Gavana,
December 2006
"""
"""
Please see the example at the end of this file.
----------------------------------------
Creation:
wxVTKRenderWindowInteractor(parent, ID, stereo=0, [wx keywords]):
You should create a wx.PySimpleApp() or some other wx**App before
creating the window.
Behaviour:
Uses __getattr__ to make the wxVTKRenderWindowInteractor behave just
like a vtkGenericRenderWindowInteractor.
----------------------------------------
"""
# import usual libraries
import math
import sys
import os
baseClass = object
_useCapture = None
try:
import wx
# a few configuration items, see what works best on your system
# Use GLCanvas as base class instead of wx.Window.
# This is sometimes necessary under wxGTK or the image is blank.
# (in wxWindows 2.3.1 and earlier, the GLCanvas had scroll bars)
if wx.Platform == "__WXGTK__":
import wx.glcanvas
baseClass = wx.glcanvas.GLCanvas
# Keep capturing mouse after mouse is dragged out of window
# (in wxGTK 2.3.2 there is a bug that keeps this from working,
# but it is only relevant in wxGTK if there are multiple windows)
_useCapture = (wx.Platform == "__WXMSW__")
except ImportError as e:
import traceback
#traceback.print_exc(file=sys.stdout)
sys.stderr.write("No proper wx installed'.\n")
try:
import vtk
except Exception as e:
sys.stderr.write("No proper vtk installed'.\n")
# end of configuration items
class EventTimer(wx.Timer):
"""Simple wx.Timer class."""
def __init__(self, iren):
"""
Default class constructor.
@param iren: current render window
"""
wx.Timer.__init__(self)
self.iren = iren
def Notify(self):
"""The timer has expired."""
self.iren.TimerEvent()
class wxVTKRenderWindowInteractor(baseClass):
"""
A wxRenderWindow for wxPython.
Use GetRenderWindow() to get the vtkRenderWindow.
Create with the keyword stereo=1 in order to
generate a stereo-capable window.
"""
# class variable that can also be used to request instances that use
# stereo; this is overridden by the stereo=1/0 parameter. If you set
# it to True, the NEXT instantiated object will attempt to allocate a
# stereo visual. E.g.:
# wxVTKRenderWindowInteractor.USE_STEREO = True
# myRWI = wxVTKRenderWindowInteractor(parent, -1)
USE_STEREO = False
def __init__(self, parent, ID, *args, **kw):
"""
Default class constructor.
@param parent: parent window
@param ID: window id
@param **kw: wxPython keywords (position, size, style) plus the
'stereo' keyword
"""
# private attributes
self.__RenderWhenDisabled = 0
# First do special handling of some keywords:
# stereo, position, size, style
stereo = 0
if 'stereo' in kw:
if kw['stereo']:
stereo = 1
del kw['stereo']
elif self.USE_STEREO:
stereo = 1
position, size = wx.DefaultPosition, wx.DefaultSize
if 'position' in kw:
position = kw['position']
del kw['position']
if 'size' in kw:
size = kw['size']
del kw['size']
# wx.WANTS_CHARS says to give us e.g. TAB
# wx.NO_FULL_REPAINT_ON_RESIZE cuts down resize flicker under GTK
style = wx.WANTS_CHARS | wx.NO_FULL_REPAINT_ON_RESIZE
if 'style' in kw:
style = style | kw['style']
del kw['style']
# the enclosing frame must be shown under GTK or the windows
# don't connect together properly
if wx.Platform != '__WXMSW__':
l = []
p = parent
while p: # make a list of all parents
l.append(p)
p = p.GetParent()
l.reverse() # sort list into descending order
for p in l:
p.Show(1)
if baseClass.__name__ == 'GLCanvas':
# code added by cpbotha to enable stereo and double
# buffering correctly where the user requests this; remember
# that the glXContext in this case is NOT allocated by VTK,
# but by WX, hence all of this.
# Initialize GLCanvas with correct attriblist
attribList = [wx.glcanvas.WX_GL_RGBA,
wx.glcanvas.WX_GL_MIN_RED, 1,
wx.glcanvas.WX_GL_MIN_GREEN, 1,
wx.glcanvas.WX_GL_MIN_BLUE, 1,
wx.glcanvas.WX_GL_DEPTH_SIZE, 16,
wx.glcanvas.WX_GL_DOUBLEBUFFER]
if stereo:
attribList.append(wx.glcanvas.WX_GL_STEREO)
try:
baseClass.__init__(self, parent, id = ID, pos = position, size = size, style = style,
attribList=attribList)
except wx.PyAssertionError:
# visual couldn't be allocated, so we go back to default
baseClass.__init__(self, parent, ID, position, size, style)
if stereo:
# and make sure everyone knows that the stereo
# visual wasn't set.
stereo = 0
else:
baseClass.__init__(self, parent, ID, position, size, style)
# create the RenderWindow and initialize it
self._Iren = vtk.vtkGenericRenderWindowInteractor()
self._Iren.SetRenderWindow( vtk.vtkRenderWindow() )
self._Iren.AddObserver('CreateTimerEvent', self.CreateTimer)
self._Iren.AddObserver('DestroyTimerEvent', self.DestroyTimer)
self._Iren.GetRenderWindow().AddObserver('CursorChangedEvent',
self.CursorChangedEvent)
try:
self._Iren.GetRenderWindow().SetSize(size.width, size.height)
except AttributeError:
self._Iren.GetRenderWindow().SetSize(size[0], size[1])
if stereo:
self._Iren.GetRenderWindow().StereoCapableWindowOn()
self._Iren.GetRenderWindow().SetStereoTypeToCrystalEyes()
self.__handle = None
self.BindEvents()
# with this, we can make sure that the reparenting logic in
# Render() isn't called before the first OnPaint() has
# successfully been run (and set up the VTK/WX display links)
self.__has_painted = False
# set when we have captured the mouse.
self._own_mouse = False
# used to store WHICH mouse button led to mouse capture
self._mouse_capture_button = 0
# A mapping for cursor changes.
self._cursor_map = {0: wx.CURSOR_ARROW, # VTK_CURSOR_DEFAULT
1: wx.CURSOR_ARROW, # VTK_CURSOR_ARROW
2: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZENE
3: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZENWSE
4: wx.CURSOR_SIZENESW, # VTK_CURSOR_SIZESW
5: wx.CURSOR_SIZENWSE, # VTK_CURSOR_SIZESE
6: wx.CURSOR_SIZENS, # VTK_CURSOR_SIZENS
7: wx.CURSOR_SIZEWE, # VTK_CURSOR_SIZEWE
8: wx.CURSOR_SIZING, # VTK_CURSOR_SIZEALL
9: wx.CURSOR_HAND, # VTK_CURSOR_HAND
10: wx.CURSOR_CROSS, # VTK_CURSOR_CROSSHAIR
}
def BindEvents(self):
"""Binds all the necessary events for navigation, sizing, drawing."""
# refresh window by doing a Render
self.Bind(wx.EVT_PAINT, self.OnPaint)
# turn off background erase to reduce flicker
self.Bind(wx.EVT_ERASE_BACKGROUND, lambda e: None)
# Bind the events to the event converters
self.Bind(wx.EVT_RIGHT_DOWN, self.OnButtonDown)
self.Bind(wx.EVT_LEFT_DOWN, self.OnButtonDown)
self.Bind(wx.EVT_MIDDLE_DOWN, self.OnButtonDown)
self.Bind(wx.EVT_RIGHT_UP, self.OnButtonUp)
self.Bind(wx.EVT_LEFT_UP, self.OnButtonUp)
self.Bind(wx.EVT_MIDDLE_UP, self.OnButtonUp)
self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_ENTER_WINDOW, self.OnEnter)
self.Bind(wx.EVT_LEAVE_WINDOW, self.OnLeave)
# If we use EVT_KEY_DOWN instead of EVT_CHAR, capital versions
# of all characters are always returned. EVT_CHAR also performs
# other necessary keyboard-dependent translations.
self.Bind(wx.EVT_CHAR, self.OnKeyDown)
self.Bind(wx.EVT_KEY_UP, self.OnKeyUp)
self.Bind(wx.EVT_SIZE, self.OnSize)
# the wx 2.8.7.1 documentation states that you HAVE to handle
# this event if you make use of CaptureMouse, which we do.
if _useCapture and hasattr(wx, 'EVT_MOUSE_CAPTURE_LOST'):
self.Bind(wx.EVT_MOUSE_CAPTURE_LOST,
self.OnMouseCaptureLost)
def __getattr__(self, attr):
"""Makes the object behave like a vtkGenericRenderWindowInteractor."""
if attr == '__vtk__':
return lambda t=self._Iren: t
elif hasattr(self._Iren, attr):
return getattr(self._Iren, attr)
else:
raise AttributeError(self.__class__.__name__ + \
" has no attribute named " + attr)
def CreateTimer(self, obj, evt):
"""Creates a timer."""
self._timer = EventTimer(self)
self._timer.Start(10, True)
def DestroyTimer(self, obj, evt):
"""The timer is a one shot timer so will expire automatically."""
return 1
def _CursorChangedEvent(self, obj, evt):
"""Change the wx cursor if the renderwindow's cursor was changed."""
cur = self._cursor_map[obj.GetCurrentCursor()]
c = wx.StockCursor(cur)
self.SetCursor(c)
def CursorChangedEvent(self, obj, evt):
"""Called when the CursorChangedEvent fires on the render window."""
# This indirection is needed since when the event fires, the
# current cursor is not yet set so we defer this by which time
# the current cursor should have been set.
wx.CallAfter(self._CursorChangedEvent, obj, evt)
def HideCursor(self):
"""Hides the cursor."""
c = wx.StockCursor(wx.CURSOR_BLANK)
self.SetCursor(c)
def ShowCursor(self):
"""Shows the cursor."""
rw = self._Iren.GetRenderWindow()
cur = self._cursor_map[rw.GetCurrentCursor()]
c = wx.StockCursor(cur)
self.SetCursor(c)
def GetDisplayId(self):
"""
Function to get X11 Display ID from WX and return it in a format that
can be used by VTK Python.
We query the X11 Display with a new call that was added in wxPython
2.6.0.1. The call returns a SWIG object which we can query for the
address and subsequently turn into an old-style SWIG-mangled string
representation to pass to VTK.
"""
d = None
try:
d = wx.GetXDisplay()
except NameError:
# wx.GetXDisplay was added by Robin Dunn in wxPython 2.6.0.1
# if it's not available, we can't pass it. In general,
# things will still work; on some setups, it'll break.
pass
else:
# wx returns None on platforms where wx.GetXDisplay is not relevant
if d:
d = hex(d)
# On wxPython-2.6.3.2 and above there is no leading '0x'.
if not d.startswith('0x'):
d = '0x' + d
# we now have 0xdeadbeef
# VTK wants it as: _deadbeef_void_p (pre-SWIG-1.3 style)
d = '_%s_%s' % (d[2:], 'void_p')
return d
def OnMouseCaptureLost(self, event):
"""
This is signalled when we lose mouse capture due to an external event,
such as when a dialog box is shown.
See the wx documentation.
"""
# the documentation seems to imply that by this time we've
# already lost capture. I have to assume that we don't need
# to call ReleaseMouse ourselves.
if _useCapture and self._own_mouse:
self._own_mouse = False
def OnPaint(self,event):
"""Handles the wx.EVT_PAINT event for wxVTKRenderWindowInteractor."""
# wx should continue event processing after this handler.
# We call this BEFORE Render(), so that if Render() raises
# an exception, wx doesn't re-call OnPaint repeatedly.
event.Skip()
dc = wx.PaintDC(self)
# make sure the RenderWindow is sized correctly
self._Iren.GetRenderWindow().SetSize(self.GetSizeTuple())
# Tell the RenderWindow to render inside the wx.Window.
if not self.__handle:
# on relevant platforms, set the X11 Display ID
d = self.GetDisplayId()
if d:
self._Iren.GetRenderWindow().SetDisplayId(d)
# store the handle
self.__handle = self.GetHandle()
# and give it to VTK
self._Iren.GetRenderWindow().SetWindowInfo(str(self.__handle))
# now that we've painted once, the Render() reparenting logic
# is safe
self.__has_painted = True
self.Render()
def OnSize(self,event):
"""Handles the wx.EVT_SIZE event for wxVTKRenderWindowInteractor."""
# event processing should continue (we call this before the
# Render(), in case it raises an exception)
event.Skip()
try:
width, height = event.GetSize()
except:
width = event.GetSize().width
height = event.GetSize().height
self._Iren.SetSize(width, height)
self._Iren.ConfigureEvent()
# this will check for __handle
self.Render()
def OnMotion(self,event):
"""Handles the wx.EVT_MOTION event for wxVTKRenderWindowInteractor."""
# event processing should continue
# we call this early in case any of the VTK code raises an
# exception.
event.Skip()
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
event.ControlDown(),
event.ShiftDown(),
chr(0), 0, None)
self._Iren.MouseMoveEvent()
def OnEnter(self,event):
"""Handles the wx.EVT_ENTER_WINDOW event for
wxVTKRenderWindowInteractor."""
# event processing should continue
event.Skip()
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
event.ControlDown(),
event.ShiftDown(),
chr(0), 0, None)
self._Iren.EnterEvent()
def OnLeave(self,event):
"""Handles the wx.EVT_LEAVE_WINDOW event for
wxVTKRenderWindowInteractor."""
# event processing should continue
event.Skip()
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
event.ControlDown(),
event.ShiftDown(),
chr(0), 0, None)
self._Iren.LeaveEvent()
def OnButtonDown(self,event):
"""Handles the wx.EVT_LEFT/RIGHT/MIDDLE_DOWN events for
wxVTKRenderWindowInteractor."""
# allow wx event processing to continue
# on wxPython 2.6.0.1, omitting this will cause problems with
# the initial focus, resulting in the wxVTKRWI ignoring keypresses
# until we focus elsewhere and then refocus the wxVTKRWI frame
# we do it this early in case any of the following VTK code
# raises an exception.
event.Skip()
ctrl, shift = event.ControlDown(), event.ShiftDown()
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
ctrl, shift, chr(0), 0, None)
button = 0
if event.RightDown():
self._Iren.RightButtonPressEvent()
button = 'Right'
elif event.LeftDown():
self._Iren.LeftButtonPressEvent()
button = 'Left'
elif event.MiddleDown():
self._Iren.MiddleButtonPressEvent()
button = 'Middle'
# save the button and capture mouse until the button is released
# we only capture the mouse if it hasn't already been captured
if _useCapture and not self._own_mouse:
self._own_mouse = True
self._mouse_capture_button = button
self.CaptureMouse()
def OnButtonUp(self,event):
"""Handles the wx.EVT_LEFT/RIGHT/MIDDLE_UP events for
wxVTKRenderWindowInteractor."""
# event processing should continue
event.Skip()
button = 0
if event.RightUp():
button = 'Right'
elif event.LeftUp():
button = 'Left'
elif event.MiddleUp():
button = 'Middle'
# if the same button is released that captured the mouse, and
# we have the mouse, release it.
# (we need to get rid of this as soon as possible; if we don't
# and one of the event handlers raises an exception, mouse
# is never released.)
if _useCapture and self._own_mouse and \
button==self._mouse_capture_button:
self.ReleaseMouse()
self._own_mouse = False
ctrl, shift = event.ControlDown(), event.ShiftDown()
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
ctrl, shift, chr(0), 0, None)
if button == 'Right':
self._Iren.RightButtonReleaseEvent()
elif button == 'Left':
self._Iren.LeftButtonReleaseEvent()
elif button == 'Middle':
self._Iren.MiddleButtonReleaseEvent()
def OnMouseWheel(self,event):
"""Handles the wx.EVT_MOUSEWHEEL event for
wxVTKRenderWindowInteractor."""
# event processing should continue
event.Skip()
ctrl, shift = event.ControlDown(), event.ShiftDown()
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
ctrl, shift, chr(0), 0, None)
if event.GetWheelRotation() > 0:
self._Iren.MouseWheelForwardEvent()
else:
self._Iren.MouseWheelBackwardEvent()
def OnKeyDown(self,event):
"""Handles the wx.EVT_KEY_DOWN event for
wxVTKRenderWindowInteractor."""
# event processing should continue
event.Skip()
ctrl, shift = event.ControlDown(), event.ShiftDown()
keycode, keysym = event.GetKeyCode(), None
key = chr(0)
if keycode < 256:
key = chr(keycode)
# wxPython 2.6.0.1 does not return a valid event.Get{X,Y}()
# for this event, so we use the cached position.
(x,y)= self._Iren.GetEventPosition()
self._Iren.SetEventInformation(x, y,
ctrl, shift, key, 0,
keysym)
self._Iren.KeyPressEvent()
self._Iren.CharEvent()
def OnKeyUp(self,event):
"""Handles the wx.EVT_KEY_UP event for wxVTKRenderWindowInteractor."""
# event processing should continue
event.Skip()
ctrl, shift = event.ControlDown(), event.ShiftDown()
keycode, keysym = event.GetKeyCode(), None
key = chr(0)
if keycode < 256:
key = chr(keycode)
self._Iren.SetEventInformationFlipY(event.GetX(), event.GetY(),
ctrl, shift, key, 0,
keysym)
self._Iren.KeyReleaseEvent()
def GetRenderWindow(self):
"""Returns the render window (vtkRenderWindow)."""
return self._Iren.GetRenderWindow()
def Render(self):
"""Actually renders the VTK scene on screen."""
RenderAllowed = 1
if not self.__RenderWhenDisabled:
# the user doesn't want us to render when the toplevel frame
# is disabled - first find the top level parent
topParent = wx.GetTopLevelParent(self)
if topParent:
# if it exists, check whether it's enabled
# if it's not enabeld, RenderAllowed will be false
RenderAllowed = topParent.IsEnabled()
if RenderAllowed:
if self.__handle and self.__handle == self.GetHandle():
self._Iren.GetRenderWindow().Render()
elif self.GetHandle() and self.__has_painted:
# this means the user has reparented us; let's adapt to the
# new situation by doing the WindowRemap dance
self._Iren.GetRenderWindow().SetNextWindowInfo(
str(self.GetHandle()))
# make sure the DisplayId is also set correctly
d = self.GetDisplayId()
if d:
self._Iren.GetRenderWindow().SetDisplayId(d)
# do the actual remap with the new parent information
self._Iren.GetRenderWindow().WindowRemap()
# store the new situation
self.__handle = self.GetHandle()
self._Iren.GetRenderWindow().Render()
def SetRenderWhenDisabled(self, newValue):
"""
Change value of __RenderWhenDisabled ivar.
If __RenderWhenDisabled is false (the default), this widget will not
call Render() on the RenderWindow if the top level frame (i.e. the
containing frame) has been disabled.
This prevents recursive rendering during wx.SafeYield() calls.
wx.SafeYield() can be called during the ProgressMethod() callback of
a VTK object to have progress bars and other GUI elements updated -
it does this by disabling all windows (disallowing user-input to
prevent re-entrancy of code) and then handling all outstanding
GUI events.
However, this often triggers an OnPaint() method for wxVTKRWIs,
resulting in a Render(), resulting in Update() being called whilst
still in progress.
"""
self.__RenderWhenDisabled = bool(newValue)
#--------------------------------------------------------------------
def wxVTKRenderWindowInteractorConeExample():
"""Like it says, just a simple example."""
# every wx app needs an app
app = wx.PySimpleApp()
# create the top-level frame, sizer and wxVTKRWI
frame = wx.Frame(None, -1, "wxVTKRenderWindowInteractor", size=(400,400))
widget = wxVTKRenderWindowInteractor(frame, -1)
sizer = wx.BoxSizer(wx.VERTICAL)
sizer.Add(widget, 1, wx.EXPAND)
frame.SetSizer(sizer)
frame.Layout()
# It would be more correct (API-wise) to call widget.Initialize() and
# widget.Start() here, but Initialize() calls RenderWindow.Render().
# That Render() call will get through before we can setup the
# RenderWindow() to render via the wxWidgets-created context; this
# causes flashing on some platforms and downright breaks things on
# other platforms. Instead, we call widget.Enable(). This means
# that the RWI::Initialized ivar is not set, but in THIS SPECIFIC CASE,
# that doesn't matter.
widget.Enable(1)
widget.AddObserver("ExitEvent", lambda o,e,f=frame: f.Close())
ren = vtk.vtkRenderer()
widget.GetRenderWindow().AddRenderer(ren)
cone = vtk.vtkConeSource()
cone.SetResolution(8)
coneMapper = vtk.vtkPolyDataMapper()
coneMapper.SetInput(cone.GetOutput())
coneActor = vtk.vtkActor()
coneActor.SetMapper(coneMapper)
ren.AddActor(coneActor)
# show the window
frame.Show()
app.MainLoop()
if __name__ == "__main__":
wxVTKRenderWindowInteractorConeExample()
|
gpl-3.0
| -454,796,966,052,879,700
| 34.573066
| 102
| 0.57499
| false
| 4.141094
| false
| false
| false
|
spencerlyon2/pygments
|
pygments/lexers/_clbuiltins.py
|
2
|
14050
|
# -*- coding: utf-8 -*-
"""
pygments.lexers._clbuiltins
~~~~~~~~~~~~~~~~~~~~~~~~~~~
ANSI Common Lisp builtins.
:copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
BUILTIN_FUNCTIONS = set(( # 638 functions
'<', '<=', '=', '>', '>=', '-', '/', '/=', '*', '+', '1-', '1+',
'abort', 'abs', 'acons', 'acos', 'acosh', 'add-method', 'adjoin',
'adjustable-array-p', 'adjust-array', 'allocate-instance',
'alpha-char-p', 'alphanumericp', 'append', 'apply', 'apropos',
'apropos-list', 'aref', 'arithmetic-error-operands',
'arithmetic-error-operation', 'array-dimension', 'array-dimensions',
'array-displacement', 'array-element-type', 'array-has-fill-pointer-p',
'array-in-bounds-p', 'arrayp', 'array-rank', 'array-row-major-index',
'array-total-size', 'ash', 'asin', 'asinh', 'assoc', 'assoc-if',
'assoc-if-not', 'atan', 'atanh', 'atom', 'bit', 'bit-and', 'bit-andc1',
'bit-andc2', 'bit-eqv', 'bit-ior', 'bit-nand', 'bit-nor', 'bit-not',
'bit-orc1', 'bit-orc2', 'bit-vector-p', 'bit-xor', 'boole',
'both-case-p', 'boundp', 'break', 'broadcast-stream-streams',
'butlast', 'byte', 'byte-position', 'byte-size', 'caaaar', 'caaadr',
'caaar', 'caadar', 'caaddr', 'caadr', 'caar', 'cadaar', 'cadadr',
'cadar', 'caddar', 'cadddr', 'caddr', 'cadr', 'call-next-method', 'car',
'cdaaar', 'cdaadr', 'cdaar', 'cdadar', 'cdaddr', 'cdadr', 'cdar',
'cddaar', 'cddadr', 'cddar', 'cdddar', 'cddddr', 'cdddr', 'cddr', 'cdr',
'ceiling', 'cell-error-name', 'cerror', 'change-class', 'char', 'char<',
'char<=', 'char=', 'char>', 'char>=', 'char/=', 'character',
'characterp', 'char-code', 'char-downcase', 'char-equal',
'char-greaterp', 'char-int', 'char-lessp', 'char-name',
'char-not-equal', 'char-not-greaterp', 'char-not-lessp', 'char-upcase',
'cis', 'class-name', 'class-of', 'clear-input', 'clear-output',
'close', 'clrhash', 'code-char', 'coerce', 'compile',
'compiled-function-p', 'compile-file', 'compile-file-pathname',
'compiler-macro-function', 'complement', 'complex', 'complexp',
'compute-applicable-methods', 'compute-restarts', 'concatenate',
'concatenated-stream-streams', 'conjugate', 'cons', 'consp',
'constantly', 'constantp', 'continue', 'copy-alist', 'copy-list',
'copy-pprint-dispatch', 'copy-readtable', 'copy-seq', 'copy-structure',
'copy-symbol', 'copy-tree', 'cos', 'cosh', 'count', 'count-if',
'count-if-not', 'decode-float', 'decode-universal-time', 'delete',
'delete-duplicates', 'delete-file', 'delete-if', 'delete-if-not',
'delete-package', 'denominator', 'deposit-field', 'describe',
'describe-object', 'digit-char', 'digit-char-p', 'directory',
'directory-namestring', 'disassemble', 'documentation', 'dpb',
'dribble', 'echo-stream-input-stream', 'echo-stream-output-stream',
'ed', 'eighth', 'elt', 'encode-universal-time', 'endp',
'enough-namestring', 'ensure-directories-exist',
'ensure-generic-function', 'eq', 'eql', 'equal', 'equalp', 'error',
'eval', 'evenp', 'every', 'exp', 'export', 'expt', 'fboundp',
'fceiling', 'fdefinition', 'ffloor', 'fifth', 'file-author',
'file-error-pathname', 'file-length', 'file-namestring',
'file-position', 'file-string-length', 'file-write-date',
'fill', 'fill-pointer', 'find', 'find-all-symbols', 'find-class',
'find-if', 'find-if-not', 'find-method', 'find-package', 'find-restart',
'find-symbol', 'finish-output', 'first', 'float', 'float-digits',
'floatp', 'float-precision', 'float-radix', 'float-sign', 'floor',
'fmakunbound', 'force-output', 'format', 'fourth', 'fresh-line',
'fround', 'ftruncate', 'funcall', 'function-keywords',
'function-lambda-expression', 'functionp', 'gcd', 'gensym', 'gentemp',
'get', 'get-decoded-time', 'get-dispatch-macro-character', 'getf',
'gethash', 'get-internal-real-time', 'get-internal-run-time',
'get-macro-character', 'get-output-stream-string', 'get-properties',
'get-setf-expansion', 'get-universal-time', 'graphic-char-p',
'hash-table-count', 'hash-table-p', 'hash-table-rehash-size',
'hash-table-rehash-threshold', 'hash-table-size', 'hash-table-test',
'host-namestring', 'identity', 'imagpart', 'import',
'initialize-instance', 'input-stream-p', 'inspect',
'integer-decode-float', 'integer-length', 'integerp',
'interactive-stream-p', 'intern', 'intersection',
'invalid-method-error', 'invoke-debugger', 'invoke-restart',
'invoke-restart-interactively', 'isqrt', 'keywordp', 'last', 'lcm',
'ldb', 'ldb-test', 'ldiff', 'length', 'lisp-implementation-type',
'lisp-implementation-version', 'list', 'list*', 'list-all-packages',
'listen', 'list-length', 'listp', 'load',
'load-logical-pathname-translations', 'log', 'logand', 'logandc1',
'logandc2', 'logbitp', 'logcount', 'logeqv', 'logical-pathname',
'logical-pathname-translations', 'logior', 'lognand', 'lognor',
'lognot', 'logorc1', 'logorc2', 'logtest', 'logxor', 'long-site-name',
'lower-case-p', 'machine-instance', 'machine-type', 'machine-version',
'macroexpand', 'macroexpand-1', 'macro-function', 'make-array',
'make-broadcast-stream', 'make-concatenated-stream', 'make-condition',
'make-dispatch-macro-character', 'make-echo-stream', 'make-hash-table',
'make-instance', 'make-instances-obsolete', 'make-list',
'make-load-form', 'make-load-form-saving-slots', 'make-package',
'make-pathname', 'make-random-state', 'make-sequence', 'make-string',
'make-string-input-stream', 'make-string-output-stream', 'make-symbol',
'make-synonym-stream', 'make-two-way-stream', 'makunbound', 'map',
'mapc', 'mapcan', 'mapcar', 'mapcon', 'maphash', 'map-into', 'mapl',
'maplist', 'mask-field', 'max', 'member', 'member-if', 'member-if-not',
'merge', 'merge-pathnames', 'method-combination-error',
'method-qualifiers', 'min', 'minusp', 'mismatch', 'mod',
'muffle-warning', 'name-char', 'namestring', 'nbutlast', 'nconc',
'next-method-p', 'nintersection', 'ninth', 'no-applicable-method',
'no-next-method', 'not', 'notany', 'notevery', 'nreconc', 'nreverse',
'nset-difference', 'nset-exclusive-or', 'nstring-capitalize',
'nstring-downcase', 'nstring-upcase', 'nsublis', 'nsubst', 'nsubst-if',
'nsubst-if-not', 'nsubstitute', 'nsubstitute-if', 'nsubstitute-if-not',
'nth', 'nthcdr', 'null', 'numberp', 'numerator', 'nunion', 'oddp',
'open', 'open-stream-p', 'output-stream-p', 'package-error-package',
'package-name', 'package-nicknames', 'packagep',
'package-shadowing-symbols', 'package-used-by-list', 'package-use-list',
'pairlis', 'parse-integer', 'parse-namestring', 'pathname',
'pathname-device', 'pathname-directory', 'pathname-host',
'pathname-match-p', 'pathname-name', 'pathnamep', 'pathname-type',
'pathname-version', 'peek-char', 'phase', 'plusp', 'position',
'position-if', 'position-if-not', 'pprint', 'pprint-dispatch',
'pprint-fill', 'pprint-indent', 'pprint-linear', 'pprint-newline',
'pprint-tab', 'pprint-tabular', 'prin1', 'prin1-to-string', 'princ',
'princ-to-string', 'print', 'print-object', 'probe-file', 'proclaim',
'provide', 'random', 'random-state-p', 'rassoc', 'rassoc-if',
'rassoc-if-not', 'rational', 'rationalize', 'rationalp', 'read',
'read-byte', 'read-char', 'read-char-no-hang', 'read-delimited-list',
'read-from-string', 'read-line', 'read-preserving-whitespace',
'read-sequence', 'readtable-case', 'readtablep', 'realp', 'realpart',
'reduce', 'reinitialize-instance', 'rem', 'remhash', 'remove',
'remove-duplicates', 'remove-if', 'remove-if-not', 'remove-method',
'remprop', 'rename-file', 'rename-package', 'replace', 'require',
'rest', 'restart-name', 'revappend', 'reverse', 'room', 'round',
'row-major-aref', 'rplaca', 'rplacd', 'sbit', 'scale-float', 'schar',
'search', 'second', 'set', 'set-difference',
'set-dispatch-macro-character', 'set-exclusive-or',
'set-macro-character', 'set-pprint-dispatch', 'set-syntax-from-char',
'seventh', 'shadow', 'shadowing-import', 'shared-initialize',
'short-site-name', 'signal', 'signum', 'simple-bit-vector-p',
'simple-condition-format-arguments', 'simple-condition-format-control',
'simple-string-p', 'simple-vector-p', 'sin', 'sinh', 'sixth', 'sleep',
'slot-boundp', 'slot-exists-p', 'slot-makunbound', 'slot-missing',
'slot-unbound', 'slot-value', 'software-type', 'software-version',
'some', 'sort', 'special-operator-p', 'sqrt', 'stable-sort',
'standard-char-p', 'store-value', 'stream-element-type',
'stream-error-stream', 'stream-external-format', 'streamp', 'string',
'string<', 'string<=', 'string=', 'string>', 'string>=', 'string/=',
'string-capitalize', 'string-downcase', 'string-equal',
'string-greaterp', 'string-left-trim', 'string-lessp',
'string-not-equal', 'string-not-greaterp', 'string-not-lessp',
'stringp', 'string-right-trim', 'string-trim', 'string-upcase',
'sublis', 'subseq', 'subsetp', 'subst', 'subst-if', 'subst-if-not',
'substitute', 'substitute-if', 'substitute-if-not', 'subtypep','svref',
'sxhash', 'symbol-function', 'symbol-name', 'symbolp', 'symbol-package',
'symbol-plist', 'symbol-value', 'synonym-stream-symbol', 'syntax:',
'tailp', 'tan', 'tanh', 'tenth', 'terpri', 'third',
'translate-logical-pathname', 'translate-pathname', 'tree-equal',
'truename', 'truncate', 'two-way-stream-input-stream',
'two-way-stream-output-stream', 'type-error-datum',
'type-error-expected-type', 'type-of', 'typep', 'unbound-slot-instance',
'unexport', 'unintern', 'union', 'unread-char', 'unuse-package',
'update-instance-for-different-class',
'update-instance-for-redefined-class', 'upgraded-array-element-type',
'upgraded-complex-part-type', 'upper-case-p', 'use-package',
'user-homedir-pathname', 'use-value', 'values', 'values-list', 'vector',
'vectorp', 'vector-pop', 'vector-push', 'vector-push-extend', 'warn',
'wild-pathname-p', 'write', 'write-byte', 'write-char', 'write-line',
'write-sequence', 'write-string', 'write-to-string', 'yes-or-no-p',
'y-or-n-p', 'zerop',
))
SPECIAL_FORMS = set((
'block', 'catch', 'declare', 'eval-when', 'flet', 'function', 'go', 'if',
'labels', 'lambda', 'let', 'let*', 'load-time-value', 'locally', 'macrolet',
'multiple-value-call', 'multiple-value-prog1', 'progn', 'progv', 'quote',
'return-from', 'setq', 'symbol-macrolet', 'tagbody', 'the', 'throw',
'unwind-protect',
))
MACROS = set((
'and', 'assert', 'call-method', 'case', 'ccase', 'check-type', 'cond',
'ctypecase', 'decf', 'declaim', 'defclass', 'defconstant', 'defgeneric',
'define-compiler-macro', 'define-condition', 'define-method-combination',
'define-modify-macro', 'define-setf-expander', 'define-symbol-macro',
'defmacro', 'defmethod', 'defpackage', 'defparameter', 'defsetf',
'defstruct', 'deftype', 'defun', 'defvar', 'destructuring-bind', 'do',
'do*', 'do-all-symbols', 'do-external-symbols', 'dolist', 'do-symbols',
'dotimes', 'ecase', 'etypecase', 'formatter', 'handler-bind',
'handler-case', 'ignore-errors', 'incf', 'in-package', 'lambda', 'loop',
'loop-finish', 'make-method', 'multiple-value-bind', 'multiple-value-list',
'multiple-value-setq', 'nth-value', 'or', 'pop',
'pprint-exit-if-list-exhausted', 'pprint-logical-block', 'pprint-pop',
'print-unreadable-object', 'prog', 'prog*', 'prog1', 'prog2', 'psetf',
'psetq', 'push', 'pushnew', 'remf', 'restart-bind', 'restart-case',
'return', 'rotatef', 'setf', 'shiftf', 'step', 'time', 'trace', 'typecase',
'unless', 'untrace', 'when', 'with-accessors', 'with-compilation-unit',
'with-condition-restarts', 'with-hash-table-iterator',
'with-input-from-string', 'with-open-file', 'with-open-stream',
'with-output-to-string', 'with-package-iterator', 'with-simple-restart',
'with-slots', 'with-standard-io-syntax',
))
LAMBDA_LIST_KEYWORDS = set((
'&allow-other-keys', '&aux', '&body', '&environment', '&key', '&optional',
'&rest', '&whole',
))
DECLARATIONS = set((
'dynamic-extent', 'ignore', 'optimize', 'ftype', 'inline', 'special',
'ignorable', 'notinline', 'type',
))
BUILTIN_TYPES = set((
'atom', 'boolean', 'base-char', 'base-string', 'bignum', 'bit',
'compiled-function', 'extended-char', 'fixnum', 'keyword', 'nil',
'signed-byte', 'short-float', 'single-float', 'double-float', 'long-float',
'simple-array', 'simple-base-string', 'simple-bit-vector', 'simple-string',
'simple-vector', 'standard-char', 'unsigned-byte',
# Condition Types
'arithmetic-error', 'cell-error', 'condition', 'control-error',
'division-by-zero', 'end-of-file', 'error', 'file-error',
'floating-point-inexact', 'floating-point-overflow',
'floating-point-underflow', 'floating-point-invalid-operation',
'parse-error', 'package-error', 'print-not-readable', 'program-error',
'reader-error', 'serious-condition', 'simple-condition', 'simple-error',
'simple-type-error', 'simple-warning', 'stream-error', 'storage-condition',
'style-warning', 'type-error', 'unbound-variable', 'unbound-slot',
'undefined-function', 'warning',
))
BUILTIN_CLASSES = set((
'array', 'broadcast-stream', 'bit-vector', 'built-in-class', 'character',
'class', 'complex', 'concatenated-stream', 'cons', 'echo-stream',
'file-stream', 'float', 'function', 'generic-function', 'hash-table',
'integer', 'list', 'logical-pathname', 'method-combination', 'method',
'null', 'number', 'package', 'pathname', 'ratio', 'rational', 'readtable',
'real', 'random-state', 'restart', 'sequence', 'standard-class',
'standard-generic-function', 'standard-method', 'standard-object',
'string-stream', 'stream', 'string', 'structure-class', 'structure-object',
'symbol', 'synonym-stream', 't', 'two-way-stream', 'vector',
))
|
bsd-2-clause
| 8,959,820,288,131,650,000
| 59.560345
| 80
| 0.629751
| false
| 2.994459
| false
| false
| false
|
mmerce/python
|
bigml/tests/create_forecast_steps.py
|
1
|
1792
|
# -*- coding: utf-8 -*-
#
# Copyright 2017-2020 BigML
#
# 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 json
import time
from nose.tools import assert_almost_equals, eq_
from datetime import datetime
from .world import world
from bigml.api import HTTP_CREATED
from bigml.api import FINISHED, FAULTY
from bigml.api import get_status
from .read_forecast_steps import i_get_the_forecast
def i_create_a_forecast(step, data=None):
if data is None:
data = "{}"
time_series = world.time_series['resource']
data = json.loads(data)
resource = world.api.create_forecast(time_series, data)
world.status = resource['code']
eq_(world.status, HTTP_CREATED)
world.location = resource['location']
world.forecast = resource['object']
world.forecasts.append(resource['resource'])
def the_forecast_is(step, predictions):
predictions = json.loads(predictions)
attrs = ["point_forecast", "model"]
for field_id in predictions:
forecast = world.forecast['forecast']['result'][field_id]
prediction = predictions[field_id]
eq_(len(forecast), len(prediction), "forecast: %s" % forecast)
for index in range(len(forecast)):
for attr in attrs:
eq_(forecast[index][attr], prediction[index][attr])
|
apache-2.0
| 7,671,300,440,271,742,000
| 34.137255
| 75
| 0.704241
| false
| 3.820896
| false
| false
| false
|
terrycojones/dark-matter
|
dark/mutations.py
|
1
|
16454
|
import os
from collections import defaultdict
import numpy as np
try:
import matplotlib
if not os.environ.get('DISPLAY'):
# Use non-interactive Agg backend
matplotlib.use('Agg')
import matplotlib.pyplot as plt
except ImportError:
import platform
if platform.python_implementation() == 'PyPy':
# PyPy doesn't have a version of matplotlib. Make a fake
# class that raises if it is used. This allows us to use other
# 'dark' code that happens to import dark.mutations but not use the
# functions that rely on matplotlib.
class plt(object):
def __getattr__(self, _):
raise NotImplementedError(
'matplotlib is not supported under pypy')
else:
raise
from random import choice, uniform
from dark import ncbidb
def basePlotter(blastHits, title):
"""
Plot the reads and the subject, so that bases in the reads which are
different from the subject are shown. Else a '.' is shown.
like so:
subject_gi ATGCGTACGTACGACACC
read_1 A......TTC..T
@param blastHits: A L{dark.blast.BlastHits} instance.
@param title: A C{str} sequence title that was matched by BLAST. We plot
the reads that matched this title.
"""
result = []
params = blastHits.plotParams
assert params is not None, ('Oops, it looks like you forgot to run '
'computePlotInfo.')
sequence = ncbidb.getSequence(title, blastHits.records.blastDb)
subject = sequence.seq
gi = title.split('|')[1]
sub = '%s\t \t \t%s' % (gi, subject)
result.append(sub)
plotInfo = blastHits.titles[title]['plotInfo']
assert plotInfo is not None, ('Oops, it looks like you forgot to run '
'computePlotInfo.')
items = plotInfo['items']
count = 0
for item in items:
count += 1
hsp = item['hsp']
queryTitle = blastHits.fasta[item['readNum']].id
# If the product of the subject and query frame values is +ve,
# then they're either both +ve or both -ve, so we just use the
# query as is. Otherwise, we need to reverse complement it.
if item['frame']['subject'] * item['frame']['query'] > 0:
query = blastHits.fasta[item['readNum']].seq
reverse = False
else:
# One of the subject or query has negative sense.
query = blastHits.fasta[
item['readNum']].reverse_complement().seq
reverse = True
query = query.upper()
queryStart = hsp['queryStart']
subjectStart = hsp['subjectStart']
queryEnd = hsp['queryEnd']
subjectEnd = hsp['subjectEnd']
# Before comparing the read to the subject, make a string of the
# same length as the subject, which contains the read and
# has ' ' where the read does not match.
# 3 parts need to be taken into account:
# 1) the left offset (if the query doesn't stick out to the left)
# 2) the query. if the frame is -1, it has to be reversed.
# The query consists of 3 parts: left, middle (control for gaps)
# 3) the right offset
# Do part 1) and 2).
if queryStart < 0:
# The query is sticking out to the left.
leftQuery = ''
if subjectStart == 0:
# The match starts at the first base of the subject.
middleLeftQuery = ''
else:
# The match starts into the subject.
# Determine the length of the not matching query
# part to the left.
leftOffset = -1 * queryStart
rightOffset = subjectStart + leftOffset
middleLeftQuery = query[leftOffset:rightOffset]
else:
# The query is not sticking out to the left
# make the left offset.
leftQuery = queryStart * ' '
leftQueryOffset = subjectStart - queryStart
middleLeftQuery = query[:leftQueryOffset]
# Do part 3).
# Disregard gaps in subject while adding.
matchQuery = item['origHsp'].query
matchSubject = item['origHsp'].sbjct
index = 0
mid = ''
for item in range(len(matchQuery)):
if matchSubject[index] != ' ':
mid += matchQuery[index]
index += 1
# if the query has been reversed, turn the matched part around
if reverse:
rev = ''
toReverse = mid
reverseDict = {' ': ' ', '-': '-', 'A': 'T', 'T': 'A',
'C': 'G', 'G': 'C', '.': '.', 'N': 'N'}
for item in toReverse:
newItem = reverseDict[item]
rev += newItem
mid = rev[::-1]
middleQuery = middleLeftQuery + mid
# add right not-matching part of the query
rightQueryOffset = queryEnd - subjectEnd
rightQuery = query[-rightQueryOffset:]
middleQuery += rightQuery
read = leftQuery + middleQuery
# do part 3)
offset = len(subject) - len(read)
# if the read is sticking out to the right
# chop it off
if offset < 0:
read = read[:offset]
# if it's not sticking out, fill the space with ' '
elif offset > 0:
read += offset * ' '
# compare the subject and the read, make a string
# called 'comparison', which contains a '.' if the bases
# are equal and the letter of the read if they are not.
comparison = ''
for readBase, subjectBase in zip(read, subject):
if readBase == ' ':
comparison += ' '
elif readBase == subjectBase:
comparison += '.'
elif readBase != subjectBase:
comparison += readBase
index += 1
que = '%s \t %s' % (queryTitle, comparison)
result.append(que)
# sanity checks
assert (len(comparison) == len(subject)), (
'%d != %d' % (len(comparison), len(subject)))
index = 0
if comparison[index] == ' ':
index += 1
else:
start = index - 1
assert (start == queryStart or start == -1), (
'%s != %s or %s != -1' % (start, queryStart, start))
return result
def getAPOBECFrequencies(dotAlignment, orig, new, pattern):
"""
Gets mutation frequencies if they are in a certain pattern.
@param dotAlignment: result from calling basePlotter
@param orig: A C{str}, naming the original base
@param new: A C{str}, what orig was mutated to
@param pattern: A C{str}m which pattern we're looking for
(must be one of 'cPattern', 'tPattern')
"""
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right pattern
if pattern == 'cPattern':
patterns = cPattern
middleBase = 'C'
else:
patterns = tPattern
middleBase = 'T'
# generate the freqs dict with the right pattern
freqs = defaultdict(int)
for pattern in patterns:
freqs[pattern] = 0
# get the subject sequence from dotAlignment
subject = dotAlignment[0].split('\t')[3]
# exclude the subject from the dotAlignment, so just the queries
# are left over
queries = dotAlignment[1:]
for item in queries:
query = item.split('\t')[1]
index = 0
for queryBase in query:
qBase = query[index]
sBase = subject[index]
if qBase == new and sBase == orig:
try:
plusSb = subject[index + 1]
minusSb = subject[index - 1]
except IndexError:
plusSb = 'end'
motif = '%s%s%s' % (minusSb, middleBase, plusSb)
if motif in freqs:
freqs[motif] += 1
index += 1
return freqs
def getCompleteFreqs(blastHits):
"""
Make a dictionary which collects all mutation frequencies from
all reads.
Calls basePlotter to get dotAlignment, which is passed to
getAPOBECFrequencies with the respective parameter, to collect
the frequencies.
@param blastHits: A L{dark.blast.BlastHits} instance.
"""
allFreqs = {}
for title in blastHits.titles:
allFreqs[title] = {
'C>A': {},
'C>G': {},
'C>T': {},
'T>A': {},
'T>C': {},
'T>G': {},
}
basesPlotted = basePlotter(blastHits, title)
for mutation in allFreqs[title]:
orig = mutation[0]
new = mutation[2]
if orig == 'C':
pattern = 'cPattern'
else:
pattern = 'tPattern'
freqs = getAPOBECFrequencies(basesPlotted, orig, new, pattern)
allFreqs[title][mutation] = freqs
numberOfReads = len(blastHits.titles[title]['plotInfo']['items'])
allFreqs[title]['numberOfReads'] = numberOfReads
allFreqs[title]['bitScoreMax'] = blastHits.titles[
title]['plotInfo']['bitScoreMax']
return allFreqs
def makeFrequencyGraph(allFreqs, title, substitution, pattern,
color='blue', createFigure=True, showFigure=True,
readsAx=False):
"""
For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param title: A C{str}, title of virus of which frequencies should be
plotted.
@param substitution: A C{str}, which substitution should be plotted;
must be one of 'C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G'.
@param pattern: A C{str}, which pattern we're looking for ( must be
one of 'cPattern', 'tPattern')
@param color: A C{str}, color of bars.
@param createFigure: If C{True}, create a figure.
@param showFigure: If C{True}, show the created figure.
@param readsAx: If not None, use this as the subplot for displaying reads.
"""
cPattern = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG', 'CCT',
'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC', 'TCG', 'TCT']
tPattern = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG', 'CTT',
'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC', 'TTG', 'TTT']
# choose the right pattern
if pattern == 'cPattern':
patterns = cPattern
else:
patterns = tPattern
fig = plt.figure(figsize=(10, 10))
ax = readsAx or fig.add_subplot(111)
# how many bars
N = 16
ind = np.arange(N)
width = 0.4
# make a list in the right order, so that it can be plotted easily
divisor = allFreqs[title]['numberOfReads']
toPlot = allFreqs[title][substitution]
index = 0
data = []
for item in patterns:
newData = toPlot[patterns[index]] / divisor
data.append(newData)
index += 1
# create the bars
ax.bar(ind, data, width, color=color)
maxY = np.max(data) + 5
# axes and labels
if createFigure:
title = title.split('|')[4][:50]
ax.set_title('%s \n %s' % (title, substitution), fontsize=20)
ax.set_ylim(0, maxY)
ax.set_ylabel('Absolute Number of Mutations', fontsize=16)
ax.set_xticks(ind + width)
ax.set_xticklabels(patterns, rotation=45, fontsize=8)
if createFigure is False:
ax.set_xticks(ind + width)
ax.set_xticklabels(patterns, rotation=45, fontsize=0)
else:
if showFigure:
plt.show()
return maxY
def makeFrequencyPanel(allFreqs, patientName):
"""
For a title, make a graph showing the frequencies.
@param allFreqs: result from getCompleteFreqs
@param patientName: A C{str}, title for the panel
"""
titles = sorted(
iter(allFreqs.keys()),
key=lambda title: (allFreqs[title]['bitScoreMax'], title))
origMaxY = 0
cols = 6
rows = len(allFreqs)
figure, ax = plt.subplots(rows, cols, squeeze=False)
substitutions = ['C>A', 'C>G', 'C>T', 'T>A', 'T>C', 'T>G']
colors = ['blue', 'black', 'red', 'yellow', 'green', 'orange']
for i, title in enumerate(titles):
for index in range(6):
for subst in allFreqs[str(title)]:
substitution = substitutions[index]
print(i, index, title, 'substitution', substitutions[index])
if substitution[0] == 'C':
pattern = 'cPattern'
else:
pattern = 'tPattern'
maxY = makeFrequencyGraph(allFreqs, title, substitution,
pattern, color=colors[index],
createFigure=False, showFigure=False,
readsAx=ax[i][index])
if maxY > origMaxY:
origMaxY = maxY
# add title for individual plot.
# if used for other viruses, this will have to be adapted.
if index == 0:
gi = title.split('|')[1]
titles = title.split(' ')
try:
typeIndex = titles.index('type')
except ValueError:
typeNumber = 'gi: %s' % gi
else:
typeNumber = titles[typeIndex + 1]
ax[i][index].set_ylabel(('Type %s \n maxBitScore: %s' % (
typeNumber, allFreqs[title]['bitScoreMax'])), fontsize=10)
# add xAxis tick labels
if i == 0:
ax[i][index].set_title(substitution, fontsize=13)
if i == len(allFreqs) - 1 or i == (len(allFreqs) - 1) / 2:
if index < 3:
pat = ['ACA', 'ACC', 'ACG', 'ACT', 'CCA', 'CCC', 'CCG',
'CCT', 'GCA', 'GCC', 'GCG', 'GCT', 'TCA', 'TCC',
'TCG', 'TCT']
else:
pat = ['ATA', 'ATC', 'ATG', 'ATT', 'CTA', 'CTC', 'CTG',
'CTT', 'GTA', 'GTC', 'GTG', 'GTT', 'TTA', 'TTC',
'TTG', 'TTT']
ax[i][index].set_xticklabels(pat, rotation=45, fontsize=8)
# make Y-axis equal
for i, title in enumerate(allFreqs):
for index in range(6):
a = ax[i][index]
a.set_ylim([0, origMaxY])
# add title of whole panel
figure.suptitle('Mutation Signatures in %s' % patientName, fontsize=20)
figure.set_size_inches(5 * cols, 3 * rows, forward=True)
figure.show()
return allFreqs
def mutateString(original, n, replacements='acgt'):
"""
Mutate C{original} in C{n} places with chars chosen from C{replacements}.
@param original: The original C{str} to mutate.
@param n: The C{int} number of locations to mutate.
@param replacements: The C{str} of replacement letters.
@return: A new C{str} with C{n} places of C{original} mutated.
@raises ValueError: if C{n} is too high, or C{replacement} contains
duplicates, or if no replacement can be made at a certain locus
because C{replacements} is of length one, or if C{original} is of
zero length.
"""
if not original:
raise ValueError('Empty original string passed.')
if n > len(original):
raise ValueError('Cannot make %d mutations in a string of length %d' %
(n, len(original)))
if len(replacements) != len(set(replacements)):
raise ValueError('Replacement string contains duplicates')
if len(replacements) == 1 and original.find(replacements) != -1:
raise ValueError('Impossible replacement')
result = list(original)
length = len(original)
for offset in range(length):
if uniform(0.0, 1.0) < float(n) / (length - offset):
# Mutate.
while True:
new = choice(replacements)
if new != result[offset]:
result[offset] = new
break
n -= 1
if n == 0:
break
return ''.join(result)
|
mit
| -974,948,910,823,843,200
| 35.64588
| 79
| 0.544427
| false
| 3.942967
| false
| false
| false
|
nati/fun
|
cube.py
|
1
|
4119
|
import copy
import math
import re
import subprocess
import sys
import time
ret = subprocess.check_output(["resize"])
m = re.match("COLUMNS=(\d+);\nLINES=(\d+);", ret)
WIDTH = int(m.group(1))
HEIGHT = int(m.group(2))
SCALE = 7
X = 0
Y = 1
Z = 2
POINTS = [
[-1, -1, 1],
[-1, 1, 1],
[1, 1, 1],
[1, -1, 1],
[-1, -1, -1],
[-1, 1, -1],
[1, 1, -1],
[1, -1, -1]
]
LINES = [
[0, 1],
[1, 2],
[2, 3],
[0, 3],
[4, 5],
[5, 6],
[6, 7],
[7, 4],
[0, 4],
[1, 5],
[2, 6],
[3, 7],
]
POINTS2 = [
[-1, -1, 0],
[-1, 1, 0],
[1, 1, 0],
[1, -1, 0],
[0, 0, 3],
]
LINES2 = [
[0, 1],
[1, 2],
[2, 3],
[3, 0],
[0, 4],
[1, 4],
[2, 4],
[3, 4]
]
class Campas(object):
def draw_line(self, p1, p2):
steep = abs(p2[Y] - p1[Y]) > abs(p2[X] - p1[X])
if steep:
p1[X], p1[Y] = p1[Y], p1[X]
p2[X], p2[Y] = p2[Y], p2[X]
if p1[X] > p2[X]:
p1[X], p2[X] = p2[X], p1[X]
p1[Y], p2[Y] = p2[Y], p1[Y]
dx = p2[X] - p1[X]
dy = abs(p2[Y] - p1[Y])
error = dx / 2.0
y = p1[Y]
if p1[Y] < p2[Y]:
ystep = 1
else:
ystep = -1
for x in range(p1[X], p2[X]):
if steep:
self.draw_point([y, x])
else:
self.draw_point([x, y])
error = error - dy
if error < 0:
y = y + ystep
error = error + dx
def draw_point(self, p, char="#"):
if p[X] >= WIDTH or 0 > p[X]:
return
if p[Y] >= HEIGHT or 0 > p[Y]:
return
sys.stdout.write("\033[%i;%iH%s" % (p[Y], p[X], char))
def clear_screen(self):
sys.stdout.write("\033[2J")
def flush(self):
sys.stdout.flush()
class Poly(object):
points = []
lines = []
def __init__(self, points, lines, campas):
self.points = copy.deepcopy(points)
self.lines = copy.deepcopy(lines)
self.campas = campas
self.base_point = [0, 0, 1]
def mult(self, transform):
self.points = [self.mult_m_p(transform, p) for p in self.points]
def move(self, axis, distance):
self.base_point[axis] = distance
def mult_m_p(self, m, p):
x, y, z = p
r1 = sum([m[0][0] * x, m[0][1] * y, m[0][2] * z])
r2 = sum([m[1][0] * x, m[1][1] * y, m[1][2] * z])
r3 = sum([m[2][0] * x, m[2][1] * y, m[2][2] * z])
return [r1, r2, r3]
def projection(self, p):
cx, cy = WIDTH / 2, HEIGHT / 2
x = (p[X] + self.base_point[X]) * SCALE / self.base_point[Z] + cx
y = (p[Y] + self.base_point[Y]) * SCALE / self.base_point[Z] + cy
return [int(x), int(y)]
def draw(self):
if self.base_point[Z] <= 0:
return
for point in self.points:
self.campas.draw_point(self.projection(point))
for line in self.lines:
self.campas.draw_line(self.projection(self.points[line[0]]),
self.projection(self.points[line[1]]))
def matrix_rotate_x(a):
return [[1, 0, 0],
[0, math.cos(a), -math.sin(a)],
[0, math.sin(a), math.cos(a)]]
def matrix_rotate_y(a):
return [[math.cos(a), 0, math.sin(a)],
[0, 1, 0],
[-math.sin(a), 0, math.cos(a)]]
campas = Campas()
campas.clear_screen()
cube = Poly(POINTS, LINES, campas)
cube2 = Poly(POINTS2, LINES2, campas)
cube3 = Poly(POINTS, LINES, campas)
i = math.pi / 100.0
j = 0
mx = matrix_rotate_x(i * 1)
my = matrix_rotate_y(i * 5)
while True:
campas.clear_screen()
cube.mult(mx)
cube.mult(my)
cube3.mult(mx)
cube3.mult(my)
cube.move(Z, math.sin(j) + 1.5)
cube.move(X, 10 * math.cos(j))
cube3.move(Z, math.sin(j + math.pi / 2) + 1.5)
cube3.move(Y, 3 * math.cos(j + math.pi / 2))
j += math.pi / 50.0
cube2.mult(mx)
cube2.mult(my)
cube2.move(Z, 1.5)
cube.draw()
cube2.draw()
cube3.draw()
campas.flush()
time.sleep(0.1)
|
apache-2.0
| -4,906,687,155,164,076,000
| 20.793651
| 73
| 0.453265
| false
| 2.525445
| false
| false
| false
|
chemiron/aiopool
|
aiopool/fork.py
|
1
|
6082
|
import asyncio
import logging
import os
import signal
from struct import Struct
import time
from .base import (WorkerProcess, ChildProcess,
IDLE_CHECK, IDLE_TIME)
MSG_HEAD = 0x0
MSG_PING = 0x1
MSG_PONG = 0x2
MSG_CLOSE = 0x3
PACK_MSG = Struct('!BB').pack
UNPACK_MSG = Struct('!BB').unpack
logger = logging.getLogger(__name__)
class ConnectionClosedError(Exception):
pass
@asyncio.coroutine
def connect_write_pipe(file):
loop = asyncio.get_event_loop()
transport, _ = yield from loop.connect_write_pipe(asyncio.Protocol, file)
return PipeWriter(transport)
@asyncio.coroutine
def connect_read_pipe(file):
loop = asyncio.get_event_loop()
pipe_reader = PipeReader(loop=loop)
transport, _ = yield from loop.connect_read_pipe(
lambda: PipeReadProtocol(pipe_reader), file)
pipe_reader.transport = transport
return pipe_reader
class PipeWriter:
def __init__(self, transport):
self.transport = transport
def _send(self, msg):
self.transport.write(PACK_MSG(MSG_HEAD, msg))
def ping(self):
self._send(MSG_PING)
def pong(self):
self._send(MSG_PONG)
def stop(self):
self._send(MSG_CLOSE)
def close(self):
if self.transport is not None:
self.transport.close()
class PipeReadProtocol(asyncio.Protocol):
def __init__(self, reader):
self.reader = reader
def data_received(self, data):
self.reader.feed(data)
def connection_lost(self, exc):
self.reader.close()
class PipeReader:
closed = False
transport = None
def __init__(self, loop):
self.loop = loop
self._waiters = asyncio.Queue()
def close(self):
self.closed = True
while not self._waiters.empty():
waiter = self._waiters.get_nowait()
if not waiter.done():
waiter.set_exception(ConnectionClosedError())
if self.transport is not None:
self.transport.close()
def feed(self, data):
asyncio.async(self._feed_waiter(data))
@asyncio.coroutine
def _feed_waiter(self, data):
waiter = yield from self._waiters.get()
waiter.set_result(data)
@asyncio.coroutine
def read(self):
if self.closed:
raise ConnectionClosedError()
waiter = asyncio.Future(loop=self.loop)
yield from self._waiters.put(waiter)
data = yield from waiter
hdr, msg = UNPACK_MSG(data)
if hdr == MSG_HEAD:
return msg
class ForkChild(ChildProcess):
_heartbeat_task = None
def __init__(self, parent_read, parent_write, loader, **options):
ChildProcess.__init__(self, loader, **options)
self.parent_read = parent_read
self.parent_write = parent_write
@asyncio.coroutine
def on_start(self):
self._heartbeat_task = asyncio.Task(self.heartbeat())
def stop(self):
if self._heartbeat_task is not None:
self._heartbeat_task.cancel()
ChildProcess.stop(self)
@asyncio.coroutine
def heartbeat(self):
# setup pipes
reader = yield from connect_read_pipe(
os.fdopen(self.parent_read, 'rb'))
writer = yield from connect_write_pipe(
os.fdopen(self.parent_write, 'wb'))
while True:
try:
msg = yield from reader.read()
except ConnectionClosedError:
logger.info('Parent is dead, {} stopping...'
''.format(os.getpid()))
break
if msg == MSG_PING:
writer.pong()
elif msg.tp == MSG_CLOSE:
break
reader.close()
writer.close()
self.stop()
class ForkWorker(WorkerProcess):
pid = ping = None
reader = writer = None
chat_task = heartbeat_task = None
def start_child(self):
parent_read, child_write = os.pipe()
child_read, parent_write = os.pipe()
pid = os.fork()
if pid:
# parent
os.close(parent_read)
os.close(parent_write)
asyncio.async(self.connect(pid, child_write, child_read))
else:
# child
os.close(child_write)
os.close(child_read)
# cleanup after fork
asyncio.set_event_loop(None)
# setup process
process = ForkChild(parent_read, parent_write, self.loader)
process.start()
def kill_child(self):
self.chat_task.cancel()
self.heartbeat_task.cancel()
self.reader.close()
self.writer.close()
try:
os.kill(self.pid, signal.SIGTERM)
os.waitpid(self.pid, 0)
except ProcessLookupError:
pass
@asyncio.coroutine
def heartbeat(self, writer):
idle_time = self.options.get('idle_time', IDLE_TIME)
idle_check = self.options.get('idle_check', IDLE_CHECK)
while True:
yield from asyncio.sleep(idle_check)
if (time.monotonic() - self.ping) < idle_time:
writer.ping()
else:
self.restart()
return
@asyncio.coroutine
def chat(self, reader):
while True:
try:
msg = yield from reader.read()
except ConnectionClosedError:
self.restart()
return
if msg == MSG_PONG:
self.ping = time.monotonic()
@asyncio.coroutine
def connect(self, pid, up_write, down_read):
# setup pipes
reader = yield from connect_read_pipe(
os.fdopen(down_read, 'rb'))
writer = yield from connect_write_pipe(
os.fdopen(up_write, 'wb'))
# store info
self.pid = pid
self.ping = time.monotonic()
self.reader = reader
self.writer = writer
self.chat_task = asyncio.Task(self.chat(reader))
self.heartbeat_task = asyncio.Task(self.heartbeat(writer))
|
mit
| 982,928,408,585,555,200
| 24.447699
| 77
| 0.57366
| false
| 4.017173
| false
| false
| false
|
hypebeast/etapi
|
etapi/utils.py
|
1
|
1765
|
# -*- coding: utf-8 -*-
'''Helper utilities and decorators.'''
import time
from flask import flash
def flash_errors(form, category="warning"):
'''Flash all errors for a form.'''
for field, errors in form.errors.items():
for error in errors:
flash("{0} - {1}"
.format(getattr(form, field).label.text, error), category)
def pretty_date(dt, default=None):
"""
Returns string representing "time since" e.g.
3 days ago, 5 hours ago etc.
Ref: https://bitbucket.org/danjac/newsmeme/src/a281babb9ca3/newsmeme/
"""
if default is None:
default = 'just now'
now = datetime.utcnow()
diff = now - dt
periods = (
(diff.days / 365, 'year', 'years'),
(diff.days / 30, 'month', 'months'),
(diff.days / 7, 'week', 'weeks'),
(diff.days, 'day', 'days'),
(diff.seconds / 3600, 'hour', 'hours'),
(diff.seconds / 60, 'minute', 'minutes'),
(diff.seconds, 'second', 'seconds'),
)
for period, singular, plural in periods:
if not period:
continue
if period == 1:
return u'%d %s ago' % (period, singular)
else:
return u'%d %s ago' % (period, plural)
return default
def pretty_seconds_to_hhmmss(seconds):
if not seconds:
return None
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "%d h %d m %s s" % (h, m, s)
def pretty_seconds_to_hhmm(seconds):
if not seconds:
return None
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "%d h %d m" % (h, m)
def pretty_seconds_to_hh(seconds):
if not seconds:
return None
m, s = divmod(seconds, 60)
h, m = divmod(m, 60)
return "%d h" % (h)
|
bsd-3-clause
| -7,001,446,943,259,879,000
| 24.955882
| 78
| 0.549575
| false
| 3.374761
| false
| false
| false
|
DBeath/flask-feedrsub
|
tests/period_test.py
|
1
|
1488
|
from datetime import datetime
from dateutil.relativedelta import relativedelta
from feedrsub.database import db
from feedrsub.models.period import PERIOD, Period
from feedrsub.models.populate_db import populate_periods
def test_populate_periods(session):
populate_periods()
daily = Period.query.filter_by(name=PERIOD.DAILY).first()
assert daily.name == PERIOD.DAILY
immediate = Period.query.filter_by(name=PERIOD.IMMEDIATE).first()
assert immediate.name == PERIOD.IMMEDIATE
weekly = Period.query.filter_by(name=PERIOD.WEEKLY).first()
assert weekly.name == PERIOD.WEEKLY
monthly = Period.query.filter_by(name=PERIOD.MONTHLY).first()
assert monthly.name == PERIOD.MONTHLY
def test_period_creation(session):
period_desc = "A Yearly period"
period_name = "YEARLY"
period = Period(period_name, period_desc)
db.session.add(period)
db.session.commit()
yearly = Period.query.filter_by(name=period_name).first()
assert yearly.name == period_name
assert yearly.description == period_desc
def test_get_from_date_with_name(session):
now = datetime.utcnow()
past = now - relativedelta(days=1)
from_date = Period.get_from_date(PERIOD.DAILY, now)
assert from_date == past
def test_get_from_date_with_period(session):
now = datetime.utcnow()
past = now - relativedelta(days=1)
period = Period(name=PERIOD.DAILY)
from_date = Period.get_from_date(period, now)
assert from_date == past
|
mit
| 7,589,990,972,609,637,000
| 27.615385
| 69
| 0.715054
| false
| 3.43649
| false
| false
| false
|
nigelb/Static-UPnP
|
examples/Chromecast/StaticUPnP_StaticServices.py
|
1
|
3345
|
# static_upnp responds to upnp search requests with statically configures responses.
# Copyright (C) 2016 NigelB
#
# 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 socket
from dnslib import DNSQuestion, QTYPE
from static_upnp.chromecast_helpers import get_chromecast_uuid, get_date, get_chromecast_mdns_response
from static_upnp.chromecast_helpers import get_service_descriptor, get_chromecast_friendly_name
from static_upnp.mDNS import StaticMDNDService
from static_upnp.static import StaticService
OK = """HTTP/1.1 200 OK
CACHE-CONTROL: max-age={max_age}
DATE: {date}
EXT:
LOCATION: http://{ip}:{port}/ssdp/device-desc.xml
OPT: "http://schemas.upnp.org/upnp/1/0/"; ns=01
01-NLS: 161d2e68-1dd2-11b2-9fd5-f9d9dc2ad10b
SERVER: Linux/3.8.13+, UPnP/1.0, Portable SDK for UPnP devices/1.6.18
X-User-Agent: redsonic
ST: {st}
USN: {usn}
BOOTID.UPNP.ORG: 4
CONFIGID.UPNP.ORG: 2
"""
NOTIFY = """NOTIFY * HTTP/1.1
HOST: 239.255.255.250:1900
CACHE-CONTROL: max-age=1800
LOCATION: http://{ip}:{port}/ssdp/device-desc.xml
NT: {st}
NTS: {nts}
OPT: "http://schemas.upnp.org/upnp/1/0/"; ns=01
01-NLS: 161d2e68-1dd2-11b2-9fd5-f9d9dc2ad10b
SERVER: Linux/3.8.13+, UPnP/1.0, Portable SDK for UPnP devices/1.6.18
X-User-Agent: redsonic
USN: {uuid}
"""
chromecast_ip = socket.gethostbyname_ex("Chromecast")[2][0]
chromecast_port = 8008
chromecast_service_descriptor = get_service_descriptor(chromecast_ip, chromecast_port)
chromecast_uuid = get_chromecast_uuid(chromecast_service_descriptor)
chromecast_friendly_name = get_chromecast_friendly_name(chromecast_service_descriptor)
chromecast_bs = "XXXXXXXXXXXX"
chromecast_cd = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
services = [
StaticService({
"ip": chromecast_ip,
"port": chromecast_port,
"uuid": chromecast_uuid,
"max_age": "1800",
"date": get_date
}, 1024,
OK=OK,
NOTIFY=NOTIFY,
services=[
{
"st": "upnp:rootdevice",
"usn": "uuid:{uuid}::{st}"
},
{
"st": "uuid:{uuid}",
"usn": "uuid:{uuid}"
},
{
"st": "urn:dial-multiscreen-org:device:dial:1",
"usn": "uuid:{uuid}::{st}"
},
{
"st": "urn:dial-multiscreen-org:service:dial:1",
"usn": "uuid:{uuid}::{st}"
},
])
]
mdns_services=[StaticMDNDService(
response_generator=lambda query: get_chromecast_mdns_response(query, chromecast_ip, chromecast_uuid, chromecast_friendly_name, chromecast_bs, chromecast_cd),
dns_question=DNSQuestion(qname="_googlecast._tcp.local", qtype=QTYPE.PTR, qclass=32769)
)]
|
gpl-2.0
| 871,185,580,901,961,200
| 31.794118
| 161
| 0.676233
| false
| 3.117428
| false
| false
| false
|
ponty/MyElectronicProjects
|
pavement.py
|
1
|
1718
|
from easyprocess import Proc
from paver.easy import *
import paver.doctools
import paver.virtual
import paver.misctasks
from paved import *
from paved.dist import *
from paved.util import *
from paved.docs import *
from paved.pycheck import *
from paved.pkg import *
options(
sphinx=Bunch(
docroot='docs',
builddir="_build",
),
# pdf=Bunch(
# builddir='_build',
# builder='latex',
# ),
)
options.paved.clean.rmdirs += ['.tox',
'dist',
'build',
]
options.paved.clean.patterns += ['*.pickle',
'*.doctree',
'*.gz',
'nosetests.xml',
'sloccount.sc',
'*.pdf', '*.tex',
'*_sch_*.png',
'*_brd_*.png',
'*.b#*', '*.s#*', # eagle
#'*.pro',
'*.hex',
'*.zip',
'distribute_setup.py',
'*.bak',
# kicad
'$savepcb.brd',
'*.erc',
'*.000',
]
options.paved.dist.manifest.include.remove('distribute_setup.py')
options.paved.dist.manifest.include.remove('paver-minilib.zip')
@task
@needs(
# 'clean',
'cog',
'html',
'pdf',
)
def alltest():
'all tasks to check'
pass
|
bsd-2-clause
| 2,015,404,359,761,255,000
| 25.430769
| 65
| 0.360885
| false
| 4.569149
| false
| false
| false
|
GoogleCloudPlatform/python-docs-samples
|
appengine/standard/endpoints-frameworks-v2/quickstart/main_test.py
|
1
|
1894
|
# Copyright 2016 Google Inc. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from endpoints import message_types
import mock
import main
def test_list_greetings(testbed):
api = main.GreetingApi()
response = api.list_greetings(message_types.VoidMessage())
assert len(response.items) == 2
def test_get_greeting(testbed):
api = main.GreetingApi()
request = main.GreetingApi.get_greeting.remote.request_type(id=1)
response = api.get_greeting(request)
assert response.message == 'goodbye world!'
def test_multiply_greeting(testbed):
api = main.GreetingApi()
request = main.GreetingApi.multiply_greeting.remote.request_type(
times=4,
message='help I\'m trapped in a test case.')
response = api.multiply_greeting(request)
assert response.message == 'help I\'m trapped in a test case.' * 4
def test_authed_greet(testbed):
api = main.AuthedGreetingApi()
with mock.patch('main.endpoints.get_current_user') as user_mock:
user_mock.return_value = None
response = api.greet(message_types.VoidMessage())
assert response.message == 'Hello, Anonymous'
user_mock.return_value = mock.Mock()
user_mock.return_value.email.return_value = 'user@example.com'
response = api.greet(message_types.VoidMessage())
assert response.message == 'Hello, user@example.com'
|
apache-2.0
| -4,486,417,427,585,140,700
| 34.074074
| 74
| 0.712777
| false
| 3.663443
| true
| false
| false
|
OSU-CS-325/Project_Two_Coin_Change
|
run-files/analysisQ7.py
|
1
|
2957
|
import sys
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import random
import datetime
# Import the three change making algorithms
sys.path.insert(0, "../divide-conquer/")
sys.path.insert(0, "../dynamic-programming")
sys.path.insert(0, "../greedy")
from changeslow import changeslow
from changegreedy import changegreedy
from changedp import changedp
### QUESTION 7 ###
def Q7(slow, minChange, maxChange):
lenV = []
runtimeGreedy = []
runtimeDP = []
runtimeSlow = []
numExp = 10
maxRange = 1000
if (slow):
maxRange = 10 # some much smaller number
for i in range(1, maxRange): # V can be of length 1 to (maxRange - 1)
print "\n------ running V length=" + str(i) + "------"
lenV.append(i)
#print "lenV:", lenV
runtimeGreedy.append(0)
runtimeDP.append(0)
runtimeSlow.append(0)
for j in range(numExp): # run numExp experiments for this length of V
print "\n ---- running experiment=" + str(j + 1) + " ----"
coinArray = []
for k in range(i): # generate V of size i [1, rand, ..., rand, max=1 + 5*(maxRange-2)]
if (k == 0):
coinArray.append(1)
else:
randFrom = coinArray[len(coinArray) - 1] + 1
randTo = coinArray[len(coinArray) - 1] + 5
coinArray.append(random.randint(randFrom, randTo))
change = random.randint(minChange, maxChange)
#print " coinArray:", coinArray
#print " change:", change
print " running greedy..."
start = datetime.datetime.now()
_, _ = changegreedy(coinArray, change)
end = datetime.datetime.now()
delta = end - start
delta = int(delta.total_seconds() * 1000000)
print " " + str(delta)
runtimeGreedy[i - 1] += delta
print " running DP..."
start = datetime.datetime.now()
_, _ = changedp(coinArray, change)
end = datetime.datetime.now()
delta = end - start
delta = int(delta.total_seconds() * 1000000)
print " " + str(delta)
runtimeDP[i - 1] += delta
if (slow):
print " running slow..."
start = datetime.datetime.now()
_, _ = changeslow(coinArray, change)
end = datetime.datetime.now()
delta = end - start
delta = int(delta.total_seconds() * 1000000)
print " " + str(delta)
runtimeSlow[i - 1] += delta
runtimeGreedy[i - 1] /= numExp
runtimeDP[i - 1] /= numExp
if (slow):
runtimeSlow[i - 1] /= numExp
plt.figure(21)
plt.plot(lenV, runtimeGreedy, 'b-', linewidth=2.0, label='Greedy')
plt.plot(lenV, runtimeDP, 'r--', linewidth=2.0, label='DP')
if (slow):
plt.plot(lenV, runtimeSlow, 'g-.', linewidth=2.0, label='Slow')
plt.legend(loc='upper left')
plt.title('Runtime vs len(V[]) for randomized V[] and A')
plt.ylabel('Avg. Runtime (10^-6 sec)')
plt.xlabel('len(V[])')
plt.grid(True)
if (slow):
plt.savefig('img/Q7slow_runtime.png', bbox_inches='tight')
else:
plt.savefig('img/Q7_runtime.png', bbox_inches='tight')
def main():
Q7(False, 100, 100)
#Q7(True)
if __name__ == "__main__":
main()
|
mit
| 992,061,664,401,384,600
| 26.37963
| 89
| 0.631721
| false
| 2.882066
| false
| false
| false
|
mikedh/trimesh
|
trimesh/creation.py
|
1
|
40606
|
"""
creation.py
--------------
Create meshes from primitives, or with operations.
"""
from .base import Trimesh
from .constants import log, tol
from .geometry import faces_to_edges, align_vectors, plane_transform
from . import util
from . import grouping
from . import triangles
from . import transformations as tf
import numpy as np
import collections
try:
# shapely is a soft dependency
from shapely.geometry import Polygon
from shapely.wkb import loads as load_wkb
except BaseException as E:
# shapely will sometimes raise OSErrors
# on import rather than just ImportError
from . import exceptions
# re-raise the exception when someone tries
# to use the module that they don't have
Polygon = exceptions.closure(E)
load_wkb = exceptions.closure(E)
def revolve(linestring,
angle=None,
sections=None,
transform=None,
**kwargs):
"""
Revolve a 2D line string around the 2D Y axis, with a result with
the 2D Y axis pointing along the 3D Z axis.
This function is intended to handle the complexity of indexing
and is intended to be used to create all radially symmetric primitives,
eventually including cylinders, annular cylinders, capsules, cones,
and UV spheres.
Note that if your linestring is closed, it needs to be counterclockwise
if you would like face winding and normals facing outwards.
Parameters
-------------
linestring : (n, 2) float
Lines in 2D which will be revolved
angle : None or float
Angle in radians to revolve curve by
sections : None or int
Number of sections result should have
If not specified default is 32 per revolution
transform : None or (4, 4) float
Transform to apply to mesh after construction
**kwargs : dict
Passed to Trimesh constructor
Returns
--------------
revolved : Trimesh
Mesh representing revolved result
"""
linestring = np.asanyarray(linestring, dtype=np.float64)
# linestring must be ordered 2D points
if len(linestring.shape) != 2 or linestring.shape[1] != 2:
raise ValueError('linestring must be 2D!')
if angle is None:
# default to closing the revolution
angle = np.pi * 2
closed = True
else:
# check passed angle value
closed = angle >= ((np.pi * 2) - 1e-8)
if sections is None:
# default to 32 sections for a full revolution
sections = int(angle / (np.pi * 2) * 32)
# change to face count
sections += 1
# create equally spaced angles
theta = np.linspace(0, angle, sections)
# 2D points around the revolution
points = np.column_stack((np.cos(theta), np.sin(theta)))
# how many points per slice
per = len(linestring)
# use the 2D X component as radius
radius = linestring[:, 0]
# use the 2D Y component as the height along revolution
height = linestring[:, 1]
# a lot of tiling to get our 3D vertices
vertices = np.column_stack((
np.tile(points, (1, per)).reshape((-1, 2)) *
np.tile(radius, len(points)).reshape((-1, 1)),
np.tile(height, len(points))))
if closed:
# should be a duplicate set of vertices
assert np.allclose(vertices[:per],
vertices[-per:])
# chop off duplicate vertices
vertices = vertices[:-per]
if transform is not None:
# apply transform to vertices
vertices = tf.transform_points(vertices, transform)
# how many slices of the pie
slices = len(theta) - 1
# start with a quad for every segment
# this is a superset which will then be reduced
quad = np.array([0, per, 1,
1, per, per + 1])
# stack the faces for a single slice of the revolution
single = np.tile(quad, per).reshape((-1, 3))
# `per` is basically the stride of the vertices
single += np.tile(np.arange(per), (2, 1)).T.reshape((-1, 1))
# remove any zero-area triangle
# this covers many cases without having to think too much
single = single[triangles.area(vertices[single]) > tol.merge]
# how much to offset each slice
# note arange multiplied by vertex stride
# but tiled by the number of faces we actually have
offset = np.tile(np.arange(slices) * per,
(len(single), 1)).T.reshape((-1, 1))
# stack a single slice into N slices
stacked = np.tile(single.ravel(), slices).reshape((-1, 3))
if tol.strict:
# make sure we didn't screw up stacking operation
assert np.allclose(stacked.reshape((-1, single.shape[0], 3)) - single, 0)
# offset stacked and wrap vertices
faces = (stacked + offset) % len(vertices)
# create the mesh from our vertices and faces
mesh = Trimesh(vertices=vertices, faces=faces,
**kwargs)
# strict checks run only in unit tests
if (tol.strict and
np.allclose(radius[[0, -1]], 0.0) or
np.allclose(linestring[0], linestring[-1])):
# if revolved curve starts and ends with zero radius
# it should really be a valid volume, unless the sign
# reversed on the input linestring
assert mesh.is_volume
return mesh
def extrude_polygon(polygon,
height,
transform=None,
triangle_args=None,
**kwargs):
"""
Extrude a 2D shapely polygon into a 3D mesh
Parameters
----------
polygon : shapely.geometry.Polygon
2D geometry to extrude
height : float
Distance to extrude polygon along Z
triangle_args : str or None
Passed to triangle
**kwargs:
passed to Trimesh
Returns
----------
mesh : trimesh.Trimesh
Resulting extrusion as watertight body
"""
# create a triangulation from the polygon
vertices, faces = triangulate_polygon(
polygon, triangle_args=triangle_args, **kwargs)
# extrude that triangulation along Z
mesh = extrude_triangulation(vertices=vertices,
faces=faces,
height=height,
transform=transform,
**kwargs)
return mesh
def sweep_polygon(polygon,
path,
angles=None,
**kwargs):
"""
Extrude a 2D shapely polygon into a 3D mesh along an
arbitrary 3D path. Doesn't handle sharp curvature well.
Parameters
----------
polygon : shapely.geometry.Polygon
Profile to sweep along path
path : (n, 3) float
A path in 3D
angles : (n,) float
Optional rotation angle relative to prior vertex
at each vertex
Returns
-------
mesh : trimesh.Trimesh
Geometry of result
"""
path = np.asanyarray(path, dtype=np.float64)
if not util.is_shape(path, (-1, 3)):
raise ValueError('Path must be (n, 3)!')
# Extract 2D vertices and triangulation
verts_2d = np.array(polygon.exterior)[:-1]
base_verts_2d, faces_2d = triangulate_polygon(polygon, **kwargs)
n = len(verts_2d)
# Create basis for first planar polygon cap
x, y, z = util.generate_basis(path[0] - path[1])
tf_mat = np.ones((4, 4))
tf_mat[:3, :3] = np.c_[x, y, z]
tf_mat[:3, 3] = path[0]
# Compute 3D locations of those vertices
verts_3d = np.c_[verts_2d, np.zeros(n)]
verts_3d = tf.transform_points(verts_3d, tf_mat)
base_verts_3d = np.c_[base_verts_2d,
np.zeros(len(base_verts_2d))]
base_verts_3d = tf.transform_points(base_verts_3d,
tf_mat)
# keep matching sequence of vertices and 0- indexed faces
vertices = [base_verts_3d]
faces = [faces_2d]
# Compute plane normals for each turn --
# each turn induces a plane halfway between the two vectors
v1s = util.unitize(path[1:-1] - path[:-2])
v2s = util.unitize(path[1:-1] - path[2:])
norms = np.cross(np.cross(v1s, v2s), v1s + v2s)
norms[(norms == 0.0).all(1)] = v1s[(norms == 0.0).all(1)]
norms = util.unitize(norms)
final_v1 = util.unitize(path[-1] - path[-2])
norms = np.vstack((norms, final_v1))
v1s = np.vstack((v1s, final_v1))
# Create all side walls by projecting the 3d vertices into each plane
# in succession
for i in range(len(norms)):
verts_3d_prev = verts_3d
# Rotate if needed
if angles is not None:
tf_mat = tf.rotation_matrix(angles[i],
norms[i],
path[i])
verts_3d_prev = tf.transform_points(verts_3d_prev,
tf_mat)
# Project vertices onto plane in 3D
ds = np.einsum('ij,j->i', (path[i + 1] - verts_3d_prev), norms[i])
ds = ds / np.dot(v1s[i], norms[i])
verts_3d_new = np.einsum('i,j->ij', ds, v1s[i]) + verts_3d_prev
# Add to face and vertex lists
new_faces = [[i + n, (i + 1) % n, i] for i in range(n)]
new_faces.extend([[(i - 1) % n + n, i + n, i] for i in range(n)])
# save faces and vertices into a sequence
faces.append(np.array(new_faces))
vertices.append(np.vstack((verts_3d, verts_3d_new)))
verts_3d = verts_3d_new
# do the main stack operation from a sequence to (n,3) arrays
# doing one vstack provides a substantial speedup by
# avoiding a bunch of temporary allocations
vertices, faces = util.append_faces(vertices, faces)
# Create final cap
x, y, z = util.generate_basis(path[-1] - path[-2])
vecs = verts_3d - path[-1]
coords = np.c_[np.einsum('ij,j->i', vecs, x),
np.einsum('ij,j->i', vecs, y)]
base_verts_2d, faces_2d = triangulate_polygon(Polygon(coords))
base_verts_3d = (np.einsum('i,j->ij', base_verts_2d[:, 0], x) +
np.einsum('i,j->ij', base_verts_2d[:, 1], y)) + path[-1]
faces = np.vstack((faces, faces_2d + len(vertices)))
vertices = np.vstack((vertices, base_verts_3d))
return Trimesh(vertices, faces)
def extrude_triangulation(vertices,
faces,
height,
transform=None,
**kwargs):
"""
Extrude a 2D triangulation into a watertight mesh.
Parameters
----------
vertices : (n, 2) float
2D vertices
faces : (m, 3) int
Triangle indexes of vertices
height : float
Distance to extrude triangulation
**kwargs : dict
Passed to Trimesh constructor
Returns
---------
mesh : trimesh.Trimesh
Mesh created from extrusion
"""
vertices = np.asanyarray(vertices, dtype=np.float64)
height = float(height)
faces = np.asanyarray(faces, dtype=np.int64)
if not util.is_shape(vertices, (-1, 2)):
raise ValueError('Vertices must be (n,2)')
if not util.is_shape(faces, (-1, 3)):
raise ValueError('Faces must be (n,3)')
if np.abs(height) < tol.merge:
raise ValueError('Height must be nonzero!')
# make sure triangulation winding is pointing up
normal_test = triangles.normals(
[util.stack_3D(vertices[faces[0]])])[0]
normal_dot = np.dot(normal_test,
[0.0, 0.0, np.sign(height)])[0]
# make sure the triangulation is aligned with the sign of
# the height we've been passed
if normal_dot < 0.0:
faces = np.fliplr(faces)
# stack the (n,3) faces into (3*n, 2) edges
edges = faces_to_edges(faces)
edges_sorted = np.sort(edges, axis=1)
# edges which only occur once are on the boundary of the polygon
# since the triangulation may have subdivided the boundary of the
# shapely polygon, we need to find it again
edges_unique = grouping.group_rows(
edges_sorted, require_count=1)
# (n, 2, 2) set of line segments (positions, not references)
boundary = vertices[edges[edges_unique]]
# we are creating two vertical triangles for every 2D line segment
# on the boundary of the 2D triangulation
vertical = np.tile(boundary.reshape((-1, 2)), 2).reshape((-1, 2))
vertical = np.column_stack((vertical,
np.tile([0, height, 0, height],
len(boundary))))
vertical_faces = np.tile([3, 1, 2, 2, 1, 0],
(len(boundary), 1))
vertical_faces += np.arange(len(boundary)).reshape((-1, 1)) * 4
vertical_faces = vertical_faces.reshape((-1, 3))
# stack the (n,2) vertices with zeros to make them (n, 3)
vertices_3D = util.stack_3D(vertices)
# a sequence of zero- indexed faces, which will then be appended
# with offsets to create the final mesh
faces_seq = [faces[:, ::-1],
faces.copy(),
vertical_faces]
vertices_seq = [vertices_3D,
vertices_3D.copy() + [0.0, 0, height],
vertical]
# append sequences into flat nicely indexed arrays
vertices, faces = util.append_faces(vertices_seq, faces_seq)
if transform is not None:
# apply transform here to avoid later bookkeeping
vertices = tf.transform_points(
vertices, transform)
# if the transform flips the winding flip faces back
# so that the normals will be facing outwards
if tf.flips_winding(transform):
# fliplr makes arrays non-contiguous
faces = np.ascontiguousarray(np.fliplr(faces))
# create mesh object with passed keywords
mesh = Trimesh(vertices=vertices,
faces=faces,
**kwargs)
# only check in strict mode (unit tests)
if tol.strict:
assert mesh.volume > 0.0
return mesh
def triangulate_polygon(polygon,
triangle_args=None,
engine=None,
**kwargs):
"""
Given a shapely polygon create a triangulation using a
python interface to `triangle.c` or mapbox-earcut.
> pip install triangle
> pip install mapbox_earcut
Parameters
---------
polygon : Shapely.geometry.Polygon
Polygon object to be triangulated
triangle_args : str or None
Passed to triangle.triangulate i.e: 'p', 'pq30'
engine : None or str
Any value other than 'earcut' will use `triangle`
Returns
--------------
vertices : (n, 2) float
Points in space
faces : (n, 3) int
Index of vertices that make up triangles
"""
if engine == 'earcut':
from mapbox_earcut import triangulate_float64
# get vertices as sequence where exterior is the first value
vertices = [np.array(polygon.exterior)]
vertices.extend(np.array(i) for i in polygon.interiors)
# record the index from the length of each vertex array
rings = np.cumsum([len(v) for v in vertices])
# stack vertices into (n, 2) float array
vertices = np.vstack(vertices)
# run triangulation
faces = triangulate_float64(vertices, rings).reshape(
(-1, 3)).astype(np.int64).reshape((-1, 3))
return vertices, faces
# do the import here for soft requirement
from triangle import triangulate
# set default triangulation arguments if not specified
if triangle_args is None:
triangle_args = 'p'
# turn the polygon in to vertices, segments, and hole points
arg = _polygon_to_kwargs(polygon)
# run the triangulation
result = triangulate(arg, triangle_args)
return result['vertices'], result['triangles']
def _polygon_to_kwargs(polygon):
"""
Given a shapely polygon generate the data to pass to
the triangle mesh generator
Parameters
---------
polygon : Shapely.geometry.Polygon
Input geometry
Returns
--------
result : dict
Has keys: vertices, segments, holes
"""
if not polygon.is_valid:
raise ValueError('invalid shapely polygon passed!')
def round_trip(start, length):
"""
Given a start index and length, create a series of (n, 2) edges which
create a closed traversal.
Examples
---------
start, length = 0, 3
returns: [(0,1), (1,2), (2,0)]
"""
tiled = np.tile(np.arange(start, start + length).reshape((-1, 1)), 2)
tiled = tiled.reshape(-1)[1:-1].reshape((-1, 2))
tiled = np.vstack((tiled, [tiled[-1][-1], tiled[0][0]]))
return tiled
def add_boundary(boundary, start):
# coords is an (n, 2) ordered list of points on the polygon boundary
# the first and last points are the same, and there are no
# guarantees on points not being duplicated (which will
# later cause meshpy/triangle to shit a brick)
coords = np.array(boundary.coords)
# find indices points which occur only once, and sort them
# to maintain order
unique = np.sort(grouping.unique_rows(coords)[0])
cleaned = coords[unique]
vertices.append(cleaned)
facets.append(round_trip(start, len(cleaned)))
# holes require points inside the region of the hole, which we find
# by creating a polygon from the cleaned boundary region, and then
# using a representative point. You could do things like take the mean of
# the points, but this is more robust (to things like concavity), if
# slower.
test = Polygon(cleaned)
holes.append(np.array(test.representative_point().coords)[0])
return len(cleaned)
# sequence of (n,2) points in space
vertices = collections.deque()
# sequence of (n,2) indices of vertices
facets = collections.deque()
# list of (2) vertices in interior of hole regions
holes = collections.deque()
start = add_boundary(polygon.exterior, 0)
for interior in polygon.interiors:
try:
start += add_boundary(interior, start)
except BaseException:
log.warning('invalid interior, continuing')
continue
# create clean (n,2) float array of vertices
# and (m, 2) int array of facets
# by stacking the sequence of (p,2) arrays
vertices = np.vstack(vertices)
facets = np.vstack(facets).tolist()
# shapely polygons can include a Z component
# strip it out for the triangulation
if vertices.shape[1] == 3:
vertices = vertices[:, :2]
result = {'vertices': vertices,
'segments': facets}
# holes in meshpy lingo are a (h, 2) list of (x,y) points
# which are inside the region of the hole
# we added a hole for the exterior, which we slice away here
holes = np.array(holes)[1:]
if len(holes) > 0:
result['holes'] = holes
return result
def box(extents=None, transform=None, **kwargs):
"""
Return a cuboid.
Parameters
------------
extents : float, or (3,) float
Edge lengths
transform: (4, 4) float
Transformation matrix
**kwargs:
passed to Trimesh to create box
Returns
------------
geometry : trimesh.Trimesh
Mesh of a cuboid
"""
# vertices of the cube
vertices = np.array([0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1,
1, 1, 0, 0, 1, 0, 1, 1, 1, 0, 1, 1, 1],
order='C',
dtype=np.float64).reshape((-1, 3))
vertices -= 0.5
# resize cube based on passed extents
if extents is not None:
extents = np.asanyarray(extents, dtype=np.float64)
if extents.shape != (3,):
raise ValueError('Extents must be (3,)!')
vertices *= extents
else:
extents = np.asarray((1.0, 1.0, 1.0), dtype=np.float64)
# hardcoded face indices
faces = [1, 3, 0, 4, 1, 0, 0, 3, 2, 2, 4, 0, 1, 7, 3, 5, 1, 4,
5, 7, 1, 3, 7, 2, 6, 4, 2, 2, 7, 6, 6, 5, 4, 7, 5, 6]
faces = np.array(faces, order='C', dtype=np.int64).reshape((-1, 3))
face_normals = [-1, 0, 0, 0, -1, 0, -1, 0, 0, 0, 0, -1, 0, 0, 1, 0, -1,
0, 0, 0, 1, 0, 1, 0, 0, 0, -1, 0, 1, 0, 1, 0, 0, 1, 0, 0]
face_normals = np.asanyarray(face_normals,
order='C',
dtype=np.float64).reshape(-1, 3)
if 'metadata' not in kwargs:
kwargs['metadata'] = dict()
kwargs['metadata'].update(
{'shape': 'box',
'extents': extents})
box = Trimesh(vertices=vertices,
faces=faces,
face_normals=face_normals,
process=False,
**kwargs)
# do the transform here to preserve face normals
if transform is not None:
box.apply_transform(transform)
return box
def icosahedron():
"""
Create an icosahedron, a 20 faced polyhedron.
Returns
-------------
ico : trimesh.Trimesh
Icosahederon centered at the origin.
"""
t = (1.0 + 5.0**.5) / 2.0
vertices = [-1, t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, 0, -1, t, 0, 1, t,
0, -1, -t, 0, 1, -t, t, 0, -1, t, 0, 1, -t, 0, -1, -t, 0, 1]
faces = [0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 0, 10, 11,
1, 5, 9, 5, 11, 4, 11, 10, 2, 10, 7, 6, 7, 1, 8,
3, 9, 4, 3, 4, 2, 3, 2, 6, 3, 6, 8, 3, 8, 9,
4, 9, 5, 2, 4, 11, 6, 2, 10, 8, 6, 7, 9, 8, 1]
# scale vertices so each vertex radius is 1.0
vertices = np.reshape(vertices, (-1, 3)) / np.sqrt(2.0 + t)
faces = np.reshape(faces, (-1, 3))
mesh = Trimesh(vertices=vertices,
faces=faces,
process=False)
return mesh
def icosphere(subdivisions=3, radius=1.0, color=None):
"""
Create an isophere centered at the origin.
Parameters
----------
subdivisions : int
How many times to subdivide the mesh.
Note that the number of faces will grow as function of
4 ** subdivisions, so you probably want to keep this under ~5
radius : float
Desired radius of sphere
color: (3,) float or uint8
Desired color of sphere
Returns
---------
ico : trimesh.Trimesh
Meshed sphere
"""
def refine_spherical():
vectors = ico.vertices
scalar = (vectors ** 2).sum(axis=1)**.5
unit = vectors / scalar.reshape((-1, 1))
offset = radius - scalar
ico.vertices += unit * offset.reshape((-1, 1))
ico = icosahedron()
ico._validate = False
for j in range(subdivisions):
ico = ico.subdivide()
refine_spherical()
ico._validate = True
if color is not None:
ico.visual.face_colors = color
ico.metadata.update({'shape': 'sphere',
'radius': radius})
return ico
def uv_sphere(radius=1.0,
count=[32, 32],
theta=None,
phi=None):
"""
Create a UV sphere (latitude + longitude) centered at the
origin. Roughly one order of magnitude faster than an
icosphere but slightly uglier.
Parameters
----------
radius : float
Radius of sphere
count : (2,) int
Number of latitude and longitude lines
theta : (n,) float
Optional theta angles in radians
phi : (n,) float
Optional phi angles in radians
Returns
----------
mesh : trimesh.Trimesh
Mesh of UV sphere with specified parameters
"""
count = np.array(count, dtype=np.int64)
count += np.mod(count, 2)
count[1] *= 2
# generate vertices on a sphere using spherical coordinates
if theta is None:
theta = np.linspace(0, np.pi, count[0])
if phi is None:
phi = np.linspace(0, np.pi * 2, count[1])[:-1]
spherical = np.dstack((np.tile(phi, (len(theta), 1)).T,
np.tile(theta, (len(phi), 1)))).reshape((-1, 2))
vertices = util.spherical_to_vector(spherical) * radius
# generate faces by creating a bunch of pie wedges
c = len(theta)
# a quad face as two triangles
pairs = np.array([[c, 0, 1],
[c + 1, c, 1]])
# increment both triangles in each quad face by the same offset
incrementor = np.tile(np.arange(c - 1), (2, 1)).T.reshape((-1, 1))
# create the faces for a single pie wedge of the sphere
strip = np.tile(pairs, (c - 1, 1))
strip += incrementor
# the first and last faces will be degenerate since the first
# and last vertex are identical in the two rows
strip = strip[1:-1]
# tile pie wedges into a sphere
faces = np.vstack([strip + (i * c) for i in range(len(phi))])
# poles are repeated in every strip, so a mask to merge them
mask = np.arange(len(vertices))
# the top pole are all the same vertex
mask[0::c] = 0
# the bottom pole are all the same vertex
mask[c - 1::c] = c - 1
# faces masked to remove the duplicated pole vertices
# and mod to wrap to fill in the last pie wedge
faces = mask[np.mod(faces, len(vertices))]
# we save a lot of time by not processing again
# since we did some bookkeeping mesh is watertight
mesh = Trimesh(vertices=vertices, faces=faces, process=False,
metadata={'shape': 'sphere',
'radius': radius})
return mesh
def capsule(height=1.0,
radius=1.0,
count=[32, 32]):
"""
Create a mesh of a capsule, or a cylinder with hemispheric ends.
Parameters
----------
height : float
Center to center distance of two spheres
radius : float
Radius of the cylinder and hemispheres
count : (2,) int
Number of sections on latitude and longitude
Returns
----------
capsule : trimesh.Trimesh
Capsule geometry with:
- cylinder axis is along Z
- one hemisphere is centered at the origin
- other hemisphere is centered along the Z axis at height
"""
height = float(height)
radius = float(radius)
count = np.array(count, dtype=np.int64)
count += np.mod(count, 2)
# create a theta where there is a double band around the equator
# so that we can offset the top and bottom of a sphere to
# get a nicely meshed capsule
theta = np.linspace(0, np.pi, count[0])
center = np.clip(np.arctan(tol.merge / radius),
tol.merge, np.inf)
offset = np.array([-center, center]) + (np.pi / 2)
theta = np.insert(theta,
int(len(theta) / 2),
offset)
capsule = uv_sphere(radius=radius,
count=count,
theta=theta)
top = capsule.vertices[:, 2] > tol.zero
capsule.vertices[top] += [0, 0, height]
capsule.metadata.update({'shape': 'capsule',
'height': height,
'radius': radius})
return capsule
def cone(radius,
height,
sections=None,
transform=None,
**kwargs):
"""
Create a mesh of a cone along Z centered at the origin.
Parameters
----------
radius : float
The radius of the cylinder
height : float
The height of the cylinder
sections : int or None
How many pie wedges per revolution
transform : (4, 4) float or None
Transform to apply after creation
**kwargs : dict
Passed to Trimesh constructor
Returns
----------
cone: trimesh.Trimesh
Resulting mesh of a cone
"""
# create the 2D outline of a cone
linestring = [[0, 0],
[radius, 0],
[0, height]]
# revolve the profile to create a cone
if 'metadata' not in kwargs:
kwargs['metadata'] = dict()
kwargs['metadata'].update(
{'shape': 'cone',
'radius': radius,
'height': height})
cone = revolve(linestring=linestring,
sections=sections,
transform=transform,
**kwargs)
return cone
def cylinder(radius,
height=None,
sections=None,
segment=None,
transform=None,
**kwargs):
"""
Create a mesh of a cylinder along Z centered at the origin.
Parameters
----------
radius : float
The radius of the cylinder
height : float or None
The height of the cylinder
sections : int or None
How many pie wedges should the cylinder have
segment : (2, 3) float
Endpoints of axis, overrides transform and height
transform : (4, 4) float
Transform to apply
**kwargs:
passed to Trimesh to create cylinder
Returns
----------
cylinder: trimesh.Trimesh
Resulting mesh of a cylinder
"""
if segment is not None:
# override transform and height with the segment
transform, height = _segment_to_cylinder(segment=segment)
if height is None:
raise ValueError('either `height` or `segment` must be passed!')
half = abs(float(height)) / 2.0
# create a profile to revolve
linestring = [[0, -half],
[radius, -half],
[radius, half],
[0, half]]
if 'metadata' not in kwargs:
kwargs['metadata'] = dict()
kwargs['metadata'].update(
{'shape': 'cylinder',
'height': height,
'radius': radius})
# generate cylinder through simple revolution
return revolve(linestring=linestring,
sections=sections,
transform=transform,
**kwargs)
def annulus(r_min,
r_max,
height=None,
sections=None,
transform=None,
segment=None,
**kwargs):
"""
Create a mesh of an annular cylinder along Z centered at the origin.
Parameters
----------
r_min : float
The inner radius of the annular cylinder
r_max : float
The outer radius of the annular cylinder
height : float
The height of the annular cylinder
sections : int or None
How many pie wedges should the annular cylinder have
transform : (4, 4) float or None
Transform to apply to move result from the origin
segment : None or (2, 3) float
Override transform and height with a line segment
**kwargs:
passed to Trimesh to create annulus
Returns
----------
annulus : trimesh.Trimesh
Mesh of annular cylinder
"""
if segment is not None:
# override transform and height with the segment if passed
transform, height = _segment_to_cylinder(segment=segment)
if height is None:
raise ValueError('either `height` or `segment` must be passed!')
r_min = abs(float(r_min))
# if center radius is zero this is a cylinder
if r_min < tol.merge:
return cylinder(radius=r_max,
height=height,
sections=sections,
transform=transform)
r_max = abs(float(r_max))
# we're going to center at XY plane so take half the height
half = abs(float(height)) / 2.0
# create counter-clockwise rectangle
linestring = [[r_min, -half],
[r_max, -half],
[r_max, half],
[r_min, half],
[r_min, -half]]
if 'metadata' not in kwargs:
kwargs['metadata'] = dict()
kwargs['metadata'].update(
{'shape': 'annulus',
'r_min': r_min,
'r_max': r_max,
'height': height})
# revolve the curve
annulus = revolve(linestring=linestring,
sections=sections,
transform=transform,
**kwargs)
return annulus
def _segment_to_cylinder(segment):
"""
Convert a line segment to a transform and height for a cylinder
or cylinder-like primitive.
Parameters
-----------
segment : (2, 3) float
3D line segment in space
Returns
-----------
transform : (4, 4) float
Matrix to move a Z-extruded origin cylinder to segment
height : float
The height of the cylinder needed
"""
segment = np.asanyarray(segment, dtype=np.float64)
if segment.shape != (2, 3):
raise ValueError('segment must be 2 3D points!')
vector = segment[1] - segment[0]
# override height with segment length
height = np.linalg.norm(vector)
# point in middle of line
midpoint = segment[0] + (vector * 0.5)
# align Z with our desired direction
rotation = align_vectors([0, 0, 1], vector)
# translate to midpoint of segment
translation = tf.translation_matrix(midpoint)
# compound the rotation and translation
transform = np.dot(translation, rotation)
return transform, height
def random_soup(face_count=100):
"""
Return random triangles as a Trimesh
Parameters
-----------
face_count : int
Number of faces desired in mesh
Returns
-----------
soup : trimesh.Trimesh
Geometry with face_count random faces
"""
vertices = np.random.random((face_count * 3, 3)) - 0.5
faces = np.arange(face_count * 3).reshape((-1, 3))
soup = Trimesh(vertices=vertices, faces=faces)
return soup
def axis(origin_size=0.04,
transform=None,
origin_color=None,
axis_radius=None,
axis_length=None):
"""
Return an XYZ axis marker as a Trimesh, which represents position
and orientation. If you set the origin size the other parameters
will be set relative to it.
Parameters
----------
transform : (4, 4) float
Transformation matrix
origin_size : float
Radius of sphere that represents the origin
origin_color : (3,) float or int, uint8 or float
Color of the origin
axis_radius : float
Radius of cylinder that represents x, y, z axis
axis_length: float
Length of cylinder that represents x, y, z axis
Returns
-------
marker : trimesh.Trimesh
Mesh geometry of axis indicators
"""
# the size of the ball representing the origin
origin_size = float(origin_size)
# set the transform and use origin-relative
# sized for other parameters if not specified
if transform is None:
transform = np.eye(4)
if origin_color is None:
origin_color = [255, 255, 255, 255]
if axis_radius is None:
axis_radius = origin_size / 5.0
if axis_length is None:
axis_length = origin_size * 10.0
# generate a ball for the origin
axis_origin = uv_sphere(radius=origin_size,
count=[10, 10])
axis_origin.apply_transform(transform)
# apply color to the origin ball
axis_origin.visual.face_colors = origin_color
# create the cylinder for the z-axis
translation = tf.translation_matrix(
[0, 0, axis_length / 2])
z_axis = cylinder(
radius=axis_radius,
height=axis_length,
transform=transform.dot(translation))
# XYZ->RGB, Z is blue
z_axis.visual.face_colors = [0, 0, 255]
# create the cylinder for the y-axis
translation = tf.translation_matrix(
[0, 0, axis_length / 2])
rotation = tf.rotation_matrix(np.radians(-90),
[1, 0, 0])
y_axis = cylinder(
radius=axis_radius,
height=axis_length,
transform=transform.dot(rotation).dot(translation))
# XYZ->RGB, Y is green
y_axis.visual.face_colors = [0, 255, 0]
# create the cylinder for the x-axis
translation = tf.translation_matrix(
[0, 0, axis_length / 2])
rotation = tf.rotation_matrix(np.radians(90),
[0, 1, 0])
x_axis = cylinder(
radius=axis_radius,
height=axis_length,
transform=transform.dot(rotation).dot(translation))
# XYZ->RGB, X is red
x_axis.visual.face_colors = [255, 0, 0]
# append the sphere and three cylinders
marker = util.concatenate([axis_origin,
x_axis,
y_axis,
z_axis])
return marker
def camera_marker(camera,
marker_height=0.4,
origin_size=None):
"""
Create a visual marker for a camera object, including an axis and FOV.
Parameters
---------------
camera : trimesh.scene.Camera
Camera object with FOV and transform defined
marker_height : float
How far along the camera Z should FOV indicators be
origin_size : float
Sphere radius of the origin (default: marker_height / 10.0)
Returns
------------
meshes : list
Contains Trimesh and Path3D objects which can be visualized
"""
# create sane origin size from marker height
if origin_size is None:
origin_size = marker_height / 10.0
# append the visualizations to an array
meshes = [axis(origin_size=origin_size)]
try:
# path is a soft dependency
from .path.exchange.load import load_path
except ImportError:
# they probably don't have shapely installed
log.warning('unable to create FOV visualization!',
exc_info=True)
return meshes
# calculate vertices from camera FOV angles
x = marker_height * np.tan(np.deg2rad(camera.fov[0]) / 2.0)
y = marker_height * np.tan(np.deg2rad(camera.fov[1]) / 2.0)
z = marker_height
# combine the points into the vertices of an FOV visualization
points = np.array(
[(0, 0, 0),
(-x, -y, z),
(x, -y, z),
(x, y, z),
(-x, y, z)],
dtype=float)
# create line segments for the FOV visualization
# a segment from the origin to each bound of the FOV
segments = np.column_stack(
(np.zeros_like(points), points)).reshape(
(-1, 3))
# add a loop for the outside of the FOV then reshape
# the whole thing into multiple line segments
segments = np.vstack((segments,
points[[1, 2,
2, 3,
3, 4,
4, 1]])).reshape((-1, 2, 3))
# add a single Path3D object for all line segments
meshes.append(load_path(segments))
return meshes
def truncated_prisms(tris, origin=None, normal=None):
"""
Return a mesh consisting of multiple watertight prisms below
a list of triangles, truncated by a specified plane.
Parameters
-------------
triangles : (n, 3, 3) float
Triangles in space
origin : None or (3,) float
Origin of truncation plane
normal : None or (3,) float
Unit normal vector of truncation plane
Returns
-----------
mesh : trimesh.Trimesh
Triangular mesh
"""
if origin is None:
transform = np.eye(4)
else:
transform = plane_transform(origin=origin, normal=normal)
# transform the triangles to the specified plane
transformed = tf.transform_points(
tris.reshape((-1, 3)), transform).reshape((-1, 9))
# stack triangles such that every other one is repeated
vs = np.column_stack((transformed, transformed)).reshape((-1, 3, 3))
# set the Z value of the second triangle to zero
vs[1::2, :, 2] = 0
# reshape triangles to a flat array of points and transform back to original frame
vertices = tf.transform_points(
vs.reshape((-1, 3)), matrix=np.linalg.inv(transform))
# face indexes for a *single* truncated triangular prism
f = np.array([[2, 1, 0],
[3, 4, 5],
[0, 1, 4],
[1, 2, 5],
[2, 0, 3],
[4, 3, 0],
[5, 4, 1],
[3, 5, 2]])
# find the projection of each triangle with the normal vector
cross = np.dot([0, 0, 1], triangles.cross(transformed.reshape((-1, 3, 3))).T)
# stack faces into one prism per triangle
f_seq = np.tile(f, (len(transformed), 1)).reshape((-1, len(f), 3))
# if the normal of the triangle was positive flip the winding
f_seq[cross > 0] = np.fliplr(f)
# offset stacked faces to create correct indices
faces = (f_seq + (np.arange(len(f_seq)) * 6).reshape((-1, 1, 1))).reshape((-1, 3))
# create a mesh from the data
mesh = Trimesh(vertices=vertices, faces=faces, process=False)
return mesh
|
mit
| 7,771,530,752,950,177,000
| 30.973228
| 86
| 0.580727
| false
| 3.824261
| false
| false
| false
|
stormvirux/vturra-cli
|
vturra/asys.py
|
1
|
1936
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# from scipy import stats
# import statsmodels.api as sm
# from numpy.random import randn
import matplotlib as mpl
# import seaborn as sns
# sns.set_color_palette("deep", desat=.6)
mpl.rc("figure", figsize=(8, 4))
def Compavg():
data=Total()
markMax=[]
markAvg=[]
N = 5
ind = np.arange(N)
width = 0.35
fig = plt.figure()
ax = fig.add_subplot(111)
markMax.extend((data["Total"].max(),data["Total.1"].max(),data["Total.2"].max(),data["Total.3"].max(),data["Total.4"].max()))
markAvg.extend((data["Total"].mean(),data["Total.1"].mean(),data["Total.2"].mean(),data["Total.3"].mean(),data["Total.4"].mean()))
rects1 = ax.bar(ind, markMax, width, color='black')
rects2 = ax.bar(ind+width, markAvg, width, color='green')
ax.set_xlim(-width,len(ind)+width)
ax.set_ylim(0,120)
ax.set_ylabel('Marks')
ax.set_title('Max, Mean and Your Marks')
xTickMarks = ['Subject'+str(i) for i in range(1,6)]
ax.set_xticks(ind+width)
xtickNames = ax.set_xticklabels(xTickMarks)
plt.setp(xtickNames, rotation=10, fontsize=10)
ax.legend( (rects1[0], rects2[0]), ('Max', 'Mean') )
plt.show()
def compSub():
# max_data = np.r_[data["Total"]].max()
# bins = np.linspace(0, max_data, max_data + 1)
data=Total()
plt.hist(data['Total'],linewidth=0, alpha=.7)
plt.hist(data['Total.1'],linewidth=0,alpha=.7)
plt.hist(data['Total.2'],linewidth=0,alpha=.7)
plt.hist(data['Total.3'],linewidth=0,alpha=.7)
plt.hist(data['Total.4'],linewidth=0,alpha=.7)
plt.title("Total marks Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
def Total():
data=pd.read_csv("output10cs.csv")
df3=data[['Total','Total.1','Total.2','Total.3','Total.4','Total.5','Total.6','Total.7']]
data["Main Total"]=df3.sum(axis=1)
data = data.dropna()
data.reset_index(drop=True)
return data
#compSub()
# Compavg()
|
mit
| 5,560,022,484,515,166,000
| 29.730159
| 131
| 0.66064
| false
| 2.564238
| false
| false
| false
|
hall1467/wikidata_usage_tracking
|
wbc_usage/utilities/determine_wikis.py
|
1
|
2123
|
"""
Prints all wikis to stdout.
Usage:
determine_wikis (-h|--help)
determine_wikis [--debug]
[--verbose]
Options:
-h, --help This help message is printed
--debug Print debug logging to stderr
--verbose Print dots and stuff to stderr
"""
import logging
import mwapi
import sys
import json
import docopt
logger = logging.getLogger(__name__)
def main(argv=None):
args = docopt.docopt(__doc__, argv=argv)
logging.basicConfig(
level=logging.WARNING if not args['--debug'] else logging.DEBUG,
format='%(asctime)s %(levelname)s:%(name)s -- %(message)s'
)
verbose = args['--verbose']
run(verbose)
# Contacts API to return list of wikis
# Code credit: https://github.com/WikiEducationFoundation/academic_classification/blob/master/pageclassifier/revgather.py
def run(verbose):
session = mwapi.Session(
'https://en.wikipedia.org',
user_agent='hall1467'
)
results = session.get(
action='sitematrix'
)
for database_dictionary in extract_query_results(results):
if verbose:
sys.stderr.write("Printing json for the database: " +
database_dictionary['dbname'] + "\n")
sys.stderr.flush()
sys.stdout.write(json.dumps(database_dictionary) + "\n")
# Code credit: https://github.com/WikiEducationFoundation/academic_classification/blob/master/pageclassifier/revgather.py
def extract_query_results(results):
results = results['sitematrix']
for entry in results:
if entry == 'count':
continue
if entry == 'specials':
for special_entry in results[entry]:
yield ({
"dbname" : special_entry['dbname'],
"wikiurl" : special_entry['url']
})
continue
for wiki in results[entry]['site']:
yield {
"dbname" : wiki['dbname'],
"wikiurl" : wiki['url']
}
|
mit
| 7,319,689,185,539,322,000
| 25.5375
| 121
| 0.563354
| false
| 4.179134
| false
| false
| false
|
nboley/grit
|
grit/simulator/reads_simulator.py
|
1
|
21238
|
"""
Copyright (c) 2011-2015 Nathan Boley
This file is part of GRIT.
GRIT 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.
GRIT 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 GRIT. If not, see <http://www.gnu.org/licenses/>.
"""
import sys
import os
import os.path
import numpy
import pickle
import pysam
import math
from random import random
from collections import defaultdict
import tempfile
DEFAULT_QUALITY_SCORE = 'r'
DEFAULT_BASE = 'A'
DEFAULT_FRAG_LENGTH = 150
DEFAULT_READ_LENGTH = 100
DEFAULT_NUM_FRAGS = 100
NUM_NORM_SDS = 4
FREQ_GTF_STRINGS = [ 'freq', 'frac' ]
# add slide dir to sys.path and import frag_len mod
#sys.path.append(os.path.join(os.path.dirname(sys.argv[0]), ".." ))
sys.path.insert(0, "/home/nboley/grit/grit/")
import grit.frag_len as frag_len
from grit.files.gtf import load_gtf
from grit.files.reads import clean_chr_name
def fix_chr_name(x):
return "chr" + clean_chr_name(x)
def get_transcript_sequence(transcript, fasta):
""" get the mRNA sequence of the transcript from the gene seq
"""
trans_seq = []
for start, stop in transcript.exons:
seq = fasta.fetch(fix_chr_name(transcript.chrm), start, stop+1)
trans_seq.append( seq.upper() )
trans_seq = "".join(trans_seq)
return trans_seq
def get_cigar( transcript, start, stop ):
"""loop through introns within the read and add #N to the cigar for each
intron add #M for portions of read which map to exons
"""
def calc_len(interval):
return interval[1]-interval[0]+1
cigar = []
# find the exon index of the start
genome_start = transcript.genome_pos(start)
start_exon = next(i for i, (e_start, e_stop) in enumerate(transcript.exons)
if genome_start >= e_start and genome_start <= e_stop)
genome_stop = transcript.genome_pos(stop-1)
stop_exon = next(i for i, (e_start, e_stop) in enumerate(transcript.exons)
if genome_stop >= e_start and genome_stop <= e_stop)
if start_exon == stop_exon:
return "%iM" % (stop-start)
tl = 0
# add the first overlap match
skipped_bases = sum(calc_len(e) for e in transcript.exons[:start_exon+1])
cigar.append("%iM" % (skipped_bases-start))
tl += skipped_bases-start
# add the first overlap intron
cigar.append("%iN" % calc_len(transcript.introns[start_exon]))
# add the internal exon and intron matches
for i in xrange(start_exon+1, stop_exon):
cigar.append("%iM" % calc_len(transcript.exons[i]))
cigar.append("%iN" % calc_len(transcript.introns[i]))
tl += calc_len(transcript.exons[i])
# add the last overlap match
skipped_bases = sum(e[1]-e[0]+1 for e in transcript.exons[:stop_exon])
cigar.append("%iM" % (stop-skipped_bases))
tl += stop - skipped_bases
assert tl == (stop-start)
return "".join(cigar)
def build_sam_line( transcript, read_len, offset, read_identifier, quality_string ):
"""build a single ended SAM formatted line with given inforamtion
"""
# set flag to indcate strandedness of read matching that of the transcript
flag = 0
if transcript.strand == '+': flag += 16
# adjust start position to correct genomic position
start = transcript.genome_pos(offset)
# set cigar string corresponding to transcript and read offset
cigar = get_cigar( transcript, offset, (offset + read_len) )
# calculate insert size by difference of genomic offset and genomic offset+read_len
insert_size = transcript.genome_pos(offset+read_len) - transcript.genome_pos(offset)
# get slice of seq from transcript
seq = ( transcript.seq[ offset : (offset + read_len) ]
if transcript.seq != None else '*' )
# initialize sam lines with read identifiers and then add appropriate fields
sam_line = '\t'.join( (
read_identifier, str( flag ), fix_chr_name(transcript.chrm),
str(start+1),
'255', cigar, "*", '0', str( insert_size ), seq, quality_string,
"NM:i:0", "NH:i:1" ) ) + "\n"
return sam_line
def build_sam_lines( transcript, read_len, frag_len, offset,
read_identifier, read_quals ):
"""build paired end SAM formatted lines with given information
"""
# set ordered quals and reverse the qualities for the read on the negative strand
ordered_quals = read_quals
# determine whether read1 should be the 5' read or visa verses
# and initialize attributes that are specific to a read number
# instead of 5' or 3' attribute
if transcript.strand == '+':
up_strm_read, dn_strm_read = (0, 1)
flag = [ 99, 147 ]
ordered_quals[1] = ordered_quals[1][::-1]
else:
up_strm_read, dn_strm_read = (1, 0)
flag = [ 83, 163 ]
ordered_quals[0] = ordered_quals[0][::-1]
# get slice of seq from transcript
seq = ['*', '*']
if transcript.seq != None:
seq[ up_strm_read ] = transcript.seq[offset:(offset + read_len)]
seq[ dn_strm_read ] = transcript.seq[
(offset + frag_len - read_len):(offset + frag_len)]
# adjust five and three prime read start positions to correct genomic positions
start = [ transcript.start, transcript.start ]
start[ up_strm_read ] = transcript.genome_pos(offset)
start[ dn_strm_read ] = transcript.genome_pos(offset + frag_len - read_len)
# set cigar string for five and three prime reads
cigar = [ None, None ]
cigar[ up_strm_read ] = get_cigar( transcript, offset, (offset+read_len) )
cigar[ dn_strm_read ] = get_cigar(
transcript, (offset+frag_len-read_len), (offset + frag_len))
# calculate insert size by difference of the mapped start and end
insert_size = (
transcript.genome_pos(offset+read_len) - transcript.genome_pos(offset))
insert_size = [ insert_size, insert_size ]
insert_size[ dn_strm_read ] *= -1
# initialize sam lines with read identifiers and then add appropriate fields
sam_lines = [ read_identifier + '\t', read_identifier + '\t' ]
for i in (0,1):
other_i = 0 if i else 1
sam_lines[i] += '\t'.join( (
str( flag[i] ), fix_chr_name(transcript.chrm),
str( start[i]+1 ),"255",
cigar[i], "=", str( start[other_i]+1 ), str( insert_size[i] ),
seq[i], ordered_quals[i], "NM:i:0", "NH:i:1" ) ) + "\n"
return sam_lines
def write_fastq_lines( fp1, fp2, transcript, read_len, frag_len, offset,
read_identifier ):
"""STUB for writing fastq lines to running through alignment pipeline
"""
pass
def simulate_reads( genes, fl_dist, fasta, quals, num_frags, single_end,
full_fragment, read_len, assay='RNAseq'):
"""write a SAM format file with the specified options
"""
# global variable that stores the current read number, we use this to
# generate a unique id for each read.
global curr_read_index
curr_read_index = 1
def sample_fragment_length( fl_dist, transcript ):
"""Choose a random fragment length from fl_dist
"""
if assay == 'CAGE':
return read_len
# if the fl_dist is constant
if isinstance( fl_dist, int ):
assert fl_dist <= transcript.calc_length(), 'Transcript which ' + \
'cannot contain a valid fragment was included in transcripts.'
return fl_dist
# Choose a valid fragment length from the distribution
while True:
fl_index = fl_dist.fl_density_cumsum.searchsorted( random() ) - 1
fl = fl_index + fl_dist.fl_min
# if fragment_length is valid return it
if fl <= transcript.calc_length():
return fl
assert False
def sample_read_offset( transcript, fl ):
# calculate maximum offset
max_offset = transcript.calc_length() - fl
if assay in ('CAGE', 'RAMPAGE'):
if transcript.strand == '+': return 0
else: return max_offset
elif assay == 'RNAseq':
return int( random() * max_offset )
elif assay == 'PASseq':
if transcript.strand == '-': return 0
else: return max_offset
def get_random_qual_score( read_len ):
# if no quality score were provided
if not quals:
return DEFAULT_QUALITY_SCORE * read_len
# else return quality string from input quality file
# scores are concatenated to match read_len if necessary
else:
qual_string = ''
while len( qual_string ) < read_len:
qual_string += str( quals[ int(random() * len(quals) ) ] )
return qual_string[0:read_len]
def get_random_read_pos( transcript ):
while True:
# find a valid fragment length
fl = sample_fragment_length( fl_dist, transcript )
if (fl >= read_len) or full_fragment: break
# find a valid random read start position
offset = sample_read_offset( transcript, fl )
# get a unique string for this fragment
global curr_read_index
read_identifier = 'SIM:%015d:%s' % (curr_read_index, transcript.id)
curr_read_index += 1
return fl, offset, read_identifier
def build_random_sam_line( transcript, read_len ):
"""build a random single ended sam line
"""
fl, offset, read_identifier = get_random_read_pos( transcript )
if full_fragment:
read_len = fl
# get a random quality scores
if transcript.seq == None:
read_qual = '*'
else:
read_qual = get_random_qual_score( read_len )
# build the sam lines
return build_sam_line(
transcript, read_len, offset, read_identifier, read_qual )
def build_random_sam_lines( transcript, read_len ):
"""build random paired end sam lines
"""
fl, offset, read_identifier = get_random_read_pos( transcript )
# adjust read length so that paired end read covers the entire fragment
if full_fragment:
read_len = int( math.ceil( fl / float(2) ) )
# get two random quality scores
if transcript.seq == None:
read_quals = ['*', '*']
else:
read_quals = [ get_random_qual_score( read_len ),
get_random_qual_score( read_len ) ]
sam_lines = build_sam_lines(
transcript, read_len, fl, offset, read_identifier, read_quals )
return sam_lines
def get_fl_min():
if isinstance( fl_dist, int ):
return fl_dist
else:
return fl_dist.fl_min
def calc_scale_factor(t):
if assay in ('RNAseq',):
length = t.calc_length()
if length < fl_dist.fl_min: return 0
fl_min, fl_max = fl_dist.fl_min, min(length, fl_dist.fl_max)
allowed_fl_lens = numpy.arange(fl_min, fl_max+1)
weights = fl_dist.fl_density[
fl_min-fl_dist.fl_min:fl_max-fl_dist.fl_min+1]
mean_fl_len = float((allowed_fl_lens*weights).sum())
return length - mean_fl_len
elif assay in ('CAGE', 'RAMPAGE', 'PASseq'):
return 1.0
# initialize the transcript objects, and calculate their relative weights
transcript_weights = []
transcripts = []
contig_lens = defaultdict(int)
min_transcript_length = get_fl_min()
for gene in genes:
contig_lens[fix_chr_name(gene.chrm)] = max(
gene.stop+1000, contig_lens[fix_chr_name(gene.chrm)])
for transcript in gene.transcripts:
if fasta != None:
transcript.seq = get_transcript_sequence(transcript, fasta)
else:
transcript.seq = None
if transcript.fpkm != None:
weight = transcript.fpkm*calc_scale_factor(transcript)
elif transcript.frac != None:
assert len(genes) == 1
weight = transcript.frac
else:
weight = 1./len(gene.transcripts)
#assert False, "Transcript has neither an FPKM nor a frac"
transcripts.append( transcript )
transcript_weights.append( weight )
#assert False
assert len( transcripts ) > 0, "No valid trancripts."
# normalize the transcript weights to be on 0,1
transcript_weights = numpy.array(transcript_weights, dtype=float)
transcript_weights = transcript_weights/transcript_weights.sum()
transcript_weights_cumsum = transcript_weights.cumsum()
# update the contig lens from the fasta file, if available
if fasta != None:
for name, length in zip(fasta.references, fasta.lengths):
if fix_chr_name(name) in contig_lens:
contig_lens[fix_chr_name(name)] = max(
length, contig_lens[name])
# create the output directory
bam_prefix = assay + ".sorted"
with tempfile.NamedTemporaryFile( mode='w+' ) as sam_fp:
# write out the header
for contig, contig_len in contig_lens.iteritems():
data = ["@SQ", "SN:%s" % contig, "LN:%i" % contig_len]
sam_fp.write("\t".join(data) + "\n")
while curr_read_index <= num_frags:
# pick a transcript to randomly take a read from. Note that they
# should be chosen in proportion to the *expected number of reads*,
# not their relative frequencies.
transcript_index = \
transcript_weights_cumsum.searchsorted( random(), side='left' )
transcript = transcripts[ transcript_index ]
if single_end:
sam_line_s = build_random_sam_line( transcript, read_len )
else:
sam_line_s = build_random_sam_lines( transcript, read_len )
sam_fp.writelines( sam_line_s )
# create sorted bam file and index it
sam_fp.flush()
#sam_fp.seek(0)
#print sam_fp.read()
call = 'samtools view -bS {} | samtools sort - {}'
os.system( call.format( sam_fp.name, bam_prefix ) )
os.system( 'samtools index {}.bam'.format( bam_prefix ) )
return
def build_objs( gtf_fp, fl_dist_const,
fl_dist_norm, full_fragment,
read_len, fasta_fn, qual_fn ):
genes = load_gtf( gtf_fp )
gtf_fp.close()
def build_normal_fl_dist( fl_mean, fl_sd ):
fl_min = max( 0, fl_mean - (fl_sd * NUM_NORM_SDS) )
fl_max = fl_mean + (fl_sd * NUM_NORM_SDS)
fl_dist = frag_len.build_normal_density( fl_min, fl_max, fl_mean, fl_sd )
return fl_dist
if fl_dist_norm:
fl_dist = build_normal_fl_dist( fl_dist_norm[0], fl_dist_norm[1] )
assert fl_dist.fl_max > read_len or full_fragment, \
'Invalid fragment length distribution and read length!!!'
else:
assert read_len < fl_dist_const or full_fragment, \
'Invalid read length and constant fragment length!!!'
fl_dist = fl_dist_const
if fasta_fn:
# create indexed fasta file handle object with pysam
fasta = pysam.Fastafile( fasta_fn )
else:
fasta = None
# if quals_fn is None, quals remains empty and reads will default to
# all base qualities of DEFAULT_BASE_QUALITY_SCORE
quals = []
if qual_fn:
with open( quals_fn ) as quals_fp:
for line in quals_fp:
quals.append( line.strip() )
quals = numpy.array( quals )
return genes, fl_dist, fasta, quals
def parse_arguments():
import argparse
parser = argparse.ArgumentParser(\
description='Produce simulated reads in a perfecty aligned BAM file.' )
# gtf is the only required argument
parser.add_argument( 'gtf', type=file, \
help='GTF file from which to produce simulated reads ' + \
'(Note: Only the first trascript from this file will ' + \
'be simulated)' )
parser.add_argument(
'--assay', choices=['RNAseq', 'RAMPAGE', 'CAGE', 'PASseq'],
default='RNAseq', help='Which assay type to simulate from' )
# fragment length distribution options
parser.add_argument( '--fl-dist-const', type=int, default=DEFAULT_FRAG_LENGTH, \
help='Constant length fragments. (default: ' + \
'%(default)s)' )
parser.add_argument( '--fl-dist-norm', \
help='Mean and standard deviation (format "mn:sd") ' + \
'used to create normally distributed fragment lengths.' )
# files providing quality and sequnce information
parser.add_argument( '--fasta', '-f', \
help='Fasta file from which to create reads ' + \
'(default: all sequences are "' + DEFAULT_BASE + \
'" * length of sequence)' )
parser.add_argument( '--quality', '-q', \
help='Flat file containing one FASTQ quality score ' + \
'per line, created with get_quals.sh. (default: ' + \
'quality strings are "' + str(DEFAULT_QUALITY_SCORE) + \
'" * length of sequence.)' )
# type and number of fragments requested
parser.add_argument(
'--num-frags', '-n', type=int, default=1000,
help='Total number of fragments to create across all trascripts')
parser.add_argument('--single-end', action='store_true', default=False,
help='Produce single-end reads.' )
parser.add_argument('--paired-end', dest='single_end', action='store_false',
help='Produce paired-end reads. (default)' )
# XXX not sure if this works
#parser.add_argument(
# '--full-fragment', action='store_true', default=False,
# help='Produce reads spanning the entire fragment.')
parser.add_argument( '--read-len', '-r', type=int, default=DEFAULT_READ_LENGTH, \
help='Length of reads to produce in base pairs ' + \
'(default: %(default)s)' )
# output options
parser.add_argument( '--out_prefix', '-o', default='simulated_reads', \
help='Prefix for output FASTQ/BAM file ' + \
'(default: %(default)s)' )
parser.add_argument( '--verbose', '-v', default=False, action='store_true', \
help='Print status information.' )
args = parser.parse_args()
# set to false, but we may want to bring this option back
args.full_fragment = False
global VERBOSE
VERBOSE = args.verbose
if args.assay == 'CAGE':
args.read_len = 28
args.single_end = True
# parse normal distribution argument
if args.fl_dist_norm:
try:
mean, sd = args.fl_dist_norm.split( ':' )
args.fl_dist_norm = [ int( mean ), int( sd ) ]
except ValueError:
args.fl_dist_norm = None
print >> sys.stderr, \
"WARNING: User input mean and sd are not formatted correctly.\n"+\
"\tUsing default values.\n"
return ( args.gtf, args.fl_dist_const, args.fl_dist_norm,
args.fasta, args.quality, args.num_frags,
args.single_end, args.full_fragment,
args.read_len, args.out_prefix, args.assay )
def main():
( gtf_fp, fl_dist_const, fl_dist_norm, fasta_fn, qual_fn,
num_frags, single_end, full_fragment, read_len, out_prefix, assay )\
= parse_arguments()
try: os.mkdir(out_prefix)
except OSError:
ofname = os.path.join(out_prefix, assay + '.sorted.bam')
if os.path.isfile(ofname):
raise OSError, "File '%s' already exists" % ofname
os.chdir(out_prefix)
genes, fl_dist, fasta, quals = build_objs(
gtf_fp, fl_dist_const,
fl_dist_norm, full_fragment, read_len,
fasta_fn, qual_fn )
"""
for gene in genes:
for t in gene.transcripts:
t.chrm = "chr" + t.chrm
print t.build_gtf_lines(gene.id, {})
assert False
"""
simulate_reads( genes, fl_dist, fasta, quals, num_frags, single_end,
full_fragment, read_len, assay=assay )
if __name__ == "__main__":
main()
|
gpl-3.0
| -4,307,114,510,354,580,500
| 37.33574
| 88
| 0.584377
| false
| 3.781695
| false
| false
| false
|
Netflix-Skunkworks/iep-apps
|
atlas-slotting/src/scripts/lift-data.py
|
1
|
4221
|
#!/usr/bin/env python3
# Copyright 2014-2019 Netflix, Inc.
#
# 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 argparse
import gzip
import json
import pprint
from argparse import Namespace
from datetime import datetime
from typing import Dict, List
import boto3
import requests
import sys
from boto3.dynamodb.types import Binary
from botocore.exceptions import ClientError, ProfileNotFound
def parse_args() -> Namespace:
parser = argparse.ArgumentParser(description='Lift slotting data from Edda into DynamoDB')
parser.add_argument('--profile', type=str, required=True,
help='AWS credentials profile used to write to the Atlas Slotting DynamoDB table')
parser.add_argument('--region', type=str, nargs='+', required=True,
choices=['eu-west-1', 'us-east-1', 'us-west-1', 'us-west-2'],
help='List of AWS regions where data will be lifted from Edda into DynamoDB')
parser.add_argument('--edda_name', type=str, required=True,
help='Edda DNS name, with a region placeholder, where data will be read')
parser.add_argument('--slotting_table', type=str, required=True,
help='Atlas Slotting DynamoDB table name, where data will be written')
parser.add_argument('--app_name', type=str, nargs='+', required=True,
help='List of application names that will be lifted')
parser.add_argument('--dryrun', action='store_true', required=False, default=False,
help='Enable dryrun mode, to preview changes')
return parser.parse_args()
def get_edda_data(args: Namespace, region: str) -> List[Dict]:
url = f'http://{args.edda_name.format(region)}/api/v2/group/autoScalingGroups;_expand'
r = requests.get(url)
if not r.ok:
print(f'ERROR: Failed to load Edda data from {url}')
sys.exit(1)
else:
return [asg for asg in r.json() if asg['name'].split('-')[0] in args.app_name]
def get_ddb_table(args: Namespace, region: str):
try:
session = boto3.session.Session(profile_name=args.profile)
except ProfileNotFound:
print(f'ERROR: AWS profile {args.profile} does not exist')
sys.exit(1)
dynamodb = session.resource('dynamodb', region_name=region)
table = dynamodb.Table(args.slotting_table)
try:
table.table_status
except ClientError as e:
code = e.response['Error']['Code']
if code == 'ExpiredTokenException':
print(f'ERROR: Security token in AWS profile {args.profile} has expired')
elif code == 'ResourceNotFoundException':
print(f'ERROR: Table {args.slotting_table} does not exist in {region}')
else:
pprint.pprint(e.response)
sys.exit(1)
return table
def lift_data(args: Namespace, region: str):
asgs = get_edda_data(args, region)
table = get_ddb_table(args, region)
for asg in asgs:
item = {
'name': asg['name'],
'active': True,
'data': Binary(gzip.compress(bytes(json.dumps(asg), encoding='utf-8'))),
'timestamp': int(datetime.utcnow().timestamp() * 1000)
}
if args.dryrun:
print(f'DRYRUN: PUT {asg["name"]}')
else:
print(f'PUT {asg["name"]}')
table.put_item(Item=item)
def main():
args = parse_args()
print('==== config ====')
print(f'AWS Profile: {args.profile}')
print(f'Source Edda: {args.edda_name}')
print(f'Destination Table: {args.slotting_table}')
for region in args.region:
print(f'==== {region} ====')
lift_data(args, region)
if __name__ == "__main__":
main()
|
apache-2.0
| -9,102,378,163,587,709,000
| 34.175
| 106
| 0.637764
| false
| 3.758682
| false
| false
| false
|
nemonik/CoCreateLite
|
ccl-cookbook/files/default/cocreatelite/cocreate/views/playgrounds.py
|
1
|
5229
|
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404
from django.core.urlresolvers import reverse
from ..models import VMPlayground
from ..forms import VMPlaygroundForm, VMPlaygroundDescriptionForm, VMPlaygroundUserAccessForm, VMPlaygroundGroupAccessForm
from . import util
from ..util import single_user_mode
"""
View controllers for playground data
"""
@single_user_mode
def index(request):
"""
Show the list of playgrounds for this user.
"""
# determine all of the playgrounds this user has access to
groupids = [group.id for group in request.user.groups.all()]
print ("Group ids: " + str(groupids))
playgrounds = VMPlayground.objects.filter(creator = request.user) | VMPlayground.objects.filter(access_users__id = request.user.id) | VMPlayground.objects.filter(access_groups__id__in = groupids)
# determine all of the demo boxes from a set of playgrounds
demos = []
for playground in playgrounds:
demos = demos + playground.getDemos()
context = {
"playgrounds": playgrounds,
"demos": demos
}
return render(request, "playgrounds.html", util.fillContext(context, request))
@single_user_mode
def add(request):
"""
Add a new playground.
"""
if request.method == 'GET':
form = VMPlaygroundForm()
elif request.method == 'POST':
form = VMPlaygroundForm(request.POST)
if form.is_valid():
# hooray, let's create the playground
playground = VMPlayground.objects.create(
name = form.data['name'],
creator = request.user,
description = form.data['description'],
description_is_markdown = form.data.get('description_is_markdown', False),
environment = form.data['environment'],
)
playground.save()
return HttpResponseRedirect(reverse("playground", args=[playground.id]))
else:
pass
opts = {"form": form}
return render(request, "addPlayground.html", util.fillContext(opts, request))
@single_user_mode
def remove(request, playground_id):
"""
Remove a playground.
"""
playground = get_object_or_404(VMPlayground, pk = playground_id)
for sandbox in playground.sandboxes.all():
sandox.delete()
playground.delete()
return HttpResponseRedirect(reverse("playgrounds"))
@single_user_mode
def playground(request, playground_id):
"""
Show the details for this playground.
"""
playground = get_object_or_404(VMPlayground, pk = playground_id)
opts = {"playground": playground}
return render(request, "newPlaygroundDetails.html", util.fillContext(opts, request))
@single_user_mode
def alterUserAccess(request, playground_id):
"""
Alter the access control list for a playground.
"""
playground = get_object_or_404(VMPlayground, pk = playground_id)
if request.method == 'GET':
form = VMPlaygroundUserAccessForm(instance = playground)
elif request.method == 'POST':
form = VMPlaygroundUserAccessForm(request.POST, instance=playground)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("playground", args=[playground.id]))
else:
pass
opts = {"form": form, "playground": playground }
return render(request, "alterPlaygroundUserAccess.html", util.fillContext(opts, request))
@single_user_mode
def alterGroupAccess(request, playground_id):
"""
Alter the access control list for a playground.
"""
playground = get_object_or_404(VMPlayground, pk = playground_id)
if request.method == 'GET':
form = VMPlaygroundGroupAccessForm(instance = playground)
elif request.method == 'POST':
form = VMPlaygroundGroupAccessForm(request.POST, instance=playground)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse("playground", args=[playground.id]))
else:
pass
opts = {"form": form, "playground": playground }
return render(request, "alterPlaygroundGroupAccess.html", util.fillContext(opts, request))
@single_user_mode
def editDesc(request, playground_id):
"""
Alter or edit the description of the playground
"""
playground = get_object_or_404(VMPlayground, pk = playground_id)
if request.method == 'GET':
form = VMPlaygroundDescriptionForm(instance = playground)
elif request.method == 'POST':
form = VMPlaygroundDescriptionForm(request.POST)
if form.is_valid():
playground.description_is_markdown = form.data['description_is_markdown']
playground.description = form.data['description']
playground.save()
return HttpResponseRedirect(reverse("playground", args=[playground.id]))
else:
pass
opts = {"form": form, "playground": playground }
return render(request, "editPlaygroundDesc.html", util.fillContext(opts, request))
|
bsd-3-clause
| 5,452,664,651,074,782,000
| 32.954545
| 199
| 0.643526
| false
| 3.991603
| false
| false
| false
|
roscopecoltran/scraper
|
.staging/meta-engines/xlinkBook/update/spider.py
|
1
|
7851
|
#!/usr/bin/env python
#author: wowdd1
#mail: developergf@gmail.com
#data: 2014.12.09
import requests
import json
from bs4 import BeautifulSoup;
import os,sys
import time
import re
from all_subject import subject_dict, need_update_subject_list
reload(sys)
sys.setdefaultencoding("utf-8")
sys.path.append("..")
from record import Category
class Spider:
google = None
baidu = None
bing = None
yahoo = None
db_dir = None
zh_re = None
shcool = None
subject = None
url = None
count = None
deep_mind = None
category = ''
category_obj = None
proxies = {
"http": "http://127.0.0.1:8087",
"https": "http://127.0.0.1:8087",
}
proxies2 = {
"http": "http://127.0.0.1:8787",
"https": "http://127.0.0.1:8787",
}
def __init__(self):
self.google = "https://www.google.com.hk/?gws_rd=cr,ssl#safe=strict&q="
self.baidu = "http://www.baidu.com/s?word="
self.bing = "http://cn.bing.com/search?q=a+b&go=Submit&qs=n&form=QBLH&pq="
self.yahoo = "https://search.yahoo.com/search;_ylt=Atkyc2y9pQQo09zbTUWM4CWbvZx4?p="
self.db_dir = os.path.abspath('.') + "/../" + "db/"
self.zh_re=re.compile(u"[\u4e00-\u9fa5]+")
self.school = None
self.subject = None
self.url = None
self.count = 0
self.deep_mind = False
self.category_obj = Category()
def doWork(self):
return
def requestWithProxy(self, url):
return requests.get(url, proxies=self.proxies, verify=False)
def requestWithProxy2(self, url):
return requests.get(url, proxies=self.proxies2, verify=False)
def format_subject(self, subject):
match_list = []
for (k, v) in subject_dict.items():
if subject.find('/') != -1 and subject.lower()[0:subject.find('/')].strip().find(k.lower()) != -1:
match_list.append(k)
elif subject.find('/') == -1 and subject.lower().strip().find(k.lower()) != -1:
match_list.append(k)
result = subject
if len(match_list) > 1:
max_len = 0
for key in match_list:
if key.lower() == subject[0: subject.find(' ')].lower().strip():
result = subject_dict[key]
break
if len(key) > max_len:
max_len = len(key)
result = subject_dict[key]
elif len(match_list) == 1:
#print subject_dict[match_list[0]]
result = subject_dict[match_list[0]]
#print subject
if result != subject and subject.find('/') != -1:
last_index = 0
while subject.find('/', last_index + 1) != -1:
last_index = subject.find('/', last_index + 1)
return result + subject[subject.find('/') : last_index + 1]
elif result != subject:
return result + "/"
else:
if subject.strip()[len(subject) - 1 : ] != '/':
return subject + "/"
else:
return subject
def need_update_subject(self, subject):
subject_converted = self.format_subject(subject)
if subject_converted[len(subject_converted) - 1 : ] == '/':
subject_converted = subject_converted[0 : len(subject_converted) - 1]
for item in need_update_subject_list:
if subject_converted.find(item) != -1:
return True
print subject + " not config in all_subject.py, ignore it"
return False
def replace_sp_char(self, text):
while text.find('/') != -1:
text = text[text.find('/') + 1 : ]
return text.replace(",","").replace("&","").replace(":","").replace("-"," ").replace(" "," ").replace(" ","-").lower()
def get_file_name(self, subject, school):
dir_name = self.format_subject(subject)
return self.db_dir + dir_name + self.replace_sp_char(subject) + "-" + school + time.strftime("%Y")
def create_dir_by_file_name(self, file_name):
if os.path.exists(file_name) == False:
index = 0
for i in range(0, len(file_name)):
if file_name[i] == "/":
index = i
if index > 0:
if os.path.exists(file_name[0:index]) == False:
print "creating " + file_name[0:index] + " dir"
os.makedirs(file_name[0:index])
def open_db(self, file_name, append=False):
self.create_dir_by_file_name(file_name)
flag = 'w'
if append:
flag = 'a'
try:
f = open(file_name, flag)
except IOError, err:
print str(err)
return f
def do_upgrade_db(self, file_name):
tmp_file = file_name + ".tmp"
if os.path.exists(file_name) and os.path.exists(tmp_file):
print "upgrading..."
#os.system("diff -y --suppress-common-lines -EbwBi " + file_name + " " + file_name + ".tmp " + "| colordiff")
#print "remove " + file_name[file_name.find("db"):]
os.remove(file_name)
#print "rename " + file_name[file_name.find("db"):] + ".tmp"
os.rename(tmp_file, file_name)
print "upgrade done"
elif os.path.exists(tmp_file):
print "upgrading..."
#print "rename " + file_name[file_name.find("db"):] + ".tmp"
os.rename(tmp_file, file_name)
print "upgrade done"
else:
print "upgrade error"
def cancel_upgrade(self, file_name):
if os.path.exists(file_name + ".tmp"):
os.remove(file_name + ".tmp")
def close_db(self, f):
f.close()
def write_db(self, f, course_num, course_name, url, describe=""):
#if url == "":
# url = self.google + course_num + " " + course_name
if self.category != '' and describe.find('category:') == -1:
describe += ' category:' + self.category
f.write(course_num.strip() + " | " + course_name.replace("|","") + " | " + url + " | " + describe + "\n")
def get_storage_format(self,course_num, course_name, url, describe=""):
if url == "":
url = self.google + course_num + " " + course_name
return course_num.strip() + " | " + course_name.replace("|","") + " | " + url + " | " + describe
def countFileLineNum(self, file_name):
if os.path.exists(file_name):
line_count = len(open(file_name,'rU').readlines())
return line_count
return 0
def truncateUrlData(self, dir_name):
print "truncateUrlData ...."
self.create_dir_by_file_name(get_url_file_name(dir_name))
f = open(get_url_file_name(dir_name), "w+")
f.truncate()
f.close
def delZh(self, text):
if isinstance(text, unicode):
list_u = self.zh_re.findall(text)
if len(list_u) > 0 :
last_ele = list_u[len(list_u) - 1]
last_pos = text.find(last_ele)
first_pos = text.find(list_u[0])
title = ""
if first_pos == 0:
title = text[last_pos + len(last_ele):]
else:
title = text[0:first_pos] + text[last_pos + len(last_ele):].strip()
if title.find("|") != -1:
title = title.replace("|", "").strip()
return title
return text
def getKeyValue(self, option):
value_pos = option.find("value=") + 7
return option[value_pos : option.find('"', value_pos)], option[option.find(">") + 1 : option.find("</", 2)].replace("&", "").replace("\n", "").strip()
|
mit
| -5,365,539,054,781,821,000
| 34.524887
| 162
| 0.515858
| false
| 3.560544
| false
| false
| false
|
codeforamerica/westsac-urban-land-locator
|
farmsList/public/views.py
|
1
|
5434
|
# -*- coding: utf-8 -*-
'''Public section, including homepage and signup.'''
from flask import (Blueprint, request, render_template, flash, url_for,
redirect, session)
from flask_mail import Message
from flask.ext.login import login_user, login_required, logout_user
from farmsList.extensions import mail, login_manager
from farmsList.user.models import User
from farmsList.public.forms import LoginForm, ContactLandOwnerForm
from farmsList.public.models import Farmland
from farmsList.user.forms import RegisterForm
from farmsList.user.models import Email
from farmsList.utils import flash_errors
from farmsList.database import db
blueprint = Blueprint('public', __name__, static_folder="../static")
@login_manager.user_loader
def load_user(id):
return User.get_by_id(int(id))
@blueprint.route("/", methods=["GET", "POST"])
def home():
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", 'success')
redirect_url = request.args.get("next") or url_for("user.members")
return redirect(redirect_url)
else:
flash_errors(form)
return render_template("public/home.html", form=form)
@blueprint.route('/logout/')
@login_required
def logout():
logout_user()
flash('You are logged out.', 'info')
return redirect(url_for('public.home'))
@blueprint.route("/register/", methods=['GET', 'POST'])
def register():
form = RegisterForm(request.form, csrf_enabled=False)
if form.validate_on_submit():
new_user = User.create(username=form.username.data,
email=form.email.data,
password=form.password.data,
active=True)
flash("Thank you for registering. You can now log in.", 'success')
return redirect(url_for('public.home'))
else:
flash_errors(form)
return render_template('public/register.html', form=form)
@blueprint.route("/contact-land-owner/<int:farmlandId>", methods=["GET", "POST"])
def contactLandOwner(farmlandId):
form = ContactLandOwnerForm(request.form)
farmland = Farmland.query.filter(Farmland.id == farmlandId).all()[0]
if form.validate_on_submit():
address = "Unknown" if farmland.address is None else farmland.address
mainBodyContent = ("<p style=\"margin-left: 50px;\">"
"<b>Name:</b> " + form.name.data + "<br>"
"<b>Email:</b> " + form.email.data + "<br>"
"<b>Phone:</b> " + form.phone.data + "<br>"
"</p>"
"<p style=\"margin-left: 50px;\">"
"<b>What is your past experience farming?</b><br>"
"" + form.experience.data + "</p>"
"<p><br>Thanks,<br>"
"Acres"
"</p>")
# msg = Message("Inquiry: " + address + " Property", recipients=["aaronl@cityofwestsacramento.org")
msg = Message("Inquiry: " + address + " Property", recipients=[farmland.email])
msg.html = ("<html>"
"<body>"
"<p>Someone has contacted you about your " + address + " property:</p>"
"" + mainBodyContent + ""
"</body>"
"</html>")
mail.send(msg)
Email.create(sender=msg.sender,
recipients=",".join(msg.recipients),
body=msg.html)
msg = Message("Inquiry: " + address + " Property", recipients=[form.email.data])
msg.html = ("<html>"
"<body>"
"<p>Just a note that we sent your request for more information about the " + address + " property to " + farmland.ownerName + ":</p>"
"" + mainBodyContent + ""
"</body>"
"</html>")
mail.send(msg)
Email.create(sender=msg.sender,
recipients=",".join(msg.recipients),
body=msg.html)
flash("Thanks for your inquiry! We sent your email for more information about the property. " + farmland.ownerName + " will follow up with you shortly.", 'info')
return redirect(url_for('public.home'))
else:
flash_errors(form)
return render_template("public/contact-land-owner.html", form=form, farmland=farmland)
@blueprint.route("/farmland-details/<int:farmlandId>")
def farmlandDetails(farmlandId):
return render_template("public/farmland-details.html")
@blueprint.route("/farmland-approval/<int:farmlandId>")
def farmlandApproval(farmlandId):
return render_template("public/farmland-approval.html")
@blueprint.route("/find-land/")
def find_land():
form = LoginForm(request.form)
# Handle logging in
if request.method == 'POST':
if form.validate_on_submit():
login_user(form.user)
flash("You are logged in.", 'success')
redirect_url = request.args.get("next") or url_for("user.members")
return redirect(redirect_url)
else:
flash_errors(form)
return render_template("public/find_land.html", form=form)
|
bsd-3-clause
| -4,999,825,131,017,609,000
| 42.822581
| 169
| 0.573979
| false
| 3.923466
| false
| false
| false
|
basicthinker/Sexain-MemController
|
gem5-stable/src/mem/SimpleMemory.py
|
1
|
3222
|
# Copyright (c) 2012-2013 ARM Limited
# 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.
#
# Copyright (c) 2005-2008 The Regents of The University of Michigan
# 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: Nathan Binkert
# Andreas Hansson
from m5.params import *
from AbstractMemory import *
class SimpleMemory(AbstractMemory):
type = 'SimpleMemory'
cxx_header = "mem/simple_mem.hh"
port = SlavePort("Slave ports")
latency = Param.Latency('40ns', "Latency on row buffer hit")
latency_miss = Param.Latency('80ns', "Latency on row buffer miss")
latency_var = Param.Latency('0ns', "Request to response latency variance")
# The memory bandwidth limit default is set to 12.8GB/s which is
# representative of a x64 DDR3-1600 channel.
bandwidth = Param.MemoryBandwidth('12.8GB/s',
"Combined read and write bandwidth")
lat_att_operate = Param.Latency('3ns', "ATT operation latency")
lat_buffer_operate = Param.Latency('3ns',
"Version buffer operation latency")
lat_nvm_read = Param.Latency('128ns', "NVM read latency")
lat_nvm_write = Param.Latency('368ns', "NVM write latency")
disable_timing = Param.Bool(True, "If THNVM is not timed")
|
apache-2.0
| 5,142,405,133,285,989,000
| 50.967742
| 78
| 0.753569
| false
| 4.245059
| false
| false
| false
|
ubc/compair
|
alembic/versions/316f3b73962c_modified_criteria_tables.py
|
1
|
2136
|
"""modified criteria tables
Revision ID: 316f3b73962c
Revises: 2fe3d8183c34
Create Date: 2014-09-10 15:42:55.963855
"""
# revision identifiers, used by Alembic.
revision = '316f3b73962c'
down_revision = '2fe3d8183c34'
import logging
from alembic import op
import sqlalchemy as sa
from sqlalchemy import UniqueConstraint, exc
from sqlalchemy.sql import text
from compair.models import convention
def upgrade():
try:
with op.batch_alter_table('Criteria', naming_convention=convention,
table_args=(UniqueConstraint('name'))) as batch_op:
batch_op.drop_constraint('uq_Criteria_name', type_='unique')
except exc.InternalError:
with op.batch_alter_table('Criteria', naming_convention=convention,
table_args=(UniqueConstraint('name'))) as batch_op:
batch_op.drop_constraint('name', type_='unique')
except ValueError:
logging.warning('Drop unique constraint is not support for SQLite, dropping uq_Critiera_name ignored!')
# set existing criteria's active attribute to True using server_default
with op.batch_alter_table('CriteriaAndCourses', naming_convention=convention) as batch_op:
batch_op.add_column(sa.Column('active', sa.Boolean(), default=True, server_default='1', nullable=False))
with op.batch_alter_table('Criteria', naming_convention=convention) as batch_op:
batch_op.add_column(sa.Column('public', sa.Boolean(), default=False, server_default='0', nullable=False))
# set the first criteria as public
t = {"name": "Which is better?", "public": True}
op.get_bind().execute(text("Update Criteria set public=:public where name=:name"), **t)
def downgrade():
with op.batch_alter_table('Criteria', naming_convention=convention,
table_args=(UniqueConstraint('name'))) as batch_op:
batch_op.create_unique_constraint('uq_Criteria_name', ['name'])
batch_op.drop_column('public')
with op.batch_alter_table('CriteriaAndCourses', naming_convention=convention) as batch_op:
batch_op.drop_column('active')
|
gpl-3.0
| -3,058,094,704,712,623,600
| 40.882353
| 113
| 0.684925
| false
| 3.589916
| false
| false
| false
|
BT-jmichaud/l10n-switzerland
|
l10n_ch_payment_slip/tests/test_payment_slip.py
|
1
|
9506
|
# -*- coding: utf-8 -*-
# © 2014-2016 Camptocamp SA
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
import time
import re
import odoo.tests.common as test_common
from odoo.report import render_report
class TestPaymentSlip(test_common.TransactionCase):
_compile_get_ref = re.compile(r'[^0-9]')
def make_bank(self):
company = self.env.ref('base.main_company')
self.assertTrue(company)
partner = self.env.ref('base.main_partner')
self.assertTrue(partner)
bank = self.env['res.bank'].create(
{
'name': 'BCV',
'ccp': '01-1234-1',
'bic': '23452345',
'clearing': '234234',
}
)
bank_account = self.env['res.partner.bank'].create(
{
'partner_id': partner.id,
'bank_id': bank.id,
'bank_bic': bank.bic,
'acc_number': '01-1234-1',
'bvr_adherent_num': '1234567',
'print_bank': True,
'print_account': True,
'print_partner': True,
}
)
bank_account.onchange_acc_number_set_swiss_bank()
self.assertEqual(bank_account.ccp, '01-1234-1')
return bank_account
def make_invoice(self):
if not hasattr(self, 'bank_account'):
self.bank_account = self.make_bank()
account_model = self.env['account.account']
account_debtor = account_model.search([('code', '=', '1100')])
if not account_debtor:
account_debtor = account_model.create({
'code': 1100,
'name': 'Debitors',
'user_type_id':
self.env.ref('account.data_account_type_receivable').id,
'reconcile': True,
})
account_sale = account_model.search([('code', '=', '3200')])
if not account_sale:
account_sale = account_model.create({
'code': 3200,
'name': 'Goods sales',
'user_type_id':
self.env.ref('account.data_account_type_revenue').id,
'reconcile': False,
})
invoice = self.env['account.invoice'].create({
'partner_id': self.env.ref('base.res_partner_12').id,
'reference_type': 'none',
'name': 'A customer invoice',
'account_id': account_debtor.id,
'type': 'out_invoice',
'partner_bank_id': self.bank_account.id
})
self.env['account.invoice.line'].create({
'account_id': account_sale.id,
'product_id': False,
'quantity': 1,
'price_unit': 862.50,
'invoice_id': invoice.id,
'name': 'product that cost 862.50 all tax included',
})
invoice.action_invoice_open()
# waiting for the cache to refresh
attempt = 0
while not invoice.move_id:
invoice.refresh()
time.sleep(0.1)
attempt += 1
if attempt > 20:
break
return invoice
def test_invoice_confirmation(self):
"""Test that confirming an invoice generate slips correctly"""
invoice = self.make_invoice()
self.assertTrue(invoice.move_id)
for line in invoice.move_id.line_ids:
if line.account_id.user_type_id.type in ('payable', 'receivable'):
self.assertTrue(line.transaction_ref)
else:
self.assertFalse(line.transaction_ref)
for line in invoice.move_id.line_ids:
slip = self.env['l10n_ch.payment_slip'].search(
[('move_line_id', '=', line.id)]
)
if line.account_id.user_type_id.type in ('payable', 'receivable'):
self.assertTrue(slip)
self.assertEqual(slip.amount_total, 862.50)
self.assertEqual(slip.invoice_id.id, invoice.id)
else:
self.assertFalse(slip)
def test_slip_validity(self):
"""Test that confirming slip are valid"""
invoice = self.make_invoice()
self.assertTrue(invoice.move_id)
for line in invoice.move_id.line_ids:
slip = self.env['l10n_ch.payment_slip'].search(
[('move_line_id', '=', line.id)]
)
if line.account_id.user_type_id.type in ('payable', 'receivable'):
self.assertTrue(slip.reference)
self.assertTrue(slip.scan_line)
self.assertTrue(slip.slip_image)
self.assertTrue(slip.a4_pdf)
inv_num = line.invoice_id.number
line_ident = self._compile_get_ref.sub(
'', "%s%s" % (inv_num, line.id)
)
self.assertIn(line_ident, slip.reference.replace(' ', ''))
def test_print_report(self):
invoice = self.make_invoice()
data, format = render_report(
self.env.cr,
self.env.uid,
[invoice.id],
'l10n_ch_payment_slip.one_slip_per_page_from_invoice',
{},
context={'force_pdf': True},
)
self.assertTrue(data)
self.assertEqual(format, 'pdf')
def test_print_multi_report_merge_in_memory(self):
# default value as in memory
self.assertEqual(self.env.user.company_id.merge_mode, 'in_memory')
invoice1 = self.make_invoice()
invoice2 = self.make_invoice()
data, format = render_report(
self.env.cr,
self.env.uid,
[invoice1.id, invoice2.id],
'l10n_ch_payment_slip.one_slip_per_page_from_invoice',
{},
context={'force_pdf': True},
)
self.assertTrue(data)
self.assertEqual(format, 'pdf')
def test_print_multi_report_merge_on_disk(self):
self.env.user.company_id.merge_mode = 'on_disk'
invoice1 = self.make_invoice()
invoice2 = self.make_invoice()
data, format = render_report(
self.env.cr,
self.env.uid,
[invoice1.id, invoice2.id],
'l10n_ch_payment_slip.one_slip_per_page_from_invoice',
{},
context={'force_pdf': True},
)
self.assertTrue(data)
self.assertEqual(format, 'pdf')
def test_address_format(self):
invoice = self.make_invoice()
self.assertTrue(invoice.move_id)
line = invoice.move_id.line_ids[0]
slip = self.env['l10n_ch.payment_slip'].search(
[('move_line_id', '=', line.id)]
)
com_partner = slip.get_comm_partner()
address_lines = slip._get_address_lines(com_partner)
self.assertEqual(
address_lines,
[u'93, Press Avenue', u'', u'73377 Le Bourget du Lac']
)
def test_address_format_no_country(self):
invoice = self.make_invoice()
self.assertTrue(invoice.move_id)
line = invoice.move_id.line_ids[0]
slip = self.env['l10n_ch.payment_slip'].search(
[('move_line_id', '=', line.id)]
)
com_partner = slip.get_comm_partner()
com_partner.country_id = False
address_lines = slip._get_address_lines(com_partner)
self.assertEqual(
address_lines,
[u'93, Press Avenue', u'', u'73377 Le Bourget du Lac']
)
def test_address_format_special_format(self):
""" Test special formating without street2 """
ICP = self.env['ir.config_parameter']
ICP.set_param(
'bvr.address.format',
"%(street)s\n%(zip)s %(city)s"
)
invoice = self.make_invoice()
self.assertTrue(invoice.move_id)
line = invoice.move_id.line_ids[0]
slip = self.env['l10n_ch.payment_slip'].search(
[('move_line_id', '=', line.id)]
)
com_partner = slip.get_comm_partner()
com_partner.country_id = False
address_lines = slip._get_address_lines(com_partner)
self.assertEqual(
address_lines,
[u'93, Press Avenue', u'73377 Le Bourget du Lac']
)
def test_address_length(self):
invoice = self.make_invoice()
self.assertTrue(invoice.move_id)
line = invoice.move_id.line_ids[0]
slip = self.env['l10n_ch.payment_slip'].search(
[('move_line_id', '=', line.id)]
)
com_partner = slip.get_comm_partner()
address_lines = slip._get_address_lines(com_partner)
f_size = 11
len_tests = [
(15, (11, None)),
(23, (11, None)),
(26, (10, None)),
(27, (10, None)),
(30, (9, None)),
(32, (8, 34)),
(34, (8, 34)),
(40, (8, 34))]
for text_len, result in len_tests:
com_partner.name = 'x' * text_len
res = slip._get_address_font_size(
f_size, address_lines, com_partner)
self.assertEqual(res, result, "Wrong result for len %s" % text_len)
def test_print_bvr(self):
invoice = self.make_invoice()
bvr = invoice.print_bvr()
self.assertEqual(bvr['report_name'],
'l10n_ch_payment_slip.one_slip_per_page_from_invoice')
self.assertEqual(bvr['report_file'],
'l10n_ch_payment_slip.one_slip_per_page')
|
agpl-3.0
| 7,121,606,143,357,714,000
| 35.417625
| 79
| 0.523935
| false
| 3.664225
| true
| false
| false
|
ncphillips/django_rpg
|
rpg_base/models/encounter.py
|
1
|
1907
|
from django.db import models
class EncounterManager(models.Manager):
def enemy_npcs(self):
pass
def friendly_npcs(self):
pass
def players(self):
return super(EncounterManager, self).get_queryset().filter(character__player_owned=True)
class Encounter(models.Model):
name = models.CharField(max_length=75)
campaign = models.ForeignKey("Campaign")
is_running = models.BooleanField(default=False)
round = models.PositiveIntegerField(default=0)
objects = EncounterManager()
class Meta:
app_label = "rpg_base"
def __unicode__(self):
return self.name
def start(self):
"""
Sets `is_running` to True, and initiative and NPCs.
"""
for row in self.charactertemplateinencounter_set.all():
num = row.num
template = row.character_template
encounter = row.encounter
characters = template.create_characters(encounter.campaign, num=num)
for character in characters:
CharacterInEncounter.objects.create(character=character,
encounter=encounter,
hp_current=character.hp,
initiative=0)
# TODO Roll everyone's initiative.
self.is_running = True
self.save()
def end(self):
# Sum experience from enemy NPCs
# Split experience amongst players
self.is_running = False
self.save()
class CharacterInEncounter(models.Model):
"""
Characters have a rolled Initiative specific to an encounter, as well as
Hit Points.
"""
character = models.ForeignKey("Character")
encounter = models.ForeignKey(Encounter)
hp_current = models.IntegerField()
initiative = models.PositiveIntegerField
|
mit
| -1,455,354,487,229,714,200
| 27.477612
| 96
| 0.598846
| false
| 4.476526
| false
| false
| false
|
SymbiFlow/edalize
|
edalize/trellis.py
|
1
|
3499
|
# Copyright edalize contributors
# Licensed under the 2-Clause BSD License, see LICENSE for details.
# SPDX-License-Identifier: BSD-2-Clause
import os.path
from edalize.edatool import Edatool
from edalize.yosys import Yosys
from importlib import import_module
class Trellis(Edatool):
argtypes = ['vlogdefine', 'vlogparam']
@classmethod
def get_doc(cls, api_ver):
if api_ver == 0:
yosys_help = Yosys.get_doc(api_ver)
trellis_help = {
'lists' : [
{'name' : 'nextpnr_options',
'type' : 'String',
'desc' : 'Additional options for nextpnr'},
{'name' : 'yosys_synth_options',
'type' : 'String',
'desc' : 'Additional options for the synth_ecp5 command'},
]}
combined_members = []
combined_lists = trellis_help['lists']
yosys_members = yosys_help['members']
yosys_lists = yosys_help['lists']
combined_members.extend(m for m in yosys_members if m['name'] not in [i['name'] for i in combined_members])
combined_lists.extend(l for l in yosys_lists if l['name'] not in [i['name'] for i in combined_lists])
return {'description' : "Project Trellis enables a fully open-source flow for ECP5 FPGAs using Yosys for Verilog synthesis and nextpnr for place and route",
'members' : combined_members,
'lists' : combined_lists}
def configure_main(self):
# Write yosys script file
(src_files, incdirs) = self._get_fileset_files()
yosys_synth_options = self.tool_options.get('yosys_synth_options', [])
yosys_synth_options = ["-nomux"] + yosys_synth_options
yosys_edam = {
'files' : self.files,
'name' : self.name,
'toplevel' : self.toplevel,
'parameters' : self.parameters,
'tool_options' : {'yosys' : {
'arch' : 'ecp5',
'yosys_synth_options' : yosys_synth_options,
'yosys_as_subtool' : True,
}
}
}
yosys = getattr(import_module("edalize.yosys"), 'Yosys')(yosys_edam, self.work_root)
yosys.configure()
lpf_files = []
for f in src_files:
if f.file_type == 'LPF':
lpf_files.append(f.name)
elif f.file_type == 'user':
pass
if not lpf_files:
lpf_files = ['empty.lpf']
with open(os.path.join(self.work_root, lpf_files[0]), 'a'):
os.utime(os.path.join(self.work_root, lpf_files[0]), None)
elif len(lpf_files) > 1:
raise RuntimeError("trellis backend supports only one LPF file. Found {}".format(', '.join(lpf_files)))
# Write Makefile
nextpnr_options = self.tool_options.get('nextpnr_options', [])
template_vars = {
'name' : self.name,
'lpf_file' : lpf_files[0],
'nextpnr_options' : nextpnr_options,
}
self.render_template('trellis-makefile.j2',
'Makefile',
template_vars)
|
bsd-2-clause
| 4,870,784,944,533,456,000
| 40.164706
| 168
| 0.497285
| false
| 3.790899
| false
| false
| false
|
dietrichc/streamline-ppc-reports
|
examples/dfp/v201405/creative_service/get_creatives_by_statement.py
|
1
|
2307
|
#!/usr/bin/python
#
# Copyright 2014 Google Inc. 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.
"""This code example gets all image creatives.
To create an image creative, run create_creatives.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information, see the "Caching authentication information"
section of our README.
Tags: CreativeService.getCreativesByStatement
"""
__author__ = ('Nicholas Chen',
'Joseph DiLallo')
# Import appropriate modules from the client library.
from googleads import dfp
def main(client):
# Initialize appropriate service.
creative_service = client.GetService('CreativeService', version='v201405')
# Create statement object to only select image creatives.
values = [{
'key': 'creativeType',
'value': {
'xsi_type': 'TextValue',
'value': 'ImageCreative'
}
}]
query = 'WHERE creativeType = :creativeType'
statement = dfp.FilterStatement(query, values)
# Get creatives by statement.
while True:
response = creative_service.getCreativesByStatement(
statement.ToStatement())
creatives = response['results']
if creatives:
# Display results.
for creative in creatives:
print ('Creative with id \'%s\', name \'%s\', and type \'%s\' was '
'found.' % (creative['id'], creative['name'],
creative['Creative.Type']))
statement.offset += dfp.SUGGESTED_PAGE_LIMIT
else:
break
print '\nNumber of results found: %s' % response['totalResultSetSize']
if __name__ == '__main__':
# Initialize client object.
dfp_client = dfp.DfpClient.LoadFromStorage()
main(dfp_client)
|
apache-2.0
| 8,719,420,815,159,008,000
| 31.041667
| 77
| 0.691374
| false
| 3.903553
| false
| false
| false
|
sssundar/Drone
|
rotation/viz.py
|
1
|
5332
|
# Python script to visualize rotation about a non-body axis.
# Let the lab frame be the inertial frame S.
# Let the origin of the rigid body be O, in the inertial frame S'.
# Let r_ss' be the vector from S to S'.
# Let the body frame relative to O be S''.
# Consider a fixed point on the body, r_s' in S', and r_s'' in S''.
# Assume the body is subject to zero external torques.
# It must be rotating about a fixed axis, n, by Euler's rotation theorem.
# It must have a constant angular velocity about that axis by d/dt L = sum(T_external) = 0 and L = Jw about the rotation axis.
# Let R be the rotation matrix mapping a vector in S'' to S', with inverse R^T
# We know r_s' = R r_s''
# We know d/dt r_s' = (dR/dt R^T) * (R r_s'') = (dR/dt R^T) r_s'
# Therefore we expect (dR/dt R^T) to be the operator (w x) in the S' frame.
# The goal of this script is to visualize this.
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import sys
import numpy as np
from numpy import pi as pi
from numpy import cos as c
from numpy import sin as s
from numpy import dot as dot
from numpy import transpose as transpose
# The axis phi is a rotation about the z axis in the body frame (yaw)
# The axis theta is a rotation about the y axis in the phi-rotated body frame (pitch)
# The axis psi is a rotation about the x axis in the phi, theta-rotated body frame (roll)
def R(phi, theta, psi):
R = np.zeros((3,3))
R[0,0] = c(phi)*c(theta)
R[1,0] = s(phi)*c(theta)
R[2,0] = -s(theta)
R[0,1] = -s(phi)*c(psi) + c(phi)*s(theta)*s(psi)
R[1,1] = c(phi)*c(psi) + s(phi)*s(theta)*s(psi)
R[2,1] = c(theta)*s(psi)
R[0,2] = s(phi)*s(psi) + c(phi)*s(theta)*c(psi)
R[1,2] = -c(phi)*s(psi) + s(phi)*s(theta)*c(psi)
R[2,2] = c(theta)*c(psi)
return R
# Rotate z-axis (0,0,1) by pi radians about x-axis. Should end up at (0,0,-1) cutting across y.
# Rotate (0,0,-1) by pi radians about y-axis. Should end up at (0,0,1) again, cutting across x.
# Try both at the same time. Should still end up at (0,0,1).
def test_R():
e3_spp = np.array((0,0,1))
vectors = []
for k in np.linspace(0,pi,100):
vectors.append(dot(R(0,0,k), e3_spp))
e3_spp = vectors[-1]
for k in np.linspace(0,pi,100):
vectors.append(dot(R(0,k,0), e3_spp))
e3_spp = vectors[-1]
for k in np.linspace(0,pi,100):
vectors.append(dot(R(0,k,k), e3_spp))
xs = [k[0] for k in vectors]
ys = [k[1] for k in vectors]
zs = [k[2] for k in vectors]
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot(xs=xs,ys=ys,zs=zs)
ax.set_xlabel("x")
ax.set_ylabel("y")
ax.set_zlabel("z")
plt.show()
# Sets values lower than epsilon to zero.
# Prints the result with precision 0.3f.
def sanitize_matrix(A):
print ""
epsilon = 0.001
for r in xrange(3):
text = ""
for c in xrange(3):
if abs(A[r, c]) < epsilon:
A[r,c] = 0
text += "%6.2f,\t" % A[r,c]
print text[:-2]
print ""
def sanitize_vector(a):
print ""
epsilon = 0.001
text = ""
for r in xrange(3):
if abs(a[r]) < epsilon:
a[r] = 0
text += "%6.2f,\t" % a[r]
print text[:-2]
print ""
def vectorize(W):
v = np.zeros(3)
v[0] = W[1,0]
v[1] = W[0,2]
v[2] = W[2,1]
return v
# This is the (w x) operator, W, with respect to changing body yaw, pitch, and roll.
# It is dR/dt R^T. The arguments are the current Euler angles and their time derivatives.
def W(phi, theta, psi, dphi, dtheta, dpsi):
Rp = np.zeros((3,3))
Rp[0,0] = (-s(phi)*dphi)*c(theta)
Rp[0,0] += c(phi)*(-s(theta)*dtheta)
Rp[1,0] = (c(phi)*dphi)*c(theta)
Rp[1,0] += s(phi)*(-s(theta)*dtheta)
Rp[2,0] = -c(theta)*dtheta
Rp[0,1] = (-c(phi)*dphi)*c(psi)
Rp[0,1] += -s(phi)*(-s(psi)*dpsi)
Rp[0,1] += (-s(phi)*dphi)*s(theta)*s(psi)
Rp[0,1] += c(phi)*(c(theta)*dtheta)*s(psi)
Rp[0,1] += c(phi)*s(theta)*(c(psi)*dpsi)
Rp[1,1] = (-s(phi)*dphi)*c(psi)
Rp[1,1] += c(phi)*(-s(psi)*dpsi)
Rp[1,1] += (c(phi)*dphi)*s(theta)*s(psi)
Rp[1,1] += s(phi)*(c(theta)*dtheta)*s(psi)
Rp[1,1] += s(phi)*s(theta)*(c(psi)*dpsi)
Rp[2,1] = (-s(theta)*dtheta)*s(psi)
Rp[2,1] += c(theta)*(c(psi)*dpsi)
Rp[0,2] = (c(phi)*dphi)*s(psi)
Rp[0,2] += s(phi)*(c(psi)*dpsi)
Rp[0,2] += (-s(phi)*dphi)*s(theta)*c(psi)
Rp[0,2] += c(phi)*(c(theta)*dtheta)*c(psi)
Rp[0,2] += c(phi)*s(theta)*(-s(psi)*dpsi)
Rp[1,2] = (s(phi)*dphi)*s(psi)
Rp[1,2] += -c(phi)*(c(psi)*dpsi)
Rp[1,2] += (c(phi)*dphi)*s(theta)*c(psi)
Rp[1,2] += s(phi)*(c(theta)*dtheta)*c(psi)
Rp[1,2] += s(phi)*s(theta)*(-s(psi)*dpsi)
Rp[2,2] = (-s(theta)*dtheta)*c(psi)
Rp[2,2] += c(theta)*(-s(psi)*dpsi)
w_i = vectorize(dot(Rp, transpose(R(phi,theta,psi))))
w_b = dot(transpose(R(phi,theta,psi)), w_i)
return (w_i, w_b)
def test_W():
# Is the effective w for a rotation of x rad/s about ek just.. ek*x,
# regardless of the angle about axis ek? We expect W = -W^T as well.
# sanitize_matrix(W(3*pi/12,0,0,2*pi,0,0)[0])
# sanitize_matrix(W(0,3*pi/12,0,0,2*pi,0)[0])
# sanitize_matrix(W(0,0,3*pi/12,0,0,2*pi)[0])
# Let's see what it looks like once we've rotated a bit.
# It's still skew antisymmetric with zero trace! This looks like the operation (w x)!!!!
phi, theta, psi = (pi/4, 3*pi/12, -pi)
w_i, w_b = W(phi, theta, psi, pi, 2*pi, 3*pi)
def Main():
test_W()
if __name__ == "__main__":
Main()
|
gpl-3.0
| 8,605,246,386,922,294,000
| 29.295455
| 126
| 0.597524
| false
| 2.332458
| false
| false
| false
|
mozilla/normandy
|
normandy/recipes/tests/test_checks.py
|
1
|
4355
|
from datetime import timedelta
from django.db.utils import ProgrammingError
import pytest
import requests.exceptions
from normandy.recipes import checks, signing
from normandy.recipes.tests import ActionFactory, RecipeFactory, SignatureFactory, UserFactory
@pytest.mark.django_db
class TestSignaturesUseGoodCertificates(object):
def test_it_works(self):
assert checks.signatures_use_good_certificates(None) == []
def test_it_fails_if_a_signature_does_not_verify(self, mocker, settings):
settings.CERTIFICATES_EXPIRE_EARLY_DAYS = None
recipe = RecipeFactory(approver=UserFactory(), signed=True)
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
mock_verify_x5u.side_effect = signing.BadCertificate("testing exception")
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once_with(recipe.signature.x5u, None)
assert len(errors) == 1
assert errors[0].id == checks.ERROR_BAD_SIGNING_CERTIFICATE
assert recipe.approved_revision.name in errors[0].msg
def test_it_ignores_signatures_without_x5u(self):
recipe = RecipeFactory(approver=UserFactory(), signed=True)
recipe.signature.x5u = None
recipe.signature.save()
actions = ActionFactory(signed=True)
actions.signature.x5u = None
actions.signature.save()
assert checks.signatures_use_good_certificates(None) == []
def test_it_ignores_signatures_not_in_use(self, mocker, settings):
settings.CERTIFICATES_EXPIRE_EARLY_DAYS = None
recipe = RecipeFactory(approver=UserFactory(), signed=True)
SignatureFactory(x5u="https://example.com/bad_x5u") # unused signature
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
def side_effect(x5u, *args):
if "bad" in x5u:
raise signing.BadCertificate("testing exception")
return True
mock_verify_x5u.side_effect = side_effect
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once_with(recipe.signature.x5u, None)
assert errors == []
def test_it_passes_expire_early_setting(self, mocker, settings):
settings.CERTIFICATES_EXPIRE_EARLY_DAYS = 7
recipe = RecipeFactory(approver=UserFactory(), signed=True)
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once_with(recipe.signature.x5u, timedelta(7))
assert errors == []
def test_it_reports_x5u_network_errors(self, mocker):
RecipeFactory(approver=UserFactory(), signed=True)
mock_verify_x5u = mocker.patch("normandy.recipes.checks.signing.verify_x5u")
mock_verify_x5u.side_effect = requests.exceptions.ConnectionError
errors = checks.signatures_use_good_certificates(None)
mock_verify_x5u.assert_called_once()
assert len(errors) == 1
assert errors[0].id == checks.ERROR_COULD_NOT_VERIFY_CERTIFICATE
@pytest.mark.django_db
class TestRecipeSignatureAreCorrect:
def test_it_warns_if_a_field_isnt_available(self, mocker):
"""This is to allow for un-applied to migrations to not break running migrations."""
RecipeFactory(approver=UserFactory(), signed=True)
mock_canonical_json = mocker.patch("normandy.recipes.models.Recipe.canonical_json")
mock_canonical_json.side_effect = ProgrammingError("error for testing")
errors = checks.recipe_signatures_are_correct(None)
assert len(errors) == 1
assert errors[0].id == checks.WARNING_COULD_NOT_CHECK_SIGNATURES
@pytest.mark.django_db
class TestActionSignatureAreCorrect:
def test_it_warns_if_a_field_isnt_available(self, mocker):
"""This is to allow for un-applied to migrations to not break running migrations."""
ActionFactory(signed=True)
mock_canonical_json = mocker.patch("normandy.recipes.models.Action.canonical_json")
mock_canonical_json.side_effect = ProgrammingError("error for testing")
errors = checks.action_signatures_are_correct(None)
assert len(errors) == 1
assert errors[0].id == checks.WARNING_COULD_NOT_CHECK_SIGNATURES
|
mpl-2.0
| -1,509,006,960,226,237,200
| 44.842105
| 94
| 0.7031
| false
| 3.662742
| true
| false
| false
|
Dwii/Master-Thesis
|
implementation/Palabos/cavity_benchmark/plot_benchmark.py
|
1
|
1854
|
# Display a list of *.dat files in a bar chart.
# Based on an example from https://chrisalbon.com/python/matplotlib_grouped_bar_plot.html
import sys
import os
import matplotlib.pyplot as plt
import numpy as np
if len(sys.argv) > 3 and (len(sys.argv)-3) % 2 :
print("usage: python3 {0} <benchmark> <image path> (<dat1> <legend1> [<dat2> <legend2>] .. [<datN> <legendN>] ) ".format(os.path.basename(sys.argv[0])))
exit(1)
benchmark = sys.argv[1]
image_path = sys.argv[2]
groups = (len(sys.argv)-3)/2
# Load benchark
domains = ()
nb_setups = 0
for line in open(benchmark,'r'):
n, snx, sny, snz = line.split()
domains += ( r"{0}$^3$".format(snx), ) #+= ( "{0}x{1}x{2}".format(snx, sny, snz), )
nb_setups += 1
# Setting the positions and width for the bars
pos = list(range(nb_setups))
width = 1 / (groups+2)
# Plotting the bars
fig, ax = plt.subplots(figsize=(10,5))
prop_iter = iter(plt.rcParams['axes.prop_cycle'])
legends = ()
maxLups = 0
for i, argi in enumerate(range(3, len(sys.argv), 2)):
mlups = np.array(list(map(float, open(sys.argv[argi])))) / 1E6
legends += ( sys.argv[argi+1], )
maxLups = max(maxLups, max(mlups))
plt.bar([p + width*i for p in pos],
mlups,
width,
alpha=0.5,
color=next(prop_iter)['color'])
# Set the y axis label
ax.set_ylabel('MLUPS')
ax.set_xlabel('Taille du sous-domaine')
# Set the chart's title
#ax.set_title(title)
# Set the position of the x ticks
ax.set_xticks([p + 1.5 * width for p in pos])
# Set the labels for the x ticks
ax.set_xticklabels(domains)
# Setting the x-axis and y-axis limits
plt.xlim(min(pos)-width, max(pos)+width*4)
#plt.ylim([0, maxLups] )
# Adding the legend and showing the plot
plt.legend(legends, loc='upper center')
ax.yaxis.grid()
plt.savefig(image_path)
plt.tight_layout()
plt.show()
|
mit
| -7,959,568,732,201,215,000
| 26.279412
| 156
| 0.641855
| false
| 2.714495
| false
| false
| false
|
AxelTLarsson/robot-localisation
|
robot_localisation/main.py
|
1
|
6009
|
"""
This module contains the logic to run the simulation.
"""
import sys
import os
import argparse
import numpy as np
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from robot_localisation.grid import Grid, build_transition_matrix
from robot_localisation.robot import Robot, Sensor
from robot_localisation.hmm_filter import FilterState
def help_text():
"""
Return a helpful text explaining usage of the program.
"""
return """
------------------------------- HMM Filtering ---------------------------------
Type a command to get started. Type 'quit' or 'q' to quit.
Valid commands (all commands are case insensitive):
ENTER move the robot one step further in the simulation,
will also output current pose and estimated
position of the robot
help show this help text
show T show the transition matrix T
show f show the filter column vector
show O show the observation matrix
quit | q quit the program
-------------------------------------------------------------------------------
"""
def main():
parser = argparse.ArgumentParser(description='Robot localisation with HMM')
parser.add_argument(
'-r', '--rows',
type=int,
help='the number of rows on the grid, default is 4',
default=4)
parser.add_argument(
'-c', '--columns',
type=int,
help='the number of columns on the grid, default is 4',
default=4)
args = parser.parse_args()
# Initialise the program
size = (args.rows, args.columns)
the_T_matrix = build_transition_matrix(*size)
the_filter = FilterState(transition=the_T_matrix)
the_sensor = Sensor()
the_grid = Grid(*size)
the_robot = Robot(the_grid, the_T_matrix)
sensor_value = None
obs = None
print(help_text())
print("Grid size is {} x {}".format(size[0], size[1]))
print(the_robot)
print("The sensor says: {}".format(sensor_value))
filter_est = the_grid.index_to_pose(the_filter.belief_state)
pos_est = (filter_est[0], filter_est[1])
print("The HMM filter thinks the robot is at {}".format(filter_est))
print("The Manhattan distance is: {}".format(
manhattan(the_robot.get_position(), pos_est)))
np.set_printoptions(linewidth=1000)
# Main loop
while True:
user_command = str(input('> '))
if user_command.upper() == 'QUIT' or user_command.upper() == 'Q':
break
elif user_command.upper() == 'HELP':
print(help_text())
elif user_command.upper() == 'SHOW T':
print(the_T_matrix)
elif user_command.upper() == 'SHOW F':
print(the_filter.belief_matrix)
elif user_command.upper() == 'SHOW O':
print(obs)
elif not user_command:
# take a step then approximate etc.
the_robot.step()
sensor_value = the_sensor.get_position(the_robot)
obs = the_sensor.get_obs_matrix(sensor_value, size)
the_filter.forward(obs)
print(the_robot)
print("The sensor says: {}".format(sensor_value))
filter_est = the_grid.index_to_pose(the_filter.belief_state)
pos_est = (filter_est[0], filter_est[1])
print("The HMM filter thinks the robot is at {}".format(filter_est))
print("The Manhattan distance is: {}".format(
manhattan(the_robot.get_position(), pos_est)))
else:
print("Unknown command!")
def manhattan(pos1, pos2):
"""
Calculate the Manhattan distance between pos1 and pos2.
"""
x1, y1 = pos1
x2, y2 = pos2
return abs(x1-x2) + abs(y1-y2)
def automated_run():
import matplotlib.pyplot as plt
fig = plt.figure(figsize=(10, 7))
navg = 20
nsteps = 10
for size in (2, 2), (3, 3), (4, 4), (5, 5), (10, 10):
avg_distances = np.zeros(shape=(nsteps+1,))
for n in range(navg):
distances = list()
none_values = list()
the_T_matrix = build_transition_matrix(*size)
the_filter = FilterState(transition=the_T_matrix)
the_sensor = Sensor()
the_grid = Grid(*size)
the_robot = Robot(the_grid, the_T_matrix)
# get the manhattan distance at the start
filter_est = the_grid.index_to_pose(the_filter.belief_state)
pos_est = (filter_est[0], filter_est[1])
distances.append(manhattan(the_robot.get_position(), pos_est))
for i in range(nsteps):
# take a step then approximate etc.
the_robot.step()
sensor_value = the_sensor.get_position(the_robot)
if sensor_value is None:
none_values.append(i) # keep track of where None was returned
obs = the_sensor.get_obs_matrix(sensor_value, size)
the_filter.forward(obs)
filter_est = the_grid.index_to_pose(the_filter.belief_state)
pos_est = (filter_est[0], filter_est[1])
distances.append(manhattan(the_robot.get_position(), pos_est))
avg_distances += np.array(distances)
avg_distances /= navg
base_line, = plt.plot(avg_distances, label="Grid size {}".format(size))
# for point in none_values:
# plt.scatter(point, distances[point], marker='o',
# color=base_line.get_color(), s=40)
plt.legend()
plt.xlim(0, nsteps)
plt.ylim(0,)
plt.ylabel("Manhattan distance")
plt.xlabel("Steps")
plt.title("Manhattan distance from true position and inferred position \n"
"from the hidden Markov model (average over %s runs)" % navg)
fig.savefig("automated_run.png")
plt.show()
if __name__ == '__main__':
main()
# automated_run()
|
mit
| 1,122,709,431,503,210,400
| 33.337143
| 82
| 0.564487
| false
| 3.786389
| false
| false
| false
|
confpack/confpacker
|
libconfpacker/packagers/base/__init__.py
|
1
|
4696
|
from __future__ import absolute_import
from datetime import datetime
import logging
import os
import os.path
import subprocess
import yaml
from cpcommon import cd
from .task import Task
class Package(object):
def src_path(self, *path):
return os.path.join(self.src_directory, *path)
def __init__(self, name, src_directory, build_version):
self.logger = logging.getLogger("confpacker")
self.name = name
self.src_directory = src_directory
self.build_version = build_version
self.meta = self.load_meta()
self.main_tasks = self.load_tasks()
self.main_handlers = self.load_handlers(ignore_error=True)
self.vars = self.load_vars(ignore_error=True)
self.secrets = self.load_secrets(ignore_error=True)
self.files = self.scan_files()
self.templates = self.scan_templates()
def _load_yml_file(self, filepath, expected_type, ignore_error=False):
if not os.path.exists(filepath):
if ignore_error:
return expected_type()
raise LookupError("cannot find {}".format(filepath))
with open(filepath) as f:
thing = yaml.load(f.read())
if thing is None and ignore_error:
return expected_type()
if not isinstance(thing, expected_type):
raise TypeError("expected a {} but got a {} in {}".format(expected_type, type(thing), filepath))
return thing
def load_meta(self):
meta_path = self.src_path("meta.yml")
return self._load_yml_file(meta_path, dict, ignore_error=True)
def load_tasks(self, filename="main.yml", ignore_error=False):
tasks_path = self.src_path("tasks", filename)
return [Task(rt) for rt in self._load_yml_file(tasks_path, list, ignore_error=ignore_error)]
def load_handlers(self, filename="main.yml", ignore_error=False):
handlers_path = self.src_path("handlers", filename)
return self._load_yml_file(handlers_path, list, ignore_error=ignore_error)
def load_vars(self, filename="main.yml", directory="vars", ignore_error=False):
vars_path = self.src_path(directory, filename)
return self._load_yml_file(vars_path, dict, ignore_error=ignore_error)
def load_secrets(self, filename="main.yml", ignore_error=False):
# TODO: this is not yet implemented
return {}
def scan_directory_for_files(self, directory):
base_path = self.src_path(directory)
if not os.path.isdir(base_path):
return []
files = []
for root, dirs, files_in_dir in os.walk(base_path):
for filename in files_in_dir:
path = os.path.join(root, filename)
if path.startswith(base_path):
target_path = path[len(base_path):]
else:
# TODO: This may happen for a symlink. Need to be investigated
raise RuntimeError("file path {} does not start with src directory path {}?".format(path, self.src_directory))
files.append((path, target_path))
return files
def scan_files(self):
return self.scan_directory_for_files("files")
def scan_templates(self):
return self.scan_directory_for_files("templates")
class BasePackager(object):
def __init__(self, build_config, output_dir):
self.logger = logging.getLogger("confpacker")
self.build_config = build_config
self.output_dir = os.path.abspath(output_dir)
if not os.path.exists(self.output_dir):
os.mkdir(self.output_dir)
def get_source_git_sha(self):
with cd(self.build_config.src_directory):
if os.path.isdir(".git"):
sha = subprocess.check_output(["git", "rev-parse", "--short", "HEAD"]).strip()
else:
sha = ""
return sha
def get_timestamp(self):
return datetime.now().strftime("%Y%m%d%H%M%S")
def get_build_version(self):
timestamp = self.get_timestamp()
git_sha = self.get_source_git_sha()
build_version = timestamp
if git_sha:
build_version = build_version + "-" + git_sha
return build_version
def build(self):
build_version = self.get_build_version()
this_out_dir = os.path.join(self.output_dir, build_version)
if os.path.exists(this_out_dir):
raise RuntimeError("{} already exists? this should not happen".format(this_out_dir))
os.mkdir(this_out_dir)
for pkg_name, pkg_src_path in self.build_config.package_paths.items():
package = Package(pkg_name, pkg_src_path, build_version)
this_package_out_dir = os.path.join(this_out_dir, pkg_name)
os.mkdir(this_package_out_dir)
self.build_one(package, build_version, this_package_out_dir)
def build_one(self, package, build_version, out_dir):
"""Builds one package
out_dir is for this package. The final should emit a file at <out_dir>/package.<typename>
"""
raise NotImplementedError
|
apache-2.0
| -5,239,246,716,933,589,000
| 30.945578
| 120
| 0.672487
| false
| 3.48368
| false
| false
| false
|
chromium/chromium
|
third_party/android_deps/libs/com_google_errorprone_error_prone_annotation/3pp/fetch.py
|
5
|
1396
|
#!/usr/bin/env python
# Copyright 2021 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.
# This is generated, do not edit. Update BuildConfigGenerator.groovy and
# 3ppFetch.template instead.
from __future__ import print_function
import argparse
import json
import os
_FILE_URL = 'https://repo.maven.apache.org/maven2/com/google/errorprone/error_prone_annotation/2.7.1/error_prone_annotation-2.7.1.jar'
_FILE_NAME = 'error_prone_annotation-2.7.1.jar'
_FILE_VERSION = '2.7.1'
def do_latest():
print(_FILE_VERSION)
def get_download_url(version):
if _FILE_URL.endswith('.jar'):
ext = '.jar'
elif _FILE_URL.endswith('.aar'):
ext = '.aar'
else:
raise Exception('Unsupported extension for %s' % _FILE_URL)
partial_manifest = {
'url': [_FILE_URL],
'name': [_FILE_NAME],
'ext': ext,
}
print(json.dumps(partial_manifest))
def main():
ap = argparse.ArgumentParser()
sub = ap.add_subparsers()
latest = sub.add_parser("latest")
latest.set_defaults(func=lambda _opts: do_latest())
download = sub.add_parser("get_url")
download.set_defaults(
func=lambda _opts: get_download_url(os.environ['_3PP_VERSION']))
opts = ap.parse_args()
opts.func(opts)
if __name__ == '__main__':
main()
|
bsd-3-clause
| 6,280,813,716,697,671,000
| 23.928571
| 134
| 0.648997
| false
| 3.21659
| false
| false
| false
|
mclaughlin6464/pearce
|
bin/optimization/sloppy_joes_optimization_indiv_bins.py
|
1
|
1573
|
from pearce.emulator import OriginalRecipe, ExtraCrispy, SpicyBuffalo, LemonPepperWet
from pearce.mocks import cat_dict
import numpy as np
from os import path
from SloppyJoes import lazy_wrapper
training_file = '/scratch/users/swmclau2/xi_zheng07_cosmo_lowmsat/PearceRedMagicXiCosmoFixedNd.hdf5'
em_method = 'gp'
fixed_params = {'z':0.0, 'r': 0.19118072}
#emu = SpicyBuffalo(training_file, method = em_method, fixed_params=fixed_params,
# custom_mean_function = 'linear', downsample_factor = 0.01)
emu = OriginalRecipe(training_file, method = em_method, fixed_params=fixed_params,
custom_mean_function = 'linear', downsample_factor = 0.01)
def resids_bins(p, gps, xs, ys, yerrs):
res = []
p_np = np.array(p).reshape((len(gps), -1))
for gp, x, y,yerr, dy, p in zip(gps, xs, ys,yerrs, emu.downsample_y, p_np):
gp.set_parameter_vector(p)
gp.recompute()
r = (gp.predict(dy, x, return_cov=False)-y)/(yerr+1e-5)
res.append(r)
#print res[0].shape
return np.hstack(res)
def resids(p, gp, x, y, yerr):
p = np.array(p)
gp.set_parameter_vector(p)
gp.recompute()
res = (gp.predict(emu.downsample_y, x, return_cov=False)-y)/(yerr+1e-5)
#print res[0].shape
return res
n_hps = len(emu._emulator.get_parameter_vector())
#vals = np.ones((n_hps*emu.n_bins))
vals = np.ones((n_hps,))
args = (emu._emulator, emu.x, emu.y, emu.yerr)
result = lazy_wrapper(resids, vals, func_args = args, print_level = 3)\
print result
np.savetxt('sloppy_joes_result_indiv_bins.npy', result)
|
mit
| 905,506,763,249,726,100
| 33.195652
| 100
| 0.664336
| false
| 2.6
| false
| false
| false
|
Alexanderkorn/Automatisation
|
oude scripts/Self/IFScraper.py
|
1
|
2199
|
__author__ = 'alexander'
import urllib2
import os
from lib import pyperclip
def PageScrape(pageurl):
hdr= {'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.110 Safari/537.36'}
req = urllib2.Request(pageurl, "", hdr)
response = urllib2.urlopen(req)
html = response.read()
search = 'Gallery:'
for i in range(len(html)-len(search)):
if search == html[i:i+len(search)]:
foldername = html[i+len(search)-1:]
foldername = foldername.split('<')[3].split('>')[1]
while foldername[-1]=='.' or foldername[-1]==' ':
foldername = foldername[:-1]
search = 'original=\"'
imgnum = 1
imgcount = 0
for i in range(len(html)-len(search)):
if search == html[i:i+len(search)]:
imgcount += 1
print "\n\nThere are "+str(imgcount)+" pics in the gallery: "+foldername+"."
contnum = 2
contnum = raw_input("Would you like to download them all? 1=yes 2=no: ")
foldername = 'Downloads/'+foldername
if contnum == '1':
print '\n'
try:
os.makedirs(foldername)
except:
print "Error, make sure there is no directory with this script"
return 0
for i in range(len(html)-len(search)):
if search == html[i:i+len(search)]:
imgurl = html[i+len(search):]
imgurl = imgurl.split('"')[0]
if imgurl[-4] == '.':
imgname = foldername+'/'+str(imgnum)+imgurl[-4:]
else:
imgname = foldername+'/'+str(imgnum)+imgurl[-5:]
f = open(imgname, 'wb')
f.write(urllib2.urlopen(imgurl).read())
f.close()
print '\t'+str(imgnum)+'/'+str(imgcount)+ ' completed\n'
imgnum += 1
return 0
urltest = pyperclip.paste()
print "URL in clipboard: "+ urltest
use = raw_input("\nWould you like to use the above url? 1=yes 2=input other: ")
if use == '1':
url = urltest
else:
url = raw_input("\nEnter the url: ")
PageScrape(url)
|
gpl-3.0
| -8,366,557,063,171,999,000
| 36.271186
| 135
| 0.554343
| false
| 3.367534
| false
| false
| false
|
jdumas/autobib
|
pdftitle.py
|
1
|
14035
|
#!/usr/bin/env python2.7
# https://gist.github.com/nevesnunes/84b2eb7a2cf63cdecd170c139327f0d6
"""
Extract title from PDF file.
Dependencies:
pip install --user unidecode pyPDF PDFMiner
Usage:
find . -name "*.pdf" | xargs -I{} pdftitle -d tmp --rename {}
Limitations:
- No processing of CID keyed fonts. PDFMiner seems to decode them
in some methods (e.g. PDFTextDevice.render_string()).
- Some `LTTextLine` elements report incorrect height, leading to some
blocks of text being consider bigger than title text.
- Heuristics are used to judge invalid titles, implying the possibility of
false positives.
"""
import getopt
import os
import re
import string
import subprocess
import sys
import unidecode
from pyPdf import PdfFileReader
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import PDFPageAggregator
from pdfminer.layout import LAParams, LTChar, LTFigure, LTTextBox, LTTextLine
__all__ = ['pdf_title']
def make_parsing_state(*sequential, **named):
enums = dict(zip(sequential, range(len(sequential))), **named)
return type('ParsingState', (), enums)
CHAR_PARSING_STATE = make_parsing_state('INIT_X', 'INIT_D', 'INSIDE_WORD')
def log(text):
if IS_LOG_ON:
print('--- ' + text)
IS_LOG_ON = False
MIN_CHARS = 6
MAX_WORDS = 20
MAX_CHARS = MAX_WORDS * 10
TOLERANCE = 1e-06
def sanitize(filename):
"""Turn string into a valid file name.
"""
# If the title was picked up from text, it may be too large.
# Preserve a certain number of words and characters
words = filename.split(' ')
filename = ' '.join(words[0:MAX_WORDS])
if len(filename) > MAX_CHARS:
filename = filename[0:MAX_CHARS]
# Preserve letters with diacritics
try:
filename = unidecode.unidecode(filename.encode('utf-8').decode('utf-8'))
except UnicodeDecodeError:
print("*** Skipping invalid title decoding for file %s! ***" % filename)
# Preserve subtitle and itemization separators
filename = re.sub(r',', ' ', filename)
filename = re.sub(r': ', ' - ', filename)
# Strip repetitions
filename = re.sub(r'\.pdf(\.pdf)*$', '', filename)
filename = re.sub(r'[ \t][ \t]*', ' ', filename)
valid_chars = "-_.() %s%s" % (string.ascii_letters, string.digits)
return ''.join([c for c in filename if c in valid_chars])
def meta_title(filename):
"""Title from pdf metadata.
"""
docinfo = PdfFileReader(file(filename, 'rb')).getDocumentInfo()
if docinfo is None:
return ''
return docinfo.title if docinfo.title else ''
def junk_line(line):
"""Judge if a line is not appropriate for a title.
"""
too_small = len(line.strip()) < MIN_CHARS
is_placeholder_text = bool(re.search(r'^[0-9 \t-]+(abstract|introduction)?\s+$|^(abstract|unknown|title|untitled):?$', line.strip().lower()))
is_copyright_info = bool(re.search(r'paper\s+title|technical\s+report|proceedings|preprint|to\s+appear|submission|(integrated|international).*conference|transactions\s+on|symposium\s+on|downloaded\s+from\s+http', line.lower()))
# NOTE: Titles which only contain a number will be discarded
stripped_to_ascii = ''.join([c for c in line.strip() if c in string.ascii_letters])
ascii_length = len(stripped_to_ascii)
stripped_to_chars = re.sub(r'[ \t\n]', '', line.strip())
chars_length = len(stripped_to_chars)
is_serial_number = ascii_length < chars_length / 2
return too_small or is_placeholder_text or is_copyright_info or is_serial_number
def empty_str(s):
return len(s.strip()) == 0
def is_close(a, b, relative_tolerance=TOLERANCE):
return abs(a-b) <= relative_tolerance * max(abs(a), abs(b))
def update_largest_text(line, y0, size, largest_text):
log('update size: ' + str(size))
log('largest_text size: ' + str(largest_text['size']))
# Sometimes font size is not correctly read, so we
# fallback to text y0 (not even height may be calculated).
# In this case, we consider the first line of text to be a title.
if ((size == largest_text['size'] == 0) and (y0 - largest_text['y0'] < -TOLERANCE)):
return largest_text
# If it is a split line, it may contain a new line at the end
line = re.sub(r'\n$', ' ', line)
if (size - largest_text['size'] > TOLERANCE):
largest_text = {
'contents': line,
'y0': y0,
'size': size
}
# Title spans multiple lines
elif is_close(size, largest_text['size']):
largest_text['contents'] = largest_text['contents'] + line
largest_text['y0'] = y0
return largest_text
def extract_largest_text(obj, largest_text):
# Skip first letter of line when calculating size, as articles
# may enlarge it enough to be bigger then the title size.
# Also skip other elements such as `LTAnno`.
for i, child in enumerate(obj):
if isinstance(child, LTTextLine):
log('lt_obj child line: ' + str(child))
for j, child2 in enumerate(child):
if j > 1 and isinstance(child2, LTChar):
largest_text = update_largest_text(child.get_text(), child2.y0, child2.size, largest_text)
# Only need to parse size of one char
break
elif i > 1 and isinstance(child, LTChar):
log('lt_obj child char: ' + str(child))
largest_text = update_largest_text(obj.get_text(), child.y0, child.size, largest_text)
# Only need to parse size of one char
break
return largest_text
def extract_figure_text(lt_obj, largest_text):
"""
Extract text contained in a `LTFigure`.
Since text is encoded in `LTChar` elements, we detect separate lines
by keeping track of changes in font size.
"""
text = ''
line = ''
y0 = 0
size = 0
char_distance = 0
char_previous_x1 = 0
state = CHAR_PARSING_STATE.INIT_X
for child in lt_obj:
log('child: ' + str(child))
# Ignore other elements
if not isinstance (child, LTChar):
continue
char_y0 = child.y0
char_size = child.size
char_text = child.get_text()
decoded_char_text = unidecode.unidecode(char_text.encode('utf-8').decode('utf-8'))
log('char: ' + str(char_size) + ' ' + str(decoded_char_text))
# A new line was detected
if char_size != size:
log('new line')
largest_text = update_largest_text(line, y0, size, largest_text)
text += line + '\n'
line = char_text
y0 = char_y0
size = char_size
char_previous_x1 = child.x1
state = CHAR_PARSING_STATE.INIT_D
else:
# Spaces may not be present as `LTChar` elements,
# so we manually add them.
# NOTE: A word starting with lowercase can't be
# distinguished from the current word.
char_current_distance = abs(child.x0 - char_previous_x1)
log('char_current_distance: ' + str(char_current_distance))
log('char_distance: ' + str(char_distance))
log('state: ' + str(state))
# Initialization
if state == CHAR_PARSING_STATE.INIT_X:
char_previous_x1 = child.x1
state = CHAR_PARSING_STATE.INIT_D
elif state == CHAR_PARSING_STATE.INIT_D:
# Update distance only if no space is detected
if (char_distance > 0) and (char_current_distance < char_distance * 2.5):
char_distance = char_current_distance
if (char_distance < 0.1):
char_distance = 0.1
state = CHAR_PARSING_STATE.INSIDE_WORD
# If the x-position decreased, then it's a new line
if (state == CHAR_PARSING_STATE.INSIDE_WORD) and (child.x1 < char_previous_x1):
log('x-position decreased')
line += ' '
char_previous_x1 = child.x1
state = CHAR_PARSING_STATE.INIT_D
# Large enough distance: it's a space
elif (state == CHAR_PARSING_STATE.INSIDE_WORD) and (char_current_distance > char_distance * 8.5):
log('space detected')
log('char_current_distance: ' + str(char_current_distance))
log('char_distance: ' + str(char_distance))
line += ' '
char_previous_x1 = child.x1
# When larger distance is detected between chars, use it to
# improve our heuristic
elif (state == CHAR_PARSING_STATE.INSIDE_WORD) and (char_current_distance > char_distance) and (char_current_distance < char_distance * 2.5):
char_distance = char_current_distance
char_previous_x1 = child.x1
# Chars are sequential
else:
char_previous_x1 = child.x1
child_text = child.get_text()
if not empty_str(child_text):
line += child_text
return (largest_text, text)
def pdf_text(filename):
fp = open(filename, 'rb')
parser = PDFParser(fp)
doc = PDFDocument(parser, '')
parser.set_document(doc)
rsrcmgr = PDFResourceManager()
laparams = LAParams()
device = PDFPageAggregator(rsrcmgr, laparams=laparams)
interpreter = PDFPageInterpreter(rsrcmgr, device)
text = ''
largest_text = {
'contents': '',
'y0': 0,
'size': 0
}
for page in PDFPage.create_pages(doc):
interpreter.process_page(page)
layout = device.get_result()
for lt_obj in layout:
log('lt_obj: ' + str(lt_obj))
if isinstance(lt_obj, LTFigure):
(largest_text, figure_text) = extract_figure_text(lt_obj, largest_text)
text += figure_text
elif isinstance(lt_obj, (LTTextBox, LTTextLine)):
# Ignore body text blocks
stripped_to_chars = re.sub(r'[ \t\n]', '', lt_obj.get_text().strip())
if (len(stripped_to_chars) > MAX_CHARS * 2):
continue
largest_text = extract_largest_text(lt_obj, largest_text)
text += lt_obj.get_text() + '\n'
# Remove unprocessed CID text
largest_text['contents'] = re.sub(r'(\(cid:[0-9 \t-]*\))*', '', largest_text['contents'])
# Only parse the first page
return (largest_text, text)
def title_start(lines):
for i, line in enumerate(lines):
if not empty_str(line) and not junk_line(line):
return i
return 0
def title_end(lines, start, max_lines=2):
for i, line in enumerate(lines[start+1:start+max_lines+1], start+1):
if empty_str(line):
return i
return start + 1
def text_title(filename):
"""Extract title from PDF's text.
"""
(largest_text, lines_joined) = pdf_text(filename)
if empty_str(largest_text['contents']):
lines = lines_joined.strip().split('\n')
i = title_start(lines)
j = title_end(lines, i)
text = ' '.join(line.strip() for line in lines[i:j])
else:
text = largest_text['contents'].strip()
# Strip dots, which conflict with os.path's splittext()
text = re.sub(r'\.', '', text)
# Strip extra whitespace
text = re.sub(r'[\t\n]', '', text)
return text
def pdftotext_title(filename):
"""Extract title using `pdftotext`
"""
command = 'pdftotext {} -'.format(re.sub(' ', '\\ ', filename))
process = subprocess.Popen([command], \
shell=True, \
stdout=subprocess.PIPE, \
stderr=subprocess.PIPE)
out, err = process.communicate()
lines = out.strip().split('\n')
i = title_start(lines)
j = title_end(lines, i)
text = ' '.join(line.strip() for line in lines[i:j])
# Strip dots, which conflict with os.path's splittext()
text = re.sub(r'\.', '', text)
# Strip extra whitespace
text = re.sub(r'[\t\n]', '', text)
return text
def valid_title(title):
return not empty_str(title) and not junk_line(title) and empty_str(os.path.splitext(title)[1])
def pdf_title(filename):
"""Extract title using one of multiple strategies.
"""
try:
title = meta_title(filename)
if valid_title(title):
return title
except Exception as e:
print("*** Skipping invalid metadata for file %s! ***" % filename)
print(e)
try:
title = text_title(filename)
if valid_title(title):
return title
except Exception as e:
print("*** Skipping invalid parsing for file %s! ***" % filename)
print(e)
title = pdftotext_title(filename)
if valid_title(title):
return title
return os.path.basename(os.path.splitext(filename)[0])
if __name__ == "__main__":
opts, args = getopt.getopt(sys.argv[1:], 'nd:', ['dry-run', 'rename'])
dry_run = False
rename = False
target_dir = "."
for opt, arg in opts:
if opt in ['-n', '--dry-run']:
dry_run = True
elif opt in ['--rename']:
rename = True
elif opt in ['-d']:
target_dir = arg
if len(args) == 0:
print("Usage: %s [-d output] [--dry-run] [--rename] filenames" % sys.argv[0])
sys.exit(1)
for filename in args:
title = pdf_title(filename)
title = sanitize(' '.join(title.split()))
if rename:
new_name = os.path.join(target_dir, title + ".pdf")
print("%s => %s" % (filename, new_name))
if not dry_run:
if os.path.exists(new_name):
print("*** Target %s already exists! ***" % new_name)
else:
os.rename(filename, new_name)
else:
print(title)
|
gpl-3.0
| 4,369,930,326,702,331,000
| 34.441919
| 231
| 0.591307
| false
| 3.603338
| false
| false
| false
|
yaybu/touchdown
|
touchdown/provisioner/fuselage.py
|
1
|
4827
|
# Copyright 2015 Isotoma Limited
#
# 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 __future__ import absolute_import
import re
from touchdown.core import argument, errors, resource, serializers
from . import provisioner
try:
import fuselage
from fuselage import argument as f_args, builder, bundle, resources
except ImportError:
raise errors.Error(
"You need the fuselage package to use the fuselage_bundle resource"
)
def underscore(title):
return re.sub(r"(?<=[a-z])(?=[A-Z])", u"_", title).lower()
arguments = {
f_args.Boolean: lambda resource_type, klass, arg: argument.Boolean(field=arg),
f_args.String: lambda resource_type, klass, arg: argument.String(field=arg),
f_args.FullPath: lambda resource_type, klass, arg: argument.String(field=arg),
f_args.File: lambda resource_type, klass, arg: argument.String(field=arg),
f_args.Integer: lambda resource_type, klass, arg: argument.Integer(field=arg),
f_args.Octal: lambda resource_type, klass, arg: argument.Integer(field=arg),
f_args.Dict: lambda resource_type, klass, arg: argument.Dict(field=arg),
f_args.List: lambda resource_type, klass, arg: argument.List(field=arg),
f_args.SubscriptionArgument: lambda resource_type, klass, arg: argument.List(
field=arg
),
f_args.PolicyArgument: lambda resource_type, klass, arg: argument.String(
field=arg, choices=resource_type.policies.keys()
),
}
class FuselageResource(resource.Resource):
@classmethod
def adapt(base_klass, resource_type):
args = {
"resource_name": underscore(resource_type.__resource_name__),
"fuselage_class": resource_type,
"root": argument.Resource(Bundle),
}
for arg, klass in resource_type.__args__.items():
args[arg] = arguments[klass.__class__](resource_type, klass, arg)
cls = type(resource_type.__resource_name__, (base_klass,), args)
def _(self, **kwargs):
arguments = {"parent": self}
arguments.update(kwargs)
resource = cls(**arguments)
if not self.resources:
self.resources = []
self.resources.append(resource)
self.add_dependency(resource)
return resource
setattr(Bundle, "add_%s" % cls.resource_name, _)
return cls
class BundleSerializer(serializers.Serializer):
def render(self, runner, value):
b = bundle.ResourceBundle()
for res in value:
b.add(res.fuselage_class(**serializers.Resource().render(runner, res)))
return builder.build(b)
def pending(self, runner, value):
for res in value:
if serializers.Resource().pending(runner, res):
return True
return False
class Bundle(provisioner.Provisioner):
resource_name = "fuselage_bundle"
always_apply = argument.Boolean()
resources = argument.List(
argument.Resource(FuselageResource),
field="script",
serializer=BundleSerializer(),
)
sudo = argument.Boolean(field="sudo", default=True)
class Describe(provisioner.Describe):
name = "describe"
resource = Bundle
def describe_object(self):
if self.resource.always_apply:
return {"Results": "Pending"}
if not self.resource.target:
# If target is not set we are probably dealing with an AMI... YUCK
# Bail out
return {"Result": "Pending"}
serializer = serializers.Resource()
if serializer.pending(self.runner, self.resource):
return {"Result": "Pending"}
kwargs = serializer.render(self.runner, self.resource)
try:
client = self.runner.get_plan(self.resource.target).get_client()
except errors.ServiceNotReady:
return {"Result": "Pending"}
try:
client.run_script(kwargs["script"], ["-s"])
except errors.CommandFailed as e:
if e.exit_code == 254:
return {"Result": "Success"}
return {"Result": "Pending"}
class Apply(provisioner.Apply):
resource = Bundle
for attr, value in vars(resources).items():
if type(value) == fuselage.resource.ResourceType:
locals()[attr] = FuselageResource.adapt(value)
|
apache-2.0
| -1,469,942,013,499,236,900
| 30.966887
| 83
| 0.645743
| false
| 3.982673
| false
| false
| false
|
yukisakurai/hhana
|
mva/plotting/utils.py
|
1
|
4190
|
import ROOT
from itertools import izip
from matplotlib import cm
from rootpy.plotting.style.atlas.labels import ATLAS_label
from rootpy.memory.keepalive import keepalive
from .. import ATLAS_LABEL
def set_colors(hists, colors='jet'):
if isinstance(colors, basestring):
colors = cm.get_cmap(colors, len(hists))
if hasattr(colors, '__call__'):
for i, h in enumerate(hists):
color = colors((i + 1) / float(len(hists) + 1))
h.SetColor(color)
else:
for h, color in izip(hists, colors):
h.SetColor(color)
def category_lumi_atlas(pad, category_label=None,
data_info=None, atlas_label=None,
textsize=20):
left, right, bottom, top = pad.margin_pixels
height = float(pad.height_pixels)
# draw the category label
if category_label:
label = ROOT.TLatex(
1. - pad.GetRightMargin(),
1. - (textsize - 2) / height,
category_label)
label.SetNDC()
label.SetTextFont(43)
label.SetTextSize(textsize)
label.SetTextAlign(31)
with pad:
label.Draw()
keepalive(pad, label)
# draw the luminosity label
if data_info is not None:
plabel = ROOT.TLatex(
1. - pad.GetLeftMargin() - 0.25,
1. - (top + textsize + 60) / height,
str(data_info))
plabel.SetNDC()
plabel.SetTextFont(43)
plabel.SetTextSize(textsize)
plabel.SetTextAlign(31)
with pad:
plabel.Draw()
keepalive(pad, plabel)
# draw the ATLAS label
if atlas_label is not False:
label = atlas_label or ATLAS_LABEL
ATLAS_label(pad.GetLeftMargin() + 0.03,
1. - (top + textsize + 15) / height,
sep=0.132, pad=pad, sqrts=None,
text=label,
textsize=textsize)
pad.Update()
pad.Modified()
def label_plot(pad, template, xaxis, yaxis,
ylabel='Events', xlabel=None,
units=None, data_info=None,
category_label=None,
atlas_label=None,
extra_label=None,
extra_label_position='left',
textsize=22):
# set the axis labels
binw = list(template.xwidth())
binwidths = list(set(['%.2g' % w for w in binw]))
if units is not None:
if xlabel is not None:
xlabel = '%s [%s]' % (xlabel, units)
if ylabel and len(binwidths) == 1 and binwidths[0] != '1':
# constant width bins
ylabel = '%s / %s %s' % (ylabel, binwidths[0], units)
elif ylabel and len(binwidths) == 1 and binwidths[0] != '1':
ylabel = '%s / %s' % (ylabel, binwidths[0])
if ylabel:
yaxis.SetTitle(ylabel)
if xlabel:
xaxis.SetTitle(xlabel)
left, right, bottom, top = pad.margin_pixels
height = float(pad.height_pixels)
category_lumi_atlas(pad, category_label, data_info, atlas_label)
# draw the extra label
if extra_label is not None:
if extra_label_position == 'left':
label = ROOT.TLatex(pad.GetLeftMargin() + 0.03,
1. - (top + 2 * (textsize + 40)) / height,
extra_label)
else: # right
label = ROOT.TLatex(1. - pad.GetRightMargin() - 0.03,
1. - (top + 2 * (textsize + 40)) / height,
extra_label)
label.SetTextAlign(31)
label.SetNDC()
label.SetTextFont(43)
label.SetTextSize(textsize)
with pad:
label.Draw()
keepalive(pad, label)
pad.Update()
pad.Modified()
# class rootpy.plotting.Legend(
# entries, pad=None,
# leftmargin=0.5, topmargin=0.05, rightmargin=0.05,
# entryheight=0.06, entrysep=0.02, margin=0.3,
# textfont=None, textsize=None, header=None)
def legend_params(position, textsize):
return dict(
leftmargin=0.48, topmargin=0.03, rightmargin=0.05,
entryheight=0.05,
entrysep=0.01,
margin=0.25,
textsize=textsize)
|
gpl-3.0
| 7,927,911,205,312,527,000
| 30.742424
| 74
| 0.548449
| false
| 3.512154
| false
| false
| false
|
O-T-L/PyOptimization
|
parameters/optimizer/epsilon_moea.py
|
1
|
4120
|
"""
Copyright (C) 2014, 申瑞珉 (Ruimin Shen)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
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/>.
"""
def epsilon(config, problem):
if type(problem).__name__ == 'DTLZ1':
table = {
3: 0.033,
4: 0.052,
5: 0.059,
6: 0.0554,
8: 0.0549,
10: 0.0565,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'DTLZ2':
table = {
2: 0.006,
3: 0.06,
4: 0.1312,
5: 0.1927,
6: 0.234,
8: 0.29,
10: 0.308,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'DTLZ3':
table = {
3: 0.06,
4: 0.1385,
5: 0.2,
6: 0.227,
8: 0.1567,
10: 0.85,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'DTLZ4':
table = {
3: 0.06,
4: 0.1312,
5: 0.1927,
6: 0.234,
8: 0.29,
10: 0.308,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'DTLZ5':
table = {
3: 0.0052,
4: 0.042,
5: 0.0785,
6: 0.11,
8: 0.1272,
10: 0.1288,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'DTLZ6':
table = {
3: 0.0227,
4: 0.12,
5: 0.3552,
6: 0.75,
8: 1.15,
10: 1.45,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'DTLZ7':
table = {
2: 0.005,
3: 0.048,
4: 0.105,
5: 0.158,
6: 0.15,
8: 0.225,
10: 0.46,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'ConvexDTLZ2':
table = {
2: 0.0075,
3: 0.035,
4: 0.039,
5: 0.034,
6: 0.0273,
8: 0.0184,
10: 0.0153,
}
_epsilon = table[problem.GetNumberOfObjectives()]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
elif type(problem).__name__ == 'DTLZ5I':
if problem.GetNumberOfObjectives() == 10:
table = {
3: 0.06,
4: 0.12,
5: 0.16,
6: 0.2,
7: 0.24,
8: 0.25,
9: 0.26,
}
_epsilon = table[problem.GetManifold() + 1]
epsilon = [_epsilon] * problem.GetNumberOfObjectives()
return [epsilon]
raise Exception(type(problem).__name__, problem.GetNumberOfObjectives())
|
lgpl-3.0
| -8,347,849,438,186,841,000
| 29.932331
| 76
| 0.495139
| false
| 3.643933
| false
| false
| false
|
tulsawebdevs/django-multi-gtfs
|
multigtfs/models/trip.py
|
1
|
4025
|
#
# Copyright 2012-2014 John Whitlock
#
# 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 __future__ import unicode_literals
from django.contrib.gis.geos import LineString
from django.utils.encoding import python_2_unicode_compatible
from jsonfield import JSONField
from multigtfs.models.base import models, Base
@python_2_unicode_compatible
class Trip(Base):
"""A trip along a route
This implements trips.txt in the GTFS feed
"""
route = models.ForeignKey('Route', on_delete=models.CASCADE)
service = models.ForeignKey(
'Service', null=True, blank=True, on_delete=models.SET_NULL)
trip_id = models.CharField(
max_length=255, db_index=True,
help_text="Unique identifier for a trip.")
headsign = models.CharField(
max_length=255, blank=True,
help_text="Destination identification for passengers.")
short_name = models.CharField(
max_length=63, blank=True,
help_text="Short name used in schedules and signboards.")
direction = models.CharField(
max_length=1, blank=True,
choices=(('0', '0'), ('1', '1')),
help_text="Direction for bi-directional routes.")
block = models.ForeignKey(
'Block', null=True, blank=True, on_delete=models.SET_NULL,
help_text="Block of sequential trips that this trip belongs to.")
shape = models.ForeignKey(
'Shape', null=True, blank=True, on_delete=models.SET_NULL,
help_text="Shape used for this trip")
geometry = models.LineStringField(
null=True, blank=True,
help_text='Geometry cache of Shape or Stops')
wheelchair_accessible = models.CharField(
max_length=1, blank=True,
choices=(
('0', 'No information'),
('1', 'Some wheelchair accommodation'),
('2', 'No wheelchair accommodation')),
help_text='Are there accommodations for riders with wheelchair?')
bikes_allowed = models.CharField(
max_length=1, blank=True,
choices=(
('0', 'No information'),
('1', 'Some bicycle accommodation'),
('2', 'No bicycles allowed')),
help_text='Are bicycles allowed?')
extra_data = JSONField(default={}, blank=True, null=True)
def update_geometry(self, update_parent=True):
"""Update the geometry from the Shape or Stops"""
original = self.geometry
if self.shape:
self.geometry = self.shape.geometry
else:
stoptimes = self.stoptime_set.order_by('stop_sequence')
if stoptimes.count() > 1:
self.geometry = LineString(
[st.stop.point.coords for st in stoptimes])
if self.geometry != original:
self.save()
if update_parent:
self.route.update_geometry()
def __str__(self):
return "%s-%s" % (self.route, self.trip_id)
class Meta:
db_table = 'trip'
app_label = 'multigtfs'
_column_map = (
('route_id', 'route__route_id'),
('service_id', 'service__service_id'),
('trip_id', 'trip_id'),
('trip_headsign', 'headsign'),
('trip_short_name', 'short_name'),
('direction_id', 'direction'),
('block_id', 'block__block_id'),
('shape_id', 'shape__shape_id'),
('wheelchair_accessible', 'wheelchair_accessible'),
('bikes_allowed', 'bikes_allowed'),
)
_filename = 'trips.txt'
_rel_to_feed = 'route__feed'
_unique_fields = ('trip_id',)
|
apache-2.0
| -85,679,634,461,076,020
| 36.268519
| 74
| 0.623354
| false
| 3.790019
| false
| false
| false
|
taotaocoule/stock
|
spider/data/bond.py
|
1
|
1159
|
# 国债指数:id=0000121;http://pdfm2.eastmoney.com/EM_UBG_PDTI_Fast/api/js?id=0000121&TYPE=k&js=(x)&rtntype=5&isCR=false&fsData1518154947301=fsData1518154947301
# 沪市企业: id=0000131;http://pdfm2.eastmoney.com/EM_UBG_PDTI_Fast/api/js?id=0000131&TYPE=k&js=(x)&rtntype=5&isCR=false&fsData1518156740923=fsData1518156740923
# 深圳企业:id=3994812;http://pdfm2.eastmoney.com/EM_UBG_PDTI_Fast/api/js?id=3994812&TYPE=k&js=(x)&rtntype=5&isCR=false&fsData1518156947700=fsData1518156947700
import urllib.request
import pandas as pd
import json
class Bond(object):
"""docstring for Bond"""
def __init__(self):
self.index = {
'国债指数':'0000121',
'沪市企业债':'0000131',
'深圳企业债':'3994812'
}
def bond_index(self,id):
url = r'http://pdfm2.eastmoney.com/EM_UBG_PDTI_Fast/api/js?id={}&TYPE=k&js=(x)&rtntype=5&isCR=false&fsData1518154947301=fsData1518154947301'.format(id)
raw = json.loads(urllib.request.urlopen(url).read())
head = ['日期','开盘','收盘','最高','最低','成交量','成交金额','振幅']
return pd.DataFrame(list(map(lambda x:x.split(','),raw['data'])),columns=head)
|
mit
| -7,352,327,051,511,593,000
| 46.5
| 155
| 0.707981
| false
| 2.020873
| false
| false
| false
|
skatsuta/aerospike-training
|
book/exercise/Key-valueOperations/Python/Program.py
|
1
|
8944
|
#!/usr/bin/env python
#
# * Copyright 2012-2014 by Aerospike.
# *
# * 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.
#
from __future__ import print_function
import aerospike
import sys
from optparse import OptionParser
from UserService import UserService
from TweetService import TweetService
#
# * @author Raghavendra Kumar
#
class Program(object):
client=None
seedHost = str()
port = int()
namespace = str()
set = str()
writePolicy = {}
policy = {}
def __init__(self, host, port, namespace, set):
# TODO: Establish a connection to Aerospike cluster
# Exercise 1
print("\nTODO: Establish a connection to Aerospike cluster");
self.client = aerospike.client({ 'hosts': [ (host, port) ] }).connect()
self.seedHost = host
self.port = port
self.namespace = namespace
self.set = set
self.writePolicy = {}
self.policy = {}
@classmethod
def main(cls, args):
usage = "usage: %prog [options] "
optparser = OptionParser(usage=usage, add_help_option=False)
optparser.add_option( "--help", dest="help", action="store_true", help="Displays this message.")
optparser.add_option( "-h", "--host", dest="host", type="string", default="127.0.0.1", metavar="<ADDRESS>", help="Address of Aerospike server (default: 127.0.0.1)")
optparser.add_option( "-p", "--port", dest="port", type="int", default=3000, metavar="<PORT>", help="Port of the Aerospike server (default: 3000)")
optparser.add_option( "-n", "--namespace", dest="namespace", type="string", metavar="<NAMESPACE>", help="Namespace (default: test)")
optparser.add_option( "-s", "--set", dest="set", type="string",metavar="<SET>", help="Set (default: demo)")
(options, args) = optparser.parse_args()
if options.help:
optparser.print_help()
print()
sys.exit(1)
aero=Program(options.host,options.port,options.namespace,options.set)
aero.work()
def work(self):
print("***** Welcome to Aerospike Developer Training *****\n")
print("INFO: Connecting to Aerospike cluster...")
# Establish connection to Aerospike server
# TODO: Check to see if the cluster connection succeeded
# Exercise 1
if not True:
print("\nERROR: Connection to Aerospike cluster failed! Please check the server settings and try again!")
else:
print("\nINFO: Connection to Aerospike cluster succeeded!\n")
# Create instance of UserService
us = UserService(self.client)
# Create instance of TweetService
ts = TweetService(self.client)
# Present options
print("\nWhat would you like to do:\n")
print("1> Create A User And A Tweet\n")
print("2> Read A User Record\n")
print("3> Batch Read Tweets For A User\n")
print("4> Scan All Tweets For All Users\n")
print("5> Record UDF -- Update User Password\n")
print("6> Query Tweets By Username And Users By Tweet Count Range\n")
print("7> Stream UDF -- Aggregation Based on Tweet Count By Region\n")
print("0> Exit\n")
print("\nSelect 0-7 and hit enter:\n")
try:
feature=int(raw_input('Input:'))
except ValueError:
print("Input a valid feature number")
sys.exit(0)
if feature != 0:
if feature==1:
print("\n********** Your Selection: Create User And A Tweet **********\n")
us.createUser()
ts.createTweet()
elif feature==2:
print("\n********** Your Selection: Read A User Record **********\n")
us.getUser()
elif feature==3:
print("\n********** Your Selection: Batch Read Tweets For A User **********\n")
us.batchGetUserTweets()
elif feature==4:
print("\n********** Your Selection: Scan All Tweets For All Users **********\n")
ts.scanAllTweetsForAllUsers()
elif feature==5:
print("\n********** Your Selection: Update User Password using CAS **********\n")
us.updatePasswordUsingCAS()
elif feature==6:
print("\n********** Your Selection: Query Tweets By Username And Users By Tweet Count Range **********\n")
ts.queryTweetsByUsername()
ts.queryUsersByTweetCount()
elif feature==7:
print("\n********** Your Selection: Stream UDF -- Aggregation Based on Tweet Count By Region **********\n")
us.aggregateUsersByTweetCountByRegion()
elif feature==12:
print("\n********** Create Users **********\n")
us.createUsers()
elif feature==23:
print("\n********** Create Tweets **********\n")
ts.createTweets()
else:
print ("Enter a Valid number from above menue !!")
# TODO: Close Aerospike cluster connection
# Exercise 1
print("\nTODO: Close Aerospike cluster connection");
#
# * example method calls
#
def readPartial(self, userName):
""" Python read specific bins """
(key, metadata, record) = self.client.get(("test", "users", userName), ("username", "password", "gender", "region") )
return record
def readMeta(self, userName):
""" not supported in Python Client """
def write(self, username, password):
""" Python read-modify-write """
meta = None
wr_policy = {
AS_POLICY_W_GEN: AS_POLICY_GEN_EQ
}
key = ("test", "users", username)
self.client.put(key,{"username": username,"password": password},meta,wr_policy)
def delete(self, username):
""" Delete Record """
key = ("test", "users", username)
self.client.remove(key)
def exisis(self, username):
""" Python key exists """
key = ("test", "users", username)
(key,itsHere) = self.client.exists(key)
# itsHere should not be Null
return itsHere
def add(self, username):
""" Add """
key = ("test", "users", username)
self.client.put(key, {"tweetcount":1})
def touch(self, username):
""" Not supported in Python Client """
def append(self, username):
""" Not supported in Python Client """
def connectWithClientPolicy(self):
""" Connect with Client configs """
config = { 'hosts': [ ( '127.0.0.1', 3000 )
],
'policies': { 'timeout': 1000 # milliseconds
} }
client = aerospike.client(config)
def deleteBin(self, username):
key = ("test", "users", username)
# Set bin value to null to drop bin.
self.client.put(key, {"interests": None} )
AS_POLICY_W_GEN = "generation"
AS_POLICY_GEN_UNDEF = 0 # Use default value
AS_POLICY_GEN_IGNORE = 1 # Write a record, regardless of generation.
AS_POLICY_GEN_EQ = 2 # Write a record, ONLY if generations are equal
AS_POLICY_GEN_GT = 3 # Write a record, ONLY if local generation is
# greater-than remote generation.
AS_POLICY_GEN_DUP = 4 # Write a record creating a duplicate, ONLY if
if __name__ == '__main__':
import sys
Program.main(sys.argv)
|
mit
| -1,456,257,365,734,570,800
| 42.629268
| 172
| 0.55814
| false
| 4.224846
| true
| false
| false
|
xianian/qt-creator
|
share/qtcreator/debugger/gdbbridge.py
|
1
|
64687
|
try:
import __builtin__
except:
import builtins
try:
import gdb
except:
pass
import os
import os.path
import sys
import struct
import types
def warn(message):
print("XXX: %s\n" % message.encode("latin1"))
from dumper import *
#######################################################################
#
# Infrastructure
#
#######################################################################
def safePrint(output):
try:
print(output)
except:
out = ""
for c in output:
cc = ord(c)
if cc > 127:
out += "\\\\%d" % cc
elif cc < 0:
out += "\\\\%d" % (cc + 256)
else:
out += c
print(out)
def registerCommand(name, func):
class Command(gdb.Command):
def __init__(self):
super(Command, self).__init__(name, gdb.COMMAND_OBSCURE)
def invoke(self, args, from_tty):
safePrint(func(args))
Command()
#######################################################################
#
# Types
#
#######################################################################
PointerCode = gdb.TYPE_CODE_PTR
ArrayCode = gdb.TYPE_CODE_ARRAY
StructCode = gdb.TYPE_CODE_STRUCT
UnionCode = gdb.TYPE_CODE_UNION
EnumCode = gdb.TYPE_CODE_ENUM
FlagsCode = gdb.TYPE_CODE_FLAGS
FunctionCode = gdb.TYPE_CODE_FUNC
IntCode = gdb.TYPE_CODE_INT
FloatCode = gdb.TYPE_CODE_FLT # Parts of GDB assume that this means complex.
VoidCode = gdb.TYPE_CODE_VOID
#SetCode = gdb.TYPE_CODE_SET
RangeCode = gdb.TYPE_CODE_RANGE
StringCode = gdb.TYPE_CODE_STRING
#BitStringCode = gdb.TYPE_CODE_BITSTRING
#ErrorTypeCode = gdb.TYPE_CODE_ERROR
MethodCode = gdb.TYPE_CODE_METHOD
MethodPointerCode = gdb.TYPE_CODE_METHODPTR
MemberPointerCode = gdb.TYPE_CODE_MEMBERPTR
ReferenceCode = gdb.TYPE_CODE_REF
CharCode = gdb.TYPE_CODE_CHAR
BoolCode = gdb.TYPE_CODE_BOOL
ComplexCode = gdb.TYPE_CODE_COMPLEX
TypedefCode = gdb.TYPE_CODE_TYPEDEF
NamespaceCode = gdb.TYPE_CODE_NAMESPACE
#Code = gdb.TYPE_CODE_DECFLOAT # Decimal floating point.
#Code = gdb.TYPE_CODE_MODULE # Fortran
#Code = gdb.TYPE_CODE_INTERNAL_FUNCTION
#######################################################################
#
# Convenience
#
#######################################################################
# Just convienience for 'python print ...'
class PPCommand(gdb.Command):
def __init__(self):
super(PPCommand, self).__init__("pp", gdb.COMMAND_OBSCURE)
def invoke(self, args, from_tty):
print(eval(args))
PPCommand()
# Just convienience for 'python print gdb.parse_and_eval(...)'
class PPPCommand(gdb.Command):
def __init__(self):
super(PPPCommand, self).__init__("ppp", gdb.COMMAND_OBSCURE)
def invoke(self, args, from_tty):
print(gdb.parse_and_eval(args))
PPPCommand()
def scanStack(p, n):
p = int(p)
r = []
for i in xrange(n):
f = gdb.parse_and_eval("{void*}%s" % p)
m = gdb.execute("info symbol %s" % f, to_string=True)
if not m.startswith("No symbol matches"):
r.append(m)
p += f.type.sizeof
return r
class ScanStackCommand(gdb.Command):
def __init__(self):
super(ScanStackCommand, self).__init__("scanStack", gdb.COMMAND_OBSCURE)
def invoke(self, args, from_tty):
if len(args) == 0:
args = 20
safePrint(scanStack(gdb.parse_and_eval("$sp"), int(args)))
ScanStackCommand()
#######################################################################
#
# Import plain gdb pretty printers
#
#######################################################################
class PlainDumper:
def __init__(self, printer):
self.printer = printer
self.typeCache = {}
def __call__(self, d, value):
printer = self.printer.invoke(value)
lister = getattr(printer, "children", None)
children = [] if lister is None else list(lister())
d.putType(self.printer.name)
val = printer.to_string()
if isinstance(val, str):
d.putValue(val)
else: # Assuming LazyString
d.putStdStringHelper(val.address, val.length, val.type.sizeof)
d.putNumChild(len(children))
if d.isExpanded():
with Children(d):
for child in children:
d.putSubItem(child[0], child[1])
def importPlainDumpers(args):
if args == "off":
gdb.execute("disable pretty-printer .* .*")
else:
theDumper.importPlainDumpers()
registerCommand("importPlainDumpers", importPlainDumpers)
class OutputSafer:
def __init__(self, d):
self.d = d
def __enter__(self):
self.savedOutput = self.d.output
self.d.output = []
def __exit__(self, exType, exValue, exTraceBack):
if self.d.passExceptions and not exType is None:
showException("OUTPUTSAFER", exType, exValue, exTraceBack)
self.d.output = self.savedOutput
else:
self.savedOutput.extend(self.d.output)
self.d.output = self.savedOutput
return False
#def couldBePointer(p, align):
# typeobj = lookupType("unsigned int")
# ptr = gdb.Value(p).cast(typeobj)
# d = int(str(ptr))
# warn("CHECKING : %s %d " % (p, ((d & 3) == 0 and (d > 1000 or d == 0))))
# return (d & (align - 1)) and (d > 1000 or d == 0)
Value = gdb.Value
def stripTypedefs(typeobj):
typeobj = typeobj.unqualified()
while typeobj.code == TypedefCode:
typeobj = typeobj.strip_typedefs().unqualified()
return typeobj
#######################################################################
#
# The Dumper Class
#
#######################################################################
class Dumper(DumperBase):
def __init__(self):
DumperBase.__init__(self)
# These values will be kept between calls to 'showData'.
self.isGdb = True
self.childEventAddress = None
self.typeCache = {}
self.typesReported = {}
self.typesToReport = {}
self.qtNamespaceToReport = None
self.qmlEngines = []
self.qmlBreakpoints = []
def prepare(self, args):
self.output = []
self.currentIName = ""
self.currentPrintsAddress = True
self.currentChildType = ""
self.currentChildNumChild = -1
self.currentMaxNumChild = -1
self.currentNumChild = -1
self.currentValue = ReportItem()
self.currentType = ReportItem()
self.currentAddress = None
# The guess does not need to be updated during a showData()
# as the result is fixed during that time (ignoring "active"
# dumpers causing loading of shared objects etc).
self.currentQtNamespaceGuess = None
self.resultVarName = args.get("resultvarname", "")
self.expandedINames = set(args.get("expanded", []))
self.stringCutOff = int(args.get("stringcutoff", 10000))
self.displayStringLimit = int(args.get("displaystringlimit", 100))
self.typeformats = args.get("typeformats", {})
self.formats = args.get("formats", {})
self.watchers = args.get("watchers", {})
self.qmlcontext = int(args.get("qmlcontext", "0"), 0)
self.useDynamicType = int(args.get("dyntype", "0"))
self.useFancy = int(args.get("fancy", "0"))
self.forceQtNamespace = int(args.get("forcens", "0"))
self.passExceptions = int(args.get("passExceptions", "0"))
self.nativeMixed = int(args.get("nativemixed", "0"))
self.autoDerefPointers = int(args.get("autoderef", "0"))
self.partialUpdate = int(args.get("partial", "0"))
self.fallbackQtVersion = 0x50200
self.sortStructMembers = bool(args.get("sortStructMembers", True))
#warn("NAMESPACE: '%s'" % self.qtNamespace())
#warn("EXPANDED INAMES: %s" % self.expandedINames)
#warn("WATCHERS: %s" % self.watchers)
def listOfLocals(self):
frame = gdb.selected_frame()
try:
block = frame.block()
#warn("BLOCK: %s " % block)
except RuntimeError as error:
#warn("BLOCK IN FRAME NOT ACCESSIBLE: %s" % error)
return []
except:
warn("BLOCK NOT ACCESSIBLE FOR UNKNOWN REASONS")
return []
items = []
shadowed = {}
while True:
if block is None:
warn("UNEXPECTED 'None' BLOCK")
break
for symbol in block:
name = symbol.print_name
if name == "__in_chrg" or name == "__PRETTY_FUNCTION__":
continue
# "NotImplementedError: Symbol type not yet supported in
# Python scripts."
#warn("SYMBOL %s (%s): " % (symbol, name))
if name in shadowed:
level = shadowed[name]
name1 = "%s@%s" % (name, level)
shadowed[name] = level + 1
else:
name1 = name
shadowed[name] = 1
#warn("SYMBOL %s (%s, %s)): " % (symbol, name, symbol.name))
item = self.LocalItem()
item.iname = "local." + name1
item.name = name1
try:
item.value = frame.read_var(name, block)
#warn("READ 1: %s" % item.value)
items.append(item)
continue
except:
pass
try:
#warn("READ 2: %s" % item.value)
item.value = frame.read_var(name)
items.append(item)
continue
except:
# RuntimeError: happens for
# void foo() { std::string s; std::wstring w; }
# ValueError: happens for (as of 2010/11/4)
# a local struct as found e.g. in
# gcc sources in gcc.c, int execute()
pass
try:
#warn("READ 3: %s %s" % (name, item.value))
item.value = gdb.parse_and_eval(name)
#warn("ITEM 3: %s" % item.value)
items.append(item)
except:
# Can happen in inlined code (see last line of
# RowPainter::paintChars(): "RuntimeError:
# No symbol \"__val\" in current context.\n"
pass
# The outermost block in a function has the function member
# FIXME: check whether this is guaranteed.
if not block.function is None:
break
block = block.superblock
return items
# Hack to avoid QDate* dumper timeouts with GDB 7.4 on 32 bit
# due to misaligned %ebx in SSE calls (qstring.cpp:findChar)
# This seems to be fixed in 7.9 (or earlier)
def canCallLocale(self):
return False if self.is32bit() else True
def showData(self, args):
self.prepare(args)
partialVariable = args.get("partialVariable", "")
isPartial = len(partialVariable) > 0
#
# Locals
#
self.output.append('data=[')
if self.qmlcontext:
locals = self.extractQmlVariables(self.qmlcontext)
elif isPartial:
parts = partialVariable.split('.')
name = parts[1]
item = self.LocalItem()
item.iname = parts[0] + '.' + name
item.name = name
try:
if parts[0] == 'local':
frame = gdb.selected_frame()
item.value = frame.read_var(name)
else:
item.name = self.hexdecode(name)
item.value = gdb.parse_and_eval(item.name)
except RuntimeError as error:
item.value = error
except:
item.value = "<no value>"
locals = [item]
else:
locals = self.listOfLocals()
# Take care of the return value of the last function call.
if len(self.resultVarName) > 0:
try:
item = self.LocalItem()
item.name = self.resultVarName
item.iname = "return." + self.resultVarName
item.value = self.parseAndEvaluate(self.resultVarName)
locals.append(item)
except:
# Don't bother. It's only supplementary information anyway.
pass
locals.sort(key = lambda item: item.name)
for item in locals:
value = self.downcast(item.value) if self.useDynamicType else item.value
with OutputSafer(self):
self.anonNumber = -1
if item.iname == "local.argv" and str(value.type) == "char **":
self.putSpecialArgv(value)
else:
# A "normal" local variable or parameter.
with TopLevelItem(self, item.iname):
self.put('iname="%s",' % item.iname)
self.put('name="%s",' % item.name)
self.putItem(value)
with OutputSafer(self):
self.handleWatches(args)
self.output.append('],typeinfo=[')
for name in self.typesToReport.keys():
typeobj = self.typesToReport[name]
# Happens e.g. for '(anonymous namespace)::InsertDefOperation'
if not typeobj is None:
self.output.append('{name="%s",size="%s"}'
% (self.hexencode(name), typeobj.sizeof))
self.output.append(']')
self.typesToReport = {}
if self.forceQtNamespace:
self.qtNamepaceToReport = self.qtNamespace()
if self.qtNamespaceToReport:
self.output.append(',qtnamespace="%s"' % self.qtNamespaceToReport)
self.qtNamespaceToReport = None
self.output.append(',partial="%d"' % isPartial)
safePrint(''.join(self.output))
def enterSubItem(self, item):
if not item.iname:
item.iname = "%s.%s" % (self.currentIName, item.name)
#warn("INAME %s" % item.iname)
self.put('{')
#if not item.name is None:
if isinstance(item.name, str):
self.put('name="%s",' % item.name)
item.savedIName = self.currentIName
item.savedValue = self.currentValue
item.savedType = self.currentType
item.savedCurrentAddress = self.currentAddress
self.currentIName = item.iname
self.currentValue = ReportItem();
self.currentType = ReportItem();
self.currentAddress = None
def exitSubItem(self, item, exType, exValue, exTraceBack):
#warn("CURRENT VALUE: %s: %s %s" % (self.currentIName, self.currentValue, self.currentType))
if not exType is None:
if self.passExceptions:
showException("SUBITEM", exType, exValue, exTraceBack)
self.putNumChild(0)
self.putSpecialValue(SpecialNotAccessibleValue)
try:
if self.currentType.value:
typeName = self.stripClassTag(self.currentType.value)
if len(typeName) > 0 and typeName != self.currentChildType:
self.put('type="%s",' % typeName) # str(type.unqualified()) ?
if self.currentValue.value is None:
self.put('value="",encoding="%d","numchild="0",'
% SpecialNotAccessibleValue)
else:
if not self.currentValue.encoding is None:
self.put('valueencoded="%d",' % self.currentValue.encoding)
if self.currentValue.elided:
self.put('valueelided="%d",' % self.currentValue.elided)
self.put('value="%s",' % self.currentValue.value)
except:
pass
if not self.currentAddress is None:
self.put(self.currentAddress)
self.put('},')
self.currentIName = item.savedIName
self.currentValue = item.savedValue
self.currentType = item.savedType
self.currentAddress = item.savedCurrentAddress
return True
def parseAndEvaluate(self, exp):
return gdb.parse_and_eval(exp)
def callHelper(self, value, func, args):
# args is a tuple.
arg = ""
for i in range(len(args)):
if i:
arg += ','
a = args[i]
if (':' in a) and not ("'" in a):
arg = "'%s'" % a
else:
arg += a
#warn("CALL: %s -> %s(%s)" % (value, func, arg))
typeName = self.stripClassTag(str(value.type))
if typeName.find(":") >= 0:
typeName = "'" + typeName + "'"
# 'class' is needed, see http://sourceware.org/bugzilla/show_bug.cgi?id=11912
#exp = "((class %s*)%s)->%s(%s)" % (typeName, value.address, func, arg)
ptr = value.address if value.address else self.pokeValue(value)
exp = "((%s*)%s)->%s(%s)" % (typeName, ptr, func, arg)
#warn("CALL: %s" % exp)
result = gdb.parse_and_eval(exp)
#warn(" -> %s" % result)
if not value.address:
gdb.parse_and_eval("free(0x%x)" % ptr)
return result
def childWithName(self, value, name):
try:
return value[name]
except:
return None
def isBadPointer(self, value):
try:
target = value.dereference()
target.is_optimized_out # Access test.
return False
except:
return True
def makeValue(self, typeobj, init):
typename = "::" + self.stripClassTag(str(typeobj));
# Avoid malloc symbol clash with QVector.
gdb.execute("set $d = (%s*)calloc(sizeof(%s), 1)" % (typename, typename))
gdb.execute("set *$d = {%s}" % init)
value = gdb.parse_and_eval("$d").dereference()
#warn(" TYPE: %s" % value.type)
#warn(" ADDR: %s" % value.address)
#warn(" VALUE: %s" % value)
return value
def makeExpression(self, value):
typename = "::" + self.stripClassTag(str(value.type))
#warn(" TYPE: %s" % typename)
#exp = "(*(%s*)(&%s))" % (typename, value.address)
exp = "(*(%s*)(%s))" % (typename, value.address)
#warn(" EXP: %s" % exp)
return exp
def makeStdString(init):
# Works only for small allocators, but they are usually empty.
gdb.execute("set $d=(std::string*)calloc(sizeof(std::string), 2)");
gdb.execute("call($d->basic_string(\"" + init +
"\",*(std::allocator<char>*)(1+$d)))")
value = gdb.parse_and_eval("$d").dereference()
#warn(" TYPE: %s" % value.type)
#warn(" ADDR: %s" % value.address)
#warn(" VALUE: %s" % value)
return value
def childAt(self, value, index):
field = value.type.fields()[index]
try:
# Official access in GDB 7.6 or later.
return value[field]
except:
pass
try:
# Won't work with anon entities, tradionally with empty
# field name, but starting with GDB 7.7 commit b5b08fb4
# with None field name.
return value[field.name]
except:
pass
# FIXME: Cheat. There seems to be no official way to access
# the real item, so we pass back the value. That at least
# enables later ...["name"] style accesses as gdb handles
# them transparently.
return value
def fieldAt(self, typeobj, index):
return typeobj.fields()[index]
def simpleValue(self, value):
return str(value)
def directBaseClass(self, typeobj, index = 0):
for f in typeobj.fields():
if f.is_base_class:
if index == 0:
return f.type
index -= 1;
return None
def directBaseObject(self, value, index = 0):
for f in value.type.fields():
if f.is_base_class:
if index == 0:
return value.cast(f.type)
index -= 1;
return None
def checkPointer(self, p, align = 1):
if not self.isNull(p):
p.dereference()
def pointerValue(self, p):
return toInteger(p)
def isNull(self, p):
# The following can cause evaluation to abort with "UnicodeEncodeError"
# for invalid char *, as their "contents" is being examined
#s = str(p)
#return s == "0x0" or s.startswith("0x0 ")
#try:
# # Can fail with: "RuntimeError: Cannot access memory at address 0x5"
# return p.cast(self.lookupType("void").pointer()) == 0
#except:
# return False
try:
# Can fail with: "RuntimeError: Cannot access memory at address 0x5"
return toInteger(p) == 0
except:
return False
def templateArgument(self, typeobj, position):
try:
# This fails on stock 7.2 with
# "RuntimeError: No type named myns::QObject.\n"
return typeobj.template_argument(position)
except:
# That's something like "myns::QList<...>"
return self.lookupType(self.extractTemplateArgument(str(typeobj.strip_typedefs()), position))
def numericTemplateArgument(self, typeobj, position):
# Workaround for gdb < 7.1
try:
return int(typeobj.template_argument(position))
except RuntimeError as error:
# ": No type named 30."
msg = str(error)
msg = msg[14:-1]
# gdb at least until 7.4 produces for std::array<int, 4u>
# for template_argument(1): RuntimeError: No type named 4u.
if msg[-1] == 'u':
msg = msg[0:-1]
return int(msg)
def intType(self):
self.cachedIntType = self.lookupType('int')
self.intType = lambda: self.cachedIntType
return self.cachedIntType
def charType(self):
return self.lookupType('char')
def sizetType(self):
return self.lookupType('size_t')
def charPtrType(self):
return self.lookupType('char*')
def voidPtrType(self):
return self.lookupType('void*')
def addressOf(self, value):
return toInteger(value.address)
def createPointerValue(self, address, pointeeType):
# This might not always work:
# a Python 3 based GDB due to the bug addressed in
# https://sourceware.org/ml/gdb-patches/2013-09/msg00571.html
try:
return gdb.Value(address).cast(pointeeType.pointer())
except:
# Try _some_ fallback (good enough for the std::complex dumper)
return gdb.parse_and_eval("(%s*)%s" % (pointeeType, address))
def intSize(self):
return 4
def ptrSize(self):
self.cachedPtrSize = self.lookupType('void*').sizeof
self.ptrSize = lambda: self.cachedPtrSize
return self.cachedPtrSize
def pokeValue(self, value):
"""
Allocates inferior memory and copies the contents of value.
Returns a pointer to the copy.
"""
# Avoid malloc symbol clash with QVector
size = value.type.sizeof
data = value.cast(gdb.lookup_type("unsigned char").array(0, int(size - 1)))
string = ''.join("\\x%02x" % int(data[i]) for i in range(size))
exp = '(%s*)memcpy(calloc(%s, 1), "%s", %s)' % (value.type, size, string, size)
#warn("EXP: %s" % exp)
return toInteger(gdb.parse_and_eval(exp))
def createValue(self, address, referencedType):
try:
return gdb.Value(address).cast(referencedType.pointer()).dereference()
except:
# Try _some_ fallback (good enough for the std::complex dumper)
return gdb.parse_and_eval("{%s}%s" % (referencedType, address))
def setValue(self, address, typename, value):
cmd = "set {%s}%s=%s" % (typename, address, value)
gdb.execute(cmd)
def setValues(self, address, typename, values):
cmd = "set {%s[%s]}%s={%s}" \
% (typename, len(values), address, ','.join(map(str, values)))
gdb.execute(cmd)
def selectedInferior(self):
try:
# gdb.Inferior is new in gdb 7.2
self.cachedInferior = gdb.selected_inferior()
except:
# Pre gdb 7.4. Right now we don't have more than one inferior anyway.
self.cachedInferior = gdb.inferiors()[0]
# Memoize result.
self.selectedInferior = lambda: self.cachedInferior
return self.cachedInferior
def readRawMemory(self, addr, size):
mem = self.selectedInferior().read_memory(addr, size)
if sys.version_info[0] >= 3:
mem.tobytes()
return mem
def extractInt64(self, addr):
return struct.unpack("q", self.readRawMemory(addr, 8))[0]
def extractUInt64(self, addr):
return struct.unpack("Q", self.readRawMemory(addr, 8))[0]
def extractInt(self, addr):
return struct.unpack("i", self.readRawMemory(addr, 4))[0]
def extractUInt(self, addr):
return struct.unpack("I", self.readRawMemory(addr, 4))[0]
def extractShort(self, addr):
return struct.unpack("h", self.readRawMemory(addr, 2))[0]
def extractUShort(self, addr):
return struct.unpack("H", self.readRawMemory(addr, 2))[0]
def extractByte(self, addr):
return struct.unpack("b", self.readRawMemory(addr, 1))[0]
def findStaticMetaObject(self, typename):
return self.findSymbol(typename + "::staticMetaObject")
def findSymbol(self, symbolName):
try:
result = gdb.lookup_global_symbol(symbolName)
return result.value() if result else 0
except:
pass
# Older GDB ~7.4
try:
address = gdb.parse_and_eval("&'%s'" % symbolName)
typeobj = gdb.lookup_type(self.qtNamespace() + "QMetaObject")
return self.createPointerValue(address, typeobj)
except:
return 0
def put(self, value):
self.output.append(value)
def childRange(self):
if self.currentMaxNumChild is None:
return xrange(0, toInteger(self.currentNumChild))
return xrange(min(toInteger(self.currentMaxNumChild), toInteger(self.currentNumChild)))
def isArmArchitecture(self):
return 'arm' in gdb.TARGET_CONFIG.lower()
def isQnxTarget(self):
return 'qnx' in gdb.TARGET_CONFIG.lower()
def isWindowsTarget(self):
# We get i686-w64-mingw32
return 'mingw' in gdb.TARGET_CONFIG.lower()
def qtVersionString(self):
try:
return str(gdb.lookup_symbol("qVersion")[0].value()())
except:
pass
try:
ns = self.qtNamespace()
return str(gdb.parse_and_eval("((const char*(*)())'%sqVersion')()" % ns))
except:
pass
return None
def qtVersion(self):
try:
version = self.qtVersionString()
(major, minor, patch) = version[version.find('"')+1:version.rfind('"')].split('.')
qtversion = 0x10000 * int(major) + 0x100 * int(minor) + int(patch)
self.qtVersion = lambda: qtversion
return qtversion
except:
# Use fallback until we have a better answer.
return self.fallbackQtVersion
def isQt3Support(self):
if self.qtVersion() >= 0x050000:
return False
else:
try:
# This will fail on Qt 4 without Qt 3 support
gdb.execute("ptype QChar::null", to_string=True)
self.cachedIsQt3Suport = True
except:
self.cachedIsQt3Suport = False
# Memoize good results.
self.isQt3Support = lambda: self.cachedIsQt3Suport
return self.cachedIsQt3Suport
def putAddress(self, addr):
if self.currentPrintsAddress and not self.isCli:
try:
# addr can be "None", int(None) fails.
#self.put('addr="0x%x",' % int(addr))
self.currentAddress = 'addr="0x%x",' % toInteger(addr)
except:
pass
def putSimpleValue(self, value, encoding = None, priority = 0):
self.putValue(value, encoding, priority)
def putPointerValue(self, value):
# Use a lower priority
if value is None:
self.putEmptyValue(-1)
else:
self.putValue("0x%x" % value.cast(
self.lookupType("unsigned long")), None, -1)
def stripNamespaceFromType(self, typeName):
typename = self.stripClassTag(typeName)
ns = self.qtNamespace()
if len(ns) > 0 and typename.startswith(ns):
typename = typename[len(ns):]
pos = typename.find("<")
# FIXME: make it recognize foo<A>::bar<B>::iterator?
while pos != -1:
pos1 = typename.rfind(">", pos)
typename = typename[0:pos] + typename[pos1+1:]
pos = typename.find("<")
return typename
def isMovableType(self, typeobj):
if typeobj.code == PointerCode:
return True
if self.isSimpleType(typeobj):
return True
return self.isKnownMovableType(self.stripNamespaceFromType(str(typeobj)))
def putSubItem(self, component, value, tryDynamic=True):
with SubItem(self, component):
self.putItem(value, tryDynamic)
def isSimpleType(self, typeobj):
code = typeobj.code
return code == BoolCode \
or code == CharCode \
or code == IntCode \
or code == FloatCode \
or code == EnumCode
def simpleEncoding(self, typeobj):
code = typeobj.code
if code == BoolCode or code == CharCode:
return Hex2EncodedInt1
if code == IntCode:
if str(typeobj).find("unsigned") >= 0:
if typeobj.sizeof == 1:
return Hex2EncodedUInt1
if typeobj.sizeof == 2:
return Hex2EncodedUInt2
if typeobj.sizeof == 4:
return Hex2EncodedUInt4
if typeobj.sizeof == 8:
return Hex2EncodedUInt8
else:
if typeobj.sizeof == 1:
return Hex2EncodedInt1
if typeobj.sizeof == 2:
return Hex2EncodedInt2
if typeobj.sizeof == 4:
return Hex2EncodedInt4
if typeobj.sizeof == 8:
return Hex2EncodedInt8
if code == FloatCode:
if typeobj.sizeof == 4:
return Hex2EncodedFloat4
if typeobj.sizeof == 8:
return Hex2EncodedFloat8
return None
def isReferenceType(self, typeobj):
return typeobj.code == gdb.TYPE_CODE_REF
def isStructType(self, typeobj):
return typeobj.code == gdb.TYPE_CODE_STRUCT
def isFunctionType(self, typeobj):
return typeobj.code == MethodCode or typeobj.code == FunctionCode
def putItem(self, value, tryDynamic=True):
if value is None:
# Happens for non-available watchers in gdb versions that
# need to use gdb.execute instead of gdb.parse_and_eval
self.putSpecialValue(SpecialNotAvailableValue)
self.putType("<unknown>")
self.putNumChild(0)
return
typeobj = value.type.unqualified()
typeName = str(typeobj)
if value.is_optimized_out:
self.putSpecialValue(SpecialOptimizedOutValue)
self.putType(typeName)
self.putNumChild(0)
return
tryDynamic &= self.useDynamicType
self.addToCache(typeobj) # Fill type cache
if tryDynamic:
self.putAddress(value.address)
# FIXME: Gui shows references stripped?
#warn(" ")
#warn("REAL INAME: %s" % self.currentIName)
#warn("REAL TYPE: %s" % value.type)
#warn("REAL CODE: %s" % value.type.code)
#warn("REAL VALUE: %s" % value)
if typeobj.code == ReferenceCode:
try:
# Try to recognize null references explicitly.
if toInteger(value.address) == 0:
self.putSpecialValue(SpecialNullReferenceValue)
self.putType(typeName)
self.putNumChild(0)
return
except:
pass
if tryDynamic:
try:
# Dynamic references are not supported by gdb, see
# http://sourceware.org/bugzilla/show_bug.cgi?id=14077.
# Find the dynamic type manually using referenced_type.
value = value.referenced_value()
value = value.cast(value.dynamic_type)
self.putItem(value)
self.putBetterType("%s &" % value.type)
return
except:
pass
try:
# FIXME: This throws "RuntimeError: Attempt to dereference a
# generic pointer." with MinGW's gcc 4.5 when it "identifies"
# a "QWidget &" as "void &" and with optimized out code.
self.putItem(value.cast(typeobj.target().unqualified()))
self.putBetterType("%s &" % self.currentType.value)
return
except RuntimeError:
self.putSpecialValue(SpecialOptimizedOutValue)
self.putType(typeName)
self.putNumChild(0)
return
if typeobj.code == IntCode or typeobj.code == CharCode:
self.putType(typeName)
if typeobj.sizeof == 1:
# Force unadorned value transport for char and Co.
self.putValue(int(value) & 0xff)
else:
self.putValue(value)
self.putNumChild(0)
return
if typeobj.code == FloatCode or typeobj.code == BoolCode:
self.putType(typeName)
self.putValue(value)
self.putNumChild(0)
return
if typeobj.code == EnumCode:
self.putType(typeName)
self.putValue("%s (%d)" % (value, value))
self.putNumChild(0)
return
if typeobj.code == ComplexCode:
self.putType(typeName)
self.putValue("%s" % value)
self.putNumChild(0)
return
if typeobj.code == TypedefCode:
if typeName in self.qqDumpers:
self.putType(typeName)
self.qqDumpers[typeName](self, value)
return
typeobj = stripTypedefs(typeobj)
# The cast can destroy the address?
#self.putAddress(value.address)
# Workaround for http://sourceware.org/bugzilla/show_bug.cgi?id=13380
if typeobj.code == ArrayCode:
value = self.parseAndEvaluate("{%s}%s" % (typeobj, value.address))
else:
try:
value = value.cast(typeobj)
except:
self.putValue("<optimized out typedef>")
self.putType(typeName)
self.putNumChild(0)
return
self.putItem(value)
self.putBetterType(typeName)
return
if typeobj.code == ArrayCode:
self.putCStyleArray(value)
return
if typeobj.code == PointerCode:
# This could still be stored in a register and
# potentially dereferencable.
self.putFormattedPointer(value)
return
if typeobj.code == MethodPointerCode \
or typeobj.code == MethodCode \
or typeobj.code == FunctionCode \
or typeobj.code == MemberPointerCode:
self.putType(typeName)
self.putValue(value)
self.putNumChild(0)
return
if typeName.startswith("<anon"):
# Anonymous union. We need a dummy name to distinguish
# multiple anonymous unions in the struct.
self.putType(typeobj)
self.putSpecialValue(SpecialEmptyStructureValue)
self.anonNumber += 1
with Children(self, 1):
self.listAnonymous(value, "#%d" % self.anonNumber, typeobj)
return
if typeobj.code == StringCode:
# FORTRAN strings
size = typeobj.sizeof
data = self.readMemory(value.address, size)
self.putValue(data, Hex2EncodedLatin1, 1)
self.putType(typeobj)
if typeobj.code != StructCode and typeobj.code != UnionCode:
warn("WRONG ASSUMPTION HERE: %s " % typeobj.code)
self.check(False)
if tryDynamic:
self.putItem(self.expensiveDowncast(value), False)
return
if self.tryPutPrettyItem(typeName, value):
return
# D arrays, gdc compiled.
if typeName.endswith("[]"):
n = value["length"]
base = value["ptr"]
self.putType(typeName)
self.putItemCount(n)
if self.isExpanded():
self.putArrayData(base.type.target(), base, n)
return
#warn("GENERIC STRUCT: %s" % typeobj)
#warn("INAME: %s " % self.currentIName)
#warn("INAMES: %s " % self.expandedINames)
#warn("EXPANDED: %s " % (self.currentIName in self.expandedINames))
staticMetaObject = self.extractStaticMetaObject(value.type)
if staticMetaObject:
self.putQObjectNameValue(value)
self.putType(typeName)
self.putEmptyValue()
self.putNumChild(len(typeobj.fields()))
if self.currentIName in self.expandedINames:
innerType = None
with Children(self, 1, childType=innerType):
self.putFields(value)
if staticMetaObject:
self.putQObjectGuts(value, staticMetaObject)
def toBlob(self, value):
size = toInteger(value.type.sizeof)
if value.address:
return self.extractBlob(value.address, size)
# No address. Possibly the result of an inferior call.
y = value.cast(gdb.lookup_type("unsigned char").array(0, int(size - 1)))
buf = bytearray(struct.pack('x' * size))
for i in range(size):
buf[i] = int(y[i])
return Blob(bytes(buf))
def extractBlob(self, base, size):
inferior = self.selectedInferior()
return Blob(inferior.read_memory(base, size))
def readCString(self, base):
inferior = self.selectedInferior()
mem = ""
while True:
char = inferior.read_memory(base, 1)[0]
if not char:
break
mem += char
base += 1
#if sys.version_info[0] >= 3:
# return mem.tobytes()
return mem
def putFields(self, value, dumpBase = True):
fields = value.type.fields()
if self.sortStructMembers:
def sortOrder(field):
if field.is_base_class:
return 0
if field.name and field.name.startswith("_vptr."):
return 1
return 2
fields.sort(key = lambda field: "%d%s" % (sortOrder(field), field.name))
#warn("TYPE: %s" % value.type)
#warn("FIELDS: %s" % fields)
baseNumber = 0
for field in fields:
#warn("FIELD: %s" % field)
#warn(" BITSIZE: %s" % field.bitsize)
#warn(" ARTIFICIAL: %s" % field.artificial)
# Since GDB commit b5b08fb4 anonymous structs get also reported
# with a 'None' name.
if field.name is None:
if value.type.code == ArrayCode:
# An array.
typeobj = stripTypedefs(value.type)
innerType = typeobj.target()
p = value.cast(innerType.pointer())
for i in xrange(int(typeobj.sizeof / innerType.sizeof)):
with SubItem(self, i):
self.putItem(p.dereference())
p = p + 1
else:
# Something without a name.
self.anonNumber += 1
with SubItem(self, str(self.anonNumber)):
self.putItem(value[field])
continue
# Ignore vtable pointers for virtual inheritance.
if field.name.startswith("_vptr."):
with SubItem(self, "[vptr]"):
# int (**)(void)
n = 100
self.putType(" ")
self.putValue(value[field.name])
self.putNumChild(n)
if self.isExpanded():
with Children(self):
p = value[field.name]
for i in xrange(n):
if toInteger(p.dereference()) != 0:
with SubItem(self, i):
self.putItem(p.dereference())
self.putType(" ")
p = p + 1
continue
#warn("FIELD NAME: %s" % field.name)
#warn("FIELD TYPE: %s" % field.type)
if field.is_base_class:
# Field is base type. We cannot use field.name as part
# of the iname as it might contain spaces and other
# strange characters.
if dumpBase:
baseNumber += 1
with UnnamedSubItem(self, "@%d" % baseNumber):
baseValue = value.cast(field.type)
self.putBaseClassName(field.name)
self.putAddress(baseValue.address)
self.putItem(baseValue, False)
elif len(field.name) == 0:
# Anonymous union. We need a dummy name to distinguish
# multiple anonymous unions in the struct.
self.anonNumber += 1
self.listAnonymous(value, "#%d" % self.anonNumber,
field.type)
else:
# Named field.
with SubItem(self, field.name):
#bitsize = getattr(field, "bitsize", None)
#if not bitsize is None:
# self.put("bitsize=\"%s\"" % bitsize)
self.putItem(self.downcast(value[field.name]))
def putBaseClassName(self, name):
self.put('iname="%s",' % self.currentIName)
self.put('name="[%s]",' % name)
def listAnonymous(self, value, name, typeobj):
for field in typeobj.fields():
#warn("FIELD NAME: %s" % field.name)
if field.name:
with SubItem(self, field.name):
self.putItem(value[field.name])
else:
# Further nested.
self.anonNumber += 1
name = "#%d" % self.anonNumber
#iname = "%s.%s" % (selitem.iname, name)
#child = SameItem(item.value, iname)
with SubItem(self, name):
self.put('name="%s",' % name)
self.putEmptyValue()
fieldTypeName = str(field.type)
if fieldTypeName.endswith("<anonymous union>"):
self.putType("<anonymous union>")
elif fieldTypeName.endswith("<anonymous struct>"):
self.putType("<anonymous struct>")
else:
self.putType(fieldTypeName)
with Children(self, 1):
self.listAnonymous(value, name, field.type)
#def threadname(self, maximalStackDepth, objectPrivateType):
# e = gdb.selected_frame()
# out = ""
# ns = self.qtNamespace()
# while True:
# maximalStackDepth -= 1
# if maximalStackDepth < 0:
# break
# e = e.older()
# if e == None or e.name() == None:
# break
# if e.name() == ns + "QThreadPrivate::start" \
# or e.name() == "_ZN14QThreadPrivate5startEPv@4":
# try:
# thrptr = e.read_var("thr").dereference()
# d_ptr = thrptr["d_ptr"]["d"].cast(objectPrivateType).dereference()
# try:
# objectName = d_ptr["objectName"]
# except: # Qt 5
# p = d_ptr["extraData"]
# if not self.isNull(p):
# objectName = p.dereference()["objectName"]
# if not objectName is None:
# data, size, alloc = self.stringData(objectName)
# if size > 0:
# s = self.readMemory(data, 2 * size)
#
# thread = gdb.selected_thread()
# inner = '{valueencoded="';
# inner += str(Hex4EncodedLittleEndianWithoutQuotes)+'",id="'
# inner += str(thread.num) + '",value="'
# inner += s
# #inner += self.encodeString(objectName)
# inner += '"},'
#
# out += inner
# except:
# pass
# return out
def threadnames(self, maximalStackDepth):
# FIXME: This needs a proper implementation for MinGW, and only there.
# Linux, Mac and QNX mirror the objectName() to the underlying threads,
# so we get the names already as part of the -thread-info output.
return '[]'
#out = '['
#oldthread = gdb.selected_thread()
#if oldthread:
# try:
# objectPrivateType = gdb.lookup_type(ns + "QObjectPrivate").pointer()
# inferior = self.selectedInferior()
# for thread in inferior.threads():
# thread.switch()
# out += self.threadname(maximalStackDepth, objectPrivateType)
# except:
# pass
# oldthread.switch()
#return out + ']'
def importPlainDumper(self, printer):
name = printer.name.replace("::", "__")
self.qqDumpers[name] = PlainDumper(printer)
self.qqFormats[name] = ""
def importPlainDumpers(self):
for obj in gdb.objfiles():
for printers in obj.pretty_printers + gdb.pretty_printers:
for printer in printers.subprinters:
self.importPlainDumper(printer)
def qtNamespace(self):
if not self.currentQtNamespaceGuess is None:
return self.currentQtNamespaceGuess
# This only works when called from a valid frame.
try:
cand = "QArrayData::shared_null"
symbol = gdb.lookup_symbol(cand)[0]
if symbol:
ns = symbol.name[:-len(cand)]
self.qtNamespaceToReport = ns
self.qtNamespace = lambda: ns
return ns
except:
pass
try:
# This is Qt, but not 5.x.
cand = "QByteArray::shared_null"
symbol = gdb.lookup_symbol(cand)[0]
if symbol:
ns = symbol.name[:-len(cand)]
self.qtNamespaceToReport = ns
self.qtNamespace = lambda: ns
self.fallbackQtVersion = 0x40800
return ns
except:
pass
try:
# Last fall backs.
s = gdb.execute("ptype QByteArray", to_string=True)
if s.find("QMemArray") >= 0:
# Qt 3.
self.qtNamespaceToReport = ""
self.qtNamespace = lambda: ""
self.qtVersion = lambda: 0x30308
self.fallbackQtVersion = 0x30308
return ""
# Seemingly needed with Debian's GDB 7.4.1
ns = s[s.find("class")+6:s.find("QByteArray")]
if len(ns):
self.qtNamespaceToReport = ns
self.qtNamespace = lambda: ns
return ns
except:
pass
self.currentQtNamespaceGuess = ""
return ""
def assignValue(self, args):
typeName = self.hexdecode(args['type'])
expr = self.hexdecode(args['expr'])
value = self.hexdecode(args['value'])
simpleType = int(args['simpleType'])
ns = self.qtNamespace()
if typeName.startswith(ns):
typeName = typeName[len(ns):]
typeName = typeName.replace("::", "__")
pos = typeName.find('<')
if pos != -1:
typeName = typeName[0:pos]
if typeName in self.qqEditable and not simpleType:
#self.qqEditable[typeName](self, expr, value)
expr = gdb.parse_and_eval(expr)
self.qqEditable[typeName](self, expr, value)
else:
cmd = "set variable (%s)=%s" % (expr, value)
gdb.execute(cmd)
def hasVTable(self, typeobj):
fields = typeobj.fields()
if len(fields) == 0:
return False
if fields[0].is_base_class:
return hasVTable(fields[0].type)
return str(fields[0].type) == "int (**)(void)"
def dynamicTypeName(self, value):
if self.hasVTable(value.type):
#vtbl = str(gdb.parse_and_eval("{int(*)(int)}%s" % int(value.address)))
try:
# Fails on 7.1 due to the missing to_string.
vtbl = gdb.execute("info symbol {int*}%s" % int(value.address),
to_string = True)
pos1 = vtbl.find("vtable ")
if pos1 != -1:
pos1 += 11
pos2 = vtbl.find(" +", pos1)
if pos2 != -1:
return vtbl[pos1 : pos2]
except:
pass
return str(value.type)
def downcast(self, value):
try:
return value.cast(value.dynamic_type)
except:
pass
#try:
# return value.cast(self.lookupType(self.dynamicTypeName(value)))
#except:
# pass
return value
def expensiveDowncast(self, value):
try:
return value.cast(value.dynamic_type)
except:
pass
try:
return value.cast(self.lookupType(self.dynamicTypeName(value)))
except:
pass
return value
def addToCache(self, typeobj):
typename = str(typeobj)
if typename in self.typesReported:
return
self.typesReported[typename] = True
self.typesToReport[typename] = typeobj
def enumExpression(self, enumType, enumValue):
return self.qtNamespace() + "Qt::" + enumValue
def lookupType(self, typestring):
typeobj = self.typeCache.get(typestring)
#warn("LOOKUP 1: %s -> %s" % (typestring, typeobj))
if not typeobj is None:
return typeobj
if typestring == "void":
typeobj = gdb.lookup_type(typestring)
self.typeCache[typestring] = typeobj
self.typesToReport[typestring] = typeobj
return typeobj
#try:
# typeobj = gdb.parse_and_eval("{%s}&main" % typestring).typeobj
# if not typeobj is None:
# self.typeCache[typestring] = typeobj
# self.typesToReport[typestring] = typeobj
# return typeobj
#except:
# pass
# See http://sourceware.org/bugzilla/show_bug.cgi?id=13269
# gcc produces "{anonymous}", gdb "(anonymous namespace)"
# "<unnamed>" has been seen too. The only thing gdb
# understands when reading things back is "(anonymous namespace)"
if typestring.find("{anonymous}") != -1:
ts = typestring
ts = ts.replace("{anonymous}", "(anonymous namespace)")
typeobj = self.lookupType(ts)
if not typeobj is None:
self.typeCache[typestring] = typeobj
self.typesToReport[typestring] = typeobj
return typeobj
#warn(" RESULT FOR 7.2: '%s': %s" % (typestring, typeobj))
# This part should only trigger for
# gdb 7.1 for types with namespace separators.
# And anonymous namespaces.
ts = typestring
while True:
#warn("TS: '%s'" % ts)
if ts.startswith("class "):
ts = ts[6:]
elif ts.startswith("struct "):
ts = ts[7:]
elif ts.startswith("const "):
ts = ts[6:]
elif ts.startswith("volatile "):
ts = ts[9:]
elif ts.startswith("enum "):
ts = ts[5:]
elif ts.endswith(" const"):
ts = ts[:-6]
elif ts.endswith(" volatile"):
ts = ts[:-9]
elif ts.endswith("*const"):
ts = ts[:-5]
elif ts.endswith("*volatile"):
ts = ts[:-8]
else:
break
if ts.endswith('*'):
typeobj = self.lookupType(ts[0:-1])
if not typeobj is None:
typeobj = typeobj.pointer()
self.typeCache[typestring] = typeobj
self.typesToReport[typestring] = typeobj
return typeobj
try:
#warn("LOOKING UP '%s'" % ts)
typeobj = gdb.lookup_type(ts)
except RuntimeError as error:
#warn("LOOKING UP '%s': %s" % (ts, error))
# See http://sourceware.org/bugzilla/show_bug.cgi?id=11912
exp = "(class '%s'*)0" % ts
try:
typeobj = self.parseAndEvaluate(exp).type.target()
except:
# Can throw "RuntimeError: No type named class Foo."
pass
except:
#warn("LOOKING UP '%s' FAILED" % ts)
pass
if not typeobj is None:
self.typeCache[typestring] = typeobj
self.typesToReport[typestring] = typeobj
return typeobj
# This could still be None as gdb.lookup_type("char[3]") generates
# "RuntimeError: No type named char[3]"
self.typeCache[typestring] = typeobj
self.typesToReport[typestring] = typeobj
return typeobj
def stackListFrames(self, args):
def fromNativePath(str):
return str.replace('\\', '/')
limit = int(args['limit'])
if limit <= 0:
limit = 10000
options = args['options']
opts = {}
if options == "nativemixed":
opts["nativemixed"] = 1
self.prepare(opts)
self.output = []
frame = gdb.newest_frame()
i = 0
self.currentCallContext = None
while i < limit and frame:
with OutputSafer(self):
name = frame.name()
functionName = "??" if name is None else name
fileName = ""
objfile = ""
fullName = ""
pc = frame.pc()
sal = frame.find_sal()
line = -1
if sal:
line = sal.line
symtab = sal.symtab
if not symtab is None:
objfile = fromNativePath(symtab.objfile.filename)
fileName = fromNativePath(symtab.filename)
fullName = symtab.fullname()
if fullName is None:
fullName = ""
else:
fullName = fromNativePath(fullName)
if self.nativeMixed:
if self.isReportableQmlFrame(functionName):
engine = frame.read_var("engine")
h = self.extractQmlLocation(engine)
self.put(('frame={level="%s",func="%s",file="%s",'
'fullname="%s",line="%s",language="js",addr="0x%x"}')
% (i, h['functionName'], h['fileName'], h['fileName'],
h['lineNumber'], h['context']))
i += 1
frame = frame.older()
continue
if self.isInternalQmlFrame(functionName):
frame = frame.older()
self.put(('frame={level="%s",addr="0x%x",func="%s",'
'file="%s",fullname="%s",line="%s",'
'from="%s",language="c",usable="0"}') %
(i, pc, functionName, fileName, fullName, line, objfile))
i += 1
frame = frame.older()
continue
self.put(('frame={level="%s",addr="0x%x",func="%s",'
'file="%s",fullname="%s",line="%s",'
'from="%s",language="c"}') %
(i, pc, functionName, fileName, fullName, line, objfile))
frame = frame.older()
i += 1
safePrint(''.join(self.output))
def createResolvePendingBreakpointsHookBreakpoint(self, args):
class Resolver(gdb.Breakpoint):
def __init__(self, dumper, args):
self.dumper = dumper
self.args = args
spec = "qt_v4ResolvePendingBreakpointsHook"
print("Preparing hook to resolve pending QML breakpoint at %s" % args)
super(Resolver, self).\
__init__(spec, gdb.BP_BREAKPOINT, internal=True, temporary=False)
def stop(self):
bp = self.dumper.doInsertQmlBreakpoint(args)
print("Resolving QML breakpoint %s -> %s" % (args, bp))
self.enabled = False
return False
self.qmlBreakpoints.append(Resolver(self, args))
def exitGdb(self, _):
gdb.execute("quit")
def loadDumpers(self, args):
self.setupDumpers()
def reportDumpers(self, msg):
print(msg)
def profile1(self, args):
"""Internal profiling"""
import tempfile
import cProfile
tempDir = tempfile.gettempdir() + "/bbprof"
cProfile.run('theDumper.showData(%s)' % args, tempDir)
import pstats
pstats.Stats(tempDir).sort_stats('time').print_stats()
def profile2(self, args):
import timeit
print(timeit.repeat('theDumper.showData(%s)' % args,
'from __main__ import theDumper', number=10))
class CliDumper(Dumper):
def __init__(self):
Dumper.__init__(self)
self.childrenPrefix = '['
self.chidrenSuffix = '] '
self.indent = 0
self.isCli = True
def reportDumpers(self, msg):
return msg
def enterSubItem(self, item):
if not item.iname:
item.iname = "%s.%s" % (self.currentIName, item.name)
self.indent += 1
self.putNewline()
if isinstance(item.name, str):
self.output += item.name + ' = '
item.savedIName = self.currentIName
item.savedValue = self.currentValue
item.savedType = self.currentType
item.savedCurrentAddress = self.currentAddress
self.currentIName = item.iname
self.currentValue = ReportItem();
self.currentType = ReportItem();
self.currentAddress = None
def exitSubItem(self, item, exType, exValue, exTraceBack):
self.indent -= 1
#warn("CURRENT VALUE: %s: %s %s" %
# (self.currentIName, self.currentValue, self.currentType))
if not exType is None:
if self.passExceptions:
showException("SUBITEM", exType, exValue, exTraceBack)
self.putNumChild(0)
self.putSpecialValue(SpecialNotAccessibleValue)
try:
if self.currentType.value:
typeName = self.stripClassTag(self.currentType.value)
self.put('<%s> = {' % typeName)
if self.currentValue.value is None:
self.put('<not accessible>')
else:
value = self.currentValue.value
if self.currentValue.encoding is Hex2EncodedLatin1:
value = self.hexdecode(value)
elif self.currentValue.encoding is Hex2EncodedUtf8:
value = self.hexdecode(value)
elif self.currentValue.encoding is Hex4EncodedLittleEndian:
b = bytes.fromhex(value)
value = codecs.decode(b, 'utf-16')
self.put('"%s"' % value)
if self.currentValue.elided:
self.put('...')
if self.currentType.value:
self.put('}')
except:
pass
if not self.currentAddress is None:
self.put(self.currentAddress)
self.currentIName = item.savedIName
self.currentValue = item.savedValue
self.currentType = item.savedType
self.currentAddress = item.savedCurrentAddress
return True
def putNewline(self):
self.output += '\n' + ' ' * self.indent
def put(self, line):
if self.output.endswith('\n'):
self.output = self.output[0:-1]
self.output += line
def putNumChild(self, numchild):
pass
def putBaseClassName(self, name):
pass
def putOriginalAddress(self, value):
pass
def putAddressRange(self, base, step):
return True
def showData(self, args):
args['fancy'] = 1
args['passException'] = 1
args['autoderef'] = 1
name = args['varlist']
self.prepare(args)
self.output = name + ' = '
frame = gdb.selected_frame()
value = frame.read_var(name)
with TopLevelItem(self, name):
self.putItem(value)
return self.output
# Global instance.
if gdb.parameter('height') is None:
theDumper = Dumper()
else:
import codecs
theDumper = CliDumper()
######################################################################
#
# ThreadNames Command
#
#######################################################################
def threadnames(arg):
return theDumper.threadnames(int(arg))
registerCommand("threadnames", threadnames)
#######################################################################
#
# Native Mixed
#
#######################################################################
#class QmlEngineCreationTracker(gdb.Breakpoint):
# def __init__(self):
# spec = "QQmlEnginePrivate::init"
# super(QmlEngineCreationTracker, self).\
# __init__(spec, gdb.BP_BREAKPOINT, internal=True)
#
# def stop(self):
# engine = gdb.parse_and_eval("q_ptr")
# print("QML engine created: %s" % engine)
# theDumper.qmlEngines.append(engine)
# return False
#
#QmlEngineCreationTracker()
class TriggeredBreakpointHookBreakpoint(gdb.Breakpoint):
def __init__(self):
spec = "qt_v4TriggeredBreakpointHook"
super(TriggeredBreakpointHookBreakpoint, self).\
__init__(spec, gdb.BP_BREAKPOINT, internal=True)
def stop(self):
print("QML engine stopped.")
return True
TriggeredBreakpointHookBreakpoint()
|
lgpl-2.1
| 4,238,433,531,481,384,400
| 34.328782
| 105
| 0.519471
| false
| 4.142885
| false
| false
| false
|
ClearCorp/server-tools
|
external_file_location/models/task.py
|
1
|
8567
|
# coding: utf-8
# @ 2015 Valentin CHEMIERE @ Akretion
# © @author Mourad EL HADJ MIMOUNE <mourad.elhadj.mimoune@akretion.com>
# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html).
from openerp import models, fields, api
import openerp
from openerp import tools
from base64 import b64encode
import os
import datetime
import logging
_logger = logging.getLogger(__name__)
try:
# We use a jinja2 sandboxed environment to render mako templates.
# Note that the rendering does not cover all the mako syntax, in particular
# arbitrary Python statements are not accepted, and not all expressions are
# allowed: only "public" attributes (not starting with '_') of objects may
# be accessed.
# This is done on purpose: it prevents incidental or malicious execution of
# Python code that may break the security of the server.
from jinja2.sandbox import SandboxedEnvironment
mako_template_env = SandboxedEnvironment(
variable_start_string="${",
variable_end_string="}",
line_statement_prefix="%",
trim_blocks=True, # do not output newline after blocks
)
mako_template_env.globals.update({
'str': str,
'datetime': datetime,
'len': len,
'abs': abs,
'min': min,
'max': max,
'sum': sum,
'filter': filter,
'reduce': reduce,
'map': map,
'round': round,
})
except ImportError:
_logger.warning("jinja2 not available, templating features will not work!")
class Task(models.Model):
_name = 'external.file.task'
_description = 'External file task'
name = fields.Char(required=True)
method_type = fields.Selection(
[('import', 'Import'), ('export', 'Export')],
required=True)
filename = fields.Char(help='File name which is imported.'
'You can use file pattern like *.txt'
'to import all txt files')
filepath = fields.Char(help='Path to imported/exported file')
location_id = fields.Many2one('external.file.location', string='Location',
required=True)
attachment_ids = fields.One2many('ir.attachment.metadata', 'task_id',
string='Attachment')
move_path = fields.Char(string='Move Path',
help='Imported File will be moved to this path')
new_name = fields.Char(string='New Name',
help='Imported File will be renamed to this name'
'Name can use mako template where obj is an '
'ir_attachement. template exemple : '
' ${obj.name}-${obj.create_date}.csv')
md5_check = fields.Boolean(help='Control file integrity after import with'
' a md5 file')
after_import = fields.Selection(selection='_get_action',
help='Action after import a file')
company_id = fields.Many2one(
'res.company', 'Company',
default=lambda self: self.env['res.company']._company_default_get(
'external.file.task'))
file_type = fields.Selection(
selection=[],
string="File Type",
help="The file type determines an import method to be used "
"to parse and transform data before their import in ERP")
active = fields.Boolean(default=True)
def _get_action(self):
return [('rename', 'Rename'),
('move', 'Move'),
('move_rename', 'Move & Rename'),
('delete', 'Delete'),
]
@api.multi
def _prepare_attachment_vals(self, datas, filename, md5_datas):
self.ensure_one()
vals = {
'name': filename,
'datas': b64encode(datas),
'datas_fname': filename,
'task_id': self.id,
'external_hash': md5_datas,
'file_type': self.file_type or False,
}
return vals
@api.model
def _template_render(self, template, record):
try:
template = mako_template_env.from_string(tools.ustr(template))
except Exception:
_logger.exception("Failed to load template %r", template)
variables = {'obj': record}
try:
render_result = template.render(variables)
except Exception:
_logger.exception(
"Failed to render template %r using values %r" %
(template, variables))
render_result = u""
if render_result == u"False":
render_result = u""
return render_result
@api.model
def run_task_scheduler(self, domain=None):
if domain is None:
domain = []
tasks = self.env['external.file.task'].search(domain)
for task in tasks:
if task.method_type == 'import':
task.run_import()
elif task.method_type == 'export':
task.run_export()
@api.multi
def run_import(self):
self.ensure_one()
protocols = self.env['external.file.location']._get_classes()
cls = protocols.get(self.location_id.protocol)[1]
attach_obj = self.env['ir.attachment.metadata']
with cls.connect(self.location_id) as conn:
md5_datas = ''
for file_name in conn.listdir(path=self.filepath,
wildcard=self.filename or '',
files_only=True):
with api.Environment.manage():
with openerp.registry(
self.env.cr.dbname).cursor() as new_cr:
new_env = api.Environment(new_cr, self.env.uid,
self.env.context)
try:
full_path = os.path.join(self.filepath, file_name)
file_data = conn.open(full_path, 'rb')
datas = file_data.read()
if self.md5_check:
md5_file = conn.open(full_path + '.md5', 'rb')
md5_datas = md5_file.read().rstrip('\r\n')
attach_vals = self._prepare_attachment_vals(
datas, file_name, md5_datas)
attachment = attach_obj.with_env(new_env).create(
attach_vals)
new_full_path = False
if self.after_import == 'rename':
new_name = self._template_render(
self.new_name, attachment)
new_full_path = os.path.join(
self.filepath, new_name)
elif self.after_import == 'move':
new_full_path = os.path.join(
self.move_path, file_name)
elif self.after_import == 'move_rename':
new_name = self._template_render(
self.new_name, attachment)
new_full_path = os.path.join(
self.move_path, new_name)
if new_full_path:
conn.rename(full_path, new_full_path)
if self.md5_check:
conn.rename(
full_path + '.md5',
new_full_path + '/md5')
if self.after_import == 'delete':
conn.remove(full_path)
if self.md5_check:
conn.remove(full_path + '.md5')
except Exception, e:
new_env.cr.rollback()
raise e
else:
new_env.cr.commit()
@api.multi
def run_export(self):
self.ensure_one()
attachment_obj = self.env['ir.attachment.metadata']
attachments = attachment_obj.search(
[('task_id', '=', self.id), ('state', '!=', 'done')])
for attachment in attachments:
attachment.run()
|
agpl-3.0
| 3,746,848,047,542,242,000
| 39.40566
| 79
| 0.494747
| false
| 4.573412
| false
| false
| false
|
eldstal/cardcinogen
|
card.py
|
1
|
2572
|
#!/bin/env python3
import unittest
import os
import sys
import util
import log
from PIL import Image
from layout import SimpleLayout, ComplexLayout
class CardTemplate:
""" Parsed version of a JSON card template """
def __init__(self, json, rootdir="."):
self.front_name = util.get_default(json, "front-image", "front.png")
self.hidden_name = util.get_default(json, "hidden-image", "hidden.png")
self.layouts = []
for j in util.get_default(json, "layouts", []):
self.type = util.get_default(j, "type", "simple")
if (self.type == "complex"):
self.layouts.append(ComplexLayout(j, rootdir))
else:
self.layouts.append(SimpleLayout(j, rootdir))
front_path = os.path.join(rootdir, self.front_name)
hidden_path = os.path.join(rootdir, self.hidden_name)
# Make sure we have valid images and they all have matching sizes
self.front = util.default_image(front_path, (372, 520))
self.hidden = util.default_image(hidden_path, self.front.size, self.front.size)
def make_card(self, textgen):
""" Generate a single card """
if (len(self.layouts) == 0):
log.log.write("Warning: No layouts specified.")
return None
face = self.front.copy()
for l in self.layouts:
overlay = l.render(face.size, textgen)
if (overlay is None):
# This layout is done generating cards.
# This happens when, eventually, textgen runs out of card texts for a given layout.
continue
# We have a card! Return it and that's that.
face.paste(overlay, mask=overlay)
return face
# None of the layouts can generate any cards. We're done.
return None
#
# Unit tests
#
class TestCardStuff(unittest.TestCase):
def test_default(self):
tmpl_default = CardTemplate({})
self.assertEqual(tmpl_default.front_name, "front.png")
self.assertEqual(tmpl_default.hidden_name, "hidden.png")
self.assertEqual(tmpl_default.labels, [])
# Override all settings
dic = {
"front-image": "card-front.jpeg",
"hidden-image": "card-hidden.jpeg",
"layout": [
{
"x": 10
},
{
"y": 20
}
]
}
tmpl = CardTemplate(dic)
self.assertEqual(tmpl.front_name, dic["front-image"])
self.assertEqual(tmpl.hidden_name, dic["hidden-image"])
self.assertEqual(len(tmpl.labels), 2)
self.assertEqual(tmpl.labels[0].x, dic["layout"][0]["x"])
self.assertEqual(tmpl.labels[1].y, dic["layout"][1]["y"])
if __name__ == '__main__':
unittest.main()
|
mit
| 445,096,269,937,110,460
| 26.073684
| 91
| 0.630638
| false
| 3.475676
| true
| false
| false
|
dpaiton/OpenPV
|
pv-core/python/pvtools/writepvpfile.py
|
1
|
10534
|
import numpy as np
import scipy.sparse as sp
import pdb
from readpvpheader import headerPattern, extendedHeaderPattern
def checkData(data):
#Check if dictionary
if not isinstance(data, dict):
raise ValueError("Input data structure must be a dictionary with the keys \"values\" and \"time\"")
#Check for fields values and time
if not 'values' in data.keys():
raise ValueError("Input data structure missing \"values\" key");
if not 'time' in data.keys():
raise ValueError("Input data structure missing \"time\" key");
values = data["values"]
time = data["time"]
#Make sure the 2 arrays are numpy arrays or sparse matrices
if not sp.issparse(values) and not type(values).__module__ == np.__name__:
raise ValueError("Values field must be either a sparse matrix or a numpy array")
#If time is a list, convert to numpy array
if type(time) == list:
data["time"] = np.array(data["time"])
time = data["time"]
if not type(time).__module__ == np.__name__:
raise ValueError("Time field must be either a numpy array or a list")
#Check dimensions of values and time
if sp.issparse(values):
if not values.ndim == 2:
raise ValueError("Sparse values must have 2 dimensions")
else:
if not values.ndim == 4 and not values.ndim == 6:
raise ValueError("Dense values must have either 4 or 6 dimensions")
#Check that sizes of values and time matches
valuesShape = values.shape
timeShape = time.shape
if not valuesShape[0] == timeShape[0]:
raise ValueError("Values must have the same number of frames as time (" + str(valuesShape[0]) + " vs " + str(timeShape[0]) + ")")
#Values should be single floats, time should be double floats
data["values"] = data["values"].astype(np.float32)
data["time"] = data["time"].astype(np.float64)
#Dense values must be c-contiguous
if(not sp.issparse(data["values"]) and not data["values"].flags["C_CONTIGUOUS"]):
data["values"] = data["values"].copy(order='C')
def generateHeader(data, inShape):
#data["values"] can be one of 3 shapes: dense 4d mat for activity, dense 6d mat for weights
#scipy coo_sparse matrix for sparse activity
header = {}
values = data["values"]
#If sparse matrix, write as sparse format
if(sp.issparse(values)):
if(inShape == None):
raise ValueError("Sparse values must have shape input when generating header")
if len(inShape) != 3:
raise ValueError("Shape parameter must be a 3 tuple of (ny, nx, nf)")
(ny, nx, nf) = inShape
(numFrames, numFeat) = values.shape
if(not numFeat == ny*nx*nf):
raise ValueError("Shape provided does not match the data shape (" + str(ny) + "*" + str(nx) + "*" + str(nf) + " vs " + str(numFeat) + ")")
header["headersize"] = np.uint32(80)
header["numparams"] = np.uint32(20)
header["filetype"] = np.uint32(6)
header["nx"] = np.uint32(nx)
header["ny"] = np.uint32(ny)
header["nf"] = np.uint32(nf)
header["numrecords"] = np.uint32(1)
header["recordsize"] = np.uint32(0) #Not used in sparse activity
header["datasize"] = np.uint32(8) #Int/float are 4 bytes each
header["datatype"] = np.uint32(4) #Type is location-value pair
header["nxprocs"] = np.uint32(1) #No longer used
header["nyprocs"] = np.uint32(1)
header["nxGlobal"] = np.uint32(nx)
header["nyGlobal"] = np.uint32(ny)
header["kx0"] = np.uint32(0)
header["ky0"] = np.uint32(0)
header["nbatch"] = np.uint32(1)
header["nbands"] = np.uint32(numFrames)
header["time"] = np.float64(data["time"][0])
#If 4d dense matrix, write as dense format
elif(values.ndim == 4):
(numFrames, ny, nx, nf) = values.shape
header["headersize"] = np.uint32(80)
header["numparams"] = np.uint32(20)
header["filetype"] = np.uint32(4)
header["nx"] = np.uint32(nx)
header["ny"] = np.uint32(ny)
header["nf"] = np.uint32(nf)
header["numrecords"] = np.uint32(1)
header["recordsize"] = np.uint32(nx*ny*nf) #Not used in sparse activity
header["datasize"] = np.uint32(4) #floats are 4 bytes
header["datatype"] = np.uint32(3) #Type is float
header["nxprocs"] = np.uint32(1) #No longer used
header["nyprocs"] = np.uint32(1)
header["nxGlobal"] = np.uint32(nx)
header["nyGlobal"] = np.uint32(ny)
header["kx0"] = np.uint32(0)
header["ky0"] = np.uint32(0)
header["nbatch"] = np.uint32(1)
header["nbands"] = np.uint32(numFrames)
header["time"] = np.float64(data["time"][0])
#If 6d dense matrix, write as weights format
elif(values.ndim == 6):
(numFrames, numArbors, numKernels, nyp, nxp, nfp) = values.shape
header["headersize"] = np.uint32(104)
header["numparams"] = np.uint32(26)
header["filetype"] = np.uint32(5)
header["nx"] = np.uint32(1) #size not used by weights
header["ny"] = np.uint32(1)
header["nf"] = np.uint32(numKernels) #Pre nf
header["numrecords"] = np.uint32(numArbors)
#Each data for arbor is preceded by nxp(2 bytes), ny (2 bytes) and offset (4 bytes)
header["recordsize"] = np.uint32(numKernels * (8+4*nxp*nyp*nfp))
header["datasize"] = np.uint32(4) #floats are 4 bytes
header["datatype"] = np.uint32(3) #float type
header["nxprocs"] = np.uint32(1)
header["nyprocs"] = np.uint32(1)
header["nxGlobal"] = np.uint32(1)
header["nyGlobal"] = np.uint32(1)
header["kx0"] = np.uint32(0)
header["ky0"] = np.uint32(0)
header["nbatch"] = np.uint32(1)
header["nbands"] = np.uint32(numArbors) #For weights, numArbors is stored in nbands, no field for numFrames
#This field will be updated on write
header["time"] = np.float64(data["time"][0])
#Weights have extended header
header["nxp"] = np.uint32(nxp)
header["nyp"] = np.uint32(nyp)
header["nfp"] = np.uint32(nfp)
header["wMax"] = np.uint32(1) #This field will be updated on write
header["wMin"] = np.uint32(1) #This field will be updated on write
header["numpatches"] = np.uint32(numKernels)
return header
def writepvpfile(filename, data, shape=None, useExistingHeader=False):
#Check data structure
checkData(data)
if not 'header' in data.keys():
if useExistingHeader:
raise ValueError("Must specify a \"header\" field if using existing header")
#Data can either have a header field or not
#Generate header if no header field
if not useExistingHeader:
#If it doesn't exist, generate header
data["header"] = generateHeader(data, shape)
# To get ordered list of header params
if data["header"]['numparams'] == 26:
hPattern = extendedHeaderPattern
else:
hPattern = headerPattern
with open(filename, 'wb') as stream:
if data["header"]['filetype'] == 1:
print('Filetype 1 not yet supported for write pvp')
elif data["header"]['filetype'] == 2:
print('Filetype 2 not yet supported for write pvp')
elif data["header"]['filetype'] == 3:
print('Filetype 3 not yet supported for write pvp')
elif data["header"]['filetype'] == 4:
(numFrames, ny, nx, nf) = data["values"].shape
#Write out header
for headerEntry in hPattern:
stream.write(headerEntry[1](data["header"][headerEntry[0]]))
for dataFrame in range(numFrames):
stream.write(data["time"][dataFrame])
stream.write(data["values"][dataFrame, :, :, :])
elif data["header"]['filetype'] == 5:
(numFrames, numArbors, numKernels, nyp, nxp, nfp) = data["values"].shape
# Type 5's have a header in each frame
#Make a copy of header dictionary to avoid changing
#the header field
tmpHeader = data["header"].copy()
for dataFrame in range(numFrames):
#Set header fields that change from frame to frame
tmpHeader["time"] = np.float64(data["time"][dataFrame])
##wMax and wMin are int32's, whereas the max and min might not be an int
#tmpHeader["wMax"] = np.uint32(np.max(data["values"][dataFrame, :, :, :, :, :]))
#tmpHeader["wMin"] = np.uint32(np.min(data["values"][dataFrame, :, :, :, :, :]))
for headerEntry in hPattern:
stream.write(headerEntry[1](tmpHeader[headerEntry[0]]))
#Within each patch, we write out each nxp, nyp, and offset
for dataArbor in range(numArbors):
for dataKernel in range(numKernels):
stream.write(np.uint16(nxp))
stream.write(np.uint16(nyp))
stream.write(np.uint32(0)) #Offset is always 0 for kernels
stream.write(data["values"][dataFrame, dataArbor, dataKernel, :, :, :])
#Sparse values
elif data["header"]['filetype'] == 6:
(numFrames, numData) = data["values"].shape
# Copied from filetype 4
for headerEntry in hPattern:
stream.write(headerEntry[1](data["header"][headerEntry[0]]))
for dataFrame in range(numFrames):
frameVals = data["values"].getrow(dataFrame)
count = frameVals.nnz
index = frameVals.indices
value = frameVals.data
#Write time first, followed by count, followed by values
stream.write(data["time"][dataFrame])
stream.write(np.uint32(count))
for i in range(count):
stream.write(np.uint32(index[i]))
stream.write(np.float32(value[i]))
if __name__ == "__main__":
data = {}
values = np.ones((2, 10))
data["values"] = sp.coo_matrix(values)
data["time"] = range(2)
writepvpfile("test.pvp", data, shape=(2, 5, 1))
|
epl-1.0
| 6,473,318,771,748,574,000
| 43.447257
| 150
| 0.57566
| false
| 3.675506
| false
| false
| false
|
thinkAmi-sandbox/Bottle-sample
|
e.g._bbs_app/bbs.py
|
1
|
1890
|
import datetime
import pickle
from pathlib import Path
from bottle import Bottle, run, get, post, redirect, request, response, jinja2_template
class Message(object):
def __init__(self, title, handle, message):
self.title = title
self.handle = handle
self.message = message
self.created_at = datetime.datetime.now().strftime('%Y/%m/%d %H:%M:%S')
# テストコードで扱えるよう、変数appにインスタンスをセット
app = Bottle()
@app.get('/')
def get_form():
# Cookieの値をUnicodeで取得するため、getunicode()メソッドを使う
# https://bottlepy.org/docs/dev/tutorial.html#introducing-formsdict
# https://bottlepy.org/docs/dev/api.html#bottle.FormsDict
# handle = request.get_cookie('handle') #=> 「ã」がセットされてしまう
handle = request.cookies.getunicode('handle', default='')
messages = read_messages()
return jinja2_template('bbs.html', handle=handle, messages=messages)
@app.post('/')
def post_form():
response.set_cookie('handle', request.forms.get('handle'))
message = Message(
# こちらもHTML上での文字化けを防ぐため、get()ではなくgetunicode()を使う
title=request.forms.getunicode('title'),
handle=request.forms.getunicode('handle'),
message=request.forms.getunicode('message'),
)
messages = read_messages()
messages.append(message)
with open('bbs.pickle', mode='wb') as f:
pickle.dump(messages, f)
redirect('/')
@app.get('/delete_cookie')
def delete_cookie():
response.delete_cookie('handle')
redirect('/')
def read_messages():
if Path('bbs.pickle').exists():
with open('bbs.pickle', mode='rb') as f:
return pickle.load(f)
return []
if __name__ == "__main__":
run(app, host="localhost", port=8080, debug=True, reloader=True)
|
unlicense
| -4,043,259,285,766,576,000
| 27.8
| 87
| 0.653735
| false
| 2.972461
| false
| false
| false
|
capitalone/cloud-custodian
|
tools/c7n_azure/c7n_azure/provisioning/deployment_unit.py
|
1
|
1645
|
import logging
from abc import ABCMeta, abstractmethod
from c7n.utils import local_session
from c7n_azure.session import Session
class DeploymentUnit(metaclass=ABCMeta):
log = logging.getLogger('custodian.azure.deployment_unit.DeploymentUnit')
def __init__(self, client):
self.type = ""
self.session = local_session(Session)
self.client = self.session.client(client)
def get(self, params):
result = self._get(params)
if result:
self.log.info('Found %s "%s".' % (self.type, params['name']))
else:
self.log.info('%s "%s" not found.' % (self.type, params['name']))
return result
def check_exists(self):
return self.get() is not None
def provision(self, params):
self.log.info('Creating %s "%s"' % (self.type, params['name']))
result = self._provision(params)
if result:
self.log.info('%s "%s" successfully created' % (self.type, params['name']))
else:
self.log.info('Failed to create %s "%s"' % (self.type, params['name']))
return result
def provision_if_not_exists(self, params):
result = self.get(params)
if result is None:
if 'id' in params.keys():
raise Exception('%s with %s id is not found' % (self.type, params['id']))
result = self.provision(params)
return result
@abstractmethod
def _get(self, params):
raise NotImplementedError()
@abstractmethod
def _provision(self, params):
raise NotImplementedError()
|
apache-2.0
| -3,710,982,216,230,997,000
| 30.254902
| 89
| 0.579331
| false
| 4.09204
| false
| false
| false
|
iYgnohZ/crack-geetest
|
geetest/geetest.py
|
1
|
4035
|
# -*- coding: utf-8 -*-
import time
import uuid
import StringIO
from PIL import Image
from selenium.webdriver.common.action_chains import ActionChains
class BaseGeetestCrack(object):
"""验证码破解基础类"""
def __init__(self, driver):
self.driver = driver
self.driver.maximize_window()
def input_by_id(self, text=u"中国移动", element_id="keyword_qycx"):
"""输入查询关键词
:text: Unicode, 要输入的文本
:element_id: 输入框网页元素id
"""
input_el = self.driver.find_element_by_id(element_id)
input_el.clear()
input_el.send_keys(text)
time.sleep(3.5)
def click_by_id(self, element_id="popup-submit"):
"""点击查询按钮
:element_id: 查询按钮网页元素id
"""
search_el = self.driver.find_element_by_id(element_id)
search_el.click()
time.sleep(3.5)
def calculate_slider_offset(self):
"""计算滑块偏移位置,必须在点击查询按钮之后调用
:returns: Number
"""
img1 = self.crop_captcha_image()
self.drag_and_drop(x_offset=5)
img2 = self.crop_captcha_image()
w1, h1 = img1.size
w2, h2 = img2.size
if w1 != w2 or h1 != h2:
return False
left = 0
flag = False
for i in xrange(45, w1):
for j in xrange(h1):
if not self.is_pixel_equal(img1, img2, i, j):
left = i
flag = True
break
if flag:
break
if left == 45:
left -= 2
return left
def is_pixel_equal(self, img1, img2, x, y):
pix1 = img1.load()[x, y]
pix2 = img2.load()[x, y]
if (abs(pix1[0] - pix2[0] < 60) and abs(pix1[1] - pix2[1] < 60) and abs(pix1[2] - pix2[2] < 60)):
return True
else:
return False
def crop_captcha_image(self, element_id="gt_box"):
"""截取验证码图片
:element_id: 验证码图片网页元素id
:returns: StringIO, 图片内容
"""
captcha_el = self.driver.find_element_by_class_name(element_id)
location = captcha_el.location
size = captcha_el.size
left = int(location['x'])
top = int(location['y'])
left = 1010
top = 535
# right = left + int(size['width'])
# bottom = top + int(size['height'])
right = left + 523
bottom = top + 235
print(left, top, right, bottom)
screenshot = self.driver.get_screenshot_as_png()
screenshot = Image.open(StringIO.StringIO(screenshot))
captcha = screenshot.crop((left, top, right, bottom))
captcha.save("%s.png" % uuid.uuid4().get_hex())
return captcha
def get_browser_name(self):
"""获取当前使用浏览器名称
:returns: TODO
"""
return str(self.driver).split('.')[2]
def drag_and_drop(self, x_offset=0, y_offset=0, element_class="gt_slider_knob"):
"""拖拽滑块
:x_offset: 相对滑块x坐标偏移
:y_offset: 相对滑块y坐标偏移
:element_class: 滑块网页元素CSS类名
"""
dragger = self.driver.find_element_by_class_name(element_class)
action = ActionChains(self.driver)
action.drag_and_drop_by_offset(dragger, x_offset, y_offset).perform()
# 这个延时必须有,在滑动后等待回复原状
time.sleep(8)
def move_to_element(self, element_class="gt_slider_knob"):
"""鼠标移动到网页元素上
:element: 目标网页元素
"""
time.sleep(3)
element = self.driver.find_element_by_class_name(element_class)
action = ActionChains(self.driver)
action.move_to_element(element).perform()
time.sleep(4.5)
def crack(self):
"""执行破解程序
"""
raise NotImplementedError
|
mit
| 1,481,177,789,686,042,400
| 25.435714
| 105
| 0.543367
| false
| 2.816591
| false
| false
| false
|
j5shi/Thruster
|
pylibs/idlelib/IdleHistory.py
|
1
|
4239
|
"Implement Idle Shell history mechanism with History class"
from idlelib.configHandler import idleConf
class History:
''' Implement Idle Shell history mechanism.
store - Store source statement (called from PyShell.resetoutput).
fetch - Fetch stored statement matching prefix already entered.
history_next - Bound to <<history-next>> event (default Alt-N).
history_prev - Bound to <<history-prev>> event (default Alt-P).
'''
def __init__(self, text):
'''Initialize data attributes and bind event methods.
.text - Idle wrapper of tk Text widget, with .bell().
.history - source statements, possibly with multiple lines.
.prefix - source already entered at prompt; filters history list.
.pointer - index into history.
.cyclic - wrap around history list (or not).
'''
self.text = text
self.history = []
self.prefix = None
self.pointer = None
self.cyclic = idleConf.GetOption("main", "History", "cyclic", 1, "bool")
text.bind("<<history-previous>>", self.history_prev)
text.bind("<<history-next>>", self.history_next)
def history_next(self, event):
"Fetch later statement; start with ealiest if cyclic."
self.fetch(reverse=False)
return "break"
def history_prev(self, event):
"Fetch earlier statement; start with most recent."
self.fetch(reverse=True)
return "break"
def fetch(self, reverse):
'''Fetch statememt and replace current line in text widget.
Set prefix and pointer as needed for successive fetches.
Reset them to None, None when returning to the start line.
Sound bell when return to start line or cannot leave a line
because cyclic is False.
'''
nhist = len(self.history)
pointer = self.pointer
prefix = self.prefix
if pointer is not None and prefix is not None:
if self.text.compare("insert", "!=", "end-1c") or \
self.text.get("iomark", "end-1c") != self.history[pointer]:
pointer = prefix = None
self.text.mark_set("insert", "end-1c") # != after cursor move
if pointer is None or prefix is None:
prefix = self.text.get("iomark", "end-1c")
if reverse:
pointer = nhist # will be decremented
else:
if self.cyclic:
pointer = -1 # will be incremented
else: # abort history_next
self.text.bell()
return
nprefix = len(prefix)
while 1:
pointer += -1 if reverse else 1
if pointer < 0 or pointer >= nhist:
self.text.bell()
if not self.cyclic and pointer < 0: # abort history_prev
return
else:
if self.text.get("iomark", "end-1c") != prefix:
self.text.delete("iomark", "end-1c")
self.text.insert("iomark", prefix)
pointer = prefix = None
break
item = self.history[pointer]
if item[:nprefix] == prefix and len(item) > nprefix:
self.text.delete("iomark", "end-1c")
self.text.insert("iomark", item)
break
self.text.see("insert")
self.text.tag_remove("sel", "1.0", "end")
self.pointer = pointer
self.prefix = prefix
def store(self, source):
"Store Shell input statement into history list."
source = source.strip()
if len(source) > 2:
# avoid duplicates
try:
self.history.remove(source)
except ValueError:
pass
self.history.append(source)
self.pointer = None
self.prefix = None
if __name__ == "__main__":
from test import test_support as support
support.use_resources = ['gui']
from unittest import main
main('idlelib.idle_test.test_idlehistory', verbosity=2, exit=False)
|
gpl-2.0
| 6,686,773,657,945,853,000
| 37.990566
| 80
| 0.548714
| false
| 4.424843
| false
| false
| false
|
Youwotma/splash
|
splash/kernel/kernel.py
|
1
|
9476
|
# -*- coding: utf-8 -*-
from __future__ import absolute_import
import os
import six
import sys
import lupa
from ipykernel.kernelapp import IPKernelApp
from ipykernel.eventloops import loop_qt5
from jupyter_client.kernelspec import install_kernel_spec
from twisted.internet import defer
import splash
from splash.lua import get_version, get_main_sandboxed, get_main
from splash.browser_tab import BrowserTab
from splash.lua_runtime import SplashLuaRuntime
from splash.qtrender_lua import (
Splash, MainCoroutineRunner, StoredExceptions, Extras
)
from splash.qtutils import init_qt_app
from splash.render_options import RenderOptions
from splash import defaults
from splash.kernel.kernelbase import Kernel
from splash.utils import BinaryCapsule
from splash.kernel.completer import Completer
from splash.kernel.inspections import Inspector
from splash.kernel.errors import error_repr
import splash.server as server
def install(user=True):
""" Install IPython kernel specification """
name = 'splash-py2' if six.PY2 else 'splash-py3'
folder = os.path.join(os.path.dirname(__file__), 'kernels', name)
install_kernel_spec(folder, kernel_name="splash", user=user, replace=True)
def init_browser(network_manager_factory):
# TODO: support the same command-line options as HTTP server.
# from splash.server import start_logging
# class opts(object):
# logfile = "./kernel.log"
# start_logging(opts)
proxy_factory = None # TODO
data = {}
data['uid'] = id(data)
tab = BrowserTab(
network_manager=network_manager_factory(),
splash_proxy_factory=proxy_factory,
verbosity=2, # TODO
render_options=RenderOptions(data, defaults.MAX_TIMEOUT), # TODO: timeout
visible=True,
)
return tab
class DeferredSplashRunner(object):
def __init__(self, lua, splash, sandboxed, log=None, render_options=None):
self.lua = lua
self.splash = splash
self.sandboxed = sandboxed
if log is None:
self.log = self.splash.tab.logger.log
else:
self.log = log
self.runner = MainCoroutineRunner(
lua=self.lua,
log=self.log,
splash=splash,
sandboxed=self.sandboxed,
)
def run(self, main_coro):
"""
Run main_coro Lua coroutine, passing it a Splash
instance as an argument. Return a Deferred.
"""
d = defer.Deferred()
def return_result(result):
d.callback(result)
def return_error(err):
d.errback(err)
self.runner.start(
main_coro=main_coro,
return_result=return_result,
return_error=return_error,
)
return d
class SplashKernel(Kernel):
implementation = 'Splash'
implementation_version = splash.__version__
language = 'Lua'
language_version = get_version()
language_info = {
'name': 'Splash',
'mimetype': 'application/x-lua',
'display_name': 'Splash',
'language': 'lua',
'codemirror_mode': {
"name": "text/x-lua",
},
'file_extension': '.lua',
'pygments_lexer': 'lua',
'version': get_version(),
}
banner = "Splash kernel - write browser automation scripts interactively"
help_links = [
{
'text': "Splash Tutorial",
'url': 'http://splash.readthedocs.org/en/latest/scripting-tutorial.html'
},
{
'text': "Splash Reference",
'url': 'http://splash.readthedocs.org/en/latest/scripting-ref.html'
},
{
'text': "Programming in Lua",
'url': 'http://www.lua.org/pil/contents.html'
},
{
'text': "Lua 5.2 Manual",
'url': 'http://www.lua.org/manual/5.2/'
},
]
sandboxed = False
def __init__(self, **kwargs):
super(SplashKernel, self).__init__(**kwargs)
self.tab = init_browser(SplashKernel.network_manager_factory)
self.lua = SplashLuaRuntime(self.sandboxed, "", ())
self.exceptions = StoredExceptions()
self.splash = Splash(
lua=self.lua,
exceptions=self.exceptions,
tab=self.tab
)
self.lua.add_to_globals("splash", self.splash.get_wrapped())
self.extras = Extras(self.lua, self.exceptions)
self.extras.inject_to_globals()
self.runner = DeferredSplashRunner(self.lua, self.splash, self.sandboxed) #, self.log_msg)
self.completer = Completer(self.lua)
self.inspector = Inspector(self.lua)
#
# try:
# sys.stdout.write = self._print
# sys.stderr.write = self._print
# except:
# pass # Can't change stdout
def send_execute_reply(self, stream, ident, parent, md, reply_content):
def done(result):
reply, result, ct = result
if result:
data = {
'text/plain': result if isinstance(result, six.text_type) else str(result),
}
if isinstance(result, BinaryCapsule):
if result.content_type in {'image/png', 'image/jpeg'}:
data[result.content_type] = result.as_b64()
self._publish_execute_result(parent, data, {}, self.execution_count)
super(SplashKernel, self).send_execute_reply(stream, ident, parent, md, reply)
assert isinstance(reply_content, defer.Deferred)
reply_content.addCallback(done)
def do_execute(self, code, silent, store_history=True, user_expressions=None,
allow_stdin=False):
def success(res):
result, content_type, headers, status_code = res
reply = {
'status': 'ok',
'execution_count': self.execution_count,
'payload': [],
'user_expressions': {},
}
return reply, result, content_type or 'text/plain'
def error(failure):
text = "<unknown error>"
try:
failure.raiseException()
except Exception as e:
text = error_repr(e)
reply = {
'status': 'error',
'execution_count': self.execution_count,
'ename': '',
'evalue': text,
'traceback': []
}
return reply, text, 'text/plain'
try:
try:
# XXX: this ugly formatting is important for exception
# line numbers to be displayed properly!
lua_source = 'local repr = require("repr"); function main(splash) return repr(%s) end' % code
main_coro = self._get_main(lua_source)
except lupa.LuaSyntaxError:
try:
lines = code.splitlines(False)
lua_source = '''local repr = require("repr"); function main(splash) %s
return repr(%s)
end
''' % ("\n".join(lines[:-1]), lines[-1])
main_coro = self._get_main(lua_source)
except lupa.LuaSyntaxError:
lua_source = "function main(splash) %s end" % code
main_coro = self._get_main(lua_source)
except (lupa.LuaSyntaxError, lupa.LuaError) as e:
d = defer.Deferred()
d.addCallbacks(success, error)
d.errback(e)
return d
except Exception:
d = defer.Deferred()
d.addCallbacks(success, error)
d.errback()
return d
d = self.runner.run(main_coro)
d.addCallbacks(success, error)
return d
def do_complete(self, code, cursor_pos):
return self.completer.complete(code, cursor_pos)
def do_inspect(self, code, cursor_pos, detail_level=0):
return self.inspector.help(code, cursor_pos, detail_level)
def _publish_execute_result(self, parent, data, metadata, execution_count):
msg = {
u'data': data,
u'metadata': metadata,
u'execution_count': execution_count
}
self.session.send(self.iopub_socket, u'execute_result', msg,
parent=parent, ident=self._topic('execute_result')
)
def log_msg(self, text, min_level=2):
self._print(text + "\n")
def _print(self, message):
stream_content = {'name': 'stdout', 'text': message, 'metadata': dict()}
self.log.debug('Write: %s' % message)
self.send_response(self.iopub_socket, 'stream', stream_content)
def _get_main(self, lua_source):
if self.sandboxed:
main, env = get_main_sandboxed(self.lua, lua_source)
else:
main, env = get_main(self.lua, lua_source)
return self.lua.create_coroutine(main)
def server_factory(network_manager_factory, verbosity, **kwargs):
init_qt_app(verbose=verbosity >= 5)
SplashKernel.network_manager_factory = network_manager_factory
kernel = IPKernelApp.instance(kernel_class=SplashKernel)
kernel.initialize()
kernel.kernel.eventloop = loop_qt5
kernel.start()
def start():
splash_args = os.environ.get('SPLASH_ARGS', '').split()
server.main(jupyter=True, argv=splash_args, server_factory=server_factory)
|
bsd-3-clause
| 2,472,990,847,262,979,600
| 32.249123
| 109
| 0.577353
| false
| 3.801043
| false
| false
| false
|
smARTLab-liv/smartlabatwork-release
|
slaw_smach/src/slaw_smach/slaw_smach.py
|
1
|
11996
|
#!/usr/bin/env python
import rospy
from ArmStates import *
from MoveStates import *
from ObjectDetectState import *
from DecisionStates import *
from std_srvs.srv import Empty, EmptyResponse
from std_msgs.msg import Bool
## TODO after Eindhoven: Add failsafe if hole not detected
## add states if object too far or too close to gripper
class Smach():
def __init__(self):
rospy.init_node('slaw_smach')
self.sm = smach.StateMachine(outcomes=['end'])
with self.sm:
### MOVE STATE WITH RECOVER
smach.StateMachine.add('MoveToNext', MoveStateUserData(), transitions = {'reached':'DecideAfterMove', 'not_reached': 'RecoverMove', 'failed': 'DeleteCurGoal'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('RecoverMove', RecoverState(), transitions = {'done':'MoveToNext'}, remapping = {'pose_in':'pose', 'pose_out': 'pose'})
### END MOVE STATE WITH RECOVER
##Decision state after Move:
smach.StateMachine.add('DecideAfterMove', DecideAfterMoveState(),transitions = {'BNT': 'ScanMatcher_BNT', 'Pickup':'ScanMatcher_Pickup', 'Place':'ScanMatcher_Place', 'End':'end'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
######BNT SPECIFIC
smach.StateMachine.add('ScanMatcher_BNT', ScanMatcher(), transitions = {'reached':'SleepState', 'not_reached':'ScanMatcher_BNT', 'failed':'SleepState'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('SleepState', SleepState(), transitions = {'done':'DeleteCurGoal'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
########END BNT
##### DELETE CURRENT GOAL OR GET NEXT GOAL
smach.StateMachine.add('DeleteCurGoal', DeleteCurrentGoalState(), transitions = {'done':'MoveToNext'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('GetNextGoal', GetNextGoalState(), transitions = {'done':'MoveToNext'}, remapping = {'pose_in':'pose','object_in':'object', 'pose_out':'pose'})
##### END DELETE CURRENT GOAL OR GET NEXT GOAL
### PICKUP
smach.StateMachine.add('ScanMatcher_Pickup', ScanMatcher(), transitions = {'reached':'DecideBeforePreGrip', 'not_reached':'ScanMatcher_Pickup', 'failed':'MoveToNext'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
#smach.StateMachine.add('ScanMatcher_Pickup', ScanMatcher(), transitions = {'reached':'ScanMatcher_Align', 'not_reached':'ScanMatcher_Pickup', 'failed':'MoveToNext'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
#smach.StateMachine.add('ScanMatcher_Align', AlignState(), transitions = {'done':'DecideBeforePreGrip'})
##
#Either CBT Pickup or normal Pickup
smach.StateMachine.add('DecideBeforePreGrip', DecideBeforePreGripState(),transitions = {'CBT': 'PreGrip_CBT', 'Pickup':'PreGrip'}, remapping = {'pose_in':'pose', 'pose_out':'pose', 'dist_out':'dist'})
######CBT STUFF
smach.StateMachine.add('PreGrip_CBT', PreGripCBT(), transitions = {'success':'ScanForObjectCBT', 'failed':'TuckArmPreGripCBT'},remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('TuckArmPreGripCBT', TuckArm(), transitions = {'success':'PreGrip_CBT', 'not_reached':'TuckArmPreGripCBT','failed':'end'})
smach.StateMachine.add('ScanForObjectCBT', ScanForObjectCBT(), transitions = {'success':'GripCBT'})
smach.StateMachine.add('GripCBT', GripCBT(), transitions = {'end':'DeleteCurGoal'})
#### END CBT Stuff
### NORMAL PICKUP
smach.StateMachine.add('PreGrip', PreGrip(), transitions = {'success':'Scan', 'failed':'TuckArmPreGrip'},remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('TuckArmPreGrip', TuckArm(), transitions = {'success':'PreGrip', 'not_reached':'TuckArmPreGrip','failed':'end'})
#scan
smach.StateMachine.add("Scan", ScanForObjectsState(), transitions = {'success': 'Grip', 'failed':'TuckArmMoveNext','nothing_found': 'TuckArmDelete'}, remapping = {'pose_in':'pose', 'pose_out':'pose', 'object_out':'object', 'point_out':'point', 'dist_in':'dist','dist_out':'dist'})
#if misdetection try again
smach.StateMachine.add('TuckArmMoveNext', TuckArm(), transitions = {'success':'MoveToNext', 'not_reached':'TuckArmMoveNext','failed':'end'})
#if nothing found try next Goal
smach.StateMachine.add('TuckArmDelete', TuckArm(), transitions = {'success':'DeleteCurGoal', 'not_reached':'TuckArmDelete','failed':'end'})
#Grip Object
smach.StateMachine.add("Grip", Grip(), transitions = {'success':'DecideRV20', 'too_far':'ScanMatcher_Pickup', 'failed':'TuckArmFailGrip', 'failed_after_grip':'TuckArmGrip'}, remapping = {'pose_in':'pose', 'object_in':'object', 'point_in':'point','pose_out':'pose', 'object_out':'object', 'point_out':'point'})
#Decide RV20:
smach.StateMachine.add('DecideRV20', DecideRV20State(),transitions = {'RV20': 'TuckForDriveAfterGrip', 'Normal':'TuckForDriveAfterGrip'}, remapping = {'object_in':'object', 'object_out':'object'})
#smach.StateMachine.add('DecideRV20', DecideRV20State(),transitions = {'RV20': 'RV20CheckArm', 'Normal':'TuckForDriveAfterGrip'}, remapping = {'object_in':'object', 'object_out':'object', 'pose_out':'pose'})
####CHECK if RV20 which one
smach.StateMachine.add('RV20CheckArm', RV20CheckState(), transitions = {'success':'RV20CheckVision','failed':'TuckArmPreCheckArm'}, remapping = {'pose_in':'pose'})
smach.StateMachine.add('TuckArmPreCheckArm', TuckArm(), transitions = {'success':'RV20CheckArm', 'not_reached':'TuckArmPreCheckArm','failed':'end'})
#smach.StateMachine.add('RV20CheckVision', RV20CheckVision(), transitions = {'success':'RV20RotateTake','failed':'RV20RotateReplace'}, remapping = {'pose_in':'pose', 'object_in':'object', 'pose_out':'pose'})
smach.StateMachine.add('RV20CheckVision', RV20CheckVision(), transitions = {'success':'RV20RotateTake','failed':'RV20Trash'}, remapping = {'pose_in':'pose', 'object_in':'object', 'pose_out':'pose'})
smach.StateMachine.add('RV20Trash', RV20Trash(), transitions = {'done':'PreGrip'})
#smach.StateMachine.add('RV20RotateReplace', RV20ReplaceObjectRotate(), transitions = {'success':'RV20Replace','failed':'RV20Replace'}, remapping = {'pose_in':'pose'})
smach.StateMachine.add('RV20RotateTake', RV20ReplaceObjectRotate(), transitions = {'success':'TuckForDriveAfterGrip','failed':'TuckForDriveAfterGrip'}, remapping = {'pose_in':'pose'})
#smach.StateMachine.add('RV20Replace', FinePlace(), transitions = {'success':'RV20ReplaceUp', 'failed':'TuckArmFailPlace_RV20', 'too_far':'RV20Replace','failed_after_place':'TuckArmFailPlace_RV20'}, remapping = {'object_in':'object','pose_in':'pose', 'pose_out':'pose', 'point_in':'point'})
#smach.StateMachine.add('TuckArmFailPlace_RV20', TuckArm(), transitions = {'success':'RV20Replace', 'not_reached':'TuckArmFailPlace_RV20','failed':'end'})
#smach.StateMachine.add('RV20ReplaceUp', RV20ReplaceUp(), transitions = {'done':'MoveBack10'})
#MoveBack 10 to skip object and resume scanning
#smach.StateMachine.add('MoveBack10', MoveBack(0.10), transitions = {'done':'Remove10'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
#smach.StateMachine.add('Remove10', RemoveDist(0.10), transitions = {'done':'PreGrip'}, remapping = {'dist_in':'dist', 'dist_out':'dist'})
#Tuck and Move away
##Tuck For Drive
smach.StateMachine.add('TuckForDriveAfterGrip', TuckForDrive(), transitions={'done':'MoveAwayFromPlatform'}, remapping = {'pose_in':'pose'} )
smach.StateMachine.add('TuckArmGrip', TuckArm(), transitions = {'success':'MoveAwayFromPlatform', 'not_reached':'TuckArmGrip','failed':'end'})
smach.StateMachine.add('TuckArmFailGrip', TuckArm(), transitions = {'success':'MoveToNext', 'not_reached':'TuckArmFailGrip','failed':'end'})
smach.StateMachine.add('MoveAwayFromPlatform', RecoverState(), transitions = {'done':'MoveToPlace'})
### Move to Place location
smach.StateMachine.add('MoveToPlace', MoveStateUserData(), transitions = {'reached': 'ScanMatcher_Place', 'not_reached': 'MoveAwayFromPlatform', 'failed': 'MoveAwayFromPlatform'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('ScanMatcher_Place', ScanMatcher(), transitions = {'reached':'DecideBeforePlace', 'not_reached':'ScanMatcher_Place', 'failed':'DecideBeforePlace'}, remapping = {'pose_in':'pose', 'suffix_in':'suffix', 'pose_out':'pose'})
#### Decide either Normal place or PPT place
smach.StateMachine.add('DecideBeforePlace', DecideBeforePlaceState(),transitions = {'PPT': 'PreScanHole', 'Normal':'MoveBack'}, remapping = {'object_in':'object', 'object_out':'object'})
####PPT
smach.StateMachine.add('PreScanHole', PreGrip(), transitions = {'success':'ScanHole', 'failed':'TuckArmPreScan'},remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('TuckArmPreScan', TuckArm(), transitions = {'success':'PreScanHole', 'not_reached':'TuckArmPreScan','failed':'end'})
smach.StateMachine.add("ScanHole", ScanForHoles(), transitions = {'success': 'FinePlace', 'failed':'ScanMatcher_Place','nothing_found': 'ScanMatcher_Place'}, remapping = {'pose_in':'pose', 'pose_out':'pose', 'object_in':'object', 'object_out':'object', 'point_out':'point'})
smach.StateMachine.add('FinePlace', FinePlace(), transitions = {'success':'TuckForDriveAfterPlace', 'failed':'TuckArmFailPlace_PPT', 'too_far':'ScanMatcher_Place','failed_after_place':'TuckArmFailPlace_PPT'}, remapping = {'object_in':'object','pose_in':'pose', 'pose_out':'pose', 'point_in':'point'})
smach.StateMachine.add('TuckArmFailPlace_PPT', TuckArm(), transitions = {'success':'FinePlace', 'not_reached':'TuckArmFailPlace_PPT','failed':'end'})
### END PPT
##NORMAL PLACE
smach.StateMachine.add('MoveBack', MoveBack(0.25), transitions = {'done':'Place'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
smach.StateMachine.add('Place', Place(), transitions = {'success':'TuckForDriveAfterPlace', 'failed':'TuckArmFailPlace'}, remapping = {'pose_in':'pose', 'pose_out':'pose'})
##Tuck For Drive
smach.StateMachine.add('TuckForDriveAfterPlace', TuckForDrive(), transitions={'done':'MoveAwayFromPlatformAfterPlace'}, remapping = {'pose_in':'pose'} )
smach.StateMachine.add('TuckArmFailPlace', TuckArm(), transitions = {'success':'Place', 'not_reached':'TuckArmFailPlace','failed':'end'})
smach.StateMachine.add('MoveAwayFromPlatformAfterPlace', RecoverState(), transitions = {'done':'GetNextGoal'})
# Create and start the introspection server
self.sis = smach_ros.IntrospectionServer('server_name', self.sm, '/SLAW_SMACH')
self.sis.start()
self.serv = rospy.Service("/start_SMACH", Empty, self.go)
def go(self, req):
#sm.userdata.pose = "D2"
print "Starting SMACH"
locations = rospy.get_param('locations')
self.sm.userdata.pose = locations[0]
#self.sm.userdata.suffix = "_grip"
self.sm.execute()
return EmptyResponse()
def stop(self):
self.sis.stop()
if __name__ == '__main__':
smach = Smach()
rospy.spin()
smach.stop()
|
mit
| -3,893,603,533,906,580,000
| 68.744186
| 321
| 0.635128
| false
| 3.580896
| false
| false
| false
|
mtrdesign/pylogwatch
|
pylogwatch/logwlib.py
|
1
|
5917
|
# Python 2.5 compatibility
from __future__ import with_statement
# Python version
import sys
if sys.version_info < (2, 5):
raise "Required python 2.5 or greater"
import os, sqlite3, itertools, time
from datetime import datetime
PROJECT_DIR = os.path.abspath(os.path.dirname(__file__))
proj_path = lambda x: os.path.abspath(os.path.join(PROJECT_DIR,x))
# Check if we are bundled together with raven, and add our dir to the pythonpath if we are
if os.path.exists(proj_path( 'raven')):
sys.path.append(PROJECT_DIR)
from raven import Client
def item_import(name):
d = name.rfind(".")
classname = name[d+1:]
m = __import__(name[:d], globals(), locals(), [classname])
return getattr(m, classname)
class PyLog (object):
def __init__ (self, filenames, dbname = 'logw.db', filetable = 'file_cursor', eventtable = 'events'):
self._filetable = filetable
self._eventtable = eventtable
self.conn = self.init_db(dbname)
self.curs = self.conn.cursor()
self.fnames = filenames
def init_db (self, dbname):
"""Set up the DB"""
conn = sqlite3.connect (dbname)
curs = conn.cursor()
sql = 'create table if not exists file_cursor (filename TEXT PRIMARY KEY, inode INTEGER, lastbyte INTEGER, updated INTEGER)'
curs.execute (sql)
sql = 'create table if not exists events (event TEXT PRIMARY KEY, args TEXT, updated INTEGER)'
curs.execute (sql)
conn.commit()
return conn
def readlines (self, f, lastpos = 0):
"""Read full lines from the file object f starting from lastpos"""
self.save_fileinfo (f.name, os.stat(f.name)[1], lastpos)
f.seek(lastpos)
result = []
for line in f:
# handle lines that are not yet finished (no \n)
curpos = f.tell()
if not line.endswith('\n'):
f.seek(curpos)
raise StopIteration
yield line
def get_fileinfo (self, fname):
self.curs.execute ('SELECT filename, inode, lastbyte from file_cursor where filename=?', [fname,])
result = self.curs.fetchone()
if result and len(result)==3:
f, inode, lastbyte = result
return inode,lastbyte
else:
return None,0
def save_fileinfo (self, fname, inode, lastbyte):
self.curs.execute ("REPLACE into file_cursor (filename, inode, lastbyte, updated) \
values (?,?,?,datetime())", [fname,inode, lastbyte ])
self.conn.commit()
return
def update_bytes (self,fname, lastbyte):
"""
Only updates the lastbyte property of a file, without touching the inode.
Meant for calling after each line is processed
"""
def save_fileinfo (self, fname, inode, lastbyte):
self.curs.execute ("UPDATE into file_cursor set lastbyte=? where filename=?",\
[fname,inode, lastbyte ])
self.conn.commit()
return
def process_lines (self, fname, lines):
"""Dummy line processor - should be overridden"""
raise NotImplementedError
def open_rotated_version(self, fname):
sufxs = ['.1','.1.gz','.0']
for sufx in sufxs:
newname = fname + sufx
if not os.path.exists (newname):
continue
try:
f = open(newname)
return f
except:
continue
def run (self):
for fn in self.fnames:
if not os.path.exists (fn):
continue
newlines = []
rotated = None
lastinode, lastbyte = self.get_fileinfo (fn)
if lastbyte and not lastinode == os.stat(fn)[1]:
# handle rotated files
rotated = self.open_rotated_version(fn)
if rotated:
newlines = self.readlines (rotated, lastbyte)
lastbyte = 0
self.process_lines (fn, rotated, newlines)
try:
f = open(fn)
except:
continue
self.process_lines (fn, f, self.readlines (f, lastbyte))
lastbyte = f.tell()
lastinode = os.stat(fn)[1]
f.close()
self.save_fileinfo (fn, lastinode, lastbyte)
if rotated:
rotated.close()
class PyLogConf (PyLog):
def __init__ (self, conf):
"""
Initialize object based on the provided configuration
"""
self.conf = conf
self.client = Client (conf.RAVEN['dsn'])
self.formatters = {}
for k,v in self.conf.FILE_FORMATTERS.iteritems():
if isinstance(v,str):
raise ValueError ('Please use a list or a tuple for the file formatters values')
self.formatters[k] = [item_import(i)() for i in v]
dbname = os.path.join(os.path.dirname(conf.__file__),'pylogwatch.db')
return super(PyLogConf, self).__init__ (self.conf.FILE_FORMATTERS.keys(), dbname = dbname)
def process_lines (self, fname, fileobject, lines):
"""Main workhorse. Called with the filename that is being logged and an iterable of lines"""
for line in lines:
paramdict = {}
data = {'event_type':'Message', 'message': line.replace('%','%%'), 'data' :{'logger':fname}}
for fobj in self.formatters[fname]:
fobj.format_line(line, data, paramdict)
if not data.pop('_do_not_send', False): # Skip lines that have the '_do_not_send' key
if paramdict:
data['params'] = tuple([paramdict[i] for i in sorted(paramdict.keys())])
if self.conf.DEBUG:
print data
self.client.capture(**data)
self.update_bytes(fname, fileobject.tell())
|
gpl-3.0
| -7,848,765,276,239,736,000
| 36.449367
| 132
| 0.564982
| false
| 4.066667
| false
| false
| false
|
googlemaps/google-maps-services-python
|
googlemaps/convert.py
|
1
|
10197
|
#
# Copyright 2014 Google Inc. 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.
#
"""Converts Python types to string representations suitable for Maps API server.
For example:
sydney = {
"lat" : -33.8674869,
"lng" : 151.2069902
}
convert.latlng(sydney)
# '-33.8674869,151.2069902'
"""
def format_float(arg):
"""Formats a float value to be as short as possible.
Truncates float to 8 decimal places and trims extraneous
trailing zeros and period to give API args the best
possible chance of fitting within 2000 char URL length
restrictions.
For example:
format_float(40) -> "40"
format_float(40.0) -> "40"
format_float(40.1) -> "40.1"
format_float(40.001) -> "40.001"
format_float(40.0010) -> "40.001"
format_float(40.000000001) -> "40"
format_float(40.000000009) -> "40.00000001"
:param arg: The lat or lng float.
:type arg: float
:rtype: string
"""
return ("%.8f" % float(arg)).rstrip("0").rstrip(".")
def latlng(arg):
"""Converts a lat/lon pair to a comma-separated string.
For example:
sydney = {
"lat" : -33.8674869,
"lng" : 151.2069902
}
convert.latlng(sydney)
# '-33.8674869,151.2069902'
For convenience, also accepts lat/lon pair as a string, in
which case it's returned unchanged.
:param arg: The lat/lon pair.
:type arg: string or dict or list or tuple
"""
if is_string(arg):
return arg
normalized = normalize_lat_lng(arg)
return "%s,%s" % (format_float(normalized[0]), format_float(normalized[1]))
def normalize_lat_lng(arg):
"""Take the various lat/lng representations and return a tuple.
Accepts various representations:
1) dict with two entries - "lat" and "lng"
2) list or tuple - e.g. (-33, 151) or [-33, 151]
:param arg: The lat/lng pair.
:type arg: dict or list or tuple
:rtype: tuple (lat, lng)
"""
if isinstance(arg, dict):
if "lat" in arg and "lng" in arg:
return arg["lat"], arg["lng"]
if "latitude" in arg and "longitude" in arg:
return arg["latitude"], arg["longitude"]
# List or tuple.
if _is_list(arg):
return arg[0], arg[1]
raise TypeError(
"Expected a lat/lng dict or tuple, "
"but got %s" % type(arg).__name__)
def location_list(arg):
"""Joins a list of locations into a pipe separated string, handling
the various formats supported for lat/lng values.
For example:
p = [{"lat" : -33.867486, "lng" : 151.206990}, "Sydney"]
convert.waypoint(p)
# '-33.867486,151.206990|Sydney'
:param arg: The lat/lng list.
:type arg: list
:rtype: string
"""
if isinstance(arg, tuple):
# Handle the single-tuple lat/lng case.
return latlng(arg)
else:
return "|".join([latlng(location) for location in as_list(arg)])
def join_list(sep, arg):
"""If arg is list-like, then joins it with sep.
:param sep: Separator string.
:type sep: string
:param arg: Value to coerce into a list.
:type arg: string or list of strings
:rtype: string
"""
return sep.join(as_list(arg))
def as_list(arg):
"""Coerces arg into a list. If arg is already list-like, returns arg.
Otherwise, returns a one-element list containing arg.
:rtype: list
"""
if _is_list(arg):
return arg
return [arg]
def _is_list(arg):
"""Checks if arg is list-like. This excludes strings and dicts."""
if isinstance(arg, dict):
return False
if isinstance(arg, str): # Python 3-only, as str has __iter__
return False
return _has_method(arg, "__getitem__") if not _has_method(arg, "strip") else _has_method(arg, "__iter__")
def is_string(val):
"""Determines whether the passed value is a string, safe for 2/3."""
try:
basestring
except NameError:
return isinstance(val, str)
return isinstance(val, basestring)
def time(arg):
"""Converts the value into a unix time (seconds since unix epoch).
For example:
convert.time(datetime.now())
# '1409810596'
:param arg: The time.
:type arg: datetime.datetime or int
"""
# handle datetime instances.
if _has_method(arg, "timestamp"):
arg = arg.timestamp()
if isinstance(arg, float):
arg = int(arg)
return str(arg)
def _has_method(arg, method):
"""Returns true if the given object has a method with the given name.
:param arg: the object
:param method: the method name
:type method: string
:rtype: bool
"""
return hasattr(arg, method) and callable(getattr(arg, method))
def components(arg):
"""Converts a dict of components to the format expected by the Google Maps
server.
For example:
c = {"country": "US", "postal_code": "94043"}
convert.components(c)
# 'country:US|postal_code:94043'
:param arg: The component filter.
:type arg: dict
:rtype: basestring
"""
# Components may have multiple values per type, here we
# expand them into individual key/value items, eg:
# {"country": ["US", "AU"], "foo": 1} -> "country:AU", "country:US", "foo:1"
def expand(arg):
for k, v in arg.items():
for item in as_list(v):
yield "%s:%s" % (k, item)
if isinstance(arg, dict):
return "|".join(sorted(expand(arg)))
raise TypeError(
"Expected a dict for components, "
"but got %s" % type(arg).__name__)
def bounds(arg):
"""Converts a lat/lon bounds to a comma- and pipe-separated string.
Accepts two representations:
1) string: pipe-separated pair of comma-separated lat/lon pairs.
2) dict with two entries - "southwest" and "northeast". See convert.latlng
for information on how these can be represented.
For example:
sydney_bounds = {
"northeast" : {
"lat" : -33.4245981,
"lng" : 151.3426361
},
"southwest" : {
"lat" : -34.1692489,
"lng" : 150.502229
}
}
convert.bounds(sydney_bounds)
# '-34.169249,150.502229|-33.424598,151.342636'
:param arg: The bounds.
:type arg: dict
"""
if is_string(arg) and arg.count("|") == 1 and arg.count(",") == 2:
return arg
elif isinstance(arg, dict):
if "southwest" in arg and "northeast" in arg:
return "%s|%s" % (latlng(arg["southwest"]),
latlng(arg["northeast"]))
raise TypeError(
"Expected a bounds (southwest/northeast) dict, "
"but got %s" % type(arg).__name__)
def size(arg):
if isinstance(arg, int):
return "%sx%s" % (arg, arg)
elif _is_list(arg):
return "%sx%s" % (arg[0], arg[1])
raise TypeError(
"Expected a size int or list, "
"but got %s" % type(arg).__name__)
def decode_polyline(polyline):
"""Decodes a Polyline string into a list of lat/lng dicts.
See the developer docs for a detailed description of this encoding:
https://developers.google.com/maps/documentation/utilities/polylinealgorithm
:param polyline: An encoded polyline
:type polyline: string
:rtype: list of dicts with lat/lng keys
"""
points = []
index = lat = lng = 0
while index < len(polyline):
result = 1
shift = 0
while True:
b = ord(polyline[index]) - 63 - 1
index += 1
result += b << shift
shift += 5
if b < 0x1f:
break
lat += (~result >> 1) if (result & 1) != 0 else (result >> 1)
result = 1
shift = 0
while True:
b = ord(polyline[index]) - 63 - 1
index += 1
result += b << shift
shift += 5
if b < 0x1f:
break
lng += ~(result >> 1) if (result & 1) != 0 else (result >> 1)
points.append({"lat": lat * 1e-5, "lng": lng * 1e-5})
return points
def encode_polyline(points):
"""Encodes a list of points into a polyline string.
See the developer docs for a detailed description of this encoding:
https://developers.google.com/maps/documentation/utilities/polylinealgorithm
:param points: a list of lat/lng pairs
:type points: list of dicts or tuples
:rtype: string
"""
last_lat = last_lng = 0
result = ""
for point in points:
ll = normalize_lat_lng(point)
lat = int(round(ll[0] * 1e5))
lng = int(round(ll[1] * 1e5))
d_lat = lat - last_lat
d_lng = lng - last_lng
for v in [d_lat, d_lng]:
v = ~(v << 1) if v < 0 else v << 1
while v >= 0x20:
result += (chr((0x20 | (v & 0x1f)) + 63))
v >>= 5
result += (chr(v + 63))
last_lat = lat
last_lng = lng
return result
def shortest_path(locations):
"""Returns the shortest representation of the given locations.
The Elevations API limits requests to 2000 characters, and accepts
multiple locations either as pipe-delimited lat/lng values, or
an encoded polyline, so we determine which is shortest and use it.
:param locations: The lat/lng list.
:type locations: list
:rtype: string
"""
if isinstance(locations, tuple):
# Handle the single-tuple lat/lng case.
locations = [locations]
encoded = "enc:%s" % encode_polyline(locations)
unencoded = location_list(locations)
if len(encoded) < len(unencoded):
return encoded
else:
return unencoded
|
apache-2.0
| 7,628,449,255,522,140,000
| 25.417098
| 109
| 0.5939
| false
| 3.619808
| false
| false
| false
|
mo-ki/pypgpwords
|
pypgpwords.py
|
1
|
13257
|
#!/usr/bin/python3
"""Define a PGPWords object inherited from bytearray.
Adding initialization via hex-, or pgp-word-string,
adding .hex() method and
overriding __str__
Mainline code:
Convert pgp words to hex strings and vice versa.
Example:
$ pypgpwords.py DEAD 1337
tactics perceptive Aztec consensus
or
$ pypgpwords.py absurd bodyguard baboon unicorn
0116 14EC
moki@posteo.de
"""
from __future__ import print_function
import sys
SEPARATOR = " "
EVEN = ("aardvark",
"absurd",
"accrue",
"acme",
"adrift",
"adult",
"afflict",
"ahead",
"aimless",
"Algol",
"allow",
"alone",
"ammo",
"ancient",
"apple",
"artist",
"assume",
"Athens",
"atlas",
"Aztec",
"baboon",
"backfield",
"backward",
"banjo",
"beaming",
"bedlamp",
"beehive",
"beeswax",
"befriend",
"Belfast",
"berserk",
"billiard",
"bison",
"blackjack",
"blockade",
"blowtorch",
"bluebird",
"bombast",
"bookshelf",
"brackish",
"breadline",
"breakup",
"brickyard",
"briefcase",
"Burbank",
"button",
"buzzard",
"cement",
"chairlift",
"chatter",
"checkup",
"chisel",
"choking",
"chopper",
"Christmas",
"clamshell",
"classic",
"classroom",
"cleanup",
"clockwork",
"cobra",
"commence",
"concert",
"cowbell",
"crackdown",
"cranky",
"crowfoot",
"crucial",
"crumpled",
"crusade",
"cubic",
"dashboard",
"deadbolt",
"deckhand",
"dogsled",
"dragnet",
"drainage",
"dreadful",
"drifter",
"dropper",
"drumbeat",
"drunken",
"Dupont",
"dwelling",
"eating",
"edict",
"egghead",
"eightball",
"endorse",
"endow",
"enlist",
"erase",
"escape",
"exceed",
"eyeglass",
"eyetooth",
"facial",
"fallout",
"flagpole",
"flatfoot",
"flytrap",
"fracture",
"framework",
"freedom",
"frighten",
"gazelle",
"Geiger",
"glitter",
"glucose",
"goggles",
"goldfish",
"gremlin",
"guidance",
"hamlet",
"highchair",
"hockey",
"indoors",
"indulge",
"inverse",
"involve",
"island",
"jawbone",
"keyboard",
"kickoff",
"kiwi",
"klaxon",
"locale",
"lockup",
"merit",
"minnow",
"miser",
"Mohawk",
"mural",
"music",
"necklace",
"Neptune",
"newborn",
"nightbird",
"Oakland",
"obtuse",
"offload",
"optic",
"orca",
"payday",
"peachy",
"pheasant",
"physique",
"playhouse",
"Pluto",
"preclude",
"prefer",
"preshrunk",
"printer",
"prowler",
"pupil",
"puppy",
"python",
"quadrant",
"quiver",
"quota",
"ragtime",
"ratchet",
"rebirth",
"reform",
"regain",
"reindeer",
"rematch",
"repay",
"retouch",
"revenge",
"reward",
"rhythm",
"ribcage",
"ringbolt",
"robust",
"rocker",
"ruffled",
"sailboat",
"sawdust",
"scallion",
"scenic",
"scorecard",
"Scotland",
"seabird",
"select",
"sentence",
"shadow",
"shamrock",
"showgirl",
"skullcap",
"skydive",
"slingshot",
"slowdown",
"snapline",
"snapshot",
"snowcap",
"snowslide",
"solo",
"southward",
"soybean",
"spaniel",
"spearhead",
"spellbind",
"spheroid",
"spigot",
"spindle",
"spyglass",
"stagehand",
"stagnate",
"stairway",
"standard",
"stapler",
"steamship",
"sterling",
"stockman",
"stopwatch",
"stormy",
"sugar",
"surmount",
"suspense",
"sweatband",
"swelter",
"tactics",
"talon",
"tapeworm",
"tempest",
"tiger",
"tissue",
"tonic",
"topmost",
"tracker",
"transit",
"trauma",
"treadmill",
"Trojan",
"trouble",
"tumor",
"tunnel",
"tycoon",
"uncut",
"unearth",
"unwind",
"uproot",
"upset",
"upshot",
"vapor",
"village",
"virus",
"Vulcan",
"waffle",
"wallet",
"watchword",
"wayside",
"willow",
"woodlark",
"Zulu")
ODD = ("adroitness",
"adviser",
"aftermath",
"aggregate",
"alkali",
"almighty",
"amulet",
"amusement",
"antenna",
"applicant",
"Apollo",
"armistice",
"article",
"asteroid",
"Atlantic",
"atmosphere",
"autopsy",
"Babylon",
"backwater",
"barbecue",
"belowground",
"bifocals",
"bodyguard",
"bookseller",
"borderline",
"bottomless",
"Bradbury",
"bravado",
"Brazilian",
"breakaway",
"Burlington",
"businessman",
"butterfat",
"Camelot",
"candidate",
"cannonball",
"Capricorn",
"caravan",
"caretaker",
"celebrate",
"cellulose",
"certify",
"chambermaid",
"Cherokee",
"Chicago",
"clergyman",
"coherence",
"combustion",
"commando",
"company",
"component",
"concurrent",
"confidence",
"conformist",
"congregate",
"consensus",
"consulting",
"corporate",
"corrosion",
"councilman",
"crossover",
"crucifix",
"cumbersome",
"customer",
"Dakota",
"decadence",
"December",
"decimal",
"designing",
"detector",
"detergent",
"determine",
"dictator",
"dinosaur",
"direction",
"disable",
"disbelief",
"disruptive",
"distortion",
"document",
"embezzle",
"enchanting",
"enrollment",
"enterprise",
"equation",
"equipment",
"escapade",
"Eskimo",
"everyday",
"examine",
"existence",
"exodus",
"fascinate",
"filament",
"finicky",
"forever",
"fortitude",
"frequency",
"gadgetry",
"Galveston",
"getaway",
"glossary",
"gossamer",
"graduate",
"gravity",
"guitarist",
"hamburger",
"Hamilton",
"handiwork",
"hazardous",
"headwaters",
"hemisphere",
"hesitate",
"hideaway",
"holiness",
"hurricane",
"hydraulic",
"impartial",
"impetus",
"inception",
"indigo",
"inertia",
"infancy",
"inferno",
"informant",
"insincere",
"insurgent",
"integrate",
"intention",
"inventive",
"Istanbul",
"Jamaica",
"Jupiter",
"leprosy",
"letterhead",
"liberty",
"maritime",
"matchmaker",
"maverick",
"Medusa",
"megaton",
"microscope",
"microwave",
"midsummer",
"millionaire",
"miracle",
"misnomer",
"molasses",
"molecule",
"Montana",
"monument",
"mosquito",
"narrative",
"nebula",
"newsletter",
"Norwegian",
"October",
"Ohio",
"onlooker",
"opulent",
"Orlando",
"outfielder",
"Pacific",
"pandemic",
"Pandora",
"paperweight",
"paragon",
"paragraph",
"paramount",
"passenger",
"pedigree",
"Pegasus",
"penetrate",
"perceptive",
"performance",
"pharmacy",
"phonetic",
"photograph",
"pioneer",
"pocketful",
"politeness",
"positive",
"potato",
"processor",
"provincial",
"proximate",
"puberty",
"publisher",
"pyramid",
"quantity",
"racketeer",
"rebellion",
"recipe",
"recover",
"repellent",
"replica",
"reproduce",
"resistor",
"responsive",
"retraction",
"retrieval",
"retrospect",
"revenue",
"revival",
"revolver",
"sandalwood",
"sardonic",
"Saturday",
"savagery",
"scavenger",
"sensation",
"sociable",
"souvenir",
"specialist",
"speculate",
"stethoscope",
"stupendous",
"supportive",
"surrender",
"suspicious",
"sympathy",
"tambourine",
"telephone",
"therapist",
"tobacco",
"tolerance",
"tomorrow",
"torpedo",
"tradition",
"travesty",
"trombonist",
"truncated",
"typewriter",
"ultimate",
"undaunted",
"underfoot",
"unicorn",
"unify",
"universe",
"unravel",
"upcoming",
"vacancy",
"vagabond",
"vertigo",
"Virginia",
"visitor",
"vocalist",
"voyager",
"warranty",
"Waterloo",
"whimsical",
"Wichita",
"Wilmington",
"Wyoming",
"yesteryear",
"Yucatan")
class InvalidWordError(ValueError):
pass
def words_to_int(word_iter, odd=False):
"""Generator yielding integer indices for each word in word_iter.
:param word_iter: iterable of pgp words
:type word_iter: iterable
:param odd: start with odd word list
:type odd: boolean
:return: integer
:rtype: generator
"""
for word in word_iter:
try:
yield (ODD if odd else EVEN).index(word)
except ValueError:
msg = "not in {} word list: '{}'"
raise InvalidWordError(msg.format("odd" if odd else "even", word))
# toggle odd/even
odd = not odd
def ints_to_word(int_iter, odd=False):
"""Generator yielding PGP words for each byte/int in int_iter.
:param int_iter: iterable of integers between 0 and 255
:type int_iter: iterable
:param odd: start with odd word list
:type odd: boolean
:return: pgp words
:rtype: generator
"""
for idx in int_iter:
yield (ODD if odd else EVEN)[idx]
# toggle odd/even
odd = not odd
class PGPWords(bytearray):
"""Inherits from bytearray. Add .hex() method and overwrite __str__"""
def __init__(self, source, **kwargs):
"""Initiate bytearray. Added initialization styles:
E.g.:
p = PGPWords("absurd bodyguard baboon", encoding="pgp-words")
p = PGPWords("DEAD 1337", encoding="hex")
"""
enc = kwargs.get("encoding")
if enc == "pgp-words":
kwargs.pop("encoding")
source = words_to_int(source.split(SEPARATOR), **kwargs)
kwargs = {}
elif enc == "hex" or source.startswith('0x'):
kwargs.pop("encoding")
tmp = source.replace("0x", '').replace(' ', '')
source = (int(tmp[i:i+2], 16) for i in range(0, len(tmp), 2))
super(PGPWords, self).__init__(source, **kwargs)
def __str__(self):
"""Return corresponding pgp words, separated by SEPARATOR."""
gen = ints_to_word(self)
return SEPARATOR.join(gen)
def hex(self):
"""Return corresponding hex representation as string"""
tmp = ''.join([hex(i).split('x')[1].zfill(2) for i in self])
gen = (tmp[i:i+4].upper() for i in range(0, len(tmp), 4))
return SEPARATOR.join(gen)
def main():
"""Try to convert arguments in either direction."""
if len(sys.argv) < 2 or sys.argv[1].startswith('-'):
print(__doc__.split("Mainline code:\n\n")[1], file=sys.stderr)
exit(-1)
arg_str = ' '.join(sys.argv[1:])
try:
result = PGPWords(arg_str, encoding="hex")
print(result)
except ValueError as err1:
try:
result = PGPWords(arg_str, encoding="pgp-words").hex()
print(result)
except InvalidWordError as err2:
print(err1, file=sys.stderr)
print(err2, file=sys.stderr)
exit(-1)
if __name__ == "__main__":
main()
|
mit
| -7,093,815,584,150,289,000
| 19.746479
| 78
| 0.45063
| false
| 3.529553
| false
| false
| false
|
petezybrick/iote2e
|
iote2e-pyclient/src/iote2epyclient/test/testhatsensors.py
|
1
|
3137
|
# Copyright 2016, 2017 Peter Zybrick and others.
#
# 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.
"""
testhatsensors - Test RPi HAT sensors
:author: Pete Zybrick
:contact: pzybrick@gmail.com
:version: 1.0.0
"""
import sys
import datetime
from sense_hat import SenseHat
from time import sleep
def main(conf_file):
import logging.config
logging.config.fileConfig( conf_file, disable_existing_loggers=False)
logger = logging.getLogger(__name__)
logger.info('Starting')
sense = SenseHat()
#showMessages(sense)
#showLetters(sense)
#showPixels(sense)
showTemperature(sense)
#showJoystickPoll(sense)
#showJoystickWait(sense)
sense.clear()
logger.info('Done')
def showJoystickPoll(sense):
while True:
for event in sense.stick.get_events():
print("The joystick was {} {}".format(event.action,event.direction))
sleep(.25)
print('poll')
def showJoystickWait(sense):
while True:
event = sense.stick.wait_for_event()
if "middle" == event.direction:
if "pressed" == event.action:
print("1");
elif "released" == event.action:
print("0");
#print("The joystick was {} {}".format(event.action,event.direction))
def showTemperature(sense):
for i in range(0,5):
t = round(sense.get_temperature(),2)
print(t)
sense.show_message("{}".format(t), scroll_speed=.1)
sleep(1)
def showMessages(sense):
sense.show_message("Watson, come here. I need you.", scroll_speed=.025);
def showLetters(sense):
sense.show_letter("R", text_colour=[255,0,0],back_colour=[0,0,0]);
sleep(1.5)
sense.show_letter("G", text_colour=[0,255,0],back_colour=[0,0,0]);
sleep(1.5)
sense.show_letter("B", text_colour=[0,0,255],back_colour=[0,0,0]);
sleep(1.5)
def showPixels(sense):
b = [0,0,255]
y = [255,255,0]
e = [0,0,0]
image = [
b,b,e,b,b,e,y,y,
b,b,e,b,b,e,y,y,
e,e,e,e,e,e,e,e,
b,b,e,b,b,e,b,b,
b,b,e,b,b,e,b,b,
e,e,e,e,e,e,e,e,
b,b,e,b,b,e,b,b,
b,b,e,b,b,e,b,b
]
sense.set_pixels(image)
angles = [0,90,180,270,0,90,180,270]
for angle in angles:
sense.set_rotation(angle)
sleep(2)
if __name__ == '__main__':
sys.argv = ['testhatsensors.py', '/home/pete/iote2epyclient/log-configs/client_consoleonly.conf']
if( len(sys.argv) < 2 ):
print('Invalid format, execution cancelled')
print('Correct format: python <consoleConfigFile.conf>')
sys.exit(8)
main(sys.argv[1])
|
apache-2.0
| 3,881,030,705,390,971,000
| 27.008929
| 101
| 0.620019
| false
| 3.115194
| false
| false
| false
|
Goyatuzo/Challenges
|
HackerRank/Algorithms/Sorting/Insertion Sort Part 1/insertion_sort_p1.py
|
1
|
1113
|
def insertion_sort(lst):
"""Instead of just inserting the value where it should be at,
it shifts the entire array until the location is found. It prints
out all the intermediate steps, but the final step is actually just
returned, so the output must be manually printed.
:param lst: The list of values to be sorted by insertion."""
# The value to be inserted.
to_insert = lst[-1]
n = len(lst)
# Remove the element to be added and replace with last element.
del lst[-1]
lst.append(lst[-1])
print(" ".join(map(str, lst)))
for i in range(n - 2, -1, -1):
# If it's at the beginning of the list, just insert it.
if i <= 0:
lst.insert(0, to_insert)
del lst[1]
break
# If it's in the middle of the list.
elif lst[i - 1] <= to_insert and lst[i] >= to_insert:
lst.insert(i, to_insert)
del lst[i + 1]
break
else:
lst.insert(i, lst[i - 1])
del lst[i + 1]
print(" ".join(map(str, lst)))
return " ".join(map(str, lst))
|
mit
| 3,846,452,538,363,552,000
| 29.916667
| 71
| 0.562444
| false
| 3.673267
| false
| false
| false
|
ict-felix/stack
|
vt_manager_kvm/src/python/vt_manager_kvm/controller/dispatchers/ui/GUIdispatcher.py
|
1
|
17272
|
from django.core.urlresolvers import reverse
from django.forms.models import modelformset_factory
from django.shortcuts import get_object_or_404
from django.http import HttpResponseRedirect, HttpResponse
from django.views.generic import simple
from django.views.generic import list_detail, simple
from django.views.generic.create_update import apply_extra_context
from vt_manager_kvm.models import *
from vt_manager_kvm.communication.utils.XmlHelper import XmlHelper
import uuid, time, logging
from django.template import loader, RequestContext
from django.core.xheaders import populate_xheaders
from django.contrib import messages
#News
from vt_manager_kvm.controller.drivers.VTDriver import VTDriver
from vt_manager_kvm.utils.HttpUtils import HttpUtils
from vt_manager_kvm.models.NetworkInterface import NetworkInterface
from vt_manager_kvm.models.MacRange import MacRange
from vt_manager_kvm.controller.dispatchers.xmlrpc.InformationDispatcher import InformationDispatcher
from vt_manager_kvm.controller.dispatchers.forms.NetworkInterfaceForm import MgmtBridgeForm
from vt_manager_kvm.controller.dispatchers.forms.ServerForm import ServerForm
from django.db import transaction
def userIsIslandManager(request):
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
@transaction.commit_on_success
def servers_crud(request, server_id=None):
"""Show a page for the user to add/edit an VTServer """
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
vmProjects = {}
vmSlices = {}
try:
for vm in VTDriver.getVMsInServer(VTDriver.getServerById(server_id)):
if vm.projectName not in vmProjects:
vmProjects[vm.projectName] = vm.projectId
if vm.sliceName not in vmSlices:
vmSlices[vm.sliceName] = vm.sliceId
except Exception as e:
print e
pass
serverFormClass = HttpUtils.getFormFromModel(VTServer)
ifaceFormClass = HttpUtils.getFormFromModel(NetworkInterface)
IfaceFormSetClass = modelformset_factory(NetworkInterface)
if server_id != None:
server = get_object_or_404(VTServer, pk=server_id)
else:
server = None
if request.method == "GET":
#serverForm = serverFormClass(instance=server)
serverForm = ServerForm(instance=server, prefix ="server")
if server != None:
mgmt = server.getNetworkInterfaces().filter(isMgmt = True)
if mgmt:
mgmt = mgmt.get()
mgmtIfaceForm = MgmtBridgeForm({'mgmtBridge-name':mgmt.getName(), 'mgmtBridge-mac':mgmt.getMacStr()}, prefix ="mgmtBridge")
else:
mgmtIfaceForm = MgmtBridgeForm(prefix ="mgmtBridge")
data = server.getNetworkInterfaces().filter(isMgmt = False)
if data:
IfaceFormSetClass = modelformset_factory(NetworkInterface,extra = 0)
ifaceformset = IfaceFormSetClass(queryset= data)
else:
mgmtIfaceForm = MgmtBridgeForm(prefix ="mgmtBridge")
ifaceformset = IfaceFormSetClass(queryset= NetworkInterface.objects.none())
elif request.method == "POST":
#serverForm = serverFormClass(request.POST, instance=server)
serverForm = ServerForm(request.POST, instance=server, prefix ="server")
ifaceformset = IfaceFormSetClass(request.POST)
mgmtIfaceForm = MgmtBridgeForm(request.POST, prefix ="mgmtBridge")
if serverForm.is_valid() and ifaceformset.is_valid() and mgmtIfaceForm.is_valid():
ifaces = ifaceformset.save(commit = False)
if server == None:
server = serverForm.save(commit = False)
try:
server = VTDriver.crudServerFromInstance(server)
VTDriver.setMgmtBridge(request, server)
VTDriver.crudDataBridgeFromInstance(server, ifaces,request.POST.getlist("DELETE"))
except Exception as e:
print e
e = HttpUtils.processException(e)
context = {"exception":e, "serverForm": serverForm, 'vmProjects': vmProjects, 'vmSlices': vmSlices,'ifaceformset' : ifaceformset, 'mgmtIfaceForm' : mgmtIfaceForm}
if server_id != None: context["server"] = server
return simple.direct_to_template(
request,
template="servers/servers_crud.html",
extra_context=context,
)
# Returns to server's admin page and rollback transactions
return HttpResponseRedirect('/servers/admin/')
else:
return HttpResponseNotAllowed("GET", "POST")
context = {"serverForm": serverForm, 'vmProjects': vmProjects, 'vmSlices': vmSlices,'ifaceformset' : ifaceformset, 'mgmtIfaceForm' : mgmtIfaceForm}
if server_id != None: context["server"] = server
return simple.direct_to_template(
request,
template="servers/servers_crud.html",
extra_context=context,
)
def admin_servers(request):
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
servers = VTDriver.getAllServers()
return simple.direct_to_template(
request, template="servers/admin_servers.html",
extra_context={"servers_ids": servers})
def delete_server(request, server_id):
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
if request.method == 'POST':
try:
VTDriver.deleteServer(VTDriver.getServerById(server_id))
return HttpResponseRedirect(reverse('dashboard'))
except Exception as e:
logging.error(e)
e = HttpUtils.processException(e)
return simple.direct_to_template(request,
template = 'servers/delete_server.html',
extra_context = {'user':request.user, 'exception':e, 'next':reverse("admin_servers")},
)
elif request.method == 'GET':
return simple.direct_to_template(request,
template = 'servers/delete_server.html',
extra_context = {'user':request.user, 'next':reverse("admin_servers"),'object':VTDriver.getServerById(server_id)},
)
def action_vm(request, server_id, vm_id, action):
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
if(action == 'list'):
return simple.direct_to_template(
request, template="servers/server_vm_details.html",
extra_context={"vm": VTDriver.getVMbyId(vm_id), "server_id":server_id}
)
elif(action == 'check_status'):
#XXX: Do this function if needed
return simple.direct_to_template(
request, template="servers/list_vm.html",
extra_context={"vm": VM.objects.get(id = vm_id)}
)
elif(action == 'force_update_server'):
InformationDispatcher.forceListActiveVMs(serverID=server_id)
elif(action == 'force_update_vm'):
InformationDispatcher.forceListActiveVMs(vmID=vm_id)
else:
#XXX: serverUUID should be passed in a different way
VTDriver.PropagateActionToProvisioningDispatcher(vm_id, VTServer.objects.get(id=server_id).uuid, action)
#return HttpResponseRedirect(reverse('edit_server', args = [server_id]))
return HttpResponse("")
def subscribeEthernetRanges(request, server_id):
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
macRanges = MacRange.objects.all()
if server_id != None:
server = get_object_or_404(VTServer, pk=server_id)
else:
raise Exception ("NO SERVER")
if request.method == "GET":
return simple.direct_to_template(request,
template = 'servers/servers_subscribeEthernetRanges.html',
extra_context = {'server': server, 'macRanges':macRanges},
)
elif request.method=='POST':
VTDriver.manageEthernetRanges(request,server,macRanges)
return HttpResponseRedirect(reverse('edit_server', args = [server_id]))
else:
return HttpResponseNotAllowed("GET", "POST")
def subscribeIp4Ranges(request, server_id):
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
ipRanges = Ip4Range.objects.all()
if server_id != None:
server = get_object_or_404(VTServer, pk=server_id)
else:
raise Exception ("NO SERVER")
if request.method == "GET":
return simple.direct_to_template(request,
template = 'servers/servers_subscribeIp4Ranges.html',
extra_context = {'server': server, 'ipRanges':ipRanges},
)
elif request.method=='POST':
VTDriver.manageIp4Ranges(request,server,ipRanges)
return HttpResponseRedirect(reverse('edit_server', args = [server_id]))
else:
return HttpResponseNotAllowed("GET", "POST")
def list_vms(request, server_id):
if (not request.user.is_superuser):
return simple.direct_to_template(request,
template = 'not_admin.html',
extra_context = {'user':request.user},
)
vmProjects = {}
vmSlices = {}
try:
for vm in VTDriver.getVMsInServer(VTDriver.getServerById(server_id)):
if vm.projectName not in vmProjects:
vmProjects[vm.projectName] = vm.projectId
if vm.sliceName not in vmSlices:
vmSlices[vm.sliceName] = vm.sliceId
except Exception as e:
print e
pass
server = get_object_or_404(VTServer, pk=server_id)
context = { 'vmProjects': vmProjects, 'vmSlices': vmSlices,'server':server}
return simple.direct_to_template(
request,
template="servers/servers_list_vms.html",
extra_context=context,
)
'''
Networking point of entry
'''
from vt_manager_kvm.controller.networking.EthernetController import EthernetController
from vt_manager_kvm.controller.networking.Ip4Controller import Ip4Controller
from vt_manager_kvm.models.MacRange import MacRange
NETWORKING_ACTION_ADD="add"
NETWORKING_ACTION_EDIT="edit"
NETWORKING_ACTION_DELETE="delete"
NETWORKING_ACTION_SHOW="show"
NETWORKING_ACTION_ADDEXCLUDED="addExcluded"
NETWORKING_ACTION_REMOVEXCLUDED="removeExcluded"
NETWORKING_POSSIBLE_ACTIONS=(NETWORKING_ACTION_ADD,NETWORKING_ACTION_DELETE,NETWORKING_ACTION_EDIT,NETWORKING_ACTION_SHOW,NETWORKING_ACTION_ADDEXCLUDED,NETWORKING_ACTION_REMOVEXCLUDED,None)
def networkingDashboard(request):#,rangeId):
extra_context = {"section": "networking","subsection":"None"}
extra_context["macRanges"] = EthernetController.listRanges()
extra_context["MacRange"] = MacRange
extra_context["ip4Ranges"] = Ip4Controller.listRanges()
extra_context["Ip4Range"] = Ip4Range
template = "networking/index.html"
return simple.direct_to_template(
request,
extra_context=extra_context,
template=template,
)
def manageIp4(request,rangeId=None,action=None,ip4Id=None):
if not action in NETWORKING_POSSIBLE_ACTIONS:
raise Exception("Unknown action")
#Define context
extra_context = {"section": "networking","subsection":"ip4"+str(action),}
#Add process
if (action == NETWORKING_ACTION_ADD):
if request.method == "GET":
#Show form
extra_context["form"] = HttpUtils.getFormFromModel(Ip4Range)
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ip4/rangeCrud.html",
)
return
# return HttpResponseRedirect("/networking/ip4/")
elif request.method == "POST":
try:
instance = HttpUtils.getInstanceFromForm(request,Ip4Range)
#Create Range
Ip4Controller.createRange(instance)
return HttpResponseRedirect("/networking/ip4/")
except Exception as e:
print e
extra_context["form"] = HttpUtils.processExceptionForm(e,request,Ip4Range)
#Process creation query
#return HttpResponseRedirect("/networking/ip4/")
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ip4/rangeCrud.html",
)
#Show
if ((action == None) or (action==NETWORKING_ACTION_SHOW)) and (not rangeId==None):
instance = Ip4Controller.getRange(rangeId)
extra_context["range"] = instance
#return HttpResponseRedirect("/networking/ip4/")
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ip4/rangeDetail.html",
)
#Edit
#TODO
#Add excluded Ip
if (action == NETWORKING_ACTION_ADDEXCLUDED) and (request.method == "POST"):
if not request.method == "POST":
raise Exception("Invalid method")
try:
instance = Ip4Controller.getRange(rangeId)
extra_context["range"] = instance
#Create excluded
Ip4Controller.addExcludedIp4(instance,request)
return HttpResponseRedirect("/networking/ip4/"+rangeId)
except Exception as e:
print e
extra_context["errors"] = HttpUtils.processException(e)
pass
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ip4/rangeDetail.html",
)
#Release excluded Ip
if (action == NETWORKING_ACTION_REMOVEXCLUDED) and (request.method == "POST"):
try:
instance = Ip4Controller.getRange(rangeId)
#Create excluded
Ip4Controller.removeExcludedIp4(instance,ip4Id)
#FIXME: Why initial instance is not refreshed?
instance = Ip4Controller.getRange(rangeId)
extra_context["range"] = instance
return HttpResponseRedirect("/networking/ip4/"+rangeId)
except Exception as e:
print e
extra_context["errors"] = HttpUtils.processException(e)
pass
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ip4/rangeDetail.html",
)
#Delete
if (action == NETWORKING_ACTION_DELETE) and (request.method == "POST"):
try:
Ip4Controller.deleteRange(rangeId)
return HttpResponseRedirect("/networking/ip4/")
except Exception as e:
print e
extra_context["errors"] = HttpUtils.processException(e)
pass
extra_context["ranges"] = Ip4Controller.listRanges()
template = "networking/ip4/index.html"
return simple.direct_to_template(
request,
extra_context = extra_context,
template=template,
)
def manageEthernet(request,rangeId=None,action=None,macId=None):
if not action in NETWORKING_POSSIBLE_ACTIONS:
raise Exception("Unknown action")
#Define context
extra_context = {"section": "networking","subsection":"ethernet",}
#Add process
if (action == NETWORKING_ACTION_ADD):
if request.method == "GET":
#Show form
extra_context["form"] = HttpUtils.getFormFromModel(MacRange)
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ethernet/rangeCrud.html",
)
return
elif request.method == "POST":
try:
instance = HttpUtils.getInstanceFromForm(request,MacRange)
#Create Range
EthernetController.createRange(instance)
return HttpResponseRedirect("/networking/ethernet/")
except Exception as e:
print e
extra_context["form"] = HttpUtils.processExceptionForm(e,request,MacRange)
#Process creation query
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ethernet/rangeCrud.html",
)
#Show
if ((action == None) or (action==NETWORKING_ACTION_SHOW)) and (not rangeId==None):
instance = EthernetController.getRange(rangeId)
extra_context["range"] = instance
#return HttpResponseRedirect("/networking/ethernet/")
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ethernet/rangeDetail.html",
)
#Edit
#TODO
#Add excluded Mac
if (action == NETWORKING_ACTION_ADDEXCLUDED) and (request.method == "POST"):
if not request.method == "POST":
raise Exception("Invalid method")
try:
instance = EthernetController.getRange(rangeId)
extra_context["range"] = instance
#Create excluded
EthernetController.addExcludedMac(instance,request)
return HttpResponseRedirect("/networking/ethernet/"+rangeId)
except Exception as e:
print e
extra_context["errors"] = HttpUtils.processException(e)
pass
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ethernet/rangeDetail.html",
)
#Release excluded Mac
if (action == NETWORKING_ACTION_REMOVEXCLUDED) and (request.method == "POST"):
try:
instance = EthernetController.getRange(rangeId)
#Create excluded
#FIXME: Why initial instance is not refreshed?
EthernetController.removeExcludedMac(instance,macId)
instance = EthernetController.getRange(rangeId)
extra_context["range"] = instance
return HttpResponseRedirect("/networking/ethernet/"+rangeId)
except Exception as e:
print e
extra_context["errors"] = HttpUtils.processException(e)
pass
return simple.direct_to_template(
request,
extra_context = extra_context,
template="networking/ethernet/rangeDetail.html",
)
#Delete
if (action == NETWORKING_ACTION_DELETE) and (request.method == "POST"):
try:
EthernetController.deleteRange(rangeId)
return HttpResponseRedirect("/networking/ethernet/")
except Exception as e:
print e
extra_context["errors"] = HttpUtils.processException(e)
pass
#Listing ranges
extra_context["ranges"] = EthernetController.listRanges()
return simple.direct_to_template(
request,
extra_context = extra_context,
template = "networking/ethernet/index.html",
)
|
apache-2.0
| -5,939,845,024,590,403,000
| 29.898032
| 189
| 0.721688
| false
| 3.373438
| false
| false
| false
|
edx-solutions/discussion-edx-platform-extensions
|
social_engagement/engagement.py
|
1
|
14753
|
"""
Business logic tier regarding social engagement scores
"""
import logging
import sys
from collections import defaultdict
from datetime import datetime
import pytz
from django.conf import settings
from django.db.models.signals import post_save, pre_save
from django.dispatch import receiver
from django.http import HttpRequest
import openedx.core.djangoapps.django_comment_common.comment_client as cc
from edx_notifications.data import NotificationMessage
from edx_notifications.lib.publisher import (get_notification_type,
publish_notification_to_user)
from edx_solutions_api_integration.utils import get_aggregate_exclusion_user_ids
from lms.djangoapps.discussion.rest_api.exceptions import (CommentNotFoundError,
ThreadNotFoundError)
from opaque_keys import InvalidKeyError
from opaque_keys.edx.keys import CourseKey
from openedx.core.djangoapps.django_comment_common.comment_client.user import get_course_social_stats
from openedx.core.djangoapps.django_comment_common.comment_client.utils import CommentClientRequestError
from requests.exceptions import ConnectionError
from xmodule.modulestore.django import modulestore
from .models import StudentSocialEngagementScore
log = logging.getLogger(__name__)
def update_course_engagement(course_id, compute_if_closed_course=False, course_descriptor=None):
"""
Compute and save engagement scores and stats for whole course.
"""
if not settings.FEATURES.get('ENABLE_SOCIAL_ENGAGEMENT', False):
return
course_key = course_id if isinstance(course_id, CourseKey) else CourseKey.from_string(course_id)
# cs_comment_service works is slash separated course_id strings
slash_course_id = str(course_key)
if not course_descriptor:
# it course descriptor was not passed in (as an optimization)
course_descriptor = modulestore().get_course(course_key)
if not course_descriptor:
# couldn't find course?!?
return
if not compute_if_closed_course and course_descriptor.end:
# if course is closed then don't bother. Note we can override this if we want to force update
now_utc = datetime.now(pytz.UTC)
if now_utc > course_descriptor.end:
log.info('update_user_engagement_score() is skipping because the course is closed...')
return
score_update_count = 0
try:
for user_id, social_stats in _get_course_social_stats(slash_course_id):
log.info('Updating social engagement score for user_id {} in course_key {}'.format(user_id, course_key))
current_score = _compute_social_engagement_score(social_stats)
StudentSocialEngagementScore.save_user_engagement_score(
course_key, user_id, current_score, social_stats
)
score_update_count += 1
except (CommentClientRequestError, ConnectionError) as error:
log.exception(error)
return score_update_count
def _get_course_social_stats(course_id):
""""
Yield user and user's stats for whole course from Forum API.
"""
stats = get_course_social_stats(course_id)
yield from stats.items()
def get_social_metric_points():
"""
Get custom or default social metric points.
"""
return getattr(
settings,
'SOCIAL_METRIC_POINTS',
{
'num_threads': 10,
'num_comments': 15,
'num_replies': 15,
'num_upvotes': 25,
'num_thread_followers': 5,
'num_comments_generated': 15,
}
)
def _compute_social_engagement_score(social_metrics):
"""
For a list of social_stats, compute the social score
"""
social_metric_points = get_social_metric_points()
social_total = 0
for key, val in social_metric_points.items():
social_total += social_metrics.get(key, 0) * val
return social_total
#
# Support for Notifications, these two receivers should actually be migrated into a new Leaderboard django app.
# For now, put the business logic here, but it is pretty decoupled through event signaling
# so we should be able to move these files easily when we are able to do so
#
@receiver(pre_save, sender=StudentSocialEngagementScore)
def handle_progress_pre_save_signal(sender, instance, **kwargs):
"""
Handle the pre-save ORM event on StudentSocialEngagementScore
"""
if settings.FEATURES['ENABLE_NOTIFICATIONS']:
# If notifications feature is enabled, then we need to get the user's
# rank before the save is made, so that we can compare it to
# after the save and see if the position changes
instance.presave_leaderboard_rank = StudentSocialEngagementScore.get_user_leaderboard_position(
instance.course_id,
user_id=instance.user.id,
exclude_users=get_aggregate_exclusion_user_ids(instance.course_id)
)['position']
@receiver(post_save, sender=StudentSocialEngagementScore)
def handle_progress_post_save_signal(sender, instance, **kwargs):
"""
Handle the pre-save ORM event on CourseModuleCompletions
"""
if settings.FEATURES['ENABLE_NOTIFICATIONS']:
# If notifications feature is enabled, then we need to get the user's
# rank before the save is made, so that we can compare it to
# after the save and see if the position changes
leaderboard_rank = StudentSocialEngagementScore.get_user_leaderboard_position(
instance.course_id,
user_id=instance.user.id,
exclude_users=get_aggregate_exclusion_user_ids(instance.course_id)
)['position']
if leaderboard_rank == 0:
# quick escape when user is not in the leaderboard
# which means rank = 0. Trouble is 0 < 3, so unfortunately
# the semantics around 0 don't match the logic below
return
# logic for Notification trigger is when a user enters into the Leaderboard
leaderboard_size = getattr(settings, 'LEADERBOARD_SIZE', 3)
presave_leaderboard_rank = instance.presave_leaderboard_rank if instance.presave_leaderboard_rank else sys.maxsize
if leaderboard_rank <= leaderboard_size and presave_leaderboard_rank > leaderboard_size:
try:
notification_msg = NotificationMessage(
msg_type=get_notification_type('open-edx.lms.leaderboard.engagement.rank-changed'),
namespace=str(instance.course_id),
payload={
'_schema_version': '1',
'rank': leaderboard_rank,
'leaderboard_name': 'Engagement',
}
)
#
# add in all the context parameters we'll need to
# generate a URL back to the website that will
# present the new course announcement
#
# IMPORTANT: This can be changed to msg.add_click_link() if we
# have a particular URL that we wish to use. In the initial use case,
# we need to make the link point to a different front end website
# so we need to resolve these links at dispatch time
#
notification_msg.add_click_link_params({
'course_id': str(instance.course_id),
})
publish_notification_to_user(int(instance.user.id), notification_msg)
except Exception as ex:
# Notifications are never critical, so we don't want to disrupt any
# other logic processing. So log and continue.
log.exception(ex)
def get_involved_users_in_thread(request, thread):
"""
Compute all the users involved in the children of a specific thread.
"""
params = {"thread_id": thread.id, "page_size": 100}
is_question = getattr(thread, "thread_type", None) == "question"
author_id = getattr(thread, 'user_id', None)
results = _detail_results_factory()
if is_question:
# get users of the non-endorsed comments in thread
params.update({"endorsed": False})
_get_details_for_deletion(_get_request(request, params), results=results, is_thread=True)
# get users of the endorsed comments in thread
if getattr(thread, 'has_endorsed', False):
params.update({"endorsed": True})
_get_details_for_deletion(_get_request(request, params), results=results, is_thread=True)
else:
_get_details_for_deletion(_get_request(request, params), results=results, is_thread=True)
users = results['users']
if author_id:
users[author_id]['num_upvotes'] += thread.votes.get('count', 0)
users[author_id]['num_threads'] += 1
users[author_id]['num_comments_generated'] += results['all_comments']
users[author_id]['num_thread_followers'] += thread.get_num_followers()
if thread.abuse_flaggers:
users[author_id]['num_flagged'] += 1
return users
def get_involved_users_in_comment(request, comment):
"""
Method used to extract the involved users in the comment.
This method also returns the creator of the post.
"""
params = {"page_size": 100}
comment_author_id = getattr(comment, 'user_id', None)
thread_author_id = None
if hasattr(comment, 'thread_id'):
thread_author_id = _get_author_of_thread(comment.thread_id)
results = _get_details_for_deletion(_get_request(request, params), comment.id, nested=True)
users = results['users']
if comment_author_id:
users[comment_author_id]['num_upvotes'] += comment.votes.get('count', 0)
if getattr(comment, 'parent_id', None):
# It's a reply.
users[comment_author_id]['num_replies'] += 1
else:
# It's a comment.
users[comment_author_id]['num_comments'] += 1
if comment.abuse_flaggers:
users[comment_author_id]['num_flagged'] += 1
if thread_author_id:
users[thread_author_id]['num_comments_generated'] += results['replies'] + 1
return users
def _detail_results_factory():
"""
Helper method to maintain organized result structure while getting involved users.
"""
return {
'replies': 0,
'all_comments': 0,
'users': defaultdict(lambda: defaultdict(int)),
}
def _get_users_in_thread(request):
from lms.djangoapps.discussion.rest_api.views import CommentViewSet
users = set()
response_page = 1
has_results = True
while has_results:
try:
params = {"page": response_page}
response = CommentViewSet().list(
_get_request(request, params)
)
for comment in response.data["results"]:
users.add(comment["author"])
if comment["child_count"] > 0:
users.update(_get_users_in_comment(request, comment["id"]))
has_results = response.data["pagination"]["next"]
response_page += 1
except (ThreadNotFoundError, InvalidKeyError):
return users
return users
def _get_users_in_comment(request, comment_id):
from lms.djangoapps.discussion.rest_api.views import CommentViewSet
users = set()
response_page = 1
has_results = True
while has_results:
try:
response = CommentViewSet().retrieve(_get_request(request, {"page": response_page}), comment_id)
for comment in response.data["results"]:
users.add(comment["author"])
if comment["child_count"] > 0:
users.update(_get_users_in_comment(request, comment["id"]))
has_results = response.data["pagination"]["next"]
response_page += 1
except (ThreadNotFoundError, InvalidKeyError):
return users
return users
def _get_request(incoming_request, params):
request = HttpRequest()
request.method = 'GET'
request.user = incoming_request.user
request.META = incoming_request.META.copy()
request.GET = incoming_request.GET.copy()
request.GET.update(params)
return request
def _get_author_of_comment(parent_id):
comment = cc.Comment.find(parent_id)
if comment and hasattr(comment, 'user_id'):
return comment.user_id
def _get_author_of_thread(thread_id):
thread = cc.Thread.find(thread_id)
if thread and hasattr(thread, 'user_id'):
return thread.user_id
def _get_details_for_deletion(request, comment_id=None, results=None, nested=False, is_thread=False):
"""
Get details of comment or thread and related users that are required for deletion purposes.
"""
if not results:
results = _detail_results_factory()
for page, response in enumerate(_get_paginated_results(request, comment_id, is_thread)):
if page == 0:
results['all_comments'] += response.data['pagination']['count']
if results['replies'] == 0:
results['replies'] = response.data['pagination']['count']
for comment in response.data['results']:
_extract_stats_from_comment(request, comment, results, nested)
return results
def _get_paginated_results(request, comment_id, is_thread):
"""
Yield paginated comments of comment or thread.
"""
from lms.djangoapps.discussion.rest_api.views import CommentViewSet
response_page = 1
has_next = True
while has_next:
try:
if is_thread:
response = CommentViewSet().list(_get_request(request, {"page": response_page}))
else:
response = CommentViewSet().retrieve(_get_request(request, {"page": response_page}), comment_id)
except (ThreadNotFoundError, CommentNotFoundError, InvalidKeyError):
raise StopIteration
has_next = response.data["pagination"]["next"]
response_page += 1
yield response
def _extract_stats_from_comment(request, comment, results, nested):
"""
Extract results from comment and its nested comments.
"""
user_id = comment.serializer.instance['user_id']
if not nested:
results['users'][user_id]['num_comments'] += 1
else:
results['users'][user_id]['num_replies'] += 1
results['users'][user_id]['num_upvotes'] += comment['vote_count']
if comment.serializer.instance['abuse_flaggers']:
results['users'][user_id]['num_flagged'] += 1
if comment['child_count'] > 0:
_get_details_for_deletion(request, comment['id'], results, nested=True)
|
agpl-3.0
| -3,449,035,946,806,721,000
| 35.790524
| 122
| 0.638582
| false
| 4.156946
| false
| false
| false
|
arkanister/minitickets
|
lib/utils/html/templatetags/icons.py
|
1
|
2009
|
# -*- coding: utf-8 -*-
from django import template
from django.template import TemplateSyntaxError, Node
from ..icons.base import Icon
from ..tags import token_kwargs, resolve_kwargs
register = template.Library()
class IconNode(Node):
def __init__(self, _icon, kwargs=None):
super(IconNode, self).__init__()
self.icon = _icon
self.kwargs = kwargs or {}
def render(self, context):
icon = self.icon.resolve(context)
if isinstance(icon, Icon):
return icon.as_html()
attrs = resolve_kwargs(self.kwargs, context)
prefix = attrs.pop('prefix', None)
content = attrs.pop('content', None)
html_tag = attrs.pop('html_tag', None)
icon = Icon(icon, prefix=prefix, content=content,
html_tag=html_tag, attrs=attrs)
return icon.as_html()
@register.tag
def icon(parser, token):
"""
Render a HTML icon.
The tag can be given either a `.Icon` object or a name of the icon.
An optional second argument can specify the icon prefix to use.
An optional third argument can specify the icon html tag to use.
An optional fourth argument can specify the icon content to use.
Others arguments can specify any html attribute to use.
Example::
{% icon 'icon' 'kwarg1'='value1' 'kwarg2'='value2' ... %}
{% icon 'icon' 'prefix'='fa-' 'kwarg1'='value1' 'kwarg2'='value2' ... %}
{% icon 'icon' 'prefix'='fa-' 'html_tag'='b' 'kwarg1'='value1' 'kwarg2'='value2' ... %}
{% icon 'icon' 'prefix'='fa-' 'html_tag'='b' 'content'='R$' 'kwarg1'='value1' 'kwarg2'='value2' ... %}
"""
bits = token.split_contents()
try:
tag, _icon = bits.pop(0), parser.compile_filter(bits.pop(0))
except ValueError:
raise TemplateSyntaxError("'%s' must be given a icon." % bits[0])
kwargs = {}
# split optional args
if len(bits):
kwargs = token_kwargs(bits, parser)
return IconNode(_icon, kwargs=kwargs)
|
apache-2.0
| 8,514,085,994,507,164,000
| 29.923077
| 110
| 0.610254
| false
| 3.626354
| false
| false
| false
|
isaacbernat/awis
|
setup.py
|
1
|
1887
|
from setuptools import setup, find_packages
# from codecs import open
# from os import path
# here = path.abspath(path.dirname(__file__))
# # Get the long description from the README file
# with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
# long_description = f.read()
setup(
# Application name:
name="myawis",
# Version number (initial):
version="0.2.4",
# Application author details:
author="Ashim Lamichhane",
author_email="punchedrock@gmail.com",
# Packages
packages=['myawis'],
# data_files
data_files=[('awis', ['LICENSE.txt', 'README.rst'])],
# Include additional files into the package
include_package_data=True,
# Details
url="https://github.com/ashim888/awis",
# Keywords
keywords='python awis api call',
#
license='GNU General Public License v3.0',
description="A simple AWIS python wrapper",
long_description=open('README.rst').read(),
classifiers=[
# How mature is this project? Common values are
# 3 - Alpha
# 4 - Beta
# 5 - Production/Stable
'Development Status :: 2 - Pre-Alpha',
# Indicate who your project is intended for
'Intended Audience :: Developers',
'Topic :: Software Development :: Libraries :: Python Modules',
# Pick your license as you wish (should match "license" above)
'License :: Public Domain',
# Specify the Python versions you support here. In particular, ensure
# that you indicate whether you support Python 2, Python 3 or both.
'Programming Language :: Python :: 2.6',
'Programming Language :: Python :: 2.7',
],
install_requires=[
"requests",
"beautifulsoup4",
"lxml",
],
entry_points={
'console_scripts': [
'myawis=myawis:main',
],
},
)
|
gpl-3.0
| -1,147,754,553,041,353,200
| 27.590909
| 77
| 0.608903
| false
| 3.997881
| false
| true
| false
|
google-research/google-research
|
kws_streaming/models/lstm.py
|
1
|
3941
|
# coding=utf-8
# Copyright 2021 The Google Research Authors.
#
# 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.
"""LSTM with Mel spectrum and fully connected layers."""
from kws_streaming.layers import lstm
from kws_streaming.layers import modes
from kws_streaming.layers import speech_features
from kws_streaming.layers import stream
from kws_streaming.layers.compat import tf
import kws_streaming.models.model_utils as utils
def model_parameters(parser_nn):
"""LSTM model parameters."""
parser_nn.add_argument(
'--lstm_units',
type=str,
default='500',
help='Output space dimensionality of lstm layer ',
)
parser_nn.add_argument(
'--return_sequences',
type=str,
default='0',
help='Whether to return the last output in the output sequence,'
'or the full sequence',
)
parser_nn.add_argument(
'--stateful',
type=int,
default='1',
help='If True, the last state for each sample at index i'
'in a batch will be used as initial state for the sample '
'of index i in the following batch',
)
parser_nn.add_argument(
'--num_proj',
type=str,
default='200',
help='The output dimensionality for the projection matrices.',
)
parser_nn.add_argument(
'--use_peepholes',
type=int,
default='1',
help='True to enable diagonal/peephole connections',
)
parser_nn.add_argument(
'--dropout1',
type=float,
default=0.3,
help='Percentage of data dropped',
)
parser_nn.add_argument(
'--units1',
type=str,
default='',
help='Number of units in the last set of hidden layers',
)
parser_nn.add_argument(
'--act1',
type=str,
default='',
help='Activation function of the last set of hidden layers',
)
def model(flags):
"""LSTM model.
Similar model in papers:
Convolutional Recurrent Neural Networks for Small-Footprint Keyword Spotting
https://arxiv.org/pdf/1703.05390.pdf (with no conv layer)
Model topology is similar with "Hello Edge: Keyword Spotting on
Microcontrollers" https://arxiv.org/pdf/1711.07128.pdf
Args:
flags: data/model parameters
Returns:
Keras model for training
"""
input_audio = tf.keras.layers.Input(
shape=modes.get_input_data_shape(flags, modes.Modes.TRAINING),
batch_size=flags.batch_size)
net = input_audio
if flags.preprocess == 'raw':
# it is a self contained model, user need to feed raw audio only
net = speech_features.SpeechFeatures(
speech_features.SpeechFeatures.get_params(flags))(
net)
for units, return_sequences, num_proj in zip(
utils.parse(flags.lstm_units), utils.parse(flags.return_sequences),
utils.parse(flags.num_proj)):
net = lstm.LSTM(
units=units,
return_sequences=return_sequences,
stateful=flags.stateful,
use_peepholes=flags.use_peepholes,
num_proj=num_proj)(
net)
net = stream.Stream(cell=tf.keras.layers.Flatten())(net)
net = tf.keras.layers.Dropout(rate=flags.dropout1)(net)
for units, activation in zip(
utils.parse(flags.units1), utils.parse(flags.act1)):
net = tf.keras.layers.Dense(units=units, activation=activation)(net)
net = tf.keras.layers.Dense(units=flags.label_count)(net)
if flags.return_softmax:
net = tf.keras.layers.Activation('softmax')(net)
return tf.keras.Model(input_audio, net)
|
apache-2.0
| 9,010,055,643,208,554,000
| 30.031496
| 78
| 0.678508
| false
| 3.693533
| false
| false
| false
|
fake-name/ReadableWebProxy
|
WebMirror/management/GravityTalesManage.py
|
1
|
1202
|
import calendar
import datetime
import json
import os
import os.path
import shutil
import traceback
from concurrent.futures import ThreadPoolExecutor
import urllib.error
import urllib.parse
from sqlalchemy import and_
from sqlalchemy import or_
import sqlalchemy.exc
from sqlalchemy_continuum_vendored.utils import version_table
if __name__ == "__main__":
import logSetup
logSetup.initLogging()
import common.database as db
import common.Exceptions
import common.management.file_cleanup
import Misc.HistoryAggregator.Consolidate
import flags
import pprint
import config
from config import C_RAW_RESOURCE_DIR
import WebMirror.OutputFilters.rss.FeedDataParser
def exposed_delete_gravitytales_bot_blocked_pages():
'''
Delete the "checking you're not a bot" garbage pages
that sometimes get through the gravitytales scraper.
'''
with db.session_context() as sess:
tables = [
db.WebPages.__table__,
version_table(db.WebPages.__table__)
]
for ctbl in tables:
update = ctbl.delete() \
.where(ctbl.c.netloc == "gravitytales.com") \
.where(ctbl.c.content.like('%<div id="bot-alert" class="alert alert-info">%'))
print(update)
sess.execute(update)
sess.commit()
|
bsd-3-clause
| 2,929,935,509,704,662,000
| 21.259259
| 82
| 0.75624
| false
| 3.414773
| false
| false
| false
|
McIntyre-Lab/papers
|
newman_t1d_cases_2017/scripts/bwa_sam_parse.py
|
1
|
2304
|
#!/usr/bin/env python
import argparse
## This script parses a sam file from BWA-MEM and outputs a log of alignment counts and percentages.
# Parse command line arguments
parser = argparse.ArgumentParser(description='Parse sam file to get alignment counts.')
parser.add_argument('-sam','--sam_file',dest='sam', action='store', required=True, help='A Sam file to parse [Required]')
parser.add_argument('-o','--out', dest='out', action='store', required=True, help='Output file for alignment log [Required]')
args = parser.parse_args()
flags=list()
# Open sam file and create a list that contains only the second column from the sam file, (the bitwise flags).
with open(args.sam,'r') as sam:
for line in sam.readlines():
cols=line.split('\t')
flags.append(cols[1])
# Count the flags. These flags are based on BWA sam output, may not be the same for other aligners.
# The flags are different for paired data. There is another python script 'bwa_sam_parse_se.py' for single-end alignments.
unaln=flags.count('77') + flags.count('141') + flags.count('181') + flags.count('121') + flags.count('133') + flags.count('117') + flags.count('69')
aln=flags.count('99') + flags.count('73') + flags.count('185') + flags.count('147') + flags.count('83') + flags.count('163') + flags.count('97') + flags.count('137') + flags.count('145') + flags.count('81') + flags.count('161')+ flags.count('177') + flags.count('113') + flags.count('65') + flags.count('129')
ambig=flags.count('337') + flags.count('417') + flags.count('369') + flags.count('433') + flags.count('353') + flags.count('401') + flags.count('371')+ flags.count('355') + flags.count('403') + flags.count('419') + flags.count('339') + flags.count('387') + flags.count('385') + flags.count('323') + flags.count('435') + flags.count('321')
total = unaln + aln
# Get percentages
percent_aln = float (aln) / (total) * 100
percent_unaln = float (unaln) / (total) * 100
percent_ambig = float (ambig) / (total) * 100
# Write the counts to the output.
with open(args.out,'w') as dataout:
dataout.write('Total reads '+str(total)+'\nAligned '+str(aln)+'\nUnaligned '+str(unaln)+'\nAmbiguous '+str(ambig)+'\nPercent aligned '+str(percent_aln)+'\nPercent unaligned '+str(percent_unaln)+'\nPercent ambiguous '+str(percent_ambig))
|
lgpl-3.0
| -7,280,314,419,809,801,000
| 52.581395
| 338
| 0.680122
| false
| 3.191136
| false
| false
| false
|
sbg/sevenbridges-python
|
sevenbridges/meta/collection.py
|
1
|
4097
|
from sevenbridges.errors import PaginationError, SbgError
from sevenbridges.models.compound.volumes.volume_object import VolumeObject
from sevenbridges.models.compound.volumes.volume_prefix import VolumePrefix
from sevenbridges.models.link import Link, VolumeLink
class Collection(list):
"""
Wrapper for SevenBridges pageable resources.
Among the actual collection items it contains information regarding
the total number of entries available in on the server and resource href.
"""
resource = None
def __init__(self, resource, href, total, items, links, api):
super().__init__(items)
self.resource = resource
self.href = href
self.links = links
self._items = items
self._total = total
self._api = api
@property
def total(self):
return int(self._total)
def all(self):
"""
Fetches all available items.
:return: Collection object.
"""
page = self._load(self.href)
while True:
try:
for item in page._items:
yield item
page = page.next_page()
except PaginationError:
break
def _load(self, url):
if self.resource is None:
raise SbgError('Undefined collection resource.')
else:
response = self._api.get(url, append_base=False)
data = response.json()
total = response.headers['x-total-matching-query']
items = [
self.resource(api=self._api, **group)
for group in data['items']
]
links = [Link(**link) for link in data['links']]
href = data['href']
return Collection(
resource=self.resource, href=href, total=total,
items=items, links=links, api=self._api
)
def next_page(self):
"""
Fetches next result set.
:return: Collection object.
"""
for link in self.links:
if link.rel.lower() == 'next':
return self._load(link.href)
raise PaginationError('No more entries.')
def previous_page(self):
"""
Fetches previous result set.
:return: Collection object.
"""
for link in self.links:
if link.rel.lower() == 'prev':
return self._load(link.href)
raise PaginationError('No more entries.')
def __repr__(self):
return (
f'<Collection: total={self.total}, available={len(self._items)}>'
)
class VolumeCollection(Collection):
def __init__(self, href, items, links, prefixes, api):
super().__init__(
VolumeObject, href, 0, items, links, api)
self.prefixes = prefixes
@property
def total(self):
return -1
def next_page(self):
"""
Fetches next result set.
:return: VolumeCollection object.
"""
for link in self.links:
if link.next:
return self._load(link.next)
raise PaginationError('No more entries.')
def previous_page(self):
raise PaginationError('Cannot paginate backwards')
def _load(self, url):
if self.resource is None:
raise SbgError('Undefined collection resource.')
else:
response = self._api.get(url, append_base=False)
data = response.json()
items = [
self.resource(api=self._api, **group) for group in
data['items']
]
prefixes = [
VolumePrefix(api=self._api, **prefix) for prefix in
data['prefixes']
]
links = [VolumeLink(**link) for link in data['links']]
href = data['href']
return VolumeCollection(
href=href, items=items, links=links,
prefixes=prefixes, api=self._api
)
def __repr__(self):
return f'<VolumeCollection: items={len(self._items)}>'
|
apache-2.0
| -4,023,204,058,258,332,700
| 30.037879
| 77
| 0.547962
| false
| 4.46783
| false
| false
| false
|
RNAcentral/rnacentral-webcode
|
rnacentral/portal/management/commands/update_example_locations.py
|
1
|
4551
|
"""
Copyright [2009-2017] EMBL-European Bioinformatics Institute
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 __future__ import print_function
from django.core.management.base import BaseCommand
from portal.models import EnsemblAssembly
from portal.models import SequenceRegion
example_locations = {
'homo_sapiens': {
'chromosome': 'X',
'start': 73819307,
'end': 73856333,
},
'mus_musculus': {
'chromosome': 1,
'start': 86351908,
'end': 86352200,
},
'danio_rerio': {
'chromosome': 9,
'start': 7633910,
'end': 7634210,
},
'bos_taurus': {
'chromosome': 15,
'start': 82197673,
'end': 82197837,
},
'rattus_norvegicus': {
'chromosome': 'X',
'start': 118277628,
'end': 118277850,
},
'felis_catus': {
'chromosome': 'X',
'start': 18058223,
'end': 18058546,
},
'macaca_mulatta': {
'chromosome': 1,
'start': 146238837,
'end': 146238946,
},
'pan_troglodytes': {
'chromosome': 11,
'start': 78369004,
'end': 78369219,
},
'canis_familiaris': {
'chromosome': 19,
'start': 22006909,
'end': 22007119,
},
'gallus_gallus': {
'chromosome': 9,
'start': 15676031,
'end': 15676160,
},
'xenopus_tropicalis': {
'chromosome': 'NC_006839',
'start': 11649,
'end': 11717,
},
'saccharomyces_cerevisiae': {
'chromosome': 'XII',
'start': 856709,
'end': 856919,
},
'schizosaccharomyces_pombe': {
'chromosome': 'I',
'start': 540951,
'end': 544327,
},
'triticum_aestivum': {
'chromosome': '6A',
'start': 100656614,
'end': 100656828,
},
'caenorhabditis_elegans': {
'chromosome': 'III',
'start': 11467363,
'end': 11467705,
},
'drosophila_melanogaster': {
'chromosome': '3R',
'start': 7474331,
'end': 7475217,
},
'bombyx_mori': {
'chromosome': 'scaf16',
'start': 6180018,
'end': 6180422,
},
'anopheles_gambiae': {
'chromosome': '2R',
'start': 34644956,
'end': 34645131,
},
'dictyostelium_discoideum': {
'chromosome': 2,
'start': 7874546,
'end': 7876498,
},
'plasmodium_falciparum': {
'chromosome': 13,
'start': 2796339,
'end': 2798488,
},
'arabidopsis_thaliana': {
'chromosome': 2,
'start': 18819643,
'end': 18822629,
}
}
def update_example_locations():
"""
"""
for assembly in EnsemblAssembly.objects.filter().all():
print(assembly.ensembl_url)
if assembly.ensembl_url in example_locations:
assembly.example_chromosome = example_locations[assembly.ensembl_url]['chromosome']
assembly.example_start = example_locations[assembly.ensembl_url]['start']
assembly.example_end = example_locations[assembly.ensembl_url]['end']
assembly.save()
continue
try:
region = SequenceRegion.objects.filter(assembly_id=assembly.assembly_id).all()[:1].get()
assembly.example_chromosome = region.chromosome
assembly.example_start = region.region_start
assembly.example_end = region.region_stop
print('\t', assembly.assembly_id, region.chromosome, region.region_start, region.region_stop)
assembly.save()
except SequenceRegion.DoesNotExist:
print('No regions found {}'.format(assembly.ensembl_url))
except SequenceRegion.MultipleObjectsReturned:
print('Multiple assemblies found {}'.format(assembly.ensembl_url))
class Command(BaseCommand):
"""
Usage:
python manage.py update_example_locations
"""
def handle(self, *args, **options):
"""Main function, called by django."""
update_example_locations()
|
apache-2.0
| -2,314,792,031,606,948,400
| 27.622642
| 105
| 0.5735
| false
| 3.416667
| false
| false
| false
|
mikelum/pyspeckit
|
pyspeckit/spectrum/readers/read_class.py
|
1
|
67070
|
"""
------------------------
GILDAS CLASS file reader
------------------------
Read a CLASS file into an :class:`pyspeckit.spectrum.ObsBlock`
"""
from __future__ import print_function
from astropy.extern.six.moves import xrange
from astropy.extern.six import iteritems
try:
import astropy.io.fits as pyfits
except ImportError:
import pyfits
import numpy
import numpy as np
from numpy import pi
from astropy import log
# from astropy.time import Time
from astropy import units as u
import pyspeckit
import sys
import re
try:
from astropy.utils.console import ProgressBar
except ImportError:
ProgressBar = lambda x: None
ProgressBar.update = lambda x: None
import struct
import time
# 'range' is needed as a keyword
irange = range
def print_timing(func):
"""
Prints execution time of decorated function.
Included here because CLASS files can take a little while to read;
this should probably be replaced with a progressbar
"""
def wrapper(*arg,**kwargs):
t1 = time.time()
res = func(*arg,**kwargs)
t2 = time.time()
log.info('%s took %0.5g s' % (func.func_name, (t2-t1)))
return res
wrapper.__doc__ = func.__doc__
return wrapper
""" Specification: http://iram.fr/IRAMFR/GILDAS/doc/html/class-html/node58.html """
filetype_dict = {'1A ':'Multiple_IEEE','1 ':'Multiple_Vax','1B ':'Multiple_EEEI',
'2A ':'v2','2 ':'v2','2B ':'v2',
'9A ':'Single_IEEE','9 ':'Single_Vax','9B ':'Single_EEEI'}
fileversion_dict = {'1A ':'v1',
'2A ':'v2'}
record_lengths = {'1A': 512,
'2A': 1024*4}
header_id_numbers = {0: 'USER CODE',
-1: 'COMMENT',
-2: 'GENERAL',
-3: 'POSITION',
-4: 'SPECTRO',
-5: 'BASELINE',
-6: 'HISTORY',
# -8: 'SWITCH',
-10: 'DRIFT',
-14: 'CALIBRATION',
}
header_id_lengths = {-2: 9, # may really be 10?
-3: 17,
-4: 17,
-5: None, # variable length
-6: 3, # variable length
-14: 25,
}
# from packages/classic/lib/classic_mod.f90
filedescv2_nw1=14
"""
GENERAL
integer(kind=obsnum_length) :: num ! [ ] Observation number
integer(kind=4) :: ver ! [ ] Version number
integer(kind=4) :: teles(3) ! [ ] Telescope name
integer(kind=4) :: dobs ! [MJD-60549] Date of observation
integer(kind=4) :: dred ! [MJD-60549] Date of reduction
integer(kind=4) :: typec ! [ code] Type of coordinates
integer(kind=4) :: kind ! [ code] Type of data
integer(kind=4) :: qual ! [ code] Quality of data
integer(kind=4) :: subscan ! [ ] Subscan number
integer(kind=obsnum_length) :: scan ! [ ] Scan number
! Written in the entry
real(kind=8) :: ut ! 1-2 [ rad] UT of observation
real(kind=8) :: st ! 3-4 [ rad] LST of observation
real(kind=4) :: az ! 5 [ rad] Azimuth
real(kind=4) :: el ! 6 [ rad] Elevation
real(kind=4) :: tau ! 7 [neper] Opacity
real(kind=4) :: tsys ! 8 [ K] System temperature
real(kind=4) :: time ! 9 [ s] Integration time
! Not in this section in file
integer(kind=4) :: xunit ! [ code] X unit (if X coordinates section is present)
! NOT in data ---
character(len=12) :: cdobs ! [string] Duplicate of dobs
character(len=12) :: cdred ! [string] Duplicate of dred
"""
keys_lengths = {
'unknown': [
( 'NUM' ,1,'int32'), # Observation number
( 'VER' ,1,'int32'), # Version number
( 'TELES' ,3,'|S12') , # Telescope name
( 'DOBS' ,1,'int32'), # Date of observation
( 'DRED' ,1,'int32'), # Date of reduction
( 'TYPEC' ,1,'int32'), # Type of coordinates
( 'KIND' ,1,'int32'), # Type of data
( 'QUAL' ,1,'int32'), # Quality of data
( 'SCAN' ,1,'int32'), # Scan number
( 'SUBSCAN' ,1,'int32'), # Subscan number
],
'COMMENT': [ # -1
('LTEXT',1,'int32'), # integer(kind=4) :: ltext ! Length of comment
('CTEXT',1024/4,'|S1024'), # character ctext*1024 ! Comment string
],
'GENERAL': [ # -2
( 'UT' ,2,'float64'), # rad UT of observation
( 'ST' ,2,'float64'), # rad LST of observation
( 'AZ' ,1,'float32'), # rad Azimuth
( 'EL' ,1,'float32'), # rad Elevation
( 'TAU' ,1,'float32'), # neper Opacity
( 'TSYS' ,1,'float32'), # K System temperature
( 'TIME' ,1,'float32'), # s Integration time
# XUNIT should not be there?
#( 'XUNIT' ,1,'int32'), # code X unit (if xcoord_sec is present)
] ,
'POSITION': [ # -3
('SOURC',3,'|S12') , # [ ] Source name
('EPOCH',1,'float32'), # [ ] Epoch of coordinates
('LAM' ,2,'float64'), #[rad] Lambda
('BET' ,2,'float64'), #[rad] Beta
('LAMOF',1,'float32'), # [rad] Offset in Lambda
('BETOF',1,'float32'), # [rad] Offset in Beta
('PROJ' ,1,'int32') , # [rad] Projection system
('SL0P' ,1,'float64'), # lambda of descriptive system # MAY NOT EXIST IN OLD CLASS
('SB0P' ,1,'float64'), # beta of descriptive system # MAY NOT EXIST IN OLD CLASS
('SK0P' ,1,'float64'), # angle of descriptive system # MAY NOT EXIST IN OLD CLASS
],
'SPECTRO': [ # -4
#('align' ,1,'int32'), # [ ] Alignment padding
('LINE' ,3,'|S12'), # [ ] Line name
('RESTF' ,2,'float64'), # [ MHz] Rest frequency
('NCHAN' ,1,'int32'), # [ ] Number of channels
('RCHAN' ,1,'float32'), # [ ] Reference channels
('FRES' ,1,'float32'), # [ MHz] Frequency resolution
('FOFF' ,1,'float32'), # [ MHz] Frequency offset
('VRES' ,1,'float32'), # [km/s] Velocity resolution
('VOFF' ,1,'float32'), # [km/s] Velocity at reference channel
('BAD' ,1,'float32'), # [ ] Blanking value
#('ALIGN_1',1,'int32'), # [ ] Alignment padding
('IMAGE' ,2,'float64'), # [ MHz] Image frequency
#('ALIGN_2',1,'int32'), # [ ] Alignment padding
('VTYPE' ,1,'int32'), # [code] Type of velocity
('DOPPLER',2,'float64'), # [ ] Doppler factor = -V/c (CLASS convention)
],
'CALIBRATION': [ # -14
('ALIGN',1,'int32'), # BUFFER (it's a zero - it is not declared in the docs!!!!)
('BEEFF',1,'float32'), # [ ] Beam efficiency
('FOEFF',1,'float32'), # [ ] Forward efficiency
('GAINI',1,'float32'), # [ ] Image/Signal gain ratio
('H2OMM',1,'float32'), # [ mm] Water vapor content
('PAMB',1,'float32'), # [ hPa] Ambient pressure
('TAMB',1,'float32'), # [ K] Ambient temperature
('TATMS',1,'float32'), # [ K] Atmosphere temp. in signal band
('TCHOP',1,'float32'), # [ K] Chopper temperature
('TCOLD',1,'float32'), # [ K] Cold load temperature
('TAUS',1,'float32'), # [neper] Opacity in signal band
('TAUI',1,'float32'), # [neper] Opacity in image band
('TATMI',1,'float32'), # [ K] Atmosphere temp. in image band
('TREC',1,'float32'), # [ K] Receiver temperature
('CMODE',1,'int32'), # [ code] Calibration mode
('ATFAC',1,'float32'), # [ ] Applied calibration factor
('ALTI',1,'float32'), # [ m] Site elevation
('COUNT',3,'3float32'), # [count] Power of Atm., Chopp., Cold
('LCALOF',1,'float32'), # [ rad] Longitude offset for sky measurement
('BCALOF',1,'float32'), # [ rad] Latitude offset for sky measurement
('GEOLONG',1,'float64'), # [ rad] Geographic longitude of observatory # MAY NOT EXIST IN OLD CLASS
('GEOLAT',1,'float64'), # [ rad] Geographic latitude of observatory # MAY NOT EXIST IN OLD CLASS
],
'BASELINE':[
('DEG',1,'int32'), #! [ ] Degree of last baseline
('SIGFI',1,'float32'), #! [Int. unit] Sigma
('AIRE',1,'float32'), #! [Int. unit] Area under windows
('NWIND',1,'int32'), #! [ ] Number of line windows
# WARNING: These should probably have 'n', the second digit, = NWIND
# The docs are really unclear about this, they say "W1(MWIND)"
('W1MWIND',1,'float32'), #! [km/s] Lower limits of windows
('W2MWIND',1,'float32'), #! [km/s] Upper limits of windows
('SINUS',3,'float32'), #![] Sinus baseline results
],
'DRIFT':[ # 16?
('FREQ',1,'float64') , #! [ MHz] Rest frequency real(kind=8) ::
('WIDTH',1,'float32'), #! [ MHz] Bandwidth real(kind=4) ::
('NPOIN',1,'int32') , #! [ ] Number of data points integer(kind=4) ::
('RPOIN',1,'float32'), #! [ ] Reference point real(kind=4) ::
('TREF',1,'float32') , #! [ ?] Time at reference real(kind=4) ::
('AREF',1,'float32') , #! [ rad] Angular offset at ref. real(kind=4) ::
('APOS',1,'float32') , #! [ rad] Position angle of drift real(kind=4) ::
('TRES',1,'float32') , #! [ ?] Time resolution real(kind=4) ::
('ARES',1,'float32') , #! [ rad] Angular resolution real(kind=4) ::
('BAD',1,'float32') , #! [ ] Blanking value real(kind=4) ::
('CTYPE',1,'int32') , #! [code] Type of offsets integer(kind=4) ::
('CIMAG',1,'float64'), #! [ MHz] Image frequency real(kind=8) ::
('COLLA',1,'float32'), #! [ ?] Collimation error Az real(kind=4) ::
('COLLE',1,'float32'), #! [ ?] Collimation error El real(kind=4) ::
],
}
def _read_bytes(f, n):
'''Read the next `n` bytes (from idlsave)'''
return f.read(n)
"""
Warning: UNCLEAR what endianness should be!
Numpy seemed to get it right, and I think numpy assumes NATIVE endianness
"""
def _read_byte(f):
'''Read a single byte (from idlsave)'''
return numpy.uint8(struct.unpack('=B', f.read(4)[:1])[0])
def _read_int16(f):
'''Read a signed 16-bit integer (from idlsave)'''
return numpy.int16(struct.unpack('=h', f.read(4)[2:4])[0])
def _read_int32(f):
'''Read a signed 32-bit integer (from idlsave)'''
return numpy.int32(struct.unpack('=i', f.read(4))[0])
def _read_int64(f):
'''Read a signed 64-bit integer '''
return numpy.int64(struct.unpack('=q', f.read(8))[0])
def _read_float32(f):
'''Read a 32-bit float (from idlsave)'''
return numpy.float32(struct.unpack('=f', f.read(4))[0])
def _align_32(f):
'''Align to the next 32-bit position in a file (from idlsave)'''
pos = f.tell()
if pos % 4 != 0:
f.seek(pos + 4 - pos % 4)
return
def _read_word(f,length):
if length > 0:
chars = _read_bytes(f, length)
_align_32(f)
else:
chars = None
return chars
def _read_int(f):
return struct.unpack('i',f.read(4))
def is_ascii(s):
try:
s.decode('ascii')
return True
except UnicodeDecodeError:
return False
except UnicodeEncodeError:
return False
def is_all_null(s):
return all(x=='\x00' for x in s)
"""
from clic_file.f90: v1, v2
integer(kind=4) :: bloc ! 1 : observation address [records] integer(kind=8) :: bloc ! 1- 2: observation address [records] integer(kind=4) :: bloc ! 1 : block read from index
integer(kind=4) :: num ! 2 : observation number integer(kind=4) :: word ! 3 : address offset [4-bytes] integer(kind=4) :: num ! 2 : number read
integer(kind=4) :: ver ! 3 : observation version integer(kind=4) :: ver ! 4 : observation version integer(kind=4) :: ver ! 3 : version read from index
integer(kind=4) :: sourc(3) ! 4- 6: source name integer(kind=8) :: num ! 5- 6: observation number character(len=12) :: csour ! 4- 6: source read from index
integer(kind=4) :: line(3) ! 7- 9: line name integer(kind=4) :: sourc(3) ! 7- 9: source name character(len=12) :: cline ! 7- 9: line read from index
integer(kind=4) :: teles(3) ! 10-12: telescope name integer(kind=4) :: line(3) ! 10-12: line name character(len=12) :: ctele ! 10-12: telescope read from index
integer(kind=4) :: dobs ! 13 : observation date [class_date] integer(kind=4) :: teles(3) ! 13-15: telescope name integer(kind=4) :: dobs ! 13 : date obs. read from index
integer(kind=4) :: dred ! 14 : reduction date [class_date] integer(kind=4) :: dobs ! 16 : observation date [class_date] integer(kind=4) :: dred ! 14 : date red. read from index
real(kind=4) :: off1 ! 15 : lambda offset [radian] integer(kind=4) :: dred ! 17 : reduction date [class_date] real(kind=4) :: off1 ! 15 : read offset 1
real(kind=4) :: off2 ! 16 : beta offset [radian] real(kind=4) :: off1 ! 18 : lambda offset [radian] real(kind=4) :: off2 ! 16 : read offset 2
integer(kind=4) :: typec ! 17 : coordinates types real(kind=4) :: off2 ! 19 : beta offset [radian] integer(kind=4) :: type ! 17 : type of read offsets
integer(kind=4) :: kind ! 18 : data kind integer(kind=4) :: typec ! 20 : coordinates types integer(kind=4) :: kind ! 18 : type of observation
integer(kind=4) :: qual ! 19 : data quality integer(kind=4) :: kind ! 21 : data kind integer(kind=4) :: qual ! 19 : Quality read from index
integer(kind=4) :: scan ! 20 : scan number integer(kind=4) :: qual ! 22 : data quality integer(kind=4) :: scan ! 20 : Scan number read from index
integer(kind=4) :: proc ! 21 : procedure type integer(kind=4) :: scan ! 23 : scan number real(kind=4) :: posa ! 21 : Position angle
integer(kind=4) :: itype ! 22 : observation type integer(kind=4) :: proc ! 24 : procedure type integer(kind=4) :: subscan ! 22 : Subscan number
real(kind=4) :: houra ! 23 : hour angle [radian] integer(kind=4) :: itype ! 25 : observation type integer(kind=4) :: pad(10) ! 23-32: Pad to 32 words
integer(kind=4) :: project ! 24 : project name real(kind=4) :: houra ! 26 : hour angle [radian]
integer(kind=4) :: pad1 ! 25 : unused word integer(kind=4) :: project(2) ! 27 : project name
integer(kind=4) :: bpc ! 26 : baseline bandpass cal status integer(kind=4) :: bpc ! 29 : baseline bandpass cal status
integer(kind=4) :: ic ! 27 : instrumental cal status integer(kind=4) :: ic ! 30 : instrumental cal status
integer(kind=4) :: recei ! 28 : receiver number integer(kind=4) :: recei ! 31 : receiver number
real(kind=4) :: ut ! 29 : UT [s] real(kind=4) :: ut ! 32 : UT [s]
integer(kind=4) :: pad2(3) ! 30-32: padding to 32 4-bytes word
equivalently
integer(kind=obsnum_length) :: num ! [ ] Observation number
integer(kind=4) :: ver ! [ ] Version number
integer(kind=4) :: teles(3) ! [ ] Telescope name
integer(kind=4) :: dobs ! [MJD-60549] Date of observation
integer(kind=4) :: dred ! [MJD-60549] Date of reduction
integer(kind=4) :: typec ! [ code] Type of coordinates
integer(kind=4) :: kind ! [ code] Type of data
integer(kind=4) :: qual ! [ code] Quality of data
integer(kind=4) :: subscan ! [ ] Subscan number
integer(kind=obsnum_length) :: scan ! [ ] Scan number
"""
"""
index.f90:
call conv%read%i8(data(1), indl%bloc, 1) ! bloc
call conv%read%i4(data(3), indl%word, 1) ! word
call conv%read%i8(data(4), indl%num, 1) ! num
call conv%read%i4(data(6), indl%ver, 1) ! ver
call conv%read%cc(data(7), indl%csour, 3) ! csour
call conv%read%cc(data(10),indl%cline, 3) ! cline
call conv%read%cc(data(13),indl%ctele, 3) ! ctele
call conv%read%i4(data(16),indl%dobs, 1) ! dobs
call conv%read%i4(data(17),indl%dred, 1) ! dred
call conv%read%r4(data(18),indl%off1, 1) ! off1
call conv%read%r4(data(19),indl%off2, 1) ! off2
call conv%read%i4(data(20),indl%type, 1) ! type
call conv%read%i4(data(21),indl%kind, 1) ! kind
call conv%read%i4(data(22),indl%qual, 1) ! qual
call conv%read%r4(data(23),indl%posa, 1) ! posa
call conv%read%i8(data(24),indl%scan, 1) ! scan
call conv%read%i4(data(26),indl%subscan,1) ! subscan
if (isv3) then
call conv%read%r8(data(27),indl%ut, 1) ! ut
else
"""
def _read_indices(f, file_description):
#if file_description['version'] in (1,2):
# extension_positions = (file_description['aex']-1)*file_description['reclen']*4
# all_indices = {extension:
# [_read_index(f,
# filetype=file_description['version'],
# entry=ii,
# #position=position,
# )
# for ii in range(file_description['lex1'])]
# for extension,position in enumerate(extension_positions)
# if position > 0
# }
#elif file_description['version'] == 1:
extension_positions = ((file_description['aex'].astype('int64')-1)
*file_description['reclen']*4)
all_indices = [_read_index(f,
filetype=file_description['version'],
# 1-indexed files
entry_number=ii+1,
file_description=file_description,
)
for ii in range(file_description['xnext']-1)]
#else:
# raise ValueError("Invalid file version {0}".format(file_description['version']))
return all_indices
def _find_index(entry_number, file_description, return_position=False):
if file_description['gex'] == 10:
kex=(entry_number-1)/file_description['lex1'] + 1
else:
# exponential growth:
#kex = gi8_dicho(file_description['nex'], file_description['lexn'], entry_number) - 1
kex = len([xx for xx in file_description['lexn'] if xx<entry_number])
ken = entry_number - file_description['lexn'][kex-1]
#! Find ken (relative entry number in the extension, starts from 1)
#ken = entry_num - file%desc%lexn(kex-1)
kb = ((ken-1)*file_description['lind'])/file_description['reclen']
#kb = ((ken-1)*file%desc%lind)/file%desc%reclen ! In the extension, the
# ! relative record position (as an offset, starts from 0) where the
# ! Entry Index starts. NB: there can be a non-integer number of Entry
# ! Indexes per record
# Subtract 1: 'aex' is 1-indexed
kbl = (file_description['aex'][kex-1]+kb)-1
# kbl = file%desc%aex(kex)+kb ! The absolute record number where the Entry Index goes
k = ((ken-1)*file_description['lind']) % file_description['reclen']
#k = mod((ken-1)*file%desc%lind,file%desc%reclen)+1 ! = in the record, the
# ! first word of the Entry Index of the entry number 'entry_num'
if return_position:
return (kbl*file_description['reclen']+k)*4
else:
return kbl,k
def _read_index(f, filetype='v1', DEBUG=False, clic=False, position=None,
entry_number=None, file_description=None):
if position is not None:
f.seek(position)
if entry_number is not None:
indpos = _find_index(entry_number, file_description, return_position=True)
f.seek(indpos)
x0 = f.tell()
if filetype in ('1A ','v1', 1):
log.debug('Index filetype 1A')
index = {
"XBLOC":_read_int32(f),
"XNUM":_read_int32(f),
"XVER":_read_int32(f),
"XSOURC":_read_word(f,12),
"XLINE":_read_word(f,12),
"XTEL":_read_word(f,12),
"XDOBS":_read_int32(f),
"XDRED":_read_int32(f),
"XOFF1":_read_float32(f),# first offset (real, radians)
"XOFF2":_read_float32(f),# second offset (real, radians)
"XTYPE":_read_int32(f),# coordinate system ('EQ'', 'GA', 'HO')
"XKIND":_read_int32(f),# Kind of observation (0: spectral, 1: continuum, )
"XQUAL":_read_int32(f),# Quality (0-9)
"XSCAN":_read_int32(f),# Scan number
}
index['BLOC'] = index['XBLOC'] # v2 compatibility
index['WORD'] = 1 # v2 compatibility
index['SOURC'] = index['CSOUR'] = index['XSOURC']
index['DOBS'] = index['CDOBS'] = index['XDOBS']
index['CTELE'] = index['XTEL']
index['LINE'] = index['XLINE']
index['OFF1'] = index['XOFF1']
index['OFF2'] = index['XOFF2']
index['QUAL'] = index['XQUAL']
index['SCAN'] = index['XSCAN']
index['KIND'] = index['XKIND']
if clic: # use header set up in clic
nextchunk = {
"XPROC":_read_int32(f),# "procedure type"
"XITYPE":_read_int32(f),#
"XHOURANG":_read_float32(f),#
"XPROJNAME":_read_int32(f),#
"XPAD1":_read_int32(f),
"XBPC" :_read_int32(f),
"XIC" :_read_int32(f),
"XRECEI" :_read_int32(f),
"XUT":_read_float32(f),
"XPAD2":numpy.fromfile(f,count=3,dtype='int32') # BLANK is NOT ALLOWED!!! It is a special KW
}
else:
nextchunk = {"XPOSA":_read_float32(f),
"XSUBSCAN":_read_int32(f),
'XPAD2': numpy.fromfile(f,count=10,dtype='int32'),
}
nextchunk['SUBSCAN'] = nextchunk['XSUBSCAN']
nextchunk['POSA'] = nextchunk['XPOSA']
index.update(nextchunk)
if (f.tell() - x0 != 128):
missed_bits = (f.tell()-x0)
X = f.read(128-missed_bits)
if DEBUG: print("read_index missed %i bits: %s" % (128-missed_bits,X))
#raise IndexError("read_index did not successfully read 128 bytes at %i. Read %i bytes." % (x0,f.tell()-x0))
if any(not is_ascii(index[x]) for x in ('XSOURC','XLINE','XTEL')):
raise ValueError("Invalid index read from {0}.".format(x0))
elif filetype in ('2A ','v2', 2):
log.debug('Index filetype 2A')
index = {
"BLOC" : _read_int64(f) , #(data(1), 1) ! bloc
"WORD" : _read_int32(f) , #(data(3), 1) ! word
"NUM" : _read_int64(f) , #(data(4), 1) ! num
"VER" : _read_int32(f) , #(data(6), 1) ! ver
"CSOUR" : _read_word(f,12), #(data(7), 3) ! csour
"CLINE" : _read_word(f,12), #(data(10), 3) ! cline
"CTELE" : _read_word(f,12), #(data(13), 3) ! ctele
"DOBS" : _read_int32(f) , #(data(16), 1) ! dobs
"DRED" : _read_int32(f) , #(data(17), 1) ! dred
"OFF1" : _read_float32(f), #(data(18), 1) ! off1
"OFF2" : _read_float32(f), #(data(19), 1) ! off2
"TYPE" : _read_int32(f) , #(data(20), 1) ! type
"KIND" : _read_int32(f) , #(data(21), 1) ! kind
"QUAL" : _read_int32(f) , #(data(22), 1) ! qual
"POSA" : _read_float32(f), #(data(23), 1) ! posa
"SCAN" : _read_int64(f) , #(data(24), 1) ! scan
"SUBSCAN": _read_int32(f) , #(data(26), 1) ! subscan
}
#last24bits = f.read(24)
#log.debug("Read 24 bits: '{0}'".format(last24bits))
if any((is_all_null(index[x]) or not is_ascii(index[x]))
for x in ('CSOUR','CLINE','CTELE')):
raise ValueError("Invalid index read from {0}.".format(x0))
index['SOURC'] = index['XSOURC'] = index['CSOUR']
index['LINE'] = index['XLINE'] = index['CLINE']
index['XKIND'] = index['KIND']
try:
index['DOBS'] = index['XDOBS'] = index['CDOBS']
except KeyError:
index['CDOBS'] = index['XDOBS'] = index['DOBS']
else:
raise NotImplementedError("Filetype {0} not implemented.".format(filetype))
# from kernel/lib/gsys/date.f90: gag_julda
class_dobs = index['DOBS']
index['DOBS'] = ((class_dobs + 365*2025)/365.2425 + 1)
# SLOW
#index['DATEOBS'] = Time(index['DOBS'], format='jyear')
#index['DATEOBSS'] = index['DATEOBS'].iso
log.debug("Indexing finished at {0}".format(f.tell()))
return index
def _read_header(f, type=0, position=None):
"""
Read a header entry from a CLASS file
(helper function)
"""
if position is not None:
f.seek(position)
if type in keys_lengths:
hdrsec = [(x[0],numpy.fromfile(f,count=1,dtype=x[2])[0])
for x in keys_lengths[type]]
return dict(hdrsec)
else:
return {}
raise ValueError("Unrecognized type {0}".format(type))
def _read_first_record(f):
f.seek(0)
filetype = f.read(4)
if fileversion_dict[filetype] == 'v1':
return _read_first_record_v1(f)
else:
return _read_first_record_v2(f)
def _read_first_record_v1(f, record_length_words=128):
r"""
Position & Parameter & Fortran Kind & Purpose \\
\hline
1 & {\tt code} & Character*4 & File code \\
2 & {\tt next} & Integer*4 & Next free record \\
3 & {\tt lex} & Integer*4 & Length of first extension (number of entries) \\
4 & {\tt nex} & Integer*4 & Number of extensions \\
5 & {\tt xnext} & Integer*4 & Next available entry number \\
6:2*{\tt reclen} & {\tt ex(:)} & Integer*4 & Array of extension addresses
from classic_mod.f90:
integer(kind=4) :: code ! 1 File code
integer(kind=4) :: next ! 2 Next free record
integer(kind=4) :: lex ! 3 Extension length (number of entries)
integer(kind=4) :: nex ! 4 Number of extensions
integer(kind=4) :: xnext ! 5 Next available entry number
integer(kind=4) :: aex(mex_v1) ! 6:256 Extension addresses
from old (<dec2013) class, file.f90:
read(ilun,rec=1,err=11,iostat=ier) ibx%code,ibx%next, &
& ibx%ilex,ibx%imex,ibx%xnext
also uses filedesc_v1tov2 from classic/lib/file.f90
"""
# OLD NOTES
# hdr = header
# hdr.update(obshead) # re-overwrite things
# hdr.update({'OBSNUM':obsnum,'RECNUM':spcount})
# hdr.update({'RA':hdr['LAM']/pi*180,'DEC':hdr['BET']/pi*180})
# hdr.update({'RAoff':hdr['LAMOF']/pi*180,'DECoff':hdr['BETOF']/pi*180})
# hdr.update({'OBJECT':hdr['SOURC'].strip()})
# hdr.update({'BUNIT':'Tastar'})
# hdr.update({'EXPOSURE':hdr['TIME']})
f.seek(0)
file_description = {
'code': f.read(4),
'next': _read_int32(f),
'lex': _read_int32(f),
'nex': _read_int32(f),
'xnext': _read_int32(f),
'gex': 10.,
'vind': 1, # classic_vind_v1 packages/classic/lib/classic_mod.f90
'version': 1,
'nextrec': 3,
'nextword': 1,
'lind': 32, #classic_lind_v1 packages/classic/lib/classic_mod.f90
'kind': 'unknown',
'flags': 0,
}
file_description['reclen'] = record_length_words # should be 128w = 512 bytes
ex = np.fromfile(f, count=(record_length_words*2-5), dtype='int32')
file_description['ex'] = ex[ex!=0]
file_description['nextrec'] = file_description['next'] # this can't be...
file_description['lex1'] = file_description['lex'] # number of entries
file_description['lexn'] = (np.arange(file_description['nex']+1) *
file_description['lex1'])
file_description['nentries'] = np.sum(file_description['lexn'])
file_description['aex'] = file_description['ex'][:file_description['nex']]
#file_description['version'] = fileversion_dict[file_description['code']]
assert f.tell() == 1024
# Something is not quite right with the 'ex' parsing
#assert len(file_description['ex']) == file_description['nex']
return file_description
def _read_first_record_v2(f):
r""" packages/classic/lib/file.f90
Position & Parameter & Fortran Kind & Purpose & Unit \\
\hline
1 & {\tt code} & Character*4 & File code & - \\
2 & {\tt reclen} & Integer*4 & Record length & words \\
3 & {\tt kind} & Integer*4 & File kind & - \\
4 & {\tt vind} & Integer*4 & Index version & - \\
5 & {\tt lind} & Integer*4 & Index length & words \\
6 & {\tt flags} & Integer*4 & Bit flags. \#1: single or multiple, & - \\
& & & \#2-32: provision (0-filled) & \\
\hline
7:8 & {\tt xnext} & Integer*8 & Next available entry number & - \\
9:10 & {\tt nextrec} & Integer*8 & Next record which contains free space & record \\
11 & {\tt nextword} & Integer*4 & Next free word in this record & word \\
\hline
12 & {\tt lex1} & Integer*4 & Length of first extension index & entries \\
13 & {\tt nex} & Integer*4 & Number of extensions & - \\
14 & {\tt gex} & Integer*4 & Extension growth rule & - \\
15:{\tt reclen} & {\tt aex(:)} & Integer*8 & Array of extension addresses & record
"""
f.seek(0)
file_description = {
'code': f.read(4),
'reclen': _read_int32(f),
'kind': _read_int32(f),
'vind': _read_int32(f),
'lind': _read_int32(f),
'flags': _read_int32(f),
'xnext': _read_int64(f),
'nextrec': _read_int64(f),
'nextword': _read_int32(f),
'lex1': _read_int32(f),
'nex': _read_int32(f),
'gex': _read_int32(f),
}
file_description['lexn'] = [0]
if file_description['gex'] == 10:
for ii in range(1, file_description['nex']+1):
file_description['lexn'].append(file_description['lexn'][-1]+file_description['lex1'])
else:
#! Exponential growth. Only growth with mantissa 2.0 is supported
for ii in range(1, file_description['nex']):
# I don't know what the fortran does here!!!
# ahh, maybe 2_8 means int(2, dtype='int64')
nent = int(file_description['lex1'] * 2**(ii-1))
#nent = int(file%desc%lex1,kind=8) * 2_8**(iex-1)
file_description['lexn'].append(file_description['lexn'][-1]+nent)
#file%desc%lexn(iex) = file%desc%lexn(iex-1) + nent
file_description['nentries'] = np.sum(file_description['lexn'])
record_length_words = file_description['reclen']
aex = numpy.fromfile(f, count=(record_length_words-15)/2, dtype='int64')
file_description['aex'] = aex[aex!=0]
assert len(file_description['aex']) == file_description['nex']
file_description['version'] = 2
return file_description
def gi8_dicho(ninp,lexn,xval,ceil=True):
"""
! @ public
! Find ival such as
! X(ival-1) < xval <= X(ival) (ceiling mode)
! or
! X(ival) <= xval < X(ival+1) (floor mode)
! for input data ordered. Use a dichotomic search for that.
call gi8_dicho(nex,file%desc%lexn,entry_num,.true.,kex,error)
"""
#integer(kind=size_length), intent(in) :: np ! Number of input points
#integer(kind=8), intent(in) :: x(np) ! Input ordered Values
#integer(kind=8), intent(in) :: xval ! The value we search for
#logical, intent(in) :: ceil ! Ceiling or floor mode?
#integer(kind=size_length), intent(out) :: ival ! Position in the array
#logical, intent(inout) :: error ! Logical error flag
iinf = 1
isup = ninp
#! Ceiling mode
while isup > (iinf+1):
imid = int(np.floor((isup + iinf)/2.))
if (lexn[imid-1] < xval):
iinf = imid
else:
isup = imid
ival = isup
return ival
def _read_obshead(f, file_description, position=None):
if file_description['version'] == 1:
return _read_obshead_v1(f, position=position)
if file_description['version'] == 2:
return _read_obshead_v2(f, position=position)
else:
raise ValueError("Invalid file version {0}.".
format(file_description['version']))
def _read_obshead_v2(f, position=None):
"""
! Version 2 (public)
integer(kind=4), parameter :: entrydescv2_nw1=11 ! Number of words, in 1st part
integer(kind=4), parameter :: entrydescv2_nw2=5 ! Number of words for 1 section in 2nd part
type classic_entrydesc_t
sequence
integer(kind=4) :: code ! 1 : code observation icode
integer(kind=4) :: version ! 2 : observation version
integer(kind=4) :: nsec ! 3 : number of sections
integer(kind=4) :: pad1 ! - : memory padding (not in data)
integer(kind=8) :: nword ! 4- 5: number of words
integer(kind=8) :: adata ! 6- 7: data address
integer(kind=8) :: ldata ! 8- 9: data length
integer(kind=8) :: xnum ! 10-11: entry number
! Out of the 'sequence' block:
integer(kind=4) :: msec ! Not in data: maximum number of sections the
! Observation Index can hold
integer(kind=4) :: pad2 ! Memory padding for 8 bytes alignment
integer(kind=4) :: seciden(classic_maxsec) ! Section Numbers (on disk: 1 to ed%nsec)
integer(kind=8) :: secleng(classic_maxsec) ! Section Lengths (on disk: 1 to ed%nsec)
integer(kind=8) :: secaddr(classic_maxsec) ! Section Addresses (on disk: 1 to ed%nsec)
end type classic_entrydesc_t
"""
if position is not None:
f.seek(position)
else:
position = f.tell()
IDcode = f.read(4)
if IDcode.strip() != '2':
raise IndexError("Observation Header reading failure at {0}. "
"Record does not appear to be an observation header.".
format(position))
f.seek(position)
entrydescv2_nw1=11
entrydescv2_nw2=5
obshead = {
'CODE': f.read(4),
'VERSION': _read_int32(f),
'NSEC': _read_int32(f),
#'_blank': _read_int32(f),
'NWORD': _read_int64(f),
'ADATA': _read_int64(f),
'LDATA': _read_int64(f),
'XNUM': _read_int64(f),
#'MSEC': _read_int32(f),
#'_blank2': _read_int32(f),
}
section_numbers = np.fromfile(f, count=obshead['NSEC'], dtype='int32')
section_lengths = np.fromfile(f, count=obshead['NSEC'], dtype='int64')
section_addresses = np.fromfile(f, count=obshead['NSEC'], dtype='int64')
return obshead['XNUM'],obshead,dict(zip(section_numbers,section_addresses))
def _read_obshead_v1(f, position=None, verbose=False):
"""
Read the observation header of a CLASS file
(helper function for read_class; should not be used independently)
"""
if position is not None:
f.seek(position)
IDcode = f.read(4)
if IDcode.strip() != '2':
raise IndexError("Observation Header reading failure at {0}. "
"Record does not appear to be an observation header.".
format(f.tell() - 4))
(nblocks, nbyteob, data_address, nheaders, data_length, obindex, nsec,
obsnum) = numpy.fromfile(f, count=8, dtype='int32')
if verbose:
print("nblocks,nbyteob,data_address,data_length,nheaders,obindex,nsec,obsnum",nblocks,nbyteob,data_address,data_length,nheaders,obindex,nsec,obsnum)
print("DATA_LENGTH: ",data_length)
seccodes = numpy.fromfile(f,count=nsec,dtype='int32')
# Documentation says addresses then length: It is apparently wrong
seclen = numpy.fromfile(f,count=nsec,dtype='int32')
secaddr = numpy.fromfile(f,count=nsec,dtype='int32')
if verbose: print("Section codes, addresses, lengths: ",seccodes,secaddr,seclen)
hdr = {'NBLOCKS':nblocks, 'NBYTEOB':nbyteob, 'DATAADDR':data_address,
'DATALEN':data_length, 'NHEADERS':nheaders, 'OBINDEX':obindex,
'NSEC':nsec, 'OBSNUM':obsnum}
#return obsnum,seccodes
return obsnum,hdr,dict(zip(seccodes,secaddr))
# THIS IS IN READ_OBSHEAD!!!
# def _read_preheader(f):
# """
# Not entirely clear what this is, but it is stuff that precedes the actual data
#
# Looks something like this:
# array([ 1, -2, -3, -4, -14,
# 9, 17, 18, 25, 55,
# 64, 81, 99, -1179344801, 979657591,
#
# -2, -3, -4, -14 indicate the 4 header types
# 9,17,18,25 *MAY* indicate the number of bytes in each
#
#
# HOW is it indicated how many entries there are?
# """
# # 13 comes from counting 1, -2,....99 above
# numbers = np.fromfile(f, count=13, dtype='int32')
# sections = [n for n in numbers if n in header_id_numbers]
# return sections
def downsample_1d(myarr,factor,estimator=np.mean, weight=None):
"""
Downsample a 1D array by averaging over *factor* pixels.
Crops right side if the shape is not a multiple of factor.
This code is pure numpy and should be fast.
keywords:
estimator - default to mean. You can downsample by summing or
something else if you want a different estimator
(e.g., downsampling error: you want to sum & divide by sqrt(n))
weight: np.ndarray
An array of weights to use for the downsampling. If None,
assumes uniform 1
"""
if myarr.ndim != 1:
raise ValueError("Only works on 1d data. Says so in the title.")
xs = myarr.size
crarr = myarr[:xs-(xs % int(factor))]
if weight is None:
dsarr = estimator(np.concatenate([[crarr[i::factor] for i in
range(factor)]]),axis=0)
else:
dsarr = estimator(np.concatenate([[crarr[i::factor]*weight[i::factor] for i in
range(factor)]]),axis=0)
warr = estimator(np.concatenate([[weight[i::factor] for i in
range(factor)]]),axis=0)
dsarr = dsarr/warr
return dsarr
# unit test
def test_downsample1d():
data = np.arange(10)
weight = np.ones(10)
weight[5]=0
assert np.all(downsample_1d(data, 2, weight=weight, estimator=np.mean) ==
np.array([ 0.5, 2.5, 4. , 6.5, 8.5]))
def read_observation(f, obsid, file_description=None, indices=None,
my_memmap=None, memmap=True):
if isinstance(f, str):
f = open(f,'rb')
opened = True
if memmap:
my_memmap = numpy.memmap(filename, offset=0, dtype='float32',
mode='r')
else:
my_memmap = None
elif my_memmap is None and memmap:
raise ValueError("Must pass in a memmap object if passing in a file object.")
else:
opened = False
if file_description is None:
file_description = _read_first_record(f)
if indices is None:
indices = _read_indices(f, file_description)
index = indices[obsid]
obs_position = (index['BLOC']-1)*file_description['reclen']*4 + (index['WORD']-1)*4
obsnum,obshead,sections = _read_obshead(f, file_description,
position=obs_position)
header = obshead
datastart = 0
for section_id,section_address in iteritems(sections):
# Section addresses are 1-indexed byte addresses
# in the current "block"
sec_position = obs_position + (section_address-1)*4
temp_hdr = _read_header(f, type=header_id_numbers[section_id],
position=sec_position)
header.update(temp_hdr)
datastart = max(datastart,f.tell())
hdr = header
hdr.update(obshead) # re-overwrite things
hdr.update({'OBSNUM':obsnum,'RECNUM':obsid})
hdr.update({'RA':hdr['LAM']/pi*180,'DEC':hdr['BET']/pi*180})
hdr.update({'RAoff':hdr['LAMOF']/pi*180,'DECoff':hdr['BETOF']/pi*180})
hdr.update({'OBJECT':hdr['SOURC'].strip()})
hdr.update({'BUNIT':'Tastar'})
hdr.update({'EXPOSURE':float(hdr['TIME'])})
hdr['HDRSTART'] = obs_position
hdr['DATASTART'] = datastart
hdr.update(indices[obsid])
# Apparently the data are still valid in this case?
#if hdr['XNUM'] != obsid+1:
# log.error("The spectrum read was {0} but {1} was requested.".
# format(hdr['XNUM']-1, obsid))
if hdr['KIND'] == 1: # continuum
nchan = hdr['NPOIN']
elif 'NCHAN' in hdr:
nchan = hdr['NCHAN']
else:
log.error("No NCHAN in header. This is not a spectrum.")
import ipdb; ipdb.set_trace()
# There may be a 1-channel offset? CHECK!!!
# (changed by 1 pixel - October 14, 2014)
# (changed back - October 21, 2014 - I think the ends are just bad, but not
# zero.)
f.seek(datastart-1)
spec = _read_spectrum(f, position=datastart-1, nchan=nchan,
memmap=memmap, my_memmap=my_memmap)
if opened:
f.close()
return spec, hdr
def _read_spectrum(f, position, nchan, my_memmap=None, memmap=True):
if position != f.tell():
log.warn("Reading data from {0}, but the file is wound "
"to {1}.".format(position, f.tell()))
if memmap:
here = position
#spectrum = numpy.memmap(filename, offset=here, dtype='float32',
# mode='r', shape=(nchan,))
spectrum = my_memmap[here/4:here/4+nchan]
f.seek(here+nchan*4)
else:
f.seek(position)
spectrum = numpy.fromfile(f,count=nchan,dtype='float32')
return spectrum
def _spectrum_from_header(fileobj, header, memmap=None):
return _read_spectrum(fileobj, position=header['DATASTART'],
nchan=header['NCHAN'] if 'NCHAN' in hdr else hdr['NPOIN'],
my_memmap=memmap)
def clean_header(header):
newheader = {}
for k in header:
if not isinstance(header[k], (int, float, str)):
if isinstance(header[k], np.ndarray) and header[k].size > 1:
if header[k].size > 10:
raise ValueError("Large array being put in header. That's no good. key={0}".format(k))
for ii,val in enumerate(header[k]):
newheader[k[:7]+str(ii)] = val
else:
newheader[k[:8]] = str(header[k])
else:
newheader[k[:8]] = header[k]
return newheader
class ClassObject(object):
def __init__(self, filename, verbose=False):
t0 = time.time()
self._file = open(filename, 'rb')
self.file_description = _read_first_record(self._file)
self.allind = _read_indices(self._file, self.file_description)
self._data = np.memmap(self._file, dtype='float32', mode='r')
if verbose: log.info("Setting _spectra")
self._spectra = LazyItem(self)
t1 = time.time()
if verbose: log.info("Setting posang. t={0}".format(t1-t0))
self.set_posang()
t2 = time.time()
if verbose: log.info("Identifying otf scans. t={0}".format(t2-t1))
self._identify_otf_scans(verbose=verbose)
t3 = time.time()
#self._load_all_spectra()
if verbose:
log.info("Loaded CLASS object with {3} indices. Time breakdown:"
" {0}s for indices, "
"{1}s for posang, and {2}s for OTF scan identification"
.format(t1-t0, t2-t1, t3-t2, len(self.allind)))
def __repr__(self):
s = "\n".join(["{k}: {v}".format(k=k,v=v)
for k,v in iteritems(self.getinfo())])
return "ClassObject({id}) with {nspec} entries\n".format(id=id(self),
nspec=len(self.allind)) + s
def getinfo(self, allsources=False):
info = dict(
tels = self.tels,
lines = self.lines,
scans = self.scans,
sources = self.sources if allsources else self.sci_sources,
)
return info
def set_posang(self):
h0 = self.headers[0]
for h in self.headers:
dx = h['OFF1'] - h0['OFF1']
dy = h['OFF2'] - h0['OFF2']
h['COMPPOSA'] = np.arctan2(dy,dx)*180/np.pi
h0 = h
def _identify_otf_scans(self, verbose=False):
h0 = self.allind[0]
st = 0
otfscan = 0
posangs = [h['COMPPOSA'] for h in self.allind]
if verbose:
pb = ProgressBar(len(self.allind))
for ii,h in enumerate(self.allind):
if (h['SCAN'] != h0['SCAN']
or h['SOURC'] != h0['SOURC']):
h0['FIRSTSCAN'] = st
cpa = np.median(posangs[st:ii])
for hh in self.allind[st:ii]:
hh['SCANPOSA'] = cpa % 180
st = ii
if h['SCAN'] == h0['SCAN']:
h0['OTFSCAN'] = otfscan
otfscan += 1
h['OTFSCAN'] = otfscan
else:
otfscan = 0
h['OTFSCAN'] = otfscan
else:
h['OTFSCAN'] = otfscan
if verbose:
pb.update(ii)
def listscans(self, source=None, telescope=None, out=sys.stdout):
minid=0
scan = -1
sourc = ""
#tel = ''
minoff1,maxoff1 = np.inf,-np.inf
minoff2,maxoff2 = np.inf,-np.inf
ttlangle,nangle = 0.0,0
print("{entries:15s} {SOURC:12s} {XTEL:12s} {SCAN:>8s} {SUBSCAN:>8s} "
"[ {RAmin:>12s}, {RAmax:>12s} ] "
"[ {DECmin:>12s}, {DECmax:>12s} ] "
"{angle:>12s} {SCANPOSA:>12s} {OTFSCAN:>8s} {TSYS:>8s} {UTD:>12s}"
.format(entries='Scans', SOURC='Source', XTEL='Telescope',
SCAN='Scan', SUBSCAN='Subscan',
RAmin='min(RA)', RAmax='max(RA)',
DECmin='min(DEC)', DECmax='max(DEC)',
SCANPOSA='Scan PA',
angle='Angle', OTFSCAN='OTFscan',
TSYS='TSYS', UTD='UTD'),
file=out)
data_rows = []
for ii,row in enumerate(self.headers):
if (row['SCAN'] == scan
and row['SOURC'] == sourc
#and row['XTEL'] == tel
):
minoff1 = min(minoff1, row['OFF1'])
maxoff1 = max(maxoff1, row['OFF1'])
minoff2 = min(minoff2, row['OFF2'])
maxoff2 = max(maxoff2, row['OFF2'])
ttlangle += np.arctan2(row['OFF2'] - prevrow['OFF2'],
row['OFF1'] - prevrow['OFF1'])%np.pi
nangle += 1
prevrow = row
else:
if scan == -1:
scan = row['SCAN']
sourc = row['SOURC']
#tel = row['XTEL']
prevrow = row
continue
ok = True
if source is not None:
if isinstance(source, (list,tuple)):
ok = ok and any(re.search((s), prevrow['SOURC'])
for s in source)
else:
ok = ok and re.search((source), prevrow['SOURC'])
if telescope is not None:
ok = ok and re.search((telescope), prevrow['XTEL'])
if ok:
data = dict(RAmin=minoff1*180/np.pi*3600,
RAmax=maxoff1*180/np.pi*3600,
DECmin=minoff2*180/np.pi*3600,
DECmax=maxoff2*180/np.pi*3600,
angle=(ttlangle/nangle)*180/np.pi if nangle>0 else 0,
e0=minid,
e1=ii-1,
#TSYS=row['TSYS'] if 'TSYS' in row else '--',
UTD=row['DOBS']+row['UT'] if 'UT' in row else -99,
**prevrow)
print("{e0:7d}-{e1:7d} {SOURC:12s} {XTEL:12s} {SCAN:8d} {SUBSCAN:8d} "
"[ {RAmin:12f}, {RAmax:12f} ] "
"[ {DECmin:12f}, {DECmax:12f} ] "
"{angle:12.1f} {SCANPOSA:12.1f} {OTFSCAN:8d}"
" {TSYS:>8.1f} {UTD:12f}".
format(**data),
file=out)
data_rows.append(data)
minoff1,maxoff1 = np.inf,-np.inf
minoff2,maxoff2 = np.inf,-np.inf
ttlangle,nangle = 0.0,0
scan = row['SCAN']
sourc = row['SOURC']
#tel = row['XTEL']
minid = ii
return data
@property
def tels(self):
if hasattr(self,'_tels'):
return self._tels
else:
self._tels = set([h['XTEL'] for h in self.allind])
return self._tels
@property
def sources(self):
if hasattr(self,'_source'):
return self._source
else:
self._source = set([h['SOURC'] for h in self.allind])
return self._source
@property
def scans(self):
if hasattr(self,'_scan'):
return self._scan
else:
self._scan = set([h['SCAN'] for h in self.allind])
return self._scan
@property
def sci_sources(self):
return set([s for s in self.sources
if s[:4] not in ('SKY-', 'TSYS', 'TCAL', 'TREC', 'HOT-',
'COLD')])
@property
def lines(self):
if hasattr(self,'_lines'):
return self._lines
else:
self._lines = set([h['LINE'] for h in self.allind])
return self._lines
def _load_all_spectra(self, indices=None):
if indices is None:
indices = range(self.file_description['xnext']-1)
if hasattr(self, '_loaded_indices'):
indices_set = set(indices)
indices_to_load = (indices_set.difference(self._loaded_indices))
self._loaded_indices = self._loaded_indices.union(indices_set)
if any(indices_to_load):
pb = ProgressBar(len(indices_to_load))
for ii,k in enumerate(xrange(indices_to_load)):
self._spectra[k]
pb.update(ii)
else:
self._loaded_indices = set(indices)
self._spectra.load_all()
@property
def spectra(self):
return [x[0] for x in self._spectra]
@property
def headers(self):
return [self._spectra[ii][1]
if ii in self._spectra else x
for ii,x in enumerate(self.allind)]
def select_spectra(self,
all=None,
line=None,
linere=None,
linereflags=re.IGNORECASE,
number=None,
scan=None,
offset=None,
source=None,
sourcere=None,
sourcereflags=re.IGNORECASE,
range=None,
quality=None,
telescope=None,
telescopere=None,
telescopereflags=re.IGNORECASE,
subscan=None,
entry=None,
posang=None,
#observed=None,
#reduced=None,
frequency=None,
section=None,
user=None,
include_old_versions=False,
):
"""
Parameters
----------
include_old_versions: bool
Include spectra with XVER numbers <0? These are CLASS spectra that
have been "overwritten" (re-reduced?)
"""
if entry is not None and len(entry)==2:
return irange(entry[0], entry[1])
if frequency is not None:
self._load_all_spectra()
sel = [(re.search(re.escape(line), h['LINE'], re.IGNORECASE)
if line is not None else True) and
(re.search(linere, h['LINE'], linereflags)
if linere is not None else True) and
(h['SCAN'] == scan if scan is not None else True) and
((h['OFF1'] == offset or
h['OFF2'] == offset) if offset is not None else True) and
(re.search(re.escape(source), h['CSOUR'], re.IGNORECASE)
if source is not None else True) and
(re.search(sourcere, h['CSOUR'], sourcereflags)
if sourcere is not None else True) and
(h['OFF1']>range[0] and h['OFF1'] < range[1] and
h['OFF2']>range[2] and h['OFF2'] < range[3]
if range is not None and len(range)==4 else True) and
(h['QUAL'] == quality if quality is not None else True) and
(re.search(re.escape(telescope), h['CTELE'], re.IGNORECASE)
if telescope is not None else True) and
(re.search(telescopere, h['CTELE'], telescopereflags)
if telescopere is not None else True) and
(h['SUBSCAN']==subscan if subscan is not None else True) and
(h['NUM'] >= number[0] and h['NUM'] < number[1]
if number is not None else True) and
('RESTF' in h and # Need to check that it IS a spectrum: continuum data can't be accessed this way
h['RESTF'] > frequency[0] and
h['RESTF'] < frequency[1]
if frequency is not None and len(frequency)==2
else True) and
(h['COMPPOSA']%180 > posang[0] and
h['COMPPOSA']%180 < posang[1]
if posang is not None and len(posang)==2
else True) and
(h['XVER'] > 0 if not include_old_versions else True)
for h in self.headers
]
return [ii for ii,k in enumerate(sel) if k]
def get_spectra(self, progressbar=True, **kwargs):
selected_indices = self.select_spectra(**kwargs)
if not any(selected_indices):
raise ValueError("Selection yielded empty.")
self._spectra.load(selected_indices, progressbar=progressbar)
return [self._spectra[ii] for ii in selected_indices]
def get_pyspeckit_spectra(self, progressbar=True, **kwargs):
spdata = self.get_spectra(progressbar=progressbar, **kwargs)
spectra = [pyspeckit.Spectrum(data=data,
xarr=make_axis(header),
header=clean_header(header))
for data,header in spdata]
return spectra
def read_observations(self, observation_indices, progressbar=True):
self._spectra.load(observation_indices, progressbar=progressbar)
return [self._spectra[ii] for ii in observation_indices]
@print_timing
def read_class(filename, downsample_factor=None, sourcename=None,
telescope=None, posang=None, verbose=False,
flag_array=None):
"""
Read a binary class file.
Based on the
`GILDAS CLASS file type Specification
<http://iram.fr/IRAMFR/GILDAS/doc/html/class-html/node58.html>`_
Parameters
----------
filename: str
downsample_factor: None or int
Factor by which to downsample data by averaging. Useful for
overresolved data.
sourcename: str or list of str
Source names to match to the data (uses regex)
telescope: str or list of str
'XTEL' or 'TELE' parameters: the telescope & instrument
flag_array: np.ndarray
An array with the same shape as the data used to flag out
(remove) data when downsampling. True = flag out
"""
classobj = ClassObject(filename)
if not isinstance(sourcename, (list,tuple)):
sourcename = [sourcename]
if not isinstance(telescope, (list,tuple)):
telescope = [telescope]
spectra,headers = [],[]
if verbose:
log.info("Reading...")
selection = [ii
for source in sourcename
for tel in telescope
for ii in classobj.select_spectra(sourcere=source,
telescope=tel,
posang=posang)]
sphdr = classobj.read_observations(selection)
if len(sphdr) == 0:
return None
spec,hdr = zip(*sphdr)
spectra += spec
headers += hdr
indexes = headers
weight = ~flag_array if flag_array is not None else None
if downsample_factor is not None:
if verbose:
log.info("Downsampling...")
spectra = [downsample_1d(spec, downsample_factor,
weight=weight)
for spec in ProgressBar(spectra)]
headers = [downsample_header(h, downsample_factor)
for h in ProgressBar(headers)]
return spectra,headers,indexes
def downsample_header(hdr, downsample_factor):
for k in ('NCHAN','NPOIN','DATALEN'):
if k in hdr:
hdr[k] = hdr[k] / downsample_factor
# maybe wrong? h['RCHAN'] = (h['RCHAN']-1) / downsample_factor + 1
scalefactor = 1./downsample_factor
hdr['RCHAN'] = (hdr['RCHAN']-1)*scalefactor + 0.5 + scalefactor/2.
for kw in ['FRES','VRES']:
if kw in hdr:
hdr[kw] *= downsample_factor
return hdr
def make_axis(header,imagfreq=False):
"""
Create a :class:`pyspeckit.spectrum.units.SpectroscopicAxis` from the CLASS "header"
"""
from .. import units
rest_frequency = header.get('RESTF')
xunits = 'MHz'
nchan = header.get('NCHAN')
voff = header.get('VOFF')
foff = header.get('FOFF')
doppler = header.get('DOPPLER')
fres = header.get('FRES')
refchan = header.get('RCHAN')
imfreq = header.get('IMAGE')
if foff in (None, 0.0) and voff not in (None, 0.0):
# Radio convention
foff = -voff/2.997924580e5 * rest_frequency
if not imagfreq:
xarr = rest_frequency + foff + (numpy.arange(1, nchan+1) - refchan) * fres
XAxis = units.SpectroscopicAxis(xarr,unit='MHz',refX=rest_frequency*u.MHz)
else:
xarr = imfreq - (numpy.arange(1, nchan+1) - refchan) * fres
XAxis = units.SpectroscopicAxis(xarr,unit='MHz',refX=imfreq*u.MHz)
return XAxis
@print_timing
def class_to_obsblocks(filename, telescope, line, datatuple=None, source=None,
imagfreq=False, DEBUG=False, **kwargs):
"""
Load an entire CLASS observing session into a list of ObsBlocks based on
matches to the 'telescope', 'line' and 'source' names
Parameters
----------
filename : string
The Gildas CLASS data file to read the spectra from.
telescope : list
List of telescope names to be matched.
line : list
List of line names to be matched.
source : list (optional)
List of source names to be matched. Defaults to None.
imagfreq : bool
Create a SpectroscopicAxis with the image frequency.
"""
if datatuple is None:
spectra,header,indexes = read_class(filename,DEBUG=DEBUG, **kwargs)
else:
spectra,header,indexes = datatuple
obslist = []
lastscannum = -1
spectrumlist = None
for sp,hdr,ind in zip(spectra,header,indexes):
hdr.update(ind)
# this is slow but necessary...
H = pyfits.Header()
for k,v in iteritems(hdr):
if hasattr(v,"__len__") and not isinstance(v,str):
if len(v) > 1:
for ii,vv in enumerate(v):
H.update(k[:7]+str(ii),vv)
else:
H.update(k,v[0])
elif pyfits.Card._comment_FSC_RE.match(str(v)) is not None:
H.update(k,v)
scannum = hdr['SCAN']
if 'XTEL' in hdr and hdr['XTEL'].strip() not in telescope:
continue
if hdr['LINE'].strip() not in line:
continue
if (source is not None) and (hdr['SOURC'].strip() not in source):
continue
hdr.update({'RESTFREQ':hdr.get('RESTF')})
H.update('RESTFREQ',hdr.get('RESTF'))
#print "Did not skip %s,%s. Scannum, last: %i,%i" % (hdr['XTEL'],hdr['LINE'],scannum,lastscannum)
if scannum != lastscannum:
lastscannum = scannum
if spectrumlist is not None:
obslist.append(pyspeckit.ObsBlock(spectrumlist))
xarr = make_axis(hdr,imagfreq=imagfreq)
spectrumlist = [(
pyspeckit.Spectrum(xarr=xarr,
header=H,
data=sp))]
else:
spectrumlist.append(
pyspeckit.Spectrum(xarr=xarr,
header=H,
data=sp))
return obslist
class LazyItem(object):
"""
Simple lazy spectrum-retriever wrapper
"""
def __init__(self, parent):
self.parent = parent
self.sphdr = {}
self.nind = len(self.parent.allind)
self.nloaded = 0
def __repr__(self):
return ("Set of {0} spectra & headers, {1} loaded"
" ({2:0.2f}%)".format(self.nind, self.nloaded,
(float(self.nloaded)/self.nind)*100))
def load_all(self, progressbar=True):
self.load(range(self.nind))
def load(self, indices, progressbar=True):
pb = ProgressBar(len(indices))
counter = 0
for k in indices:
self[k]
counter += 1
pb.update(counter)
def __getitem__(self, key):
if key in self.sphdr:
return self.sphdr[key]
elif isinstance(key, slice):
return [self[k] for k in xrange(key.start or 0,
key.end or len(self.parent.allind),
key.step or 1)]
else:
sphd = read_observation(self.parent._file, key,
file_description=self.parent.file_description,
indices=self.parent.allind,
my_memmap=self.parent._data)
# Update the header with OTFSCAN and POSANG info
sphd[1].update(self.parent.allind[key])
self.sphdr[key] = sphd
self.nloaded += 1
return sphd
def __iter__(self):
return self.next()
def __next__(self):
for k in self.spheader:
yield self.spheader[k]
def __contains__(self, key):
return key in self.sphdr
@print_timing
def class_to_spectra(filename, datatuple=None, **kwargs):
"""
Load each individual spectrum within a CLASS file into a list of Spectrum
objects
"""
if datatuple is None:
spectra,header,indexes = read_class(filename, **kwargs)
else:
spectra,header,indexes = datatuple
spectrumlist = []
for sp,hdr,ind in zip(spectra,header,indexes):
hdr.update(ind)
xarr = make_axis(hdr)
spectrumlist.append(
pyspeckit.Spectrum(xarr=xarr,
header=hdr,
data=sp))
return pyspeckit.Spectra(spectrumlist)
def tests():
"""
Tests are specific to the machine on which this code was developed.
"""
fn1 = '/Users/adam/work/bolocam/hht/class_003.smt'
#fn1 = '/Users/adam/work/bolocam/hht/class_001.smt'
#fn1 = '/Users/adam/work/bolocam/hht/test_SMT-F1M-VU-20824-073.cls'
#fn2 = '/Users/adam/work/bolocam/hht/test_SMT-F1M-VU-79472+203.cls'
#F1 = read_class(fn1)#,DEBUG=True)
#F2 = read_class(fn2)
n2hp = class_to_obsblocks(fn1,telescope=['SMT-F1M-HU','SMT-F1M-VU'],line=['N2HP(3-2)','N2H+(3-2)'])
hcop = class_to_obsblocks(fn1,telescope=['SMT-F1M-HL','SMT-F1M-VL'],line=['HCOP(3-2)','HCO+(3-2)'])
|
mit
| -4,625,620,523,675,145,000
| 41.584127
| 220
| 0.516267
| false
| 3.424385
| false
| false
| false
|
xbuf/blender_io_xbuf
|
protocol.py
|
1
|
4603
|
# This file is part of blender_io_xbuf. blender_io_xbuf 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, version 2.
#
# 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.
#
# Copyright David Bernard
# <pep8 compliant>
import struct
import asyncio
import atexit
import xbuf
import xbuf.datas_pb2
import xbuf.cmds_pb2
from . import xbuf_export # pylint: disable=W0406
# TODO better management off the event loop (eg on unregister)
loop = asyncio.get_event_loop()
atexit.register(loop.close)
class Kind:
pingpong = 0x01
logs = 0x02
ask_screenshot = 0x03
raw_screenshot = 0x04
msgpack = 0x05
xbuf_cmd = 0x06
class Client:
def __init__(self):
self.writer = None
self.reader = None
self.host = None
self.port = None
def __del__(self):
self.close()
def close(self):
if self.writer is not None:
print('Close the socket/writer')
self.writer.write_eof()
self.writer.close()
self.writer = None
self.reader = None
@asyncio.coroutine
def connect(self, host, port):
if (host != self.host) or (port != self.port):
self.close()
if self.writer is None:
self.host = host
self.port = port
(self.reader, self.writer) = yield from asyncio.open_connection(host, port, loop=loop)
return self
@asyncio.coroutine
def readHeader(reader):
"""return (size, kind)"""
header = yield from reader.readexactly(5)
return struct.unpack('>iB', header)
@asyncio.coroutine
def readMessage(reader):
"""return (kind, raw_message)"""
(size, kind) = yield from readHeader(reader)
# kind = header[4]
raw = yield from reader.readexactly(size)
return (kind, raw)
def writeMessage(writer, kind, body):
writer.write((len(body)).to_bytes(4, byteorder='big'))
writer.write((kind).to_bytes(1, byteorder='big'))
writer.write(body)
def askScreenshot(writer, width, height):
b = bytearray()
b.extend((width).to_bytes(4, byteorder='big'))
b.extend((height).to_bytes(4, byteorder='big'))
writeMessage(writer, Kind.ask_screenshot, b)
def setEye(writer, location, rotation, projection_matrix, near, far, is_ortho):
# sendCmd(writer, 'updateCamera', (_encode_vec3(location), _encode_quat(rotation), _encode_mat4(projection_matrix)))
cmd = xbuf.cmds_pb2.Cmd()
# cmd.setCamera = xbuf.cmds_pb2.SetCamera()
xbuf_export.cnv_translation(location, cmd.setEye.location)
xbuf_export.cnv_quatZupToYup(rotation, cmd.setEye.rotation)
xbuf_export.cnv_mat4(projection_matrix, cmd.setEye.projection)
cmd.setEye.near = near
cmd.setEye.far = far
cmd.setEye.projMode = xbuf.cmds_pb2.SetEye.orthographic if is_ortho else xbuf.cmds_pb2.SetEye.perspective
writeMessage(writer, Kind.xbuf_cmd, cmd.SerializeToString())
def setData(writer, scene, cfg):
cmd = xbuf.cmds_pb2.Cmd()
xbuf_export.export(scene, cmd.setData, cfg)
send = (len(cmd.setData.relations) > 0 or
len(cmd.setData.tobjects) > 0 or
len(cmd.setData.geometries) > 0 or
len(cmd.setData.materials) > 0 or
len(cmd.setData.lights) > 0
)
if send:
# print("send setData")
writeMessage(writer, Kind.xbuf_cmd, cmd.SerializeToString())
def changeAssetFolders(writer, cfg):
cmd = xbuf.cmds_pb2.Cmd()
cmd.changeAssetFolders.path.append(cfg.assets_path)
cmd.changeAssetFolders.register = True
cmd.changeAssetFolders.unregisterOther = True
writeMessage(writer, Kind.xbuf_cmd, cmd.SerializeToString())
def playAnimation(writer, ref, anims):
cmd = xbuf.cmds_pb2.Cmd()
cmd.playAnimation.ref = ref
cmd.playAnimation.animationsNames.extend(anims)
writeMessage(writer, Kind.xbuf_cmd, cmd.SerializeToString())
def run_until_complete(f, *args, **kwargs):
if asyncio.iscoroutine(f):
loop.run_until_complete(f)
else:
coro = asyncio.coroutine(f)
future = coro(*args, **kwargs)
loop.run_until_complete(future)
|
gpl-3.0
| -6,606,697,315,505,430,000
| 30.101351
| 120
| 0.669781
| false
| 3.412157
| false
| false
| false
|
ModulousSmash/Modulous
|
KerbalStuff/blueprints/mods.py
|
1
|
19423
|
from flask import Blueprint, render_template, request, g, Response, redirect, session, abort, send_file, make_response, url_for
from flask.ext.login import current_user
from sqlalchemy import desc
from KerbalStuff.objects import User, Mod, ModVersion, DownloadEvent, FollowEvent, ReferralEvent, Featured, Media, GameVersion, Category, Report
from KerbalStuff.email import send_update_notification, send_autoupdate_notification
from KerbalStuff.database import db
from KerbalStuff.common import *
from KerbalStuff.config import _cfg
from KerbalStuff.blueprints.api import default_description
from KerbalStuff.ckan import send_to_ckan
from werkzeug.utils import secure_filename
from datetime import datetime, timedelta
from shutil import rmtree, copyfile
from urllib.parse import urlparse
import os
import zipfile
import urllib
import random
mods = Blueprint('mods', __name__, template_folder='../../templates/mods')
@mods.route("/random")
def random_mod():
mods = Mod.query.filter(Mod.published == True).all()
mod = random.choice(mods)
return redirect(url_for("mods.mod", id=mod.id, mod_name=mod.name))
@mods.route("/mod/<int:id>/<path:mod_name>/update")
def update(id, mod_name):
mod = Mod.query.filter(Mod.id == id).first()
if not mod:
abort(404)
editable = False
if current_user.admin:
editable = True
if current_user.id == mod.user_id:
editable = True
if any([u.accepted and u.user == current_user for u in mod.shared_authors]):
editable = True
if not editable:
abort(401)
return render_template("update.html", mod=mod, game_versions=GameVersion.query.order_by(desc(GameVersion.id)).all())
@mods.route("/mod/<int:id>.rss", defaults={'mod_name': None})
@mods.route("/mod/<int:id>/<path:mod_name>.rss")
def mod_rss(id, mod_name):
mod = Mod.query.filter(Mod.id == id).first()
if not mod:
abort(404)
return render_template("rss-mod.xml", mod=mod)
@mods.route("/mod/<int:id>", defaults={'mod_name': None})
@mods.route("/mod/<int:id>/<path:mod_name>")
@with_session
def mod(id, mod_name):
mod = Mod.query.filter(Mod.id == id).first()
if not mod:
abort(404)
editable = False
if current_user:
if current_user.admin:
editable = True
if current_user.id == mod.user_id:
editable = True
if not mod.published and not editable:
abort(401)
latest = mod.default_version()
referral = request.referrer
if referral:
host = urllib.parse.urlparse(referral).hostname
event = ReferralEvent.query\
.filter(ReferralEvent.mod_id == mod.id)\
.filter(ReferralEvent.host == host)\
.first()
if not event:
event = ReferralEvent()
event.mod = mod
event.events = 1
event.host = host
db.add(event)
db.flush()
db.commit()
mod.referrals.append(event)
else:
event.events += 1
download_stats = None
follower_stats = None
referrals = None
json_versions = None
thirty_days_ago = datetime.now() - timedelta(days=30)
referrals = list()
for r in ReferralEvent.query\
.filter(ReferralEvent.mod_id == mod.id)\
.order_by(desc(ReferralEvent.events)):
referrals.append( { 'host': r.host, 'count': r.events } )
download_stats = list()
for d in DownloadEvent.query\
.filter(DownloadEvent.mod_id == mod.id)\
.filter(DownloadEvent.created > thirty_days_ago)\
.order_by(DownloadEvent.created):
download_stats.append(dumb_object(d))
follower_stats = list()
for f in FollowEvent.query\
.filter(FollowEvent.mod_id == mod.id)\
.filter(FollowEvent.created > thirty_days_ago)\
.order_by(FollowEvent.created):
follower_stats.append(dumb_object(f))
json_versions = list()
for v in mod.versions:
json_versions.append({ 'name': v.friendly_version, 'id': v.id })
if request.args.get('noedit') != None:
editable = False
forumThread = False
if mod.external_link != None:
try:
u = urlparse(mod.external_link)
if u.netloc == 'forum.kerbalspaceprogram.com':
forumThread = True
except e:
print(e)
pass
total_authors = 1
pending_invite = False
owner = editable
for a in mod.shared_authors:
if a.accepted:
total_authors += 1
if current_user:
if current_user.id == a.user_id and not a.accepted:
pending_invite = True
if current_user.id == a.user_id and a.accepted:
editable = True
game_versions = GameVersion.query.order_by(desc(GameVersion.id)).all()
outdated = False
if latest:
outdated = game_versions[0].friendly_version != latest.ksp_version
return render_template("mod.html",
**{
'mod': mod,
'latest': latest,
'safe_name': secure_filename(mod.name)[:64],
'featured': any(Featured.query.filter(Featured.mod_id == mod.id).all()),
'editable': editable,
'owner': owner,
'pending_invite': pending_invite,
'download_stats': download_stats,
'follower_stats': follower_stats,
'referrals': referrals,
'json_versions': json_versions,
'thirty_days_ago': thirty_days_ago,
'share_link': urllib.parse.quote_plus(_cfg("protocol") + "://" + _cfg("domain") + "/mod/" + str(mod.id)),
'game_versions': game_versions,
'outdated': outdated,
'forum_thread': forumThread,
'new': request.args.get('new') != None,
'stupid_user': request.args.get('stupid_user') != None,
'total_authors': total_authors
})
@mods.route("/mod/<int:id>/<path:mod_name>/edit", methods=['GET', 'POST'])
@with_session
@loginrequired
def edit_mod(id, mod_name):
mod = Mod.query.filter(Mod.id == id).first()
if not mod:
abort(404)
editable = False
if current_user.admin:
editable = True
if current_user.id == mod.user_id:
editable = True
if any([u.accepted and u.user == current_user for u in mod.shared_authors]):
editable = True
if not editable:
abort(401)
if request.method == 'GET':
return render_template("edit_mod.html", mod=mod, original=mod.user == current_user, categories = Category.query.all())
else:
short_description = request.form.get('short-description')
tags = request.form.get('tags')
other_authors = request.form.get('other-authors')
print(request.form.get('other-authors'))
tags_array = request.form.get('tags')
modmm = request.form.get('modmm')
if modmm == None:
modmm = False
else:
modmm = (modmm.lower() == "true" or modmm.lower() == "yes" or modmm.lower() == "on")
license = request.form.get('license')
category = request.form.get('category')
donation_link = request.form.get('donation-link')
external_link = request.form.get('external-link')
source_link = request.form.get('source-link')
description = request.form.get('description')
background = request.form.get('background')
bgOffsetY = request.form.get('bg-offset-y')
if not license or license == '':
return render_template("edit_mod.html", mod=mod, error="All mods must have a license.")
if not category or category == '':
abort(401)
else:
category = Category.query.filter(Category.name == category).first()
mod.short_description = short_description
mod.license = license
mod.donation_link = donation_link
mod.external_link = external_link
mod.source_link = source_link
mod.description = description
mod.tags = tags
mod.modmm = modmm
mod.category = category
if other_authors == 'None' or other_authors == '':
mod.other_authors = None
else:
mod.other_authors = other_authors
if background and background != '':
mod.background = background
try:
mod.bgOffsetY = int(bgOffsetY)
except:
pass
return redirect(url_for("mods.mod", id=mod.id, mod_name=mod.name))
@mods.route("/create/mod")
@loginrequired
@with_session
def create_mod():
return render_template("create.html", **{ 'game_versions': GameVersion.query.order_by(desc(GameVersion.id)).all(), 'categories': Category.query.all()})
@mods.route("/mod/<int:mod_id>/stats/downloads", defaults={'mod_name': None})
@mods.route("/mod/<int:mod_id>/<path:mod_name>/stats/downloads")
def export_downloads(mod_id, mod_name):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
download_stats = DownloadEvent.query\
.filter(DownloadEvent.mod_id == mod.id)\
.order_by(DownloadEvent.created)
response = make_response(render_template("downloads.csv", stats=download_stats))
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment;filename=downloads.csv'
return response
@mods.route("/mod/<int:mod_id>/stats/followers", defaults={'mod_name': None})
@mods.route("/mod/<int:mod_id>/<path:mod_name>/stats/followers")
def export_followers(mod_id, mod_name):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
follower_stats = FollowEvent.query\
.filter(FollowEvent.mod_id == mod.id)\
.order_by(FollowEvent.created)
response = make_response(render_template("followers.csv", stats=follower_stats))
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment;filename=followers.csv'
return response
@mods.route("/mod/<int:mod_id>/stats/referrals", defaults={'mod_name': None})
@mods.route("/mod/<mod_id>/<path:mod_name>/stats/referrals")
def export_referrals(mod_id, mod_name):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
referral_stats = ReferralEvent.query\
.filter(ReferralEvent.mod_id == mod.id)\
.order_by(desc(ReferralEvent.events))
response = make_response(render_template("referrals.csv", stats=referral_stats))
response.headers['Content-Type'] = 'text/csv'
response.headers['Content-Disposition'] = 'attachment;filename=referrals.csv'
return response
@mods.route("/mod/<int:mod_id>/delete", methods=['POST'])
@loginrequired
@with_session
def delete(mod_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
editable = False
if current_user:
if current_user.admin:
editable = True
if current_user.id == mod.user_id:
editable = True
if not editable:
abort(401)
db.delete(mod)
for feature in Featured.query.filter(Featured.mod_id == mod.id).all():
db.delete(feature)
for media in Media.query.filter(Media.mod_id == mod.id).all():
db.delete(media)
for version in ModVersion.query.filter(ModVersion.mod_id == mod.id).all():
db.delete(version)
base_path = os.path.join(secure_filename(mod.user.username) + '_' + str(mod.user.id), secure_filename(mod.name))
full_path = os.path.join(_cfg('storage'), base_path)
db.commit()
rmtree(full_path)
return redirect("/profile/" + current_user.username)
@mods.route("/mod/<int:mod_id>/follow", methods=['POST'])
@loginrequired
@json_output
@with_session
def follow(mod_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
if any(m.id == mod.id for m in current_user.following):
abort(418)
event = FollowEvent.query\
.filter(FollowEvent.mod_id == mod.id)\
.order_by(desc(FollowEvent.created))\
.first()
# Events are aggregated hourly
if not event or ((datetime.now() - event.created).seconds / 60 / 60) >= 1:
event = FollowEvent()
event.mod = mod
event.delta = 1
event.events = 1
db.add(event)
db.flush()
db.commit()
mod.follow_events.append(event)
else:
event.delta += 1
event.events += 1
mod.follower_count += 1
current_user.following.append(mod)
return { "success": True }
@mods.route("/mod/<int:mod_id>/unfollow", methods=['POST'])
@loginrequired
@json_output
@with_session
def unfollow(mod_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
if not any(m.id == mod.id for m in current_user.following):
abort(418)
event = FollowEvent.query\
.filter(FollowEvent.mod_id == mod.id)\
.order_by(desc(FollowEvent.created))\
.first()
# Events are aggregated hourly
if not event or ((datetime.now() - event.created).seconds / 60 / 60) >= 1:
event = FollowEvent()
event.mod = mod
event.delta = -1
event.events = 1
mod.follow_events.append(event)
db.add(event)
else:
event.delta -= 1
event.events += 1
mod.follower_count -= 1
current_user.following = [m for m in current_user.following if m.id != int(mod_id)]
return { "success": True }
@mods.route('/mod/<int:mod_id>/feature', methods=['POST'])
@adminrequired
@json_output
@with_session
def feature(mod_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
if any(Featured.query.filter(Featured.mod_id == mod_id).all()):
abort(409)
feature = Featured()
feature.mod = mod
db.add(feature)
return { "success": True }
@mods.route('/mod/<mod_id>/unfeature', methods=['POST'])
@adminrequired
@json_output
@with_session
def unfeature(mod_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
feature = Featured.query.filter(Featured.mod_id == mod_id).first()
if not feature:
abort(404)
db.delete(feature)
return { "success": True }
@mods.route('/mod/<int:mod_id>/<path:mod_name>/publish')
@with_session
@loginrequired
def publish(mod_id, mod_name):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
if current_user.id != mod.user_id:
abort(401)
if mod.description == default_description:
return redirect(url_for("mods.mod", id=mod.id, mod_name=mod.name, stupid_user=True))
mod.published = True
mod.updated = datetime.now()
send_to_ckan(mod)
return redirect(url_for("mods.mod", id=mod.id, mod_name=mod.name))
@mods.route('/mod/<int:mod_id>/download/<version>', defaults={ 'mod_name': None })
@mods.route('/mod/<int:mod_id>/<path:mod_name>/download/<version>')
@with_session
def download(mod_id, mod_name, version):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
if not mod.published and (not current_user or current_user.id != mod.user_id):
abort(401)
version = ModVersion.query.filter(ModVersion.mod_id == mod_id, \
ModVersion.friendly_version == version).first()
if not version:
abort(404)
download = DownloadEvent.query\
.filter(DownloadEvent.mod_id == mod.id and DownloadEvent.version_id == version.id)\
.order_by(desc(DownloadEvent.created))\
.first()
if not os.path.isfile(os.path.join(_cfg('storage'), version.download_path)):
abort(404)
if not 'Range' in request.headers:
# Events are aggregated hourly
if not download or ((datetime.now() - download.created).seconds / 60 / 60) >= 1:
download = DownloadEvent()
download.mod = mod
download.version = version
download.downloads = 1
db.add(download)
db.flush()
db.commit()
mod.downloads.append(download)
else:
download.downloads += 1
mod.download_count += 1
response = make_response(send_file(os.path.join(_cfg('storage'), version.download_path), as_attachment = True))
if _cfg("use-x-accel") == 'true':
response = make_response("")
response.headers['Content-Type'] = 'application/zip'
response.headers['Content-Disposition'] = 'attachment; filename=' + os.path.basename(version.download_path)
response.headers['X-Accel-Redirect'] = '/internal/' + version.download_path
return response
@mods.route('/mod/<int:mod_id>/version/<version_id>/delete', methods=['POST'])
@with_session
@loginrequired
def delete_version(mod_id, version_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
editable = False
if current_user:
if current_user.admin:
editable = True
if current_user.id == mod.user_id:
editable = True
if any([u.accepted and u.user == current_user for u in mod.shared_authors]):
editable = True
if not editable:
abort(401)
version = [v for v in mod.versions if v.id == int(version_id)]
if len(mod.versions) == 1:
abort(400)
if len(version) == 0:
abort(404)
if version[0].id == mod.default_version_id:
abort(400)
db.delete(version[0])
mod.versions = [v for v in mod.versions if v.id != int(version_id)]
db.commit()
return redirect(url_for("mods.mod", id=mod.id, mod_name=mod.name))
@mods.route('/mod/<int:mod_id>/<mod_name>/edit_version', methods=['POST'])
@mods.route('/mod/<int:mod_id>/edit_version', methods=['POST'], defaults={ 'mod_name': None })
@with_session
@loginrequired
def edit_version(mod_name, mod_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
editable = False
if current_user:
if current_user.admin:
editable = True
if current_user.id == mod.user_id:
editable = True
if any([u.accepted and u.user == current_user for u in mod.shared_authors]):
editable = True
if not editable:
abort(401)
version_id = int(request.form.get('version-id'))
changelog = request.form.get('changelog')
version = [v for v in mod.versions if v.id == version_id]
if len(version) == 0:
abort(404)
version = version[0]
version.changelog = changelog
return redirect(url_for("mods.mod", id=mod.id, mod_name=mod.name))
@mods.route('/mod/<int:mod_id>/autoupdate', methods=['POST'])
@with_session
@loginrequired
def autoupdate(mod_id):
mod = Mod.query.filter(Mod.id == mod_id).first()
if not mod:
abort(404)
editable = False
if current_user:
if current_user.admin:
editable = True
if current_user.id == mod.user_id:
editable = True
if any([u.accepted and u.user == current_user for u in mod.shared_authors]):
editable = True
if not editable:
abort(401)
default = mod.default_version()
default.ksp_version = GameVersion.query.order_by(desc(GameVersion.id)).first().friendly_version
send_autoupdate_notification(mod)
return redirect(url_for("mods.mod", id=mod.id, mod_name=mod.name))
|
mit
| -6,892,305,928,326,822,000
| 35.855787
| 155
| 0.615713
| false
| 3.514839
| false
| false
| false
|
ratschlab/RNA-geeq
|
SAFT/find_optimal_param_set.py
|
1
|
11493
|
"""
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.
Written (W) 2095-2010 Andre Kahles
Copyright (C) 2009-2010 by Friedrich Miescher Laboratory, Tuebingen, Germany
This script finds an optimal parameter set to maximize the performance of a
given intronfeature file.
For detailed usage information type:
python find_optimal_param_set.py
"""
import sys
import cPickle
class Feature(object):
"""Is an intron feature object"""
def __init__(self, max_mm=80, feature_string=''):
if feature_string == '':
self.alignment_support = 0
self.submission_support = 1
self.mm_ex = dict()
self.max_mm = max_mm + 1
else:
self.alignment_support = int(feature_string[0])
self.submission_support = int(feature_string[1])
self.mm_ex = dict()
self.max_mm = max_mm + 1
for _sl in feature_string[2:]:
(key, value) = _sl.split(':')
self.mm_ex[key] = int(value)
def merge_features(self, feature_string):
"""Merges information in feature_string into current feature object"""
self.alignment_support += int(feature_string[0])
self.submission_support += int(feature_string[1])
for _sl in feature_string[2:]:
(key, value) = _sl.split(':')
try:
self.mm_ex[key] += int(value)
except KeyError:
self.mm_ex[key] = int(value)
def add_mm_ex(self, ex, mm):
"""Adds mm ex information"""
self.alignment_support += 1
try:
self.mm_ex[(ex*self.max_mm) + mm] += 1
except KeyError:
self.mm_ex[(ex*self.max_mm) + mm] = 1
def get_feature_string(self):
"""Returns string with mm ex elements."""
_line = (str(self.alignment_support) + '\t' + str(self.submission_support) + '\t')
for key in self.mm_ex:
_line += (str(key) + ':' + str(self.mm_ex[key]) + '\t')
return _line[:-1]
def get_submission_support(self):
"""Returns submission support"""
return int(self.submission_support)
def is_valid(self, mm, ex, mc, options):
"""Returns true, if at least one alignment fulfills the requirements with respect to mm, ex, and mc. False otherwise."""
if self.alignment_support < mc:
return False
is_valid = False
for key in self.mm_ex.keys():
_ex = int(key) / (options.max_feat_mismatches + 1)
_mm = int(key) % (options.max_feat_mismatches + 1)
if _mm <= mm and _ex >= ex:
is_valid = True
break
return is_valid
def parse_options(argv):
"""Parses options from the command line """
from optparse import OptionParser, OptionGroup
parser = OptionParser()
required = OptionGroup(parser, 'REQUIRED')
required.add_option('-b', '--best_score', dest='best_scores', metavar='FILE', help='file to store the best scoring parameters', default='-')
required.add_option('-m', '--matrix', dest='matrix', metavar='FILE', help='file to store the full performance matrix', default='-')
required.add_option('-f', '--features', dest='features', metavar='FILE', help='alignment intron features', default='-')
required.add_option('-i', '--annotation_introns', dest='anno_int', metavar='FILE', help='annotation intron list', default='-')
optional = OptionGroup(parser, 'OPTIONAL')
optional.add_option('-E', '--exclude_introns', dest='exclude_introns', metavar='STRINGLIST', help='list of comma separated intron files to exclude from submitted features', default='-')
optional.add_option('-I', '--max_intron_len', dest='max_intron_len', metavar='INT', type='int', help='maximal intron length [10000000]', default=10000000)
optional.add_option('-s', '--ignore_strand', dest='ignore_strand', action='store_true', help='ignore strand information present in annotation', default=False)
optional.add_option('-X', '--max_feat_mismatches', dest='max_feat_mismatches', metavar='INT', type='int', help='max number of mismatches for feat generation [80] (do only change, if you are absolutely sure!)', default=80)
optional.add_option('-v', '--verbose', dest='verbose', action='store_true', help='verbosity', default=False)
parser.add_option_group(required)
parser.add_option_group(optional)
(options, args) = parser.parse_args()
if len(argv) < 2:
parser.print_help()
sys.exit(2)
return options
def get_performance_value(full_features, mm, ex, mc, annotation_list, options):
"""Builds up a filtered intron list from the given alignment features and compares to the annotation."""
alignment_list = dict()
for feat in full_features.keys():
chrm = feat[0]
intron = (0, int(feat[1]), int(feat[2]))
### filter step
if (intron[2] - intron[1]) > options.max_intron_len:
continue
if not full_features[feat].is_valid(mm, ex, mc, options):
continue
try:
alignment_list[chrm][intron] = 0
except KeyError:
alignment_list[chrm] = {intron:0}
### match intron lists
total_precision = float(0)
total_recall = float(0)
key_count = 0
for chrm in annotation_list.keys():
if alignment_list.has_key(chrm):
matches = len(set(annotation_list[chrm].keys()).intersection(set(alignment_list[chrm].keys())))
total_precision += (float(matches) / float(max(1, len(alignment_list[chrm].keys()))))
total_recall += (float(matches) / float(max(1, len(annotation_list[chrm].keys()))))
### do not include chromosomes with zero values into average
if matches > 0:
key_count += 1
total_precision /= max(1.0, float(key_count))
total_recall /= max(1.0, float(key_count))
return (total_precision, total_recall)
def main():
"""Main function extracting intron features."""
options = parse_options(sys.argv)
### get list of annotated introns
annotation_list = cPickle.load(open(options.anno_int, 'r'))
if options.ignore_strand:
for chrm in annotation_list.keys():
skiplist = set()
for intron in annotation_list[chrm].keys():
if intron[0] == 0:
continue
annotation_list[chrm][(0, intron[1], intron[2])] = annotation_list[chrm][intron]
skiplist.add(intron)
for intron in skiplist:
del annotation_list[chrm][intron]
del skiplist
### filter annotation for max intron length
print '\nFiltering intron list for max intron len'
print '-----------------------------------------'
skipped = 0
for chrm in annotation_list.keys():
skiplist = set()
for intron in annotation_list[chrm].keys():
if (intron[2] - intron[1]) > options.max_intron_len:
skiplist.add(intron)
for intron in skiplist:
del annotation_list[chrm][intron]
skipped += len(skiplist)
print '%s introns removed from annotation' % skipped
del skiplist
full_features = dict()
if options.verbose:
print 'Parsing %s' % options.features
line_counter = 0
for line in open(options.features, 'r'):
if options.verbose and line_counter % 1000 == 0:
print 'parsed %i features from %s' % (line_counter, options.features)
line_counter += 1
sl = line.strip().split('\t')
(chrm, start, stop) = sl[:3]
try:
full_features[(chrm, start, stop)].full_features(sl[3:])
except KeyError:
full_features[(chrm, start, stop)] = Feature(80, sl[3:])
### filter full feature list for excluded introns
if options.exclude_introns != '-':
_ex_introns = options.exclude_introns.strip().split(',')
### handle leading or trailing commas
if _ex_introns[0] == '':
_ex_introns = _ex_introns[1:]
if _ex_introns[-1] == '':
_ex_introns = _ex_introns[:-1]
for _infile in _ex_introns:
_ex_intron = cPickle.load(open(_infile, 'r'))
for chrm in _ex_intron.keys():
for _intron in _ex_intron[chrm].keys():
try:
del full_features[(chrm, str(_intron[1]), str(_intron[2]))]
except KeyError:
continue
del _ex_intron
if options.verbose:
print 'Parsing completed.'
print 'parsed %i features from %s' % (line_counter, options.features)
### SEARCH SPACE
### iterate over different filter dimensions
#ex_list = [2, 4, 6, 8, 10, 12, 15, 20, 25, 30] # 10
#ex_list = [2, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18 ] # 15
ex_list = [1, 2, 4, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 18 ] # 15
mm_list = [0, 1, 2, 3, 4, 5, 6] # 7
mc_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # 10 ==> 700 combinations
checked_combs = 0
# pre rec fsc
max_pre = (0.0, 0.0, 0.0)
max_rec = (0.0, 0.0, 0.0)
max_fsc = (0.0, 0.0, 0.0)
max_pre_idx = (0, 0, 0)
max_rec_idx = (0, 0, 0)
max_fsc_idx = (0, 0, 0)
matrix_file = open(options.matrix, 'w')
for ex in ex_list:
for mm in mm_list:
for mc in mc_list:
if options.verbose and checked_combs % 10 == 0:
print 'checked %i parameter combinations' % checked_combs
print 'best scores so far:\n \tbest fScore: %0.2f, best recall: %0.2f, best precision: %0.2f' % (max_fsc[2], max_rec[1], max_pre[0])
checked_combs += 1
(pre, rec) = get_performance_value(full_features, mm, ex, mc, annotation_list, options)
if float(rec) + float(pre) > 0:
fsc = (2 * float(rec) * float(pre)) / (float(rec) + float(pre))
else:
fsc = 0.0
if pre > max_pre[0]:
max_pre = (pre, rec, fsc)
max_pre_idx = (ex, mm, mc)
if rec > max_rec[1]:
max_rec = (pre, rec, fsc)
max_rec_idx = (ex, mm, mc)
if fsc > max_fsc[2]:
max_fsc = (pre, rec, fsc)
max_fsc_idx = (ex, mm, mc)
### store information
### ex mm mc pre rec fsc
print >> matrix_file, '%s\t%s\t%s\t%s\t%s\t%s' % (ex, mm, mc, pre, rec, fsc)
matrix_file.close()
best_file = open(options.best_scores, 'w')
# best precision
print >> best_file, '%s\t%s\t%s\t%s\t%s\t%s' % (max_pre_idx[0], max_pre_idx[1], max_pre_idx[2], max_pre[0], max_pre[1], max_pre[2])
# best recall
print >> best_file, '%s\t%s\t%s\t%s\t%s\t%s' % (max_rec_idx[0], max_rec_idx[1], max_rec_idx[2], max_rec[0], max_rec[1], max_rec[2])
# best fScore
print >> best_file, '%s\t%s\t%s\t%s\t%s\t%s' % (max_fsc_idx[0], max_fsc_idx[1], max_fsc_idx[2], max_fsc[0], max_fsc[1], max_fsc[2])
best_file.close()
if __name__ == "__main__":
main()
|
mit
| 5,016,354,970,529,404,000
| 37.69697
| 225
| 0.560515
| false
| 3.484839
| false
| false
| false
|
intel-ctrlsys/actsys
|
datastore/datastore/database_schema/schema_migration/versions/d43655797899_changing_table_name_from_group_to_.py
|
1
|
2060
|
"""Changing table name from 'group' to 'device_group'
Revision ID: d43655797899
Revises: 38f3c80e9932
Create Date: 2017-08-24 15:17:10.671537
"""
import textwrap
from alembic import op
# revision identifiers, used by Alembic.
revision = 'd43655797899'
down_revision = '38f3c80e9932'
branch_labels = None
depends_on = None
def upgrade():
op.execute(textwrap.dedent("""ALTER TABLE public.group RENAME TO device_group;"""))
op.execute(textwrap.dedent("""
CREATE OR REPLACE FUNCTION public.upsert_group(p_group_name character varying, p_device_list character varying)
RETURNS integer AS
$BODY$
DECLARE num_rows integer;
BEGIN
INSERT INTO public.device_group AS gro (group_name, device_list)
VALUES (p_group_name, p_device_list)
ON CONFLICT (group_name) DO UPDATE
SET
device_list = p_device_list
WHERE gro.group_name = p_group_name;
GET DIAGNOSTICS num_rows = ROW_COUNT;
RETURN num_rows;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;"""))
def downgrade():
op.execute(textwrap.dedent("""ALTER TABLE device_group RENAME TO "group";"""))
op.execute(textwrap.dedent("""
CREATE OR REPLACE FUNCTION public.upsert_group(p_group_name character varying, p_device_list character varying)
RETURNS integer AS
$BODY$
DECLARE num_rows integer;
BEGIN
INSERT INTO public.group AS gro (group_name, device_list)
VALUES (p_group_name, p_device_list)
ON CONFLICT (group_name) DO UPDATE
SET
device_list = p_device_list
WHERE gro.group_name = p_group_name;
GET DIAGNOSTICS num_rows = ROW_COUNT;
RETURN num_rows;
END;
$BODY$
LANGUAGE plpgsql VOLATILE
COST 100;"""))
|
apache-2.0
| -1,239,599,158,944,896,800
| 33.333333
| 123
| 0.571845
| false
| 3.814815
| false
| false
| false
|
jorik041/stackprinter
|
app/lib/deliciousapi.py
|
2
|
50450
|
"""
Unofficial Python API for retrieving data from Delicious.com.
This module provides the following features plus some more:
* retrieving a URL's full public bookmarking history including
* users who bookmarked the URL including tags used for such bookmarks
and the creation time of the bookmark (up to YYYY-MM-DD granularity)
* top tags (up to a maximum of 10) including tag count
* title as stored on Delicious.com
* total number of bookmarks/users for this URL at Delicious.com
* retrieving a user's full bookmark collection, including any private bookmarks
if you know the corresponding password
* retrieving a user's full public tagging vocabulary, i.e. tags and tag counts
* retrieving a user's network information (network members and network fans)
* HTTP proxy support
* updated to support Delicious.com "version 2" (mini-relaunch as of August 2008)
The official Delicious.com API and the JSON/RSS feeds do not provide all
the functionality mentioned above, and in such cases this module will query
the Delicious.com *website* directly and extract the required information
by parsing the HTML code of the resulting Web pages (a kind of poor man's
web mining). The module is able to detect IP throttling, which is employed
by Delicious.com to temporarily block abusive HTTP request behavior, and
will raise a custom Python error to indicate that. Please be a nice netizen
and do not stress the Delicious.com service more than necessary.
It is strongly advised that you read the Delicious.com Terms of Use
before using this Python module. In particular, read section 5
'Intellectual Property'.
The code is licensed to you under version 2 of the GNU General Public
License.
More information about this module can be found at
http://www.michael-noll.com/wiki/Del.icio.us_Python_API
Changelog is available at
http://code.michael-noll.com/?p=deliciousapi;a=log
Copyright 2006-2010 Michael G. Noll <http://www.michael-noll.com/>
"""
__author__ = "Michael G. Noll"
__copyright__ = "(c) 2006-2010 Michael G. Noll"
__description__ = "Unofficial Python API for retrieving data from Delicious.com"
__email__ = "coding[AT]michael-REMOVEME-noll[DOT]com"
__license__ = "GPLv2"
__maintainer__ = "Michael G. Noll"
__status__ = "Development"
__url__ = "http://www.michael-noll.com/"
__version__ = "1.6.3"
import base64
import cgi
import datetime
import hashlib
from operator import itemgetter
import re
import socket
import time
import urllib2
import xml.dom.minidom
try:
from BeautifulSoup import BeautifulSoup
except:
print "ERROR: could not import BeautifulSoup Python module"
print
print "You can download BeautifulSoup from the Python Cheese Shop at"
print "http://cheeseshop.python.org/pypi/BeautifulSoup/"
print "or directly from http://www.crummy.com/software/BeautifulSoup/"
print
raise
try:
from app.lib import simplejson
except:
print "ERROR: could not import simplejson module"
print
print "Since version 1.5.0, DeliciousAPI requires the simplejson module."
print "You can download simplejson from the Python Cheese Shop at"
print "http://pypi.python.org/pypi/simplejson"
print
raise
class DeliciousUser(object):
"""This class wraps all available information about a user into one object.
Variables:
bookmarks:
A list of (url, tags, title, comment, timestamp) tuples representing
a user's bookmark collection.
url is a 'unicode'
tags is a 'list' of 'unicode' ([] if no tags)
title is a 'unicode'
comment is a 'unicode' (u"" if no comment)
timestamp is a 'datetime.datetime'
tags (read-only property):
A list of (tag, tag_count) tuples, aggregated over all a user's
retrieved bookmarks. The tags represent a user's tagging vocabulary.
username:
The Delicious.com account name of the user.
"""
def __init__(self, username, bookmarks=None):
assert username
self.username = username
self.bookmarks = bookmarks or []
def __str__(self):
total_tag_count = 0
total_tags = set()
for url, tags, title, comment, timestamp in self.bookmarks:
if tags:
total_tag_count += len(tags)
for tag in tags:
total_tags.add(tag)
return "[%s] %d bookmarks, %d tags (%d unique)" % \
(self.username, len(self.bookmarks), total_tag_count, len(total_tags))
def __repr__(self):
return self.username
def get_tags(self):
"""Returns a dictionary mapping tags to their tag count.
For example, if the tag count of tag 'foo' is 23, then
23 bookmarks were annotated with 'foo'. A different way
to put it is that 23 users used the tag 'foo' when
bookmarking the URL.
"""
total_tags = {}
for url, tags, title, comment, timestamp in self.bookmarks:
for tag in tags:
total_tags[tag] = total_tags.get(tag, 0) + 1
return total_tags
tags = property(fget=get_tags, doc="Returns a dictionary mapping tags to their tag count")
class DeliciousURL(object):
"""This class wraps all available information about a web document into one object.
Variables:
bookmarks:
A list of (user, tags, comment, timestamp) tuples, representing a
document's bookmark history. Generally, this variable is populated
via get_url(), so the number of bookmarks available in this variable
depends on the parameters of get_url(). See get_url() for more
information.
user is a 'unicode'
tags is a 'list' of 'unicode's ([] if no tags)
comment is a 'unicode' (u"" if no comment)
timestamp is a 'datetime.datetime' (granularity: creation *day*,
i.e. the day but not the time of day)
tags (read-only property):
A list of (tag, tag_count) tuples, aggregated over all a document's
retrieved bookmarks.
top_tags:
A list of (tag, tag_count) tuples, representing a document's so-called
"top tags", i.e. the up to 10 most popular tags for this document.
url:
The URL of the document.
hash (read-only property):
The MD5 hash of the URL.
title:
The document's title.
total_bookmarks:
The number of total bookmarks (posts) of the document.
Note that the value of total_bookmarks can be greater than the
length of "bookmarks" depending on how much (detailed) bookmark
data could be retrieved from Delicious.com.
Here's some more background information:
The value of total_bookmarks is the "real" number of bookmarks of
URL "url" stored at Delicious.com as reported by Delicious.com
itself (so it's the "ground truth"). On the other hand, the length
of "bookmarks" depends on iteratively scraped bookmarking data.
Since scraping Delicous.com's Web pages has its limits in practice,
this means that DeliciousAPI could most likely not retrieve all
available bookmarks. In such a case, the value reported by
total_bookmarks is greater than the length of "bookmarks".
"""
def __init__(self, url, top_tags=None, bookmarks=None, title=u"", total_bookmarks=0):
assert url
self.url = url
self.top_tags = top_tags or []
self.bookmarks = bookmarks or []
self.title = title
self.total_bookmarks = total_bookmarks
def __str__(self):
total_tag_count = 0
total_tags = set()
for user, tags, comment, timestamp in self.bookmarks:
if tags:
total_tag_count += len(tags)
for tag in tags:
total_tags.add(tag)
return "[%s] %d total bookmarks (= users), %d tags (%d unique), %d out of 10 max 'top' tags" % \
(self.url, self.total_bookmarks, total_tag_count, \
len(total_tags), len(self.top_tags))
def __repr__(self):
return self.url
def get_tags(self):
"""Returns a dictionary mapping tags to their tag count.
For example, if the tag count of tag 'foo' is 23, then
23 bookmarks were annotated with 'foo'. A different way
to put it is that 23 users used the tag 'foo' when
bookmarking the URL.
@return: Dictionary mapping tags to their tag count.
"""
total_tags = {}
for user, tags, comment, timestamp in self.bookmarks:
for tag in tags:
total_tags[tag] = total_tags.get(tag, 0) + 1
return total_tags
tags = property(fget=get_tags, doc="Returns a dictionary mapping tags to their tag count")
def get_hash(self):
m = hashlib.md5()
m.update(self.url)
return m.hexdigest()
hash = property(fget=get_hash, doc="Returns the MD5 hash of the URL of this document")
class DeliciousAPI(object):
"""
This class provides a custom, unofficial API to the Delicious.com service.
Instead of using just the functionality provided by the official
Delicious.com API (which has limited features), this class retrieves
information from the Delicious.com website directly and extracts data from
the Web pages.
Note that Delicious.com will block clients with too many queries in a
certain time frame (similar to their API throttling). So be a nice citizen
and don't stress their website.
"""
def __init__(self,
http_proxy="",
tries=3,
wait_seconds=3,
user_agent="DeliciousAPI/%s (+http://www.michael-noll.com/wiki/Del.icio.us_Python_API)" % __version__,
timeout=30,
):
"""Set up the API module.
@param http_proxy: Optional, default: "".
Use an HTTP proxy for HTTP connections. Proxy support for
HTTPS is not available yet.
Format: "hostname:port" (e.g., "localhost:8080")
@type http_proxy: str
@param tries: Optional, default: 3.
Try the specified number of times when downloading a monitored
document fails. tries must be >= 1. See also wait_seconds.
@type tries: int
@param wait_seconds: Optional, default: 3.
Wait the specified number of seconds before re-trying to
download a monitored document. wait_seconds must be >= 0.
See also tries.
@type wait_seconds: int
@param user_agent: Optional, default: "DeliciousAPI/<version>
(+http://www.michael-noll.com/wiki/Del.icio.us_Python_API)".
The User-Agent HTTP Header to use when querying Delicous.com.
@type user_agent: str
@param timeout: Optional, default: 30.
Set network timeout. timeout must be >= 0.
@type timeout: int
"""
assert tries >= 1
assert wait_seconds >= 0
assert timeout >= 0
self.http_proxy = http_proxy
self.tries = tries
self.wait_seconds = wait_seconds
self.user_agent = user_agent
self.timeout = timeout
#socket.setdefaulttimeout(self.timeout)
def _query(self, path, host="delicious.com", user=None, password=None, use_ssl=False):
"""Queries Delicious.com for information, specified by (query) path.
@param path: The HTTP query path.
@type path: str
@param host: The host to query, default: "delicious.com".
@type host: str
@param user: The Delicious.com username if any, default: None.
@type user: str
@param password: The Delicious.com password of user, default: None.
@type password: unicode/str
@param use_ssl: Whether to use SSL encryption or not, default: False.
@type use_ssl: bool
@return: None on errors (i.e. on all HTTP status other than 200).
On success, returns the content of the HTML response.
"""
opener = None
handlers = []
# add HTTP Basic authentication if available
if user and password:
pwd_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
pwd_mgr.add_password(None, host, user, password)
basic_auth_handler = urllib2.HTTPBasicAuthHandler(pwd_mgr)
handlers.append(basic_auth_handler)
# add proxy support if requested
if self.http_proxy:
proxy_handler = urllib2.ProxyHandler({'http': 'http://%s' % self.http_proxy})
handlers.append(proxy_handler)
if handlers:
opener = urllib2.build_opener(*handlers)
else:
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', self.user_agent)]
data = None
tries = self.tries
if use_ssl:
protocol = "https"
else:
protocol = "http"
url = "%s://%s%s" % (protocol, host, path)
while tries > 0:
try:
f = opener.open(url)
data = f.read()
f.close()
break
except urllib2.HTTPError, e:
if e.code == 301:
raise DeliciousMovedPermanentlyWarning, "Delicious.com status %s - url moved permanently" % e.code
if e.code == 302:
raise DeliciousMovedTemporarilyWarning, "Delicious.com status %s - url moved temporarily" % e.code
elif e.code == 401:
raise DeliciousUnauthorizedError, "Delicious.com error %s - unauthorized (authentication failed?)" % e.code
elif e.code == 403:
raise DeliciousForbiddenError, "Delicious.com error %s - forbidden" % e.code
elif e.code == 404:
raise DeliciousNotFoundError, "Delicious.com error %s - url not found" % e.code
elif e.code == 500:
raise Delicious500Error, "Delicious.com error %s - server problem" % e.code
elif e.code == 503 or e.code == 999:
raise DeliciousThrottleError, "Delicious.com error %s - unable to process request (your IP address has been throttled/blocked)" % e.code
else:
raise DeliciousUnknownError, "Delicious.com error %s - unknown error" % e.code
break
except urllib2.URLError, e:
time.sleep(self.wait_seconds)
except socket.error, msg:
# sometimes we get a "Connection Refused" error
# wait a bit and then try again
time.sleep(self.wait_seconds)
#finally:
# f.close()
tries -= 1
return data
def get_url(self, url, max_bookmarks=50, sleep_seconds=1):
"""
Returns a DeliciousURL instance representing the Delicious.com history of url.
Generally, this method is what you want for getting title, bookmark, tag,
and user information about a URL.
Delicious only returns up to 50 bookmarks per URL. This means that
we have to do subsequent queries plus parsing if we want to retrieve
more than 50. Roughly speaking, the processing time of get_url()
increases linearly with the number of 50-bookmarks-chunks; i.e.
it will take 10 times longer to retrieve 500 bookmarks than 50.
@param url: The URL of the web document to be queried for.
@type url: str
@param max_bookmarks: Optional, default: 50.
See the documentation of get_bookmarks() for more information
as get_url() uses get_bookmarks() to retrieve a url's
bookmarking history.
@type max_bookmarks: int
@param sleep_seconds: Optional, default: 1.
See the documentation of get_bookmarks() for more information
as get_url() uses get_bookmarks() to retrieve a url's
bookmarking history. sleep_seconds must be >= 1 to comply with
Delicious.com's Terms of Use.
@type sleep_seconds: int
@return: DeliciousURL instance representing the Delicious.com history
of url.
"""
# we must wait at least 1 second between subsequent queries to
# comply with Delicious.com's Terms of Use
assert sleep_seconds >= 1
document = DeliciousURL(url)
m = hashlib.md5()
m.update(url)
hash = m.hexdigest()
path = "/v2/json/urlinfo/%s" % hash
data = self._query(path, host="feeds.delicious.com")
if data:
urlinfo = {}
try:
urlinfo = simplejson.loads(data)
if urlinfo:
urlinfo = urlinfo[0]
else:
urlinfo = {}
except TypeError:
pass
try:
document.title = urlinfo['title'] or u""
except KeyError:
pass
try:
top_tags = urlinfo['top_tags'] or {}
if top_tags:
document.top_tags = sorted(top_tags.iteritems(), key=itemgetter(1), reverse=True)
else:
document.top_tags = []
except KeyError:
pass
try:
document.total_bookmarks = int(urlinfo['total_posts'])
except (KeyError, ValueError):
pass
document.bookmarks = self.get_bookmarks(url=url, max_bookmarks=max_bookmarks, sleep_seconds=sleep_seconds)
return document
def get_network(self, username):
"""
Returns the user's list of followees and followers.
Followees are users in his Delicious "network", i.e. those users whose
bookmark streams he's subscribed to. Followers are his Delicious.com
"fans", i.e. those users who have subscribed to the given user's
bookmark stream).
Example:
A --------> --------> C
D --------> B --------> E
F --------> --------> F
followers followees
of B of B
Arrows from user A to user B denote that A has subscribed to B's
bookmark stream, i.e. A is "following" or "tracking" B.
Note that user F is both a followee and a follower of B, i.e. F tracks
B and vice versa. In Delicious.com terms, F is called a "mutual fan"
of B.
Comparing this network concept to information retrieval, one could say
that followers are incoming links and followees outgoing links of B.
@param username: Delicous.com username for which network information is
retrieved.
@type username: unicode/str
@return: Tuple of two lists ([<followees>, [<followers>]), where each list
contains tuples of (username, tracking_since_timestamp).
If a network is set as private, i.e. hidden from public view,
(None, None) is returned.
If a network is public but empty, ([], []) is returned.
"""
assert username
followees = followers = None
# followees (network members)
path = "/v2/json/networkmembers/%s" % username
data = None
try:
data = self._query(path, host="feeds.delicious.com")
except DeliciousForbiddenError:
pass
if data:
followees = []
users = []
try:
users = simplejson.loads(data)
except TypeError:
pass
uname = tracking_since = None
for user in users:
# followee's username
try:
uname = user['user']
except KeyError:
pass
# try to convert uname to Unicode
if uname:
try:
# we assume UTF-8 encoding
uname = uname.decode('utf-8')
except UnicodeDecodeError:
pass
# time when the given user started tracking this user
try:
tracking_since = datetime.datetime.strptime(user['dt'], "%Y-%m-%dT%H:%M:%SZ")
except KeyError:
pass
if uname:
followees.append( (uname, tracking_since) )
# followers (network fans)
path = "/v2/json/networkfans/%s" % username
data = None
try:
data = self._query(path, host="feeds.delicious.com")
except DeliciousForbiddenError:
pass
if data:
followers = []
users = []
try:
users = simplejson.loads(data)
except TypeError:
pass
uname = tracking_since = None
for user in users:
# fan's username
try:
uname = user['user']
except KeyError:
pass
# try to convert uname to Unicode
if uname:
try:
# we assume UTF-8 encoding
uname = uname.decode('utf-8')
except UnicodeDecodeError:
pass
# time when fan started tracking the given user
try:
tracking_since = datetime.datetime.strptime(user['dt'], "%Y-%m-%dT%H:%M:%SZ")
except KeyError:
pass
if uname:
followers.append( (uname, tracking_since) )
return ( followees, followers )
def get_bookmarks(self, url=None, username=None, max_bookmarks=50, sleep_seconds=1):
"""
Returns the bookmarks of url or user, respectively.
Delicious.com only returns up to 50 bookmarks per URL on its website.
This means that we have to do subsequent queries plus parsing if
we want to retrieve more than 50. Roughly speaking, the processing
time of get_bookmarks() increases linearly with the number of
50-bookmarks-chunks; i.e. it will take 10 times longer to retrieve
500 bookmarks than 50.
@param url: The URL of the web document to be queried for.
Cannot be used together with 'username'.
@type url: str
@param username: The Delicious.com username to be queried for.
Cannot be used together with 'url'.
@type username: str
@param max_bookmarks: Optional, default: 50.
Maximum number of bookmarks to retrieve. Set to 0 to disable
this limitation/the maximum and retrieve all available
bookmarks of the given url.
Bookmarks are sorted so that newer bookmarks are first.
Setting max_bookmarks to 50 means that get_bookmarks() will retrieve
the 50 most recent bookmarks of the given url.
In the case of getting bookmarks of a URL (url is set),
get_bookmarks() will take *considerably* longer to run
for pages with lots of bookmarks when setting max_bookmarks
to a high number or when you completely disable the limit.
Delicious returns only up to 50 bookmarks per result page,
so for example retrieving 250 bookmarks requires 5 HTTP
connections and parsing 5 HTML pages plus wait time between
queries (to comply with delicious' Terms of Use; see
also parameter 'sleep_seconds').
In the case of getting bookmarks of a user (username is set),
the same restrictions as for a URL apply with the exception
that we can retrieve up to 100 bookmarks per HTTP query
(instead of only up to 50 per HTTP query for a URL).
@type max_bookmarks: int
@param sleep_seconds: Optional, default: 1.
Wait the specified number of seconds between subsequent
queries in case that there are multiple pages of bookmarks
for the given url. sleep_seconds must be >= 1 to comply with
Delicious.com's Terms of Use.
See also parameter 'max_bookmarks'.
@type sleep_seconds: int
@return: Returns the bookmarks of url or user, respectively.
For urls, it returns a list of (user, tags, comment, timestamp)
tuples.
For users, it returns a list of (url, tags, title, comment,
timestamp) tuples.
Bookmarks are sorted "descendingly" by creation time, i.e. newer
bookmarks come first.
"""
# we must wait at least 1 second between subsequent queries to
# comply with delicious' Terms of Use
assert sleep_seconds >= 1
# url XOR username
assert bool(username) is not bool(url)
# maximum number of urls/posts Delicious.com will display
# per page on its website
max_html_count = 100
# maximum number of pages that Delicious.com will display;
# currently, the maximum number of pages is 20. Delicious.com
# allows to go beyond page 20 via pagination, but page N (for
# N > 20) will always display the same content as page 20.
max_html_pages = 20
path = None
if url:
m = hashlib.md5()
m.update(url)
hash = m.hexdigest()
# path will change later on if there are multiple pages of boomarks
# for the given url
path = "/url/%s" % hash
elif username:
# path will change later on if there are multiple pages of boomarks
# for the given username
path = "/%s?setcount=%d" % (username, max_html_count)
else:
raise Exception('You must specify either url or user.')
page_index = 1
bookmarks = []
while path and page_index <= max_html_pages:
data = self._query(path)
path = None
if data:
# extract bookmarks from current page
if url:
bookmarks.extend(self._extract_bookmarks_from_url_history(data))
else:
bookmarks.extend(self._extract_bookmarks_from_user_history(data))
# stop scraping if we already have as many bookmarks as we want
if (len(bookmarks) >= max_bookmarks) and max_bookmarks != 0:
break
else:
# check if there are multiple pages of bookmarks for this
# url on Delicious.com
soup = BeautifulSoup(data)
paginations = soup.findAll("div", id="pagination")
if paginations:
# find next path
nexts = paginations[0].findAll("a", attrs={ "class": "pn next" })
if nexts and (max_bookmarks == 0 or len(bookmarks) < max_bookmarks) and len(bookmarks) > 0:
# e.g. /url/2bb293d594a93e77d45c2caaf120e1b1?show=all&page=2
path = nexts[0]['href']
if username:
path += "&setcount=%d" % max_html_count
page_index += 1
# wait one second between queries to be compliant with
# delicious' Terms of Use
time.sleep(sleep_seconds)
if max_bookmarks > 0:
return bookmarks[:max_bookmarks]
else:
return bookmarks
def _extract_bookmarks_from_url_history(self, data):
"""
Extracts user bookmarks from a URL's history page on Delicious.com.
The Python library BeautifulSoup is used to parse the HTML page.
@param data: The HTML source of a URL history Web page on Delicious.com.
@type data: str
@return: list of user bookmarks of the corresponding URL
"""
bookmarks = []
soup = BeautifulSoup(data)
bookmark_elements = soup.findAll("div", attrs={"class": re.compile("^bookmark\s*")})
timestamp = None
for bookmark_element in bookmark_elements:
# extract bookmark creation time
#
# this timestamp has to "persist" until a new timestamp is
# found (delicious only provides the creation time data for the
# first bookmark in the list of bookmarks for a given day
dategroups = bookmark_element.findAll("div", attrs={"class": "dateGroup"})
if dategroups:
spans = dategroups[0].findAll('span')
if spans:
date_str = spans[0].contents[0].strip()
timestamp = datetime.datetime.strptime(date_str, '%d %b %y')
# extract comments
comment = u""
datas = bookmark_element.findAll("div", attrs={"class": "data"})
if datas:
divs = datas[0].findAll("div", attrs={"class": "description"})
if divs:
comment = divs[0].contents[0].strip()
# extract tags
user_tags = []
tagdisplays = bookmark_element.findAll("div", attrs={"class": "tagdisplay"})
if tagdisplays:
spans = tagdisplays[0].findAll("span", attrs={"class": "tagItem"})
for span in spans:
tag = span.contents[0]
user_tags.append(tag)
# extract user information
metas = bookmark_element.findAll("div", attrs={"class": "meta"})
if metas:
links = metas[0].findAll("a", attrs={"class": "user user-tag"})
if links:
user_a = links[0]
spans = user_a.findAll('span')
if spans:
try:
user = spans[0].contents[0]
except IndexError:
# WORKAROUND: it seems there is a bug on Delicious.com where
# sometimes a bookmark is shown in a URL history without any
# associated Delicious username (username is empty); this could
# be caused by special characters in the username or other things
#
# this problem of Delicious is very rare, so we just skip such
# entries until they find a fix
pass
bookmarks.append( (user, user_tags, comment, timestamp) )
return bookmarks
def _extract_bookmarks_from_user_history(self, data):
"""
Extracts a user's bookmarks from his user page on Delicious.com.
The Python library BeautifulSoup is used to parse the HTML page.
@param data: The HTML source of a user page on Delicious.com.
@type data: str
@return: list of bookmarks of the corresponding user
"""
bookmarks = []
soup = BeautifulSoup(data)
ul = soup.find("ul", id="bookmarklist")
if ul:
bookmark_elements = ul.findAll("div", attrs={"class": re.compile("^bookmark\s*")})
timestamp = None
for bookmark_element in bookmark_elements:
# extract bookmark creation time
#
# this timestamp has to "persist" until a new timestamp is
# found (delicious only provides the creation time data for the
# first bookmark in the list of bookmarks for a given day
dategroups = bookmark_element.findAll("div", attrs={"class": "dateGroup"})
if dategroups:
spans = dategroups[0].findAll('span')
if spans:
date_str = spans[0].contents[0].strip()
timestamp = datetime.datetime.strptime(date_str, '%d %b %y')
# extract url, title and comments
url = u""
title = u""
comment = u""
datas = bookmark_element.findAll("div", attrs={"class": "data"})
if datas:
links = datas[0].findAll("a", attrs={"class": re.compile("^taggedlink\s*")})
if links:
title = links[0].contents[0].strip()
url = links[0]['href']
divs = datas[0].findAll("div", attrs={"class": "description"})
if divs:
comment = divs[0].contents[0].strip()
# extract tags
url_tags = []
tagdisplays = bookmark_element.findAll("div", attrs={"class": "tagdisplay"})
if tagdisplays:
spans = tagdisplays[0].findAll("span", attrs={"class": "tagItem"})
for span in spans:
tag = span.contents[0]
url_tags.append(tag)
bookmarks.append( (url, url_tags, title, comment, timestamp) )
return bookmarks
def get_user(self, username, password=None, max_bookmarks=50, sleep_seconds=1):
"""Retrieves a user's bookmarks from Delicious.com.
If a correct username AND password are supplied, a user's *full*
bookmark collection (which also includes private bookmarks) is
retrieved. Data communication is encrypted using SSL in this case.
If no password is supplied, only the *public* bookmarks of the user
are retrieved. Here, the parameter 'max_bookmarks' specifies how
many public bookmarks will be retrieved (default: 50). Set the
parameter to 0 to retrieve all public bookmarks.
This function can be used to backup all of a user's bookmarks if
called with a username and password.
@param username: The Delicious.com username.
@type username: str
@param password: Optional, default: None.
The user's Delicious.com password. If password is set,
all communication with Delicious.com is SSL-encrypted.
@type password: unicode/str
@param max_bookmarks: Optional, default: 50.
See the documentation of get_bookmarks() for more
information as get_url() uses get_bookmarks() to
retrieve a url's bookmarking history.
The parameter is NOT used when a password is specified
because in this case the *full* bookmark collection of
a user will be retrieved.
@type max_bookmarks: int
@param sleep_seconds: Optional, default: 1.
See the documentation of get_bookmarks() for more information as
get_url() uses get_bookmarks() to retrieve a url's bookmarking
history. sleep_seconds must be >= 1 to comply with Delicious.com's
Terms of Use.
@type sleep_seconds: int
@return: DeliciousUser instance
"""
assert username
user = DeliciousUser(username)
bookmarks = []
if password:
# We have username AND password, so we call
# the official Delicious.com API.
path = "/v1/posts/all"
data = self._query(path, host="api.del.icio.us", use_ssl=True, user=username, password=password)
if data:
soup = BeautifulSoup(data)
elements = soup.findAll("post")
for element in elements:
url = element["href"]
title = element["description"] or u""
comment = element["extended"] or u""
tags = []
if element["tag"]:
tags = element["tag"].split()
timestamp = datetime.datetime.strptime(element["time"], "%Y-%m-%dT%H:%M:%SZ")
bookmarks.append( (url, tags, title, comment, timestamp) )
user.bookmarks = bookmarks
else:
# We have only the username, so we extract data from
# the user's JSON feed. However, the feed is restricted
# to the most recent public bookmarks of the user, which
# is about 100 if any. So if we need more than 100, we start
# scraping the Delicious.com website directly
if max_bookmarks > 0 and max_bookmarks <= 100:
path = "/v2/json/%s/stackoverflow?count=100" % username
data = self._query(path, host="feeds.delicious.com", user=username)
if data:
posts = []
try:
posts = simplejson.loads(data)
except TypeError:
pass
url = timestamp = None
title = comment = u""
tags = []
for post in posts:
# url
try:
url = post['u']
except KeyError:
pass
# title
try:
title = post['d']
except KeyError:
pass
# tags
try:
tags = post['t']
except KeyError:
pass
if not tags:
tags = [u"system:unfiled"]
# comment / notes
try:
comment = post['n']
except KeyError:
pass
# bookmark creation time
try:
timestamp = datetime.datetime.strptime(post['dt'], "%Y-%m-%dT%H:%M:%SZ")
except KeyError:
pass
bookmarks.append( (url, tags, title, comment, timestamp) )
user.bookmarks = bookmarks[:max_bookmarks]
else:
# TODO: retrieve the first 100 bookmarks via JSON before
# falling back to scraping the delicous.com website
user.bookmarks = self.get_bookmarks(username=username, max_bookmarks=max_bookmarks, sleep_seconds=sleep_seconds)
return user
def get_urls(self, tag=None, popular=True, max_urls=100, sleep_seconds=1):
"""
Returns the list of recent URLs (of web documents) tagged with a given tag.
This is very similar to parsing Delicious' RSS/JSON feeds directly,
but this function will return up to 2,000 links compared to a maximum
of 100 links when using the official feeds (with query parameter
count=100).
The return list of links will be sorted by recency in descending order,
i.e. newest items first.
Note that even when setting max_urls, get_urls() cannot guarantee that
it can retrieve *at least* this many URLs. It is really just an upper
bound.
@param tag: Retrieve links which have been tagged with the given tag.
If tag is not set (default), links will be retrieved from the
Delicious.com front page (aka "delicious hotlist").
@type tag: unicode/str
@param popular: If true (default), retrieve only popular links (i.e.
/popular/<tag>). Otherwise, the most recent links tagged with
the given tag will be retrieved (i.e. /tag/<tag>).
As of January 2009, it seems that Delicious.com modified the list
of popular tags to contain only up to a maximum of 15 URLs.
This also means that setting max_urls to values larger than 15
will not change the results of get_urls().
So if you are interested in more URLs, set the "popular" parameter
to false.
Note that if you set popular to False, the returned list of URLs
might contain duplicate items. This is due to the way Delicious.com
creates its /tag/<tag> Web pages. So if you need a certain
number of unique URLs, you have to take care of that in your
own code.
@type popular: bool
@param max_urls: Retrieve at most max_urls links. The default is 100,
which is the maximum number of links that can be retrieved by
parsing the official JSON feeds. The maximum value of max_urls
in practice is 2000 (currently). If it is set higher, Delicious
will return the same links over and over again, giving lots of
duplicate items.
@type max_urls: int
@param sleep_seconds: Optional, default: 1.
Wait the specified number of seconds between subsequent queries in
case that there are multiple pages of bookmarks for the given url.
Must be greater than or equal to 1 to comply with Delicious.com's
Terms of Use.
See also parameter 'max_urls'.
@type sleep_seconds: int
@return: The list of recent URLs (of web documents) tagged with a given tag.
"""
assert sleep_seconds >= 1
urls = []
path = None
if tag is None or (tag is not None and max_urls > 0 and max_urls <= 100):
# use official JSON feeds
max_json_count = 100
if tag:
# tag-specific JSON feed
if popular:
path = "/v2/json/popular/%s?count=%d" % (tag, max_json_count)
else:
path = "/v2/json/tag/%s?count=%d" % (tag, max_json_count)
else:
# Delicious.com hotlist
path = "/v2/json/?count=%d" % (max_json_count)
data = self._query(path, host="feeds.delicious.com")
if data:
posts = []
try:
posts = simplejson.loads(data)
except TypeError:
pass
for post in posts:
# url
try:
url = post['u']
if url:
urls.append(url)
except KeyError:
pass
else:
# maximum number of urls/posts Delicious.com will display
# per page on its website
max_html_count = 100
# maximum number of pages that Delicious.com will display;
# currently, the maximum number of pages is 20. Delicious.com
# allows to go beyond page 20 via pagination, but page N (for
# N > 20) will always display the same content as page 20.
max_html_pages = 20
if popular:
path = "/popular/%s?setcount=%d" % (tag, max_html_count)
else:
path = "/tag/%s?setcount=%d" % (tag, max_html_count)
page_index = 1
urls = []
while path and page_index <= max_html_pages:
data = self._query(path)
path = None
if data:
# extract urls from current page
soup = BeautifulSoup(data)
links = soup.findAll("a", attrs={"class": re.compile("^taggedlink\s*")})
for link in links:
try:
url = link['href']
if url:
urls.append(url)
except KeyError:
pass
# check if there are more multiple pages of urls
soup = BeautifulSoup(data)
paginations = soup.findAll("div", id="pagination")
if paginations:
# find next path
nexts = paginations[0].findAll("a", attrs={ "class": "pn next" })
if nexts and (max_urls == 0 or len(urls) < max_urls) and len(urls) > 0:
# e.g. /url/2bb293d594a93e77d45c2caaf120e1b1?show=all&page=2
path = nexts[0]['href']
path += "&setcount=%d" % max_html_count
page_index += 1
# wait between queries to Delicious.com to be
# compliant with its Terms of Use
time.sleep(sleep_seconds)
if max_urls > 0:
return urls[:max_urls]
else:
return urls
def get_tags_of_user(self, username):
"""
Retrieves user's public tags and their tag counts from Delicious.com.
The tags represent a user's full public tagging vocabulary.
DeliciousAPI uses the official JSON feed of the user. We could use
RSS here, but the JSON feed has proven to be faster in practice.
@param username: The Delicious.com username.
@type username: str
@return: Dictionary mapping tags to their tag counts.
"""
tags = {}
path = "/v2/json/tags/%s" % username
data = self._query(path, host="feeds.delicious.com")
if data:
try:
tags = simplejson.loads(data)
except TypeError:
pass
return tags
def get_number_of_users(self, url):
"""get_number_of_users() is obsolete and has been removed. Please use get_url() instead."""
reason = "get_number_of_users() is obsolete and has been removed. Please use get_url() instead."
raise Exception(reason)
def get_common_tags_of_url(self, url):
"""get_common_tags_of_url() is obsolete and has been removed. Please use get_url() instead."""
reason = "get_common_tags_of_url() is obsolete and has been removed. Please use get_url() instead."
raise Exception(reason)
def _html_escape(self, s):
"""HTML-escape a string or object.
This converts any non-string objects passed into it to strings
(actually, using unicode()). All values returned are
non-unicode strings (using "&#num;" entities for all non-ASCII
characters).
None is treated specially, and returns the empty string.
@param s: The string that needs to be escaped.
@type s: str
@return: The escaped string.
"""
if s is None:
return ''
if not isinstance(s, basestring):
if hasattr(s, '__unicode__'):
s = unicode(s)
else:
s = str(s)
s = cgi.escape(s, True)
if isinstance(s, unicode):
s = s.encode('ascii', 'xmlcharrefreplace')
return s
class DeliciousError(Exception):
"""Used to indicate that an error occurred when trying to access Delicious.com via its API."""
class DeliciousWarning(Exception):
"""Used to indicate a warning when trying to access Delicious.com via its API.
Warnings are raised when it is useful to alert the user of some condition
where that condition doesn't warrant raising an exception and terminating
the program. For example, we issue a warning when Delicious.com returns a
HTTP status code for redirections (3xx).
"""
class DeliciousThrottleError(DeliciousError):
"""Used to indicate that the client computer (i.e. its IP address) has been temporarily blocked by Delicious.com."""
pass
class DeliciousUnknownError(DeliciousError):
"""Used to indicate that Delicious.com returned an (HTTP) error which we don't know how to handle yet."""
pass
class DeliciousUnauthorizedError(DeliciousError):
"""Used to indicate that Delicious.com returned a 401 Unauthorized error.
Most of the time, the user credentials for accessing restricted functions
of the official Delicious.com API are incorrect.
"""
pass
class DeliciousForbiddenError(DeliciousError):
"""Used to indicate that Delicious.com returned a 403 Forbidden error.
"""
pass
class DeliciousNotFoundError(DeliciousError):
"""Used to indicate that Delicious.com returned a 404 Not Found error.
Most of the time, retrying some seconds later fixes the problem
(because we only query existing pages with this API).
"""
pass
class Delicious500Error(DeliciousError):
"""Used to indicate that Delicious.com returned a 500 error.
Most of the time, retrying some seconds later fixes the problem.
"""
pass
class DeliciousMovedPermanentlyWarning(DeliciousWarning):
"""Used to indicate that Delicious.com returned a 301 Found (Moved Permanently) redirection."""
pass
class DeliciousMovedTemporarilyWarning(DeliciousWarning):
"""Used to indicate that Delicious.com returned a 302 Found (Moved Temporarily) redirection."""
pass
__all__ = ['DeliciousAPI', 'DeliciousURL', 'DeliciousError', 'DeliciousThrottleError', 'DeliciousUnauthorizedError', 'DeliciousUnknownError', 'DeliciousNotFoundError' , 'Delicious500Error', 'DeliciousMovedTemporarilyWarning']
if __name__ == "__main__":
d = DeliciousAPI()
max_bookmarks = 50
url = 'http://www.michael-noll.com/wiki/Del.icio.us_Python_API'
print "Retrieving Delicious.com information about url"
print "'%s'" % url
print "Note: This might take some time..."
print "========================================================="
document = d.get_url(url, max_bookmarks=max_bookmarks)
print document
|
bsd-3-clause
| 3,970,781,760,770,663,400
| 39.263368
| 225
| 0.565451
| false
| 4.53198
| false
| false
| false
|
hugobranquinho/ines
|
ines/__init__.py
|
1
|
1198
|
# -*- coding: utf-8 -*-
import datetime
import errno
from os import getpid, linesep, uname
from os.path import join as os_join
import sys
from tempfile import gettempdir
from time import time as _now_time
APPLICATIONS = {}
CAMELCASE_UPPER_WORDS = {'CSV'}
MARKER = object()
API_CONFIGURATION_EXTENSIONS = {}
DEFAULT_RENDERERS = {}
DEFAULT_METHODS = ['GET', 'PUT', 'POST', 'DELETE']
IGNORE_FULL_NAME_WORDS = ['de', 'da', 'e', 'do']
PROCESS_ID = getpid()
SYSTEM_NAME, DOMAIN_NAME, SYSTEM_RELEASE, SYSTEM_VERSION, MACHINE = uname()
DEFAULT_CACHE_DIRPATH = os_join(gettempdir(), 'ines-cache')
DEFAULT_RETRY_ERRNO = {errno.ESTALE}
DEFAULT_RETRY_ERRNO.add(116) # Stale NFS file handle
OPEN_BLOCK_SIZE = 2**18
# datetime now without microseconds
_now = datetime.datetime.now
NOW = lambda: _now().replace(microsecond=0)
# timestamp without microseconds
NOW_TIME = lambda: int(_now_time())
TODAY_DATE = datetime.date.today
HTML_NEW_LINE = '<br/>'
NEW_LINE = linesep
NEW_LINE_AS_BYTES = NEW_LINE.encode()
def lazy_import_module(name):
module = sys.modules.get(name, MARKER)
if module is not MARKER:
return module
else:
__import__(name)
return sys.modules[name]
|
mit
| 6,989,389,053,462,082,000
| 23.958333
| 75
| 0.69616
| false
| 3.152632
| false
| false
| false
|
Dwolla/arbalest
|
examples/s3_json_object_to_redshift.py
|
1
|
2379
|
#!/usr/bin/env python
import psycopg2
from arbalest.configuration import env
from arbalest.redshift import S3CopyPipeline
from arbalest.redshift.schema import JsonObject, Property
"""
**Example: Bulk copy JSON objects from S3 bucket to Redshift table**
Arbalest orchestrates data loading using pipelines. Each `Pipeline`
can have one or many steps that are made up of three parts:
metadata: Path in an S3 bucket to store information needed for the copy process.
`s3://{BUCKET_NAME}/path_to_save_pipeline_metadata`
source: Path in an S3 bucket where data to be copied from is located.
`s3://{BUCKET_NAME}/path_of_source_data` consisting of JSON files:
```
{
"id": "66bc8153-d6d9-4351-bada-803330f22db7",
"someNumber": 1
}
```
schema: Definition of JSON objects to map into Redshift rows using a
`JsonObject` mapper which consists of one or many `Property` declarations.
By default the name of the JSON property is used as the column, but can be set
to a custom column name.
"""
if __name__ == '__main__':
pipeline = S3CopyPipeline(
aws_access_key_id=env('AWS_ACCESS_KEY_ID'),
aws_secret_access_key=env('AWS_SECRET_ACCESS_KEY'),
bucket=env('BUCKET_NAME'),
db_connection=psycopg2.connect(env('REDSHIFT_CONNECTION')))
pipeline.bulk_copy(metadata='path_to_save_pipeline_metadata',
source='path_of_source_data',
schema=JsonObject('destination_table_name',
Property('id', 'VARCHAR(36)'),
Property('someNumber', 'INTEGER',
'custom_column_name')))
pipeline.manifest_copy(metadata='path_to_save_pipeline_metadata',
source='path_of_incremental_source_data',
schema=JsonObject('incremental_destination_table_name',
Property('id', 'VARCHAR(36)'),
Property('someNumber', 'INTEGER',
'custom_column_name')))
pipeline.sql(('SELECT someNumber + %s '
'INTO some_olap_table FROM destination_table_name', 1),
('SELECT * INTO destination_table_name_copy '
'FROM destination_table_name'))
pipeline.run()
|
mit
| 2,963,051,004,563,553,000
| 38.65
| 82
| 0.599412
| false
| 4.12305
| false
| false
| false
|
hlmnrmr/superdesk-core
|
superdesk/tests/steps.py
|
1
|
91099
|
# -*- coding: utf-8; -*-
#
# This file is part of Superdesk.
#
# Copyright 2013, 2014 Sourcefabric z.u. and contributors.
#
# For the full copyright and license information, please see the
# AUTHORS and LICENSE files distributed with this source code, or
# at https://www.sourcefabric.org/superdesk/license
import os
import time
import shutil
from base64 import b64encode
from datetime import datetime, timedelta
from os.path import basename
from re import findall
from unittest.mock import patch
from urllib.parse import urlparse
import arrow
from behave import given, when, then # @UnresolvedImport
from bson import ObjectId
from eve.io.mongo import MongoJSONEncoder
from eve.methods.common import parse
from eve.utils import ParsedRequest, config
from flask import json
from wooper.assertions import (
assert_in, assert_equal, assertions
)
from wooper.general import (
fail_and_print_body, apply_path, parse_json_response,
WooperAssertionError
)
from wooper.expect import (
expect_status, expect_status_in,
expect_json, expect_json_length,
expect_json_contains, expect_json_not_contains,
expect_headers_contain,
)
import superdesk
from superdesk import tests
from superdesk.io import registered_feeding_services
from superdesk.io.commands.update_ingest import LAST_ITEM_UPDATE
from superdesk import default_user_preferences, get_resource_service, utc, etree
from superdesk.io.feed_parsers import XMLFeedParser, EMailRFC822FeedParser
from superdesk.utc import utcnow, get_expiry_date
from superdesk.tests import get_prefixed_url, set_placeholder
from apps.dictionaries.resource import DICTIONARY_FILE
from superdesk.filemeta import get_filemeta
external_url = 'http://thumbs.dreamstime.com/z/digital-nature-10485007.jpg'
DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S%z"
ANALYTICS_DATETIME_FORMAT = "%Y-%m-%d %H:00:00"
def test_json(context):
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data, response_data), True,
msg=str(context_data) + '\n != \n' + str(response_data))
return response_data
def test_json_with_string_field_value(context, field):
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data[field], response_data[field]), True,
msg=str(context_data) + '\n != \n' + str(response_data))
return response_data
def test_key_is_present(key, context, response):
"""Test if given key is present in response.
In case the context value is empty - "", {}, [] - it checks if it's non empty in response.
If it's set in context to false, it will check that it's falsy/empty in response too.
:param key
:param context
:param response
"""
assert not isinstance(context[key], bool) or not response[key], \
'"%s" should be empty or false, but it was "%s" in (%s)' % (key, response[key], response)
def test_key_is_not_present(key, response):
"""Test if given key is not present in response.
:param key
:param response
"""
assert key not in response, \
'"%s" should not be present, but it was "%s" in (%s)' % (key, response[key], response)
def assert_is_now(val, key):
"""Assert that given datetime value is now (with 2s tolerance).
:param val: datetime
:param key: val label - used for error reporting
"""
now = arrow.get()
val = arrow.get(val)
assert val + timedelta(seconds=2) > now, '%s should be now, it is %s' % (key, val)
def json_match(context_data, response_data):
if isinstance(context_data, dict):
if (not isinstance(response_data, dict)):
return False
for key in context_data:
if context_data[key] == "__none__":
assert response_data[key] is None
continue
if context_data[key] == "__no_value__":
test_key_is_not_present(key, response_data)
continue
if key not in response_data:
print(key, ' not in ', response_data)
return False
if context_data[key] == "__any_value__":
test_key_is_present(key, context_data, response_data)
continue
if context_data[key] == "__now__":
assert_is_now(response_data[key], key)
continue
if context_data[key] == "__empty__":
assert len(response_data[key]) == 0, '%s is not empty' % key
continue
if not json_match(context_data[key], response_data[key]):
return False
return True
elif isinstance(context_data, list):
for item_context in context_data:
found = False
for item_response in response_data:
if json_match(item_context, item_response):
found = True
break
if not found:
print(item_context, ' not in ', json.dumps(response_data, indent=2))
return False
return True
elif not isinstance(context_data, dict):
if context_data != response_data:
print('---' + str(context_data) + '---\n', ' != \n', '---' + str(response_data) + '---\n')
return context_data == response_data
def get_fixture_path(context, fixture):
path = context.app.settings['BEHAVE_TESTS_FIXTURES_PATH']
return os.path.join(path, fixture)
def get_macro_path(macro):
abspath = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
return os.path.join(abspath, 'macros', macro)
def get_self_href(resource, context):
assert '_links' in resource, 'expted "_links", but got only %s' % (resource)
return resource['_links']['self']['href']
def get_res(url, context):
response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
expect_status(response, 200)
return json.loads(response.get_data())
def parse_date(datestr):
return datetime.strptime(datestr, DATETIME_FORMAT)
def format_date(date_to_format):
return date_to_format.strftime(DATETIME_FORMAT)
def format_date_analytics(date_to_format):
return date_to_format.strftime(ANALYTICS_DATETIME_FORMAT)
def assert_200(response):
"""Assert we get status code 200."""
expect_status_in(response, (200, 201, 204))
def assert_404(response):
"""Assert we get status code 404."""
assert response.status_code == 404, 'Expected 404, got %d' % (response.status_code)
def assert_ok(response):
"""Assert we get ok status within api response."""
expect_status_in(response, (200, 201))
expect_json_contains(response, {'_status': 'OK'})
def get_json_data(response):
return json.loads(response.get_data())
def get_it(context):
it = context.data[0]
res = get_res('/%s/%s' % (context.resource, it['_id']), context)
return get_self_href(res, context), res.get('_etag')
def if_match(context, etag):
headers = []
if etag:
headers = [('If-Match', etag)]
headers = unique_headers(headers, context.headers)
return headers
def unique_headers(headers_to_add, old_headers):
headers = dict(old_headers)
for item in headers_to_add:
headers.update({item[0]: item[1]})
unique_headers = [(k, v) for k, v in headers.items()]
return unique_headers
def patch_current_user(context, data):
response = context.client.get(get_prefixed_url(context.app, '/users/%s' % context.user['_id']),
headers=context.headers)
user = json.loads(response.get_data())
headers = if_match(context, user.get('_etag'))
response = context.client.patch(get_prefixed_url(context.app, '/users/%s' % context.user['_id']),
data=data, headers=headers)
assert_ok(response)
return response
def apply_placeholders(context, text):
placeholders = getattr(context, 'placeholders', {})
for placeholder in findall('#([^#"]+)#', text):
if placeholder.startswith('DATE'):
value = utcnow()
unit = placeholder.find('+')
if unit != -1:
value += timedelta(days=int(placeholder[unit + 1]))
else:
unit = placeholder.find('-')
if unit != -1:
value -= timedelta(days=int(placeholder[unit + 1]))
if placeholder == 'ANALYTICS_DATE_FORMATTED':
value = format_date_analytics(value)
else:
value = format_date(value)
placeholders['LAST_DATE_VALUE'] = value
elif placeholder not in placeholders:
try:
resource_name, field_name = placeholder.split('.', maxsplit=1)
except Exception:
continue
resource = getattr(context, resource_name, None)
for name in field_name.split('.'):
if not resource:
break
resource = resource.get(name, None)
if not resource:
continue
if isinstance(resource, datetime):
value = format_date(resource)
else:
value = str(resource)
else:
value = placeholders[placeholder]
text = text.replace('#%s#' % placeholder, value)
return text
def get_resource_name(url):
parsed_url = urlparse(url)
return basename(parsed_url.path)
def format_items(items):
output = [''] # insert empty line
for item in items:
if item.get('formatted_item'):
item['formatted_item'] = json.loads(item['formatted_item'])
output.append(json.dumps(item, indent=4, sort_keys=True))
return ',\n'.join(output)
@given('empty "{resource}"')
def step_impl_given_empty(context, resource):
if not is_user_resource(resource):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
get_resource_service(resource).delete_action()
@given('"{resource}"')
def step_impl_given_(context, resource):
data = apply_placeholders(context, context.text)
with context.app.test_request_context(context.app.config['URL_PREFIX']):
if not is_user_resource(resource):
get_resource_service(resource).delete_action()
items = [parse(item, resource) for item in json.loads(data)]
if is_user_resource(resource):
for item in items:
item.setdefault('needs_activation', False)
get_resource_service(resource).post(items)
context.data = items
context.resource = resource
try:
setattr(context, resource, items[-1])
except KeyError:
pass
@given('"{resource}" with objectid')
def step_impl_given_with_objectid(context, resource):
data = apply_placeholders(context, context.text)
with context.app.test_request_context(context.app.config['URL_PREFIX']):
items = [parse(item, resource) for item in json.loads(data)]
for item in items:
if '_id' in item:
item['_id'] = ObjectId(item['_id'])
get_resource_service(resource).post(items)
context.data = items
context.resource = resource
setattr(context, resource, items[-1])
@given('the "{resource}"')
def step_impl_given_the(context, resource):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
if not is_user_resource(resource):
get_resource_service(resource).delete_action()
orig_items = {}
items = [parse(item, resource) for item in json.loads(context.text)]
get_resource_service(resource).post(items)
context.data = orig_items or items
context.resource = resource
@given('ingest from "{provider}"')
def step_impl_given_resource_with_provider(context, provider):
resource = 'ingest'
with context.app.test_request_context(context.app.config['URL_PREFIX']):
get_resource_service(resource).delete_action()
items = [parse(item, resource) for item in json.loads(context.text)]
ingest_provider = get_resource_service('ingest_providers').find_one(req=None,
_id=context.providers[provider])
for item in items:
item['ingest_provider'] = context.providers[provider]
item['source'] = ingest_provider.get('source')
get_resource_service(resource).post(items)
context.data = items
context.resource = resource
@given('config update')
def given_config_update(context):
diff = json.loads(context.text)
context.app.config.update(diff)
if 'AMAZON_CONTAINER_NAME' in diff:
from superdesk.storage import AmazonMediaStorage
context.app.media = AmazonMediaStorage(context.app)
m = patch.object(context.app.media, 'client')
m.start()
@given('config')
def step_impl_given_config(context):
tests.setup(context, json.loads(context.text))
tests.setup_auth_user(context)
@given('we have "{role_name}" role')
def step_impl_given_role(context, role_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
role = get_resource_service('roles').find_one(name=role_name, req=None)
data = MongoJSONEncoder().encode({'role': role.get('_id')})
response = patch_current_user(context, data)
assert_ok(response)
@given('we have "{user_type}" as type of user')
def step_impl_given_user_type(context, user_type):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
data = json.dumps({'user_type': user_type})
response = patch_current_user(context, data)
assert_ok(response)
@when('we post to auth_db')
def step_impl_when_auth(context):
data = context.text
context.response = context.client.post(
get_prefixed_url(context.app, '/auth_db'), data=data, headers=context.headers)
if context.response.status_code == 200 or context.response.status_code == 201:
item = json.loads(context.response.get_data())
if item.get('_id'):
set_placeholder(context, 'AUTH_ID', item['_id'])
context.headers.append(('Authorization', b'basic ' + b64encode(item['token'].encode('ascii') + b':')))
context.user = item['user']
@when('we sleep for {limit}s')
def when_we_sleep_for(context, limit):
time.sleep(int(limit))
@given('we create a new macro "{macro_name}"')
def step_create_new_macro(context, macro_name):
src = get_fixture_path(context, macro_name)
dst = get_macro_path(macro_name)
shutil.copyfile(src, dst)
@when('we fetch from "{provider_name}" ingest "{guid}"')
def step_impl_fetch_from_provider_ingest(context, provider_name, guid):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
fetch_from_provider(context, provider_name, guid)
def embed_routing_scheme_rules(scheme):
"""Fetch all content filters referenced by the given routing scheme and embed those into scheme.
:param dict scheme: routing scheme configuration
"""
filters_service = superdesk.get_resource_service('content_filters')
rules_filters = (
(rule, str(rule['filter']))
for rule in scheme['rules'] if rule.get('filter'))
for rule, filter_id in rules_filters:
content_filter = filters_service.find_one(_id=filter_id, req=None)
rule['filter'] = content_filter
@when('we fetch from "{provider_name}" ingest "{guid}" using routing_scheme')
def step_impl_fetch_from_provider_ingest_using_routing(context, provider_name, guid):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
_id = apply_placeholders(context, context.text)
routing_scheme = get_resource_service('routing_schemes').find_one(_id=_id, req=None)
embed_routing_scheme_rules(routing_scheme)
fetch_from_provider(context, provider_name, guid, routing_scheme)
@when('we ingest and fetch "{provider_name}" "{guid}" to desk "{desk}" stage "{stage}" using routing_scheme')
def step_impl_fetch_from_provider_ingest_using_routing_with_desk(context, provider_name, guid, desk, stage):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
_id = apply_placeholders(context, context.text)
desk_id = apply_placeholders(context, desk)
stage_id = apply_placeholders(context, stage)
routing_scheme = get_resource_service('routing_schemes').find_one(_id=_id, req=None)
embed_routing_scheme_rules(routing_scheme)
fetch_from_provider(context, provider_name, guid, routing_scheme, desk_id, stage_id)
@when('we ingest with routing scheme "{provider_name}" "{guid}"')
def step_impl_ingest_with_routing_scheme(context, provider_name, guid):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
_id = apply_placeholders(context, context.text)
routing_scheme = get_resource_service('routing_schemes').find_one(_id=_id, req=None)
embed_routing_scheme_rules(routing_scheme)
fetch_from_provider(context, provider_name, guid, routing_scheme)
def fetch_from_provider(context, provider_name, guid, routing_scheme=None, desk_id=None, stage_id=None):
ingest_provider_service = get_resource_service('ingest_providers')
provider = ingest_provider_service.find_one(name=provider_name, req=None)
provider['routing_scheme'] = routing_scheme
if 'rule_set' in provider:
rule_set = get_resource_service('rule_sets').find_one(_id=provider['rule_set'], req=None)
else:
rule_set = None
provider_service = registered_feeding_services[provider['feeding_service']]
provider_service = provider_service.__class__()
if provider.get('name', '').lower() in ('aap', 'dpa', 'ninjs', 'email'):
file_path = os.path.join(provider.get('config', {}).get('path', ''), guid)
feeding_parser = provider_service.get_feed_parser(provider)
if isinstance(feeding_parser, XMLFeedParser):
with open(file_path, 'rb') as f:
xml_string = etree.etree.fromstring(f.read())
items = [feeding_parser.parse(xml_string, provider)]
elif isinstance(feeding_parser, EMailRFC822FeedParser):
with open(file_path, 'rb') as f:
data = f.read()
items = feeding_parser.parse([(1, data)], provider)
else:
parsed = feeding_parser.parse(file_path, provider)
items = [parsed] if not isinstance(parsed, list) else parsed
else:
provider_service.provider = provider
provider_service.URL = provider.get('config', {}).get('url')
items = provider_service.fetch_ingest(guid)
for item in items:
item['versioncreated'] = utcnow()
item['expiry'] = utcnow() + timedelta(minutes=20)
if desk_id:
from bson.objectid import ObjectId
item['task'] = {'desk': ObjectId(desk_id), 'stage': ObjectId(stage_id)}
failed = context.ingest_items(items, provider, provider_service, rule_set=rule_set,
routing_scheme=provider.get('routing_scheme'))
assert len(failed) == 0, failed
provider = ingest_provider_service.find_one(name=provider_name, req=None)
ingest_provider_service.system_update(provider['_id'], {LAST_ITEM_UPDATE: utcnow()}, provider)
for item in items:
set_placeholder(context, '{}.{}'.format(provider_name, item['guid']), item['_id'])
@when('we post to "{url}"')
def step_impl_when_post_url(context, url):
post_data(context, url)
@when('we post to "{url}" with delay')
def step_impl_when_post_url_delay(context, url):
time.sleep(1)
post_data(context, url)
def set_user_default(url, data):
if is_user_resource(url):
user = json.loads(data)
user.setdefault('needs_activation', False)
data = json.dumps(user)
def get_response_etag(response):
return json.loads(response.get_data())['_etag']
@when('we save etag')
def step_when_we_save_etag(context):
context.etag = get_response_etag(context.response)
@then('we get same etag')
def step_then_we_get_same_etag(context):
assert context.etag == get_response_etag(context.response), 'etags not matching'
def store_placeholder(context, url):
if context.response.status_code in (200, 201):
item = json.loads(context.response.get_data())
if item['_status'] == 'OK' and item.get('_id'):
try:
setattr(context, get_resource_name(url), item)
except (IndexError, KeyError):
pass
def post_data(context, url, success=False):
with context.app.mail.record_messages() as outbox:
data = apply_placeholders(context, context.text)
url = apply_placeholders(context, url)
set_user_default(url, data)
context.response = context.client.post(get_prefixed_url(context.app, url),
data=data, headers=context.headers)
if success:
assert_ok(context.response)
item = json.loads(context.response.get_data())
context.outbox = outbox
store_placeholder(context, url)
return item
@when('we post to "{url}" with "{tag}" and success')
def step_impl_when_post_url_with_tag(context, url, tag):
item = post_data(context, url, True)
if item.get('_id'):
set_placeholder(context, tag, item.get('_id'))
@given('we have "{url}" with "{tag}" and success')
def step_impl_given_post_url_with_tag(context, url, tag):
item = post_data(context, url, True)
if item.get('_id'):
set_placeholder(context, tag, item.get('_id'))
@when('we post to "{url}" with success')
def step_impl_when_post_url_with_success(context, url):
post_data(context, url, True)
@when('we put to "{url}"')
def step_impl_when_put_url(context, url):
with context.app.mail.record_messages() as outbox:
data = apply_placeholders(context, context.text)
href = get_self_href(url)
context.response = context.client.put(get_prefixed_url(context.app, href), data=data, headers=context.headers)
assert_ok(context.response)
context.outbox = outbox
@when('we get "{url}"')
def when_we_get_url(context, url):
url = apply_placeholders(context, url).encode('ascii').decode('unicode-escape')
headers = []
if context.text:
for line in context.text.split('\n'):
key, val = line.split(': ')
headers.append((key, val))
headers = unique_headers(headers, context.headers)
url = apply_placeholders(context, url)
context.response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
@when('we get dictionary "{dictionary_id}"')
def when_we_get_dictionary(context, dictionary_id):
dictionary_id = apply_placeholders(context, dictionary_id)
url = '/dictionaries/' + dictionary_id + '?projection={"content": 1}'
return when_we_get_url(context, url)
@then('we get latest')
def step_impl_we_get_latest(context):
data = get_json_data(context.response)
href = get_self_href(data, context)
headers = if_match(context, data.get('_etag'))
href = get_prefixed_url(context.app, href)
context.response = context.client.get(href, headers=headers)
assert_200(context.response)
@when('we find for "{resource}" the id as "{name}" by "{search_criteria}"')
def when_we_find_for_resource_the_id_as_name_by_search_criteria(context, resource, name, search_criteria):
url = '/' + resource + '?' + search_criteria
context.response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
if context.response.status_code == 200:
expect_json_length(context.response, 1, path='_items')
item = json.loads(context.response.get_data())
item = item['_items'][0]
if item.get('_id'):
set_placeholder(context, name, item['_id'])
@when('we delete "{url}"')
def step_impl_when_delete_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
href = get_prefixed_url(context.app, href)
context.response = context.client.delete(href, headers=headers)
context.outbox = outbox
@when('we delete link "{url}"')
def step_impl_when_delete_link_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
headers = context.headers
context.response = context.client.delete(get_prefixed_url(context.app, url), headers=headers)
context.outbox = outbox
@when('we delete all sessions "{url}"')
def step_impl_when_delete_all_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
headers = context.headers
href = get_prefixed_url(context.app, url)
context.response = context.client.delete(href, headers=headers)
context.outbox = outbox
@when('we delete latest')
def when_we_delete_it(context):
with context.app.mail.record_messages() as outbox:
res = get_json_data(context.response)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
href = get_prefixed_url(context.app, href)
context.response = context.client.delete(href, headers=headers)
context.email = outbox
@when('we patch "{url}"')
def step_impl_when_patch_url(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
data = apply_placeholders(context, context.text)
href = get_prefixed_url(context.app, href)
context.response = context.client.patch(href, data=data, headers=headers)
context.outbox = outbox
@when('we patch latest')
def step_impl_when_patch_again(context):
with context.app.mail.record_messages() as outbox:
data = get_json_data(context.response)
href = get_prefixed_url(context.app, get_self_href(data, context))
headers = if_match(context, data.get('_etag'))
data2 = apply_placeholders(context, context.text)
context.response = context.client.patch(href, data=data2, headers=headers)
if context.response.status_code in (200, 201):
item = json.loads(context.response.get_data())
if item['_status'] == 'OK' and item.get('_id'):
setattr(context, get_resource_name(href), item)
assert_ok(context.response)
context.outbox = outbox
@when('we patch latest without assert')
def step_impl_when_patch_without_assert(context):
data = get_json_data(context.response)
href = get_prefixed_url(context.app, get_self_href(data, context))
headers = if_match(context, data.get('_etag'))
data2 = apply_placeholders(context, context.text)
context.response = context.client.patch(href, data=data2, headers=headers)
@when('we patch routing scheme "{url}"')
def step_impl_when_patch_routing_scheme(context, url):
with context.app.mail.record_messages() as outbox:
url = apply_placeholders(context, url)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
data = json.loads(apply_placeholders(context, context.text))
res.get('rules', []).append(data)
context.response = context.client.patch(get_prefixed_url(context.app, href),
data=json.dumps({'rules': res.get('rules', [])}),
headers=headers)
context.outbox = outbox
@when('we patch given')
def step_impl_when_patch(context):
with context.app.mail.record_messages() as outbox:
href, etag = get_it(context)
headers = if_match(context, etag)
context.response = context.client.patch(get_prefixed_url(context.app, href), data=context.text, headers=headers)
assert_ok(context.response)
context.outbox = outbox
@when('we get given')
def step_impl_when_get(context):
href, _etag = get_it(context)
context.response = context.client.get(get_prefixed_url(context.app, href), headers=context.headers)
@when('we restore version {version}')
def step_impl_when_restore_version(context, version):
data = get_json_data(context.response)
href = get_self_href(data, context)
headers = if_match(context, data.get('_etag'))
text = '{"type": "text", "old_version": %s, "last_version": %s}' % (version, data.get('_current_version'))
context.response = context.client.put(get_prefixed_url(context.app, href), data=text, headers=headers)
assert_ok(context.response)
@when('we upload a file "{filename}" to "{dest}"')
def step_impl_when_upload_image(context, filename, dest):
upload_file(context, dest, filename, 'media')
@when('we upload a binary file with cropping')
def step_impl_when_upload_with_crop(context):
data = {'CropTop': '0', 'CropLeft': '0', 'CropBottom': '333', 'CropRight': '333'}
upload_file(context, '/upload', 'bike.jpg', 'media', data)
@when('upload a file "{file_name}" to "{destination}" with "{guid}"')
def step_impl_when_upload_image_with_guid(context, file_name, destination, guid):
upload_file(context, destination, file_name, 'media', {'guid': guid})
if destination == 'archive':
set_placeholder(context, 'original.href', context.archive['renditions']['original']['href'])
set_placeholder(context, 'original.media', context.archive['renditions']['original']['media'])
@when('we upload a new dictionary with success')
def when_upload_dictionary(context):
data = json.loads(apply_placeholders(context, context.text))
upload_file(context, '/dictionaries', 'test_dict.txt', DICTIONARY_FILE, data)
assert_ok(context.response)
@when('we upload to an existing dictionary with success')
def when_upload_patch_dictionary(context):
data = json.loads(apply_placeholders(context, context.text))
url = apply_placeholders(context, '/dictionaries/#dictionaries._id#')
etag = apply_placeholders(context, '#dictionaries._etag#')
upload_file(context, url, 'test_dict2.txt', DICTIONARY_FILE, data, 'patch', [('If-Match', etag)])
assert_ok(context.response)
def upload_file(context, dest, filename, file_field, extra_data=None, method='post', user_headers=[]):
with open(get_fixture_path(context, filename), 'rb') as f:
data = {file_field: f}
if extra_data:
data.update(extra_data)
headers = [('Content-Type', 'multipart/form-data')]
headers.extend(user_headers)
headers = unique_headers(headers, context.headers)
url = get_prefixed_url(context.app, dest)
context.response = getattr(context.client, method)(url, data=data, headers=headers)
assert_ok(context.response)
store_placeholder(context, url)
@when('we upload a file from URL')
def step_impl_when_upload_from_url(context):
data = {'URL': external_url}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/upload'), data=data, headers=headers)
@when('we upload a file from URL with cropping')
def step_impl_when_upload_from_url_with_crop(context):
data = {'URL': external_url,
'CropTop': '0',
'CropLeft': '0',
'CropBottom': '333',
'CropRight': '333'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/upload'), data=data, headers=headers)
@when('we get user profile')
def step_impl_when_get_user(context):
profile_url = '/%s/%s' % ('users', context.user['_id'])
context.response = context.client.get(get_prefixed_url(context.app, profile_url), headers=context.headers)
@then('we get new resource')
def step_impl_then_get_new(context):
assert_ok(context.response)
expect_json_contains(context.response, 'self', path='_links')
if context.text is not None:
return test_json(context)
@then('we get error {code}')
def step_impl_then_get_error(context, code):
expect_status(context.response, int(code))
if context.text:
test_json(context)
@then('we get list with {total_count} items')
def step_impl_then_get_list(context, total_count):
assert_200(context.response)
data = get_json_data(context.response)
int_count = int(total_count.replace('+', '').replace('<', ''))
if '+' in total_count:
assert int_count <= data['_meta']['total'], '%d items is not enough' % data['_meta']['total']
elif total_count.startswith('<'):
assert int_count > data['_meta']['total'], '%d items is too much' % data['_meta']['total']
else:
assert int_count == data['_meta']['total'], 'got %d: %s' % (data['_meta']['total'],
format_items(data['_items']))
if context.text:
test_json(context)
@then('we get list ordered by {field} with {total_count} items')
def step_impl_ordered_list(context, field, total_count):
step_impl_then_get_list(context, total_count)
data = get_json_data(context.response)
fields = []
for i in data['_items']:
fields.append(i[field])
assert sorted(fields) == fields
@then('we get "{value}" in formatted output')
def step_impl_then_get_formatted_output(context, value):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if value in item['formatted_item']:
return
assert False
@then('we get "{value}" in formatted output as "{group}" story for subscriber "{sub}"')
def step_impl_then_get_formatted_output_as_story(context, value, group, sub):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if item['subscriber_id'] != sub:
continue
try:
formatted_data = json.loads(item['formatted_item'])
except Exception:
continue
associations = formatted_data.get('associations', {})
for assoc_group in associations:
if assoc_group.startswith(group) and associations[assoc_group].get('guid', '') == value:
return
assert False
@then('we get "{value}" as "{group}" story for subscriber "{sub}" in package "{pck}"')
def step_impl_then_get_formatted_output_pck(context, value, group, sub, pck):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if item['item_id'] != pck:
continue
if item['subscriber_id'] != sub:
continue
try:
formatted_data = json.loads(item['formatted_item'])
except Exception:
continue
associations = formatted_data.get('associations', {})
for assoc_group in associations:
if assoc_group.startswith(group) and associations[assoc_group].get('guid', '') == value:
return
assert False
@then('we get "{value}" as "{group}" story for subscriber "{sub}" not in package "{pck}" version "{v}"')
def step_impl_then_get_formatted_output_pck_version(context, value, group, sub, pck, v):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if item['item_id'] == pck:
if item['subscriber_id'] == sub and str(item['item_version']) == v:
try:
formatted_data = json.loads(item['formatted_item'])
except Exception:
continue
associations = formatted_data.get('associations', {})
for assoc_group in associations:
if assoc_group.startswith(group) \
and associations[assoc_group].get('guid', '') == value:
assert False
assert True
return
assert False
@then('we get "{value}" in formatted output as "{group}" newsml12 story')
def step_impl_then_get_formatted_output_newsml(context, value, group):
assert_200(context.response)
value = apply_placeholders(context, value)
data = get_json_data(context.response)
for item in data['_items']:
if '<' + group + '>' + value + '</' + group + '>' in item['formatted_item']:
return
assert False
@then('we get no "{field}"')
def step_impl_then_get_nofield(context, field):
assert_200(context.response)
expect_json_not_contains(context.response, field)
@then('expect json in "{path}"')
def step_impl_then_get_nofield_in_path(context, path):
assert_200(context.response)
expect_json(context.response, context.text, path)
@then('we get existing resource')
def step_impl_then_get_existing(context):
assert_200(context.response)
test_json(context)
@then('we get existing saved search')
def step_impl_then_get_existing_saved_search(context):
assert_200(context.response)
test_json_with_string_field_value(context, 'filter')
@then('we get OK response')
def step_impl_then_get_ok(context):
assert_200(context.response)
@then('we get response code {code}')
def step_impl_then_get_code(context, code):
expect_status(context.response, int(code))
@then('we get updated response')
def step_impl_then_get_updated(context):
assert_ok(context.response)
if context.text:
test_json(context)
@then('we get "{key}" in "{url}"')
def step_impl_then_get_key_in_url(context, key, url):
url = apply_placeholders(context, url)
res = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
assert_200(res)
expect_json_contains(res, key)
@then('we get file metadata')
def step_impl_then_get_file_meta(context):
assert len(
json.loads(apply_path(
parse_json_response(context.response),
'filemeta_json'
)).items()
) > 0
'expected non empty metadata dictionary'
@then('we get "{filename}" metadata')
def step_impl_then_get_given_file_meta(context, filename):
if filename == 'bike.jpg':
metadata = {
'ycbcrpositioning': 1,
'imagelength': 2448,
'exifimagewidth': 2448,
'meteringmode': 2,
'datetimedigitized': '2013:08:01 16:19:28',
'exposuremode': 0,
'flashpixversion': '0100',
'isospeedratings': 80,
'length': 469900,
'imageuniqueid': 'f3533c05daef2debe6257fd99e058eec',
'datetimeoriginal': '2013:08:01 16:19:28',
'whitebalance': 0,
'exposureprogram': 3,
'colorspace': 1,
'exifimageheight': 3264,
'software': 'Google',
'resolutionunit': 2,
'make': 'SAMSUNG',
'maxaperturevalue': [276, 100],
'aperturevalue': [276, 100],
'scenecapturetype': 0,
'exposuretime': [1, 2004],
'datetime': '2013:08:01 16:19:28',
'exifoffset': 216,
'yresolution': [72, 1],
'orientation': 1,
'componentsconfiguration': '0000',
'exifversion': '0220',
'focallength': [37, 10],
'flash': 0,
'model': 'GT-I9300',
'xresolution': [72, 1],
'fnumber': [26, 10],
'imagewidth': 3264,
'brightnessvalue': [2362, 256],
'exposurebiasvalue': [0, 10],
'shutterspeedvalue': [2808, 256]
}
elif filename == 'green.ogg':
metadata = {
'producer': 'Lavf54.59.103',
'music_genre': 'New Age',
'sample_rate': '44100',
'artist': 'Maxime Abbey',
'length': 368058,
'bit_rate': '160000',
'title': 'Green Hills',
'mime_type': 'audio/vorbis',
'format_version': 'Vorbis version 0',
'compression': 'Vorbis',
'duration': '0:00:20.088163',
'endian': 'Little endian',
'nb_channel': '2'
}
elif filename == 'this_week_nasa.mp4':
metadata = {
'mime_type': 'video/mp4',
'creation_date': '1904-01-01T00:00:00+00:00',
'duration': '0:00:10.224000',
'width': '480',
'length': 877869,
'comment': 'User volume: 100.0%',
'height': '270',
'endian': 'Big endian',
'last_modification': '1904-01-01T00:00:00+00:00'
}
else:
raise NotImplementedError("No metadata for file '{}'.".format(filename))
assertions.maxDiff = None
data = json.loads(context.response.get_data())
filemeta = get_filemeta(data)
json_match(filemeta, metadata)
@then('we get "{type}" renditions')
def step_impl_then_get_renditions(context, type):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
for rend_name in context.app.config['RENDITIONS'][type]:
desc = renditions[rend_name]
assert isinstance(desc, dict), 'expected dict for rendition description'
assert 'href' in desc, 'expected href in rendition description'
assert 'media' in desc, 'expected media identifier in rendition description'
we_can_fetch_a_file(context, desc['href'], 'image/jpeg')
@then('we get "{crop_name}" in renditions')
def step_impl_then_get_renditions(context, crop_name):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
desc = renditions[crop_name]
assert isinstance(desc, dict), 'expected dict for rendition description'
assert 'href' in desc, 'expected href in rendition description'
assert 'media' in desc, 'expected media identifier in rendition description'
we_can_fetch_a_file(context, desc['href'], 'image/jpeg')
@then('we get "{crop_name}" not in renditions')
def step_impl_then_get_renditions(context, crop_name):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
assert crop_name not in renditions, 'expected crop not in renditions'
@then('item "{item_id}" is unlocked')
def then_item_is_unlocked(context, item_id):
assert_200(context.response)
data = json.loads(context.response.get_data())
assert data.get('lock_user', None) is None, 'item is locked by user #{0}'.format(data.get('lock_user'))
@then('item "{item_id}" is locked')
def then_item_is_locked(context, item_id):
assert_200(context.response)
resp = parse_json_response(context.response)
assert resp['lock_user'] is not None
@then('item "{item_id}" is assigned')
def then_item_is_assigned(context, item_id):
resp = parse_json_response(context.response)
assert resp['task'].get('user', None) is not None, 'item is not assigned'
@then('we get rendition "{name}" with mimetype "{mimetype}"')
def step_impl_then_get_rendition_with_mimetype(context, name, mimetype):
expect_json_contains(context.response, 'renditions')
renditions = apply_path(parse_json_response(context.response), 'renditions')
assert isinstance(renditions, dict), 'expected dict for image renditions'
desc = renditions[name]
assert isinstance(desc, dict), 'expected dict for rendition description'
assert 'href' in desc, 'expected href in rendition description'
we_can_fetch_a_file(context, desc['href'], mimetype)
set_placeholder(context, "rendition.{}.href".format(name), desc['href'])
@when('we get updated media from archive')
def get_updated_media_from_archive(context):
url = 'archive/%s' % context._id
when_we_get_url(context, url)
assert_200(context.response)
@then('baseImage rendition is updated')
def check_base_image_rendition(context):
check_rendition(context, 'baseImage')
@then('original rendition is updated with link to file having mimetype "{mimetype}"')
def check_original_rendition(context, mimetype):
rv = parse_json_response(context.response)
link_to_file = rv['renditions']['original']['href']
assert link_to_file
we_can_fetch_a_file(context, link_to_file, mimetype)
@then('thumbnail rendition is updated')
def check_thumbnail_rendition(context):
check_rendition(context, 'thumbnail')
def check_rendition(context, rendition_name):
rv = parse_json_response(context.response)
assert rv['renditions'][rendition_name] != context.renditions[rendition_name], rv['renditions']
@then('we get "{key}"')
def step_impl_then_get_key(context, key):
assert_200(context.response)
expect_json_contains(context.response, key)
item = json.loads(context.response.get_data())
set_placeholder(context, '%s' % key, item[key])
@then('we store "{key}" with value "{value}" to context')
def step_impl_then_we_store_key_value_to_context(context, key, value):
set_placeholder(context, key, apply_placeholders(context, value))
@then('we get action in user activity')
def step_impl_then_get_action(context):
response = context.client.get(get_prefixed_url(context.app, '/activity'), headers=context.headers)
expect_json_contains(response, '_items')
@then('we get a file reference')
def step_impl_then_get_file(context):
assert_200(context.response)
expect_json_contains(context.response, 'renditions')
data = get_json_data(context.response)
url = '/upload/%s' % data['_id']
headers = [('Accept', 'application/json')]
headers = unique_headers(headers, context.headers)
response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
assert_200(response)
assert len(response.get_data()), response
assert response.mimetype == 'application/json', response.mimetype
expect_json_contains(response, 'renditions')
expect_json_contains(response, {'mimetype': 'image/jpeg'})
fetched_data = get_json_data(context.response)
context.fetched_data = fetched_data
@then('we get cropped data smaller than "{max_size}"')
def step_impl_then_get_cropped_file(context, max_size):
assert int(get_filemeta(context.fetched_data, 'length')) < int(max_size), 'was expecting smaller image'
@then('we can fetch a data_uri')
def step_impl_we_fetch_data_uri(context):
we_can_fetch_a_file(context, context.fetched_data['renditions']['original']['href'], 'image/jpeg')
@then('we fetch a file "{url}"')
def step_impl_we_cannot_fetch_file(context, url):
url = apply_placeholders(context, url)
headers = [('Accept', 'application/json')]
headers = unique_headers(headers, context.headers)
context.response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
def we_can_fetch_a_file(context, url, mimetype):
headers = [('Accept', 'application/json')]
headers = unique_headers(headers, context.headers)
response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
assert_200(response)
assert len(response.get_data()), response
assert response.mimetype == mimetype, response.mimetype
@then('we can delete that file')
def step_impl_we_delete_file(context):
url = '/upload/%s' % context.fetched_data['_id']
context.headers.append(('Accept', 'application/json'))
headers = if_match(context, context.fetched_data.get('_etag'))
response = context.client.delete(get_prefixed_url(context.app, url), headers=headers)
assert_200(response)
response = context.client.get(get_prefixed_url(context.app, url), headers=headers)
assert_404(response)
@then('we get a picture url')
def step_impl_then_get_picture(context):
assert_ok(context.response)
expect_json_contains(context.response, 'picture_url')
@then('we get aggregations "{keys}"')
def step_impl_then_get_aggs(context, keys):
assert_200(context.response)
expect_json_contains(context.response, '_aggregations')
data = get_json_data(context.response)
aggs = data['_aggregations']
for key in keys.split(','):
assert_in(key, aggs)
@then('the file is stored localy')
def step_impl_then_file(context):
assert_200(context.response)
folder = context.app.config['UPLOAD_FOLDER']
assert os.path.exists(os.path.join(folder, context.filename))
@then('we get version {version}')
def step_impl_then_get_version(context, version):
assert_200(context.response)
expect_json_contains(context.response, {'_current_version': int(version)})
@then('the field "{field}" value is "{value}"')
def step_impl_then_get_field_value(context, field, value):
assert_200(context.response)
expect_json_contains(context.response, {field: value})
@then('we get etag matching "{url}"')
def step_impl_then_get_etag(context, url):
if context.app.config['IF_MATCH']:
assert_200(context.response)
expect_json_contains(context.response, '_etag')
etag = get_json_data(context.response).get('_etag')
response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
expect_json_contains(response, {'_etag': etag})
@then('we get not modified response')
def step_impl_then_not_modified(context):
expect_status(context.response, 304)
@then('we get "{header}" header')
def step_impl_then_get_header(context, header):
expect_headers_contain(context.response, header)
@then('we get "{header}" header with "{type}" type')
def step_impl_then_get_header_with_type(context, header, type):
expect_headers_contain(context.response, header, type)
@then('we get link to "{resource}"')
def then_we_get_link_to_resource(context, resource):
doc = get_json_data(context.response)
self_link = doc.get('_links').get('self')
assert resource in self_link['href'], 'expect link to "%s", got %s' % (resource, self_link)
@then('we get deleted response')
def then_we_get_deleted_response(context):
assert_200(context.response)
@when('we post to reset_password we get email with token')
def we_post_to_reset_password(context):
data = {'email': 'foo@bar.org'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
with context.app.mail.record_messages() as outbox:
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (200, 201))
assert len(outbox) == 1
assert outbox[0].subject == "Reset password"
email_text = outbox[0].body
assert "24" in email_text
words = email_text.split()
url = urlparse(words[words.index("link") + 1])
token = url.fragment.split('token=')[-1]
assert token
context.token = token
@then('we can check if token is valid')
def we_can_check_token_is_valid(context):
data = {'token': context.token}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (200, 201))
@then('we update token to be expired')
def we_update_token_to_expired(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
expiry = utc.utcnow() - timedelta(days=2)
reset_request = get_resource_service('reset_user_password').find_one(req=None, token=context.token)
reset_request['expire_time'] = expiry
id = reset_request.pop('_id')
get_resource_service('reset_user_password').patch(id, reset_request)
@then('token is invalid')
def check_token_invalid(context):
data = {'token': context.token}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (403, 401))
@when('we post to reset_password we do not get email with token')
def we_post_to_reset_password_it_fails(context):
data = {'email': 'foo@bar.org'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
with context.app.mail.record_messages() as outbox:
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
expect_status_in(context.response, (200, 201))
assert len(outbox) == 0
def start_reset_password_for_user(context):
data = {'token': context.token, 'password': 'test_pass'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/reset_user_password'),
data=data, headers=headers)
@then('we fail to reset password for user')
def we_fail_to_reset_password_for_user(context):
start_reset_password_for_user(context)
step_impl_then_get_error(context, 403)
@then('we reset password for user')
def we_reset_password_for_user(context):
start_reset_password_for_user(context)
expect_status_in(context.response, (200, 201))
auth_data = {'username': 'foo', 'password': 'test_pass'}
headers = [('Content-Type', 'multipart/form-data')]
headers = unique_headers(headers, context.headers)
context.response = context.client.post(get_prefixed_url(context.app, '/auth_db'), data=auth_data, headers=headers)
expect_status_in(context.response, (200, 201))
@when('we switch user')
def when_we_switch_user(context):
user = {'username': 'test-user-2', 'password': 'pwd', 'is_active': True,
'needs_activation': False, 'sign_off': 'foo'}
tests.setup_auth_user(context, user)
set_placeholder(context, 'USERS_ID', str(context.user['_id']))
@when('we setup test user')
def when_we_setup_test_user(context):
tests.setup_auth_user(context, tests.test_user)
@when('we get my "{url}"')
def when_we_get_my_url(context, url):
user_id = str(context.user.get('_id'))
my_url = '{0}?where={1}'.format(url, json.dumps({'user': user_id}))
return when_we_get_url(context, my_url)
@when('we get user "{resource}"')
def when_we_get_user_resource(context, resource):
url = '/users/{0}/{1}'.format(str(context.user.get('_id')), resource)
return when_we_get_url(context, url)
@then('we get embedded items')
def we_get_embedded_items(context):
response_data = json.loads(context.response.get_data())
href = get_self_href(response_data, context)
url = href + '/?embedded={"items": 1}'
context.response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
assert_200(context.response)
context.response_data = json.loads(context.response.get_data())
assert len(context.response_data['items']['view_items']) == 2
@when('we reset notifications')
def step_when_we_reset_notifications(context):
context.app.notification_client.reset()
@then('we get notifications')
def then_we_get_notifications(context):
assert hasattr(context.app.notification_client, 'messages'), 'no messages'
notifications = context.app.notification_client.messages
notifications_data = [json.loads(notification) for notification in notifications]
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data, notifications_data), True,
msg=str(context_data) + '\n != \n' + str(notifications_data))
@then('we get default preferences')
def get_default_prefs(context):
response_data = json.loads(context.response.get_data())
assert_equal(response_data['user_preferences'], default_user_preferences)
@when('we spike "{item_id}"')
def step_impl_when_spike_url(context, item_id):
item_id = apply_placeholders(context, item_id)
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/spike/' + item_id),
data='{"state": "spiked"}', headers=headers)
@when('we spike fetched item')
def step_impl_when_spike_fetched_item(context):
data = json.loads(apply_placeholders(context, context.text))
item_id = data["_id"]
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/spike/' + item_id),
data='{"state": "spiked"}', headers=headers)
@when('we unspike "{item_id}"')
def step_impl_when_unspike_url(context, item_id):
item_id = apply_placeholders(context, item_id)
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/unspike/' + item_id),
data=apply_placeholders(context, context.text or '{}'), headers=headers)
@then('we get spiked content "{item_id}"')
def get_spiked_content(context, item_id):
item_id = apply_placeholders(context, item_id)
url = 'archive/{0}'.format(item_id)
when_we_get_url(context, url)
assert_200(context.response)
response_data = json.loads(context.response.get_data())
assert_equal(response_data['state'], 'spiked')
assert_equal(response_data['operation'], 'spike')
@then('we get unspiked content "{id}"')
def get_unspiked_content(context, id):
text = context.text
context.text = ''
url = 'archive/{0}'.format(id)
when_we_get_url(context, url)
assert_200(context.response)
response_data = json.loads(context.response.get_data())
assert_equal(response_data['state'], 'draft')
assert_equal(response_data['operation'], 'unspike')
# Tolga Akin (05/11/14)
# Expiry value doesn't get set to None properly in Elastic.
# Discussed with Petr so we'll look into this later
# assert_equal(response_data['expiry'], None)
if text:
assert json_match(json.loads(apply_placeholders(context, text)), response_data)
@then('we get global content expiry')
def get_global_content_expiry(context):
validate_expired_content(context, context.app.config['CONTENT_EXPIRY_MINUTES'], utcnow())
@then('we get content expiry {minutes}')
def get_content_expiry(context, minutes):
validate_expired_content(context, minutes, utcnow())
@then('we get expiry for schedule and embargo content {minutes} minutes after "{future_date}"')
def get_content_expiry_schedule(context, minutes, future_date):
future_date = parse_date(apply_placeholders(context, future_date))
validate_expired_content(context, minutes, future_date)
@then('we get desk spike expiry after "{test_minutes}"')
def get_desk_spike_expiry(context, test_minutes):
validate_expired_content(context, test_minutes, utcnow())
def validate_expired_content(context, minutes, start_datetime):
response_data = json.loads(context.response.get_data())
assert response_data['expiry']
response_expiry = parse_date(response_data['expiry'])
expiry = start_datetime + timedelta(minutes=int(minutes))
assert response_expiry <= expiry
@when('we mention user in comment for "{url}"')
def we_mention_user_in_comment(context, url):
with context.app.mail.record_messages() as outbox:
step_impl_when_post_url(context, url)
assert len(outbox) == 1
assert_equal(outbox[0].subject, "You were mentioned in a comment by test_user")
email_text = outbox[0].body
assert email_text
@when('we change user status to "{status}" using "{url}"')
def we_change_user_status(context, status, url):
with context.app.mail.record_messages() as outbox:
step_impl_when_patch_url(context, url)
assert len(outbox) == 1
assert_equal(outbox[0].subject, "Your Superdesk account is " + status)
assert outbox[0].body
@when('we get the default incoming stage')
def we_get_default_incoming_stage(context):
data = json.loads(context.response.get_data())
incoming_stage = data['_items'][0]['incoming_stage'] if '_items' in data else data['incoming_stage']
assert incoming_stage
url = 'stages/{0}'.format(incoming_stage)
when_we_get_url(context, url)
assert_200(context.response)
data = json.loads(context.response.get_data())
assert data['default_incoming'] is True
assert data['name'] == 'Incoming Stage'
@then('we get stage filled in to default_incoming')
def we_get_stage_filled_in(context):
data = json.loads(context.response.get_data())
assert data['task']['stage']
@given('we have sessions "{url}"')
def we_have_sessions_get_id(context, url):
when_we_get_url(context, url)
item = json.loads(context.response.get_data())
context.session_id = item['_items'][0]['_id']
context.data = item
set_placeholder(context, 'SESSION_ID', item['_items'][0]['_id'])
setattr(context, 'users', item['_items'][0]['user'])
@then('we get session by id')
def we_get_session_by_id(context):
url = 'sessions/' + context.session_id
when_we_get_url(context, url)
item = json.loads(context.response.get_data())
returned_id = item["_id"]
assert context.session_id == returned_id
@then('we delete session by id')
def we_delete_session_by_id(context):
url = 'sessions/' + context.session_id
step_impl_when_delete_url(context, url)
assert_200(context.response)
@when('we create a new user')
def step_create_a_user(context):
data = apply_placeholders(context, context.text)
with context.app.mail.record_messages() as outbox:
context.response = context.client.post(get_prefixed_url(context.app, '/users'),
data=data, headers=context.headers)
expect_status_in(context.response, (200, 201))
assert len(outbox) == 1
context.email = outbox[0]
@then('we get activation email')
def step_get_activation_email(context):
assert context.email.subject == 'Superdesk account created'
email_text = context.email.body
words = email_text.split()
url = urlparse(words[words.index("to") + 1])
token = url.fragment.split('token=')[-1]
assert token
@then('we set elastic limit')
def step_set_limit(context):
context.app.settings['MAX_SEARCH_DEPTH'] = 1
@then('we get emails')
def step_we_get_email(context):
data = json.loads(context.text)
for email in data:
assert check_if_email_sent(context, email)
@then('we get {count} emails')
def step_we_get_no_email(context, count):
assert len(context.outbox) == int(count)
if context.text:
step_we_get_email(context)
def check_if_email_sent(context, spec):
if context.outbox:
for key in spec:
found = False
values = [getattr(email, key) for email in context.outbox]
for value in values:
if spec[key] in value:
found = True
if not found:
print('%s:%s not found in %s' % (key, spec[key], json.dumps(values, indent=2)))
return False
return True
print('no email sent')
return False
@then('we get activity')
def then_we_get_activity(context):
url = apply_placeholders(context, '/activity?where={"name": {"$in": ["notify", "user:mention" , "desk:mention"]}}')
context.response = context.client.get(get_prefixed_url(context.app, url), headers=context.headers)
if context.response.status_code == 200:
expect_json_length(context.response, 1, path='_items')
item = json.loads(context.response.get_data())
item = item['_items'][0]
if item.get('_id'):
setattr(context, 'activity', item)
set_placeholder(context, 'USERS_ID', item['user'])
def login_as(context, username, password, user_type):
user = {'username': username, 'password': password, 'is_active': True,
'is_enabled': True, 'needs_activation': False, user_type: user_type}
if context.text:
user.update(json.loads(context.text))
tests.setup_auth_user(context, user)
@given('we login as user "{username}" with password "{password}" and user type "{user_type}"')
def given_we_login_as_user(context, username, password, user_type):
login_as(context, username, password, user_type)
@when('we login as user "{username}" with password "{password}" and user type "{user_type}"')
def when_we_login_as_user(context, username, password, user_type):
login_as(context, username, password, user_type)
def is_user_resource(resource):
return resource in ('users', '/users')
@then('we get {no_of_stages} invisible stages')
def when_we_get_invisible_stages(context, no_of_stages):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
stages = get_resource_service('stages').get_stages_by_visibility(is_visible=False)
assert len(stages) == int(no_of_stages)
@then('we get {no_of_stages} visible stages')
def when_we_get_visible_stages(context, no_of_stages):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
stages = get_resource_service('stages').get_stages_by_visibility(is_visible=True)
assert len(stages) == int(no_of_stages)
@then('we get {no_of_stages} invisible stages for user')
def when_we_get_invisible_stages_for_user(context, no_of_stages):
data = json.loads(apply_placeholders(context, context.text))
with context.app.test_request_context(context.app.config['URL_PREFIX']):
stages = get_resource_service('users').get_invisible_stages(data['user'])
assert len(stages) == int(no_of_stages)
@then('we get "{field_name}" populated')
def then_field_is_populated(context, field_name):
resp = parse_json_response(context.response)
assert resp[field_name].get('user', None) is not None, 'item is not populated'
@then('we get "{field_name}" not populated')
def then_field_is_not_populated(context, field_name):
resp = parse_json_response(context.response)
assert resp[field_name] is None, 'item is not populated'
@then('the field "{field_name}" value is not "{field_value}"')
def then_field_value_is_not_same(context, field_name, field_value):
resp = parse_json_response(context.response)
assert resp[field_name] != field_value, 'values are the same'
@then('we get "{field_name}" not populated in results')
def then_field_is_not_populated_in_results(context, field_name):
resps = parse_json_response(context.response)
for resp in resps['_items']:
assert resp[field_name] is None, 'item is not populated'
@when('we delete content filter "{name}"')
def step_delete_content_filter(context, name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
filter = get_resource_service('content_filters').find_one(req=None, name=name)
url = '/content_filters/{}'.format(filter['_id'])
headers = if_match(context, filter.get('_etag'))
context.response = context.client.delete(get_prefixed_url(context.app, url), headers=headers)
@when('we rewrite "{item_id}"')
def step_impl_when_rewrite(context, item_id):
context_data = {}
_id = apply_placeholders(context, item_id)
if context.text:
context_data.update(json.loads(apply_placeholders(context, context.text)))
data = json.dumps(context_data)
context.response = context.client.post(
get_prefixed_url(context.app, '/archive/{}/rewrite'.format(_id)),
data=data, headers=context.headers)
if context.response.status_code == 400:
return
resp = parse_json_response(context.response)
set_placeholder(context, 'REWRITE_OF', _id)
set_placeholder(context, 'REWRITE_ID', resp['_id'])
@then('we get "{field_name}" does not exist')
def then_field_is_not_populated_in_results(context, field_name):
resps = parse_json_response(context.response)
if '_items' in resps:
for resp in resps['_items']:
assert field_name not in resp, 'field exists'
else:
assert field_name not in resps, 'field exists'
@then('we get "{field_name}" does exist')
def then_field_is_not_populated_in_results(context, field_name):
resps = parse_json_response(context.response)
for resp in resps['_items']:
assert field_name in resp, 'field does not exist'
@when('we publish "{item_id}" with "{pub_type}" type and "{state}" state')
def step_impl_when_publish_url(context, item_id, pub_type, state):
item_id = apply_placeholders(context, item_id)
res = get_res('/archive/' + item_id, context)
headers = if_match(context, res.get('_etag'))
context_data = {"state": state}
if context.text:
data = apply_placeholders(context, context.text)
context_data.update(json.loads(data))
data = json.dumps(context_data)
context.response = context.client.patch(get_prefixed_url(context.app, '/archive/{}/{}'.format(pub_type, item_id)),
data=data, headers=headers)
store_placeholder(context, 'archive_{}'.format(pub_type))
@then('the ingest item is routed based on routing scheme and rule "{rule_name}"')
def then_ingest_item_is_routed_based_on_routing_scheme(context, rule_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
validate_routed_item(context, rule_name, True)
@then('the ingest item is routed and transformed based on routing scheme and rule "{rule_name}"')
def then_ingest_item_is_routed_transformed_based_on_routing_scheme(context, rule_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
validate_routed_item(context, rule_name, True, True)
@then('the ingest item is not routed based on routing scheme and rule "{rule_name}"')
def then_ingest_item_is_not_routed_based_on_routing_scheme(context, rule_name):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
validate_routed_item(context, rule_name, False)
def validate_routed_item(context, rule_name, is_routed, is_transformed=False):
data = json.loads(apply_placeholders(context, context.text))
def validate_rule(action, state):
for destination in rule.get('actions', {}).get(action, []):
query = {
'and': [
{'term': {'ingest_id': str(data['ingest'])}},
{'term': {'task.desk': str(destination['desk'])}},
{'term': {'task.stage': str(destination['stage'])}},
{'term': {'state': state}}
]
}
item = get_archive_items(query) + get_published_items(query)
if is_routed:
assert len(item) > 0, 'No routed items found for criteria: ' + str(query)
assert item[0]['ingest_id'] == data['ingest']
assert item[0]['task']['desk'] == str(destination['desk'])
assert item[0]['task']['stage'] == str(destination['stage'])
assert item[0]['state'] == state
if is_transformed:
assert item[0]['abstract'] == 'Abstract has been updated'
assert_items_in_package(item[0], state, str(destination['desk']), str(destination['stage']))
else:
assert len(item) == 0
scheme = get_resource_service('routing_schemes').find_one(_id=data['routing_scheme'], req=None)
rule = next((rule for rule in scheme['rules'] if rule['name'].lower() == rule_name.lower()), {})
validate_rule('fetch', 'routed')
validate_rule('publish', 'published')
@when('we schedule the routing scheme "{scheme_id}"')
def when_we_schedule_the_routing_scheme(context, scheme_id):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
scheme_id = apply_placeholders(context, scheme_id)
url = apply_placeholders(context, 'routing_schemes/%s' % scheme_id)
res = get_res(url, context)
href = get_self_href(res, context)
headers = if_match(context, res.get('_etag'))
rule = res.get('rules')[0]
now = utcnow()
from apps.rules.routing_rules import Weekdays
rule['schedule'] = {
'day_of_week': [
Weekdays.dayname(now + timedelta(days=1)),
Weekdays.dayname(now + timedelta(days=2))
],
'hour_of_day_from': '16:00:00',
'hour_of_day_to': '20:00:00'
}
if len(res.get('rules')) > 1:
rule = res.get('rules')[1]
rule['schedule'] = {
'day_of_week': [Weekdays.dayname(now)]
}
context.response = context.client.patch(get_prefixed_url(context.app, href),
data=json.dumps({'rules': res.get('rules', [])}),
headers=headers)
assert_200(context.response)
def get_archive_items(query):
req = ParsedRequest()
req.max_results = 100
req.args = {'filter': json.dumps(query)}
return list(get_resource_service('archive').get(lookup=None, req=req))
def get_published_items(query):
req = ParsedRequest()
req.max_results = 100
req.args = {'filter': json.dumps(query)}
return list(get_resource_service('published').get(lookup=None, req=req))
def assert_items_in_package(item, state, desk, stage):
if item.get('groups'):
terms = [{'term': {'_id': ref.get('residRef')}}
for ref in [ref for group in item.get('groups', [])
for ref in group.get('refs', []) if 'residRef' in ref]]
query = {'or': terms}
items = get_archive_items(query)
assert len(items) == len(terms)
for item in items:
assert item.get('state') == state
assert item.get('task', {}).get('desk') == desk
assert item.get('task', {}).get('stage') == stage
@given('I logout')
def logout(context):
we_have_sessions_get_id(context, '/sessions')
step_impl_when_delete_url(context, '/auth_db/{}'.format(context.session_id))
assert_200(context.response)
@then('we get "{url}" and match')
def we_get_and_match(context, url):
url = apply_placeholders(context, url)
response_data = get_res(url, context)
context_data = json.loads(apply_placeholders(context, context.text))
assert_equal(json_match(context_data, response_data), True,
msg=str(context_data) + '\n != \n' + str(response_data))
@then('there is no "{key}" in response')
def there_is_no_key_in_response(context, key):
data = get_json_data(context.response)
assert key not in data, 'key "%s" is in %s' % (key, data)
@then('there is no "{key}" in task')
def there_is_no_key_in_preferences(context, key):
data = get_json_data(context.response)['task']
assert key not in data, 'key "%s" is in task' % key
@then('there is no "{key}" in data')
def there_is_no_profile_in_data(context, key):
data = get_json_data(context.response)['_items'][0]['data']
assert key not in data, 'key "%s" is in data' % key
@then('broadcast "{key}" has value "{value}"')
def broadcast_key_has_value(context, key, value):
data = get_json_data(context.response).get('broadcast', {})
value = apply_placeholders(context, value)
if value.lower() == 'none':
assert data[key] is None, 'key "%s" is not none and has value "%s"' % (key, data[key])
else:
assert data[key] == value, 'key "%s" does not have valid value "%s"' % (key, data[key])
@then('there is no "{key}" preference')
def there_is_no_preference(context, key):
data = get_json_data(context.response)
assert key not in data['user_preferences'], '%s is in %s' % (key, data['user_preferences'].keys())
@then('there is no "{key}" in "{namespace}" preferences')
def there_is_no_key_in_namespace_preferences(context, key, namespace):
data = get_json_data(context.response)['user_preferences']
assert key not in data[namespace], 'key "%s" is in %s' % (key, data[namespace])
@then('we check if article has Embargo')
def step_impl_then_check_embargo(context):
assert_200(context.response)
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
if response_data.get('_meta') and response_data.get('_items'):
for item in response_data.get('_items'):
assert_embargo(context, item)
else:
assert_embargo(context, response_data)
def assert_embargo(context, item):
if not item.get('embargo'):
fail_and_print_body(context, context.response, 'Embargo not found')
@when('embargo lapses for "{item_id}"')
def embargo_lapses(context, item_id):
item_id = apply_placeholders(context, item_id)
item = get_res("/archive/%s" % item_id, context)
updates = {'embargo': (utcnow() - timedelta(minutes=10)),
'schedule_settings': {'utc_embargo': (utcnow() - timedelta(minutes=10))}}
with context.app.test_request_context(context.app.config['URL_PREFIX']):
get_resource_service('archive').system_update(id=item['_id'], original=item, updates=updates)
@then('we validate the published item expiry to be after publish expiry set in desk settings {publish_expiry_in_desk}')
def validate_published_item_expiry(context, publish_expiry_in_desk):
assert_200(context.response)
try:
response_data = json.loads(context.response.get_data())
except Exception:
fail_and_print_body(context.response, 'response is not valid json')
if response_data.get('_meta') and response_data.get('_items'):
for item in response_data.get('_items'):
assert_expiry(item, publish_expiry_in_desk)
else:
assert_expiry(response_data, publish_expiry_in_desk)
@then('we get updated timestamp "{field}"')
def step_we_get_updated_timestamp(context, field):
data = get_json_data(context.response)
timestamp = arrow.get(data[field])
now = utcnow()
assert timestamp + timedelta(seconds=5) > now, 'timestamp < now (%s, %s)' % (timestamp, now) # 5s tolerance
def assert_expiry(item, publish_expiry_in_desk):
embargo = item.get('embargo')
actual = parse_date(item.get('expiry'))
error_message = 'Published Item Expiry validation fails'
publish_expiry_in_desk = int(publish_expiry_in_desk)
if embargo:
expected = get_expiry_date(minutes=publish_expiry_in_desk,
offset=datetime.strptime(embargo, '%Y-%m-%dT%H:%M:%S%z'))
if actual != expected:
raise WooperAssertionError("{}. Expected: {}, Actual: {}".format(error_message, expected, actual))
else:
expected = get_expiry_date(minutes=publish_expiry_in_desk)
if expected < actual:
raise WooperAssertionError("{}. Expected: {}, Actual: {}".format(error_message, expected, actual))
@when('run import legal publish queue')
def run_import_legal_publish_queue(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
from apps.legal_archive import ImportLegalPublishQueueCommand
ImportLegalPublishQueueCommand().run()
@when('we expire items')
def expire_content(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
ids = json.loads(apply_placeholders(context, context.text))
expiry = utcnow() - timedelta(minutes=5)
for item_id in ids:
original = get_resource_service('archive').find_one(req=None, _id=item_id)
get_resource_service('archive').system_update(item_id, {'expiry': expiry}, original)
get_resource_service('published').update_published_items(item_id, 'expiry', expiry)
from apps.archive.commands import RemoveExpiredContent
RemoveExpiredContent().run()
@when('the publish schedule lapses')
def run_overdue_schedule_jobs(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
ids = json.loads(apply_placeholders(context, context.text))
lapse_time = utcnow() - timedelta(minutes=5)
updates = {
'publish_schedule': lapse_time,
'schedule_settings': {
'utc_publish_schedule': lapse_time,
'time_zone': None
}
}
for item_id in ids:
original = get_resource_service('archive').find_one(req=None, _id=item_id)
get_resource_service('archive').system_update(item_id, updates, original)
get_resource_service('published').update_published_items(item_id, 'publish_schedule', lapse_time)
get_resource_service('published').update_published_items(item_id, 'schedule_settings.utc_publish_schedule',
lapse_time)
@when('we transmit items')
def expire_content(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
from superdesk.publish.publish_content import PublishContent
PublishContent().run()
@when('we remove item "{_id}" from mongo')
def remove_item_from_mongo(context, _id):
with context.app.app_context():
context.app.data.mongo.remove('archive', {'_id': _id})
@then('we get text "{text}" in response field "{field}"')
def we_get_text_in_field(context, text, field):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
resp = parse_json_response(context.response)
assert field in resp, 'Field {} not found in response.'.format(field)
assert isinstance(resp.get(field), str), 'Invalid type'
assert text in resp.get(field, ''), '{} contains text: {}. Text To find: {}'.format(field,
resp.get(field, ''),
text)
@then('we reset priority flag for updated articles')
def we_get_reset_default_priority_for_updated_articles(context):
context.app.config['RESET_PRIORITY_VALUE_FOR_UPDATE_ARTICLES'] = True
@then('we mark the items not moved to legal')
def we_mark_the_items_not_moved_to_legal(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
ids = json.loads(apply_placeholders(context, context.text))
for item_id in ids:
get_resource_service('published').update_published_items(item_id, 'moved_to_legal', False)
@when('we run import legal archive command')
def we_run_import_legal_archive_command(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
from apps.legal_archive.commands import ImportLegalArchiveCommand
ImportLegalArchiveCommand().run()
@then('we find no reference of package "{reference}" in item')
def we_find_no_reference_of_package_in_item(context, reference):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
reference = apply_placeholders(context, reference)
resp = parse_json_response(context.response)
linked_in_packages = resp.get('linked_in_packages', [])
assert reference not in [p.get('package') for p in linked_in_packages], \
'Package reference {} found in item'.format(reference)
@then('we set spike exipry "{expiry}"')
def we_set_spike_exipry(context, expiry):
context.app.settings['SPIKE_EXPIRY_MINUTES'] = int(expiry)
@then('we set published item expiry {expiry}')
def we_set_published_item_expiry(context, expiry):
context.app.settings['PUBLISHED_CONTENT_EXPIRY_MINUTES'] = int(expiry)
@then('we set copy metadata from parent flag')
def we_set_copy_metadata_from_parent(context):
context.app.settings['COPY_METADATA_FROM_PARENT'] = True
@then('we assert the content api item "{item_id}" is published to subscriber "{subscriber}"')
def we_assert_content_api_item_is_published_to_subscriber(context, item_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
req = ParsedRequest()
req.projection = json.dumps({'subscribers': 1})
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
subscriber = apply_placeholders(context, subscriber)
assert len(item.get('subscribers', [])) > 0, 'No subscribers found.'
assert subscriber in item.get('subscribers', []), 'Subscriber with Id: {} not found.'.format(subscriber)
@then('we assert the content api item "{item_id}" is not published to subscriber "{subscriber}"')
def we_assert_content_api_item_is_not_published_to_subscriber(context, item_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
req = ParsedRequest()
req.projection = json.dumps({'subscribers': 1})
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
subscriber = apply_placeholders(context, subscriber)
assert subscriber not in item.get('subscribers', []), \
'Subscriber with Id: {} found for the item. '.format(subscriber)
@then('we assert the content api item "{item_id}" is not published to any subscribers')
def we_assert_content_api_item_is_not_published(context, item_id):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
req = ParsedRequest()
req.projection = json.dumps({'subscribers': 1})
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
assert len(item.get('subscribers', [])) == 0, \
'Item published to subscribers {}.'.format(item.get('subscribers', []))
@then('we ensure that archived schema extra fields are not present in duplicated item')
def we_ensure_that_archived_schema_extra_fields_are_not_present(context):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
eve_keys = set([config.ID_FIELD, config.LAST_UPDATED, config.DATE_CREATED, config.VERSION, config.ETAG])
archived_schema_keys = set(context.app.config['DOMAIN']['archived']['schema'].keys())
archived_schema_keys.union(eve_keys)
archive_schema_keys = set(context.app.config['DOMAIN']['archive']['schema'].keys())
archive_schema_keys.union(eve_keys)
extra_fields = [key for key in archived_schema_keys if key not in archive_schema_keys]
duplicate_item = json.loads(context.response.get_data())
for field in extra_fields:
assert field not in duplicate_item, 'Field {} found the duplicate item'.format(field)
@then('we assert content api item "{item_id}" with associated item "{embedded_id}" is published to "{subscriber}"')
def we_assert_that_associated_item_for_subscriber(context, item_id, embedded_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
embedded_id = apply_placeholders(context, embedded_id)
req = ParsedRequest()
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
assert embedded_id in (item.get('associations') or {}), '{} association not found.'.format(embedded_id)
assert subscriber in (item['associations'][embedded_id] or {}).get('subscribers', []), \
'{} subscriber not found in associations {}'.format(subscriber, embedded_id)
@then('we assert content api item "{item_id}" with associated item "{embedded_id}" is not published to "{subscriber}"')
def we_assert_that_associated_item_for_subscriber(context, item_id, embedded_id, subscriber):
with context.app.test_request_context(context.app.config['URL_PREFIX']):
item_id = apply_placeholders(context, item_id)
subscriber = apply_placeholders(context, subscriber)
embedded_id = apply_placeholders(context, embedded_id)
req = ParsedRequest()
cursor = get_resource_service('items').get_from_mongo(req, {'_id': item_id})
assert cursor.count() > 0, 'Item not found'
item = cursor[0]
assert embedded_id in (item.get('associations') or {}), '{} association not found.'.format(embedded_id)
assert subscriber not in (item['associations'][embedded_id] or {}).get('subscribers', []), \
'{} subscriber found in associations {}'.format(subscriber, embedded_id)
@then('file exists "{path}"')
def then_file_exists(context, path):
assert os.path.isfile(path), '{} is not a file'.format(path)
|
agpl-3.0
| -117,397,680,062,153,810
| 38.317652
| 120
| 0.64768
| false
| 3.620787
| true
| false
| false
|
ESS-LLP/erpnext-healthcare
|
erpnext/hr/doctype/payroll_entry/payroll_entry.py
|
1
|
20575
|
# -*- coding: utf-8 -*-
# Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from dateutil.relativedelta import relativedelta
from frappe.utils import cint, flt, nowdate, add_days, getdate, fmt_money, add_to_date, DATE_FORMAT, date_diff
from frappe import _
from erpnext.accounts.utils import get_fiscal_year
from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
class PayrollEntry(Document):
def on_submit(self):
self.create_salary_slips()
def before_submit(self):
if self.validate_attendance:
if self.validate_employee_attendance():
frappe.throw(_("Cannot Submit, Employees left to mark attendance"))
def get_emp_list(self):
"""
Returns list of active employees based on selected criteria
and for which salary structure exists
"""
cond = self.get_filter_condition()
cond += self.get_joining_releiving_condition()
condition = ''
if self.payroll_frequency:
condition = """and payroll_frequency = '%(payroll_frequency)s'"""% {"payroll_frequency": self.payroll_frequency}
sal_struct = frappe.db.sql_list("""
select
name from `tabSalary Structure`
where
docstatus = 1 and
is_active = 'Yes'
and company = %(company)s and
ifnull(salary_slip_based_on_timesheet,0) = %(salary_slip_based_on_timesheet)s
{condition}""".format(condition=condition),
{"company": self.company, "salary_slip_based_on_timesheet":self.salary_slip_based_on_timesheet})
if sal_struct:
cond += "and t2.salary_structure IN %(sal_struct)s "
cond += "and %(from_date)s >= t2.from_date"
emp_list = frappe.db.sql("""
select
distinct t1.name as employee, t1.employee_name, t1.department, t1.designation
from
`tabEmployee` t1, `tabSalary Structure Assignment` t2
where
t1.name = t2.employee
and t2.docstatus = 1
%s order by t2.from_date desc
""" % cond, {"sal_struct": tuple(sal_struct), "from_date": self.end_date}, as_dict=True)
return emp_list
def fill_employee_details(self):
self.set('employees', [])
employees = self.get_emp_list()
if not employees:
frappe.throw(_("No employees for the mentioned criteria"))
for d in employees:
self.append('employees', d)
self.number_of_employees = len(employees)
if self.validate_attendance:
return self.validate_employee_attendance()
def get_filter_condition(self):
self.check_mandatory()
cond = ''
for f in ['company', 'branch', 'department', 'designation']:
if self.get(f):
cond += " and t1." + f + " = '" + self.get(f).replace("'", "\'") + "'"
return cond
def get_joining_releiving_condition(self):
cond = """
and ifnull(t1.date_of_joining, '0000-00-00') <= '%(end_date)s'
and ifnull(t1.relieving_date, '2199-12-31') >= '%(start_date)s'
""" % {"start_date": self.start_date, "end_date": self.end_date}
return cond
def check_mandatory(self):
for fieldname in ['company', 'start_date', 'end_date']:
if not self.get(fieldname):
frappe.throw(_("Please set {0}").format(self.meta.get_label(fieldname)))
def create_salary_slips(self):
"""
Creates salary slip for selected employees if already not created
"""
self.check_permission('write')
self.created = 1
emp_list = [d.employee for d in self.get_emp_list()]
if emp_list:
args = frappe._dict({
"salary_slip_based_on_timesheet": self.salary_slip_based_on_timesheet,
"payroll_frequency": self.payroll_frequency,
"start_date": self.start_date,
"end_date": self.end_date,
"company": self.company,
"posting_date": self.posting_date,
"deduct_tax_for_unclaimed_employee_benefits": self.deduct_tax_for_unclaimed_employee_benefits,
"deduct_tax_for_unsubmitted_tax_exemption_proof": self.deduct_tax_for_unsubmitted_tax_exemption_proof,
"payroll_entry": self.name
})
if len(emp_list) > 30:
frappe.enqueue(create_salary_slips_for_employees, timeout=600, employees=emp_list, args=args)
else:
create_salary_slips_for_employees(emp_list, args, publish_progress=False)
def get_sal_slip_list(self, ss_status, as_dict=False):
"""
Returns list of salary slips based on selected criteria
"""
cond = self.get_filter_condition()
ss_list = frappe.db.sql("""
select t1.name, t1.salary_structure from `tabSalary Slip` t1
where t1.docstatus = %s and t1.start_date >= %s and t1.end_date <= %s
and (t1.journal_entry is null or t1.journal_entry = "") and ifnull(salary_slip_based_on_timesheet,0) = %s %s
""" % ('%s', '%s', '%s','%s', cond), (ss_status, self.start_date, self.end_date, self.salary_slip_based_on_timesheet), as_dict=as_dict)
return ss_list
def submit_salary_slips(self):
self.check_permission('write')
ss_list = self.get_sal_slip_list(ss_status=0)
if len(ss_list) > 30:
frappe.enqueue(submit_salary_slips_for_employees, timeout=600, payroll_entry=self, salary_slips=ss_list)
else:
submit_salary_slips_for_employees(self, ss_list, publish_progress=False)
def email_salary_slip(self, submitted_ss):
if frappe.db.get_single_value("HR Settings", "email_salary_slip_to_employee"):
for ss in submitted_ss:
ss.email_salary_slip()
def get_loan_details(self):
"""
Get loan details from submitted salary slip based on selected criteria
"""
cond = self.get_filter_condition()
return frappe.db.sql(""" select eld.loan_account, eld.loan,
eld.interest_income_account, eld.principal_amount, eld.interest_amount, eld.total_payment
from
`tabSalary Slip` t1, `tabSalary Slip Loan` eld
where
t1.docstatus = 1 and t1.name = eld.parent and start_date >= %s and end_date <= %s %s
""" % ('%s', '%s', cond), (self.start_date, self.end_date), as_dict=True) or []
def get_salary_component_account(self, salary_component):
account = frappe.db.get_value("Salary Component Account",
{"parent": salary_component, "company": self.company}, "default_account")
if not account:
frappe.throw(_("Please set default account in Salary Component {0}")
.format(salary_component))
return account
def get_salary_components(self, component_type):
salary_slips = self.get_sal_slip_list(ss_status = 1, as_dict = True)
if salary_slips:
salary_components = frappe.db.sql("""select salary_component, amount, parentfield
from `tabSalary Detail` where parentfield = '%s' and parent in (%s)""" %
(component_type, ', '.join(['%s']*len(salary_slips))), tuple([d.name for d in salary_slips]), as_dict=True)
return salary_components
def get_salary_component_total(self, component_type = None):
salary_components = self.get_salary_components(component_type)
if salary_components:
component_dict = {}
for item in salary_components:
add_component_to_accrual_jv_entry = True
if component_type == "earnings":
is_flexible_benefit, only_tax_impact = frappe.db.get_value("Salary Component", item['salary_component'], ['is_flexible_benefit', 'only_tax_impact'])
if is_flexible_benefit == 1 and only_tax_impact ==1:
add_component_to_accrual_jv_entry = False
if add_component_to_accrual_jv_entry:
component_dict[item['salary_component']] = component_dict.get(item['salary_component'], 0) + item['amount']
account_details = self.get_account(component_dict = component_dict)
return account_details
def get_account(self, component_dict = None):
account_dict = {}
for s, a in component_dict.items():
account = self.get_salary_component_account(s)
account_dict[account] = account_dict.get(account, 0) + a
return account_dict
def get_default_payroll_payable_account(self):
payroll_payable_account = frappe.get_cached_value('Company',
{"company_name": self.company}, "default_payroll_payable_account")
if not payroll_payable_account:
frappe.throw(_("Please set Default Payroll Payable Account in Company {0}")
.format(self.company))
return payroll_payable_account
def make_accrual_jv_entry(self):
self.check_permission('write')
earnings = self.get_salary_component_total(component_type = "earnings") or {}
deductions = self.get_salary_component_total(component_type = "deductions") or {}
default_payroll_payable_account = self.get_default_payroll_payable_account()
loan_details = self.get_loan_details()
jv_name = ""
precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
if earnings or deductions:
journal_entry = frappe.new_doc('Journal Entry')
journal_entry.voucher_type = 'Journal Entry'
journal_entry.user_remark = _('Accrual Journal Entry for salaries from {0} to {1}')\
.format(self.start_date, self.end_date)
journal_entry.company = self.company
journal_entry.posting_date = self.posting_date
accounts = []
payable_amount = 0
# Earnings
for acc, amount in earnings.items():
payable_amount += flt(amount, precision)
accounts.append({
"account": acc,
"debit_in_account_currency": flt(amount, precision),
"cost_center": self.cost_center,
"project": self.project
})
# Deductions
for acc, amount in deductions.items():
payable_amount -= flt(amount, precision)
accounts.append({
"account": acc,
"credit_in_account_currency": flt(amount, precision),
"cost_center": self.cost_center,
"project": self.project
})
# Loan
for data in loan_details:
accounts.append({
"account": data.loan_account,
"credit_in_account_currency": data.principal_amount
})
if data.interest_amount and not data.interest_income_account:
frappe.throw(_("Select interest income account in loan {0}").format(data.loan))
if data.interest_income_account and data.interest_amount:
accounts.append({
"account": data.interest_income_account,
"credit_in_account_currency": data.interest_amount,
"cost_center": self.cost_center,
"project": self.project
})
payable_amount -= flt(data.total_payment, precision)
# Payable amount
accounts.append({
"account": default_payroll_payable_account,
"credit_in_account_currency": flt(payable_amount, precision)
})
journal_entry.set("accounts", accounts)
journal_entry.title = default_payroll_payable_account
journal_entry.save()
try:
journal_entry.submit()
jv_name = journal_entry.name
self.update_salary_slip_status(jv_name = jv_name)
except Exception as e:
frappe.msgprint(e)
return jv_name
def make_payment_entry(self):
self.check_permission('write')
cond = self.get_filter_condition()
salary_slip_name_list = frappe.db.sql(""" select t1.name from `tabSalary Slip` t1
where t1.docstatus = 1 and start_date >= %s and end_date <= %s %s
""" % ('%s', '%s', cond), (self.start_date, self.end_date), as_list = True)
if salary_slip_name_list and len(salary_slip_name_list) > 0:
salary_slip_total = 0
for salary_slip_name in salary_slip_name_list:
salary_slip = frappe.get_doc("Salary Slip", salary_slip_name[0])
for sal_detail in salary_slip.earnings:
is_flexible_benefit, only_tax_impact, creat_separate_je, statistical_component = frappe.db.get_value("Salary Component", sal_detail.salary_component,
['is_flexible_benefit', 'only_tax_impact', 'create_separate_payment_entry_against_benefit_claim', 'statistical_component'])
if only_tax_impact != 1 and statistical_component != 1:
if is_flexible_benefit == 1 and creat_separate_je == 1:
self.create_journal_entry(sal_detail.amount, sal_detail.salary_component)
else:
salary_slip_total += sal_detail.amount
for sal_detail in salary_slip.deductions:
statistical_component = frappe.db.get_value("Salary Component", sal_detail.salary_component, 'statistical_component')
if statistical_component != 1:
salary_slip_total -= sal_detail.amount
if salary_slip_total > 0:
self.create_journal_entry(salary_slip_total, "salary")
def create_journal_entry(self, je_payment_amount, user_remark):
default_payroll_payable_account = self.get_default_payroll_payable_account()
precision = frappe.get_precision("Journal Entry Account", "debit_in_account_currency")
journal_entry = frappe.new_doc('Journal Entry')
journal_entry.voucher_type = 'Bank Entry'
journal_entry.user_remark = _('Payment of {0} from {1} to {2}')\
.format(user_remark, self.start_date, self.end_date)
journal_entry.company = self.company
journal_entry.posting_date = self.posting_date
payment_amount = flt(je_payment_amount, precision)
journal_entry.set("accounts", [
{
"account": self.payment_account,
"credit_in_account_currency": payment_amount
},
{
"account": default_payroll_payable_account,
"debit_in_account_currency": payment_amount,
"reference_type": self.doctype,
"reference_name": self.name
}
])
journal_entry.save(ignore_permissions = True)
def update_salary_slip_status(self, jv_name = None):
ss_list = self.get_sal_slip_list(ss_status=1)
for ss in ss_list:
ss_obj = frappe.get_doc("Salary Slip",ss[0])
frappe.db.set_value("Salary Slip", ss_obj.name, "journal_entry", jv_name)
def set_start_end_dates(self):
self.update(get_start_end_dates(self.payroll_frequency,
self.start_date or self.posting_date, self.company))
def validate_employee_attendance(self):
employees_to_mark_attendance = []
days_in_payroll, days_holiday, days_attendance_marked = 0, 0, 0
for employee_detail in self.employees:
days_holiday = self.get_count_holidays_of_employee(employee_detail.employee)
days_attendance_marked = self.get_count_employee_attendance(employee_detail.employee)
days_in_payroll = date_diff(self.end_date, self.start_date) + 1
if days_in_payroll > days_holiday + days_attendance_marked:
employees_to_mark_attendance.append({
"employee": employee_detail.employee,
"employee_name": employee_detail.employee_name
})
return employees_to_mark_attendance
def get_count_holidays_of_employee(self, employee):
holiday_list = get_holiday_list_for_employee(employee)
holidays = 0
if holiday_list:
days = frappe.db.sql("""select count(*) from tabHoliday where
parent=%s and holiday_date between %s and %s""", (holiday_list,
self.start_date, self.end_date))
if days and days[0][0]:
holidays = days[0][0]
return holidays
def get_count_employee_attendance(self, employee):
marked_days = 0
attendances = frappe.db.sql("""select count(*) from tabAttendance where
employee=%s and docstatus=1 and attendance_date between %s and %s""",
(employee, self.start_date, self.end_date))
if attendances and attendances[0][0]:
marked_days = attendances[0][0]
return marked_days
@frappe.whitelist()
def get_start_end_dates(payroll_frequency, start_date=None, company=None):
'''Returns dict of start and end dates for given payroll frequency based on start_date'''
if payroll_frequency == "Monthly" or payroll_frequency == "Bimonthly" or payroll_frequency == "":
fiscal_year = get_fiscal_year(start_date, company=company)[0]
month = "%02d" % getdate(start_date).month
m = get_month_details(fiscal_year, month)
if payroll_frequency == "Bimonthly":
if getdate(start_date).day <= 15:
start_date = m['month_start_date']
end_date = m['month_mid_end_date']
else:
start_date = m['month_mid_start_date']
end_date = m['month_end_date']
else:
start_date = m['month_start_date']
end_date = m['month_end_date']
if payroll_frequency == "Weekly":
end_date = add_days(start_date, 6)
if payroll_frequency == "Fortnightly":
end_date = add_days(start_date, 13)
if payroll_frequency == "Daily":
end_date = start_date
return frappe._dict({
'start_date': start_date, 'end_date': end_date
})
def get_frequency_kwargs(frequency_name):
frequency_dict = {
'monthly': {'months': 1},
'fortnightly': {'days': 14},
'weekly': {'days': 7},
'daily': {'days': 1}
}
return frequency_dict.get(frequency_name)
@frappe.whitelist()
def get_end_date(start_date, frequency):
start_date = getdate(start_date)
frequency = frequency.lower() if frequency else 'monthly'
kwargs = get_frequency_kwargs(frequency) if frequency != 'bimonthly' else get_frequency_kwargs('monthly')
# weekly, fortnightly and daily intervals have fixed days so no problems
end_date = add_to_date(start_date, **kwargs) - relativedelta(days=1)
if frequency != 'bimonthly':
return dict(end_date=end_date.strftime(DATE_FORMAT))
else:
return dict(end_date='')
def get_month_details(year, month):
ysd = frappe.db.get_value("Fiscal Year", year, "year_start_date")
if ysd:
import calendar, datetime
diff_mnt = cint(month)-cint(ysd.month)
if diff_mnt<0:
diff_mnt = 12-int(ysd.month)+cint(month)
msd = ysd + relativedelta(months=diff_mnt) # month start date
month_days = cint(calendar.monthrange(cint(msd.year) ,cint(month))[1]) # days in month
mid_start = datetime.date(msd.year, cint(month), 16) # month mid start date
mid_end = datetime.date(msd.year, cint(month), 15) # month mid end date
med = datetime.date(msd.year, cint(month), month_days) # month end date
return frappe._dict({
'year': msd.year,
'month_start_date': msd,
'month_end_date': med,
'month_mid_start_date': mid_start,
'month_mid_end_date': mid_end,
'month_days': month_days
})
else:
frappe.throw(_("Fiscal Year {0} not found").format(year))
def get_payroll_entry_bank_entries(payroll_entry_name):
journal_entries = frappe.db.sql(
'select name from `tabJournal Entry Account` '
'where reference_type="Payroll Entry" '
'and reference_name=%s and docstatus=1',
payroll_entry_name,
as_dict=1
)
return journal_entries
@frappe.whitelist()
def payroll_entry_has_bank_entries(name):
response = {}
bank_entries = get_payroll_entry_bank_entries(name)
response['submitted'] = 1 if bank_entries else 0
return response
def create_salary_slips_for_employees(employees, args, publish_progress=True):
salary_slips_exists_for = get_existing_salary_slips(employees, args)
count=0
for emp in employees:
if emp not in salary_slips_exists_for:
args.update({
"doctype": "Salary Slip",
"employee": emp
})
ss = frappe.get_doc(args)
ss.insert()
count+=1
if publish_progress:
frappe.publish_progress(count*100/len(set(employees) - set(salary_slips_exists_for)),
title = _("Creating Salary Slips..."))
payroll_entry = frappe.get_doc("Payroll Entry", args.payroll_entry)
payroll_entry.db_set("salary_slips_created", 1)
payroll_entry.notify_update()
def get_existing_salary_slips(employees, args):
return frappe.db.sql_list("""
select distinct employee from `tabSalary Slip`
where docstatus!= 2 and company = %s
and start_date >= %s and end_date <= %s
and employee in (%s)
""" % ('%s', '%s', '%s', ', '.join(['%s']*len(employees))),
[args.company, args.start_date, args.end_date] + employees)
def submit_salary_slips_for_employees(payroll_entry, salary_slips, publish_progress=True):
submitted_ss = []
not_submitted_ss = []
frappe.flags.via_payroll_entry = True
count = 0
for ss in salary_slips:
ss_obj = frappe.get_doc("Salary Slip",ss[0])
if ss_obj.net_pay<0:
not_submitted_ss.append(ss[0])
else:
try:
ss_obj.submit()
submitted_ss.append(ss_obj)
except frappe.ValidationError:
not_submitted_ss.append(ss[0])
count += 1
if publish_progress:
frappe.publish_progress(count*100/len(salary_slips), title = _("Submitting Salary Slips..."))
if submitted_ss:
payroll_entry.make_accrual_jv_entry()
frappe.msgprint(_("Salary Slip submitted for period from {0} to {1}")
.format(ss_obj.start_date, ss_obj.end_date))
payroll_entry.email_salary_slip(submitted_ss)
payroll_entry.db_set("salary_slips_submitted", 1)
payroll_entry.notify_update()
if not submitted_ss and not not_submitted_ss:
frappe.msgprint(_("No salary slip found to submit for the above selected criteria OR salary slip already submitted"))
if not_submitted_ss:
frappe.msgprint(_("Could not submit some Salary Slips"))
def get_payroll_entries_for_jv(doctype, txt, searchfield, start, page_len, filters):
return frappe.db.sql("""
select name from `tabPayroll Entry`
where `{key}` LIKE %(txt)s
and name not in
(select reference_name from `tabJournal Entry Account`
where reference_type="Payroll Entry")
order by name limit %(start)s, %(page_len)s"""
.format(key=searchfield), {
'txt': "%%%s%%" % frappe.db.escape(txt),
'start': start, 'page_len': page_len
})
|
gpl-3.0
| 4,264,990,217,364,493,000
| 35.675579
| 154
| 0.693026
| false
| 2.978
| false
| false
| false
|
alvin777/excelsior
|
sort/benchmark.py
|
1
|
2909
|
#!/usr/bin/python
import time
from simple_sorts import *
from shell_sort import *
from quick_sort import *
from external_merge_sort import *
from radix_sort import *
from merge_sort import *
from heap_sort import *
from intro_sort import *
from timsort import *
from list_generators import *
result = {}
def run_until(sort_func, max_duration = 1.0, generator = random_generator):
print sort_func
duration = 0
list_size = 100
while duration < max_duration:
randomList = [x for x in generator(list_size)]
time_start = time.time()
try:
sort_func(randomList)
except RuntimeError:
print 'failed on list size: %5d' % list_size
return
duration = time.time() - time_start
print 'list size: %7d, duration: %0.3f' % (list_size, duration)
if not generator in result:
result[generator] = {}
if not list_size in result[generator]:
result[generator][list_size] = {}
result[generator][list_size][sort_func] = duration
list_size *= 2
def test_run_benchmarks():
generators_list = [random_generator, almost_sorted_generator, reverse_sorted_generator, few_uniq_generator]
# generators_list = [random_generator, reverse_sorted_generator]
# generators_list = [few_uniq_generator]
# sort_func_list = [bubble_sort, insertion_sort, insertion_sort2]
sort_func_list = [bubble_sort, insertion_sort, insertion_sort2, selection_sort, shell_sort, \
merge_sort, quick_sort, lambda x: quick_sort(x, splitByMedian), heap_sort,
lambda x: radix_sort(x, 1000), intro_sort, timsort]
# sort_func_list = [quick_sort, \
# lambda x: quick_sort(x, partition_func=splitByMiddleElement), \
# lambda x: quick_sort(x, partition_func=splitByMedian), \
# lambda x: quick_sort(x, leaf_sort_func=leaf_insertion_sort)]
# sort_func_list = [radix_sort, \
# lambda x: radix_sort(x, 2), \
# lambda x: radix_sort(x, 100),
# lambda x: radix_sort(x, 1000),
# lambda x: radix_sort(x, 10000)
# ]
for generator in generators_list:
print generator
for sort_func in sort_func_list:
run_until(sort_func, 0.5, generator)
for generator in generators_list:
print generator
for list_size in sorted(result[generator]):
sys.stdout.write(str(list_size) + "\t")
for sort_func in sort_func_list:
if sort_func in result[generator][list_size]:
sys.stdout.write("{:.3f}\t".format(result[generator][list_size][sort_func]))
else:
sys.stdout.write("\t")
sys.stdout.write("\n")
test_run_benchmarks()
|
gpl-2.0
| -2,014,888,064,060,402,700
| 34.487805
| 111
| 0.584393
| false
| 3.691624
| false
| false
| false
|
amitdhiman000/MyOffers
|
myadmin/views.py
|
1
|
7396
|
from myadmin.backenddb import (insert_default_areas, insert_custom_areas, insert_default_categories)
from offer.models import CategoryModel
from locus.models import (CountryModel ,StateModel, CityModel, AreaModel)
from mail.models import (PublicMessageModel)
from myadmin.preload_data import (gCountries, gCategories)
from base.apputil import (App_AdminRequired, App_Render)
# Create your views here.
@App_AdminRequired
def home(request):
data = {'title': 'MyAdmin'}
return App_Render(request, 'admin/admin_home_1.html', data)
@App_AdminRequired
def locus_area_view(request, country, state, city, area):
print(area)
areas = AreaModel.fetch_by_name(area, city, state, country)
data = {'title': 'MyAdmin', 'country': country, 'state': state, 'city': city, 'area': area, 'areas': areas}
return App_Render(request, 'admin/admin_locus_area_1.html', data)
@App_AdminRequired
def locus_city_view(request, country, state, city):
print(city)
filter = {'fk_city__name': city, 'fk_state__name': state, 'fk_country__name': country}
areas = AreaModel.fetch(filter)
data = {'title': 'MyAdmin', 'country': country, 'state': state, 'city': city, 'areas': areas}
return App_Render(request, 'admin/admin_locus_city_1.html', data)
@App_AdminRequired
def locus_state_view(request, country, state):
print(state)
filter = {'fk_state__name': state, 'fk_country__name': country}
cities = CityModel.fetch(filter)
data = {'title': 'MyAdmin', 'country': country, 'state': state, 'cities': cities}
return App_Render(request, 'admin/admin_locus_state_1.html', data)
@App_AdminRequired
def locus_country_view(request, country):
print(country)
states = StateModel.fetch({'fk_country__name': country})
data = {'title': 'MyAdmin', 'country': country, 'states': states}
return App_Render(request, 'admin/admin_locus_country_1.html', data)
@App_AdminRequired
def locus_view0(request):
countries = CountryModel.fetch_all()
states = StateModel.fetch({'fk_country__name': 'India'})
data = {'title': 'MyAdmin', 'countries': countries, 'states': states}
return App_Render(request, 'admin/admin_locus_view_1.html', data)
@App_AdminRequired
def locus_view(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
if length == 1 and params[0] != '':
return locus_country_view(request, params[0])
elif length == 2:
return locus_state_view(request, params[0], params[1])
elif length == 3:
return locus_city_view(request, params[0], params[1], params[2])
elif length == 4:
return locus_area_view(request, params[0], params[1], params[2], params[3])
return locus_view0(request)
@App_AdminRequired
def locus_country_add_view(request, country):
states = {}
if country in gCountries:
states = gCountries[country]
data = {'title': 'MyAdmin', 'country': country, 'states': states}
return App_Render(request, 'admin/admin_locus_country_add_1.html', data)
@App_AdminRequired
def locus_add_view0(request):
countries = list(gCountries.keys())
data = {'title': 'MyAdmin', 'countries': countries}
return App_Render(request, 'admin/admin_locus_add_1.html', data)
@App_AdminRequired
def locus_add_view(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
if length == 1 and params[0] != '':
return locus_country_add_view(request, params[0])
elif length == 2:
return locus_state_add_view(request, params[0], params[1])
elif length == 3:
return locus_city_add_view(request, params[0], params[1], params[2])
elif length == 4:
return locus_area_add_view(request, params[0], params[1], params[2], params[3])
return locus_add_view0(request)
@App_AdminRequired
def locus_auth(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
if length < 3:
return None
country = params[0]
state = params[1]
city = params[2]
print(country, state, city)
if CityModel.fetch_by_name(city_name=city, state_name=state, country_name=country) is None:
insert_custom_areas(city, state, country)
areas = AreaModel.fetch_by_city(city)
data = {'title': 'Location', 'country': country, 'state': state, 'city': city, 'areas': areas}
return App_Render(request, 'admin/admin_locus_added_1.html', data)
@App_AdminRequired
def category_view(request, query=''):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
name = "All"
if length > 0 and params[0] != '':
name = params[length - 1]
categories = CategoryModel.fetch_children(name)
data = {'title': 'MyAdmin', 'categories': categories}
return App_Render(request, 'admin/admin_category_1.html', data)
@App_AdminRequired
def category_add_view0(request):
base_cat = gCategories[0]['sub']
print(len(base_cat))
data = {'title': 'MyAdmin', 'categories': base_cat}
return App_Render(request, 'admin/admin_category_add_1.html', data)
@App_AdminRequired
def category_add_view1(request, params, length):
print(request)
index = 0
cat_list = gCategories
while index < length:
for cat in cat_list:
if cat['name'] == params[index]:
if 'sub' in cat:
cat_list = cat['sub']
else:
print('No more subcategories, jump to root')
cat_list = cat
index = length
break
index = index + 1
nav_links = []
url = '/myadmin/category-add/'
for param in params:
print('param : '+param)
url += param + "/"
nav_links.append({'text': param, 'href': url})
data = {}
if type(cat_list) is list:
categories = []
desired_attrs = ['name', 'desc']
for cat in cat_list:
categories.append({ key: value for key,value in cat.items() if key in desired_attrs })
print(len(categories))
print(categories)
data.update({'categories': categories})
else:
data.update({'category': cat_list})
data.update({'title': 'Add Category | MyAdmin', 'nav_links': nav_links, })
return App_Render(request, 'admin/admin_category_add_1.html', data)
@App_AdminRequired
def category_add(request, params):
insert_default_categories()
@App_AdminRequired
def category_add_view(request, query):
print('query : '+query)
params = query.rstrip('/').split('/')
length = len(params)
print(params)
print('length : '+str(length))
command = request.GET.get('command', '')
if command == 'Add':
category_add(request, params)
if params[0] == '':
params[0] = 'All';
return category_add_view1(request, params, length)
@App_AdminRequired
def messages_view(request):
print('chaum executing this')
messages = PublicMessageModel.fetch_all()
data = {'title': 'Messages', 'messages': messages}
return App_Render(request, 'admin/admin_message_1.html', data)
|
apache-2.0
| -4,578,698,669,415,442,000
| 32.165919
| 111
| 0.636966
| false
| 3.44
| false
| false
| false
|
uqyge/combustionML
|
FPV_ANN_pureResNet/data_reader_2.py
|
1
|
5981
|
import numpy as np
import pandas as pd
from sklearn.preprocessing import MinMaxScaler, StandardScaler
class data_scaler(object):
def __init__(self):
self.norm = None
self.norm_1 = None
self.std = None
self.case = None
self.scale = 1
self.bias = 1e-20
# self.bias = 1
self.switcher = {
'min_std': 'min_std',
'std2': 'std2',
'std_min': 'std_min',
'min': 'min',
'no': 'no',
'log': 'log',
'log_min': 'log_min',
'log2': 'log2',
'tan': 'tan'
}
def fit_transform(self, input_data, case):
self.case = case
if self.switcher.get(self.case) == 'min_std':
self.norm = MinMaxScaler()
self.std = StandardScaler()
out = self.norm.fit_transform(input_data)
out = self.std.fit_transform(out)
if self.switcher.get(self.case) == 'std2':
self.std = StandardScaler()
out = self.std.fit_transform(input_data)
if self.switcher.get(self.case) == 'std_min':
self.norm = MinMaxScaler()
self.std = StandardScaler()
out = self.std.fit_transform(input_data)
out = self.norm.fit_transform(out)
if self.switcher.get(self.case) == 'min':
self.norm = MinMaxScaler()
out = self.norm.fit_transform(input_data)
if self.switcher.get(self.case) == 'no':
self.norm = MinMaxScaler()
self.std = StandardScaler()
out = input_data
if self.switcher.get(self.case) == 'log':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
self.std = StandardScaler()
out = self.std.fit_transform(out)
if self.switcher.get(self.case) == 'log_min':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
self.norm = MinMaxScaler()
out = self.norm.fit_transform(out)
if self.switcher.get(self.case) == 'log2':
self.norm = MinMaxScaler()
self.norm_1 = MinMaxScaler()
out = self.norm.fit_transform(input_data)
out = np.log(np.asarray(out) + self.bias)
out = self.norm_1.fit_transform(out)
if self.switcher.get(self.case) == 'tan':
self.norm = MaxAbsScaler()
self.std = StandardScaler()
out = self.std.fit_transform(input_data)
out = self.norm.fit_transform(out)
out = np.tan(out / (2 * np.pi + self.bias))
return out
def transform(self, input_data):
if self.switcher.get(self.case) == 'min_std':
out = self.norm.transform(input_data)
out = self.std.transform(out)
if self.switcher.get(self.case) == 'std2':
out = self.std.transform(input_data)
if self.switcher.get(self.case) == 'std_min':
out = self.std.transform(input_data)
out = self.norm.transform(out)
if self.switcher.get(self.case) == 'min':
out = self.norm.transform(input_data)
if self.switcher.get(self.case) == 'no':
out = input_data
if self.switcher.get(self.case) == 'log':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
out = self.std.transform(out)
if self.switcher.get(self.case) == 'log_min':
out = - np.log(np.asarray(input_data / self.scale) + self.bias)
out = self.norm.transform(out)
if self.switcher.get(self.case) == 'log2':
out = self.norm.transform(input_data)
out = np.log(np.asarray(out) + self.bias)
out = self.norm_1.transform(out)
if self.switcher.get(self.case) == 'tan':
out = self.std.transform(input_data)
out = self.norm.transform(out)
out = np.tan(out / (2 * np.pi + self.bias))
return out
def inverse_transform(self, input_data):
if self.switcher.get(self.case) == 'min_std':
out = self.std.inverse_transform(input_data)
out = self.norm.inverse_transform(out)
if self.switcher.get(self.case) == 'std2':
out = self.std.inverse_transform(input_data)
if self.switcher.get(self.case) == 'std_min':
out = self.norm.inverse_transform(input_data)
out = self.std.inverse_transform(out)
if self.switcher.get(self.case) == 'min':
out = self.norm.inverse_transform(input_data)
if self.switcher.get(self.case) == 'no':
out = input_data
if self.switcher.get(self.case) == 'log':
out = self.std.inverse_transform(input_data)
out = (np.exp(-out) - self.bias) * self.scale
if self.switcher.get(self.case) == 'log_min':
out = self.norm.inverse_transform(input_data)
out = (np.exp(-out) - self.bias) * self.scale
if self.switcher.get(self.case) == 'log2':
out = self.norm_1.inverse_transform(input_data)
out = np.exp(out) - self.bias
out = self.norm.inverse_transform(out)
if self.switcher.get(self.case) == 'tan':
out = (2 * np.pi + self.bias) * np.arctan(input_data)
out = self.norm.inverse_transform(out)
out = self.std.inverse_transform(out)
return out
def read_h5_data(fileName, input_features, labels):
df = pd.read_hdf(fileName)
df = df[df['f'] < 0.45]
input_df = df[input_features]
in_scaler = data_scaler()
input_np = in_scaler.fit_transform(input_df.values, 'no')
label_df = df[labels].clip(0)
# if 'PVs' in labels:
# label_df['PVs']=np.log(label_df['PVs']+1)
out_scaler = data_scaler()
label_np = out_scaler.fit_transform(label_df.values, 'std2')
return input_np, label_np, df, in_scaler, out_scaler
|
mit
| 5,411,136,813,735,696,000
| 33.578035
| 75
| 0.546397
| false
| 3.381006
| false
| false
| false
|
UITools/saleor
|
saleor/shipping/migrations/0013_auto_20180822_0721.py
|
1
|
4293
|
# Generated by Django 2.0.3 on 2018-08-22 12:20
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
import django_countries.fields
import django_measurement.models
import django_prices.models
import saleor.core.weight
class Migration(migrations.Migration):
dependencies = [
('checkout', '0010_auto_20180822_0720'),
('order', '0052_auto_20180822_0720'),
('shipping', '0012_remove_legacy_shipping_methods'),
]
operations = [
migrations.CreateModel(
name='ShippingMethodTranslation',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('language_code', models.CharField(max_length=10)),
('name', models.CharField(blank=True, max_length=255, null=True)),
],
),
migrations.CreateModel(
name='ShippingZone',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('name', models.CharField(max_length=100)),
('countries', django_countries.fields.CountryField(max_length=749, multiple=True)),
],
options={
'permissions': (('manage_shipping', 'Manage shipping.'),),
},
),
migrations.AlterUniqueTogether(
name='shippingmethodcountry',
unique_together=set(),
),
migrations.RemoveField(
model_name='shippingmethodcountry',
name='shipping_method',
),
migrations.AlterModelOptions(
name='shippingmethod',
options={},
),
migrations.RemoveField(
model_name='shippingmethod',
name='description',
),
migrations.AddField(
model_name='shippingmethod',
name='maximum_order_price',
field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, max_digits=12, null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='maximum_order_weight',
field=django_measurement.models.MeasurementField(blank=True, measurement_class='Mass', null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='minimum_order_price',
field=django_prices.models.MoneyField(blank=True, currency=settings.DEFAULT_CURRENCY, decimal_places=2, default=0, max_digits=12, null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='minimum_order_weight',
field=django_measurement.models.MeasurementField(blank=True, default=saleor.core.weight.zero_weight, measurement_class='Mass', null=True),
),
migrations.AddField(
model_name='shippingmethod',
name='price',
field=django_prices.models.MoneyField(currency=settings.DEFAULT_CURRENCY, decimal_places=2, default=0, max_digits=12),
),
migrations.AddField(
model_name='shippingmethod',
name='type',
field=models.CharField(choices=[('price', 'Price based shipping'), ('weight', 'Weight based shipping')], default=None, max_length=30),
preserve_default=False,
),
migrations.DeleteModel(
name='ShippingMethodCountry',
),
migrations.AddField(
model_name='shippingmethodtranslation',
name='shipping_method',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='translations', to='shipping.ShippingMethod'),
),
migrations.AddField(
model_name='shippingmethod',
name='shipping_zone',
field=models.ForeignKey(default=None, on_delete=django.db.models.deletion.CASCADE, related_name='shipping_methods', to='shipping.ShippingZone'),
preserve_default=False,
),
migrations.AlterUniqueTogether(
name='shippingmethodtranslation',
unique_together={('language_code', 'shipping_method')},
),
]
|
bsd-3-clause
| 1,969,370,652,778,655,500
| 39.885714
| 156
| 0.603075
| false
| 4.444099
| false
| false
| false
|
jakerockland/find-s
|
find-s.py
|
1
|
3211
|
# This program is an machine learning experiment with the FindS concept learning algorithm
# Based on an excercise from Machine Learning by Thomas Mitchell (1997)
# By: Jacob Rockland
#
# The attribute EnjoySport indicates whether or not Aldo enjoys his favorite
# water sport on this day
#
# For all possible days with the following attributes:
# Sky: Sunny/Rainy
# AirTemp: Warm/Cold
# Humidity: Normal/High
# Wind: Strong/Weak
# Water: Warm/Cool
# Forecast: Same/Change
#
# Let us represent the hypothesis with the vector:
# [Sky, AirTemp, Humidity, Wind, Water, Forecast]
#
# Where each constraint may be '?' to represent that any value is acceptable,
# '0' to represent that no value is acceptable, or a specific value (from above)
#
# A training example for the hypothesis is True if it correctly predicts that
# Aldo will enjoy his water sport on this day, and False otherwise
import random
attributes = [['Sunny','Rainy'],
['Warm','Cold'],
['Normal','High'],
['Strong','Weak'],
['Warm','Cool'],
['Same','Change']]
num_attributes = len(attributes)
def getRandomTrainingExample(target_concept = ['?'] * num_attributes):
training_example = []
classification = True
for i in range(num_attributes):
training_example.append(attributes[i][random.randint(0,1)])
if target_concept[i] != '?' and target_concept[i] != training_example[i]:
classification = False
return training_example, classification
def findS(training_examples = []):
hypothesis = ['0'] * num_attributes
for example in training_examples:
if example[1]:
for i in range(num_attributes):
example_attribute = example[0][i]
hypothesis_attribute = hypothesis[i]
if example_attribute == attributes[i][0]:
if hypothesis_attribute == '0':
hypothesis_attribute = attributes[i][0]
elif hypothesis_attribute == attributes[i][1]:
hypothesis_attribute = '?'
elif example_attribute == attributes[i][1]:
if hypothesis_attribute == '0':
hypothesis_attribute = attributes[i][1]
elif hypothesis_attribute == attributes[i][0]:
hypothesis_attribute = '?'
hypothesis[i] = hypothesis_attribute
return hypothesis
def experiment(target_concept = ['?'] * num_attributes):
training_examples = []
while findS(training_examples) != target_concept:
training_examples.append(getRandomTrainingExample(target_concept))
return len(training_examples)
def main():
target_concept = ['Sunny','Warm','?','?','?','?']
num_experiments = 1000
experiment_results = []
for i in range(num_experiments):
experiment_results.append(experiment(target_concept))
average_result = sum(experiment_results) / num_experiments
print(str(len(experiment_results)) + ' Experiments Ran')
print('Average # Examples Required: ' + str(average_result))
print('Target Concept:' + str(target_concept))
if __name__ == "__main__":
main()
|
mit
| 5,064,658,467,091,919,000
| 37.22619
| 90
| 0.629088
| false
| 4.095663
| false
| false
| false
|
souzabrizolara/py-home-shell
|
src/dao/appliancedao.py
|
1
|
1109
|
__author__ = 'alisonbento'
import basedao
from src.entities.hsappliance import HomeShellAppliance
import datetime
import configs
class ApplianceDAO(basedao.BaseDAO):
def __init__(self, connection):
basedao.BaseDAO.__init__(self, connection, 'hs_appliances', 'appliance_id')
def convert_row_to_object(self, entity_row):
appliance = HomeShellAppliance()
appliance.id = entity_row['appliance_id']
appliance.package = entity_row['package']
appliance.type = entity_row['type']
appliance.name = entity_row['type']
appliance.key = None
appliance.address = entity_row['address']
appliance.hash = entity_row['appliance_hash']
appliance.modified = entity_row['modified']
appliance.modified_datetime = datetime.datetime.strptime(appliance.modified, configs.DATABASE_DATE_FORMAT)
return appliance
def update(self, entity):
cursor = self.connection.cursor()
sql = "UPDATE " + self.table + " SET modified = ? WHERE appliance_id = ?"
cursor.execute(sql, (entity.modified, entity.id))
|
apache-2.0
| 3,405,373,118,082,334,000
| 33.65625
| 114
| 0.66817
| false
| 4.018116
| false
| false
| false
|
Flutras/techstitution
|
app/mod_main/views.py
|
1
|
15521
|
from flask import Blueprint, render_template, request, redirect, url_for, Response, jsonify, flash
from flask_wtf import FlaskForm
from wtforms import StringField, IntegerField, DateTimeField, TextField, SubmitField, TextAreaField, RadioField
from wtforms import validators, ValidationError
from wtforms.validators import InputRequired
from bson import ObjectId
from app import mongo
from bson import json_util
import json
mod_main = Blueprint('main', __name__)
@mod_main.route('/login', methods=['GET', 'POST'])
def login():
error = None
if request.method == 'POST':
if request.form['username'] == 'admin' and request.form['password'] == 'admin':
return redirect(url_for('main.index'))
else:
error = 'Invalid Credentials. Please try again.'
return render_template('mod_main/login.html', error=error)
else:
return render_template('mod_main/login.html', error=error)
class AddPeopleForm(FlaskForm):
firstname = StringField('Firstname', validators=[InputRequired("Please fill out firstname")])
lastname = StringField('Lastname', validators=[InputRequired()])
# submit = SubmitField("Submit")
@mod_main.route('/index', methods=['GET', 'POST'])
def indexpage():
form=AddPeopleForm();
if request.method == 'GET':
reports = mongo.db.reports.find()
return render_template('mod_main/index.html', reports=reports, form=form)
@mod_main.route('/', methods=['GET', 'POST'])
def index():
form = AddPeopleForm()
if request.method == 'GET':
reports = mongo.db.reports.find()
audits = mongo.db.audits.find()
return render_template('mod_main/dashboard.html', reports=reports, audits=audits, form=form)
elif request.method == 'POST' and form.validate_on_submit():
mongo.db.reports.insert({
"firstname": request.form['firstname'],
"lastname": request.form['lastname']
})
return redirect(url_for('main.index'))
@mod_main.route('/audit_list', methods=['GET', 'POST'])
def audit_list():
audits = mongo.db.audits.find()
return render_template('mod_main/audit_list.html', audits=audits)
# New Audit Form
class AddAuditForm(FlaskForm):
audit_ref_num = IntegerField('Reference number', validators=[InputRequired("Please enter audit reference number!")])
audit_title = StringField('Title', validators=[InputRequired("Please enter audit title!")])
audit_type = StringField('Audit type', validators=[InputRequired("Please enter audit type!")])
audit_organization = StringField('Organization', validators=[InputRequired("Please enter organization!")])
audit_start_date = DateTimeField('Audit Start Date', validators=[InputRequired("Please enter start date!")])
audit_end_date = DateTimeField('Audit End Date', validators=[InputRequired("Please enter end date!")])
audit_auditee = StringField('Auditee', validators=[InputRequired("Please enter auditee!")])
audit_place = StringField('Place', validators=[InputRequired("Please enter place!")])
audit_frefnum = IntegerField('Follow-up reference number', validators=[InputRequired("Please enter follow-up reference number!")])
audit_chrefnum = IntegerField('Change reference number', validators=[InputRequired("Please enter changed reference number!")])
audit_tl = StringField('Audit Team Leader', validators=[InputRequired("Please enter team leader name!")])
audit_tm = StringField('Audit Team Members', validators=[InputRequired("Please enter team members!")])
audit_ap = StringField('Auditee Participants', validators=[InputRequired("Please enter auditee participants!")])
submit = SubmitField("Submit")
@mod_main.route('/add_audit_form', methods=['GET', 'POST'])
def add_audit_form():
form = AddAuditForm()
if request.method == 'GET':
audits = mongo.db.audits.find()
return render_template('mod_main/add_audit_form.html', audits=audits, form=form)
elif request.method == 'POST':
data = request.form
new_inputs = ({})
counter = 1
while counter < 5:
if 'input'+str(counter) in data:
new_inputs.update({
'input_'+str(counter): data['input'+str(counter)]
})
counter += 1
print new_inputs
mongo.db.audits.insert({
"new_inputs": new_inputs,
"audit_ref_num": request.form['audit_ref_num'],
"audit_title": request.form['audit_title'],
"audit_type": request.form['audit_type'],
"audit_organization": request.form['audit_organization'],
"audit_start_date": request.form['audit_start_date'],
"audit_end_date": request.form['audit_end_date'],
"audit_auditee": request.form['audit_auditee'],
"audit_place": request.form['audit_place'],
"audit_frefnum": request.form['audit_frefnum'],
"audit_chrefnum": request.form['audit_chrefnum'],
"audit_tl": request.form['audit_tl'],
"audit_tm": request.form['audit_tm'],
"audit_ap": request.form['audit_ap']
})
return redirect(url_for('main.index'))
# New NC Form
class AddNCForm(FlaskForm):
nc_title = StringField('Title', validators=[InputRequired("Please enter NC title!")])
nc_operator_auditee = StringField('Operator Auditee', validators=[InputRequired("Please enter operator auditee!")])
nc_number = IntegerField('Number', validators=[InputRequired("Please enter number!")])
nc_date = DateTimeField('Date', validators=[InputRequired("Please enter date!")])
nc_status = StringField('Status', validators=[InputRequired("Please enter status!")])
nc_agreed_date_for_CAP = DateTimeField('Agreed date for CAP', validators=[InputRequired("Please enter agreed date for CAP!")])
nc_level = StringField('Level', validators=[InputRequired("Please enter level!")])
nc_due_date = DateTimeField('Due Date', validators=[InputRequired("Please enter due date!")])
nc_closure_date = DateTimeField('Closure Date', validators=[InputRequired("Please enter closure date!")])
nc_requirement_references = StringField('Requirement References', validators=[InputRequired("Please enter requirement refeences!")])
nc_further_references = StringField('Further References', validators=[InputRequired("Please enter further references!")])
nc_auditor_ofcaa = StringField('Auditor of CAA', validators=[InputRequired("Please enter auditor of CAA!")])
nc_auditee_rfCAP = StringField('Auditee responsible for CAP', validators=[InputRequired("Please enter auditee!")])
requirement_references = TextAreaField('', validators=[InputRequired("Please enter requirement references!")])
nc_details = TextAreaField('Non Conformity Details', validators=[InputRequired("Please enter details!")])
submit = SubmitField("Submit")
@mod_main.route('/<string:audit_id>/add_nc_form', methods=['GET', 'POST'])
def add_nc_form(audit_id):
form = AddNCForm()
if request.method == 'GET':
audit = mongo.db.audits.find({"_id": ObjectId(audit_id)})
return render_template('mod_main/add_nc_form.html', audit=audit, form=form)
elif request.method == 'POST':
# print "post request"
mongo.db.audits.update({"_id": ObjectId(audit_id)}, {"$set": {nonconformities: {
"nc_title": request.form['nc_title'],
"nc_operator_auditee": request.form['nc_operator_auditee'],
"nc_number": request.form['nc_number'],
"nc_date": request.form['nc_date'],
"nc_status": request.form['nc_status'],
"nc_agreed_date_for_CAP": request.form['nc_agreed_date_for_CAP'],
"nc_level": request.form['nc_level'],
"nc_due_date": request.form['nc_due_date'],
"nc_closure_date": request.form['nc_closure_date'],
"nc_requirement_references": request.form['nc_requirement_references'],
"nc_further_references": request.form['nc_further_references'],
"nc_auditor_ofcaa": request.form['nc_auditor_ofcaa'],
"nc_auditee_rfCAP": request.form['nc_auditee_rfCAP'],
"requirement_references": request.form['requirement_references'],
"nc_details": request.form['nc_details']
}}})
return redirect(url_for('main.show_audit', audit_id=audit_id))
# New NC Form
class AddCAForm(FlaskForm):
ca_description = StringField('Corrective Action Description', validators=[InputRequired("Please enter description!")])
ca_date_of_capapproval = DateTimeField('Date of CAP approval', validators=[InputRequired("Please enter date!")])
ca_due_date = DateTimeField('Due Date', validators=[InputRequired("Please enter due date!")])
ca_contact_person = StringField('Contact Person', validators=[InputRequired("Please enter contact!")])
ca_closure_date = DateTimeField('Closure Date', validators=[InputRequired("Please enter due date!")])
ca_due_date_history = TextAreaField('Due Date History', validators=[InputRequired("Please enter due date!")])
submit = SubmitField("Submit")
@mod_main.route('/<string:audit_id>/add_ca_form', methods=['GET', 'POST'])
def add_ca_form(audit_id):
form = AddCAForm()
if request.method == 'GET':
audit = mongo.db.audits.find({"_id": ObjectId(audit_id)})
return render_template('mod_main/add_ca_form.html', audit=audit, form=form)
elif request.method == 'POST':
# print "post request"
mongo.db.correctiveactions.update({"_id": ObjectId(audit_id)}, {"$set": {
"ca_description": request.form['ca_description'],
"ca_date_of_capapproval": request.form['ca_date_of_capapproval'],
"ca_due_date": request.form['ca_due_date'],
"ca_contact_person": request.form['ca_contact_person'],
"ca_closure_date": request.form['ca_closure_date'],
"ca_due_date_history": request.form['ca_due_date_history']
}})
return redirect(url_for('main.show_nc', audit_id=audit_id))
@mod_main.route('/add_people_form', methods=['GET', 'POST'])
def add_people_form():
form = AddPeopleForm()
if request.method == 'GET':
reports = mongo.db.reports.find()
return render_template('mod_main/add_people_form.html', reports=reports, form=form)
elif request.method == 'POST' and form.validate_on_submit():
# print "post request"
mongo.db.reports.insert({
"firstname": request.form['firstname'],
"lastname": request.form['lastname']
})
# return "Form successfully submitted!"
return redirect(url_for('main.indexpage'))
# behet post request ne kete url
@mod_main.route('/remove/audit', methods=['POST'])
def remove_audit():
if request.method == 'POST':
audit_id = request.form['id']
mongo.db.audits.remove({"_id": ObjectId(audit_id)})
return Response(json.dumps({"removed": True}), mimetype='application/json')
@mod_main.route('/remove/report', methods=['POST'])
def remove_report():
if request.method == 'POST':
report_id = request.form['id']
mongo.db.reports.remove({"_id": ObjectId(report_id)})
return Response(json.dumps({"removed": True}), mimetype='application/json')
@mod_main.route('/show_audit/<string:audit_id>', methods=['GET', 'POST'])
def show_audit(audit_id):
form = AddAuditForm()
if request.method == 'GET':
audit = mongo.db.audits.find_one({"_id": ObjectId(audit_id)})
return render_template('mod_main/audit_details.html', audit=audit, form=form)
@mod_main.route('/edit/<string:audit_id>', methods=['GET', 'POST'])
def edit_audit(audit_id):
form = AddAuditForm()
if request.method == 'GET':
audit = mongo.db.audits.find_one({"_id": ObjectId(audit_id)})
return render_template('mod_main/audit_edit.html', audit=audit, form=form)
elif request.method == 'POST':
audit = mongo.db.audits.find_one({"_id": ObjectId(audit_id)})
mongo.db.audits.update({"_id": ObjectId(audit_id)}, {"$set": {
"audit_ref_num": request.form['audit_ref_num'],
"audit_title": request.form['audit_title'],
"audit_type": request.form['audit_type'],
"audit_organization": request.form['audit_organization'],
"audit_start_date": request.form['audit_start_date'],
"audit_end_date": request.form['audit_end_date'],
"audit_auditee": request.form['audit_auditee'],
"audit_place": request.form['audit_place'],
"audit_frefnum": request.form['audit_frefnum'],
"audit_chrefnum": request.form['audit_chrefnum'],
"audit_tl": request.form['audit_tl'],
"audit_tm": request.form['audit_tm'],
"audit_ap": request.form['audit_ap']
}})
return redirect(url_for('main.show_audit', audit_id= audit_id))
# return 'Showing result ' + str(result)
@mod_main.route('/show_report/<string:report_id>', methods=['GET'])
def show_report(report_id):
result = mongo.db.reports.find_one({"_id": ObjectId(report_id)})
return 'Showing result ' + str(result)
@mod_main.route('/add-people', methods=['GET', 'POST'])
def add_people():
# TODO: Implement POST REQUEST
# if success:
form = AddPeopleForm()
reports = mongo.db.reports.find();
if request.method == 'GET':
return render_template('mod_main/index.html', form=form, reports=reports)
elif request.method == 'POST':
# Get form
form = AddPeopleForm()
# Get form data
data = form.data
# Add document to the database
added_report_id = mongo.db.reports.insert(data)
# Get the added document
report_doc = mongo.db.reports.find_one({"_id": ObjectId(added_report_id)})
# Return a json response
return Response(json_util.dumps(report_doc),mimetype="application/json")
else:
return Response(json_util.dumps({"error":"Something went wrong!"}),mimetype="application/json")
@mod_main.route('/add-audit', methods=['GET', 'POST'])
def add_audit():
# TODO: Implement POST REQUEST
# if success:
form = AddAuditForm()
if request.method == 'POST':
if form.validate() == False:
# flash('All fields are required!')
audits = mongo.db.audits.find()
return render_template('mod_main/add_audit.html', audits=audits, form=form)
else:
mongo.db.audits.insert({
"audit_title": request.form['audit_title'],
"audit_ref_num": request.form['audit_ref_num'],
"audit_start_date": request.form['audit_start_date']
})
return redirect(url_for('main.audit_list'))
elif request.method == 'GET':
return render_template('mod_main/add_audit.html', form=form)
# views for new bootstrap admin dashboard theme template
@mod_main.route('/corrective_actions', methods=['GET', 'POST'])
def corrective_actions():
# audits = mongo.db.audits.find()
return render_template('mod_main/corrective_actions.html')
@mod_main.route('/forms', methods=['GET', 'POST'])
def forms():
# audits = mongo.db.audits.find()
return render_template('mod_main/forms.html')
@mod_main.route('/blank-page', methods=['GET', 'POST'])
def blank_page():
# audits = mongo.db.audits.find()
return render_template('mod_main/blank-page.html')
|
cc0-1.0
| -1,095,109,134,127,927,400
| 42.844633
| 136
| 0.644611
| false
| 3.768148
| false
| false
| false
|
theDarkForce/websearch
|
webseach_book.py
|
1
|
2428
|
# -*- coding: UTF-8 -*-
# webseach
# create at 2015/10/30
# autor: qianqians
import sys
reload(sys)
sys.setdefaultencoding('utf8')
sys.path.append('../')
from webget import gethtml
import pymongo
from doclex import doclex
import time
collection_key = None
def seach(urllist):
def process_keyurl(keyurl):
if keyurl is not None:
for key, urllist in keyurl.iteritems():
for url in urllist:
urlinfo = gethtml.process_url(url)
if urlinfo is None:
continue
list, keyurl1 = urlinfo
if list is not None:
gethtml.collection.insert({'key':key, 'url':url, 'timetmp':time.time()})
if keyurl1 is not None:
process_keyurl(keyurl1)
def process_urllist(url_list):
for url in url_list:
#print url,"sub url"
urlinfo = gethtml.process_url(url)
if urlinfo is None:
continue
list, keyurl = urlinfo
if list is not None:
process_urllist(list)
if keyurl is not None:
process_keyurl(keyurl)
time.sleep(0.1)
suburl = []
subkeyurl = {}
for url in urllist:
print url, "root url"
urlinfo = gethtml.process_url(url)
if urlinfo is None:
continue
list, keyurl = urlinfo
suburl.extend(list)
subkeyurl.update(keyurl)
try:
process_urllist(suburl)
process_keyurl(subkeyurl)
except:
import traceback
traceback.print_exc()
urllist = ["http://www.qidian.com/Default.aspx",
"http://www.zongheng.com/",
"http://chuangshi.qq.com/"
]
def refkeywords():
c = collection_key.find()
keywords = []
for it in c:
keywords.append(it["key"])
doclex.keykorks = keywords
if __name__ == '__main__':
conn = pymongo.Connection('localhost',27017)
db = conn.webseach
gethtml.collection = db.webpage
gethtml.collection_url_profile = db.urlprofile
gethtml.collection_url_title = db.urltitle
collection_key = db.keys
t = 0
while True:
timetmp = time.time()-t
if timetmp > 86400:
refkeywords()
t = time.time()
#urllist = seach(urllist)
seach(urllist)
|
bsd-2-clause
| 5,170,723,839,560,860,000
| 21.700935
| 96
| 0.543657
| false
| 3.68997
| false
| false
| false
|
mmw125/MuDimA
|
server/database_reader.py
|
1
|
7747
|
"""Functions for reading from the database."""
import constants
import database_utils
import models
def get_urls():
"""Get all of the urls in articles in the database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT link FROM article;")
urls = set(item[0] for item in cursor.fetchall())
cursor.execute("SELECT link FROM bad_article;")
return urls.union(item[0] for item in cursor.fetchall())
def get_number_topics(category=None):
"""Get just the number of topics from the database."""
with database_utils.DatabaseConnection() as (connection, cursor):
if category is None:
cursor.execute("SELECT 1 FROM article, topic WHERE article.topic_id = topic.id AND "
"article.topic_id IS NOT NULL GROUP BY topic.id ORDER BY count(*) DESC;")
else:
cursor.execute("SELECT 1 FROM article, topic WHERE article.topic_id = topic.id AND article.category = ? AND"
" article.topic_id IS NOT NULL GROUP BY topic.id ORDER BY count(*) DESC;", (category,))
return len(cursor.fetchall())
def get_topics(category=None, page_number=0, articles_per_page=constants.ARTICLES_PER_PAGE):
"""Get the topics for the given page."""
with database_utils.DatabaseConnection() as (connection, cursor):
start = page_number * articles_per_page
end = (page_number + 1) * articles_per_page
total_items = get_number_topics()
if category is None:
cursor.execute("SELECT topic.name, topic.id, topic.image_url, topic.category, count(*) FROM article, topic "
"WHERE article.topic_id = topic.id AND article.topic_id IS NOT NULL "
"GROUP BY topic.id ORDER BY count(*) DESC;")
else:
cursor.execute("SELECT topic.name, topic.id, topic.image_url, topic.category, count(*) FROM article, topic "
"WHERE article.topic_id = topic.id AND topic.category = ? AND article.topic_id IS NOT NULL "
"GROUP BY topic.id ORDER BY count(*) DESC;", (category,))
return sorted([{"total_items": total_items, "title": item[0], "id": item[1],
"image": item[2], "category": item[3], "count": item[4]}
for item in cursor.fetchall()[start:end]], key=lambda x: -x["count"])
def get_sources():
"""Get all of the stories for the topic with the given topic id. Returns empty dict if topic not in database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT source, count(1) FROM article GROUP BY source")
return cursor.fetchall()
def get_stories_for_topic(topic_id):
"""Get all of the stories for the topic with the given topic id. Returns empty dict if topic not in database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name FROM topic WHERE id=?", (topic_id,))
db_item = cursor.fetchone()
if db_item is not None:
title = db_item[0]
cursor.execute("SELECT name, link, image_url, group_fit_x, group_fit_y, popularity, source, favicon "
"FROM article WHERE topic_id=?",
(topic_id,))
items = cursor.fetchall()
else:
title, items = None, []
return {"title": title, "articles": [{"name": item[0], "link": item[1], "image": item[2], "x": item[3],
"y": item[4], "popularity": item[5], "source": item[6], "favicon": item[7]
} for item in items]}
def get_ungrouped_articles():
"""Get the items in the database and puts them into Article and Grouping objects."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name, link, article_text FROM article "
"WHERE article_text != '' AND topic_id IS NULL;")
articles = []
for item in cursor.fetchall():
name, url, article_text = item
articles.append(models.Article(url=url, title=name, text=article_text, in_database=True,
keywords=_get_article_keywords(url, cursor)))
return articles
def get_top_keywords(num=constants.DEFAULT_NUM_KEYWORDS):
"""Get the top keywords used in the database."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT keyword, COUNT(1) AS c FROM keyword GROUP BY keyword ORDER BY c DESC LIMIT ?;", (num,))
return [item[0] for item in cursor.fetchall()]
def get_groups_with_unfit_articles():
"""Get the ids of the groups in the database that have articles that are not fit."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT topic_id FROM article WHERE group_fit_x IS NULL AND topic_id IS NOT NULL "
"GROUP BY topic_id;")
return [i[0] for i in cursor.fetchall()]
def get_number_articles_without_overall_fit():
"""Get the number of articles in the database without an overall fit."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT topic_id FROM article WHERE group_fit_x IS NULL AND topic_id IS NOT NULL;")
return len(cursor.fetchall())
def _get_article_keywords(article_url, cursor):
"""Get the keywords for the given article."""
cursor.execute("SELECT keyword FROM keyword WHERE article_link = ?;", (article_url,))
return set(item[0] for item in cursor.fetchall())
def get_grouped_articles():
"""Get the items in the database and puts them into Article and Grouping objects."""
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name, topic_id, link, article_text, image_url FROM article "
"WHERE article_text != '' AND topic_id IS NOT NULL;")
groups = {}
for item in cursor.fetchall():
name, id, url, article_text, image_url = item
article = models.Article(url=url, title=name, text=article_text, urlToImage=image_url, in_database=True)
article.set_keywords(_get_article_keywords(url, cursor))
if id in groups:
groups.get(id).add_article(article, new_article=False)
else:
groups[id] = models.Grouping(article, uuid=id, in_database=True, has_new_articles=False)
return list(groups.values())
def get_articles(keyword, page=0, limit=10, order_by=None, descending=True):
"""Get the items in the database and puts them into Article and Grouping objects."""
order_by = "date" if order_by is None else order_by
with database_utils.DatabaseConnection() as (connection, cursor):
cursor.execute("SELECT name, link, image_url, fit_x, fit_y, popularity, source, favicon "
"FROM keyword JOIN article ON keyword.article_link = article.link "
"WHERE keyword = ? OR ? GROUP BY article_link ORDER BY ? DESC;",
(keyword, keyword is None, order_by))
items = [item for item in cursor.fetchall()]
num_items = len(items)
if not descending:
items.reverse()
start = limit * page
items = items[start:start + limit]
return {"num": num_items, "articles": [{
"name": item[0], "link": item[1], "image": item[2], "x": item[3], "y": item[4],
"popularity": item[5], "source": item[6], "favicon": item[7]} for item in items]}
|
gpl-3.0
| 4,023,521,665,624,149,500
| 51.70068
| 120
| 0.61469
| false
| 4.136145
| false
| false
| false
|
andrew-rogers/DSP
|
GPS/file_reader.py
|
1
|
1929
|
#!/usr/bin/env python3
"""Global Position System (GPS) file reader for captured IQ signal
The Standard Positioning Service (SPS) spec can be found at
https://www.navcen.uscg.gov/pubs/gps/sigspec/gpssps1.pdf
"""
# Copyright (c) 2021 Andrew Rogers
#
# 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.
import numpy as np
class FileReader :
# Data file available from https://sourceforge.net/projects/gnss-sdr/files/data/
def __init__( self, filename='2013_04_04_GNSS_SIGNAL_at_CTTC_SPAIN/2013_04_04_GNSS_SIGNAL_at_CTTC_SPAIN.dat') :
self.offset = 0
self.filename = filename
def read( self, num_samples ) :
data=np.fromfile(self.filename, dtype=np.int16, offset=self.offset, count=num_samples*2)
self.offset = self.offset + 2 * len(data)
# Convert values to complex
data=data.reshape(num_samples,2)
data=np.matmul(data,[1,1j])
return data
|
gpl-3.0
| -1,833,778,985,490,122,800
| 39.1875
| 115
| 0.733022
| false
| 3.827381
| false
| false
| false
|
renzon/pypratico
|
setup.py
|
1
|
4933
|
import codecs
import os
import sys
from distutils.util import convert_path
from fnmatch import fnmatchcase
from setuptools import setup, find_packages
def read(fname):
return codecs.open(os.path.join(os.path.dirname(__file__), fname)).read()
# Provided as an attribute, so you can append to these instead
# of replicating them:
standard_exclude = ["*.py", "*.pyc", "*$py.class", "*~", ".*", "*.bak"]
standard_exclude_directories = [
".*", "CVS", "_darcs", "./build", "./dist", "EGG-INFO", "*.egg-info"
]
# (c) 2005 Ian Bicking and contributors; written for Paste (
# http://pythonpaste.org)
# Licensed under the MIT license:
# http://www.opensource.org/licenses/mit-license.php
# Note: you may want to copy this into your setup.py file verbatim, as
# you can't import this from another package, when you don't know if
# that package is installed yet.
def find_package_data(
where=".",
package="",
exclude=standard_exclude,
exclude_directories=standard_exclude_directories,
only_in_packages=True,
show_ignored=False):
"""
Return a dictionary suitable for use in ``package_data``
in a distutils ``setup.py`` file.
The dictionary looks like::
{"package": [files]}
Where ``files`` is a list of all the files in that package that
don"t match anything in ``exclude``.
If ``only_in_packages`` is true, then top-level directories that
are not packages won"t be included (but directories under packages
will).
Directories matching any pattern in ``exclude_directories`` will
be ignored; by default directories with leading ``.``, ``CVS``,
and ``_darcs`` will be ignored.
If ``show_ignored`` is true, then all the files that aren"t
included in package data are shown on stderr (for debugging
purposes).
Note patterns use wildcards, or can be exact paths (including
leading ``./``), and all searching is case-insensitive.
"""
out = {}
stack = [(convert_path(where), "", package, only_in_packages)]
while stack:
where, prefix, package, only_in_packages = stack.pop(0)
for name in os.listdir(where):
fn = os.path.join(where, name)
if os.path.isdir(fn):
bad_name = False
for pattern in exclude_directories:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"Directory %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
if (os.path.isfile(os.path.join(fn, "__init__.py"))
and not prefix):
if not package:
new_package = name
else:
new_package = package + "." + name
stack.append((fn, "", new_package, False))
else:
stack.append(
(fn, prefix + name + "/", package, only_in_packages))
elif package or not only_in_packages:
# is a file
bad_name = False
for pattern in exclude:
if (fnmatchcase(name, pattern)
or fn.lower() == pattern.lower()):
bad_name = True
if show_ignored:
print >> sys.stderr, (
"File %s ignored by pattern %s"
% (fn, pattern))
break
if bad_name:
continue
out.setdefault(package, []).append(prefix + name)
return out
PACKAGE = "pypraticot6"
DESCRIPTION = "Pacote de exemplo do curso pypratico"
NAME = PACKAGE
AUTHOR = "Renzo Nuccitelli"
AUTHOR_EMAIL = "renzo.n@gmail.com"
URL = "https://github.com/renzon/pypratico"
VERSION = __import__(PACKAGE).__version__
setup(
name=NAME,
version=VERSION,
description=DESCRIPTION,
long_description=URL,
author=AUTHOR,
author_email=AUTHOR_EMAIL,
license="AGPL",
url=URL,
packages=find_packages(exclude=["tests.*", "tests"]),
package_data=find_package_data(PACKAGE, only_in_packages=False),
classifiers=[
"Development Status :: 4 - Beta",
"Environment :: Web Environment",
"Intended Audience :: Developers",
"License :: OSI Approved :: GNU Affero General Public License v3 or "
"later (AGPLv3+)",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Framework :: Paste",
],
zip_safe=False,
install_requires=[
'requests>=2.13.0'
]
)
|
agpl-3.0
| 6,054,291,991,308,348,000
| 33.739437
| 77
| 0.550578
| false
| 4.267301
| false
| false
| false
|
gurneyalex/odoo
|
addons/auth_signup/models/res_partner.py
|
4
|
7625
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import random
import werkzeug.urls
from collections import defaultdict
from datetime import datetime, timedelta
from odoo import api, exceptions, fields, models, _
class SignupError(Exception):
pass
def random_token():
# the token has an entropy of about 120 bits (6 bits/char * 20 chars)
chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
return ''.join(random.SystemRandom().choice(chars) for _ in range(20))
def now(**kwargs):
return datetime.now() + timedelta(**kwargs)
class ResPartner(models.Model):
_inherit = 'res.partner'
signup_token = fields.Char(copy=False, groups="base.group_erp_manager")
signup_type = fields.Char(string='Signup Token Type', copy=False, groups="base.group_erp_manager")
signup_expiration = fields.Datetime(copy=False, groups="base.group_erp_manager")
signup_valid = fields.Boolean(compute='_compute_signup_valid', string='Signup Token is Valid')
signup_url = fields.Char(compute='_compute_signup_url', string='Signup URL')
@api.depends('signup_token', 'signup_expiration')
def _compute_signup_valid(self):
dt = now()
for partner, partner_sudo in zip(self, self.sudo()):
partner.signup_valid = bool(partner_sudo.signup_token) and \
(not partner_sudo.signup_expiration or dt <= partner_sudo.signup_expiration)
def _compute_signup_url(self):
""" proxy for function field towards actual implementation """
result = self.sudo()._get_signup_url_for_action()
for partner in self:
if any(u.has_group('base.group_user') for u in partner.user_ids if u != self.env.user):
self.env['res.users'].check_access_rights('write')
partner.signup_url = result.get(partner.id, False)
def _get_signup_url_for_action(self, url=None, action=None, view_type=None, menu_id=None, res_id=None, model=None):
""" generate a signup url for the given partner ids and action, possibly overriding
the url state components (menu_id, id, view_type) """
res = dict.fromkeys(self.ids, False)
for partner in self:
base_url = partner.get_base_url()
# when required, make sure the partner has a valid signup token
if self.env.context.get('signup_valid') and not partner.user_ids:
partner.sudo().signup_prepare()
route = 'login'
# the parameters to encode for the query
query = dict(db=self.env.cr.dbname)
signup_type = self.env.context.get('signup_force_type_in_url', partner.sudo().signup_type or '')
if signup_type:
route = 'reset_password' if signup_type == 'reset' else signup_type
if partner.sudo().signup_token and signup_type:
query['token'] = partner.sudo().signup_token
elif partner.user_ids:
query['login'] = partner.user_ids[0].login
else:
continue # no signup token, no user, thus no signup url!
if url:
query['redirect'] = url
else:
fragment = dict()
base = '/web#'
if action == '/mail/view':
base = '/mail/view?'
elif action:
fragment['action'] = action
if view_type:
fragment['view_type'] = view_type
if menu_id:
fragment['menu_id'] = menu_id
if model:
fragment['model'] = model
if res_id:
fragment['res_id'] = res_id
if fragment:
query['redirect'] = base + werkzeug.urls.url_encode(fragment)
url = "/web/%s?%s" % (route, werkzeug.urls.url_encode(query))
if not self.env.context.get('relative_url'):
url = werkzeug.urls.url_join(base_url, url)
res[partner.id] = url
return res
def action_signup_prepare(self):
return self.signup_prepare()
def signup_get_auth_param(self):
""" Get a signup token related to the partner if signup is enabled.
If the partner already has a user, get the login parameter.
"""
if not self.env.user.has_group('base.group_user') and not self.env.is_admin():
raise exceptions.AccessDenied()
res = defaultdict(dict)
allow_signup = self.env['res.users']._get_signup_invitation_scope() == 'b2c'
for partner in self:
partner = partner.sudo()
if allow_signup and not partner.user_ids:
partner.signup_prepare()
res[partner.id]['auth_signup_token'] = partner.signup_token
elif partner.user_ids:
res[partner.id]['auth_login'] = partner.user_ids[0].login
return res
def signup_cancel(self):
return self.write({'signup_token': False, 'signup_type': False, 'signup_expiration': False})
def signup_prepare(self, signup_type="signup", expiration=False):
""" generate a new token for the partners with the given validity, if necessary
:param expiration: the expiration datetime of the token (string, optional)
"""
for partner in self:
if expiration or not partner.signup_valid:
token = random_token()
while self._signup_retrieve_partner(token):
token = random_token()
partner.write({'signup_token': token, 'signup_type': signup_type, 'signup_expiration': expiration})
return True
@api.model
def _signup_retrieve_partner(self, token, check_validity=False, raise_exception=False):
""" find the partner corresponding to a token, and possibly check its validity
:param token: the token to resolve
:param check_validity: if True, also check validity
:param raise_exception: if True, raise exception instead of returning False
:return: partner (browse record) or False (if raise_exception is False)
"""
partner = self.search([('signup_token', '=', token)], limit=1)
if not partner:
if raise_exception:
raise exceptions.UserError(_("Signup token '%s' is not valid") % token)
return False
if check_validity and not partner.signup_valid:
if raise_exception:
raise exceptions.UserError(_("Signup token '%s' is no longer valid") % token)
return False
return partner
@api.model
def signup_retrieve_info(self, token):
""" retrieve the user info about the token
:return: a dictionary with the user information:
- 'db': the name of the database
- 'token': the token, if token is valid
- 'name': the name of the partner, if token is valid
- 'login': the user login, if the user already exists
- 'email': the partner email, if the user does not exist
"""
partner = self._signup_retrieve_partner(token, raise_exception=True)
res = {'db': self.env.cr.dbname}
if partner.signup_valid:
res['token'] = token
res['name'] = partner.name
if partner.user_ids:
res['login'] = partner.user_ids[0].login
else:
res['email'] = res['login'] = partner.email or ''
return res
|
agpl-3.0
| 5,222,862,158,435,340,000
| 42.323864
| 119
| 0.590557
| false
| 4.205736
| false
| false
| false
|
importre/kotlin-unwrap
|
utils/gen.py
|
1
|
1264
|
#! /usr/bin/env python3
import os
impl = '''
class Unwrap(private var valid: Boolean) {
infix fun <R> nah(f: () -> R) {
if (!valid) f()
}
}
'''
template = '''
inline fun <{0}, R> unwrap(
{1},
block: ({0}) -> R): Unwrap {{
val valid = null !in arrayOf{4}({2})
if (valid) block({3})
return Unwrap(valid = valid)
}}
'''
if __name__ == '__main__':
max = 5
root = os.path.join('src', 'main', 'kotlin', '')
path = [i[0] for i in os.walk(root)
if i[0].endswith(os.sep + 'unwrap')][0].replace(root, '')
codes = ['package {}\n'.format(path.replace(os.sep, '.')), impl]
for iter in range(1, max + 1):
types = ', '.join(['T{}'.format(i + 1) for i in range(iter)])
params = ', '.join(['t{0}: T{0}?'.format(i + 1) for i in range(iter)])
args1 = ', '.join(['t{}'.format(i + 1) for i in range(iter)])
args2 = ', '.join(['t{}!!'.format(i + 1) for i in range(iter)])
arrayType = '<Any?>' if (iter == 1) else ''
code = template.format(types, params, args1, args2, arrayType)
codes.append(code)
filename = os.path.join(root, path, 'Unwrap.kt')
with open(filename, 'w') as fout:
fout.write(''.join(codes).strip() + '\n')
pass
|
apache-2.0
| 3,446,911,921,353,584,000
| 29.095238
| 78
| 0.508703
| false
| 2.939535
| false
| false
| false
|
josiah-wolf-oberholtzer/supriya
|
supriya/ugens/dynamics.py
|
1
|
3847
|
import collections
from supriya import CalculationRate
from supriya.synthdefs import PseudoUGen, UGen
from .delay import DelayN
class Amplitude(UGen):
"""
An amplitude follower.
::
>>> source = supriya.ugens.In.ar(0)
>>> amplitude = supriya.ugens.Amplitude.kr(
... attack_time=0.01, release_time=0.01, source=source,
... )
>>> amplitude
Amplitude.kr()
"""
_ordered_input_names = collections.OrderedDict(
[("source", None), ("attack_time", 0.01), ("release_time", 0.01)]
)
_valid_calculation_rates = (CalculationRate.AUDIO, CalculationRate.CONTROL)
class Compander(UGen):
"""
A general purpose hard-knee dynamics processor.
"""
_ordered_input_names = collections.OrderedDict(
[
("source", None),
("control", 0.0),
("threshold", 0.5),
("slope_below", 1.0),
("slope_above", 1.0),
("clamp_time", 0.01),
("relax_time", 0.1),
]
)
_valid_calculation_rates = (CalculationRate.AUDIO,)
class CompanderD(PseudoUGen):
"""
A convenience constructor for Compander.
"""
### PUBLIC METHODS ###
@classmethod
def ar(
cls,
source=None,
threshold=0.5,
clamp_time=0.01,
relax_time=0.1,
slope_above=1.0,
slope_below=1.0,
):
"""
Constructs an audio-rate dynamics processor.
.. container:: example
::
>>> source = supriya.ugens.In.ar(bus=0)
>>> compander_d = supriya.ugens.CompanderD.ar(source=source,)
>>> supriya.graph(compander_d) # doctest: +SKIP
::
>>> print(compander_d)
synthdef:
name: d4e7b88df56af5070a88f09b0f8c633e
ugens:
- In.ar:
bus: 0.0
- DelayN.ar:
delay_time: 0.01
maximum_delay_time: 0.01
source: In.ar[0]
- Compander.ar:
clamp_time: 0.01
control: DelayN.ar[0]
relax_time: 0.1
slope_above: 1.0
slope_below: 1.0
source: In.ar[0]
threshold: 0.5
Returns ugen graph.
"""
control = DelayN.ar(
source=source, maximum_delay_time=clamp_time, delay_time=clamp_time
)
return Compander._new_expanded(
clamp_time=clamp_time,
calculation_rate=CalculationRate.AUDIO,
relax_time=relax_time,
slope_above=slope_above,
slope_below=slope_below,
source=source,
control=control,
threshold=threshold,
)
class Limiter(UGen):
"""
A peak limiter.
::
>>> source = supriya.ugens.In.ar(0)
>>> limiter = supriya.ugens.Limiter.ar(duration=0.01, level=1, source=source,)
>>> limiter
Limiter.ar()
"""
_ordered_input_names = collections.OrderedDict(
[("source", None), ("level", 1), ("duration", 0.01)]
)
_valid_calculation_rates = (CalculationRate.AUDIO,)
class Normalizer(UGen):
"""
A dynamics flattener.
::
>>> source = supriya.ugens.In.ar(0)
>>> normalizer = supriya.ugens.Normalizer.ar(duration=0.01, level=1, source=source,)
>>> normalizer
Normalizer.ar()
"""
_ordered_input_names = collections.OrderedDict(
[("source", None), ("level", 1), ("duration", 0.01)]
)
_valid_calculation_rates = (CalculationRate.AUDIO,)
|
mit
| 7,030,170,808,679,921,000
| 24.476821
| 92
| 0.494671
| false
| 3.778978
| false
| false
| false
|
CDE-UNIBE/qcat
|
apps/search/search.py
|
1
|
8779
|
from functools import lru_cache
from django.conf import settings
from elasticsearch import TransportError
from questionnaire.models import Questionnaire
from .index import get_elasticsearch
from .utils import get_alias, ElasticsearchAlias
es = get_elasticsearch()
def get_es_query(
filter_params: list=None, query_string: str='',
match_all: bool=True) -> dict:
"""
Kwargs:
``filter_params`` (list): A list of filter parameters. Each
parameter is a tuple consisting of the following elements:
[0]: questiongroup
[1]: key
[2]: values (list)
[3]: operator
[4]: type (eg. checkbox / text)
``query_string`` (str): A query string for the full text search.
``match_all`` (bool): Whether the query MUST match all filters or not.
If not all filters must be matched, the results are ordered by relevance
to show hits matching more filters at the top. Defaults to False.
Returns:
``dict``. A dictionary containing the query to be passed to ES.
"""
if filter_params is None:
filter_params = []
es_queries = []
def _get_terms(qg, k, v):
return {
'terms': {
f'filter_data.{qg}__{k}': [v.lower()]
}
}
# Filter parameters: Nested subqueries to access the correct
# questiongroup.
for filter_param in list(filter_params):
if filter_param.type in [
'checkbox', 'image_checkbox', 'select_type', 'select_model',
'radio', 'bool']:
# So far, range operators only works with one filter value. Does it
# even make sense to have multiple of these joined by OR with the
# same operator?
if filter_param.operator in ['gt', 'gte', 'lt', 'lte']:
raise NotImplementedError(
'Filtering by range is not yet implemented.')
else:
if len(filter_param.values) > 1:
matches = [
_get_terms(filter_param.questiongroup,
filter_param.key, v) for v in
filter_param.values]
query = {
'bool': {
'should': matches
}
}
else:
query = _get_terms(
filter_param.questiongroup, filter_param.key,
filter_param.values[0])
es_queries.append(query)
elif filter_param.type in ['text', 'char']:
raise NotImplementedError(
'Filtering by text or char is not yet implemented/supported.')
elif filter_param.type in ['_date']:
raise NotImplementedError('Not yet implemented.')
elif filter_param.type in ['_flag']:
raise NotImplementedError('Not yet implemented.')
elif filter_param.type in ['_lang']:
es_queries.append({
'terms': {
'translations': [filter_param.values]
}
})
elif filter_param.type == '_edition':
es_queries.append({
'terms': {
'serializer_edition': [filter_param.values]
}
})
if query_string:
es_queries.append({
'multi_match': {
'query': get_escaped_string(query_string),
'fields': [
'list_data.name.*^4',
'list_data.definition.*',
'list_data.country'
],
'type': 'cross_fields',
'operator': 'and',
}
})
es_bool = 'must' if match_all is True else 'should'
if query_string == '':
# Default sort: By country, then by score.
sort = [
{
'list_data.country.keyword': {
'order': 'asc'
}
},
'_score',
]
else:
# If a phrase search is done, then only use the score to sort.
sort = ['_score']
return {
'query': {
'bool': {
es_bool: es_queries
}
},
'sort': sort,
}
def advanced_search(
filter_params: list=None, query_string: str='',
configuration_codes: list=None, limit: int=10,
offset: int=0, match_all: bool=True) -> dict:
"""
Kwargs:
``filter_params`` (list): A list of filter parameters. Each
parameter is a tuple consisting of the following elements:
[0]: questiongroup
[1]: key
[2]: values (list)
[3]: operator
[4]: type (eg. checkbox / text)
``query_string`` (str): A query string for the full text search.
``configuration_codes`` (list): An optional list of
configuration codes to limit the search to certain indices.
``limit`` (int): A limit of query results to return.
``offset`` (int): The number of query results to skip.
``match_all`` (bool): Whether the query MUST match all filters or not.
If not all filters must be matched, the results are ordered by relevance
to show hits matching more filters at the top. Defaults to False.
Returns:
``dict``. The search results as returned by
``elasticsearch.Elasticsearch.search``.
"""
query = get_es_query(
filter_params=filter_params, query_string=query_string,
match_all=match_all)
if configuration_codes is None:
configuration_codes = []
alias = get_alias(*ElasticsearchAlias.from_code_list(*configuration_codes))
return es.search(index=alias, body=query, size=limit, from_=offset)
def get_aggregated_values(
questiongroup, key, filter_type, filter_params: list=None,
query_string: str='', configuration_codes: list=None,
match_all: bool=True) -> dict:
if filter_params is None:
filter_params = []
# Remove the filter_param with the current questiongroup and key from the
# list of filter_params
relevant_filter_params = [
f for f in filter_params if
f.questiongroup != questiongroup and f.key != key]
query = get_es_query(
filter_params=relevant_filter_params, query_string=query_string,
match_all=match_all)
# For text values, use the keyword. This does not work for integer values
# (the way boolean values are stored).
# https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html
if filter_type == 'bool':
field = f'filter_data.{questiongroup}__{key}'
else:
field = f'filter_data.{questiongroup}__{key}.keyword'
query.update({
'aggs': {
'values': {
'terms': {
'field': field,
# Limit needs to be high enough to include all values.
'size': 1000,
}
}
},
'size': 0, # Do not include the actual hits
})
alias = get_alias(*ElasticsearchAlias.from_code_list(*configuration_codes))
es_query = es.search(index=alias, body=query)
buckets = es_query.get('aggregations', {}).get('values', {}).get('buckets', [])
return {b.get('key'): b.get('doc_count') for b in buckets}
def get_element(questionnaire: Questionnaire) -> dict:
"""
Get a single element from elasticsearch.
"""
alias = get_alias(
ElasticsearchAlias.from_configuration(configuration=questionnaire.configuration_object)
)
try:
return es.get_source(index=alias, id=questionnaire.pk, doc_type='questionnaire')
except TransportError:
return {}
def get_escaped_string(query_string: str) -> str:
"""
Replace all reserved characters when searching the ES index.
"""
for char in settings.ES_QUERY_RESERVED_CHARS:
query_string = query_string.replace(char, '\\{}'.format(char))
return query_string
@lru_cache(maxsize=1)
def get_indices_alias() -> list:
"""
Return a list of all elasticsearch index aliases. Only ES indices which
start with the QCAT prefix are respected. Editions are stripped away, only the 'type' of the
index / configuration is relevant.
"""
indices = []
for aliases in es.indices.get_alias('*').values():
for alias in aliases.get('aliases', {}).keys():
if settings.ES_INDEX_PREFIX not in alias:
continue
indices.append(alias.replace(settings.ES_INDEX_PREFIX, '').rsplit('_', 1)[0])
return indices
|
apache-2.0
| 638,632,226,290,109,800
| 30.579137
| 96
| 0.552569
| false
| 4.331031
| true
| false
| false
|
Lindy21/CSE498-LRS
|
oauth_provider/views.py
|
1
|
8387
|
from oauth.oauth import OAuthError
from django.conf import settings
from django.http import (
HttpResponse, HttpResponseBadRequest, HttpResponseRedirect, HttpResponseForbidden)
from django.utils.translation import ugettext as _
from django.contrib.auth.decorators import login_required
from django.core.urlresolvers import get_callable
from django.template import RequestContext
from utils import initialize_server_request, send_oauth_error
from decorators import oauth_required
from stores import check_valid_callback
from consts import OUT_OF_BAND
from django.utils.decorators import decorator_from_middleware
from django.shortcuts import render_to_response
from lrs.forms import AuthClientForm
from lrs.models import Token
OAUTH_AUTHORIZE_VIEW = 'OAUTH_AUTHORIZE_VIEW'
OAUTH_CALLBACK_VIEW = 'OAUTH_CALLBACK_VIEW'
INVALID_PARAMS_RESPONSE = send_oauth_error(OAuthError(
_('Invalid request parameters.')))
def oauth_home(request):
rsp = """
<html><head></head><body><h1>Oauth Authorize</h1></body></html>"""
return HttpResponse(rsp)
def request_token(request):
"""
The Consumer obtains an unauthorized Request Token by asking the Service
Provider to issue a Token. The Request Token's sole purpose is to receive
User approval and can only be used to obtain an Access Token.
"""
# If oauth is not enabled, don't initiate the handshake
if settings.OAUTH_ENABLED:
oauth_server, oauth_request = initialize_server_request(request)
if oauth_server is None:
return INVALID_PARAMS_RESPONSE
try:
# create a request token
token = oauth_server.fetch_request_token(oauth_request)
# return the token
response = HttpResponse(token.to_string(), mimetype="text/plain")
except OAuthError, err:
response = send_oauth_error(err)
return response
else:
return HttpResponseBadRequest("OAuth is not enabled. To enable, set the OAUTH_ENABLED flag to true in settings")
# tom c added login_url
@login_required(login_url="/XAPI/accounts/login")
def user_authorization(request):
"""
The Consumer cannot use the Request Token until it has been authorized by
the User.
"""
oauth_server, oauth_request = initialize_server_request(request)
if oauth_request is None:
return INVALID_PARAMS_RESPONSE
try:
# get the request token
token = oauth_server.fetch_request_token(oauth_request)
# tom c .. we know user.. save it
token.user = request.user
token.save()
except OAuthError, err:
return send_oauth_error(err)
try:
# get the request callback, though there might not be one
callback = oauth_server.get_callback(oauth_request)
# OAuth 1.0a: this parameter should not be present on this version
if token.callback_confirmed:
return HttpResponseBadRequest("Cannot specify oauth_callback at authorization step for 1.0a protocol")
if not check_valid_callback(callback):
return HttpResponseBadRequest("Invalid callback URL")
except OAuthError:
callback = None
# OAuth 1.0a: use the token's callback if confirmed
if token.callback_confirmed:
callback = token.callback
if callback == OUT_OF_BAND:
callback = None
# entry point for the user
if request.method == 'GET':
# try to get custom authorize view
authorize_view_str = getattr(settings, OAUTH_AUTHORIZE_VIEW,
'oauth_provider.views.fake_authorize_view')
try:
authorize_view = get_callable(authorize_view_str)
except AttributeError:
raise Exception, "%s view doesn't exist." % authorize_view_str
params = oauth_request.get_normalized_parameters()
# set the oauth flag
request.session['oauth'] = token.key
return authorize_view(request, token, callback, params)
# user grant access to the service
if request.method == 'POST':
# verify the oauth flag set in previous GET
if request.session.get('oauth', '') == token.key:
request.session['oauth'] = ''
try:
form = AuthClientForm(request.POST)
if form.is_valid():
if int(form.cleaned_data.get('authorize_access', 0)):
# authorize the token
token = oauth_server.authorize_token(token, request.user)
# return the token key
s = form.cleaned_data.get('scopes', '')
if isinstance(s, (list, tuple)):
s = ",".join([v.strip() for v in s])
# changed scope, gotta save
if s:
token.scope = s
token.save()
args = { 'token': token }
else:
args = { 'error': _('Access not granted by user.') }
else:
# try to get custom authorize view
authorize_view_str = getattr(settings, OAUTH_AUTHORIZE_VIEW,
'oauth_provider.views.fake_authorize_view')
try:
authorize_view = get_callable(authorize_view_str)
except AttributeError:
raise Exception, "%s view doesn't exist." % authorize_view_str
params = oauth_request.get_normalized_parameters()
# set the oauth flag
request.session['oauth'] = token.key
return authorize_view(request, token, callback, params, form)
except OAuthError, err:
response = send_oauth_error(err)
if callback:
if "?" in callback:
url_delimiter = "&"
else:
url_delimiter = "?"
if 'token' in args:
query_args = args['token'].to_string(only_key=True)
else: # access is not authorized i.e. error
query_args = 'error=%s' % args['error']
response = HttpResponseRedirect('%s%s%s' % (callback, url_delimiter, query_args))
else:
# try to get custom callback view
callback_view_str = getattr(settings, OAUTH_CALLBACK_VIEW,
'oauth_provider.views.fake_callback_view')
try:
callback_view = get_callable(callback_view_str)
except AttributeError:
raise Exception, "%s view doesn't exist." % callback_view_str
response = callback_view(request, **args)
else:
response = send_oauth_error(OAuthError(_('Action not allowed.')))
return response
def access_token(request):
"""
The Consumer exchanges the Request Token for an Access Token capable of
accessing the Protected Resources.
"""
oauth_server, oauth_request = initialize_server_request(request)
if oauth_request is None:
return INVALID_PARAMS_RESPONSE
try:
# get the request token
token = oauth_server.fetch_access_token(oauth_request)
# return the token
response = HttpResponse(token.to_string(), mimetype="text/plain")
except OAuthError, err:
response = send_oauth_error(err)
return response
def authorize_client(request, token=None, callback=None, params=None, form=None):
if not form:
form = AuthClientForm(initial={'scopes': token.scope_to_list(),
'obj_id': token.pk})
d = {}
d['form'] = form
d['name'] = token.consumer.name
d['description'] = token.consumer.description
d['params'] = params
return render_to_response('oauth_authorize_client.html', d, context_instance=RequestContext(request))
def callback_view(request, **args):
d = {}
if 'error' in args:
d['error'] = args['error']
d['verifier'] = args['token'].verifier
return render_to_response('oauth_verifier_pin.html', args, context_instance=RequestContext(request))
|
apache-2.0
| 868,409,682,363,586,200
| 41.573604
| 120
| 0.595088
| false
| 4.585566
| false
| false
| false
|
joshuaunderwood7/HaskeLinGeom
|
pysrc/LG/Board.py
|
1
|
2993
|
def indexToLocation(x):
return ( (8-(x%8)) , (int(x/8)+1) )
class Location:
def __init__(self, x=1, y=1, z=1):
self.x = x
self.y = y
self.z = z
def parseStr(self, inStr):
inStr = inStr[1:-1]
inStr = inStr.split(',')
self.x = int(inStr[0])
self.y = int(inStr[1])
self.z = int(inStr[2])
def arrayShift(self):
self.x-=1
self.y-=1
self.z-=1
return self
def shiftBack(self):
self.x+=1
self.y+=1
self.z+=1
return self
def __repr__(self):
return '(' + str(self.x) + ', ' + \
str(self.y) + ', ' + \
str(self.z) + ')'
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
def __hash__(self):
return hash(str(self))
class Board:
def __init__(self, minx=1, maxx=1, miny=1, maxy=1, minz=1, maxz=1):
"""Default board is 1x1x1 and filled with #'s"""
self.minX = minx
self.maxX = maxx
self.minY = miny
self.maxY = maxy
self.minZ = minz
self.maxZ = maxz
self.locations = set()
for loc in [ (x,y,z) for z in range(minz, maxz+1) for y in range(miny, maxy+1) for x in range(minx, maxx+1)]:
self.locations.add(loc)
def fill(self, locations):
"""give a Location to assign to each square"""
self.locations.union(locations)
return self
def canAccess(self, location):
return (location in self.locations)
def get(self, location):
if self.canAccess(location):
return '#'
return ''
def set(self, location):
self.locations.add(location)
return self
def rangeOfX(self):
"""Return an eager list of X values"""
return range(self.minX, self.maxX+1)
def rangeOfY(self):
"""Return an eager list of Y values"""
return range(self.minY, self.maxY+1)
def rangeOfZ(self):
"""Return an eager list of Z values"""
return range(self.minZ, self.maxZ+1)
def __repr__(self):
returnString = "loacations = set("
for loc in self.locations:
returnString += srt(loc) + ", "
returnString += ")"
return returnString
def __eq__(self, other):
return (isinstance(other, self.__class__) and self.__dict__ == other.__dict__)
def __ne__(self, other):
return not self.__eq__(other)
def getDistanceboard(self):
return Board(maxx=((self.maxX*2)-1), maxy=((self.maxY*2)-1), maxz=((self.maxZ*2)-1))
def middle(self):
"""Only returns approximate middle of the distance Board"""
return Location(self.maxX, self.maxY, self.maxZ)
chessboard = Board(maxx= 8, maxy=8)
distanceboard = chessboard.getDistanceboard()
chessboard3D = Board(maxx= 8, maxy=8, maxz=8)
|
gpl-3.0
| -2,676,868,010,432,471,000
| 26.712963
| 117
| 0.539926
| false
| 3.289011
| false
| false
| false
|
i19870503/i19870503
|
Python/eggnog2go_anno.py
|
1
|
2591
|
import os
import re
import pandas as pd
import string
import itertools
import numpy as np
import sys
import argparse
from collections import OrderedDict
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Create GO annotation and enrichment file')
parser.add_argument('-i',type=str,dest='infile',required=True,help="Input file")
parser.add_argument('-o',type=str,dest='out',required=True,help="Ouput file")
parser.add_argument('-db',type=str,dest='db',required=True,help="GO Database file")
args = parser.parse_args()
print (args)
def sort_uniq(sequence):
return (x[0] for x in itertools.groupby(sorted(sequence)))
path = "/home/zluna/Work/GO"
fout = open(args.out+"_anno.xls", 'w')
print("Gene_id", "GO_annotation", sep = '\t', file = fout)
go_db = pd.read_table(os.path.join(path, args.db), header = None)
eggout = pd.read_table(os.path.join(path, args.infile), header = None)
#pd.DataFrame.head(eggout)
#eggout.head(100)
dict = OrderedDict()
first_flag = 1
a = list(go_db[0])
for i in range(len(eggout)):
gene_id = eggout[0][i]
go_id = eggout[5][i]
if pd.isnull(eggout[5][i]):
go_id = ''
#print(gene_id, kegg_id, type(kegg_id), sep ='\t')
go_id = go_id.split(',')
if len(go_id) == 0:
continue
go_term = '; '.join(list(go_db[go_db[2].isin(go_id)][0]))
#print(gene_id, go_id, go_term, sep ='\t')
go_sum = []
sel_go_table = go_db[go_db[2].isin(go_id)]
for j in range(len(sel_go_table)):
go_sum.append(''.join(( list(sel_go_table[2])[j], "~", list(sel_go_table[0])[j])))
print(gene_id, str(go_sum).strip('[]').replace(']','').replace("'","").replace(", ","; "), sep = '\t', file = fout)
a = list(go_db[2])
### Use dictionary
for k in range(len(a)):
if str(go_sum).find(a[k]) != -1 :
if a[k] not in dict.keys():
### The value must be list type, if just give the 'gene_id' as the value of key, it can not use 'append' method to add the new 'gene_id' to the existing key.
dict[a[k]] = []
dict[a[k]].append(gene_id)
else:
dict[a[k]].append(gene_id)
#dict[a[j]] = [dict[a[j]], gene_id]
fout.close()
fout2 = open(args.out+"_enrich.xls", 'w')
print('GOID', 'Term', 'Genes', 'Gene_count', sep = '\t', file = fout2)
for key,values in dict.items():
print(key, list(go_db[go_db[2] == key][0]), str(values).strip('[]').replace(']','').replace("'",""), len(values), sep ='\t', file = fout2)
fout2.cloes()
|
gpl-2.0
| -6,269,192,895,930,068,000
| 37.102941
| 157
| 0.580085
| false
| 2.914511
| false
| false
| false
|
rcwoolley/device-cloud-python
|
device_cloud/osal.py
|
1
|
3073
|
'''
Copyright (c) 2016-2017 Wind River Systems, Inc.
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.
'''
"""
Operating System Abstraction Layer (OSAL). This module provides abstractions of
functions that are different on different operating systems.
"""
import os
import platform
import subprocess
import sys
# Constants
NOT_SUPPORTED = -20
EXECUTION_FAILURE = -21
BAD_PARAMETER = -22
# Setup platform info statics
WIN32 = sys.platform.startswith('win32')
LINUX = sys.platform.startswith('linux')
MACOS = sys.platform.startswith('darwin')
POSIX = LINUX or MACOS
OTHER = not POSIX and not WIN32
# Define Functions
def execl(*args):
"""
Replaces the current process with a new instance of the specified
executable. This function will only return if there is an issue starting the
new instance, in which case it will return false. Otherwise, it will not
return.
"""
retval = EXECUTION_FAILURE
if POSIX:
os.execvp(args[0], args)
elif WIN32:
os.execvp(sys.executable, args)
else:
retval = NOT_SUPPORTED
return retval
def os_kernel():
"""
Get the operating system's kernel version
"""
ker = "Unknown"
if LINUX:
ker = platform.release()
elif WIN32 or MACOS:
ker = platform.version()
return ker
def os_name():
"""
Get the operating system name
"""
name = "Unknown"
if LINUX:
distro = platform.linux_distribution()
plat = subprocess.check_output(["uname", "-o"])[:-1].decode()
name = "{} ({})".format(distro[0], plat)
elif WIN32:
name = platform.system()
elif MACOS:
name = "macOS"
return name
def os_version():
"""
Get the operating system version
"""
ver = "Unknown"
if LINUX:
distro = platform.linux_distribution()
ver = "{}-{}".format(distro[1], distro[2])
elif WIN32:
ver = platform.release()
elif MACOS:
ver = platform.mac_ver()[0]
return ver
def system_reboot(delay=0, force=True):
"""
Reboot the system.
"""
return system_shutdown(delay=delay, reboot=True, force=force)
def system_shutdown(delay=0, reboot=False, force=True):
"""
Run the system shutdown command. Can be used to reboot the system.
"""
command = "shutdown "
if POSIX:
command += "-r " if reboot else "-h "
command += "now " if delay == 0 else "+{} ".format(delay)
elif WIN32:
command += "/r " if reboot else "/s "
command += "/t {} ".format(delay*60)
command += "/f" if force else ""
else:
return NOT_SUPPORTED
return os.system(command)
|
apache-2.0
| 6,464,276,360,981,115,000
| 25.491379
| 84
| 0.633257
| false
| 3.909669
| false
| false
| false
|
dnarvaez/virtualenv-bootstrap
|
bootstrap.py
|
1
|
4429
|
#!/usr/bin/env python3
# Copyright 2013 Daniel Narvaez
#
# 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.
# This script is from https://github.com/dnarvaez/virtualenv-bootstrap
import hashlib
import json
import os
import shutil
import subprocess
import sys
import tarfile
import urllib.request
base_dir = os.path.dirname(os.path.abspath(__file__))
environ_namespace = "TEST"
start_message = "Installing virtualenv"
end_message = "\n"
packages = ["osourcer"]
submodules = []
virtualenv_version = "1.8.4"
virtualenv_dir = "sandbox"
cache_dir = "cache"
run_module = "osourcer.tool"
etag = "1"
def get_cache_dir():
return os.path.join(base_dir, cache_dir)
def get_virtualenv_dir():
return os.path.join(base_dir, virtualenv_dir)
def get_stamp_path():
return get_virtualenv_dir() + ".stamp"
def get_bin_path(name):
return os.path.join(get_virtualenv_dir(), "bin", name)
def create_virtualenv():
source_dir = os.path.join(get_cache_dir(),
"virtualenv-%s" % virtualenv_version)
if not os.path.exists(source_dir):
url = "https://pypi.python.org/packages/source/v/" \
"virtualenv/virtualenv-%s.tar.gz" % virtualenv_version
f = urllib.request.urlopen(url)
with tarfile.open(fileobj=f, mode="r:gz") as tar:
tar.extractall(get_cache_dir())
subprocess.check_call(["python3",
os.path.join(source_dir, "virtualenv.py"),
"-q", get_virtualenv_dir()])
def get_submodule_dirs():
return [os.path.join(base_dir, submodule) for submodule in submodules]
def install_packages():
args = [get_bin_path("pip"), "-q", "install"]
args.extend(packages)
args.extend(get_submodule_dirs())
subprocess.check_call(args)
def upgrade_submodules():
args = [get_bin_path("pip"), "-q", "install", "--no-deps", "--upgrade"]
args.extend(get_submodule_dirs())
subprocess.check_call(args)
def compute_submodules_hash():
data = ""
for submodule in submodules:
for root, dirs, files in os.walk(os.path.join(base_dir, submodule)):
for name in files:
path = os.path.join(root, name)
mtime = os.lstat(path).st_mtime
data = "%s%s %s\n" % (data, mtime, path)
return hashlib.sha256(data.encode("utf-8")).hexdigest()
def check_stamp():
try:
with open(get_stamp_path()) as f:
stamp = json.load(f)
except (IOError, ValueError):
return True, True
return (stamp["etag"] != etag,
stamp["submodules_hash"] != compute_submodules_hash())
def write_stamp():
stamp = {"etag": etag,
"submodules_hash": compute_submodules_hash()}
with open(get_stamp_path(), "w") as f:
json.dump(stamp, f)
def update_submodules():
update = os.environ.get(environ_namespace + "_UPDATE_SUBMODULES", "yes")
if update != "yes":
return
os.chdir(base_dir)
for module in submodules:
subprocess.check_call(["git", "submodule", "update", "--init",
module])
def main():
os.environ["PIP_DOWNLOAD_CACHE"] = get_cache_dir()
os.environ[environ_namespace + "_BASE_DIR"] = base_dir
os.environ[environ_namespace + "_VIRTUALENV"] = get_virtualenv_dir()
etag_changed, submodules_changed = check_stamp()
if etag_changed:
print(start_message)
update_submodules()
try:
shutil.rmtree(get_virtualenv_dir())
except OSError:
pass
create_virtualenv()
install_packages()
write_stamp()
print(end_message)
elif submodules_changed:
upgrade_submodules()
write_stamp()
args = [get_bin_path("python3"), "-m", run_module]
if len(sys.argv) > 1:
args.extend(sys.argv[1:])
os.execl(args[0], *args)
if __name__ == "__main__":
main()
|
apache-2.0
| 4,880,690,577,747,265,000
| 24.601156
| 76
| 0.621585
| false
| 3.592052
| false
| false
| false
|
CCI-Tools/cate-core
|
cate/ops/index.py
|
1
|
8641
|
# The MIT License (MIT)
# Copyright (c) 2016, 2017 by the ESA CCI Toolbox development team and contributors
#
# 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.
"""
Description
===========
Index calculation operations
Functions
=========
"""
import xarray as xr
import pandas as pd
from cate.core.op import op, op_input
from cate.ops.select import select_var
from cate.ops.subset import subset_spatial
from cate.ops.anomaly import anomaly_external
from cate.core.types import PolygonLike, VarName, ValidationError
from cate.util.monitor import Monitor
_ALL_FILE_FILTER = dict(name='All Files', extensions=['*'])
@op(tags=['index'])
@op_input('file', file_open_mode='r', file_filters=[dict(name='NetCDF', extensions=['nc']), _ALL_FILE_FILTER])
@op_input('var', value_set_source='ds', data_type=VarName)
def enso_nino34(ds: xr.Dataset,
var: VarName.TYPE,
file: str,
threshold: float = None,
monitor: Monitor = Monitor.NONE) -> pd.DataFrame:
"""
Calculate nino34 index, which is defined as a five month running mean of
anomalies of monthly means of SST data in Nino3.4 region:: lon_min=-170
lat_min=-5 lon_max=-120 lat_max=5.
:param ds: A monthly SST dataset
:param file: Path to the reference data file e.g. a climatology. A suitable reference dataset
can be generated using the long_term_average operation
:param var: Dataset variable (geophysial quantity) to use for index
calculation.
:param threshold: If given, boolean El Nino/La Nina timeseries will be
calculated and added to the output dataset according to the given
threshold. Where anomaly larger than the positive value of the threshold
indicates El Nino and anomaly smaller than the negative of the given
threshold indicates La Nina.
:param monitor: a progress monitor.
:return: A dataset that contains the index timeseries.
"""
n34 = '-170, -5, -120, 5'
name = 'ENSO N3.4 Index'
return _generic_index_calculation(ds, var, n34, 5, file, name, threshold, monitor)
@op(tags=['index'])
@op_input('var', value_set_source='ds', data_type=VarName)
@op_input('file', file_open_mode='r', file_filters=[dict(name='NetCDF', extensions=['nc']), _ALL_FILE_FILTER])
@op_input('region', value_set=['N1+2', 'N3', 'N34', 'N4', 'custom'])
@op_input('custom_region', data_type=PolygonLike)
def enso(ds: xr.Dataset,
var: VarName.TYPE,
file: str,
region: str = 'n34',
custom_region: PolygonLike.TYPE = None,
threshold: float = None,
monitor: Monitor = Monitor.NONE) -> pd.DataFrame:
"""
Calculate ENSO index, which is defined as a five month running mean of
anomalies of monthly means of SST data in the given region.
:param ds: A monthly SST dataset
:param file: Path to the reference data file e.g. a climatology. A suitable reference dataset
can be generated using the long_term_average operation
:param var: Dataset variable to use for index calculation
:param region: Region for index calculation, the default is Nino3.4
:param custom_region: If 'custom' is chosen as the 'region', this parameter
has to be provided to set the desired region.
:param threshold: If given, boolean El Nino/La Nina timeseries will be
calculated and added to the output dataset, according to the given
threshold. Where anomaly larger than then positive value of the threshold
indicates El Nino and anomaly smaller than the negative of the given
threshold indicates La Nina.
:param monitor: a progress monitor.
:return: A dataset that contains the index timeseries.
"""
regions = {'N1+2': '-90, -10, -80, 0',
'N3': '-150, -5, -90, 5',
'N3.4': '-170, -5, -120, 5',
'N4': '160, -5, -150, 5',
'custom': custom_region}
converted_region = PolygonLike.convert(regions[region])
if not converted_region:
raise ValidationError('No region has been provided to ENSO index calculation')
name = 'ENSO ' + region + ' Index'
if 'custom' == region:
name = 'ENSO Index over ' + PolygonLike.format(converted_region)
return _generic_index_calculation(ds, var, converted_region, 5, file, name, threshold, monitor)
@op(tags=['index'])
@op_input('var', value_set_source='ds', data_type=VarName)
@op_input('file', file_open_mode='r', file_filters=[dict(name='NetCDF', extensions=['nc']), _ALL_FILE_FILTER])
def oni(ds: xr.Dataset,
var: VarName.TYPE,
file: str,
threshold: float = None,
monitor: Monitor = Monitor.NONE) -> pd.DataFrame:
"""
Calculate ONI index, which is defined as a three month running mean of
anomalies of monthly means of SST data in the Nino3.4 region.
:param ds: A monthly SST dataset
:param file: Path to the reference data file e.g. a climatology. A suitable reference dataset
can be generated using the long_term_average operation
:param var: Dataset variable to use for index calculation
:param threshold: If given, boolean El Nino/La Nina timeseries will be
calculated and added to the output dataset, according to the given
threshold. Where anomaly larger than then positive value of the threshold
indicates El Nino and anomaly smaller than the negative of the given
threshold indicates La Nina.
:param monitor: a progress monitor.
:return: A dataset that containts the index timeseries
"""
n34 = '-170, -5, -120, 5'
name = 'ONI Index'
return _generic_index_calculation(ds, var, n34, 3, file, name, threshold, monitor)
def _generic_index_calculation(ds: xr.Dataset,
var: VarName.TYPE,
region: PolygonLike.TYPE,
window: int,
file: str,
name: str,
threshold: float = None,
monitor: Monitor = Monitor.NONE) -> pd.DataFrame:
"""
A generic index calculation. Where an index is defined as an anomaly
against the given reference of a moving average of the given window size of
the given given region of the given variable of the given dataset.
:param ds: Dataset from which to calculate the index
:param var: Variable from which to calculate index
:param region: Spatial subset from which to calculate the index
:param window: Window size for the moving average
:param file: Path to the reference file
:param threshold: Absolute threshold that indicates an ENSO event
:param name: Name of the index
:param monitor: a progress monitor.
:return: A dataset that contains the index timeseries
"""
var = VarName.convert(var)
region = PolygonLike.convert(region)
with monitor.starting("Calculate the index", total_work=2):
ds = select_var(ds, var)
ds_subset = subset_spatial(ds, region)
anom = anomaly_external(ds_subset, file, monitor=monitor.child(1))
with monitor.child(1).observing("Calculate mean"):
ts = anom.mean(dim=['lat', 'lon'])
df = pd.DataFrame(data=ts[var].values, columns=[name], index=ts.time.values)
retval = df.rolling(window=window, center=True).mean().dropna()
if threshold is None:
return retval
retval['El Nino'] = pd.Series((retval[name] > threshold),
index=retval.index)
retval['La Nina'] = pd.Series((retval[name] < -threshold),
index=retval.index)
return retval
|
mit
| 3,199,853,828,415,307,300
| 43.312821
| 110
| 0.671566
| false
| 3.967401
| false
| false
| false
|
los-cocos/etc_code
|
cocos#248--RectMapCollider, player sometimes stuck/start.py
|
1
|
6979
|
"""
A script to demo a defect in RectMapCollider, initial report by Netanel at
https://groups.google.com/forum/#!topic/cocos-discuss/a494vcH-u3I
The defect is that the player gets stuck at some positions, and it was confirmed
for cocos master Aug 1, 2015 (292ae676) and cocos-0.6.3-release, see cocos #248
The package 'blinker' (available from pipy) is needed to run this script
Further investigation shows that this happens when both of this concur
1. the player actively pushes against a blocking surface
2. player rect alligns with the grid tile.
changes from the OP bugdemo code:
lines irrelevant to the bug removed
changed player controls
added a view to show the potentially colliding cells that RectMapCollider
will consider (sin as red rectangle overlapping the player)
player pic edited to make visible the actual player boundary
Controlling the player:
use left-right for horizontal move, must keep pressing to move
use up-down to move vertical; a press adds/substracts up to y-velocity
Demoing the bug:
1. move to touch the left wall.
2. release 'left' key
3. move up and down, this works
4. keep pressed the 'left' key, and try to move down: player gets stuck
at some alineations
scene
background
scroller=ScrollingManager
tilemap <- load(...)['map0']
layer=Game (a ScrollableLayer)
sprite
particles
potential collisions view, ShowCollision
"""
from __future__ import division, print_function
from cocos.particle_systems import *
from cocos.particle import Color
from cocos.text import Label
from cocos.tiles import load, RectMapLayer
from cocos.mapcolliders import RectMapWithPropsCollider
from cocos.layer import Layer, ColorLayer, ScrollingManager, ScrollableLayer
from cocos.sprite import Sprite
from cocos.actions import *
from cocos.scene import Scene
from cocos.director import director
from pyglet.window import key
from pyglet.window.key import symbol_string, KeyStateHandler
from menu import GameMenu
import blinker
director.init(width=1920, height=480, autoscale = True, resizable = True)
Map = load("mapmaking.tmx")
scroller = ScrollingManager()
tilemap = Map['map0']
assert tilemap.origin_x == 0
assert tilemap.origin_y == 0
class Background(ColorLayer):
def __init__(self):
super(Background, self).__init__(65,120,255,255)
class ShowCollision(ScrollableLayer):
"""
A layer to show the cells a RectMapCollider considers potentially
colliding with the 'new' rect.
Use with CustomRectMapCollider so the event of interest is published
"""
def __init__(self):
super(ShowCollision, self).__init__()
self.collision_view = []
for i in range(10):
self.collision_view.append(ColorLayer(255, 0, 0, 255, width=64, height=64))
for e in self.collision_view:
self.add(e)
signal = blinker.signal("collider cells")
signal.connect(self.on_collision_changed)
def on_collision_changed(self, sender, payload=None):
for cell, view in zip(payload, self.collision_view):
view.position = (cell.i * 64, cell.j * 64)
view.opacity = 140
for i in range(len(payload), len(self.collision_view)):
self.collision_view[i].opacity = 0
class Game(ScrollableLayer):
is_event_handler = True
def __init__(self):
super(Game, self).__init__()
self.score = 0
# Add player
self.sprite = Sprite('magic.png')
self.sprite.position = 320, 240
self.sprite.direction = "right"
self.sprite.dx = 0
self.sprite.dy = 0
self.add(self.sprite, z=1)
# A list of balls
self.balls = set()
# Teleportation counter
self.teleportation = 0
self.sprite.jump = 0
def on_key_press(self, inp, modifers):
if symbol_string(inp) == "LEFT":
self.sprite.dx -= 3
print("press left, dx:", self.sprite.dx)
if symbol_string(inp) == "RIGHT":
self.sprite.dx += 3
print("press right, dx:", self.sprite.dx)
if symbol_string(inp) == "UP":
self.sprite.dy += 3
if self.sprite.dy > 6:
self.sprite.dy = 6
print("press up, dy:", self.sprite.dy)
if symbol_string(inp) == "DOWN":
self.sprite.dy -= 3
if self.sprite.dy < -6:
self.sprite.dy = -6
print("press down, dy:", self.sprite.dy)
def on_key_release(self, inp, modifers):
if symbol_string(inp) == "LEFT":
self.sprite.dx = 0
print("release left, dx:", self.sprite.dx)
if symbol_string(inp) == "RIGHT":
self.sprite.dx = 0
print("release right, dx:", self.sprite.dx)
class SpyCollider(RectMapWithPropsCollider):
"""
Same as RectMapWithPropsCollider, except it publishes which cells will be considered
for collision.
Usage:
# istantiate
a = SpyCollider()
# set the behavior for velocity change on collision with
# a.on_bump_handler = a.on_bump_slide
# add the signal we want to emit
a.signal = blinker.signal("collider cells")
# use as stock RectMapCollider
# catch the signal with something like ShowCollision
"""
def collide_map(self, maplayer, last, new, vx, vy):
"""collide_map en dos pasadas; """
objects = maplayer.get_in_region(*(new.bottomleft + new.topright))
self.signal.send(payload=objects)
return super(SpyCollider, self).collide_map(maplayer, last, new, vx, vy)
layer = Game()
collider = SpyCollider()
collider.on_bump_handler = collider.on_bump_slide
collider.signal = blinker.signal("collider cells")
#collider = RectMapCollider()
# WARN: this was hacked for bugdemo purposes only; don't use in real code:
# lots of globals
# position delta must use dt, else unpredictable view velocity
def update(dt):
""" Update game"""
last = layer.sprite.get_rect()
new = last.copy()
new.x += layer.sprite.dx
new.y += layer.sprite.dy
# dont care about velocity, pass 0, 0
collider.collide_map(tilemap, last, new, 0.0, 0.0)
layer.sprite.position = new.center
scroller.set_focus(*new.center)
# Schedule Updates
layer.schedule(update)
# Add map to scroller
scroller.add(tilemap)
#Create Scene
scene = Scene()
# Create and add background
background = Background()
scene.add(background)
#Add main layer to scroller
scroller.add(layer)
scroller.add(ShowCollision())
# Add scroller to scene
scene.add(scroller)
# Game menu configuration
menu = GameMenu(scene)
menuScene = Scene()
menuScene.add(menu)
director.run(menuScene)
|
mit
| 2,921,396,511,402,230,300
| 29.609649
| 91
| 0.640923
| false
| 3.638686
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.