How to use Block method in storybook-root

Best JavaScript code snippet using storybook-root

lobpcg.py

Source:lobpcg.py Github

copy

Full Screen

1"""2Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG).3References4----------5.. [1] A. V. Knyazev (2001),6 Toward the Optimal Preconditioned Eigensolver: Locally Optimal7 Block Preconditioned Conjugate Gradient Method.8 SIAM Journal on Scientific Computing 23, no. 2,9 pp. 517-541. http://dx.doi.org/10.1137/S106482750036612410.. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov (2007),11 Block Locally Optimal Preconditioned Eigenvalue Xolvers (BLOPEX)12 in hypre and PETSc. https://arxiv.org/abs/0705.262613.. [3] A. V. Knyazev's C and MATLAB implementations:14 https://github.com/lobpcg/blopex15"""16from __future__ import division, print_function, absolute_import17import numpy as np18from scipy.linalg import (inv, eigh, cho_factor, cho_solve, cholesky, orth,19 LinAlgError)20from scipy.sparse.linalg import aslinearoperator21from scipy.sparse.sputils import bmat22__all__ = ['lobpcg']23def _report_nonhermitian(M, name):24 """25 Report if `M` is not a hermitian matrix given its type.26 """27 from scipy.linalg import norm28 md = M - M.T.conj()29 nmd = norm(md, 1)30 tol = 10 * np.finfo(M.dtype).eps31 tol = max(tol, tol * norm(M, 1))32 if nmd > tol:33 print('matrix %s of the type %s is not sufficiently Hermitian:'34 % (name, M.dtype))35 print('condition: %.e < %e' % (nmd, tol))36def _as2d(ar):37 """38 If the input array is 2D return it, if it is 1D, append a dimension,39 making it a column vector.40 """41 if ar.ndim == 2:42 return ar43 else: # Assume 1!44 aux = np.array(ar, copy=False)45 aux.shape = (ar.shape[0], 1)46 return aux47def _makeOperator(operatorInput, expectedShape):48 """Takes a dense numpy array or a sparse matrix or49 a function and makes an operator performing matrix * blockvector50 products."""51 if operatorInput is None:52 return None53 else:54 operator = aslinearoperator(operatorInput)55 if operator.shape != expectedShape:56 raise ValueError('operator has invalid shape')57 return operator58def _applyConstraints(blockVectorV, factYBY, blockVectorBY, blockVectorY):59 """Changes blockVectorV in place."""60 YBV = np.dot(blockVectorBY.T.conj(), blockVectorV)61 tmp = cho_solve(factYBY, YBV)62 blockVectorV -= np.dot(blockVectorY, tmp)63def _b_orthonormalize(B, blockVectorV, blockVectorBV=None, retInvR=False):64 """B-orthonormalize the given block vector using Cholesky."""65 normalization = blockVectorV.max(axis=0)+np.finfo(blockVectorV.dtype).eps66 blockVectorV = blockVectorV / normalization67 if blockVectorBV is None:68 if B is not None:69 blockVectorBV = B(blockVectorV)70 else:71 blockVectorBV = blockVectorV # Shared data!!!72 else:73 blockVectorBV = blockVectorBV / normalization74 VBV = np.matmul(blockVectorV.T.conj(), blockVectorBV)75 try:76 # VBV is a Cholesky factor from now on...77 VBV = cholesky(VBV, overwrite_a=True)78 VBV = inv(VBV, overwrite_a=True)79 blockVectorV = np.matmul(blockVectorV, VBV)80 # blockVectorV = (cho_solve((VBV.T, True), blockVectorV.T)).T81 if B is not None:82 blockVectorBV = np.matmul(blockVectorBV, VBV)83 # blockVectorBV = (cho_solve((VBV.T, True), blockVectorBV.T)).T84 else:85 blockVectorBV = None86 except LinAlgError:87 #raise ValueError('Cholesky has failed')88 blockVectorV = None89 blockVectorBV = None90 VBV = None91 if retInvR:92 return blockVectorV, blockVectorBV, VBV, normalization93 else:94 return blockVectorV, blockVectorBV95def _get_indx(_lambda, num, largest):96 """Get `num` indices into `_lambda` depending on `largest` option."""97 ii = np.argsort(_lambda)98 if largest:99 ii = ii[:-num-1:-1]100 else:101 ii = ii[:num]102 return ii103def lobpcg(A, X,104 B=None, M=None, Y=None,105 tol=None, maxiter=None,106 largest=True, verbosityLevel=0,107 retLambdaHistory=False, retResidualNormsHistory=False):108 """Locally Optimal Block Preconditioned Conjugate Gradient Method (LOBPCG)109 LOBPCG is a preconditioned eigensolver for large symmetric positive110 definite (SPD) generalized eigenproblems.111 Parameters112 ----------113 A : {sparse matrix, dense matrix, LinearOperator}114 The symmetric linear operator of the problem, usually a115 sparse matrix. Often called the "stiffness matrix".116 X : ndarray, float32 or float64117 Initial approximation to the ``k`` eigenvectors (non-sparse). If `A`118 has ``shape=(n,n)`` then `X` should have shape ``shape=(n,k)``.119 B : {dense matrix, sparse matrix, LinearOperator}, optional120 The right hand side operator in a generalized eigenproblem.121 By default, ``B = Identity``. Often called the "mass matrix".122 M : {dense matrix, sparse matrix, LinearOperator}, optional123 Preconditioner to `A`; by default ``M = Identity``.124 `M` should approximate the inverse of `A`.125 Y : ndarray, float32 or float64, optional126 n-by-sizeY matrix of constraints (non-sparse), sizeY < n127 The iterations will be performed in the B-orthogonal complement128 of the column-space of Y. Y must be full rank.129 tol : scalar, optional130 Solver tolerance (stopping criterion).131 The default is ``tol=n*sqrt(eps)``.132 maxiter : int, optional133 Maximum number of iterations. The default is ``maxiter = 20``.134 largest : bool, optional135 When True, solve for the largest eigenvalues, otherwise the smallest.136 verbosityLevel : int, optional137 Controls solver output. The default is ``verbosityLevel=0``.138 retLambdaHistory : bool, optional139 Whether to return eigenvalue history. Default is False.140 retResidualNormsHistory : bool, optional141 Whether to return history of residual norms. Default is False.142 Returns143 -------144 w : ndarray145 Array of ``k`` eigenvalues146 v : ndarray147 An array of ``k`` eigenvectors. `v` has the same shape as `X`.148 lambdas : list of ndarray, optional149 The eigenvalue history, if `retLambdaHistory` is True.150 rnorms : list of ndarray, optional151 The history of residual norms, if `retResidualNormsHistory` is True.152 Notes153 -----154 If both ``retLambdaHistory`` and ``retResidualNormsHistory`` are True,155 the return tuple has the following format156 ``(lambda, V, lambda history, residual norms history)``.157 In the following ``n`` denotes the matrix size and ``m`` the number158 of required eigenvalues (smallest or largest).159 The LOBPCG code internally solves eigenproblems of the size ``3m`` on every160 iteration by calling the "standard" dense eigensolver, so if ``m`` is not161 small enough compared to ``n``, it does not make sense to call the LOBPCG162 code, but rather one should use the "standard" eigensolver, e.g. numpy or163 scipy function in this case.164 If one calls the LOBPCG algorithm for ``5m > n``, it will most likely break165 internally, so the code tries to call the standard function instead.166 It is not that ``n`` should be large for the LOBPCG to work, but rather the167 ratio ``n / m`` should be large. It you call LOBPCG with ``m=1``168 and ``n=10``, it works though ``n`` is small. The method is intended169 for extremely large ``n / m``, see e.g., reference [28] in170 https://arxiv.org/abs/0705.2626171 The convergence speed depends basically on two factors:172 1. How well relatively separated the seeking eigenvalues are from the rest173 of the eigenvalues. One can try to vary ``m`` to make this better.174 2. How well conditioned the problem is. This can be changed by using proper175 preconditioning. For example, a rod vibration test problem (under tests176 directory) is ill-conditioned for large ``n``, so convergence will be177 slow, unless efficient preconditioning is used. For this specific178 problem, a good simple preconditioner function would be a linear solve179 for `A`, which is easy to code since A is tridiagonal.180 References181 ----------182 .. [1] A. V. Knyazev (2001),183 Toward the Optimal Preconditioned Eigensolver: Locally Optimal184 Block Preconditioned Conjugate Gradient Method.185 SIAM Journal on Scientific Computing 23, no. 2,186 pp. 517-541. http://dx.doi.org/10.1137/S1064827500366124187 .. [2] A. V. Knyazev, I. Lashuk, M. E. Argentati, and E. Ovchinnikov188 (2007), Block Locally Optimal Preconditioned Eigenvalue Xolvers189 (BLOPEX) in hypre and PETSc. https://arxiv.org/abs/0705.2626190 .. [3] A. V. Knyazev's C and MATLAB implementations:191 https://bitbucket.org/joseroman/blopex192 Examples193 --------194 Solve ``A x = lambda x`` with constraints and preconditioning.195 >>> import numpy as np196 >>> from scipy.sparse import spdiags, issparse197 >>> from scipy.sparse.linalg import lobpcg, LinearOperator198 >>> n = 100199 >>> vals = np.arange(1, n + 1)200 >>> A = spdiags(vals, 0, n, n)201 >>> A.toarray()202 array([[ 1., 0., 0., ..., 0., 0., 0.],203 [ 0., 2., 0., ..., 0., 0., 0.],204 [ 0., 0., 3., ..., 0., 0., 0.],205 ...,206 [ 0., 0., 0., ..., 98., 0., 0.],207 [ 0., 0., 0., ..., 0., 99., 0.],208 [ 0., 0., 0., ..., 0., 0., 100.]])209 Constraints:210 >>> Y = np.eye(n, 3)211 Initial guess for eigenvectors, should have linearly independent212 columns. Column dimension = number of requested eigenvalues.213 >>> X = np.random.rand(n, 3)214 Preconditioner in the inverse of A in this example:215 >>> invA = spdiags([1./vals], 0, n, n)216 The preconditiner must be defined by a function:217 >>> def precond( x ):218 ... return invA @ x219 The argument x of the preconditioner function is a matrix inside `lobpcg`,220 thus the use of matrix-matrix product ``@``.221 The preconditioner function is passed to lobpcg as a `LinearOperator`:222 >>> M = LinearOperator(matvec=precond, matmat=precond,223 ... shape=(n, n), dtype=float)224 Let us now solve the eigenvalue problem for the matrix A:225 >>> eigenvalues, _ = lobpcg(A, X, Y=Y, M=M, largest=False)226 >>> eigenvalues227 array([4., 5., 6.])228 Note that the vectors passed in Y are the eigenvectors of the 3 smallest229 eigenvalues. The results returned are orthogonal to those.230 """231 blockVectorX = X232 blockVectorY = Y233 residualTolerance = tol234 if maxiter is None:235 maxiter = 20236 if blockVectorY is not None:237 sizeY = blockVectorY.shape[1]238 else:239 sizeY = 0240 # Block size.241 if len(blockVectorX.shape) != 2:242 raise ValueError('expected rank-2 array for argument X')243 n, sizeX = blockVectorX.shape244 if verbosityLevel:245 aux = "Solving "246 if B is None:247 aux += "standard"248 else:249 aux += "generalized"250 aux += " eigenvalue problem with"251 if M is None:252 aux += "out"253 aux += " preconditioning\n\n"254 aux += "matrix size %d\n" % n255 aux += "block size %d\n\n" % sizeX256 if blockVectorY is None:257 aux += "No constraints\n\n"258 else:259 if sizeY > 1:260 aux += "%d constraints\n\n" % sizeY261 else:262 aux += "%d constraint\n\n" % sizeY263 print(aux)264 A = _makeOperator(A, (n, n))265 B = _makeOperator(B, (n, n))266 M = _makeOperator(M, (n, n))267 if (n - sizeY) < (5 * sizeX):268 # warn('The problem size is small compared to the block size.' \269 # ' Using dense eigensolver instead of LOBPCG.')270 sizeX = min(sizeX, n)271 if blockVectorY is not None:272 raise NotImplementedError('The dense eigensolver '273 'does not support constraints.')274 # Define the closed range of indices of eigenvalues to return.275 if largest:276 eigvals = (n - sizeX, n-1)277 else:278 eigvals = (0, sizeX-1)279 A_dense = A(np.eye(n, dtype=A.dtype))280 B_dense = None if B is None else B(np.eye(n, dtype=B.dtype))281 vals, vecs = eigh(A_dense, B_dense, eigvals=eigvals,282 check_finite=False)283 if largest:284 # Reverse order to be compatible with eigs() in 'LM' mode.285 vals = vals[::-1]286 vecs = vecs[:, ::-1]287 return vals, vecs288 if (residualTolerance is None) or (residualTolerance <= 0.0):289 residualTolerance = np.sqrt(1e-15) * n290 # Apply constraints to X.291 if blockVectorY is not None:292 if B is not None:293 blockVectorBY = B(blockVectorY)294 else:295 blockVectorBY = blockVectorY296 # gramYBY is a dense array.297 gramYBY = np.dot(blockVectorY.T.conj(), blockVectorBY)298 try:299 # gramYBY is a Cholesky factor from now on...300 gramYBY = cho_factor(gramYBY)301 except LinAlgError:302 raise ValueError('cannot handle linearly dependent constraints')303 _applyConstraints(blockVectorX, gramYBY, blockVectorBY, blockVectorY)304 ##305 # B-orthonormalize X.306 blockVectorX, blockVectorBX = _b_orthonormalize(B, blockVectorX)307 ##308 # Compute the initial Ritz vectors: solve the eigenproblem.309 blockVectorAX = A(blockVectorX)310 gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)311 _lambda, eigBlockVector = eigh(gramXAX, check_finite=False)312 ii = _get_indx(_lambda, sizeX, largest)313 _lambda = _lambda[ii]314 eigBlockVector = np.asarray(eigBlockVector[:, ii])315 blockVectorX = np.dot(blockVectorX, eigBlockVector)316 blockVectorAX = np.dot(blockVectorAX, eigBlockVector)317 if B is not None:318 blockVectorBX = np.dot(blockVectorBX, eigBlockVector)319 ##320 # Active index set.321 activeMask = np.ones((sizeX,), dtype=bool)322 lambdaHistory = [_lambda]323 residualNormsHistory = []324 previousBlockSize = sizeX325 ident = np.eye(sizeX, dtype=A.dtype)326 ident0 = np.eye(sizeX, dtype=A.dtype)327 ##328 # Main iteration loop.329 blockVectorP = None # set during iteration330 blockVectorAP = None331 blockVectorBP = None332 iterationNumber = -1333 restart = True334 explicitGramFlag = False335 while iterationNumber < maxiter:336 iterationNumber += 1337 if verbosityLevel > 0:338 print('iteration %d' % iterationNumber)339 if B is not None:340 aux = blockVectorBX * _lambda[np.newaxis, :]341 else:342 aux = blockVectorX * _lambda[np.newaxis, :]343 blockVectorR = blockVectorAX - aux344 aux = np.sum(blockVectorR.conj() * blockVectorR, 0)345 residualNorms = np.sqrt(aux)346 residualNormsHistory.append(residualNorms)347 ii = np.where(residualNorms > residualTolerance, True, False)348 activeMask = activeMask & ii349 if verbosityLevel > 2:350 print(activeMask)351 currentBlockSize = activeMask.sum()352 if currentBlockSize != previousBlockSize:353 previousBlockSize = currentBlockSize354 ident = np.eye(currentBlockSize, dtype=A.dtype)355 if currentBlockSize == 0:356 break357 if verbosityLevel > 0:358 print('current block size:', currentBlockSize)359 print('eigenvalue:', _lambda)360 print('residual norms:', residualNorms)361 if verbosityLevel > 10:362 print(eigBlockVector)363 activeBlockVectorR = _as2d(blockVectorR[:, activeMask])364 if iterationNumber > 0:365 activeBlockVectorP = _as2d(blockVectorP[:, activeMask])366 activeBlockVectorAP = _as2d(blockVectorAP[:, activeMask])367 if B is not None:368 activeBlockVectorBP = _as2d(blockVectorBP[:, activeMask])369 if M is not None:370 # Apply preconditioner T to the active residuals.371 activeBlockVectorR = M(activeBlockVectorR)372 ##373 # Apply constraints to the preconditioned residuals.374 if blockVectorY is not None:375 _applyConstraints(activeBlockVectorR,376 gramYBY, blockVectorBY, blockVectorY)377 ##378 # B-orthogonalize the preconditioned residuals to X.379 if B is not None:380 activeBlockVectorR = activeBlockVectorR - np.matmul(blockVectorX,381 np.matmul(blockVectorBX.T.conj(),382 activeBlockVectorR))383 else:384 activeBlockVectorR = activeBlockVectorR - np.matmul(blockVectorX,385 np.matmul(blockVectorX.T.conj(),386 activeBlockVectorR))387 ##388 # B-orthonormalize the preconditioned residuals.389 aux = _b_orthonormalize(B, activeBlockVectorR)390 activeBlockVectorR, activeBlockVectorBR = aux391 activeBlockVectorAR = A(activeBlockVectorR)392 if iterationNumber > 0:393 if B is not None:394 aux = _b_orthonormalize(B, activeBlockVectorP,395 activeBlockVectorBP, retInvR=True)396 activeBlockVectorP, activeBlockVectorBP, invR, normal = aux397 else:398 aux = _b_orthonormalize(B, activeBlockVectorP, retInvR=True)399 activeBlockVectorP, _, invR, normal = aux400 # Function _b_orthonormalize returns None if Cholesky fails401 if activeBlockVectorP is not None:402 activeBlockVectorAP = activeBlockVectorAP / normal403 activeBlockVectorAP = np.dot(activeBlockVectorAP, invR)404 restart = False405 else:406 restart = True407 ##408 # Perform the Rayleigh Ritz Procedure:409 # Compute symmetric Gram matrices:410 if activeBlockVectorAR.dtype == 'float32':411 myeps = 1412 elif activeBlockVectorR.dtype == 'float32':413 myeps = 1e-4414 else:415 myeps = 1e-8416 if residualNorms.max() > myeps and not explicitGramFlag:417 explicitGramFlag = False418 else:419 # Once explicitGramFlag, forever explicitGramFlag.420 explicitGramFlag = True421 # Shared memory assingments to simplify the code422 if B is None:423 blockVectorBX = blockVectorX424 activeBlockVectorBR = activeBlockVectorR425 if not restart:426 activeBlockVectorBP = activeBlockVectorP427 # Common submatrices:428 gramXAR = np.dot(blockVectorX.T.conj(), activeBlockVectorAR)429 gramRAR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAR)430 if explicitGramFlag:431 gramRAR = (gramRAR + gramRAR.T.conj())/2432 gramXAX = np.dot(blockVectorX.T.conj(), blockVectorAX)433 gramXAX = (gramXAX + gramXAX.T.conj())/2434 gramXBX = np.dot(blockVectorX.T.conj(), blockVectorBX)435 gramRBR = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBR)436 gramXBR = np.dot(blockVectorX.T.conj(), activeBlockVectorBR)437 else:438 gramXAX = np.diag(_lambda)439 gramXBX = ident0440 gramRBR = ident441 gramXBR = np.zeros((sizeX, currentBlockSize), dtype=A.dtype)442 def _handle_gramA_gramB_verbosity(gramA, gramB):443 if verbosityLevel > 0:444 _report_nonhermitian(gramA, 'gramA')445 _report_nonhermitian(gramB, 'gramB')446 if verbosityLevel > 10:447 # Note: not documented, but leave it in here for now448 np.savetxt('gramA.txt', gramA)449 np.savetxt('gramB.txt', gramB)450 if not restart:451 gramXAP = np.dot(blockVectorX.T.conj(), activeBlockVectorAP)452 gramRAP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorAP)453 gramPAP = np.dot(activeBlockVectorP.T.conj(), activeBlockVectorAP)454 gramXBP = np.dot(blockVectorX.T.conj(), activeBlockVectorBP)455 gramRBP = np.dot(activeBlockVectorR.T.conj(), activeBlockVectorBP)456 if explicitGramFlag:457 gramPAP = (gramPAP + gramPAP.T.conj())/2458 gramPBP = np.dot(activeBlockVectorP.T.conj(),459 activeBlockVectorBP)460 else:461 gramPBP = ident462 gramA = bmat([[gramXAX, gramXAR, gramXAP],463 [gramXAR.T.conj(), gramRAR, gramRAP],464 [gramXAP.T.conj(), gramRAP.T.conj(), gramPAP]])465 gramB = bmat([[gramXBX, gramXBR, gramXBP],466 [gramXBR.T.conj(), gramRBR, gramRBP],467 [gramXBP.T.conj(), gramRBP.T.conj(), gramPBP]])468 _handle_gramA_gramB_verbosity(gramA, gramB)469 try:470 _lambda, eigBlockVector = eigh(gramA, gramB,471 check_finite=False)472 except LinAlgError:473 # try again after dropping the direction vectors P from RR474 restart = True475 if restart:476 gramA = bmat([[gramXAX, gramXAR],477 [gramXAR.T.conj(), gramRAR]])478 gramB = bmat([[gramXBX, gramXBR],479 [gramXBR.T.conj(), gramRBR]])480 _handle_gramA_gramB_verbosity(gramA, gramB)481 try:482 _lambda, eigBlockVector = eigh(gramA, gramB,483 check_finite=False)484 except LinAlgError:485 raise ValueError('eigh has failed in lobpcg iterations')486 ii = _get_indx(_lambda, sizeX, largest)487 if verbosityLevel > 10:488 print(ii)489 print(_lambda)490 _lambda = _lambda[ii]491 eigBlockVector = eigBlockVector[:, ii]492 lambdaHistory.append(_lambda)493 if verbosityLevel > 10:494 print('lambda:', _lambda)495# # Normalize eigenvectors!496# aux = np.sum( eigBlockVector.conj() * eigBlockVector, 0 )497# eigVecNorms = np.sqrt( aux )498# eigBlockVector = eigBlockVector / eigVecNorms[np.newaxis, :]499# eigBlockVector, aux = _b_orthonormalize( B, eigBlockVector )500 if verbosityLevel > 10:501 print(eigBlockVector)502 # Compute Ritz vectors.503 if B is not None:504 if not restart:505 eigBlockVectorX = eigBlockVector[:sizeX]506 eigBlockVectorR = eigBlockVector[sizeX:sizeX+currentBlockSize]507 eigBlockVectorP = eigBlockVector[sizeX+currentBlockSize:]508 pp = np.dot(activeBlockVectorR, eigBlockVectorR)509 pp += np.dot(activeBlockVectorP, eigBlockVectorP)510 app = np.dot(activeBlockVectorAR, eigBlockVectorR)511 app += np.dot(activeBlockVectorAP, eigBlockVectorP)512 bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)513 bpp += np.dot(activeBlockVectorBP, eigBlockVectorP)514 else:515 eigBlockVectorX = eigBlockVector[:sizeX]516 eigBlockVectorR = eigBlockVector[sizeX:]517 pp = np.dot(activeBlockVectorR, eigBlockVectorR)518 app = np.dot(activeBlockVectorAR, eigBlockVectorR)519 bpp = np.dot(activeBlockVectorBR, eigBlockVectorR)520 if verbosityLevel > 10:521 print(pp)522 print(app)523 print(bpp)524 blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp525 blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app526 blockVectorBX = np.dot(blockVectorBX, eigBlockVectorX) + bpp527 blockVectorP, blockVectorAP, blockVectorBP = pp, app, bpp528 else:529 if not restart:530 eigBlockVectorX = eigBlockVector[:sizeX]531 eigBlockVectorR = eigBlockVector[sizeX:sizeX+currentBlockSize]532 eigBlockVectorP = eigBlockVector[sizeX+currentBlockSize:]533 pp = np.dot(activeBlockVectorR, eigBlockVectorR)534 pp += np.dot(activeBlockVectorP, eigBlockVectorP)535 app = np.dot(activeBlockVectorAR, eigBlockVectorR)536 app += np.dot(activeBlockVectorAP, eigBlockVectorP)537 else:538 eigBlockVectorX = eigBlockVector[:sizeX]539 eigBlockVectorR = eigBlockVector[sizeX:]540 pp = np.dot(activeBlockVectorR, eigBlockVectorR)541 app = np.dot(activeBlockVectorAR, eigBlockVectorR)542 if verbosityLevel > 10:543 print(pp)544 print(app)545 blockVectorX = np.dot(blockVectorX, eigBlockVectorX) + pp546 blockVectorAX = np.dot(blockVectorAX, eigBlockVectorX) + app547 blockVectorP, blockVectorAP = pp, app548 if B is not None:549 aux = blockVectorBX * _lambda[np.newaxis, :]550 else:551 aux = blockVectorX * _lambda[np.newaxis, :]552 blockVectorR = blockVectorAX - aux553 aux = np.sum(blockVectorR.conj() * blockVectorR, 0)554 residualNorms = np.sqrt(aux)555 # Future work: Need to add Postprocessing here:556 # Making sure eigenvectors "exactly" satisfy the blockVectorY constrains?557 # Making sure eigenvecotrs are "exactly" othonormalized by final "exact" RR558 # Computing the actual true residuals559 if verbosityLevel > 0:560 print('final eigenvalue:', _lambda)561 print('final residual norms:', residualNorms)562 if retLambdaHistory:563 if retResidualNormsHistory:564 return _lambda, blockVectorX, lambdaHistory, residualNormsHistory565 else:566 return _lambda, blockVectorX, lambdaHistory567 else:568 if retResidualNormsHistory:569 return _lambda, blockVectorX, residualNormsHistory570 else:...

Full Screen

Full Screen

js.js

Source:js.js Github

copy

Full Screen

...45}46function robot(i,j){47 if(i<=startD[1]&&j<=endD[1]){48 if(block[i][j]==2){49 drawBlock(i+1,j,"red");50 drawBlock(i,j,"white");51 block[i+1][j]=3;52 block[i][j]=0;53 }else{54 drawBlock(i,j+1,"red");55 drawBlock(i,j,"white");56 block[i][j+1]=3;57 block[i][j]=0;58 }59 }else if(i>startD[1]&&j<=endD[1]){60 if(block[i][j]==2){61 drawBlock(i,j+1,"red");62 drawBlock(i,j,"white");63 block[i][j+1]=3;64 block[i][j]=0;65 }else{66 drawBlock(i-1,j,"red");67 drawBlock(i,j,"white");68 block[i-1][j]=3;69 block[i][j]=0;70 }71 }else if(i>startD[1]&&j>endD[1]){72 if(block[i][j]==2){73 drawBlock(i-1,j,"red");74 drawBlock(i,j,"white");75 block[i-1][j]=3;76 block[i][j]=0;77 }else{78 drawBlock(i,j-1,"red");79 drawBlock(i,j,"white");80 block[i][j-1]=3;81 block[i][j]=0;82 }83 }else if(i<=startD[1]&&j>endD[1]){84 if(block[i][j]==2){85 drawBlock(i,j-1,"red");86 drawBlock(i,j,"white");87 block[i][j-1]=3;88 block[i][j]=0;89 }else{90 drawBlock(i+1,j,"red");91 drawBlock(i,j,"white");92 block[i+1][j]=3;93 block[i][j]=0;94 }95 }96}97//Òƶ¯»úÆ÷ÈË98//function mvRobot(){99// for(var i=1;i<10;i++){100// for(var j=1;j<10;j++){101// if(block[i][j]==3){102// if(i<=startD[1]){103// if(j<=endD[1]){104// if(block[i][j+1]==2){105// drawBlock(i+1,j,"red");106// drawBlock(i,j,"white");107// block[i+1][j]=3;108// block[i][j]=0;109// }else {110// if(j-endD[1]>=i-startD[1]){111// drawBlock(i,j+1,"red");112// drawBlock(i,j,"white");113// block[i][j+1]=3;114// block[i][j]=0;115// }else if(j-endD[1]<i-startD[1]){116// drawBlock(i+1,j,"red");117// drawBlock(i,j,"white");118// block[i+1][j]=3;119// block[i][j]=0;120// }121// }122// }else{123// if(block[i][j+1]==2){124// drawBlock(i-1,j,"red");125// drawBlock(i,j,"white");126// block[i-1][j]=3;127// block[i][j]=0;128// }else{129// if(j-endD[1]>=i-startD[1]){130// drawBlock(i,j-1,"red");131// drawBlock(i,j,"white");132// block[i][j-1]=3;133// block[i][j]=0;134// }else if(j-endD[1]<i-startD[1]){135// drawBlock(i-1,j,"red");136// drawBlock(i,j,"white");137// block[i-1][j]=3;138// block[i][j]=0;139// }140// }141// }142// }else{143// if(j<=endD[1]){144// if(block[i][j+1]==2){145// drawBlock(i-1,j,"red");146// drawBlock(i,j,"white");147// block[i-1][j]=3;148// block[i][j]=0;149// }else{150// if(j-endD[1]>=i-startD[1]){151// drawBlock(i,j+1,"red");152// drawBlock(i,j,"white");153// block[i][j+1]=3;154// block[i][j]=0;155// }else if(j-endD[1]<i-startD[1]){156// drawBlock(i+1,j,"red");157// drawBlock(i,j,"white");158// block[i+1][j]=3;159// block[i][j]=0;160// }161// }162// }else{163// if(block[i][j+1]==2){164// drawBlock(i+1,j,"red");165// drawBlock(i,j,"white");166// block[i+1][j]=3;167// block[i][j]=0;168// }else{169// if(j-endD[1]>=i-startD[1]){170// drawBlock(i,j-1,"red");171// drawBlock(i,j,"white");172// block[i][j-1]=3;173// block[i][j]=0;174// }else if(j-endD[1]<i-startD[1]){175// drawBlock(i-1,j,"red");176// drawBlock(i,j,"white");177// block[i-1][j]=3;178// block[i][j]=0;179// }180// }181// }182// }183// }184// }185// }186//}187//Òƶ¯hero188function mvSuper(pX,pY){189 if(block[startD[1]-pX][endD[1]-pY]==0){//-1 0190 startD[1] -= pX;191 endD[1]-=pY;192 if(superBlock==-1){193 drawBlock(startD[1],endD[1],"green");194 }else if(superBlock<3){195 drawBlock(startD[1],endD[1],"#6BF65E");196 superBlock+=1;197 if(superBlock==2){198 superBlock=-1;199 }200 }201 drawBlock(startD[1]+pX,endD[1]+pY,"white");//+1 0202 block[startD[1]][endD[1]]=-1;203 block[startD[1]+pX][endD[1]+pY]=0;//+1 0204 }else if(block[startD[1]-pX][endD[1]-pY]==2){//-1 0205 alert("no");206 }else if(block[startD[1]-pX][endD[1]-pY]==1){207 startD[1] -= pX;208 endD[1]-=pY;209 drawBlock(startD[1],endD[1],"#6BF65E");210 drawBlock(startD[1]+pX,endD[1]+pY,"white");211 block[startD[1]][endD[1]]=-1;212 block[startD[1]+pX][endD[1]+pY]=0;213 superBlock=0;214 }else if(block[startD[1]-pX][endD[1]-pY]==3){215 if(superBlock==-1) {216 alert("failed");217 } else if(superBlock!=-1){218 startD[1] -= pX;219 endD[1]-=pY;220 drawBlock(startD[1],endD[1],"#6BF65E");221 drawBlock(startD[1]+pX,endD[1]+pY,"white");222 block[startD[1]][endD[1]]=-1;223 block[startD[1]+1][endD[1]]=0;224 superBlock++;225 }226 }227 var robot=0;228 var suptool=0;229 for(var i=1;i<=10;i++){230 for(var j=1;j<=10;j++){231 if(block[i][j]==3){232 robot++;233 }234 if(block[i][j]==1){235 suptool++;236 }237 }238 }239 if(robot==0){240 alert("win");241 }else if(robot!=0 || (robot!=0&&suptool==0)){242 if(superBlock==-1) alert("failed");243 else{244 return;245 }246 }247}248//²úÉúhero robot super as....249function clickXY(){250 i=1;251 var x,y;252 chess.onclick=function(e){253 x= e.offsetX;254 y= e.offsetY;255 startD[i]= Math.floor(x / 30);256 endD [i]= Math.floor(y / 30);257 if(startD[i]<1 || startD[i]>10 || endD[i]<1 || endD[i]>10) return;258 if(i==1){259 drawBlock(startD[i],endD[i],"green");260 block[startD[i]][endD[i]]=-1;261 //console.log(startD[i],endD[i]);262 i++;263 }else if(i>1){264 if(block[startD[i]][endD[i]]==0){265 var str=window.prompt("1,0,2","");266 if(str==0){267 drawBlock(startD[i],endD[i],"red");268 block[startD[i]][endD[i]]=3;269 i++;270 }else if(str==1){271 drawBlock(startD[i],endD[i],"blue");272 block[startD[i]][endD[i]]=1;273 i++;274 }else if(str==2){275 drawBlock(startD[i],endD[i],"#F6C462");276 block[startD[i]][endD[i]]=2;277 i++;278 }279 }else alert("repeat");280 }281 else return;282 }283}284//»­±í¸ñ285var drawchessbox=function(){286 for(var i=0;i<11;i++)287 {288 context.moveTo(30+i*30,30);289 context.lineTo(30+i*30,360-30);290 context.stroke();291 context.moveTo(30,30+i*30);292 context.lineTo(360-30,30+i*30);293 context.stroke();294 }295}296//»­·½¿é297function drawBlock(startD,endD,color) {298 if(startD>0&&startD<11&&endD>0&&endD<11){299 context.strokeStyle = "block";300 context.fillStyle = color;301 context.fillRect(startD*30,endD*30,30,30);302 context.strokeRect(startD*30,endD*30,30,30);303 }304}305//if(block[startD[1]-1][endD[1]]==0){306// startD[1] -= 1;307// if(superBlock==-1){308// drawBlock(startD[1],endD[1],"green");309// }else if(superBlock<3){310// drawBlock(startD[1],endD[1],"#6BF65E");311// superBlock+=1;312// if(superBlock==2){313// superBlock=-1;314// }315// }316// drawBlock(startD[1]+1,endD[1],"white");317// block[startD[1]][endD[1]]=-1;318// block[startD[1]+1][endD[1]]=0;319//}else if(block[startD[1]-1][endD[1]]==2){320// alert("no");321//}else if(block[startD[1]-1][endD[1]]==1){322// startD[1] -= 1;323// drawBlock(startD[1],endD[1],"#6BF65E");324// drawBlock(startD[1]+1,endD[1],"white");325// block[startD[1]][endD[1]]=-1;326// block[startD[1]+1][endD[1]]=0;327// superBlock=0;328//}else if(block[startD[1]-1][endD[1]]==3){329// if(superBlock==-1) {330// alert("failed");331// } else if(superBlock!=-1){332// startD[1] -= 1;333// drawBlock(startD[1],endD[1],"#6BF65E");334// drawBlock(startD[1]+1,endD[1],"white");335// block[startD[1]][endD[1]]=-1;336// block[startD[1]+1][endD[1]]=0;337// superBlock++;338// }339//}340//startD[1] += 1;341//drawBlock(startD[1],endD[1],"green");342//drawBlock(startD[1]-1,endD[1],"white");343//endD[1] += 1;344//drawBlock(startD[1],endD[1],"green");345//drawBlock(startD[1],endD[1]-1,"white");346//endD[1] -= 1;347//drawBlock(startD[1],endD[1],"green");348//drawBlock(startD[1],endD[1]+1,"white");349//if(i<=startD[1]){350// if(j<=endD[1]){351// if(block[i][j+1]!=2){352// drawBlock(i,j+1,"red");353// drawBlock(i,j-1,"white");354// block[i][j+1]=3;355// block[i][j]=0;356// }else{357// drawBlock(i+1,j,"red");358// drawBlock(i-1,j,"white");359// block[i+1][j]=3;360// block[i][j]=0;361// }362// }else{363// if(block[i][j-1]!=2){364// drawBlock(i,j-1,"red");365// drawBlock(i,j+1,"white");366// block[i][j-1]=3;367// block[i][j]=0;368// }else{369// drawBlock(i-1,j,"red");370// drawBlock(i+1,j,"white");371// block[i-1][j]=3;372// block[i][j]=0;373// }374// }375//}376//if(i>startD[1]){377// if(j<=endD[1]){378// if(block[i][j-1]!=2){379// drawBlock(i,j-1,"red");380// drawBlock(i,j+1,"white");381// block[i][j-1]=3;382// block[i][j]=0;383// }else{384// drawBlock(i-1,j,"red");385// drawBlock(i+1,j,"white");386// block[i-1][j]=3;387// block[i][j]=0;388// }389// }else{390// if(block[i][j+1]!=2){391// drawBlock(i,j+1,"red");392// drawBlock(i,j-1,"white");393// block[i][j+1]=3;394// block[i][j]=0;395// }else{396// drawBlock(i+1,j,"red");397// drawBlock(i-1,j,"white");398// block[i+1][j]=3;399// block[i][j]=0;400// }401// }...

Full Screen

Full Screen

block-prop-container.ts

Source:block-prop-container.ts Github

copy

Full Screen

1import {AfterViewInit, ChangeDetectorRef, Component, Inject, ViewChild} from "@angular/core";2import {Compbaser} from "ng-mslib";3import {YellowPepperService} from "../../services/yellowpepper.service";4import {BlockService, IBlockData, ISceneData} from "./block-service";5import {CampaignTimelineChanelPlayersModel} from "../../store/imsdb.interfaces_auto";6import {ColorPickerService} from "ngx-color-picker";7import {Tab} from "../../comps/tabs/tab";8import {BlockLabels, PLACEMENT_CHANNEL, PLACEMENT_SCENE} from "../../interfaces/Consts";9@Component({10 selector: 'block-prop-container',11 template: `12 <small class="debug">{{me}}</small>13 <tabs>14 <tab [tabtitle]="'style'">15 <block-prop-common [setBlockData]="m_blockData"></block-prop-common>16 </tab>17 <tab [tabtitle]="m_tabTitle">18 <div [ngSwitch]="m_blockTypeSelected">19 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_IMAGE">20 <block-prop-image [external]="false" [setBlockData]="m_blockData"></block-prop-image>21 </div>22 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_SVG">23 <block-prop-image [external]="false" [setBlockData]="m_blockData"></block-prop-image>24 </div>25 <div *ngSwitchCase="m_blockLabels.IMAGE">26 <block-prop-image [external]="true" [setBlockData]="m_blockData"></block-prop-image>27 </div>28 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_VIDEO">29 <block-prop-video [external]="false" [setBlockData]="m_blockData"></block-prop-video>30 </div>31 <div *ngSwitchCase="m_blockLabels.EXTERNAL_VIDEO">32 <block-prop-video [external]="true" [setBlockData]="m_blockData"></block-prop-video>33 </div>34 <div *ngSwitchCase="m_blockLabels.MRSS">35 <block-prop-mrss [setBlockData]="m_blockData"></block-prop-mrss>36 </div>37 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_COLLECTION">38 <block-prop-collection [setBlockData]="m_blockData"></block-prop-collection>39 </div>40 <div *ngSwitchCase="m_blockLabels.RSS">41 <block-prop-rss [setBlockData]="m_blockData"></block-prop-rss>42 </div>43 <div *ngSwitchCase="m_blockLabels.LABEL">44 <block-prop-label [setBlockData]="m_blockData"></block-prop-label>45 </div>46 <div *ngSwitchCase="m_blockLabels.QR">47 <block-prop-qr [setBlockData]="m_blockData"></block-prop-qr>48 </div>49 <div *ngSwitchCase="m_blockLabels.CLOCK">50 <block-prop-clock [setBlockData]="m_blockData"></block-prop-clock>51 </div>52 <div *ngSwitchCase="m_blockLabels.HTML">53 <block-prop-html [setBlockData]="m_blockData"></block-prop-html>54 </div>55 <div *ngSwitchCase="m_blockLabels.FASTERQ">56 <block-prop-fasterq [setBlockData]="m_blockData"></block-prop-fasterq>57 </div>58 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_SCENE">59 <block-prop-scene [setBlockData]="m_blockData"></block-prop-scene>60 </div>61 <div *ngSwitchCase="m_blockLabels.LOCATION">62 <block-prop-location [setBlockData]="m_blockData"></block-prop-location>63 </div>64 <div *ngSwitchCase="m_blockLabels.YOUTUBE">65 <block-prop-youtube [setBlockData]="m_blockData"></block-prop-youtube>66 </div>67 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_JSON">68 <block-prop-json-player [standAlone]="true" [setBlockData]="m_blockData"></block-prop-json-player>69 </div>70 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_JSON_ITEM">71 <block-prop-json-item [setBlockData]="m_blockData"></block-prop-json-item>72 </div>73 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_WORLD_WEATHER">74 <block-prop-weather [setBlockData]="m_blockData"></block-prop-weather>75 </div>76 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_INSTAGRAM">77 <block-prop-instagram [setBlockData]="m_blockData"></block-prop-instagram>78 </div>79 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_DIGG">80 <block-prop-digg [setBlockData]="m_blockData"></block-prop-digg>81 </div>82 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_CALENDAR">83 <block-prop-calendar [setBlockData]="m_blockData"></block-prop-calendar>84 </div>85 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_TWITTERV3">86 <block-prop-twitter [setBlockData]="m_blockData"></block-prop-twitter>87 </div>88 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_GOOGLE_SHEETS">89 <block-prop-sheets [setBlockData]="m_blockData"></block-prop-sheets>90 </div>91 <div *ngSwitchDefault>92 <h3>no block prop found, new?</h3>93 {{m_blockTypeSelected}}94 </div>95 </div>96 </tab>97 <!-- below are JSON based blocked which bind to scenes -->98 <tab #settings [tabtitle]="'settings'">99 <div [ngSwitch]="m_blockTypeSelected">100 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_WORLD_WEATHER">101 <block-prop-weather [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-weather>102 </div>103 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_INSTAGRAM">104 <block-prop-instagram [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-instagram>105 </div>106 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_DIGG">107 <block-prop-digg [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-digg>108 </div>109 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_CALENDAR">110 <block-prop-calendar [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-calendar>111 </div>112 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_TWITTERV3">113 <block-prop-twitter [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-twitter>114 </div>115 <div *ngSwitchCase="m_blockLabels.BLOCKCODE_GOOGLE_SHEETS">116 <block-prop-sheets [jsonMode]="true" [setBlockData]="m_blockData"></block-prop-sheets>117 </div>118 </div>119 </tab>120 </tabs>121 `,122})123export class BlockPropContainer extends Compbaser implements AfterViewInit {124 m_blockTypeSelected: string = 'none';125 m_blockLabels = BlockLabels;126 m_blockData: IBlockData;127 m_tabTitle: string = 'none';128 m_showSettingsTab = true;129 constructor(@Inject('BLOCK_PLACEMENT') private blockPlacement: string, private yp: YellowPepperService, private bs: BlockService, private cpService: ColorPickerService, private cd: ChangeDetectorRef) {130 super();131 // console.log(blockPlacement);132 if (this.blockPlacement == PLACEMENT_CHANNEL)133 this._listenOnChannels();134 if (this.blockPlacement == PLACEMENT_SCENE)135 this._listenOnScenes();136 }137 @ViewChild('settings')138 settings: Tab;139 ngAfterViewInit() {140 this.toggleSettingsTab();141 }142 private _listenOnChannels() {143 this.cancelOnDestroy(144 //145 this.yp.listenBlockChannelSelectedOrChanged()146 .mergeMap((i_campaignTimelineChanelPlayersModel: CampaignTimelineChanelPlayersModel) => {147 return this.bs.getBlockData(i_campaignTimelineChanelPlayersModel.getCampaignTimelineChanelPlayerId())148 })149 .subscribe((blockData: IBlockData) => {150 this.m_blockTypeSelected = blockData.blockCode;151 this.m_tabTitle = blockData.blockAcronym;152 this.m_blockData = blockData;153 // for json based scenes show the settings, unless its the actual Json Player which we don't154 if (blockData.playerMimeScene && this.m_blockTypeSelected != '4300') {155 this.m_showSettingsTab = true;156 this.toggleSettingsTab();157 } else {158 this.m_showSettingsTab = false;159 this.toggleSettingsTab();160 }161 }, (e) => console.error(e))162 )163 }164 private _listenOnScenes() {165 this.cancelOnDestroy(166 //167 this.yp.listenSceneOrBlockSelectedChanged()168 .mergeMap((i_sceneData: ISceneData) => {169 return this.bs.getBlockDataInScene(i_sceneData)170 })171 .subscribe((blockData: IBlockData) => {172 this.m_blockTypeSelected = blockData.blockCode;173 this.m_tabTitle = blockData.blockAcronym;174 this.m_blockData = blockData;175 this.m_showSettingsTab = false;176 this.toggleSettingsTab();177 this.cd.markForCheck();178 }, (e) => console.error(e))179 )180 }181 // private getTabTitle(i_blockData: IBlockData): string {182 // // this.bs.getCommonBorderXML()if (i_blockData.blockAcronym.indexOf('JSON')) > -1 ? blockData.playerMimeScene : blockData.blockAcronym183 // }184 private toggleSettingsTab() {185 if (!this.settings) return;186 this.settings.show = this.m_showSettingsTab;187 }188 ngOnInit() {189 }190 destroy() {191 }...

Full Screen

Full Screen

zerocoin_publicSpend_reorg.py

Source:zerocoin_publicSpend_reorg.py Github

copy

Full Screen

...37 self.unspent = self.node.listunspent()38 block_count = self.node.getblockcount()39 pastBlockHash = self.node.getblockhash(block_count)40 self.log.info("Block count: %d - Current best: %s..." % (self.node.getblockcount(), self.node.getbestblockhash()[:5]))41 pastBlock = CBlock()42 pastBlock.deserialize(BytesIO(hex_str_to_bytes(self.node.getblock(pastBlockHash, False))))43 checkpoint = pastBlock.nAccumulatorCheckpoint44 # 5) get the raw zerocoin spend txes45 self.log.info("Getting the raw zerocoin public spends...")46 public_spend_A = self.node.createrawzerocoinpublicspend(mints[0].get("serial hash"))47 tx_A = CTransaction()48 tx_A.deserialize(BytesIO(hex_str_to_bytes(public_spend_A)))49 tx_A.rehash()50 public_spend_B = self.node.createrawzerocoinpublicspend(mints[1].get("serial hash"))51 tx_B = CTransaction()52 tx_B.deserialize(BytesIO(hex_str_to_bytes(public_spend_B)))53 tx_B.rehash()54 # Spending same coins to different recipients to get different txids55 my_addy = "yAVWM5urwaTyhiuFQHP2aP47rdZsLUG5PH"...

Full Screen

Full Screen

block.js

Source:block.js Github

copy

Full Screen

...16 return null17 }18 const web3 = await Web3Util.getWeb3()19 const start = new Date()20 const _block = await web3.eth.getBlock(blockNumber)21 const end = new Date() - start22 logger.info(`Execution time : %dms web3.eth.getBlock(${blockNumber})`, end)23 if (!_block) {24 return null25 }26 const { m1, m2 } = await utils.getM1M2(_block)27 _block.m2 = m228 _block.signer = m129 const timestamp = _block.timestamp * 100030 // Update end tx count.31 _block.timestamp = timestamp32 _block.e_tx = _block.transactions.length33 try {34 const data = {35 jsonrpc: '2.0',36 method: 'eth_getBlockFinalityByHash',37 params: [_block.hash],38 id: 8839 }40 const response = await axios.post(config.get('WEB3_URI'), data)41 const result = response.data42 let finalityNumber = parseInt(result.result)43 // blockNumber = 0 is genesis block44 if (parseInt(blockNumber) === 0) {45 finalityNumber = 10046 }47 _block.finality = finalityNumber48 } catch (e) {49 logger.warn('Cannot get block finality %s', blockNumber)50 logger.warn(e)51 }52 const txs = _block.transactions53 delete _block.transactions54 _block.status = true55 _block.updateFinalityTime = 056 delete _block._id57 delete _block.signers58 await db.Block.updateOne({ number: _block.number }, _block,59 { upsert: true, new: true })60 await elastic.index(_block.hash, 'blocks', _block)61 if (_block.number % config.get('BLOCK_PER_EPOCH') === 0) {62 const slashedNode = []63 const blk = await BlockHelper.getBlock(_block.number)64 if (blk.penalties && blk.penalties !== '0x') {65 const sbuff = Buffer.from((blk.penalties || '').substring(2), 'hex')66 if (sbuff.length > 0) {67 for (let i = 1; i <= sbuff.length / 20; i++) {68 const address = sbuff.slice((i - 1) * 20, i * 20)69 const add = '0x' + address.toString('hex')70 slashedNode.push(add.toLowerCase())71 }72 }73 }74 const buff = Buffer.from(blk.extraData.substring(2), 'hex')75 const sbuff = buff.slice(32, buff.length - 65)76 const signers = []77 if (sbuff.length > 0) {78 for (let i = 1; i <= sbuff.length / 20; i++) {79 const address = sbuff.slice((i - 1) * 20, i * 20)80 signers.push('0x' + address.toString('hex'))81 }82 }83 const epoch = _block.number / config.get('BLOCK_PER_EPOCH')84 // TODO: update slash for next 5 epochs85 if (slashedNode.length > 0) {86 for (let i = 0; i < 5; i++) {87 const nextEpoch = epoch + 1 + i88 const e = await db.Epoch.findOne({ epoch: nextEpoch })89 if (e) {90 const sn = e.slashedNode91 const newArr = sn.concat(slashedNode)92 e.slashedNode = Array.from(new Set(newArr))93 await e.save()94 } else {95 const ne = new db.Epoch({96 epoch: nextEpoch,97 startBlock: (nextEpoch - 1) * 900 + 1,98 endBlock: nextEpoch * 900,99 slashedNode: slashedNode,100 isActive: false101 })102 await ne.save()103 }104 }105 }106 }107 return { txs, timestamp }108 },109 getBlockDetail: async (hashOrNumber) => {110 try {111 let block = await db.Block.findOne({ number: hashOrNumber })112 if (!block) {113 block = await db.Block.findOne({ hash: String(hashOrNumber).toLowerCase() })114 }115 if (block && block.finality === 100) {116 return block117 }118 const web3 = await Web3Util.getWeb3()119 const _block = await web3.eth.getBlock(hashOrNumber)120 if (!_block) {121 return null122 }123 try {124 const { m1, m2 } = await utils.getM1M2(_block)125 _block.m2 = m2126 _block.signer = m1127 } catch (e) {128 logger.warn('Cannot get M1, M2 of block %s', hashOrNumber)129 logger.warn(e)130 }131 // Update end tx count.132 _block.timestamp = _block.timestamp * 1000133 _block.e_tx = _block.transactions.length134 try {135 const data = {136 jsonrpc: '2.0',137 method: 'eth_getBlockFinalityByHash',138 params: [_block.hash],139 id: 88140 }141 const response = await axios.post(config.get('WEB3_URI'), data)142 const result = response.data143 _block.finality = parseInt(result.result)144 } catch (e) {145 logger.warn('Cannot get block finality %s', hashOrNumber)146 logger.warn(e)147 }148 _block.status = true149 if (block) {150 if (!Object.prototype.hasOwnProperty.call(block, 'updateFinalityTime')) {151 _block.updateFinalityTime = 0152 }153 } else {154 _block.updateFinalityTime = 0155 }156 delete _block._id157 delete _block.signers158 block = await db.Block.findOneAndUpdate({ number: _block.number }, _block,159 { upsert: true, new: true })160 return block161 } catch (e) {162 logger.warn('cannot get block %s with error %s', hashOrNumber, e)163 return {}164 }165 },166 getBlockOnChain: async (number) => {167 try {168 const _block = await BlockHelper.getBlock(number)169 if (!_block) {170 return null171 }172 // Get signer.173 const signer = await utils.toAddress(await utils.getSigner(_block), 100)174 _block.signer = signer.toLowerCase()175 // Update end tx count.176 _block.timestamp = _block.timestamp * 1000177 _block.e_tx = _block.transactions.length178 try {179 const data = {180 jsonrpc: '2.0',181 method: 'eth_getBlockFinalityByHash',182 params: [_block.hash],183 id: 88184 }185 const response = await axios.post(config.get('WEB3_URI'), data)186 const result = response.data187 let finalityNumber = parseInt(result.result)188 // blockNumber = 0 is genesis block189 if (parseInt(_block.number) === 0) {190 finalityNumber = 100191 }192 _block.finality = finalityNumber193 } catch (e) {194 logger.warn('Cannot get block finality %s', number)195 logger.warn(e)196 }197 _block.status = true198 return _block199 } catch (e) {200 logger.warn('cannot get block on chain with error %s', e)201 return {}202 }203 },204 getBlock: async (number) => {205 const web3 = await Web3Util.getWeb3()206 return web3.eth.getBlock(number).catch(e => {207 logger.warn('Cannot get block %s detail. Sleep 2 seconds and try more. Error %s', number, e)208 return sleep(2000).then(() => {209 return BlockHelper.getBlock(number)210 })211 })212 },213 getLastBlockNumber: async () => {214 const web3 = await Web3Util.getWeb3()215 return web3.eth.getBlockNumber().catch(e => {216 logger.warn('Cannot get last block number. Sleep 2 seconds and try more. Error %s', e)217 return sleep(2000).then(() => {218 return BlockHelper.getLastBlockNumber()219 })220 })221 }222}223module.exports = BlockHelper

Full Screen

Full Screen

block.py

Source:block.py Github

copy

Full Screen

...7 return hash(self) - hash(rhs)8 def __hash__(self):9 return (self.id << 8) + self.data10 def withData(self, data):11 return Block(self.id, data)12 def __iter__(self):13 """Allows a Block to be sent whenever id [and data] is needed"""14 return iter((self.id, self.data))15 16 def __repr__(self):17 return "Block(%d, %d)"%(self.id, self.data)18AIR = Block(0)19STONE = Block(1)20GRASS = Block(2)21DIRT = Block(3)22COBBLESTONE = Block(4)23WOOD_PLANKS = Block(5)24SAPLING = Block(6)25BEDROCK = Block(7)26WATER_FLOWING = Block(8)27WATER = WATER_FLOWING28WATER_STATIONARY = Block(9)29LAVA_FLOWING = Block(10)30LAVA = LAVA_FLOWING31LAVA_STATIONARY = Block(11)32SAND = Block(12)33GRAVEL = Block(13)34GOLD_ORE = Block(14)35IRON_ORE = Block(15)36COAL_ORE = Block(16)37WOOD = Block(17)38LEAVES = Block(18)39GLASS = Block(20)40LAPIS_LAZULI_ORE = Block(21)41LAPIS_LAZULI_BLOCK = Block(22)42SANDSTONE = Block(24)43BED = Block(26)44COBWEB = Block(30)45GRASS_TALL = Block(31)46WOOL = Block(35)47FLOWER_YELLOW = Block(37)48FLOWER_CYAN = Block(38)49MUSHROOM_BROWN = Block(39)50MUSHROOM_RED = Block(40)51GOLD_BLOCK = Block(41)52IRON_BLOCK = Block(42)53STONE_SLAB_DOUBLE = Block(43)54STONE_SLAB = Block(44)55BRICK_BLOCK = Block(45)56TNT = Block(46)57BOOKSHELF = Block(47)58MOSS_STONE = Block(48)59OBSIDIAN = Block(49)60TORCH = Block(50)61FIRE = Block(51)62STAIRS_WOOD = Block(53)63CHEST = Block(54)64DIAMOND_ORE = Block(56)65DIAMOND_BLOCK = Block(57)66CRAFTING_TABLE = Block(58)67FARMLAND = Block(60)68FURNACE_INACTIVE = Block(61)69FURNACE_ACTIVE = Block(62)70DOOR_WOOD = Block(64)71LADDER = Block(65)72STAIRS_COBBLESTONE = Block(67)73DOOR_IRON = Block(71)74REDSTONE_ORE = Block(73)75SNOW = Block(78)76ICE = Block(79)77SNOW_BLOCK = Block(80)78CACTUS = Block(81)79CLAY = Block(82)80SUGAR_CANE = Block(83)81FENCE = Block(85)82GLOWSTONE_BLOCK = Block(89)83BEDROCK_INVISIBLE = Block(95)84STONE_BRICK = Block(98)85GLASS_PANE = Block(102)86MELON = Block(103)87FENCE_GATE = Block(107)88GLOWING_OBSIDIAN = Block(246)...

Full Screen

Full Screen

test_block.py

Source:test_block.py Github

copy

Full Screen

...26 time.sleep(MINE_RATE / SECONDS)27 mined_block = Block.mine_block(last_block, 'bar')28 assert mined_block.difficulty == last_block.difficulty - 129def test_mined_block_difficulty_limits_at_1():30 last_block = Block(time.time_ns(), 'test_last_hash', 'test_hash',31 'test_data', 1, 0)32 time.sleep(MINE_RATE / SECONDS)33 mined_block = Block.mine_block(last_block, 'bar')34 assert mined_block.difficulty == 135@pytest.fixture36def last_block():37 return Block.genesis_block()38@pytest.fixture39def block(last_block):40 return Block.mine_block(last_block, 'test_data')41def test_is_valid_block(last_block, block):42 Block.is_valid_block(last_block, block)43def test_is_valid_block_bad_last_hash(last_block, block):44 block.last_hash = 'evil_last_hash'...

Full Screen

Full Screen

index.ts

Source:index.ts Github

copy

Full Screen

...15 this.data = data;16 this.timestamp = timestamp;17 }18}19const genesisBlock:Block = new Block(0, "2021", "", "Hello", 123456);20let blockchain: Block[] = [genesisBlock];21const getBlockchain = () : Block[] => blockchain;22const getLatestBlock = () : Block => blockchain[blockchain.length -1];23const getNewTimeStamp = () : number => Math.round(new Date().getTime() / 1000);24const createNewBlock = (data: string) : Block => {25 const previousBlock : Block = getLatestBlock();26 const newIndex : number = previousBlock.index + 1;27 const newTimestamp : number = getNewTimeStamp();28 const newHash : string = Block.calculateBlockHash(newIndex, previousBlock.hash, newTimestamp, data);29 const newBlock : Block = new Block(newIndex, newHash, previousBlock.hash, data, newTimestamp);30 addBlock(newBlock);31 return newBlock;32};33const getHashForBlock = (aBlock: Block) : string => Block.calculateBlockHash(aBlock.index, aBlock.previousHash, aBlock.timestamp, aBlock.data);34const isBlockValid = (candidateBlock : Block, previousBlock : Block): boolean => {35 if(!Block.validateStructure(candidateBlock)) {36 return false;37 } else if(previousBlock.index + 1 !== candidateBlock.index){38 return false;39 } else if(previousBlock.hash !== candidateBlock.previousHash){40 return false;41 } else if(getHashForBlock(candidateBlock) !== candidateBlock.hash){42 return false;43 } else {44 return true;45 }46};47const addBlock = (candidateBlock: Block) : void => {48 if(isBlockValid(candidateBlock, getLatestBlock())) {49 blockchain.push(candidateBlock);50 }51};52createNewBlock("second block");53createNewBlock("third block");54createNewBlock("fourth block");55console.log(blockchain);...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import React from 'react';2import { storiesOf } from '@storybook/react';3import { action } from '@storybook/addon-actions';4import { linkTo } from '@storybook/addon-links';5import { withKnobs, text, boolean, number } from '@storybook/addon-knobs';6import { withInfo } from '@storybook/addon-info';7import { Button, Welcome } from '@storybook/react/demo';8import { withReadme } from 'storybook-readme';9import { withDocs } from 'storybook-readme';10import { withDocsCustom } from 'storybook-readme';11import { withDocsCustom2 } from 'storybook-readme';12import { withDocsCustom3 } from 'storybook-readme';13import { withDocsCustom4 } from 'storybook-readme';14import { withDocsCustom5 } from 'storybook-readme';15import { withDocsCustom6 } from 'storybook-readme';16import { withDocsCustom7 } from 'storybook-readme';17import { withDocsCustom8 } from 'storybook-readme';18import { withDocsCustom9 } from 'storybook-readme';19import { withDocsCustom10 } from 'storybook-readme';20import { withDocsCustom11 } from 'storybook-readme';21import { withDocsCustom12 } from 'storybook-readme';22import { withDocsCustom13 } from 'storybook-readme';23import { withDocsCustom14 } from 'storybook-readme';24import { withDocsCustom15 } from 'storybook-readme';25import { withDocsCustom16 } from 'storybook-readme';26import { withDocsCustom17 } from 'storybook-readme';27import { withDocsCustom18 } from 'storybook-readme';28import { withDocsCustom19 } from 'storybook-readme';29import { withDocsCustom20 } from 'storybook-readme';30import { withDocsCustom21 } from 'storybook-readme';31import { withDocsCustom22 } from 'storybook-readme';32import { withDocsCustom23 } from 'storybook-readme';33import { withDocsCustom24 } from 'storybook-readme';34import { withDocsCustom25 } from 'storybook-readme';35import { withDocsCustom26 } from 'storybook-readme';36import { withDocsCustom27 } from 'storybook-readme';37import { withDocsCustom28 } from 'storybook-readme';38import { withDocsCustom29 } from 'storybook-readme';39import { withDocsCustom30 } from 'storybook-readme';40import { with

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from '@storybook/react';2import { Block } from 'storybook-root';3storiesOf('Block', module)4 .add('default', () => (5 ));6@import "~storybook-root/dist/styles.css";7import { configure } from '@storybook/react';8import 'storybook-root/dist/styles.css';9configure(require.context('../src', true, /\.stories\.js$/), module);10const path = require('path');11module.exports = (baseConfig, env, defaultConfig) => {12 defaultConfig.module.rules.push({13 test: /\.(js|jsx)$/,14 include: path.resolve(__dirname, '../'),15 {16 options: {17 ['es2015', { modules: false }],18 }19 }20 });21 return defaultConfig;22};23import '@storybook/addon-actions/register';24import '@storybook/addon-links/register';25import '@storybook/addon-knobs/register';26import 'storybook-root/dist/addon/register';27import { addons } from '@storybook/addons';28import { create } from '@storybook/theming';29addons.setConfig({30 theme: create({

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Block } from 'storybook-root';2export default Block;3import React from 'react';4import { storiesOf } from '@storybook/react';5import Test from './test';6storiesOf('Test', module).add('default', () => <Test />);

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Block } from 'storybook-root';2import { Button } from 'storybook-root';3import { Block } from 'storybook-root';4import { Button } from 'storybook-root';5import { Block } from 'storybook-root';6import { Button } from 'storybook-root';7import { Block } from 'storybook-root';8import { Button } from 'storybook-root';9import { Block } from 'storybook-root';10import { Button } from 'storybook-root';11import { Block } from 'storybook-root';12import { Button } from 'storybook-root';

Full Screen

Using AI Code Generation

copy

Full Screen

1import {Block} from 'storybook-root';2export default function Test() {3 return (4 );5}6import Test from './test';7export default Test;8module.exports = {9 webpackFinal: async config => {10 config.resolve.alias['storybook-root'] = path.resolve(__dirname, '../src');11 return config;12 },13};

Full Screen

Using AI Code Generation

copy

Full Screen

1import { Block } from 'storybook-root';2export default {3};4export const Default = () => <Block width="100%" height="200px" bg="primary" />;5export const WithChildren = () => (6);7export const WithProps = () => (8);9export const WithResponsiveProps = () => (10 <Block width="100%" height="200px" bg="primary" p={['10px', '20px', '30px']}>11 <Block width="100%" height="100px" bg="secondary" p={['10px', '20px', '30px']} />12);13export const WithCustomProps = () => (14 <Block width="100%" height="200px" bg="primary" p={['10px', '20px', '30px']} customProp="test">15 <Block width="100%" height="100px" bg="secondary" p={['10px', '20px', '30px']} customProp="test" />16);17export const WithCustomProps2 = () => (18 <Block width="100%" height="200px" bg="primary" p={['10px', '20px', '30px']} customProp="test">19 <Block width="100%" height="100px" bg="secondary" p={['10px', '20px', '30px']} customProp="test" />20);21export const WithCustomProps3 = () => (22 <Block width="100%" height="200px" bg="primary" p={['10px', '20px', '30px']} customProp="test">23 <Block width="100%" height="100px" bg="secondary" p={['10px', '20px', '30px']} customProp="test" />24);25export const WithCustomProps4 = () => (

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful