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 ) [ ...
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 . ...
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 ...
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 = u...
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 : war...
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 compa...
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 = ...
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 ( co...
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...
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_ga...
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 [ ...
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 ] Ro...
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...
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 . d...
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_entr...
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...
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_leve...
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 . ...
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 . i...
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 ( ...
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 ...
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 ( AP...
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-%...
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 intera...
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 . ex...
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 == w...
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...
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 conf...
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 = CodeF...
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 )...
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 ( resul...
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 ( lno...
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 != ...
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' ) ) desc...
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 ...
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 ...
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_e...
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 ( ...
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...
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 has...
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 mod...
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 , stder...
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 p...
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 . ...
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_...
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 =...
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_p...
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 = Internal...
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 . trac...
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_leve...
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...
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 instr...
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 ) s...
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 c...
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...
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 , MixedBitsWarn...
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 . eras...
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 aPr...
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...
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 . EXCE...
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 ...
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...
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...
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 ...
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' ) : s...
Notify the load of a new module .