idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
20,400 | def connected_components ( G ) : G = asgraph ( G ) N = G . shape [ 0 ] components = np . empty ( N , G . indptr . dtype ) fn = amg_core . connected_components fn ( N , G . indptr , G . indices , components ) return components | Compute the connected components of a graph . |
20,401 | def symmetric_rcm ( A ) : n = A . shape [ 0 ] root , order , level = pseudo_peripheral_node ( A ) Perm = sparse . identity ( n , format = 'csr' ) p = level . argsort ( ) Perm = Perm [ p , : ] return Perm * A * Perm . T | Symmetric Reverse Cutthill - McKee . |
20,402 | def pseudo_peripheral_node ( A ) : from pyamg . graph import breadth_first_search n = A . shape [ 0 ] valence = np . diff ( A . indptr ) x = int ( np . random . rand ( ) * n ) delta = 0 while True : order , level = breadth_first_search ( A , x ) maxlevel = level . max ( ) lastnodes = np . where ( level == maxlevel ) [ 0 ] lastnodesvalence = valence [ lastnodes ] minlastnodesvalence = lastnodesvalence . min ( ) y = np . where ( lastnodesvalence == minlastnodesvalence ) [ 0 ] [ 0 ] y = lastnodes [ y ] if level [ y ] > delta : x = y delta = level [ y ] else : return x , order , level | Find a pseudo peripheral node . |
20,403 | def profile_solver ( ml , accel = None , ** kwargs ) : A = ml . levels [ 0 ] . A b = A * sp . rand ( A . shape [ 0 ] , 1 ) residuals = [ ] if accel is None : ml . solve ( b , residuals = residuals , ** kwargs ) else : def callback ( x ) : residuals . append ( norm ( np . ravel ( b ) - np . ravel ( A * x ) ) ) M = ml . aspreconditioner ( cycle = kwargs . get ( 'cycle' , 'V' ) ) accel ( A , b , M = M , callback = callback , ** kwargs ) return np . asarray ( residuals ) | Profile a particular multilevel object . |
20,404 | def diag_sparse ( A ) : if isspmatrix ( A ) : return A . diagonal ( ) else : if ( np . ndim ( A ) != 1 ) : raise ValueError ( 'input diagonal array expected to be 1d' ) return csr_matrix ( ( np . asarray ( A ) , np . arange ( len ( A ) ) , np . arange ( len ( A ) + 1 ) ) , ( len ( A ) , len ( A ) ) ) | Return a diagonal . |
20,405 | def scale_rows ( A , v , copy = True ) : v = np . ravel ( v ) M , N = A . shape if not isspmatrix ( A ) : raise ValueError ( 'scale rows needs a sparse matrix' ) if M != len ( v ) : raise ValueError ( 'scale vector has incompatible shape' ) if copy : A = A . copy ( ) A . data = np . asarray ( A . data , dtype = upcast ( A . dtype , v . dtype ) ) else : v = np . asarray ( v , dtype = A . dtype ) if isspmatrix_csr ( A ) : csr_scale_rows ( M , N , A . indptr , A . indices , A . data , v ) elif isspmatrix_bsr ( A ) : R , C = A . blocksize bsr_scale_rows ( int ( M / R ) , int ( N / C ) , R , C , A . indptr , A . indices , np . ravel ( A . data ) , v ) elif isspmatrix_csc ( A ) : pyamg . amg_core . csc_scale_rows ( M , N , A . indptr , A . indices , A . data , v ) else : fmt = A . format A = scale_rows ( csr_matrix ( A ) , v ) . asformat ( fmt ) return A | Scale the sparse rows of a matrix . |
20,406 | def scale_columns ( A , v , copy = True ) : v = np . ravel ( v ) M , N = A . shape if not isspmatrix ( A ) : raise ValueError ( 'scale columns needs a sparse matrix' ) if N != len ( v ) : raise ValueError ( 'scale vector has incompatible shape' ) if copy : A = A . copy ( ) A . data = np . asarray ( A . data , dtype = upcast ( A . dtype , v . dtype ) ) else : v = np . asarray ( v , dtype = A . dtype ) if isspmatrix_csr ( A ) : csr_scale_columns ( M , N , A . indptr , A . indices , A . data , v ) elif isspmatrix_bsr ( A ) : R , C = A . blocksize bsr_scale_columns ( int ( M / R ) , int ( N / C ) , R , C , A . indptr , A . indices , np . ravel ( A . data ) , v ) elif isspmatrix_csc ( A ) : pyamg . amg_core . csc_scale_columns ( M , N , A . indptr , A . indices , A . data , v ) else : fmt = A . format A = scale_columns ( csr_matrix ( A ) , v ) . asformat ( fmt ) return A | Scale the sparse columns of a matrix . |
20,407 | def type_prep ( upcast_type , varlist ) : varlist = to_type ( upcast_type , varlist ) for i in range ( len ( varlist ) ) : if np . isscalar ( varlist [ i ] ) : varlist [ i ] = np . array ( [ varlist [ i ] ] ) return varlist | Upcast variables to a type . |
20,408 | def to_type ( upcast_type , varlist ) : for i in range ( len ( varlist ) ) : if np . isscalar ( varlist [ i ] ) : varlist [ i ] = np . array ( [ varlist [ i ] ] , upcast_type ) [ 0 ] else : try : if varlist [ i ] . dtype != upcast_type : varlist [ i ] = varlist [ i ] . astype ( upcast_type ) except AttributeError : warn ( 'Failed to cast in to_type' ) pass return varlist | Loop over all elements of varlist and convert them to upcasttype . |
20,409 | def get_block_diag ( A , blocksize , inv_flag = True ) : if not isspmatrix ( A ) : raise TypeError ( 'Expected sparse matrix' ) if A . shape [ 0 ] != A . shape [ 1 ] : raise ValueError ( "Expected square matrix" ) if sp . mod ( A . shape [ 0 ] , blocksize ) != 0 : raise ValueError ( "blocksize and A.shape must be compatible" ) if hasattr ( A , 'block_D_inv' ) and inv_flag : if ( A . block_D_inv . shape [ 1 ] == blocksize ) and ( A . block_D_inv . shape [ 2 ] == blocksize ) and ( A . block_D_inv . shape [ 0 ] == int ( A . shape [ 0 ] / blocksize ) ) : return A . block_D_inv elif hasattr ( A , 'block_D' ) and ( not inv_flag ) : if ( A . block_D . shape [ 1 ] == blocksize ) and ( A . block_D . shape [ 2 ] == blocksize ) and ( A . block_D . shape [ 0 ] == int ( A . shape [ 0 ] / blocksize ) ) : return A . block_D if not isspmatrix_bsr ( A ) : A = bsr_matrix ( A , blocksize = ( blocksize , blocksize ) ) if A . blocksize != ( blocksize , blocksize ) : A = A . tobsr ( blocksize = ( blocksize , blocksize ) ) A = A . asfptype ( ) block_diag = sp . zeros ( ( int ( A . shape [ 0 ] / blocksize ) , blocksize , blocksize ) , dtype = A . dtype ) AAIJ = ( sp . arange ( 1 , A . indices . shape [ 0 ] + 1 ) , A . indices , A . indptr ) shape = ( int ( A . shape [ 0 ] / blocksize ) , int ( A . shape [ 0 ] / blocksize ) ) diag_entries = csr_matrix ( AAIJ , shape = shape ) . diagonal ( ) diag_entries -= 1 nonzero_mask = ( diag_entries != - 1 ) diag_entries = diag_entries [ nonzero_mask ] if diag_entries . shape != ( 0 , ) : block_diag [ nonzero_mask , : , : ] = A . data [ diag_entries , : , : ] if inv_flag : if block_diag . shape [ 1 ] < 7 : pyamg . amg_core . pinv_array ( block_diag . ravel ( ) , block_diag . shape [ 0 ] , block_diag . shape [ 1 ] , 'T' ) else : pinv_array ( block_diag ) A . block_D_inv = block_diag else : A . block_D = block_diag return block_diag | Return the block diagonal of A in array form . |
20,410 | def amalgamate ( A , blocksize ) : if blocksize == 1 : return A elif sp . mod ( A . shape [ 0 ] , blocksize ) != 0 : raise ValueError ( "Incompatible blocksize" ) A = A . tobsr ( blocksize = ( blocksize , blocksize ) ) A . sort_indices ( ) subI = ( np . ones ( A . indices . shape ) , A . indices , A . indptr ) shape = ( int ( A . shape [ 0 ] / A . blocksize [ 0 ] ) , int ( A . shape [ 1 ] / A . blocksize [ 1 ] ) ) return csr_matrix ( subI , shape = shape ) | Amalgamate matrix A . |
20,411 | def UnAmal ( A , RowsPerBlock , ColsPerBlock ) : data = np . ones ( ( A . indices . shape [ 0 ] , RowsPerBlock , ColsPerBlock ) ) blockI = ( data , A . indices , A . indptr ) shape = ( RowsPerBlock * A . shape [ 0 ] , ColsPerBlock * A . shape [ 1 ] ) return bsr_matrix ( blockI , shape = shape ) | Unamalgamate a CSR A with blocks of 1 s . |
20,412 | def print_table ( table , title = '' , delim = '|' , centering = 'center' , col_padding = 2 , header = True , headerchar = '-' ) : table_str = '\n' if isinstance ( table , tuple ) : title = table [ 0 ] table = table [ 1 ] colwidths = [ ] for i in range ( len ( table ) ) : for k in range ( len ( table [ i ] ) - len ( colwidths ) ) : colwidths . append ( - 1 ) for j in range ( len ( table [ i ] ) ) : if len ( table [ i ] [ j ] ) > colwidths [ j ] : colwidths [ j ] = len ( table [ i ] [ j ] ) for i in range ( len ( colwidths ) ) : colwidths [ i ] += col_padding ttwidth = sum ( colwidths ) + len ( delim ) * ( len ( colwidths ) - 1 ) if len ( title ) > 0 : title = title . split ( "\n" ) for i in range ( len ( title ) ) : table_str += str . center ( title [ i ] , ttwidth ) + '\n' table_str += "\n" centering = centering . lower ( ) if centering == 'center' : centering = str . center if centering == 'right' : centering = str . rjust if centering == 'left' : centering = str . ljust if header : for elmt , elmtwidth in zip ( table [ 0 ] , colwidths ) : table_str += centering ( str ( elmt ) , elmtwidth ) + delim if table [ 0 ] != [ ] : table_str = table_str [ : - len ( delim ) ] + '\n' if len ( headerchar ) == 0 : headerchar = ' ' table_str += headerchar * int ( sp . ceil ( float ( ttwidth ) / float ( len ( headerchar ) ) ) ) + '\n' table = table [ 1 : ] for row in table : for elmt , elmtwidth in zip ( row , colwidths ) : table_str += centering ( str ( elmt ) , elmtwidth ) + delim if row != [ ] : table_str = table_str [ : - len ( delim ) ] + '\n' else : table_str += '\n' return table_str | Print a table from a list of lists representing the rows of a table . |
20,413 | def Coord2RBM ( numNodes , numPDEs , x , y , z ) : if ( numPDEs == 1 ) : numcols = 1 elif ( ( numPDEs == 3 ) or ( numPDEs == 6 ) ) : numcols = 6 else : raise ValueError ( "Coord2RBM(...) only supports 1, 3 or 6 PDEs per\ spatial location,i.e. numPDEs = [1 | 3 | 6].\ You've entered " + str ( numPDEs ) + "." ) if ( ( max ( x . shape ) != numNodes ) or ( max ( y . shape ) != numNodes ) or ( max ( z . shape ) != numNodes ) ) : raise ValueError ( "Coord2RBM(...) requires coordinate vectors of equal\ length. Length must be numNodes = " + str ( numNodes ) ) rbm = np . mat ( np . zeros ( ( numNodes * numPDEs , numcols ) ) ) for node in range ( numNodes ) : dof = node * numPDEs if ( numPDEs == 1 ) : rbm [ node ] = 1.0 if ( numPDEs == 6 ) : for ii in range ( 3 , 6 ) : for jj in range ( 0 , 6 ) : if ( ii == jj ) : rbm [ dof + ii , jj ] = 1.0 else : rbm [ dof + ii , jj ] = 0.0 if ( ( numPDEs == 3 ) or ( numPDEs == 6 ) ) : for ii in range ( 0 , 3 ) : for jj in range ( 0 , 3 ) : if ( ii == jj ) : rbm [ dof + ii , jj ] = 1.0 else : rbm [ dof + ii , jj ] = 0.0 for ii in range ( 0 , 3 ) : for jj in range ( 3 , 6 ) : if ( ii == ( jj - 3 ) ) : rbm [ dof + ii , jj ] = 0.0 else : if ( ( ii + jj ) == 4 ) : rbm [ dof + ii , jj ] = z [ node ] elif ( ( ii + jj ) == 5 ) : rbm [ dof + ii , jj ] = y [ node ] elif ( ( ii + jj ) == 6 ) : rbm [ dof + ii , jj ] = x [ node ] else : rbm [ dof + ii , jj ] = 0.0 ii = 0 jj = 5 rbm [ dof + ii , jj ] *= - 1.0 ii = 1 jj = 3 rbm [ dof + ii , jj ] *= - 1.0 ii = 2 jj = 4 rbm [ dof + ii , jj ] *= - 1.0 return rbm | Convert 2D or 3D coordinates into Rigid body modes . |
20,414 | def relaxation_as_linear_operator ( method , A , b ) : from pyamg import relaxation from scipy . sparse . linalg . interface import LinearOperator import pyamg . multilevel def unpack_arg ( v ) : if isinstance ( v , tuple ) : return v [ 0 ] , v [ 1 ] else : return v , { } accepted_methods = [ 'gauss_seidel' , 'block_gauss_seidel' , 'sor' , 'gauss_seidel_ne' , 'gauss_seidel_nr' , 'jacobi' , 'block_jacobi' , 'richardson' , 'schwarz' , 'strength_based_schwarz' , 'jacobi_ne' ] b = np . array ( b , dtype = A . dtype ) fn , kwargs = unpack_arg ( method ) lvl = pyamg . multilevel_solver . level ( ) lvl . A = A if not accepted_methods . __contains__ ( fn ) : raise NameError ( "invalid relaxation method: " , fn ) try : setup_smoother = getattr ( relaxation . smoothing , 'setup_' + fn ) except NameError : raise NameError ( "invalid presmoother method: " , fn ) relax = setup_smoother ( lvl , ** kwargs ) def matvec ( x ) : xcopy = x . copy ( ) relax ( A , xcopy , b ) return xcopy return LinearOperator ( A . shape , matvec , dtype = A . dtype ) | Create a linear operator that applies a relaxation method for the given right - hand - side . |
20,415 | def scale_T ( T , P_I , I_F ) : if not isspmatrix_bsr ( T ) : raise TypeError ( 'Expected BSR matrix T' ) elif T . blocksize [ 0 ] != T . blocksize [ 1 ] : raise TypeError ( 'Expected BSR matrix T with square blocks' ) if not isspmatrix_bsr ( P_I ) : raise TypeError ( 'Expected BSR matrix P_I' ) elif P_I . blocksize [ 0 ] != P_I . blocksize [ 1 ] : raise TypeError ( 'Expected BSR matrix P_I with square blocks' ) if not isspmatrix_bsr ( I_F ) : raise TypeError ( 'Expected BSR matrix I_F' ) elif I_F . blocksize [ 0 ] != I_F . blocksize [ 1 ] : raise TypeError ( 'Expected BSR matrix I_F with square blocks' ) if ( I_F . blocksize [ 0 ] != P_I . blocksize [ 0 ] ) or ( I_F . blocksize [ 0 ] != T . blocksize [ 0 ] ) : raise TypeError ( 'Expected identical blocksize in I_F, P_I and T' ) if P_I . nnz > 0 : D = P_I . T * T if D . nnz > 0 : pinv_array ( D . data ) T = T * D T = I_F * T + P_I return T | Scale T with a block diagonal matrix . |
20,416 | def compute_BtBinv ( B , C ) : if not isspmatrix_bsr ( C ) and not isspmatrix_csr ( C ) : raise TypeError ( 'Expected bsr_matrix or csr_matrix for C' ) if C . shape [ 1 ] != B . shape [ 0 ] : raise TypeError ( 'Expected matching dimensions such that C*B' ) if isspmatrix_bsr ( C ) : ColsPerBlock = C . blocksize [ 1 ] RowsPerBlock = C . blocksize [ 0 ] else : ColsPerBlock = 1 RowsPerBlock = 1 Ncoarse = C . shape [ 1 ] Nfine = C . shape [ 0 ] NullDim = B . shape [ 1 ] Nnodes = int ( Nfine / RowsPerBlock ) BtBinv = np . zeros ( ( Nnodes , NullDim , NullDim ) , dtype = B . dtype ) BsqCols = sum ( range ( NullDim + 1 ) ) Bsq = np . zeros ( ( Ncoarse , BsqCols ) , dtype = B . dtype ) counter = 0 for i in range ( NullDim ) : for j in range ( i , NullDim ) : Bsq [ : , counter ] = np . conjugate ( np . ravel ( np . asarray ( B [ : , i ] ) ) ) * np . ravel ( np . asarray ( B [ : , j ] ) ) counter = counter + 1 pyamg . amg_core . calc_BtB ( NullDim , Nnodes , ColsPerBlock , np . ravel ( np . asarray ( Bsq ) ) , BsqCols , np . ravel ( np . asarray ( BtBinv ) ) , C . indptr , C . indices ) BtBinv = BtBinv . transpose ( ( 0 , 2 , 1 ) ) . copy ( ) pinv_array ( BtBinv ) return BtBinv | Create block inverses . |
20,417 | def eliminate_diag_dom_nodes ( A , C , theta = 1.02 ) : r A_abs = A . copy ( ) A_abs . data = np . abs ( A_abs . data ) D_abs = get_diagonal ( A_abs , norm_eq = 0 , inv = False ) diag_dom_rows = ( D_abs > ( theta * ( A_abs * np . ones ( ( A_abs . shape [ 0 ] , ) , dtype = A_abs ) - D_abs ) ) ) bsize = blocksize ( A_abs ) if bsize > 1 : diag_dom_rows = np . array ( diag_dom_rows , dtype = int ) diag_dom_rows = diag_dom_rows . reshape ( - 1 , bsize ) diag_dom_rows = np . sum ( diag_dom_rows , axis = 1 ) diag_dom_rows = ( diag_dom_rows == bsize ) Id = eye ( C . shape [ 0 ] , C . shape [ 1 ] , format = 'csr' ) Id . data [ diag_dom_rows ] = 0.0 C = Id * C * Id Id . data [ diag_dom_rows ] = 1.0 Id . data [ np . where ( diag_dom_rows == 0 ) [ 0 ] ] = 0.0 C = C + Id del A_abs return C | r Eliminate diagonally dominance . |
20,418 | def remove_diagonal ( S ) : if not isspmatrix_csr ( S ) : raise TypeError ( 'expected csr_matrix' ) if S . shape [ 0 ] != S . shape [ 1 ] : raise ValueError ( 'expected square matrix, shape=%s' % ( S . shape , ) ) S = coo_matrix ( S ) mask = S . row != S . col S . row = S . row [ mask ] S . col = S . col [ mask ] S . data = S . data [ mask ] return S . tocsr ( ) | Remove the diagonal of the matrix S . |
20,419 | def scale_rows_by_largest_entry ( S ) : if not isspmatrix_csr ( S ) : raise TypeError ( 'expected csr_matrix' ) largest_row_entry = np . zeros ( ( S . shape [ 0 ] , ) , dtype = S . dtype ) pyamg . amg_core . maximum_row_value ( S . shape [ 0 ] , largest_row_entry , S . indptr , S . indices , S . data ) largest_row_entry [ largest_row_entry != 0 ] = 1.0 / largest_row_entry [ largest_row_entry != 0 ] S = scale_rows ( S , largest_row_entry , copy = True ) return S | Scale each row in S by it s largest in magnitude entry . |
20,420 | def levelize_strength_or_aggregation ( to_levelize , max_levels , max_coarse ) : if isinstance ( to_levelize , tuple ) : if to_levelize [ 0 ] == 'predefined' : to_levelize = [ to_levelize ] max_levels = 2 max_coarse = 0 else : to_levelize = [ to_levelize for i in range ( max_levels - 1 ) ] elif isinstance ( to_levelize , str ) : if to_levelize == 'predefined' : raise ValueError ( 'predefined to_levelize requires a user-provided\ CSR matrix representing strength or aggregation\ i.e., (\'predefined\', {\'C\' : CSR_MAT}).' ) else : to_levelize = [ to_levelize for i in range ( max_levels - 1 ) ] elif isinstance ( to_levelize , list ) : if isinstance ( to_levelize [ - 1 ] , tuple ) and ( to_levelize [ - 1 ] [ 0 ] == 'predefined' ) : max_levels = len ( to_levelize ) + 1 max_coarse = 0 else : if len ( to_levelize ) < max_levels - 1 : mlz = max_levels - 1 - len ( to_levelize ) toext = [ to_levelize [ - 1 ] for i in range ( mlz ) ] to_levelize . extend ( toext ) elif to_levelize is None : to_levelize = [ ( None , { } ) for i in range ( max_levels - 1 ) ] else : raise ValueError ( 'invalid to_levelize' ) return max_levels , max_coarse , to_levelize | Turn parameter into a list per level . |
20,421 | def levelize_smooth_or_improve_candidates ( to_levelize , max_levels ) : if isinstance ( to_levelize , tuple ) or isinstance ( to_levelize , str ) : to_levelize = [ to_levelize for i in range ( max_levels ) ] elif isinstance ( to_levelize , list ) : if len ( to_levelize ) < max_levels : mlz = max_levels - len ( to_levelize ) toext = [ to_levelize [ - 1 ] for i in range ( mlz ) ] to_levelize . extend ( toext ) elif to_levelize is None : to_levelize = [ ( None , { } ) for i in range ( max_levels ) ] return to_levelize | Turn parameter in to a list per level . |
20,422 | def filter_matrix_columns ( A , theta ) : if not isspmatrix ( A ) : raise ValueError ( "Sparse matrix input needed" ) if isspmatrix_bsr ( A ) : blocksize = A . blocksize Aformat = A . format if ( theta < 0 ) or ( theta >= 1.0 ) : raise ValueError ( "theta must be in [0,1)" ) A = A . copy ( ) . tocsc ( ) A_filter = A . copy ( ) A . indices += A . shape [ 1 ] A_filter . indices += A . shape [ 1 ] pyamg . amg_core . classical_strength_of_connection_abs ( A . shape [ 1 ] , theta , A . indptr , A . indices , A . data , A_filter . indptr , A_filter . indices , A_filter . data ) A_filter . indices [ : A_filter . indptr [ - 1 ] ] -= A_filter . shape [ 1 ] A_filter = csc_matrix ( ( A_filter . data [ : A_filter . indptr [ - 1 ] ] , A_filter . indices [ : A_filter . indptr [ - 1 ] ] , A_filter . indptr ) , shape = A_filter . shape ) del A if Aformat == 'bsr' : A_filter = A_filter . tobsr ( blocksize ) else : A_filter = A_filter . asformat ( Aformat ) return A_filter | Filter each column of A with tol . |
20,423 | def filter_matrix_rows ( A , theta ) : if not isspmatrix ( A ) : raise ValueError ( "Sparse matrix input needed" ) if isspmatrix_bsr ( A ) : blocksize = A . blocksize Aformat = A . format A = A . tocsr ( ) if ( theta < 0 ) or ( theta >= 1.0 ) : raise ValueError ( "theta must be in [0,1)" ) A_filter = A . copy ( ) A . indices += A . shape [ 0 ] A_filter . indices += A . shape [ 0 ] pyamg . amg_core . classical_strength_of_connection_abs ( A . shape [ 0 ] , theta , A . indptr , A . indices , A . data , A_filter . indptr , A_filter . indices , A_filter . data ) A_filter . indices [ : A_filter . indptr [ - 1 ] ] -= A_filter . shape [ 0 ] A_filter = csr_matrix ( ( A_filter . data [ : A_filter . indptr [ - 1 ] ] , A_filter . indices [ : A_filter . indptr [ - 1 ] ] , A_filter . indptr ) , shape = A_filter . shape ) if Aformat == 'bsr' : A_filter = A_filter . tobsr ( blocksize ) else : A_filter = A_filter . asformat ( Aformat ) A . indices -= A . shape [ 0 ] return A_filter | Filter each row of A with tol . |
20,424 | def truncate_rows ( A , nz_per_row ) : if not isspmatrix ( A ) : raise ValueError ( "Sparse matrix input needed" ) if isspmatrix_bsr ( A ) : blocksize = A . blocksize if isspmatrix_csr ( A ) : A = A . copy ( ) Aformat = A . format A = A . tocsr ( ) nz_per_row = int ( nz_per_row ) pyamg . amg_core . truncate_rows_csr ( A . shape [ 0 ] , nz_per_row , A . indptr , A . indices , A . data ) A . eliminate_zeros ( ) if Aformat == 'bsr' : A = A . tobsr ( blocksize ) else : A = A . asformat ( Aformat ) return A | Truncate the rows of A by keeping only the largest in magnitude entries in each row . |
20,425 | def require_auth ( function ) : @ functools . wraps ( function ) def wrapper ( self , * args , ** kwargs ) : if not self . access_token ( ) : raise MissingAccessTokenError return function ( self , * args , ** kwargs ) return wrapper | A decorator that wraps the passed in function and raises exception if access token is missing |
20,426 | def randomizable ( function ) : @ functools . wraps ( function ) def wrapper ( self , * args , ** kwargs ) : if self . randomize : self . randomize_headers ( ) return function ( self , * args , ** kwargs ) return wrapper | A decorator which randomizes requests if needed |
20,427 | def get_profile ( self ) : r = self . _session . get ( API_URL + "/logins/me" ) r . raise_for_status ( ) return r . json ( ) | Get my own profile |
20,428 | def get_calendar ( self , listing_id , starting_month = datetime . datetime . now ( ) . month , starting_year = datetime . datetime . now ( ) . year , calendar_months = 12 ) : params = { 'year' : str ( starting_year ) , 'listing_id' : str ( listing_id ) , '_format' : 'with_conditions' , 'count' : str ( calendar_months ) , 'month' : str ( starting_month ) } r = self . _session . get ( API_URL + "/calendar_months" , params = params ) r . raise_for_status ( ) return r . json ( ) | Get availability calendar for a given listing |
20,429 | def get_reviews ( self , listing_id , offset = 0 , limit = 20 ) : params = { '_order' : 'language_country' , 'listing_id' : str ( listing_id ) , '_offset' : str ( offset ) , 'role' : 'all' , '_limit' : str ( limit ) , '_format' : 'for_mobile_client' , } print ( self . _session . headers ) r = self . _session . get ( API_URL + "/reviews" , params = params ) r . raise_for_status ( ) return r . json ( ) | Get reviews for a given listing |
20,430 | def get_listing_calendar ( self , listing_id , starting_date = datetime . datetime . now ( ) , calendar_months = 6 ) : params = { '_format' : 'host_calendar_detailed' } starting_date_str = starting_date . strftime ( "%Y-%m-%d" ) ending_date_str = ( starting_date + datetime . timedelta ( days = 30 ) ) . strftime ( "%Y-%m-%d" ) r = self . _session . get ( API_URL + "/calendars/{}/{}/{}" . format ( str ( listing_id ) , starting_date_str , ending_date_str ) , params = params ) r . raise_for_status ( ) return r . json ( ) | Get host availability calendar for a given listing |
20,431 | def find_gui_and_backend ( ) : matplotlib = sys . modules [ 'matplotlib' ] backend = matplotlib . rcParams [ 'backend' ] gui = backend2gui . get ( backend , None ) return gui , backend | Return the gui and mpl backend . |
20,432 | def is_interactive_backend ( backend ) : matplotlib = sys . modules [ 'matplotlib' ] from matplotlib . rcsetup import interactive_bk , non_interactive_bk if backend in interactive_bk : return True elif backend in non_interactive_bk : return False else : return matplotlib . is_interactive ( ) | Check if backend is interactive |
20,433 | def activate_matplotlib ( enable_gui_function ) : matplotlib = sys . modules [ 'matplotlib' ] gui , backend = find_gui_and_backend ( ) is_interactive = is_interactive_backend ( backend ) if is_interactive : enable_gui_function ( gui ) if not matplotlib . is_interactive ( ) : sys . stdout . write ( "Backend %s is interactive backend. Turning interactive mode on.\n" % backend ) matplotlib . interactive ( True ) else : if matplotlib . is_interactive ( ) : sys . stdout . write ( "Backend %s is non-interactive backend. Turning interactive mode off.\n" % backend ) matplotlib . interactive ( False ) patch_use ( enable_gui_function ) patch_is_interactive ( ) | Set interactive to True for interactive backends . enable_gui_function - Function which enables gui should be run in the main thread . |
20,434 | def flag_calls ( func ) : if hasattr ( func , 'called' ) : return func def wrapper ( * args , ** kw ) : wrapper . called = False out = func ( * args , ** kw ) wrapper . called = True return out wrapper . called = False wrapper . __doc__ = func . __doc__ return wrapper | Wrap a function to detect and flag when it gets called . |
20,435 | def is_valid_py_file ( path ) : import os is_valid = False if os . path . isfile ( path ) and not os . path . splitext ( path ) [ 1 ] == '.pyx' : try : with open ( path , 'rb' ) as f : compile ( f . read ( ) , path , 'exec' ) is_valid = True except : pass return is_valid | Checks whether the file can be read by the coverage module . This is especially needed for . pyx files and . py files with syntax errors . |
20,436 | def __get_hooks_for_dll ( self , event ) : result = [ ] if self . __apiHooks : path = event . get_module ( ) . get_filename ( ) if path : lib_name = PathOperations . pathname_to_filename ( path ) . lower ( ) for hook_lib , hook_api_list in compat . iteritems ( self . __apiHooks ) : if hook_lib == lib_name : result . extend ( hook_api_list ) return result | Get the requested API hooks for the current DLL . |
20,437 | def event ( self , event ) : eventCode = event . get_event_code ( ) pid = event . get_pid ( ) handler = self . forward . get ( pid , None ) if handler is None : handler = self . cls ( * self . argv , ** self . argd ) if eventCode != win32 . EXIT_PROCESS_DEBUG_EVENT : self . forward [ pid ] = handler elif eventCode == win32 . EXIT_PROCESS_DEBUG_EVENT : del self . forward [ pid ] return handler ( event ) | Forwards events to the corresponding instance of your event handler for this process . |
20,438 | def set_event_handler ( self , eventHandler ) : if eventHandler is not None and not callable ( eventHandler ) : raise TypeError ( "Event handler must be a callable object" ) try : wrong_type = issubclass ( eventHandler , EventHandler ) except TypeError : wrong_type = False if wrong_type : classname = str ( eventHandler ) msg = "Event handler must be an instance of class %s" msg += "rather than the %s class itself. (Missing parens?)" msg = msg % ( classname , classname ) raise TypeError ( msg ) try : previous = self . __eventHandler except AttributeError : previous = None self . __eventHandler = eventHandler return previous | Set the event handler . |
20,439 | def should_skip ( filename , config , path = '/' ) : for skip_path in config [ 'skip' ] : if posixpath . abspath ( posixpath . join ( path , filename ) ) == posixpath . abspath ( skip_path . replace ( '\\' , '/' ) ) : return True position = os . path . split ( filename ) while position [ 1 ] : if position [ 1 ] in config [ 'skip' ] : return True position = os . path . split ( position [ 0 ] ) for glob in config [ 'skip_glob' ] : if fnmatch . fnmatch ( filename , glob ) : return True return False | Returns True if the file should be skipped based on the passed in settings . |
20,440 | def ismethod ( func ) : try : if isinstance ( func , core . PyFunction ) : def getargs ( func_code ) : nargs = func_code . co_argcount names = func_code . co_varnames args = list ( names [ : nargs ] ) step = 0 if not hasattr ( func_code , 'CO_VARARGS' ) : from org . python . core import CodeFlag co_varargs_flag = CodeFlag . CO_VARARGS . flag co_varkeywords_flag = CodeFlag . CO_VARKEYWORDS . flag else : co_varargs_flag = func_code . CO_VARARGS co_varkeywords_flag = func_code . CO_VARKEYWORDS varargs = None if func_code . co_flags & co_varargs_flag : varargs = func_code . co_varnames [ nargs ] nargs = nargs + 1 varkw = None if func_code . co_flags & co_varkeywords_flag : varkw = func_code . co_varnames [ nargs ] return args , varargs , varkw args = getargs ( func . func_code ) return 1 , [ Info ( func . func_name , args = args [ 0 ] , varargs = args [ 1 ] , kwargs = args [ 2 ] , doc = func . func_doc ) ] if isinstance ( func , core . PyMethod ) : func = func . im_func if isinstance ( func , PyReflectedFunction ) : infos = [ ] for i in xrange ( len ( func . argslist ) ) : if func . argslist [ i ] : met = func . argslist [ i ] . data name = met . getName ( ) try : ret = met . getReturnType ( ) except AttributeError : ret = '' parameterTypes = met . getParameterTypes ( ) args = [ ] for j in xrange ( len ( parameterTypes ) ) : paramTypesClass = parameterTypes [ j ] try : try : paramClassName = paramTypesClass . getName ( ) except : paramClassName = paramTypesClass . getName ( paramTypesClass ) except AttributeError : try : paramClassName = repr ( paramTypesClass ) paramClassName = paramClassName . split ( '\'' ) [ 1 ] except : paramClassName = repr ( paramTypesClass ) a = format_param_class_name ( paramClassName ) args . append ( a ) info = Info ( name , args = args , ret = ret ) infos . append ( info ) return 1 , infos except Exception : s = StringIO . StringIO ( ) traceback . print_exc ( file = s ) return 1 , [ Info ( str ( 'ERROR' ) , doc = s . getvalue ( ) ) ] return 0 , None | this function should return the information gathered on a function |
20,441 | def format_arg ( arg ) : s = str ( arg ) dot = s . rfind ( '.' ) if dot >= 0 : s = s [ dot + 1 : ] s = s . replace ( ';' , '' ) s = s . replace ( '[]' , 'Array' ) if len ( s ) > 0 : c = s [ 0 ] . lower ( ) s = c + s [ 1 : ] return s | formats an argument to be shown |
20,442 | def start_server ( port ) : s = socket ( AF_INET , SOCK_STREAM ) s . settimeout ( None ) try : from socket import SO_REUSEPORT s . setsockopt ( SOL_SOCKET , SO_REUSEPORT , 1 ) except ImportError : s . setsockopt ( SOL_SOCKET , SO_REUSEADDR , 1 ) s . bind ( ( '' , port ) ) pydev_log . info ( "Bound to port :%s" , port ) try : s . listen ( 1 ) newSock , _addr = s . accept ( ) pydev_log . info ( "Connection accepted" ) s . shutdown ( SHUT_RDWR ) s . close ( ) return newSock except : pydev_log . exception ( "Could not bind to port: %s\n" , port ) | binds to a port waits for the debugger to connect |
20,443 | def internal_change_variable ( dbg , seq , thread_id , frame_id , scope , attr , value ) : try : frame = dbg . find_frame ( thread_id , frame_id ) if frame is not None : result = pydevd_vars . change_attr_expression ( frame , attr , value , dbg ) else : result = None xml = "<xml>" xml += pydevd_xml . var_to_xml ( result , "" ) xml += "</xml>" cmd = dbg . cmd_factory . make_variable_changed_message ( seq , xml ) dbg . writer . add_command ( cmd ) except Exception : cmd = dbg . cmd_factory . make_error_message ( seq , "Error changing variable attr:%s expression:%s traceback:%s" % ( attr , value , get_exception_traceback_str ( ) ) ) dbg . writer . add_command ( cmd ) | Changes the value of a variable |
20,444 | def internal_get_next_statement_targets ( dbg , seq , thread_id , frame_id ) : try : frame = dbg . find_frame ( thread_id , frame_id ) if frame is not None : code = frame . f_code xml = "<xml>" if hasattr ( code , 'co_lnotab' ) : lineno = code . co_firstlineno lnotab = code . co_lnotab for i in itertools . islice ( lnotab , 1 , len ( lnotab ) , 2 ) : if isinstance ( i , int ) : lineno = lineno + i else : lineno = lineno + ord ( i ) xml += "<line>%d</line>" % ( lineno , ) else : xml += "<line>%d</line>" % ( frame . f_lineno , ) del frame xml += "</xml>" cmd = dbg . cmd_factory . make_get_next_statement_targets_message ( seq , xml ) dbg . writer . add_command ( cmd ) else : cmd = dbg . cmd_factory . make_error_message ( seq , "Frame not found: %s from thread: %s" % ( frame_id , thread_id ) ) dbg . writer . add_command ( cmd ) except : cmd = dbg . cmd_factory . make_error_message ( seq , "Error resolving frame: %s from thread: %s" % ( frame_id , thread_id ) ) dbg . writer . add_command ( cmd ) | gets the valid line numbers for use with set next statement |
20,445 | def internal_evaluate_expression ( dbg , seq , thread_id , frame_id , expression , is_exec , trim_if_too_big , attr_to_set_result ) : try : frame = dbg . find_frame ( thread_id , frame_id ) if frame is not None : result = pydevd_vars . evaluate_expression ( dbg , frame , expression , is_exec ) if attr_to_set_result != "" : pydevd_vars . change_attr_expression ( frame , attr_to_set_result , expression , dbg , result ) else : result = None xml = "<xml>" xml += pydevd_xml . var_to_xml ( result , expression , trim_if_too_big ) xml += "</xml>" cmd = dbg . cmd_factory . make_evaluate_expression_message ( seq , xml ) dbg . writer . add_command ( cmd ) except : exc = get_exception_traceback_str ( ) cmd = dbg . cmd_factory . make_error_message ( seq , "Error evaluating expression " + exc ) dbg . writer . add_command ( cmd ) | gets the value of a variable |
20,446 | def internal_get_description ( dbg , seq , thread_id , frame_id , expression ) : try : frame = dbg . find_frame ( thread_id , frame_id ) description = pydevd_console . get_description ( frame , thread_id , frame_id , expression ) description = pydevd_xml . make_valid_xml_value ( quote ( description , '/>_= \t' ) ) description_xml = '<xml><var name="" type="" value="%s"/></xml>' % description cmd = dbg . cmd_factory . make_get_description_message ( seq , description_xml ) dbg . writer . add_command ( cmd ) except : exc = get_exception_traceback_str ( ) cmd = dbg . cmd_factory . make_error_message ( seq , "Error in fetching description" + exc ) dbg . writer . add_command ( cmd ) | Fetch the variable description stub from the debug console |
20,447 | def internal_get_exception_details_json ( dbg , request , thread_id , max_frames , set_additional_thread_info = None , iter_visible_frames_info = None ) : try : response = build_exception_info_response ( dbg , thread_id , request . seq , set_additional_thread_info , iter_visible_frames_info , max_frames ) except : exc = get_exception_traceback_str ( ) response = pydevd_base_schema . build_response ( request , kwargs = { 'success' : False , 'message' : exc , 'body' : { } } ) dbg . writer . add_command ( NetCommand ( CMD_RETURN , 0 , response , is_json = True ) ) | Fetch exception details |
20,448 | def _on_run ( self ) : try : while True : try : try : cmd = self . cmdQueue . get ( 1 , 0.1 ) except _queue . Empty : if self . killReceived : try : self . sock . shutdown ( SHUT_WR ) self . sock . close ( ) except : pass return else : continue except : return cmd . send ( self . sock ) if cmd . id == CMD_EXIT : break if time is None : break time . sleep ( self . timeout ) except Exception : GlobalDebuggerHolder . global_dbg . finish_debugging_session ( ) if DebugInfoHolder . DEBUG_TRACE_LEVEL >= 0 : pydev_log_exception ( ) | just loop and write responses |
20,449 | def can_be_executed_by ( self , thread_id ) : return self . thread_id == thread_id or self . thread_id . endswith ( '|' + thread_id ) | By default it must be in the same thread to be executed |
20,450 | def do_it ( self , dbg ) : try : frame = dbg . find_frame ( self . thread_id , self . frame_id ) completions_xml = pydevd_console . get_completions ( frame , self . act_tok ) cmd = dbg . cmd_factory . make_send_console_message ( self . sequence , completions_xml ) dbg . writer . add_command ( cmd ) except : exc = get_exception_traceback_str ( ) cmd = dbg . cmd_factory . make_error_message ( self . sequence , "Error in fetching completions" + exc ) dbg . writer . add_command ( cmd ) | Get completions and write back to the client |
20,451 | def do_it ( self , dbg ) : try : var_objects = [ ] for variable in self . vars : variable = variable . strip ( ) if len ( variable ) > 0 : if '\t' in variable : scope , attrs = variable . split ( '\t' , 1 ) name = attrs [ 0 ] else : scope , attrs = ( variable , None ) name = scope var_obj = pydevd_vars . getVariable ( dbg , self . thread_id , self . frame_id , scope , attrs ) var_objects . append ( ( var_obj , name ) ) t = GetValueAsyncThreadDebug ( dbg , self . sequence , var_objects ) t . start ( ) except : exc = get_exception_traceback_str ( ) sys . stderr . write ( '%s\n' % ( exc , ) ) cmd = dbg . cmd_factory . make_error_message ( self . sequence , "Error evaluating variable %s " % exc ) dbg . writer . add_command ( cmd ) | Starts a thread that will load values asynchronously |
20,452 | def RaiseIfLastError ( result , func = None , arguments = ( ) ) : code = GetLastError ( ) if code != ERROR_SUCCESS : raise ctypes . WinError ( code ) return result | Error checking for Win32 API calls with no error - specific return value . |
20,453 | def close ( self ) : if self . bOwnership and self . value not in ( None , INVALID_HANDLE_VALUE ) : if Handle . __bLeakDetection : print ( "CLOSE HANDLE (%d) %r" % ( self . value , self ) ) try : self . _close ( ) finally : self . _value = None | Closes the Win32 handle . |
20,454 | def _normalize ( value ) : if hasattr ( value , 'value' ) : value = value . value if value is not None : value = long ( value ) return value | Normalize handle values . |
20,455 | def wait ( self , dwMilliseconds = None ) : if self . value is None : raise ValueError ( "Handle is already closed!" ) if dwMilliseconds is None : dwMilliseconds = INFINITE r = WaitForSingleObject ( self . value , dwMilliseconds ) if r != WAIT_OBJECT_0 : raise ctypes . WinError ( r ) | Wait for the Win32 object to be signaled . |
20,456 | def add ( self , pattern , start ) : "Recursively adds a linear pattern to the AC automaton" if not pattern : return [ start ] if isinstance ( pattern [ 0 ] , tuple ) : match_nodes = [ ] for alternative in pattern [ 0 ] : end_nodes = self . add ( alternative , start = start ) for end in end_nodes : match_nodes . extend ( self . add ( pattern [ 1 : ] , end ) ) return match_nodes else : if pattern [ 0 ] not in start . transition_table : next_node = BMNode ( ) start . transition_table [ pattern [ 0 ] ] = next_node else : next_node = start . transition_table [ pattern [ 0 ] ] if pattern [ 1 : ] : end_nodes = self . add ( pattern [ 1 : ] , start = next_node ) else : end_nodes = [ next_node ] return end_nodes | Recursively adds a linear pattern to the AC automaton |
20,457 | def _get_globals ( ) : if _get_globals_callback is not None : return _get_globals_callback ( ) else : try : from __main__ import __dict__ as namespace except ImportError : try : import __main__ namespace = __main__ . __dict__ except : namespace shell = namespace . get ( '__ipythonshell__' ) if shell is not None and hasattr ( shell , 'user_ns' ) : return shell . user_ns else : return namespace return namespace | Return current Python interpreter globals namespace |
20,458 | def run ( self , verbose = False ) : log = [ ] modules_copy = dict ( sys . modules ) for modname , module in modules_copy . items ( ) : if modname == 'aaaaa' : print ( modname , module ) print ( self . previous_modules ) if modname not in self . previous_modules : modpath = getattr ( module , '__file__' , None ) if modpath is None : continue if not self . is_module_blacklisted ( modname , modpath ) : log . append ( modname ) del sys . modules [ modname ] if verbose and log : print ( "\x1b[4;33m%s\x1b[24m%s\x1b[0m" % ( "UMD has deleted" , ": " + ", " . join ( log ) ) ) | Del user modules to force Python to deeply reload them |
20,459 | def get_stdlib_path ( ) : if sys . version_info >= ( 2 , 7 ) : import sysconfig return sysconfig . get_paths ( ) [ 'stdlib' ] else : return os . path . join ( sys . prefix , 'lib' ) | Returns the path to the standard lib for the current path installation . |
20,460 | def exists_case_sensitive ( path ) : result = os . path . exists ( path ) if sys . platform . startswith ( 'win' ) and result : directory , basename = os . path . split ( path ) result = basename in os . listdir ( directory ) return result | Returns if the given path exists and also matches the case on Windows . |
20,461 | def _add_comments ( self , comments , original_string = "" ) : return comments and "{0} # {1}" . format ( self . _strip_comments ( original_string ) [ 0 ] , "; " . join ( comments ) ) or original_string | Returns a string with comments added |
20,462 | def settrace ( host = None , stdoutToServer = False , stderrToServer = False , port = 5678 , suspend = True , trace_only_current_thread = False , overwrite_prev_trace = False , patch_multiprocessing = False , stop_at_frame = None , ) : _set_trace_lock . acquire ( ) try : _locked_settrace ( host , stdoutToServer , stderrToServer , port , suspend , trace_only_current_thread , patch_multiprocessing , stop_at_frame , ) finally : _set_trace_lock . release ( ) | Sets the tracing function with the pydev debug function and initializes needed facilities . |
20,463 | def settrace_forked ( ) : from _pydevd_bundle . pydevd_constants import GlobalDebuggerHolder GlobalDebuggerHolder . global_dbg = None threading . current_thread ( ) . additional_info = None from _pydevd_frame_eval . pydevd_frame_eval_main import clear_thread_local_info host , port = dispatch ( ) import pydevd_tracing pydevd_tracing . restore_sys_set_trace_func ( ) if port is not None : global connected connected = False global forked forked = True custom_frames_container_init ( ) if clear_thread_local_info is not None : clear_thread_local_info ( ) settrace ( host , port = port , suspend = False , trace_only_current_thread = False , overwrite_prev_trace = True , patch_multiprocessing = True , ) | When creating a fork from a process in the debugger we need to reset the whole debugger environment! |
20,464 | def enable_tracing ( self , thread_trace_func = None ) : if self . frame_eval_func is not None : self . frame_eval_func ( ) pydevd_tracing . SetTrace ( self . dummy_trace_dispatch ) return if thread_trace_func is None : thread_trace_func = self . get_thread_local_trace_func ( ) else : self . _local_thread_trace_func . thread_trace_func = thread_trace_func pydevd_tracing . SetTrace ( thread_trace_func ) | Enables tracing . |
20,465 | def on_breakpoints_changed ( self , removed = False ) : if not self . ready_to_run : return self . mtime += 1 if not removed : self . set_tracing_for_untraced_contexts ( ) | When breakpoints change we have to re - evaluate all the assumptions we ve made so far . |
20,466 | def apply_files_filter ( self , frame , filename , force_check_project_scope ) : cache_key = ( frame . f_code . co_firstlineno , frame . f_code . co_name , filename , force_check_project_scope ) try : return self . _apply_filter_cache [ cache_key ] except KeyError : if self . plugin is not None and ( self . has_plugin_line_breaks or self . has_plugin_exception_breaks ) : if not self . plugin . can_skip ( self , frame ) : self . _apply_filter_cache [ cache_key ] = False return False if self . _exclude_filters_enabled : exclude_by_filter = self . _exclude_by_filter ( frame , filename ) if exclude_by_filter is not None : if exclude_by_filter : self . _apply_filter_cache [ cache_key ] = True return True else : self . _apply_filter_cache [ cache_key ] = False return False if ( self . _is_libraries_filter_enabled or force_check_project_scope ) and not self . in_project_scope ( filename ) : self . _apply_filter_cache [ cache_key ] = True return True self . _apply_filter_cache [ cache_key ] = False return False | Should only be called if self . is_files_filter_enabled == True . |
20,467 | def get_internal_queue ( self , thread_id ) : if thread_id . startswith ( '__frame__' ) : thread_id = thread_id [ thread_id . rfind ( '|' ) + 1 : ] return self . _cmd_queue [ thread_id ] | returns internal command queue for a given thread . if new queue is created notify the RDB about it |
20,468 | def notify_thread_not_alive ( self , thread_id , use_lock = True ) : if self . writer is None : return with self . _lock_running_thread_ids if use_lock else NULL : if not self . _enable_thread_notifications : return thread = self . _running_thread_ids . pop ( thread_id , None ) if thread is None : return was_notified = thread . additional_info . pydev_notify_kill if not was_notified : thread . additional_info . pydev_notify_kill = True self . writer . add_command ( self . cmd_factory . make_thread_killed_message ( thread_id ) ) | if thread is not alive cancel trace_dispatch processing |
20,469 | def process_internal_commands ( self ) : with self . _main_lock : self . check_output_redirect ( ) program_threads_alive = { } all_threads = threadingEnumerate ( ) program_threads_dead = [ ] with self . _lock_running_thread_ids : reset_cache = not self . _running_thread_ids for t in all_threads : if getattr ( t , 'is_pydev_daemon_thread' , False ) : pass elif isinstance ( t , PyDBDaemonThread ) : pydev_log . error_once ( 'Error in debugger: Found PyDBDaemonThread not marked with is_pydev_daemon_thread=True.' ) elif is_thread_alive ( t ) : if reset_cache : clear_cached_thread_id ( t ) thread_id = get_thread_id ( t ) program_threads_alive [ thread_id ] = t self . notify_thread_created ( thread_id , t , use_lock = False ) thread_ids = list ( self . _running_thread_ids . keys ( ) ) for thread_id in thread_ids : if thread_id not in program_threads_alive : program_threads_dead . append ( thread_id ) for thread_id in program_threads_dead : self . notify_thread_not_alive ( thread_id , use_lock = False ) if len ( program_threads_alive ) == 0 : self . finish_debugging_session ( ) for t in all_threads : if hasattr ( t , 'do_kill_pydev_thread' ) : t . do_kill_pydev_thread ( ) else : curr_thread_id = get_current_thread_id ( threadingCurrentThread ( ) ) for thread_id in ( curr_thread_id , '*' ) : queue = self . get_internal_queue ( thread_id ) cmds_to_add_back = [ ] try : while True : int_cmd = queue . get ( False ) if not self . mpl_hooks_in_debug_console and isinstance ( int_cmd , InternalConsoleExec ) : try : self . init_matplotlib_in_debug_console ( ) self . mpl_in_use = True except : pydev_log . debug ( "Matplotlib support in debug console failed" , traceback . format_exc ( ) ) self . mpl_hooks_in_debug_console = True if int_cmd . can_be_executed_by ( curr_thread_id ) : pydev_log . verbose ( "processing internal command " , int_cmd ) int_cmd . do_it ( self ) else : pydev_log . verbose ( "NOT processing internal command " , int_cmd ) cmds_to_add_back . append ( int_cmd ) except _queue . Empty : for int_cmd in cmds_to_add_back : queue . put ( int_cmd ) | This function processes internal commands |
20,470 | def _send_breakpoint_condition_exception ( self , thread , conditional_breakpoint_exception_tuple ) : thread_id = get_thread_id ( thread ) if conditional_breakpoint_exception_tuple and len ( conditional_breakpoint_exception_tuple ) == 2 : exc_type , stacktrace = conditional_breakpoint_exception_tuple int_cmd = InternalGetBreakpointException ( thread_id , exc_type , stacktrace ) self . post_internal_command ( int_cmd , thread_id ) | If conditional breakpoint raises an exception during evaluation send exception details to java |
20,471 | def send_caught_exception_stack_proceeded ( self , thread ) : thread_id = get_thread_id ( thread ) int_cmd = InternalSendCurrExceptionTraceProceeded ( thread_id ) self . post_internal_command ( int_cmd , thread_id ) self . process_internal_commands ( ) | Sends that some thread was resumed and is no longer showing an exception trace . |
20,472 | def send_process_created_message ( self ) : cmd = self . cmd_factory . make_process_created_message ( ) self . writer . add_command ( cmd ) | Sends a message that a new process has been created . |
20,473 | def do_wait_suspend ( self , thread , frame , event , arg , is_unhandled_exception = False ) : self . process_internal_commands ( ) thread_id = get_current_thread_id ( thread ) message = thread . additional_info . pydev_message suspend_type = thread . additional_info . trace_suspend_type thread . additional_info . trace_suspend_type = 'trace' frame_id_to_lineno = { } stop_reason = thread . stop_reason if is_unhandled_exception : tb = arg [ 2 ] while tb is not None : frame_id_to_lineno [ id ( tb . tb_frame ) ] = tb . tb_lineno tb = tb . tb_next with self . suspended_frames_manager . track_frames ( self ) as frames_tracker : frames_tracker . track ( thread_id , frame , frame_id_to_lineno ) cmd = frames_tracker . create_thread_suspend_command ( thread_id , stop_reason , message , suspend_type ) self . writer . add_command ( cmd ) with CustomFramesContainer . custom_frames_lock : from_this_thread = [ ] for frame_custom_thread_id , custom_frame in dict_iter_items ( CustomFramesContainer . custom_frames ) : if custom_frame . thread_id == thread . ident : frames_tracker . track ( thread_id , custom_frame . frame , frame_id_to_lineno , frame_custom_thread_id = frame_custom_thread_id ) self . writer . add_command ( self . cmd_factory . make_custom_frame_created_message ( frame_custom_thread_id , custom_frame . name ) ) self . writer . add_command ( frames_tracker . create_thread_suspend_command ( frame_custom_thread_id , CMD_THREAD_SUSPEND , "" , suspend_type ) ) from_this_thread . append ( frame_custom_thread_id ) with self . _threads_suspended_single_notification . notify_thread_suspended ( thread_id , stop_reason ) : keep_suspended = self . _do_wait_suspend ( thread , frame , event , arg , suspend_type , from_this_thread , frames_tracker ) if keep_suspended : self . _threads_suspended_single_notification . increment_suspend_time ( ) self . do_wait_suspend ( thread , frame , event , arg , is_unhandled_exception ) | busy waits until the thread state changes to RUN it expects thread s state as attributes of the thread . Upon running processes any outstanding Stepping commands . |
20,474 | def _get_arch ( ) : try : si = GetNativeSystemInfo ( ) except Exception : si = GetSystemInfo ( ) try : return _arch_map [ si . id . w . wProcessorArchitecture ] except KeyError : return ARCH_UNKNOWN | Determines the current processor architecture . |
20,475 | def _get_wow64 ( ) : if bits == 64 : wow64 = False else : try : wow64 = IsWow64Process ( GetCurrentProcess ( ) ) except Exception : wow64 = False return wow64 | Determines if the current process is running in Windows - On - Windows 64 bits . |
20,476 | def log_context ( trace_level , stream ) : original_trace_level = DebugInfoHolder . DEBUG_TRACE_LEVEL original_stream = DebugInfoHolder . DEBUG_STREAM DebugInfoHolder . DEBUG_TRACE_LEVEL = trace_level DebugInfoHolder . DEBUG_STREAM = stream try : yield finally : DebugInfoHolder . DEBUG_TRACE_LEVEL = original_trace_level DebugInfoHolder . DEBUG_STREAM = original_stream | To be used to temporarily change the logging settings . |
20,477 | def __is_control_flow ( self ) : jump_instructions = ( 'jmp' , 'jecxz' , 'jcxz' , 'ja' , 'jnbe' , 'jae' , 'jnb' , 'jb' , 'jnae' , 'jbe' , 'jna' , 'jc' , 'je' , 'jz' , 'jnc' , 'jne' , 'jnz' , 'jnp' , 'jpo' , 'jp' , 'jpe' , 'jg' , 'jnle' , 'jge' , 'jnl' , 'jl' , 'jnge' , 'jle' , 'jng' , 'jno' , 'jns' , 'jo' , 'js' ) call_instructions = ( 'call' , 'ret' , 'retn' ) loop_instructions = ( 'loop' , 'loopz' , 'loopnz' , 'loope' , 'loopne' ) control_flow_instructions = call_instructions + loop_instructions + jump_instructions isControlFlow = False instruction = None if self . pc is not None and self . faultDisasm : for disasm in self . faultDisasm : if disasm [ 0 ] == self . pc : instruction = disasm [ 2 ] . lower ( ) . strip ( ) break if instruction : for x in control_flow_instructions : if x in instruction : isControlFlow = True break return isControlFlow | Private method to tell if the instruction pointed to by the program counter is a control flow instruction . |
20,478 | def __is_block_data_move ( self ) : block_data_move_instructions = ( 'movs' , 'stos' , 'lods' ) isBlockDataMove = False instruction = None if self . pc is not None and self . faultDisasm : for disasm in self . faultDisasm : if disasm [ 0 ] == self . pc : instruction = disasm [ 2 ] . lower ( ) . strip ( ) break if instruction : for x in block_data_move_instructions : if x in instruction : isBlockDataMove = True break return isBlockDataMove | Private method to tell if the instruction pointed to by the program counter is a block data move instruction . |
20,479 | def marshall_key ( self , key ) : if key in self . __keys : return self . __keys [ key ] skey = pickle . dumps ( key , protocol = 0 ) if self . compressKeys : skey = zlib . compress ( skey , zlib . Z_BEST_COMPRESSION ) if self . escapeKeys : skey = skey . encode ( 'hex' ) if self . binaryKeys : skey = buffer ( skey ) self . __keys [ key ] = skey return skey | Marshalls a Crash key to be used in the database . |
20,480 | def unmarshall_key ( self , key ) : key = str ( key ) if self . escapeKeys : key = key . decode ( 'hex' ) if self . compressKeys : key = zlib . decompress ( key ) key = pickle . loads ( key ) return key | Unmarshalls a Crash key read from the database . |
20,481 | def unmarshall_value ( self , value ) : value = str ( value ) if self . escapeValues : value = value . decode ( 'hex' ) if self . compressValues : value = zlib . decompress ( value ) value = pickle . loads ( value ) return value | Unmarshalls a Crash object read from the database . |
20,482 | def add ( self , crash ) : if crash not in self : key = crash . key ( ) skey = self . marshall_key ( key ) data = self . marshall_value ( crash , storeMemoryMap = True ) self . __db [ skey ] = data | Adds a new crash to the container . If the crash appears to be already known it s ignored . |
20,483 | def add ( self , crash ) : self . __keys . add ( crash . signature ) self . __count += 1 | Adds a new crash to the container . |
20,484 | def _schedule_callback ( prev , next ) : try : if not prev and not next : return current_frame = sys . _getframe ( ) if next : register_tasklet_info ( next ) debugger = get_global_debugger ( ) if debugger is not None : next . trace_function = debugger . get_thread_local_trace_func ( ) frame = next . frame if frame is current_frame : frame = frame . f_back if hasattr ( frame , 'f_trace' ) : frame . f_trace = debugger . get_thread_local_trace_func ( ) debugger = None if prev : register_tasklet_info ( prev ) try : for tasklet_ref , tasklet_info in dict_items ( _weak_tasklet_registered_to_info ) : tasklet = tasklet_ref ( ) if tasklet is None or not tasklet . alive : try : del _weak_tasklet_registered_to_info [ tasklet_ref ] except KeyError : pass if tasklet_info . frame_id is not None : remove_custom_frame ( tasklet_info . frame_id ) else : is_running = stackless . get_thread_info ( tasklet . thread_id ) [ 1 ] is tasklet if tasklet is prev or ( tasklet is not next and not is_running ) : frame = tasklet . frame if frame is current_frame : frame = frame . f_back if frame is not None : abs_real_path_and_base = get_abs_path_real_path_and_base_from_frame ( frame ) if debugger . get_file_type ( abs_real_path_and_base ) is None : tasklet_info . update_name ( ) if tasklet_info . frame_id is None : tasklet_info . frame_id = add_custom_frame ( frame , tasklet_info . tasklet_name , tasklet . thread_id ) else : update_custom_frame ( tasklet_info . frame_id , frame , tasklet . thread_id , name = tasklet_info . tasklet_name ) elif tasklet is next or is_running : if tasklet_info . frame_id is not None : remove_custom_frame ( tasklet_info . frame_id ) tasklet_info . frame_id = None finally : tasklet = None tasklet_info = None frame = None except : pydev_log . exception ( ) if _application_set_schedule_callback is not None : return _application_set_schedule_callback ( prev , next ) | Called when a context is stopped or a new context is made runnable . |
20,485 | def patch_stackless ( ) : global _application_set_schedule_callback _application_set_schedule_callback = stackless . set_schedule_callback ( _schedule_callback ) def set_schedule_callback ( callable ) : global _application_set_schedule_callback old = _application_set_schedule_callback _application_set_schedule_callback = callable return old def get_schedule_callback ( ) : global _application_set_schedule_callback return _application_set_schedule_callback set_schedule_callback . __doc__ = stackless . set_schedule_callback . __doc__ if hasattr ( stackless , "get_schedule_callback" ) : get_schedule_callback . __doc__ = stackless . get_schedule_callback . __doc__ stackless . set_schedule_callback = set_schedule_callback stackless . get_schedule_callback = get_schedule_callback if not hasattr ( stackless . tasklet , "trace_function" ) : __call__ . __doc__ = stackless . tasklet . __call__ . __doc__ stackless . tasklet . __call__ = __call__ setup . __doc__ = stackless . tasklet . setup . __doc__ stackless . tasklet . setup = setup run . __doc__ = stackless . run . __doc__ stackless . run = run | This function should be called to patch the stackless module so that new tasklets are properly tracked in the debugger . |
20,486 | def attach ( self , dwProcessId ) : try : aProcess = self . system . get_process ( dwProcessId ) except KeyError : aProcess = Process ( dwProcessId ) if System . bits != aProcess . get_bits ( ) : msg = "Mixture of 32 and 64 bits is considered experimental." " Use at your own risk!" warnings . warn ( msg , MixedBitsWarning ) win32 . DebugActiveProcess ( dwProcessId ) self . __attachedDebugees . add ( dwProcessId ) self . __setSystemKillOnExitMode ( ) if not self . system . has_process ( dwProcessId ) : self . system . _add_process ( aProcess ) aProcess . scan_threads ( ) aProcess . scan_modules ( ) return aProcess | Attaches to an existing process for debugging . |
20,487 | def __cleanup_process ( self , dwProcessId , bIgnoreExceptions = False ) : if self . is_debugee ( dwProcessId ) : if not self . system . has_process ( dwProcessId ) : aProcess = Process ( dwProcessId ) try : aProcess . get_handle ( ) except WindowsError : pass self . system . _add_process ( aProcess ) try : self . erase_process_breakpoints ( dwProcessId ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : self . stop_tracing_process ( dwProcessId ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : if dwProcessId in self . __attachedDebugees : self . __attachedDebugees . remove ( dwProcessId ) if dwProcessId in self . __startedDebugees : self . __startedDebugees . remove ( dwProcessId ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : if self . system . has_process ( dwProcessId ) : try : self . system . get_process ( dwProcessId ) . clear ( ) finally : self . system . _del_process ( dwProcessId ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : if self . lastEvent and self . lastEvent . get_pid ( ) == dwProcessId : self . lastEvent = None except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) | Perform the necessary cleanup of a process about to be killed or detached from . |
20,488 | def kill ( self , dwProcessId , bIgnoreExceptions = False ) : try : aProcess = self . system . get_process ( dwProcessId ) except KeyError : aProcess = Process ( dwProcessId ) self . __cleanup_process ( dwProcessId , bIgnoreExceptions = bIgnoreExceptions ) try : try : if self . is_debugee ( dwProcessId ) : try : if aProcess . is_alive ( ) : aProcess . suspend ( ) finally : self . detach ( dwProcessId , bIgnoreExceptions = bIgnoreExceptions ) finally : aProcess . kill ( ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : aProcess . clear ( ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) | Kills a process currently being debugged . |
20,489 | def kill_all ( self , bIgnoreExceptions = False ) : for pid in self . get_debugee_pids ( ) : self . kill ( pid , bIgnoreExceptions = bIgnoreExceptions ) | Kills from all processes currently being debugged . |
20,490 | def detach ( self , dwProcessId , bIgnoreExceptions = False ) : try : aProcess = self . system . get_process ( dwProcessId ) except KeyError : aProcess = Process ( dwProcessId ) try : win32 . DebugActiveProcessStop can_detach = True except AttributeError : can_detach = False try : if can_detach and self . lastEvent and self . lastEvent . get_pid ( ) == dwProcessId : self . cont ( self . lastEvent ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) self . __cleanup_process ( dwProcessId , bIgnoreExceptions = bIgnoreExceptions ) try : if can_detach : try : win32 . DebugActiveProcessStop ( dwProcessId ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) else : try : aProcess . kill ( ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) finally : aProcess . clear ( ) | Detaches from a process currently being debugged . |
20,491 | def detach_from_all ( self , bIgnoreExceptions = False ) : for pid in self . get_debugee_pids ( ) : self . detach ( pid , bIgnoreExceptions = bIgnoreExceptions ) | Detaches from all processes currently being debugged . |
20,492 | def wait ( self , dwMilliseconds = None ) : raw = win32 . WaitForDebugEvent ( dwMilliseconds ) event = EventFactory . get ( self , raw ) self . lastEvent = event return event | Waits for the next debug event . |
20,493 | def dispatch ( self , event = None ) : if event is None : event = self . lastEvent if not event : return code = event . get_event_code ( ) if code == win32 . EXCEPTION_DEBUG_EVENT : exc_code = event . get_exception_code ( ) if exc_code in ( win32 . EXCEPTION_BREAKPOINT , win32 . EXCEPTION_WX86_BREAKPOINT , win32 . EXCEPTION_SINGLE_STEP , win32 . EXCEPTION_GUARD_PAGE , ) : event . continueStatus = win32 . DBG_CONTINUE elif exc_code == win32 . EXCEPTION_INVALID_HANDLE : if self . __bHostileCode : event . continueStatus = win32 . DBG_EXCEPTION_NOT_HANDLED else : event . continueStatus = win32 . DBG_CONTINUE else : event . continueStatus = win32 . DBG_EXCEPTION_NOT_HANDLED elif code == win32 . RIP_EVENT and event . get_rip_type ( ) == win32 . SLE_ERROR : event . continueStatus = win32 . DBG_TERMINATE_PROCESS else : event . continueStatus = win32 . DBG_CONTINUE return EventDispatcher . dispatch ( self , event ) | Calls the debug event notify callbacks . |
20,494 | def cont ( self , event = None ) : if event is None : event = self . lastEvent if not event : return dwProcessId = event . get_pid ( ) dwThreadId = event . get_tid ( ) dwContinueStatus = event . continueStatus if self . is_debugee ( dwProcessId ) : try : if self . system . has_process ( dwProcessId ) : aProcess = self . system . get_process ( dwProcessId ) else : aProcess = Process ( dwProcessId ) aProcess . flush_instruction_cache ( ) except WindowsError : pass win32 . ContinueDebugEvent ( dwProcessId , dwThreadId , dwContinueStatus ) if event == self . lastEvent : self . lastEvent = None | Resumes execution after processing a debug event . |
20,495 | def stop ( self , bIgnoreExceptions = True ) : try : event = self . lastEvent has_event = bool ( event ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) has_event = False if has_event : try : pid = event . get_pid ( ) self . disable_process_breakpoints ( pid ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : tid = event . get_tid ( ) self . disable_thread_breakpoints ( tid ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : event . continueDebugEvent = win32 . DBG_CONTINUE self . cont ( event ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : if self . __bKillOnExit : self . kill_all ( bIgnoreExceptions ) else : self . detach_from_all ( bIgnoreExceptions ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) try : self . system . clear ( ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) self . force_garbage_collection ( bIgnoreExceptions ) | Stops debugging all processes . |
20,496 | def next ( self ) : try : event = self . wait ( ) except Exception : self . stop ( ) raise try : self . dispatch ( ) finally : self . cont ( ) | Handles the next debug event . |
20,497 | def interactive ( self , bConfirmQuit = True , bShowBanner = True ) : print ( '' ) print ( "-" * 79 ) print ( "Interactive debugging session started." ) print ( "Use the \"help\" command to list all available commands." ) print ( "Use the \"quit\" command to close this session." ) print ( "-" * 79 ) if self . lastEvent is None : print ( '' ) console = ConsoleDebugger ( ) console . confirm_quit = bConfirmQuit console . load_history ( ) try : console . start_using_debugger ( self ) console . loop ( ) finally : console . stop_using_debugger ( ) console . save_history ( ) print ( '' ) print ( "-" * 79 ) print ( "Interactive debugging session closed." ) print ( "-" * 79 ) print ( '' ) | Start an interactive debugging session . |
20,498 | def force_garbage_collection ( bIgnoreExceptions = True ) : try : import gc gc . collect ( ) bRecollect = False for obj in list ( gc . garbage ) : try : if isinstance ( obj , win32 . Handle ) : obj . close ( ) elif isinstance ( obj , Event ) : obj . debug = None elif isinstance ( obj , Process ) : obj . clear ( ) elif isinstance ( obj , Thread ) : obj . set_process ( None ) obj . clear ( ) elif isinstance ( obj , Module ) : obj . set_process ( None ) elif isinstance ( obj , Window ) : obj . set_process ( None ) else : continue gc . garbage . remove ( obj ) del obj bRecollect = True except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) if bRecollect : gc . collect ( ) except Exception : if not bIgnoreExceptions : raise e = sys . exc_info ( ) [ 1 ] warnings . warn ( str ( e ) , RuntimeWarning ) | Close all Win32 handles the Python garbage collector failed to close . |
20,499 | def _notify_load_dll ( self , event ) : bCallHandler = _BreakpointContainer . _notify_load_dll ( self , event ) aProcess = event . get_process ( ) bCallHandler = aProcess . _notify_load_dll ( event ) and bCallHandler if self . __bHostileCode : aModule = event . get_module ( ) if aModule . match_name ( 'ntdll.dll' ) : self . break_at ( aProcess . get_pid ( ) , aProcess . resolve_label ( 'ntdll!DbgUiRemoteBreakin' ) ) return bCallHandler | Notify the load of a new module . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.