rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
for i in xrange(0, l - 2):
|
for i in xrange(0, l-1):
|
def is_square_free(self): r""" Returns True if self does not contain squares, and False otherwise. EXAMPLES:: sage: W = Words('123') sage: W('12312').is_square_free() True sage: W('31212').is_square_free() False sage: W().is_square_free() True """ l = self.length() if l < 2: return True suff = self for i in xrange(0, l - 2): for ll in xrange(2, l-i+1, 2): if suff[:ll].is_square(): return False suff = suff[1:] return True
|
except:
|
except MIPSolverException:
|
def edge_coloring(g, value_only=False, vizing=False, hex_colors=False, log=0): r""" Properly colors the edges of a graph. See the URL http://en.wikipedia.org/wiki/Edge_coloring for further details on edge coloring. INPUT: - ``g`` -- a graph. - ``value_only`` -- (default: ``False``): - When set to ``True``, only the chromatic index is returned. - When set to ``False``, a partition of the edge set into matchings is returned if possible. - ``vizing`` -- (default: ``False``): - When set to ``True``, tries to find a `\Delta + 1`-edge-coloring, where `\Delta` is equal to the maximum degree in the graph. - When set to ``False``, tries to find a `\Delta`-edge-coloring, where `\Delta` is equal to the maximum degree in the graph. If impossible, tries to find and returns a `\Delta + 1`-edge-coloring. This implies that ``value_only=False``. - ``hex_colors`` -- (default: ``False``) when set to ``True``, the partition returned is a dictionary whose keys are colors and whose values are the color classes (ideal for plotting). - ``log`` -- (default: ``0``) as edge-coloring is an `NP`-complete problem, this function may take some time depending on the graph. Use ``log`` to define the level of verbosity you wantfrom the linear program solver. By default ``log=0``, meaning that there will be no message printed by the solver. OUTPUT: In the following, `\Delta` is equal to the maximum degree in the graph ``g``. - If ``vizing=True`` and ``value_only=False``, return a partition of the edge set into `\Delta + 1` matchings. - If ``vizing=False`` and ``value_only=True``, return the chromatic index. - If ``vizing=False`` and ``value_only=False``, return a partition of the edge set into the minimum number of matchings. - If ``vizing=True`` and ``value_only=True``, should return something, but mainly you are just trying to compute the maximum degree of the graph, and this is not the easiest way. By Vizing's theorem, a graph has a chromatic index equal to `\Delta` or to `\Delta + 1`. .. NOTE:: In a few cases, it is possible to find very quickly the chromatic index of a graph, while it remains a tedious job to compute a corresponding coloring. For this reason, ``value_only = True`` can sometimes be much faster, and it is a bad idea to compute the whole coloring if you do not need it ! EXAMPLE:: sage: from sage.graphs.graph_coloring import edge_coloring sage: g = graphs.PetersenGraph() sage: edge_coloring(g, value_only=True) # optional - requires GLPK or CBC 4 Complete graphs are colored using the linear-time round-robin coloring:: sage: from sage.graphs.graph_coloring import edge_coloring sage: len(edge_coloring(graphs.CompleteGraph(20))) 19 """ from sage.numerical.mip import MixedIntegerLinearProgram from sage.plot.colors import rainbow from sage.numerical.mip import MIPSolverException if g.is_clique(): if value_only: return g.order()-1 if g.order() % 2 == 0 else g.order() vertices = g.vertices() r = round_robin(g.order()) classes = [[] for v in g] if g.order() % 2 == 0 and not vizing: classes.pop() for (u, v, c) in r.edge_iterator(): classes[c].append((vertices[u], vertices[v])) if hex_colors: return dict(zip(rainbow(len(classes)), classes)) else: return classes if value_only and g.is_overfull(): return max(g.degree())+1 p = MixedIntegerLinearProgram(maximization=True) color = p.new_variable(dim=2) obj = {} k = max(g.degree()) # reorders the edge if necessary... R = lambda x: x if (x[0] <= x[1]) else (x[1], x[0]) # Vizing's coloring uses Delta + 1 colors if vizing: value_only = False k += 1 # A vertex can not have two incident edges with the same color. [p.add_constraint( sum([color[R(e)][i] for e in g.edges_incident(v, labels=False)]), max=1) for v in g.vertex_iterator() for i in xrange(k)] # an edge must have a color [p.add_constraint(sum([color[R(e)][i] for i in xrange(k)]), max=1, min=1) for e in g.edge_iterator(labels=False)] # anything is good as an objective value as long as it is satisfiable e = g.edge_iterator(labels=False).next() p.set_objective(color[R(e)][0]) p.set_binary(color) try: if value_only: p.solve(objective_only=True, log=log) else: chi = p.solve(log=log) except: if value_only: return k + 1 else: # if the coloring with Delta colors fails, tries Delta + 1 return edge_coloring(g, vizing=True, hex_colors=hex_colors, log=log) if value_only: return k # Builds the color classes color = p.get_values(color) classes = [[] for i in xrange(k)] [classes[i].append(e) for e in g.edge_iterator(labels=False) for i in xrange(k) if color[R(e)][i] == 1] # if needed, builds a dictionary from the color classes adding colors if hex_colors: return dict(zip(rainbow(len(classes)), classes)) else: return classes
|
"""
|
r"""
|
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.endomorphism_ring()([[1,-1,0],[-1,1,1],[0,3,1]]) sage: H.eigenvalues() [3, 1, -1] Note the effect of the extend option:: sage: V=QQ^2 sage: H=V.endomorphism_ring()([[0,-1],[1,0]]) sage: H.eigenvalues() [-1*I, 1*I] sage: H.eigenvalues(extend=False) []
|
If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered.
|
INPUT: - ``extend`` -- boolean (default: True) decides if base field extensions should be considered or not.
|
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.endomorphism_ring()([[1,-1,0],[-1,1,1],[0,3,1]]) sage: H.eigenvalues() [3, 1, -1] Note the effect of the extend option:: sage: V=QQ^2 sage: H=V.endomorphism_ring()([[0,-1],[1,0]]) sage: H.eigenvalues() [-1*I, 1*I] sage: H.eigenvalues(extend=False) []
|
We compute the eigenvalues of an endomorphism of QQ^3::
|
We compute the eigenvalues of an endomorphism of `\QQ^3`::
|
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.endomorphism_ring()([[1,-1,0],[-1,1,1],[0,3,1]]) sage: H.eigenvalues() [3, 1, -1] Note the effect of the extend option:: sage: V=QQ^2 sage: H=V.endomorphism_ring()([[0,-1],[1,0]]) sage: H.eigenvalues() [-1*I, 1*I] sage: H.eigenvalues(extend=False) []
|
Note the effect of the extend option::
|
Note the effect of the ``extend`` option::
|
def eigenvalues(self,extend=True): """ Returns a list with the eigenvalues of the endomorphism of vector spaces. If the option extend is set to True (default), then eigenvalues in extensions of the base field are considered. EXAMPLES: We compute the eigenvalues of an endomorphism of QQ^3:: sage: V=QQ^3 sage: H=V.endomorphism_ring()([[1,-1,0],[-1,1,1],[0,3,1]]) sage: H.eigenvalues() [3, 1, -1] Note the effect of the extend option:: sage: V=QQ^2 sage: H=V.endomorphism_ring()([[0,-1],[1,0]]) sage: H.eigenvalues() [-1*I, 1*I] sage: H.eigenvalues(extend=False) []
|
- extend (True) decides if base field extensions should be considered or not.
|
- ``extend`` -- boolean (default: True) decides if base field extensions should be considered or not.
|
def eigenvectors(self,extend=True): """ Computes the subspace of eigenvectors of a given eigenvalue. INPUT: - extend (True) decides if base field extensions should be considered or not. OUTPUT: A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors, and the algebraic multiplicity of the eigenvalue. EXAMPLES: :: sage: V=(QQ^4).subspace([[0,2,1,4],[1,2,5,0],[1,1,1,1]]) sage: H=(V.Hom(V))([[0,1,0],[-1,0,0],[0,0,3]]) sage: H.eigenvectors() [(3, [(0, 0, 1, -6/7)], 1), (-1*I, [(1, 1*I, 0, -0.571428571428572? + 2.428571428571429?*I)], 1), (1*I, [(1, -1*I, 0, -0.571428571428572? - 2.428571428571429?*I)], 1)] sage: H.eigenvectors(extend=False) [(3, [(0, 0, 1, -6/7)], 1)] sage: H1=(V.Hom(V))([[2,1,0],[0,2,0],[0,0,3]]) sage: H1.eigenvectors() [(3, [(0, 0, 1, -6/7)], 1), (2, [(0, 1, 0, 17/7)], 2)] sage: H1.eigenvectors(extend=False) [(3, [(0, 0, 1, -6/7)], 1), (2, [(0, 1, 0, 17/7)], 2)]
|
A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors, and the algebraic multiplicity of the eigenvalue.
|
A sequence of tuples. Each tuple contains an eigenvalue, a sequence with a basis of the corresponding subspace of eigenvectors, and the algebraic multiplicity of the eigenvalue.
|
def eigenvectors(self,extend=True): """ Computes the subspace of eigenvectors of a given eigenvalue. INPUT: - extend (True) decides if base field extensions should be considered or not. OUTPUT: A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors, and the algebraic multiplicity of the eigenvalue. EXAMPLES: :: sage: V=(QQ^4).subspace([[0,2,1,4],[1,2,5,0],[1,1,1,1]]) sage: H=(V.Hom(V))([[0,1,0],[-1,0,0],[0,0,3]]) sage: H.eigenvectors() [(3, [(0, 0, 1, -6/7)], 1), (-1*I, [(1, 1*I, 0, -0.571428571428572? + 2.428571428571429?*I)], 1), (1*I, [(1, -1*I, 0, -0.571428571428572? - 2.428571428571429?*I)], 1)] sage: H.eigenvectors(extend=False) [(3, [(0, 0, 1, -6/7)], 1)] sage: H1=(V.Hom(V))([[2,1,0],[0,2,0],[0,0,3]]) sage: H1.eigenvectors() [(3, [(0, 0, 1, -6/7)], 1), (2, [(0, 1, 0, 17/7)], 2)] sage: H1.eigenvectors(extend=False) [(3, [(0, 0, 1, -6/7)], 1), (2, [(0, 1, 0, 17/7)], 2)]
|
svectors=map(lambda j: V(j * V.basis_matrix()),i[1]) resu.append(tuple([i[0],svectors,i[2]]))
|
svectors=Sequence(map(lambda j: V(j * V.basis_matrix()),i[1]), cr=True) resu.append((i[0],svectors,i[2]))
|
def eigenvectors(self,extend=True): """ Computes the subspace of eigenvectors of a given eigenvalue. INPUT: - extend (True) decides if base field extensions should be considered or not. OUTPUT: A sequence of tuples. Each tuple contains an eigenvalue, a list with a basis of the corresponding subspace of eigenvectors, and the algebraic multiplicity of the eigenvalue. EXAMPLES: :: sage: V=(QQ^4).subspace([[0,2,1,4],[1,2,5,0],[1,1,1,1]]) sage: H=(V.Hom(V))([[0,1,0],[-1,0,0],[0,0,3]]) sage: H.eigenvectors() [(3, [(0, 0, 1, -6/7)], 1), (-1*I, [(1, 1*I, 0, -0.571428571428572? + 2.428571428571429?*I)], 1), (1*I, [(1, -1*I, 0, -0.571428571428572? - 2.428571428571429?*I)], 1)] sage: H.eigenvectors(extend=False) [(3, [(0, 0, 1, -6/7)], 1)] sage: H1=(V.Hom(V))([[2,1,0],[0,2,0],[0,0,3]]) sage: H1.eigenvectors() [(3, [(0, 0, 1, -6/7)], 1), (2, [(0, 1, 0, 17/7)], 2)] sage: H1.eigenvectors(extend=False) [(3, [(0, 0, 1, -6/7)], 1), (2, [(0, 1, 0, 17/7)], 2)]
|
- ``var`` - string (default: 'x') a variable
|
- ``var`` - string (default: 'x') a variable name
|
def minpoly(self,var='x'): """ Computes the minimal polynomial. INPUT: - ``var`` - string (default: 'x') a variable OUTPUT: polynomial in var - the minimal polynomial of the endomorphism. EXAMPLES: Compute the minimal polynomial, and check it :: sage: V=GF(7)^3 sage: H=V.Hom(V)([[0,1,2],[-1,0,3],[2,4,1]]) sage: H Free module morphism defined by the matrix [0 1 2] [6 0 3] [2 4 1] Domain: Vector space of dimension 3 over Finite Field of size 7 Codomain: Vector space of dimension 3 over Finite Field of size 7 sage: H.minpoly() x^3 + 6*x^2 + 6*x + 1 sage: H^3+6*H^2+6*H+1 Free module morphism defined by the matrix [0 0 0] [0 0 0] [0 0 0] Domain: Vector space of dimension 3 over Finite Field of size 7 Codomain: Vector space of dimension 3 over Finite Field of size 7
|
.. [CB07] Nicolas T\. Courtois, Gregory V\. Bard *Algebraic Cryptanalysis of the Data Encryption Standard*; Cryptography and Coding -- 11th IMA International Conference; 2007; available at http://eprint.iacr.org/2006/402
|
.. [CBJ07] Gregory V\. Bard, and Nicolas T\. Courtois, and Chris Jefferson. *Efficient Methods for Conversion and Solution of Sparse Systems of Low-Degree Multivariate Polynomials over GF(2) via SAT-Solvers*. Cryptology ePrint Archive: Report 2007/024. available at http://eprint.iacr.org/2007/024
|
def eliminate_linear_variables(self, maxlength=3, skip=lambda lm,tail: False): """ Return a new system where "linear variables" are eliminated.
|
This is called "massaging" in [CB07]_.
|
This is called "massaging" in [CBJ07]_.
|
def eliminate_linear_variables(self, maxlength=3, skip=lambda lm,tail: False): """ Return a new system where "linear variables" are eliminated.
|
Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``.
|
Return a list of the associated primes of primary ideals of which the intersection is `I` = ``self``.
|
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``. An ideal `Q` is called primary if it is a proper ideal of the ring `R` and if whenever `ab \in Q` and `a \not\in Q` then `b^n \in Q` for some `n \in \ZZ`. If `Q` is a primary ideal of the ring `R`, then the radical ideal `P` of `Q`, i.e. `P = \{a \in R, a^n \in Q\}` for some `n \in \ZZ`, is called the *associated prime* of `Q`. If `I` is a proper ideal of the ring `R` then there exists a decomposition in primary ideals `Q_i` such that - their intersection is `I` - none of the `Q_i` contains the intersection of the rest, and - the associated prime ideals of `Q_i` are pairwise different. This method returns the associated primes of the `Q_i`. INPUT: - ``algorithm`` - string: - ``'sy'`` - (default) use the shimoyama-yokoyama algorithm - ``'gtz'`` - use the gianni-trager-zacharias algorithm OUTPUT: - ``list`` - a list of primary ideals and their associated primes [(primary ideal, associated prime), ...] EXAMPLES:: sage: R.<x,y,z> = PolynomialRing(QQ, 3, order='lex') sage: p = z^2 + 1; q = z^3 + 2 sage: I = (p*q^2, y-z^2)*R sage: pd = I.associated_primes(); pd [Ideal (z^3 + 2, y - z^2) of Multivariate Polynomial Ring in x, y, z over Rational Field, Ideal (z^2 + 1, y + 1) of Multivariate Polynomial Ring in x, y, z over Rational Field] ALGORITHM: Uses Singular. REFERENCES:
|
- ``list`` - a list of primary ideals and their associated primes [(primary ideal, associated prime), ...]
|
- ``list`` - a list of associated primes
|
def associated_primes(self, algorithm='sy'): r""" Return a list of primary ideals (and their associated primes) such that their intersection is `I` = ``self``. An ideal `Q` is called primary if it is a proper ideal of the ring `R` and if whenever `ab \in Q` and `a \not\in Q` then `b^n \in Q` for some `n \in \ZZ`. If `Q` is a primary ideal of the ring `R`, then the radical ideal `P` of `Q`, i.e. `P = \{a \in R, a^n \in Q\}` for some `n \in \ZZ`, is called the *associated prime* of `Q`. If `I` is a proper ideal of the ring `R` then there exists a decomposition in primary ideals `Q_i` such that - their intersection is `I` - none of the `Q_i` contains the intersection of the rest, and - the associated prime ideals of `Q_i` are pairwise different. This method returns the associated primes of the `Q_i`. INPUT: - ``algorithm`` - string: - ``'sy'`` - (default) use the shimoyama-yokoyama algorithm - ``'gtz'`` - use the gianni-trager-zacharias algorithm OUTPUT: - ``list`` - a list of primary ideals and their associated primes [(primary ideal, associated prime), ...] EXAMPLES:: sage: R.<x,y,z> = PolynomialRing(QQ, 3, order='lex') sage: p = z^2 + 1; q = z^3 + 2 sage: I = (p*q^2, y-z^2)*R sage: pd = I.associated_primes(); pd [Ideal (z^3 + 2, y - z^2) of Multivariate Polynomial Ring in x, y, z over Rational Field, Ideal (z^2 + 1, y + 1) of Multivariate Polynomial Ring in x, y, z over Rational Field] ALGORITHM: Uses Singular. REFERENCES:
|
f_l_dict = {(None,None):[(tuple([x]),tuple(self._vertex_face_indexset([x])))
|
f_l_dict = {(None,tuple(range(self.n_Hrepresentation()))):[(tuple([x]),tuple(self._vertex_face_indexset([x])))
|
def face_lattice(self): """ Computes the face-lattice poset. Elements are tuples of (vertices, facets) - i.e. this keeps track of both the vertices in each face, and all the facets containing them.
|
tuple(range(self.n_Hrepresentation()))))
|
None))
|
def face_lattice(self): """ Computes the face-lattice poset. Elements are tuples of (vertices, facets) - i.e. this keeps track of both the vertices in each face, and all the facets containing them.
|
if len(xi) != n:
|
if len(yi) != n:
|
def cnf(self, xi=None, yi=None, format=None): """ Return a representation of this S-Box in conjunctive normal form.
|
x = self.to_bits(e)
|
x = self.to_bits(e, m)
|
def cnf(self, xi=None, yi=None, format=None): """ Return a representation of this S-Box in conjunctive normal form.
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().is_prime()`` to find out for sure whether this quotient ring is really not an integral domain, of if Sage is unable to determine the answer. EXAMPLES:: sage: R = Integers(8) sage: R.is_integral_domain()
|
def is_integral_domain(self, proof=True): r""" With ``proof`` equal to ``True`` (the default), this function may raise a ``NotImplementedError``. When ``proof`` is ``False``, if ``True`` is returned, then self is definitely an integral domain. If the function returns ``False``, then either self is not an integral domain or it was unable to determine whether or not self is an integral domain. EXAMPLES:: sage: R.<x,y> = QQ[] sage: R.quo(x^2 - y).is_integral_domain() True sage: R.quo(x^2 - y^2).is_integral_domain()
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().is_prime()`` to find out for sure whether this quotient ring is really not an integral domain, of if Sage is unable to determine the answer. EXAMPLES:: sage: R = Integers(8) sage: R.is_integral_domain() False sage: R.<a,b,c> = ZZ['a','b','c'] sage: I = R.ideal(a,b) sage: Q = R.quotient_ring(I) sage: Q.is_integral_domain() Traceback (most recent call last): ... NotImplementedError """ if proof: return self.defining_ideal().is_prime() else: try: return self.defining_ideal.is_prime() except AttributeError: return False except NotImplementedError: return False
|
sage: R.<a,b,c> = ZZ['a','b','c'] sage: I = R.ideal(a,b) sage: Q = R.quotient_ring(I)
|
sage: R.quo(x^2 - y^2).is_integral_domain(proof=False) False sage: R.<a,b,c> = ZZ[] sage: Q = R.quotient_ring([a, b])
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().is_prime()`` to find out for sure whether this quotient ring is really not an integral domain, of if Sage is unable to determine the answer. EXAMPLES:: sage: R = Integers(8) sage: R.is_integral_domain() False sage: R.<a,b,c> = ZZ['a','b','c'] sage: I = R.ideal(a,b) sage: Q = R.quotient_ring(I) sage: Q.is_integral_domain() Traceback (most recent call last): ... NotImplementedError """ if proof: return self.defining_ideal().is_prime() else: try: return self.defining_ideal.is_prime() except AttributeError: return False except NotImplementedError: return False
|
return self.defining_ideal.is_prime() except AttributeError: return False
|
return self.defining_ideal().is_prime()
|
def is_integral_domain(self, proof = True): r""" If this function returns ``True`` then self is definitely an integral domain. If it returns ``False``, then either self is definitely not an integral domain or this function was unable to determine whether or not self is an integral domain. Use ``self.defining_ideal().is_prime()`` to find out for sure whether this quotient ring is really not an integral domain, of if Sage is unable to determine the answer. EXAMPLES:: sage: R = Integers(8) sage: R.is_integral_domain() False sage: R.<a,b,c> = ZZ['a','b','c'] sage: I = R.ideal(a,b) sage: Q = R.quotient_ring(I) sage: Q.is_integral_domain() Traceback (most recent call last): ... NotImplementedError """ if proof: return self.defining_ideal().is_prime() else: try: return self.defining_ideal.is_prime() except AttributeError: return False except NotImplementedError: return False
|
xy_data_arrays = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays)
|
xy_data_arrays = numpy.asarray([[[func(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)] for func in g],dtype=float) xy_data_array=numpy.abs(xy_data_arrays.prod(axis=0)) neg_indices = (xy_data_arrays<0).all(axis=0) xy_data_array[neg_indices]=-xy_data_array[neg_indices]
|
def region_plot(f, xrange, yrange, plot_points, incol, outcol, bordercol, borderstyle, borderwidth): r""" ``region_plot`` takes a boolean function of two variables, `f(x,y)` and plots the region where f is True over the specified ``xrange`` and ``yrange`` as demonstrated below. ``region_plot(f, (xmin, xmax), (ymin, ymax), ...)`` INPUT: - ``f`` -- a boolean function of two variables - ``(xmin, xmax)`` -- 2-tuple, the range of ``x`` values OR 3-tuple ``(x,xmin,xmax)`` - ``(ymin, ymax)`` -- 2-tuple, the range of ``y`` values OR 3-tuple ``(y,ymin,ymax)`` - ``plot_points`` -- integer (default: 100); number of points to plot in each direction of the grid - ``incol`` -- a color (default: ``'blue'``), the color inside the region - ``outcol`` -- a color (default: ``'white'``), the color of the outside of the region If any of these options are specified, the border will be shown as indicated, otherwise it is only implicit (with color ``incol``) as the border of the inside of the region. - ``bordercol`` -- a color (default: ``None``), the color of the border (``'black'`` if ``borderwidth`` or ``borderstyle`` is specified but not ``bordercol``) - ``borderstyle`` -- string (default: 'solid'), one of 'solid', 'dashed', 'dotted', 'dashdot' - ``borderwidth`` -- integer (default: None), the width of the border in pixels EXAMPLES: Here we plot a simple function of two variables:: sage: x,y = var('x,y') sage: region_plot(cos(x^2+y^2) <= 0, (x, -3, 3), (y, -3, 3)) Here we play with the colors:: sage: region_plot(x^2+y^3 < 2, (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray') An even more complicated plot, with dashed borders:: sage: region_plot(sin(x)*sin(y) >= 1/4, (x,-10,10), (y,-10,10), incol='yellow', bordercol='black', borderstyle='dashed', plot_points=250) A disk centered at the origin:: sage: region_plot(x^2+y^2<1, (x,-1,1), (y,-1,1)).show(aspect_ratio=1) A plot with more than one condition:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2)) Since it doesn't look very good, let's increase plot_points:: sage: region_plot([x^2+y^2<1, x<y], (x,-2,2), (y,-2,2), plot_points=400).show(aspect_ratio=1) #long time The first quadrant of the unit circle:: sage: region_plot([y>0, x>0, x^2+y^2<1], (x,-1.1, 1.1), (y,-1.1, 1.1), plot_points = 400).show(aspect_ratio=1) Here is another plot, with a huge border:: sage: region_plot(x*(x-1)*(x+1)+y^2<0, (x, -3, 2), (y, -3, 3), incol='lightblue', bordercol='gray', borderwidth=10, plot_points=50) If we want to keep only the region where x is positive:: sage: region_plot([x*(x-1)*(x+1)+y^2<0, x>-1], (x, -3, 2), (y, -3, 3), incol='lightblue', plot_points=50) Here we have a cut circle:: sage: region_plot([x^2+y^2<4, x>-1], (x, -2, 2), (y, -2, 2), incol='lightblue', bordercol='gray', plot_points=200).show(aspect_ratio=1) """ from sage.plot.plot import Graphics from sage.plot.misc import setup_for_eval_on_grid if not isinstance(f, (list, tuple)): f = [f] f = [equify(g) for g in f] g, ranges = setup_for_eval_on_grid(f, [xrange, yrange], plot_points) xrange,yrange=[r[:2] for r in ranges] xy_data_arrays = map(lambda g: [[g(x, y) for x in xsrange(*ranges[0], include_endpoint=True)] for y in xsrange(*ranges[1], include_endpoint=True)], g) xy_data_array = map(lambda *rows: map(lambda *vals: mangle_neg(vals), *rows), *xy_data_arrays) from matplotlib.colors import ListedColormap incol = rgbcolor(incol) outcol = rgbcolor(outcol) cmap = ListedColormap([incol, outcol]) cmap.set_over(outcol) cmap.set_under(incol) g = Graphics() opt = contour_plot.options.copy() opt.pop('plot_points') opt.pop('fill') opt.pop('contours') opt.pop('frame') g.add_primitive(ContourPlot(xy_data_array, xrange,yrange, dict(plot_points=plot_points, contours=[-1e307, 0, 1e307], cmap=cmap, fill=True, **opt))) if bordercol or borderstyle or borderwidth: cmap = [rgbcolor(bordercol)] if bordercol else ['black'] linestyles = [borderstyle] if borderstyle else None linewidths = [borderwidth] if borderwidth else None opt.pop('linestyles') opt.pop('linewidths') g.add_primitive(ContourPlot(xy_data_array, xrange, yrange, dict(plot_points=plot_points, linestyles=linestyles, linewidths=linewidths, contours=[0], cmap=[bordercol], fill=False, **opt))) return g
|
def mangle_neg(vals): """ Returns the product of all values in vals, with the result nonnegative if any of the values is nonnegative. EXAMPLES:: sage: from sage.plot.contour_plot import mangle_neg sage: mangle_neg([-1.2, -0.74, -2.56, -1.01]) -2.29601280000000 sage: mangle_neg([-1.2, 0.0, -2.56]) 0.000000000000000 sage: mangle_neg([-1.2, -0.74, -2.56, 1.01]) 2.29601280000000 """ from sage.misc.misc_c import prod res = abs(prod(vals)) if any(map(lambda v: v>=0, vals)): return res else: return -res
|
def equify(f): """ Returns the equation rewritten as a symbolic function to give negative values when True, positive when False. EXAMPLES:: sage: from sage.plot.contour_plot import equify sage: var('x, y') (x, y) sage: equify(x^2 < 2) x^2 - 2 sage: equify(x^2 > 2) -x^2 + 2 sage: equify(x*y > 1) -x*y + 1 sage: equify(y > 0) -y """ import operator from sage.calculus.all import symbolic_expression op = f.operator() if op is operator.gt or op is operator.ge: return symbolic_expression(f.rhs() - f.lhs()) else: return symbolic_expression(f.lhs() - f.rhs())
|
|
- ``e`` - A Composition
|
- ``e`` - a composition
|
def LyndonWords(e=None, k=None): """ Returns the combinatorial class of Lyndon words. A Lyndon word `w` is a word that is lexicographically less than all of its rotations. Equivalently, whenever `w` is split into two non-empty substrings, `w` is lexicographically less than the right substring. INPUT: - no input at all or - ``e`` - integer, size of alphabet - ``k`` - integer, length of the words or - ``e`` - A Composition OUTPUT: A combinatorial class of Lyndon words EXAMPLES:: sage: LyndonWords() Lyndon words If e is an integer, then e specifies the length of the alphabet; k must also be specified in this case:: sage: LW = LyndonWords(3,3); LW Lyndon words from an alphabet of size 3 of length 3 sage: LW.first() word: 112 sage: LW.last() word: 233 sage: LW.random_element() word: 112 sage: LW.cardinality() 8 If e is a (weak) composition, then it returns the class of Lyndon words that have evaluation e:: sage: LyndonWords([2, 0, 1]).list() [word: 113] sage: LyndonWords([2, 0, 1, 0, 1]).list() [word: 1135, word: 1153, word: 1315] sage: LyndonWords([2, 1, 1]).list() [word: 1123, word: 1132, word: 1213] """ if e is None and k is None: return LyndonWords_class() elif isinstance(e, (int, Integer)): if e > 0: if not isinstance(k, (int, Integer)): raise TypeError, "k must be a non-negative integer" if k < 0: raise TypeError, "k must be a non-negative integer" return LyndonWords_nk(e, k) elif e in Compositions(): return LyndonWords_evaluation(e) raise TypeError, "e must be a positive integer or a composition"
|
A combinatorial class of Lyndon words
|
A combinatorial class of Lyndon words.
|
def LyndonWords(e=None, k=None): """ Returns the combinatorial class of Lyndon words. A Lyndon word `w` is a word that is lexicographically less than all of its rotations. Equivalently, whenever `w` is split into two non-empty substrings, `w` is lexicographically less than the right substring. INPUT: - no input at all or - ``e`` - integer, size of alphabet - ``k`` - integer, length of the words or - ``e`` - A Composition OUTPUT: A combinatorial class of Lyndon words EXAMPLES:: sage: LyndonWords() Lyndon words If e is an integer, then e specifies the length of the alphabet; k must also be specified in this case:: sage: LW = LyndonWords(3,3); LW Lyndon words from an alphabet of size 3 of length 3 sage: LW.first() word: 112 sage: LW.last() word: 233 sage: LW.random_element() word: 112 sage: LW.cardinality() 8 If e is a (weak) composition, then it returns the class of Lyndon words that have evaluation e:: sage: LyndonWords([2, 0, 1]).list() [word: 113] sage: LyndonWords([2, 0, 1, 0, 1]).list() [word: 1135, word: 1153, word: 1315] sage: LyndonWords([2, 1, 1]).list() [word: 1123, word: 1132, word: 1213] """ if e is None and k is None: return LyndonWords_class() elif isinstance(e, (int, Integer)): if e > 0: if not isinstance(k, (int, Integer)): raise TypeError, "k must be a non-negative integer" if k < 0: raise TypeError, "k must be a non-negative integer" return LyndonWords_nk(e, k) elif e in Compositions(): return LyndonWords_evaluation(e) raise TypeError, "e must be a positive integer or a composition"
|
verification that the input data represent a lyndon word.
|
verification that the input data represent a Lyndon word.
|
def __init__(self, data, check=True): r""" Construction of a Lyndon word.
|
a lyndon word
|
A Lyndon word.
|
def __init__(self, data, check=True): r""" Construction of a Lyndon word.
|
sage: browse_sage_doc(identity_matrix, 'rst')[:9] '**File:**' sage: browse_sage_doc(identity_matrix, 'rst')[-60:] 'MatrixSpace of 3 by 3 sparse matrices over Integer Ring\n ' sage: browse_sage_doc(identity_matrix, 'html', False)[:59] '<div class="docstring">\n \n <p><strong>File:</strong> /v'
|
sage: browse_sage_doc(identity_matrix, 'rst') "...**File:**...**Type:**...**Definition:** identity_matrix..." sage: identity_matrix.__doc__.replace('\\','\\\\') in browse_sage_doc(identity_matrix, 'rst') True sage: browse_sage_doc(identity_matrix, 'html', False) '...div...File:...Type:...Definition:...identity_matrix...'
|
def __call__(self, obj, output='html', view=True): r""" Return the documentation for ``obj``.
|
return (self._sublattice_polytope.facet_constant(i) - self.facet_normal(i) * self._shift_vector)
|
return (self._sublattice_polytope.facet_constant(i) * self._dual_embedding_scale - self.facet_normal(i) * self._shift_vector )
|
def facet_constant(self, i): r""" Return the constant in the ``i``-th facet inequality of this polytope. The i-th facet inequality is given by self.facet_normal(i) * X + self.facet_constant(i) >= 0. INPUT: - ``i`` - integer, the index of the facet OUTPUT: - integer -- the constant in the ``i``-th facet inequality. EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1 """ if self.is_reflexive(): return 1 elif self.ambient_dim() == self.dim(): return self._facet_constants[i] else: return (self._sublattice_polytope.facet_constant(i) - self.facet_normal(i) * self._shift_vector)
|
return (self._embedding_matrix * self._sublattice_polytope.facet_normal(i))
|
return ( self._sublattice_polytope.facet_normal(i) * self._dual_embedding_matrix )
|
def facet_normal(self, i): r""" Return the inner normal to the ``i``-th facet of this polytope. If this polytope is not full-dimensional, facet normals will be parallel to the affine subspace spanned by this polytope. INPUT: - ``i`` -- integer, the index of the facet OUTPUT: - vectors -- the inner normal of the ``i``-th facet EXAMPLES: Let's take a look at facets of the octahedron and some polytopes inside it:: sage: o = lattice_polytope.octahedron(3) sage: o.vertices() [ 1 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: o.facet_normal(0) (-1, -1, 1) sage: o.facet_constant(0) 1 sage: m = copy(o.vertices()) sage: m[0,0] = 0 sage: m [ 0 0 0 -1 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (-1, 0, 0) sage: p.facet_constant(0) 0 sage: m[0,3] = 0 sage: m [ 0 0 0 0 0 0] [ 0 1 0 0 -1 0] [ 0 0 1 0 0 -1] sage: p = LatticePolytope(m) sage: p.facet_normal(0) (0, -1, 1) sage: p.facet_constant(0) 1 """ if self.is_reflexive(): return self.polar().vertex(i) elif self.ambient_dim() == self.dim(): return self._facet_normals[i] else: return (self._embedding_matrix * self._sublattice_polytope.facet_normal(i))
|
from optparse import OptionParser parser = OptionParser() parser.add_option("-y", "--ymin", dest="ymin", default="0", help="minimum y value") parser.add_option("-Y", "--ymax", dest="ymax", default="10", help="maximum y value") parser.add_option("-N", "--Names", dest="hosts", nargs=2, default=None, help="host list for sync graph") parser.add_option("-s", "--start", dest="start", type="int", default=0, help="starting sequence number") parser.add_option("-d", "--debug", dest="debug", type="int", default=0, help="print debugging info (verbose)") (options, args) = parser.parse_args()
|
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == None: continue if packet.data.data == None: continue if type(packet.data.data) != icmpv4: continue icmp = packet.data.data if type(icmp.data) != icmpv4echo: continue if icmp.type != ICMP_ECHO: continue trace[icmp.data.sequence] = datetime.datetime.fromtimestamp(packet.timestamp) files.append(trace) for i in range(0,len(files[0])): try: if files[0][i] == files[1][i]: print "0:00:00.000000" continue except KeyError: print "missing packet %d" % i continue if files[0][i] < files[1][i]: print files[1][i] - files[0][i] else: print files[0][i] - files[1][i]
|
|
for filename in sys.argv[1:]:
|
for filename in options.hosts:
|
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == None: continue if packet.data.data == None: continue if type(packet.data.data) != icmpv4: continue icmp = packet.data.data if type(icmp.data) != icmpv4echo: continue if icmp.type != ICMP_ECHO: continue trace[icmp.data.sequence] = datetime.datetime.fromtimestamp(packet.timestamp) files.append(trace) for i in range(0,len(files[0])): try: if files[0][i] == files[1][i]: print "0:00:00.000000" continue except KeyError: print "missing packet %d" % i continue if files[0][i] < files[1][i]: print files[1][i] - files[0][i] else: print files[0][i] - files[1][i]
|
for i in range(0,len(files[0])):
|
plotter = Gnuplot.Gnuplot(debug=1) plotter.set_range('yrange', [options.ymin, options.ymax]) graph = [] for i in range(options.start,options.start + len(files[0])):
|
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == None: continue if packet.data.data == None: continue if type(packet.data.data) != icmpv4: continue icmp = packet.data.data if type(icmp.data) != icmpv4echo: continue if icmp.type != ICMP_ECHO: continue trace[icmp.data.sequence] = datetime.datetime.fromtimestamp(packet.timestamp) files.append(trace) for i in range(0,len(files[0])): try: if files[0][i] == files[1][i]: print "0:00:00.000000" continue except KeyError: print "missing packet %d" % i continue if files[0][i] < files[1][i]: print files[1][i] - files[0][i] else: print files[0][i] - files[1][i]
|
if files[0][i] == files[1][i]: print "0:00:00.000000" continue
|
delta = abs(files[1][i] - files[0][i])
|
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == None: continue if packet.data.data == None: continue if type(packet.data.data) != icmpv4: continue icmp = packet.data.data if type(icmp.data) != icmpv4echo: continue if icmp.type != ICMP_ECHO: continue trace[icmp.data.sequence] = datetime.datetime.fromtimestamp(packet.timestamp) files.append(trace) for i in range(0,len(files[0])): try: if files[0][i] == files[1][i]: print "0:00:00.000000" continue except KeyError: print "missing packet %d" % i continue if files[0][i] < files[1][i]: print files[1][i] - files[0][i] else: print files[0][i] - files[1][i]
|
if files[0][i] < files[1][i]: print files[1][i] - files[0][i] else: print files[0][i] - files[1][i]
|
def main(): # Right now there are no command line arguments # we just open every file we're given # and read the packets from it. files = [] for filename in sys.argv[1:]: pcap = pcs.PcapConnector(filename) trace = {} done = False while not done: try: packet = pcap.readpkt() except: done = True if packet.data == None: continue if packet.data.data == None: continue if type(packet.data.data) != icmpv4: continue icmp = packet.data.data if type(icmp.data) != icmpv4echo: continue if icmp.type != ICMP_ECHO: continue trace[icmp.data.sequence] = datetime.datetime.fromtimestamp(packet.timestamp) files.append(trace) for i in range(0,len(files[0])): try: if files[0][i] == files[1][i]: print "0:00:00.000000" continue except KeyError: print "missing packet %d" % i continue if files[0][i] < files[1][i]: print files[1][i] - files[0][i] else: print files[0][i] - files[1][i]
|
|
self.file = socket(AF_INET6, SOCK_RAW, IPPROTO_IP)
|
self.file = socket(AF_INET6, SOCK_RAW, IPPROTO_IPV6)
|
def __init__(self, name = None): """initialize an IPPConnector class for raw IPv6 access""" try: self.file = socket(AF_INET6, SOCK_RAW, IPPROTO_IP) except: raise
|
m = pcs.Field("m", 4)
|
m = pcs.Field("m", 1)
|
def __init__(self, bytes = None, timestamp = None, **kv): v = pcs.Field("v", 2) # version p = pcs.Field("p", 1) # padded x = pcs.Field("x", 1) # extended cc = pcs.Field("cc", 4) # csrc count m = pcs.Field("m", 4) # m-bit pt = pcs.Field("pt", 7, discriminator=True) # payload type seq = pcs.Field("seq", 16) # sequence ssrc = pcs.Field("ssrc", 32) # source opt = pcs.OptionListField("opt") # optional fields
|
pcs.Packet.__init__(self, [v, p, x, cc, m, pt, seq, ssrc, opt], \
|
pcs.Packet.__init__(self, [v, p, x, cc, m, pt, seq, ts, ssrc, opt], \
|
def __init__(self, bytes = None, timestamp = None, **kv): v = pcs.Field("v", 2) # version p = pcs.Field("p", 1) # padded x = pcs.Field("x", 1) # extended cc = pcs.Field("cc", 4) # csrc count m = pcs.Field("m", 4) # m-bit pt = pcs.Field("pt", 7, discriminator=True) # payload type seq = pcs.Field("seq", 16) # sequence ssrc = pcs.Field("ssrc", 32) # source opt = pcs.OptionListField("opt") # optional fields
|
if packet.data is not None:
|
if packet.data not in [None, packet]:
|
def chain(self): """Return the packet and its next packets as a chain.""" chain = Chain([]) packet = self done = False while not done: packet._head = chain chain.append(packet) if packet.data is not None: packet = packet.data else: done = True return chain
|
* simtype (string='DP'): The simulator type """
|
* simtype (string='Python'): The simulator type """
|
def __init__(self, nsd=2, time=None, space_symbs=None, simtype="Python", **kwargs): """Constructor. Arguments are: * nsd (int=2) : The number of space dimensions for the PDE * time (symbol=None): The symbol for time * space_symbs (symbol=None): List of existing symbols. * simtype (string='DP'): The simulator type """ if space_symbs: self.x = space_symbs self.n = len(space_symbs) else: self.x = [] self.n = nsd for i in range(nsd): symb = "x_%i" % (i,) self.x.append(Symbol(symb)) self.t = None if isinstance(time, Symbol): self.t = time elif time: self.t = Symbol('t') self.simtype = simtype self.simtype_obj = SimTypeFactory(simtype) # Todo: Move the name of the attach methods for callbacks to SimType self.v_func_name = "set_v_func" self.b_func_name = "set_b_func" if kwargs: # Additional Python callbacks can be passed as keyword arguments self.extra_callbacks = kwargs
|
the symbolic.expression v, that returns float
|
the Symbolic.expression v, that returns float
|
def _vValue(self, point, time): """This is the point eval of the analytical solution. Pass the point to the symbolic.expression v, that returns float """ try: retVal = self.v.eval(*(point+(time, ))) except: raise FammsError, "Could not evaluate the analytical solution" return retVal
|
def listfiles(archive): pin = os.popen("tar ztf %s | sort" % (archive), "r") files = map(lambda x: x.strip(), pin.readlines()) pin.close() cleanedfiles = [] for file in files: slashpos = file.find("/") if slashpos != -1: cleanedname = file[slashpos+1:] else: cleanedname = file if cleanedname.find(".cache.html") != -1: continue cleanedfiles.append(cleanedname) return cleanedfiles
|
def listfiles(archive): pin = os.popen("tar ztf %s | sort" % (archive), "r") files = map(lambda x: x.strip(), pin.readlines()) pin.close() cleanedfiles = [] for file in files: # Remove archive file name from the file names slashpos = file.find("/") if slashpos != -1: cleanedname = file[slashpos+1:] else: cleanedname = file # Purge GWT compilation files. if cleanedname.find(".cache.html") != -1: continue cleanedfiles.append(cleanedname) return cleanedfiles
|
|
def listTarVaadinJarFiles(tarfile, vaadinversion): jarfile = "vaadin-linux-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "tar zOxf %s %s > %s " % (tarfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
def listJarFiles(jarfile): # Read the jar content listing pin = os.popen("unzip -ql %s" % jarfile, "r") lines = map(lambda x: x[:-1], pin.readlines()) pin.close() # Determine the position of file names namepos = lines[0].find("Name") files = [] for i in xrange(2, len(lines)-2): filename = lines[i][namepos:] files.append(filename) return files
|
|
tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd)
|
zipcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (zipcmd)
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
filename = "vaadin-%s.tar.gz" % (latestversion) package = latestURL + filename localpackage = "/tmp/%s" % (filename)
|
latestfilename = "vaadin-%s.zip" % (latestversion) latestpackage = latestURL + latestfilename locallatestpackage = "/tmp/%s" % (latestfilename)
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
os.stat(localpackage) print "Latest package already exists in %s" % (localpackage)
|
os.stat(locallatestpackage) print "Latest package already exists in %s" % (locallatestpackage)
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
print "Downloading package %s to %s" % (package, localpackage) wgetcmd = "wget -q -O %s %s" % (localpackage, package)
|
print "Downloading latest release package %s to %s" % (latestpackage, locallatestpackage) wgetcmd = "wget -q -O %s %s" % (locallatestpackage, latestpackage)
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
latestfiles = listfiles(localpackage)
|
latestfiles = listZipFiles(locallatestpackage)
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
print "\n--------------------------------------------------------------------------------\nVaadin TAR differences"
|
print "\n--------------------------------------------------------------------------------\nVaadin ZIP differences"
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
latestJarFiles = listTarVaadinJarFiles(localpackage, latestversion) builtJarFiles = listZipVaadinJarFiles(builtpackage, builtversion)
|
latestJarFiles = listZipVaadinJarFiles(locallatestpackage, latestversion) builtJarFiles = listZipVaadinJarFiles(builtpackage, builtversion)
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
command("rm %s" % (localpackage))
|
command("rm %s" % (locallatestpackage))
|
def listZipVaadinJarFiles(zipfile, vaadinversion): jarfile = "vaadin-%s/WebContent/vaadin-%s.jar" % (vaadinversion, vaadinversion) extractedjar = "/tmp/vaadinjar-tmp-%d.jar" % (os.getpid()) tarcmd = "unzip -p %s %s > %s " % (zipfile, jarfile, extractedjar) command (tarcmd) files = listJarFiles(extractedjar) command ("rm %s" % (extractedjar)) return files
|
"""Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other threads until the function returns, so if it intends to perform long calculations, it should start a new thread itself -- but NOT an ExitNotifyThread, or else an infinite loop may result. Furthermore, the monitor will hold the lock all the while the other thread is waiting.
|
"""An infinite "monitoring" loop watching for finished ExitNotifyThread's. :param callback: the function to call when a thread terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other threads until 'callback' returns, so if it intends to perform long calculations, it should start a new thread itself -- but NOT an ExitNotifyThread, or else an infinite loop may result. Furthermore, the monitor will hold the lock all the while the other thread is waiting. :type callback: a callable function
|
def exitnotifymonitorloop(callback): """Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other threads until the function returns, so if it intends to perform long calculations, it should start a new thread itself -- but NOT an ExitNotifyThread, or else an infinite loop may result. Furthermore, the monitor will hold the lock all the while the other thread is waiting. """ global exitthreads while 1: # Loop forever. try: thrd = exitthreads.get(False) callback(thrd) except Empty: time.sleep(1)
|
while 1: try: thrd = exitthreads.get(False)
|
while 1: try: thrd = exitthreads.get(True, 60)
|
def exitnotifymonitorloop(callback): """Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other threads until the function returns, so if it intends to perform long calculations, it should start a new thread itself -- but NOT an ExitNotifyThread, or else an infinite loop may result. Furthermore, the monitor will hold the lock all the while the other thread is waiting. """ global exitthreads while 1: # Loop forever. try: thrd = exitthreads.get(False) callback(thrd) except Empty: time.sleep(1)
|
time.sleep(1)
|
pass
|
def exitnotifymonitorloop(callback): """Enter an infinite "monitoring" loop. The argument, callback, defines the function to call when an ExitNotifyThread has terminated. That function is called with a single argument -- the ExitNotifyThread that has terminated. The monitor will not continue to monitor for other threads until the function returns, so if it intends to perform long calculations, it should start a new thread itself -- but NOT an ExitNotifyThread, or else an infinite loop may result. Furthermore, the monitor will hold the lock all the while the other thread is waiting. """ global exitthreads while 1: # Loop forever. try: thrd = exitthreads.get(False) callback(thrd) except Empty: time.sleep(1)
|
abortsleep = s.sleeping(1, sleepsecs) sleepsecs -= 1
|
abortsleep = s.sleeping(10, sleepsecs) sleepsecs -= 10
|
def sleep(s, sleepsecs, siglistener): """This function does not actually output anything, but handles the overall sleep, dealing with updates as necessary. It will, however, call sleeping() which DOES output something.
|
s._msg("Next refresh in %d seconds" % remainingsecs)
|
def sleeping(s, sleepsecs, remainingsecs): """Sleep for sleepsecs, remainingsecs to go. If sleepsecs is 0, indicates we're done sleeping.
|
|
def warn(s, msg, minor):
|
def warn(s, msg, minor = 0):
|
def warn(s, msg, minor): s._printData('warn', '%s\n%d' % (msg, int(minor)))
|
flagmap = {'\\seen': 'S', '\\answered': 'R', '\\flagged': 'F', '\\deleted': 'T', '\\draft': 'D'}
|
def flagsimap2maildir(flagstring): flagmap = {'\\seen': 'S', '\\answered': 'R', '\\flagged': 'F', '\\deleted': 'T', '\\draft': 'D'} retval = [] imapflaglist = [x.lower() for x in flagstring[1:-1].split()] for imapflag in imapflaglist: if flagmap.has_key(imapflag): retval.append(flagmap[imapflag]) retval.sort() return retval
|
|
for imapflag in imapflaglist: if flagmap.has_key(imapflag): retval.append(flagmap[imapflag])
|
for imapflag, maildirflag in flagmap: if imapflag.lower() in imapflaglist: retval.append(maildirflag)
|
def flagsimap2maildir(flagstring): flagmap = {'\\seen': 'S', '\\answered': 'R', '\\flagged': 'F', '\\deleted': 'T', '\\draft': 'D'} retval = [] imapflaglist = [x.lower() for x in flagstring[1:-1].split()] for imapflag in imapflaglist: if flagmap.has_key(imapflag): retval.append(flagmap[imapflag]) retval.sort() return retval
|
def flagsmaildir2imap(list): flagmap = {'S': '\\Seen', 'R': '\\Answered', 'F': '\\Flagged', 'T': '\\Deleted', 'D': '\\Draft'} retval = [] for mdflag in list: if flagmap.has_key(mdflag): retval.append(flagmap[mdflag])
|
def flagsmaildir2imap(maildirflaglist): retval = [] for imapflag, maildirflag in flagmap: if maildirflag in maildirflaglist: retval.append(imapflag)
|
def flagsmaildir2imap(list): flagmap = {'S': '\\Seen', 'R': '\\Answered', 'F': '\\Flagged', 'T': '\\Deleted', 'D': '\\Draft'} retval = [] for mdflag in list: if flagmap.has_key(mdflag): retval.append(flagmap[mdflag]) retval.sort() return '(' + ' '.join(retval) + ')'
|
import profile
|
try: import cProfile as profile except ImportError: import profile
|
def run(self): global exitthreads, profiledir self.threadid = thread.get_ident() try: if not profiledir: # normal case Thread.run(self) else: import profile prof = profile.Profile() try: prof = prof.runctx("Thread.run(self)", globals(), locals()) except SystemExit: pass prof.dump_stats( \ profiledir + "/" + str(self.threadid) + "_" + \ self.getName() + ".prof") except: self.setExitCause('EXCEPTION') if sys: self.setExitException(sys.exc_info()[1]) sbuf = StringIO() traceback.print_exc(file = sbuf) self.setExitStackTrace(sbuf.getvalue()) else: self.setExitCause('NORMAL') if not hasattr(self, 'exitmessage'): self.setExitMessage(None)
|
repo = setup['repo']
|
self.datastore = setup['repo']
|
def __call__(self, args): Bcfg2.Server.Admin.MetadataCore.__call__(self, args) # Get Bcfg2 repo directory opts = {'repo': Bcfg2.Options.SERVER_REPOSITORY} setup = Bcfg2.Options.OptionParser(opts) setup.parse(sys.argv[1:]) repo = setup['repo']
|
out = tarfile.open(filename, mode=mode) content = os.listdir(os.getcwd())
|
out = tarfile.open(self.datastore + '/' + filename, mode=mode) content = os.listdir(self.datastore)
|
def __call__(self, args): Bcfg2.Server.Admin.MetadataCore.__call__(self, args) # Get Bcfg2 repo directory opts = {'repo': Bcfg2.Options.SERVER_REPOSITORY} setup = Bcfg2.Options.OptionParser(opts) setup.parse(sys.argv[1:]) repo = setup['repo']
|
print "Archive %s was stored.\nLocation: %s" % (filename, datastore)
|
print "Archive %s was stored.\nLocation: %s" % (filename, self.datastore)
|
def __call__(self, args): Bcfg2.Server.Admin.MetadataCore.__call__(self, args) # Get Bcfg2 repo directory opts = {'repo': Bcfg2.Options.SERVER_REPOSITORY} setup = Bcfg2.Options.OptionParser(opts) setup.parse(sys.argv[1:]) repo = setup['repo']
|
data = raw_input("What is the server's hostname: [%s]" % socket.getfqdn())
|
data = raw_input("What is the server's hostname: [%s]: " % socket.getfqdn())
|
def _prompt_hostname(self): """Ask for the server hostname.""" data = raw_input("What is the server's hostname: [%s]" % socket.getfqdn()) if data != '': self.shostname = data else: self.shostname = socket.getfqdn()
|
os.makedirs(path) self._init_plugins() print "Repository created successfuly in %s" % (self.repopath)
|
try: os.makedirs(path) self._init_plugins() print "Repository created successfuly in %s" % (self.repopath) except OSError: print("Failed to create %s." % path)
|
def init_repo(self): """Setup a new repo and create the content of the configuration file.""" keypath = os.path.dirname(os.path.abspath(self.configfile)) confdata = config % ( self.repopath, ','.join(self.opts['plugins']), self.opts['sendmail'], self.opts['proto'], self.password, keypath, 'bcfg2.crt', keypath, 'bcfg2.key', keypath, 'bcfg2.crt', self.server_uri )
|
data = raw_input("What is the server's hostname: [%s]: " % socket.getfqdn())
|
data = raw_input("What is the server's hostname [%s]: " % socket.getfqdn())
|
def _prompt_hostname(self): """Ask for the server hostname.""" data = raw_input("What is the server's hostname: [%s]: " % socket.getfqdn()) if data != '': self.shostname = data else: self.shostname = socket.getfqdn()
|
if resolved == client:
|
if resolved.lower() == client.lower():
|
def validate_client_address(self, client, addresspair): '''Check address against client''' address = addresspair[0] if client in self.floating: self.debug_log("Client %s is floating" % client) return True if address in self.addresses: if client in self.addresses[address]: self.debug_log("Client %s matches address %s" % (client, address)) return True else: self.logger.error("Got request for non-float client %s from %s" \ % (client, address)) return False resolved = self.resolve_client(addresspair) if resolved == client: return True else: self.logger.error("Got request for %s from incorrect address %s" \ % (client, address)) self.logger.error("Resolved to %s" % resolved) return False
|
try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False
|
def VerifyService(self, entry, _): ''' Verify Service status for entry. Assumes we run in the "default" runlevel. ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False # check is service is enabled cmd = '/etc/init.d/%s status | grep started' rc = self.cmd.run(cmd % entry.get('name'))[0] is_enabled = (rc == 0)
|
|
cmd = '/etc/init.d/%s status | grep started'
|
cmd = '/sbin/rc-update show default | grep %s'
|
def VerifyService(self, entry, _): ''' Verify Service status for entry. Assumes we run in the "default" runlevel. ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False # check is service is enabled cmd = '/etc/init.d/%s status | grep started' rc = self.cmd.run(cmd % entry.get('name'))[0] is_enabled = (rc == 0)
|
cmd = '/bin/rc-status -s | grep %s | grep started'
|
cmd = '/etc/init.d/%s status | grep started'
|
def VerifyService(self, entry, _): ''' Verify Service status for entry. Assumes we run in the "default" runlevel. ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug("Init script for service %s does not exist" % entry.get('name')) return False # check is service is enabled cmd = '/etc/init.d/%s status | grep started' rc = self.cmd.run(cmd % entry.get('name'))[0] is_enabled = (rc == 0)
|
self.logger.info("Installing Service %s" % entry.get('name'))
|
self.logger.info('Installing Service %s' % entry.get('name'))
|
def InstallService(self, entry): ''' Install Service entry In supervised mode we also take care it's (not) running ''' # check if init script exists try: os.stat('/etc/init.d/%s' % entry.get('name')) except OSError: self.logger.debug('Init script for service %s does not exist' % entry.get('name')) return False
|
self.__important__ = [e.get('name') for struct in config for entry in struct \
|
self.__important__ = [entry.get('name') for struct in config for entry in struct \
|
def __init__(self, logger, setup, config): Bcfg2.Client.Tools.RPMng.RPMng.__init__(self, logger, setup, config) self.__important__ = [e.get('name') for struct in config for entry in struct \ if entry.tag in ['Path', 'ConfigFile'] and \ e.get('name').startswith('/etc/yum.d') or e.get('name') == '/etc/yum.conf'] self.yum_avail = dict() self.yum_installed = dict() self.yb = yum.YumBase() self.yb.doConfigSetup() self.yb.doTsSetup() self.yb.doRpmDBSetup() yup = self.yb.doPackageLists(pkgnarrow='updates') if hasattr(self.yb.rpmdb, 'pkglist'): yinst = self.yb.rpmdb.pkglist else: yinst = self.yb.rpmdb.getPkgList() for dest, source in [(self.yum_avail, yup.updates), (self.yum_installed, yinst)]: for pkg in source: if dest is self.yum_avail: pname = pkg.name data = [(pkg.arch, (pkg.epoch, pkg.version, pkg.release))] else: pname = pkg[0] data = [(pkg[1], (pkg[2], pkg[3], pkg[4]))] if pname in dest: dest[pname].update(data) else: dest[pname] = dict(data)
|
e.get('name').startswith('/etc/yum.d') or e.get('name') == '/etc/yum.conf']
|
entry.get('name').startswith('/etc/yum.d') or entry.get('name') == '/etc/yum.conf']
|
def __init__(self, logger, setup, config): Bcfg2.Client.Tools.RPMng.RPMng.__init__(self, logger, setup, config) self.__important__ = [e.get('name') for struct in config for entry in struct \ if entry.tag in ['Path', 'ConfigFile'] and \ e.get('name').startswith('/etc/yum.d') or e.get('name') == '/etc/yum.conf'] self.yum_avail = dict() self.yum_installed = dict() self.yb = yum.YumBase() self.yb.doConfigSetup() self.yb.doTsSetup() self.yb.doRpmDBSetup() yup = self.yb.doPackageLists(pkgnarrow='updates') if hasattr(self.yb.rpmdb, 'pkglist'): yinst = self.yb.rpmdb.pkglist else: yinst = self.yb.rpmdb.getPkgList() for dest, source in [(self.yum_avail, yup.updates), (self.yum_installed, yinst)]: for pkg in source: if dest is self.yum_avail: pname = pkg.name data = [(pkg.arch, (pkg.epoch, pkg.version, pkg.release))] else: pname = pkg[0] data = [(pkg[1], (pkg[2], pkg[3], pkg[4]))] if pname in dest: dest[pname].update(data) else: dest[pname] = dict(data)
|
status = (len(onlevels) > 0 )
|
status = (len(onlevels) > 0) command = 'start'
|
def VerifyService(self, entry, _): '''Verify Service status for entry''' try: cmd = "/sbin/chkconfig --list %s " % (entry.get('name')) raw = self.cmd.run(cmd)[1] patterns = ["error reading information", "unknown service"] srvdata = [line.split() for line in raw for pattern in patterns \ if pattern not in line][0] except IndexError: # Ocurrs when no lines are returned (service not installed) entry.set('current_status', 'off') return False if len(srvdata) == 2: # This is an xinetd service if entry.get('status') == srvdata[1]: return True else: entry.set('current_status', srvdata[1]) return False
|
pstatus, pout = self.cmd.run('/sbin/service %s status' % \ entry.get('name')) if pstatus: self.cmd.run('/sbin/service %s start' % (entry.get('name'))) pstatus, pout = self.cmd.run('/sbin/service %s status' % \ entry.get('name'))
|
pstatus = self.cmd.run('/sbin/service %s status' % \ entry.get('name'))[0] needs_modification = ((command == 'start' and pstatus) or \ (command == 'stop' and not pstatus)) if not(self.setup.get('dryrun')) and needs_modification: self.cmd.run('/sbin/service %s %s' % (entry.get('name'), command)) pstatus = self.cmd.run('/sbin/service %s status' % \ entry.get('name'))[0]
|
def VerifyService(self, entry, _): '''Verify Service status for entry''' try: cmd = "/sbin/chkconfig --list %s " % (entry.get('name')) raw = self.cmd.run(cmd)[1] patterns = ["error reading information", "unknown service"] srvdata = [line.split() for line in raw for pattern in patterns \ if pattern not in line][0] except IndexError: # Ocurrs when no lines are returned (service not installed) entry.set('current_status', 'off') return False if len(srvdata) == 2: # This is an xinetd service if entry.get('status') == srvdata[1]: return True else: entry.set('current_status', srvdata[1]) return False
|
files.append(item.split()[5])
|
if item.split()[5] not in self.nonexistent: files.append(item.split()[5])
|
def VerifyDebsums(self, entry, modlist): output = self.cmd.run("%s -as %s" % (DEBSUMS, entry.get('name')))[1] if len(output) == 1 and "no md5sums for" in output[0]: self.logger.info("Package %s has no md5sums. Cannot verify" % \ entry.get('name')) entry.set('qtext', "Reinstall Package %s-%s to setup md5sums? (y/N) " \ % (entry.get('name'), entry.get('version'))) return False files = [] for item in output: if "checksum mismatch" in item: files.append(item.split()[-1]) elif "changed file" in item: files.append(item.split()[3]) elif "can't open" in item: files.append(item.split()[5]) elif "missing file" in item and \ item.split()[3] in self.nonexistent: # these files should not exist continue elif "is not installed" in item or "missing file" in item: self.logger.error("Package %s is not fully installed" \ % entry.get('name')) else: self.logger.error("Got Unsupported pattern %s from debsums" \ % item) files.append(item) # We check if there is file in the checksum to do if files: # if files are found there we try to be sure our modlist is sane # with erroneous symlinks modlist = [os.path.realpath(filename) for filename in modlist] bad = [filename for filename in files if filename not in modlist] if bad: self.logger.info("Package %s failed validation. Bad files are:" % \ entry.get('name')) self.logger.info(bad) entry.set('qtext', "Reinstall Package %s-%s to fix failing files? (y/N) " % \ (entry.get('name'), entry.get('version'))) return False return True
|
start_sequence = int(entry.get('sequence')) kill_sequence = 100 - start_sequence
|
if (deb_version in DEBIAN_OLD_STYLE_BOOT_SEQUENCE): start_sequence = int(entry.get('sequence')) kill_sequence = 100 - start_sequence else: self.logger.warning("Your debian version boot sequence is dependency based \"sequence\" attribute wil be ignored.")
|
def VerifyService(self, entry, _): """Verify Service status for entry.""" rawfiles = glob.glob("/etc/rc*.d/[SK]*%s" % (entry.get('name'))) files = [] if entry.get('sequence'): start_sequence = int(entry.get('sequence')) kill_sequence = 100 - start_sequence else: start_sequence = None
|
source.setup_data(force_update)
|
if not self.disableMetaData: source.setup_data(force_update)
|
def _load_config(self, force_update=False): ''' Load the configuration data and setup sources
|
pass
|
deps = set()
|
def resolve_requirement(self, metadata, requirement, packages, debug=False): '''Resolve requirement to packages and or additional requirements
|
node.append(newstat)
|
node.append(copy.deepcopy(newstat))
|
def updateStats(self, xml, client): '''Updates the statistics of a current node with new data'''
|
fpath = "%s/etc/statistics.xml" % datastore self.data_file = StatisticsStore(fpath)
|
self.fpath = "%s/etc/statistics.xml" % datastore self.terminate = core.terminate self.work_queue = Queue.Queue() self.worker = threading.Thread(target=self.process_statistics_loop) self.worker.start() def process_statistics_loop(self): self.data_file = StatisticsStore(self.fpath) while not (self.terminate.isSet() and self.work_queue.empty()): try: (xdata, hostname) = self.work_queue.get(block=True, timeout=5) except: continue self.data_file.updateStats(xdata, hostname)
|
def __init__(self, core, datastore): Bcfg2.Server.Plugin.Plugin.__init__(self, core, datastore) Bcfg2.Server.Plugin.Statistics.__init__(self) Bcfg2.Server.Plugin.PullSource.__init__(self) fpath = "%s/etc/statistics.xml" % datastore self.data_file = StatisticsStore(fpath)
|
self.data_file.updateStats(copy.deepcopy(xdata), client.hostname)
|
self.work_queue.put((copy.deepcopy(xdata), client.hostname))
|
def process_statistics(self, client, xdata): self.data_file.updateStats(copy.deepcopy(xdata), client.hostname)
|
chksum = md5.new()
|
if py24compat: chksum = md5.new() else: chksum = hashlib.md5()
|
def prelink_md5_check(filename): """ Checks if a file is prelinked. If it is run it through prelink -y to get the unprelinked md5 and file size. Return 0 if the file was not prelinked, otherwise return the file size. Always return the md5. """ prelink = False try: plf = open(filename, "rb") except IOError: return False, 0 if prelink_exists: if isprelink_imported: plfd = plf.fileno() if isprelink(plfd): plf.close() cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \ % (re.escape(filename)) plf = os.popen(cmd, 'rb') prelink = True elif whitelist_re.search(filename) and not blacklist_re.search(filename): plf.close() cmd = '/usr/sbin/prelink -y %s 2> /dev/null' \ % (re.escape(filename)) plf = os.popen(cmd, 'rb') prelink = True fsize = 0 chksum = md5.new() while 1: data = plf.read() if not data: break fsize += len(data) chksum.update(data) plf.close() file_md5 = chksum.hexdigest() if prelink: return file_md5, fsize else: return file_md5, 0
|
if source.is_pkg(meta, current):
|
if source.is_package(meta, current):
|
def complete(self, meta, input_requirements, debug=False): '''Build the transitive closure of all package dependencies
|
if xsource.find('Recommended').text == 'true':
|
if xsource.find('Recommended').text in ['True', 'true']:
|
def source_from_xml(xsource): ret = dict([('rawurl', False), ('url', False)]) for key, tag in [('groups', 'Group'), ('components', 'Component'), ('arches', 'Arch'), ('blacklist', 'Blacklist')]: ret[key] = [item.text for item in xsource.findall(tag)] # version and component need to both contain data for sources to work try: ret['version'] = xsource.find('Version').text except: ret['version'] = 'placeholder' if ret['components'] == []: ret['components'] = ['placeholder'] try: if xsource.find('Recommended').text == 'true': ret['recommended'] = True except: ret['recommended'] = False if xsource.find('RawURL') is not None: ret['rawurl'] = xsource.find('RawURL').text if not ret['rawurl'].endswith('/'): ret['rawurl'] += '/' else: ret['url'] = xsource.find('URL').text if not ret['url'].endswith('/'): ret['url'] += '/' return ret
|
cmd = "git archive --format=tar --prefix=%s-%s v%s | gzip > %s" % \
|
cmd = "git archive --format=tar --prefix=%s-%s/ v%s | gzip > %s" % \
|
def run(command): return Popen(command, shell=True, stdout=PIPE).communicate()
|
('arches', 'Arch'), ('blacklist', 'Blacklist')]:
|
('arches', 'Arch'), ('blacklist', 'Blacklist'), ('whitelist', 'Whitelist')]:
|
def source_from_xml(xsource): ret = dict([('rawurl', False), ('url', False)]) for key, tag in [('groups', 'Group'), ('components', 'Component'), ('arches', 'Arch'), ('blacklist', 'Blacklist')]: ret[key] = [item.text for item in xsource.findall(tag)] # version and component need to both contain data for sources to work try: ret['version'] = xsource.find('Version').text except: ret['version'] = 'placeholder' if ret['components'] == []: ret['components'] = ['placeholder'] try: if xsource.find('Recommended').text in ['True', 'true']: ret['recommended'] = True else: ret['recommended'] = False except: ret['recommended'] = False if xsource.find('RawURL') is not None: ret['rawurl'] = xsource.find('RawURL').text if not ret['rawurl'].endswith('/'): ret['rawurl'] += '/' else: ret['url'] = xsource.find('URL').text if not ret['url'].endswith('/'): ret['url'] += '/' return ret
|
blacklist, recommended):
|
blacklist, whitelist, recommended):
|
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): self.basepath = basepath self.version = version self.components = components self.url = url self.rawurl = rawurl self.groups = groups self.arches = arches self.deps = dict() self.provides = dict() self.blacklist = set(blacklist) self.cachefile = None self.recommended = recommended
|
if requirement in self.blacklist:
|
if requirement in self.blacklist or \ (len(self.whitelist) > 0 and requirement not in self.whitelist):
|
def resolve_requirement(self, metadata, requirement, packages, debug=False): '''Resolve requirement to packages and or additional requirements
|
rawurl, blacklist, recommended):
|
rawurl, blacklist, whitelist, recommended):
|
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.baseurl = self.url + '%(version)s/%(component)s/%(arch)s/' else: self.baseurl = self.rawurl self.cachefile = self.escape_url(self.baseurl + '@' + version) + '.data' self.packages = dict() self.deps = dict([('global', dict())]) self.provides = dict([('global', dict())]) self.filemap = dict([(x, dict()) for x in ['global'] + self.arches]) self.needed_paths = set() self.file_to_arch = dict()
|
groups, rawurl, blacklist, recommended)
|
groups, rawurl, blacklist, whitelist, recommended)
|
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.baseurl = self.url + '%(version)s/%(component)s/%(arch)s/' else: self.baseurl = self.rawurl self.cachefile = self.escape_url(self.baseurl + '@' + version) + '.data' self.packages = dict() self.deps = dict([('global', dict())]) self.provides = dict([('global', dict())]) self.filemap = dict([(x, dict()) for x in ['global'] + self.arches]) self.needed_paths = set() self.file_to_arch = dict()
|
rawurl, blacklist, recommended):
|
rawurl, blacklist, whitelist, recommended):
|
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.cachefile = self.escape_url(self.url + '@' + self.version) + '.data' else: self.cachefile = self.escape_url(self.rawurl) + '.data' self.pkgnames = set()
|
rawurl, blacklist, recommended)
|
rawurl, blacklist, whitelist, recommended)
|
def __init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended): Source.__init__(self, basepath, url, version, arches, components, groups, rawurl, blacklist, recommended) if not self.rawurl: self.cachefile = self.escape_url(self.url + '@' + self.version) + '.data' else: self.cachefile = self.escape_url(self.rawurl) + '.data' self.pkgnames = set()
|
path = context['request'].path
|
path = context['request'].META['PATH_INFO']
|
def page_navigator(context): """ Creates paginated links. Expects the context to be a RequestContext and views.prepare_paginated_list() to have populated page information. """ fragment = dict() try: path = context['request'].path total_pages = int(context['total_pages']) records_per_page = int(context['records_per_page']) except KeyError, e: return fragment except ValueError, e: return fragment if total_pages < 2: return {} try: view, args, kwargs = resolve(path) current_page = int(kwargs.get('page_number',1)) fragment['current_page'] = current_page fragment['page_number'] = current_page fragment['total_pages'] = total_pages fragment['records_per_page'] = records_per_page if current_page > 1: kwargs['page_number'] = current_page - 1 fragment['prev_page'] = reverse(view, args=args, kwargs=kwargs) if current_page < total_pages: kwargs['page_number'] = current_page + 1 fragment['next_page'] = reverse(view, args=args, kwargs=kwargs) view_range = 5 if total_pages > view_range: pager_start = current_page - 2 pager_end = current_page + 2 if pager_start < 1: pager_end += (1 - pager_start) pager_start = 1 if pager_end > total_pages: pager_start -= (pager_end - total_pages) pager_end = total_pages else: pager_start = 1 pager_end = total_pages if pager_start > 1: kwargs['page_number'] = 1 fragment['first_page'] = reverse(view, args=args, kwargs=kwargs) if pager_end < total_pages: kwargs['page_number'] = total_pages fragment['last_page'] = reverse(view, args=args, kwargs=kwargs) pager = [] for page in range(pager_start, int(pager_end) + 1): kwargs['page_number'] = page pager.append( (page, reverse(view, args=args, kwargs=kwargs)) ) kwargs['page_number'] = 1 page_limits = [] for limit in __PAGE_NAV_LIMITS__: kwargs['page_limit'] = limit page_limits.append( (limit, reverse(view, args=args, kwargs=kwargs)) ) # resolver doesn't like this del kwargs['page_number'] del kwargs['page_limit'] page_limits.append( ('all', reverse(view, args=args, kwargs=kwargs) + "|all") ) fragment['pager'] = pager fragment['page_limits'] = page_limits except Resolver404: path = "404" except NoReverseMatch, nr: path = "NoReverseMatch: %s" % nr except ValueError: path = "ValueError" #FIXME - Handle these fragment['path'] = path return fragment
|
path = context['request'].path
|
path = context['request'].META['PATH_INFO']
|
def filter_navigator(context): try: path = context['request'].path view, args, kwargs = resolve(path) # Strip any page limits and numbers if 'page_number' in kwargs: del kwargs['page_number'] if 'page_limit' in kwargs: del kwargs['page_limit'] filters = [] for filter in filter_list: if filter in kwargs: myargs = kwargs.copy() del myargs[filter] filters.append( (filter, reverse(view, args=args, kwargs=myargs) ) ) filters.sort(lambda x,y: cmp(x[0], y[0])) return { 'filters': filters } except (Resolver404, NoReverseMatch, ValueError, KeyError): pass return dict()
|
path = context['request'].path
|
path = context['request'].META['PATH_INFO']
|
def render(self, context): link = '#' try: path = context['request'].path view, args, kwargs = resolve(path) filter_value = self.filter_value.resolve(context, True) if filter_value: filter_name = smart_str(self.filter_name) filter_value = smart_unicode(filter_value) kwargs[filter_name] = filter_value # These two don't make sense if filter_name == 'server' and 'hostname' in kwargs: del kwargs['hostname'] elif filter_name == 'hostname' and 'server' in kwargs: del kwargs['server'] try: link = reverse(view, args=args, kwargs=kwargs) except NoReverseMatch, rm: link = reverse(self.fallback_view, args=None, kwargs={ filter_name: filter_value }) except NoReverseMatch, rm: raise rm except (Resolver404, ValueError), e: pass return link
|
if res == cert + ": OK\n"
|
if res == cert + ": OK\n":
|
def verify_cert(self, filename, entry): """ check that a certificate validates against the ca cert, and that it has not expired. """ chaincert = self.CAs[self.cert_specs[entry.get('name')]['ca']].get('chaincert') cert = self.data + filename cmd = "openssl verify -CAfile %s %s" % (chaincert, cert) res = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT).stdout.read() if res == cert + ": OK\n" return True return False
|
for alias in metadata.aliases: cp.set('alt_names', 'DNS.'+str(x), alias)
|
altnames = list(metadata.aliases) altnames.append(metadata.hostname) for altname in altnames: cp.set('alt_names', 'DNS.'+str(x), altname)
|
def build_req_config(self, entry, metadata): """ generates a temporary openssl configuration file that is used to generate the required certificate request """ # create temp request config file conffile = open(tempfile.mkstemp()[1], 'w') cp = ConfigParser({}) cp.optionxform = str defaults = { 'req': { 'default_md': 'sha1', 'distinguished_name': 'req_distinguished_name', 'req_extensions': 'v3_req', 'x509_extensions': 'v3_req', 'prompt': 'no' }, 'req_distinguished_name': {}, 'v3_req': { 'subjectAltName': '@alt_names' }, 'alt_names': {} } for section in defaults.keys(): cp.add_section(section) for key in defaults[section]: cp.set(section, key, defaults[section][key]) x = 1 for alias in metadata.aliases: cp.set('alt_names', 'DNS.'+str(x), alias) x += 1 for item in ['C', 'L', 'ST', 'O', 'OU', 'emailAddress']: if self.cert_specs[entry.get('name')][item]: cp.set('req_distinguished_name', item, self.cert_specs[entry.get('name')][item]) cp.set('req_distinguished_name', 'CN', metadata.hostname) cp.write(conffile) conffile.close() return conffile.name
|
except Exception as e:
|
except Exception, e:
|
def Install(self, packages, states): ''' Pacman Install ''' pkgline = "" for pkg in packages: pkgline += " " + pkg.get('name')
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.